Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

test: deflake TTL-takeover websocket test (#9912)

Kiran Gadhavea46aff86cdf9
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 25186c7a18..5605f86e58 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -468,44 +468,91 @@ async def test_ttl_close_does_not_kill_session_owned_by_new_consumer(
2. Consumer A disconnects → TTL timer scheduled
3. Consumer B connects with same session_id → takes over session
4. TTL timer fires → must NOT close the session
+
+ The TTL close callback is captured rather than scheduled on a real timer,
+ then fired by hand only after Consumer B has provably taken over. This
+ exercises the live guard in `_close` deterministically, without racing a
+ wall-clock timer against Consumer B's connect. Firing inline is safe: when
+ a consumer has taken over, `_close` short-circuits at the guard with only
+ synchronous reads and never touches the event loop.
"""
session_manager = get_session_manager(client)
session_manager.mode = SessionMode.RUN
session_manager.ttl_seconds = 120 # enable TTL (run mode default)
- # Step 1: Consumer A connects
- with client.websocket_connect(WS_URL) as ws_a:
- data = ws_a.receive_json()
- assert_kernel_ready_response(data)
-
- session = session_manager.get_session("123")
- assert session is not None
-
- # Override session TTL to a very short value for the test
- session.ttl_seconds = 0.3
-
- # Consumer A has disconnected — _on_disconnect schedules _close() in 0.3s
- # Step 2: Consumer B connects immediately (before TTL fires)
- with client.websocket_connect(WS_URL) as ws_b:
- data = ws_b.receive_json()
- assert data["op"] == "reconnected", (
- f"Expected reconnected, got {data.get('op')} — "
- "session may have been closed before Consumer B connected"
- )
+ captured: list[Callable[[], None]] = []
+ real_get_running_loop = asyncio.get_running_loop
+
+ class _CaptureCloseLoop:
+ """Event-loop wrapper that diverts only the TTL close callback.
+
+ `_on_disconnect` schedules the session close via `call_later`; capturing
+ that one callback lets the test fire it on demand. Every other loop
+ operation forwards to the real loop untouched.
+ """
+
+ def __init__(self, loop: Any) -> None:
+ self._loop = loop
+
+ def call_later(
+ self, delay: float, callback: Callable[[], None], *args: Any
+ ) -> Any:
+ if "_on_disconnect" in getattr(callback, "__qualname__", ""):
+ captured.append(callback)
+ return MagicMock()
+ return self._loop.call_later(delay, callback, *args)
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._loop, name)
+
+ # Step 1: Consumer A connects → session created. Entered manually (not via
+ # `with`) because the disconnect must happen under the patch below; the
+ # try/finally guarantees the session is closed exactly once even if an
+ # assertion fails before the deliberate disconnect.
+ ws_a = client.websocket_connect(WS_URL)
+ ws_a.__enter__()
+ a_disconnected = False
+ try:
+ assert_kernel_ready_response(ws_a.receive_json())
+ assert session_manager.get_session("123") is not None
+
+ # Step 2: Consumer A disconnects under the patch so its TTL close is
+ # captured instead of scheduled. The patch stays active until the
+ # server loop has processed the disconnect.
+ with patch(
+ "marimo._server.api.endpoints.ws_endpoint.asyncio.get_running_loop",
+ lambda: _CaptureCloseLoop(real_get_running_loop()),
+ ):
+ a_disconnected = True
+ ws_a.__exit__(None, None, None)
+ for _ in range(200):
+ if captured:
+ break
+ await asyncio.sleep(0.01)
+ assert captured, "Consumer A disconnect did not schedule a TTL close"
+
+ # Step 3: Consumer B takes over the same session
+ with client.websocket_connect(WS_URL) as ws_b:
+ data = ws_b.receive_json()
+ assert data["op"] == "reconnected", (
+ f"Expected reconnected, got {data.get('op')}"
+ )
- # Step 3: Wait for Consumer A's TTL timer to fire
- # (Unit test test_ttl_close_skips_when_session_has_active_consumer
- # verifies the fix; integration timing may vary with TestClient)
- await asyncio.sleep(0.4)
+ # Step 4: Fire Consumer A's stale TTL close now that Consumer B is
+ # the active consumer. The guard must see B's OPEN session and skip
+ # the close.
+ for ttl_close in captured:
+ ttl_close()
- # Session must still be alive — Consumer B is actively connected
- # (Without the fix, the old handler's TTL timer would have killed it)
- session = session_manager.get_session("123")
- assert session is not None, (
- "Session was killed by old handler's TTL timer "
- "despite having an active consumer"
- )
- assert session.connection_state() == ConnectionState.OPEN
+ session = session_manager.get_session("123")
+ assert session is not None, (
+ "Session was killed by old handler's TTL timer "
+ "despite having an active consumer"
+ )
+ assert session.connection_state() == ConnectionState.OPEN
+ finally:
+ if not a_disconnected:
+ ws_a.__exit__(None, None, None)
def test_ttl_close_skips_when_session_has_active_consumer() -> None: