|
14 | 14 |
|
15 | 15 | from __future__ import annotations |
16 | 16 |
|
| 17 | +import asyncio |
| 18 | +import gc |
| 19 | +import logging |
17 | 20 | import sys |
18 | 21 | import time |
19 | 22 | from pathlib import Path |
@@ -425,3 +428,89 @@ def test_ws_disconnect_releases_active_session( |
425 | 428 |
|
426 | 429 | assert run_async(active.current()) is None |
427 | 430 | assert stub.end_calls == 1 |
| 431 | + |
| 432 | + |
| 433 | +# --------------------------------------------------------------------------- |
| 434 | +# The drained pull future is retrieved on every exit |
| 435 | +# --------------------------------------------------------------------------- |
| 436 | + |
| 437 | + |
| 438 | +class _GatedStub(StubTransport): |
| 439 | + """A transport whose stream drains only when the test says so. |
| 440 | +
|
| 441 | + ``events()`` yields ``Started`` and then waits on an ``asyncio.Event`` |
| 442 | + created in the server loop; setting it ends the generator, which is what |
| 443 | + a real session's ``end()`` does when it pushes the queue sentinel. |
| 444 | + """ |
| 445 | + |
| 446 | + def __init__(self) -> None: |
| 447 | + super().__init__() |
| 448 | + self.release: asyncio.Event | None = None |
| 449 | + |
| 450 | + async def events(self): # type: ignore[override] |
| 451 | + self.release = asyncio.Event() |
| 452 | + yield Started(agent="claude") |
| 453 | + await self.release.wait() |
| 454 | + |
| 455 | + |
| 456 | +class TestDrainedPullFuture: |
| 457 | + def test_a_drain_that_lands_beside_a_takeover_is_retrieved( |
| 458 | + self, |
| 459 | + config: SessionConfig, |
| 460 | + caplog: pytest.LogCaptureFixture, |
| 461 | + monkeypatch: pytest.MonkeyPatch, |
| 462 | + ) -> None: |
| 463 | + """Regression: ``Task exception was never retrieved ... StopAsyncIteration``. |
| 464 | +
|
| 465 | + The pump pulls each transport event as its own future. When a newer |
| 466 | + socket takes the consumer slot at the same moment the stream drains, |
| 467 | + the pump raised ``_SupersededError`` before reading the drained |
| 468 | + future's ``StopAsyncIteration``, and its ``finally`` left a *done* |
| 469 | + future neither cancelled nor read -- so asyncio logged the exception |
| 470 | + from the future's finalizer. Seen live on 2026-09-23 when a PWA tab |
| 471 | + reattached to a session whose transport had already ended. |
| 472 | + """ |
| 473 | + from studyloop.web.routes.session import _grace |
| 474 | + |
| 475 | + # The pump must wake because the pull completed, never because its |
| 476 | + # supersede poll timed out first: that path cancels a still-pending |
| 477 | + # pull and never exhibited the leak. |
| 478 | + monkeypatch.setattr(_grace, "SUPERSEDE_POLL_S", 5.0) |
| 479 | + stub = _GatedStub() |
| 480 | + _install_active(stub, config) |
| 481 | + |
| 482 | + with ( |
| 483 | + TestClient(create_app()) as client, |
| 484 | + caplog.at_level(logging.ERROR, logger="asyncio"), |
| 485 | + ): |
| 486 | + portal = client.portal |
| 487 | + assert portal is not None |
| 488 | + with client.websocket_connect( |
| 489 | + "/api/session/ws?study_session_id=study-1", |
| 490 | + headers={"Origin": "http://127.0.0.1:8788"}, |
| 491 | + ) as ws: |
| 492 | + assert ws.receive_json() == {"type": "started", "agent": "claude"} |
| 493 | + |
| 494 | + def takeover_and_drain() -> None: |
| 495 | + # The synchronous half of ``_grace.acquire_consumer``: a |
| 496 | + # newer socket has claimed the slot ... |
| 497 | + holder = _grace._attachment # pyright: ignore[reportPrivateUsage] |
| 498 | + assert holder is not None |
| 499 | + holder.superseded = True |
| 500 | + # ... and the stream drains in the same loop turn. |
| 501 | + assert stub.release is not None |
| 502 | + stub.release.set() |
| 503 | + |
| 504 | + portal.call(takeover_and_drain) |
| 505 | + frame = ws.receive_json() |
| 506 | + assert frame["type"] == "attach_superseded" |
| 507 | + |
| 508 | + # A future whose exception was never read logs from its finalizer; |
| 509 | + # force the finalizer so the assertion does not depend on refcount luck. |
| 510 | + gc.collect() |
| 511 | + leaked = [ |
| 512 | + record.getMessage() |
| 513 | + for record in caplog.records |
| 514 | + if record.name == "asyncio" and "never retrieved" in record.getMessage() |
| 515 | + ] |
| 516 | + assert leaked == [], leaked[0] |
0 commit comments