iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / itx / src / context / reactive-catalog.test.tsmain at 949894f

// The reactive catalog against a brute-force oracle. The oracle shares no code with the engine:
// its own facts, its own byte order (Buffer.compare), a filter, a sort and a slice over a model of
// the rows. After EVERY operation each watcher's rows must equal the oracle's, each stored window
// must agree with the rows, and a write must send a frame to exactly the queries whose answer it
// changed.
import { DatabaseSync } from "node:sqlite";
import type { CatalogCursor, CatalogOrder, CatalogQuery } from "iterate/api";
import { expect, onTestFinished, test, vi } from "vitest";
import {
  CATALOG_LIMITS,
  compareTextBinary,
  ReactiveCatalog,
  type CatalogRowInput,
} from "./reactive-catalog.ts";

test("holds against a brute-force oracle through random writes, queries in every order, hibernations and reconnects", () => {
  const total = { writes: 0, frames: 0, quiet: 0, resumes: 0, rowsHeld: 0, hibernations: 0 };
  // a short run by default; the long run is 40 seeds of 3,000 operations
  const seeds = Number(process.env.CATALOG_TEST_SEEDS || 6);
  const steps = Number(process.env.CATALOG_TEST_STEPS || 800);
  for (let seed = 1; seed <= seeds; seed++) {
    const tally = runSeed(seed, steps);
    for (const key of Object.keys(total) as (keyof typeof total)[]) total[key] += tally[key];
  }
  console.info({ event: "reactive-catalog.random-run", seeds, steps, ...total });
  // the run did what it is for
  expect(total.quiet).toBeGreaterThan(seeds * 20);
  expect(total.resumes).toBeGreaterThan(seeds);
  expect(total.rowsHeld).toBeGreaterThan(seeds);
  expect(total.hibernations).toBeGreaterThan(seeds * 10);
}, 600_000);

test("orders text as SQLite does, by UTF-8 bytes", () => {
  const texts = ["", "a", "a/", "ab", "b", "é", "z", "", "￿", "😀", "😀a", "𐀀", "퟿", "a", "a😀"];
  for (const a of texts)
    for (const b of texts)
      expect(
        Math.sign(compareTextBinary(a, b)),
        `${JSON.stringify(a)} against ${JSON.stringify(b)}`,
      ).toBe(Math.sign(byteOrder(a, b)));
  // the case that JavaScript's own comparison gets wrong: U+E000 is before an emoji in UTF-8
  expect(["😀", ""].sort()).toEqual(["😀", ""]);
  expect(compareTextBinary("", "😀")).toBeLessThan(0);
});

test("the six steps of the acceptance test, counted", () => {
  using object = fakeObject();
  const catalog = object.wake();
  catalog.fill();
  // 600 open and 400 closed rows
  catalog.upsertMany(
    Array.from({ length: 1000 }, (_, index) =>
      task(index, index < 600 ? "open" : "closed", 10_000 - index),
    ),
  );
  const client = new Client();
  client.connect(catalog);
  const spec = { where: { status: "open" }, limit: 50 };
  const statements = () => catalog.counters.statements;

  // 1. the snapshot
  let before = statements();
  client.subscribe(catalog, "open", spec);
  const sub = client.subs.get("open")!;
  expect(sub.rows).toMatchObject({ size: 50 });
  const snapshotStatements = statements() - before;
  const paths = () => client.sorted(sub).map((row) => row.path);
  expect(paths().slice(0, 1)).toEqual(["/tasks/t0000"]);
  expect(paths().slice(49)).toEqual(["/tasks/t0049"]);

  // 2. a row enters: the old 50th leaves in the same frame
  before = statements();
  sub.frames = 0;
  expect(catalog.upsert(task(2000, "open", 20_000))).toMatchObject({ frames: 1, messages: 1 });
  expect(sub).toMatchObject({ frames: 1 });
  expect(paths()).toHaveLength(50);
  expect(paths().slice(0, 1)).toEqual(["/tasks/t2000"]);
  expect(sub.rows.has("/tasks/t0049")).toBe(false);
  const enterStatements = statements() - before;

  // 3. a row leaves: the 51st takes its place in the same frame
  sub.frames = 0;
  before = statements();
  expect(catalog.upsert(task(2000, "closed", 20_001))).toMatchObject({ frames: 1 });
  expect(sub).toMatchObject({ frames: 1 });
  expect(paths()).toHaveLength(50);
  expect(sub.rows.has("/tasks/t0049")).toBe(true);
  const leaveStatements = statements() - before;

  // 4. a row moves inside the window
  sub.frames = 0;
  expect(catalog.upsert(task(25, "open", 30_000))).toMatchObject({ frames: 1 });
  expect(paths().slice(0, 1)).toEqual(["/tasks/t0025"]);

  // 5. 1,000 unrelated updates of each kind: no frame, and no statement beyond the write's own
  sub.frames = 0;
  before = statements();
  const seeks = catalog.counters.seeks;
  for (let index = 0; index < 1000; index++)
    catalog.upsert(task(600 + (index % 400), "closed", 40_000 + index));
  const closedStatements = (statements() - before) / 1000;
  before = statements();
  for (let index = 0; index < 500; index++)
    catalog.upsert(task(100 + index, "open", 5_000 - index));
  const outsideStatements = (statements() - before) / 500;
  expect(sub).toMatchObject({ frames: 0 });
  expect(catalog.counters).toMatchObject({ seeks });
  // the write's own statements: one read of the row, one write of it, the revision, and for each
  // of its five facts one entry out and one in, in the index of the order `active` alone
  expect({ closedStatements, outsideStatements }).toEqual({
    closedStatements: 13,
    outsideStatements: 13,
  });

  // 6. the watcher goes away, four rows change, and it comes back with its cursor
  const heldBefore = new Set(sub.rows.keys());
  client.socket!.close();
  object.sockets.delete(client.socket!);
  const woken = object.wake();
  woken.upsert(task(3000, "open", 50_000));
  woken.upsert(task(25, "closed", 50_001));
  woken.upsert(task(10, "closed", 50_002));
  woken.upsert(task(3, "open", 50_003));
  client.connect(woken);
  client.subscribe(woken, "open", spec, true);
  const answer = sub.answers.at(-1)!;
  // The new row, the touched row, and ONE row that was never written while the watcher was away:
  // two rows closed and one came, so the window took a row from after the watcher's bound. Its
  // revision is old, and only the cursor's bound shows that the watcher lacks it.
  expect(answer).toMatchObject({ reset: false, put: 3 });
  expect(
    [...sub.rows.keys()].filter((path) => !heldBefore.has(path) && path !== "/tasks/t3000"),
  ).toEqual(["/tasks/t0050"]);
  expect(sub.rows).toMatchObject({ size: heldBefore.size });
  expect(answer.chars).toBeLessThan(sub.answers[0]!.chars / 3);
  console.info({
    event: "reactive-catalog.acceptance",
    snapshotStatements,
    enterStatements,
    leaveStatements,
    closedStatements,
    outsideStatements,
    snapshotChars: sub.answers[0]!.chars,
    resumeChars: answer.chars,
  });
  expect(woken.verify()).toEqual([]);
});

test("a row's new activity writes the entries of one order, and a new fact one entry in each", () => {
  using object = fakeObject();
  const catalog = object.wake();
  catalog.fill();
  const row = (activeMs: number, status: string) => ({
    path: "/agents/a/b",
    activeMs,
    createdMs: 5,
    processors: ["agent"],
    metadata: { status, tags: ["x", "y"] },
  });
  catalog.upsert(row(10, "open"));
  // $parent, $under ×3, $processor, status, tags ×2
  const facts = 8;
  const count = (table: string) =>
    object.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number };
  for (const table of ["rcat_fact_active", "rcat_fact_created", "rcat_fact_path"])
    expect(count(table), table).toEqual({ n: facts });

  // the same row again: one read, and no write
  let before = catalog.counters.statements;
  expect(catalog.upsert(row(10, "open"))).toMatchObject({ changed: 0 });
  expect(catalog.counters.statements - before).toBe(1);

  // new activity: a read, the row, the revision, and each entry of `active` out and in
  before = catalog.counters.statements;
  expect(catalog.upsert(row(11, "open"))).toMatchObject({ changed: 1 });
  expect(catalog.counters.statements - before).toBe(3 + 2 * facts);

  // one fact changes and the time stays: one entry out and one in, in each of the three indexes
  before = catalog.counters.statements;
  expect(catalog.upsert(row(11, "closed"))).toMatchObject({ changed: 1 });
  expect(catalog.counters.statements - before).toBe(3 + 2 * 3);
  for (const table of ["rcat_fact_active", "rcat_fact_created", "rcat_fact_path"])
    expect(count(table), table).toEqual({ n: facts });
});

test("refuses a query it cannot answer exactly, with a reason", () => {
  using object = fakeObject();
  const catalog = object.wake();
  catalog.fill();
  const client = new Client();
  client.connect(catalog);
  const ask = (query: unknown) => {
    client.errors = [];
    client.subs.set("q", newSub({}));
    catalog.handleWatchMessage(
      client.socket as never,
      JSON.stringify({ op: "subscribe", sub: "q", query }),
    );
    return client.errors[0];
  };
  expect(ask({ where: { status: { not: "open" } } })).toMatch(/where\.status/);
  expect(ask({ limit: 0 })).toMatch(/limit/);
  expect(ask({ limit: 1.5 })).toMatch(/limit/);
  expect(ask({ limit: CATALOG_LIMITS.limit + 1 })).toMatch(/limit/);
  expect(ask({ orderBy: "title" })).toMatch(/orderBy/);
  expect(ask({ order: "title" })).toMatch(/order/);
  expect(ask({ keys: ["/a"], limit: 3 })).toMatch(/stands alone/);
  expect(ask({ awake: true, order: "path" })).toMatch(/stands alone/);
  expect(ask({ under: "tasks" })).toMatch(/starts with/);
  expect(ask({ where: { a: "\ud800" } })).toMatch(/not plain text/);
  expect(ask("status=open")).toMatch(/not a query/);
  // a message that is no request
  client.errors = [];
  catalog.handleWatchMessage(client.socket as never, "not JSON");
  expect(client.errors[0]).toMatch(/one JSON object/);
  // and a write the catalog cannot order
  expect(() => catalog.upsert({ path: "/a", activeMs: Number.NaN, createdMs: 1 })).toThrow(
    /activeMs/,
  );
  expect(() => catalog.upsert({ path: "a", activeMs: 1, createdMs: 1 })).toThrow(/starts with/);
  // a refused row in a batch undoes the batch
  expect(() =>
    catalog.upsertMany([
      { path: "/ok", activeMs: 1, createdMs: 1 },
      { path: "/bad", activeMs: 1.5, createdMs: 1 },
    ]),
  ).toThrow();
  client.subscribe(catalog, "all", { limit: 5 });
  expect(client.subs.get("all")!.rows).toMatchObject({ size: 0 });
});

test("a cursor of another query gets every row, and a cursor of the same facts serves a larger limit", () => {
  using object = fakeObject();
  const catalog = object.wake();
  catalog.fill();
  const model = new Map<string, ModelRow>();
  const rows = [
    ...Array.from({ length: 6 }, (_, index) => ({
      path: `/t/open${index}`,
      activeMs: 10 - index,
      createdMs: index,
      metadata: { status: "open" },
    })),
    ...Array.from({ length: 6 }, (_, index) => ({
      path: `/t/closed${index}`,
      activeMs: 30 - index,
      createdMs: index,
      metadata: { status: "closed" },
    })),
  ];
  catalog.upsertMany(rows);
  rows.forEach((row, index) =>
    model.set(row.path, { ...row, processors: [], metadata: row.metadata, rev: index + 1 }),
  );
  const client = new Client();
  client.connect(catalog);
  client.subscribe(catalog, "q", { where: { status: "open" }, limit: 3 });
  const sub = client.subs.get("q")!;
  expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 3 });

  // the same facts, a larger limit: the cursor holds, and only the three new rows come
  client.subscribe(catalog, "q", { where: { status: "open" }, limit: 6 }, true);
  expect(sub.answers.at(-1)).toMatchObject({ reset: false, put: 3 });
  expectClientMatches(client, model, "a larger limit");

  // other facts under the same name, with the old cursor: every closed row is newer than the
  // cursor's bound and older than its revision, so a trusted cursor would send no row at all
  client.subscribe(catalog, "q", { where: { status: "closed" }, limit: 3 }, true);
  expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 3 });
  expectClientMatches(client, model, "another query");

  // the same facts in another order: the bound is a key of the old order, so every row comes
  client.subscribe(catalog, "q", { where: { status: "closed" }, order: "path", limit: 3 }, true);
  expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 3 });
  expectClientMatches(client, model, "another order");
});

