In Rails 8.1, when exactly are Current attributes reset, and what do the before_reset and resets hooks on a CurrentAttributes class run?
answer
- the Rails executor wraps requests and jobs
- to_complete calls CurrentAttributes.clear_all
- before_reset runs before, resets after
- 8.1 discards the instance
- resets { Time.zone = nil }
basics
~20 sThe Rails executor wraps each request and job; when it completes, CurrentAttributes.clear_all runs every instance's reset callbacks and discards the instances, so the next execution builds fresh ones from the defaults. before_reset runs before the values are cleared, resets after.
solid answer
~40 sRequests (through the `ActionDispatch::Executor` middleware) and Active Job executions run inside the **Rails executor**. Active Support registers two hooks on it: `to_run` starts a fresh execution context, and `to_complete` calls `ActiveSupport::CurrentAttributes.clear_all`, which calls `reset` on every Current instance created during that execution and then drops them. `reset` runs the `before_reset` callbacks, puts the attributes back to their defaults, then runs the `resets` (alias `after_reset`) callbacks. Since Rails 8.1.0 the instance is thrown away afterwards, so the next request builds a new one; earlier versions reset and reused it, which could leak instance variables a Current class kept beyond its attributes. Use `resets` to undo side effects such as `resets { Time.zone = nil }`, and `before_reset` when the cleanup needs the old values.
go deeper
Recall that Rails clears Current automatically after each request and job, so values never carry over to the next one.
Explain the executor's to_run and to_complete hooks, clear_all, the order of before_reset and resets, and why resets is the place to undo Time.zone.
Know the 8.1 change to discarding instances, that callbacks run only for instances created in the execution, and how to wrap custom threads in the executor.
Judge which global side effects a Current class may trigger at all, and require each one to have a matching reset path before it ships.
## Why reset matters Puma serves requests on a small pool of reused threads. `Current` stores its values per thread, so if nothing cleared them, the next request on the same thread would start with the previous user's account: a cross-tenant leak in a multi-tenant CRM. Rails prevents that without any code in the app, through the **executor**. ## The executor and its hooks `Rails.application.executor` is an execution wrapper that brackets every unit of application work: - each HTTP request, via the `ActionDispatch::Executor` middleware in the default stack; - each Active Job execution, which Active Job wraps with the application's reloader and, through it, the executor; - other framework entry points, and tests when `config.active_support.executor_around_test_case` is on. The Active Support railtie attaches two hooks to it: 1. **`to_run`**: start a new execution context, so any `Current` instance created from now on belongs to this request or job. 2. **`to_complete`**: call `ActiveSupport::CurrentAttributes.clear_all`, then pop the execution context (in tests, where contexts nest, that restores the outer one). For a request, completion happens when the response body is closed, not when the controller action returns, so code that runs while the body streams still sees the values. ## What `clear_all` does `clear_all` walks the `Current` instances created during this execution and, for each one: 1. calls `reset`, which runs the **`before_reset`** callbacks, sets the attributes back to their resolved defaults, then runs the **`resets`** callbacks (`after_reset` is an alias); 2. then empties the registry, so the instance is abandoned. The next request lazily creates a brand-new instance on first access, resolving `default:` values again. | Hook | Runs | Typical use | |---|---|---| | `before_reset` | before attributes are cleared | flush something that still needs `Current.account` | | `resets` / `after_reset` | after attributes are cleared | undo global side effects: `Time.zone = nil`, reset a client | ```ruby class Current < ActiveSupport::CurrentAttributes attribute :account, :user before_reset { AuditBuffer.flush(account) if account } resets { Time.zone = nil } def user=(user) super Time.zone = user&.time_zone end end ``` The `user=` writer changes `Time.zone`, a separate per-thread setting that `Current` does not own. Without the `resets` hook, that zone would stay set on the thread for whatever runs next. ## The Rails 8.1 change Before 8.1, the end of a request **reset** each `Current` instance and kept it for the next request on the thread. That assumed the instance held nothing but its declared attributes. A `Current` class that memoized a value in an instance variable, say `@permissions ||= ...`, carried it into the next request. Rails 8.1.0 changed the rule: instances are **always cleared**, abandoned after their reset callbacks run, and recreated on the next access. Memoizing inside `Current` is therefore safe per request in 8.1, but not on older versions. ## `reset` versus `set` Two calls change values mid-execution, and they behave differently: - `Current.reset` runs the same `before_reset` and `resets` callbacks and puts every attribute back to its default. It is what the framework calls for you, but an app may call it too, for example between tenants in a loop that processes several accounts in one job. - `Current.set(account: other) { ... }` changes only the named attributes for the block and restores the previous values afterwards. It runs no reset callbacks. ## Edge cases worth knowing - Reset callbacks run only for instances that were **created during the execution**. If no code touched `Current` in a request, its `resets` hook does not run then, so do not rely on `resets` to clean up state that something else set. - Code outside the executor (a raw `Thread.new`, a script outside Rails' wrappers) never gets the automatic reset; wrap such work in `Rails.application.executor.wrap { ... }`. - A job run with `perform_now` inside a request does not start a new execution, because the executor is already active; it shares the request's `Current`.
- Why does a `resets` hook sometimes not run at the end of a request?`clear_all` resets only the `Current` instances created during that execution, and an instance is created lazily on first access. If the request never read or wrote `Current`, there is no instance and no callbacks run. Cleanup for state set elsewhere belongs with the code that set it, or in an `around_action` with `ensure`.
- How would you get the automatic reset for work done in a thread you start yourself?Wrap the thread's body in `Rails.application.executor.wrap { ... }`. The executor then runs its `to_run` and `to_complete` hooks around that work, so `Current` starts empty and `clear_all` runs at the end, and the work also gets the framework's other per-execution cleanup, such as returning database connections.
- Current is reset by a before_action that every controller must call.
- resets runs before the attributes are cleared, so it can still read Current.account.
- In Rails 8.1 the same Current instance is reused for every request on a thread.
- A resets hook runs at the end of every request, even if nothing touched Current.
- Current values are cleared when the controller action returns, before the body streams.
Assumes Rails 8.1: since 8.1.0 CurrentAttributes instances are discarded at the end of each request or job instead of being reset and reused.