1
import { runInNewContext } from "node:vm";2
import type { Context } from "@earendil-works/chord";3
import { createModels } from "@earendil-works/pi-ai";4
import {5
createRegistry,6
defineExtension,7
defineTask,8
Harness,9
type Id,10
LiveDoc,11
MemoryStorage,12
StorageRequestError,13
type TaskId,14
watchEvents,15
} from "@earendil-works/pi-durable";16
import { describe, expect, it } from "vitest";17
import { safeNow } from "../src/harness/harness.ts";18
import { conversationViews } from "../src/harness/view.ts";19
import { contained } from "../src/session/session.ts";20
import { ControlledStorage, context } from "./session-support.ts";21
import { aborted, deferred, openTasks } from "./task-support.ts";23
/** Waits for its signal, records that it saw it, and ends `aborted` through its abort handler. */24
const signals: string[] = [];25
const Waiting = defineTask<null, { phase: "work" }, null>({26
name: "test.waiting",27
version: 1,28
initial: () => ({ phase: "work" }),29
phases: {30
work: async (_task, runtime) => {31
await aborted(runtime.signal).catch(() => {});32
signals.push("aborted");33
},34
},35
abort: async (_task, runtime, abortContext) => {36
await runtime.commit(() => ({ status: "terminal", outcome: { status: "aborted" } }), abortContext);37
},38
});40
/**41
* Fails each Storage method named in `failing` once, with `error`. A scan of entries with a limit above 1 is the context42
* read's scan of its range, off the Session line; `heldRange` holds it until released.43
*/44
class FailingCalls extends ControlledStorage {45
readonly error = new Error("disk gone");46
readonly failing = new Set<string>();47
heldRange: { readonly entered: ReturnType<typeof deferred<void>>; readonly release: Promise<unknown> } | undefined;48
#fail(method: string): void {49
if (this.failing.delete(method)) throw this.error;50
}51
override async task(...args: Parameters<MemoryStorage["task"]>) {52
this.#fail("task");53
return super.task(...args);54
}55
override async scanEntries(...args: Parameters<MemoryStorage["scanEntries"]>) {56
if (args[1] > 1) {57
const held = this.heldRange;58
if (held !== undefined) {59
held.entered.resolve();60
await held.release;61
}62
this.#fail("scanRange");63
}64
return super.scanEntries(...args);65
}66
override async mintId<I extends Id<string>>(): Promise<I> {67
this.#fail("mintId");68
return super.mintId<I>();69
}70
}72
async function started(storage: MemoryStorage) {73
signals.length = 0;74
const opened = await openTasks(storage, [Waiting]);75
const root = await opened.harness.root(context);76
return { ...opened, root };77
}79
async function running(harness: Harness, id: TaskId): Promise<void> {80
while ((await harness.getTask(id, context))?.state.status !== "running") {81
await new Promise((resolve) => setTimeout(resolve, 1));82
}83
}85
describe("a failed Storage call", () => {86
it("ends everything with the first error: the call, later calls, waits, watches, streams, running tasks", async () => {87
const storage = new ControlledStorage();88
const { harness, root, reports } = await started(storage);89
const id = await root.commit(90
(tx) => tx.createTask(Waiting, null, { ownership: { kind: "conversation" } }),91
context,92
);93
harness.resume();94
await running(harness, id);95
const task = harness.waitForTask(id, context);96
const idle = harness.waitForIdle(context);97
const watch = (await harness.watchDoc(LiveDoc, root.id, context))!;98
const stream = await watchEvents(harness, root.id, context);99
stream.start(async () => {});101
const failure = new Error("disk gone");102
storage.failNextCommit(failure);103
// The call that hit it gets the storage error itself.104
await expect(root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context)).rejects.toBe(failure);106
const failed = { name: "SessionFailed", cause: failure };107
await expect(task).rejects.toMatchObject(failed);108
await expect(idle).rejects.toMatchObject(failed);109
expect(await watch.closed).toEqual({ reason: "session_failed", error: failure });110
expect(await stream.closed).toEqual({ reason: "session_failed", error: failure });111
// Every later call, and a wait that starts now.112
await expect(harness.getTask(id, context)).rejects.toMatchObject(failed);113
await expect(harness.waitForIdle(context)).rejects.toMatchObject(failed);114
await expect(root.submit({ type: "input", content: "x" }, context)).rejects.toMatchObject(failed);115
expect(await harness.closed).toEqual({ reason: "failed", error: failure });116
expect(signals).toEqual(["aborted"]);117
expect(reports).toEqual([failure]);118
await harness.close(context);119
});121
it("fails it from a read off the Session line, as a context read makes", async () => {122
const storage = new FailingCalls();123
const { harness, root, reports } = await started(storage);124
await root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context);125
storage.failing.add("scanRange");126
await expect(root.context(context)).rejects.toBe(storage.error);127
expect(await harness.closed).toEqual({ reason: "failed", error: storage.error });128
expect(reports).toEqual([storage.error]);129
await harness.close(context);130
});132
it("ends Storage calls underway with SessionFailed, and closes once they have settled", async () => {133
const storage = new FailingCalls();134
const { harness, root } = await started(storage);135
const release = deferred();136
await root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context);137
storage.heldRange = { entered: deferred(), release: release.promise };138
const reading = root.context(context);139
await storage.heldRange.entered.promise;140
// Another call fails the Session while the context read is underway.141
storage.failing.add("mintId");142
await expect(root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context)).rejects.toBe(storage.error);143
let closed = false;144
void harness.closed.then(() => {145
closed = true;146
});147
for (let i = 0; i < 5; i++) await new Promise((resolve) => setTimeout(resolve, 0));148
expect(closed).toBe(false);149
// The read succeeds at the backend, yet its caller gets the failure: nothing it read is used.150
release.resolve();151
await expect(reading).rejects.toMatchObject({ name: "SessionFailed", cause: storage.error });152
expect(await harness.closed).toEqual({ reason: "failed", error: storage.error });153
await harness.close(context);154
});156
it("closes the backend only after a paged read underway, which cannot start another page", async () => {157
const pages: string[] = [];158
const firstPage = deferred();159
const releaseFirst = deferred();160
class Paged extends ControlledStorage {161
override async scanEntries(...args: Parameters<MemoryStorage["scanEntries"]>) {162
if (args[1] > 1) {163
pages.push(args[2] === undefined ? "first" : "next");164
if (args[2] === undefined) {165
firstPage.resolve();166
await releaseFirst.promise;167
}168
}169
return super.scanEntries(...args);170
}171
override async close(closeContext: Context): Promise<void> {172
pages.push("close");173
return super.close(closeContext);174
}175
}176
const storage = new Paged();177
const { harness, root } = await started(storage);178
// More entries than one page of the context read.179
await root.commit(async (tx) => {180
for (let n = 0; n < 300; n++) await tx.appendEntry(root.id, { kind: "note" });181
}, context);182
const reading = root.context(context);183
await firstPage.promise;184
const closing = harness.close(context);185
releaseFirst.resolve();186
await expect(reading).rejects.toThrow("is closed");187
await closing;188
expect(pages).toEqual(["first", "close"]);189
expect(await harness.closed).toEqual({ reason: "closed" });190
});192
it("fails it when Storage cannot close; an earlier failure stays the cause", async () => {193
const closeError = new Error("close failed");194
class FailingClose extends ControlledStorage {195
override async close(closeContext: Context): Promise<void> {196
await super.close(closeContext);197
throw closeError;198
}199
}200
const healthy = await started(new FailingClose());201
await expect(healthy.harness.close(context)).rejects.toBe(closeError);202
expect(await healthy.harness.closed).toEqual({ reason: "failed", error: closeError });203
expect(healthy.reports).toEqual([closeError]);205
const storage = new FailingClose();206
const failed = await started(storage);207
const failure = new Error("disk gone");208
storage.failNextCommit(failure);209
await expect(failed.root.commit((tx) => tx.appendEntry(failed.root.id, { kind: "note" }), context)).rejects.toBe(210
failure,211
);212
expect(await failed.harness.closed).toEqual({ reason: "failed", error: failure });213
expect(failed.reports).toEqual([failure]);214
});216
it("rejects the Harness's own calls with SessionFailed after a failure", async () => {217
const storage = new ControlledStorage();218
const { harness, root } = await started(storage);219
const failure = new Error("disk gone");220
storage.failNextCommit(failure);221
await expect(root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context)).rejects.toBe(failure);222
const failed = { name: "SessionFailed", cause: failure };223
expect(() => harness.resume()).toThrow(expect.objectContaining(failed));224
await expect(harness.root(context)).rejects.toMatchObject(failed);225
await expect(harness.conversation(root.id, context)).rejects.toMatchObject(failed);226
await expect(harness.createConversation({ ownership: { kind: "ownerless" } }, context)).rejects.toMatchObject(227
failed,228
);229
await harness.close(context);230
});232
it("ends what a task holds with session_failed, not as cancelled by its signal", async () => {233
const ends: unknown[] = [];234
const watching = deferred();235
const Watcher = defineTask<null, { phase: "work" }, null>({236
name: "test.watcher",237
version: 1,238
initial: () => ({ phase: "work" }),239
phases: {240
work: async (_task, runtime, phaseContext) => {241
const doc = (await runtime.watchDoc(LiveDoc, runtime.conversationId, phaseContext))!;242
const handle = (await runtime.conversation(runtime.conversationId, phaseContext))!;243
const idle = handle.waitForIdle(phaseContext).then(244
() => "resolved",245
(error: Error) => error.name,246
);247
watching.resolve();248
ends.push(await doc.closed, await idle);249
},250
},251
abort: async () => {},252
});253
const storage = new ControlledStorage();254
const opened = await openTasks(storage, [Watcher]);255
const root = await opened.harness.root(context);256
await root.commit((tx) => tx.createTask(Watcher, null, { ownership: { kind: "conversation" } }), context);257
opened.harness.resume();258
await watching.promise;259
const failure = new Error("disk gone");260
storage.failNextCommit(failure);261
await expect(root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context)).rejects.toBe(failure);262
await opened.harness.closed;263
expect(ends).toEqual([{ reason: "session_failed", error: failure }, "SessionFailed"]);264
await opened.harness.close(context);265
});267
it("fails it from a failed ID mint", async () => {268
const storage = new FailingCalls();269
const { harness, root } = await started(storage);270
storage.failing.add("mintId");271
await expect(root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context)).rejects.toBe(storage.error);272
expect(await harness.closed).toEqual({ reason: "failed", error: storage.error });273
await harness.close(context);274
});276
it("does not commit what a callback did after it caught a failed read", async () => {277
const storage = new FailingCalls();278
const { harness, root } = await started(storage);279
const written = storage.admittedCommits.length;280
storage.failing.add("task");281
await expect(282
root.commit(async (tx) => {283
await tx.task(1 as TaskId).catch(() => {});284
await tx.appendEntry(root.id, { kind: "note" });285
}, context),286
).rejects.toMatchObject({ name: "SessionFailed", cause: storage.error });287
expect(storage.admittedCommits.length).toBe(written);288
await harness.close(context);289
});291
it("fails it for a StorageRequestError from a commit, whose effect is unknown", async () => {292
const storage = new ControlledStorage();293
const { harness, root } = await started(storage);294
const rejection = new StorageRequestError("bad batch");295
storage.failNextCommit(rejection);296
await expect(root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context)).rejects.toBe(rejection);297
expect(await harness.closed).toEqual({ reason: "failed", error: rejection });298
await harness.close(context);299
});301
it("fails only the call for an invalid request", async () => {302
const { harness, root, reports } = await started(new MemoryStorage());303
const entry = await root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context);304
const requests: (() => Promise<unknown>)[] = [305
() => root.entries({}, 10, { after: "x" }, context),306
async () => {307
const page = await root.entries({ order: "ascending" }, 1, undefined, context);308
return root.entries({ order: "descending" }, 1, page.next ?? { after: 1, order: "ascending" }, context);309
},310
() => root.commit((tx) => tx.scanEntries({ conversationId: 999_999 as never }, 10), context),311
// `pi.live` keeps no history.312
() => harness.snapshotAsOf(LiveDoc as never, root.id, entry.id, context),313
];314
for (const request of requests) {315
await expect(request()).rejects.toMatchObject({ name: "StorageRequestError" });316
}317
await expect(root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context)).resolves.toBeDefined();318
let ended = false;319
void harness.closed.then(() => {320
ended = true;321
});322
await new Promise((resolve) => setTimeout(resolve, 0));323
expect(ended).toBe(false);324
expect(reports).toEqual([]);325
await harness.close(context);326
});328
it("fails it for a throw in its own commit listeners, which would leave memory behind storage", async () => {329
const storage = new ControlledStorage();330
const { harness, root, reports } = await started(storage);331
const bug = new Error("listener bug");332
(harness as unknown as { observeCommits(listener: () => void): void }).observeCommits(() => {333
throw bug;334
});335
// The commit itself is durable and resolves; the Session fails behind it.336
await expect(root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context)).resolves.toBeDefined();337
expect(await harness.closed).toEqual({ reason: "failed", error: bug });338
expect(reports).toEqual([bug]);339
await harness.close(context);340
});342
it("fails it for a storage error during a host close, before the backend closes", async () => {343
const storage = new ControlledStorage();344
const { harness, root, reports } = await started(storage);345
const held = storage.holdCommits();346
const failure = new Error("disk gone");347
storage.failNextCommit(failure);348
const committing = root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context);349
await held.entered;350
const closing = harness.close(context);351
held.release();352
await expect(committing).rejects.toBe(failure);353
await closing;354
expect(await harness.closed).toEqual({ reason: "failed", error: failure });355
expect(reports).toEqual([failure]);356
});358
it("ends an abort that joins a run ignoring its signal, and a reentrant report finds the Session failed", async () => {359
const release = deferred();360
const entered = deferred();361
const Stubborn = defineTask<null, { phase: "work" }, null>({362
name: "test.stubborn",363
version: 1,364
initial: () => ({ phase: "work" }),365
phases: {366
work: async () => {367
entered.resolve();368
await release.promise;369
},370
},371
abort: async () => {},372
});373
const storage = new ControlledStorage();374
const registry = createRegistry();375
registry.install(defineExtension({ name: "tasks", tasks: [Stubborn] }));376
let reentered: Promise<unknown> | undefined;377
const harness: Harness = await Harness.open(378
storage,379
{380
models: createModels(),381
registry,382
onReport: () => {383
reentered ??= harness.waitForIdle(context);384
},385
},386
context,387
);388
const root = await harness.root(context);389
const id = await root.commit(390
(tx) => tx.createTask(Stubborn, null, { ownership: { kind: "conversation" } }),391
context,392
);393
harness.resume();394
await entered.promise;395
const held = storage.holdCommits();396
const aborting = harness.abortTask(id, context);397
await held.entered;398
held.release();399
// The abort mark commits and the abort joins the run, which ignores its signal; then the Session fails.400
const failure = new Error("disk gone");401
await new Promise((resolve) => setTimeout(resolve, 5));402
storage.failNextCommit(failure);403
await expect(root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context)).rejects.toBe(failure);404
await expect(aborting).rejects.toMatchObject({ name: "SessionFailed", cause: failure });405
await expect(reentered).rejects.toMatchObject({ name: "SessionFailed", cause: failure });406
release.resolve();407
await harness.close(context);408
});410
it("does not fail it for a read its caller cancelled", async () => {411
const controller = new AbortController();412
const cancelled = new Error("caller gave up");413
class CancelledRead extends MemoryStorage {414
override async scanEntries(...args: Parameters<MemoryStorage["scanEntries"]>) {415
if (args[3].abortSignal === controller.signal) {416
controller.abort(cancelled);417
throw cancelled;418
}419
return super.scanEntries(...args);420
}421
}422
const { harness, root } = await started(new CancelledRead());423
const cancelling: Context = { ...context, abortSignal: controller.signal };424
await expect(root.context(cancelling)).rejects.toBe(cancelled);425
await expect(root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context)).resolves.toBeDefined();426
await harness.close(context);427
});428
});430
describe("listener and report errors", () => {431
it("reports a listener or onReport whose promise rejects, without an unhandled rejection", async () => {432
const unhandled: unknown[] = [];433
const onUnhandled = (error: unknown) => unhandled.push(error);434
process.on("unhandledRejection", onUnhandled);435
try {436
const { harness, root, reports } = await started(new MemoryStorage());437
const asyncThrow = async () => {438
throw new Error("async listener");439
};440
harness.subscribeCommits(asyncThrow);441
harness.subscribeClose(asyncThrow);442
await root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context);443
await harness.close(context);444
await new Promise((resolve) => setTimeout(resolve, 10));445
expect(reports.map(String)).toEqual(["Error: async listener", "Error: async listener"]);447
const registry = createRegistry();448
const rejecting = await Harness.open(449
new MemoryStorage(),450
{ models: createModels(), registry, onReport: asyncThrow },451
context,452
);453
rejecting.subscribeCommits(() => {454
throw new Error("sync listener");455
});456
const again = await rejecting.root(context);457
await again.commit((tx) => tx.appendEntry(again.id, { kind: "note" }), context);458
await rejecting.close(context);459
await new Promise((resolve) => setTimeout(resolve, 10));460
expect(unhandled).toEqual([]);461
} finally {462
process.off("unhandledRejection", onUnhandled);463
}464
});466
it("reports a throwing commit or close listener and runs the others; the commit stands", async () => {467
const storage = new MemoryStorage();468
const { harness, root, reports } = await started(storage);469
const seen: string[] = [];470
harness.subscribeCommits(() => {471
throw new Error("commit listener");472
});473
harness.subscribeCommits(() => seen.push("commit"));474
harness.subscribeClose(() => {475
throw new Error("close listener");476
});477
harness.subscribeClose(() => seen.push("close"));478
await expect(root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context)).resolves.toBeDefined();479
await harness.close(context);480
expect(seen).toEqual(["commit", "close"]);481
expect(reports.map(String)).toEqual(["Error: commit listener", "Error: close listener"]);482
});484
it("keeps feeding the other observers of a view when one throws", async () => {485
const { harness, root, reports } = await started(new MemoryStorage());486
const views = conversationViews(harness);487
const failure = new Error("observer broke");488
await views.attach(489
root.id,490
async () => ({491
publication: () => {492
throw failure;493
},494
closeSession: () => {},495
}),496
context,497
);498
const watch = await root.watch(context);499
const seen: unknown[] = [];500
watch.start(async (value) => {501
seen.push(value);502
});503
await root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context);504
while (seen.length === 0) await new Promise((resolve) => setTimeout(resolve, 1));505
expect(reports).toEqual([failure]);506
await harness.close(context);507
expect(await watch.closed).toEqual({ reason: "session_closed" });508
});510
it("contains a fulfilled thenable that calls only its fulfillment handler", async () => {511
const unhandled: unknown[] = [];512
const onUnhandled = (error: unknown) => unhandled.push(error);513
process.on("uncaughtException", onUnhandled);514
process.on("unhandledRejection", onUnhandled);515
try {516
const errors: unknown[] = [];517
// A thenable that, like some libraries' promises, calls only the handler it settles with.518
// biome-ignore lint/suspicious/noThenProperty: the test is about a thenable519
const thenable = { then: (resolve: () => void) => queueMicrotask(() => resolve()) };520
contained(521
() => thenable,522
(error) => errors.push(error),523
);524
await new Promise((resolve) => setTimeout(resolve, 10));525
expect(errors).toEqual([]);526
expect(unhandled).toEqual([]);527
} finally {528
process.off("uncaughtException", onUnhandled);529
process.off("unhandledRejection", onUnhandled);530
}531
});533
it("contains a rejected promise from another realm", async () => {534
const unhandled: unknown[] = [];535
const onUnhandled = (error: unknown) => unhandled.push(error);536
process.on("unhandledRejection", onUnhandled);537
try {538
const foreign = runInNewContext("Promise.reject(new Error('foreign'))") as Promise<never>;539
const errors: unknown[] = [];540
contained(541
() => foreign,542
(error) => errors.push(error),543
);544
await new Promise((resolve) => setTimeout(resolve, 10));545
expect(errors.map(String)).toEqual(["Error: foreign"]);546
expect(unhandled).toEqual([]);547
} finally {548
process.off("unhandledRejection", onUnhandled);549
}550
});552
it("reports a throwing watch listener, which ends that watch", async () => {553
const { harness, root, reports } = await started(new MemoryStorage());554
const watch = (await harness.watchDoc(LiveDoc, root.id, context))!;555
const failure = new Error("listener broke");556
watch.start(async () => {557
throw failure;558
});559
await root.commit(async (tx) => {560
(await tx.doc(LiveDoc, root.id)).compactions = [];561
}, context);562
expect(await watch.closed).toEqual({ reason: "listener_error", error: failure });563
expect(reports).toEqual([failure]);564
await harness.close(context);565
});567
it("faults only the task, and ends only the watch, for a thrown value that cannot be formatted", async () => {568
const unformattable = Object.create(null) as object;569
const Throws = defineTask<null, { phase: "work" }, null>({570
name: "test.throws-unformattable",571
version: 1,572
initial: () => ({ phase: "work" }),573
phases: {574
work: async () => {575
throw unformattable;576
},577
},578
abort: async () => {},579
});580
const opened = await openTasks(new MemoryStorage(), [Throws]);581
const root = await opened.harness.root(context);582
const watch = (await opened.harness.watchDoc(LiveDoc, root.id, context))!;583
watch.start(async () => {584
throw unformattable;585
});586
const id = await root.commit(587
(tx) => tx.createTask(Throws, null, { ownership: { kind: "conversation" } }),588
context,589
);590
opened.harness.resume();591
expect((await opened.harness.waitForTask(id, context)).state.outcome).toEqual({592
status: "faulted",593
error: { message: "[object Object]" },594
});595
await root.commit(async (tx) => {596
(await tx.doc(LiveDoc, root.id)).compactions = [];597
}, context);598
expect(await watch.closed).toMatchObject({ reason: "listener_error" });599
await expect(root.commit((tx) => tx.appendEntry(root.id, { kind: "note" }), context)).resolves.toBeDefined();600
await opened.harness.close(context);601
});603
it("reports a throwing clock once, also when the report handler reads the clock again", () => {604
const reports: unknown[] = [];605
const clock = safeNow(606
() => {607
throw new Error("clock broke");608
},609
(error) => {610
reports.push(error);611
// Reentry, as a handler that commits does: the clock is read again before this report returns.612
if (reports.length < 5) clock();613
},614
);615
expect(clock()).toEqual(expect.any(Number));616
clock();617
expect(reports.map(String)).toEqual(["Error: clock broke"]);618
});620
it("keeps working when onReport throws, and falls back to Date.now when the clock throws", async () => {621
const registry = createRegistry();622
registry.install(defineExtension({ name: "tasks", tasks: [Waiting] }));623
const harness = await Harness.open(624
new MemoryStorage(),625
{626
models: createModels(),627
registry,628
now: () => {629
throw new Error("clock broke");630
},631
onReport: () => {632
throw new Error("report broke");633
},634
},635
context,636
);637
const root = await harness.root(context);638
const id = await root.commit(639
(tx) => tx.createTask(Waiting, null, { ownership: { kind: "conversation" } }),640
context,641
);642
harness.resume();643
await running(harness, id);644
expect((await harness.getTask(id, context))?.startedAt).toEqual(expect.any(Number));645
await harness.abortTask(id, context);646
expect((await harness.waitForTask(id, context)).state.outcome.status).toBe("aborted");647
await harness.close(context);648
});649
});