test("the awake list comes from the sockets, with no row and no revision", () => {
  using object = fakeObject();
  const catalog = object.wake();
  expect(catalog.awakeWatched()).toBe(false);
  object.awake.set("/agents/a", { since: 111 });
  const client = new Client();
  client.connect(catalog);
  client.subscribe(catalog, "awake", { awake: true });
  const sub = client.subs.get("awake")!;
  expect([...sub.rows.values()]).toEqual([{ path: "/agents/a", since: 111 }]);
  expect(catalog.awakeWatched()).toBe(true);
  // the awake list needs no row: a watch of it alone keeps the catalog asleep
  expect(catalog.active()).toBe(false);
  // after a hibernation the window is found in storage, and the frame still arrives
  const woken = object.wake();
  const working = { since: 222, activities: [{ key: "run", text: "Runs a script" }] };
  object.awake.set("/agents/b", working);
  woken.awakeChanged("/agents/b", working);
  object.awake.delete("/agents/a");
  woken.awakeChanged("/agents/a", undefined);
  expect([...sub.rows.values()]).toEqual([{ path: "/agents/b", ...working }]);
  client.unsubscribe(woken, "awake");
  expect(woken.awakeWatched()).toBe(false);
});

test("a window that no socket names goes at its first frame", () => {
  using object = fakeObject();
  const catalog = object.wake();
  const client = new Client();
  client.connect(catalog);
  client.subscribe(catalog, "open", { where: { status: "open" }, limit: 5 });
  // the socket ends with no close event, and the object hibernates
  client.socket!.close();
  object.sockets.delete(client.socket!);
  const woken = object.wake();
  expect(woken.watches().windows).toHaveLength(1);
  woken.upsert({ path: "/t/1", activeMs: 1, createdMs: 1, metadata: { status: "open" } });
  expect(woken.watches().windows).toHaveLength(0);
});

test("nothing is kept before the first watch, and the first watch copies every row of the catalog", () => {
  const source = Array.from({ length: 1_203 }, (_, index) =>
    task(index, index % 3 ? "open" : "closed", 1_000 + index),
  );
  // a row that this collection refuses is left out, and the others are kept
  source.push({ ...task(0, "open", 1), path: "/tasks/zz-bad", activeMs: 1.5 });
  source.sort((a, b) => byteOrder(a.path, b.path));
  const pages: number[] = [];
  using object = fakeObject((after, limit) => {
    const page = source.filter((row) => byteOrder(row.path, after) > 0).slice(0, limit);
    pages.push(page.length);
    return page;
  });
  const catalog = object.wake();
  expect(catalog.active()).toBe(false);
  // a write before the first watch is no write: no row, no revision
  expect(catalog.upsert(task(9_000, "open", 1))).toMatchObject({ changed: 0, rev: 0 });
  expect(catalog.watches()).toMatchObject({ active: false, rows: 0 });

  const client = new Client();
  client.connect(catalog);
  client.subscribe(catalog, "open", { where: { status: "open" }, order: "path", limit: 4 });
  expect(pages).toEqual([500, 500, 204, 0]);
  expect(catalog.watches()).toMatchObject({ active: true, rows: 1_203, rev: 1_203 });
  expect(client.sorted(client.subs.get("open")!).map((row) => row.path)).toEqual([
    "/tasks/t0001",
    "/tasks/t0002",
    "/tasks/t0004",
    "/tasks/t0005",
  ]);
  // from then on a write is kept, and a later object does not fill again
  const woken = object.wake();
  expect(woken.upsert(task(9_000, "open", 1))).toMatchObject({ changed: 1, rev: 1_204 });
  woken.fill();
  expect(pages).toHaveLength(4);
});

test("a fill that stopped goes on from the last page it wrote", () => {
  const source = Array.from({ length: 1_100 }, (_, index) => task(index, "open", index)).sort(
    (a, b) => byteOrder(a.path, b.path),
  );
  let calls = 0;
  using object = fakeObject((after, limit) => {
    calls += 1;
    if (calls === 2) throw new Error("the object died");
    return source.filter((row) => byteOrder(row.path, after) > 0).slice(0, limit);
  });
  expect(() => object.wake().fill()).toThrow("the object died");
  const woken = object.wake();
  // a fill that began keeps what is written meanwhile
  expect(woken.active()).toBe(true);
  woken.fill();
  expect(woken.watches()).toMatchObject({ rows: 1_100, rev: 1_100 });
  // the second object read the two pages that were left, and the empty page that ends the fill
  expect(calls).toBe(5);
});

test("tables of another schema are made again and filled again, and a cursor of the old ones gets every row", () => {
  const source = [task(1, "open", 10), task(2, "open", 20)];
  using object = fakeObject((after, limit) =>
    source.filter((row) => byteOrder(row.path, after) > 0).slice(0, limit),
  );
  const client = new Client();
  client.connect(object.wake());
  const spec = { where: { status: "open" }, limit: 5 };
  client.subscribe(object.wake(), "open", spec);
  const sub = client.subs.get("open")!;
  expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 2 });
  const generation = sub.gen;

  // a later release of the kernel keeps its tables in another shape
  object.db.exec("UPDATE rcat_meta SET v = 'an earlier schema' WHERE k = 'schema'");
  client.socket!.close();
  object.sockets.delete(client.socket!);
  const later = object.wake();
  client.connect(later);
  // The watcher's cursor fits the new tables by its numbers alone: the two rows have the same
  // revisions and the same keys again. Only the generation says that it is of other tables.
  client.subscribe(later, "open", spec, true);
  expect(sub.answers.at(-1)).toMatchObject({ reset: true, put: 2 });
  expect(sub).not.toMatchObject({ gen: generation });
  expect(later.watches({ verify: true })).toMatchObject({ active: true, rows: 2, faults: [] });
});

test("a full socket and a full catalog refuse a query as a limit, not as a fault of the query", () => {
  using object = fakeObject();
  const catalog = object.wake();
  catalog.fill();
  // eight sockets, each with as many queries as one may hold, all of them different
  const clients = Array.from(
    { length: CATALOG_LIMITS.windows / CATALOG_LIMITS.subsPerSocket },
    () => {
      const client = new Client();
      client.connect(catalog);
      return client;
    },
  );
  clients.forEach((client, at) => {
    for (let index = 0; index < CATALOG_LIMITS.subsPerSocket; index++)
      client.subscribe(catalog, `s${index}`, {
        where: { n: at * CATALOG_LIMITS.subsPerSocket + index },
      });
  });
  expect(catalog.watches().windows).toHaveLength(CATALOG_LIMITS.windows);
  // one more for a socket that is full
  clients[0]!.subscribe(catalog, "one-more", { limit: 3 });
  expect(clients[0]!).toMatchObject({
    refusals: [{ kind: "limit", error: expect.stringContaining("at most 64 watches") }],
  });
  // one more for the catalog, on a socket that has room
  const late = new Client();
  late.connect(catalog);
  late.subscribe(catalog, "q", { limit: 3 });
  expect(late).toMatchObject({
    refusals: [
      { kind: "limit", error: expect.stringContaining("at most 512 different live queries") },
    ],
  });
  // a query that another socket watches already is no new one
  late.subscribe(catalog, "shared", { where: { n: 5 } });
  expect(late.refusals).toHaveLength(1);
  // a socket that ended with no close event: at the limit its windows go, and there is room
  clients[1]!.socket!.close();
  object.sockets.delete(clients[1]!.socket!);
  const woken = object.wake();
  late.subscribe(woken, "q", { limit: 3 });
  expect(late.refusals).toHaveLength(1);
  expect(woken.watches().windows).toHaveLength(
    CATALOG_LIMITS.windows - CATALOG_LIMITS.subsPerSocket + 1,
  );
  // a query that cannot be answered is the query's own fault
  late.subscribe(woken, "bad", { limit: 0 });
  expect(late.refusals.at(-1)).toMatchObject({ kind: "query" });
});

test("no fact of a row is cut in silence: the 65th tag is found, and a row with more facts than the index takes is refused whole", () => {
  using object = fakeObject();
  const catalog = object.wake();
  catalog.fill();
  const tags = Array.from({ length: 65 }, (_, index) => `tag-${index}`);
  catalog.upsert({ path: "/agents/tagged", activeMs: 1, createdMs: 1, metadata: { tags } });
  const client = new Client();
  client.connect(catalog);
  client.subscribe(catalog, "last", { where: { tags: "tag-64" } });
  expect([...client.subs.get("last")!.rows.keys()]).toEqual(["/agents/tagged"]);

  // more facts than the catalog indexes for a row: refused, with the count
  const many = Array.from({ length: CATALOG_LIMITS.factsPerRow }, (_, index) => `t${index}`);
  expect(() =>
    catalog.upsert({ path: "/agents/huge", activeMs: 2, createdMs: 2, metadata: { tags: many } }),
  ).toThrow(/has 2051 facts, and the catalog indexes at most 2048/);
  // as the catalog hands it over: the row leaves the copy, and a watcher sees no old row of it
  catalog.upsert({ path: "/agents/huge", activeMs: 1, createdMs: 1, metadata: { tags: ["t0"] } });
  client.subscribe(catalog, "huge", { keys: ["/agents/huge"] });
  expect(client.subs.get("huge")!.rows).toMatchObject({ size: 1 });
  vi.spyOn(console, "info").mockImplementation(() => {});
  catalog.keep({ path: "/agents/huge", activeMs: 2, createdMs: 2, metadata: { tags: many } });
  expect(client.subs.get("huge")!.rows).toMatchObject({ size: 0 });
  expect(catalog.watches()).toMatchObject({ owed: 0 });

  // a key that starts with `$` is the kernel's: a query cannot name one that it has not
  client.subscribe(catalog, "bad", { where: { $owner: "ada" } });
  expect(client.refusals.at(-1)).toMatchObject({
    kind: "query",
    error: expect.stringContaining('no fact "$owner"'),
  });
  client.subscribe(catalog, "good", { where: { $processor: "agent" } });
  expect(client.refusals).toHaveLength(1);
});

test("a write that the copy cannot make is owed: it is reported, and made again from the catalog's own row", () => {
  vi.useFakeTimers();
  onTestFinished(() => void vi.useRealTimers());
  const reported = vi.spyOn(console, "error").mockImplementation(() => {});
  using object = fakeObject();
  const catalog = object.wake();
  catalog.fill();
  const client = new Client();
  client.connect(catalog);
  client.subscribe(catalog, "open", { where: { status: "open" }, limit: 5 });
  const sub = client.subs.get("open")!;

  // the copy's store fails for one context's row
  const boom = task(1, "open", 10);
  object.catalogRows.set(boom.path, boom);
  object.failing.when = (query, params) =>
    query.startsWith("INSERT INTO rcat_row") && params[0] === boom.path;
  catalog.keep(boom);
  expect(sub.rows).toMatchObject({ size: 0 });
  expect(catalog.watches()).toMatchObject({ owed: 1, rows: 0 });
  expect(reported).toHaveBeenCalledTimes(1);

  // another context's summary, before the owed write is due: it is kept, and the debt stays
  catalog.keep(task(2, "open", 20));
  expect([...sub.rows.keys()]).toEqual(["/tasks/t0002"]);
  expect(catalog.watches()).toMatchObject({ owed: 1 });

  // an object that wakes knows of the debt, and a write a minute later settles it
  object.failing.when = undefined;
  vi.advanceTimersByTime(60_000);
  const woken = object.wake();
  woken.keep(task(3, "closed", 30));
  expect([...sub.rows.keys()].toSorted()).toEqual(["/tasks/t0001", "/tasks/t0002"]);
  expect(woken.watches({ verify: true })).toMatchObject({ owed: 0, faults: [] });
  expect(reported).toHaveBeenCalledTimes(1);
});

