Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
test(ci): prove cancellation completes before cleanup (#1921)
Call Whitef80fd9c99de0
diff --git a/docs/plans/ci-cancel-completion-evidence.md b/docs/plans/ci-cancel-completion-evidence.mdnew file mode 100644index 000000000..52cb2d9e8--- /dev/null+++ b/docs/plans/ci-cancel-completion-evidence.md@@ -0,0 +1,78 @@+# Cancellation Completion Evidence in Internal API Tests++## Scope and Decision++Change only the two cancellation scenarios in `tests/test_internal_server.py`+and this plan. The owner approved this correctness repair, followed by a+separate review of Model Hub authority scan boundaries and repeated parsing.+Further dedicated CI optimization stops after those two items. Historical+migrations, locking tests, installation isolation, UI coverage, runner counts,+and shard allocation remain unchanged.++At base `47300bfb8`, the durable cancellation path already distinguishes an+accepted Stop receipt from terminal evidence. No production cancellation bug+was established, so no production change is warranted.++## Observed False Positives++A temporary probe around the original tests recorded the state immediately+before `asyncio.run` began loop cleanup:++- The queued-message test received a successful Stop receipt at 0.108 seconds.+ Its synthetic work returned naturally at 5.108 seconds, but the streaming+ dispatch was still alive at 6.680 seconds. Loop cleanup cancelled that+ dispatch, which then resumed the queued message. The test passed.+- The scheduled test received its receipt at 0.087 seconds. Its actual dispatch+ remained alive at 4.462 seconds, even after cancelling the separate submission+ task. Loop cleanup cancelled the dispatch at 4.463 seconds. The test passed.++Thus both tests could pass without proving completion before teardown. These+local observations establish a test-oracle defect, not a hosted-runner cause or+a production cancellation failure.++## Completion Contract++The synthetic backend exposes separate Stop-received and terminal-ready events.+Only the original cancellation route may request Stop. Before releasing terminal+evidence, each test verifies the exact stopped context, successful receipt, and+continued ownership of the live task; queued work must not have started yet.++The human test releases the real streaming sink through+`Controller.mark_turn_complete` with the existing `stopped` settlement. The+scheduled dispatch double returns that same settlement. The tests then join the+actual dispatch tasks, verify durable `canceled` outcomes and released ownership,+and verify queued work has finished, all before cleanup can cancel any task.+Submission admission is not treated as dispatch completion.++Event/task waits are bounded at three seconds, matching the existing startup+wait convention. Shielding the dispatch prevents timeout cancellation from+creating the evidence under test. `finally` cancels and joins remaining tasks+only for cleanup. No sleep, polling retry, fake clock, production timeout,+workflow timeout, test-selection, or dependency change is introduced.++## Evidence++- All 175 original top-level definitions and 844 assertions remain; only the two+ named test bodies change. Every unrelated definition is AST-identical.+- Both focused tests pass, followed by all 176 internal-server cases in 12.01+ seconds and 109 dispatch, stream-sink, priority-cutover, and workflow cases.+- A diagnostic mutation suppressing terminal-ready delivery makes both tests+ fail at the shielded completion wait. Cleanup still joins the pending work.+ Suppressing the Stop-received signal also makes both fail before that wait.+- Ruff 0.4.9, dependency compatibility, and whitespace validation pass.+- The temporary probes are not committed. Local timing is not a CI speedup+ claim; the main benefit is removing false-positive completion evidence.++## Delivery Gates and Residuals++Require a current-head Codex PASS, complete review/comment/thread inventory,+zero unresolved whole-PR threads, all 17 expected checks, every exact-head lint+run successful, and clean scope/integration before guarded exact-head squash.+Then verify the exact merged source with its own master Actions run, including+the complete unit selection and real distribution/installation/Windows gates.+The new model-catalog browser checks from base PR #1919 remain in the UI job.+The current findings-bearing review-head count is zero before PR creation.++No real backend or production service is invoked locally. Backend stop transport+behavior remains covered by its existing tests; these scenarios validate the+internal API's receipt-to-completion and queue-resumption contracts.diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 47b187757..2b56b0d6e 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -4390,41 +4390,77 @@ def test_cancel_resumes_the_oldest_queued_segment(monkeypatch, tmp_path):session_id = session["id"]started = asyncio.Event()+ stop_requested = asyncio.Event()+ terminal_ready = asyncio.Event()+ queued_started = asyncio.Event()+ tasks: list[asyncio.Task] = []seen: list[str] = []async def long_handler(ctx, text):_bind_test_native_start(engine, ctx)+ tasks.append(asyncio.current_task())seen.append(text)if text == "first":started.set()- await asyncio.sleep(5) # held until the test cancels it+ await stop_requested.wait()+ await terminal_ready.wait()+ Controller.mark_turn_complete(controller, ctx, settled_by=SETTLED_BY_STOPPED)else:- controller.mark_turn_complete(ctx)- return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)+ Controller.mark_turn_complete(controller, ctx, settled_by=SETTLED_BY_TERMINAL_RESULT)+ queued_started.set()++ async def stop_backend(ctx):+ assert ctx is app.state.in_flight_dispatches[session_id].context+ stop_requested.set()+ return Truecontroller = _build_controller_double(handler=long_handler)+ controller.command_handler.handle_stop = AsyncMock(side_effect=stop_backend)app = internal_server.create_app(controller)transport = httpx.ASGITransport(app=app)async def _go():- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:- await client.post(- "/internal/dispatch_async",- json={- "session_id": session_id,- "text": "first",- "user_message_id": first["id"],- },- )- await asyncio.wait_for(started.wait(), timeout=3)- # Queue a message while the turn runs, then Stop.- with engine.begin() as conn:- message_deliveries.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q1")- await client.post(f"/internal/cancel/{session_id}")- for _ in range(300):- if seen == ["first", "q1"] and session_id not in app.state.in_flight_dispatches:- break- await asyncio.sleep(0.02)+ try:+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ response = await client.post(+ "/internal/dispatch_async",+ json={+ "session_id": session_id,+ "text": "first",+ "user_message_id": first["id"],+ },+ )+ assert response.status_code == 202+ await asyncio.wait_for(started.wait(), timeout=3)+ turn = app.state.in_flight_dispatches[session_id]+ # A receipt alone cannot retire the active owner or start q1.+ with engine.begin() as conn:+ message_deliveries.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q1")+ response = await client.post(f"/internal/cancel/{session_id}")+ assert response.status_code == 200+ assert response.json()["status"] == "cancel_requested"+ controller.command_handler.handle_stop.assert_awaited_once_with(turn.context)+ assert stop_requested.is_set()+ assert not turn.task.done()+ assert app.state.in_flight_dispatches[session_id] is turn+ assert seen == ["first"]++ terminal_ready.set()+ await asyncio.wait_for(asyncio.shield(turn.task), timeout=3)+ await asyncio.wait_for(queued_started.wait(), timeout=3)+ await asyncio.wait_for(asyncio.shield(tasks[-1]), timeout=3)+ assert all(task.done() and not task.cancelled() for task in tasks)+ assert session_id not in app.state.in_flight_dispatches+ with engine.connect() as conn:+ stopped_turn = message_deliveries.get_turn(conn, turn.logical_turn_id)+ assert stopped_turn["terminal_outcome"] == "canceled"+ finally:+ # Failure cleanup must not manufacture the completion asserted above.+ pending = set(tasks) | {entry.task for entry in app.state.in_flight_dispatches.values()}+ for task in pending:+ if not task.done():+ task.cancel()+ await asyncio.gather(*pending, return_exceptions=True)asyncio.run(_go())with engine.connect() as conn:@@ -7157,18 +7193,27 @@ def test_scheduled_gate_cancel_stops_scheduled_run(monkeypatch, tmp_path):session_id = session["id"]started = asyncio.Event()+ stop_requested = asyncio.Event()+ terminal_ready = asyncio.Event()async def _long_dispatch_turn(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None, **_kwargs):_bind_test_native_start(engine, ctx)started.set()- await asyncio.sleep(5) # held until the test cancels it- return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)+ await stop_requested.wait()+ await terminal_ready.wait()+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_STOPPED)++ async def stop_backend(stop_context):+ assert stop_context is app.state.in_flight_dispatches[session_id].context+ stop_requested.set()+ return Truemonkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _long_dispatch_turn)controller = _build_controller_double()+ controller.command_handler.handle_stop = AsyncMock(side_effect=stop_backend)app = internal_server.create_app(controller)transport = httpx.ASGITransport(app=app)ctx = MessageContext(user_id="workbench", channel_id=session_id, platform="avibe")@@ -7176,15 +7221,37 @@ def test_scheduled_gate_cancel_stops_scheduled_run(monkeypatch, tmp_path):async def _go():# Start the scheduled run in the background (it holds in_flight open).run = asyncio.create_task(controller.session_turn_gate.submit_scheduled(session_id, ctx, "scheduled run"))- await asyncio.wait_for(started.wait(), timeout=3)- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:- resp = await client.post(f"/internal/cancel/{session_id}")- for _ in range(200):- if session_id not in app.state.in_flight_dispatches:- break- await asyncio.sleep(0.02)- run.cancel()- return resp+ turn = None+ try:+ await asyncio.wait_for(started.wait(), timeout=3)+ turn = app.state.in_flight_dispatches[session_id]+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ resp = await client.post(f"/internal/cancel/{session_id}")+ assert resp.status_code == 200+ assert resp.json()["status"] == "cancel_requested"+ controller.command_handler.handle_stop.assert_awaited_once_with(turn.context)+ assert stop_requested.is_set()+ assert not turn.task.done()+ assert app.state.in_flight_dispatches[session_id] is turn++ terminal_ready.set()+ # Submission is admission, not completion: join the real dispatch too.+ await asyncio.wait_for(asyncio.shield(turn.task), timeout=3)+ await asyncio.wait_for(asyncio.shield(run), timeout=3)+ assert turn.task.done() and not turn.task.cancelled()+ assert session_id not in app.state.in_flight_dispatches, "slot released after the scheduled run was stopped"+ with engine.connect() as conn:+ stopped_turn = message_deliveries.get_turn(conn, turn.logical_turn_id)+ assert stopped_turn["terminal_outcome"] == "canceled"+ return resp+ finally:+ pending = {run} | {entry.task for entry in app.state.in_flight_dispatches.values()}+ if turn is not None:+ pending.add(turn.task)+ for task in pending:+ if not task.done():+ task.cancel()+ await asyncio.gather(*pending, return_exceptions=True)resp = asyncio.run(_go())assert resp.status_code == 200