Cotton code
82 lines · 5.2 KB · TypeScriptRaw
/** * LIVE CPU 2 (coordinator, 23 Nov 2026). A pass's opening figures never read every row of a big table: on an object of * his shape (row_counts counted, as on his), a pass from nothing sums row_counts, and a later pass that carries a table * again (`again=`, a new build keeping a column the copy's cursor went past) counts that table from row_counts and its * rows changed since along rows_cursor, where it counted every row of it twice. `BIG_OBJECT=1` at full size. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { BIG, personalShape, writeShape } from "./big_object.ts";import { http, personalObject } from "./personal.ts";type Exec = { exec: (q: string, ...a: unknown[]) => { rowsRead: number }; seen?: [string, () => number][] };describe("a pass's opening figures", { timeout: 1_800_000 }, () => {  it("read row_counts and the rows changed, never every row of a table", async () => {    const slug = "pass-counts-big";    const { credential } = await personalObject(slug, { arrival: true });    const phone = { authorization: `Bearer ${credential}` };    const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));    const shape = personalShape(BIG ? 1.25 : 1 / 100);    const messages = shape.find((t) => t.table === "message")!.rows;    const version = await runInDurableObject(stub, (instance, s) => {      const last = writeShape(s.storage.sql, shape);      s.storage.sql.exec("UPDATE meta SET value = CAST(? AS TEXT) WHERE key = 'version'", last);      const store = (instance as unknown as { store: { carryCounts(steps: number, tx: (step: () => void) => void): boolean } }).store;      while (store.carryCounts(50, (step) => s.storage.transactionSync(step)));      return last;    });    // Every count over rows (row_counts is the day-bucketed tally, read whole) a pass's first page runs, with the rows each read.    const counting = async (path: string): Promise<[string, number][]> => {      await runInDurableObject(stub, (_i, s) => {        const sql = s.storage.sql as unknown as Exec;        const real = sql.exec.bind(sql);        sql.seen = [];        sql.exec = (q: string, ...a: unknown[]) => {          const c = real(q, ...a);          if (/COUNT\(|SUM\(/i.test(q) && /FROM rows\b/.test(q)) sql.seen!.push([q.replace(/\s+/g, " ").slice(0, 120), () => c.rowsRead]);          return c;        };      });      const r = await http(slug, "GET", path, undefined, phone);      expect(r.status, path).toBe(200);      return runInDurableObject(stub, (_i, s) => {        const sql = s.storage.sql as unknown as Exec;        const seen = (sql.seen ?? []).map(([q, n]) => [q, n()] as [string, number]);        sql.exec = Object.getPrototypeOf(sql).exec.bind(sql);        return seen;      });    };    for (const path of ["/v1/sync?since=0", `/v1/sync?since=${version - 20}&again=message`, `/v1/sync?since=0&tables=message,thread`]) {      const seen = await counting(path);      const most = Math.max(0, ...seen.map(([, n]) => n));      console.log(`${path}: ${seen.length} counting statements, the most read ${most} rows (message holds ${messages})`);      expect(most, `${path}: ${JSON.stringify(seen.sort((a, b) => b[1] - a[1]).slice(0, 3))}`).toBeLessThan(messages / 10);    }    // SLOW READ (26 Nov 2026, dev at 1.8 GB: a first page took 3 to 4.5 s while a recount ran): a recount of one table    // under way (a kit dating `thread` anew) leaves every other table's counts read from row_counts, and the figures    // the same as when every table is counted.    type Figures = { total: number; remaining: number; done: number; tables: Record<string, { rows: number }> };    const whole = (await http<Figures>(slug, "GET", "/v1/sync?since=0", undefined, phone)).body;    await runInDurableObject(stub, (instance, s) => {      const plan = JSON.parse(s.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'row_counts_plan'").one().value) as { by: Record<string, string> };      plan.by.thread = "a_date_it_no_longer_has";      s.storage.sql.exec("UPDATE meta SET value = ? WHERE key = 'row_counts_plan'", JSON.stringify(plan));      // One row a step, so the recount is still under way through the page below.      (instance as unknown as { store: { recountChunk: number } }).store.recountChunk = 1;    });    const threads = shape.find((t) => t.table === "thread")!.rows;    const seen = await counting("/v1/sync?since=0");    const most = Math.max(0, ...seen.map(([, n]) => n));    console.log(`a recount of thread under way: ${seen.length} counting statements, the most read ${most} rows (thread holds ${threads})`);    // `rowsRead` counts the index entries a count walks as well as the rows: about twice the table's rows, that table alone.    expect(most, JSON.stringify(seen.sort((a, b) => b[1] - a[1]).slice(0, 3))).toBeLessThanOrEqual(threads * 2.5);    const during = (await http<Figures>(slug, "GET", "/v1/sync?since=0", undefined, phone)).body;    expect(during.total, "the same total while thread is counted again").toBe(whole.total);    expect(during.remaining).toBe(whole.remaining);    expect(during.tables.thread?.rows).toBe(whole.tables.thread?.rows);    expect(during.tables.message?.rows).toBe(whole.tables.message?.rows);  });});