test("an owed write that keeps failing is tried eight times, at longer waits, and a later summary of that context pays it", () => {
  vi.useFakeTimers();
  onTestFinished(() => void vi.useRealTimers());
  vi.spyOn(console, "error").mockImplementation(() => {});
  using object = fakeObject();
  const catalog = object.wake();
  catalog.fill();
  const boom = task(1, "open", 10);
  object.catalogRows.set(boom.path, boom);
  let tries = 0;
  object.failing.when = (query, params) => {
    const hit = query.startsWith("INSERT INTO rcat_row") && params[0] === boom.path;
    if (hit) tries += 1;
    return hit;
  };
  catalog.keep(boom);
  const waits: number[] = [];
  let tick = 0;
  for (let step = 0; step < 400 && tries < CATALOG_LIMITS.owedTries; step++) {
    const before = tries;
    vi.advanceTimersByTime(30_000);
    tick += 30_000;
    // any other context's summary is a chance to settle what is due
    catalog.keep(task(2, "open", 100 + step));
    if (tries > before) {
      waits.push(tick);
      tick = 0;
    }
  }
  // one minute, then doubled, thirty minutes at most
  expect(waits).toEqual([60_000, 120_000, 240_000, 480_000, 960_000, 1_800_000, 1_800_000]);
  // and then no more: the mark stays, for a person to see
  vi.advanceTimersByTime(24 * 60 * 60_000);
  catalog.keep(task(2, "open", 9_999));
  expect(tries).toBe(CATALOG_LIMITS.owedTries);
  expect(catalog.watches()).toMatchObject({ owed: 1 });
  // the context's own next summary, which the copy can write, pays the debt
  object.failing.when = undefined;
  catalog.keep(task(1, "open", 10_000));
  expect(catalog.watches()).toMatchObject({ owed: 0, rows: 2 });
});

test("a write that is longer than one message comes in parts, each but the last marked", () => {
  using object = fakeObject();
  const catalog = object.wake();
  catalog.fill();
  const client = new Client();
  client.connect(catalog);
  client.subscribe(catalog, "all", { limit: 50 });
  const parts: boolean[] = [];
  client.onChange = (message) => parts.push(!!message.more);
  // one transaction of 30 rows, each with a description of 20,000 characters
  expect(
    catalog.upsertMany(
      Array.from({ length: 30 }, (_, index) => ({
        ...task(index, "open", index),
        description: "x".repeat(20_000),
      })),
    ),
  ).toMatchObject({ changed: 30, frames: 30 });
  expect(parts.length).toBeGreaterThan(1);
  expect(parts).toEqual([...parts.slice(0, -1).map(() => true), false]);
  expect(client.subs.get("all")!.rows).toMatchObject({ size: 30 });
});

test("one write is one message for a socket, over all of its queries", () => {
  using object = fakeObject();
  const catalog = object.wake();
  const client = new Client();
  client.connect(catalog);
  client.subscribe(catalog, "open", { where: { status: "open" }, limit: 5 });
  client.subscribe(catalog, "byPath", { under: "/tasks", order: "path", limit: 5 });
  client.subscribe(catalog, "key", { keys: ["/tasks/t0001"] });
  client.messages = 0;
  expect(catalog.upsert(task(1, "open", 10))).toMatchObject({ frames: 3, messages: 1 });
  expect(client).toMatchObject({ messages: 1 });
  for (const name of ["open", "byPath", "key"])
    expect(client.subs.get(name)!.rows.has("/tasks/t0001"), name).toBe(true);
});

// ── A Durable Object's SQLite, sockets and hibernation, in Node ──

function sqlOf(
  db: DatabaseSync,
  failing: { when?: (query: string, params: unknown[]) => boolean },
) {
  // prepared once for each text, as a Durable Object's own `sql.exec` keeps its statements
  const prepared = new Map<string, ReturnType<DatabaseSync["prepare"]>>();
  return {
    exec(query: string, ...params: unknown[]) {
      if (failing.when?.(query, params)) throw new Error("the store said no");
      let statement = prepared.get(query);
      if (!statement) prepared.set(query, (statement = db.prepare(query)));
      const rows = statement.all(...(params as never[])) as Record<string, unknown>[];
      return { toArray: () => rows };
    },
  };
}

class FakeSocket {
  readyState = WebSocket.OPEN;
  attachment: unknown = null;
  onMessage: (raw: string) => void = () => {};
  send(raw: string) {
    if (this.readyState !== WebSocket.OPEN) throw new Error("the socket is closed");
    this.onMessage(raw);
  }
  close() {
    this.readyState = WebSocket.CLOSED;
  }
  serializeAttachment(value: unknown) {
    this.attachment = structuredClone(value);
  }
  deserializeAttachment() {
    return structuredClone(this.attachment);
  }
}

function fakeObject(seed: (after: string, limit: number) => CatalogRowInput[] = () => []) {
  const db = new DatabaseSync(":memory:");
  const sockets = new Set<FakeSocket>();
  const awake = new Map<string, { since: number; activities?: { key: string; text: string }[] }>();
  const catalogRows = new Map<string, CatalogRowInput>();
  const failing: { when?: (query: string, params: unknown[]) => boolean } = {};
  const ctx = {
    getWebSockets: () => [...sockets],
    acceptWebSocket: (ws: FakeSocket) => void sockets.add(ws),
    getTags: () => ["catalog-watch"],
    storage: {
      transactionSync<T>(work: () => T): T {
        db.exec("BEGIN");
        try {
          const answer = work();
          db.exec("COMMIT");
          return answer;
        } catch (error) {
          db.exec("ROLLBACK");
          throw error;
        }
      },
    },
  };
  return {
    db,
    sockets,
    awake,
    /** A new instance over the same storage and sockets: what a hibernation leaves. */
    wake: () =>
      new ReactiveCatalog(sqlOf(db, failing) as never, ctx as never, {
        awake: () => awake,
        seed,
        row: (path) => catalogRows.get(path),
      }),
    /** The catalog's own rows, which a write that the copy owes is made again from. */
    catalogRows,
    /** A statement that this answers true for throws, as a store that fails does. */
    failing,
    [Symbol.dispose]: () => db.close(),
  };
}

function task(index: number, status: string, at: number): Omit<ModelRow, "rev"> {
  return {
    path: `/tasks/t${String(index).padStart(4, "0")}`,
    activeMs: at,
    createdMs: index,
    description: `Task ${index}`,
    processors: ["task"],
    metadata: { status },
  };
}

