diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 39543e9a5f26..a297d92a444d 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1232,6 +1232,8 @@ export const OrchestrationV2ProviderTurn = Schema.Struct({ nodeId: NodeId, runAttemptId: Schema.NullOr(RunAttemptId), nativeTurnRef: Schema.NullOr(OrchestrationV2ProviderRef), + /** The native session that held this turn, when a provider can move a thread between sessions. */ + nativeThreadRef: Schema.optional(OrchestrationV2ProviderRef), ordinal: PositiveInt, status: Schema.Literals([ "pending", diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index a1dd152e662e..1a50c56cce69 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -164,6 +164,7 @@ interface FakePi { readonly queueEntries: (data: unknown) => void; readonly queueMessages: (data: unknown) => void; readonly vetoNextSwitch: () => void; + readonly failNextFork: () => void; readonly queueState: (data: Record) => void; readonly setStreaming: (streaming: boolean) => void; readonly setCompacting: (compacting: boolean) => void; @@ -237,6 +238,7 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { let failStateAfter: number | null = null; let failThinking = false; let vetoSwitch = false; + let failFork = false; let vetoNewSession = false; let deferredLifecycle: string | undefined; let sessionFile = FAKE_SESSION_FILE; @@ -354,6 +356,10 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { case "get_session_stats": return { ...base, data: statsQueue.shift() ?? {} }; case "fork": + if (failFork) { + failFork = false; + return { ...base, success: false, error: "Invalid entry ID for forking" }; + } serviceTier = null; return { ...base, data: { text: "Hello pi", cancelled: false } }; case "clear_queue": @@ -498,6 +504,9 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { vetoNextSwitch: () => { vetoSwitch = true; }, + failNextFork: () => { + failFork = true; + }, queueState: (data) => stateQueue.push(data), setStreaming: (streaming) => { isStreaming = streaming; @@ -2806,6 +2815,16 @@ describe("PiAdapterV2", () => { yield* fake.emit({ type: "agent_start" }); yield* fake.emit({ type: "agent_end", messages: [], willRetry: false }); yield* fake.emit({ type: "agent_settled" }); + const completed = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.equal( + completed.type === "provider_turn.updated" + ? completed.providerTurn.nativeThreadRef?.nativeId + : undefined, + childFile, + ); const idle = yield* takeEvent( (event) => event.type === "provider_thread.updated" && event.providerThread.status === "idle", @@ -2965,9 +2984,21 @@ describe("PiAdapterV2", () => { ); it.effect.each([ - { historical: false, label: "the latest turn" }, - { historical: true, label: "a historical turn" }, - ])("natively forks $label into an independent session", ({ historical }) => + { historical: false, moved: false, split: false, label: "the latest turn" }, + { historical: true, moved: false, split: false, label: "a historical turn" }, + { + historical: true, + moved: true, + split: false, + label: "a historical turn after a session switch", + }, + { + historical: true, + moved: true, + split: true, + label: "the last turn before a switch to a fresh session", + }, + ])("natively forks $label into an independent session", ({ historical, moved, split }) => Effect.gen(function* () { const fake = yield* makeFakePi; const forkFake = yield* makeFakePi; @@ -2984,12 +3015,22 @@ describe("PiAdapterV2", () => { modelSelection: modelSelection("default"), runtimePolicy, }); + const freshSession = { + driver: PI_PROVIDER, + nativeId: "/fake/new-session.jsonl", + strength: "strong", + } as const; const turn = (ordinal: number): OrchestrationV2ProviderTurn => ({ id: ProviderTurnId.make(`turn-${ordinal}`), providerThreadId: source.id, nodeId: NodeId.make(`node-${ordinal}`), runAttemptId: null, nativeTurnRef: { driver: PI_PROVIDER, nativeId: `u${ordinal}`, strength: "strong" }, + ...(split && ordinal === 2 + ? { nativeThreadRef: freshSession } + : moved && source.nativeThreadRef !== null + ? { nativeThreadRef: source.nativeThreadRef } + : {}), ordinal, status: "completed", startedAt: null, @@ -3005,7 +3046,7 @@ describe("PiAdapterV2", () => { fake.queueState({ sessionFile: forkFile }); const target = ThreadId.make("fork-target"); const forked = yield* runtime.forkThread({ - sourceProviderThread: source, + sourceProviderThread: moved ? { ...source, nativeThreadRef: freshSession } : source, sourceProviderTurns: historical ? [turn(1), turn(2)] : [turn(1)], providerTurnId: turn(1).id, targetThreadId: target, @@ -3025,7 +3066,7 @@ describe("PiAdapterV2", () => { .allRequests() .filter((request) => request.type === "fork") .map((request) => request.entryId), - historical ? ["u2"] : [], + historical && !split ? ["u2"] : [], ); assert.isFalse( fake.allRequests().some((request) => request.type === "fork" || request.type === "clone"), @@ -3061,6 +3102,64 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("recovers a historical Pi fork recorded before turns stored the session file", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped(); + const oldFile = `${dir}/original.jsonl`; + const unrelatedFile = `${dir}/unrelated.jsonl`; + const currentFile = `${dir}/current.jsonl`; + const header = { type: "session", version: 3 }; + const writeSession = (file: string, entries: ReadonlyArray) => + fs.writeFileString( + file, + [header, ...entries].map((entry) => encodeJsonLine(entry)).join("\n") + "\n", + ); + yield* writeSession(oldFile, UNCAPTURED_TURN_TREE.entries); + yield* writeSession(unrelatedFile, [ + sessionMessage("u1", null, "user", 10), + sessionMessage("u2", null, "user", 110), + ]); + yield* writeSession(currentFile, [sessionMessage("new", null, "user", 120)]); + + const fake = yield* makeFakePi; + const forkFake = yield* makeFakePi; + const { runtime } = yield* openRuntime(fake, "default", THREAD_ID, SESSION_ID, forkFake); + const source = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + const forkFile = `${dir}/forked.jsonl`; + forkFake.failNextFork(); + forkFake.queueState({ sessionFile: forkFile }); + fake.queueState({ sessionFile: forkFile }); + const [target, boundary] = uncapturedTurns(source.id, { + startedAt: 100, + completedAt: 145, + }); + if (target === undefined || boundary === undefined) throw new Error("missing fork turns"); + const forked = yield* runtime.forkThread({ + sourceProviderThread: { + ...source, + nativeThreadRef: { driver: PI_PROVIDER, nativeId: currentFile, strength: "strong" }, + }, + sourceProviderTurns: [ + target, + { + ...boundary, + nativeTurnRef: { driver: PI_PROVIDER, nativeId: "u2", strength: "strong" }, + }, + ], + providerTurnId: target.id, + targetThreadId: ThreadId.make("fork-target"), + }); + const args = forkFake.lastSpawn().args; + assert.equal(args[args.indexOf("--fork") + 1], oldFile); + assert.equal(forked.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 1e80b48d7fb9..9374419556bf 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -520,7 +520,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( Effect.orElseSucceed(() => undefined), ); if (header === undefined) return true; - const sessionCwd = recordString(Option.getOrUndefined(decodeSessionHeader(header)), "cwd"); + const sessionCwd = recordString(Option.getOrUndefined(decodeSessionLine(header)), "cwd"); if (sessionCwd === undefined || sessionCwd === cwd) return true; const realCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); return sessionCwd === realCwd; @@ -2067,6 +2067,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ...(treeRefs === null || treeRefs.nativeTurnRef === undefined ? {} : { nativeTurnRef: treeRefs.nativeTurnRef }), + ...(state.providerThread.nativeThreadRef === null + ? {} + : { nativeThreadRef: state.providerThread.nativeThreadRef }), status: interrupted ? "interrupted" : failure !== null ? "failed" : "completed", completedAt, ...(tokenUsage === undefined ? {} : { tokenUsage }), @@ -2936,6 +2939,68 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)); }); + // 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* ( + currentFile: string, + boundary: Extract, + ) { + const targetId = piTurnEntryId(boundary.target); + const startedAt = boundary.target?.startedAt; + const completedAt = boundary.target?.completedAt; + const boundaryEnd = boundary.turn.completedAt; + if ( + targetId === undefined || + startedAt == null || + completedAt == null || + boundaryEnd === null + ) { + return undefined; + } + 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; + const entries = new Map(); + let leafId: string | null = null; + const readable = yield* fileSystem.stream(file).pipe( + Stream.decodeText(), + Stream.splitLines, + Stream.runForEach((line) => + Effect.sync(() => { + const entry = readPiSessionEntry(Option.getOrUndefined(decodeSessionLine(line))); + if (entry === null) return; + const [id, value] = entry; + entries.set(id, value); + leafId = id; + }), + ), + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + if ( + readable && + piUserEntryInWindow(entries.get(targetId), from, between) && + piUserEntryInWindow(entries.get(boundary.entryId), between, to) && + walkPiBranch(entries, leafId, boundary.entryId)?.reachedStop === true && + walkPiBranch(entries, boundary.entryId, targetId)?.reachedStop === true + ) { + return file; + } + } + return undefined; + }); + const sessionFileInCwd = Effect.fnUntraced(function* ( sessionFile: string, providerThreadCreatedAt: DateTime.Utc, @@ -3354,6 +3419,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( nodeId: turnInput.rootNodeId, runAttemptId: turnInput.attemptId, nativeTurnRef: providerRef(syntheticNativeTurnId, "weak"), + ...(state.providerThread.nativeThreadRef === null + ? {} + : { nativeThreadRef: state.providerThread.nativeThreadRef }), ordinal: turnInput.providerTurnOrdinal, status: "running", startedAt, @@ -3912,8 +3980,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return yield* protocolError("Cannot fork while a Pi turn is active"); } const source = forkInput.sourceProviderThread; - const sourceFile = source.nativeThreadRef?.nativeId; - if (sourceFile == null) + const currentFile = source.nativeThreadRef?.nativeId; + if (currentFile == null) return yield* protocolError("Pi fork source has no session file"); const sourceTurns = (forkInput.sourceProviderTurns ?? []).filter( (turn) => turn.providerThreadId === source.id, @@ -3922,14 +3990,39 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if (forkInput.providerTurnId !== undefined && target === undefined) { return yield* protocolError("Pi fork target turn is missing"); } + const targetFile = target?.nativeThreadRef?.nativeId ?? undefined; const boundary: PiForkBoundary = target === undefined ? { type: "nothing" } : piForkBoundary({ target: { type: "provider_turn", providerTurn: target }, providerThreadTurns: sourceTurns, + sessionFile: targetFile, }); - const nativeId = yield* forkSessionIntoCwd(sourceFile, boundary, source.createdAt); + const boundaryFile = + boundary.type === "nothing" ? undefined : boundary.turn.nativeThreadRef?.nativeId; + const sourceFile = targetFile ?? boundaryFile ?? currentFile; + const nativeId = yield* forkSessionIntoCwd(sourceFile, boundary, source.createdAt).pipe( + Effect.catchTags({ + PiRpcError: (error) => { + if ( + boundary.type !== "entry" || + boundaryFile != null || + error.operation !== "fork" || + error.detail !== "Invalid entry ID for forking" + ) { + return Effect.fail(error); + } + return findHistoricalForkSession(currentFile, boundary).pipe( + Effect.flatMap((file) => + file === undefined + ? Effect.fail(error) + : forkSessionIntoCwd(file, boundary, source.createdAt), + ), + ); + }, + }), + ); const now = yield* DateTime.now; return yield* registerThread( { @@ -3983,7 +4076,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( }); }); -const decodeSessionHeader = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); +const decodeSessionLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); interface PiSessionEntry { readonly parentId: string | null; @@ -4006,15 +4099,24 @@ function piSessionListing(data: unknown): PiSessionListing | null { } function piSessionEntries(entries: unknown): ReadonlyMap | null { - const byId = new Map(); 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; - const timestamp = recordString(entry, "timestamp"); - byId.set(id, { + const byId = new Map(); + for (const raw of entries) { + const entry = readPiSessionEntry(raw); + if (entry === null || byId.has(entry[0])) return null; + byId.set(...entry); + } + return byId; +} + +function readPiSessionEntry(entry: unknown): [string, PiSessionEntry] | null { + const id = recordString(entry, "id"); + const parentId = recordField(entry, "parentId"); + if (id === undefined || (parentId !== null && typeof parentId !== "string")) return null; + const timestamp = recordString(entry, "timestamp"); + return [ + id, + { parentId, isUserMessage: recordField(entry, "type") === "message" && @@ -4023,9 +4125,22 @@ function piSessionEntries(entries: unknown): ReadonlyMap timestamp === undefined ? null : Option.getOrNull(Option.map(DateTime.make(timestamp), DateTime.toEpochMillis)), - }); - } - return byId; + }, + ]; +} + +function piUserEntryInWindow(entry: PiSessionEntry | undefined, from: number, to: number): boolean { + return ( + entry?.isUserMessage === true && + entry.timestamp !== null && + entry.timestamp >= from && + entry.timestamp <= to + ); +} + +function piTurnEntryId(turn: OrchestrationV2ProviderTurn | null | undefined): string | undefined { + const ref = turn?.nativeTurnRef; + return ref?.strength === "strong" ? (ref.nativeId ?? undefined) : undefined; } function walkPiBranch( @@ -4052,7 +4167,12 @@ function walkPiBranch( } type PiForkBoundary = - | { readonly type: "entry"; readonly entryId: string } + | { + readonly type: "entry"; + readonly entryId: string; + readonly turn: OrchestrationV2ProviderTurn; + readonly target: OrchestrationV2ProviderTurn | null; + } | { readonly type: "nothing" } | { readonly type: "uncaptured"; @@ -4070,15 +4190,22 @@ function piForkBoundary(input: { | { readonly type: "thread_start" } | { readonly type: "provider_turn"; readonly providerTurn: OrchestrationV2ProviderTurn }; readonly providerThreadTurns: ReadonlyArray; + /** Only turns recorded in this session can bound a fork from it. */ + readonly sessionFile?: string | undefined; }): PiForkBoundary { const target = input.target.type === "thread_start" ? null : input.target.providerTurn; const boundary = input.providerThreadTurns - .filter((turn) => turn.ordinal > (target?.ordinal ?? 0) && turn.nativeTurnRef !== null) + .filter( + (turn) => + turn.ordinal > (target?.ordinal ?? 0) && + turn.nativeTurnRef !== null && + (input.sessionFile === undefined || turn.nativeThreadRef?.nativeId === input.sessionFile), + ) .sort((a, b) => a.ordinal - b.ordinal)[0]; const ref = boundary?.nativeTurnRef; if (boundary === undefined || ref == null) return { type: "nothing" }; return ref.strength === "strong" && ref.nativeId !== null - ? { type: "entry", entryId: ref.nativeId } + ? { type: "entry", entryId: ref.nativeId, turn: boundary, target } : { type: "uncaptured", turn: boundary, target }; }