Skip to content

fix(watchdog): claim a finished sync turn's retained terminal instead of failing it after a backend restart (#2944) - #2947

Merged
vybe merged 1 commit into
devfrom
fix/2944-recover-sync-result
Sep 22, 2026
Merged

vybe merged 1 commit into
devfrom
fix/2944-recover-sync-result

Conversation

@dolho

@dolho dolho commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Summary

A synchronously dispatched turn (every trigger while DISPATCH_ASYNC is off — the default — 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_ids marker, 300 s — exactly one CLEANUP_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/task and /api/chat retains 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 + an unknown in-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 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 FastAPI 404.

Backend

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/task success/cancelled/HTTPException/cancelled-HTTPException/no-id/retention-failure, /api/chat success (session id from metadata) + failure, GET /result 200 + 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 exact apply_result kwargs, confirmed_running exclusion, 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).
  • Negative control: with origin/dev's cleanup_service.py + chat.py swapped in, 27 of 52 fail; with the fix, 52 pass.
  • Existing suites: 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-dependent test_ent582 cases that pass in isolation on this branch and on dev.
  • tests/unit/conftest.py points 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)

  • The chat transcript surface of a recovered /api/chat row (assistant chat_messages row, collaboration activity) — needs session/user context the execution row lacks; the notice says so.
  • Extending the in-flight registration to span finalize + retries (the root of the 180 s grace) — non-reentrant registry, hotspot file.
  • Timeout-side loss (backend HTTP timeout writes FAILED while the agent finishes and bills) is the sibling class, not this one.

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

… 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]>
@dolho dolho added priority-p2 Important type-bug Bug fix theme-reliability Theme: Reliability labels Sep 22, 2026
@dolho
dolho requested a review from vybe September 22, 2026 09:37
@vybe

vybe commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-09-22: riding this train. Validated lane C (/validate-pr READY, /review READY, /cso --diff CLEAN). Nothing pushed to this branch. Two notes, neither blocking:

  1. Hardening suggestion (from /review) — process_registry.list_recently_completed_ids never subtracts live _processes, so on a same-id retry (SUB-003 / Async chat_with_agent: long execution silently fails with null response (reader-thread) #678) an execution can sit in both running and recently_completed for 300 s while attempt 1's retained FAILED(auth) envelope is on disk. The new if execution_id in recently_completed: branch in _reconcile_orphaned_executions runs before the is_on_agent branch, so safety there rests on the in-flight marker. A one-liner closes it: ids.recently_completed = recent_ids - running_ids in _extract_agent_known_ids, plus a test for _known(running=("exec-1",), recent=("exec-1",)). Worth a follow-up.
  2. Deploy note — the fix is inert on agents still running the old base image (the backend deliberately takes 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 path on a bare 404). bug: watchdog fails a completed synchronous execution after a backend restart instead of recovering its result #2944 is closed in production only after build-base-image.sh + agent recreate.

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merge-train: batch validated on train/20260922-1340 (train PR #2954, full suite green)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority-p2 Important theme-reliability Theme: Reliability type-bug Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants