ActiveSupport::IsolatedExecutionState.share_with shallow-copies nested state, leaking mutations (e.g. ActiveRecord's connected_to_stack) across threads
Steps to reproduce
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem "activesupport", "8.0.5.1"
end
require "active_support"
require "active_support/isolated_execution_state"
# `ActiveRecord::Core.connected_to_stack` stores its stack under exactly this
# key, and `ActionController::Live` calls `share_with` to copy a streaming
# request's execution state into the thread it spawns for the response body
# (actionpack/lib/action_controller/metal/live.rb):
#
# ActiveSupport::IsolatedExecutionState.share_with(t1, except: self.class.live_streaming_excluded_keys)
main_thread = Thread.current
main_thread.active_support_execution_state = { active_record_connected_to_stack: [] }
spawned_thread = Thread.new do
ActiveSupport::IsolatedExecutionState.share_with(main_thread)
# The spawned thread pushes a frame onto what it believes is its own,
# isolated connected_to stack (mirrors ActiveRecord::Core#connected_to).
ActiveSupport::IsolatedExecutionState[:active_record_connected_to_stack] << { shard: :spawned_thread_shard }
end
spawned_thread.join
main_stack = main_thread.active_support_execution_state[:active_record_connected_to_stack]
spawned_stack = spawned_thread.active_support_execution_state[:active_record_connected_to_stack]
puts "main thread stack: #{main_stack.inspect}"
puts "spawned thread stack: #{spawned_stack.inspect}"
puts "same object? #{main_stack.equal?(spawned_stack)}"Expected behavior
share_with is documented as copying the other execution context's state into the current one. A copy should be independent: pushing a frame onto the spawned thread's active_record_connected_to_stack (e.g. via ActiveRecord::Base.connected_to) should not be visible from the main thread's stack, and vice versa.
Expected output:
main thread stack: []
spawned thread stack: [{:shard=>:spawned_thread_shard}]
same object? falseActual behavior
IsolatedExecutionState.share_with builds the copy with other.active_support_execution_state.dup, which is a shallow Hash#dup. Any mutable value nested inside that hash, in particular the Concurrent::Array that ActiveRecord::Core.connected_to_stack stores under :active_record_connected_to_stack, is not copied; the same array object ends up referenced from both threads' state hashes. Mutating the stack from either thread (pushing/popping a connected_to frame) is visible from the other thread as well:
main thread stack: [{:shard=>:spawned_thread_shard}]
spawned thread stack: [{:shard=>:spawned_thread_shard}]
same object? trueIn production this surfaces through ActionController::Live, which spawns a thread per streaming response and calls share_with to copy the original thread's execution state into it. Because the connected_to_stack array is shared by reference rather than copied, a connected_to/shard-swapping block entered on one of the two threads can push or pop a frame that the other thread then also observes, letting the streaming thread and the request thread corrupt each other's view of the current shard/role, rather than staying isolated as share_with intends. Concretely, this ends up failing requests because at least one of them then fails to lookup a record from the database.
Suggested fix
Changing state.dup to state.deep_dup in share_with fixes the reproduction above: each thread ends up with its own connected_to_stack array, and mutating one doesn't affect the other. We've been running with this patched in locally (monkey-patching IsolatedExecutionState.share_with via prepend) without issue.
One thing worth weighing before landing a blanket deep_dup, though: not every value stashed in this state hash is stack-shaped, per-thread data. Some keys hold what look like intentionally shared, live singletons, e.g. active_record_connection_handler, which owns the process's connection pools via ActiveRecord::ConnectionAdapters::ConnectionHandler. Only Array and Hash override deep_dup to recurse; everything else falls back to Object#deep_dup (duplicable? ? dup : self). ConnectionHandler doesn't opt out of duplicable? (that's reserved for Method/UnboundMethod and classes including Singleton), so a blanket deep_dup on the state hash would call plain dup on it: a new ConnectionHandler object whose internal @connection_name_to_pool_manager still points at the same underlying Concurrent::Map. The spawned thread would end up with a distinct object identity for something that's arguably supposed to stay the exact same object across threads. We didn't hit a concrete failure from that in our case, but the question I discussed with @tenderlove at RailsWorld: should share_with deep-copy the whole state hash indiscriminately, or should the copy-vs-share behavior be declared per key (similar to how except: already opts individual keys out of the copy entirely)? If the latter, how would that be configured for the different frameworks?
System configuration
Rails version: 8.0.5.1 (reproduces on main/8.1.3 too; IsolatedExecutionState#share_with in activesupport/lib/active_support/isolated_execution_state.rb still does state.dup there, it was just reshaped to take a block)
Ruby version: 3.4.8 (also reproduces under 3.3.x and 4.0.6; not Ruby-version-specific)
Source: rails/rails