iterate.com / kernel

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

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

// reactive-catalog.ts — THE CATALOG AS A COLLECTION THAT ANSWERS REACTIVE QUERIES. It runs in the
// context that accepts the awake sockets (awake.ts), beside the catalog's own rows
// (context-catalog.ts), in tables of its own (`rcat_*`). Nothing under it changes: a context still
// folds its log into a summary and sends it down its awake socket. This file keeps a copy of what
// arrives, as a row with an index of facts, and tells the watchers of a query what a write changed.
//
// A ROW is one context: its path, when it was last active, when it was made, and what its listing
// says of it (iterate/api `CatalogRow`). Its FACTS are every scalar at the top of its metadata (and
// each scalar of a list there), and the kernel's own: `$parent`, `$under` for the path and each
// ancestor, `$processor`.
//
// A WATCHED QUERY is a window over that index: the rows that hold every fact the query names, in
// one order, up to a limit. No query is known ahead of time: a watcher sends one at run time, and
// any two watchers may send different ones (iterate/api `CatalogQuery`).
//
// THE ORDERS. Each is total (the path breaks every tie) and each has one index of the facts:
//   active   the newest activity first   rcat_fact_active  (k, v, active_at DESC, path DESC)
//   created  the newest context first    rcat_fact_created (k, v, created_at DESC, path DESC)
//   path     by path, A to Z             rcat_fact_path    (k, v, path)
// A row's new activity moves its entries of `active` alone. The entries of the other two change
// only when the row's facts do, so two more orders cost a common write nothing.
//
// For a window the object keeps two values, in SQLite: its SIZE and its BOUND, the sort key of its
// last row (Zero's `take` operator). A write changes a window only when the row's old key or its
// new key is at or before the bound. Any other write costs the window nothing: no statement, no
// frame. A row that leaves a full window is replaced by the one row after the bound, in the same
// frame.
//
// Three kinds of query:
//   a window — `{ where, under, childrenOf, order, limit }`
//   keys     — `{ keys: [paths] }`: exactly these rows, which is what a join asks for
//   awake    — `{ awake: true }`: the contexts that hold an awake socket now, from the sockets alone
//
// TEXT IS ORDERED AS SQLITE ORDERS IT: a path is compared as UTF-8 bytes, here and in every
// watcher (`compareTextBinary`). JavaScript's `<` puts U+E000 after an emoji, and UTF-8 puts it
// before.
//
// NOTHING IS KEPT UNTIL SOMEONE WATCHES. The first watch copies every row of the catalog, a page
// at a time (`fill`), and from then on each summary that the catalog keeps is written here too. A
// mind that never watches pays for no index.
//
// THE WIRE, as JSON on a hibernated WebSocket of its own. Its other end is the session's end
// (catalog-watch.ts), never a client: a client holds a capnweb callback.
//   to the object:  { op: "subscribe", sub, query, cursor? } · { op: "unsubscribe", sub }
//   the answer to a subscribe:  { sub, q, gen, rev, full, reset: [rows] }, or with a cursor the
//                   object accepts { sub, q, gen, rev, full, ids: [paths], put: [rows] }: every
//                   path of the window, and only the rows the watcher lacks
//   a change:       { gen, rows: [rows], d: [[sub, from, rev, [paths to delete], [paths to put]]] }
//                   ONE message for each socket and write (or batch of writes), over all of the
//                   socket's queries, so a join never sees half of a write. `from` is the revision
//                   of the query's frame before. A write that is longer than
//                   `CATALOG_LIMITS.messageChars` is cut into several messages, and each but the
//                   last says `more: true`: the session's end hands them on as one batch.
//   a refusal:      { sub, kind: "query" | "limit" | "failed", error }: the query cannot be
//                   answered, a limit is reached, or the catalog itself failed
//
// A watcher that comes back sends its cursor `{ gen, rev, q, bound }`: the generation, the
// revision of its last frame, the name of what the query selects, and the sort key of the last row
// it holds. A row is HELD when it is unchanged since `rev` and its key is at or before `bound`.
// The second half matters: a row that backfilled while the watcher was away has an old revision,
// and the watcher never had it.
import { z } from "zod";
import type { CatalogOrder, CatalogWatches } from "iterate/api";
import { reportIssue } from "iterate/lib";
import type { AwakeContextState } from "./awake.ts";
import { activeContextActivities } from "./context-activity-stack.ts";

export const CATALOG_LIMITS = {
  /** The most rows of one window. */
  limit: 500,
  /** The most live windows of the object, over all sockets. */
  windows: 512,
  /** The most queries of one socket. */
  subsPerSocket: 64,
  predicates: 8,
  keys: 500,
  /** No summary that the catalog keeps comes near it (4,000 characters of metadata, a path of
   *  512). A row with more is REFUSED, never cut: a fact that is not indexed would be a row that
   *  a query misses. */
  factsPerRow: 2_048,
  factKeyChars: 80,
  factValueChars: 200,
  pathChars: 512,
  /** The most characters of a row's stored JSON. A summary's own limits keep a row far below it:
   *  200 event types, 4,000 characters of metadata, 2,000 of description. */
  bodyChars: 32_000,
  subChars: 16,
  /** A change message is cut into parts of about this many characters. */
  messageChars: 256_000,
  /** How many rows one transaction of the first fill writes. */
  fillPage: 500,
  /** How many times a write that the copy owes is made again before it is left as it is. */
  owedTries: 8,
} as const;

const SCHEMA = "1";
const WATCH_SOCKET_TAG = "catalog-watch";

/** A refusal that the watcher or the writer caused: its message goes back to them. */
export class CatalogRefusal extends Error {}

/** A refusal that is no fault of the query: the catalog, or the watcher's socket, holds as many
 *  live queries as it may. */
export class CatalogLimit extends Error {}

// ── The order ──

/** No lone surrogate: such a text has one UTF-8 form, which is what SQLite stores and compares. */
function wellFormed(text: string): boolean {
  for (let i = 0; i < text.length; i++) {
    const unit = text.charCodeAt(i);
    if (unit < 0xd800 || unit > 0xdfff) continue;
    const next = text.charCodeAt(i + 1);
    if (unit > 0xdbff || !(next >= 0xdc00 && next <= 0xdfff)) return false;
    i += 1;
  }
  return true;
}

/** As SQLite's BINARY collation compares two texts: by their UTF-8 bytes. For well-formed strings
 *  that differs from UTF-16 code unit order in one case: a surrogate (a code point from U+10000)
 *  against a code unit from U+E000 to U+FFFF. No bytes are made. */
export function compareTextBinary(a: string, b: string): number {
  if (a === b) return 0;
  const shared = Math.min(a.length, b.length);
  for (let i = 0; i < shared; i++) {
    const x = a.charCodeAt(i);
    const y = b.charCodeAt(i);
    if (x === y) continue;
    const xSurrogate = x >= 0xd800 && x <= 0xdfff;
    const ySurrogate = y >= 0xd800 && y <= 0xdfff;
    if (xSurrogate === ySurrogate) return x < y ? -1 : 1;
    return xSurrogate ? 1 : -1;
  }
  return a.length < b.length ? -1 : 1;
}

/** Where a row stands in a window: the order's own value (0 for the order `path`), then the path. */
type SortKey = [at: number, path: string];

/** Each order's index of the facts, and the column that holds the order's own value there and in
 *  `rcat_row`. The order `path` has none: the path is the whole key. */
const ORDER_INDEX = {
  active: { facts: "rcat_fact_active", column: "active_at" },
  created: { facts: "rcat_fact_created", column: "created_at" },
  path: { facts: "rcat_fact_path", column: "" },
} as const satisfies Record<CatalogOrder, { facts: string; column: string }>;

/** Negative: `a` is before `b` in the window. */
function compareSortKeys(order: CatalogOrder, a: SortKey, b: SortKey): number {
  if (order === "path") return compareTextBinary(a[1], b[1]);
  if (a[0] !== b[0]) return a[0] > b[0] ? -1 : 1;
  return -compareTextBinary(a[1], b[1]);
}

/** `ORDER BY` in a window's order (`forward`) or against it, for the table alias `at`. */
function orderTerms(order: CatalogOrder, at: string, forward: boolean): string {
  const { column } = ORDER_INDEX[order];
  if (!column) return `${at}.path ${forward ? "ASC" : "DESC"}`;
  const direction = forward ? "DESC" : "ASC";
  return `${at}.${column} ${direction}, ${at}.path ${direction}`;
}

