Skip to content

Background task killed at CLI exit leaves no trace — execution records clean success while the work is lost #2467

Closed

Description

@webmixgamer

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)

  1. 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 sets metadata.background_tasks_pending_at_exit from ctx.waited_bg_tasks, and _count_waited_bg_tasks skips _NON_WAITED_BG_TASK_TYPES = {local_bash, local_shell} — so for a killed background shell the marker is structurally unreachable.
  2. 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.py handles only init, compact_boundary, result, assistant/user; the kill events land in raw_messages and go no further).
  3. 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)

  1. Track background-task lifecycle in the stream reader (headless_executor.py): first-seen from background_tasks_changed snapshots (task_id, task_type), promotion from the is_backgrounded patch, terminal status from task_updated/task_notification. Keyed on the kill events, NOT the ledger (see root cause 2).
  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: prefer task_type/ids over free-text description/summary (which carry model/prompt text); if a description is included it must be capped + pass the existing sanitizer.
  3. Prepend a visible notice to the stored response when 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).
  4. 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_status value (note: that column has an existing RETRY-001 validation vocabulary — reusing it needs care).
  5. local_bash/local_shell tasks 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 the background_tasks_changed ledger.
  • 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. Existing background_tasks_pending_at_exit (waited path) behavior unchanged.
  • Negative control pinned in tests: the same stream with the final task_updated reporting "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_background tail → 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.py stays green untouched.

Technical Notes

Activity

  1. added
    priority-p1
    type-bug
    theme-reliability
    complexity-medium
    status-ready
    on Sep 1, 2026
  2. removed
    status-ready
    on Sep 1, 2026
  3. webmixgamer commented on Sep 1, 2026

    @webmixgamer
    ContributorAuthor

    /claim

  4. added
    status-in-progress
    on Sep 1, 2026
  5. github-actions commented on Sep 1, 2026

    @github-actions

    Claimed by @webmixgamer. Label status-in-progress added.

    Next steps:

    1. Create branch: feature/2467-<short-slug>
    2. Implement the feature
    3. Open a PR with Fixes #2467
  6. added
    status-in-dev
    and removed
    status-in-progress
    on Sep 1, 2026
  7. removed
    status-in-dev
    on Sep 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

complexity-mediumpriority-p1theme-reliabilitytype-bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions