fix(orchestrator): Wake settled parents when delegated children finish #4499
t3code/codex-turn-mapping fromrefs/pull/4499/head·merged by juliusmarminge View on GitHubSummary#
- Wake a settled parent thread when an app-owned
delegate_taskchild terminalizes, so an async delegation's result is acted on instead of waiting for the user's next message. - Gate the wake on a per-task
completionWakepolicy so async delegations and blocking waits do not double-deliver. - Deliver the wake as a real prompt. A wake that only starts a run does not help if the provider never sees the text.
- Narrow the Claude adapter's task-notification drop, so the wake this PR introduces can actually settle its run. Carried as a second commit because it is an adapter concern rather than a wake concern, but it is a prerequisite: without it this PR ships a hang.
Problem and Fix#
| Problem and Why it Happened | Fix |
|---|---|
finalizeAppOwnedSubagent wrote the child result transfer but had no wake path, so the parent never ran again after an async delegation. The result card appeared and the thread simply parked. | Offer a ProviderContinuationRequest for the parent when a delegated child terminalizes. The existing ProviderContinuationService worker dispatches it as a queue_after_active message.dispatch that starts a wake run. |
| An unconditional wake would double-deliver for blocking waits, where the tool call already returns the result, while a settled-only wake would miss async children that finish mid-turn. | Record a per-task completionWake policy. "always" for async delegations offers on every child terminal and queues behind a live parent run. "settled_only" for wait-mode delegations, and for legacy records without the field, offers only when the parent has no run in preparing/starting/running. |
A settled_only wait child that terminalized under a live parent lost its wake permanently once the blocking wait had timed out. | New delegated_task.wake-policy command. On wait timeout the MCP service upgrades the task to "always" best-effort, and for an already-terminal task it offers the wake directly when the parent has a live run, which is exactly the state where finalize's gate skipped it. |
| The gate could read a stale parent snapshot, and finalize wrote the parent subagent row while holding only the child dispatch lock, racing the wake-policy command's write of the same row. | Resolve the parent from the child's immutable lineage, then run finalize under the parent thread lock and startNextQueuedRun under the child lock, sequentially and never nested. Gates re-read run state fresh inside the parent lock. |
The wake started a run but never prompted the model, so the agent still could not act on the result. ProviderContinuationRequests is provider-native: its dispatch only triggers ingestion of output an adapter already buffered, and both ClaudeAdapterV2 and AcpAdapterV2 discard the message text when it is marked creationSource: "provider". An app-owned child buffers nothing, so the adapter drained an empty buffer and finalized the turn immediately. | Add delivery to ProviderContinuationRequest. adapter_buffered stays the default and preserves provider-native behavior; message_text dispatches creationSource: "server", which no adapter mistakes for a buffered wake. Both offer sites build the request through one delegatedTaskWakeRequest helper so they cannot diverge. |
| Agents polled or spawned watchers for async children because the tool description did not say the thread wakes. | delegate_task description now states that async children wake the thread, so callers should end the turn rather than poll or spawn watchers. |
The message_text wake above is dispatched as creationSource: "server" precisely so no adapter mistakes it for a buffered wake. But ClaudeAdapterV2 keys its task-notification guard on that same "provider" marker, and dropped every task-notification-origin terminal result on a turn without it. So the wake run's own terminal was discarded, finalizeActiveTurn never ran, and the run stayed running while every run queued behind it stalled. Observed in production for 8h27m, with three terminal success results carrying num_turns 154, 60 and 7 all dropped, and five queued runs never dispatched. | fix(claude): Settle positive task-notification results, the second commit here, gates that drop on message.num_turns === 0. The stale interrupt-recovery debris the guard was written for is explicitly zero-turn and is still dropped; a result representing real model work now reaches the steering classifier and terminalization as normal. It drops strictly fewer results than before, so no previously working path can regress. |
Manual test guide#
Browsable scenario guide: <https://nam7nt0rbtm6.postplan.dev/>
Sections that cover this PR:
- Claude · background 7, App-owned delegated child wakes the parent.
The scenario for this change. Automated equivalent is the
claude-delegated-task-wakepack. - Claude · background 2, Background Bash post-settle wake. The provider-native regression guard: this PR narrows when a continuation is offered, so a native background wake must still fire exactly once.
- Claude · background 5, Background subagent post-settle and 6, Resume completed subagent. Provider-native subagent wakes, which must keep working unchanged.
Validation#
Focused suites: contracts decode tests for
completionWakeand thedelegated_task.wake-policycommand struct;ProviderContinuationServicetests for both delivery mappings; MCP toolkit integration tests covering wait-completes, async-cancel under a live parent, wait-timeout upgrade, an already-terminal upgrade in both sub-cases, and a legacy field-omitted child. The integration probes assertdeliveryat every offer site.Full
apps/serversuite passes on this base: 1674 passed, 10 skipped.vp checkandvp run typecheckclean.Live-verified on a packaged desktop build, reading the provider session transcript rather than the projection, because a projected message does not prove delivery:
- Settled parent: the wake prompt reached the model, it called
task_status, and replied with the child's result. The wake run took 5.5s, versus an 89ms empty run before the delivery fix. - Mid-turn
alwayspath: the child terminalized 35s before the root turn ended, the wake was requested while the parent was still live, queued behind it, and was delivered exactly once after the root settled. - Provider-native regression guard: a background Bash wake still attaches its buffered CLI output and responds normally.
- Settled parent: the wake prompt reached the model, it called
For the second commit:
ClaudeAdapterV2.test.tscovers a server wake and a user turn settling from a positive task-notification result, a zero-turn result still being ignored on a normal turn, a zero-turn result still consumed by a provider continuation, debris racing an interrupt, and a positive error result. Removing only thenum_turns === 0condition fails exactly the positive-turn cases, run independently as a negative check.Claude live packs on this base pass: in-turn background bash, foreground subagent, monitor, post-settle background bash wake, post-settle subagent, and resume subagent. These are the provider-native regression guard for the adapter change; the drop this commit narrows is not reachable from them, because a task-notification result only arrives on a provider continuation turn there, which the guard deliberately never applied to.
The unit and integration layers prove the offer and the delivery mapping; the packaged run is what proves the model is actually prompted end to end.
Known limitations#
- The offer queue is in-memory. A crash between the result-transfer write and the worker dispatch loses that wake on replay, since the transfer guard blocks re-offering. A durable outbox keyed by the result transfer is the proper fix.
- One documented missed-wake window remains: finalize skips under
settled_onlywith a live parent, the parent settles, and a late upgrade then also skips because the parent is no longer live. The MCP path awaits the upgrade inside the parent's turn, so this mostly affects direct command callers. Tracking wake delivery explicitly, rather than dual-gating on liveness, would close it. - Reconcile-path run updates skip
finalizeAppOwnedSubagententirely, so recovery-cancelled children produce no transfer and no wake. Pre-existing. - A wake can start ahead of a queued-only user run, because
queue_after_activeonly queues behind blocking runs.
Note
Wake settled parent threads when delegated child tasks finish#
- Adds a
completionWakepolicy field to subagent records anddelegated_task.requestcommands:settled_only(wait mode) wakes the parent only when it has no live run;always(async mode) wakes it even mid-turn. - Adds a new
delegated_task.wake-policycommand so the orchestrator MCP service can upgrade a timed-out wait-mode task's wake policy toalwaysafter the blocking wait expires. ProviderContinuationServicenow dispatchesmessage_textwake requests asserver-created prompts so adapters ingest the child result as a real message instead of a buffered wake signal.ClaudeAdapterV2no longer finalizes normal (non-continuation) turns on zero-turn task-notification results, preventing spurious turn endings from async child completions.- Lock acquisition in
resumeQueuedRunsis restructured to take the parent thread lock before the child lock, avoiding nested lock inversion during subagent finalization.
Note
High Risk Touches orchestration locking, MCP delegation delivery, and Claude turn finalization on a path that previously caused multi-hour stuck runs; incorrect wake gating or adapter handling could duplicate wakes, miss wakes, or leave runs non-terminal.
Overview Settled parent threads now get a continuation when app-owned delegated children finish, instead of parking until the user sends another message.
The orchestrator records a per-task completionWake policy (always for async MCP delegations, settled_only for blocking wait). When a child terminalizes, finalizeAppOwnedSubagent may offer a parent wake via ProviderContinuationRequest, gated on whether the parent still has a live run. A new delegated_task.wake-policy command rewrites that policy; MCP delegate_task dispatches it best-effort after a wait timeout so a late child finish can still wake a mid-turn parent. Finalization now takes the parent thread lock (child lock only for queueing), avoiding races on the subagent row.
Wakes are delivered as real prompts: delivery: "message_text" on continuation requests makes ProviderContinuationService dispatch with creationSource: "server" so adapters do not treat app-owned completion text as an empty buffered wake.
ClaudeAdapterV2 only drops zero-turn task-notification-origin results on normal turns (stale debris); positive-turn results can settle the run so those continuations do not hang. delegate_task tool copy tells agents async children wake the thread and to avoid polling.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit cf467bed0fa781bc5ba3ececaf9a2623363bc491. Configure [here](https://www.cursor.com/dashboard/bugbot).
apps/server/src/orchestration-v2/Orchestrator.ts line 5073Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -4895,0 +5053,21 @@5053+ */5054+ const appOwnedSubagentParentThreadId = (childThreadId: ThreadId) =>5055+ Effect.gen(function* () {5056+ const childProjection = yield* projectionStore.getThreadProjection(childThreadId);5057+ const lineage = childProjection.thread.lineage;5058+ return lineage.relationshipToParent === "subagent" &&5059+ lineage.parentThreadId !== null &&5060+ childProjection.thread.forkedFrom?.type === "node"5061+ ? lineage.parentThreadId5062+ : undefined;5063+ });5064+5065+ /**5066+ * Transfers a terminal child's result into its parent and offers the parent5067+ * wake. Every mutation here targets the PARENT thread, so callers must hold5068+ * the parent thread's dispatch lock rather than the child's: the5069+ * delegated_task.wake-policy handler rewrites the same subagent row under5070+ * that lock with a full-row payload, and unserialized writers clobber each5071+ * other (stale policy on the terminal row, or a terminal row regressed to5072+ * running).5073+ */Transfer guard blocks wake retry#
Medium Severity
In
finalizeAppOwnedSubagent, an existingsubagent_resulttransfer causes an immediate return before the continuation wake is offered. The wake runs only afterwriteSystemEventspersists that transfer, so any retry or replay after a successful transfer write but before a successful offer permanently skips the parent wake even though the result is already on the parent.Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit cf467bed0fa781bc5ba3ececaf9a2623363bc491. Configure [here](https://www.cursor.com/dashboard/bugbot).Additional Locations (1)
Confirmed, and thanks: the early return does sit above the offer, so once the result transfer is persisted a replay cannot re-offer the wake.
I'm leaving it as a documented limitation in this PR rather than fixing it here, for two reasons.
It is pre-existing rather than introduced by this change.
ProviderContinuationRequestshas been an in-memory queue since it landed, and provider-native wakes (background Bash, monitors) have always carried the same exposure. This PR adds a second producer to that mechanism; it does not create the durability gap.The correct fix is also architectural rather than local. Weakening the transfer guard would reintroduce duplicate wakes on boot replay, which is exactly what the guard exists to prevent. Making it genuinely durable means moving the wake into the existing effect outbox as a replay-safe effect emitted in the same
commitCommandas the result transfer, so the guard and the wake can no longer diverge. That is roughly six to nine files including the MCP integration probes, and it deserves its own review rather than riding along here.That follow-up is designed and queued, and it is listed under Known limitations in the PR description along with the other durability caveats.
One detail worth recording for whoever picks it up: app-owned wakes can be made durable precisely because they carry their own payload, so replaying one after a restart is meaningful. Provider-native wakes point into the adapter's in-memory wake buffer, which a restart destroys, so replaying one would attach to nothing and produce the empty continuation the adapter already guards against. The two mechanisms should stay split.
Approvability#
Verdict: Needs human review
This PR introduces significant new orchestration behavior including a new command type, new schema fields, and changed wake logic for parent-child task delegation. Despite the 'fix' framing, this adds substantial new capability to core orchestration infrastructure that controls runtime behavior of task completion notifications.
You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).juliusmarminge merged this3b6251f
juliusmarminge closed this
Sign in to join this conversation.

Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
53e5b720-424d-4ec0-9ac1-09ae8b7d3c4fYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share