Repository navigation
ruflet_rails: run each WebSocket message in its own Rails executor (fixes dev hang after code edits, stale query cache, leaked DB connections) - #102
Merged
Conversation
Ruflet::Rails.native wrapped a client's whole WebSocket in a single Rails.application.executor.wrap. While a client stayed connected: - in development, the socket thread held the code-reload interlock share, so the first request after a code edit (and every request after it) hung until the client disconnected; - the Active Record query cache stayed on for the whole connection, so a handler that repeated a query read rows cached before other processes wrote; - a leased database connection never went back to the pool, so N clients could exhaust a pool of N and HTTP requests failed with ConnectionTimeoutError. LocalServer now runs each message, and the disconnect, as one executor run, like Rails runs an HTTP request and ActionCable runs a channel command. The executor resets CurrentAttributes and the error/event reporter context when a run completes. A connection used to keep that state until it disconnected, so Execution carries it from one run to the next and lets the executor reset it once, at the disconnect, as before. Handler errors are re-raised outside the run, so they are still only logged plus session_crashed, and not also reported to Rails.error. Endpoint keeps the whole-socket wrap for any other server passed to it. Fixes #101
…point errors, the endpoint's socket run and nested runs - The stub test read the initial patch and checked executor.active? at once, while the server thread could still be finishing the run that sent it. It now waits with a deadline. - The error scenario also raises from the entrypoint, so it keeps guarding the executor's error capture once handler errors are rescued earlier. - Endpoint keeps the whole-socket run for a server that does not declare runs_messages_in_rails_executor?, and starts none for one that does. - A unit inside an outer executor run starts no run of its own. - The harness removes its temporary app directory before exit!.
Under bundle exec the full file runs with ::Rails already defined, so the endpoint tests skipped. Stub Endpoint#rails_executor_wrap on the instance instead; session_registry_test covers that the wrap uses Rails.application.executor.
This was referenced Nov 20, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #101
What changed
Ruflet::Rails.nativeused to wrap a client's whole WebSocket in oneRails.application.executor.wrap. Now each client message, and the disconnect, is its own executor run. This is how Rails runs an HTTP request and how Action Cable runs a channel command.Protocol::LocalServer#handle_message/#close_connectionrun insideProtocol::Execution#run/#finish(new fileprotocol/execution.rb).ActiveSupport::CurrentAttributes,ActiveSupport::ExecutionContext(Rails.error.set_context) and, on Rails 8.1, the event reporter context when a run completes. Before this change a connection kept that state until it disconnected. To keep it that way,Executiontakes the CurrentAttributes instances off a run before it completes and puts the same instances back at the start of the next run. It also carries the two contexts. The executor then resets everything once, at the disconnect. Because the instances are never reset in between,resetscallbacks (such asTime.zone = nil) do not run between messages, and setters are not called again.Currentclass between two messages, its values are copied into an instance of the reloaded class.Rails.erroras unhandled.Endpointlets a server that declaresruns_messages_in_rails_executor?(LocalServer) manage the executor. Any other server passed toEndpoint.new(server:)keeps the old whole-socket wrap.ruflet run, tests, the H1 harness), the executor is nil and nothing changes.Behavior changes
All three are part of the bug fix. App code does not need to change.
post = Post.create!,post.rbis edited, and the handler'sComment.create!(post: post)then raisesActiveRecord::AssociationTypeMismatch; on main the reload never happened, so the click succeeded and every HTTP request hung instead. An HTML-DSL screen gets a new controller instance from the reloaded class, so its instance variables (such as@count) start over;sessionis kept. Production does not reload code, so this applies to development only. Disconnecting clients on reload, as Action Cable does, would be a further change; this PR does not do that.Current.*set in the entrypoint would reset after the first message. The testtest_execution_state_the_app_sets_lasts_until_the_client_disconnectspasses both on main and on this branch; it fails when the carry-over is removed.How verified
New
packages/ruflet_rails/test/rails_executor_test.rb. Five scenarios each boot a real Rails app (development reloading,FileUpdateChecker, Active Record on SQLite) in their own process, usingtest/support/rails_executor_app.rb, so no booted app shares a process with the test files that stub::Rails. Four tests use a stub executor and need no Rails.Results with main's
packages/ruflet_rails/liband with this branch:GET /up"blocked"(expected[200, "v2"])Widget::VERSION == 2andCurrent.userstill set0(expected1)ActiveRecord::ConnectionTimeoutErrorExecutiondoes not existExecutiondoes not existEndpointstarts no run for a server that declares its own (stub)Endpointkeeps the socket run for any other server (stub)Rails.errorMutations planted on this branch, each caught:
runs_messages_in_rails_executor?(the old whole-socket wrap): the three real-Rails bug tests fail.Current.userisnil.raisein place offailure = e): the error test fails. With open PR fix: a raising event handler no longer ends the ruflet_rails session #97 merged in (it rescues handler errors earlier), the entrypoint case still catches it:Rails.errorreceives["entrypoint failed"].Endpointalways callinghandle_socketbare, or always wrapping: one stub test fails each.executor.active?guard inExecution#perform: 2 runs instead of 1.The real-Puma end-to-end repro (Puma 7.2.1, Rails 8.1.3.1, development, route-mounted, TCP WebSocket client) on this branch:
GET /upafter an edit with a client connected returns 200 in 0.02 s (on main it timed out after 8 s), and the click handler's patch showscount=1(count=0on main).Suites on the final head ca3db23:
packages/ruflet_rails, one process per file underbundle exec: all 18 files green.bundle exec rake test: 304 runs, 0 failures, 2 skips. The skips are the two Active Record scenarios, because sqlite3 is not in this package's bundle. Under plainruby -Ilib -Itest, with Rails and sqlite3 installed,rails_executor_test.rbruns 9 tests with 0 failures and 0 skips.rails_executor_test.rbon Ruby 3.4.5 (the CI version) with Rails 8.0.2: 9 runs, 0 failures, 0 skips.ruby test/compat/compat.rb --jobs 4checked 292 goldens, exit 0.ruby -Ilib -Itest test/compat_goldens_test.rb: 300 runs, 0 failures.The mutation checks, the main-lib table, the Ruby 3.4.5 run and the Puma repro ran on bcbe20c. Its
packages/tree is identical to ca3db23 (git rev-parse <sha>:packagesgives 354e6bd3 for both); the last main merge brought in onlyruby_runtime,toolsand CI files.Not covered: CI does not run the
packages/ruflet_railstests today.