diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 99adf0393e53..4b335c5150cb 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -163,6 +163,10 @@ interface FakePi { readonly emit: (record: PiRpcRecord, chunkBytes?: number) => Effect.Effect; readonly takeRequest: (type: string) => Effect.Effect; readonly queueEntries: (data: unknown) => void; + readonly setSessionEntries: ( + entries: ReadonlyArray>, + forkFile: string, + ) => void; readonly queueMessages: (data: unknown) => void; readonly vetoNextSwitch: () => void; readonly failNextFork: () => void; @@ -231,6 +235,8 @@ const makeFakePiWithResponses = Effect.fnUntraced(function* ( const stdout = yield* Queue.unbounded(); const requests = yield* Queue.unbounded(); const entriesQueue: Array = []; + let sessionEntries: ReadonlyArray> | undefined; + let forkFile: string | undefined; const messagesQueue: Array = []; const stateQueue: Array> = []; const statsQueue: Array = []; @@ -353,7 +359,13 @@ const makeFakePiWithResponses = Effect.fnUntraced(function* ( return { ...base, data: { cancelled } }; } case "get_entries": - return { ...base, data: entriesQueue.shift() ?? { entries: [], leafId: null } }; + return { + ...base, + data: entriesQueue.shift() ?? { + entries: sessionEntries ?? [], + leafId: sessionEntries?.at(-1)?.id ?? null, + }, + }; case "get_messages": return { ...base, data: messagesQueue.shift() ?? { messages: [] } }; case "get_session_stats": @@ -363,6 +375,13 @@ const makeFakePiWithResponses = Effect.fnUntraced(function* ( failFork = false; return { ...base, success: false, error: "Invalid entry ID for forking" }; } + if (sessionEntries !== undefined && forkFile !== undefined) { + const index = sessionEntries.findIndex((entry) => entry.id === record["entryId"]); + if (index === -1) + return { ...base, success: false, error: "Invalid entry ID for forking" }; + sessionEntries = sessionEntries.slice(0, index); + sessionFile = forkFile; + } serviceTier = null; return { ...base, data: { text: "Hello pi", cancelled: false } }; case "clear_queue": @@ -471,6 +490,10 @@ const makeFakePiWithResponses = Effect.fnUntraced(function* ( emit, takeRequest, queueEntries: (data) => entriesQueue.push(data), + setSessionEntries: (entries, file) => { + sessionEntries = entries; + forkFile = file; + }, queueMessages: (data) => messagesQueue.push(data), deferNextState: (started) => { deferState = true; @@ -4825,6 +4848,126 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect.each([ + { + checkpoint: "strong", + ordinal: 2, + handoff: "command", + returnedPrompt: false, + discarded: true, + }, + { checkpoint: "strong", ordinal: 2, handoff: "prompt", returnedPrompt: true, discarded: true }, + { + checkpoint: "command", + ordinal: 2, + handoff: "prompt", + returnedPrompt: false, + discarded: false, + }, + { checkpoint: "weak", ordinal: 2, handoff: "prompt", returnedPrompt: false, discarded: false }, + { + checkpoint: "command", + ordinal: 1, + handoff: "prompt", + returnedPrompt: false, + discarded: false, + }, + { checkpoint: "weak", ordinal: 1, handoff: "prompt", returnedPrompt: true, discarded: true }, + ] as const)("restores the Pi checkpoint after a session round trip %j", (scenario) => + 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 ref = (nativeId: string, strength: "strong" | "weak" = "strong") => ({ + driver: PI_PROVIDER, + nativeId, + strength, + }); + const sessionFile = providerThread.nativeThreadRef!.nativeId!; + const forkFile = "/fake/rewound.jsonl"; + const turn = ( + ordinal: number, + nativeTurnRef: OrchestrationV2ProviderTurn["nativeTurnRef"], + file = sessionFile, + ): OrchestrationV2ProviderTurn => ({ + id: ProviderTurnId.make(`turn-${ordinal}`), + providerThreadId: providerThread.id, + nodeId: NodeId.make(`node-${ordinal}`), + runAttemptId: null, + nativeTurnRef, + nativeThreadRef: ref(file), + ordinal, + status: "completed", + startedAt: at(ordinal * 50 - 50), + completedAt: at(ordinal * 50), + }); + const target = turn( + scenario.ordinal, + scenario.checkpoint === "strong" + ? ref("u2") + : scenario.checkpoint === "weak" + ? ref("uncaptured", "weak") + : null, + ); + const retained = + scenario.ordinal === 1 || scenario.checkpoint === "command" + ? TURN_ONE_ENTRIES + : [ + ...TURN_ONE_ENTRIES, + sessionMessage("u2", "a1b", "user", 60), + sessionMessage("a2", "u2", "assistant", 80), + ]; + const retainedHead = retained.at(-1)!.id; + const entries = [ + ...retained, + ...(scenario.discarded + ? [ + sessionMessage("discarded", retainedHead, "user", 110), + sessionMessage("discarded-answer", "discarded", "assistant", 120), + ] + : []), + ...(scenario.returnedPrompt ? [sessionMessage("u5", "discarded-answer", "user", 210)] : []), + ]; + fake.setSessionEntries(entries, forkFile); + const restored = yield* runtime.rollbackThread({ + providerThread, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("checkpoint-1"), + appRunOrdinal: target.ordinal, + providerTurn: target, + }, + providerThreadTurns: [ + ...(target.ordinal === 2 ? [turn(1, ref("u1"))] : []), + target, + turn( + target.ordinal + 1, + scenario.handoff === "prompt" ? ref("away") : null, + "/fake/other.jsonl", + ), + turn(target.ordinal + 2, null, "/fake/clone.jsonl"), + turn(target.ordinal + 3, null), + ...(scenario.returnedPrompt ? [turn(target.ordinal + 4, ref("u5"))] : []), + ], + }); + const requests = fake.allRequests(); + assert.isFalse(requests.some((request) => request.type === "switch_session")); + assert.deepEqual( + requests.filter((request) => request.type === "fork").map((request) => request.entryId), + scenario.discarded ? ["discarded"] : [], + ); + assert.equal( + restored.providerThread.nativeThreadRef?.nativeId, + scenario.discarded ? forkFile : sessionFile, + ); + assert.equal(restored.providerThread.nativeConversationHeadRef?.nativeId, retainedHead); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("rolls back a persisted thread on a fresh runtime after its session was released", () => Effect.gen(function* () { const previousFake = yield* makeFakePi; diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 3195b6c62d2a..146e189cf88a 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -4032,6 +4032,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const isCurrentFile = (file: string) => currentFile != null && path.resolve(cwd, file) === path.resolve(cwd, currentFile); + const targetPath = + targetFile === undefined ? undefined : path.resolve(cwd, targetFile); + const isTargetFile = (file: string | null | undefined) => + file != null && path.resolve(cwd, file) === targetPath; const boundaryFile = firstBoundary.type === "nothing" ? undefined @@ -4045,7 +4049,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if ( targetFile !== undefined && boundaryFile != null && - path.resolve(cwd, boundaryFile) !== path.resolve(cwd, targetFile) + !isTargetFile(boundaryFile) ) { // A previous fork can carry the checkpoint into the session with the discard boundary. const listing = @@ -4165,17 +4169,26 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ); } } - let forkEntryId: string | undefined; - if (boundary.type !== "nothing") { - forkEntryId = yield* piForkEntry( - boundary, - rollbackInput.providerThread.createdAt, - switchedTo === undefined ? readCurrentEntries : readEntries, - ); - } else if (switchedTo === undefined && recoveredLegacySource === undefined) { + const leftTargetFile = + target !== null && + isTargetFile(sourceFile) && + rollbackInput.providerThreadTurns.some((turn) => { + const file = turn.nativeThreadRef?.nativeId; + return turn.ordinal > target.ordinal && file != null && !isTargetFile(file); + }); + const verifySource = + leftTargetFile || (boundary.type === "nothing" && switchedTo !== undefined); + if ( + boundary.type === "nothing" && + !verifySource && + recoveredLegacySource === undefined + ) { return piThreadSnapshot(state.providerThread); - } else { - const listing = piSessionListing(yield* request({ type: "get_entries" })); + } + let forkEntryId: string | undefined; + let sourceEntries = switchedTo === undefined ? readCurrentEntries : readEntries; + if (recoveredLegacySource !== undefined) { + const listing = piSessionListing(yield* sourceEntries); const completedAt = target?.completedAt; const retained = listing !== null && targetId !== undefined @@ -4188,18 +4201,68 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if ( listing === null || retained === undefined || - (recoveredLegacySource !== undefined && - !piSameHistory( - listing, - retained.headId, - recoveredLegacySource.listing, - recoveredLegacySource.retained.headId, - )) + !piSameHistory( + listing, + retained.headId, + recoveredLegacySource.listing, + recoveredLegacySource.retained.headId, + ) ) return yield* protocolError( "Pi rollback could not verify the retained session head", ); forkEntryId = retained.forkEntryId; + } else if (verifySource) { + const data = yield* sourceEntries; + sourceEntries = Effect.succeed(data); + const listing = piSessionListing(data); + // Without a captured checkpoint prompt, verify back to an earlier retained + // prompt in the same file or to the root if none was captured. + const anchorId = + targetId ?? + piTurnEntryId( + rollbackInput.providerThreadTurns + .filter( + (turn) => + target !== null && + turn.ordinal < target.ordinal && + isTargetFile(turn.nativeThreadRef?.nativeId) && + piTurnEntryId(turn) !== undefined, + ) + .sort((a, b) => b.ordinal - a.ordinal)[0], + ) ?? + null; + const walk = + listing !== null && (anchorId === null || listing.entries.has(anchorId)) + ? walkPiBranch(listing.entries, listing.leafId, anchorId) + : null; + if (listing === null || walk?.reachedStop !== true) + return yield* protocolError( + "Pi rollback could not verify the retained session head", + ); + // A handoff can leave a prompt before the next recorded turn in this file. + for (const id of [...walk.userEntryIds].reverse()) { + if (boundary.type === "entry" && id === boundary.entryId) { + forkEntryId = id; + break; + } + const timestamp = listing.entries.get(id)?.timestamp; + if (timestamp == null || target?.completedAt == null) + return yield* protocolError( + "Pi rollback could not verify the retained session head", + ); + if (timestamp >= DateTime.toEpochMillis(target.completedAt)) { + forkEntryId = id; + break; + } + } + } + if (forkEntryId === undefined && boundary.type !== "nothing") { + forkEntryId = yield* piForkEntry( + boundary, + rollbackInput.providerThread.createdAt, + sourceEntries, + ); } if (forkEntryId !== undefined) { const forkData = yield* lifecycleRequest({