Skip to content
TypeScript

fix(server): reconcile Pi native session rewinds (#13839)

Wout Stiens7a2b1c72beed
diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
index 1ccbdaf9597..d1b978e3862 100644
--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
@@ -1,5 +1,8 @@
import { assert, it } from "@effect/vitest";
import {
+ CheckpointId,
+ CheckpointRef,
+ CheckpointScopeId,
MessageId,
type ModelSelection,
NodeId,
@@ -14,6 +17,8 @@ import {
ProviderDriverKind,
ProviderInstanceId,
PlanId,
+ type ProviderThreadId,
+ ProviderTurnId,
RunAttemptId,
RunId,
RuntimeRequestId,
@@ -318,6 +323,254 @@ layer("ProviderEventIngestorV2", (it) => {
}),
);
+ it.effect("rolls back runs a provider rewound off its active branch", () =>
+ Effect.gen(function* () {
+ const now = yield* DateTime.now;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
+ const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
+ const threadEvent = yield* threadCreatedEvent(now);
+ const threadId = threadEvent.threadId;
+ const providerSessionId = yield* idAllocator.allocate.providerSession({
+ providerInstanceId: modelSelection.instanceId,
+ threadId,
+ });
+ const rewoundThreadId = idAllocator.derive.providerThread({
+ driver: CODEX_DRIVER,
+ nativeThreadId: "rewound-thread",
+ });
+ const otherThreadId = idAllocator.derive.providerThread({
+ driver: CODEX_DRIVER,
+ nativeThreadId: "other-thread",
+ });
+ const scopeId = CheckpointScopeId.make("checkpoint-scope:rewound");
+ // A run as execution leaves it: attempt, provider turn, root node, and a
+ // checkpoint once completed. A null native turn id is a weak ref.
+ const seedRun = Effect.fnUntraced(function* (input: {
+ readonly ordinal: number;
+ readonly providerThreadId: ProviderThreadId;
+ readonly status: "completed" | "interrupted" | "running";
+ readonly nativeTurnId: string | null;
+ }) {
+ const runId = RunId.make(`run:rewound:${input.ordinal}`);
+ const attemptId = RunAttemptId.make(`attempt:rewound:${input.ordinal}`);
+ const nodeId = NodeId.make(`node:rewound:${input.ordinal}`);
+ const providerTurnId = ProviderTurnId.make(`provider-turn:rewound:${input.ordinal}`);
+ const completedAt = input.status === "running" ? null : now;
+ const eventId = () => idAllocator.allocate.event({ threadId });
+ const events: Array<OrchestrationV2DomainEvent> = [
+ {
+ id: yield* eventId(),
+ type: "run.created",
+ threadId,
+ occurredAt: now,
+ payload: {
+ id: runId,
+ threadId,
+ ordinal: input.ordinal,
+ providerInstanceId: modelSelection.instanceId,
+ modelSelection,
+ providerThreadId: input.providerThreadId,
+ userMessageId: MessageId.make(`message:rewound:${input.ordinal}`),
+ rootNodeId: nodeId,
+ activeAttemptId: attemptId,
+ status: input.status,
+ requestedAt: now,
+ startedAt: now,
+ completedAt,
+ checkpointId: null,
+ contextHandoffId: null,
+ },
+ },
+ {
+ id: yield* eventId(),
+ type: "run-attempt.created",
+ threadId,
+ occurredAt: now,
+ payload: {
+ id: attemptId,
+ runId,
+ attemptOrdinal: 1,
+ rootNodeId: nodeId,
+ providerInstanceId: modelSelection.instanceId,
+ providerThreadId: input.providerThreadId,
+ providerTurnId,
+ reason: "initial",
+ status: input.status,
+ startedAt: now,
+ completedAt,
+ },
+ },
+ {
+ id: yield* eventId(),
+ type: "provider-turn.updated",
+ threadId,
+ occurredAt: now,
+ payload: {
+ id: providerTurnId,
+ providerThreadId: input.providerThreadId,
+ nodeId,
+ runAttemptId: attemptId,
+ nativeTurnRef:
+ input.nativeTurnId === null
+ ? {
+ driver: CODEX_DRIVER,
+ nativeId: `synthetic:${input.ordinal}`,
+ strength: "weak",
+ }
+ : { driver: CODEX_DRIVER, nativeId: input.nativeTurnId, strength: "strong" },
+ ordinal: input.ordinal,
+ status: input.status,
+ startedAt: now,
+ completedAt,
+ },
+ },
+ {
+ id: yield* eventId(),
+ type: "node.updated",
+ threadId,
+ occurredAt: now,
+ payload: {
+ id: nodeId,
+ threadId,
+ runId,
+ parentNodeId: null,
+ rootNodeId: nodeId,
+ kind: "root_turn",
+ status: input.status,
+ countsForRun: true,
+ providerThreadId: input.providerThreadId,
+ providerTurnId,
+ nativeItemRef: null,
+ runtimeRequestId: null,
+ checkpointScopeId: scopeId,
+ startedAt: now,
+ completedAt,
+ },
+ },
+ ...(input.status === "completed"
+ ? [
+ {
+ id: yield* eventId(),
+ type: "checkpoint.captured" as const,
+ threadId,
+ occurredAt: now,
+ payload: {
+ id: CheckpointId.make(`checkpoint:rewound:${input.ordinal}`),
+ threadId,
+ scopeId,
+ runId,
+ nodeId,
+ parentCheckpointId: null,
+ ordinalWithinScope: input.ordinal,
+ appRunOrdinal: input.ordinal,
+ ref: CheckpointRef.make(`refs/t3/checkpoints/rewound/${input.ordinal}`),
+ status: "ready" as const,
+ files: [],
+ capturedAt: now,
+ },
+ },
+ ]
+ : []),
+ ];
+ yield* eventSink.write({ events });
+ return runId;
+ });
+
+ yield* eventSink.write({ events: [threadEvent] });
+ const otherProviderRun = yield* seedRun({
+ ordinal: 1,
+ providerThreadId: otherThreadId,
+ status: "completed",
+ nativeTurnId: "other-turn",
+ });
+ const keptRun = yield* seedRun({
+ ordinal: 2,
+ providerThreadId: rewoundThreadId,
+ status: "completed",
+ nativeTurnId: "kept-turn",
+ });
+ const abandonedRun = yield* seedRun({
+ ordinal: 3,
+ providerThreadId: rewoundThreadId,
+ status: "completed",
+ nativeTurnId: "abandoned-turn",
+ });
+ const unlocatedRun = yield* seedRun({
+ ordinal: 4,
+ providerThreadId: rewoundThreadId,
+ status: "interrupted",
+ nativeTurnId: null,
+ });
+ const rewindingRun = yield* seedRun({
+ ordinal: 5,
+ providerThreadId: rewoundThreadId,
+ status: "running",
+ nativeTurnId: null,
+ });
+
+ yield* ingestor.ingestNormalized({
+ providerSessionId,
+ providerInstanceId: modelSelection.instanceId,
+ threadId,
+ runId: rewindingRun,
+ event: {
+ type: "provider_thread.updated",
+ driver: CODEX_DRIVER,
+ providerThread: {
+ id: rewoundThreadId,
+ driver: CODEX_DRIVER,
+ providerInstanceId: modelSelection.instanceId,
+ providerSessionId,
+ appThreadId: threadId,
+ ownerNodeId: null,
+ nativeThreadRef: {
+ driver: CODEX_DRIVER,
+ nativeId: "rewound-thread",
+ strength: "strong",
+ },
+ nativeConversationHeadRef: {
+ driver: CODEX_DRIVER,
+ nativeId: "kept-turn-reply",
+ strength: "strong",
+ },
+ status: "idle",
+ firstRunOrdinal: 2,
+ lastRunOrdinal: 5,
+ handoffIds: [],
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ },
+ retainedNativeTurnIds: ["turn-started-outside-t3", "kept-turn"],
+ },
+ });
+
+ const projection = yield* projectionStore.getThreadProjection(threadId);
+ const runIds = [otherProviderRun, keptRun, abandonedRun, unlocatedRun, rewindingRun];
+ assert.deepEqual(
+ runIds.map((runId) => projection.runs.find((run) => run.id === runId)?.status),
+ ["completed", "completed", "rolled_back", "rolled_back", "running"],
+ );
+ assert.deepEqual(
+ runIds.map((runId) => projection.nodes.find((node) => node.runId === runId)?.status),
+ ["completed", "completed", "rolled_back", "rolled_back", "running"],
+ );
+ assert.deepEqual(
+ [otherProviderRun, keptRun, abandonedRun].map(
+ (runId) =>
+ projection.checkpoints.find((checkpoint) => checkpoint.runId === runId)?.status,
+ ),
+ ["ready", "ready", "stale"],
+ );
+ assert.equal(
+ projection.providerThreads.find((thread) => thread.id === rewoundThreadId)?.lastRunOrdinal,
+ 5,
+ );
+ }),
+ );
+
it.effect("carries plan-step durations through consecutive and restarted ingestion", () =>
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse("2026-09-07T00:00:00.000Z"));
diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts
index b794883c092..355a73e2199 100644
--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts
+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts
@@ -7,6 +7,7 @@ import {
type OrchestrationV2Run,
type OrchestrationV2ProviderTurn,
type OrchestrationV2Subagent,
+ type OrchestrationV2ThreadProjection,
type ModelSelection,
type RuntimeMode,
type ProviderInteractionMode,
@@ -197,6 +198,57 @@ function withPlanStepDurations(
};
}
+/** Settled runs that carried conversation to the provider. */
+const CONVERSATION_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
+ "completed",
+ "interrupted",
+ "failed",
+]);
+
+/**
+ * Settled runs on a provider thread that a native rewind left off the active
+ * branch. A run whose provider turn has a strong native ref is judged by that
+ * ref. A run without one cannot be located, so it falls with everything after
+ * the last run still on the branch.
+ */
+function runsOffNativeBranch(input: {
+ readonly projection: Pick<OrchestrationV2ThreadProjection, "runs" | "attempts" | "providerTurns">;
+ readonly providerThreadId: ProviderThreadId;
+ readonly retainedNativeTurnIds: ReadonlySet<string>;
+ readonly reportingRunId: RunId | undefined;
+}): ReadonlyArray<OrchestrationV2Run> {
+ const { attempts, providerTurns, runs } = input.projection;
+ const nativeTurnId = (run: OrchestrationV2Run) => {
+ const attempt = attempts.find((candidate) => candidate.id === run.activeAttemptId);
+ if (attempt === undefined) return null;
+ const ref = providerTurns.find(
+ (turn) => turn.id === attempt.providerTurnId || turn.runAttemptId === attempt.id,
+ )?.nativeTurnRef;
+ return ref?.strength === "strong" ? ref.nativeId : null;
+ };
+ const settled = runs.flatMap((run) =>
+ run.providerThreadId === input.providerThreadId &&
+ run.id !== input.reportingRunId &&
+ CONVERSATION_RUN_STATUSES.has(run.status)
+ ? [{ run, nativeTurnId: nativeTurnId(run) }]
+ : [],
+ );
+ const lastRetainedOrdinal = settled.reduce(
+ (last, { run, nativeTurnId }) =>
+ nativeTurnId !== null && input.retainedNativeTurnIds.has(nativeTurnId)
+ ? Math.max(last, run.ordinal)
+ : last,
+ 0,
+ );
+ return settled
+ .filter(({ run, nativeTurnId }) =>
+ nativeTurnId === null
+ ? run.ordinal > lastRetainedOrdinal
+ : !input.retainedNativeTurnIds.has(nativeTurnId),
+ )
+ .map(({ run }) => run);
+}
+
export interface ProviderEventIngestInput {
readonly providerSessionId: ProviderSessionId;
readonly providerInstanceId: ProviderInstanceId;
@@ -387,6 +439,84 @@ export const layer: Layer.Layer<
},
);
+ /**
+ * The provider rewound its conversation outside T3. Retire the runs that
+ * fell off its active branch with the same run, root-node, and checkpoint
+ * updates CheckpointRollbackService writes for a T3 revert. The run
+ * reporting the rewind performed it and stays, so it keeps lastRunOrdinal.
+ */
+ const rollBackRewoundRuns = Effect.fn("ProviderEventIngestor.rollBackRewoundRuns")(function* (
+ input: ProviderEventIngestInput,
+ rewind: {
+ readonly threadId: ThreadId;
+ readonly providerThreadId: ProviderThreadId;
+ readonly retainedNativeTurnIds: ReadonlySet<string>;
+ },
+ ) {
+ const projection = yield* projections.getThreadRecords(rewind.threadId, [
+ "runs",
+ "attempts",
+ "providerTurns",
+ "nodes",
+ "checkpoints",
+ ]);
+ const runs = runsOffNativeBranch({
+ projection,
+ providerThreadId: rewind.providerThreadId,
+ retainedNativeTurnIds: rewind.retainedNativeTurnIds,
+ reportingRunId: input.runId,
+ });
+ if (runs.length === 0) return [];
+ const now = yield* DateTime.now;
+ const eventId = () =>
+ idAllocator.allocate.event({
+ threadId: rewind.threadId,
+ providerSessionId: input.providerSessionId,
+ });
+ const runIds = new Set(runs.map((run) => run.id));
+ const events: Array<OrchestrationV2DomainEvent> = [];
+ for (const checkpoint of projection.checkpoints) {
+ if (checkpoint.status !== "ready" || checkpoint.runId === null) continue;
+ if (!runIds.has(checkpoint.runId)) continue;
+ events.push({
+ id: yield* eventId(),
+ type: "checkpoint.captured",
+ threadId: rewind.threadId,
+ runId: checkpoint.runId,
+ nodeId: checkpoint.nodeId,
+ providerInstanceId: input.providerInstanceId,
+ occurredAt: now,
+ payload: { ...checkpoint, status: "stale" },
+ });
+ }
+ for (const run of runs) {
+ const rootNode = projection.nodes.find((node) => node.id === run.rootNodeId);
+ events.push({
+ id: yield* eventId(),
+ type: "run.updated",
+ threadId: rewind.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({
+ id: yield* eventId(),
+ type: "node.updated",
+ threadId: rewind.threadId,
+ runId: run.id,
+ nodeId: rootNode.id,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: { ...rootNode, status: "rolled_back", completedAt: now },
+ });
+ }
+ }
+ return events;
+ });
+
const normalize: ProviderEventIngestorV2Shape["normalize"] = (input) =>
Effect.gen(function* () {
switch (input.event.type) {
@@ -405,14 +535,24 @@ export const layer: Layer.Layer<
payload: input.event.providerSession,
}),
];
- case "provider_thread.updated":
- return [
- yield* makeDomainEvent(input, {
- type: "provider-thread.updated",
- threadId: input.event.providerThread.appThreadId ?? input.threadId,
- payload: input.event.providerThread,
- }),
- ];
+ case "provider_thread.updated": {
+ const threadId = input.event.providerThread.appThreadId ?? input.threadId;
+ const updated = yield* makeDomainEvent(input, {
+ type: "provider-thread.updated",
+ threadId,
+ payload: input.event.providerThread,
+ });
+ return input.event.retainedNativeTurnIds === undefined
+ ? [updated]
+ : [
+ updated,
+ ...(yield* rollBackRewoundRuns(input, {
+ threadId,
+ providerThreadId: input.event.providerThread.id,
+ retainedNativeTurnIds: new Set(input.event.retainedNativeTurnIds),
+ })),
+ ];
+ }
case "provider_turn.updated":
return [
...(["completed", "interrupted", "failed", "cancelled"].includes(
diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts
index 3cc27acd6d5..c6e6ef48627 100644
--- a/packages/provider-core/src/server/ProviderAdapter.ts
+++ b/packages/provider-core/src/server/ProviderAdapter.ts
@@ -90,6 +90,13 @@ export const ProviderAdapterV2Event = Schema.Union([
type: Schema.Literal("provider_thread.updated"),
driver: ProviderDriverKind,
providerThread: OrchestrationV2ProviderThread,
+ /**
+ * Set when the provider rewound its own conversation outside T3, for
+ * example a Pi extension moving the session-tree leaf back. Lists every
+ * native turn id still on the active branch; the ingestor rolls back
+ * earlier runs whose turns fell off it.
+ */
+ retainedNativeTurnIds: Schema.optional(Schema.Array(Schema.String)),
}),
Schema.Struct({
type: Schema.Literal("provider_turn.updated"),
diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts
index 562fb5ca079..f737c3d5878 100644
--- a/packages/provider-pi/src/server/adapter.test.ts
+++ b/packages/provider-pi/src/server/adapter.test.ts
@@ -2019,6 +2019,317 @@ describe("PiAdapterV2", () => {
}).pipe(Effect.scoped, Effect.provide(layerTest)),
);
+ it.effect.each([false, true])("follows an extension rewind with summarize=%s", (summarize) =>
+ Effect.gen(function* () {
+ const fake = yield* makeFakePi;
+ const { runtime, takeEvent } = yield* openRuntime(fake);
+ const root = { type: "model_change", id: "root", parentId: null };
+ const user = (id: string, parentId: string) => ({
+ type: "message",
+ id,
+ parentId,
+ message: { role: "user", content: [{ type: "text", text: id }] },
+ });
+ const reply = (id: string, parentId: string) => ({
+ type: "message",
+ id,
+ parentId,
+ message: { role: "assistant", content: [] },
+ });
+ fake.queueEntries({ entries: [root], leafId: "root" });
+ const providerThread = yield* runtime.ensureThread({
+ threadId: THREAD_ID,
+ modelSelection: modelSelection("default"),
+ runtimePolicy,
+ });
+ // Runs one turn to its terminal. `listings` answer the turn's
+ // get_entries requests in order.
+ const settle = Effect.fnUntraced(function* (
+ text: string,
+ runOrdinal: number,
+ ...listings: ReadonlyArray<unknown>
+ ) {
+ yield* startTurn(runtime, providerThread, "default", [], text, undefined, runOrdinal);
+ yield* fake.takeRequest("prompt");
+ for (const listing of listings) fake.queueEntries(listing);
+ // Pi acks every prompt; a command-only prompt then settles from
+ // an idle probe instead of agent events.
+ yield* fake.emit({ type: "response", command: "prompt", success: true });
+ if (!text.startsWith("/")) {
+ yield* fake.emit({ type: "agent_start" });
+ yield* fake.emit({ type: "agent_settled" });
+ }
+ const turn = yield* takeEvent(
+ (event) =>
+ event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
+ );
+ const thread = yield* takeEvent(
+ (event) =>
+ event.type === "provider_thread.updated" && event.providerThread.status === "idle",
+ );
+ yield* takeEvent((event) => event.type === "turn.terminal");
+ return {
+ turnRef:
+ turn.type === "provider_turn.updated" ? turn.providerTurn.nativeTurnRef : undefined,
+ head:
+ thread.type === "provider_thread.updated"
+ ? thread.providerThread.nativeConversationHeadRef?.nativeId
+ : undefined,
+ retained:
+ thread.type === "provider_thread.updated" ? thread.retainedNativeTurnIds : undefined,
+ };
+ });
+
+ yield* settle("prompt A", 1, {
+ entries: [user("uA", "root"), reply("aA", "uA")],
+ leafId: "aA",
+ });
+ const promptB = yield* settle("prompt B", 2, {
+ entries: [user("uB", "aA"), reply("aB", "uB")],
+ leafId: "aB",
+ });
+ assert.equal(promptB.turnRef?.nativeId, "uB");
+ assert.isUndefined(promptB.retained);
+
+ // The extension moves the leaf back to A's reply. With a summary,
+ // pi appends a branch_summary child of that reply as the new leaf.
+ const rewoundLeaf = summarize ? "summary" : "aA";
+ const summary = summarize ? [{ type: "branch_summary", id: "summary", parentId: "aA" }] : [];
+ const rewind = yield* settle(
+ "/rewind",
+ 3,
+ { entries: summary, leafId: rewoundLeaf },
+ {
+ entries: [
+ root,
+ user("uA", "root"),
+ reply("aA", "uA"),
+ user("uB", "aA"),
+ reply("aB", "uB"),
+ ...summary,
+ ],
+ leafId: rewoundLeaf,
+ },
+ );
+ assert.deepEqual(rewind.retained, ["uA"]);
+ assert.equal(rewind.head, rewoundLeaf);
+ if (summarize) {
+ // The summary is this turn's only entry, and fork cannot re-root
+ // before a non-user entry, so rollback may not pass it.
+ assert.equal(rewind.turnRef?.strength, "weak");
+ } else {
+ // Nothing of this turn is on the branch; rollback can pass it.
+ assert.isNull(rewind.turnRef);
+ }
+
+ // get_entries is append-ordered: after a rewind to an older leaf,
+ // the abandoned branch still comes first in the next window.
+ const promptC = yield* settle("prompt C", 4, {
+ entries: [
+ ...(summarize ? [] : [user("uB", "aA"), reply("aB", "uB")]),
+ user("uC", rewoundLeaf),
+ reply("aC", "uC"),
+ ],
+ leafId: "aC",
+ });
+ assert.deepEqual(promptC.turnRef, {
+ driver: PI_PROVIDER,
+ nativeId: "uC",
+ strength: "strong",
+ });
+ assert.isUndefined(promptC.retained);
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
+ );
+
+ // Corrupted session data can loop its parentId chain. Finalizing the turn
+ // must still finish, and must not report a branch to roll runs back to.
+ it.effect.each(["turn window", "full tree"] as const)(
+ "finishes a turn whose %s has a parentId cycle",
+ (cycleIn) =>
+ Effect.gen(function* () {
+ const fake = yield* makeFakePi;
+ const { runtime, takeEvent } = yield* openRuntime(fake);
+ const root = { type: "model_change", id: "root", parentId: null };
+ const cycle = [
+ { type: "message", id: "x", parentId: "y", message: { role: "user", content: [] } },
+ { type: "message", id: "y", parentId: "x", message: { role: "assistant", content: [] } },
+ ];
+ fake.queueEntries({ entries: [root], leafId: "root" });
+ const providerThread = yield* runtime.ensureThread({
+ threadId: THREAD_ID,
+ modelSelection: modelSelection("default"),
+ runtimePolicy,
+ });
+ yield* startTurn(runtime, providerThread, "default", [], "prompt", undefined, 1);
+ yield* fake.takeRequest("prompt");
+ if (cycleIn === "turn window") {
+ fake.queueEntries({ entries: cycle, leafId: "x" });
+ } else {
+ // The leaf is outside the `since` window, so this reads as a rewind
+ // and the full tree is walked for the surviving branch.
+ fake.queueEntries({ entries: [], leafId: "x" });
+ fake.queueEntries({ entries: [root, ...cycle], leafId: "x" });
+ }
+ yield* fake.emit({ type: "response", command: "prompt", success: true });
+ yield* fake.emit({ type: "agent_start" });
+ yield* fake.emit({ type: "agent_settled" });
+ yield* takeEvent(
+ (event) =>
+ event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
+ );
+ const thread = yield* takeEvent(
+ (event) =>
+ event.type === "provider_thread.updated" && event.providerThread.status === "idle",
+ );
+ assert.isUndefined(
+ thread.type === "provider_thread.updated" ? thread.retainedNativeTurnIds : null,
+ );
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
+ );
+
+ it.effect.each(["missing parent", "invalid parent", "duplicate id"] as const)(
+ "does not reconcile malformed session entries: %s",
+ (malformed) =>
+ Effect.gen(function* () {
+ const fake = yield* makeFakePi;
+ const { runtime, takeEvent } = yield* openRuntime(fake);
+ const root = { type: "model_change", id: "root", parentId: null };
+ fake.queueEntries({ entries: [root], leafId: "root" });
+ const providerThread = yield* runtime.ensureThread({
+ threadId: THREAD_ID,
+ modelSelection: modelSelection("default"),
+ runtimePolicy,
+ });
+ yield* startTurn(runtime, providerThread);
+ yield* fake.takeRequest("prompt");
+ const entry = {
+ type: "message",
+ id: "x",
+ message: { role: "user", content: [] },
+ ...(malformed === "missing parent"
+ ? {}
+ : { parentId: malformed === "invalid parent" ? 42 : null }),
+ };
+ fake.queueEntries({ entries: [], leafId: "x" });
+ fake.queueEntries({
+ entries: [
+ root,
+ entry,
+ ...(malformed === "duplicate id" ? [{ ...entry, parentId: "root" }] : []),
+ ],
+ leafId: "x",
+ });
+ yield* fake.emit({ type: "response", command: "prompt", success: true });
+ yield* fake.emit({ type: "agent_start" });
+ yield* fake.emit({ type: "agent_settled" });
+ yield* takeEvent(
+ (event) =>
+ event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
+ );
+ const thread = yield* takeEvent(
+ (event) =>
+ event.type === "provider_thread.updated" && event.providerThread.status === "idle",
+ );
+ assert.isUndefined(
+ thread.type === "provider_thread.updated" ? thread.retainedNativeTurnIds : null,
+ );
+ yield* takeEvent((event) => event.type === "turn.terminal");
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
+ );
+
+ it.effect("does not reconcile a replacement session tree as a native rewind", () =>
+ Effect.gen(function* () {
+ const fake = yield* makeFakePi;
+ fake.queueEntries({
+ entries: [{ type: "model_change", id: "old-leaf", parentId: null }],
+ leafId: "old-leaf",
+ });
+ const { runtime, takeEvent } = yield* openRuntime(fake);
+ const providerThread = yield* runtime.ensureThread({
+ threadId: THREAD_ID,
+ modelSelection: modelSelection("default"),
+ runtimePolicy,
+ });
+ const finish = Effect.fnUntraced(function* () {
+ yield* startTurn(runtime, providerThread);
+ yield* fake.takeRequest("prompt");
+ yield* fake.emit({ type: "response", command: "prompt", success: true });
+ yield* fake.emit({ type: "agent_start" });
+ yield* fake.emit({ type: "agent_settled" });
+ const update = yield* takeEvent(
+ (event) =>
+ event.type === "provider_thread.updated" && event.providerThread.status === "idle",
+ );
+ yield* takeEvent((event) => event.type === "turn.terminal");
+ assert.isUndefined(
+ update.type === "provider_thread.updated" ? update.retainedNativeTurnIds : null,
+ );
+ });
+ // A failed cursor read is followed by a full listing from a new session.
+ fake.queueEntries({ entries: [] });
+ yield* finish();
+ fake.queueEntries({
+ entries: [
+ {
+ type: "message",
+ id: "new-user",
+ parentId: null,
+ message: { role: "user", content: [] },
+ },
+ ],
+ leafId: "new-user",
+ });
+ yield* finish();
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
+ );
+
+ it.effect("rolls back past turns that left nothing in the session tree", () =>
+ Effect.gen(function* () {
+ const fake = yield* makeFakePi;
+ const { runtime } = yield* openRuntime(fake);
+ const providerThread = yield* runtime.ensureThread({
+ threadId: THREAD_ID,
+ modelSelection: modelSelection("default"),
+ runtimePolicy,
+ });
+ const turn = (ordinal: number, entryId: string | null): OrchestrationV2ProviderTurn => ({
+ id: ProviderTurnId.make(`turn-${ordinal}`),
+ providerThreadId: providerThread.id,
+ nodeId: NodeId.make(`node-${ordinal}`),
+ runAttemptId: null,
+ nativeTurnRef:
+ entryId === null ? null : { driver: PI_PROVIDER, nativeId: entryId, strength: "strong" },
+ ordinal,
+ status: "completed",
+ startedAt: null,
+ completedAt: null,
+ });
+ const rollBackToFirst = (turns: ReadonlyArray<OrchestrationV2ProviderTurn>) =>
+ runtime.rollbackThread({
+ providerThread,
+ target: {
+ type: "provider_turn",
+ checkpointId: CheckpointId.make("checkpoint-1"),
+ appRunOrdinal: 1,
+ providerTurn: turns[0]!,
+ },
+ providerThreadTurns: turns,
+ });
+ const forkedEntries = () =>
+ fake
+ .allRequests()
+ .filter((request) => request.type === "fork")
+ .map((request) => request.entryId);
+
+ // Only a turn that left nothing follows the target: already there.
+ yield* rollBackToFirst([turn(1, "u1"), turn(2, null)]);
+ assert.deepEqual(forkedEntries(), []);
+ // Pi re-roots before the first later turn that left entries.
+ yield* rollBackToFirst([turn(1, "u1"), turn(2, null), turn(3, "u3")]);
+ assert.deepEqual(forkedEntries(), ["u3"]);
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
+ );
+
it.effect("settles a command-only prompt from its deferred ack and idle probe", () =>
Effect.gen(function* () {
const fake = yield* makeFakePi;
diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts
index d8dedd71d0b..e0d93d51a01 100644
--- a/packages/provider-pi/src/server/adapter.ts
+++ b/packages/provider-pi/src/server/adapter.ts
@@ -341,8 +341,11 @@ interface ActivePiTurn {
}
interface PiTurnTreeRefs {
- readonly turnStartEntryId: string | null;
+ /** Omitted keeps the synthetic ref; null means the turn left nothing on the active branch. */
+ readonly nativeTurnRef: OrchestrationV2ProviderRef | null | undefined;
readonly leafId: string | null;
+ /** Set after a native rewind: every user entry still on the active branch. */
+ readonly retainedNativeTurnIds: ReadonlyArray<string> | undefined;
}
interface PendingPiPrompt {
@@ -567,6 +570,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
const updateProviderThread = (
state: PiThreadState,
patch: Partial<OrchestrationV2ProviderThread>,
+ retainedNativeTurnIds?: ReadonlyArray<string>,
) =>
Effect.gen(function* () {
const updatedAt = yield* DateTime.now;
@@ -575,6 +579,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
type: "provider_thread.updated",
driver: PI_PROVIDER,
providerThread: state.providerThread,
+ ...(retainedNativeTurnIds === undefined ? {} : { retainedNativeTurnIds }),
});
});
@@ -1380,53 +1385,78 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
// ── turn lifecycle ────────────────────────────────────
+ /** One `get_entries` listing, or null when the request failed or named no leaf. */
+ const listSessionEntries = (since: string | null, timeoutMs: number) =>
+ request({ type: "get_entries", ...(since === null ? {} : { since }) }, timeoutMs).pipe(
+ Effect.map((data) => {
+ const leafId = recordField(data, "leafId");
+ const entries = piSessionEntries(recordField(data, "entries"));
+ return entries !== null && (typeof leafId === "string" || leafId === null)
+ ? { entries, leafId }
+ : null;
+ }),
+ Effect.orElseSucceed(() => null),
+ );
+
/**
* Locate this turn's first user entry and the new leaf in pi's session
* tree. The user-entry id becomes the provider turn's native ref (the
* point `fork` rolls back to); the leaf becomes the conversation head.
+ * `get_entries` is append-ordered and keeps abandoned branches, so both
+ * come from walking the leaf's `parentId` chain, never from list order.
+ * A leaf that no longer descends from the previous one means something
+ * outside T3 rewound the session, such as an extension calling
+ * `navigateTree`. The user entries left on the active branch are then
+ * returned so orchestration can roll back runs that fell off it.
* Pure bookkeeping: failures degrade to the synthetic refs.
*/
const captureTurnTreeRefs = Effect.fnUntraced(function* (
timeoutMs = PI_REQUEST_TIMEOUT_MS,
): Effect.fn.Return<PiTurnTreeRefs | null> {
const cursorWasStale = leafCursorStale;
- const cursor = cursorWasStale ? null : lastKnownLeaf;
- const data = yield* request(
- {
- type: "get_entries",
- ...(cursor === null ? {} : { since: cursor }),
- },
- timeoutMs,
- ).pipe(Effect.orElseSucceed(() => undefined));
- if (data === undefined) {
- // Pi may have advanced past `lastKnownLeaf` while this failed, so the
- // cursor can no longer be trusted to bound a single turn.
+ const previousLeaf = lastKnownLeaf;
+ const fullListing = cursorWasStale || previousLeaf === null;
+ const listing = yield* listSessionEntries(fullListing ? null : previousLeaf, timeoutMs);
+ const turnWalk =
+ listing === null ? null : walkPiBranch(listing.entries, listing.leafId, previousLeaf);
+ const rewound = turnWalk !== null && previousLeaf !== null && !turnWalk.reachedStop;
+ // A `since` window ends at the previous leaf; the rewound branch
+ // continues past it, so its ancestry needs the whole tree.
+ const tree = rewound && !fullListing ? yield* listSessionEntries(null, timeoutMs) : listing;
+ if (listing === null || turnWalk === null || tree === null) {
+ // The read failed or its ancestry loops. Pi may have advanced past
+ // `lastKnownLeaf` meanwhile, so the cursor can no longer be trusted
+ // to bound a single turn.
leafCursorStale = true;
return null;
}
- const entries = recordField(data, "entries");
- const leafId = recordString(data, "leafId");
- if (leafId !== undefined) lastKnownLeaf = leafId;
- // Without a trustworthy cursor this window spans more than one turn, so
- // its first user entry belongs to an earlier turn. Re-sync the cursor
- // and skip the turn-start ref rather than pointing rollback too far
- // back; the next turn gets an accurate ref again.
+ lastKnownLeaf = listing.leafId;
leafCursorStale = false;
- const firstUserEntryId = cursorWasStale
- ? undefined
- : Array.isArray(entries)
- ? entries
- .filter(
- (entry) =>
- recordField(entry, "type") === "message" &&
- recordString(recordField(entry, "message"), "role") === "user",
- )
- .map((entry) => recordString(entry, "id"))
- .find((id) => id !== undefined)
+ const turnStartEntryId = turnWalk.userEntryIds.at(-1);
+ // Only a branch walked to its root lists every survivor; a partial or
+ // cyclic walk would roll back runs that are still in the conversation.
+ // A replaced session has a different tree. Only an old leaf still in
+ // this tree proves an in-session rewind rather than a session switch.
+ const branch =
+ rewound && previousLeaf !== null && tree.entries.has(previousLeaf)
+ ? walkPiBranch(tree.entries, listing.leafId, null)
: undefined;
return {
- turnStartEntryId: firstUserEntryId ?? null,
- leafId: leafId ?? null,
+ // Without a trustworthy cursor the walk spans more than one turn, so
+ // its earliest user entry belongs to an earlier turn. Keep the
+ // synthetic ref rather than pointing rollback too far back; the next
+ // turn gets an accurate ref again. A turn that left nothing on the
+ // active branch (a command, or a rewind) gets no ref: a rollback
+ // past it needs no fork of its own.
+ nativeTurnRef: cursorWasStale
+ ? undefined
+ : turnStartEntryId !== undefined
+ ? providerRef(turnStartEntryId)
+ : turnWalk.entryCount === 0
+ ? null
+ : undefined,
+ leafId: listing.leafId,
+ retainedNativeTurnIds: branch?.reachedStop === true ? branch.userEntryIds : undefined,
};
});
@@ -1467,20 +1497,27 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
threadId: turn.turnInput.threadId,
providerTurn: {
...turn.providerTurn,
- ...(treeRefs?.turnStartEntryId == null
+ ...(treeRefs === null || treeRefs.nativeTurnRef === undefined
? {}
- : { nativeTurnRef: providerRef(treeRefs.turnStartEntryId) }),
+ : { nativeTurnRef: treeRefs.nativeTurnRef }),
status: turn.interrupted ? "interrupted" : failure !== null ? "failed" : "completed",
completedAt,
...(tokenUsage === undefined ? {} : { tokenUsage }),
},
});
- yield* updateProviderThread(state, {
- status: "idle",
- ...(treeRefs?.leafId == null
- ? {}
- : { nativeConversationHeadRef: providerRef(treeRefs.leafId) }),
- });
+ yield* updateProviderThread(
+ state,
+ {
+ status: "idle",
+ ...(treeRefs === null
+ ? {}
+ : {
+ nativeConversationHeadRef:
+ treeRefs.leafId === null ? null : providerRef(treeRefs.leafId),
+ }),
+ },
+ treeRefs?.retainedNativeTurnIds,
+ );
yield* updateProviderSession(
failure !== null ? "error" : "ready",
failure?.message ?? null,
@@ -3053,11 +3090,68 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
});
});
+interface PiSessionEntry {
+ readonly parentId: string | null;
+ readonly isUserMessage: boolean;
+}
+
+/** Index a `get_entries` listing, rejecting ambiguous ancestry. */
+function piSessionEntries(entries: unknown): ReadonlyMap<string, PiSessionEntry> | null {
+ const byId = new Map<string, PiSessionEntry>();
+ if (!Array.isArray(entries)) return null;
+ for (const entry of entries) {
+ const id = recordString(entry, "id");
+ const parentId = recordField(entry, "parentId");
+ if (id === undefined || byId.has(id) || (parentId !== null && typeof parentId !== "string"))
+ return null;
+ byId.set(id, {
+ parentId,
+ isUserMessage:
+ recordField(entry, "type") === "message" &&
+ recordString(recordField(entry, "message"), "role") === "user",
+ });
+ }
+ return byId;
+}
+
+/**
+ * Walk pi's active branch from `leafId` towards the root through `entries`,
+ * stopping at `stopAt`. Returns how many entries it passed, the user entries
+ * among them (newest first), and whether the walk reached `stopAt`. Leaving a
+ * partial listing anywhere else means the branch does not descend from `stopAt`.
+ * Returns null when the `parentId` chain loops, which only corrupted session
+ * data can produce; callers treat that like a failed listing.
+ */
+function walkPiBranch(
+ entries: ReadonlyMap<string, PiSessionEntry>,
+ leafId: string | null,
+ stopAt: string | null,
+): {
+ readonly entryCount: number;
+ readonly userEntryIds: ReadonlyArray<string>;
+ readonly reachedStop: boolean;
+} | null {
+ const visited = new Set<string>();
+ const userEntryIds: Array<string> = [];
+ let current = leafId;
+ while (current !== null && current !== stopAt) {
+ const entry = entries.get(current);
+ if (entry === undefined) break;
+ if (visited.has(current)) return null;
+ visited.add(current);
+ if (entry.isUserMessage) userEntryIds.push(current);
+ current = entry.parentId;
+ }
+ return { entryCount: visited.size, userEntryIds, reachedStop: current === stopAt };
+}
+
/**
* Resolve the pi session-tree entry `fork` should re-root at for a rollback.
- * Returns `null` when no turns follow the target (nothing to discard) and
- * `undefined` when the boundary turn has no captured entry ref (only
- * turn-boundary refs recorded by `captureTurnTreeRefs` are strong).
+ * Turns without a ref left nothing on the active branch, so the boundary is
+ * the first discarded turn that has one. Returns `null` when no such turn
+ * follows the target (nothing to discard) and `undefined` when the boundary
+ * turn has no captured entry ref (only turn-boundary refs recorded by
+ * `captureTurnTreeRefs` are strong).
*/
function piRollbackForkEntry(input: {
readonly target:
@@ -3067,13 +3161,11 @@ function piRollbackForkEntry(input: {
}): string | null | undefined {
const boundaryOrdinal =
input.target.type === "thread_start" ? 0 : input.target.providerTurn.ordinal;
- const discarded = input.providerThreadTurns
- .filter((turn) => turn.ordinal > boundaryOrdinal)
- .sort((a, b) => a.ordinal - b.ordinal);
- const boundary = discarded[0];
- if (boundary === undefined) return null;
- const ref = boundary.nativeTurnRef;
- if (ref === null || ref.strength !== "strong" || ref.nativeId === null) return undefined;
+ const ref = input.providerThreadTurns
+ .filter((turn) => turn.ordinal > boundaryOrdinal && turn.nativeTurnRef !== null)
+ .sort((a, b) => a.ordinal - b.ordinal)[0]?.nativeTurnRef;
+ if (ref == null) return null;
+ if (ref.strength !== "strong" || ref.nativeId === null) return undefined;
return ref.nativeId;
}