Skip to content

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
AdamMusa merged 12 commits into
mainfrom
fix/rails-executor-per-message
Nov 20, 2026
Merged

AdamMusa merged 12 commits into
mainfrom
fix/rails-executor-per-message

Conversation

@AdamMusa

@AdamMusa AdamMusa commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner

Fixes #101

What changed

Ruflet::Rails.native used to wrap a client's whole WebSocket in one Rails.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_connection run inside Protocol::Execution#run / #finish (new file protocol/execution.rb).
  • The executor resets 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, Execution takes 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, resets callbacks (such as Time.zone = nil) do not run between messages, and setters are not called again.
    • If development reloads a Current class between two messages, its values are copied into an instance of the reloaded class.
  • An error raised by the entrypoint or a handler is caught inside the run and re-raised outside it. The connection protocol still handles it as before, and the executor does not also report it to Rails.error as unhandled.
  • Endpoint lets a server that declares runs_messages_in_rails_executor? (LocalServer) manage the executor. Any other server passed to Endpoint.new(server:) keeps the old whole-socket wrap.
  • Without a Rails app (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.

  1. The query cache and the connection lease now last one message, not the whole connection. A handler that repeats a query sees rows other processes wrote since the previous message. A leased database connection goes back to the pool after each message, unless a transaction is still open, the same rule Rails applies after a request.
  2. In development, code can reload between two messages of a connected client. Previously the reload hung until the client disconnected. A connected page keeps its handler blocks and the objects they captured before the reload, while constants resolve to the reloaded classes. Code that mixes the two can fail until the client reconnects. Example: the entrypoint runs post = Post.create!, post.rb is edited, and the handler's Comment.create!(post: post) then raises ActiveRecord::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; session is 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.
  3. CurrentAttributes and the error/event reporter context stay what the app set. This holds for the rest of the connection, through snapshot and restore, so nothing visible changes for apps. Without this, Current.* set in the entrypoint would reset after the first message. The test test_execution_state_the_app_sets_lasts_until_the_client_disconnects passes 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, using test/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/lib and with this branch:

Test main's lib this branch
edit app code while a client is connected → GET /up fails: "blocked" (expected [200, "v2"]) pass; the click after the reload sees Widget::VERSION == 2 and Current.user still set
handler re-queries after another connection inserted fails: 0 (expected 1) pass
pool of 1, entrypoint leased a connection → HTTP query fails: ActiveRecord::ConnectionTimeoutError pass
each message and the disconnect get their own run (stub) errors: Execution does not exist pass
a unit inside an outer executor run starts no run of its own (stub) errors: Execution does not exist pass
Endpoint starts no run for a server that declares its own (stub) fails: the socket is wrapped pass
Endpoint keeps the socket run for any other server (stub) pass (parity) pass
CurrentAttributes / Time.zone / error + event context persist across clicks, reset once at disconnect pass (parity) pass
entrypoint and handler errors not reported to Rails.error pass (parity) pass

Mutations planted on this branch, each caught:

  • LocalServer not declaring runs_messages_in_rails_executor? (the old whole-socket wrap): the three real-Rails bug tests fail.
  • Per-message wrap without the carry-over: the execution-state test fails, and after the reload Current.user is nil.
  • Errors flowing through the executor (raise in place of failure = 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.error receives ["entrypoint failed"].
  • Endpoint always calling handle_socket bare, or always wrapping: one stub test fails each.
  • No executor.active? guard in Execution#perform: 2 runs instead of 1.
  • A 50 ms delay inside the run after the patch is sent (the race the merge gate hit): the stub test now waits for the run to end and passes.

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 /up after 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 shows count=1 (count=0 on main).

Suites on the final head ca3db23:

  • packages/ruflet_rails, one process per file under bundle 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 plain ruby -Ilib -Itest, with Rails and sqlite3 installed, rails_executor_test.rb runs 9 tests with 0 failures and 0 skips.
  • rails_executor_test.rb on Ruby 3.4.5 (the CI version) with Rails 8.0.2: 9 runs, 0 failures, 0 skips.
  • H1 goldens: ruby test/compat/compat.rb --jobs 4 checked 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>:packages gives 354e6bd3 for both); the last main merge brought in only ruby_runtime, tools and CI files.

Not covered: CI does not run the packages/ruflet_rails tests today.

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant