fix(orchestration-v2): harden reused subagent recovery

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
Shivam SharmaandClaude authored and T3 Code Test committed 2026-08-14 15:04:11 +05:30
1 parent 6ece559186
commit dedb92f627
4 files changed
+453 -52

No files matched your search

@@ -1,8 +1,12 @@
import { expect, it, vi } from "vite-plus/test";
import { assert, it } from "@effect/vitest";
import {
CheckpointScopeId,
MessageId,
NodeId,
type OrchestrationV2ThreadProjection,
ProviderDriverKind,
ProviderInstanceId,
ProviderSessionId,
ProviderThreadId,
RunAttemptId,
@@ -42,6 +46,58 @@ it("does not commit running state when inherited background routing cannot be re
runs: [
{
id: runId,
TurnItemId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts";
import { EventSinkV2 } from "./EventSink.ts";
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
import type { ProviderAdapterV2SessionRuntime } from "./ProviderAdapter.ts";
import {
ProjectionStoreReadError,
ProjectionStoreThreadNotFoundError,
ProjectionStoreV2,
type ProjectionStoreV2Error,
} from "./ProjectionStore.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import {
layer as providerTurnStartLayer,
ProviderTurnStartServiceV2,
} from "./ProviderTurnStartService.ts";
import { RunExecutionServiceV2 } from "./RunExecutionService.ts";
import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
const driver = ProviderDriverKind.make("codex");
const threadId = ThreadId.make("thread:provider-turn-start");
const childThreadId = ThreadId.make("thread:provider-turn-start:child");
const runId = RunId.make("run:provider-turn-start");
const rootNodeId = NodeId.make("node:provider-turn-start:root");
const subagentId = NodeId.make("node:provider-turn-start:subagent");
const attemptId = RunAttemptId.make("attempt:provider-turn-start");
const providerThreadId = ProviderThreadId.make("provider-thread:provider-turn-start");
const childProviderThreadId = ProviderThreadId.make("provider-thread:provider-turn-start:child");
const providerSessionId = ProviderSessionId.make("provider-session:provider-turn-start");
const providerInstanceId = ProviderInstanceId.make("codex");
const messageId = MessageId.make("message:provider-turn-start");
const checkpointScopeId = CheckpointScopeId.make("checkpoint-scope:provider-turn-start");
function makeRootProjection(now: DateTime.Utc): OrchestrationV2ThreadProjection {
return {
thread: {
id: threadId,
runtimeMode: "full-access",
interactionMode: "default",
worktreePath: "/tmp/provider-turn-start",
},
runs: [
{
id: runId,
threadId,
ordinal: 1,
status: "starting",
rootNodeId,
activeAttemptId: attemptId,
@@ -101,3 +157,230 @@ it("does not commit running state when inherited background routing cannot be re
expect(startRootRun).not.toHaveBeenCalled();
}).pipe(Effect.provide(layer), Effect.runPromise);
});
providerInstanceId,
userMessageId: messageId,
modelSelection: { instanceId: providerInstanceId },
},
],
nodes: [
{
id: rootNodeId,
checkpointScopeId,
},
],
attempts: [
{
id: attemptId,
providerTurnId: null,
},
],
providerThreads: [
{
id: providerThreadId,
providerSessionId,
nativeThreadRef: {
driver,
nativeId: "native-root-thread",
strength: "strong",
},
ownerNodeId: rootNodeId,
firstRunOrdinal: 1,
lastRunOrdinal: 1,
handoffIds: [],
forkedFrom: null,
createdAt: now,
},
],
messages: [
{
id: messageId,
text: "continue the agent",
attachments: [],
createdBy: "user",
creationSource: "user",
},
],
checkpointScopes: [{ id: checkpointScopeId }],
contextHandoffs: [],
contextTransfers: [],
providerSessions: [],
subagents: [
{
id: subagentId,
status: "idle",
childThreadId,
providerThreadId: childProviderThreadId,
},
],
turnItems: [
{
id: TurnItemId.make("turn-item:provider-turn-start:subagent"),
type: "subagent",
subagentId,
ordinal: 1,
},
],
providerTurns: [],
} as unknown as OrchestrationV2ThreadProjection;
}
function makeChildProjection(now: DateTime.Utc): OrchestrationV2ThreadProjection {
return {
thread: { id: childThreadId },
providerThreads: [
{
id: childProviderThreadId,
nativeThreadRef: {
driver,
nativeId: "native-child-thread",
strength: "strong",
},
createdAt: now,
},
],
} as unknown as OrchestrationV2ThreadProjection;
}
function makeTestLayer(input: {
readonly rootProjection: OrchestrationV2ThreadProjection;
readonly childProjection: Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error>;
readonly existingSubagentCounts: Ref.Ref<ReadonlyArray<number>>;
readonly providerSessionOpens: Ref.Ref<number>;
readonly runningWrites: Ref.Ref<number>;
}) {
const session = {
driver,
providerSession: { id: providerSessionId },
resumeThread: ({ providerThread }: { readonly providerThread: unknown }) =>
Effect.succeed(providerThread),
} as unknown as ProviderAdapterV2SessionRuntime;
return providerTurnStartLayer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(ContextHandoffServiceV2)({}),
Layer.mock(EventSinkV2)({
writeIfRunCurrent: () =>
Ref.update(input.runningWrites, (count) => count + 1).pipe(
Effect.as({ committed: true, storedEvents: [] }),
),
}),
idAllocatorLayer,
Layer.mock(ProjectionStoreV2)({
getThreadProjection: (requestedThreadId) =>
requestedThreadId === threadId
? Effect.succeed(input.rootProjection)
: input.childProjection,
}),
Layer.mock(ProviderSessionManagerV2)({
open: () =>
Ref.update(input.providerSessionOpens, (count) => count + 1).pipe(Effect.as(session)),
}),
Layer.mock(RunExecutionServiceV2)({
startRootRun: (startInput) =>
Ref.update(input.existingSubagentCounts, (counts) => [
...counts,
startInput.existingSubagents?.length ?? 0,
]),
}),
Layer.mock(RuntimePolicyV2)({
resolve: () =>
Effect.succeed({
runtimeMode: "full-access",
interactionMode: "default",
cwd: "/tmp/provider-turn-start",
}),
}),
),
),
);
}
it.effect("fails before provider turn start when child projection rehydration cannot be read", () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const existingSubagentCounts = yield* Ref.make<ReadonlyArray<number>>([]);
const providerSessionOpens = yield* Ref.make(0);
const runningWrites = yield* Ref.make(0);
const readError = new ProjectionStoreReadError({
threadId: childThreadId,
cause: "temporary database failure",
});
const error = yield* Effect.gen(function* () {
const service = yield* ProviderTurnStartServiceV2;
return yield* service.start({ threadId, runId }).pipe(Effect.flip);
}).pipe(
Effect.provide(
makeTestLayer({
rootProjection: makeRootProjection(now),
childProjection: Effect.fail(readError),
existingSubagentCounts,
providerSessionOpens,
runningWrites,
}),
),
);
assert.equal(error._tag, "ProviderTurnStartError");
assert.strictEqual(error.cause, readError);
assert.deepEqual(yield* Ref.get(existingSubagentCounts), []);
assert.equal(yield* Ref.get(providerSessionOpens), 0);
assert.equal(yield* Ref.get(runningWrites), 0);
}),
);
it.effect("skips a missing child projection and still starts the provider turn", () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const existingSubagentCounts = yield* Ref.make<ReadonlyArray<number>>([]);
const providerSessionOpens = yield* Ref.make(0);
const runningWrites = yield* Ref.make(0);
yield* Effect.gen(function* () {
const service = yield* ProviderTurnStartServiceV2;
yield* service.start({ threadId, runId });
}).pipe(
Effect.provide(
makeTestLayer({
rootProjection: makeRootProjection(now),
childProjection: Effect.fail(
new ProjectionStoreThreadNotFoundError({ threadId: childThreadId }),
),
existingSubagentCounts,
providerSessionOpens,
runningWrites,
}),
),
);
assert.deepEqual(yield* Ref.get(existingSubagentCounts), [0]);
assert.equal(yield* Ref.get(providerSessionOpens), 1);
assert.equal(yield* Ref.get(runningWrites), 1);
}),
);
it.effect("rehydrates an existing child projection before starting the provider turn", () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const existingSubagentCounts = yield* Ref.make<ReadonlyArray<number>>([]);
const providerSessionOpens = yield* Ref.make(0);
const runningWrites = yield* Ref.make(0);
yield* Effect.gen(function* () {
const service = yield* ProviderTurnStartServiceV2;
yield* service.start({ threadId, runId });
}).pipe(
Effect.provide(
makeTestLayer({
rootProjection: makeRootProjection(now),
childProjection: Effect.succeed(makeChildProjection(now)),
existingSubagentCounts,
providerSessionOpens,
runningWrites,
}),
),
);
assert.deepEqual(yield* Ref.get(existingSubagentCounts), [1]);
assert.equal(yield* Ref.get(providerSessionOpens), 1);
assert.equal(yield* Ref.get(runningWrites), 1);
}),
);
@@ -20,8 +20,7 @@ import {
providerMessageWithContextHandoffs,
} from "./ContextHandoffService.ts";
import { IdAllocatorV2 } from "./IdAllocator.ts";
import type { ProviderAdapterV2ExistingSubagent } from "./ProviderAdapter.ts";
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
import { ProjectionStoreThreadNotFoundError, ProjectionStoreV2 } from "./ProjectionStore.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import {
canReactivateSubagent,
@@ -144,6 +143,53 @@ export const layer: Layer.Layer<
.getThreadProjection(projection.thread.id)
.pipe(Effect.map(selectInheritedBackgroundItems));
const providerSessionId = providerThread.providerSessionId;
const routableSubagents = projection.subagents.filter((subagent) =>
canRouteRelatedSubagent(subagent.status),
);
// Broader than the child-thread list above: an interrupted agent is still
// resumable, so it stays re-activatable even though its thread must not
// be adopted up front.
const reactivatableSubagents = projection.subagents.filter((subagent) =>
canReactivateSubagent(subagent.status),
);
// Resolve the persisted registry before opening the provider session or
// advancing the run. Operational read failures must leave the run in
// `starting` so the durable effect can retry safely.
const existingSubagents = yield* Effect.forEach(
reactivatableSubagents,
(subagent, index) =>
Effect.gen(function* () {
const childThreadId = subagent.childThreadId;
if (childThreadId === null) return [];
const turnItem = projection.turnItems.find(
(item) => item.type === "subagent" && item.subagentId === subagent.id,
);
if (turnItem === undefined) return [];
const childProjection = yield* projectionStore
.getThreadProjection(childThreadId)
.pipe(
Effect.catchIf(Schema.is(ProjectionStoreThreadNotFoundError), () =>
Effect.succeed(null),
),
);
if (childProjection === null) return [];
const childProviderThread = childProjection.providerThreads.find(
(candidate) => candidate.id === subagent.providerThreadId,
);
if (childProviderThread === undefined) return [];
return [
{
subagent,
childThread: childProjection.thread,
childProviderThread,
turnItemId: turnItem.id,
turnItemOrdinal: turnItem.ordinal,
ordinal: index + 1,
},
];
}),
{ concurrency: "unbounded" },
).pipe(Effect.map((entries) => entries.flat()));
const isCurrentAttemptInStatus = (
expectedStatus: OrchestrationV2Run["status"],
): Effect.Effect<boolean, never> =>
@@ -422,50 +468,6 @@ export const layer: Layer.Layer<
if (!runningWrite.committed) {
return;
}
const routableSubagents = projection.subagents.filter((subagent) =>
canRouteRelatedSubagent(subagent.status),
);
// Broader than the child-thread list above: an interrupted agent is still
// resumable, so it stays re-activatable even though its thread must not
// be adopted up front.
const reactivatableSubagents = projection.subagents.filter((subagent) =>
canReactivateSubagent(subagent.status),
);
// Adapters keep their subagent registry in memory, so it is empty after a
// session reap or a server restart. Hand back the reusable identities
// from the projection so a returning agent thread is recognised instead
// of being spawned again as a duplicate.
const existingSubagents = yield* Effect.forEach(
reactivatableSubagents,
(subagent, index): Effect.Effect<ReadonlyArray<ProviderAdapterV2ExistingSubagent>> =>
Effect.gen(function* () {
const childThreadId = subagent.childThreadId;
if (childThreadId === null) return [];
const turnItem = projection.turnItems.find(
(item) => item.type === "subagent" && item.subagentId === subagent.id,
);
if (turnItem === undefined) return [];
const childProjection = yield* projectionStore
.getThreadProjection(childThreadId)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (childProjection === null) return [];
const childProviderThread = childProjection.providerThreads.find(
(candidate) => candidate.id === subagent.providerThreadId,
);
if (childProviderThread === undefined) return [];
return [
{
subagent,
childThread: childProjection.thread,
childProviderThread,
turnItemId: turnItem.id,
turnItemOrdinal: turnItem.ordinal,
ordinal: index + 1,
},
];
}),
{ concurrency: "unbounded" },
).pipe(Effect.map((entries) => entries.flat()));
yield* runExecution.startRootRun({
commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`),
appThread: projection.thread,
@@ -46,6 +46,7 @@ import {
canRouteRelatedSubagent,
cascadeTerminalizeRunOwnedSubagents,
finalProviderThreadStatus,
isRunOwnedSubagentTurnItem,
layer as runExecutionServiceLayer,
makeProviderEventRoutingState,
type ProviderEventRouteIdentity,
@@ -213,6 +214,34 @@ it.effect("routes a reused subagent's rows to the run that re-activated it", ()
updatedAt: now,
},
};
const turnItemEvent = {
type: "turn_item.updated",
driver,
turnItem: {
id: TurnItemId.make("turn-item:reuse:subagent"),
threadId,
runId: spawnRunId,
nodeId: subagentId,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 2,
status: "running",
title: "reused agent",
startedAt: now,
completedAt: null,
updatedAt: now,
type: "subagent",
subagentId,
origin: "provider_native",
driver,
providerInstanceId: ProviderInstanceId.make("codex"),
childThreadId,
prompt: "continue",
result: null,
},
} satisfies ProviderAdapterV2Event;
const withoutSeed = makeProviderEventRoutingState({
identity: laterRun,
@@ -220,6 +249,7 @@ it.effect("routes a reused subagent's rows to the run that re-activated it", ()
});
assert.isFalse(routeProviderEvent(subagentEvent, laterRun, withoutSeed)[0]);
assert.isFalse(routeProviderEvent(activationEvent, laterRun, withoutSeed)[0]);
assert.isFalse(routeProviderEvent(turnItemEvent, laterRun, withoutSeed)[0]);
const seeded = makeProviderEventRoutingState({
identity: laterRun,
@@ -229,6 +259,14 @@ it.effect("routes a reused subagent's rows to the run that re-activated it", ()
const [subagentAccepted, afterSubagent] = routeProviderEvent(subagentEvent, laterRun, seeded);
assert.isTrue(subagentAccepted);
assert.isTrue(routeProviderEvent(activationEvent, laterRun, afterSubagent)[0]);
assert.isTrue(routeProviderEvent(turnItemEvent, laterRun, afterSubagent)[0]);
assert.isTrue(
isRunOwnedSubagentTurnItem({
turnItem: turnItemEvent.turnItem,
runId: laterRun.runId,
ownedSubagentIds: afterSubagent.ownedSubagentIds,
}),
);
// Accepting the row also adopts its child thread, so the agent's own
// messages and turn items route into this run for the rest of it.
assert.isTrue(afterSubagent.ownedThreadIds.has(childThreadId));
@@ -2826,6 +2864,73 @@ it.effect("cascade helper is provider-neutral for Claude and Codex-shaped child
}),
);
it.effect("terminalizes an identity-owned reused subagent turn item from its spawning run", () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const runId = RunId.make("run:reused-turn-item:current");
const spawnRunId = RunId.make("run:reused-turn-item:spawn");
const threadId = ThreadId.make("thread:reused-turn-item");
const subagentId = NodeId.make("node:reused-turn-item:subagent");
const turnItem = {
id: TurnItemId.make("turn-item:reused-turn-item:subagent"),
threadId,
runId: spawnRunId,
nodeId: subagentId,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 1,
status: "running" as const,
title: "reused agent",
startedAt: now,
completedAt: null,
updatedAt: now,
type: "subagent" as const,
subagentId,
origin: "provider_native" as const,
driver,
providerInstanceId: ProviderInstanceId.make("codex"),
childThreadId: ThreadId.make("thread:reused-turn-item:child"),
prompt: "continue",
progress: "working",
result: null,
} satisfies Extract<OrchestrationV2TurnItem, { type: "subagent" }>;
const events = yield* cascadeTerminalizeRunOwnedSubagents({
run: {
id: runId,
threadId,
ordinal: 2,
providerInstanceId: ProviderInstanceId.make("codex"),
} as OrchestrationV2Run,
open: {
subagents: new Map(),
activations: new Map(),
turnItems: new Map([[subagentId, turnItem]]),
childTurnItems: new Map(),
nodes: new Map(),
linkedChildThreadIds: new Set(),
},
status: "interrupted",
completedAt: now,
allocateEventId: () => Effect.succeed(EventId.make("event:reused-turn-item:cascade")),
});
assert.lengthOf(events, 1);
const event = events[0];
assert.isDefined(event);
if (event.type !== "turn-item.updated" || event.payload.type !== "subagent") {
assert.fail("expected reused subagent turn-item.updated event");
return;
}
assert.equal(event.runId, runId);
assert.equal(event.payload.runId, spawnRunId);
assert.equal(event.payload.status, "interrupted");
assert.equal(event.payload.id, turnItem.id);
}),
);
it.effect("omits interrupt results and subagent cascade for a superseded attempt", () =>
Effect.gen(function* () {
const written = yield* captureInterruptTerminalTurnItems({
@@ -208,6 +208,17 @@ export function canReactivateSubagent(status: OrchestrationV2Subagent["status"])
return status !== "failed" && status !== "cancelled";
}
export function isRunOwnedSubagentTurnItem(input: {
readonly turnItem: OrchestrationV2TurnItem;
readonly runId: OrchestrationV2Run["id"];
readonly ownedSubagentIds: ReadonlySet<NodeId>;
}): boolean {
return (
input.turnItem.runId === input.runId ||
(input.turnItem.type === "subagent" && input.ownedSubagentIds.has(input.turnItem.subagentId))
);
}
function emptyOpenRunOwnedSubagentProjection(): OpenRunOwnedSubagentProjection {
return {
subagents: new Map(),
@@ -297,11 +308,7 @@ export function cascadeTerminalizeRunOwnedSubagents(input: {
});
}
const turnItem = input.open.turnItems.get(key);
if (
turnItem !== undefined &&
turnItem.runId === input.run.id &&
!isTerminalTurnItemStatus(turnItem.status)
) {
if (turnItem !== undefined && !isTerminalTurnItemStatus(turnItem.status)) {
events.push({
id: yield* input.allocateEventId(),
type: "turn-item.updated",
@@ -1131,7 +1138,11 @@ export const layer: Layer.Layer<
});
}
if (event.type === "turn_item.updated") {
const belongsToRootRun = event.turnItem.runId === input.run.id;
const belongsToRootRun = isRunOwnedSubagentTurnItem({
turnItem: event.turnItem,
runId: input.run.id,
ownedSubagentIds: routing.ownedSubagentIds,
});
const belongsToOwnedChildThread =
event.turnItem.threadId !== input.run.threadId &&
routing.ownedThreadIds.has(event.turnItem.threadId);