diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 5565f456677f..99adf0393e53 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -225,7 +225,9 @@ const recordedIdleState = (sessionFile: string) => ({ const PI_COMPACTING_PROMPT_ERROR = "Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry."; -const makeFakePi: Effect.Effect = Effect.gen(function* () { +const makeFakePiWithResponses = Effect.fnUntraced(function* ( + override?: (request: PiRpcRecord, response: PiRpcRecord) => Effect.Effect, +) { const stdout = yield* Queue.unbounded(); const requests = yield* Queue.unbounded(); const entriesQueue: Array = []; @@ -406,7 +408,8 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { continue; } const response = respondTo(record); - if (response !== null) yield* emit(response); + if (response !== null) + yield* emit(override === undefined ? response : yield* override(record, response)); } }); @@ -524,6 +527,8 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { } satisfies FakePi; }); +const makeFakePi: Effect.Effect = makeFakePiWithResponses(); + const makeAdapter = Effect.fnUntraced(function* ( fake: FakePi, launchArgs = "", @@ -4534,6 +4539,192 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect.each([ + "captured handoff", + "command-only handoff", + "legacy uncaptured boundary", + "adopted prompt", + "retry after creating a recovery fork", + "label before the discarded prompt", + "conflicting prior fork", + "captured boundary on a sibling branch", + "dangling checkpoint parent", + "different branch attached after recovery", + ] as const)("restores a legacy checkpoint after a %s", (scenario) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped(); + const original = `${dir}/z-original.jsonl`; + const switched = `${dir}/current.jsonl`; + const priorFork = `${dir}/fork.jsonl`; + const retained = TURN_ONE_ENTRIES; + const labelled = scenario === "label before the discarded prompt"; + const retry = labelled || scenario === "retry after creating a recovery fork"; + const conflicting = scenario === "conflicting prior fork"; + const sibling = scenario === "captured boundary on a sibling branch"; + const changedBranch = scenario === "different branch attached after recovery"; + const handoff = sessionMessage( + "u3", + sibling || scenario === "dangling checkpoint parent" ? "a1b" : null, + "user", + 180, + ); + type Entry = { readonly id: string; readonly parentId: string | null; readonly type: string }; + const sessions = new Map>(); + const write = (file: string, entries: ReadonlyArray) => + fs + .writeFileString( + file, + [{ type: "session", version: 3 }, ...entries] + .map((entry) => encodeJsonLine(entry)) + .join("\n") + "\n", + ) + .pipe(Effect.tap(() => Effect.sync(() => sessions.set(file, entries)))); + const extra = sessionMessage("other", "a1b", "assistant", 45); + const discarded = sessionMessage("discarded", labelled ? "label" : "a1b", "user", 160); + const label = { type: "label", id: "label", parentId: "a1b", targetId: "a1", label: "keep" }; + yield* write( + original, + changedBranch + ? [...retained, extra, discarded] + : retry + ? [...retained, ...(labelled ? [label] : []), discarded] + : retained, + ); + yield* write( + switched, + sibling + ? [...retained, handoff, sessionMessage("sibling", null, "assistant", 28)] + : scenario === "dangling checkpoint parent" + ? [...retained.slice(1), handoff] + : [handoff], + ); + if (conflicting) yield* write(priorFork, [...retained, extra]); + + let liveFile = switched; + const fake = yield* makeFakePiWithResponses((request, response) => + Effect.gen(function* () { + const entries = sessions.get(liveFile) ?? []; + switch (request.type) { + case "get_state": + return { ...response, data: recordedIdleState(liveFile) }; + case "get_entries": + return { + ...response, + data: { + entries, + leafId: + changedBranch && liveFile === original ? "other" : (entries.at(-1)?.id ?? null), + }, + }; + case "switch_session": { + const file = request.sessionPath; + if (typeof file !== "string" || !sessions.has(file)) + throw new Error("Pi switch requested an unknown fixture session"); + liveFile = file; + return response; + } + case "fork": { + let parentId = entries.find(({ id }) => id === request.entryId)?.parentId; + assert.isDefined(parentId); + const path: Array = []; + while (parentId !== null) { + const entry = entries.find(({ id }) => id === parentId); + assert.isDefined(entry); + path.unshift(entry); + parentId = entry.parentId; + } + // Like Pi, drop labels from the path and re-add them with new ids at the leaf. + const branch: Array = []; + for (const entry of path.filter(({ type }) => type !== "label")) + branch.push({ ...entry, parentId: branch.at(-1)?.id ?? null }); + for (const entry of path.filter(({ type }) => type === "label")) + branch.push({ + ...entry, + id: `${entry.id}-copy`, + parentId: branch.at(-1)?.id ?? null, + }); + yield* write(priorFork, branch).pipe(Effect.orDie); + liveFile = priorFork; + return response; + } + default: + return response; + } + }), + ); + const { runtime } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + const [first, next] = uncapturedTurns(providerThread.id); + assert.isDefined(first); + assert.isDefined(next); + const target = { ...first, startedAt: at(scenario === "adopted prompt" ? 20 : 0) }; + const boundary: OrchestrationV2ProviderTurn = { + ...next, + nativeTurnRef: + scenario === "command-only handoff" + ? null + : scenario === "legacy uncaptured boundary" + ? next.nativeTurnRef + : { driver: PI_PROVIDER, strength: "strong", nativeId: "u3" }, + ...(scenario === "legacy uncaptured boundary" + ? {} + : { + nativeThreadRef: { driver: PI_PROVIDER, strength: "strong", nativeId: switched }, + }), + }; + const rewind = runtime.rollbackThread({ + providerThread: { ...providerThread, createdAt: at(0) }, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("legacy-checkpoint"), + appRunOrdinal: target.ordinal, + providerTurn: target, + }, + providerThreadTurns: [target, boundary], + }); + const requests = () => + fake.allRequests().flatMap((request) => { + if (request.type === "switch_session") + return [{ type: request.type, value: request.sessionPath }]; + if (request.type === "fork") return [{ type: request.type, value: request.entryId }]; + return []; + }); + if (conflicting || changedBranch) { + assert.equal((yield* rewind.pipe(Effect.result))._tag, "Failure"); + assert.deepEqual( + requests(), + changedBranch ? [{ type: "switch_session", value: original }] : [], + ); + return; + } + const expected = retry || sibling ? priorFork : original; + const assertRestored = ({ providerThread: restored }: Effect.Success) => { + assert.equal(restored.nativeThreadRef?.nativeId, expected); + assert.equal(restored.nativeConversationHeadRef?.nativeId, labelled ? "label-copy" : "a1b"); + assert.equal(liveFile, expected); + assert.deepEqual( + sessions.get(liveFile)?.filter(({ type }) => type !== "label"), + retained, + ); + }; + const expectedRequests = [ + ...(sibling ? [] : [{ type: "switch_session", value: original }]), + ...(retry || sibling ? [{ type: "fork", value: sibling ? "u3" : "discarded" }] : []), + ]; + assertRestored(yield* rewind); + assert.deepEqual(requests(), expectedRequests); + if (retry) { + assertRestored(yield* rewind); + assert.deepEqual(requests(), expectedRequests); + } + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("rolls back past a turn whose start entry was never captured", () => 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 920acee2e200..3195b6c62d2a 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3042,6 +3042,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return readable ? { entries, leafId } : null; }); + const historicalSessionFiles = Effect.fnUntraced(function* (sessionFile: string) { + const dir = path.dirname(sessionFile); + const siblings = yield* fileSystem + .readDirectoryEntries(dir) + .pipe(Effect.orElseSucceed(() => [])); + return siblings + .filter((entry) => entry.type === "File" && entry.name.endsWith(".jsonl")) + .map((entry) => path.join(dir, entry.name)) + .sort() + .reverse(); + }); + // Old records hold entry IDs without a session file. Recover only when both // timestamped user entries are on the same branch in a sibling session. const findHistoricalForkSession = Effect.fnUntraced(function* ( @@ -3063,15 +3075,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const from = DateTime.toEpochMillis(startedAt); const between = DateTime.toEpochMillis(completedAt); const to = DateTime.toEpochMillis(boundaryEnd); - const dir = path.dirname(currentFile); - const siblings = yield* fileSystem - .readDirectoryEntries(dir) - .pipe(Effect.orElseSucceed(() => [])); - const files = siblings - .filter((entry) => entry.type === "File" && entry.name.endsWith(".jsonl")) - .map((entry) => path.join(dir, entry.name)) - .sort() - .reverse(); + const files = yield* historicalSessionFiles(currentFile); for (const file of files) { if (file === currentFile) continue; const listing = yield* readSessionFile(file); @@ -3088,6 +3092,40 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return undefined; }); + const findHistoricalCheckpointSession = Effect.fnUntraced(function* ( + boundaryFile: string, + targetId: string, + earliestPromptAt: DateTime.Utc, + completedAt: DateTime.Utc, + ) { + const from = DateTime.toEpochMillis(earliestPromptAt); + const to = DateTime.toEpochMillis(completedAt); + let match: PiHistoricalCheckpoint | undefined; + for (const file of yield* historicalSessionFiles(boundaryFile)) { + if (file === boundaryFile) continue; + const listing = yield* readSessionFile(file); + if (listing === null || !piUserEntryInWindow(listing.entries.get(targetId), from, to)) + continue; + const retained = piRetainedCheckpoint(listing, targetId, to); + if (retained === undefined) continue; + if ( + match !== undefined && + !piSameHistory(listing, retained.headId, match.listing, match.retained.headId) + ) { + return yield* protocolError( + "Pi rollback found conflicting histories for the checkpoint", + ); + } + if ( + match === undefined || + (match.retained.forkEntryId !== undefined && retained.forkEntryId === undefined) + ) { + match = { file, listing, retained }; + } + } + return match; + }); + const sessionFileInCwd = Effect.fnUntraced(function* ( sessionFile: string, providerThreadCreatedAt: DateTime.Utc, @@ -4000,6 +4038,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( : firstBoundary.turn.nativeThreadRef?.nativeId; let boundary = firstBoundary; let sourceFile = targetFile ?? boundaryFile; + let recoveredLegacySource: PiHistoricalCheckpoint | undefined; + const readEntries = request({ type: "get_entries" }); + const readCurrentEntries = yield* Effect.cached(readEntries); const targetId = piTurnEntryId(target); if ( targetFile !== undefined && @@ -4044,8 +4085,55 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const live = yield* readSessionFile(path.resolve(cwd, currentFile)); if (live !== null && !live.entries.has(boundary.entryId)) { sourceFile = yield* findHistoricalForkSession(currentFile, boundary); - if (sourceFile === undefined) + } + } + const candidateFile = sourceFile ?? currentFile; + if ( + targetFile === undefined && + candidateFile != null && + targetId !== undefined && + target?.startedAt != null && + target.completedAt !== null + ) { + const resolvedCandidate = path.resolve(cwd, candidateFile); + const listing = isCurrentFile(candidateFile) + ? piSessionListing(yield* readCurrentEntries) + : yield* readSessionFile(resolvedCandidate); + if (listing === null) + return yield* protocolError( + "Pi rollback could not verify the retained session head", + ); + const boundaryId = boundary.type === "entry" ? boundary.entryId : undefined; + if ( + !listing.entries.has(targetId) || + (boundaryId === undefined + ? walkPiBranch(listing.entries, listing.leafId, targetId)?.reachedStop !== + true + : !listing.entries.has(boundaryId)) + ) { + const previousTurn = rollbackInput.providerThreadTurns + .filter((turn) => turn.ordinal < target.ordinal) + .sort((a, b) => b.ordinal - a.ordinal)[0]; + const earliestPromptAt = + previousTurn?.completedAt ?? rollbackInput.providerThread.createdAt; + recoveredLegacySource = yield* findHistoricalCheckpointSession( + resolvedCandidate, + targetId, + DateTime.min(earliestPromptAt, target.startedAt), + target.completedAt, + ); + if (recoveredLegacySource === undefined) return yield* protocolError("Pi rollback entry was not found in a session"); + sourceFile = recoveredLegacySource.file; + boundary = { type: "nothing" }; + } else if ( + boundaryId !== undefined && + (boundaryId === targetId || + walkPiBranch(listing.entries, boundaryId, targetId)?.reachedStop !== true) + ) { + return yield* protocolError( + "Pi rollback could not verify the retained session head", + ); } } let switchedTo: string | undefined; @@ -4082,33 +4170,36 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( forkEntryId = yield* piForkEntry( boundary, rollbackInput.providerThread.createdAt, - request({ type: "get_entries" }), + switchedTo === undefined ? readCurrentEntries : readEntries, ); - } else if (switchedTo === undefined) { + } else if (switchedTo === undefined && recoveredLegacySource === undefined) { return piThreadSnapshot(state.providerThread); } else { const listing = piSessionListing(yield* request({ type: "get_entries" })); - const walk = - listing !== null && targetId !== undefined && listing.entries.has(targetId) - ? walkPiBranch(listing.entries, listing.leafId, targetId) - : null; - if (listing === null || walk?.reachedStop !== true) + const completedAt = target?.completedAt; + const retained = + listing !== null && targetId !== undefined + ? piRetainedCheckpoint( + listing, + targetId, + completedAt == null ? undefined : DateTime.toEpochMillis(completedAt), + ) + : undefined; + if ( + listing === null || + retained === undefined || + (recoveredLegacySource !== undefined && + !piSameHistory( + listing, + retained.headId, + recoveredLegacySource.listing, + recoveredLegacySource.retained.headId, + )) + ) return yield* protocolError( "Pi rollback could not verify the retained session head", ); - // A move can leave prompts behind in the source file, even when no later - // app turn points at that file. Keep steers sent during the retained turn. - for (const id of [...walk.userEntryIds].reverse()) { - 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; - } - } + forkEntryId = retained.forkEntryId; } if (forkEntryId !== undefined) { const forkData = yield* lifecycleRequest({ @@ -4134,6 +4225,23 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( Effect.orElseSucceed(() => undefined), ); const leafId = recordString(entriesData, "leafId") ?? null; + if (recoveredLegacySource !== undefined) { + const listing = piSessionListing(entriesData); + if ( + listing === null || + !piSameHistory( + listing, + leafId, + recoveredLegacySource.listing, + recoveredLegacySource.retained.headId, + ) + ) { + threadState = null; + return yield* protocolError( + "Pi rollback could not verify the retained session head", + ); + } + } // RPC responses bypass the pump; drain prior native events before replacing their binding. const queued = yield* Queue.offer(connection.events, { type: "t3.rollback_barrier", @@ -4303,6 +4411,7 @@ const decodeSessionLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schem interface PiSessionEntry { readonly parentId: string | null; readonly isUserMessage: boolean; + readonly isLabel: boolean; /** Pi's `timestamp` as epoch milliseconds; null when missing or unparsable. */ readonly timestamp: number | null; } @@ -4343,6 +4452,7 @@ function readPiSessionEntry(entry: unknown): [string, PiSessionEntry] | null { isUserMessage: recordField(entry, "type") === "message" && recordString(recordField(entry, "message"), "role") === "user", + isLabel: recordField(entry, "type") === "label", timestamp: timestamp === undefined ? null @@ -4388,6 +4498,65 @@ function walkPiBranch( return { entryCount: visited.size, userEntryIds, reachedStop: current === stopAt }; } +interface PiRetainedCheckpoint { + readonly headId: string; + readonly forkEntryId?: string; +} + +interface PiHistoricalCheckpoint { + readonly file: string; + readonly listing: PiSessionListing; + readonly retained: PiRetainedCheckpoint; +} + +function piRetainedCheckpoint( + listing: PiSessionListing, + targetId: string, + completedAt: number | undefined, +): PiRetainedCheckpoint | undefined { + const walk = walkPiBranch(listing.entries, listing.leafId, targetId); + if (listing.leafId === null || walk?.reachedStop !== true || !listing.entries.has(targetId)) + return undefined; + // An extension can leave later prompts in the source. Keep steers within the retained turn. + for (const id of [...walk.userEntryIds].reverse()) { + const entry = listing.entries.get(id); + if (entry?.timestamp == null || completedAt === undefined) return undefined; + if (entry.timestamp >= completedAt) + return entry.parentId === null ? undefined : { headId: entry.parentId, forkEntryId: id }; + } + return { headId: listing.leafId }; +} + +// Pi's fork drops label entries from the copied path and re-adds them with new ids at the leaf. +function piSameHistory( + a: PiSessionListing, + aHead: string | null, + b: PiSessionListing, + bHead: string | null, +): boolean { + const aPath = piContentPath(a, aHead); + const bPath = piContentPath(b, bHead); + return ( + aPath !== null && + bPath !== null && + aPath.length === bPath.length && + aPath.every((id, index) => id === bPath[index]) + ); +} + +function piContentPath(listing: PiSessionListing, headId: string | null): Array | null { + const path: Array = []; + const visited = new Set(); + for (let id = headId; id !== null;) { + const entry = listing.entries.get(id); + if (entry === undefined || visited.has(id)) return null; + visited.add(id); + if (!entry.isLabel) path.push(id); + id = entry.parentId; + } + return path; +} + type PiForkBoundary = | { readonly type: "entry"; diff --git a/packages/provider-pi/src/server/rollback.test.ts b/packages/provider-pi/src/server/rollback.test.ts index a742af314d50..1943eea0afca 100644 --- a/packages/provider-pi/src/server/rollback.test.ts +++ b/packages/provider-pi/src/server/rollback.test.ts @@ -72,9 +72,12 @@ it.effect.each([ "checkpoint inherited by a prior fork", "repeated rollback after a handoff", "handoff prompt left in the source", + "a checkpoint recorded before upgrading, followed by a session switch", "switch timed out after attaching", ] as const)("restores exactly the retained Pi history for %s", (scenario) => Effect.gen(function* () { + const repro = + scenario === "a checkpoint recorded before upgrading, followed by a session switch"; const fs = yield* FileSystem.FileSystem; const dir = yield* fs.makeTempDirectoryScoped(); const oldFile = `${dir}/old.jsonl`; @@ -215,10 +218,10 @@ it.effect.each([ nativeTurnRef: ordinal === 3 && scenario === "command-only handoff" ? null - : ordinal === 3 && scenario === "uncaptured handoff" + : ordinal === 3 && (scenario === "uncaptured handoff" || repro) ? ref("uncaptured", "weak") : ref(`u${ordinal}`), - ...(scenario === "legacy turns" + ...(scenario === "legacy turns" || (repro && ordinal < 3) ? {} : { nativeThreadRef: ref( @@ -254,6 +257,15 @@ it.effect.each([ assert.deepEqual(sessionRequests, [{ type: "switch_session", file: oldFile }]); return; } + if (repro) { + const restored = yield* rollback.pipe(Effect.result); + assert.equal(restored._tag, "Success"); + assert.deepEqual( + sessions.get(liveFile)?.map(({ id }) => id), + ["u1", "a1", "u2", "steer", "a2"], + ); + return; + } const restored = yield* rollback; assert.equal( restored.providerThread.nativeThreadRef?.nativeId,