Skip to content

fix(server): keep a Claude task owed when it finishes during a turn's last request - #43852

Open
frostney wants to merge 6 commits into
pingdotgg:mainfrom
frostney:fix/claude-in-turn-task-notification-wake
Open

frostney wants to merge 6 commits into
pingdotgg:mainfrom
frostney:fix/claude-in-turn-task-notification-wake

Conversation

@frostney

Copy link
Copy Markdown

Problem

When a Claude agent's background command finishes while the turn's last model request is in flight, Claude Code queues the notification and answers it in a turn of its own after result. ClaudeAdapterV2 has already dropped the task from the roster by then, so nothing is owed when the turn ends, and anything that closes an idle session kills the turn Claude Code starts for it. In a delegate_task child, releaseFinishedDelegateSessions starts releasing the session about 0.1 s after result, its query.close about 0.3 s later kills that turn, and the child never answers the notification.

Steps to reproduce, timelines and the earlier stalls are in #43838.

Change

ClaudeAdapterV2 now tracks Claude's root request phase per process as frames arrive: a request is in flight from a root status: requesting until the next root tool result, result or init. It is tracked as frames arrive, because buffered frames replay later. Each process keeps its own phase, so a replaced process's late frames don't change the new one's.

  • A task whose task_notification arrives while a root request is in flight stays owed: the published roster still lists it, the same way an idle completion is held.
  • The next root request after a tool step carries every notification queued before it, and so does a new turn's first request (Claude Code folds queued background completions in at turn start). That request clears the tasks it carries and drops their wake reports.
  • If the turn ends with a task still owed, its notification is buffered as if it had arrived while idle, keeping the report recorded during the turn. Claude's own follow-up turn becomes the wake continuation through the existing path, and the replayed notification retires the task.
  • In result_only echo mode, a user turn that starts before Claude's follow-up turn receives that turn's output. When no wake turn is buffered, its foreign task-notification result now retires the buffered notification it answered, matched by the notification's run_id against the result's origin.runId. A result naming no run (scheduled triggers and peer deliveries share that origin) retires only notifications with no run id. Notifications it didn't answer keep their wake reports. On main the same interleaving leaves an idle completion listed for good; this change would otherwise extend that to the in-turn case.
  • A notification that arrives with no request in flight is cleared at once, as on main. So is a background command a subagent owns (owned_by_subagent on the start or the completion), since it reports to that subagent and no root turn answers it.
  • Process exit, Stop and query replacement clear the new state with the rest of the wake state.

Not covered, as on main: Claude Code snapshots its queue after a tool step's results and then prepares the next request. A notification that lands in that gap, before the next status: requesting, misses the snapshot, and if that request is the turn's last its wake is still lost. The adapter can't see the snapshot on the stream, and holding every such notification would leave a phantom roster entry, which blocks a delegate's release and any settle, whenever the snapshot did take it. Across 945 mid-turn folds in local Claude Code transcripts, that gap had a median of 35 ms and a p90 of 195 ms.

Scope

Bug fix in the Claude adapter, one problem: a background task that finishes during a turn's last request loses its wake. Issue: #43838.

#36029 keeps an idle session open while a wake is owed. It covers a task that finishes after the turn has ended. Here the task finishes during the turn, so nothing is owed when it ends; with #36029 applied, the recorded replay below still fails the same way. Two gaps stay as they are on main for idle completions. hasPendingBackgroundWork and the query-replacement guard read the live roster rather than owed wakes, so a provider switch or a policy change in the fraction of a second before Claude's follow-up init can still close the process; #36029 changes hasPendingBackgroundWork. And a wake continuation drains everything buffered, including a later task's notification, which retires that task before its own wake turn.

Verification

