Cotton code
81 lines · 4.8 KB · TypeScriptRaw
/** * ORDER INDEX at his size (coordinator, 24 Nov 2026: prove on an invented 2 GB object). `BIG_OBJECT=1` builds it at * full size; otherwise a hundredth. Every alarm that fills a shadow is timed and its statements' rows read counted: * none may read more than its step of its own table, and none may come near an invocation's CPU. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import type { Store } from "../src/store.ts";import * as orderShadow from "../src/order_shadow.ts";import { BIG, personalShape, writeShape } from "./big_object.ts";import { ADMIN, http, personalObject } from "./personal.ts";type Instance = { store: Store };const SCALE = BIG ? 1.4 : 1 / 100;describe("order shadows at his size", { timeout: 3_600_000 }, () => {  it("fill in steps that each read one step of one table, and a pass from nothing walks them", async () => {    const slug = "order-shadow-big";    const { credential } = await personalObject(slug);    const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));    const size = await runInDurableObject(stub, (_i, s) => {      const last = writeShape(s.storage.sql, personalShape(SCALE));      s.storage.sql.exec("UPDATE meta SET value = CAST(? AS TEXT) WHERE key = 'version'", last);      for (const r of s.storage.sql.exec<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'index' AND name LIKE 'rows_first_%'").toArray()) s.storage.sql.exec(`DROP INDEX ${r.name}`);      return s.storage.sql.databaseSize;    });    expect((await http(slug, "POST", "/v1/admin/order-shadow", { on: true }, ADMIN)).status).toBe(200);    const phone = { authorization: `Bearer ${credential}` };    // His phones' pass from nothing asks.    expect((await http(slug, "GET", "/v1/sync?since=0&limit=500", undefined, phone)).status).toBe(200);    // A list in an order asks too.    await runInDurableObject(stub, (o) => (o as unknown as Instance).store.selectOrdered("message", [], "NULLIF(json_extract(data, '$.sent_at'), '') IS NULL, NULLIF(json_extract(data, '$.sent_at'), '') COLLATE NOCASE DESC, updated_at DESC, id", 20, 0));    // Every statement an alarm runs, with the rows it read (counted once each cursor is drained).    const seen: { q: string; read: () => number }[] = [];    await runInDurableObject(stub, (_i, s) => {      const sql = s.storage.sql as unknown as { exec: (q: string, ...a: unknown[]) => { rowsRead: number; toArray(): unknown[] } };      const real = sql.exec.bind(sql);      sql.exec = (q: string, ...a: unknown[]) => {        const c = real(q, ...a);        seen.push({ q, read: () => c.rowsRead });        return c;      };    });    const times: number[] = [];    let worst = { rows: 0, q: "" };    for (let i = 0; i < 2_000; i++) {      const p = await runInDurableObject(stub, (o) => (o as unknown as Instance).store.shadowProgress());      if (p.shadows.length && p.shadows.every((x) => x.ready)) break;      seen.length = 0;      // The shadow's own step, timed alone (the alarm also runs its other passes; the small test runs it through the alarm).      times.push(await runInDurableObject(stub, (o, st) => {        const t0 = Date.now();        st.storage.transactionSync(() => (o as unknown as Instance).store.shadowStep());        return Date.now() - t0;      }));      for (const st of seen) {        if (!/shadow_|FROM rows WHERE table_id = \? AND id > \?/.test(st.q)) continue;        const r = st.read();        if (r > worst.rows) worst = { rows: r, q: st.q.slice(0, 120) };      }    }    const p = await runInDurableObject(stub, (o) => (o as unknown as Instance).store.shadowProgress());    expect(p.shadows.every((x) => x.ready)).toBe(true);    times.sort((a, b) => a - b);    const line = `order shadows on ${(size / 1e6).toFixed(0)} MB: ${p.shadows.length} shadows, ${times.length} steps, step ms median ${times[times.length >> 1]} p95 ${times[Math.floor(times.length * 0.95)]} max ${times[times.length - 1]}; most rows one shadow statement read ${worst.rows} (${worst.q})`;    console.log(line);    // SAY=1 fails here on purpose, so the line reaches the run's log (the pool keeps a passing test's console).    if ((env as unknown as { SAY?: string }).SAY === "1") throw new Error(`SAY ${line}`);    // A step reads its rows of one table (a row twice at most: its id from the key, then the row), never the file.    expect(worst.rows).toBeLessThanOrEqual(2 * orderShadow.STEP_ROWS + 10);    // A pass from nothing walks them: its first page is answered.    const t0 = Date.now();    const first = await http<{ rows: unknown[] }>(slug, "GET", "/v1/sync?since=0&limit=500", undefined, phone);    console.log(`order shadows walked: a pass's first page in ${Date.now() - t0} ms`);    expect(first.status).toBe(200);    expect(first.body.rows.length).toBeGreaterThan(0);  });});