Cotton code
121 lines · 8.0 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { planFirst } from "../src/first.ts";import { Store, type Cursor, type FirstAt, type FirstPlan, type StoredRow, type SyncScope } from "../src/store.ts";import { BIG, personalShape, sortsOfRows, watchStatements, writeShape } from "./big_object.ts";/** * HOW SOON CHAT LOOKS RIGHT ON A VERY LARGE OBJECT (owner, 21 Nov 2026). * The invented object of the personal one's shape (test/big_object.ts), its * chats made real: threads with their last message's time, every message * linked to its thread and dated, the newest written last (as an account * fills). A phone pulls Chat's tables from nothing, page by page, as before * (small tables, then change order) and now (src/first.ts); measured is how * many rows, pages and milliseconds of the object's own work come before the * newest 50 messages of the 20 most recent chats are all on the phone, and * what the whole pass costs. Printed (`--disableConsoleIntercept`); * `BIG_OBJECT=1` runs it at full size. */const SCALE = BIG ? 1 : 1 / 40;const CHATS = BIG ? 3000 : 120;const NEWEST = 50;const RECENT = 20;describe("Chat's first pull on a very large object", () => {  it("brings the newest messages of the most recent chats first, and the whole pass stays as cheap", async () => {    const stub = env.BUSINESS.get(env.BUSINESS.idFromName("sync-first-big"));    await runInDurableObject(stub, (_instance, state) => {      const sql = state.storage.sql;      const shape = personalShape(SCALE).filter((t) => t.table !== "thread");      let upto = writeShape(sql, shape);      const messages = shape.find((t) => t.table === "message")!.rows;      // The chats: message x is in chat 1 + x % CHATS, sent x minutes after the start, so its version and its time rise together.      sql.exec(        `UPDATE rows SET data = json_set(data, '$.thread_id', printf('thread-%05d', 1 + CAST(substr(id, 9) AS INTEGER) % ?), '$.sent_at', strftime('%Y-%m-%dT%H:%M:%SZ', '2024-01-01', '+' || CAST(substr(id, 9) AS INTEGER) || ' minutes')) WHERE table_id = 'message' AND deleted = 0`,        CHATS,      );      sql.exec(        `WITH RECURSIVE c(t) AS (SELECT 1 UNION ALL SELECT t + 1 FROM c WHERE t < ?)         INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at)         SELECT 'thread', printf('thread-%05d', t), json_object('last_message_at', strftime('%Y-%m-%dT%H:%M:%SZ', '2024-01-01', '+' || (? - ((? - (t - 1)) % ?)) || ' minutes'), 'sealed_enc', 's1:' || hex(randomblob(100)), 'dek_enc', 'd1:x', 'seal_v', 1), NULL, ? + t, 0, '2025-01-01T00:00:00Z', '2025-06-01T00:00:00Z' FROM c`,        CHATS,        messages,        messages,        CHATS,        upto,      );      upto += CHATS;      const total = Number(sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM rows").one().n);      const store = new Store(sql, () => new Date("2026-11-21T10:00:00Z"));      store.setDateColumns(new Map(shape.filter((t) => t.dated).map((t) => [t.table, t.dated!])));      while (store.carryCounts(10_000));      const tables = ["thread", "message", "message_contact_handle", ...shape.filter((t) => t.table.startsWith("small_")).slice(0, 6).map((t) => t.table)];      const scope: SyncScope = { kind: "tables", whole: new Set(tables), own: new Set(), person: null, except: new Set() };      // What the phone waits for: the newest 50 messages of the 20 most recent chats.      const recent = sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'thread' ORDER BY json_extract(data, '$.last_message_at') DESC, id DESC LIMIT ?", RECENT).toArray().map((r) => r.id);      const wanted = new Set<string>();      for (const t of recent) for (const r of sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'message' AND deleted = 0 AND json_extract(data, '$.thread_id') = ? ORDER BY json_extract(data, '$.sent_at') DESC, id DESC LIMIT ?", t, NEWEST)) wanted.add(r.id);      expect(wanted.size, "the recent chats each hold most of 50 live messages").toBeGreaterThan(RECENT * NEWEST * 0.8);      type Run = { rowsUntil: number; pagesUntil: number; msUntil: number; rows: number; pages: number; ms: number; mostRead: number; sorts: string[] };      const measure = (page: (first: boolean) => { rows: StoredRow[]; more: boolean }): Run => {        const run: Run = { rowsUntil: 0, pagesUntil: 0, msUntil: 0, rows: 0, pages: 0, ms: 0, mostRead: 0, sorts: [] };        const left = new Set(wanted);        const begun = Date.now();        for (let more = true; more; ) {          const { result, statements } = watchStatements(sql, () => page(run.pages === 0));          run.pages++;          // The rows the phone holds when the last wanted one lands: the pages before, and this page up to it.          result.rows.forEach((r, i) => {            if (r.table === "message" && left.delete(r.id) && left.size === 0) run.rowsUntil = run.rows + i + 1;          });          run.rows += result.rows.length;          run.mostRead = Math.max(run.mostRead, ...statements.map((s) => s.rowsRead));          // Every page's statements at the suite's size; the first pages' at full size (EXPLAIN of each is slow there).          if (!BIG || run.pages <= 3) run.sorts.push(...sortsOfRows(sql, statements));          if (left.size === 0 && run.pagesUntil === 0) Object.assign(run, { pagesUntil: run.pages, msUntil: Date.now() - begun });          more = result.more;        }        run.ms = Date.now() - begun;        return run;      };      // A pass's first page is 200 rows, every later one 5000 (src/business.ts).      const limit = (first: boolean): number => (first ? 200 : 5000);      // Before: the small tables whole, then every other row in change order.      const small = store.smallFirst({ since: 0, upto, scope, windows: [], most: 10_000 });      let after: Cursor | null = null;      const before = measure((first) => {        const got = store.changedPage({ since: 0, upto, limit: limit(first), scope, windows: [], small, floor: null, after });        const last = got.rows[got.rows.length - 1];        if (last) after = { version: last.version, table: last.table, id: last.id };        return got;      });      // Now: what each app shows first, then the long tail.      const counts = store.passTables({ since: 0, upto, scope, windows: [] });      const specs = planFirst((t) => counts.get(t) ?? 0, "2026-11-21", 10_000);      const indexed = Date.now();      store.firstIndexes(specs);      const indexMs = Date.now() - indexed;      store.firstPass("big", 1, 0);      let cursor: { plan: FirstPlan; at: FirstAt | null } = { plan: { pass: "big", small: small.filter((t) => !specs.some((s) => s.table === t)), specs, cuts: specs.map(() => null) }, at: null };      const now = measure((first) => {        const got = store.firstPage({ since: 0, upto, limit: limit(first), scope, windows: [], ...cursor });        cursor = JSON.parse(JSON.stringify({ plan: got.plan, at: got.at })) as typeof cursor;        return got;      });      const line = (name: string, r: Run): string =>        `${name.padEnd(8)} the 20 recent chats' newest 50 after ${String(r.rowsUntil).padStart(8)} rows, ${String(r.pagesUntil).padStart(4)} pages, ${String(r.msUntil).padStart(6)} ms | whole pass ${r.rows} rows, ${r.pages} pages, ${r.ms} ms, most read by a statement ${r.mostRead}`;      console.log(`\nthe invented object: ${total} rows, ${messages} messages in ${CHATS} chats; Chat pulls ${tables.length} tables\n${line("before", before)}\n${line("now", now)}\nthe first orders' indexes, made once: ${indexMs} ms`);      expect(now.rows, "the same rows come").toBe(before.rows);      expect(now.rowsUntil, "the recent chats' newest messages come right after the chats' rows, nothing between").toBe(CHATS + wanted.size);      expect(now.sorts, "no page sorts rows in a temporary B-tree").toEqual([]);      expect(now.mostRead, "no statement reads more than a page and its look-ahead").toBeLessThanOrEqual(before.mostRead + 5001);    });  }, 3_000_000);});