Recorded replay claude_background_task_last_request, from Claude Code 2.1.332 (claude-sonnet-4-6): Claude starts sleep 4 && echo BG_DONE in the background, then writes a long reply with no further tool calls, so the notification arrives during that last request and Claude answers it in a turn of its own. ClaudeReplayFixtures.integration.test.ts replays it through the orchestrator, adapter and projections, and checks that the roster at the root run's completion still lists the task, that the wake run replies WAKE_DONE, and that the roster ends empty with one "Command … finished" notification. On main the wake run still answers, because nothing closes the session in the replay, but the roster at the root run's end is empty, so it fails with expected [] to deeply equal [ 'b80cmxx3h' ]; with this change it passes. The recording's hook output and task paths are sanitised like the existing fixtures', and the scenario is registered in scripts/record-claude-agent-sdk-replay-fixture.ts.

ClaudeAdapterV2.test.ts, for sequences a recording can't produce on demand:

  • "keeps a task that finishes during a turn's last request owed": a Stop hook's request follows (owed), and four guards that must leave the roster empty: a task folded after a tool step, and a subagent's own command flagged owned_by_subagent on the start, on the completion, or on a foreground start later moved to the background.
  • "retires an owed task only when a user turn that started first receives its answer" (result_only echo): its own run, another run, a result naming no run. The last two also check that the task's own wake still names the command.

On main the Stop hook case, the three retirement cases and the replay fail; the four guards pass on both. No test covers a new turn's first request folding a notification, a wake request that a continuation joins after it went out, the per-process phase after a query replacement, or the clearing on exit, Stop or replacement. A unit case for the joined wake request passed on this branch and was cut to keep the tests small. ClaudeAdapterV2.test.ts, ClaudeReplayFixtures.integration.test.ts, ClaudeAutomaticDelivery.integration.test.ts, DelegatedCompletionDelivery.test.ts and OrchestratorReplayRecovery.integration.test.ts pass on this head, and so does vp run check:changed. The orchestrator needs no change: DelegatedCompletionDelivery.test.ts already shows that a listed background task keeps a finished delegate's process.

Runtime (UTC, 26 Nov), on an isolated t3 serve with Claude Haiku 5.5 for parent and child, using the steps in #43838 (the child runs sleep 15; echo <token> in the background, calls t3_background_wait, then writes one to one thousand in words):

task_notification child result Claude's own init delegate release child replies with the token
main at the time (9868261) 15:00:52.882, request in flight since 15:00:39.182 15:01:06.596 15:01:06.930 detach 15:01:06.751, query.close 15:01:06.989 never
this branch 16:31:39.273, request in flight since 16:31:26.419 16:31:54.673 16:31:55.000, runs as the wake run 16:31:58.307, after the wake run's result once, at 16:31:58.039

Made with Claude Opus 5.5 in Claude Code, run from T3 Code. Reviewed by GPT-6.2 Sol in Codex.

… still wakes the agent

Claude Code queues a task notification that arrives mid-turn and hands it to
the model with the first request after the next tool step. A notification
that arrives while the turn's last request is in flight (or before a Stop
hook's follow-up request, which carries no queued input) is still queued at
the result, and Claude answers it in a turn of its own.

The adapter dropped the task from the roster as soon as the notification
arrived, so the turn ended with nothing owed. A finished delegate's session
release (and any other close that reads the roster) then closed the query
while Claude's own follow-up turn was starting, and the agent never saw the
result.

The adapter now keeps such a task owed until a request after a tool step
carries it, and at the turn's end buffers it as an idle wake, so Claude's
follow-up turn runs as the wake continuation.
…h a recorded replay

Review fixes for the in-turn task notification wake:

- Track the root request phase per native thread as frames arrive, so a
  continuation that attaches during Claude's own wake request keeps it.
- Never hold a background command a subagent started; it reports to that
  subagent.
- Keep the wake report recorded during the turn, and drop the reports of
  tasks a request folded.
- When a user turn that started first receives the wake's output, retire the
  notifications buffered for that wake.
- Add a recorded replay, claude_background_task_last_request, in which the
  command ends during Claude's last request.
…its request phase per process

Review fixes for the in-turn task notification wake:

- A foreign task-notification result retires only the buffered notification
  whose run id it names (all of them when the CLI reports none), through
  replaceWakeBuffer.
- Keep the root request phase on the live query context, so a replaced
  process's late frames cannot clear the new process's phase.
- Honour owned_by_subagent on a completion, and record it on a foreground
  start that moves to the background later; the fallback set lives on the
  query.
…s run

Review fixes for retiring a buffered notification from a foreign
task-notification result in result_only echo mode:

- A result that names no run retires only notifications without a run id;
  scheduled triggers and peer deliveries share that origin.
- Notifications the result did not answer keep their wake reports, so their
  own wake still names the command.
… cover

The recorded replay claude_background_task_last_request already covers a task
that finishes during the last request and its wake. Keep the Stop hook case,
the guards that keep a folded or subagent-owned task off the roster, and the
result_only retirement cases.
@github-actions github-actions Bot added vouch:unvouched Author is not yet trusted in the VOUCHED list. size:XL 500-999 changed lines (additions + deletions). labels Nov 27, 2026
@frostney
frostney marked this pull request as ready for review November 27, 2026 00:23
@coderabbitai

coderabbitai Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

ClaudeAdapterV2 now tracks background-task notifications across root requests, subagent ownership, and task results. New tests and a replay fixture cover notification buffering, wake-report handling, and a background task that completes during a long response.

Changes: Claude task notification accounting

Layer / File(s) Summary
Track and retire task notifications
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
The adapter tracks root-request phases and subagent task ownership. It buffers notifications that are not folded into a request and selectively retires buffered notifications and wake reports.
Test notification accounting
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
Tests cover notifications during final requests, tool-step and subagent handling, and retirement based on matching task result run IDs.
Add background-wake replay scenario
apps/server/src/orchestration-v2/testkit/fixtures/claude_background_task_last_request/*, apps/server/src/orchestration-v2/testkit/fixtures/index.ts, apps/server/scripts/record-claude-agent-sdk-replay-fixture.ts
Adds and registers a replay scenario in which a background task completes during a long response. The fixture checks the follow-up wake and final projection.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: juliusmarminge

Merge Risk: Minimal · up to 85caf

This change keeps a background task owed when it finishes during a turn's last request, so Claude's follow-up wake reply is no longer cut off. The reviewed concerns about process replacement closing the owing process did not hold up. No concrete merge-blocking risk remains; the gaps the author lists are unchanged from main.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the primary change: a Claude background task that finishes during a turn's last request stays owed, which is the bug fix the PR implements in ClaudeAdapterV2 and the replay fixture. It…
Description check Passed The description follows the template. It has Problem, Change, Scope and Verification sections with substantive content. It names the issue (#43838), gives reproduction context, and details focused tes…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the primary change: a Claude background task that finishes during a turn's last request stays owed, which is the bug fix the PR implements in ClaudeAdapterV2 and the replay fixture. It follows the conventional commit form and is specific, though it omits the delegated-session impact.

Full details: Description check

Explanation

The description follows the template. It has Problem, Change, Scope and Verification sections with substantive content. It names the issue (#43838), gives reproduction context, and details focused tests, a recorded replay, and runtime evidence. It also notes the model and harness used. Verification lists the tests run and what they showed on main and on this branch, and it states the gaps that remain uncovered.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 9f96e0d and 85caf77.

Files selected for processing: 7

  • apps/server/scripts/record-claude-agent-sdk-replay-fixture.ts
  • apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
  • apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
  • apps/server/src/orchestration-v2/testkit/fixtures/claude_background_task_last_request/claude_transcript.ndjson
  • apps/server/src/orchestration-v2/testkit/fixtures/claude_background_task_last_request/input.ts
  • apps/server/src/orchestration-v2/testkit/fixtures/claude_background_task_last_request/output.ts
  • apps/server/src/orchestration-v2/testkit/fixtures/index.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@github-actions

Copy link
Copy Markdown
Contributor

This PR conflicts with main. Rebase it or merge main into it. If it still conflicts after 7 days with no activity, it will be closed automatically.

See the conflict window.

@github-actions github-actions Bot added the needs-rebase Conflicts with its base branch. Closes after 7 days with no activity. label Nov 27, 2026

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

needs-rebase Conflicts with its base branch. Closes after 7 days with no activity. size:XL 500-999 changed lines (additions + deletions). vouch:unvouched Author is not yet trusted in the VOUCHED list.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant