Repository navigation
fix(claude-code): wait for background work as long as the turn can spare - #1000
kaihackney-scale wants to merge 4 commits into
Conversation
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>
|
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 We could consider also adding |
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>
|
Good catch, you're right on all three. I checked them against the pinned CLI (2.1.322):
Pushed b7df0cb:
Values already set win, and nothing changes with background tasks on. End to end on 2.1.322: |
…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>
…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>
|
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 A turn cut off at the deadline now keeps its answer. One more thing turned up while testing this: a
Checked through
Unit tests: 426 passed, 30 skipped. New tests cover both timeout cases and the server's |
| 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) |
There was a problem hiding this 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.
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.| 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) |
There was a problem hiding this 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.
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.| if turn_budget_s: | ||
| env.setdefault(_PRINT_BG_WAIT_ENV, str(turn_budget_s * 1000)) |
There was a problem hiding this comment.
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.
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 -prun 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, default600000). 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
cli_envsetsCLAUDE_CODE_PRINT_BG_WAIT_CEILING_MSto 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.-prun prints itsresultevents 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 noresult. 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 sayscut_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
resultrow a woken turn writes. It takes the last successfulresultas the answer and adds up each row'susage, 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_claudepassing 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 reportingcut_at_deadline.ruff check(0.16.10) is clean.-pstream-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_MSresultrow carries the subagent's reportThe same through the bridge (
run_claude, the pinned CLI, with this revision's wait):LAUNCHED) and the 16 events streamed are kept, no error,cut_at_deadlineset (before: empty response, error, no trajectory)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
resultrows 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/5

Not ready to merge: the timeout path can return unfinished or non-JSON answers, and callers can stop waiting before the saved answer arrives.
Findings
Fix with agent prompt
Summary
Extends background work's wait to the attempt's full budget and keeps an earlier answer when the bridge reaches its deadline.
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]Reviews (4) · Last reviewed commit: "fix(claude-code): keep a turn's answer w..." · Reviewed by Greptile