Cotton code
328 lines · 16.8 KB · TypeScriptRaw
/** * WHAT THE OBJECT HOLDS, MEASURED A STEP AT A TIME (coordinator for the owner, 23 Nov 2026: on his 4.2 GB object * storage_summary took 13 to 25 s and twice answered 500). Its three figures each read the whole file: the tables' * bytes (every row's data), the file's parts (every table and index, src/storage_parts.ts) and who fills the change log * (every change's before and after). On an object this size they are worked out on the object's own alarm instead, a * bounded run of rows at a time by rowid, their place and their sums kept in meta (`storage_measure_plan`), and the * last whole measure kept with when it began (`storage_measure`). storage_summary answers from that, at once, and says * when it was measured; a measure older than MEASURE_EVERY_MS is begun again. A small object (under SMALL_FILE) is * measured when asked, as it always was. * * COTTON DATA (CONTRACT.md "The Worker", 25 Nov 2026) adds two figures to the same walk, read from what the object * holds in clear and nothing more: each table's oldest and newest live row (min and max `created_at`, over the same * range of `rows` its counts are taken from), and the links that point at nothing (`dangling`: a single-valued link * whose target row is gone or deleted), counted over the same range of `links` its parts are, one look-up of the * target's key each. */import { measureRange, partsOf, partsPlan, partsTotal, type PartsJob, type RangeEnd, type StoragePart, type StorageParts } from "./storage_parts.ts";/** Below this file size the figures are worked out when asked (they take well under a second). */export const SMALL_FILE = 64 * 1024 * 1024;/** A measure this old is begun again on the next alarm. */export const MEASURE_EVERY_MS = 6 * 60 * 60 * 1000;/** * MEASURE GENTLE (coordinator for the owner, 26 Nov 2026: on live his object answered every request in 1.7 to 7.5 s * behind 4 steps of 10,000 rows an alarm, an alarm a second). One call is budgeted by the work it does, never by a * clock (LIVE CPU 4: a Worker's Date.now() and performance.now() stand still through synchronous work): each range * counts one unit a row read and one a BYTES_A_UNIT bytes of what it holds, and a call stops once it has done * WORK_A_STEP units. Sized on the test pool's workerd (the release build) over an invented mail table of 60,000 rows of * about 5,800 bytes (360 MB file): a range of the rows table (its figures, then its tables' sums, a second read) took * 23 ms for 500 rows, 49 for 2,000, 85 for 4,000 and 180 for 8,000; about 18 µs a row, nearly all of it its bytes, and * 13 ms a call before any row. So a mail row is 1 + 5,800 / 300, about 20 units; 2,000 of them, about 50 ms, make the * 40,000 units left after a call's own cost. The old 4 × 10,000 rows was about 1.8 s of the same rows. */export const WORK_A_STEP = 40_000;/** The bytes that count as one unit of work (one row read is another). */export const BYTES_A_UNIT = 300;/** A table's first range, before its pace is known: then its ranges are sized by the units its rows cost. */export const PROBE_ROWS = 256;/** What moving on to the next table costs besides its rows (its plan, its first statement). */const JOB_UNITS = 500;/** Who fills the change log: the writers kept, the largest first. */const CHANGES_BY_MOST = 30;const PLAN = "storage_measure_plan";/** * The plan's shape. A plan of shape 2 (every figure but the pace) is taken on in place. A plan of an unknown shape, or * one whose parts figures changed (PLAN_V moved: every table is read again for them), is begun again. */const PLAN_V = 3;/** * Each figure's own shape, beside the parts: a figure whose shape moved is summed again from nothing, over the ranges * the plan has already passed (`redo`), and every other figure already summed is kept. A deploy or a restart carries * the plan on where it was (it lives in meta). */export const FIGURES_V: Record<Figure, number> = { tables: 1, changes: 1, dangling: 1 };type Figure = "tables" | "changes" | "dangling";/** The table each figure is summed over, a range at a time beside the parts. */const FIGURE_JOB: Record<Figure, string> = { tables: "rows", changes: "change", dangling: "links" };const DONE = "storage_measure";export interface TableFigure {  table: string;  rows: number;  tombstones: number;  bytes: number;  /** The oldest and newest live row's `created_at` (null: none live, or measured before these were). */  oldest?: string | null;  newest?: string | null;}/** One link column's links whose target row is gone or deleted. */export interface Dangling {  table: string;  column: string;  /** The table the column links to. */  target: string;  count: number;}/** A single-valued link column and the table it links to: what `dangling` checks. */export type LinkTarget = [table: string, column: string, target: string];export interface ChangesBy {  via: string | null;  table: string;  kind: string;  entries: number;  chars: number;}/** A whole measure, as storage_summary says it. */export interface Measure {  /** When the measure began (its figures are of the object from then until `done_at`). */  at: string;  done_at: string;  tables: TableFigure[];  parts: StorageParts;  changes_by: ChangesBy[];  /** Links pointing at nothing, the most first (absent on a measure made before it was counted). */  dangling?: Dangling[];}interface Plan {  v?: number;  /** Each figure's shape it was summed by (absent: shape 2's, FIGURES_V of then). */  vs?: Record<Figure, number>;  /** The units one row of the table measured now costs, from its last range (absent: not known yet). */  pace?: number;  /** Figures summed again over ranges the plan had passed: the figure, how far it got, and where it stops (null: the table's end). */  redo?: { figure: Figure; after: number; upto: number | null }[];  at: string;  /** The job measured now, by its place, and where its last range ended (null: not begun). */  job: number;  after: RangeEnd | null;  /** Each job's figures so far, by name. */  figures: Record<string, number[]>;  /** live, dead, bytes, oldest live, newest live. */  tables: Record<string, [number, number, number, string | null, string | null]>;  changes: Record<string, ChangesBy>;  dangling: Record<string, Dangling>;}interface Host {  sql: SqlStorage;  meta(key: string): string | null;  setMeta(key: string, value: string | null): void;  /** The link columns `dangling` checks (none: nothing counted). */  links?: LinkTarget[];}/** The last whole measure, or null when none was made. */export function lastMeasure(host: Host): Measure | null {  const raw = host.meta(DONE);  if (!raw) return null;  try {    return JSON.parse(raw) as Measure;  } catch {    return null;  }}/** How far a measure under way has got: the share of the store's tables done, or null when none is under way. */export function measuring(host: Host): { since: string; done: number } | null {  const plan = planOf(host);  if (!plan) return null;  const jobs = partsPlan(host.sql).length || 1;  return { since: plan.at, done: Math.round((plan.job / jobs) * 100) / 100 };}/** JOBS OUT C3: whether measureStep would do anything now (a measure under way, or the last one MEASURE_EVERY_MS old). Meta only. */export function measureDue(host: Host, now: Date): boolean {  if (planOf(host)) return true;  const last = lastMeasure(host);  return !(last && now.getTime() - Date.parse(last.done_at ?? last.at) < MEASURE_EVERY_MS);}function planOf(host: Host): Plan | null {  const raw = host.meta(PLAN);  if (!raw) return null;  let plan: Plan;  try {    plan = JSON.parse(raw) as Plan;  } catch {    return null;  }  // Shape 2 is shape 3 with no pace and the figures of then: taken on as it stands.  if (plan.v === 2) plan = { ...plan, v: PLAN_V, vs: { tables: 1, changes: 1, dangling: 1 } };  if (plan.v !== PLAN_V) return null;  const vs = plan.vs ?? { tables: 1, changes: 1, dangling: 1 };  const jobs = partsPlan(host.sql).map((j) => j.name);  for (const figure of Object.keys(FIGURES_V) as Figure[]) {    if (vs[figure] === FIGURES_V[figure]) continue;    // This figure is summed again from nothing; the ranges already passed are read again for it alone.    if (figure === "tables") plan.tables = {};    if (figure === "changes") plan.changes = {};    if (figure === "dangling") plan.dangling = {};    const at = jobs.indexOf(FIGURE_JOB[figure]);    plan.redo = (plan.redo ?? []).filter((r) => r.figure !== figure);    if (at >= 0 && at < plan.job) plan.redo.push({ figure, after: 0, upto: null });    else if (at === plan.job && typeof plan.after === "number") plan.redo.push({ figure, after: 0, upto: plan.after });    vs[figure] = FIGURES_V[figure];  }  plan.vs = vs;  return plan;}const freshPlan = (at: Date): Plan => ({ v: PLAN_V, vs: { ...FIGURES_V }, at: at.toISOString(), job: 0, after: null, figures: {}, tables: {}, changes: {}, dangling: {} });/** Every figure worked out now, in one pass of each table: a small object's. */export function measureNow(sql: SqlStorage, at: Date, links: LinkTarget[] = []): Measure {  const plan = freshPlan(at);  for (const job of partsPlan(sql)) {    plan.figures[job.name] = measureRange(sql, job).figures;    if (job.name === "rows") addTables(sql, plan, null);    if (job.name === "change") addChanges(sql, plan, null);    if (job.name === "links") addDangling(sql, plan, null, links);  }  return finish(sql, plan, at);}/** * One alarm's share of the measure: begins one when none is under way and the last finished more than * MEASURE_EVERY_MS ago (never while one is unfinished), then measures until it has done `work` units (WORK_A_STEP), * always at least one range. `most` caps a range's rows (a test's many small steps). Answers whether more is left. */export function measureStep(host: Host, now: Date, work = WORK_A_STEP, most: number | null = null): boolean {  let plan = planOf(host);  if (!plan) {    const last = lastMeasure(host);    if (last && now.getTime() - Date.parse(last.done_at ?? last.at) < MEASURE_EVERY_MS) return false;    plan = freshPlan(now);  }  const jobs = partsPlan(host.sql);  let spent = 0;  const sized = (pace: number | undefined): number => {    const rows = pace ? Math.max(1, Math.min(1_000_000_000, Math.floor((work - spent) / pace))) : PROBE_ROWS;    return most === null ? rows : Math.max(1, Math.min(rows, most));  };  // A figure summed again over ranges already passed comes first.  while (plan.redo?.length && spent < work) {    const r = plan.redo[0]!;    const table = FIGURE_JOB[r.figure];    const pace = plan.pace ?? 20;    const end = host.sql      .exec<{ last: number | null; n: number }>(`SELECT MAX(rowid) AS last, COUNT(*) AS n FROM (SELECT rowid FROM ${table} WHERE rowid > ?${r.upto === null ? "" : " AND rowid <= ?"} ORDER BY rowid LIMIT ?)`, r.after, ...(r.upto === null ? [] : [r.upto]), sized(pace))      .one();    if (end.last === null) {      plan.redo.shift();      continue;    }    const range = { after: r.after, last: Number(end.last) };    if (r.figure === "tables") addTables(host.sql, plan, range);    if (r.figure === "changes") addChanges(host.sql, plan, range);    if (r.figure === "dangling") addDangling(host.sql, plan, range, host.links ?? []);    r.after = range.last;    spent += Number(end.n) * pace;  }  do {    if (plan.job >= jobs.length) break;    const job = jobs[plan.job]!;    const { figures, last } = measureRange(host.sql, job, plan.after, sized(plan.pace));    const held = plan.figures[job.name] ?? job.measures.map(() => 0);    plan.figures[job.name] = held.map((v, i) => v + (figures[i] ?? 0));    // `rows` and `change` are rowid tables: their tables' and writers' figures over the same range.    if (typeof last === "number") {      const range = { after: typeof plan.after === "number" ? plan.after : 0, last };      if (job.name === "rows") addTables(host.sql, plan, range);      if (job.name === "change") addChanges(host.sql, plan, range);      if (job.name === "links") addDangling(host.sql, plan, range, host.links ?? []);    }    // The work this range did: a unit a row, and one a BYTES_A_UNIT bytes it holds (figures 0 and 1: entries, bytes).    const entries = Number(figures[0] ?? 0);    const units = entries + Number(figures[1] ?? 0) / BYTES_A_UNIT;    spent += units;    if (entries > 0) plan.pace = Math.max(1, units / entries);    if (last === null) {      plan.job += 1;      plan.after = null;      delete plan.pace;      spent += JOB_UNITS;    } else plan.after = last;  } while (spent < work);  if (plan.job < jobs.length || plan.redo?.length) {    host.setMeta(PLAN, JSON.stringify(plan));    return true;  }  host.setMeta(DONE, JSON.stringify(finish(host.sql, plan, now, jobs)));  host.setMeta(PLAN, null);  return false;}/** The store's tables' rows, tombstones, bytes and oldest and newest live row over one range of `rows` (null: all of it). */function addTables(sql: SqlStorage, plan: Plan, range: { after: number; last: number } | null): void {  const where = range ? ` WHERE rowid > ${Math.floor(range.after)} AND rowid <= ${Math.floor(range.last)}` : "";  for (const r of sql.exec<{ table_id: string; live: number; dead: number; bytes: number; oldest: string | null; newest: string | null }>(    `SELECT table_id, SUM(deleted = 0) AS live, SUM(deleted = 1) AS dead, SUM(LENGTH(CAST(data AS BLOB)) + LENGTH(id) + 64) AS bytes, MIN(CASE WHEN deleted = 0 THEN created_at END) AS oldest, MAX(CASE WHEN deleted = 0 THEN created_at END) AS newest FROM rows${where} GROUP BY table_id`,  )) {    const held = plan.tables[r.table_id] ?? [0, 0, 0, null, null];    const least = (a: string | null, b: string | null): string | null => (a === null ? b : b === null ? a : a < b ? a : b);    const most = (a: string | null, b: string | null): string | null => (a === null ? b : b === null ? a : a > b ? a : b);    plan.tables[r.table_id] = [held[0] + Number(r.live), held[1] + Number(r.dead), held[2] + Number(r.bytes), least(held[3], r.oldest ?? null), most(held[4], r.newest ?? null)];  }}/** * The links over one range of `links` (null: all of it) whose target row is gone or deleted, by link column. Each link * is read once along the range (CROSS JOIN keeps `links` outer) and its target looked up by the rows' key. */function addDangling(sql: SqlStorage, plan: Plan, range: { after: number; last: number } | null, links: LinkTarget[]): void {  if (!links.length) return;  const where = range ? `l.rowid > ${Math.floor(range.after)} AND l.rowid <= ${Math.floor(range.last)} AND ` : "";  for (const r of sql.exec<{ t: string; c: string; to_: string; n: number }>(    `WITH lt(t, c, to_) AS MATERIALIZED (SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]'), json_extract(value, '$[2]') FROM json_each(?))     SELECT l.table_id AS t, l.column AS c, lt.to_ AS to_, COUNT(*) AS n     FROM links l CROSS JOIN lt ON lt.t = l.table_id AND lt.c = l.column     LEFT JOIN rows r ON r.table_id = lt.to_ AND r.id = l.target     WHERE ${where}(r.id IS NULL OR r.deleted = 1)     GROUP BY l.table_id, l.column, lt.to_`,    JSON.stringify(links),  )) {    const key = JSON.stringify([r.t, r.c]);    const held = plan.dangling[key] ?? { table: r.t, column: r.c, target: r.to_, count: 0 };    held.count += Number(r.n);    plan.dangling[key] = held;  }}/** Who wrote the change log over one range of it (null: all of it). */function addChanges(sql: SqlStorage, plan: Plan, range: { after: number; last: number } | null): void {  const where = range ? ` WHERE id > ${Math.floor(range.after)} AND id <= ${Math.floor(range.last)}` : "";  for (const r of sql.exec<{ via: string | null; table_id: string; kind: string; n: number; chars: number }>(    `SELECT via, table_id, kind, COUNT(*) AS n, SUM(coalesce(length(before), 0) + coalesce(length(after), 0)) AS chars FROM change${where} GROUP BY via, table_id, kind`,  )) {    const key = JSON.stringify([r.via, r.table_id, r.kind]);    const held = plan.changes[key] ?? { via: r.via, table: r.table_id, kind: r.kind, entries: 0, chars: 0 };    held.entries += Number(r.n);    held.chars += Number(r.chars);    plan.changes[key] = held;  }}function finish(sql: SqlStorage, plan: Plan, now: Date, jobs: PartsJob[] = partsPlan(sql)): Measure {  const parts: StoragePart[] = jobs.flatMap((job) => partsOf(job, plan.figures[job.name] ?? []));  const tables = Object.entries(plan.tables)    .map(([table, [rows, tombstones, bytes, oldest, newest]]) => ({ table, rows, tombstones, bytes, oldest, newest }))    .sort((a, b) => b.bytes - a.bytes || a.table.localeCompare(b.table));  const changes_by = Object.values(plan.changes)    .sort((a, b) => b.chars - a.chars || b.entries - a.entries)    .slice(0, CHANGES_BY_MOST);  const dangling = Object.values(plan.dangling).sort((a, b) => b.count - a.count || a.table.localeCompare(b.table) || a.column.localeCompare(b.column));  return { at: plan.at, done_at: now.toISOString(), tables, parts: partsTotal(sql.databaseSize, parts), changes_by, dangling };}