1
import { mkdtemp, rm } from "node:fs/promises";2
import { tmpdir } from "node:os";3
import { join } from "node:path";4
import { type AssistantMessage, createModels, fauxAssistantMessage, type Message } from "@earendil-works/pi-ai";5
import { AssistantEntry, type Harness, LiveDoc, type TaskId } from "@earendil-works/pi-durable";6
import { afterEach, describe, expect, it } from "vitest";7
import { openNodeSqliteStorage } from "../src/storage/sqlite/node.ts";8
import { allEntries, type ChatSetup, chatSetup, openChat, textOf, unanswered, waitFor } from "./chat-support.ts";9
import { addSection } from "./harness-support.ts";10
import { context } from "./session-support.ts";11
import { aborted, deferred } from "./task-support.ts";13
const directories = new Set<string>();15
afterEach(async () => {16
for (const directory of directories) await rm(directory, { recursive: true, force: true });17
directories.clear();18
});20
async function sqlitePath(): Promise<string> {21
const directory = await mkdtemp(join(tmpdir(), "pi-durable-generation-"));22
directories.add(directory);23
return join(directory, "session.sqlite");24
}26
async function open(path: string, setup: ChatSetup) {27
return openChat(await openNodeSqliteStorage(path), setup);28
}30
async function runTaskId(harness: Harness): Promise<TaskId> {31
const live = await harness.snapshot(LiveDoc, 1 as never, context);32
return live!.run!.taskId;33
}35
async function checkpoint(harness: Harness, id: TaskId) {36
const record = await harness.getTask(id, context);37
return record?.state.status === "terminal" ? undefined : record?.state.checkpoint;38
}40
describe("generation recovery", () => {41
it("reruns preparation interrupted before its commit", async () => {42
const path = await sqlitePath();43
const setup = chatSetup();44
const reached = deferred();45
let block = true;46
addSection(setup.registry, "preamble", async (_input, ctx) => {47
if (block) {48
block = false;49
reached.resolve();50
await aborted(ctx.abortSignal!);51
}52
return "p";53
});54
setup.faux.setResponses([fauxAssistantMessage("answer")]);55
let opened = await open(path, setup);56
opened.harness.resume();57
const id = (await opened.root.submit({ type: "input", content: "hi" }, context)).id;58
await reached.promise;59
const taskId = await runTaskId(opened.harness);60
await opened.harness.close(context);62
opened = await open(path, setup);63
expect(await checkpoint(opened.harness, taskId)).toEqual({ phase: "prepare", attempt: 1 });64
opened.harness.resume();65
expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");66
expect((await allEntries(opened.root)).map((entry) => entry.kind)).toEqual([67
"pi.user",68
"pi.system",69
"pi.assistant",70
]);71
await opened.harness.close(context);72
});74
it("resends a request interrupted before any partial without repeating preparation", async () => {75
const path = await sqlitePath();76
const setup = chatSetup();77
addSection(setup.registry, "preamble", () => "p", { tag: false });78
const reached = deferred();79
const sent: string[][] = [];80
const timeouts: (number | undefined)[] = [];81
setup.faux.setResponses([82
async (_context, options) => {83
reached.resolve();84
return aborted(options!.signal!);85
},86
(request, options) => {87
sent.push(request.messages.map((message) => message.role));88
timeouts.push(options?.timeoutMs);89
return fauxAssistantMessage("answer");90
},91
]);92
let opened = await open(path, setup);93
setup.settings.stream = { timeoutMs: 1234 };94
opened.harness.resume();95
const id = (await opened.root.submit({ type: "input", content: "hi" }, context)).id;96
await reached.promise;97
const taskId = await runTaskId(opened.harness);98
await opened.harness.close(context);100
opened = await open(path, setup);101
expect(await checkpoint(opened.harness, taskId)).toMatchObject({102
phase: "request",103
attempt: 1,104
thinkingLevel: "off",105
streamOptions: { timeoutMs: 1234 },106
});107
// The resend uses the pinned request, not options changed after preparation.108
setup.settings.stream = { timeoutMs: 999 };109
expect(await opened.harness.snapshot(LiveDoc, opened.root.id, context)).toMatchObject({110
generation: { attempt: 1 },111
});112
opened.harness.resume();113
expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");114
expect(sent).toEqual([["system", "user"]]);115
expect(timeouts).toEqual([1234]);116
expect((await allEntries(opened.root)).map((entry) => entry.kind)).toEqual([117
"pi.user",118
"pi.system",119
"pi.assistant",120
]);121
await opened.harness.close(context);122
});124
it("converts a committed partial into an aborted entry and resends the same messages", async () => {125
const path = await sqlitePath();126
const slow = chatSetup({ tokensPerSecond: 20, tokenSize: { min: 1, max: 1 } });127
slow.faux.setResponses([fauxAssistantMessage("z".repeat(400))]);128
let opened = await open(path, slow);129
opened.harness.resume();130
const watch = (await opened.harness.watchDoc(LiveDoc, opened.root.id, context))!;131
let watched: string | undefined;132
watch.start(async (value) => {133
watched = textOf(value?.generation?.message as Message) ?? watched;134
});135
const id = (await opened.root.submit({ type: "input", content: "hi" }, context)).id;136
await waitFor(() => watched !== undefined);137
await opened.harness.close(context);139
const setup = chatSetup();140
const sent: string[][] = [];141
setup.faux.setResponses([142
(request) => {143
sent.push(request.messages.map((message) => message.role));144
return fauxAssistantMessage("answer");145
},146
]);147
opened = await open(path, setup);148
const stored = await opened.harness.snapshot(LiveDoc, opened.root.id, context);149
const partial = textOf(stored?.generation?.message as Message)!;150
// Everything observers saw before the crash is durable.151
expect(partial.startsWith(watched!)).toBe(true);152
opened.harness.resume();153
expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");154
expect(sent).toEqual([["user"]]);155
const entries = await allEntries(opened.root);156
expect(entries.map((entry) => entry.kind)).toEqual(["pi.user", "pi.assistant", "pi.assistant"]);157
const converted = entries[1]!.model![0] as AssistantMessage;158
expect(converted.stopReason).toBe("aborted");159
expect(textOf(converted)).toBe(partial);160
expect(await opened.harness.snapshot(LiveDoc, opened.root.id, context)).toEqual({});161
await opened.harness.close(context);162
});164
it("resumes a retry backoff after reopen", async () => {165
const path = await sqlitePath();166
const setup = chatSetup();167
let now = 1_000;168
setup.now = () => now;169
setup.faux.setResponses([170
fauxAssistantMessage([], { stopReason: "error", errorMessage: "503 Service Unavailable" }),171
fauxAssistantMessage("recovered"),172
]);173
let opened = await open(path, setup);174
opened.harness.resume();175
setup.settings.retry = { enabled: true, maxRetries: 2, baseDelayMs: 60_000 };176
const id = (await opened.root.submit({ type: "input", content: "hi" }, context)).id;177
await waitFor(async () => {178
const live = await opened.harness.snapshot(LiveDoc, opened.root.id, context);179
return live?.generation?.retry !== undefined;180
});181
const taskId = await runTaskId(opened.harness);182
await opened.harness.close(context);184
opened = await open(path, setup);185
expect(await checkpoint(opened.harness, taskId)).toEqual({ phase: "retry", attempt: 1, until: 61_000 });186
expect(await opened.harness.snapshot(LiveDoc, opened.root.id, context)).toEqual({187
run: { taskId, inputs: [id] },188
generation: { attempt: 1, retry: { at: 61_000, error: "503 Service Unavailable" } },189
});190
now = 61_000;191
opened.harness.resume();192
expect((await (await opened.harness.submission(id, context))!.wait(context)).status).toBe("done");193
expect((await allEntries(opened.root)).map((entry) => entry.kind)).toEqual([194
"pi.user",195
"pi.assistant",196
"pi.assistant",197
]);198
await opened.harness.close(context);199
});201
it("resumes polling a deferred response after reopen", async () => {202
const path = await sqlitePath();203
const setup = chatSetup({ deferred: { pollAfterMs: 60_000 } });204
let now = 1_000;205
setup.now = () => now;206
setup.faux.setResponses([fauxAssistantMessage("deferred answer")]);207
let opened = await open(path, setup);208
opened.harness.resume();209
setup.settings.stream = { deferred: true };210
const id = (await opened.root.submit({ type: "input", content: "hi" }, context)).id;211
await waitFor(async () => {212
const live = await opened.harness.snapshot(LiveDoc, opened.root.id, context);213
return live?.generation?.deferred !== undefined;214
});215
const taskId = await runTaskId(opened.harness);216
await opened.harness.close(context);218
opened = await open(path, setup);219
expect(await checkpoint(opened.harness, taskId)).toMatchObject({ phase: "poll", attempt: 1, pollAt: 61_000 });220
now = 61_000;221
opened.harness.resume();222
const settled = await (await opened.harness.submission(id, context))!.wait(context);223
if (settled.status !== "done" || settled.type !== "input") throw new Error(`Unexpected ${settled.status}`);224
const answer = await opened.root.commit((tx) => tx.entry(AssistantEntry, settled.answer), context);225
expect(textOf(answer?.model?.[0])).toBe("deferred answer");226
expect(setup.faux.state.deferredFetchCount).toBe(1);227
await opened.harness.close(context);228
});230
it("fails no_model when the pinned model is gone after reopen, in request and in poll", async () => {231
const path = await sqlitePath();232
const setup = chatSetup({ deferred: { pollAfterMs: 60_000 } });233
const busy = unanswered();234
setup.faux.setResponses([busy.step, fauxAssistantMessage("deferred")]);235
let opened = await open(path, setup);236
opened.harness.resume();237
const requesting = (await opened.root.submit({ type: "input", content: "one" }, context)).id;238
await busy.reached;239
await opened.harness.close(context);241
// Reopened without the faux provider: the request's pinned model is unknown.242
const empty: ChatSetup = { ...setup, models: createModels() };243
opened = await open(path, empty);244
opened.harness.resume();245
expect(await (await opened.harness.submission(requesting, context))!.wait(context)).toMatchObject({246
status: "unanswered",247
reason: "no_model",248
});249
await opened.harness.close(context);251
opened = await open(path, setup);252
setup.settings.stream = { deferred: true };253
opened.harness.resume();254
const polling = (await opened.root.submit({ type: "input", content: "two" }, context)).id;255
await waitFor(async () => {256
const live = await opened.harness.snapshot(LiveDoc, opened.root.id, context);257
return live?.generation?.deferred !== undefined;258
});259
await opened.harness.close(context);261
opened = await open(path, empty);262
opened.harness.resume();263
expect(await (await opened.harness.submission(polling, context))!.wait(context)).toMatchObject({264
status: "unanswered",265
reason: "no_model",266
});267
await opened.harness.close(context);268
});270
it("runs a print-style turn and reads the durable answer after reopen", async () => {271
const path = await sqlitePath();272
const setup = chatSetup();273
addSection(setup.registry, "preamble", () => "You are terse.", { tag: false });274
setup.faux.setResponses([fauxAssistantMessage("42")]);275
let opened = await open(path, setup);276
opened.harness.resume();277
const submission = await opened.root.submit({ type: "input", content: "answer?" }, context);278
const settled = await submission.wait(context);279
if (settled.status !== "done" || settled.type !== "input") throw new Error(`Unexpected ${settled.status}`);280
const answer = await opened.root.commit((tx) => tx.entry(AssistantEntry, settled.answer), context);281
expect(textOf(answer?.model?.[0])).toBe("42");282
await opened.harness.close(context);284
opened = await open(path, setup);285
expect(await (await opened.harness.submission(submission.id, context))!.status(context)).toEqual(settled);286
expect(await opened.root.commit((tx) => tx.entry(AssistantEntry, settled.answer), context)).toEqual(answer);287
await opened.harness.close(context);288
});289
});