diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 5565f456677f..2e4fe429ce2d 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -3254,6 +3254,168 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect.each([ + "equivalent copies with a discarded prompt", + "running legacy boundary with a colliding entry ID", + "rollback across a handoff", + "conflicting retained branches", + "adopted wake in the same session", + "missing timing in the same session", + "assistant continuation after the selected turn", + ] as const)("recovers Pi history across a handoff for %s", (scenario) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped(); + const oldFile = `${dir}/original.jsonl`; + const copyFile = `${dir}/a-copy.jsonl`; + const currentFile = `${dir}/current.jsonl`; + const forkFile = `${dir}/result.jsonl`; + const writeSession = (file: string, entries: ReadonlyArray) => + fs.writeFileString( + file, + [{ type: "session", version: 3 }, ...entries] + .map((entry) => encodeJsonLine(entry)) + .join("\n") + "\n", + ); + const legacyBoundary = scenario === "running legacy boundary with a colliding entry ID"; + const trailingPrompt = scenario === "equivalent copies with a discarded prompt"; + const ambiguous = scenario === "conflicting retained branches"; + const adoptedWake = scenario === "adopted wake in the same session"; + const missingTiming = scenario === "missing timing in the same session"; + const sameSession = adoptedWake || missingTiming; + const lateOutput = scenario === "assistant continuation after the selected turn"; + const newerEntries = sameSession + ? [ + ...TURN_ONE_ENTRIES.map((entry) => + missingTiming && entry.id === "u1" ? { ...entry, timestamp: undefined } : entry, + ), + sessionMessage("u2", "a1b", "user", 110), + ] + : legacyBoundary + ? [ + sessionMessage("u1", null, "user", 90), + { ...sessionMessage("u2", "u1", "user", 110), timestamp: undefined }, + ] + : [sessionMessage("u2", null, "user", 110)]; + yield* writeSession(currentFile, newerEntries); + yield* writeSession( + oldFile, + lateOutput + ? [...TURN_ONE_ENTRIES, sessionMessage("late-reply", "a1b", "assistant", 60)] + : trailingPrompt + ? [...TURN_ONE_ENTRIES, sessionMessage("discarded", "a1b", "user", 60)] + : TURN_ONE_ENTRIES, + ); + if (trailingPrompt) + yield* writeSession(copyFile, [ + ...TURN_ONE_ENTRIES, + { + type: "model_change", + id: "changed-model", + parentId: "a1b", + timestamp: DateTime.formatIso(at(55)), + }, + sessionMessage("copy-prompt", "changed-model", "user", 60), + ]); + if (ambiguous) + yield* writeSession(copyFile, [ + ...TURN_ONE_ENTRIES, + sessionMessage("other-reply", "a1b", "assistant", 45), + ]); + + const fake = yield* makeFakePi; + const forkFake = yield* makeFakePi; + const { runtime } = yield* openRuntime(fake, "default", THREAD_ID, SESSION_ID, forkFake); + fake.queueState({ sessionFile: currentFile }); + const source = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + const [firstTurn, boundary] = uncapturedTurns(source.id, { + startedAt: 100, + completedAt: 150, + }); + if (firstTurn === undefined || boundary === undefined) throw new Error("missing turns"); + const target = { + ...firstTurn, + startedAt: adoptedWake ? at(15) : firstTurn.startedAt, + completedAt: missingTiming ? null : firstTurn.completedAt, + }; + const turns = [ + target, + { + ...boundary, + nativeTurnRef: { driver: PI_PROVIDER, nativeId: "u2", strength: "strong" as const }, + ...(legacyBoundary + ? { status: "running" as const, completedAt: null } + : { + nativeThreadRef: { + driver: PI_PROVIDER, + nativeId: currentFile, + strength: "strong" as const, + }, + }), + }, + ]; + if (scenario === "rollback across a handoff") { + fake.queueState({ sessionFile: oldFile }); + fake.queueState({ sessionFile: oldFile }); + const retained = { entries: TURN_ONE_ENTRIES, leafId: "a1b" }; + fake.queueEntries(retained); + fake.queueEntries(retained); + const result = yield* runtime.rollbackThread({ + providerThread: source, + providerThreadTurns: turns, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("checkpoint"), + appRunOrdinal: target.ordinal, + providerTurn: target, + }, + }); + assert.equal(result.providerThread.nativeThreadRef?.nativeId, oldFile); + assert.equal(result.providerThread.nativeConversationHeadRef?.nativeId, "a1b"); + assert.deepEqual( + fake + .allRequests() + .filter((request) => request.type === "switch_session") + .map((request) => request.sessionPath), + [oldFile], + ); + assert.isFalse(fake.allRequests().some((request) => request.type === "fork")); + return; + } + + forkFake.queueState({ sessionFile: forkFile }); + fake.queueState({ sessionFile: forkFile }); + const result = yield* runtime + .forkThread({ + sourceProviderThread: source, + sourceProviderTurns: turns, + providerTurnId: target.id, + targetThreadId: ThreadId.make("fork-target"), + }) + .pipe(Effect.result); + if (ambiguous || lateOutput) { + assert.equal(result._tag, "Failure"); + assert.isFalse(forkFake.allRequests().some((request) => request.type === "fork")); + return; + } + if (result._tag === "Failure") return yield* result.failure; + const args = forkFake.lastSpawn().args; + assert.equal(args[args.indexOf("--fork") + 1], sameSession ? currentFile : oldFile); + assert.deepEqual( + forkFake + .allRequests() + .filter((request) => request.type === "fork") + .map((request) => request.entryId), + sameSession ? ["u2"] : trailingPrompt ? ["discarded"] : [], + ); + assert.equal(result.success.nativeThreadRef?.nativeId, forkFile); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("natively forks before 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..be22df147fe2 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3042,6 +3042,19 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return readable ? { entries, leafId } : null; }); + const siblingSessionFiles = Effect.fnUntraced(function* (currentFile: string) { + const dir = path.dirname(currentFile); + 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)) + .filter((file) => file !== currentFile) + .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,17 +3076,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(); - for (const file of files) { - if (file === currentFile) continue; + for (const file of yield* siblingSessionFiles(currentFile)) { const listing = yield* readSessionFile(file); if ( listing !== null && @@ -3088,6 +3091,58 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return undefined; }); + const recoverLegacyHandoff = Effect.fnUntraced(function* ( + sourceFile: string, + boundary: Extract, + source: PiSessionListing | null, + ) { + const targetId = piTurnEntryId(boundary.target); + const startedAt = boundary.target?.startedAt; + const completedAt = boundary.target?.completedAt; + if (targetId === undefined || source === null || !source.entries.has(boundary.entryId)) + return undefined; + + const unresolved = () => protocolError("Pi fork target was not found in a session"); + const sourcePrompt = source.entries.get(targetId); + if ( + sourcePrompt?.isUserMessage === true && + (completedAt == null || + sourcePrompt.timestamp === null || + sourcePrompt.timestamp <= DateTime.toEpochMillis(completedAt)) && + walkPiBranch(source.entries, boundary.entryId, targetId)?.reachedStop === true + ) + return undefined; + + if (startedAt == null || completedAt == null) return yield* unresolved(); + const from = DateTime.toEpochMillis(startedAt); + const to = DateTime.toEpochMillis(completedAt); + // Pi accepts a fork before the first prompt in a new session even when the + // selected turn is absent. Find its retained branch before asking Pi to fork. + let recovered: + | { file: string; boundary: PiForkBoundary; history: ReadonlyArray } + | undefined; + for (const file of yield* siblingSessionFiles(sourceFile)) { + const listing = yield* readSessionFile(file); + if (listing === null || !piUserEntryInWindow(listing.entries.get(targetId), from, to)) + continue; + const retained = piLegacyRetainedBranch(listing, targetId, to); + if (retained === undefined) continue; + const { history, entryId } = retained; + if ( + recovered !== undefined && + (history.length !== recovered.history.length || + recovered.history.some((id, index) => id !== history[index])) + ) + return yield* unresolved(); + recovered ??= { + file, + boundary: entryId === undefined ? { type: "nothing" } : { ...boundary, entryId }, + history, + }; + } + return recovered ?? (yield* unresolved()); + }); + const sessionFileInCwd = Effect.fnUntraced(function* ( sessionFile: string, providerThreadCreatedAt: DateTime.Utc, @@ -4031,19 +4086,29 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( boundary = piForkBoundary({ ...rollbackInput, sessionFile: targetFile }); } } + const candidateFile = sourceFile ?? currentFile; if ( - sourceFile == null && - currentFile != null && - boundary.type === "entry" && - piTurnEntryId(boundary.target) !== undefined && - boundary.target?.startedAt != null && - boundary.target.completedAt !== null && - boundary.turn.completedAt !== null + targetFile === undefined && + candidateFile != null && + boundary.type === "entry" ) { // The persisted file avoids sending the whole tree over RPC before forking. - const live = yield* readSessionFile(path.resolve(cwd, currentFile)); - if (live !== null && !live.entries.has(boundary.entryId)) { - sourceFile = yield* findHistoricalForkSession(currentFile, boundary); + const file = path.resolve(cwd, candidateFile); + const listing = yield* readSessionFile(file); + const recovered = yield* recoverLegacyHandoff(file, boundary, listing); + if (recovered !== undefined) { + sourceFile = recovered.file; + boundary = recovered.boundary; + } else if ( + sourceFile == null && + listing !== null && + !listing.entries.has(boundary.entryId) && + targetId !== undefined && + target?.startedAt != null && + target.completedAt !== null && + boundary.turn.completedAt !== null + ) { + sourceFile = yield* findHistoricalForkSession(file, boundary); if (sourceFile === undefined) return yield* protocolError("Pi rollback entry was not found in a session"); } @@ -4224,10 +4289,24 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const boundaryFile = boundary.type === "nothing" ? undefined : boundary.turn.nativeThreadRef?.nativeId; const sourceFile = targetFile ?? boundaryFile ?? currentFile; - const nativeId = yield* forkSessionIntoCwd(sourceFile, boundary, source.createdAt).pipe( + const resolvedSourceFile = path.resolve(cwd, sourceFile); + const recovered = + targetFile === undefined && boundary.type === "entry" + ? yield* readSessionFile(resolvedSourceFile).pipe( + Effect.flatMap((listing) => + recoverLegacyHandoff(resolvedSourceFile, boundary, listing), + ), + ) + : undefined; + const nativeId = yield* forkSessionIntoCwd( + recovered?.file ?? sourceFile, + recovered?.boundary ?? boundary, + source.createdAt, + ).pipe( Effect.catchTags({ PiRpcError: (error) => { if ( + recovered !== undefined || boundary.type !== "entry" || boundaryFile != null || error.operation !== "fork" || @@ -4303,6 +4382,7 @@ const decodeSessionLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schem interface PiSessionEntry { readonly parentId: string | null; readonly isUserMessage: boolean; + readonly isSessionMetadata: boolean; /** Pi's `timestamp` as epoch milliseconds; null when missing or unparsable. */ readonly timestamp: number | null; } @@ -4336,13 +4416,18 @@ function readPiSessionEntry(entry: unknown): [string, PiSessionEntry] | null { const parentId = recordField(entry, "parentId"); if (id === undefined || (parentId !== null && typeof parentId !== "string")) return null; const timestamp = recordString(entry, "timestamp"); + const type = recordString(entry, "type"); return [ id, { parentId, isUserMessage: - recordField(entry, "type") === "message" && - recordString(recordField(entry, "message"), "role") === "user", + type === "message" && recordString(recordField(entry, "message"), "role") === "user", + isSessionMetadata: + type === "model_change" || + type === "thinking_level_change" || + type === "label" || + type === "session_info", timestamp: timestamp === undefined ? null @@ -4371,6 +4456,7 @@ function walkPiBranch( stopAt: string | null, ): { readonly entryCount: number; + readonly entryIds: ReadonlySet; readonly userEntryIds: ReadonlyArray; readonly reachedStop: boolean; } | null { @@ -4385,7 +4471,30 @@ function walkPiBranch( if (entry.isUserMessage) userEntryIds.push(current); current = entry.parentId; } - return { entryCount: visited.size, userEntryIds, reachedStop: current === stopAt }; + return { + entryCount: visited.size, + entryIds: visited, + userEntryIds, + reachedStop: current === stopAt, + }; +} + +function piLegacyRetainedBranch(listing: PiSessionListing, targetId: string, completedAt: number) { + const afterTarget = walkPiBranch(listing.entries, listing.leafId, targetId); + if (afterTarget?.reachedStop !== true) return undefined; + const throughTarget = walkPiBranch(listing.entries, targetId, null); + if (throughTarget?.reachedStop !== true) return undefined; + const history = [...throughTarget.entryIds].reverse(); + for (const id of [...afterTarget.entryIds].reverse()) { + const entry = listing.entries.get(id); + if (entry?.timestamp == null) return undefined; + if (entry.isUserMessage && entry.timestamp >= completedAt) return { history, entryId: id }; + if (entry.timestamp <= completedAt) history.push(id); + // Pi only forks before user messages. Later settings can stay in the file, + // but later conversation entries make this branch unsafe to recover. + else if (!entry.isSessionMetadata) return undefined; + } + return { history, entryId: undefined }; } type PiForkBoundary = diff --git a/packages/provider-pi/src/server/rollback.test.ts b/packages/provider-pi/src/server/rollback.test.ts index a742af314d50..0d7942285101 100644 --- a/packages/provider-pi/src/server/rollback.test.ts +++ b/packages/provider-pi/src/server/rollback.test.ts @@ -24,7 +24,9 @@ import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import { expect } from "vite-plus/test"; import { makePiAdapterV2, PI_PROVIDER } from "./adapter.ts"; const layerTest = Layer.mergeAll( @@ -64,6 +66,7 @@ const decodeRequest = Schema.decodeUnknownSync( ); it.effect.each([ + "fork across a legacy session switch", "earlier checkpoint", "last checkpoint", "uncaptured handoff", @@ -112,65 +115,76 @@ it.effect.each([ ); } - const output = yield* Queue.unbounded(); const switchApplied = yield* Deferred.make(); const sessionRequests: { readonly type: string; readonly file: string }[] = []; - let liveFile = currentFile; - let pending = ""; - const encoder = new TextEncoder(); - const decoder = new TextDecoder(); - const stdin = Sink.forEach((chunk: Uint8Array) => + let attachedFile = currentFile; + const spawner = ChildProcessSpawner.make((command) => Effect.gen(function* () { - const lines = (pending + decoder.decode(chunk, { stream: true })).split("\n"); - pending = lines.pop() ?? ""; - for (const line of lines) { - const request = decodeRequest(line); - const entries = sessions.get(liveFile) ?? []; - let data: unknown = {}; - let error: string | undefined; - if (request.type === "get_state") data = { sessionFile: liveFile }; - if (request.type === "get_entries") - data = { entries, leafId: entries.at(-1)?.id ?? null }; - if (request.type === "switch_session") { - if (request.sessionPath !== undefined && sessions.has(request.sessionPath)) { - liveFile = request.sessionPath; - sessionRequests.push({ type: "switch_session", file: liveFile }); - if (scenario === "switch timed out after attaching") { - yield* Deferred.succeed(switchApplied, undefined); - continue; + const output = yield* Queue.unbounded(); + const args = ChildProcess.isStandardCommand(command) ? command.args.map(String) : []; + const sourceFile = args.includes("--fork") ? args[args.indexOf("--fork") + 1] : undefined; + const cloneFile = `${dir}/clone.jsonl`; + let liveFile = currentFile; + if (sourceFile !== undefined) { + sessions.set(cloneFile, [...(sessions.get(sourceFile) ?? [])]); + liveFile = cloneFile; + } + let pending = ""; + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + const stdin = Sink.forEach((chunk: Uint8Array) => + Effect.gen(function* () { + const lines = (pending + decoder.decode(chunk, { stream: true })).split("\n"); + pending = lines.pop() ?? ""; + for (const line of lines) { + const request = decodeRequest(line); + const entries = sessions.get(liveFile) ?? []; + let data: unknown = {}; + let error: string | undefined; + if (request.type === "get_state") data = { sessionFile: liveFile }; + if (request.type === "get_entries") + data = { entries, leafId: entries.at(-1)?.id ?? null }; + if (request.type === "switch_session") { + if (request.sessionPath !== undefined && sessions.has(request.sessionPath)) { + liveFile = request.sessionPath; + sessionRequests.push({ type: "switch_session", file: liveFile }); + if (scenario === "switch timed out after attaching") { + attachedFile = liveFile; + yield* Deferred.succeed(switchApplied, undefined); + continue; + } + data = { cancelled: false }; + } else error = "Session not found"; + } + if (request.type === "fork") { + const index = entries.findIndex(({ id }) => id === request.entryId); + if (index === -1) error = "Invalid entry ID for forking"; + else { + sessionRequests.push({ type: "fork", file: liveFile }); + const branchFile = + sourceFile === undefined ? forkedFile : `${dir}/clone-branch.jsonl`; + sessions.set(branchFile, entries.slice(0, index)); + liveFile = branchFile; + data = { cancelled: false }; + } } - data = { cancelled: false }; - } else error = "Session not found"; - } - if (request.type === "fork") { - const index = entries.findIndex(({ id }) => id === request.entryId); - if (index === -1) error = "Invalid entry ID for forking"; - else { - sessionRequests.push({ type: "fork", file: liveFile }); - sessions.set(forkedFile, entries.slice(0, index)); - liveFile = forkedFile; - data = { cancelled: false }; + yield* Queue.offer( + output, + encoder.encode( + JSON.stringify({ + type: "response", + id: request.id, + command: request.type, + success: error === undefined, + data, + error, + }) + "\n", + ), + ); } - } - yield* Queue.offer( - output, - encoder.encode( - JSON.stringify({ - type: "response", - id: request.id, - command: request.type, - success: error === undefined, - data, - error, - }) + "\n", - ), - ); - } - }), - ); - const spawner = ChildProcessSpawner.make(() => - Effect.succeed( - ChildProcessSpawner.makeHandle({ + }), + ); + return ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(999_999_999), exitCode: Effect.never, isRunning: Effect.succeed(true), @@ -182,8 +196,8 @@ it.effect.each([ all: Stream.empty, getInputFd: () => Sink.drain, getOutputFd: () => Stream.empty, - }), - ), + }); + }), ); const instanceId = ProviderInstanceId.make("pi"); const adapter = yield* makePiAdapterV2({ @@ -218,7 +232,8 @@ it.effect.each([ : ordinal === 3 && scenario === "uncaptured handoff" ? ref("uncaptured", "weak") : ref(`u${ordinal}`), - ...(scenario === "legacy turns" + ...(scenario === "legacy turns" || + (scenario === "fork across a legacy session switch" && ordinal < 3) ? {} : { nativeThreadRef: ref( @@ -233,6 +248,30 @@ it.effect.each([ ); const shouldFork = scenario === "earlier checkpoint" || scenario === "legacy turns"; const target = turns[shouldFork ? 0 : 1]!; + if (scenario === "fork across a legacy session switch") { + const targetThreadId = ThreadId.make("pi-fork"); + const targetRuntime = yield* adapter.openSession({ + threadId: targetThreadId, + providerSessionId: ProviderSessionId.make("pi-fork"), + modelSelection, + runtimePolicy, + }); + yield* targetRuntime.events.pipe(Stream.runDrain, Effect.forkScoped); + const forked = yield* targetRuntime.forkThread({ + sourceProviderThread: providerThread, + sourceProviderTurns: turns, + providerTurnId: target.id, + targetThreadId, + }); + expect(sessions.get(forked.nativeThreadRef?.nativeId ?? "")?.map(({ id }) => id)).toEqual([ + "u1", + "a1", + "u2", + "steer", + "a2", + ]); + return; + } const rollback = runtime.rollbackThread({ providerThread, target: { @@ -246,7 +285,7 @@ it.effect.each([ if (scenario === "switch timed out after attaching") { const attempt = yield* rollback.pipe(Effect.result, Effect.forkChild); yield* Deferred.await(switchApplied); - assert.equal(liveFile, oldFile); + assert.equal(attachedFile, oldFile); yield* TestClock.adjust("61 seconds"); assert.equal((yield* Fiber.join(attempt))._tag, "Failure"); yield* Fiber.join(events); @@ -264,7 +303,7 @@ it.effect.each([ shouldFork ? "a1" : "a2", ); assert.deepEqual( - sessions.get(liveFile)?.map(({ id }) => id), + sessions.get(restored.providerThread.nativeThreadRef?.nativeId ?? "")?.map(({ id }) => id), shouldFork ? ["u1", "a1"] : ["u1", "a1", "u2", "steer", "a2"], ); assert.deepEqual(