Repository navigation
Description
Summary
When a claude --print turn ends with a background task still in flight (task_type: local_bash — either the model passed run_in_background: true, or the harness auto-promoted a foreground Bash call at its tool timeout), the CLI exits, kills the task ~5s later, and reports the kill in its own stdout stream. Trinity stores the run as a clean status: success whose response is the model's announcement ("…running in the background. Waiting for the completion notification."), full cost billed, and no structured trace of the kill anywhere — the truth exists only as raw system events buried deep in the stored execution_log.
This is the same harm class #2127/#2192 exist to prevent (announcement stored as the answer, work killed, success recorded, cost billed), reached by a path their gate correctly does not cover: the CLI exits on its own (terminal_reason: "completed", is_error: false), so the early-finalize gate never runs, and local_bash is on _NON_WAITED_BG_TASK_TYPES by sound design. Nothing here asks to change the gate, the denylist, or the kill semantics — the ask is the missing reporting half.
Context
Observed in the wild on a production deployment: a weekly scheduled data pull died this way on three consecutive fires (weeks of silently stale data downstream) and a scheduled report run lost a required artifact — every one recorded success; the loss was found by an out-of-band monitor, not by any Trinity signal.
Reproduction (local, deterministic)
Live (Claude Code 2.1.235, Trinity's exact headless invocation). A POST /api/agents/{name}/task instructing the model to background sleep 90 && echo PROOF > /home/developer/.tmp/proof.txt and end its turn produced this stored row:
status: success
error: null
response: "The job is running in the background. Waiting for the completion notification."
occurrences of "pending_at_exit" in the record: 0
task_updated {"status":"killed"} in stored log: 1 (buried among raw stream events)
task_notification {"status":"stopped"}: 1
proof file after the run: ABSENT — the work never happened
The stream tail is always the same three events, after the CLI's own result line:
{"type":"system","subtype":"background_tasks_changed","tasks":[]}
{"type":"system","subtype":"task_updated","task_id":"…","patch":{"status":"killed","end_time":1788264398136}}
{"type":"system","subtype":"task_notification","task_id":"…","status":"stopped","output_file":"…"}The tool-timeout-promotion variant reproduces identically: a foreground Bash call with timeout: 15000 on a slow script is moved to background at 15s (background_tasks_changed [local_bash] + task_updated {"is_backgrounded": true}), the tool result tells the model "Command did not complete within its 15s timeout and was moved to the background … You will be notified when it completes", the model ends its turn, and the same kill tail follows.
Offline (stream replay). Deterministic pytest fixtures replaying this exact tail through _run_headless_subprocess → _finalize_headless_result confirm today's behavior (clean success, no marker, kill events present-but-discarded) with no model in the loop. The fixtures accompany the fix PR.
Root cause (three independent gaps, verified in code)
- The bug: turn ending with background subagents still in flight records the execution as SUCCESS and silently discards the work #2127 marker is scoped to waited types by design. In
docker/base-image/agent_server/services/headless_executor.py, finalize setsmetadata.background_tasks_pending_at_exitfromctx.waited_bg_tasks, and_count_waited_bg_tasksskips_NON_WAITED_BG_TASK_TYPES = {local_bash, local_shell}— so for a killed background shell the marker is structurally unreachable. - Widening that counter would NOT fix it (proven by a replay fixture): the CLI emits
background_tasks_changed tasks: []before exiting, the natural-exit path drains the reader before finalize, and the counter reads 0 regardless of the denylist. The only reliable signal is the kill lifecycle events —task_updated {"status":"killed"}/task_notification {"status":"stopped"}— which nothing in the codebase parses today (stream_parser.pyhandles onlyinit,compact_boundary,result, assistant/user; the kill events land inraw_messagesand go no further). - Even when the existing marker fires (waited path), the backend never persists it — zero references to the field in
src/backend/; per its own docstring (agent_server/models.py) the response-text notice is the only operator-visible channel. So "queryable" is a gap on the waited path too.
Additionally, the promotion signal (task_updated {"is_backgrounded": true} mid-call) is discarded: a fixture proves the promoted-foreground shape and the deliberate run_in_background shape finalize to byte-identical records, though they mean opposite things (work the model was counting on vs fire-and-forget).
Proposed fix (additive; no behavioral change to gate/denylist/kill)
- Track background-task lifecycle in the stream reader (
headless_executor.py): first-seen frombackground_tasks_changedsnapshots (task_id, task_type), promotion from theis_backgroundedpatch, terminal status fromtask_updated/task_notification. Keyed on the kill events, NOT the ledger (see root cause 2). - New sibling metadata field (do not overload the existing int), e.g.
background_tasks_killed_at_exit: [{task_id, task_type, was_backgrounded_by: "tool_timeout"|"requested", final_status, end_time}]. Respect the bug: turn ending with background subagents still in flight records the execution as SUCCESS and silently discards the work #2127 privacy rule: prefertask_type/ids over free-textdescription/summary(which carry model/prompt text); if a description is included it must be capped + pass the existing sanitizer. - Prepend a visible notice to the stored
responsewhen the list is non-empty (the fix(agent-runtime): stop killing a fan-out turn mid-wait and calling it success (#2127) #2192 pattern, placed after the bug: Headless task returns empty response for skills with context: fork #160 empty-response branch like the existing notice). - Make it queryable on the backend — one list-endpoint field must differ from a healthy run. Candidates (implementation decides): surface the count/flag on the execution row (nullable column, dual-track migration per Invariant Feature/vector log retention #3 + Alembic), or a distinct
business_statusvalue (note: that column has an existing RETRY-001 validation vocabulary — reusing it needs care). local_bash/local_shelltasks that complete before exit produce nothing new.
Acceptance Criteria
- An execution that ends with a background task in
status: "killed"stores a non-empty structured record naming that task (id, type,was_backgrounded_by, final status) — sourced from the kill lifecycle events, not thebackground_tasks_changedledger. - That execution is distinguishable from a healthy one without reading the log — one queryable list-endpoint field differs.
- A task promoted by tool timeout is distinguishable from one the model backgrounded deliberately.
- An execution with no in-flight tasks at exit is byte-identical to today (no new field content, no new status value) — the happy path stays free.
- No change to
_NON_WAITED_BG_TASK_TYPES,_IDLE_FINALIZE_S, when the finalize fires, or kill semantics. Existingbackground_tasks_pending_at_exit(waited path) behavior unchanged. - Negative control pinned in tests: the same stream with the final
task_updatedreporting"completed"instead of"killed"produces an unchanged record — an implementation that flags on the mere presence of a background task must fail this.
Test plan
Stream-replay fixtures (the #2127 instrument), already written and passing against today's code as gap-documentation; the fix inverts them:
- Fixture A: tool-timeout promotion tail → expect 1 entry,
was_backgrounded_by: "tool_timeout", flagged. - Fixture B:
run_in_backgroundtail → 1 entry,was_backgrounded_by: "requested". - Negative control: same stream, task completes before exit → empty, record identical to today.
- Waited-path regression: existing
tests/unit/test_2127_background_task_gate.pystays green untouched.
Technical Notes
- Agent-side change ⇒ base-image rebuild + cold agent recreate to reach the fleet (bug: turn ending with background subagents still in flight records the execution as SUCCESS and silently discards the work #2127 release-note ordering requirement).
- Does not resurrect killed work or stop the model ending its turn on a false belief — that is the sibling issue ScheduleWakeup is offered in one-shot headless runs — it schedules a wakeup that never fires and tells the model it WILL be re-invoked #2468, filed together with this one: it removes the mechanism that talks the model into the plan; this issue makes the loss visible when it happens anyway.
- Related: fix(agent-runtime): stop killing a fan-out turn mid-wait and calling it success (#2127) #2192 (fixed bug: turn ending with background subagents still in flight records the execution as SUCCESS and silently discards the work #2127), bug: completed turn discarded on error_during_execution — jsonl_recovery never consulted, response lost despite end_turn in the JSONL #1870, bug: headless_executor reader thread leak causes 2h execution hangs #970.
Activity
webmixgamer commentedon Sep 1, 2026
/claim
github-actions commentedon Sep 1, 2026
Claimed by @webmixgamer. Label
status-in-progressadded.Next steps:
feature/2467-<short-slug>Fixes #2467fix(executions): killed background task leaves a queryable trace, not…
fix(runtime): deny the tool family that promises a second turn, measu…
test(2467): derive the fleet-list fixture timestamp from now, not a l…
feat(eval): Tier-0 writer, intent resolution and the first four gate …
feat(eval): Tier-0 deterministic checks + delegation link (ent#935) (#…
feat(eval): Tier-0 deterministic checks + delegation link (ent#935) (#…
feat(eval): Tier-0 deterministic checks + delegation link (ent#935) (#…
feat(eval): Tier-0 deterministic checks + delegation link (ent#935) (#…
feat(eval): Tier-0 deterministic checks + delegation link (ent#935) (#…
feat(eval): Tier-0 deterministic checks + delegation link (ent#935) (#…
feat(eval): Tier-0 deterministic checks + delegation link (ent#935) (#…
feat(eval): Tier-0 deterministic checks + delegation link (ent#935) (#…