Skip to content

fix(claude-code): wait for background work as long as the turn can spare - #1000

Open
kaihackney-scale wants to merge 4 commits into
mainfrom
kai/claude-code-disable-bg-tasks
Open

kaihackney-scale wants to merge 4 commits into
mainfrom
kai/claude-code-disable-bg-tasks

Conversation

@kaihackney-scale

@kaihackney-scale kaihackney-scale commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

By default, Claude Code runs subagents (and long shells) in the background. The Agent tool returns at once with "Async agent launched successfully", and the model can end its turn while the work is still running. Once stdin closes, a claude -p run waits for that background work, waking the model as each piece finishes, but only for 600 s after it first goes idle (CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS, default 600000). Then it kills whatever is still running. Subagent writes made after that point never happen, and their reports never reach the model.

Seen in long multi-step eval runs: the solver hands work to background helpers, ends its turn, and the helpers die 600 s later with the task half done.

Fix

  1. cli_env sets CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS to the attempt's whole budget, unless the run already sets it; nothing is set without a budget. The CLI counts that wait from when the model first goes idle, not from the turn's start, so any wait shorter than the budget could still end before the deadline and kill helpers the turn had time for, and the budget always outlasts the turn. The turn's deadline is what ends the wait.
  2. A turn cut off at its deadline after the model answered keeps its answer. A -p run prints its result events only when it exits, so a run still waiting on background work (or working on what that work reported) has streamed its answer as an assistant message but no result. Before, the bridge's timeout returned an empty response, an error and no trajectory. Now, when the model had ended a turn, the bridge returns the text of the last turn it ended, with the trajectory it streamed, as a completed task whose data says cut_at_deadline: true. A turn cut off before it answered is still a timeout.

Background tasks stay on, so the model keeps the parallelism the harness gives it: it can run helpers and keep working while they run. The CLI's Bash behaviour is unchanged too, including moving a timed-out command to the background.

An earlier revision of this PR turned background tasks off (CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1) and raised the Bash timeouts to make up for it (thanks @corey-boornazian). That fixed the lost work, but it serialised every helper, so the model sat idle while helpers ran. Raising the wait fixes the same failure without that cost.

When the run exits normally, the bridge already handles the extra result row a woken turn writes. It takes the last successful result as the answer and adds up each row's usage, which is reported per row.

Verification

  • tst/unit/agents/claude_code: 426 passed, 30 skipped. New tests cover the wait set from the budget, an explicit value winning, no value without a budget, _spawn_claude passing its budget, a turn cut off after answering keeping its answer and trajectory, a turn cut off before answering staying a timeout, and the server reporting cut_at_deadline.
  • ruff check (0.16.10) is clean.
  • End to end on the CLI version the image pins (2.1.322, downloaded and checksum-checked against its release manifest, the same way the Dockerfile does), in -p stream-json mode, with background tasks on. One background subagent runs a 90 s command, and the model ends its turn at once:
CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS Result
30000 subagent killed; the only answer is the interim one
180000 subagent finished; the CLI woke the model, and a second result row carries the subagent's report

