Files
t3code/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
T
+36 de34391427 feat(orchestrator): introduce new orchestrator (#2829)
Co-authored-by: maria-rcks <[email protected]>
Co-authored-by: Bilal Bakr <[email protected]>
Co-authored-by: shivam <[email protected]>
Co-authored-by: Vitalii Yehorov <[email protected]>
Co-authored-by: Jake Leventhal <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Alex Southwell <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Nicholas Wasmiller <[email protected]>
Co-authored-by: PB <[email protected]>
Co-authored-by: Exotic <[email protected]>
Co-authored-by: Yash Singh <[email protected]>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Theo Browne <[email protected]>
Co-authored-by: Gabriel De Andrade <[email protected]>
Co-authored-by: Dara Adedeji <[email protected]>
Co-authored-by: scratchyone <[email protected]>
Co-authored-by: Dominic Roy <[email protected]>
Co-authored-by: chukfinley <[email protected]>
Co-authored-by: Primož Ajdišek <[email protected]>
Co-authored-by: benthecarman <[email protected]>
Co-authored-by: NaveDanan <[email protected]>
Co-authored-by: aaditagrawal <[email protected]>
Co-authored-by: Aditya Garud <[email protected]>
Co-authored-by: Nick Anisimov <[email protected]>
Co-authored-by: MacKinley Smith <[email protected]>
Co-authored-by: Yordis Prieto <[email protected]>
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: AKolenda <[email protected]>
Co-authored-by: Guillermo Casanova <[email protected]>
Co-authored-by: Otavio Salvador <[email protected]>
Co-authored-by: Shirish Pothi <[email protected]>
Co-authored-by: Ishaan Kothari <[email protected]>
Co-authored-by: Bob Fowler <[email protected]>
Co-authored-by: Anton Bezdenezhnykh <[email protected]>
Co-authored-by: ValeraZSD <[email protected]>
Co-authored-by: Ephraim <[email protected]>
Co-authored-by: Ryan Ilano <[email protected]>
Co-authored-by: Alex <[email protected]>
Co-authored-by: maco <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Tristan Knight <[email protected]>
Co-authored-by: PR Batch Tester <[email protected]>
Co-authored-by: oliver <[email protected]>
Co-authored-by: kamkm <[email protected]>
Signed-off-by: Yordis Prieto <[email protected]>
2026-10-02 12:22:22 -07:00

363 lines
13 KiB
TypeScript

import {
CheckpointId,
CheckpointScopeId,
type OrchestrationV2DomainEvent,
ProviderThreadId,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import {
isCheckpointRestoreIsolated,
SHARED_WORKSPACE_RESTORE_MESSAGE,
} from "./CheckpointRestoreSafety.ts";
import { CheckpointServiceV2 } from "./CheckpointService.ts";
import { EventSinkV2 } from "./EventSink.ts";
import { IdAllocatorV2 } from "./IdAllocator.ts";
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
import * as ProjectStore from "./ProjectStore.ts";
import type { ProviderAdapterV2RollbackTarget } from "./ProviderAdapter.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
export const ROLLBACK_FAILED_MESSAGE =
"The provider could not roll back this conversation. Try again; if it keeps failing, check the provider and server logs.";
export class CheckpointRollbackExecutionError extends Schema.TaggedError<CheckpointRollbackExecutionError>()(
"CheckpointRollbackExecutionError",
{
reason: Schema.Literals([
"rollback-target-invalid",
"active-provider-changed",
"provider-turn-unavailable",
"unexpected-failure",
"shared-workspace",
]),
threadId: ThreadId,
providerThreadId: ProviderThreadId,
checkpointId: CheckpointId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
switch (this.reason) {
case "rollback-target-invalid":
return `Rollback target ${this.checkpointId} for provider thread ${this.providerThreadId} on thread ${this.threadId} is incomplete or invalid.`;
case "active-provider-changed":
return `Active provider changed before rollback target ${this.checkpointId} could execute on thread ${this.threadId}.`;
case "provider-turn-unavailable":
return `Provider turn for rollback target ${this.checkpointId} is unavailable on provider thread ${this.providerThreadId}.`;
case "shared-workspace":
return SHARED_WORKSPACE_RESTORE_MESSAGE;
case "unexpected-failure":
return ROLLBACK_FAILED_MESSAGE;
}
}
}
const isCheckpointRollbackExecutionError = Schema.is(CheckpointRollbackExecutionError);
export interface CheckpointRollbackServiceV2Shape {
readonly execute: (input: {
readonly threadId: ThreadId;
readonly providerThreadId: ProviderThreadId;
readonly checkpointId: CheckpointId;
readonly scopeId: CheckpointScopeId;
readonly restoreFiles?: boolean;
}) => Effect.Effect<void, CheckpointRollbackExecutionError>;
}
export class CheckpointRollbackServiceV2 extends Context.Service<
CheckpointRollbackServiceV2,
CheckpointRollbackServiceV2Shape
>()("t3/orchestration-v2/CheckpointRollbackService/CheckpointRollbackServiceV2") {}
export const layer: Layer.Layer<
CheckpointRollbackServiceV2,
never,
| CheckpointServiceV2
| EventSinkV2
| IdAllocatorV2
| ProjectionStoreV2
| ProviderSessionManagerV2
| RuntimePolicyV2
| FileSystem.FileSystem
| Path.Path
| ProjectStore.ProjectStoreV2
> = Layer.effect(
CheckpointRollbackServiceV2,
Effect.gen(function* () {
const checkpoints = yield* CheckpointServiceV2;
const eventSink = yield* EventSinkV2;
const ids = yield* IdAllocatorV2;
const projections = yield* ProjectionStoreV2;
const sessions = yield* ProviderSessionManagerV2;
const runtimePolicy = yield* RuntimePolicyV2;
const fileSystem = yield* FileSystem.FileSystem;
const projects = yield* ProjectStore.ProjectStoreV2;
const path = yield* Path.Path;
const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
readonly threadId: ThreadId;
readonly providerThreadId: ProviderThreadId;
readonly checkpointId: CheckpointId;
readonly scopeId: CheckpointScopeId;
readonly restoreFiles?: boolean;
}) {
const projection = yield* projections.getThreadRecords(input.threadId, [
"providerThreads",
"providerSessions",
"checkpoints",
"checkpointScopes",
"runs",
"attempts",
"nodes",
"providerTurns",
]);
const providerThread = projection.providerThreads.find(
(candidate) => candidate.id === input.providerThreadId,
);
const checkpoint = projection.checkpoints.find(
(candidate) => candidate.id === input.checkpointId,
);
const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
if (
providerThread === undefined ||
providerThread.providerSessionId === null ||
checkpoint === undefined ||
scope === undefined ||
checkpoint.scopeId !== scope.id ||
checkpoint.status !== "ready"
) {
return yield* new CheckpointRollbackExecutionError({
reason: "rollback-target-invalid",
threadId: input.threadId,
providerThreadId: input.providerThreadId,
checkpointId: input.checkpointId,
});
}
if (
providerThread.id !== projection.thread.activeProviderThreadId ||
providerThread.providerInstanceId !== projection.thread.modelSelection.instanceId
) {
return yield* new CheckpointRollbackExecutionError({
reason: "active-provider-changed",
threadId: input.threadId,
providerThreadId: input.providerThreadId,
checkpointId: input.checkpointId,
});
}
if (
input.restoreFiles !== false &&
!(yield* isCheckpointRestoreIsolated(projection.thread, scope, {
fileSystem,
projections,
projects,
path,
}))
) {
return yield* new CheckpointRollbackExecutionError({
reason: "shared-workspace",
threadId: input.threadId,
providerThreadId: input.providerThreadId,
checkpointId: input.checkpointId,
});
}
const modelSelection = projection.thread.modelSelection;
const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
thread: projection.thread,
modelSelection,
});
const existingSession = projection.providerSessions.find(
(candidate) => candidate.id === providerThread.providerSessionId,
);
const session = yield* sessions.open({
threadId: input.threadId,
providerSessionId: providerThread.providerSessionId,
modelSelection,
runtimePolicy: resolvedRuntimePolicy,
...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
...(providerThread.nativeThreadRef?.nativeId == null
? {}
: { initialNativeThreadId: providerThread.nativeThreadRef.nativeId }),
...(providerThread.nativeMetadata?.itemIdentityVersion === undefined
? {}
: {
initialProviderItemIdentityVersion: providerThread.nativeMetadata.itemIdentityVersion,
}),
});
const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
// Stopped and failed runs after the target leave the provider
// conversation too, so they must not stay visible.
const runsToRollback = projection.runs.filter(
(run) =>
run.ordinal > targetOrdinal &&
(run.status === "completed" ||
run.status === "interrupted" ||
run.status === "failed" ||
run.status === "cancelled"),
);
// Rolled-back turns stay in the audit history, but no longer exist in
// the provider conversation and must not be counted by a later rewind.
const rolledBackRunIds = new Set(
projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id),
);
const rolledBackAttemptIds = new Set(
projection.attempts
.filter((attempt) => rolledBackRunIds.has(attempt.runId))
.map((attempt) => attempt.id),
);
const providerThreadTurns = projection.providerTurns.filter(
(turn) =>
turn.providerThreadId === providerThread.id &&
(turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)),
);
const rollbackTarget: ProviderAdapterV2RollbackTarget =
targetOrdinal === 0
? {
type: "thread_start",
checkpointId: checkpoint.id,
appRunOrdinal: 0,
}
: yield* Effect.gen(function* () {
const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
const targetAttempt = projection.attempts.find(
(attempt) => attempt.id === targetRun?.activeAttemptId,
);
const targetTurn = projection.providerTurns.find(
(turn) =>
turn.id === targetAttempt?.providerTurnId ||
turn.runAttemptId === targetAttempt?.id,
);
if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) {
return yield* new CheckpointRollbackExecutionError({
reason: "provider-turn-unavailable",
threadId: input.threadId,
providerThreadId: input.providerThreadId,
checkpointId: input.checkpointId,
});
}
return {
type: "provider_turn" as const,
checkpointId: checkpoint.id,
appRunOrdinal: targetOrdinal,
providerTurn: targetTurn,
};
});
const snapshot =
runsToRollback.length === 0
? { providerThread }
: yield* session.rollbackThread({
providerThread,
target: rollbackTarget,
providerThreadTurns,
});
if (input.restoreFiles !== false) yield* checkpoints.restore({ scope, checkpoint });
const staleCheckpoints = projection.checkpoints.filter(
(candidate) =>
candidate.scopeId === scope.id &&
candidate.appRunOrdinal !== null &&
candidate.appRunOrdinal > targetOrdinal &&
candidate.status === "ready",
);
if (staleCheckpoints.length > 0) {
yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints });
}
const now = yield* DateTime.now;
const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
Effect.map(
ids.allocate.event({ threadId: event.threadId }),
(id) =>
({
...event,
id,
}) as Event,
);
const events: Array<OrchestrationV2DomainEvent> = [];
events.push(
yield* makeEvent({
type: "provider-thread.updated",
threadId: input.threadId,
driver: providerThread.driver,
providerInstanceId: providerThread.providerInstanceId,
occurredAt: now,
payload: {
...snapshot.providerThread,
lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
updatedAt: now,
},
}),
);
for (const staleCheckpoint of staleCheckpoints) {
events.push(
yield* makeEvent({
type: "checkpoint.captured",
threadId: input.threadId,
...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
nodeId: staleCheckpoint.nodeId,
providerInstanceId: providerThread.providerInstanceId,
occurredAt: now,
payload: { ...staleCheckpoint, status: "stale" },
}),
);
}
for (const run of runsToRollback) {
const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
events.push(
yield* makeEvent({
type: "run.updated",
threadId: input.threadId,
runId: run.id,
...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...run, status: "rolled_back", completedAt: now },
}),
);
if (rootNode !== undefined) {
events.push(
yield* makeEvent({
type: "node.updated",
threadId: input.threadId,
runId: run.id,
nodeId: rootNode.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...rootNode, status: "rolled_back", completedAt: now },
}),
);
}
}
yield* eventSink.write({ events });
});
return CheckpointRollbackServiceV2.of({
execute: (input) =>
execute(input).pipe(
Effect.mapError((cause) =>
isCheckpointRollbackExecutionError(cause)
? cause
: new CheckpointRollbackExecutionError({
reason: "unexpected-failure",
threadId: input.threadId,
providerThreadId: input.providerThreadId,
checkpointId: input.checkpointId,
cause,
}),
),
),
});
}),
);