/** The rows strictly after `key` in a window's order (`after`), or strictly before it. */
function beyond(order: CatalogOrder, at: string, after: boolean, key: SortKey): Statement {
  const { column } = ORDER_INDEX[order];
  if (!column) return { sql: `${at}.path ${after ? ">" : "<"} ?`, args: [key[1]] };
  return { sql: `(${at}.${column}, ${at}.path) ${after ? "<" : ">"} (?, ?)`, args: [...key] };
}

// ── Facts ──

type Fact = [key: string, value: string];
const factId = ([key, value]: Fact) => `${key}\0${value}`;

function usableFact(key: string, value: string): boolean {
  return (
    key.length > 0 &&
    key.length <= CATALOG_LIMITS.factKeyChars &&
    value.length <= CATALOG_LIMITS.factValueChars &&
    !key.includes("\0") &&
    !value.includes("\0") &&
    wellFormed(key) &&
    wellFormed(value)
  );
}

const FactValue = z.union([z.string(), z.number(), z.boolean()]);

/** The facts of a row: the kernel's own (`$parent`, `$under` for the path and each ancestor,
 *  `$processor`), then each scalar and each scalar of a list at the top of `metadata`. A key that
 *  starts with `$` is the kernel's.
 *
 *  NOTHING IS CUT IN SILENCE. A fact that the index cannot hold (a key or a value that is too
 *  long, or is not plain text) is one that no query can name either: `normalizeQuery` refuses it.
 *  A row with more facts than `CATALOG_LIMITS.factsPerRow` is refused whole. */
function extractFacts(
  path: string,
  processors: readonly string[],
  metadata: Record<string, unknown>,
): Fact[] {
  const facts: Fact[] = [];
  const seen = new Set<string>();
  const add = (key: string, value: string) => {
    if (!usableFact(key, value)) return;
    const id = factId([key, value]);
    if (seen.has(id)) return;
    seen.add(id);
    facts.push([key, value]);
  };
  const parts = path.split("/").filter(Boolean);
  if (path !== "/") add("$parent", `/${parts.slice(0, -1).join("/")}`);
  parts.forEach((_, index) => add("$under", `/${parts.slice(0, index + 1).join("/")}`));
  for (const processor of processors) add("$processor", processor);
  for (const [key, raw] of Object.entries(metadata)) {
    if (key.startsWith("$")) continue;
    for (const item of Array.isArray(raw) ? raw : [raw]) {
      const value = FactValue.safeParse(item);
      // a number that is no number (NaN, an infinity) is no fact: it has no one text
      if (value.success && (typeof value.data !== "number" || Number.isFinite(value.data)))
        add(key, String(value.data));
    }
  }
  if (facts.length > CATALOG_LIMITS.factsPerRow)
    throw new CatalogRefusal(
      `the row of ${path} has ${facts.length} facts, and the catalog indexes at most ${CATALOG_LIMITS.factsPerRow} for a row`,
    );
  return facts;
}

// ── Queries ──

const ContextPath = z
  .string()
  .startsWith("/", 'a path starts with "/"')
  .max(CATALOG_LIMITS.pathChars)
  .refine((path) => !path.includes("\0") && wellFormed(path), "a path is well-formed text")
  // one spelling of a path: no slash at its end
  .transform((path) => (path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path));

/** A query as a watcher sends it (iterate/api `CatalogQuery`). Strict: a field that the catalog
 *  does not know is refused, never dropped, since dropping a condition answers other rows. */
const WatchedQuery = z.strictObject({
  where: z.record(z.string(), FactValue).optional(),
  under: ContextPath.optional(),
  childrenOf: ContextPath.optional(),
  order: z.enum(["active", "created", "path"]).optional(),
  limit: z.number().int().min(1).max(CATALOG_LIMITS.limit).optional(),
  keys: z.array(ContextPath).max(CATALOG_LIMITS.keys).optional(),
  awake: z.literal(true).optional(),
});

type RangeQuery = { kind: "range"; predicates: Fact[]; order: CatalogOrder; limit: number };
type Query = RangeQuery | { kind: "keys"; keys: string[] } | { kind: "awake" };

/** The one form of a query. Two queries that mean the same have the same `key`, and so share a
 *  window. A query that cannot be answered exactly is refused: nothing is dropped silently. */
export function normalizeQuery(spec: unknown): { query: Query; key: string } {
  const parsed = WatchedQuery.safeParse(spec);
  if (!parsed.success)
    throw new CatalogRefusal(`not a query of the catalog: ${z.prettifyError(parsed.error)}`);
  const { where, under, childrenOf, order, limit, keys, awake } = parsed.data;
  const ranged = Boolean(where || under || childrenOf || order || limit);
  if (awake) {
    if (ranged || keys) throw new CatalogRefusal("`awake: true` stands alone");
    return { query: { kind: "awake" }, key: '{"awake":true}' };
  }
  if (keys) {
    if (ranged) throw new CatalogRefusal("`keys` stands alone");
    const paths = [...new Set(keys)].sort(compareTextBinary);
    return { query: { kind: "keys", keys: paths }, key: JSON.stringify({ k: paths }) };
  }
  const facts = new Map<string, Fact>();
  const add = (key: string, value: string) => {
    if (!usableFact(key, value))
      throw new CatalogRefusal(`the fact "${key.slice(0, 40)}" is too long or is not plain text`);
    facts.set(factId([key, value]), [key, value]);
  };
  for (const [key, value] of Object.entries(where || {})) {
    // a key that starts with `$` is the kernel's, and a row's own metadata is not indexed under
    // one: a query that named another would get no row, and no reason
    if (key.startsWith("$") && !["$processor", "$parent", "$under"].includes(key))
      throw new CatalogRefusal(
        `the catalog has no fact "${key.slice(0, 40)}": the kernel's own are $processor, $parent and $under`,
      );
    add(key, String(value));
  }
  if (under && under !== "/") add("$under", under);
  if (childrenOf) add("$parent", childrenOf);
  if (facts.size > CATALOG_LIMITS.predicates)
    throw new CatalogRefusal(`a query names at most ${CATALOG_LIMITS.predicates} facts`);
  const query: RangeQuery = {
    kind: "range",
    predicates: [...facts.values()].sort(
      (a, b) => compareTextBinary(a[0], b[0]) || compareTextBinary(a[1], b[1]),
    ),
    order: order || "active",
    limit: limit || 50,
  };
  return { query, key: JSON.stringify({ p: query.predicates, o: query.order, l: query.limit }) };
}

/** A short name of what a query selects, without its limit: a cursor is good for any limit of the
 *  same facts in the same order, because its bound says which part the watcher holds. FNV-1a, 32
 *  bits. */
function queryName(query: Query): string {
  const text =
    query.kind === "range" ? JSON.stringify([query.order, query.predicates]) : query.kind;
  let hash = 0x811c9dc5;
  for (let i = 0; i < text.length; i++) {
    hash ^= text.charCodeAt(i);
    hash = Math.imul(hash, 0x01000193);
  }
  return (hash >>> 0).toString(36);
}

/** What a watcher holds of a query (iterate/api `CatalogCursor`). */
const WatcherCursor = z.object({
  gen: z.string(),
  rev: z.number(),
  q: z.string(),
  bound: z.tuple([z.number(), z.string()]).nullable().optional(),
  have: z.array(z.string()).optional(),
});

// ── Rows ──

/** A row as its writer hands it over: the whole new value of its path. `activeMs` and `createdMs`
 *  are what the orders sort by. Every other field is the row's body, which a watcher gets as it
 *  is: `processors` and `metadata` are in it, and the facts are read from those two. */
export type CatalogRowInput = {
  path: string;
  activeMs: number;
  createdMs: number;
  processors?: string[];
  metadata?: Record<string, unknown>;
  [field: string]: unknown;
};

type StoredRow = { path: string; active_at: number; created_at: number; rev: number; body: string };

/** A stored row as the JSON a watcher gets (iterate/api `CatalogRow`), with no parse: the body is
 *  an object's JSON, and it always holds `processors`. */
function rowJson(row: StoredRow): string {
  return `{"path":${JSON.stringify(row.path)},"activeMs":${row.active_at},"createdMs":${row.created_at},"rev":${row.rev},${row.body.slice(1)}`;
}

