Cotton code
310 lines · 18.4 KB · TypeScriptRaw
/** * MEASURE GENTLE (coordinator for the owner, 26 Nov 2026: on live his object answered every request in 1.7 to 7.5 s * behind the storage measure, 4 steps of 10,000 rows an alarm, an alarm a second). A measure call is held to its work * budget, counted by rows and bytes read; its place survives a deploy (a plan of the old shape is taken on in place, * and a figure whose shape moved is summed again alone); a new measure begins only once the last finished; the * bounded jobs wait 5 s between alarms, 60 s while the object is in use; an order index is made only while nobody * uses the object; the change and act logs' trims stop at their step's budget. Invented rows only. */import { env, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { writeShape } from "./big_object.ts";import { http, personalObject } from "./personal.ts";import { FIGURES_V, lastMeasure, MEASURE_EVERY_MS, measureNow, measureStep, PROBE_ROWS, WORK_A_STEP, BYTES_A_UNIT } from "../src/storage_measure.ts";import { partsPlan } from "../src/storage_parts.ts";import { SCHEMA, Store } from "../src/store.ts";const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));type Kept = Map<string, string | null>;const hostOf = (sql: SqlStorage, kept: Kept) => ({ sql, meta: (k: string) => kept.get(k) ?? null, setMeta: (k: string, v: string | null) => void kept.set(k, v) });const MAIL_BYTES = 5_800;describe("the storage measure, a gentle step at a time", () => {  const slug = "measure-gentle";  it("holds a call to its work budget on mail-sized rows, and finishes with the figures a whole pass gives", async () => {    await runInDurableObject(stub(slug), (_i, s) => {      s.storage.sql.exec(SCHEMA);      writeShape(s.storage.sql, [{ table: "email", rows: 6_000, dated: "received_at", body: MAIL_BYTES, deadEvery: 20 }]);    });    const got = await runInDurableObject(stub(slug), (_i, s) => {      const sql = s.storage.sql;      const kept: Kept = new Map();      const rowsJob = partsPlan(sql).findIndex((j) => j.name === "rows");      kept.set("storage_measure_plan", JSON.stringify({ v: 3, vs: { ...FIGURES_V }, at: "2026-11-26T10:00:00Z", job: rowsJob, after: null, figures: {}, tables: {}, changes: {}, dangling: {} }));      measureStep(hostOf(sql, kept), new Date("2026-11-26T10:00:00Z"));      const plan = JSON.parse(kept.get("storage_measure_plan")!) as { job: number; after: number };      return { job: plan.job, rowsJob, after: plan.after };    });    expect(got.job, "one call does not finish 6,000 mail rows").toBe(got.rowsJob);    // A mail row is about 1 + 5,800 / 300 units: a call reads its probe, then what the rest of its budget buys.    const perRow = 1 + MAIL_BYTES / BYTES_A_UNIT;    expect(got.after).toBeGreaterThan(PROBE_ROWS);    expect(got.after).toBeLessThanOrEqual(PROBE_ROWS + Math.ceil(WORK_A_STEP / perRow) + 50);    const whole = await runInDurableObject(stub(slug), (_i, s) => {      const sql = s.storage.sql;      const kept: Kept = new Map();      let calls = 1;      while (measureStep(hostOf(sql, kept), new Date("2026-11-26T10:00:00Z"))) calls += 1;      return { calls, measure: lastMeasure(hostOf(sql, kept))!, now: measureNow(sql, new Date("2026-11-26T10:00:00Z")) };    });    // 6,000 mail rows are three calls of about 2,000; the other tables after.    expect(whole.calls).toBeGreaterThan(3);    expect(whole.measure.tables).toEqual(whole.now.tables);    expect(whole.measure.parts.parts).toEqual(whole.now.parts.parts);  }, 300_000);  it("carries a measure under way across a deploy: a plan of the old shape goes on in place, and a figure whose shape moved is summed again alone", async () => {    const out = await runInDurableObject(stub(slug), (_i, s) => {      const sql = s.storage.sql;      const at = new Date("2026-11-26T11:00:00Z");      const kept: Kept = new Map();      const host = hostOf(sql, kept);      const jobs = partsPlan(sql).map((j) => j.name);      // Past the rows table, as shape 2 kept it (no pace, no figures' shapes).      while (measureStep(host, at, 0, 2_000) && (JSON.parse(kept.get("storage_measure_plan")!) as { job: number }).job <= jobs.indexOf("rows"));      const mid = JSON.parse(kept.get("storage_measure_plan")!) as Record<string, unknown>;      const v2: Record<string, unknown> = { ...mid, v: 2 };      delete v2.vs;      delete v2.pace;      kept.set("storage_measure_plan", JSON.stringify(v2));      measureStep(host, at, 0);      const taken = JSON.parse(kept.get("storage_measure_plan")!) as { v: number; job: number; tables: object; figures: Record<string, number[]> };      // The tables' figure's shape moves: summed again over the rows already passed; the parts kept as they were.      const was = FIGURES_V.tables;      FIGURES_V.tables = was + 1;      let redo = false;      try {        measureStep(host, at, 0);        redo = ((JSON.parse(kept.get("storage_measure_plan")!) as { redo?: unknown[] }).redo?.length ?? 0) > 0 || Object.keys((JSON.parse(kept.get("storage_measure_plan")!) as { tables: object }).tables).length > 0;        while (measureStep(host, at));      } finally {        FIGURES_V.tables = was;      }      return { midJob: Number(mid.job), taken, redo, measure: lastMeasure(host)!, now: measureNow(sql, at), rowsJob: jobs.indexOf("rows") };    });    expect(out.taken.v, "shape 2 taken on as shape 3").toBe(3);    expect(out.taken.job, "not begun again").toBeGreaterThanOrEqual(out.midJob);    expect(Object.keys(out.taken.tables).length, "the tables already summed are kept").toBeGreaterThan(0);    expect(out.midJob).toBeGreaterThan(out.rowsJob);    expect(out.redo).toBe(true);    expect(out.measure.tables, "the figure summed again comes out whole").toEqual(out.now.tables);    expect(out.measure.parts.parts).toEqual(out.now.parts.parts);  }, 300_000);  it("begins a new measure only once the last finished, MEASURE_EVERY_MS after it finished", async () => {    const out = await runInDurableObject(stub(slug), (_i, s) => {      const sql = s.storage.sql;      const kept: Kept = new Map();      const now = new Date("2026-11-26T20:00:00Z");      // Begun long ago, finished an hour ago: not again yet.      kept.set("storage_measure", JSON.stringify({ ...measureNow(sql, new Date(now.getTime() - 2 * MEASURE_EVERY_MS)), done_at: new Date(now.getTime() - 3_600_000).toISOString() }));      const soon = measureStep(hostOf(sql, kept), now);      const later = measureStep(hostOf(sql, kept), new Date(now.getTime() + MEASURE_EVERY_MS));      return { soon, plan: kept.get("storage_measure_plan") ?? null, later };    });    expect(out.soon).toBe(false);    expect(out.later).toBe(true);  });  it("stops a trim of the change log at its step's characters, and of the act log at its lines", async () => {    const out = await runInDurableObject(stub(slug), (instance, s) => {      const sql = s.storage.sql;      sql.exec("WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 40) INSERT INTO change (at, actor, via, table_id, record_id, kind, before, after, version) SELECT '2020-01-01T00:00:00Z', NULL, 'update_record', 'note', printf('n%05d', x), 'update', hex(randomblob(500000)), NULL, 1 FROM c");      sql.exec("WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 6000) INSERT INTO acts (id, at, person_id, act, args, outcome) SELECT printf('a%05d', x), '2020-01-01T00:00:00Z', NULL, 'create', '{}', 'ok' FROM c");      const store = (instance as unknown as { store: Store }).store;      const changes = store.trimChanges("2026-01-01T00:00:00Z", 1_000_000, null, 2_000, 15_000_000);      const acts = store.trimActs("2026-01-01T00:00:00Z", 1_000_000, 2_500);      return { changes, acts };    });    // 1 MB of before each: at most 15 a step of 15 MB, and more left.    expect(out.changes.trimmed).toBeLessThanOrEqual(15);    expect(out.changes.trimmed).toBeGreaterThan(0);    expect(out.changes.more).toBe(true);    expect(out.acts.trimmed).toBe(2_500);    expect(out.acts.more).toBe(true);  });});describe("the bounded jobs' cadence", () => {  it("waits 5 s between alarms, 60 s while the object is in use, and makes an order index only while nobody uses it", async () => {    const slug = "measure-gentle-cadence";    const { owner: token } = await personalObject(slug);    const owner = { authorization: `Bearer ${token}` };    // A planted table is counted again by the alarm, a few steps at a time: a bounded job with more to do.    for (const from of [0, 5_000]) expect((await http(slug, "POST", "/v1/admin/dev/plant-rows", { table: "message", from, count: 5_000, bytes: 400, dated: "sent_at" }, owner)).status).toBe(200);    const idle = (instance: unknown) => Object.assign(instance as object, { lastRequestAt: 0, lastPullAt: 0 });    // Nobody in: the next alarm in 5 s.    await runInDurableObject(stub(slug), (instance) => void idle(instance));    await runDurableObjectAlarm(stub(slug));    const quiet = await runInDurableObject(stub(slug), async (_i, s) => ((await s.storage.getAlarm()) ?? 0) - Date.now());    // Read some time after the alarm set it (seconds, on a loaded test box): at most 5 s, and set, never the 60 s of in use.    expect(quiet).toBeGreaterThan(0);    expect(quiet).toBeLessThanOrEqual(5_000);    // A request just now: 60 s.    expect((await http(slug, "GET", "/v1/definitions", undefined, owner)).status).toBe(200);    await runDurableObjectAlarm(stub(slug));    const busy = await runInDurableObject(stub(slug), async (_i, s) => ((await s.storage.getAlarm()) ?? 0) - Date.now());    expect(busy).toBeGreaterThan(50_000);    expect(busy).toBeLessThanOrEqual(60_000);    // A pull's page just now, and no other request since 30 s: still 60 s.    await runInDurableObject(stub(slug), (instance) => void Object.assign(instance as object, { lastRequestAt: 0, lastPullAt: Date.now() }));    await runDurableObjectAlarm(stub(slug));    expect(await runInDurableObject(stub(slug), async (_i, s) => ((await s.storage.getAlarm()) ?? 0) - Date.now())).toBeGreaterThan(50_000);    // An order index asked for waits while someone uses the object, and is made once nobody has for 30 s.    const ask = await runInDurableObject(stub(slug), (_i, s) => {      s.storage.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('order_indexes_wanted', ?)", JSON.stringify({ rows_gentle_test: "CREATE INDEX IF NOT EXISTS rows_gentle_test ON rows (table_id, updated_at)" }));      return true;    });    expect(ask).toBe(true);    const made = () => runInDurableObject(stub(slug), (_i, s) => s.storage.sql.exec("SELECT 1 FROM sqlite_master WHERE name = 'rows_gentle_test'").toArray().length > 0);    await runInDurableObject(stub(slug), (instance) => void Object.assign(instance as object, { lastRequestAt: Date.now() }));    await runDurableObjectAlarm(stub(slug));    expect(await made(), "not while in use").toBe(false);    await runInDurableObject(stub(slug), (instance) => void idle(instance));    await runDurableObjectAlarm(stub(slug));    expect(await made(), "made once nobody uses it").toBe(true);  }, 300_000);});// MEASURE GENTLE 2 (coordinator's review of 97f0ef0420): the next alarm is decided in one place, as the earliest of// every job's want; a job whose want is later does nothing when the alarm comes early for another; a throw in one// bounded job never skips the rest of the alarm or its re-arm; while the object is in use, one bounded job an alarm.describe("every alarm user's want, in one place", () => {  type Live = { gentleInTests: boolean; wants: Map<string, number>; gentleOwed: string[]; lastRequestAt: number; lastPullAt: number; store: Store; alarm(): Promise<void> };  const live = (instance: unknown) => instance as Live;  const slug = "measure-gentle-wants";  // AUDIT D 11 (d525eba787): the list links' fill is a bounded job too.  const WRAPPED = ["measureStorage", "carryCounts", "shadowStep", "trimChanges", "trimActs", "listLinksStep"];  /**   * One alarm, run here and now with the scheduled one taken away first (a scheduled alarm fires by itself between a   * test's steps): `before` sets the instance up; answers the bounded jobs' calls this alarm made and when the next   * alarm comes.   */  async function oneAlarm(before: (l: Live) => void, forced: Record<string, boolean> = {}): Promise<{ calls: string[]; next: number; owed: string[] }> {    return runInDurableObject(stub(slug), async (instance, s) => {      await s.storage.deleteAlarm();      const l = live(instance);      l.gentleInTests = true;      const store = l.store as unknown as Record<string, unknown>;      const calls: string[] = [];      const real = new Map<string, unknown>();      for (const name of WRAPPED) {        const was = store[name] as (...a: unknown[]) => unknown;        real.set(name, was);        store[name] = (...a: unknown[]) => {          calls.push(name);          // A forced answer: this job has more to do (true) or none (false), without touching the file.          if (name in forced) return name === "trimChanges" || name === "trimActs" ? { trimmed: forced[name] ? 1 : 0, more: forced[name] } : forced[name];          return was.apply(store, a);        };      }      before(l);      try {        await l.alarm();      } finally {        for (const [name, was] of real) store[name] = was;      }      return { calls, next: ((await s.storage.getAlarm()) ?? 0) - Date.now(), owed: [...l.gentleOwed] };    });  }  it("comes at the earliest want, and a job whose want is later does no work when the alarm comes early", async () => {    const { owner: token } = await personalObject(slug);    const owner = { authorization: `Bearer ${token}` };    for (const from of [0, 5_000]) expect((await http(slug, "POST", "/v1/admin/dev/plant-rows", { table: "message", from, count: 5_000, bytes: 400, dated: "sent_at" }, owner)).status).toBe(200);    // The bounded jobs asked for 50 s from now; the books' pass for 20 s.    const early = await oneAlarm((l) => {      l.lastRequestAt = 0;      l.lastPullAt = 0;      l.wants.set("gentle", Date.now() + 50_000);      l.wants.set("books", Date.now() + 20_000);    });    expect(early.calls, "the bounded jobs' want is later: none of them ran").toEqual([]);    expect(early.next, "the earliest want: the books' 20 s").toBeLessThanOrEqual(20_000);    expect(early.next).toBeGreaterThan(10_000);    // Their want reached: they run.    const due = await oneAlarm((l) => {      l.wants.clear();    });    expect(due.calls.length).toBeGreaterThan(1);  }, 300_000);  it("while the object is in use, takes every bounded job in a fair turn: a job that can do nothing now does not hold the slot", async () => {    // Every job has more to do, and an order index is asked (it waits while the object is in use): each in-use alarm    // gives its one slot to the next job, so five alarms take five jobs, none twice.    await runInDurableObject(stub(slug), (_i, s) => {      s.storage.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('order_indexes_wanted', ?)", JSON.stringify({ rows_fair_test: "CREATE INDEX IF NOT EXISTS rows_fair_test ON rows (table_id, created_at)" }));    });    const busy = Object.fromEntries(WRAPPED.map((name) => [name, true]));    // The shadows' fill is not one of the turns (READ COST 4: it runs on every alarm that is its time, beside them).    const turns = WRAPPED.filter((name) => name !== "shadowStep");    const seen: string[][] = [];    let next = 0;    for (let i = 0; i < turns.length; i++) {      const one = await oneAlarm((l) => {        l.wants.delete("gentle");        l.lastRequestAt = Date.now();      }, busy);      seen.push(one.calls);      next = one.next;    }    for (const one of seen) expect(one.length, `one slot an alarm: ${JSON.stringify(seen)}`).toBe(1);    expect(new Set(seen.flat()).size, `every job in turn, the trims among them: ${JSON.stringify(seen)}`).toBe(turns.length);    expect(await runInDurableObject(stub(slug), (_i, s) => s.storage.sql.exec("SELECT 1 FROM sqlite_master WHERE name = 'rows_fair_test'").toArray().length), "no index while in use").toBe(0);    expect(await runInDurableObject(stub(slug), (instance) => live(instance).gentleOwed), "still asked").toContain("order_index");    expect(next, "in use: 60 s").toBeGreaterThan(50_000);    // A job that owed nothing and finds nothing to do does not hold the slot: the turn goes on to the one with work.    const idle = Object.fromEntries(WRAPPED.map((name) => [name, name === "carryCounts"]));    const one = await oneAlarm((l) => {      l.wants.delete("gentle");      l.gentleOwed = [];      l.lastRequestAt = Date.now();    }, idle);    expect(one.calls.at(-1), JSON.stringify(one.calls)).toBe("carryCounts");  }, 300_000);  it("a throw in a carry-on pass skips none of the others, nor the re-arm", async () => {    const out = await oneAlarm((l) => {      l.wants.clear();      (l as unknown as { calendarPass: () => Promise<never> }).calendarPass = async () => {        throw new Error("an invented failure");      };    });    expect(out.next, "re-armed").toBeGreaterThan(0);    expect(await runInDurableObject(stub(slug), (instance) => live(instance).wants.has("calendar")), "tried again at its carry-on").toBe(true);    await runInDurableObject(stub(slug), (instance) => {      delete (instance as unknown as { calendarPass?: unknown }).calendarPass;    });  }, 300_000);  it("keeps no bounded jobs' want on an object with no tables, so its alarm is not woken each second", async () => {    const bare = env.BUSINESS.get(env.BUSINESS.idFromName("measure-gentle-bare"));    const wants = await runInDurableObject(bare, async (instance, s) => {      const l = live(instance);      l.gentleInTests = true;      l.wants.set("gentle", Date.now() - 1_000);      l.gentleOwed = ["measure"];      await s.storage.deleteAlarm();      await l.alarm();      return { gentle: l.wants.has("gentle"), owed: l.gentleOwed };    });    expect(wants).toEqual({ gentle: false, owed: [] });  }, 300_000);  it("a throw in one bounded job skips none of the others, nor the re-arm", async () => {    const out = await oneAlarm((l) => {      l.wants.clear();      l.lastRequestAt = 0;      l.lastPullAt = 0;      (l.store as unknown as { measureStorage: () => boolean }).measureStorage = () => {        throw new Error("an invented failure");      };    });    expect(out.calls, "the jobs after it ran").toContain("carryCounts");    expect(out.owed).toContain("measure");    expect(out.next, "re-armed, at the bounded jobs' 5 s").toBeGreaterThan(0);    expect(out.next).toBeLessThanOrEqual(5_000);  }, 300_000);});