Skip to content

migrate ChannelsLiveServerTestCase to thread - #2182

Open
deronnax wants to merge 3 commits into
django:mainfrom
deronnax:migrate-liveservertestcase-to-thread
Open

deronnax wants to merge 3 commits into
django:mainfrom
deronnax:migrate-liveservertestcase-to-thread

Conversation

@deronnax

@deronnax deronnax commented Sep 4, 2025 •

Copy link
Copy Markdown
Contributor

Fixes #2181. Also fixes #2194.

ChannelsLiveServerTestCase now runs the live ASGI server in a thread of the test process instead of a separate DaphneProcess, closely modelled on Django's LiveServerTestCase/LiveServerThread (server_thread_class, ChannelsLiveServerThread, port, allowed_host, connections_override, ...).

Consequences:

  • State living in the test process is shared with the server, e.g. mail.outbox (ChannelsLiveServerTestCase causes mail.outbox to always be empty #2194).
  • In-memory SQLite databases now work (the connection is shared with the server thread, as Django does), so the "can't use an in-memory database" notes are removed from the docs.
  • No more spawn/pickling of the application and no more per-process DB setup (set_database_connection, make_application).

Notes for review:

  • Twisted's reactor can't be restarted, so each server thread installs a fresh one (daphne.testing._reinstall_reactor, same as DaphneProcess) and imports daphne.server afterwards. terminate() stops that same reactor. This is what lets several ChannelsLiveServerTestCase classes run in the same process.
  • Public API kept: host, serve_static, static_wrapper, live_server_url, live_server_ws_url. Only ProtocolServerProcess is removed, as there is no server process anymore.
  • This removes the dependency on DaphneProcess (process spawning, pickling), but not on Daphne itself: the server thread still uses daphne.server.Server, daphne.endpoints and the private daphne.testing._reinstall_reactor. server_class is the extension point, but it currently expects Daphne's Server API (run(), listening_addresses, ready_callable).
  • No compatibility shim is needed for enterClassContext anymore: Django >= 5.2 provides it on SimpleTestCase for all supported Python versions.

Tests: new tests/test_live.py (shared mail.outbox, DB visibility from the server thread, serve_static on/off, URLs), plus the existing Selenium tests. Run locally on Python 3.10-3.14 with Django 5.2/6.0/6.1/main, and manually with an in-memory SQLite database.

The last commit fixes an intermittent failure of the Selenium tests (Timed out waiting for window.websocketConnected). It also occurred on main: SeleniumMixin.login() returned before the post-login redirect had started, so the next driver.get() sometimes lost the race. Full suite, one run at a time, on main: 10 failures out of 40 runs without the fix, 0 out of 40 with it.

@deronnax
deronnax force-pushed the migrate-liveservertestcase-to-thread branch 5 times, most recently from 2a600b0 to f3067b8 Compare September 4, 2025 10:04
@deronnax

deronnax commented Mar 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Btw, It should fix #2194 (which should get covered by a test, meanwhile).

(I'll come back to it soon)

fin34r added a commit to fin34r/channels that referenced this pull request Nov 11, 2026
ChannelsLiveServerThread._stop_reactor stopped the reactor unconditionally. reactor.stop() fires Daphne's before:shutdown hook, which cancels every in-flight application instance; a cancelled request is inside Django's ThreadSensitiveContext, whose __aexit__ calls executor.shutdown() -- a blocking join on the thread running the request's sync code. That thread may itself be waiting for a callback on this very loop (any async_to_sync further down the sync stack), so the two wait on each other forever: the loop thread never returns from the join and terminate() cannot stop the server.

With thread-based ChannelsLiveServerTestCase (one server per class in the shared process) the stranded worker is process-global, so the next live server in the same process queues behind it and never answers -- the sequential second-server regression. The old fork-per-server model gave each server its own process, hence its own worker.

_stop_reactor now stops the listening sockets, awaits the application instances Daphne is currently running under a bounded shutdown_grace_period (5s), and only then calls reactor.stop(). Anything still running when the budget expires is cancelled exactly as before.

Regression test: tests/sample_project/tests/test_live_server_thread_reuse.py (request in flight at teardown + sequential second server serving sync->async). Verified RED with the fix reverted, GREEN with it; the fork live-server subset (5 tests) passes with a clean exit.

Context: django#2181, PR django#2182.
fin34r added a commit to fin34r/channels that referenced this pull request Nov 11, 2026
asgiref's process-global single_thread_executor is permanently wedged once a live server's thread-sensitive worker strands — every later thread-sensitive request (incl. static-file serving) queues forever. ChannelsLiveServerThread now installs a fresh executor at server start and drains the bound executor with a thread-sensitive sentinel before reactor.stop(); terminate() join widened to cover both bounded waits. Regression: with the previous server's thread-sensitive worker occupied, the next server must still serve HTTP 200. Verified RED/GREEN (GREEN 8.3s clean; RED reproduces mute server + unusable executor). Context: django#2181, PR django#2182.
fin34r added a commit to fin34r/channels that referenced this pull request Nov 11, 2026
a stopped-but-open loop lets an AsyncToSync bridge cached in a process-global Django middleware chain silently queue onto a dead loop — every later live-server class in the process hangs in CurrentThreadExecutor.run_until_future, and cancellation locks the loop thread inside ThreadSensitiveContext executor.shutdown(). Closing the loop at run() exit (first legal point) makes the stale call raise and asgiref take its self-contained fallback. Regression: sequential live-server classes over a process-global ASGI handler with sync-over-async middleware; asserts the loop is closed and call_soon_threadsafe raises. Context: django#2181, PR django#2182.
)

Run the live ASGI server in a thread of the test process, modelled on
Django's LiveServerTestCase/LiveServerThread, instead of a separate
DaphneProcess. State living in the test process (e.g. mail.outbox) is now
shared with the server, and in-memory SQLite databases are supported.

serve_static and static_wrapper are kept. ProtocolServerProcess is removed
since there is no server process anymore.
@deronnax
deronnax force-pushed the migrate-liveservertestcase-to-thread branch from 5bdb0fe to 5349fea Compare November 12, 2026 15:08
@deronnax
deronnax marked this pull request as ready for review November 12, 2026 15:09
@deronnax
deronnax force-pushed the migrate-liveservertestcase-to-thread branch from 58779ba to 97b2b7f Compare November 12, 2026 15:30
@deronnax

Copy link
Copy Markdown
Contributor Author

97b2b7f just fixes a Selenium's flaky. I wanted to open a dedicated PR for it, but I am not allowed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ChannelsLiveServerTestCase causes mail.outbox to always be empty ChannelsLiveServerTestCase can't be run in parallel

1 participant