// ── The oracle ──

/** A row as these tests write and read it. The engine keeps any body: here a description and a
 *  count, which change with no change of a sort value. */
type ModelRow = {
  path: string;
  activeMs: number;
  createdMs: number;
  rev: number;
  description?: string;
  eventCount?: number;
  processors: string[];
  metadata: Record<string, unknown>;
};

const bytes = new Map<string, Buffer>();
function byteOrder(a: string, b: string): number {
  const of = (text: string) => bytes.get(text) || bytes.set(text, Buffer.from(text)).get(text)!;
  return Buffer.compare(of(a), of(b));
}

/** A window's order, written again here: the engine's own comparison is what is tested. */
function windowOrder(order: CatalogOrder | undefined) {
  return (a: ModelRow, b: ModelRow) => {
    if (order === "path") return byteOrder(a.path, b.path);
    const [x, y] = order === "created" ? [a.createdMs, b.createdMs] : [a.activeMs, b.activeMs];
    return x !== y ? y - x : -byteOrder(a.path, b.path);
  };
}

// a write replaces a model row by a new object, so a row's facts are worked out once
const factsOfRow = new WeakMap<ModelRow, Set<string>>();
function oracleFacts(row: ModelRow): Set<string> {
  const known = factsOfRow.get(row);
  if (known) return known;
  const facts = new Set<string>();
  factsOfRow.set(row, facts);
  const parts = row.path.split("/").filter(Boolean);
  if (row.path !== "/")
    facts.add(`$parent=${parts.length > 1 ? `/${parts.slice(0, -1).join("/")}` : "/"}`);
  parts.forEach((_, index) => facts.add(`$under=/${parts.slice(0, index + 1).join("/")}`));
  for (const name of row.processors) facts.add(`$processor=${name}`);
  for (const [key, raw] of Object.entries(row.metadata)) {
    if (key.startsWith("$")) continue;
    for (const item of Array.isArray(raw) ? raw : [raw])
      if (["string", "number", "boolean"].includes(typeof item))
        facts.add(`${key}=${String(item)}`);
  }
  return facts;
}

function oracle(model: ReadonlyMap<string, ModelRow>, spec: CatalogQuery): ModelRow[] {
  if (spec.keys) {
    const wanted = new Set(spec.keys);
    return [...model.values()].filter((row) => wanted.has(row.path));
  }
  const wanted: string[] = Object.entries(spec.where || {}).map(
    ([key, value]) => `${key}=${String(value)}`,
  );
  if (spec.under && spec.under !== "/") wanted.push(`$under=${spec.under}`);
  if (spec.childrenOf) wanted.push(`$parent=${spec.childrenOf}`);
  return [...model.values()]
    .filter((row) => {
      const facts = oracleFacts(row);
      return wanted.every((fact) => facts.has(fact));
    })
    .sort(windowOrder(spec.order))
    .slice(0, spec.limit || 50);
}

/** A row as a watcher gets it: a key whose value is absent is not sent. */
const wireRows = new WeakMap<ModelRow, ModelRow>();
function wireRow(row: ModelRow): ModelRow {
  const known = wireRows.get(row);
  if (known) return known;
  const wire = JSON.parse(JSON.stringify(row)) as ModelRow;
  wireRows.set(row, wire);
  return wire;
}

// ── A watcher: a map of rows for each query, as the session's end keeps none and a page does ──

type ClientSub = {
  spec: CatalogQuery;
  rows: Map<string, ModelRow>;
  gen: string;
  rev: number;
  q: string;
  /** Change frames since the test last looked. */
  frames: number;
  answers: { reset: boolean; put: number; chars: number }[];
};

function newSub(spec: CatalogQuery): ClientSub {
  return { spec, rows: new Map(), gen: "", rev: -1, q: "", frames: 0, answers: [] };
}

class Client {
  socket: FakeSocket | undefined;
  subs = new Map<string, ClientSub>();
  errors: string[] = [];
  refusals: { kind: string; error: string }[] = [];
  onChange: (message: { more?: true }) => void = () => {};
  /** Messages since the test last looked. */
  messages = 0;

  connect(catalog: ReactiveCatalog) {
    const socket = new FakeSocket();
    socket.onMessage = (raw) => this.#receive(raw);
    this.socket = socket;
    catalog.attachWatchSocket(socket as never);
  }

  #receive(raw: string) {
    const message = JSON.parse(raw);
    if (message.hello) return;
    this.messages += 1;
    if (message.error) {
      this.refusals.push({ kind: message.kind, error: message.error });
      return void this.errors.push(message.error);
    }
    if (message.unsubscribed) return;
    if (message.sub) {
      const sub = this.subs.get(message.sub)!;
      if (message.reset) sub.rows = new Map(message.reset.map((row: ModelRow) => [row.path, row]));
      else {
        const keep = new Set<string>(message.ids);
        for (const path of [...sub.rows.keys()]) if (!keep.has(path)) sub.rows.delete(path);
        for (const row of message.put) sub.rows.set(row.path, row);
        expect([...sub.rows.keys()].sort()).toEqual([...keep].sort());
      }
      Object.assign(sub, { gen: message.gen, rev: message.rev, q: message.q });
      sub.answers.push({
        reset: !!message.reset,
        put: (message.reset || message.put).length,
        chars: raw.length,
      });
      return;
    }
    this.onChange(message);
    const rows = new Map<string, ModelRow>(message.rows.map((row: ModelRow) => [row.path, row]));
    for (const [name, from, rev, del, put] of message.d as [
      string,
      number,
      number,
      string[],
      string[],
    ][]) {
      const sub = this.subs.get(name);
      if (!sub) throw new Error(`a frame for the query ${name}, which this watcher does not hold`);
      expect({ gen: message.gen, from }).toEqual({ gen: sub.gen, from: sub.rev });
      for (const path of del) expect(sub.rows.delete(path), `${name} deletes ${path}`).toBe(true);
      for (const path of put) sub.rows.set(path, rows.get(path)!);
      sub.rev = rev;
      sub.frames += 1;
    }
  }

  /** The rows of a query in its own order. */
  sorted(sub: ClientSub): ModelRow[] {
    return [...sub.rows.values()].sort(windowOrder(sub.spec.order));
  }

  cursorOf(sub: ClientSub): CatalogCursor {
    const base = { gen: sub.gen, rev: sub.rev, q: sub.q };
    if (sub.spec.keys) return { ...base, have: [...sub.rows.keys()] };
    const last = this.sorted(sub).at(-1);
    if (!last) return { ...base, bound: null };
    const at =
      sub.spec.order === "path" ? 0 : sub.spec.order === "created" ? last.createdMs : last.activeMs;
    return { ...base, bound: [at, last.path] };
  }

  subscribe(catalog: ReactiveCatalog, name: string, spec: CatalogQuery, withCursor = false) {
    const had = this.subs.get(name);
    // the cursor is of the rows that the watcher holds, in the order it held them
    const cursor = withCursor && had ? this.cursorOf(had) : undefined;
    const sub = had && withCursor ? had : newSub(spec);
    sub.spec = spec;
    this.subs.set(name, sub);
    catalog.handleWatchMessage(
      this.socket as never,
      JSON.stringify({ op: "subscribe", sub: name, query: spec, cursor }),
    );
  }

  unsubscribe(catalog: ReactiveCatalog, name: string) {
    this.subs.delete(name);
    catalog.handleWatchMessage(
      this.socket as never,
      JSON.stringify({ op: "unsubscribe", sub: name }),
    );
  }
}

