Skip to content

fix(agent-runtime): stop killing a fan-out turn mid-wait and calling it success (#2127) - #2192

Merged
vybe merged 3 commits into
devfrom
feature/2127-background-subagent-turn
Aug 15, 2026
Merged

vybe merged 3 commits into
devfrom
feature/2127-background-subagent-turn

Conversation

@webmixgamer

Copy link
Copy Markdown
Contributor

Summary

An agent that fans out to background subagents announces "I'll wait for the notification" and ends its turn. Trinity read that as "the turn is over", killed the process group 2s later, and recorded the run as success — with the announcement stored as the answer, the work killed, and the cost billed. No error, no log, indistinguishable in the UI from a real result.

claude --print emits one {"type":"result"} per turn segment, not per run, and deliberately stays alive between them to await background subagents ("their result is part of the final output" — headless docs). #970's early-completion treated any result line as definitive and killed the CLI during a wait it was performing correctly.

#1870 is the same root cause with different timing (the notification lands early enough that the interrupted follow-on turn surfaces as error_during_execution), so one defect had been filed twice from opposite ends. The issue's own stated root cause — that the classifier trusts a clean end_turn — is wrong: the classifier never runs, because the process is killed first. Building its suggested transcript-scanner would have been a detector layered on our own kill.

The fix

Early-finalize now requires all three:

result_seen  AND  not waited_bg_tasks  AND  (now - last_stdout_at) >= _IDLE_FINALIZE_S

Ledger half — system/background_tasks_changed carries a full snapshot of in-flight work, so the latest event is the whole truth. _NON_WAITED_BG_TASK_TYPES is a denylist (local_bash, local_shell): an allowlist that hasn't heard of a future waited type restores the bug silently, while a denylist miss costs a bounded wait — and a background shell must never hold the finalize, since the CLI kills it after ~5s and gating on one re-opens #970's lingering-child class.

Idle half, not optional — the ledger drains to [] while the model is still composing the synthesis the subagents were spawned to produce. Measured: 5 subagents all reported by t+27.8s, real FINAL REPORT at t+55.9s, so a ledger-only gate stands aside and the kill lands on an interim line. Idleness is what #970's failure is: claude alive, blocked on an MCP child, emitting nothing.

_IDLE_FINALIZE_S = 300s (AGENT_IDLE_FINALIZE_S; <=0 refused, it would restore the exact kill). Set from the longest silence a healthy run produces — without --include-partial-messages one long message is a single stdout line emitted only when complete, measured at 40.54s of dead air for 9,840 chars. ~7.4x headroom, biased large because the errors are asymmetric: too large only delays a pathological finalize, too small destroys a deliverable and calls it success.

Free on the happy path — the branch is only reachable when the process does not exit — and effective_timeout remains the unconditional backstop.

Also raises CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS to the execution timeout at both spawn sites (the chat path never had the kill but inherits the same 10-minute CLI truncation; fixing only the reported path is the recurring one-of-two-call-sites escape, #686/#1264), and prepends a visible notice + background_tasks_pending_at_exit when the CLI stops waiting on its own.

Nothing is taken away from agents — subagents keep working exactly as in a local session.

Changes

File What
agent_server/services/headless_executor.py ledger tracking, idle clock, the three-part gate, CLI ceiling, pending-at-exit notice
agent_server/services/claude_code.py CLI ceiling on the chat spawn site
agent_server/models.py background_tasks_pending_at_exit (additive; backend reads metadata as a dict)
tests/unit/test_2127_background_task_gate.py 34 tests
docs/memory/feature-flows/parallel-headless-execution.md + index + learnings.md flow, revision row, bug-class entry

Test Plan

  • pytest tests/unit/test_2127_background_task_gate.py — 34 passed
  • Both halves verified failing without their own condition, replaying streams measured from a live container:
    • no ledger gate -> stores 'Waiting for the second notification (BRAVO)' instead of 'RESULTS: ALPHA BRAVO'
    • no idle gate -> stores 'ECHO reported.' instead of 'FINAL REPORT ...'
  • Headless regression suites — 152 passed
  • Full tests/unit — 10,049 passed (residual failures are pre-existing: the bug(ci): test_1081_physical_meter ceiling-clamp test fails under full-suite ordering — settings_service caches a pre-eviction db #2045 order-dependent flake, and test_pat_propagation_properties::TestKnownGaps, which exercises src/backend code this PR doesn't touch)
  • Live smoke on a patched agent container: fan-out turns complete and return the full consolidated answer

Honest caveat: the end-to-end failure is a race that needs a specific CLI flush timing; four live runs never reproduced it, before or after. The deterministic unit tests are the proof — the live runs are a non-regression check only.

Deployment

Requires a base-image rebuild + cold agent recreate. A restart is not enough.

Known bound: agents with a timeout under ~300s lose #970's early finalize — a rare stuck-process case now returns an honest 504 instead of a rescued success. Accepted over clamping the ceiling to a fraction of the budget, which would re-admit silent truncation on the agents least able to afford it. Tunable via AGENT_IDLE_FINALIZE_S, and pinned by a test.

Consequence: fan-outs now run to completion, so they spend more tokens and can newly reach --max-turns.

Fixes #2127

🤖 Generated with Claude Code

webmixgamer and others added 2 commits August 14, 2026 17:54
…it success (#2127)

`claude --print` emits one `{"type":"result"}` per turn SEGMENT, not per run, and
deliberately stays alive between them to await background subagents — "their result
is part of the final output" (headless docs). #970's early-completion treated any
result line as the definitive end of the turn and SIGTERMed the process group 2s
later with `return_code = 0`, so a fan-out was killed during a wait it was
performing correctly: recorded SUCCESS, cost billed, subagents killed, and the
model's "I'll wait for the notification" announcement stored as the response.

#1870 is the same root cause with different timing (the notification lands early
enough that the interrupted follow-on turn surfaces as `error_during_execution`),
so one defect had been filed twice from opposite ends. The issue's own stated root
cause — that the classifier trusts a clean `end_turn` — is wrong: the classifier
never runs, because the process is killed first.

Early-finalize now requires all three:

    result_seen  AND  not waited_bg_tasks  AND  stream idle >= _IDLE_FINALIZE_S

Ledger half: `system/background_tasks_changed` carries a full snapshot of in-flight
work, so the latest event is the whole truth. `_NON_WAITED_BG_TASK_TYPES` is a
denylist ({local_bash, local_shell}) because the failures are asymmetric — an
allowlist missing a future waited type restores the bug silently, a denylist miss
costs a bounded wait — and a background shell must never hold the finalize, since
the CLI kills it after ~5s and gating on one re-opens #970's lingering-child class.

Idle half, and it is not optional: the ledger drains to [] while the model is still
composing the synthesis the subagents were spawned to produce (measured: 5 subagents
all reported by t+27.8s, real FINAL REPORT at t+55.9s), so a ledger-only gate stands
aside and the kill lands on an interim line. Idleness is what #970's failure IS —
claude alive, blocked on an MCP child, emitting nothing. 300s default
(AGENT_IDLE_FINALIZE_S; <=0 refused) is set from the longest silence a healthy run
produces: without --include-partial-messages one long message is a single stdout line
emitted only when complete, measured at 40.54s of dead air for 9,840 chars. Free on
the happy path — the branch is only reachable when the process does not exit — and
`effective_timeout` remains the unconditional backstop.

Also raises CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS to the execution timeout at BOTH
spawn sites; the chat path never had the kill but inherits the same 10-minute CLI
truncation, and fixing only the reported path is the recurring one-of-two-call-sites
escape (#686, #1264). When the CLI stops waiting on its own, finalize prepends a
visible notice and sets `background_tasks_pending_at_exit`, placed after the #160
empty-response branch so a notice can never make an empty result look populated.

Root-caused by instrumenting Claude Code 2.1.220 in a live agent container. Both
halves are pinned by tests replaying the measured streams and asserting END STATE,
each verified failing without its own condition.

Known bound: agents with a timeout under ~300s lose #970's early finalize (an honest
504 replaces a rescued success) — accepted over clamping, which would re-admit silent
truncation on the agents least able to afford it. Consequence: fan-outs now run to
completion, so they spend more and can newly reach --max-turns.

Requires a base-image rebuild plus a cold agent recreate to take effect.

Fixes #2127

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…d-subagent-turn

# Conflicts:
#	docs/memory/learnings.md
@webmixgamer
webmixgamer requested a review from dolho August 14, 2026 17:24
The idle ceiling shipped documented as env-tunable — in the code comment, the
feature flow, the commit message and the PR body — and named as the escape hatch
for the known bound that agents with an execution timeout under ~300s lose #970's
early finalize. But it was wired into nothing, so there was no supported way for
an operator to set it: a knob that cannot be turned is not a mitigation, and a
false claim in the docs is worse than not offering one.

Caught by /validate-pr's config-packaging gate (the #1056 / trinity-enterprise#31
class). The var is read inside the agent container, so it needs the full
delivery chain the sibling AGENT_TOOL_STALL_LIMIT_S (#1369) already has:

  .env -> docker-compose{,.prod}.yml -> backend env
       -> crud.py (create) + lifecycle.py x2 (recreate paths) -> agent env_vars
       -> _resolve_idle_finalize_s()

Both compose files, because prod launches standalone with no base-compose merge
and no env_file, so dev-only wiring does not carry over. Set-or-CLEAR on the
config-drift recreate (that dict is seeded from the OLD container, so an unset
backend env must pop a stale baked value — the #1809/ent#109 rule), set-only on
the rebuild-from-nothing path where there is no old container to inherit from,
matching the sibling exactly rather than inventing a third pattern.

Registered in test_1811_recovery_container_parity's _SUPPLIED_BY_HELPERS so the
create/recover parity guard stays honest.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@github-actions

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

@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.

Validated via /validate-pr. 20/20 checks green; re-verified clean against dev@a1356143 after #2194 landed (the nightly bot's conflict comment is a stale false positive — branch is 0 commits behind dev).

The diagnosis is the valuable part: claude --print emits one result per turn SEGMENT, so #970's early-completion was killing the CLI during a wait it was performing correctly — and #1870 is the same root cause filed from the other end. Notably the issue's own stated root cause (classifier trusts a clean end_turn) is wrong, and building its suggested transcript-scanner would have been a detector layered on our own kill. Good catch to check rather than implement.

Both halves of the three-part gate were verified failing without their own condition, replaying streams measured from a live container — the ledger-only gate provably stands aside during the 28s window between the ledger draining and the real FINAL REPORT. The denylist direction is argued from failure cost rather than taste, and effective_timeout stays the unconditional backstop, so this can defer the kill but never remove it.

Config packaging is the part that usually fails on a change like this and it's complete: all three env writers with the right per-site semantics (set-only on create, set-or-CLEAR on the config-drift recreate since that dict is seeded from the old container, set-only on rebuild-from-nothing), both compose files, .env.example — and test_1811_recovery_container_parity.py extended, so the CLASS is guarded, not just this instance.

The unlocked reader-thread -> wait-loop sharing is fine: both fields are single-attribute rebinds with no invariant spanning them, and last_stdout_at is seeded at spawn before the readers start.

Two things for the release notes, neither blocking:

  • Requires a base-image rebuild + cold agent recreate; a restart is not enough, so this ships inert on the running fleet without it.
  • Accepted deltas, honestly disclosed: agents with a timeout under ~300s lose #970's early finalize, and fan-outs now run to completion (more tokens, can newly reach --max-turns).

Not blocking on the missing /review — the diff touches no SQL and no auth surface.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants