fix(server): a thread awaiting a delegated task's result no longer reports completed early #40881
main fromrefs/pull/40881/head·opened View on GitHubProblem#
When an async delegated subagent (origin: "app_owned") finishes while its parent thread is waiting on it, Transaction A marks the subagent turn item terminal (completed) and transitions its completionDelivery to "claimed" ~140–160 ms before Transaction B (ProviderContinuationService) creates the parent's wake run.
During that gap, derivePendingBackgroundWork and the SQL shell/awareness/settlement projections only inspect non-terminal turn items and provider rosters, so pendingBackgroundTasks drops to []. The thread briefly looks settled across sidebar, notifications, push relay, auto-settlement, and MCP status, firing a premature "Thread completed" notification before the wake run starts and then firing a second notification when the wake run finishes.
Change#
packages/shared/src/orchestrationV2PendingBackgroundWork.ts: ExtendderivePendingBackgroundWorkwith optionalsubagentsanduserMessageIdonPendingBackgroundWorkRunso terminalapp_ownedsubagents withcompletionDelivery.statein("pending", "claimed")on open, non-rolled-back parent runs keep holding completion until their wake run actually starts.- Once a
"claimed"subagent's dedicated wake run (run.userMessageId === delivery.messageId) has started (statusnot"queued"or"cancelled"), it stops holding immediately—preventing stale holds during the wake run or between wake-run completion andfinalizeDelegatedCompletionDelivery. - Cancelled wake runs and
"pending"sibling deliveries keep holding because finalization schedules a successor wake. - Intentionally omit
providerInstanceIdon these synthetic entries sohasPendingBackgroundSubagentnever grants idle parent providers native caller access.
- Once a
apps/server/src/persistence/Migrations/108_PendingSubagentDeliveryIndex.ts&Migrations.ts: Add partial indexorchestration_v2_projection_subagents_pending_delivery_idxon(thread_id) WHERE origin = 'app_owned' AND status IN ('completed', 'failed', 'cancelled', 'interrupted') AND completion_delivery_state IN ('pending', 'claimed').- Why this migration is needed: The existing subagents index from migration 075 is prefixed by
thread_id, whereaslistActiveShellIndexscans active threads globally with nothread_idfilter. Without this partial index, everylistActiveShellIndexread would scan the full subagent index; adding it follows the existing partial-index pattern used by everymay_be_livesource.
- Why this migration is needed: The existing subagents index from migration 075 is prefixed by
apps/server/src/orchestration-v2/ProjectionStore.ts: WireselectShellPendingSubagentRows(using the new partial index) intogetThreadShell,readShellSnapshot/getShellSnapshot,getAgentAwarenessSnapshot,getSettlementCandidates,threadShellFromProjection, andlistActiveShellIndex(may_be_live), keeping SQL and JS wake-run semantics identical (includingqueued/cancelledwake runs, missing/stopped/rolled-back parent runs, archived threads, andprovider_nativeexclusion).packages/client-runtime/src/state/threadExecution.ts&apps/web/src/components/ChatView.logic.ts: Pass unarchivedprojection.subagentstoderivePendingBackgroundWorkso the open chat view matches the server shell.- Tests: Add shared unit tests (
packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts), full 5-path SQL/memory parity +EXPLAIN QUERY PLAN+assertShellIndexCoversShellstests (apps/server/src/orchestration-v2/ProjectionStore.test.ts), and migration test coverage (reconcileV2PreviewMigration.test.ts).
Scope#
Fixes #40879.
Kept strictly to the server/shared hold gap for app_owned delegated subagent completions:
- Deliberately leaves
ThreadNotificationCoordinatoruntouched so it respects #29146 (which intentionally removed client continuation grace) and does not conflict with #38318. With the server fix in place, the shell transitions directly from held → queued with no settled gap. - Stop /
thread.background-work.settlealready disposes pending/claimed cohorts viaholdStoppedThread, preserving the escape hatch.
Verification#
- Reproduced from real Orchestration V2 state (two consecutive wakes in one thread):
- Confirmed both new tests fail on
upstream/main(620cf4770d) and pass on this branch (4793e46c92):- On
upstream/main:packages/shared/src/orchestrationV2PendingBackgroundWork.test.tsfails: dropsnode:claimed,node:claimed-cancelled,node:claimed-queued, andnode:pending-failed.apps/server/src/orchestration-v2/ProjectionStore.test.tsfails acrossgetThreadShell,getShellSnapshot,getAgentAwarenessSnapshot, andgetSettlementCandidates:AssertionError: expected [] to deeply equal [ { taskId: "node:delegated-wake-gap:subagent", description: "Audit PRs", kind: "subagent", childThreadId: "thread:delegated-wake-gap:child" } ]
- On
4793e46c92:- Holds the thread across all 5 read paths while
claimedwith no wake run or aqueued/cancelledwake run; releases immediately once the wake run is running/completed (beforefinalizeDelegatedCompletionDeliveryruns); excludesprovider_native,disposed/delivered/acknowledged, stopped cohorts, rolled-back runs, and archived threads; verifiedEXPLAIN QUERY PLANusesorchestration_v2_projection_subagents_pending_delivery_idx.
- Holds the thread across all 5 read paths while
- On
vp run check:changedpasses cleanly on4793e46c92:format(0.3s),lint(0 errors),knip1/2 & 2/2,graphql,typecheck(37/37 packages),test(8/8 files, 212/212 tests includingProjectionStore.test.ts63/63,Migrations.test.ts11/11,reconcileV2PreviewMigration.test.ts5/5,orchestrationV2PendingBackgroundWork.test.ts22/22), and React Compiler coverage.
Written with Gemini 4 Neon (Antigravity) and audited with Claude Opus 5.5 (Claude Code) in T3 Code.
- 1
KitsuneKode(GitHub profile, opens in a new tab) linked this to fix #40879
tanstack-source added labelsbug
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
juliusmarminge closed this
Sign in to join this conversation.
Thanks for this. #31357 makes the same change and is the one being kept.
#31357 covers the same delegated-result handoff with a smaller change. It requires a reserved wake delivery before holding a finished task, avoiding an indefinite wait for pending results that have no wake scheduled.
Your SQL and in-memory parity coverage would be useful additional coverage for that fix.
Closing as a duplicate.