Fills in the data model added by the previous PR. Every adapter now reports what its subagents are actually doing: role provenance, token usage, recent activity, and per-activation records. Usage needs two merge strategies because providers report it differently. Codex sends cumulative snapshots per thread, so those merge by maximum — duplicate and late out-of-order frames then leave the total unchanged instead of inflating it. Claude reports per activation, so lifetime usage accumulates only the delta since the previous snapshot. A subagent identity is reusable, so completing an activation leaves it at "idle" rather than "completed"; the timeline row for that activation is still recorded as completed via the status mapping. A Codex subAgentActivity frame carries no model of its own, so agents registered from one were recorded with none at all — the common case for Codex-native subagents, which then showed a role and a token count but no model. They are recorded against the turn's model selection, which is what they actually run on. Three activation-lifecycle fixes in the Claude adapter, found in review: - A resume that raced past settle was pre-opened by the wake buffer, which erased the terminal status the reopen check reads. The resume then reused the finished activation instead of starting a new one, so its ordinal stopped matching reality and its usage was measured against the previous activation's totals — clamping the delta to zero and silently dropping the resumed run's tokens. The pre-open now records that it happened, and the reopen check honours it. - A replayed "waiting" frame could resurrect a settled subagent; only pending/running were guarded before. - A duplicate terminal frame re-stamped completedAt, drifting the recorded completion time. Codex already preserved it; Claude now matches. Reuse across runs is deliberately not addressed here — a subagent row still carries the run it was spawned under. That is the next PR.
530 lines
18 KiB
TypeScript
530 lines
18 KiB
TypeScript
import { assert, it, vi } from "@effect/vitest";
|
|
import {
|
|
MessageId,
|
|
NodeId,
|
|
ProviderDriverKind,
|
|
ProviderInstanceId,
|
|
ProviderSessionId,
|
|
ProviderThreadId,
|
|
ProviderTurnId,
|
|
RunAttemptId,
|
|
RunId,
|
|
RuntimeRequestId,
|
|
ThreadId,
|
|
TurnItemId,
|
|
type OrchestrationV2ThreadProjection,
|
|
} from "@t3tools/contracts";
|
|
import * as Effect from "effect/Effect";
|
|
import * as Layer from "effect/Layer";
|
|
import * as Ref from "effect/Ref";
|
|
|
|
import * as EffectWorker from "./EffectWorker.ts";
|
|
import * as EffectOutbox from "./EffectOutbox.ts";
|
|
import * as EventSink from "./EventSink.ts";
|
|
import * as IdAllocator from "./IdAllocator.ts";
|
|
import * as ProjectionStore from "./ProjectionStore.ts";
|
|
import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
|
|
|
|
it.effect("drains durable effects before reporting recovery complete", () =>
|
|
Effect.gen(function* () {
|
|
const runs = yield* Ref.make(0);
|
|
const layer = ProviderRuntimeRecovery.layer.pipe(
|
|
Layer.provide(
|
|
Layer.mergeAll(
|
|
Layer.mock(ProjectionStore.ProjectionStoreV2)({
|
|
getShellSnapshot: () =>
|
|
Effect.succeed({
|
|
schemaVersion: 2,
|
|
snapshotSequence: 0,
|
|
threads: [],
|
|
archivedThreads: [],
|
|
}),
|
|
}),
|
|
Layer.mock(EventSink.EventSinkV2)({}),
|
|
IdAllocator.layer,
|
|
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
|
|
runOnce: Ref.getAndUpdate(runs, (count) => count + 1).pipe(
|
|
Effect.map((count) => count < 2),
|
|
),
|
|
}),
|
|
Layer.mock(EffectOutbox.EffectOutboxV2)({
|
|
reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
const summary = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService.pipe(
|
|
Effect.flatMap((recovery) => recovery.recover),
|
|
Effect.provide(layer),
|
|
);
|
|
assert.deepEqual(summary, {
|
|
terminalizedRuns: 0,
|
|
stoppedSessions: 0,
|
|
closedRequests: 0,
|
|
retiredEffects: 0,
|
|
requeuedEffects: 0,
|
|
executedEffects: 2,
|
|
});
|
|
}),
|
|
);
|
|
|
|
it.effect("expires orphaned runtime requests before command readiness", () => {
|
|
const threadId = ThreadId.make("thread_recovery_requests");
|
|
let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
|
|
null;
|
|
const committed = vi.fn(
|
|
(input: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0]) => {
|
|
committedInput = input;
|
|
return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
|
|
},
|
|
);
|
|
const projection = {
|
|
thread: { id: threadId },
|
|
runtimeRequests: [
|
|
{
|
|
id: RuntimeRequestId.make("request_orphaned"),
|
|
nodeId: NodeId.make("node_orphaned"),
|
|
status: "pending",
|
|
responseCapability: { type: "not_resumable", reason: "old process" },
|
|
},
|
|
],
|
|
providerSessions: [],
|
|
providerThreads: [],
|
|
runs: [],
|
|
nodes: [],
|
|
} as unknown as OrchestrationV2ThreadProjection;
|
|
const layer = ProviderRuntimeRecovery.layer.pipe(
|
|
Layer.provide(
|
|
Layer.mergeAll(
|
|
Layer.mock(ProjectionStore.ProjectionStoreV2)({
|
|
getShellSnapshot: () =>
|
|
Effect.succeed({
|
|
schemaVersion: 2,
|
|
snapshotSequence: 0,
|
|
threads: [{ id: threadId }],
|
|
archivedThreads: [],
|
|
} as never),
|
|
getThreadProjection: () => Effect.succeed(projection),
|
|
}),
|
|
Layer.mock(EventSink.EventSinkV2)({ commitCommand: committed }),
|
|
IdAllocator.layer,
|
|
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
|
|
Layer.mock(EffectOutbox.EffectOutboxV2)({
|
|
reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
return Effect.gen(function* () {
|
|
yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).recover;
|
|
const command = committedInput;
|
|
assert.isNotNull(command);
|
|
if (command === null) return;
|
|
assert.equal(command?.events[0]?.type, "runtime-request.updated");
|
|
if (command?.events[0]?.type === "runtime-request.updated") {
|
|
assert.equal(command.events[0].payload.status, "expired");
|
|
assert.equal(command.events[0].payload.responseCapability.type, "not_resumable");
|
|
}
|
|
}).pipe(Effect.provide(layer));
|
|
});
|
|
|
|
it.effect("uses the same reconciliation path to cancel runtime requests during shutdown", () => {
|
|
const threadId = ThreadId.make("thread_shutdown_requests");
|
|
let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
|
|
null;
|
|
const projection = {
|
|
thread: { id: threadId },
|
|
runtimeRequests: [
|
|
{
|
|
id: RuntimeRequestId.make("request_shutdown"),
|
|
nodeId: NodeId.make("node_shutdown"),
|
|
status: "pending",
|
|
responseCapability: { type: "live" },
|
|
},
|
|
],
|
|
providerSessions: [],
|
|
providerThreads: [],
|
|
runs: [],
|
|
nodes: [],
|
|
} as unknown as OrchestrationV2ThreadProjection;
|
|
const layer = ProviderRuntimeRecovery.layer.pipe(
|
|
Layer.provide(
|
|
Layer.mergeAll(
|
|
Layer.mock(ProjectionStore.ProjectionStoreV2)({
|
|
getShellSnapshot: () =>
|
|
Effect.succeed({
|
|
schemaVersion: 2,
|
|
snapshotSequence: 0,
|
|
threads: [{ id: threadId }],
|
|
archivedThreads: [],
|
|
} as never),
|
|
getThreadProjection: () => Effect.succeed(projection),
|
|
}),
|
|
Layer.mock(EventSink.EventSinkV2)({
|
|
commitCommand: (input) => {
|
|
committedInput = input;
|
|
return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
|
|
},
|
|
}),
|
|
IdAllocator.layer,
|
|
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
|
|
Layer.mock(EffectOutbox.EffectOutboxV2)({
|
|
reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
|
|
return Effect.gen(function* () {
|
|
const summary =
|
|
yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("shutdown");
|
|
assert.equal(summary.closedRequests, 1);
|
|
assert.equal(summary.retiredEffects, 1);
|
|
const requestEvent = committedInput?.events[0];
|
|
assert.equal(requestEvent?.type, "runtime-request.updated");
|
|
if (requestEvent?.type === "runtime-request.updated") {
|
|
assert.equal(requestEvent.payload.status, "cancelled");
|
|
assert.equal(requestEvent.payload.responseCapability.type, "not_resumable");
|
|
if (requestEvent.payload.responseCapability.type === "not_resumable") {
|
|
assert.match(requestEvent.payload.responseCapability.reason, /shut down/);
|
|
}
|
|
}
|
|
}).pipe(Effect.provide(layer));
|
|
});
|
|
|
|
it.effect("preserves a waiting run while its replay-safe checkpoint capture is unsettled", () => {
|
|
const threadId = ThreadId.make("thread_waiting_checkpoint");
|
|
const runId = RunId.make("run_waiting_checkpoint");
|
|
const committed = vi.fn(() => Effect.succeed({ committed: true } as never));
|
|
const projection = {
|
|
thread: { id: threadId },
|
|
runtimeRequests: [],
|
|
providerSessions: [],
|
|
providerThreads: [],
|
|
runs: [{ id: runId, status: "waiting" }],
|
|
} as unknown as OrchestrationV2ThreadProjection;
|
|
const layer = ProviderRuntimeRecovery.layer.pipe(
|
|
Layer.provide(
|
|
Layer.mergeAll(
|
|
Layer.mock(ProjectionStore.ProjectionStoreV2)({
|
|
getShellSnapshot: () =>
|
|
Effect.succeed({
|
|
schemaVersion: 2,
|
|
snapshotSequence: 0,
|
|
threads: [{ id: threadId }],
|
|
archivedThreads: [],
|
|
} as never),
|
|
getThreadProjection: () => Effect.succeed(projection),
|
|
}),
|
|
Layer.mock(EventSink.EventSinkV2)({ commitCommand: committed }),
|
|
IdAllocator.layer,
|
|
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
|
|
Layer.mock(EffectOutbox.EffectOutboxV2)({
|
|
listByCommandId: () =>
|
|
Effect.succeed([
|
|
{
|
|
request: { type: "checkpoint.capture", runId },
|
|
status: "running",
|
|
},
|
|
] as never),
|
|
cancelUnsettled: () => Effect.succeed([]),
|
|
signalCancellations: () => Effect.void,
|
|
reconcileAfterProcessLoss: Effect.succeed({ requeued: 1, cancelled: 0 }),
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
|
|
return Effect.gen(function* () {
|
|
const summary =
|
|
yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
|
|
assert.equal(summary.terminalizedRuns, 0);
|
|
assert.equal(summary.requeuedEffects, 1);
|
|
assert.equal(committed.mock.calls.length, 0);
|
|
}).pipe(Effect.provide(layer));
|
|
});
|
|
|
|
it.effect("cancels a stale waiting run when no checkpoint capture can finish it", () => {
|
|
const threadId = ThreadId.make("thread_stale_waiting");
|
|
const runId = RunId.make("run_stale_waiting");
|
|
let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
|
|
null;
|
|
const projection = {
|
|
thread: { id: threadId },
|
|
runtimeRequests: [],
|
|
providerSessions: [],
|
|
providerThreads: [],
|
|
providerTurns: [],
|
|
runs: [
|
|
{
|
|
id: runId,
|
|
status: "waiting",
|
|
providerInstanceId: ProviderInstanceId.make("codex"),
|
|
},
|
|
],
|
|
attempts: [],
|
|
nodes: [],
|
|
subagents: [],
|
|
subagentActivations: [],
|
|
messages: [],
|
|
turnItems: [],
|
|
} as unknown as OrchestrationV2ThreadProjection;
|
|
const layer = ProviderRuntimeRecovery.layer.pipe(
|
|
Layer.provide(
|
|
Layer.mergeAll(
|
|
Layer.mock(ProjectionStore.ProjectionStoreV2)({
|
|
getShellSnapshot: () =>
|
|
Effect.succeed({
|
|
schemaVersion: 2,
|
|
snapshotSequence: 0,
|
|
threads: [{ id: threadId }],
|
|
archivedThreads: [],
|
|
} as never),
|
|
getThreadProjection: () => Effect.succeed(projection),
|
|
}),
|
|
Layer.mock(EventSink.EventSinkV2)({
|
|
commitCommand: (input) => {
|
|
committedInput = input;
|
|
return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
|
|
},
|
|
}),
|
|
IdAllocator.layer,
|
|
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
|
|
Layer.mock(EffectOutbox.EffectOutboxV2)({
|
|
listByCommandId: () => Effect.succeed([]),
|
|
reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
|
|
return Effect.gen(function* () {
|
|
const summary =
|
|
yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
|
|
assert.equal(summary.terminalizedRuns, 1);
|
|
const runEvent = committedInput?.events.find((event) => event.type === "run.updated");
|
|
assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.status : null, "cancelled");
|
|
}).pipe(Effect.provide(layer));
|
|
});
|
|
|
|
it.effect("cancels accepted queued work instead of replaying it after restart", () => {
|
|
const threadId = ThreadId.make("thread_queued_restart");
|
|
const runId = RunId.make("run_queued_restart");
|
|
const attemptId = RunAttemptId.make("attempt_queued_restart");
|
|
const rootNodeId = NodeId.make("node_queued_restart");
|
|
let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
|
|
null;
|
|
const projection = {
|
|
thread: { id: threadId },
|
|
runtimeRequests: [],
|
|
providerSessions: [],
|
|
providerThreads: [],
|
|
providerTurns: [],
|
|
runs: [
|
|
{
|
|
id: runId,
|
|
status: "queued",
|
|
queuePosition: 1,
|
|
providerInstanceId: ProviderInstanceId.make("codex"),
|
|
},
|
|
],
|
|
attempts: [
|
|
{
|
|
id: attemptId,
|
|
runId,
|
|
rootNodeId,
|
|
status: "pending",
|
|
},
|
|
],
|
|
nodes: [
|
|
{
|
|
id: rootNodeId,
|
|
runId,
|
|
status: "pending",
|
|
},
|
|
],
|
|
subagents: [],
|
|
subagentActivations: [],
|
|
messages: [],
|
|
turnItems: [],
|
|
} as unknown as OrchestrationV2ThreadProjection;
|
|
const layer = ProviderRuntimeRecovery.layer.pipe(
|
|
Layer.provide(
|
|
Layer.mergeAll(
|
|
Layer.mock(ProjectionStore.ProjectionStoreV2)({
|
|
getShellSnapshot: () =>
|
|
Effect.succeed({
|
|
schemaVersion: 2,
|
|
snapshotSequence: 0,
|
|
threads: [{ id: threadId }],
|
|
archivedThreads: [],
|
|
} as never),
|
|
getThreadProjection: () => Effect.succeed(projection),
|
|
}),
|
|
Layer.mock(EventSink.EventSinkV2)({
|
|
commitCommand: (input) => {
|
|
committedInput = input;
|
|
return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
|
|
},
|
|
}),
|
|
IdAllocator.layer,
|
|
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
|
|
Layer.mock(EffectOutbox.EffectOutboxV2)({
|
|
reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
|
|
return Effect.gen(function* () {
|
|
const summary =
|
|
yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
|
|
assert.equal(summary.terminalizedRuns, 1);
|
|
const command = committedInput;
|
|
assert.isNotNull(command);
|
|
if (command === null) return;
|
|
const runEvent = command.events.find((event) => event.type === "run.updated");
|
|
const attemptEvent = command.events.find((event) => event.type === "run-attempt.updated");
|
|
const nodeEvent = command.events.find((event) => event.type === "node.updated");
|
|
assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.status : null, "cancelled");
|
|
assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queuePosition : 1, null);
|
|
assert.equal(
|
|
attemptEvent?.type === "run-attempt.updated" ? attemptEvent.payload.status : null,
|
|
"cancelled",
|
|
);
|
|
assert.equal(nodeEvent?.type === "node.updated" ? nodeEvent.payload.status : null, "cancelled");
|
|
}).pipe(Effect.provide(layer));
|
|
});
|
|
|
|
it.effect(
|
|
"cancels the complete in-flight subtree and stops its persisted session without reopening it",
|
|
() => {
|
|
const threadId = ThreadId.make("thread_recovery_cancel");
|
|
const runId = RunId.make("run_recovery_cancel");
|
|
const attemptId = RunAttemptId.make("attempt_recovery_cancel");
|
|
const rootNodeId = NodeId.make("node_recovery_cancel");
|
|
const providerThreadId = ProviderThreadId.make("provider_thread_recovery_cancel");
|
|
const providerTurnId = ProviderTurnId.make("provider_turn_recovery_cancel");
|
|
const providerSessionId = ProviderSessionId.make("provider_session_recovery_cancel");
|
|
let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
|
|
null;
|
|
const projection = {
|
|
thread: { id: threadId },
|
|
runtimeRequests: [],
|
|
providerSessions: [
|
|
{
|
|
id: providerSessionId,
|
|
driver: ProviderDriverKind.make("codex"),
|
|
providerInstanceId: ProviderInstanceId.make("codex"),
|
|
status: "ready",
|
|
},
|
|
],
|
|
providerThreads: [
|
|
{
|
|
id: providerThreadId,
|
|
driver: ProviderDriverKind.make("codex"),
|
|
providerInstanceId: ProviderInstanceId.make("codex"),
|
|
status: "active",
|
|
},
|
|
],
|
|
providerTurns: [
|
|
{
|
|
id: providerTurnId,
|
|
runAttemptId: attemptId,
|
|
nodeId: rootNodeId,
|
|
status: "running",
|
|
},
|
|
],
|
|
runs: [
|
|
{
|
|
id: runId,
|
|
status: "starting",
|
|
providerThreadId,
|
|
providerInstanceId: ProviderInstanceId.make("codex"),
|
|
},
|
|
],
|
|
attempts: [
|
|
{
|
|
id: attemptId,
|
|
runId,
|
|
rootNodeId,
|
|
status: "running",
|
|
},
|
|
],
|
|
nodes: [{ id: rootNodeId, runId, status: "running" }],
|
|
subagents: [],
|
|
subagentActivations: [],
|
|
messages: [{ id: MessageId.make("message_recovery_cancel"), runId, streaming: true }],
|
|
turnItems: [
|
|
{
|
|
id: TurnItemId.make("turn_item_recovery_cancel"),
|
|
runId,
|
|
nodeId: rootNodeId,
|
|
status: "running",
|
|
},
|
|
],
|
|
} as unknown as OrchestrationV2ThreadProjection;
|
|
const layer = ProviderRuntimeRecovery.layer.pipe(
|
|
Layer.provide(
|
|
Layer.mergeAll(
|
|
Layer.mock(ProjectionStore.ProjectionStoreV2)({
|
|
getShellSnapshot: () =>
|
|
Effect.succeed({
|
|
schemaVersion: 2,
|
|
snapshotSequence: 0,
|
|
threads: [{ id: threadId }],
|
|
archivedThreads: [],
|
|
} as never),
|
|
getThreadProjection: () => Effect.succeed(projection),
|
|
}),
|
|
Layer.mock(EventSink.EventSinkV2)({
|
|
commitCommand: (input) => {
|
|
committedInput = input;
|
|
return Effect.succeed({ committed: true, cancelledEffectCount: 2 } as never);
|
|
},
|
|
}),
|
|
IdAllocator.layer,
|
|
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
|
|
Layer.mock(EffectOutbox.EffectOutboxV2)({
|
|
reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
|
|
return Effect.gen(function* () {
|
|
const summary = yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)
|
|
.recover;
|
|
assert.equal(summary.terminalizedRuns, 1);
|
|
assert.equal(summary.stoppedSessions, 1);
|
|
assert.equal(summary.retiredEffects, 2);
|
|
assert.deepEqual(committedInput?.cancelUnsettledEffects?.effectTypes, [
|
|
"provider-turn.start",
|
|
"provider-turn.interrupt",
|
|
"provider-turn.steer",
|
|
"provider-turn.restart",
|
|
"runtime-request.respond",
|
|
]);
|
|
const events = committedInput?.events ?? [];
|
|
assert.deepEqual(
|
|
events.map((event) => [
|
|
event.type,
|
|
"status" in event.payload ? event.payload.status : null,
|
|
]),
|
|
[
|
|
["run.updated", "cancelled"],
|
|
["run-attempt.updated", "cancelled"],
|
|
["node.updated", "cancelled"],
|
|
["provider-turn.updated", "cancelled"],
|
|
["message.updated", null],
|
|
["turn-item.updated", "cancelled"],
|
|
["provider-thread.updated", "idle"],
|
|
["provider-session.updated", "stopped"],
|
|
],
|
|
);
|
|
const messageEvent = events.find((event) => event.type === "message.updated");
|
|
assert.isFalse(messageEvent?.type === "message.updated" && messageEvent.payload.streaming);
|
|
}).pipe(Effect.provide(layer));
|
|
},
|
|
);
|