function keyOf(
  order: CatalogOrder,
  row: Pick<StoredRow, "active_at" | "created_at" | "path">,
): SortKey {
  if (order === "path") return [0, row.path];
  return [order === "active" ? row.active_at : row.created_at, row.path];
}

const ROW_COLUMNS = "r.path, r.active_at, r.created_at, r.rev, r.body";

// ── Windows ──

type LiveWindow = {
  id: number;
  key: string;
  query: Query;
  /** Of a range query: which fact its index is read by, the one with the fewest rows when the
   *  window was made. Any choice is correct; this one reads the least. */
  driver: number;
  /** Of a range query: `min(matching rows, limit)`. */
  size: number;
  /** Of a range query: the sort key of the last row, kept only while the window is full. */
  bound: SortKey | null;
  /** The catalog's revision at the window's last frame. */
  rev: number;
};

type PendingFrame = {
  windowId: number;
  from: number;
  rev: number;
  del: string[];
  /** `[path, the row's JSON]`. */
  put: [string, string][];
};

/** What a watch socket remembers through a hibernation: its id, and its queries by the name the
 *  watcher gave each. */
const WatchAttachment = z.object({ sid: z.string(), subs: z.record(z.string(), z.number()) });

/** What a watch socket's other end sends. */
const WatchRequest = z.object({
  op: z.enum(["subscribe", "unsubscribe"]),
  sub: z.string().min(1).max(CATALOG_LIMITS.subChars),
  query: z.unknown().optional(),
  cursor: z.unknown().optional(),
});

type Statement = { sql: string; args: unknown[] };

/** What the engine needs of the Durable Object it runs in. */
type CatalogHost = Pick<DurableObjectState, "getWebSockets" | "acceptWebSocket" | "getTags"> & {
  storage: Pick<DurableObjectStorage, "transactionSync">;
};

/** A watch socket and its queries, by the name the watcher gave each. */
type WatchSocket = { ws: WebSocket; subs: Map<string, number> };

type CatalogDeps = {
  /** The contexts that hold an awake socket now, by path. */
  awake: () => ReadonlyMap<string, AwakeContextState>;
  /** A page of the catalog's own rows, in path order, after `after`: what the first fill copies. */
  seed: (after: string, limit: number) => CatalogRowInput[];
  /** One context's row in the catalog now: what a write that the copy owes is made again from. */
  row: (path: string) => CatalogRowInput | undefined;
};