The same through the bridge (run_claude, the pinned CLI, with this revision's wait):

Turn budget Result
60 s cut off at 60 s; the answer the model gave (LAUNCHED) and the 16 events streamed are kept, no error, cut_at_deadline set (before: empty response, error, no trajectory)
180 s helper finished at about 90 s; the turn ends at 105 s with the helper's report as its answer
  • Live runs: 9 long eval tasks that had lost their helpers to the 600 s kill were rerun twice on the promoted image, once with background tasks off (the earlier revision) and once with this revision's wait (then set to the budget less 2 min; the run budget was 24 h, so none came near its deadline).
Background tasks off This revision
Runs that lost background work 0 / 9 0 / 9
Criteria met, all runs 429 / 442 421 / 442
Total time 835 min 585 min
Runs that used helpers 4, taking 103–194 min 5, taking 76–95 min

With this revision, 5 runs launched 3–8 background helpers, and 3 of them ended a turn with helpers still running and were woken when the helpers finished (up to 12 result rows in one run). The only background tasks killed were 2 the model stopped itself mid-turn. On the tasks where both revisions used helpers, scores held or rose (72→78/81, 35→35/36, 42→42/42) while time fell (105→95, 103→80, 194→84 min). The lower total comes from 2 runs that used no helpers in this rerun (37→26/37, 16→13/16), so it reflects run-to-run variance rather than the setting.

Not done: the agent image built from this branch was not run through a hub task; live runs set the env var on the promoted image.

🤖 Generated with Claude Code

Confidence Score: 2/5RetriggerView in Greptile

Not ready to merge: the timeout path can return unfinished or non-JSON answers, and callers can stop waiting before the saved answer arrives.

FindingsFix All in Cursor

  1. P1 Unfinished messages count as answers ▶
  2. P1 JSON requests return plain text ▶
  3. P1 Saved answers miss the caller ▶
Fix with agent prompt
### Issue 1
src/agent_env/agents/agents/claude-code/claude_bridge.py:404-410
`_last_answer` treats a message as finished as soon as it has text and no tool call yet. But the CLI sends text and tool calls in separate events with the same message ID. If the deadline lands between those events, this returns narration such as “Launching a helper” as a successful answer, even when no answer was completed. Check that the message finished before using it, and keep the timeout failure when none did.

### Issue 2
src/agent_env/agents/agents/claude-code/claude_bridge.py:1112-1116
The timeout fallback also runs when `output_format` requests a JSON Schema. If background work keeps the CLI open before it emits `structured_output`, `_last_answer` can supply plain text instead. The bridge then marks the task successful without the requested JSON answer. Only keep a schema response when `structured_output` is available; otherwise return a timeout failure.

### Issue 3
src/agent_env/agents/agents/claude-code/claude_bridge.py:241-242
Using the whole budget for the background wait leaves no time to return the saved answer to `prompt_agent`. The first CLI attempt uses the same timeout as the caller's poll. When helpers are still running, the bridge waits until that limit, then kills the CLI, waits for cleanup, and reads the transcript before completing the task. A poll that still sees the task working at its deadline cancels it and raises `TimeoutError`, so the saved answer never reaches the caller. Reserve time for cleanup and delivery before the caller's deadline.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Extends background work's wait to the attempt's full budget and keeps an earlier answer when the bridge reaches its deadline.

  • Claude Code gives background work the attempt's available time.
  • Claude Code returns an answer when the deadline cuts off background work.

The earlier unnumbered Bash-timeout finding is addressed: the generated Bash-timeout overrides are no longer present.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Start CLI with attempt budget] --> B[Model launches background work]
  B --> C[Model sends text]
  C --> D{CLI exits before deadline?}
  D -->|Yes| E[Return CLI result]
  D -->|No| F[Kill CLI and wait for cleanup]
  F --> G{Saved answer found?}
  G -->|Yes| H[Return success with cut_at_deadline]
  G -->|No| I[Return timeout failure]
  F -. Caller may stop waiting here .-> J[Cancel task and raise timeout]
Loading

Reviews (4) · Last reviewed commit: "fix(claude-code): keep a turn's answer w..." · Reviewed by Greptile

The CLI backgrounds subagents and shells by default and tells the model to
answer meanwhile. In a -p run the turn then ends with them still working,
and the CLI kills them 600 s later, so their writes and reports are lost.
Set CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 unless the run sets it, so an
Agent or Bash call returns only when its work is done.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kaihackney-scale
kaihackney-scale requested a review from a team as a code owner December 3, 2026 21:26
@corey-boornazian

Copy link
Copy Markdown
Collaborator

Rn a turn gets 30 min but a single Bash call is capped at 10 min (2 min by default).

A 10–30 min build or test suite works before this PR: the model backgrounds it and polls it before ending the turn.

With CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1, every call runs in the foreground, so those commands get killed at the Bash timeout. The model can work around it with nohup … &, but it has to know to, and it loses a timed-out attempt first. (I also think the flag turns off the CLI moving a timed-out command to the background, but I haven't checked.)

We could consider also adding setdefault BASH_MAX_TIMEOUT_MS (and maybe BASH_DEFAULT_TIMEOUT_MS) to something near the turn budget so foreground commands can still use the whole turn

With background tasks off, a Bash call runs in the foreground until its
timeout, which the CLI caps at 10 min (2 min by default) and no longer moves
to the background when it passes, so a long build or test suite was killed
though the turn had time for it. Raise BASH_MAX_TIMEOUT_MS to the attempt's
budget less 2 min of headroom, and give a call without a timeout the old
10-min cap, so one hung command can't hold the turn to its deadline. Values
already set are kept, and nothing changes with background tasks on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kaihackney-scale

Copy link
Copy Markdown
Collaborator Author

Good catch, you're right on all three. I checked them against the pinned CLI (2.1.322):

  • A Bash call gets 2 min by default and 10 min at most (BASH_DEFAULT_TIMEOUT_MS / BASH_MAX_TIMEOUT_MS).
  • With CLAUDE_CODE_DISABLE_BACKGROUND_TASKS set, run_in_background is ignored, and the CLI also stops moving a timed-out command to the background, so a long build is just killed.

Pushed b7df0cb: cli_env now takes the attempt's own budget (timeout_seconds varies per task, so not a fixed 30 min) and sets

  • BASH_MAX_TIMEOUT_MS = budget − 2 min (never below the CLI's 10 min), so a call with a long timeout can use the turn;
  • BASH_DEFAULT_TIMEOUT_MS = 10 min, so a call with no timeout that hangs can't hold the turn to its deadline.

Values already set win, and nothing changes with background tasks on. End to end on 2.1.322: sleep 660 asking for a 720000 ms timeout is killed at 10 m with the stock cap and completes with the raised one. Details are in the PR description.

…are, instead of turning it off

Turning background tasks off kept subagents and shells inside the turn, but it took away the parallel work the CLI
does on its own: the model could no longer run helpers and work while they ran. The kill that lost their work is the
CLI's `-p` wait for background work after the turn ends, 10 min by default. Set it to the turn's budget less 120 s, so
the CLI keeps waiting and wakes the model as each helper finishes; background tasks and the CLI's Bash timeouts stay
as they are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kaihackney-scale kaihackney-scale changed the title fix(claude-code): keep subagents and shells inside the turn fix(claude-code): wait for background work as long as the turn can spare Dec 4, 2026
…kground work

The CLI's wait for background work counts from when the model first goes idle, not from the turn's start, so no
wait shorter than the budget is safe from the deadline and none longer is needed: the wait is now the whole budget,
without the 2 min headroom or the 10 min floor. The turn's deadline is what ends it, and a `-p` run prints its
`result` events only as it exits, so a run cut off there had streamed its answer as an assistant message but no
`result`, and the bridge dropped both the answer and the trajectory. Now a run cut off after the model ended a turn
returns that turn's text, with what it streamed, as a completed turn that says it was cut off (`cut_at_deadline`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kaihackney-scale

Copy link
Copy Markdown
Collaborator Author

Andrew raised two points on the wait (thanks). Both are fixed in 3d9c5f5.

The 10 min floor and the 2 min buffer are gone. The CLI counts CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS from when the model first goes idle, not from the turn's start. So any wait shorter than the budget can still kill helpers the turn had time for, and the full budget always outlasts the turn. cli_env now sets the wait to the attempt's whole budget, and the turn's deadline is what ends it.

A turn cut off at the deadline now keeps its answer. One more thing turned up while testing this: a -p run prints its result events only when it exits. So a run still waiting on background work at the deadline has streamed its answer as an assistant message but no result. Before, the timeout path returned an empty response, an error and no trajectory. Now:

  • If the model had ended a turn, the bridge returns the text of the last turn it ended (the main agent's last message with text and no tool call) and the trajectory it streamed, as a completed task with cut_at_deadline: true in its data.
  • A turn cut off before it answered is still a timeout.

Checked through run_claude on the pinned CLI (2.1.322), with a background subagent that needs 90 s:

Turn budget Result
60 s cut off at 60 s; keeps the answer (LAUNCHED) and the 16 events streamed, no error, cut_at_deadline set
180 s helper finishes; the turn ends at 105 s with the helper's report as its answer

Unit tests: 426 passed, 30 skipped. New tests cover both timeout cases and the server's cut_at_deadline flag.

Comment on lines +404 to +410
texts, called = messages.pop(message["id"], ([], False))
for block in message.get("content") or []:
if block.get("type") == "text" and block.get("text"):
texts.append(block["text"])
called = called or block.get("type") == "tool_use"
messages[message["id"]] = (texts, called) # re-inserted, so the dict keeps the order messages last streamed
return next(("\n\n".join(texts) for texts, called in reversed(messages.values()) if texts and not called), None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Unfinished messages count as answers

_last_answer treats a message as finished as soon as it has text and no tool call yet. But the CLI sends text and tool calls in separate events with the same message ID. If the deadline lands between those events, this returns narration such as “Launching a helper” as a successful answer, even when no answer was completed. Check that the message finished before using it, and keep the timeout failure when none did.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agent_env/agents/agents/claude-code/claude_bridge.py
Line: 404-410

Comment:
**Unfinished messages count as answers**

`_last_answer` treats a message as finished as soon as it has text and no tool call yet. But the CLI sends text and tool calls in separate events with the same message ID. If the deadline lands between those events, this returns narration such as “Launching a helper” as a successful answer, even when no answer was completed. Check that the message finished before using it, and keep the timeout failure when none did.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Cursor Fix in Claude Code Fix in Codex

Comment on lines +1112 to +1116
answer = json.dumps(structured_output) if structured_output is not None else (
final_response if final_response is not None else _last_answer(trajectory))
if answer is None:
return ClaudeResult(response="", tool_call_count=tool_count, session_id=session_id,
error=f"claude CLI timed out after {timeout_s}s", **usage)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 JSON requests return plain text

The timeout fallback also runs when output_format requests a JSON Schema. If background work keeps the CLI open before it emits structured_output, _last_answer can supply plain text instead. The bridge then marks the task successful without the requested JSON answer. Only keep a schema response when structured_output is available; otherwise return a timeout failure.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agent_env/agents/agents/claude-code/claude_bridge.py
Line: 1112-1116

Comment:
**JSON requests return plain text**

The timeout fallback also runs when `output_format` requests a JSON Schema. If background work keeps the CLI open before it emits `structured_output`, `_last_answer` can supply plain text instead. The bridge then marks the task successful without the requested JSON answer. Only keep a schema response when `structured_output` is available; otherwise return a timeout failure.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Cursor Fix in Claude Code Fix in Codex

Comment on lines +241 to +242
if turn_budget_s:
env.setdefault(_PRINT_BG_WAIT_ENV, str(turn_budget_s * 1000))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Saved answers miss the caller

Using the whole budget for the background wait leaves no time to return the saved answer to prompt_agent. The first CLI attempt uses the same timeout as the caller's poll. When helpers are still running, the bridge waits until that limit, then kills the CLI, waits for cleanup, and reads the transcript before completing the task. A poll that still sees the task working at its deadline cancels it and raises TimeoutError, so the saved answer never reaches the caller. Reserve time for cleanup and delivery before the caller's deadline.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agent_env/agents/agents/claude-code/claude_bridge.py
Line: 241-242

Comment:
**Saved answers miss the caller**

Using the whole budget for the background wait leaves no time to return the saved answer to `prompt_agent`. The first CLI attempt uses the same timeout as the caller's poll. When helpers are still running, the bridge waits until that limit, then kills the CLI, waits for cleanup, and reads the transcript before completing the task. A poll that still sees the task working at its deadline cancels it and raises `TimeoutError`, so the saved answer never reaches the caller. Reserve time for cleanup and delivery before the caller's deadline.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Cursor Fix in Claude Code Fix in Codex

This branch has not been deployed

No deployments
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