From ba5b043d1f35d746c20f8bff711be57d687b2bc0 Mon Sep 17 00:00:00 2001 From: Shivam Sharma <91240327+shivamhwp@users.noreply.github.com> Date: Wed, 5 Aug 2026 07:14:15 +0530 Subject: [PATCH] fix(orchestration-v2): require reactivation proof before identity routing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pre-seeded reactivatable identities were treated as current-run ownership, so an interrupted prior run's trailing traffic — delayed non-terminal rows, activation updates, subagent items — was admitted and misattributed: stale child threads got adopted, ingestion could be held open indefinitely, and finalization could terminalize a prior run's activation with this run's outcome. Identity routing now requires proof that this run drives the agent. The seed carries each identity's activation count at turn start; a genuine re-activation always advances past that baseline, while trailing traffic re-emits at it. Rows carrying this run's id, rows advancing the baseline, and activations with a higher ordinal all prove it; until one arrives, identity-only events are refused, and the lifecycle tracker keys on the proven set rather than the seeded one. Also folds in two review fixes: Claude cache-read tokens now count into inputTokens (they are input the model consumed, and excluding them broke reconciliation with the four-component total), and a running workflow coordinator stays counted in the Agents panel while all its members are settled — between phases the coordinator is the only live row, and dropping it read "0 active" for a visibly running workflow. Co-Authored-By: Claude Fable 5 --- .../Adapters/ClaudeAdapterV2.ts | 13 ++- .../ProviderTurnStartService.ts | 5 +- .../RunExecutionService.test.ts | 33 ++++++- .../orchestration-v2/RunExecutionService.ts | 89 +++++++++++++++---- 4 files changed, 115 insertions(+), 25 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 53daae3d96..eff751c27a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -1551,9 +1551,16 @@ function claudeSubagentUsage(value: unknown): OrchestrationV2SubagentUsage | und } return { totalTokens, - ...(inputTokens === undefined && cacheCreationTokens === undefined + // Cache reads are input the model consumed; excluding them understates + // inputTokens against the four-component totalTokens it must reconcile + // with. + ...(inputTokens === undefined && + cacheCreationTokens === undefined && + cachedInputTokens === undefined ? {} - : { inputTokens: (inputTokens ?? 0) + (cacheCreationTokens ?? 0) }), + : { + inputTokens: (inputTokens ?? 0) + (cacheCreationTokens ?? 0) + (cachedInputTokens ?? 0), + }), ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), ...(outputTokens === undefined ? {} : { outputTokens }), ...(toolUses === undefined ? {} : { toolUses }), @@ -3084,7 +3091,7 @@ export function makeClaudeAdapterV2( : { role: providerSubagentRole(input.agentType, input.roleFallback) }), ...(input.workflow === undefined ? {} - : { workflow: { phases: [], ...(priorTask?.workflow ?? {}), ...input.workflow } }), + : { workflow: { phases: [], ...priorTask?.workflow, ...input.workflow } }), ...(input.workflowMembership === undefined ? {} : { workflowMembership: input.workflowMembership }), diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 56c7742adf..6a01137c11 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -488,7 +488,10 @@ export const layer: Layer.Layer< relatedProviderThreadIds: routableSubagents.flatMap((subagent) => subagent.providerThreadId === null ? [] : [subagent.providerThreadId], ), - relatedSubagentIds: reactivatableSubagents.map((subagent) => subagent.id), + reactivatableSubagentSeeds: reactivatableSubagents.map((subagent) => ({ + id: subagent.id, + activationCount: subagent.activationCount, + })), existingSubagents, providerTurnOrdinal: Math.max( diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index 213bf43fb0..2d8e24aaec 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -254,8 +254,35 @@ it.effect("routes a reused subagent's rows to the run that re-activated it", () const seeded = makeProviderEventRoutingState({ identity: laterRun, providerTurnId: null, - relatedSubagentIds: [subagentId], + reactivatableSubagentSeeds: [{ id: subagentId, activationCount: 1 }], }); + + // Trailing traffic from the run that spawned the agent re-emits at the + // seeded baseline; identity alone must not admit it, or its stale child + // thread would be adopted into this run. + const staleTrailingRow: ProviderAdapterV2Event = { + ...subagentEvent, + subagent: { ...subagentEvent.subagent, activationCount: 1 }, + }; + assert.isFalse(routeProviderEvent(staleTrailingRow, laterRun, seeded)[0]); + const staleActivation: ProviderAdapterV2Event = { + ...activationEvent, + activation: { + ...activationEvent.activation, + id: SubagentActivationId.make(`${subagentId}:activation:1`), + ordinal: 1, + }, + }; + assert.isFalse(routeProviderEvent(staleActivation, laterRun, seeded)[0]); + // A stale subagent item is refused too until the reactivation is proven. + assert.isFalse(routeProviderEvent(turnItemEvent, laterRun, seeded)[0]); + assert.isFalse( + isRunOwnedSubagentTurnItem({ + turnItem: turnItemEvent.turnItem, + runId: laterRun.runId, + activatedSubagentIds: seeded.activatedSubagentIds, + }), + ); const [subagentAccepted, afterSubagent] = routeProviderEvent(subagentEvent, laterRun, seeded); assert.isTrue(subagentAccepted); assert.isTrue(routeProviderEvent(activationEvent, laterRun, afterSubagent)[0]); @@ -264,7 +291,7 @@ it.effect("routes a reused subagent's rows to the run that re-activated it", () isRunOwnedSubagentTurnItem({ turnItem: turnItemEvent.turnItem, runId: laterRun.runId, - ownedSubagentIds: afterSubagent.ownedSubagentIds, + activatedSubagentIds: afterSubagent.activatedSubagentIds, }), ); // Accepting the row also adopts its child thread, so the agent's own @@ -570,7 +597,7 @@ it.effect("re-activates an interrupted subagent without adopting its stale child identity: laterRun, providerTurnId: null, relatedThreadIds: [], - relatedSubagentIds: [subagentId], + reactivatableSubagentSeeds: [{ id: subagentId, activationCount: 1 }], }); // A late event from the interrupted child thread must still be refused — diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index aac5fb89b4..35f13aaea6 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -61,6 +61,16 @@ export interface ProviderEventRoutingState { // run id it was spawned under, so a later run that re-activates it cannot // recognise its rows by run or by parent thread; it matches on identity. readonly ownedSubagentIds: ReadonlySet; + // The activation count each reactivatable identity had when this run + // started. Pre-seeded membership alone is reactivation *potential*; a + // genuine re-activation always advances past this baseline, while trailing + // traffic from a prior run re-emits at it. + readonly reactivatableBaselines: ReadonlyMap; + // Identities proven driven by this run: a row carried this run's id, or an + // activation advanced past the seeded baseline. Identity-only routing + // requires this proof, or an interrupted prior run's trailing traffic would + // be misattributed here. + readonly activatedSubagentIds: ReadonlySet; readonly rootProviderTurnId: ProviderTurnId | null; } @@ -211,11 +221,13 @@ export function canReactivateSubagent(status: OrchestrationV2Subagent["status"]) export function isRunOwnedSubagentTurnItem(input: { readonly turnItem: OrchestrationV2TurnItem; readonly runId: OrchestrationV2Run["id"]; - readonly ownedSubagentIds: ReadonlySet; + /** Identities proven driven by this run — not the pre-seeded reactivatable set. */ + readonly activatedSubagentIds: ReadonlySet; }): boolean { return ( input.turnItem.runId === input.runId || - (input.turnItem.type === "subagent" && input.ownedSubagentIds.has(input.turnItem.subagentId)) + (input.turnItem.type === "subagent" && + input.activatedSubagentIds.has(input.turnItem.subagentId)) ); } @@ -388,7 +400,10 @@ export function makeProviderEventRoutingState(input: { readonly providerTurnId: ProviderTurnId | null; readonly relatedThreadIds?: ReadonlyArray; readonly relatedProviderThreadIds?: ReadonlyArray; - readonly relatedSubagentIds?: ReadonlyArray; + readonly reactivatableSubagentSeeds?: ReadonlyArray<{ + readonly id: NodeId; + readonly activationCount: number; + }>; }): ProviderEventRoutingState { return { ownedThreadIds: new Set([input.identity.threadId, ...(input.relatedThreadIds ?? [])]), @@ -401,7 +416,11 @@ export function makeProviderEventRoutingState(input: { inheritedBackgroundTurnItems: new Map( (input.inheritedBackgroundTurnItems ?? []).map((item) => [item.id, item.runId]), ), - ownedSubagentIds: new Set(input.relatedSubagentIds ?? []), + ownedSubagentIds: new Set((input.reactivatableSubagentSeeds ?? []).map((seed) => seed.id)), + reactivatableBaselines: new Map( + (input.reactivatableSubagentSeeds ?? []).map((seed) => [seed.id, seed.activationCount]), + ), + activatedSubagentIds: new Set(), rootProviderTurnId: input.providerTurnId, }; } @@ -427,7 +446,8 @@ export function routeProviderEvent( ownedProviderTurnIds: new Set([...state.ownedProviderTurnIds, providerTurnId]), rootProviderTurnId: root ? providerTurnId : state.rootProviderTurnId, }); - const ownsSubagent = (subagentId: NodeId): boolean => state.ownedSubagentIds.has(subagentId); + const drivesSubagent = (subagentId: NodeId): boolean => + state.activatedSubagentIds.has(subagentId); /** * Track the identity so every later row for the same subagent routes. * @@ -441,9 +461,13 @@ export function routeProviderEvent( subagentId: NodeId, childThreadId: ThreadId | null, live: boolean, + drivenByRun: boolean, ): ProviderEventRoutingState => ({ ...state, ownedSubagentIds: new Set([...state.ownedSubagentIds, subagentId]), + activatedSubagentIds: drivenByRun + ? new Set([...state.activatedSubagentIds, subagentId]) + : state.activatedSubagentIds, ownedThreadIds: childThreadId === null || !live ? state.ownedThreadIds @@ -498,10 +522,22 @@ export function routeProviderEvent( return [true, addProviderThread(event.node.providerThreadId)]; } case "subagent.updated": { + const drivenByRun = ownsRun(event.subagent.runId); + const baseline = state.reactivatableBaselines.get(event.subagent.id); + // Identity alone is not ownership: a pre-seeded id is admitted only once + // this run proves it drives the agent. A genuine re-activation advances + // the activation count past the seeded baseline; an interrupted prior + // run's trailing rows re-emit at it and stay excluded. + const provesReactivation = + !drivenByRun && + baseline !== undefined && + !isTerminalSubagentStatus(event.subagent.status) && + event.subagent.activationCount > baseline; const belongs = - ownsRun(event.subagent.runId) || + drivenByRun || ownsChildThread(event.subagent.threadId) || - ownsSubagent(event.subagent.id); + drivesSubagent(event.subagent.id) || + provesReactivation; return belongs ? [ true, @@ -509,17 +545,31 @@ export function routeProviderEvent( event.subagent.id, event.subagent.childThreadId, !isTerminalSubagentStatus(event.subagent.status), + drivenByRun || provesReactivation || drivesSubagent(event.subagent.id), ), ] : [false, state]; } - case "subagent_activation.updated": + case "subagent_activation.updated": { + const baseline = state.reactivatableBaselines.get(event.activation.subagentId); + const provesReactivation = baseline !== undefined && event.activation.ordinal > baseline; + if (ownsRun(event.activation.runId) || provesReactivation) { + return [ + true, + { + ...state, + activatedSubagentIds: new Set([ + ...state.activatedSubagentIds, + event.activation.subagentId, + ]), + }, + ]; + } return [ - ownsRun(event.activation.runId) || - ownsChildThread(event.activation.threadId) || - ownsSubagent(event.activation.subagentId), + ownsChildThread(event.activation.threadId) || drivesSubagent(event.activation.subagentId), state, ]; + } case "message.updated": return [ownsRun(event.message.runId) || ownsChildThread(event.message.threadId), state]; case "turn_item.updated": { @@ -529,7 +579,7 @@ export function routeProviderEvent( // A reused subagent's row and its timeline item are emitted together; // routing only the row would advance the agent while its item stayed // frozen on the spawning run. - (event.turnItem.type === "subagent" && ownsSubagent(event.turnItem.subagentId)) + (event.turnItem.type === "subagent" && drivesSubagent(event.turnItem.subagentId)) ) { return [true, state]; } @@ -620,7 +670,10 @@ export interface RunExecutionServiceV2StartRootRunInput { >; readonly relatedThreadIds?: ReadonlyArray; readonly relatedProviderThreadIds?: ReadonlyArray; - readonly relatedSubagentIds?: ReadonlyArray; + readonly reactivatableSubagentSeeds?: ReadonlyArray<{ + readonly id: NodeId; + readonly activationCount: number; + }>; readonly existingSubagents?: ReadonlyArray; readonly shouldStartProviderTurn?: () => Effect.Effect; readonly shouldFinalizeRun?: () => Effect.Effect; @@ -989,9 +1042,9 @@ export const layer: Layer.Layer< ...(input.relatedProviderThreadIds === undefined ? {} : { relatedProviderThreadIds: input.relatedProviderThreadIds }), - ...(input.relatedSubagentIds === undefined + ...(input.reactivatableSubagentSeeds === undefined ? {} - : { relatedSubagentIds: input.relatedSubagentIds }), + : { reactivatableSubagentSeeds: input.reactivatableSubagentSeeds }), }), ); const rootTerminalSeen = yield* Ref.make(false); @@ -1061,7 +1114,7 @@ export const layer: Layer.Layer< // holds this run open the same way a freshly spawned one does. const belongsToRootRun = event.subagent.runId === input.run.id || - routing.ownedSubagentIds.has(event.subagent.id); + routing.activatedSubagentIds.has(event.subagent.id); const belongsToOwnedChildThread = event.subagent.threadId !== input.run.threadId && routing.ownedThreadIds.has(event.subagent.threadId); @@ -1096,7 +1149,7 @@ export const layer: Layer.Layer< if (event.type === "subagent_activation.updated") { const belongsToRootRun = event.activation.runId === input.run.id || - routing.ownedSubagentIds.has(event.activation.subagentId); + routing.activatedSubagentIds.has(event.activation.subagentId); const belongsToOwnedChildThread = event.activation.threadId !== input.run.threadId && routing.ownedThreadIds.has(event.activation.threadId); @@ -1141,7 +1194,7 @@ export const layer: Layer.Layer< const belongsToRootRun = isRunOwnedSubagentTurnItem({ turnItem: event.turnItem, runId: input.run.id, - ownedSubagentIds: routing.ownedSubagentIds, + activatedSubagentIds: routing.activatedSubagentIds, }); const belongsToOwnedChildThread = event.turnItem.threadId !== input.run.threadId &&