export class ReactiveCatalog {
  readonly #sql: SqlStorage;
  readonly #ctx: CatalogHost;
  readonly #deps: CatalogDeps;
  #ready = false;
  #gen = "";
  #rev = 0;
  /** How far the first fill came: "" before it began, then the last path it copied, then `done`. */
  #filled: { started: boolean; done: boolean; after: string } = {
    started: false,
    done: false,
    after: "",
  };

  /** Whether the copy owes a write (`rcat_owed`). It is kept in `rcat_meta`, so an object that
   *  wakes knows it with no other read. */
  #owed = false;

  // What follows is memory that a hibernation drops. Each is read again when it is first needed:
  // the windows from `rcat_window`, the sockets from their attachments.
  #windows: Map<number, LiveWindow> | undefined;
  #windowIdByKey = new Map<string, number>();
  /** A range window is found by its driver fact; one with no fact is under `*`. */
  #rangeWindowsByFact = new Map<string, Set<number>>();
  #keysWindowsByPath = new Map<string, Set<number>>();
  #awakeWindowId: number | undefined;
  #sockets: Map<string, WatchSocket> | undefined;
  /** window id → socket id → the socket's names for the query. */
  #watchers = new Map<number, Map<string, Set<string>>>();

  counters = {
    statements: 0,
    /** Rows that SQLite read and wrote for those statements, index entries too: what a Durable
     *  Object is billed by. */
    rowsRead: 0,
    rowsWritten: 0,
    writes: 0,
    /** Writes of a row equal to the stored one. */
    sameWrites: 0,
    /** Rows whose write changed no window: no statement beyond the write's own, and no frame. */
    quietWrites: 0,
    windowChecks: 0,
    seeks: 0,
    messagesSent: 0,
    charsSent: 0,
    /** Rows that an answer to a cursor did not send again, because the watcher held them. */
    rowsNotResent: 0,
    windowsMade: 0,
    windowsDropped: 0,
  };

  constructor(sql: SqlStorage, ctx: CatalogHost, deps: CatalogDeps) {
    this.#sql = sql;
    this.#ctx = ctx;
    this.#deps = deps;
  }

  // ── Storage ──

  #ensureTables(): void {
    if (this.#ready) return;
    this.#sql.exec(
      "CREATE TABLE IF NOT EXISTS rcat_meta (k TEXT PRIMARY KEY NOT NULL, v TEXT NOT NULL) WITHOUT ROWID",
    );
    const read = () =>
      new Map(
        this.#sql
          .exec<{ k: string; v: string }>("SELECT k, v FROM rcat_meta")
          .toArray()
          .map((row) => [row.k, row.v]),
      );
    let meta = read();
    // The tables are made once for a schema. An object that wakes reads `rcat_meta` and no more:
    // this runs at the first summary after every wake of the object, watched or not.
    if (meta.get("schema") !== SCHEMA) {
      // Every row here is a copy of the catalog's own, so tables of another schema are made again
      // and filled again. A new generation: no cursor of the old tables is good for the new ones.
      for (const table of [
        "rcat_row",
        "rcat_fact_active",
        "rcat_fact_created",
        "rcat_fact_path",
        "rcat_window",
        "rcat_owed",
      ])
        this.#sql.exec(`DROP TABLE IF EXISTS ${table}`);
      this.#sql.exec(
        `CREATE TABLE rcat_row (
          path TEXT COLLATE BINARY PRIMARY KEY NOT NULL,
          active_at INTEGER NOT NULL,
          created_at INTEGER NOT NULL,
          rev INTEGER NOT NULL,
          body TEXT NOT NULL,
          facts TEXT NOT NULL
        ) WITHOUT ROWID`,
      );
      this.#sql.exec("CREATE INDEX rcat_row_active ON rcat_row (active_at DESC, path DESC)");
      this.#sql.exec("CREATE INDEX rcat_row_created ON rcat_row (created_at DESC, path DESC)");
      for (const { facts, column } of Object.values(ORDER_INDEX))
        this.#sql.exec(
          `CREATE TABLE ${facts} (
            k TEXT COLLATE BINARY NOT NULL,
            v TEXT COLLATE BINARY NOT NULL,
            ${column && `${column} INTEGER NOT NULL,`}
            path TEXT COLLATE BINARY NOT NULL,
            PRIMARY KEY (k, v, ${column && `${column} DESC,`} path${column && " DESC"})
          ) WITHOUT ROWID`,
        );
      this.#sql.exec(
        `CREATE TABLE rcat_window (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          key TEXT COLLATE BINARY NOT NULL UNIQUE,
          driver INTEGER NOT NULL,
          size INTEGER NOT NULL,
          b_at INTEGER,
          b_path TEXT COLLATE BINARY,
          rev INTEGER NOT NULL
        )`,
      );
      this.#sql.exec(
        `CREATE TABLE rcat_owed (
          path TEXT COLLATE BINARY PRIMARY KEY NOT NULL,
          tries INTEGER NOT NULL,
          due_at INTEGER NOT NULL
        ) WITHOUT ROWID`,
      );
      this.#sql.exec("DELETE FROM rcat_meta");
      // written last: tables that were half made are made again
      this.#sql.exec(
        "INSERT INTO rcat_meta (k, v) VALUES ('schema', ?), ('gen', ?), ('rev', '0')",
        SCHEMA,
        crypto.randomUUID().slice(0, 8),
      );
      meta = read();
    }
    this.#gen = meta.get("gen") || "";
    this.#rev = Number(meta.get("rev") || "0");
    const filled = meta.get("filled");
    this.#filled = {
      started: meta.has("filled"),
      done: filled === "done",
      after: filled?.startsWith(">") ? filled.slice(1) : "",
    };
    this.#owed = meta.has("owed");
    this.#ready = true;
  }

  #exec<T extends Record<string, SqlStorageValue>>(sql: string, ...args: unknown[]): T[] {
    this.counters.statements += 1;
    const cursor = this.#sql.exec<T>(sql, ...args);
    const rows = cursor.toArray();
    this.counters.rowsRead += cursor.rowsRead || 0;
    this.counters.rowsWritten += cursor.rowsWritten || 0;
    return rows;
  }

  /** Memory that no longer matches SQLite (a transaction that threw) is read again. */
  #forget(): void {
    this.#ready = false;
    this.#windows = undefined;
    this.#sockets = undefined;
  }

  /** Whether the catalog keeps rows: false until the first watch, and then for good. A writer
   *  asks before it builds a row. */
  active(): boolean {
    this.#ensureTables();
    return this.#filled.started;
  }

  /** THE FIRST FILL: every row of the catalog, copied a page at a time, each page one transaction.
   *  It runs to its end before the first window is made. A fill that stopped (the object died
   *  under it) goes on from the last page it wrote. A row that this collection refuses is left
   *  out, and the others are kept. */
  fill(): void {
    this.#ensureTables();
    while (!this.#filled.done) {
      const page = this.#deps.seed(this.#filled.after, CATALOG_LIMITS.fillPage);
      const last = page.at(-1)?.path;
      const mark = last ? `>${last}` : "done";
      const pending: PendingFrame[] = [];
      try {
        this.#ctx.storage.transactionSync(() => {
          for (const row of page) {
            try {
              this.#upsertOne(row, pending);
            } catch (error) {
              if (!(error instanceof CatalogRefusal)) throw error;
            }
          }
          this.#exec("UPDATE rcat_meta SET v = ? WHERE k = 'rev'", String(this.#rev));
          this.#exec(
            "INSERT INTO rcat_meta (k, v) VALUES ('filled', ?) ON CONFLICT (k) DO UPDATE SET v = excluded.v",
            mark,
          );
        });
      } catch (error) {
        this.#forget();
        throw error;
      }
      this.#filled = { started: true, done: !last, after: last || "" };
      this.#dispatch(pending);
    }
  }

  #loadWindows(): Map<number, LiveWindow> {
    this.#ensureTables();
    if (this.#windows) return this.#windows;
    const windows = new Map<number, LiveWindow>();
    this.#windows = windows;
    this.#windowIdByKey = new Map();
    this.#rangeWindowsByFact = new Map();
    this.#keysWindowsByPath = new Map();
    this.#awakeWindowId = undefined;
    const rows = this.#exec<{
      id: number;
      key: string;
      driver: number;
      size: number;
      b_at: number | null;
      b_path: string | null;
      rev: number;
    }>("SELECT id, key, driver, size, b_at, b_path, rev FROM rcat_window");
    for (const row of rows)
      this.#indexWindow(windows, {
        id: row.id,
        key: row.key,
        query: queryOfKey(row.key),
        driver: row.driver,
        size: row.size,
        // oxlint-disable-next-line iterate/simple-truthiness-check -- SQL NULL means "no bound"; a bound's own time may be 0 and its path is never empty
        bound: row.b_at === null || row.b_path === null ? null : [row.b_at, row.b_path],
        rev: row.rev,
      });
    return windows;
  }

  #indexWindow(windows: Map<number, LiveWindow>, win: LiveWindow): void {
    windows.set(win.id, win);
    this.#windowIdByKey.set(win.key, win.id);
    const into = (index: Map<string, Set<number>>, at: string) => {
      let ids = index.get(at);
      if (!ids) index.set(at, (ids = new Set()));
      ids.add(win.id);
    };
    if (win.query.kind === "range") into(this.#rangeWindowsByFact, driverFactOf(win));
    else if (win.query.kind === "keys")
      for (const path of win.query.keys) into(this.#keysWindowsByPath, path);
    else this.#awakeWindowId = win.id;
  }

  #dropWindow(win: LiveWindow): void {
    this.#loadWindows().delete(win.id);
    this.#windowIdByKey.delete(win.key);
    this.#watchers.delete(win.id);
    const out = (index: Map<string, Set<number>>, at: string) => {
      const ids = index.get(at);
      ids?.delete(win.id);
      if (ids?.size === 0) index.delete(at);
    };
    if (win.query.kind === "range") out(this.#rangeWindowsByFact, driverFactOf(win));
    else if (win.query.kind === "keys")
      for (const path of win.query.keys) out(this.#keysWindowsByPath, path);
    else this.#awakeWindowId = undefined;
    this.#exec("DELETE FROM rcat_window WHERE id = ?", win.id);
    this.counters.windowsDropped += 1;
  }

  #saveWindow(win: LiveWindow): void {
    this.#exec(
      "UPDATE rcat_window SET size = ?, b_at = ?, b_path = ?, rev = ? WHERE id = ?",
      win.size,
      win.bound ? win.bound[0] : null,
      win.bound ? win.bound[1] : null,
      win.rev,
      win.id,
    );
  }

  // ── The statements of a range query. Every one reads one index in its order. ──

  /** FROM and WHERE for a query's rows. With a fact: the driver fact's entries in the index of the
   *  query's order, and one point lookup in `rcat_fact_path` for each other fact. With none: the
   *  rows themselves, by the index of the order. `join` adds the row to a fact's entry. */
  #rangeSql(
    query: RangeQuery,
    driver: number,
  ): { from: string; join: string; where: string[]; args: unknown[]; at: string } {
    const driven = query.predicates[driver];
    if (!driven) return { from: "rcat_row r", join: "", where: [], args: [], at: "r" };
    const where = ["f0.k = ?", "f0.v = ?"];
    const args: unknown[] = [...driven];
    query.predicates.forEach((fact, index) => {
      if (index === driver) return;
      where.push(
        "EXISTS (SELECT 1 FROM rcat_fact_path fi WHERE fi.k = ? AND fi.v = ? AND fi.path = f0.path)",
      );
      args.push(...fact);
    });
    return {
      from: `${ORDER_INDEX[query.order].facts} f0`,
      join: " JOIN rcat_row r ON r.path = f0.path",
      where,
      args,
      at: "f0",
    };
  }

  /** The window's rows, in order. */
  #windowSql(query: RangeQuery, driver: number): Statement {
    const { from, join, where, args, at } = this.#rangeSql(query, driver);
    return {
      sql: `SELECT ${ROW_COLUMNS} FROM ${from}${join}${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY ${orderTerms(query.order, at, true)} LIMIT ?`,
      args: [...args, query.limit],
    };
  }

  /** F, the follower: the first row after `bound`. THE BACKFILL. */
  #followerSql(query: RangeQuery, driver: number, bound: SortKey): Statement {
    const { from, join, where, args, at } = this.#rangeSql(query, driver);
    const after = beyond(query.order, at, true, bound);
    return {
      sql: `SELECT ${ROW_COLUMNS} FROM ${from}${join} WHERE ${[...where, after.sql].join(" AND ")} ORDER BY ${orderTerms(query.order, at, true)} LIMIT 1`,
      args: [...args, ...after.args],
    };
  }

  /** The sort key of ONE row, read against the window's order: A, the row above `bound` (the last
   *  row before it), or with no bound M, the last matching row, which is the bound of a window
   *  that has just become full. */
  #edgeSql(query: RangeQuery, driver: number, bound: SortKey | null): Statement {
    const { from, where, args, at } = this.#rangeSql(query, driver);
    const before = bound ? beyond(query.order, at, false, bound) : { sql: "", args: [] };
    const conditions = [...where, before.sql].filter(Boolean);
    const column = ORDER_INDEX[query.order].column;
    return {
      sql: `SELECT ${column ? `${at}.${column}` : "0"} AS at, ${at}.path AS path FROM ${from}${conditions.length ? ` WHERE ${conditions.join(" AND ")}` : ""} ORDER BY ${orderTerms(query.order, at, false)} LIMIT 1`,
      args: [...args, ...before.args],
    };
  }

  #windowRows(query: RangeQuery, driver: number): StoredRow[] {
    const { sql, args } = this.#windowSql(query, driver);
    return this.#exec<StoredRow>(sql, ...args);
  }

  #follower(win: LiveWindow, query: RangeQuery, bound: SortKey): StoredRow | undefined {
    this.counters.seeks += 1;
    const { sql, args } = this.#followerSql(query, win.driver, bound);
    return this.#exec<StoredRow>(sql, ...args)[0];
  }

  #edge(win: LiveWindow, query: RangeQuery, bound: SortKey | null): SortKey | null {
    this.counters.seeks += 1;
    const { sql, args } = this.#edgeSql(query, win.driver, bound);
    const row = this.#exec<{ at: number; path: string }>(sql, ...args)[0];
    return row ? [row.at, row.path] : null;
  }

  /** The fact with the fewest rows, counted up to 1,000 each. */
  #chooseDriver(query: RangeQuery): number {
    if (query.predicates.length < 2) return 0;
    let best = 0;
    let fewest = Infinity;
    query.predicates.forEach((fact, index) => {
      const counted =
        this.#exec<{ n: number }>(
          "SELECT COUNT(*) AS n FROM (SELECT 1 FROM rcat_fact_path WHERE k = ? AND v = ? LIMIT 1000)",
          ...fact,
        )[0]?.n || 0;
      if (counted < fewest) {
        fewest = counted;
        best = index;
      }
    });
    return best;
  }

  #keysRows(paths: readonly string[]): StoredRow[] {
    return this.#exec<StoredRow>(
      `SELECT ${ROW_COLUMNS} FROM rcat_row r WHERE r.path IN (SELECT value FROM json_each(?)) ORDER BY r.path`,
      JSON.stringify(paths),
    );
  }

  // ── What the catalog kept ──

  /** A ROW THAT THE CATALOG KEPT (context-catalog.ts) is the row of this copy too, once a mind
   *  has watched. A row that the copy refuses (one it cannot order or index) is taken out of it:
   *  a watcher then sees no row of that context, and never an old one.
   *
   *  WHAT THE COPY CANNOT WRITE IT OWES: a durable mark for the path (`rcat_owed`). An owed write
   *  is made again from the catalog's own row, at a later write or watch, after a wait that
   *  doubles from one minute to thirty, `CATALOG_LIMITS.owedTries` times in all; a later summary
   *  of the same context pays it at once. So the copy is behind the catalog for a bounded time
   *  and never in silence: each failure is reported, and `watches()` counts what is owed.
   *
   *  It throws only when not even the mark could be written. */
  keep(input: CatalogRowInput): void {
    if (!this.active()) return;
    let written = true;
    try {
      this.#keepOrRefuse(input);
    } catch (error) {
      written = false;
      reportIssue("reactive-catalog.write", error, { path: input.path });
      this.#owe(input.path);
    }
    if (!this.#owed) return;
    // the write that just went pays this context's own debt
    if (written) this.#exec("DELETE FROM rcat_owed WHERE path = ?", input.path);
    this.settleOwed();
  }

  #keepOrRefuse(input: CatalogRowInput): void {
    try {
      this.upsert(input);
    } catch (error) {
      if (!(error instanceof CatalogRefusal)) throw error;
      console.info({
        event: "context.reactive-catalog-row-refused",
        path: input.path,
        message: error.message,
      });
      this.deleteMany([input.path]);
    }
  }

  /** One more try that failed: the next comes after a minute, then after twice the wait of the
   *  try before, thirty minutes at most. */
  #owe(path: string): void {
    const now = Date.now();
    this.#exec(
      `INSERT INTO rcat_owed (path, tries, due_at) VALUES (?, 1, ?)
       ON CONFLICT (path) DO UPDATE SET
         due_at = ? + MIN(60000 * (1 << MIN(rcat_owed.tries, 5)), 1800000),
         tries = rcat_owed.tries + 1`,
      path,
      now + 60_000,
      now,
    );
    if (!this.#owed)
      this.#exec(
        "INSERT INTO rcat_meta (k, v) VALUES ('owed', '1') ON CONFLICT (k) DO UPDATE SET v = '1'",
      );
    this.#owed = true;
  }

  /** Makes again the writes that the copy owes and that are due, at most 20 a call. */
  settleOwed(): void {
    if (!this.active() || !this.#owed) return;
    const due = this.#exec<{ path: string }>(
      "SELECT path FROM rcat_owed WHERE tries < ? AND due_at <= ? ORDER BY due_at LIMIT 20",
      CATALOG_LIMITS.owedTries,
      Date.now(),
    );
    for (const { path } of due) {
      try {
        const row = this.#deps.row(path);
        // a context that the catalog no longer has is in no answer
        if (row) this.#keepOrRefuse(row);
        else this.deleteMany([path]);
        this.#exec("DELETE FROM rcat_owed WHERE path = ?", path);
      } catch (error) {
        reportIssue("reactive-catalog.settle", error, { path });
        this.#owe(path);
      }
    }
    if (this.#exec("SELECT 1 AS one FROM rcat_owed LIMIT 1").length > 0) return;
    this.#exec("DELETE FROM rcat_meta WHERE k = 'owed'");
    this.#owed = false;
  }

  // ── Writes ──

  /** Writes rows, each a whole new value of its path, in one transaction. A row equal to the one
   *  stored is no write: no revision, no frame. Before the first watch it writes nothing. */
  upsertMany(inputs: readonly CatalogRowInput[]): WriteResult {
    return this.#write((out) => inputs.filter((input) => this.#upsertOne(input, out)).length);
  }

  upsert(input: CatalogRowInput): WriteResult {
    return this.upsertMany([input]);
  }

  /** Takes rows out. No writer of the kernel does so today: a context keeps its row for good, here
   *  as in the catalog. It is the collection's other verb, and the case table needs it. */
  deleteMany(paths: readonly string[]): WriteResult {
    return this.#write((out) => paths.filter((path) => this.#deleteOne(path, out)).length);
  }

  #write(work: (out: PendingFrame[]) => number): WriteResult {
    if (!this.active()) return { rev: this.#rev, changed: 0, frames: 0, messages: 0, chars: 0 };
    const pending: PendingFrame[] = [];
    let changed = 0;
    try {
      this.#ctx.storage.transactionSync(() => {
        changed = work(pending);
        if (changed > 0)
          this.#exec("UPDATE rcat_meta SET v = ? WHERE k = 'rev'", String(this.#rev));
      });
    } catch (error) {
      // the transaction is undone, and so the windows and the revision in memory are stale
      this.#forget();
      throw error;
    }
    return { rev: this.#rev, changed, frames: pending.length, ...this.#dispatch(pending) };
  }

  #storedRow(path: string): (StoredRow & { facts: string }) | undefined {
    return this.#exec<StoredRow & { facts: string }>(
      "SELECT path, active_at, created_at, rev, body, facts FROM rcat_row WHERE path = ?",
      path,
    )[0];
  }

  #upsertOne(input: CatalogRowInput, out: PendingFrame[]): boolean {
    const row = RowInput.safeParse(input);
    if (!row.success)
      throw new CatalogRefusal(`not a row of the catalog: ${z.prettifyError(row.error)}`);
    const { path, activeMs: activeAt, createdMs: createdAt, ...listing } = row.data;
    const { processors, metadata } = listing;
    const body = JSON.stringify(listing);
    if (body.length > CATALOG_LIMITS.bodyChars)
      throw new CatalogRefusal(
        `the row of ${path} is longer than ${CATALOG_LIMITS.bodyChars} characters`,
      );
    const old = this.#storedRow(path);
    if (old && old.active_at === activeAt && old.created_at === createdAt && old.body === body) {
      this.counters.sameWrites += 1;
      return false;
    }
    const facts = extractFacts(path, processors, metadata);
    // the stored list is the truth of what the old row has in each index: no parse of its body
    const oldFacts = old ? (JSON.parse(old.facts) as Fact[]) : [];
    this.#rev += 1;
    const next: StoredRow = {
      path,
      active_at: activeAt,
      created_at: createdAt,
      rev: this.#rev,
      body,
    };
    this.#exec(
      `INSERT INTO rcat_row (path, active_at, created_at, rev, body, facts) VALUES (?, ?, ?, ?, ?, ?)
       ON CONFLICT (path) DO UPDATE SET active_at = excluded.active_at,
         created_at = excluded.created_at, rev = excluded.rev, body = excluded.body,
         facts = excluded.facts`,
      path,
      activeAt,
      createdAt,
      next.rev,
      body,
      JSON.stringify(facts),
    );
    this.#moveFacts(old, oldFacts, next, facts);
    this.counters.writes += 1;
    this.#notify(old, new Set(oldFacts.map(factId)), next, new Set(facts.map(factId)), out);
    return true;
  }

  #deleteOne(path: string, out: PendingFrame[]): boolean {
    const old = this.#storedRow(path);
    if (!old) return false;
    const oldFacts = JSON.parse(old.facts) as Fact[];
    this.#rev += 1;
    this.#exec("DELETE FROM rcat_row WHERE path = ?", path);
    this.#moveFacts(old, oldFacts, undefined, []);
    this.counters.writes += 1;
    this.#notify(old, new Set(oldFacts.map(factId)), undefined, new Set(), out);
    return true;
  }

  /** A row's entries in each order's index, brought from what the old row had to what the new one
   *  has. An entry holds the order's own value, so every entry of an order moves when that value
   *  does; otherwise only the facts that came or went are written. */
  #moveFacts(
    old: StoredRow | undefined,
    oldFacts: readonly Fact[],
    next: StoredRow | undefined,
    nextFacts: readonly Fact[],
  ): void {
    const oldIds = new Set(oldFacts.map(factId));
    const nextIds = new Set(nextFacts.map(factId));
    for (const [order, { facts: table, column }] of Object.entries(ORDER_INDEX) as [
      CatalogOrder,
      (typeof ORDER_INDEX)[CatalogOrder],
    ][]) {
      const oldAt = old && keyOf(order, old)[0];
      const nextAt = next && keyOf(order, next)[0];
      const moved = oldAt !== nextAt;
      const at = column && ` AND ${column} = ?`;
      if (old)
        for (const fact of oldFacts)
          if (moved || !nextIds.has(factId(fact)))
            this.#exec(
              `DELETE FROM ${table} WHERE k = ? AND v = ?${at} AND path = ?`,
              ...fact,
              ...(column ? [oldAt] : []),
              old.path,
            );
      if (next)
        for (const fact of nextFacts)
          if (moved || !oldIds.has(factId(fact)))
            this.#exec(
              `INSERT INTO ${table} (k, v, ${column && `${column}, `}path) VALUES (?, ?, ${column && "?, "}?)`,
              ...fact,
              ...(column ? [nextAt] : []),
              next.path,
            );
    }
  }

  // ── The case table: what one write does to one window ──

  #notify(
    old: StoredRow | undefined,
    oldFacts: ReadonlySet<string>,
    next: StoredRow | undefined,
    nextFacts: ReadonlySet<string>,
    out: PendingFrame[],
  ): void {
    const windows = this.#loadWindows();
    if (windows.size === 0) return;
    const before = out.length;
    const candidates = new Set<number>();
    const collect = (ids: ReadonlySet<number> | undefined) => {
      if (ids) for (const id of ids) candidates.add(id);
    };
    collect(this.#rangeWindowsByFact.get("*"));
    // a window is under ONE of its facts: a row that never held that fact never matched it
    for (const fact of oldFacts) collect(this.#rangeWindowsByFact.get(fact));
    for (const fact of nextFacts) collect(this.#rangeWindowsByFact.get(fact));
    for (const id of candidates) {
      const win = windows.get(id);
      if (win?.query.kind === "range")
        this.#advance(win, win.query, old, oldFacts, next, nextFacts, out);
    }

    const path = next?.path || old?.path || "";
    for (const id of this.#keysWindowsByPath.get(path) || []) {
      const win = windows.get(id);
      if (!win) continue;
      this.counters.windowChecks += 1;
      out.push({
        windowId: id,
        from: win.rev,
        rev: this.#rev,
        del: next ? [] : [path],
        put: next ? [[path, rowJson(next)]] : [],
      });
      win.rev = this.#rev;
      this.#saveWindow(win);
    }
    if (out.length === before) this.counters.quietWrites += 1;
  }

  #advance(
    win: LiveWindow,
    query: RangeQuery,
    old: StoredRow | undefined,
    oldFacts: ReadonlySet<string>,
    next: StoredRow | undefined,
    nextFacts: ReadonlySet<string>,
    out: PendingFrame[],
  ): void {
    this.counters.windowChecks += 1;
    const matches = (facts: ReadonlySet<string>) =>
      query.predicates.every((fact) => facts.has(factId(fact)));
    const compare = (a: SortKey, b: SortKey) => compareSortKeys(query.order, a, b);
    const oldKey = old && matches(oldFacts) ? keyOf(query.order, old) : null;
    const nextKey = next && matches(nextFacts) ? keyOf(query.order, next) : null;

    const emit = (del: string[], put: StoredRow[]) => {
      out.push({
        windowId: win.id,
        from: win.rev,
        rev: this.#rev,
        del,
        put: put.map((row) => [row.path, rowJson(row)]),
      });
      win.rev = this.#rev;
      this.#saveWindow(win);
    };

    if (win.size < query.limit) {
      // a window with room holds every matching row, and keeps no bound
      if (!oldKey && !nextKey) return;
      if (!nextKey || !next) {
        win.size -= 1;
        return emit([oldKey ? oldKey[1] : ""], []);
      }
      if (!oldKey) {
        win.size += 1;
        if (win.size === query.limit) win.bound = this.#edge(win, query, null);
      }
      return emit([], [next]);
    }

    const bound = win.bound;
    if (!bound) throw new Error(`the full window ${win.id} has no bound`);
    const wasIn = !!oldKey && compare(oldKey, bound) <= 0;
    if (!wasIn) {
      // THE COMMON CASE: neither the old key nor the new one is in the window
      if (!nextKey || !next || compare(nextKey, bound) > 0) return;
      // the row enters: the last row leaves, and the row above it is the bound
      win.bound = this.#edge(win, query, bound);
      return emit([bound[1]], [next]);
    }
    if (!nextKey || !next) {
      // the row leaves: the follower takes the place, in the same frame
      const follower = this.#follower(win, query, bound);
      if (follower) win.bound = keyOf(query.order, follower);
      else {
        win.size -= 1;
        win.bound = null;
      }
      return emit([oldKey[1]], follower ? [follower] : []);
    }
    const moved = compare(nextKey, bound);
    const wasLast = compare(oldKey, bound) === 0;
    if (moved === 0 || (moved < 0 && !wasLast)) return emit([], [next]);
    if (moved < 0) {
      // the last row moved up: the row that is last now is the bound
      win.bound = this.#edge(win, query, bound);
      return emit([], [next]);
    }
    // the row moved to after the bound: the follower is the last row, and it may be this row
    const follower = this.#follower(win, query, bound);
    if (!follower) throw new Error(`the window ${win.id} lost the row that moved past its bound`);
    win.bound = keyOf(query.order, follower);
    if (follower.path === next.path) return emit([], [next]);
    return emit([oldKey[1]], [follower]);
  }

  // ── Awake ──

  /** Whether anyone watches the awake list: when nobody does, the object does nothing for a wake. */
  awakeWatched(): boolean {
    this.#loadWindows();
    return this.#awakeWindowId !== undefined;
  }

  /** A context woke or said what it does now (`state`), or went quiet (undefined). No row and no
   *  revision: the awake list is the sockets. */
  awakeChanged(path: string, state: AwakeContextState | undefined): void {
    const windows = this.#loadWindows();
    const win = this.#awakeWindowId === undefined ? undefined : windows.get(this.#awakeWindowId);
    if (!win) return;
    this.#dispatch([
      {
        windowId: win.id,
        from: win.rev,
        rev: win.rev,
        del: state ? [] : [path],
        put: state ? [[path, awakeJson(path, state)]] : [],
      },
    ]);
  }

  // ── Sockets ──

  #loadSockets(): Map<string, WatchSocket> {
    if (this.#sockets) return this.#sockets;
    this.#loadWindows();
    const sockets = new Map<string, WatchSocket>();
    this.#sockets = sockets;
    this.#watchers = new Map();
    for (const ws of this.#ctx.getWebSockets(WATCH_SOCKET_TAG)) {
      if (ws.readyState !== WebSocket.OPEN) continue;
      const attachment = WatchAttachment.safeParse(ws.deserializeAttachment()).data;
      if (!attachment) continue;
      const subs = new Map(Object.entries(attachment.subs));
      sockets.set(attachment.sid, { ws, subs });
      for (const [sub, windowId] of subs) this.#watch(windowId, attachment.sid, sub);
    }
    return sockets;
  }

  #watch(windowId: number, sid: string, sub: string): void {
    let bySocket = this.#watchers.get(windowId);
    if (!bySocket) this.#watchers.set(windowId, (bySocket = new Map()));
    let subs = bySocket.get(sid);
    if (!subs) bySocket.set(sid, (subs = new Set()));
    subs.add(sub);
  }

  /** Takes a socket's name for a query off its window. A window that nobody watches goes. */
  #unwatch(windowId: number, sid: string, sub: string): void {
    const bySocket = this.#watchers.get(windowId);
    const subs = bySocket?.get(sid);
    subs?.delete(sub);
    if (subs?.size === 0) bySocket?.delete(sid);
    if (bySocket && bySocket.size > 0) return;
    const win = this.#loadWindows().get(windowId);
    if (win) this.#dropWindow(win);
  }

  /** Sends each socket ONE message with every frame that is for it. Returns what was sent. */
  #dispatch(pending: readonly PendingFrame[]): { messages: number; chars: number } {
    if (pending.length === 0) return { messages: 0, chars: 0 };
    const sockets = this.#loadSockets();
    const windows = this.#loadWindows();
    type Part = { rows: Map<string, string>; frames: string[]; chars: number };
    const bySocket = new Map<string, Part[]>();
    for (const frame of pending) {
      const watchers = this.#watchers.get(frame.windowId);
      if (!watchers?.size) {
        // left by a socket that ended with no close event: the window goes at its first frame
        const win = windows.get(frame.windowId);
        if (win) this.#dropWindow(win);
        continue;
      }
      const tail = `,${frame.from},${frame.rev},${JSON.stringify(frame.del)},${JSON.stringify(frame.put.map(([path]) => path))}]`;
      const rowChars = frame.put.reduce((sum, [, json]) => sum + json.length, 0);
      for (const [sid, subs] of watchers) {
        let parts = bySocket.get(sid);
        if (!parts) bySocket.set(sid, (parts = [{ rows: new Map(), frames: [], chars: 0 }]));
        let part = parts[parts.length - 1];
        if (!part || part.chars > CATALOG_LIMITS.messageChars)
          parts.push((part = { rows: new Map(), frames: [], chars: 0 }));
        for (const [path, json] of frame.put) part.rows.set(path, json);
        for (const sub of subs) part.frames.push(`[${JSON.stringify(sub)}${tail}`);
        part.chars += rowChars + tail.length * subs.size;
      }
    }
    let messages = 0;
    let chars = 0;
    for (const [sid, parts] of bySocket) {
      const socket = sockets.get(sid);
      if (!socket) continue;
      parts.forEach((part, at) => {
        // every part but the last says that more of this write comes: the session's end hands
        // a write to its watchers whole (catalog-watch.ts)
        const more = at < parts.length - 1 ? ',"more":true' : "";
        const message = `{"gen":${JSON.stringify(this.#gen)},"rows":[${[...part.rows.values()].join(",")}],"d":[${part.frames.join(",")}]${more}}`;
        if (!this.#send(socket.ws, message)) return;
        messages += 1;
        chars += message.length;
      });
    }
    return { messages, chars };
  }

  #send(ws: WebSocket, message: string): boolean {
    try {
      ws.send(message);
      this.counters.messagesSent += 1;
      this.counters.charsSent += message.length;
      return true;
    } catch {
      // a socket that is closing: its close event takes its queries off
      return false;
    }
  }

  /** The upgrade of a watch socket: the object's end is accepted with the hibernation API. */
  acceptWatchWebSocket(): Response {
    const pair = new WebSocketPair();
    try {
      this.attachWatchSocket(pair[1]);
    } catch (error) {
      // the limit of sockets on one Durable Object
      return new Response(`${error instanceof Error ? error.message : String(error)}\n`, {
        status: 503,
      });
    }
    return new Response(null, { status: 101, webSocket: pair[0] });
  }

  attachWatchSocket(ws: WebSocket): void {
    this.#ensureTables();
    this.#ctx.acceptWebSocket(ws, [WATCH_SOCKET_TAG]);
    const sid = crypto.randomUUID().slice(0, 12);
    ws.serializeAttachment({ sid, subs: {} } satisfies z.infer<typeof WatchAttachment>);
    this.#sockets?.set(sid, { ws, subs: new Map() });
    this.#send(ws, JSON.stringify({ hello: { gen: this.#gen, rev: this.#rev } }));
  }

  isWatchWebSocket(ws: WebSocket): boolean {
    return this.#ctx.getTags(ws).includes(WATCH_SOCKET_TAG);
  }

  handleWatchMessage(ws: WebSocket, raw: string | ArrayBuffer): void {
    let request: z.infer<typeof WatchRequest> | undefined;
    try {
      try {
        request = WatchRequest.parse(JSON.parse(typeof raw === "string" ? raw : ""));
      } catch {
        throw new CatalogRefusal(
          `a message is one JSON object, { op: "subscribe" | "unsubscribe", sub: a name of 1 to ${CATALOG_LIMITS.subChars} characters, query?, cursor? }`,
        );
      }
      const sockets = this.#loadSockets();
      const sid = WatchAttachment.safeParse(ws.deserializeAttachment()).data?.sid || "";
      const socket = sockets.get(sid);
      if (!socket) throw new CatalogRefusal("this socket is not a watch socket");
      socket.ws = ws;
      if (request.op === "subscribe") {
        this.#subscribe(sid, socket, request.sub, request.query, request.cursor);
        return;
      }
      const windowId = socket.subs.get(request.sub);
      socket.subs.delete(request.sub);
      ws.serializeAttachment({ sid, subs: Object.fromEntries(socket.subs) });
      if (windowId !== undefined) this.#unwatch(windowId, sid, request.sub);
      this.#send(ws, JSON.stringify({ sub: request.sub, unsubscribed: true }));
    } catch (error) {
      // What the watcher is told: its query cannot be answered, a limit is reached, or the
      // catalog itself failed. The session's end gives each its own code (catalog-watch.ts).
      const kind =
        error instanceof CatalogRefusal
          ? "query"
          : error instanceof CatalogLimit
            ? "limit"
            : "failed";
      if (kind === "failed") {
        this.#forget();
        reportIssue("reactive-catalog.watch", error, { sub: request?.sub });
      }
      this.#send(
        ws,
        JSON.stringify({
          sub: request?.sub,
          kind,
          error:
            kind !== "failed" && error instanceof Error
              ? error.message
              : "the catalog failed, and its log says why",
        }),
      );
    }
  }

  #subscribe(sid: string, socket: WatchSocket, sub: string, spec: unknown, cursor: unknown): void {
    const { query, key } = normalizeQuery(spec);
    const had = socket.subs.get(sub);
    if (had === undefined && socket.subs.size >= CATALOG_LIMITS.subsPerSocket)
      throw new CatalogLimit(
        `a session holds at most ${CATALOG_LIMITS.subsPerSocket} watches: dispose one first`,
      );
    // the awake list is the sockets: it needs no row
    if (query.kind !== "awake") {
      this.fill();
      // an answer is as right as the copy can make it now
      this.settleOwed();
    }
    const windows = this.#loadWindows();

    let win = windows.get(this.#windowIdByKey.get(key) ?? -1);
    let rows: StoredRow[] | undefined;
    if (!win) {
      if (windows.size >= CATALOG_LIMITS.windows)
        // windows that no open socket names: left by a socket that ended with no close event
        for (const stale of [...windows.values()])
          if (!this.#watchers.get(stale.id)?.size) this.#dropWindow(stale);
      if (windows.size >= CATALOG_LIMITS.windows)
        throw new CatalogLimit(
          `the catalog holds at most ${CATALOG_LIMITS.windows} different live queries`,
        );
      const driver = query.kind === "range" ? this.#chooseDriver(query) : 0;
      rows = query.kind === "range" ? this.#windowRows(query, driver) : undefined;
      const last =
        rows && query.kind === "range" && rows.length === query.limit ? rows.at(-1) : undefined;
      const bound = last && query.kind === "range" ? keyOf(query.order, last) : null;
      const made = this.#exec<{ id: number }>(
        "INSERT INTO rcat_window (key, driver, size, b_at, b_path, rev) VALUES (?, ?, ?, ?, ?, ?) RETURNING id",
        key,
        driver,
        rows?.length || 0,
        bound ? bound[0] : null,
        bound ? bound[1] : null,
        this.#rev,
      )[0];
      if (!made) throw new Error("the window was not stored");
      win = { id: made.id, key, query, driver, size: rows?.length || 0, bound, rev: this.#rev };
      this.#indexWindow(windows, win);
      this.counters.windowsMade += 1;
    }
    // the socket's name moves to this window before the old one is let go
    socket.subs.set(sub, win.id);
    socket.ws.serializeAttachment({ sid, subs: Object.fromEntries(socket.subs) });
    this.#watch(win.id, sid, sub);
    if (had !== undefined && had !== win.id) this.#unwatch(had, sid, sub);
    this.#sendAnswer(socket.ws, sub, win, cursor, rows);
  }

  /** The answer to a subscribe: the window now. With a cursor of this generation and this query,
   *  every path and only the rows the watcher lacks; otherwise every row. */
  #sendAnswer(
    ws: WebSocket,
    sub: string,
    win: LiveWindow,
    rawCursor: unknown,
    known?: StoredRow[],
  ): void {
    const query = win.query;
    const q = queryName(query);
    const head = `{"sub":${JSON.stringify(sub)},"q":"${q}","gen":${JSON.stringify(this.#gen)},"rev":${win.rev}`;
    if (query.kind === "awake") {
      const awake = [...this.#deps.awake()].map(([path, state]) => awakeJson(path, state));
      this.#send(ws, `${head},"full":false,"reset":[${awake.join(",")}]}`);
      return;
    }
    const rows =
      known ||
      (query.kind === "range" ? this.#windowRows(query, win.driver) : this.#keysRows(query.keys));
    const full = query.kind === "range" && rows.length === query.limit;
    const cursor = WatcherCursor.safeParse(rawCursor).data;
    if (!cursor || cursor.gen !== this.#gen || cursor.q !== q) {
      this.#send(ws, `${head},"full":${full},"reset":[${rows.map(rowJson).join(",")}]}`);
      return;
    }
    const have = new Set(cursor.have);
    const { bound } = cursor;
    const held = (row: StoredRow) =>
      row.rev <= cursor.rev &&
      (query.kind === "range"
        ? !!bound && compareSortKeys(query.order, keyOf(query.order, row), bound) <= 0
        : have.has(row.path));
    const put = rows.filter((row) => !held(row));
    this.counters.rowsNotResent += rows.length - put.length;
    this.#send(
      ws,
      `${head},"full":${full},"ids":${JSON.stringify(rows.map((row) => row.path))},"put":[${put.map(rowJson).join(",")}]}`,
    );
  }

  handleWatchClose(ws: WebSocket): void {
    try {
      ws.close(1000, "closed");
    } catch {
      // already closing
    }
    const attachment = WatchAttachment.safeParse(ws.deserializeAttachment()).data;
    if (!attachment) return;
    const sockets = this.#loadSockets();
    // a socket that closed is no longer open: when memory does not have its queries, they come
    // from its attachment
    const subs = sockets.get(attachment.sid)?.subs || new Map(Object.entries(attachment.subs));
    sockets.delete(attachment.sid);
    for (const [sub, windowId] of subs) this.#unwatch(windowId, attachment.sid, sub);
  }

  // ── What a test and a person can ask ──

  /** Each window's stored size and bound against the rows now. Empty when all agree. */
  verify(): string[] {
    const faults: string[] = [];
    for (const win of this.#loadWindows().values()) {
      if (win.query.kind !== "range") continue;
      const rows = this.#windowRows(win.query, win.driver);
      const last = rows.length === win.query.limit ? rows.at(-1) : undefined;
      const bound = last ? keyOf(win.query.order, last) : null;
      if (rows.length !== win.size || JSON.stringify(bound) !== JSON.stringify(win.bound))
        faults.push(
          `window ${win.id} ${win.key}: stored size ${win.size} bound ${JSON.stringify(win.bound)}, rows give size ${rows.length} bound ${JSON.stringify(bound)}`,
        );
      const newest = rows.reduce((max, row) => Math.max(max, row.rev), 0);
      if (newest > win.rev)
        faults.push(
          `window ${win.id}: a row of revision ${newest} is past the window's ${win.rev}`,
        );
    }
    return faults;
  }

  /** Who watches what, and what the object did since it last woke (iterate/api `CatalogWatches`). */
  watches(options: { verify?: boolean; plans?: boolean } = {}): CatalogWatches {
    const windows = [...this.#loadWindows().values()];
    const sockets = this.#loadSockets();
    return {
      active: this.#filled.started,
      gen: this.#gen,
      rev: this.#rev,
      rows:
        this.#sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rcat_row").toArray()[0]?.n || 0,
      sockets: sockets.size,
      awake: this.#deps.awake().size,
      windows: windows.map((win) => ({
        query: win.key,
        size: win.size,
        bound: win.bound,
        rev: win.rev,
        watchers: [...(this.#watchers.get(win.id)?.values() || [])].reduce(
          (sum, subs) => sum + subs.size,
          0,
        ),
      })),
      owed: this.#owed
        ? this.#sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rcat_owed").toArray()[0]?.n || 0
        : 0,
      counters: { ...this.counters },
      ...(options.verify && { faults: this.verify() }),
      ...(options.plans && { plans: this.#plans() }),
    };
  }

  /** How SQLite reads the statements that the engine builds, for one fact, two facts and no fact
   *  in each order. */
  #plans(): Record<string, string[]> {
    const plan = ({ sql, args }: Statement) =>
      this.#sql
        .exec<{ detail: string }>(`EXPLAIN QUERY PLAN ${sql}`, ...args)
        .toArray()
        .map((row) => row.detail);
    const plans: Record<string, string[]> = {};
    const at: SortKey = [1_000, "/t"];
    for (const order of Object.keys(ORDER_INDEX) as CatalogOrder[]) {
      const queries: Record<string, RangeQuery> = {
        "no fact": { kind: "range", predicates: [], order, limit: 50 },
        "one fact": { kind: "range", predicates: [["status", "open"]], order, limit: 50 },
        "two facts": {
          kind: "range",
          predicates: [
            ["priority", "high"],
            ["status", "open"],
          ],
          order,
          limit: 50,
        },
      };
      for (const [facts, query] of Object.entries(queries)) {
        plans[`${order}, ${facts}: the window`] = plan(this.#windowSql(query, 0));
        plans[`${order}, ${facts}: the follower (the backfill)`] = plan(
          this.#followerSql(query, 0, at),
        );
        plans[`${order}, ${facts}: the row above the bound`] = plan(this.#edgeSql(query, 0, at));
        plans[`${order}, ${facts}: the last matching row`] = plan(this.#edgeSql(query, 0, null));
      }
    }
    plans["rows by key"] = plan({
      sql: `SELECT ${ROW_COLUMNS} FROM rcat_row r WHERE r.path IN (SELECT value FROM json_each(?))`,
      args: ["[]"],
    });
    return plans;
  }
}

type WriteResult = {
  /** The catalog's revision after the write. */
  rev: number;
  /** How many rows changed: a row equal to the stored one is not counted. */
  changed: number;
  /** How many windows got a frame. */
  frames: number;
  /** How many socket messages carried them, and their length in characters. */
  messages: number;
  chars: number;
};

/** A row as the catalog can order and index it. A time that is no whole number of milliseconds
 *  orders differently in SQLite and in JavaScript, and so does a path that is not well-formed.
 *  Every other field passes: it is the row's body. */
const RowInput = z.looseObject({
  path: ContextPath,
  activeMs: z.number().int(),
  createdMs: z.number().int(),
  processors: z.array(z.string()).default([]),
  metadata: z.record(z.string(), z.unknown()).default({}),
});

/** A window's query, read back from its stored key (`normalizeQuery` wrote it). */
function queryOfKey(key: string): Query {
  const stored = JSON.parse(key) as { p?: Fact[]; o?: CatalogOrder; l?: number; k?: string[] };
  if (stored.p)
    return {
      kind: "range",
      predicates: stored.p,
      order: stored.o || "active",
      limit: stored.l || 50,
    };
  return stored.k ? { kind: "keys", keys: stored.k } : { kind: "awake" };
}

function driverFactOf(win: LiveWindow): string {
  const fact = win.query.kind === "range" ? win.query.predicates[win.driver] : undefined;
  return fact ? factId(fact) : "*";
}

/** A row of the awake list (iterate/api `CatalogAwakeRow`). */
function awakeJson(path: string, state: AwakeContextState): string {
  const activities = activeContextActivities(state.activities);
  return JSON.stringify({ path, since: state.since, ...(activities.length > 0 && { activities }) });
}