From ee1dd2c8d5200fdc141c1507d1b45affe6885a99 Mon Sep 17 00:00:00 2001 From: Tazeem Mahashin Date: Fri, 6 Nov 2026 19:32:37 -0500 Subject: [PATCH] fix(runtime): replay submissions during concurrent admission --- deeptutor/app/service.py | 47 +++- .../session/turns/request_preparer.py | 3 +- tests/app/test_turn_application_service.py | 212 ++++++++++++++++++ 3 files changed, 255 insertions(+), 7 deletions(-) diff --git a/deeptutor/app/service.py b/deeptutor/app/service.py index 4cee68b4d..8b9e0014e 100644 --- a/deeptutor/app/service.py +++ b/deeptutor/app/service.py @@ -128,6 +128,8 @@ class TurnApplicationService: store, runtime = self._resolve() reserve = getattr(store, "reserve_submission", None) submission_turn = getattr(store, "submission_turn", None) + submission_id = "" + previous_turn_id = "" if ( request.client_submission_id and request.persist_user_message @@ -135,6 +137,7 @@ class TurnApplicationService: and callable(reserve) and callable(submission_turn) ): + submission_id = request.client_submission_id digest = self._submission_digest(payload) payload["session_id"] = await reserve( request.client_submission_id, digest, request.session_id @@ -145,15 +148,17 @@ class TurnApplicationService: if session is None: raise RuntimeError("Conversation not found in this workspace.") return session, prior + if prior is not None: + previous_turn_id = prior["id"] try: session, turn = await runtime.start_turn(payload) except ActiveTurnConflict: - if request.client_submission_id and callable(reserve) and callable(submission_turn): - prior = await submission_turn(request.client_submission_id) - if prior is not None: - session = await store.get_session(prior["session_id"]) - if session is not None: - return session, prior + if submission_id: + replay = await self._wait_for_submission_receipt( + store, submission_id, payload["session_id"], previous_turn_id + ) + if replay is not None: + return replay # Retry once, and only after something was actually reclaimed, so a # session busy with a live turn still gets its conflict. session_id = str(payload.get("session_id") or "") @@ -199,6 +204,36 @@ class TurnApplicationService: ) return session, turn + # Admission takes the execution lease before atomically binding the + # submission to its durable turn. A retry on another worker must allow + # that short gap to close. Bound the wait in case the owner dies there. + _SUBMISSION_ADMISSION_WAIT_SECONDS = 5.0 + _SUBMISSION_ADMISSION_POLL_SECONDS = 0.05 + + async def _wait_for_submission_receipt( + self, + store: SessionStoreProtocol, + submission_id: str, + session_id: str, + previous_turn_id: str, + ) -> tuple[dict[str, Any], dict[str, Any]] | None: + deadline = time.monotonic() + self._SUBMISSION_ADMISSION_WAIT_SECONDS + submission_turn = getattr(store, "submission_turn") + while True: + # Read the active row first: begin_turn inserts it and binds the + # submission together. Reading the receipt first could miss it, + # then mistake its newly committed row for a competing message. + active = await store.get_active_turn(session_id) + turn = await submission_turn(submission_id) + if turn is not None and turn["id"] != previous_turn_id: + session = await store.get_session(session_id) + if session is not None: + return session, turn + return None + if active is not None or time.monotonic() >= deadline: + return None + await asyncio.sleep(self._SUBMISSION_ADMISSION_POLL_SECONDS) + async def regenerate_last_turn( self, session_id: str, diff --git a/deeptutor/services/session/turns/request_preparer.py b/deeptutor/services/session/turns/request_preparer.py index 56425c28b..a3d97f862 100644 --- a/deeptutor/services/session/turns/request_preparer.py +++ b/deeptutor/services/session/turns/request_preparer.py @@ -17,6 +17,7 @@ from deeptutor.services.session.protocol import ( SUBMISSION_PREVIOUS_TURN_FIELD, SUBMISSION_REPLAY_FIELD, SUBMISSION_USER_FIELD, + ActiveTurnConflict, ) from deeptutor.services.session.thread_attribution import ( BACKFILL_ATTEMPTED_KEY, @@ -801,7 +802,7 @@ class TurnRequestPreparer: self.owner_id, ) if lease is None: - raise RuntimeError("Session already has an active or recovering turn") + raise ActiveTurnConflict("Session already has an active or recovering turn") try: if not payload.get("preserve_session_preferences"): await self.store.update_session_preferences(session["id"], preference_update) diff --git a/tests/app/test_turn_application_service.py b/tests/app/test_turn_application_service.py index 2d2e89e98..b89397c26 100644 --- a/tests/app/test_turn_application_service.py +++ b/tests/app/test_turn_application_service.py @@ -332,6 +332,218 @@ async def test_submission_key_cannot_be_reused_for_different_content(submission_ assert calls["count"] == 1 +@pytest.mark.asyncio +@pytest.mark.parametrize("retry_failed", [False, True]) +@pytest.mark.parametrize("owner_fails", [False, True]) +async def test_concurrent_submission_waits_for_lease_owner_to_record_receipt( + submission_service, monkeypatch, retry_failed, owner_fails +): + """A reconnect can reach another worker before begin_turn binds the ID.""" + service, store, coordinator, registry, calls = submission_service + other_store = SQLiteSessionStore(store.db_path) + other, other_registry = _service(other_store, coordinator, "worker-b") + payload = {"content": "Hello", "client_submission_id": "concurrent-first-ack"} + previous_turn = None + if retry_failed: + calls["fail"] = True + _, previous_turn = await service.start_turn(payload) + [event async for event in service.subscribe_turn(previous_turn["id"])] + calls["fail"] = owner_fails + + owner_admitting = asyncio.Event() + contender_blocked = asyncio.Event() + release_owner = asyncio.Event() + begin_turn = store.begin_turn + acquire_turn = coordinator.acquire_turn + + async def delayed_begin(*args, **kwargs): + owner_admitting.set() + await release_owner.wait() + return await begin_turn(*args, **kwargs) + + async def observed_acquire(turn_id, session_id, owner_id): + lease = await acquire_turn(turn_id, session_id, owner_id) + if owner_id == "worker-b" and lease is None: + contender_blocked.set() + return lease + + monkeypatch.setattr(store, "begin_turn", delayed_begin) + monkeypatch.setattr(coordinator, "acquire_turn", observed_acquire) + first = asyncio.create_task(service.start_turn(payload)) + tasks = [first] + try: + await asyncio.wait_for(owner_admitting.wait(), 3) + second = asyncio.create_task(other.start_turn(payload)) + tasks.append(second) + await asyncio.wait_for(contender_blocked.wait(), 3) + release_owner.set() + (session, turn), (replay_session, replay_turn) = await asyncio.wait_for( + asyncio.gather(*tasks), 3 + ) + assert replay_session["id"] == session["id"] + assert replay_turn["id"] == turn["id"] + if previous_turn is not None: + assert turn["id"] != previous_turn["id"] + events = [event async for event in other.subscribe_turn(turn["id"])] + assert any(event["type"] == "done" for event in events) + assert calls["count"] == 1 + int(retry_failed) + assert len(await store.list_sessions()) == 1 + rows = await other_store.get_messages(session["id"]) + expected_roles = ["user"] if owner_fails else ["user", "assistant"] + assert [row["role"] for row in rows] == expected_roles + assert rows[0]["metadata"]["client_submission_id"] == payload["client_submission_id"] + finally: + release_owner.set() + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + await registry.get(store).close() + await other_registry.get(other_store).close() + + +@pytest.mark.asyncio +async def test_different_submission_during_admission_still_conflicts( + submission_service, monkeypatch +): + service, store, coordinator, registry, calls = submission_service + other_store = SQLiteSessionStore(store.db_path) + other, other_registry = _service(other_store, coordinator, "worker-b") + session = await store.create_session() + payload = { + "content": "Hello", + "session_id": session["id"], + "client_submission_id": "original-admission", + } + owner_admitting = asyncio.Event() + contender_blocked = asyncio.Event() + release_owner = asyncio.Event() + finish = asyncio.Event() + begin_turn = store.begin_turn + acquire_turn = coordinator.acquire_turn + + class ParkedOrchestrator: + async def handle(self, context): + await finish.wait() + yield StreamEvent(type=StreamEventType.DONE, source="chat") + + async def delayed_begin(*args, **kwargs): + owner_admitting.set() + await release_owner.wait() + return await begin_turn(*args, **kwargs) + + async def observed_acquire(turn_id, session_id, owner_id): + lease = await acquire_turn(turn_id, session_id, owner_id) + if owner_id == "worker-b" and lease is None: + contender_blocked.set() + return lease + + monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", ParkedOrchestrator) + monkeypatch.setattr(store, "begin_turn", delayed_begin) + monkeypatch.setattr(coordinator, "acquire_turn", observed_acquire) + first = asyncio.create_task(service.start_turn(payload)) + tasks = [first] + try: + await asyncio.wait_for(owner_admitting.wait(), 3) + second = asyncio.create_task( + other.start_turn({**payload, "client_submission_id": "different-admission"}) + ) + tasks.append(second) + await asyncio.wait_for(contender_blocked.wait(), 3) + release_owner.set() + _, turn = await asyncio.wait_for(first, 3) + with pytest.raises(RuntimeError, match="active or recovering turn"): + await asyncio.wait_for(second, 3) + assert await coordinator.get_lease(turn["id"]) is not None + assert await store.submission_turn("different-admission") is None + assert calls["count"] == 0 + finally: + release_owner.set() + finish.set() + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + await registry.get(store).close() + await other_registry.get(other_store).close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("with_submission", [False, True]) +async def test_unrecorded_lease_owner_cannot_hold_admission_open_forever( + submission_service, monkeypatch, with_submission +): + service, store, coordinator, registry, calls = submission_service + session = await store.create_session() + runtime = registry.get(store) + lease = await coordinator.acquire_turn( + "unrecorded-owner", f"{runtime._coordination_scope}:{session['id']}", "worker-b" + ) + assert lease is not None + payload = {"content": "Hello", "session_id": session["id"]} + if with_submission: + payload["client_submission_id"] = "still-admitting" + monkeypatch.setattr(service, "_SUBMISSION_ADMISSION_WAIT_SECONDS", 0.01) + try: + with pytest.raises(RuntimeError, match="active or recovering turn"): + await asyncio.wait_for(service.start_turn(payload), 1) + assert await coordinator.get_lease(lease.turn_id) == lease + assert await store.get_active_turn(session["id"]) is None + assert await store.submission_turn("still-admitting") is None + assert calls["count"] == 0 + finally: + await coordinator.release_turn(lease) + await runtime.close() + + +@pytest.mark.asyncio +async def test_cancelling_receipt_wait_preserves_owner_and_later_replay( + submission_service, monkeypatch +): + service, store, coordinator, registry, calls = submission_service + session = await store.create_session() + runtime = registry.get(store) + lease = await coordinator.acquire_turn( + "admitting-owner", f"{runtime._coordination_scope}:{session['id']}", "worker-b" + ) + assert lease is not None + payload = { + "content": "Hello", + "session_id": session["id"], + "client_submission_id": "cancelled-waiter", + } + waiting = asyncio.Event() + get_active_turn = store.get_active_turn + + async def observed_active(session_id): + row = await get_active_turn(session_id) + waiting.set() + return row + + monkeypatch.setattr(store, "get_active_turn", observed_active) + retry = asyncio.create_task(service.start_turn(payload)) + try: + await asyncio.wait_for(waiting.wait(), 3) + retry.cancel() + with pytest.raises(asyncio.CancelledError): + await retry + assert await coordinator.get_lease(lease.turn_id) == lease + turn = await store.begin_turn( + session["id"], + submission_id=payload["client_submission_id"], + turn_id=lease.turn_id, + owner_id=lease.owner_id, + fencing_token=lease.fencing_token, + ) + replay_session, replay_turn = await service.start_turn(payload) + assert replay_session["id"] == session["id"] + assert replay_turn["id"] == turn["id"] + assert calls["count"] == 0 + finally: + retry.cancel() + await asyncio.gather(retry, return_exceptions=True) + await coordinator.release_turn(lease) + await runtime.close() + + @pytest.mark.asyncio async def test_second_worker_reads_shared_event_tail_without_mutating_turn(tmp_path) -> None: db_path = tmp_path / "chat_history.db"