/** * ORDER INDEX (coordinator, 24 Nov 2026; plan in the lane's LIVE CPU 3 report). An order index on `rows` cannot be * made on a big file: SQLite's CREATE INDEX reads every row of the file whatever its WHERE (1.0 to 1.4 million rows, * 9 to 12 s, on an invented 1.9 GB object), so on the owner's 3.7 GB object the alarm that made one was reset for its * CPU, rolled back and tried again (LIVE CPU 3, fbd79bc268). Past ORDER_INDEX_MAX_BYTES none is made at all, and his * reads lost their order: a pass from nothing carries rows oldest first, and list_records sorts a whole table a call. * * A SHADOW stands in for such an index. It is a small table of its own, one row per row of one table, holding only the * values the order sorts by and the row's id, with an index over them: * * 1. Made empty, with its index and three triggers on `rows`, in one cheap step. From that moment every write of a * row of its table keeps the shadow's row as the row stands (a row that leaves the order leaves the shadow). * 2. Filled in steps, one an alarm: the next STEP rows of its table along the primary key (table_id, id), from a * cursor kept in meta. A step reads that table's rows and no other, never the file. Writes in between are the * triggers' (a step takes each row's values as they stand), and the object runs one invocation at a time. * 3. Ready once the cursor has passed the table's last row: reads then walk it, joined to `rows` by id, as they * walked the partial index. * * A reset inside a step loses that step only (its transaction rolls back, the cursor with it). The alarm's reset mark * (business.ts ALARM_RUNNING) is the bell: a start that finds it while a shadow is filling halves the step. * * Off by default, per account (`order_shadow` in meta, POST /v1/admin/order-shadow). Off, nothing here runs. *//** One sort term: an expression over a row of `rows` (or exactly `id`), its collation and direction. */exportinterfaceTerm { expr: string; collate?: string; desc?: boolean;}/** What a shadow orders: one table's rows (only live ones, when `live`) by `terms`. */exportinterfaceSpec { name: string; table: string; terms: Term[]; live: boolean;/** Only rows this holds (an expression over a row of `rows`): a lookup shadow keeps its few rows, never the table (READ COST). */ where?: string;}interfaceHeldextendsSpec { made: boolean; cursor: string | null; ready: boolean; rows: number; steps: number;/** When it was made empty, and when it became ready (ISO): the fill's whole time, across its alarms. */ began?: string; readyAt?: string;}/** The meta the shadows are held in, by name. */exportconst META = "order_shadows";/** The per-account switch: "on", or absent. */exportconst SWITCH = "order_shadow";/** The rows a step takes, as the bell has left it. */exportconst STEP_META = "order_shadow_step";exportconst STEP_ROWS = 20_000;exportconst STEP_LEAST = 500;exportinterfaceMeta {get(key: string): string | null;set(key: string, value: string | null): void;}exportfunction on(meta: Meta): boolean {return meta.get(SWITCH) === "on";}function held(meta: Meta): Record<string, Held> {try {return JSON.parse(meta.get(META) ?? "{}") asRecord<string, Held>; } catch {return {}; }}function keep(meta: Meta, all: Record<string, Held>): void { meta.set(META, Object.keys(all).length ? JSON.stringify(all) : null);}/** The shadow's own table, index and trigger names. */exportfunction names(name: string): { table: string; index: string; triggers: [string, string, string] } {const table = `shadow_${name}`;return { table, index: `${table}_k`, triggers: [`${table}_in`, `${table}_up`, `${table}_out`] };}const columnOf = (terms: Term[], i: number): string => (terms[i]!.expr === "id" ? "sid" : `c${i}`);/** Each term as the shadow sorts it: `o.c<i>` (or `o.sid`), with its collation and direction. */exportfunction orderBy(spec: Spec, flip = false): string {return spec.terms.map((t, i) => `o.${columnOf(spec.terms, i)}${t.collate ? ` COLLATE ${t.collate}` : ""}${(t.desc === true) !== flip ? " DESC" : ""}`).join(", ");}/** A term's value in a read that walks the shadow. */exportfunction value(spec: Spec, i: number): string {return`o.${columnOf(spec.terms, i)}`;}/** The FROM of a read along a ready shadow: the shadow walked by its index, each row of `rows` found by id. */exportfunctionfrom(spec: Spec): string {const n = names(spec.name);return`${n.table} AS o INDEXED BY ${n.index} CROSS JOIN rows ON rows.table_id = '${spec.table}' AND rows.id = o.sid`;}/** Asks for a shadow (nothing is made here). Answers whether it is ready. */exportfunction ask(meta: Meta, spec: Spec): boolean {const all = held(meta);const was = all[spec.name];if (was) return was.ready; all[spec.name] = { ...spec, made: false, cursor: null, ready: false, rows: 0, steps: 0 }; keep(meta, all);returnfalse;}exportfunction ready(meta: Meta, name: string): Spec | null {const h = held(meta)[name];return h?.ready ? h : null;}/** Whether a shadow is asked for and not ready yet. */exportfunction filling(meta: Meta): boolean {returnObject.values(held(meta)).some((h) => !h.ready);}/** The terms that are values (not `id`), as the shadow's columns hold them. */function valued(spec: Spec): { columns: string[]; exprs: string[] } {const columns: string[] = [];const exprs: string[] = []; spec.terms.forEach((t, i) => {if (t.expr === "id") return; columns.push(`c${i}`); exprs.push(t.expr); });return { columns, exprs };}/** The statements that make a shadow, empty: its table, its index and the triggers that keep it. */exportfunction making(spec: Spec): string[] {const n = names(spec.name);const { columns, exprs } = valued(spec);const into = `INSERT OR REPLACE INTO ${n.table} (${[...columns, "sid"].join(", ")}) SELECT ${[...exprs, "id"].join(", ")} FROM rows`;const live = `${spec.live ? " AND deleted = 0" : ""}${spec.where ? ` AND (${spec.where})` : ""}`;const keyCols = spec.terms.map((t, i) => `${columnOf(spec.terms, i)}${t.collate ? ` COLLATE ${t.collate}` : ""}${t.desc ? " DESC" : ""}`);if (!spec.terms.some((t) => t.expr === "id")) keyCols.push("sid");return [`CREATE TABLE IF NOT EXISTS ${n.table} (${[...columns, "sid TEXT PRIMARY KEY"].join(", ")})`,`CREATE INDEX IF NOT EXISTS ${n.index} ON ${n.table} (${keyCols.join(", ")})`,`CREATE TRIGGER IF NOT EXISTS ${n.triggers[0]} AFTER INSERT ON rows WHEN NEW.table_id = '${spec.table}' BEGIN ${into} WHERE table_id = NEW.table_id AND id = NEW.id${live}; END`,`CREATE TRIGGER IF NOT EXISTS ${n.triggers[1]} AFTER UPDATE ON rows WHEN NEW.table_id = '${spec.table}' OR OLD.table_id = '${spec.table}' BEGIN DELETE FROM ${n.table} WHERE OLD.table_id = '${spec.table}' AND sid = OLD.id; ${into} WHERE NEW.table_id = '${spec.table}' AND table_id = NEW.table_id AND id = NEW.id${live}; END`,`CREATE TRIGGER IF NOT EXISTS ${n.triggers[2]} AFTER DELETE ON rows WHEN OLD.table_id = '${spec.table}' BEGIN DELETE FROM ${n.table} WHERE sid = OLD.id; END`, ];}/** Everything a shadow made, undone. */exportfunction unmaking(name: string): string[] {const n = names(name);return [...n.triggers.map((t) => `DROP TRIGGER IF EXISTS ${t}`), `DROP TABLE IF EXISTS ${n.table}`];}/** * One bounded step of the first shadow not yet ready: made empty (with its triggers), or its next `step` rows laid, * or found complete. Reads at most `step` rows of its table along the primary key. Answers what it did, or null when * no shadow waits. */exportfunction step(sql: SqlStorage, meta: Meta, most?: number): { name: string; did: "made" | "laid" | "ready"; rows: number } | null {const all = held(meta);const h = Object.values(all).find((x) => !x.ready);if (!h) returnnull;if (!h.made) {for (const statement of making(h)) sql.exec(statement); h.made = true; h.began = newDate().toISOString(); keep(meta, all);return { name: h.name, did: "made", rows: 0 }; }// MEASURE GENTLE: the alarm's step is held to its work budget (`most`), below the step this shadow keeps.const take = Math.max(STEP_LEAST, Math.min(Number(meta.get(STEP_META) ?? STEP_ROWS) || STEP_ROWS, most ?? Infinity));// The ids alone first (the primary key covers them): where this step ends.const ids = sql.exec<{ id: string }>(`SELECT id FROM rows WHERE table_id = ? AND id > ? ORDER BY id LIMIT ?`, h.table, h.cursor ?? "", take).toArray();if (!ids.length) { h.ready = true; h.readyAt = newDate().toISOString(); keep(meta, all);return { name: h.name, did: "ready", rows: 0 }; }const last = ids[ids.length - 1]!.id;const n = names(h.name);const { columns, exprs } = valued(h); sql.exec(`INSERT OR REPLACE INTO ${n.table} (${[...columns, "sid"].join(", ")}) SELECT ${[...exprs, "id"].join(", ")} FROM rows WHERE table_id = ? AND id > ? AND id <= ?${h.live ? " AND deleted = 0" : ""}${h.where ? ` AND (${h.where})` : ""}`, h.table, h.cursor ?? "", last, ); h.cursor = last; h.rows += ids.length; h.steps += 1; keep(meta, all);return { name: h.name, did: "laid", rows: ids.length };}/** The bell: an alarm was reset while a shadow was filling, so the next steps take half as many rows. */exportfunction smallerSteps(meta: Meta): number | null {if (!filling(meta)) returnnull;const now = Math.max(STEP_LEAST, Math.floor((Number(meta.get(STEP_META) ?? STEP_ROWS) || STEP_ROWS) / 2)); meta.set(STEP_META, String(now));return now;}/** What the admin is shown: each shadow, how far, and the step. */exportfunction progress(meta: Meta): { on: boolean; step: number; shadows: { name: string; table: string; ready: boolean; rows: number; steps: number; began: string | null; readyAt: string | null }[] } {return { on: on(meta), step: Number(meta.get(STEP_META) ?? STEP_ROWS) || STEP_ROWS, shadows: Object.values(held(meta)).map((h) => ({ name: h.name, table: h.table, ready: h.ready, rows: h.rows, steps: h.steps, began: h.began ?? null, readyAt: h.readyAt ?? null })), };}/** Turned off: every shadow, its triggers and what is held of them go (reads walk what they walked before). */exportfunction dropAll(sql: SqlStorage, meta: Meta): void {for (const name ofObject.keys(held(meta))) for (const statement of unmaking(name)) sql.exec(statement); meta.set(META, null); meta.set(STEP_META, null);}/** * An ORDER BY as list_records writes it (records/list.ts orderSql) cut into its terms: top-level commas only (a * json_extract's comma is inside parentheses, a quoted one inside quotes), each with its COLLATE and direction. */exportfunction terms(order: string): Term[] {const parts: string[] = [];let depth = 0;let quote: string | null = null;let cur = "";for (const ch of order) {if (quote) { cur += ch;if (ch === quote) quote = null;continue; }if (ch === "'" || ch === '"') quote = ch;elseif (ch === "(") depth++;elseif (ch === ")") depth--;elseif (ch === "," && depth === 0) { parts.push(cur.trim()); cur = "";continue; } cur += ch; }if (cur.trim()) parts.push(cur.trim());return parts.map((p) => {let expr = p;let desc = false;let collate: string | undefined;const d = /\s+(ASC|DESC)$/i.exec(expr);if (d) { desc = d[1]!.toUpperCase() === "DESC"; expr = expr.slice(0, d.index).trim(); }const c = /\s+COLLATE\s+(\w+)$/i.exec(expr);if (c) { collate = c[1]!.toUpperCase(); expr = expr.slice(0, c.index).trim(); }return { expr, ...(collate ? { collate } : {}), ...(desc ? { desc } : {}) }; });}