Integrate orchestration V2 controls and process recovery

- Add V2 item inspection, thread relationships, queued-run controls, and composer dispatch policies
- Reconcile interrupted provider state safely across shutdown and startup
- Preserve checkpoint baselines and shared provider-session projections
This commit is contained in:
Julius Marminge authored and Julius Marminge committed 2026-08-07 13:21:01 +02:00
1 parent 8f521e516e
commit 799e032fe9
46 files changed
+3661 -1038

No files matched your search

@@ -91,6 +91,11 @@ export const layer: Layer.Layer<
}
const capturedAt = yield* DateTime.now;
const baselineCheckpoint = projection.checkpoints.some(
(candidate) => candidate.scopeId === scope.id && candidate.ordinalWithinScope === 0,
)
? null
: yield* checkpoints.materializeBaselineCheckpoint({ scope });
const checkpoint = yield* checkpoints.capture({
scope,
runId: run.id,
@@ -107,6 +112,20 @@ export const layer: Layer.Layer<
acceptedAt: capturedAt,
effects: [],
events: [
...(baselineCheckpoint === null
? []
: [
{
id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
type: "checkpoint.captured" as const,
threadId: input.threadId,
nodeId: baselineCheckpoint.nodeId,
driver: providerThread.driver,
providerInstanceId: run.providerInstanceId,
occurredAt: capturedAt,
payload: baselineCheckpoint,
},
]),
{
id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
type: "checkpoint.captured",
@@ -131,6 +131,9 @@ export interface CheckpointServiceV2Shape {
readonly scope: OrchestrationV2CheckpointScope;
readonly ordinalWithinScope: number;
}) => Effect.Effect<void, CheckpointServiceV2Error>;
readonly materializeBaselineCheckpoint: (input: {
readonly scope: OrchestrationV2CheckpointScope;
}) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
readonly capture: (input: {
readonly scope: OrchestrationV2CheckpointScope;
readonly runId: RunId | null;
@@ -310,6 +313,51 @@ export const layer: Layer.Layer<
),
);
const materializeBaselineCheckpoint: CheckpointServiceV2Shape["materializeBaselineCheckpoint"] =
(input) =>
withWorkspaceLock(
input.scope.cwd,
Effect.gen(function* () {
const ordinalWithinScope = 0;
const checkpointRef = checkpointRefForScopeOrdinal({
scopeId: input.scope.id,
ordinalWithinScope,
});
const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
scopeId: input.scope.id,
ordinalWithinScope,
});
const checkpointable = yield* isGitCheckpointable(input.scope.cwd);
const available = checkpointable
? yield* checkpointStore.hasCheckpointRef({
cwd: input.scope.cwd,
checkpointRef,
})
: false;
return makeCheckpoint({
id: checkpointId,
scope: input.scope,
runId: null,
nodeId: input.scope.nodeId,
parentCheckpointId: null,
ordinalWithinScope,
appRunOrdinal: null,
ref: checkpointRef,
status: available ? "ready" : "missing",
files: [],
capturedAt: input.scope.createdAt,
});
}),
).pipe(
Effect.mapError(
(cause) =>
new CheckpointCaptureError({
scopeId: input.scope.id,
cause,
}),
),
);
const capture: CheckpointServiceV2Shape["capture"] = (input) =>
withWorkspaceLock(
input.scope.cwd,
@@ -319,7 +367,7 @@ export const layer: Layer.Layer<
ordinalWithinScope: input.ordinalWithinScope,
});
const parentCheckpointId =
input.ordinalWithinScope > 1
input.ordinalWithinScope > 0
? yield* checkpointIdForScopeOrdinal(idAllocator, {
scopeId: input.scope.id,
ordinalWithinScope: input.ordinalWithinScope - 1,
@@ -507,6 +555,7 @@ export const layer: Layer.Layer<
),
ensureScope,
captureBaseline,
materializeBaselineCheckpoint,
capture,
restore,
deleteStaleRefs,
@@ -81,11 +81,28 @@ export const OrchestrationEffectRequestV2 = Schema.Union([
]);
export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type;
export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [
"provider-session.detach",
"provider-thread.rollback",
"checkpoint.capture",
"terminal.cleanup",
"attachment.cleanup",
] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
export const PROCESS_BOUND_EFFECT_TYPES = [
"provider-turn.start",
"provider-turn.interrupt",
"provider-turn.steer",
"provider-turn.restart",
"runtime-request.respond",
] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
export const OrchestrationEffectStatusV2 = Schema.Literals([
"pending",
"running",
"succeeded",
"failed",
"cancelled",
]);
export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type;
@@ -138,7 +155,15 @@ export interface EffectOutboxV2Shape {
readonly listByCommandId: (
commandId: CommandId,
) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
readonly reclaimRunning: Effect.Effect<number, EffectOutboxError>;
readonly cancelUnsettled: (input: {
readonly threadId: ThreadId;
readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
readonly reason: string;
}) => Effect.Effect<number, EffectOutboxError>;
readonly reconcileAfterProcessLoss: Effect.Effect<
{ readonly requeued: number; readonly cancelled: number },
EffectOutboxError
>;
readonly claimNext: (input: {
readonly workerId: string;
readonly leaseDurationMs: number;
@@ -289,22 +314,65 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
: new EffectOutboxError({ operation: "list", cause }),
),
),
reclaimRunning: Effect.gen(function* () {
cancelUnsettled: ({ threadId, effectTypes, reason }) =>
Effect.gen(function* () {
if (effectTypes.length === 0) return 0;
const now = DateTime.formatIso(yield* DateTime.now);
const rows = yield* sql<{ readonly effect_id: string }>`
UPDATE orchestration_v2_effect_outbox
SET
status = 'cancelled',
lease_owner = NULL,
lease_expires_at = NULL,
completed_at = ${now},
updated_at = ${now},
last_error = ${reason}
WHERE thread_id = ${threadId}
AND status IN ('pending', 'running')
AND effect_type IN ${sql.in(effectTypes)}
RETURNING effect_id
`;
return rows.length;
}).pipe(
Effect.mapError(
(cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause }),
),
),
reconcileAfterProcessLoss: Effect.gen(function* () {
const now = DateTime.formatIso(yield* DateTime.now);
const rows = yield* sql<{ readonly effect_id: string }>`
const cancelledRows = yield* sql<{ readonly effect_id: string }>`
UPDATE orchestration_v2_effect_outbox
SET
status = 'cancelled',
lease_owner = NULL,
lease_expires_at = NULL,
completed_at = ${now},
updated_at = ${now},
last_error = 'Cancelled because the server process ended before the effect completed.'
WHERE status IN ('pending', 'running')
AND effect_type IN ${sql.in(PROCESS_BOUND_EFFECT_TYPES)}
RETURNING effect_id
`;
const requeuedRows = yield* sql<{ readonly effect_id: string }>`
UPDATE orchestration_v2_effect_outbox
SET
status = 'pending',
lease_owner = NULL,
lease_expires_at = NULL,
available_at = ${now},
updated_at = ${now}
updated_at = ${now},
last_error = 'Requeued after the previous server process ended.'
WHERE status = 'running'
AND effect_type IN ${sql.in(REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS)}
RETURNING effect_id
`;
if (rows.length > 0) yield* Queue.offer(available, undefined);
return rows.length;
}).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "reclaim", cause }))),
if (requeuedRows.length > 0) yield* Queue.offer(available, undefined);
return { requeued: requeuedRows.length, cancelled: cancelledRows.length };
}).pipe(
Effect.mapError(
(cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }),
),
),
claimNext: ({ workerId, leaseDurationMs }) =>
Effect.gen(function* () {
const now = yield* DateTime.now;
+15 -2
View File
@@ -21,6 +21,7 @@ import {
} from "./CommandReceiptStore.ts";
import {
EffectOutboxV2,
type OrchestrationEffectRequestV2,
type PendingOrchestrationEffectV2,
layer as effectOutboxLayer,
} from "./EffectOutbox.ts";
@@ -88,11 +89,16 @@ export interface EventSinkV2Shape {
readonly acceptedAt: DateTime.Utc;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
readonly effects: ReadonlyArray<PendingOrchestrationEffectV2>;
readonly cancelUnsettledEffects?: {
readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
readonly reason: string;
};
}) => Effect.Effect<
{
readonly receipt: CommandReceiptV2;
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
readonly committed: boolean;
readonly cancelledEffectCount: number;
},
EventSinkV2Error
>;
@@ -255,7 +261,7 @@ const baseLayer: Layer.Layer<
});
if (!reserved) {
const existing = yield* existingCommandResult(input.commandId);
return { ...existing, committed: false as const };
return { ...existing, committed: false as const, cancelledEffectCount: 0 };
}
const normalized = yield* normalizeEvents(input.events);
@@ -281,7 +287,14 @@ const baseLayer: Layer.Layer<
error: null,
};
yield* commandReceipts.upsert(receipt);
return { receipt, storedEvents, committed: true as const };
const cancelledEffectCount =
input.cancelUnsettledEffects === undefined
? 0
: yield* effectOutbox.cancelUnsettled({
threadId: input.threadId,
...input.cancelUnsettledEffects,
});
return { receipt, storedEvents, committed: true as const, cancelledEffectCount };
}),
);
if (input.effects.length > 0) {
@@ -13,6 +13,7 @@ import {
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ProviderSessionId,
ProviderThreadId,
RunId,
ThreadId,
@@ -28,6 +29,7 @@ import * as Stream from "effect/Stream";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
import { CommandReceiptStoreV2, layer as commandReceiptStoreLayer } from "./CommandReceiptStore.ts";
import { EffectOutboxV2, layer as effectOutboxLayer } from "./EffectOutbox.ts";
import {
@@ -37,11 +39,13 @@ import {
} from "./EffectWorker.ts";
import { EventSinkV2, layer as eventSinkLayer } from "./EventSink.ts";
import { EventStoreV2, layer as eventStoreLayer } from "./EventStore.ts";
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
import {
ProjectionMaintenanceV2,
layer as projectionMaintenanceLayer,
} from "./ProjectionMaintenance.ts";
import { ProjectionStoreV2, layer as projectionStoreLayer } from "./ProjectionStore.ts";
import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
const databaseLayer = SqlitePersistenceMemory;
const eventStoreProvided = eventStoreLayer.pipe(Layer.provideMerge(databaseLayer));
@@ -58,6 +62,7 @@ const TestLayer = Layer.mergeAll(
eventSinkProvided,
effectOutboxProvided,
commandReceiptStoreProvided,
idAllocatorLayer,
projectionMaintenanceProvided,
);
@@ -184,6 +189,71 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
}),
);
it.effect("replays shared provider-session payloads across every bound thread", () =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const projectionStore = yield* ProjectionStoreV2;
const maintenance = yield* ProjectionMaintenanceV2;
const now = yield* DateTime.now;
const firstThreadId = ThreadId.make("thread:foundation-shared-session:first");
const secondThreadId = ThreadId.make("thread:foundation-shared-session:second");
const providerSessionId = ProviderSessionId.make("provider-session:foundation:shared");
const firstSession = {
id: providerSessionId,
driver: providerDriver,
providerInstanceId,
status: "ready" as const,
cwd: "/workspace/first",
model: modelSelection.model,
capabilities: CodexProviderCapabilitiesV2,
createdAt: now,
updatedAt: now,
lastError: null,
};
const secondSession = { ...firstSession, cwd: "/workspace/second" };
yield* eventSink.write({
events: [
threadCreatedEvent({
id: "event:foundation-shared-session:first-thread",
thread: makeThread(firstThreadId, now),
now,
}),
{
id: EventId.make("event:foundation-shared-session:first-attachment"),
type: "provider-session.attached",
threadId: firstThreadId,
driver: providerDriver,
providerInstanceId,
occurredAt: now,
payload: firstSession,
},
threadCreatedEvent({
id: "event:foundation-shared-session:second-thread",
thread: makeThread(secondThreadId, now),
now,
}),
{
id: EventId.make("event:foundation-shared-session:second-attachment"),
type: "provider-session.attached",
threadId: secondThreadId,
driver: providerDriver,
providerInstanceId,
occurredAt: now,
payload: secondSession,
},
],
});
assert.equal(
(yield* projectionStore.getThreadProjection(firstThreadId)).providerSessions[0]?.cwd,
secondSession.cwd,
);
assert.isTrue((yield* maintenance.verify).valid);
assert.isTrue((yield* maintenance.rebuild).valid);
}),
);
it.effect(
"rolls back events, projections, receipts, and effects after a projection failure",
() =>
@@ -368,33 +438,140 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
}),
);
it.effect("reclaims running effects immediately during startup recovery", () =>
Effect.gen(function* () {
const outbox = yield* EffectOutboxV2;
const commandId = CommandId.make("command:foundation-reclaim-running");
yield* outbox.enqueue([
{
id: "effect:foundation-reclaim-running",
commandId,
threadId: ThreadId.make("thread:foundation-reclaim-running"),
request: {
type: "provider-turn.start",
runId: RunId.make("run:foundation-reclaim-running"),
it.effect(
"retires live provider effects and requeues replay-safe effects after process loss",
() =>
Effect.gen(function* () {
const outbox = yield* EffectOutboxV2;
const commandId = CommandId.make("command:foundation-reclaim-running");
yield* outbox.enqueue([
{
id: "effect:a-foundation-cancel-provider-turn",
commandId,
threadId: ThreadId.make("thread:foundation-reclaim-running"),
request: {
type: "provider-turn.start",
runId: RunId.make("run:foundation-reclaim-running"),
},
},
},
]);
{
id: "effect:b-foundation-requeue-cleanup",
commandId,
threadId: ThreadId.make("thread:foundation-reclaim-running"),
request: { type: "terminal.cleanup" },
},
]);
assert.isTrue(
Option.isSome(
yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }),
),
);
assert.isTrue(
Option.isSome(
yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }),
),
);
assert.deepEqual(yield* outbox.reconcileAfterProcessLoss, {
cancelled: 1,
requeued: 1,
});
const cancelled = yield* outbox.get("effect:a-foundation-cancel-provider-turn");
assert.isTrue(Option.isSome(cancelled));
if (Option.isSome(cancelled)) assert.equal(cancelled.value.status, "cancelled");
const reclaimed = yield* outbox.claimNext({
workerId: "recovery-worker",
leaseDurationMs: 30_000,
});
assert.isTrue(Option.isSome(reclaimed));
if (Option.isSome(reclaimed)) {
assert.equal(reclaimed.value.request.type, "terminal.cleanup");
assert.equal(reclaimed.value.attemptCount, 2);
}
}),
);
it.effect("atomically cancels stale runs and their process-bound effects", () =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const outbox = yield* EffectOutboxV2;
const projectionStore = yield* ProjectionStoreV2;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread:foundation-process-loss");
const runId = RunId.make("run:foundation-process-loss");
const commandId = CommandId.make("command:foundation-process-loss");
const thread = makeThread(threadId, now);
yield* eventSink.commitCommand({
commandId,
threadId,
commandType: "foundation.process-loss",
acceptedAt: now,
events: [
threadCreatedEvent({ id: "event:foundation-process-loss:thread", thread, now }),
{
id: EventId.make("event:foundation-process-loss:run"),
type: "run.created",
threadId,
runId,
providerInstanceId,
occurredAt: now,
payload: {
id: runId,
threadId,
ordinal: 1,
providerInstanceId,
modelSelection,
providerThreadId: null,
userMessageId: MessageId.make("message:foundation-process-loss"),
rootNodeId: null,
activeAttemptId: null,
status: "starting",
queuePosition: null,
requestedAt: now,
startedAt: null,
completedAt: null,
checkpointId: null,
contextHandoffId: null,
},
},
],
effects: [
{
id: "effect:foundation-process-loss",
commandId,
threadId,
request: { type: "provider-turn.start", runId },
},
],
});
assert.isTrue(
Option.isSome(
yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }),
),
);
assert.equal(yield* outbox.reclaimRunning, 1);
const reclaimed = yield* outbox.claimNext({
workerId: "recovery-worker",
leaseDurationMs: 30_000,
});
assert.isTrue(Option.isSome(reclaimed));
if (Option.isSome(reclaimed)) assert.equal(reclaimed.value.attemptCount, 2);
const recovery = yield* ProviderRuntimeRecovery.make.pipe(
Effect.provideService(
OrchestrationEffectWorkerV2,
OrchestrationEffectWorkerV2.of({
awaitWork: Effect.void,
runOnce: Effect.succeed(false),
drain: () => Effect.succeed(0),
}),
),
);
const first = yield* recovery.recover;
assert.equal(first.terminalizedRuns, 1);
assert.equal(first.retiredEffects, 1);
const projection = yield* projectionStore.getThreadProjection(threadId);
assert.equal(projection.runs[0]?.status, "cancelled");
const effect = yield* outbox.get("effect:foundation-process-loss");
assert.isTrue(Option.isSome(effect));
if (Option.isSome(effect)) assert.equal(effect.value.status, "cancelled");
const second = yield* recovery.recover;
assert.equal(second.terminalizedRuns, 0);
assert.equal(second.retiredEffects, 0);
}),
);
@@ -131,6 +131,7 @@ export interface OrchestratorV2DispatchResult {
}
export interface OrchestratorV2Shape {
readonly resumeQueuedRuns: Effect.Effect<number, OrchestratorV2Error>;
readonly dispatch: (
command: OrchestrationV2Command,
) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;
@@ -637,6 +638,41 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
yield* effectWorker.drain(1);
});
const resumeQueuedRuns = Effect.gen(function* () {
const shell = yield* projectionStore.getShellSnapshot();
let resumed = 0;
for (const thread of shell.threads) {
const resumedThread = yield* Effect.gen(function* () {
const projection = yield* projectionStore.getThreadProjection(thread.id);
if (projection.runs.some(isBlockingRun) || nextQueuedRun(projection) === undefined) {
return false;
}
yield* dispatchSemaphore.withPermit(startNextQueuedRun(thread.id));
return true;
}).pipe(
Effect.catch((cause) =>
Effect.logWarning("Failed to resume queued V2 run after recovery", {
threadId: thread.id,
cause,
}).pipe(Effect.as(false)),
),
);
if (resumedThread) {
resumed += 1;
}
}
return resumed;
}).pipe(
Effect.mapError(
(cause) =>
new OrchestratorDispatchError({
commandId: CommandId.make("command:system:resume-queued-runs"),
commandType: "message.dispatch",
cause,
}),
),
);
const dispatchThreadCreate = Effect.fn("orchestrationV2.dispatch.threadCreate")(function* (
command: Extract<OrchestrationV2Command, { readonly type: "thread.create" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
@@ -4340,6 +4376,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
Stream.filter(
(stored) =>
stored.event.type === "run.updated" &&
!String(stored.commandId).startsWith("command:runtime-reconcile:") &&
(stored.event.payload.status === "completed" ||
stored.event.payload.status === "interrupted" ||
stored.event.payload.status === "failed" ||
@@ -4359,6 +4396,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
);
return OrchestratorV2.of({
resumeQueuedRuns,
dispatch: dispatchWithReceipt,
getThreadProjection: (threadId) =>
projectionStore
@@ -4432,6 +4470,13 @@ export const layer: Layer.Layer<
export const layerUnavailable: Layer.Layer<OrchestratorV2> = Layer.succeed(
OrchestratorV2,
OrchestratorV2.of({
resumeQueuedRuns: Effect.fail(
new OrchestratorDispatchError({
commandId: CommandId.make("command:system:resume-queued-runs"),
commandType: "message.dispatch",
cause: "Orchestration V2 live runtime is not configured.",
}),
),
dispatch: (command) =>
Effect.fail(
new OrchestratorDispatchError({
@@ -13,8 +13,8 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
import { EventStoreV2 } from "./EventStore.ts";
import {
applyToProjection,
emptyProjection,
applyToProjectionReplayState,
makeProjectionReplayState,
ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
ProjectionStoreV2,
} from "./ProjectionStore.ts";
@@ -121,19 +121,11 @@ export const layer: Layer.Layer<
});
const expectedProjections = (events: ReadonlyArray<OrchestrationV2StoredEvent>) => {
const projections = new Map<ThreadId, OrchestrationV2ThreadProjection>();
const state = makeProjectionReplayState();
for (const stored of events) {
const event = stored.event;
if (event.type === "thread.created") {
projections.set(event.threadId, emptyProjection(event));
continue;
}
const current = projections.get(event.threadId);
if (current !== undefined) {
projections.set(event.threadId, applyToProjection(current, event));
}
applyToProjectionReplayState(state, stored.event);
}
return projections;
return state.projections;
};
const verify = Effect.gen(function* () {
@@ -7,6 +7,7 @@ import type {
OrchestrationV2ThreadShell,
OrchestrationV2ThreadProjection,
OrchestrationV2TurnItem,
ProviderSessionId,
} from "@t3tools/contracts";
import {
OrchestrationV2AppThreadJson as OrchestrationV2AppThreadJsonSchema,
@@ -283,6 +284,98 @@ export function applyToProjection(
}
}
/**
* Replay state for entities whose persisted projection is shared across thread bindings.
*
* Provider sessions are process-scoped: one session row can be bound to several app
* threads. Updating that row changes what every bound thread reads, even though the
* application event itself belongs to one thread stream. Keeping the binding index here
* makes in-memory replay match the normalized SQL projection without scanning every
* thread for every session event.
*/
export interface ProjectionReplayState {
readonly projections: Map<ThreadId, OrchestrationV2ThreadProjection>;
readonly providerSessionThreadIds: Map<ProviderSessionId, ReadonlySet<ThreadId>>;
}
export function makeProjectionReplayState(): ProjectionReplayState {
return {
projections: new Map(),
providerSessionThreadIds: new Map(),
};
}
export function applyToProjectionReplayState(
state: ProjectionReplayState,
event: OrchestrationV2DomainEvent,
): boolean {
if (event.type === "thread.created" && !state.projections.has(event.threadId)) {
state.projections.set(event.threadId, emptyProjection(event));
return true;
}
const current = state.projections.get(event.threadId);
if (current === undefined) {
return false;
}
let next = applyToProjection(current, event);
if (event.type === "provider-session.updated") {
const boundThreadIds = state.providerSessionThreadIds.get(event.payload.id);
if (boundThreadIds?.has(event.threadId) !== true) {
// The SQL projection updates the global session row but does not implicitly
// create a thread binding for an update event.
next = { ...next, providerSessions: current.providerSessions };
}
}
state.projections.set(event.threadId, next);
switch (event.type) {
case "provider-session.attached": {
const boundThreadIds = new Set(state.providerSessionThreadIds.get(event.payload.id) ?? []);
boundThreadIds.add(event.threadId);
state.providerSessionThreadIds.set(event.payload.id, boundThreadIds);
for (const threadId of boundThreadIds) {
if (threadId === event.threadId) continue;
const projection = state.projections.get(threadId);
if (projection === undefined) continue;
state.projections.set(threadId, {
...projection,
providerSessions: upsertById(projection.providerSessions, event.payload),
});
}
break;
}
case "provider-session.updated": {
const boundThreadIds = state.providerSessionThreadIds.get(event.payload.id) ?? [];
for (const threadId of boundThreadIds) {
if (threadId === event.threadId) continue;
const projection = state.projections.get(threadId);
if (projection === undefined) continue;
state.projections.set(threadId, {
...projection,
providerSessions: upsertById(projection.providerSessions, event.payload),
});
}
break;
}
case "provider-session.detached": {
const boundThreadIds = new Set(
state.providerSessionThreadIds.get(event.payload.providerSessionId) ?? [],
);
boundThreadIds.delete(event.threadId);
if (boundThreadIds.size === 0) {
state.providerSessionThreadIds.delete(event.payload.providerSessionId);
} else {
state.providerSessionThreadIds.set(event.payload.providerSessionId, boundThreadIds);
}
break;
}
}
return true;
}
type PayloadRow = {
readonly payload_json: string;
};
@@ -2110,29 +2203,23 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
ProjectionStoreV2,
Effect.gen(function* () {
const projections = yield* Ref.make(new Map<ThreadId, OrchestrationV2ThreadProjection>());
const replayState = yield* Ref.make(makeProjectionReplayState());
const sequence = yield* Ref.make(0);
const service: ProjectionStoreV2Shape = {
apply: (event) =>
Effect.gen(function* () {
const result = yield* Ref.modify(projections, (existing) => {
const next = new Map(existing);
if (event.type === "thread.created" && !next.has(event.threadId)) {
next.set(event.threadId, emptyProjection(event));
return [undefined, next] as const;
}
const projection = next.get(event.threadId);
if (!projection) {
const result = yield* Ref.modify(replayState, (existing) => {
const next: ProjectionReplayState = {
projections: new Map(existing.projections),
providerSessionThreadIds: new Map(existing.providerSessionThreadIds),
};
if (!applyToProjectionReplayState(next, event)) {
return [
new ProjectionStoreThreadNotFoundError({ threadId: event.threadId }),
existing,
] as const;
}
next.set(event.threadId, applyToProjection(projection, event));
return [undefined, next] as const;
});
@@ -2143,7 +2230,7 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
}),
getShellSnapshot: () =>
Effect.gen(function* () {
const existing = yield* Ref.get(projections);
const existing = (yield* Ref.get(replayState)).projections;
const shells = yield* Effect.forEach(
[...existing.keys()].toSorted((left, right) =>
String(left).localeCompare(String(right)),
@@ -2161,7 +2248,7 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
}),
getThreadProjection: (threadId) =>
Effect.gen(function* () {
const existing = yield* Ref.get(projections);
const existing = (yield* Ref.get(replayState)).projections;
const readProjection = (
targetThreadId: ThreadId,
seenThreadIds: ReadonlySet<ThreadId>,
@@ -1,8 +1,17 @@
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";
@@ -15,157 +24,6 @@ import * as EventSink from "./EventSink.ts";
import * as IdAllocator from "./IdAllocator.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
const { decideProviderRuntimeRecovery } = ProviderRuntimeRecovery;
it("retries process and transport failures only within the idempotent retry budget", () => {
assert.deepEqual(
decideProviderRuntimeRecovery({
kind: "process_exited",
attempt: 1,
maxAttempts: 3,
idempotent: true,
online: true,
}),
{ type: "retry_now" },
);
assert.equal(
decideProviderRuntimeRecovery({
kind: "transport_unavailable",
attempt: 3,
maxAttempts: 3,
idempotent: true,
online: true,
}).type,
"terminalize",
);
});
it("waits for connectivity and requires retry-after for rate limits", () => {
assert.deepEqual(
decideProviderRuntimeRecovery({
kind: "network_unavailable",
attempt: 0,
maxAttempts: 3,
idempotent: true,
online: false,
}),
{ type: "wait_for_connectivity" },
);
assert.deepEqual(
decideProviderRuntimeRecovery({
kind: "provider_rate_limited",
attempt: 0,
maxAttempts: 3,
idempotent: true,
retryAfterMs: 250,
online: true,
}),
{ type: "retry_after", delayMs: 250 },
);
});
it("terminalizes non-recoverable provider failures", () => {
for (const kind of [
"provider_quota_exceeded",
"auth_invalid",
"permission_denied",
"invalid_request",
"unsupported_model",
] as const) {
assert.equal(
decideProviderRuntimeRecovery({
kind,
attempt: 0,
maxAttempts: 3,
idempotent: true,
online: true,
}).type,
"terminalize",
);
}
});
it("classifies wrapped provider failures without provider-name checks", () => {
assert.deepEqual(
ProviderRuntimeRecovery.classifyProviderRuntimeFailure({
_tag: "ProviderSessionOpenError",
cause: { code: "rate_limit_exceeded", retryAfterMs: 125 },
}),
{ kind: "provider_rate_limited", retryAfterMs: 125 },
);
assert.deepEqual(
ProviderRuntimeRecovery.classifyProviderRuntimeFailure({
cause: { status: 401, message: "authentication failed" },
}),
{ kind: "auth_invalid" },
);
});
it.effect("executes bounded transport retries and returns the resumed value", () =>
Effect.gen(function* () {
const attempts = yield* Ref.make(0);
const value = yield* ProviderRuntimeRecovery.recoverWithPolicy({
operation: Ref.getAndUpdate(attempts, (count) => count + 1).pipe(
Effect.flatMap((count) =>
count < 2 ? Effect.fail("transport down") : Effect.succeed("resumed"),
),
),
classify: () => ({ kind: "transport_unavailable" }),
connectivity: { isOnline: Effect.succeed(true), awaitOnline: Effect.void },
maxAttempts: 3,
idempotent: true,
});
assert.equal(value, "resumed");
assert.equal(yield* Ref.get(attempts), 3);
}),
);
it.effect("waits for connectivity before retrying a network failure", () =>
Effect.gen(function* () {
const attempts = yield* Ref.make(0);
const online = yield* Ref.make(false);
const waits = yield* Ref.make(0);
const value = yield* ProviderRuntimeRecovery.recoverWithPolicy({
operation: Ref.getAndUpdate(attempts, (count) => count + 1).pipe(
Effect.flatMap((count) =>
count === 0 ? Effect.fail("offline") : Effect.succeed("resumed"),
),
),
classify: () => ({ kind: "network_unavailable" }),
connectivity: {
isOnline: Ref.get(online),
awaitOnline: Ref.set(online, true).pipe(
Effect.andThen(Ref.update(waits, (count) => count + 1)),
),
},
maxAttempts: 3,
idempotent: true,
});
assert.equal(value, "resumed");
assert.equal(yield* Ref.get(waits), 1);
}),
);
it.effect("does not retry unrecoverable failures", () =>
Effect.gen(function* () {
const attempts = yield* Ref.make(0);
const result = yield* Effect.result(
ProviderRuntimeRecovery.recoverWithPolicy({
operation: Ref.update(attempts, (count) => count + 1).pipe(
Effect.andThen(Effect.fail("invalid credentials")),
),
classify: () => ({ kind: "auth_invalid" }),
connectivity: { isOnline: Effect.succeed(true), awaitOnline: Effect.void },
maxAttempts: 3,
idempotent: true,
}),
);
assert.equal(result._tag, "Failure");
assert.equal(yield* Ref.get(attempts), 1);
}),
);
it.effect("drains durable effects before reporting recovery complete", () =>
Effect.gen(function* () {
@@ -182,7 +40,6 @@ it.effect("drains durable effects before reporting recovery complete", () =>
archivedThreads: [],
}),
}),
Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
Layer.mock(EventSink.EventSinkV2)({}),
IdAllocator.layer,
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
@@ -190,15 +47,24 @@ it.effect("drains durable effects before reporting recovery complete", () =>
Effect.map((count) => count < 2),
),
}),
Layer.mock(EffectOutbox.EffectOutboxV2)({ reclaimRunning: Effect.succeed(0) }),
Layer.mock(EffectOutbox.EffectOutboxV2)({
reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
}),
),
),
);
const summary = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService.pipe(
Effect.flatMap((service) => service.recover),
Effect.flatMap((recovery) => recovery.recover),
Effect.provide(layer),
);
assert.deepEqual(summary, { resumedSessions: 0, terminalizedRuns: 0, executedEffects: 2 });
assert.deepEqual(summary, {
terminalizedRuns: 0,
stoppedSessions: 0,
closedRequests: 0,
retiredEffects: 0,
requeuedEffects: 0,
executedEffects: 2,
});
}),
);
@@ -209,7 +75,7 @@ it.effect("expires orphaned runtime requests before command readiness", () => {
const committed = vi.fn(
(input: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0]) => {
committedInput = input;
return Effect.succeed({ committed: true } as never);
return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
},
);
const projection = {
@@ -223,6 +89,7 @@ it.effect("expires orphaned runtime requests before command readiness", () => {
},
],
providerSessions: [],
providerThreads: [],
runs: [],
nodes: [],
} as unknown as OrchestrationV2ThreadProjection;
@@ -239,11 +106,12 @@ it.effect("expires orphaned runtime requests before command readiness", () => {
} as never),
getThreadProjection: () => Effect.succeed(projection),
}),
Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
Layer.mock(EventSink.EventSinkV2)({ commitCommand: committed }),
IdAllocator.layer,
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
Layer.mock(EffectOutbox.EffectOutboxV2)({ reclaimRunning: Effect.succeed(0) }),
Layer.mock(EffectOutbox.EffectOutboxV2)({
reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
}),
),
),
);
@@ -259,3 +127,311 @@ it.effect("expires orphaned runtime requests before command readiness", () => {
}
}).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(0),
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: [],
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 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: [],
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));
},
);
@@ -6,7 +6,6 @@ import {
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
@@ -16,17 +15,11 @@ 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 ProviderSessionManager from "./ProviderSessionManager.ts";
export class ProviderRuntimeRecoveryError extends Schema.TaggedErrorClass<ProviderRuntimeRecoveryError>()(
"ProviderRuntimeRecoveryError",
{
operation: Schema.Literals([
"read-projections",
"resume-session",
"terminalize",
"drain-outbox",
]),
operation: Schema.Literals(["read-projections", "reconcile", "drain-outbox"]),
threadId: Schema.optional(ThreadId),
cause: Schema.Defect(),
},
@@ -37,209 +30,33 @@ export class ProviderRuntimeRecoveryError extends Schema.TaggedErrorClass<Provid
}
export interface ProviderRuntimeRecoverySummary {
readonly resumedSessions: number;
readonly terminalizedRuns: number;
readonly stoppedSessions: number;
readonly closedRequests: number;
readonly retiredEffects: number;
readonly requeuedEffects: number;
readonly executedEffects: number;
}
export const ProviderRuntimeFailureKind = Schema.Literals([
"process_exited",
"transport_unavailable",
"network_unavailable",
"provider_rate_limited",
"provider_quota_exceeded",
"auth_invalid",
"permission_denied",
"invalid_request",
"unsupported_model",
]);
export type ProviderRuntimeFailureKind = typeof ProviderRuntimeFailureKind.Type;
export type ProviderRuntimeRecoveryDecision =
| { readonly type: "retry_now" }
| { readonly type: "retry_after"; readonly delayMs: number }
| { readonly type: "wait_for_connectivity" }
| { readonly type: "terminalize"; readonly reason: string };
export function decideProviderRuntimeRecovery(input: {
readonly kind: ProviderRuntimeFailureKind;
readonly attempt: number;
readonly maxAttempts: number;
readonly idempotent: boolean;
readonly retryAfterMs?: number;
readonly online: boolean;
}): ProviderRuntimeRecoveryDecision {
if (input.attempt >= input.maxAttempts) {
return { type: "terminalize", reason: "Provider recovery retry budget was exhausted." };
}
switch (input.kind) {
case "process_exited":
case "transport_unavailable":
return input.idempotent
? { type: "retry_now" }
: { type: "terminalize", reason: "The interrupted operation is not idempotent." };
case "network_unavailable":
return input.online ? { type: "retry_now" } : { type: "wait_for_connectivity" };
case "provider_rate_limited":
return input.idempotent && input.retryAfterMs !== undefined
? { type: "retry_after", delayMs: Math.max(0, input.retryAfterMs) }
: {
type: "terminalize",
reason: "Rate-limit recovery requires retry-after and an idempotent operation.",
};
case "provider_quota_exceeded":
case "auth_invalid":
case "permission_denied":
case "invalid_request":
case "unsupported_model":
return { type: "terminalize", reason: `Provider failure ${input.kind} is not recoverable.` };
}
}
export interface ConnectivityServiceShape {
readonly isOnline: Effect.Effect<boolean>;
readonly awaitOnline: Effect.Effect<void>;
}
export class ConnectivityService extends Context.Reference<ConnectivityServiceShape>(
"t3/orchestration-v2/ConnectivityService",
{
defaultValue: () => ({ isOnline: Effect.succeed(true), awaitOnline: Effect.void }),
},
) {}
export interface ClassifiedProviderRuntimeFailure {
readonly kind: ProviderRuntimeFailureKind;
readonly retryAfterMs?: number;
}
export function classifyProviderRuntimeFailure(cause: unknown): ClassifiedProviderRuntimeFailure {
const record =
cause !== null && typeof cause === "object"
? (cause as Record<string, unknown>)
: ({} as Record<string, unknown>);
const serialized = (() => {
try {
return JSON.stringify(cause);
} catch {
return "";
}
})();
const description = [
record._tag,
record.code,
record.status,
record.message,
record.detail,
serialized,
]
.filter((value) => typeof value === "string" || typeof value === "number")
.join(" ")
.toLowerCase();
const nestedCause =
record.cause !== null && typeof record.cause === "object"
? (record.cause as Record<string, unknown>)
: undefined;
const retryAfter =
record.retryAfterMs ??
record.retry_after_ms ??
nestedCause?.retryAfterMs ??
nestedCause?.retry_after_ms;
const retryAfterMs = typeof retryAfter === "number" ? retryAfter : undefined;
if (description.includes("rate") && description.includes("limit")) {
return {
kind: "provider_rate_limited",
...(retryAfterMs === undefined ? {} : { retryAfterMs }),
};
}
if (description.includes("quota")) return { kind: "provider_quota_exceeded" };
if (description.includes("auth") || description.includes("unauthorized")) {
return { kind: "auth_invalid" };
}
if (description.includes("permission") || description.includes("forbidden")) {
return { kind: "permission_denied" };
}
if (description.includes("unsupported") && description.includes("model")) {
return { kind: "unsupported_model" };
}
if (description.includes("invalid") && description.includes("request")) {
return { kind: "invalid_request" };
}
if (
description.includes("network") ||
description.includes("offline") ||
description.includes("econnreset") ||
description.includes("enotfound")
) {
return { kind: "network_unavailable" };
}
if (description.includes("exit") || description.includes("terminated")) {
return { kind: "process_exited" };
}
return { kind: "transport_unavailable" };
}
export class ProviderRuntimeFailureClassifier extends Context.Reference<{
readonly classify: (cause: unknown) => ClassifiedProviderRuntimeFailure;
}>("t3/orchestration-v2/ProviderRuntimeFailureClassifier", {
defaultValue: () => ({ classify: classifyProviderRuntimeFailure }),
}) {}
export class ProviderRuntimeRecoveryPolicy extends Context.Reference<{
readonly maxAttempts: number;
}>("t3/orchestration-v2/ProviderRuntimeRecoveryPolicy", {
defaultValue: () => ({ maxAttempts: 3 }),
}) {}
export function recoverWithPolicy<A, E>(input: {
readonly operation: Effect.Effect<A, E>;
readonly classify: (cause: E) => ClassifiedProviderRuntimeFailure;
readonly connectivity: ConnectivityServiceShape;
readonly maxAttempts: number;
readonly idempotent: boolean;
}): Effect.Effect<A, E> {
const attempt = (attemptNumber: number): Effect.Effect<A, E> =>
input.operation.pipe(
Effect.catch((cause) =>
Effect.gen(function* () {
const classified = input.classify(cause);
const online = yield* input.connectivity.isOnline;
const decision = decideProviderRuntimeRecovery({
kind: classified.kind,
attempt: attemptNumber,
maxAttempts: input.maxAttempts,
idempotent: input.idempotent,
online,
...(classified.retryAfterMs === undefined
? {}
: { retryAfterMs: classified.retryAfterMs }),
});
switch (decision.type) {
case "retry_now":
return yield* attempt(attemptNumber + 1);
case "retry_after":
yield* Effect.sleep(Duration.millis(decision.delayMs));
return yield* attempt(attemptNumber + 1);
case "wait_for_connectivity":
yield* input.connectivity.awaitOnline;
return yield* attempt(attemptNumber + 1);
case "terminalize":
return yield* Effect.fail(cause);
}
}),
),
);
return attempt(1);
export interface ProviderRuntimeReconciliationSummary {
readonly terminalizedRuns: number;
readonly stoppedSessions: number;
readonly closedRequests: number;
readonly retiredEffects: number;
readonly requeuedEffects: number;
}
export class ProviderRuntimeRecoveryService extends Context.Service<
ProviderRuntimeRecoveryService,
{
readonly reconcile: (
trigger: "startup" | "shutdown",
) => Effect.Effect<ProviderRuntimeReconciliationSummary, ProviderRuntimeRecoveryError>;
readonly recover: Effect.Effect<ProviderRuntimeRecoverySummary, ProviderRuntimeRecoveryError>;
}
>()("t3/orchestration-v2/ProviderRuntimeRecoveryService") {}
function activeRuns(projection: OrchestrationV2ThreadProjection) {
function nonterminalRuns(projection: OrchestrationV2ThreadProjection) {
return projection.runs.filter(
(run) => run.status === "starting" || run.status === "running" || run.status === "waiting",
);
@@ -247,249 +64,317 @@ function activeRuns(projection: OrchestrationV2ThreadProjection) {
export const make = Effect.gen(function* () {
const projections = yield* ProjectionStore.ProjectionStoreV2;
const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
const eventSink = yield* EventSink.EventSinkV2;
const ids = yield* IdAllocator.IdAllocatorV2;
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
const outbox = yield* EffectOutbox.EffectOutboxV2;
const connectivity = yield* ConnectivityService;
const classifier = yield* ProviderRuntimeFailureClassifier;
const recoveryPolicy = yield* ProviderRuntimeRecoveryPolicy;
const terminalize = Effect.fn("ProviderRuntimeRecoveryService.terminalize")(function* (
projection: OrchestrationV2ThreadProjection,
detail: string,
) {
const now = yield* DateTime.now;
const runs = activeRuns(projection);
if (runs.length === 0) return 0;
const commandId = CommandId.make(`command:recovery:terminalize:${projection.thread.id}`);
const allocateEventId = () =>
ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
Effect.mapError(
(cause) =>
new ProviderRuntimeRecoveryError({
operation: "terminalize",
threadId: projection.thread.id,
cause,
}),
),
);
const events: Array<OrchestrationV2DomainEvent> = [];
for (const run of runs) {
events.push({
id: yield* allocateEventId(),
type: "run.updated",
threadId: projection.thread.id,
runId: run.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...run, status: "failed", completedAt: now },
});
for (const node of projection.nodes.filter(
(candidate) =>
candidate.runId === run.id &&
(candidate.status === "pending" ||
candidate.status === "running" ||
candidate.status === "waiting"),
)) {
events.push({
id: yield* allocateEventId(),
type: "node.updated",
threadId: projection.thread.id,
runId: run.id,
nodeId: node.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...node, status: "failed", completedAt: now },
});
}
}
yield* eventSink
.commitCommand({
commandId,
threadId: projection.thread.id,
commandType: "provider-runtime.recovery-terminalize",
acceptedAt: now,
events,
effects: [],
})
.pipe(
Effect.mapError(
(cause) =>
new ProviderRuntimeRecoveryError({
operation: "terminalize",
threadId: projection.thread.id,
cause: { detail, cause },
}),
),
);
return runs.length;
});
const expireOrphanedRequests = Effect.fn("ProviderRuntimeRecoveryService.expireOrphanedRequests")(
function* (projection: OrchestrationV2ThreadProjection) {
const requests = projection.runtimeRequests.filter((request) => request.status === "pending");
if (requests.length === 0) return;
const reconcileProjection = Effect.fn("ProviderRuntimeRecoveryService.reconcileProjection")(
function* (projection: OrchestrationV2ThreadProjection, trigger: "startup" | "shutdown") {
const now = yield* DateTime.now;
const commandId = CommandId.make(`command:recovery:expire-requests:${projection.thread.id}`);
const runs = [] as Array<OrchestrationV2ThreadProjection["runs"][number]>;
for (const run of nonterminalRuns(projection)) {
if (run.status === "waiting") {
const checkpointEffects = yield* outbox
.listByCommandId(CommandId.make(`command:effect:checkpoint.capture:${run.id}`))
.pipe(
Effect.mapError(
(cause) =>
new ProviderRuntimeRecoveryError({
operation: "reconcile",
threadId: projection.thread.id,
cause,
}),
),
);
const hasReplayableCheckpoint = checkpointEffects.some(
(effect) =>
effect.request.type === "checkpoint.capture" &&
effect.request.runId === run.id &&
(effect.status === "pending" || effect.status === "running"),
);
if (hasReplayableCheckpoint) continue;
}
runs.push(run);
}
const requests = projection.runtimeRequests.filter((request) => request.status === "pending");
const detail = `Cancelled because the server ${trigger === "startup" ? "restarted" : "shut down"} before the provider work completed.`;
const commandId = CommandId.make(
`command:runtime-reconcile:${trigger}:${projection.thread.id}:${DateTime.formatIso(now)}`,
);
const allocateEventId = () =>
ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
Effect.mapError(
(cause) =>
new ProviderRuntimeRecoveryError({
operation: "reconcile",
threadId: projection.thread.id,
cause,
}),
),
);
const events: Array<OrchestrationV2DomainEvent> = [];
for (const request of requests) {
events.push({
id: yield* ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
Effect.mapError(
(cause) =>
new ProviderRuntimeRecoveryError({
operation: "terminalize",
threadId: projection.thread.id,
cause,
}),
),
),
id: yield* allocateEventId(),
type: "runtime-request.updated",
threadId: projection.thread.id,
nodeId: request.nodeId,
occurredAt: now,
payload: {
...request,
status: "expired",
status: trigger === "startup" ? "expired" : "cancelled",
responseCapability: {
type: "not_resumable",
reason: "The server restarted before this runtime request was resolved.",
reason: `The server ${trigger === "startup" ? "restarted" : "shut down"} before this runtime request was resolved.`,
},
resolvedAt: now,
},
});
}
yield* eventSink
.commitCommand({
commandId,
for (const run of runs) {
events.push({
id: yield* allocateEventId(),
type: "run.updated",
threadId: projection.thread.id,
commandType: "provider-runtime.expire-orphaned-requests",
acceptedAt: now,
events,
effects: [],
})
runId: run.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
});
for (const attempt of projection.attempts.filter(
(candidate) =>
candidate.runId === run.id &&
(candidate.status === "pending" || candidate.status === "running"),
)) {
events.push({
id: yield* allocateEventId(),
type: "run-attempt.updated",
threadId: projection.thread.id,
runId: run.id,
nodeId: attempt.rootNodeId,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...attempt, status: "cancelled", completedAt: now },
});
}
for (const node of projection.nodes.filter(
(candidate) =>
candidate.runId === run.id &&
(candidate.status === "pending" ||
candidate.status === "running" ||
candidate.status === "waiting"),
)) {
events.push({
id: yield* allocateEventId(),
type: "node.updated",
threadId: projection.thread.id,
runId: run.id,
nodeId: node.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...node, status: "cancelled", completedAt: now },
});
}
for (const subagent of projection.subagents.filter(
(candidate) =>
candidate.runId === run.id &&
(candidate.status === "pending" ||
candidate.status === "running" ||
candidate.status === "waiting"),
)) {
events.push({
id: yield* allocateEventId(),
type: "subagent.updated",
threadId: projection.thread.id,
runId: run.id,
nodeId: subagent.id,
driver: subagent.driver,
providerInstanceId: subagent.providerInstanceId,
occurredAt: now,
payload: { ...subagent, status: "cancelled", completedAt: now, updatedAt: now },
});
}
for (const providerTurn of projection.providerTurns.filter(
(candidate) =>
candidate.runAttemptId !== null &&
projection.attempts.some(
(attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id,
) &&
(candidate.status === "pending" || candidate.status === "running"),
)) {
events.push({
id: yield* allocateEventId(),
type: "provider-turn.updated",
threadId: projection.thread.id,
runId: run.id,
nodeId: providerTurn.nodeId,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...providerTurn, status: "cancelled", completedAt: now },
});
}
for (const message of projection.messages.filter(
(candidate) => candidate.runId === run.id && candidate.streaming,
)) {
events.push({
id: yield* allocateEventId(),
type: "message.updated",
threadId: projection.thread.id,
runId: run.id,
...(message.nodeId === null ? {} : { nodeId: message.nodeId }),
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...message, streaming: false, updatedAt: now },
});
}
for (const item of projection.turnItems.filter(
(candidate) =>
candidate.runId === run.id &&
(candidate.status === "pending" ||
candidate.status === "running" ||
candidate.status === "waiting"),
)) {
events.push({
id: yield* allocateEventId(),
type: "turn-item.updated",
threadId: projection.thread.id,
runId: run.id,
...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
});
}
}
for (const providerThread of projection.providerThreads.filter(
(candidate) => candidate.status === "active",
)) {
events.push({
id: yield* allocateEventId(),
type: "provider-thread.updated",
threadId: projection.thread.id,
driver: providerThread.driver,
providerInstanceId: providerThread.providerInstanceId,
occurredAt: now,
payload: { ...providerThread, status: "idle", updatedAt: now },
});
}
for (const session of projection.providerSessions.filter(
(candidate) => candidate.status !== "stopped" && candidate.status !== "error",
)) {
events.push({
id: yield* allocateEventId(),
type: "provider-session.updated",
threadId: projection.thread.id,
driver: session.driver,
providerInstanceId: session.providerInstanceId,
occurredAt: now,
payload: { ...session, status: "stopped", updatedAt: now, lastError: null },
});
}
const stoppedSessions = projection.providerSessions.filter(
(candidate) => candidate.status !== "stopped" && candidate.status !== "error",
).length;
let retiredEffects: number;
if (events.length === 0) {
retiredEffects = yield* outbox
.cancelUnsettled({
threadId: projection.thread.id,
effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
reason: detail,
})
.pipe(
Effect.mapError(
(cause) =>
new ProviderRuntimeRecoveryError({
operation: "reconcile",
threadId: projection.thread.id,
cause: { detail, cause },
}),
),
);
} else {
const result = yield* eventSink
.commitCommand({
commandId,
threadId: projection.thread.id,
commandType: "provider-runtime.reconcile",
acceptedAt: now,
events,
effects: [],
cancelUnsettledEffects: {
effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
reason: detail,
},
})
.pipe(
Effect.mapError(
(cause) =>
new ProviderRuntimeRecoveryError({
operation: "reconcile",
threadId: projection.thread.id,
cause,
}),
),
);
retiredEffects = result.cancelledEffectCount;
}
return {
terminalizedRuns: runs.length,
stoppedSessions,
closedRequests: requests.length,
retiredEffects,
};
},
);
const reconcile = (trigger: "startup" | "shutdown") =>
Effect.gen(function* () {
const shell = yield* projections
.getShellSnapshot()
.pipe(
Effect.mapError(
(cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
),
);
let terminalizedRuns = 0;
let stoppedSessions = 0;
let closedRequests = 0;
let retiredEffects = 0;
for (const thread of [...shell.threads, ...shell.archivedThreads]) {
const projection = yield* projections.getThreadProjection(thread.id).pipe(
Effect.mapError(
(cause) =>
new ProviderRuntimeRecoveryError({
operation: "terminalize",
threadId: projection.thread.id,
operation: "read-projections",
threadId: thread.id,
cause,
}),
),
);
},
);
const recoverProjection = Effect.fn("ProviderRuntimeRecoveryService.recoverProjection")(
function* (projection: OrchestrationV2ThreadProjection) {
yield* expireOrphanedRequests(projection);
let resumedSessions = 0;
for (const session of projection.providerSessions.filter(
(candidate) => candidate.status !== "stopped" && candidate.status !== "error",
)) {
const resume = sessions
.open({
threadId: projection.thread.id,
providerSessionId: session.id,
modelSelection: projection.thread.modelSelection,
runtimePolicy: {
runtimeMode: projection.thread.runtimeMode,
interactionMode: projection.thread.interactionMode,
cwd: session.cwd,
},
resumeFromSession: session,
})
.pipe(
Effect.flatMap((runtime) =>
Effect.forEach(
projection.providerThreads.filter(
(providerThread) =>
providerThread.providerSessionId === session.id &&
providerThread.appThreadId === projection.thread.id &&
providerThread.status !== "closed" &&
providerThread.status !== "archived",
),
(providerThread) =>
runtime.resumeThread({
providerThread,
threadId: projection.thread.id,
modelSelection: projection.thread.modelSelection,
runtimePolicy: {
runtimeMode: projection.thread.runtimeMode,
interactionMode: projection.thread.interactionMode,
cwd: session.cwd,
},
}),
{ discard: true },
),
),
);
const recovered = yield* Effect.result(
recoverWithPolicy({
operation: resume,
classify: classifier.classify,
connectivity,
maxAttempts: recoveryPolicy.maxAttempts,
idempotent: true,
}),
);
if (recovered._tag === "Failure") {
const terminalizedRuns = yield* terminalize(
projection,
`Unable to resume provider session ${session.id}.`,
);
return { resumedSessions, terminalizedRuns };
}
resumedSessions += 1;
const result = yield* reconcileProjection(projection, trigger);
terminalizedRuns += result.terminalizedRuns;
stoppedSessions += result.stoppedSessions;
closedRequests += result.closedRequests;
retiredEffects += result.retiredEffects;
}
if (
resumedSessions === 0 &&
projection.runs.some((run) => run.status === "running" || run.status === "waiting")
) {
const terminalizedRuns = yield* terminalize(
projection,
"No resumable provider session remained for the active run.",
);
return { resumedSessions, terminalizedRuns };
}
return { resumedSessions, terminalizedRuns: 0 };
},
);
const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
Effect.mapError(
(cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
),
);
return {
terminalizedRuns,
stoppedSessions,
closedRequests,
retiredEffects: retiredEffects + outboxReconciliation.cancelled,
requeuedEffects: outboxReconciliation.requeued,
} satisfies ProviderRuntimeReconciliationSummary;
});
const recover = Effect.gen(function* () {
const shell = yield* projections
.getShellSnapshot()
.pipe(
Effect.mapError(
(cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
),
);
let resumedSessions = 0;
let terminalizedRuns = 0;
for (const thread of shell.threads) {
const projection = yield* projections.getThreadProjection(thread.id).pipe(
Effect.mapError(
(cause) =>
new ProviderRuntimeRecoveryError({
operation: "read-projections",
threadId: thread.id,
cause,
}),
),
);
const result = yield* recoverProjection(projection);
resumedSessions += result.resumedSessions;
terminalizedRuns += result.terminalizedRuns;
}
const reconciliation = yield* reconcile("startup");
let executedEffects = 0;
yield* outbox.reclaimRunning.pipe(
Effect.mapError(
(cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
),
);
while (
yield* worker.runOnce.pipe(
Effect.mapError(
@@ -499,10 +384,10 @@ export const make = Effect.gen(function* () {
) {
executedEffects += 1;
}
return { resumedSessions, terminalizedRuns, executedEffects };
return { ...reconciliation, executedEffects } satisfies ProviderRuntimeRecoverySummary;
});
return ProviderRuntimeRecoveryService.of({ recover });
return ProviderRuntimeRecoveryService.of({ reconcile, recover });
});
export const layer = Layer.effect(ProviderRuntimeRecoveryService, make);
@@ -509,6 +509,48 @@ it.effect("ProviderSessionManagerV2 releases live sessions when its layer shuts
}),
);
it.effect("ProviderSessionManagerV2 closes event subscriptions normally on server shutdown", () =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
const effect = Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const idAllocator = yield* IdAllocatorV2;
const manager = yield* ProviderSessionManagerV2;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-shutdown-subscription");
const providerSessionId = yield* idAllocator.allocate.providerSession({
providerInstanceId: modelSelection.instanceId,
threadId,
});
yield* eventSink.write({
events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
});
const runtime = yield* manager.open({
threadId,
providerSessionId,
modelSelection,
runtimePolicy,
});
const bufferedSubscription = yield* runtime.subscribeEvents!;
const activeSubscription = yield* runtime.subscribeEvents!;
const adapterQueue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId));
assert.isDefined(adapterQueue);
yield* Queue.offer(adapterQueue!, {
type: "provider_session.updated",
driver: CODEX_DRIVER,
providerSession: runtime.providerSession,
});
assert.isTrue(Option.isSome(yield* activeSubscription.events.pipe(Stream.runHead)));
yield* manager.shutdown;
assert.isEmpty(yield* bufferedSubscription.events.pipe(Stream.runCollect));
});
yield* effect.pipe(Effect.provide(makeTestLayer({ state, idleTimeoutMs: 60_000 })));
}),
);
it.effect(
"ProviderSessionManagerV2 issues MCP credentials before opening and revokes them on close",
() =>
@@ -53,17 +53,9 @@ export type ProviderSessionReleaseReason = typeof ProviderSessionReleaseReason.T
* ProviderSessionManager owns live session residency: open sessions, idle release,
* explicit shutdown, and release-on-runtime-failure.
*
* It intentionally does not decide whether a provider failure should be retried.
* The next recovery layer should classify adapter failures into canonical runtime
* failure kinds before attempting recovery:
*
* - process_exited / transport_unavailable: bounded restart + native thread resume.
* - network_unavailable: wait for ConnectivityService to report online, then resume.
* - provider_rate_limited: retry only when retry-after/idempotency/retry budget allow it.
* - provider_quota_exceeded / auth_invalid / permission_denied / invalid_request:
* terminal until user or configuration changes.
*
* This keeps lifecycle cleanup separate from policy-driven recovery.
* It intentionally does not resurrect persisted sessions. Process-loss recovery
* terminalizes provider-bound work and retires non-replayable effects; a later
* user command or durable replay-safe operation opens a session lazily.
*/
export class ProviderSessionOpenError extends Schema.TaggedErrorClass<ProviderSessionOpenError>()(
"ProviderSessionOpenError",
@@ -137,6 +129,7 @@ export const ProviderSessionManagerV2Error = Schema.Union([
export type ProviderSessionManagerV2Error = typeof ProviderSessionManagerV2Error.Type;
export interface ProviderSessionManagerV2Shape {
readonly shutdown: Effect.Effect<void>;
readonly open: (input: {
readonly threadId: ThreadId;
readonly providerSessionId: ProviderSessionId;
@@ -173,7 +166,9 @@ interface LiveSessionEntry {
readonly supportsMultipleProviderThreads: boolean;
readonly runtime: ProviderAdapterV2SessionRuntime;
readonly exposedRuntime: ProviderAdapterV2SessionRuntime;
readonly eventSubscribers: Ref.Ref<ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal>>>;
readonly eventSubscribers: Ref.Ref<
ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
>;
readonly scope: Scope.Closeable;
readonly idleGeneration: number;
readonly busyCount: number;
@@ -276,7 +271,9 @@ export const layerWithOptions = (
);
const publishToSubscribers = (
subscribers: Ref.Ref<ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal>>>,
subscribers: Ref.Ref<
ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
>,
signal: ProviderSessionEventSignal,
) =>
Ref.get(subscribers).pipe(
@@ -294,11 +291,26 @@ export const layerWithOptions = (
providerSessionId: entry.runtime.providerSessionId,
cause: detail,
});
yield* publishToSubscribers(entry.eventSubscribers, {
type: "failure",
cause: Cause.fail(error),
});
yield* Ref.set(entry.eventSubscribers, new Map());
const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
yield* Effect.forEach(
subscribers.values(),
(queue) =>
Queue.offer(queue, {
type: "failure",
cause: Cause.fail(error),
}),
{ discard: true },
);
});
const closeSubscribers = (entry: LiveSessionEntry) =>
Effect.gen(function* () {
const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
yield* Effect.forEach(
subscribers.values(),
(queue) => Queue.clear(queue).pipe(Effect.andThen(Queue.end(queue))),
{ discard: true },
);
});
const cancelIdleFiber = (fiber: Fiber.Fiber<void, never> | null) =>
@@ -479,10 +491,14 @@ export const layerWithOptions = (
if (input.cancelIdleFiber !== false) {
yield* cancelIdleFiber(entry.idleFiber);
}
yield* failSubscribers(
entry,
input.detail ?? `Provider session released: ${input.reason}.`,
);
if (input.reason === "server_shutdown") {
yield* closeSubscribers(entry);
} else {
yield* failSubscribers(
entry,
input.detail ?? `Provider session released: ${input.reason}.`,
);
}
const closeExit = yield* Effect.exit(Scope.close(entry.scope, Exit.void));
yield* writeReleasedSessionEvents({
entry,
@@ -779,10 +795,12 @@ export const layerWithOptions = (
);
const makeEventSubscription = (
subscribers: Ref.Ref<ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal>>>,
subscribers: Ref.Ref<
ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
>,
): Effect.Effect<ProviderAdapterV2EventSubscription> =>
Effect.gen(function* () {
const queue = yield* Queue.unbounded<ProviderSessionEventSignal>();
const queue = yield* Queue.unbounded<ProviderSessionEventSignal, Cause.Done>();
const subscriberId = yield* Ref.getAndUpdate(nextSubscriberId, (value) => value + 1);
yield* Ref.update(subscribers, (current) => {
const updated = new Map(current);
@@ -796,7 +814,13 @@ export const layerWithOptions = (
const updated = new Map(current);
updated.delete(subscriberId);
return [true, updated] as const;
}).pipe(Effect.flatMap((removed) => (removed ? Queue.shutdown(queue) : Effect.void)));
}).pipe(
Effect.flatMap((removed) =>
removed
? Queue.clear(queue).pipe(Effect.andThen(Queue.end(queue)), Effect.asVoid)
: Effect.void,
),
);
const events = Stream.fromQueue(queue).pipe(
Stream.mapEffect((signal) =>
signal.type === "event"
@@ -810,7 +834,9 @@ export const layerWithOptions = (
const decorateRuntime = (
runtime: ProviderAdapterV2SessionRuntime,
eventSubscribers: Ref.Ref<ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal>>>,
eventSubscribers: Ref.Ref<
ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
>,
): ProviderAdapterV2SessionRuntime => {
const providerSessionId = runtime.providerSessionId;
const subscribeEvents = makeEventSubscription(eventSubscribers);
@@ -1021,29 +1047,29 @@ export const layerWithOptions = (
Effect.forkIn(layerScope),
);
yield* Effect.addFinalizer(() =>
Effect.gen(function* () {
const activeSessions = [...(yield* Ref.get(sessions)).values()];
yield* Effect.forEach(
activeSessions,
(entry) =>
releaseEntry({
providerSessionId: entry.runtime.providerSessionId,
reason: "server_shutdown",
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("orchestration-v2.driver-session.shutdown-release-failed", {
providerSessionId: entry.runtime.providerSessionId,
cause,
}),
),
const shutdown = Effect.gen(function* () {
const activeSessions = [...(yield* Ref.get(sessions)).values()];
yield* Effect.forEach(
activeSessions,
(entry) =>
releaseEntry({
providerSessionId: entry.runtime.providerSessionId,
reason: "server_shutdown",
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("orchestration-v2.driver-session.shutdown-release-failed", {
providerSessionId: entry.runtime.providerSessionId,
cause,
}),
),
{ discard: true },
);
}),
);
),
{ discard: true },
);
});
yield* Effect.addFinalizer(() => shutdown);
return ProviderSessionManagerV2.of({
shutdown,
open: (input) =>
openSemaphore.withPermit(
Effect.gen(function* () {
@@ -1109,7 +1135,7 @@ export const layerWithOptions = (
),
);
const eventSubscribers = yield* Ref.make<
ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal>>
ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
>(new Map());
const exposedRuntime = decorateRuntime(runtime, eventSubscribers);
const now = yield* Clock.currentTimeMillis;
@@ -403,11 +403,13 @@ export const layer: Layer.Layer<
) + 1,
shouldFinalizeRun: () =>
projectionStore.getThreadProjection(projection.thread.id).pipe(
Effect.map(
(current) =>
current.runs.find((candidate) => candidate.id === run.id)?.activeAttemptId ===
attempt.id,
),
Effect.map((current) => {
const currentRun = current.runs.find((candidate) => candidate.id === run.id);
return (
currentRun?.activeAttemptId === attempt.id &&
(currentRun.status === "starting" || currentRun.status === "running")
);
}),
Effect.catchCause(() => Effect.succeed(false)),
),
message: {
@@ -178,7 +178,6 @@ const providerRuntimeRecoveryProvided = providerRuntimeRecoveryLayer.pipe(
eventSinkProvided,
idAllocatorLayer,
projectionStoreLayer,
providerSessionManagerProvided,
),
),
);
@@ -229,6 +228,7 @@ export const OrchestrationV2LayerLive = Layer.mergeAll(
orchestratorProvided,
threadManagementProvided,
effectWorkerProvided,
providerSessionManagerProvided,
providerRuntimeRecoveryProvided,
projectionMaintenanceProvided,
);
@@ -96,6 +96,16 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* <
assert.isDefined(projection);
const latestRun = projection.runs.at(-1);
assert.deepEqual(latestRun?.modelSelection, input.driver.modelSelection);
if (projection.runs.some((run) => run.status === "completed")) {
const threadStartCheckpoint = projection.checkpoints.find(
(checkpoint) => checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null,
);
assert.isDefined(
threadStartCheckpoint,
"completed threads must retain an addressable thread-start checkpoint",
);
assert.equal(threadStartCheckpoint.status, "ready");
}
return result;
});
+3 -9
View File
@@ -56,6 +56,7 @@ import Migration035V2 from "./Migrations/035_OrchestrationV2Foundation.ts";
import Migration036V2 from "./Migrations/036_OrchestrationV2ProviderSessionBindings.ts";
import Migration037V2 from "./Migrations/037_OrchestrationV2ThreadLaunchWorkflows.ts";
import Migration038V2 from "./Migrations/038_ApplicationEventSource.ts";
import Migration039V2 from "./Migrations/039_OrchestrationV2EffectCancellation.ts";
/**
* Migration loader with all migrations defined inline.
@@ -104,21 +105,14 @@ export const migrationEntries = [
[34, "ProjectionThreadsSnoozed", Migration0034],
[35, "ProjectionThreadTitleRegeneration", Migration0035],
[36, "ProjectionThreadsPinned", Migration0036],
<<<<<<< HEAD
[37, "ProjectionTurnsKeysetIndex", Migration0037],
[38, "OrchestrationV2", Migration033V2],
[39, "OrchestrationV2Subagents", Migration034V2],
[40, "OrchestrationV2Foundation", Migration035V2],
[41, "OrchestrationV2ProviderSessionBindings", Migration036V2],
[42, "OrchestrationV2ThreadLaunchWorkflows", Migration037V2],
=======
[37, "OrchestrationV2", Migration0026V2],
[38, "OrchestrationV2Subagents", Migration0034V2],
[39, "OrchestrationV2Foundation", Migration0035V2],
[40, "OrchestrationV2ProviderSessionBindings", Migration036V2],
[41, "OrchestrationV2ThreadLaunchWorkflows", Migration037V2],
[42, "ApplicationEventSource", Migration038V2],
>>>>>>> 56f9a4b262 (Integrate orchestration v2 with the application runtime)
[43, "ApplicationEventSource", Migration038V2],
[44, "OrchestrationV2EffectCancellation", Migration039V2],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,80 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("039_OrchestrationV2EffectCancellation", (it) => {
it.effect("preserves existing effects and adds the cancelled terminal status", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 38 });
yield* sql`
INSERT INTO orchestration_v2_effect_outbox (
effect_id,
command_id,
thread_id,
effect_type,
payload_json,
status,
attempt_count,
available_at,
lease_owner,
lease_expires_at,
created_at,
updated_at,
completed_at,
last_error
) VALUES (
'effect:existing',
'command:existing',
'thread:existing',
'provider-turn.start',
'{"type":"provider-turn.start","runId":"run:existing"}',
'running',
1,
'2026-06-20T00:00:00.000Z',
'worker:old',
'2026-06-20T00:00:30.000Z',
'2026-06-20T00:00:00.000Z',
'2026-06-20T00:00:00.000Z',
NULL,
NULL
)
`;
yield* runMigrations({ toMigrationInclusive: 39 });
yield* sql`
UPDATE orchestration_v2_effect_outbox
SET
status = 'cancelled',
lease_owner = NULL,
lease_expires_at = NULL,
completed_at = '2026-06-20T00:01:00.000Z'
WHERE effect_id = 'effect:existing'
`;
const rows = yield* sql<{
readonly effect_id: string;
readonly status: string;
readonly attempt_count: number;
readonly lease_owner: string | null;
}>`
SELECT effect_id, status, attempt_count, lease_owner
FROM orchestration_v2_effect_outbox
`;
assert.deepStrictEqual(rows, [
{
effect_id: "effect:existing",
status: "cancelled",
attempt_count: 1,
lease_owner: null,
},
]);
}),
);
});
@@ -0,0 +1,78 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE TABLE orchestration_v2_effect_outbox_next (
effect_id TEXT PRIMARY KEY,
command_id TEXT NOT NULL,
thread_id TEXT NOT NULL,
effect_type TEXT NOT NULL,
payload_json TEXT NOT NULL,
status TEXT NOT NULL CHECK (
status IN ('pending', 'running', 'succeeded', 'failed', 'cancelled')
),
attempt_count INTEGER NOT NULL DEFAULT 0,
available_at TEXT NOT NULL,
lease_owner TEXT,
lease_expires_at TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
completed_at TEXT,
last_error TEXT
)
`;
yield* sql`
INSERT INTO orchestration_v2_effect_outbox_next (
effect_id,
command_id,
thread_id,
effect_type,
payload_json,
status,
attempt_count,
available_at,
lease_owner,
lease_expires_at,
created_at,
updated_at,
completed_at,
last_error
)
SELECT
effect_id,
command_id,
thread_id,
effect_type,
payload_json,
status,
attempt_count,
available_at,
lease_owner,
lease_expires_at,
created_at,
updated_at,
completed_at,
last_error
FROM orchestration_v2_effect_outbox
`;
yield* sql`DROP TABLE orchestration_v2_effect_outbox`;
yield* sql`
ALTER TABLE orchestration_v2_effect_outbox_next
RENAME TO orchestration_v2_effect_outbox
`;
yield* sql`
CREATE INDEX orchestration_v2_effect_outbox_claim_idx
ON orchestration_v2_effect_outbox(status, available_at, lease_expires_at, created_at)
`;
yield* sql`
CREATE INDEX orchestration_v2_effect_outbox_command_idx
ON orchestration_v2_effect_outbox(command_id, effect_id)
`;
yield* sql`
CREATE INDEX orchestration_v2_effect_outbox_thread_status_idx
ON orchestration_v2_effect_outbox(thread_id, status, effect_type)
`;
});
+2 -2
View File
@@ -21,7 +21,7 @@ it.effect("runs projection repair, recovery, worker startup, and bootstrap in or
const result = yield* ServerRuntimeStartup.runOrderedV2StartupPhases({
verify: record("verify").pipe(Effect.as({ valid: false })),
rebuild: record("rebuild").pipe(Effect.as({ valid: true })),
recover: record("recover").pipe(Effect.as({ resumedSessions: 2 })),
recover: record("recover").pipe(Effect.as({ closedRequests: 2 })),
startEffectWorker: record("worker"),
autoBootstrap: record("bootstrap").pipe(Effect.as({ projectId: "project-1" })),
});
@@ -34,7 +34,7 @@ it.effect("runs projection repair, recovery, worker startup, and bootstrap in or
"bootstrap",
]);
assert.deepEqual(result, {
recovery: { resumedSessions: 2 },
recovery: { closedRequests: 2 },
bootstrap: { projectId: "project-1" },
});
}),
+54 -67
View File
@@ -8,12 +8,14 @@ import {
ThreadId,
} from "@t3tools/contracts";
import * as Console from "effect/Console";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
@@ -24,8 +26,10 @@ import * as ServerConfig from "./config.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import * as EffectWorker from "./orchestration-v2/EffectWorker.ts";
import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts";
import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts";
import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
import * as ProjectService from "./project/ProjectService.ts";
@@ -325,7 +329,9 @@ export const make = Effect.gen(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
const keybindings = yield* Keybindings.Keybindings;
const projectionMaintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
const orchestrator = yield* Orchestrator.OrchestratorV2;
const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
const serverSettings = yield* ServerSettings.ServerSettingsService;
@@ -334,6 +340,33 @@ export const make = Effect.gen(function* () {
const commandGate = yield* makeCommandGate;
const httpListening = yield* Deferred.make<void>();
const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
yield* Effect.addFinalizer(() =>
Effect.gen(function* () {
yield* commandGate.failCommandReady(
new ServerRuntimeStartupError({
mode: serverConfig.mode,
host: serverConfig.host ?? null,
port: serverConfig.port,
cause: "Server runtime is shutting down.",
}),
);
const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
if (workerFiber !== null) {
yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
}
yield* providerSessions.shutdown;
const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
cause: Cause.pretty(cause),
}),
),
),
);
yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
@@ -382,8 +415,13 @@ export const make = Effect.gen(function* () {
startEffectWorker: runStartupPhase(
"orchestration-v2.effect-worker.start",
Effect.gen(function* () {
yield* EffectWorker.runDaemon.pipe(Effect.forkScoped);
const workerFiber = yield* EffectWorker.runDaemon.pipe(Effect.forkScoped);
yield* Ref.set(effectWorkerFiber, workerFiber);
yield* agentAwarenessRelay.start();
const resumedQueuedRuns = yield* orchestrator.resumeQueuedRuns;
if (resumedQueuedRuns > 0) {
yield* Effect.logInfo("V2 queued runs resumed", { resumedQueuedRuns });
}
}),
),
autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
@@ -427,72 +465,21 @@ export const make = Effect.gen(function* () {
Effect.withSpan("server.startup", { kind: "server", root: true }),
);
yield* Effect.logDebug("startup phase: starting server settings runtime");
yield* runStartupPhase(
"settings.start",
serverSettings.start.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to start server settings runtime", {
path: error.settingsPath,
operation: error.operation,
providerInstanceId: error.providerInstanceId,
environmentVariable: error.environmentVariable,
cause: error.cause,
}),
),
),
);
yield* Effect.logDebug("startup phase: parking orchestration roots at activation");
yield* runStartupPhase(
"reactors.start",
Effect.gen(function* () {
yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));
}),
);
const welcomeBase = yield* resolveWelcomeBase;
const environment = yield* serverEnvironment.getDescriptor;
yield* Effect.logDebug("startup phase: preparing welcome payload");
if (serverConfig.autoBootstrapProjectFromCwd) {
yield* forkParked(
runStartupPhase(
"welcome.autobootstrap",
Effect.gen(function* () {
const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets.pipe(
Effect.provideService(Crypto.Crypto, crypto),
);
if (!bootstrapTargets.bootstrapProjectId && !bootstrapTargets.bootstrapThreadId) {
return;
}
yield* Effect.logDebug("startup phase: publishing bootstrapped welcome event", {
environmentId: environment.environmentId,
cwd: welcomeBase.cwd,
projectName: welcomeBase.projectName,
bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
});
yield* lifecycleEvents.publish({
version: 1,
type: "welcome",
payload: {
environment,
...welcomeBase,
...bootstrapTargets,
},
});
}).pipe(
Effect.catch((cause) =>
Effect.logWarning("startup auto-bootstrap welcome failed", {
cause,
}),
),
),
),
);
yield* Effect.forkScoped(
Effect.gen(function* () {
const startupExit = yield* Effect.exit(startup);
if (Exit.isFailure(startupExit)) {
const error = new ServerRuntimeStartupError({
mode: serverConfig.mode,
host: serverConfig.host ?? null,
port: serverConfig.port,
cause: startupExit.cause,
});
yield* Effect.logError("server runtime startup failed", {
cause: Cause.pretty(startupExit.cause),
});
yield* commandGate.failCommandReady(error);
return;
}
yield* Effect.logDebug("startup phase: waiting for http listener");