/** A watcher's row, and the oracle's row that it was found equal to: a row is an object that a
 *  write replaces, on both sides, so each pair is compared in depth once. */
const foundEqual = new WeakMap<ModelRow, ModelRow>();

function expectClientMatches(client: Client, model: ReadonlyMap<string, ModelRow>, label: string) {
  for (const [name, sub] of client.subs) {
    // a keys query has no order of its own
    const order = (rows: ModelRow[]) =>
      sub.spec.keys ? rows.toSorted((a, b) => byteOrder(a.path, b.path)) : rows;
    const wanted = order(oracle(model, sub.spec).map(wireRow));
    const have = order(client.sorted(sub));
    if (
      have.length === wanted.length &&
      have.every((row, at) => foundEqual.get(row) === wanted[at])
    )
      continue;
    expect(have, `${label}: query ${name} ${JSON.stringify(sub.spec)}`).toEqual(wanted);
    have.forEach((row, at) => foundEqual.set(row, wanted[at]!));
  }
  expect(client, label).toMatchObject({ errors: [] });
}

// ── The random run ──

function random(seed: number) {
  let state = seed >>> 0;
  const next = () => {
    state = (state + 0x6d2b79f5) >>> 0;
    let t = state;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
  const int = (below: number) => Math.floor(next() * below);
  return { next, int, pick: <T>(items: readonly T[]): T => items[int(items.length)]! };
}

// paths outside ASCII on purpose: U+E000 sorts BEFORE an emoji in UTF-8 and AFTER it in UTF-16
const PATHS = [
  ...Array.from({ length: 36 }, (_, index) => `/tasks/t${String(index).padStart(2, "0")}`),
  ...Array.from({ length: 6 }, (_, index) => `/agents/a${index}`),
  "/agents/a0/sub",
  "/agents/a1/sub/deeper",
  "/docs/😀",
  "/docs/x",
  "/docs/é",
  "/docs/z",
  "/docs/😀/child",
  "/x",
];

const QUERIES: CatalogQuery[] = [
  { where: { status: "open" }, limit: 1 },
  { where: { status: "open" }, limit: 2 },
  { where: { status: "open" }, limit: 7 },
  { where: { status: "open" }, limit: 50 },
  { where: { status: "closed" }, limit: 3 },
  { where: { status: "open", priority: "high" }, limit: 3 },
  { where: { tags: "pinned" }, limit: 5 },
  { where: { tags: "a", status: "open" }, limit: 4 },
  { where: { priority: 3 }, limit: 4 },
  { where: { flag: true }, limit: 2 },
  { under: "/tasks", limit: 7 },
  { under: "/docs", limit: 3 },
  { under: "/agents", where: { kind: "agent" }, limit: 3 },
  { childrenOf: "/agents", limit: 4 },
  { childrenOf: "/docs", limit: 2 },
  { where: { $processor: "agent" }, limit: 3 },
  { limit: 5 },
  { limit: 1 },
  // the other two orders, with one fact, two facts and none
  { where: { status: "open" }, order: "created", limit: 3 },
  { where: { status: "open", priority: "high" }, order: "created", limit: 2 },
  { under: "/tasks", order: "created", limit: 6 },
  { order: "created", limit: 4 },
  { order: "created", limit: 1 },
  { where: { status: "open" }, order: "path", limit: 3 },
  { where: { tags: "a", status: "open" }, order: "path", limit: 2 },
  { childrenOf: "/docs", order: "path", limit: 3 },
  { under: "/docs", order: "path", limit: 4 },
  { order: "path", limit: 5 },
  { order: "path", limit: 1 },
];

function randomRow(rng: ReturnType<typeof random>, clock: { now: number }): Omit<ModelRow, "rev"> {
  const path = rng.pick(PATHS);
  const agent = path.startsWith("/agents");
  // a few timestamps, to force ties; and now and then a fresh one, the newest of all
  const activeMs = rng.next() < 0.25 ? (clock.now += 1 + rng.int(3)) : 1_000 + rng.int(6);
  const tags = ["a", "b", "pinned"].filter(() => rng.next() < 0.3);
  return {
    path,
    activeMs,
    // a context is made once: its time mostly stays, and a few contexts share one
    createdMs: rng.next() < 0.1 ? 500 + rng.int(4) : 100 + (path.length % 5),
    ...(rng.next() < 0.3 && { description: `about ${rng.int(3)}` }),
    ...(rng.next() < 0.5 && { eventCount: rng.int(3) }),
    processors: agent ? ["agent"] : rng.next() < 0.2 ? ["task", "agent"] : [],
    metadata: {
      status: rng.pick(["open", "open", "closed"]),
      priority: rng.pick(["high", "normal", 3]),
      ...(tags.length > 0 && { tags }),
      ...(agent && { kind: "agent" }),
      ...(rng.next() < 0.2 && { flag: rng.next() < 0.5 }),
      nested: { ignored: true },
    },
  };
}

function runSeed(seed: number, steps: number) {
  const rng = random(seed);
  using object = fakeObject();
  let catalog = object.wake();
  catalog.fill();
  const model = new Map<string, ModelRow>();
  let rev = 0;
  const clock = { now: 2_000 };
  const clients: Client[] = [];
  const away: Client[] = [];
  const tally = { writes: 0, frames: 0, quiet: 0, resumes: 0, rowsHeld: 0, hibernations: 0 };

  const valueOf = (row: Omit<ModelRow, "rev">) => JSON.stringify(wireRow({ ...row, rev: 0 }));

  /** Applies a write to the model as the engine must apply it. True when it changed a row. */
  const modelUpsert = (input: Omit<ModelRow, "rev">): boolean => {
    const old = model.get(input.path);
    if (old && valueOf(old) === valueOf(input)) return false;
    rev += 1;
    model.set(input.path, { ...input, rev });
    return true;
  };
  const modelDelete = (path: string): boolean => {
    if (!model.delete(path)) return false;
    rev += 1;
    return true;
  };
  const answerOf = (spec: CatalogQuery) =>
    JSON.stringify(oracle(model, spec).map((row) => [row.path, row.rev]));

  for (let step = 0; step < steps; step++) {
    const roll = rng.next();
    const label = `seed ${seed} step ${step}`;

    if (roll < 0.52) {
      // one write: a frame goes to exactly the queries whose answer changed
      const watched = clients.flatMap((client) =>
        [...client.subs].map(([name, sub]) => ({ name, sub, before: answerOf(sub.spec) })),
      );
      for (const entry of watched) entry.sub.frames = 0;
      let changed: boolean;
      let result;
      const kind = rng.next();
      if (kind < 0.12 && model.size > 0) {
        const path = rng.pick([...model.keys()]);
        changed = modelDelete(path);
        result = catalog.deleteMany([path]);
      } else if (kind < 0.2 && model.size > 0) {
        // the same row again: no revision, no frame
        const { rev: _rev, ...same } = model.get(rng.pick([...model.keys()]))!;
        changed = modelUpsert(same);
        result = catalog.upsert(same);
      } else {
        const input = randomRow(rng, clock);
        changed = modelUpsert(input);
        result = catalog.upsert(input);
      }
      expect(result, label).toMatchObject({ rev, changed: changed ? 1 : 0 });
      tally.writes += 1;
      let expectedFrames = 0;
      for (const { sub, before, name } of watched) {
        const frames = before === answerOf(sub.spec) ? 0 : 1;
        // said only when it fails: an assertion for each query at each write is most of the run
        if (sub.frames !== frames)
          expect(sub, `${label}: frames for ${name} ${JSON.stringify(sub.spec)}`).toMatchObject({
            frames,
          });
        expectedFrames += sub.frames;
      }
      tally.frames += expectedFrames;
      if (expectedFrames === 0) tally.quiet += 1;
    } else if (roll < 0.58) {
      // a batch in one transaction
      const inputs = Array.from({ length: 2 + rng.int(5) }, () => randomRow(rng, clock));
      const changed = inputs.filter((input) => modelUpsert(input)).length;
      expect(catalog.upsertMany(inputs), label).toMatchObject({ rev, changed });
    } else if (roll < 0.6 && model.size > 3) {
      const paths = [rng.pick([...model.keys()]), rng.pick([...model.keys()]), "/never/there"];
      const changed = paths.filter((path) => modelDelete(path)).length;
      expect(catalog.deleteMany(paths), label).toMatchObject({ changed });
    } else if (roll < 0.7) {
      if (clients.length < 5 && (clients.length === 0 || rng.next() < 0.4)) {
        const client = new Client();
        client.connect(catalog);
        clients.push(client);
      }
      const client = rng.pick(clients);
      if (client.subs.size < 6)
        client.subscribe(
          catalog,
          `s${step}`,
          rng.next() < 0.15
            ? { keys: Array.from({ length: 1 + rng.int(6) }, () => rng.pick(PATHS)) }
            : rng.pick(QUERIES),
        );
    } else if (roll < 0.74 && clients.length > 0) {
      const client = rng.pick(clients);
      if (client.subs.size > 0) client.unsubscribe(catalog, rng.pick([...client.subs.keys()]));
    } else if (roll < 0.77 && clients.length > 0) {
      // the same name, another query: the old window is let go
      const client = rng.pick(clients);
      if (client.subs.size > 0)
        client.subscribe(catalog, rng.pick([...client.subs.keys()]), rng.pick(QUERIES));
    } else if (roll < 0.82) {
      // hibernation: the object's memory goes, its storage and its sockets stay
      catalog = object.wake();
      tally.hibernations += 1;
    } else if (roll < 0.87 && clients.length > 0) {
      // a watcher goes away, with a close event or with none
      const client = clients.splice(rng.int(clients.length), 1)[0]!;
      const socket = client.socket!;
      socket.close();
      object.sockets.delete(socket);
      if (rng.next() < 0.5) catalog.handleWatchClose(socket as never);
      away.push(client);
    } else if (roll < 0.94 && away.length > 0) {
      // it comes back on a new socket, with its cursor for each query or with none
      const client = away.splice(rng.int(away.length), 1)[0]!;
      client.connect(catalog);
      const withCursor = rng.next() < 0.8;
      for (const [name, sub] of [...client.subs]) {
        const held = sub.rows.size;
        client.subscribe(catalog, name, sub.spec, withCursor);
        const answer = client.subs.get(name)!.answers.at(-1)!;
        if (withCursor && !answer.reset) {
          tally.resumes += 1;
          tally.rowsHeld += Math.max(0, held - answer.put);
        }
      }
      clients.push(client);
    } else {
      // six queries of the pool, asked anew by a watcher that holds nothing, against the oracle
      const fresh = new Client();
      fresh.connect(catalog);
      for (let index = 0; index < 6; index++)
        fresh.subscribe(catalog, `f${index}`, rng.pick(QUERIES));
      expectClientMatches(fresh, model, `${label}: asked anew`);
      catalog.handleWatchClose(fresh.socket as never);
      object.sockets.delete(fresh.socket!);
    }
    for (const client of clients) expectClientMatches(client, model, label);
    expect(catalog.verify(), label).toEqual([]);
  }
  return tally;
}