Repository navigation
fix(watchdog): claim a finished sync turn's retained terminal instead of failing it after a backend restart (#2944) - #2947
Merged
Conversation
… of failing it after a backend restart (#2944) A synchronously dispatched turn — every trigger while DISPATCH_ASYNC is off, not only mcp/manual — returns its terminal on the held-open HTTP connection, and that coroutine is its only consumer. A backend recreate mid-turn destroys it: the agent finishes and bills, returns to a dead socket, and the watchdog skipped the row for one cycle (the #921 recently-completed marker, 300 s — exactly one cleanup interval) and FAILED it on the next with the #2433 orphan string, cost=NULL, response=NULL. Its only agent probe before the destructive write was /last-error; nothing asked for a result. Agent (docker/base-image/agent_server): - services/retained_results.py: every terminal exit of /api/task and /api/chat retains its envelope — the same typed shape the #1083 result callback POSTs (success / cancelled / HTTPException failure) — BEFORE the response is sent, under ~/.trinity/retained-results/<id>.json. Bounded: TTL 6 h, 50 newest files, transcript dropped past the callback's 16 MB cap. Same-id overwrite (the SUB-003 retry). Separate from pending-results on purpose: that directory's startup sweep re-POSTs to the callback, where a sync envelope is a permanent 409 and is deleted. - GET /api/executions/{id}/result serves it; the coded 404 {"detail":{"code":"no_retained_result"}} (for malformed ids too) is how the backend tells "asked, nothing there" from an older image's bare 404. Backend: - services/execution_envelope.py::terminal_from_callback_payload — the callback router's 3-way status map + auth-is-never-cancellation guard, extracted so the router and the watchdog share one classification. - services/cleanup_service.py: the periodic watchdog and the boot recovery ask for the retained result before writing failed — for a row the agent reports as recently completed with no live dispatcher (evaluated BEFORE the timeout/terminate branch, so a completed row past its timeout is claimed, not terminated), and for a row absent everywhere — and apply it through apply_result with the callback's exact inputs (activity_id incl. FAILED, breaker_enabled, release_slot=True). A recovered SUCCESS response carries a notice (the #1870/#2127 precedent). Claim gated on the record being >= 180 s old: track_inflight_dispatch covers only the outbound POST, so a live dispatcher reads as `absent` between its call returning and its CAS. Old image (bare 404 / non-record 200 / stub leak) keeps the pre-#2944 path unchanged; a probe that could not be asked withholds the row for a cycle (#2196). Only a won CAS counts and broadcasts (every worker runs the loop). CleanupReport gains results_recovered / result_claims_deferred / result_probe_deferred. - RECENTLY_COMPLETED_TTL_SECONDS stays 300: fetch-on-claim makes the raise the issue suggests redundant, and a raise would lengthen the #2433(C) leaked-entry shield. Tests: test_2944_retained_results.py (23) and test_2944_watchdog_claims_result.py (29); 27 of them fail on the pre-fix cleanup_service.py + chat.py (negative control). tests/unit/conftest.py points the retained store at a per-process tmp dir so handler tests never write to the developer's home. Not covered, named in the docs and DEBT_INBOX (2026-09-22): the chat transcript surface of a recovered /api/chat row, and the in-flight registration not spanning finalize/retries (the root of the 180 s grace). Fixes #2944 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Contributor
|
merge-train 2026-09-22: riding this train. Validated lane C (
|
vybe
pushed a commit
that referenced
this pull request
Sep 22, 2026
…y.json rebuilt (keep both, #2947's entries + ours) Co-Authored-By: Claude Fable 5.1 <[email protected]>
9 of 12 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
A synchronously dispatched turn (every trigger while
DISPATCH_ASYNCis off — the default — not onlymcp/manual) returns its terminal on the held-open HTTP connection, and that coroutine is its only consumer. A backend recreate mid-turn destroys it: the agent finishes and bills, returns to a dead socket, and the watchdog skipped the row for one cycle (the #921recently_completed_idsmarker, 300 s — exactly oneCLEANUP_INTERVAL_SECONDS) and failed it on the next with the #2433 orphan string,cost=NULL,response=NULL. Its only agent probe before the destructive write was/last-error; nothing asked for a result. The reported $32 run lost its response and its cost attribution.Fix: the agent retains every sync terminal; the watchdog claims it before it ever writes
failed.Agent (
docker/base-image/agent_server)services/retained_results.py(new): every terminal exit of/api/taskand/api/chatretains its envelope — the same typed shape the refactor: fire-and-forget dispatch — a hung turn holds zero backend resource #1083 result callback POSTs (_success_envelope/_cancelled_override/_envelope_from_http_exception) — before the response is sent, under~/.trinity/retained-results/<id>.json. Bounded: TTL 6 h (outlives the 120-min stale sweep + widest execution timeout + anunknownin-flight verdict while Redis is down), 50 newest files, transcript dropped past the callback's 16 MB cap (response/metadata/session always kept). Same-id overwrite (the SUB-003 retry). Best-effort — never fails the turn. Separate frompending-resultson purpose: that directory's startup sweep re-POSTs to the callback, where a sync envelope is a permanent 409 and is deleted.GET /api/executions/{id}/resultserves it. The coded 404{"detail":{"code":"no_retained_result"}}(for malformed ids too) is how the backend tells "asked, nothing there" from an older image's bare FastAPI 404.Backend
services/execution_envelope.py::terminal_from_callback_payload— the callback router's 3-way status map + auth-is-never-cancellation guard, extracted fromrouters/agents.pyso the router and the watchdog share one classification (the refactor: fire-and-forget dispatch — a hung turn holds zero backend resource #1083 endpoint tests pass unchanged).services/cleanup_service.py— periodic watchdog and boot recovery ask for the retained result before writingfailed:apply_resultwith exactly the callback's inputs (activity_idincl. FAILED,breaker_enabled,release_slot=True), so a claimed turn finalizes like a callback-delivered one (activity close, capacity, breaker, terminal event → feat(pull): make loops terminal-driven so they can run on the durable queue #2523/feat(pull): async fan-out join + sync edge adapter — the last blocking dispatch caller #2524 loop/fan-out consumers fire). A recovered SUCCESS response carries a notice (bug: completed turn discarded on error_during_execution — jsonl_recovery never consulted, response lost despite end_turn in the JSONL #1870/bug: turn ending with background subagents still in flight records the execution as SUCCESS and silently discards the work #2127 precedent).track_inflight_dispatchcovers only the outbound POST — the in-process entry is popped the instant the call returns, the cross-worker marker delete flushes on the 15 s tick, and the SUB-003/Async chat_with_agent: long execution silently fails with null response (reader-thread) #678 retries reuse the id with an uncovered gap — so a live dispatcher reads asabsentfor a window on every healthy turn, and a claim inside it would beat the caller to the CAS (emptyRECONCILEDreply, slot released twice). 180 s >INFLIGHT_MARKER_TTL60 + tick 15 + the switch gap.result_recovered) — every uvicorn worker runs the loop.CleanupReportgainsresults_recovered(intotal) /result_claims_deferred/result_probe_deferred(observability).RECENTLY_COMPLETED_TTL_SECONDSstays 300: fetch-on-claim makes the raise the issue suggests redundant, and a raise would lengthen the bug: watchdog fails admitted-but-undispatched executions as "completed on agent but status not reported", releasing their slots and masking the real terminal #2433(C) leaked-entry shield.Tests
tests/unit/test_2944_retained_results.py— 23: store (record/get, overwrite, TTL, file cap, transcript cap, containment,temp-no-op, survives re-import, failing write never raises),/api/tasksuccess/cancelled/HTTPException/cancelled-HTTPException/no-id/retention-failure,/api/chatsuccess (session id from metadata) + failure,GET /result200 + coded 404 for missing and malformed ids.tests/unit/test_2944_watchdog_claims_result.py— 29: the reported case claimed as SUCCESS (envelope, notice, the callback's exactapply_resultkwargs,confirmed_runningexclusion, event), grace gate (30 s record deferred; grace > marker TTL + tick pinned), alive/unknown never probed, completed row past timeout claimed not terminated, no-record keeps the pre-bug: watchdog fails a completed synchronous execution after a backend restart instead of recovering its result #2944 skip, lost CAS counts nothing, retained failure applied as the real error, orphan branch (found → claimed; coded 404 → extended string; bare 404 / non-record 200 / stub leak → bug: watchdog fails admitted-but-undispatched executions as "completed on agent but status not reported", releasing their slots and masking the real terminal #2433 string unchanged; transport error / 5xx / bad JSON / over-cap → withheld), caps parity with the callback endpoint, the shared mapper's rules, boot recovery (claimed immediately / fresh left for the sweep / old image recovered as before).origin/dev'scleanup_service.py+chat.pyswapped in, 27 of 52 fail; with the fix, 52 pass.test_1083_*,test_2433_*,test_watchdog_unit,test_orphaned_execution_recovery,test_startup_recovery_race,test_1804_*,test_1811_*,test_cleanup_*,test_679_terminated_marker— all green. Full unit island: 16 864 passed; the 17 failures are the known local IPv6-mapped-address set (15) + 2 order-dependenttest_ent582cases that pass in isolation on this branch and ondev.tests/unit/conftest.pypoints the retained store at a per-process tmp dir (TRINITY_RETAINED_RESULTS_DIR) so handler tests never write to the developer's home.Docs
docs/memory/architecture/execution.md(§ Retained Terminals — one home),agent-runtime.md(route + store),reliability.md(pointer),feature-flows/cleanup-service.md(helpers table, decision matrix rows, startup recovery, report counters, unit tests),requirements/infrastructure.md§12.9,learnings.md(the marker-scope + ask-for-the-outcome class).Deliberately not covered (registered in trinity-dev
DEBT_INBOX.md, 2026-09-22)/api/chatrow (assistantchat_messagesrow, collaboration activity) — needs session/user context the execution row lacks; the notice says so.Adjacent refactor #429 (cleanup pyramid) commented: this changes the verdict inside the existing Phase-0 reconcile; adds no sweep and no status writer beyond
apply_result.Fixes #2944
🤖 Generated with Claude Code