From b37a350e42a0070c7ae8ea5bc86b965018e130bd Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Sat, 28 Nov 2026 12:14:16 -0800 Subject: [PATCH 1/6] Keep image and Storybook hashes as 32 bytes, and make every table STRICT Co-Authored-By: Claude Opus 5.5 --- docs/specs/renders.md | 1 + docs/specs/renders.rationale.md | 2 ++ docs/specs/store.md | 1 + store/src/core/built-storybooks.ts | 6 +++--- store/src/core/hash-keys.ts | 10 ++++----- store/src/core/render-batches.ts | 28 ++++++++++++++------------ store/src/core/store.ts | 4 ++-- store/test/built-storybooks.test.ts | 2 +- store/test/contract/sql-contract.ts | 8 ++++---- store/test/render-batches.real.test.ts | 2 +- store/test/render-batches.test.ts | 2 +- 11 files changed, 36 insertions(+), 30 deletions(-) diff --git a/docs/specs/renders.md b/docs/specs/renders.md index ca0ca29..aa5aafe 100644 --- a/docs/specs/renders.md +++ b/docs/specs/renders.md @@ -142,6 +142,7 @@ commit_parents(commit_key → commits.key, parent_key → commits.key) PK (comm INDEX commit_parents_by_parent(parent_key, commit_key) ``` +- **Must declare every table `STRICT`**, so a value of the wrong type is refused rather than kept (rationale). - **Must leave out the CLI's local table** (`docs/specs/cli.md` → Recording only if necessary): it's in a local `store.db`, not this schema, and D1 doesn't have it. - **Must only add missing tables and indexes during setup**, in one request. A store holding only images can be opened. A store with the old text `commits.sha` column must fail setup and be recreated (rationale). - **Must store a Git commit SHA as its 20 SHA-1 bytes or 32 SHA-256 bytes, and exchange it as full lowercase hex.** (rationale) diff --git a/docs/specs/renders.rationale.md b/docs/specs/renders.rationale.md index 7a8a3f6..da4dac9 100644 --- a/docs/specs/renders.rationale.md +++ b/docs/specs/renders.rationale.md @@ -90,6 +90,8 @@ The commit SHA index names the binary column explicitly. Setup on an older `comm **Composite primary keys.** A render page walks the stories of one batch, and a history lookup walks the decisions of one environment and commit. `WITHOUT ROWID` stores the rows in those primary-key trees, so a range scan can retrieve the row contents directly. The reverse index on `commit_parents` serves a different walk, from a commit to the descendants whose statuses may need updating. +**Strict tables.** SQLite otherwise keeps a value of any type in any column, so a hex SHA bound where bytes were meant, or a time sent as text, would be stored and then match nothing. `STRICT` can't be added to a table that exists, only by rebuilding it, so every table has it from the start. It ran in the workerd tests, on D1's engine. + **Foreign keys, before there's data.** Nothing in the store deletes yet, and every write already goes through a path that writes parents first, so these catch only bugs for now. What they're for is retention: once a batch can be deleted, they're what stop one going while something points at it. SQLite can't add a foreign key to an existing table, so waiting would mean rebuilding tables in a migration, where today it's an edit to their `CREATE` statements. Inserting 10,000 renders took 9 ms with checks and 8 ms without, in one local run. They haven't run on real D1, only on its engine in the Worker tests. ## Requests diff --git a/docs/specs/store.md b/docs/specs/store.md index 2284a3e..181058c 100644 --- a/docs/specs/store.md +++ b/docs/specs/store.md @@ -42,6 +42,7 @@ Source of truth: `store/src/core/hash-keys.ts` and `store/src/core/store.ts`. - **Never give an image the key 0**, which `decisions.image_key` holds for a story being gone. - **Must return the existing key when the same image is inserted again**, including an image holding a negative key. - **Must look up the hash by integer primary key and confirm the full hash.** Only a zero prefix or a prefix held by another hash needs a search among negative keys. **Never maintain a separate index on the full hash** (rationale). +- **Must keep the full hash as its 32 bytes, in `images(key, hash)` and `built_storybooks(key, hash)`, and take and return it as lowercase hex**, as a commit's SHA is (`docs/specs/renders.md` → Schema). - **Never reuse or reassign an image key within a store.** The store has no delete. The next negative key derives from the lowest key present, so a delete must not let that key be reused. - **Must insert each image in a single SQL statement, with no read-then-write across statements**, so concurrent inserts of the same or colliding images leave one key per image, without relying on batch atomicity. diff --git a/store/src/core/built-storybooks.ts b/store/src/core/built-storybooks.ts index 3275af6..321b6e7 100644 --- a/store/src/core/built-storybooks.ts +++ b/store/src/core/built-storybooks.ts @@ -11,8 +11,8 @@ export const CREATE_BUILT_STORYBOOK_TABLES: readonly string[] = [ // A row says every file is kept, since it's written last. Its key works as an image's does. `CREATE TABLE IF NOT EXISTS built_storybooks ( key INTEGER PRIMARY KEY, - hash TEXT NOT NULL -)`, + hash BLOB NOT NULL CHECK (length(hash) = 32) +) STRICT`, ]; @@ -139,7 +139,7 @@ WHERE render_batches.id = ?3 AND found.key IS NOT NULL RETURNING id`, /** The kept built Storybook that rendered a batch, if there is one. */ async storybookOfBatch(batchId: string): Promise { const [row] = await this.#sql.run({ - sql: "SELECT s.hash FROM render_batches r JOIN built_storybooks s ON s.key = r.storybook_key WHERE r.id = ?1", + sql: "SELECT lower(hex(s.hash)) AS hash FROM render_batches r JOIN built_storybooks s ON s.key = r.storybook_key WHERE r.id = ?1", params: [batchId], idempotent: true, }); diff --git a/store/src/core/hash-keys.ts b/store/src/core/hash-keys.ts index 4b09f93..b98f426 100644 --- a/store/src/core/hash-keys.ts +++ b/store/src/core/hash-keys.ts @@ -11,9 +11,9 @@ type HashTable = "images" | "built_storybooks"; // can have a matching negative row. SQLite evaluates CASE lazily, so ordinary hits and misses // each cost one primary-key probe. export function resolvedHashKey(table: HashTable, hash: string, prefix: string): string { - return `CASE WHEN candidate.hash = ${hash} THEN candidate.key + return `CASE WHEN candidate.hash = unhex(${hash}) THEN candidate.key WHEN candidate.key IS NOT NULL OR ${prefix} = 0 THEN - (SELECT collision.key FROM ${table} collision WHERE collision.key < 0 AND collision.hash = ${hash}) + (SELECT collision.key FROM ${table} collision WHERE collision.key < 0 AND collision.hash = unhex(${hash})) END`; } @@ -32,10 +32,10 @@ export function insertHashKeyStatement(table: HashTable, hash: string): SqlState return { sql: `INSERT INTO ${table}(key, hash) VALUES ( CASE WHEN ${prefix} > 0 AND NOT EXISTS ( - SELECT 1 FROM ${table} WHERE key = ?1 AND hash <> ?2 + SELECT 1 FROM ${table} WHERE key = ?1 AND hash <> unhex(?2) ) THEN ${prefix} - ELSE COALESCE((SELECT key FROM ${table} WHERE key < 0 AND hash = ?2), - (SELECT COALESCE(MIN(key), 0) - 1 FROM ${table} WHERE key < 0)) END, ?2) + ELSE COALESCE((SELECT key FROM ${table} WHERE key < 0 AND hash = unhex(?2)), + (SELECT COALESCE(MIN(key), 0) - 1 FROM ${table} WHERE key < 0)) END, unhex(?2)) ON CONFLICT(key) DO UPDATE SET hash = excluded.hash RETURNING key`, params: [truncateHexHash(hash), hash], diff --git a/store/src/core/render-batches.ts b/store/src/core/render-batches.ts index 903a2de..2d4917a 100644 --- a/store/src/core/render-batches.ts +++ b/store/src/core/render-batches.ts @@ -10,11 +10,11 @@ import type { Sql, SqlRow, SqlStatement } from "./sql.ts"; * module takes or returns names each by its own text. See `docs/specs/renders.md` -> Schema. */ export const CREATE_BATCH_TABLES: readonly string[] = [ - "CREATE TABLE IF NOT EXISTS environments (key INTEGER PRIMARY KEY, id TEXT NOT NULL UNIQUE)", - "CREATE TABLE IF NOT EXISTS stories (key INTEGER PRIMARY KEY, id TEXT NOT NULL UNIQUE)", + "CREATE TABLE IF NOT EXISTS environments (key INTEGER PRIMARY KEY, id TEXT NOT NULL UNIQUE) STRICT", + "CREATE TABLE IF NOT EXISTS stories (key INTEGER PRIMARY KEY, id TEXT NOT NULL UNIQUE) STRICT", "CREATE TABLE IF NOT EXISTS commits (key INTEGER PRIMARY KEY, sha_bytes BLOB NOT NULL CHECK (length(sha_bytes) IN (20, 32))) STRICT", "CREATE UNIQUE INDEX IF NOT EXISTS commits_by_sha ON commits(sha_bytes)", - "CREATE TABLE IF NOT EXISTS actors (key INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE)", + "CREATE TABLE IF NOT EXISTS actors (key INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE) STRICT", `CREATE TABLE IF NOT EXISTS render_batches ( key INTEGER PRIMARY KEY, id TEXT NOT NULL UNIQUE, @@ -31,7 +31,7 @@ export const CREATE_BATCH_TABLES: readonly string[] = [ viewport_height INTEGER NOT NULL, branch TEXT, storybook_key INTEGER REFERENCES built_storybooks(key) -)`, +) STRICT`, "CREATE INDEX IF NOT EXISTS batches_by_commit ON render_batches(commit_key, environment_key, started_at)", "CREATE INDEX IF NOT EXISTS batches_by_branch ON render_batches(branch, environment_key, started_at)", `CREATE TABLE IF NOT EXISTS renders ( @@ -44,7 +44,7 @@ export const CREATE_BATCH_TABLES: readonly string[] = [ PRIMARY KEY (batch_key, story_key), CHECK (image_key IS NOT NULL OR failure IS NOT NULL), CHECK ((viewport_width IS NULL) = (viewport_height IS NULL)) -) WITHOUT ROWID`, +) STRICT, WITHOUT ROWID`, // By commit first, since what history reaches is read a commit at a time. An image key of 0, which no // image is ever given, is a decision on a story being gone, so that column can't be a foreign key. Its // batch may never have come here, so that stays an ID. @@ -58,14 +58,14 @@ export const CREATE_BATCH_TABLES: readonly string[] = [ actor_key INTEGER NOT NULL REFERENCES actors(key), batch_uuid BLOB NOT NULL CHECK (typeof(batch_uuid) = 'blob' AND length(batch_uuid) = 16), PRIMARY KEY (environment_key, commit_key, story_key, image_key) -) WITHOUT ROWID`, +) STRICT, WITHOUT ROWID`, "CREATE INDEX IF NOT EXISTS decisions_by_image ON decisions(environment_key, story_key, image_key)", // Which commits came before which, for a server with no Git to ask. Only ever added to, by whoever pushes. `CREATE TABLE IF NOT EXISTS commit_parents ( commit_key INTEGER NOT NULL REFERENCES commits(key), parent_key INTEGER NOT NULL REFERENCES commits(key), PRIMARY KEY (commit_key, parent_key) -) WITHOUT ROWID`, +) STRICT, WITHOUT ROWID`, // The other way, from a commit to those whose history holds it. "CREATE INDEX IF NOT EXISTS commit_parents_by_parent ON commit_parents(parent_key, commit_key)", ]; @@ -101,6 +101,8 @@ const BATCH_COLUMNS = `id, (SELECT lower(hex(sha_bytes)) FROM commits WHERE key const SELECT_BATCH = `SELECT ${BATCH_COLUMNS} FROM render_batches WHERE id = ?1`; const BATCH_KEY = "(SELECT key FROM render_batches WHERE id = ?1)"; +// A hash kept as bytes, as the lowercase hex that leaves the store. `hex` makes a missing one '', so it's NULL again. +const hexOrNull = (column: string) => `NULLIF(lower(hex(${column})), '')`; const commitKey = (sha: string) => `(SELECT key FROM commits WHERE sha_bytes = unhex(${sha}))`; const environmentKey = (id: string) => `(SELECT key FROM environments WHERE id = ${id})`; @@ -125,8 +127,8 @@ const DECISION_WORD = "CASE d.rejected WHEN 1 THEN 'rejected' WHEN 0 THEN 'appro /** A comparison's statements, of the batch named by ?1 against the one whose key `baselineKey` reads, with any condition `and` adds. */ const againstBatch = (baselineKey: string, and = "") => ({ // `gs` joins before the images so that a row left out never reads them. - comparedPage: `SELECT rs.story_key, s.id AS story, i.hash AS image_hash, rs.failure, - gi.hash AS golden_hash, ${DECISION_WORD} AS decision, a.name AS actor, d.decided_at + comparedPage: `SELECT rs.story_key, s.id AS story, ${hexOrNull("i.hash")} AS image_hash, rs.failure, + ${hexOrNull("gi.hash")} AS golden_hash, ${DECISION_WORD} AS decision, a.name AS actor, d.decided_at FROM render_batches r CROSS JOIN renders rs ON rs.batch_key = r.key LEFT JOIN renders gs ON gs.batch_key = ${baselineKey} AND gs.story_key = rs.story_key @@ -139,7 +141,7 @@ WHERE r.id = ?1${and} AND rs.story_key > CAST(?3 AS INTEGER) OR rs.image_key IS NOT gs.image_key) ORDER BY rs.story_key LIMIT CAST(?4 AS INTEGER)`, - removedPage: `SELECT gs.story_key, s.id AS story, gi.hash AS golden_hash + removedPage: `SELECT gs.story_key, s.id AS story, ${hexOrNull("gi.hash")} AS golden_hash FROM renders gs JOIN images gi ON gi.key = gs.image_key JOIN stories s ON s.key = gs.story_key @@ -177,14 +179,14 @@ const BATCH_PAGE_TAIL = `WHERE r.id = ?1 AND rs.story_key > CAST(?2 AS INTEGER) ORDER BY rs.story_key LIMIT CAST(?3 AS INTEGER)`; -const READ_BATCH_PAGE = `SELECT rs.story_key, s.id AS story, i.hash AS image_hash, rs.failure, rs.viewport_width, rs.viewport_height +const READ_BATCH_PAGE = `SELECT rs.story_key, s.id AS story, ${hexOrNull("i.hash")} AS image_hash, rs.failure, rs.viewport_width, rs.viewport_height FROM render_batches r CROSS JOIN renders rs ON rs.batch_key = r.key LEFT JOIN images i ON i.key = rs.image_key LEFT JOIN stories s ON s.key = rs.story_key ${BATCH_PAGE_TAIL}`; -const READ_RENDERS_PAGE = `SELECT rs.story_key, s.id AS story, i.hash AS image_hash, rs.failure +const READ_RENDERS_PAGE = `SELECT rs.story_key, s.id AS story, ${hexOrNull("i.hash")} AS image_hash, rs.failure FROM render_batches r CROSS JOIN renders rs ON rs.batch_key = r.key LEFT JOIN images i ON i.key = rs.image_key @@ -193,7 +195,7 @@ ${BATCH_PAGE_TAIL}`; // A commit at a time, each of which is a range of the primary key. A commit this store has never heard of finds nothing. // What `toPlacedDecision` reads, of a row of `d` and its commit `c`. -const PLACED_DECISION = `SELECT s.id AS story, i.hash AS image_hash, ${DECISION_WORD} AS decision, a.name AS actor, d.decided_at, lower(hex(d.batch_uuid)) AS batch_hex, lower(hex(c.sha_bytes)) AS git_sha`; +const PLACED_DECISION = `SELECT s.id AS story, ${hexOrNull("i.hash")} AS image_hash, ${DECISION_WORD} AS decision, a.name AS actor, d.decided_at, lower(hex(d.batch_uuid)) AS batch_hex, lower(hex(c.sha_bytes)) AS git_sha`; const NAMES_OF_DECISION = `CROSS JOIN actors a ON a.key = d.actor_key CROSS JOIN stories s ON s.key = d.story_key LEFT JOIN images i ON i.key = d.image_key`; diff --git a/store/src/core/store.ts b/store/src/core/store.ts index ab7316c..ed1a8e3 100644 --- a/store/src/core/store.ts +++ b/store/src/core/store.ts @@ -16,8 +16,8 @@ import type { Sql, SqlStatement } from "./sql.ts"; const CREATE_IMAGES_TABLE = `CREATE TABLE IF NOT EXISTS images ( key INTEGER PRIMARY KEY, - hash TEXT NOT NULL -)`; + hash BLOB NOT NULL CHECK (length(hash) = 32) +) STRICT`; // Bound each group of blob writes and SQL inserts sent in one request. const IMAGES_PER_GROUP = 100; diff --git a/store/test/built-storybooks.test.ts b/store/test/built-storybooks.test.ts index c9d31f5..1aa28f3 100644 --- a/store/test/built-storybooks.test.ts +++ b/store/test/built-storybooks.test.ts @@ -110,7 +110,7 @@ describe("BuiltStorybooks", () => { }); it("gives a built Storybook its key as an image's, and the next negative one on a collision", async () => { - const keyOf = async (hash: string) => (await temp.sql.run({ sql: "SELECT key FROM built_storybooks WHERE hash = ?1", params: [hash] }))[0]?.key; + const keyOf = async (hash: string) => (await temp.sql.run({ sql: "SELECT key FROM built_storybooks WHERE hash = unhex(?1)", params: [hash] }))[0]?.key; const first = "0123456789abcd" + "0".repeat(50); const colliding = "0123456789abcd" + "1".repeat(50); await keep(first, { "index.html": "one" }); diff --git a/store/test/contract/sql-contract.ts b/store/test/contract/sql-contract.ts index 26a74d1..80ba0c9 100644 --- a/store/test/contract/sql-contract.ts +++ b/store/test/contract/sql-contract.ts @@ -43,7 +43,7 @@ export function describeSqlContract(name: string, factory: SqlAdapterFactory): v const insert = async (hash: string) => { return insertedKey(await sql.run(imageInsertStatement(hash))); }; - const allRows = () => sql.run({ sql: "SELECT key, hash FROM images ORDER BY key DESC" }); + const allRows = () => sql.run({ sql: "SELECT key, lower(hex(hash)) AS hash FROM images ORDER BY key DESC" }); const insertConcurrently = (workloads: string[][]) => database.insertConcurrently(workloads, mode); @@ -167,10 +167,10 @@ export function describeSqlContract(name: string, factory: SqlAdapterFactory): v expect(await insert(hashOf(2, MAX_KEY))).toBe(MAX_KEY); }); - it("stores the key as an integer and the hash as text", async () => { + it("stores the key as an integer and the hash as its 32 bytes", async () => { await insert(hashOf(1, 7)); - const rows = await sql.run({ sql: "SELECT typeof(key) AS k, typeof(hash) AS h FROM images" }); - expect(rows).toEqual([{ k: "integer", h: "text" }]); + const rows = await sql.run({ sql: "SELECT typeof(key) AS k, typeof(hash) AS h, length(hash) AS n FROM images" }); + expect(rows).toEqual([{ k: "integer", h: "blob", n: 32 }]); }); it("assigns monotonic negative keys from -1 when the value is claimed", async () => { diff --git a/store/test/render-batches.real.test.ts b/store/test/render-batches.real.test.ts index be05c40..6f0b0cf 100644 --- a/store/test/render-batches.real.test.ts +++ b/store/test/render-batches.real.test.ts @@ -75,7 +75,7 @@ describe.skipIf(!ENABLED)("real D1 renders (opt-in: pnpm test:d1:render-batches) const group = hashes.slice(i, i + 49); imageStatements.push({ sql: `INSERT INTO images(key, hash) VALUES ${group - .map((_, j) => `(CAST(?${2 * j + 1} AS INTEGER), ?${2 * j + 2})`) + .map((_, j) => `(CAST(?${2 * j + 1} AS INTEGER), unhex(?${2 * j + 2}))`) .join(", ")}`, params: group.flatMap((hash, j) => [5_000_000 + i + j, hash]), }); diff --git a/store/test/render-batches.test.ts b/store/test/render-batches.test.ts index c6e52a6..31fffa8 100644 --- a/store/test/render-batches.test.ts +++ b/store/test/render-batches.test.ts @@ -602,7 +602,7 @@ describe("RenderBatches", () => { const seedMany = (start: number, count: number) => { const db = new DatabaseSync(temp.path); try { - const insert = db.prepare("INSERT OR IGNORE INTO images(key, hash) VALUES (?, ?)"); + const insert = db.prepare("INSERT OR IGNORE INTO images(key, hash) VALUES (?, unhex(?))"); db.exec("BEGIN"); for (let i = start; i < start + count; i++) insert.run(i, hashOf(i)); db.exec("COMMIT"); From 67fdd596f344f0fda7c3d95f262fab65837dd1b5 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Sat, 28 Nov 2026 12:16:06 -0800 Subject: [PATCH 2/6] Keep a batch's ID, and the one it reused, as 16 bytes Co-Authored-By: Claude Opus 5.5 --- docs/specs/renders.md | 3 +- docs/specs/renders.rationale.md | 2 + store/src/core/built-storybooks.ts | 4 +- store/src/core/render-batches.ts | 43 ++++++++++--------- .../test/contract/render-batches-contract.ts | 12 ++++++ store/test/render-batches.test.ts | 2 +- 6 files changed, 41 insertions(+), 25 deletions(-) diff --git a/docs/specs/renders.md b/docs/specs/renders.md index aa5aafe..6d74c56 100644 --- a/docs/specs/renders.md +++ b/docs/specs/renders.md @@ -132,7 +132,7 @@ stories(key PK, id UNIQUE) commits(key PK, sha_bytes BLOB) UNIQUE INDEX commits_by_sha(sha_bytes) actors(key PK, name UNIQUE) -render_batches(key PK, id UNIQUE, commit_key → commits.key, environment_key → environments.key, started_at, finished_at, failed_count, dirty, story_filter, reused_from_batch, scale, viewport_width, viewport_height, branch, storybook_key → built_storybooks.key) +render_batches(key PK, id BLOB UNIQUE, commit_key → commits.key, environment_key → environments.key, started_at, finished_at, failed_count, dirty, story_filter, reused_from_batch BLOB, scale, viewport_width, viewport_height, branch, storybook_key → built_storybooks.key) INDEX batches_by_commit(commit_key, environment_key, started_at) INDEX batches_by_branch(branch, environment_key, started_at) renders(batch_key → render_batches.key, story_key → stories.key, image_key → images.key, failure, viewport_width, viewport_height) PK (batch_key, story_key) WITHOUT ROWID @@ -146,6 +146,7 @@ commit_parents(commit_key → commits.key, parent_key → commits.key) PK (comm - **Must leave out the CLI's local table** (`docs/specs/cli.md` → Recording only if necessary): it's in a local `store.db`, not this schema, and D1 doesn't have it. - **Must only add missing tables and indexes during setup**, in one request. A store holding only images can be opened. A store with the old text `commits.sha` column must fail setup and be recreated (rationale). - **Must store a Git commit SHA as its 20 SHA-1 bytes or 32 SHA-256 bytes, and exchange it as full lowercase hex.** (rationale) +- **Must store a batch's ID, and the one it reused, as 16 bytes, and exchange each as a lowercase, hyphenated UUID**, as a decision's batch is (rationale). - **Must declare a foreign key wherever a row's parent is always written first and held here**, as `→` shows above, so a store refuses an orphan instead of holding one (rationale). - **Never declare one on `decisions.image_key`, `decisions.batch_uuid`, or `reused_from_batch`**, since a key of 0 is a removal, a decision may name a batch this store doesn't hold, and sync may move a batch without the one it was reused from. - **Must say in `render_batches.viewport_width` and `viewport_height` the window a batch's stories lay out in, in CSS pixels, and in those columns of `renders` only a story's own, if it differs**, both or neither, so a story with neither laid out in its batch's (`docs/specs/render.md` → A story's viewport). They only size a story running live, so a comparison never reads them (rationale). **A batch reusing another's images must hold the same sizes.** diff --git a/docs/specs/renders.rationale.md b/docs/specs/renders.rationale.md index da4dac9..55127ac 100644 --- a/docs/specs/renders.rationale.md +++ b/docs/specs/renders.rationale.md @@ -90,6 +90,8 @@ The commit SHA index names the binary column explicitly. Setup on an older `comm **Composite primary keys.** A render page walks the stories of one batch, and a history lookup walks the decisions of one environment and commit. `WITHOUT ROWID` stores the rows in those primary-key trees, so a range scan can retrieve the row contents directly. The reverse index on `commit_parents` serves a different walk, from a commit to the descendants whose statuses may need updating. +**Batch IDs as bytes.** A decision's batch was measured at 15.32 MB as text and 11.20 MB as bytes ([Size of the batch ID](#decisions)). A batch's own ID is in `render_batches` and again in its unique index, so it's held the same way, and one ID has one form wherever the store keeps it. + **Strict tables.** SQLite otherwise keeps a value of any type in any column, so a hex SHA bound where bytes were meant, or a time sent as text, would be stored and then match nothing. `STRICT` can't be added to a table that exists, only by rebuilding it, so every table has it from the start. It ran in the workerd tests, on D1's engine. **Foreign keys, before there's data.** Nothing in the store deletes yet, and every write already goes through a path that writes parents first, so these catch only bugs for now. What they're for is retention: once a batch can be deleted, they're what stop one going while something points at it. SQLite can't add a foreign key to an existing table, so waiting would mean rebuilding tables in a migration, where today it's an edit to their `CREATE` statements. Inserting 10,000 renders took 9 ms with checks and 8 ms without, in one local run. They haven't run on real D1, only on its engine in the Worker tests. diff --git a/store/src/core/built-storybooks.ts b/store/src/core/built-storybooks.ts index 321b6e7..35e21e6 100644 --- a/store/src/core/built-storybooks.ts +++ b/store/src/core/built-storybooks.ts @@ -129,7 +129,7 @@ export class BuiltStorybooks { const lookup = lookupHashKeyStatement("built_storybooks", build); const rows = await this.#sql.run({ sql: `UPDATE render_batches SET storybook_key = found.key FROM (${lookup.sql}) found -WHERE render_batches.id = ?3 AND found.key IS NOT NULL RETURNING id`, +WHERE render_batches.id = unhex(?3, '-') AND found.key IS NOT NULL RETURNING 1`, params: [...lookup.params, batchId], idempotent: true, }); @@ -139,7 +139,7 @@ WHERE render_batches.id = ?3 AND found.key IS NOT NULL RETURNING id`, /** The kept built Storybook that rendered a batch, if there is one. */ async storybookOfBatch(batchId: string): Promise { const [row] = await this.#sql.run({ - sql: "SELECT lower(hex(s.hash)) AS hash FROM render_batches r JOIN built_storybooks s ON s.key = r.storybook_key WHERE r.id = ?1", + sql: "SELECT lower(hex(s.hash)) AS hash FROM render_batches r JOIN built_storybooks s ON s.key = r.storybook_key WHERE r.id = unhex(?1, '-')", params: [batchId], idempotent: true, }); diff --git a/store/src/core/render-batches.ts b/store/src/core/render-batches.ts index 2d4917a..a165da9 100644 --- a/store/src/core/render-batches.ts +++ b/store/src/core/render-batches.ts @@ -17,7 +17,7 @@ export const CREATE_BATCH_TABLES: readonly string[] = [ "CREATE TABLE IF NOT EXISTS actors (key INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE) STRICT", `CREATE TABLE IF NOT EXISTS render_batches ( key INTEGER PRIMARY KEY, - id TEXT NOT NULL UNIQUE, + id BLOB NOT NULL UNIQUE CHECK (length(id) = 16), commit_key INTEGER NOT NULL REFERENCES commits(key), environment_key INTEGER NOT NULL REFERENCES environments(key), started_at INTEGER NOT NULL, @@ -25,7 +25,7 @@ export const CREATE_BATCH_TABLES: readonly string[] = [ failed_count INTEGER, dirty INTEGER NOT NULL CHECK (dirty IN (0, 1)), story_filter TEXT, - reused_from_batch TEXT, + reused_from_batch BLOB CHECK (length(reused_from_batch) = 16), scale REAL NOT NULL, viewport_width INTEGER NOT NULL, viewport_height INTEGER NOT NULL, @@ -93,23 +93,24 @@ export const isBatchId = (value: string) => BATCH_ID.test(value); // As `git rev-list` is asked for: see `docs/specs/renders.md` -> Scope: approvals-sync. const MAX_REACHED_COMMITS = 1_000; +// Bytes kept for a hash or an ID, as the lowercase hex that leaves the store. `hex` makes a missing one '', so it's NULL again. +const hexOrNull = (column: string) => `NULLIF(lower(hex(${column})), '')`; + // Subqueries rather than joins, since a `RETURNING` can't join. -const BATCH_COLUMNS = `id, (SELECT lower(hex(sha_bytes)) FROM commits WHERE key = commit_key) AS git_sha, +const BATCH_COLUMNS = `lower(hex(id)) AS id_hex, (SELECT lower(hex(sha_bytes)) FROM commits WHERE key = commit_key) AS git_sha, (SELECT id FROM environments WHERE key = environment_key) AS environment, - started_at, finished_at, failed_count, dirty, story_filter, reused_from_batch, scale, viewport_width, viewport_height, branch`; + started_at, finished_at, failed_count, dirty, story_filter, ${hexOrNull("reused_from_batch")} AS reused_hex, scale, viewport_width, viewport_height, branch`; -const SELECT_BATCH = `SELECT ${BATCH_COLUMNS} FROM render_batches WHERE id = ?1`; +const SELECT_BATCH = `SELECT ${BATCH_COLUMNS} FROM render_batches WHERE id = unhex(?1, '-')`; -const BATCH_KEY = "(SELECT key FROM render_batches WHERE id = ?1)"; -// A hash kept as bytes, as the lowercase hex that leaves the store. `hex` makes a missing one '', so it's NULL again. -const hexOrNull = (column: string) => `NULLIF(lower(hex(${column})), '')`; +const BATCH_KEY = "(SELECT key FROM render_batches WHERE id = unhex(?1, '-'))"; const commitKey = (sha: string) => `(SELECT key FROM commits WHERE sha_bytes = unhex(${sha}))`; const environmentKey = (id: string) => `(SELECT key FROM environments WHERE id = ${id})`; // The key of a finished batch named by ?2, only ever in the batch's own environment. const NAMED_BATCH_KEY = `(SELECT b.key FROM render_batches b - WHERE b.id = ?2 AND b.finished_at IS NOT NULL - AND b.environment_key = (SELECT environment_key FROM render_batches WHERE id = ?1))`; + WHERE b.id = unhex(?2, '-') AND b.finished_at IS NOT NULL + AND b.environment_key = (SELECT environment_key FROM render_batches WHERE id = unhex(?1, '-')))`; // A story and image can have a decision per commit. What reads one without history in hand wants the // newest, latest first, and at the same moment a rejection, then by commit so that one row wins. @@ -136,7 +137,7 @@ LEFT JOIN images i ON i.key = rs.image_key LEFT JOIN images gi ON gi.key = gs.image_key ${DECISION_ON_RENDER} LEFT JOIN stories s ON s.key = rs.story_key -WHERE r.id = ?1${and} AND rs.story_key > CAST(?3 AS INTEGER) +WHERE r.id = unhex(?1, '-')${and} AND rs.story_key > CAST(?3 AS INTEGER) AND (CAST(?5 AS INTEGER) = 1 OR rs.failure IS NOT NULL OR rs.image_key IS NOT gs.image_key) ORDER BY rs.story_key @@ -172,10 +173,10 @@ FROM ( FROM renders WHERE batch_key = ${BATCH_KEY} ) AS c -WHERE render_batches.id = ?1 AND c.total = CAST(?3 AS INTEGER) +WHERE render_batches.id = unhex(?1, '-') AND c.total = CAST(?3 AS INTEGER) RETURNING ${BATCH_COLUMNS}`; -const BATCH_PAGE_TAIL = `WHERE r.id = ?1 AND rs.story_key > CAST(?2 AS INTEGER) +const BATCH_PAGE_TAIL = `WHERE r.id = unhex(?1, '-') AND rs.story_key > CAST(?2 AS INTEGER) ORDER BY rs.story_key LIMIT CAST(?3 AS INTEGER)`; @@ -209,7 +210,7 @@ ${NAMES_OF_DECISION}`; // What a batch's commit reaches, walked by key, so that a long history's SHAs never leave the database. const REACH_OF_BATCH = `WITH RECURSIVE reach(key) AS ( - SELECT commit_key FROM render_batches WHERE id = ?1 + SELECT commit_key FROM render_batches WHERE id = unhex(?1, '-') UNION SELECT p.parent_key FROM reach CROSS JOIN commit_parents p ON p.commit_key = reach.key LIMIT ${MAX_REACHED_COMMITS} @@ -238,7 +239,7 @@ LIMIT CAST(?3 AS INTEGER)`; const DECISIONS_REACHED = `${REACH_OF_BATCH} ${PLACED_DECISION} FROM reach r -CROSS JOIN decisions d ON d.environment_key = (SELECT environment_key FROM render_batches WHERE id = ?1) AND d.commit_key = r.key +CROSS JOIN decisions d ON d.environment_key = (SELECT environment_key FROM render_batches WHERE id = unhex(?1, '-')) AND d.commit_key = r.key CROSS JOIN commits c ON c.key = d.commit_key ${NAMES_OF_DECISION}`; @@ -248,7 +249,7 @@ WHERE branch = ${branch} AND finished_at IS NOT NULL AND environment_key = ${env ORDER BY started_at DESC LIMIT 1`; const baseReached = (columns?: string) => - newestOfBranchWhere("?2", "(SELECT environment_key FROM render_batches WHERE id = ?1)", "(SELECT commit_key FROM render_batches WHERE id = ?1)", "SELECT key FROM reach", columns); + newestOfBranchWhere("?2", "(SELECT environment_key FROM render_batches WHERE id = unhex(?1, '-'))", "(SELECT commit_key FROM render_batches WHERE id = unhex(?1, '-'))", "SELECT key FROM reach", columns); const BASE_REACHED = `${REACH_OF_BATCH} ${baseReached()}`; @@ -295,7 +296,7 @@ const RECORD_RENDERS = `WITH ${jsonRows("?2", ["story", "image_hash", "image_pre INSERT INTO renders(batch_key, story_key, image_key, failure, viewport_width, viewport_height) SELECT r.key, s.key, ${resolvedHashKey("images", "v.image_hash", "v.image_prefix")} AS resolved_key, v.failure, v.viewport_width, v.viewport_height FROM render_batches r CROSS JOIN v CROSS JOIN stories s ON s.id = v.story LEFT JOIN images candidate ON candidate.key = v.image_prefix -WHERE r.id = ?1 AND r.finished_at IS NULL AND (v.image_hash IS NULL OR resolved_key IS NOT NULL) +WHERE r.id = unhex(?1, '-') AND r.finished_at IS NULL AND (v.image_hash IS NULL OR resolved_key IS NOT NULL) ON CONFLICT(batch_key, story_key) DO UPDATE SET image_key = excluded.image_key, failure = excluded.failure, viewport_width = excluded.viewport_width, viewport_height = excluded.viewport_height @@ -597,7 +598,7 @@ export class RenderBatches { const rows = await this.#sql.run({ sql: `SELECT s.id AS story, rs.viewport_width, rs.viewport_height FROM render_batches r CROSS JOIN renders rs ON rs.batch_key = r.key JOIN stories s ON s.key = rs.story_key -WHERE r.id = ?1 AND rs.viewport_width IS NOT NULL`, +WHERE r.id = unhex(?1, '-') AND rs.viewport_width IS NOT NULL`, params: [batchId], idempotent: true, }); @@ -991,7 +992,7 @@ function toBatch(row: SqlRow): RenderBatch { const failedCount = row.failed_count as number | null; const finishedAt = row.finished_at as number | null; return { - id: row.id as string, + id: uuidFromHex(row.id_hex as string), gitSha: row.git_sha as string, environment: row.environment as string, status: finishedAt === null ? "recording" : failedCount === 0 ? "complete" : "failed", @@ -1000,7 +1001,7 @@ function toBatch(row: SqlRow): RenderBatch { failedCount, dirty: row.dirty === 1, storyFilter: row.story_filter === null ? null : (JSON.parse(row.story_filter as string) as StoryFilter), - reusedFromBatch: row.reused_from_batch as string | null, + reusedFromBatch: row.reused_hex === null ? null : uuidFromHex(row.reused_hex as string), scale: row.scale as number, viewport: viewportOf(row), branch: row.branch as string | null, @@ -1203,7 +1204,7 @@ function insertBatchStatements({ id, gitSha, environment, startedAt, dirty, stor { // Sql binds no nulls, so an empty string stands for one. sql: `INSERT INTO render_batches(id, commit_key, environment_key, started_at, dirty, story_filter, reused_from_batch, scale, branch, viewport_width, viewport_height) -VALUES (?1, ${commitKey("?2")}, ${environmentKey("?3")}, CAST(?4 AS INTEGER), CAST(?5 AS INTEGER), NULLIF(?6, ''), NULLIF(?7, ''), ?8, NULLIF(?9, ''), CAST(?10 AS INTEGER), CAST(?11 AS INTEGER)) +VALUES (unhex(?1, '-'), ${commitKey("?2")}, ${environmentKey("?3")}, CAST(?4 AS INTEGER), CAST(?5 AS INTEGER), NULLIF(?6, ''), unhex(NULLIF(?7, ''), '-'), ?8, NULLIF(?9, ''), CAST(?10 AS INTEGER), CAST(?11 AS INTEGER)) ON CONFLICT(id) DO NOTHING`, params: [id, gitSha, environment, startedAt, dirty ? 1 : 0, storyFilter === null ? "" : JSON.stringify(storyFilter), reusedFromBatch ?? "", scale, branch ?? "", viewport.width, viewport.height], idempotent: true, diff --git a/store/test/contract/render-batches-contract.ts b/store/test/contract/render-batches-contract.ts index 26fd977..9d355b8 100644 --- a/store/test/contract/render-batches-contract.ts +++ b/store/test/contract/render-batches-contract.ts @@ -141,6 +141,18 @@ export function describeBatchContract( expect((await batches.batchesReaching(short, options.environment, 1)).map(({ gitSha }) => gitSha)).toEqual([long]); }); + it("keeps a batch's ID and the one it reused as 16 bytes, and returns each as its UUID", async () => { + const options = { gitSha: ON.gitSha, environment: "binary-ids", scale: 1, viewport: { width: 800, height: 600 }, dirty: false }; + const first = await batches.finishBatch((await batches.beginBatch(options)).id, 0); + const reusing = await batches.beginBatch({ ...options, reusedFromBatch: first.id }); + expect(await batches.getBatch(reusing.id)).toMatchObject({ id: reusing.id, reusedFromBatch: first.id }); + const sql = new Sql(withParamMode(database.connect(), mode)); + expect(await sql.run({ + sql: "SELECT typeof(id) AS kind, length(id) AS bytes, length(reused_from_batch) AS reused FROM render_batches WHERE id = unhex(?1, '-')", + params: [reusing.id], + })).toEqual([{ kind: "blob", bytes: 16, reused: 16 }]); + }); + it("holds a remote decision's batch UUID as 16 bytes and returns the canonical ID", async () => { const batchId = "00112233-4455-6677-8899-aabbccddeeff"; const placed = { ...ON, batchId, story: "remote", imageHash: null, decision: "approved" as const, actor: "jo", at: 1 }; diff --git a/store/test/render-batches.test.ts b/store/test/render-batches.test.ts index 31fffa8..8368de3 100644 --- a/store/test/render-batches.test.ts +++ b/store/test/render-batches.test.ts @@ -688,7 +688,7 @@ describe("RenderBatches", () => { await expect(sql.run({ sql: "INSERT INTO renders(batch_key, story_key, failure) VALUES (424242, 424242, 'boom')" })).rejects.toThrow(/FOREIGN KEY/); await expect(sql.run({ sql: "INSERT INTO decisions(environment_key, commit_key, story_key, image_key, rejected, decided_at, actor_key, batch_uuid) VALUES (424242, 424242, 424242, 0, 0, 1, 424242, zeroblob(16))" })).rejects.toThrow(/FOREIGN KEY/); const batch = await recordBatch(SHA_A, [rendered("a", 1)]); - const [{ key }] = (await sql.run({ sql: "SELECT key FROM render_batches WHERE id = ?1", params: [batch.id] })) as [{ key: number }]; + const [{ key }] = (await sql.run({ sql: "SELECT key FROM render_batches WHERE id = unhex(?1, '-')", params: [batch.id] })) as [{ key: number }]; await sql.run({ sql: "INSERT INTO stories(id) VALUES ('never-rendered')" }); await expect(sql.run({ sql: "INSERT INTO renders(batch_key, story_key, image_key) VALUES (CAST(?1 AS INTEGER), (SELECT key FROM stories WHERE id = 'never-rendered'), 424242)", params: [key] })).rejects.toThrow(/FOREIGN KEY/); }); From 6a94b541662154d93bea6abd6f0a1f6b6a2c03be Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Sat, 28 Nov 2026 12:17:08 -0800 Subject: [PATCH 3/6] Order decisions totally, so stores holding the same ones read them alike Co-Authored-By: Claude Opus 5.5 --- docs/specs/renders.md | 3 ++- docs/specs/renders.rationale.md | 2 +- store/src/core/render-batches.ts | 15 ++++++++++----- store/test/approvals-from-history.test.ts | 9 +++++++++ store/test/contract/render-batches-contract.ts | 10 ++++++++++ 5 files changed, 32 insertions(+), 7 deletions(-) diff --git a/docs/specs/renders.md b/docs/specs/renders.md index 6d74c56..978865e 100644 --- a/docs/specs/renders.md +++ b/docs/specs/renders.md @@ -79,7 +79,8 @@ A decision is an approval or a rejection, by an actor, at the time it is recorde - **Must record a decision against a render's name, an image hash or a removal, and the commit and batch it was made on.** A removal is a decision with no image, stored as an image key of 0, which [no image is ever given](store.md#image-keys). **Must store its originating batch UUID as 16 raw bytes and exchange it as a lowercase, hyphenated UUID** (rationale). - **Must keep one decision per name, hash, and commit, the one most recently recorded.** There is no history of replaced decisions. -- **Must merge decisions for the same name, image hash or removal, and commit by decision time, with rejection winning an equal-time tie.** When the incoming time and verdict both match, the stored decision keeps its actor and batch. Replaying a decision changes nothing (rationale). +- **Must merge decisions for the same name, image hash or removal, and commit by decision time, with rejection winning an equal-time tie, and then the greater batch ID.** When the incoming time, verdict, and batch all match, the stored decision keeps its actor. Replaying a decision changes nothing (rationale). +- **Must order every decision a comparison reads by that same rule, then by the greater commit SHA and image hash**, a total order, so two stores holding the same decisions read them alike, whatever order they were given them in (rationale). - **Must refuse every decision in a request if any names an image this store doesn't hold**, with `unknown-image`, as a render already must, so a decision can hold the image's key (rationale). Sync sends a batch's images before its decisions (`docs/specs/sync.md` → Pushing and pulling). ## Approvals diff --git a/docs/specs/renders.rationale.md b/docs/specs/renders.rationale.md index 55127ac..9c172ae 100644 --- a/docs/specs/renders.rationale.md +++ b/docs/specs/renders.rationale.md @@ -44,7 +44,7 @@ **Keeping no history.** A log of every decision would merge cleanly, but nothing in `selfie review` or the review UI reads one. -**Merging equal timestamps.** A rejection wins a tie with an approval so both stores report the same verdict. Later decisions still let someone change their mind, though clocks on different machines can put close decisions in the wrong order. Sync attributes an incoming decision to the authenticated writer, so the actor cannot break a tie consistently. Two approvals at the same time can still leave different batch IDs at different stores. That matters because a batch excludes its own approval when choosing its reference. Two reached approvals for different images can also tie. Reversing the supplied commit order in a local fixture changed the same render from unchanged to changed. +**Merging equal timestamps.** A rejection wins a tie with an approval so both stores report the same verdict. Later decisions still let someone change their mind, though clocks on different machines can put close decisions in the wrong order. Sync attributes an incoming decision to the authenticated writer, so the actor cannot break a tie consistently. Without more to compare, two approvals at the same time left different batch IDs at different stores, which matters because a batch excludes its own approval when choosing its reference, and two reached approvals for different images could tie, so that reversing the supplied commit order in a local fixture changed the same render from unchanged to changed. So the batch ID breaks a tie that time and verdict leave, and then, for decisions read together, the commit and the image: values every store holds alike, unlike its own keys. Which one wins doesn't matter, only that it's always the same one. **Size of the batch ID.** A decision can arrive before its batch, so it needs a portable ID. Storing the UUID bytes saves 20 bytes of payload each time a batch ID repeats. On local SQLite 3.54.1, a compacted fixture with 20,000 SHA-1 commits and ten decisions per commit used 15.32 MB with text UUIDs and 11.20 MB with 16-byte UUIDs. Only the decision's batch ID representation varied. This measures storage. The cost of returning UUID text on reads is still open. diff --git a/store/src/core/render-batches.ts b/store/src/core/render-batches.ts index a165da9..6e8ffeb 100644 --- a/store/src/core/render-batches.ts +++ b/store/src/core/render-batches.ts @@ -113,14 +113,14 @@ const NAMED_BATCH_KEY = `(SELECT b.key FROM render_batches b AND b.environment_key = (SELECT environment_key FROM render_batches WHERE id = unhex(?1, '-')))`; // A story and image can have a decision per commit. What reads one without history in hand wants the -// newest, latest first, and at the same moment a rejection, then by commit so that one row wins. +// newest, as `newestFirst` orders them. A batch is at one commit, so the commit's key only settles rows no store tells apart. // The index is named since SQLite, without statistics, picks the primary key, and so reads every decision // in the environment for every render: `docs/specs/renders.rationale.md` -> Finding a decision by its image. const DECISION_ON_RENDER = `LEFT JOIN decisions d INDEXED BY decisions_by_image ON d.environment_key = r.environment_key AND d.story_key = rs.story_key AND d.image_key = rs.image_key AND NOT EXISTS (SELECT 1 FROM decisions n INDEXED BY decisions_by_image WHERE n.environment_key = d.environment_key AND n.story_key = d.story_key AND n.image_key = d.image_key - AND (n.decided_at, n.rejected, n.commit_key) > (d.decided_at, d.rejected, d.commit_key)) + AND (n.decided_at, n.rejected, n.batch_uuid, n.commit_key) > (d.decided_at, d.rejected, d.batch_uuid, d.commit_key)) LEFT JOIN actors a ON a.key = d.actor_key`; const DECISION_WORD = "CASE d.rejected WHEN 1 THEN 'rejected' WHEN 0 THEN 'approved' END"; @@ -314,8 +314,9 @@ LEFT JOIN images candidate ON candidate.key = v.image_prefix WHERE true ON CONFLICT(environment_key, commit_key, story_key, image_key) DO UPDATE SET rejected = excluded.rejected, decided_at = excluded.decided_at, actor_key = excluded.actor_key, batch_uuid = excluded.batch_uuid`; +// The batch is last, so that two stores told the same two decisions in either order keep the same one. const MERGE_DECISION = `${UPSERT_DECISION} -WHERE (excluded.decided_at, excluded.rejected) > (decisions.decided_at, decisions.rejected)`; +WHERE (excluded.decided_at, excluded.rejected, excluded.batch_uuid) > (decisions.decided_at, decisions.rejected, decisions.batch_uuid)`; const NAME_COLUMNS = { environments: "id", stories: "id", commits: "sha_bytes", actors: "name" } as const; @@ -1022,8 +1023,12 @@ const toPlacedDecision = (row: SqlRow): PlacedDecision => ({ gitSha: row.git_sha as string, }); -// The same order as `DECISION_ON_RENDER` and the merge rule: latest first, then `rejected` before `approved`. -const newestFirst = (a: PlacedDecision, b: PlacedDecision) => b.at - a.at || b.decision.localeCompare(a.decision); +// The same order as `DECISION_ON_RENDER` and the merge rule: latest first, then `rejected` before `approved`, then +// by batch, then by commit and image, all descending. A total order, so every store reads the same decisions alike, +// whatever order it was given them in. A UUID's text sorts as its bytes do. +const descending = (a: string, b: string) => (a < b ? 1 : a > b ? -1 : 0); +const newestFirst = (a: PlacedDecision, b: PlacedDecision) => + b.at - a.at || b.decision.localeCompare(a.decision) || descending(a.batchId, b.batchId) || descending(a.gitSha, b.gitSha) || descending(a.imageHash ?? "", b.imageHash ?? ""); /** * What another store needs of these decisions to compare the same way: each story's, newest first, back diff --git a/store/test/approvals-from-history.test.ts b/store/test/approvals-from-history.test.ts index 3df306e..bd37192 100644 --- a/store/test/approvals-from-history.test.ts +++ b/store/test/approvals-from-history.test.ts @@ -47,6 +47,15 @@ describe("comparing with what history has approved", () => { expect(states([render("s", A)], [approved("s", A, 1, THIS), rejected("s", A, 1, THIS)])[0]![3]).toBe("rejected"); }); + it("reads the same whichever order it's given decisions tied in time and verdict", () => { + const LATER = "33333333-3333-4333-8333-333333333333"; + const tied = [approved("s", A, 1, OTHER), approved("s", B, 1, LATER)]; + expect(states([render("s", B)], tied)).toEqual([["s", "unchanged", B, "approved"]]); + expect(states([render("s", B)], [...tied].reverse())).toEqual([["s", "unchanged", B, "approved"]]); + const atTwoCommits = [{ ...approved("s", A, 1), gitSha: "a".repeat(40) }, { ...approved("s", B, 1), gitSha: "b".repeat(40) }]; + expect(states([render("s", B)], atTwoCommits)).toEqual(states([render("s", B)], [...atTwoCommits].reverse())); + }); + it("says a story with a reference is removed, until that's approved", () => { expect(states([], [approved("s", A, 1)])).toEqual([["s", "removed", A, null]]); expect(states([], [approved("s", A, 1), approved("s", null, 2, THIS)])).toEqual([["s", "removed", A, "approved"]]); diff --git a/store/test/contract/render-batches-contract.ts b/store/test/contract/render-batches-contract.ts index 9d355b8..236447a 100644 --- a/store/test/contract/render-batches-contract.ts +++ b/store/test/contract/render-batches-contract.ts @@ -529,6 +529,16 @@ export function describeBatchContract( } }); + it("keeps the same batch for two approvals at the same moment, in either order", async () => { + const later = "ffffffff-ffff-4fff-8fff-ffffffffffff"; + const [first, second] = [on("approved", "ned", 1_000), { ...on("approved", "ned", 1_000), batchId: later }]; + for (const [environment, order] of [["same-forward", [first, second]], ["same-backward", [second, first]]] as const) { + const batch = await finished(environment); + for (const decision of order) await batches.mergeDecisions(environment, [decision]); + expect((await decisionsOn(batch.id))?.batchId).toBe(later); + } + }); + it("reads a rejection first at the same moment, across commits", async () => { const batch = await finished("tie-across-commits"); await batches.mergeDecisions("tie-across-commits", [{ ...on("approved", "ned", 1_000), gitSha: SHA_0 }, { ...on("rejected", "bob", 1_000), gitSha: SHA_1 }]); From 35bb4b7f0b6aad5f06a93e475e622a06dcdf3fbe Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Sat, 28 Nov 2026 12:31:52 -0800 Subject: [PATCH 4/6] Keep the store's schema version, and refuse a store at any other Co-Authored-By: Claude Opus 5.5 --- OPERATIONS.md | 8 +++-- cli/src/cli.ts | 11 +++++-- cli/src/errors.ts | 1 + cli/test/commands.test.ts | 16 ++++++++-- docs/specs/cli.md | 2 +- docs/specs/renders.md | 4 ++- docs/specs/renders.rationale.md | 4 +-- docs/specs/store.md | 2 +- store/src/core/index.ts | 2 ++ store/src/core/store.ts | 53 ++++++++++++++++++++++++++----- store/test/d1-rest.test.ts | 4 +-- store/test/render-batches.test.ts | 40 +++++++++++++++++------ 12 files changed, 116 insertions(+), 31 deletions(-) diff --git a/OPERATIONS.md b/OPERATIONS.md index 0ff8009..8c3851a 100644 --- a/OPERATIONS.md +++ b/OPERATIONS.md @@ -24,9 +24,9 @@ From a laptop, the same steps are `node ui/scripts/production.mjs preflight|depl ### Resetting a project store -The release with binary Git SHAs and decision batch UUIDs changes both D1 and the CLI's SQLite schema. To keep published batches and approvals, use a machine that still has their local store and the previous CLI. +The release that brought in schema versions (`docs/specs/renders.md` → Schema) changes both D1 and the CLI's SQLite schema: hashes, SHAs, and batch IDs held as bytes, and every table `STRICT`. A store from before it is refused until it's reset. To keep published batches and approvals, use a machine that still has their local store and the previous CLI. -1. Take the old Worker offline. Run the SQL below on each project D1 database, then deploy the new Worker. The reset discards batch history, decisions, and image and built Storybook metadata. The Worker recreates the tables on first use. The image and Storybook bytes in R2 can be reused. +1. Take the old Worker offline. Run the SQL below on each project D1 database, then deploy the new Worker. The reset discards batch history, decisions, the names they share, and image and built Storybook metadata. The Worker recreates the tables on first use. The image and Storybook bytes in R2 can be reused. 2. Once the new Worker is serving, use the **previous CLI and its intact local store** to run `selfie push ` for each finished, clean batch you want to republish. Use credentials with decision permission to include approvals and rejections. A push made before the D1 reset would be erased by step 1. 3. After those pushes succeed, stop local Selfie processes and run the same SQL on each affected `$SELFIE_HOME//store.db` (default `~/.config/selfie//store.db`). Then use the upgraded CLI. To restore published decisions reachable from HEAD, run `selfie pull`. Run `selfie review` to record a fresh local batch. If all old batch history is disposable, skip step 2. @@ -38,6 +38,10 @@ DROP TABLE IF EXISTS render_batches; DROP TABLE IF EXISTS commits; DROP TABLE IF EXISTS images; DROP TABLE IF EXISTS built_storybooks; +DROP TABLE IF EXISTS environments; +DROP TABLE IF EXISTS stories; +DROP TABLE IF EXISTS actors; +DROP TABLE IF EXISTS schema_version; ``` The table reset preserves local notes and `render_keys`. Their old batch IDs may refer to discarded batches. Deleting the whole `store.db` also deletes the notes and render keys. diff --git a/cli/src/cli.ts b/cli/src/cli.ts index 12be33f..416e198 100644 --- a/cli/src/cli.ts +++ b/cli/src/cli.ts @@ -9,7 +9,7 @@ import { gitUserEmail, resolveCommit } from "./git.ts"; import { selfieHome } from "./paths.ts"; import { compareAsReviewed, openProject, type Project } from "./project.ts"; import { renderBatch, review, replyToNote, runBuild } from "./review.ts"; -import { summarizeBatch } from "selfie-store"; +import { StoreSchemaError, summarizeBatch } from "selfie-store"; import { pull, push, requireRemote, type Fetch } from "./sync.ts"; import { isNoteId, isNoteText, MAX_NOTE_CHARACTERS } from "selfie-ui/notes"; import { awaitFeedback, notesForAgent } from "./notes.ts"; @@ -155,8 +155,13 @@ async function withProject(context: Context, work: (project: Project) => Promise } } catch (error) { // Nothing migrates a store yet: docs/specs/store.md -> Open questions. - if (/no such column|has no column named/.test((error as Error).message)) { - throw new SelfieError("old-store", `This project's store.db under ${selfieHome(context.env)} is from an older Selfie. For the binary Git SHA upgrade, follow https://github.com/diffplug/selfie/blob/main/OPERATIONS.md#resetting-a-project-store to preserve local notes and republish batches. If all local data is disposable, delete it and render again. (${(error as Error).message})`); + const where = `This project's store.db under ${selfieHome(context.env)}`; + if (error instanceof StoreSchemaError && error.newer) { + throw new SelfieError("newer-store", `${where} was set up by a newer Selfie. Update Selfie to use it. (${error.message})`); + } + // A missing column is one of the CLI's own tables from before a change to it. + if (error instanceof StoreSchemaError || /no such column|has no column named/.test((error as Error).message)) { + throw new SelfieError("old-store", `${where} is from an older Selfie. To keep its batches and notes, follow https://github.com/diffplug/selfie/blob/main/OPERATIONS.md#resetting-a-project-store. If all local data is disposable, delete it and render again. (${(error as Error).message})`); } throw error; } diff --git a/cli/src/errors.ts b/cli/src/errors.ts index d0cc8d3..fa0f088 100644 --- a/cli/src/errors.ts +++ b/cli/src/errors.ts @@ -5,6 +5,7 @@ export type SelfieErrorCode = | "bad-config" | "no-config" | "old-store" + | "newer-store" | "build-failed" | "no-stories" | "head-moved" diff --git a/cli/test/commands.test.ts b/cli/test/commands.test.ts index be51215..07651be 100644 --- a/cli/test/commands.test.ts +++ b/cli/test/commands.test.ts @@ -212,18 +212,30 @@ describe("a store from before a schema change", () => { expect(json.error).toMatchObject({ code: "old-store", message: expect.stringContaining("delete it") }); }); - test("points a text-SHA store to the reset that preserves local notes", async () => { + test("points a store from before schema versions to the reset that preserves local notes", async () => { h.stories = [{ id: "a--one" }]; await review(); const [slug] = await readdir(h.home); const db = new DatabaseSync(path.join(h.home, slug!, "store.db")); - db.exec("DROP INDEX commits_by_sha; ALTER TABLE commits RENAME COLUMN sha_bytes TO sha"); + db.exec("DROP TABLE schema_version; DROP INDEX commits_by_sha; ALTER TABLE commits RENAME COLUMN sha_bytes TO sha"); db.close(); const { code, json } = await review(); expect(code).toBe(2); expect(json.error).toMatchObject({ code: "old-store", message: expect.stringContaining("OPERATIONS.md#resetting-a-project-store") }); }); + test("says to update Selfie for a store a newer one set up", async () => { + h.stories = [{ id: "a--one" }]; + await review(); + const [slug] = await readdir(h.home); + const db = new DatabaseSync(path.join(h.home, slug!, "store.db")); + db.exec("UPDATE schema_version SET version = version + 1"); + db.close(); + const { code, json } = await review(); + expect(code).toBe(2); + expect(json.error).toMatchObject({ code: "newer-store", message: expect.stringContaining("Update Selfie") }); + }); + test("says so on opening one from before integer keys, which fails at making an index", async () => { h.stories = [{ id: "a--one" }]; await review(); diff --git a/docs/specs/cli.md b/docs/specs/cli.md index 32d39dd..1764c31 100644 --- a/docs/specs/cli.md +++ b/docs/specs/cli.md @@ -77,7 +77,7 @@ Source of truth: `cli/src/paths.ts`, `cli/src/project.ts`; tests in `cli/test/un render// One render's output, deleted when recording ends ``` -- **Must report an incompatible store with a missing column as `old-store` and point to the reset instructions** (`OPERATIONS.md` → Resetting a project store). +- **Must report a store from an older Selfie as `old-store`, and point to the reset instructions** (`OPERATIONS.md` → Resetting a project store): one at an older schema version or with none (`docs/specs/renders.md` → Schema), or one whose CLI tables lack a column. **Must report one at a newer schema version as `newer-store`, and say to update Selfie.** - **Never read `/d1.env`**, or anything else in `` that isn't under a project's slug. - **Must make a slug of only `[a-z0-9-]`**, so it holds no separator or dot, can't climb out of ``, and can't be a file there such as `d1.env`. It is the readable origin, cut to 80 characters, then 8 hex digits of the normalized origin's SHA256, so `a/b-c` and `a-b/c` stay apart. - **Must normalize an origin to its lowercased host and path, with no scheme, credentials, port, trailing slash, or `.git`**, so an SSH and an HTTPS clone share a store, and a token in a URL reaches no path, document, or log. The origin goes no further than the slug. diff --git a/docs/specs/renders.md b/docs/specs/renders.md index 978865e..73a2b96 100644 --- a/docs/specs/renders.md +++ b/docs/specs/renders.md @@ -128,6 +128,7 @@ What differs from what's approved isn't what a commit changed: a default branch Source of truth: `CREATE_BATCH_TABLES` in `store/src/core/render-batches.ts`, `initStoreSchema` in `store/src/core/store.ts`. ```sql +schema_version(only PK = 1, version) environments(key PK, id UNIQUE) stories(key PK, id UNIQUE) commits(key PK, sha_bytes BLOB) @@ -145,7 +146,8 @@ commit_parents(commit_key → commits.key, parent_key → commits.key) PK (comm - **Must declare every table `STRICT`**, so a value of the wrong type is refused rather than kept (rationale). - **Must leave out the CLI's local table** (`docs/specs/cli.md` → Recording only if necessary): it's in a local `store.db`, not this schema, and D1 doesn't have it. -- **Must only add missing tables and indexes during setup**, in one request. A store holding only images can be opened. A store with the old text `commits.sha` column must fail setup and be recreated (rationale). +- **Must keep the store's schema version in `schema_version`, and check it before setting anything up**, in a request of its own: a store with none of these tables gets this version, `STORE_SCHEMA_VERSION`, and one at any other version, or with some of them and no version, is refused with `StoreSchemaError`, and left as it was (rationale). Nothing migrates a store yet (`docs/specs/store.md` → Open questions). +- **Must then only add missing tables and indexes**, in one request. - **Must store a Git commit SHA as its 20 SHA-1 bytes or 32 SHA-256 bytes, and exchange it as full lowercase hex.** (rationale) - **Must store a batch's ID, and the one it reused, as 16 bytes, and exchange each as a lowercase, hyphenated UUID**, as a decision's batch is (rationale). - **Must declare a foreign key wherever a row's parent is always written first and held here**, as `→` shows above, so a store refuses an orphan instead of holding one (rationale). diff --git a/docs/specs/renders.rationale.md b/docs/specs/renders.rationale.md index 9c172ae..6addd47 100644 --- a/docs/specs/renders.rationale.md +++ b/docs/specs/renders.rationale.md @@ -86,12 +86,12 @@ **Commit keys.** Parent edges repeat two keys, and batches and decisions also carry a commit key in their rows and indexes. In a separate fixture using hex digests, 20,000 commits, one batch and ten decisions per commit, and 19,999 parent edges, SQLite-assigned integer keys used 18.29 MB across the database. Using 53-bit digest prefixes with a full-hash check and no text index used 20.55 MB. Writing the referencing rows took 393 ms with assigned keys and 844 ms with prefixes (five-run local medians). Ancestry walks already compare integer keys. -The commit SHA index names the binary column explicitly. Setup on an older `commits` table fails at that index, before a writer can split one commit across text and binary rows. An images-only database has no commit table and gets the current schema. - **Composite primary keys.** A render page walks the stories of one batch, and a history lookup walks the decisions of one environment and commit. `WITHOUT ROWID` stores the rows in those primary-key trees, so a range scan can retrieve the row contents directly. The reverse index on `commit_parents` serves a different walk, from a commit to the descendants whose statuses may need updating. **Batch IDs as bytes.** A decision's batch was measured at 15.32 MB as text and 11.20 MB as bytes ([Size of the batch ID](#decisions)). A batch's own ID is in `render_batches` and again in its unique index, so it's held the same way, and one ID has one form wherever the store keeps it. +**A schema version, from the start.** Without one, a store set up by an older Selfie was found only by a statement failing on a column it lacked, which says nothing of what to do, and finds nothing if the change was to a column's type. D1 refuses `PRAGMA user_version`, so the version is a one-row table. A store that already had tables when versions came in can't be told apart from a damaged one, so it counts as older, which every store then was. The check is a request before setup's, since a request that fails partway would have set up some tables first. + **Strict tables.** SQLite otherwise keeps a value of any type in any column, so a hex SHA bound where bytes were meant, or a time sent as text, would be stored and then match nothing. `STRICT` can't be added to a table that exists, only by rebuilding it, so every table has it from the start. It ran in the workerd tests, on D1's engine. **Foreign keys, before there's data.** Nothing in the store deletes yet, and every write already goes through a path that writes parents first, so these catch only bugs for now. What they're for is retention: once a batch can be deleted, they're what stop one going while something points at it. SQLite can't add a foreign key to an existing table, so waiting would mean rebuilding tables in a migration, where today it's an edit to their `CREATE` statements. Inserting 10,000 renders took 9 ms with checks and 8 ms without, in one local run. They haven't run on real D1, only on its engine in the Worker tests. diff --git a/docs/specs/store.md b/docs/specs/store.md index 181058c..00db1b0 100644 --- a/docs/specs/store.md +++ b/docs/specs/store.md @@ -143,4 +143,4 @@ Source of truth: `store/src/adapters/r2.ts`; tests in `store/test/workerd/r2.wor ### Open questions - **Removing what's kept.** Nothing removes a kept image or built Storybook, so a local store only grows, by what a built Storybook changes. Decide what may go, since a batch or a decision can still refer to it. -- **Schema migrations.** How a schema change reaches every project database, and how the app treats a database still on the older schema. Current setup and compatibility: `docs/specs/renders.md` → Schema. +- **Schema migrations.** How a schema change reaches every project database. A store holds its schema version, and one at an older version is refused (`docs/specs/renders.md` → Schema), so a migration has what it needs to find one, but nothing migrates a store yet. diff --git a/store/src/core/index.ts b/store/src/core/index.ts index 4aff1a0..947a87e 100644 --- a/store/src/core/index.ts +++ b/store/src/core/index.ts @@ -61,6 +61,8 @@ export { ImageHashMismatchError, imageInsertStatement, initStoreSchema, + STORE_SCHEMA_VERSION, + StoreSchemaError, ReceivingStore, Store, type StoredImage, diff --git a/store/src/core/store.ts b/store/src/core/store.ts index ed1a8e3..11b3c42 100644 --- a/store/src/core/store.ts +++ b/store/src/core/store.ts @@ -30,17 +30,54 @@ export function imageInsertStatement(hash: string): SqlStatement { return insertHashKeyStatement("images", hash); } +/** The schema `initStoreSchema` sets up. A store at any other version is refused until it's recreated. */ +export const STORE_SCHEMA_VERSION = 1; + +const CREATE_STORE_TABLES = [CREATE_IMAGES_TABLE, ...CREATE_BATCH_TABLES, ...CREATE_BUILT_STORYBOOK_TABLES]; +const STORE_TABLES = CREATE_STORE_TABLES.flatMap((statement) => /^CREATE TABLE IF NOT EXISTS (\w+)/.exec(statement)?.[1] ?? []); + +// One row. D1 refuses `PRAGMA user_version`, so the version is a table's. +const CREATE_VERSION_TABLE = "CREATE TABLE IF NOT EXISTS schema_version (only INTEGER PRIMARY KEY CHECK (only = 1), version INTEGER NOT NULL) STRICT"; +// Only a store with none of the tables is new. One that has some and no version predates versions. +const STAMP_NEW_STORE = `INSERT INTO schema_version(only, version) SELECT 1, CAST(?1 AS INTEGER) +WHERE NOT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name IN (SELECT value FROM json_each(?2))) +ON CONFLICT(only) DO NOTHING`; + +/** A store set up by another version of Selfie, which this one can't use as it is. */ +export class StoreSchemaError extends Error { + override readonly name = "StoreSchemaError"; + + /** The store's version, or null if it predates versions. */ + readonly found: number | null; + + constructor(found: number | null) { + super( + found === null || found < STORE_SCHEMA_VERSION + ? `This store is from an older Selfie, at schema version ${found ?? "0"}, not ${STORE_SCHEMA_VERSION}.` + : `This store is from a newer Selfie, at schema version ${found}, not ${STORE_SCHEMA_VERSION}.`, + ); + this.found = found; + } + + get newer(): boolean { + return this.found !== null && this.found > STORE_SCHEMA_VERSION; + } +} + /** - * Creates the store's tables if they are missing, in one request. Safe to call - * concurrently. It only ever adds: see `docs/specs/renders.md` -> Schema. + * Sets up the store's tables if they are missing, after checking that it's at this schema version, in + * two requests. Safe to call concurrently. Throws `StoreSchemaError` for a store at another version: + * see `docs/specs/renders.md` -> Schema. */ export async function initStoreSchema(sql: Sql): Promise { - await sql.batch( - [CREATE_IMAGES_TABLE, ...CREATE_BATCH_TABLES, ...CREATE_BUILT_STORYBOOK_TABLES].map((statement) => ({ - sql: statement, - idempotent: true, - })), - ); + const [, , rows] = await sql.batch([ + { sql: CREATE_VERSION_TABLE, idempotent: true }, + { sql: STAMP_NEW_STORE, params: [STORE_SCHEMA_VERSION, JSON.stringify(STORE_TABLES)], idempotent: true }, + { sql: "SELECT version FROM schema_version", idempotent: true }, + ]); + const found = (rows?.[0]?.version as number | undefined) ?? null; + if (found !== STORE_SCHEMA_VERSION) throw new StoreSchemaError(found); + await sql.batch(CREATE_STORE_TABLES.map((statement) => ({ sql: statement, idempotent: true }))); } export interface ReceivingStoreOptions { diff --git a/store/test/d1-rest.test.ts b/store/test/d1-rest.test.ts index d5a41cc..4510fa0 100644 --- a/store/test/d1-rest.test.ts +++ b/store/test/d1-rest.test.ts @@ -384,8 +384,8 @@ describe("D1RestAdapter replay against a real SQL engine", () => { const store = new Store({ codec: sharpCodec, sql, blob: temp.blob }); const { hash: imageHash, key } = await store.putImage(pngOf(image(1))); expect(await store.lookupKey(imageHash)).toBe(key); - // Schema setup, the put's lookup and insert, and the final lookup each replay once. - expect(requests()).toBe(8); + // Schema setup's two requests, the put's lookup and insert, and the final lookup each replay once. + expect(requests()).toBe(10); }); it("resends everything the render model sends, so a lost response never fails it", async () => { diff --git a/store/test/render-batches.test.ts b/store/test/render-batches.test.ts index 8368de3..7eb7bc1 100644 --- a/store/test/render-batches.test.ts +++ b/store/test/render-batches.test.ts @@ -3,6 +3,8 @@ import { DatabaseSync } from "node:sqlite"; import { imageInsertStatement, initStoreSchema, + STORE_SCHEMA_VERSION, + StoreSchemaError, decisionsThatCount, newestRenders, RenderBatches, @@ -564,17 +566,37 @@ describe("RenderBatches", () => { }); describe("schema", () => { - it("refuses the text-SHA schema before writing a binary commit", async () => { - await sql.batch([ - { sql: "DROP TABLE commits" }, - { sql: "CREATE TABLE commits (key INTEGER PRIMARY KEY, sha TEXT NOT NULL UNIQUE)" }, - { sql: "INSERT INTO commits(sha) VALUES (?1)", params: [SHA_A] }, - ]); - await expect(initStoreSchema(sql)).rejects.toThrow(/no such column: sha_bytes/); - expect(await sql.run({ sql: "SELECT sha FROM commits" })).toEqual([{ sha: SHA_A }]); + it("gives a new store this schema version, and opens it again", async () => { + expect(await sql.run({ sql: "SELECT only, version FROM schema_version" })).toEqual([{ only: 1, version: STORE_SCHEMA_VERSION }]); + await initStoreSchema(sql); + expect(await sql.run({ sql: "SELECT version FROM schema_version" })).toEqual([{ version: STORE_SCHEMA_VERSION }]); + }); + + it("refuses a store from before schema versions, and changes nothing in it", async () => { + const elsewhere = await createTempStore(); + try { + await elsewhere.sql.batch([ + { sql: "DROP TABLE schema_version" }, + { sql: "DROP TABLE commits" }, + { sql: "CREATE TABLE commits (key INTEGER PRIMARY KEY, sha TEXT NOT NULL UNIQUE)" }, + { sql: "INSERT INTO commits(sha) VALUES (?1)", params: [SHA_A] }, + ]); + const refused = await initStoreSchema(elsewhere.sql).catch((error: unknown) => error); + expect(refused).toBeInstanceOf(StoreSchemaError); + expect(refused).toMatchObject({ found: null, newer: false }); + expect(await elsewhere.sql.run({ sql: "SELECT sha FROM commits" })).toEqual([{ sha: SHA_A }]); + expect(await elsewhere.sql.run({ sql: "SELECT version FROM schema_version" })).toEqual([]); + } finally { + await elsewhere.destroy(); + } + }); + + it("refuses a store from a newer Selfie", async () => { + await sql.run({ sql: "UPDATE schema_version SET version = ?1", params: [STORE_SCHEMA_VERSION + 1] }); + await expect(initStoreSchema(sql)).rejects.toMatchObject({ name: "StoreSchemaError", found: STORE_SCHEMA_VERSION + 1, newer: true }); }); - it("adds its tables to a store that holds only images, and can run again", async () => { + it("adds any of its tables that are missing, and can run again", async () => { const elsewhere = await createTempStore(); try { await elsewhere.sql.batch( From c558a223f019571b26ed841ef4d8f57d7e4f53d3 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Sat, 28 Nov 2026 12:36:38 -0800 Subject: [PATCH 5/6] Share the UUID conversion and batch lookups, scan-check images and Storybooks, and say each rule once Co-Authored-By: Claude Opus 5.5 --- docs/specs/cli.md | 2 +- docs/specs/renders.md | 6 ++--- docs/specs/renders.rationale.md | 2 +- docs/specs/store.md | 2 +- store/src/core/built-storybooks.ts | 5 ++-- store/src/core/render-batches.ts | 43 +++++++++++++++--------------- store/src/core/sql-bytes.ts | 7 +++++ store/src/core/store.ts | 16 +++++------ store/test/render-batches.test.ts | 29 ++++++++++++++------ 9 files changed, 65 insertions(+), 47 deletions(-) create mode 100644 store/src/core/sql-bytes.ts diff --git a/docs/specs/cli.md b/docs/specs/cli.md index 1764c31..806d3f0 100644 --- a/docs/specs/cli.md +++ b/docs/specs/cli.md @@ -77,7 +77,7 @@ Source of truth: `cli/src/paths.ts`, `cli/src/project.ts`; tests in `cli/test/un render// One render's output, deleted when recording ends ``` -- **Must report a store from an older Selfie as `old-store`, and point to the reset instructions** (`OPERATIONS.md` → Resetting a project store): one at an older schema version or with none (`docs/specs/renders.md` → Schema), or one whose CLI tables lack a column. **Must report one at a newer schema version as `newer-store`, and say to update Selfie.** +- **Must report a store `initStoreSchema` refuses as older, or whose CLI tables lack a column, as `old-store`, and point to the reset instructions** (`OPERATIONS.md` → Resetting a project store). **Must report one it refuses as newer as `newer-store`, and say to update Selfie.** - **Never read `/d1.env`**, or anything else in `` that isn't under a project's slug. - **Must make a slug of only `[a-z0-9-]`**, so it holds no separator or dot, can't climb out of ``, and can't be a file there such as `d1.env`. It is the readable origin, cut to 80 characters, then 8 hex digits of the normalized origin's SHA256, so `a/b-c` and `a-b/c` stay apart. - **Must normalize an origin to its lowercased host and path, with no scheme, credentials, port, trailing slash, or `.git`**, so an SSH and an HTTPS clone share a store, and a token in a URL reaches no path, document, or log. The origin goes no further than the slug. diff --git a/docs/specs/renders.md b/docs/specs/renders.md index 73a2b96..b6d0632 100644 --- a/docs/specs/renders.md +++ b/docs/specs/renders.md @@ -77,7 +77,7 @@ Source of truth: `RenderBatches.decide` in `store/src/core/render-batches.ts`. A decision is an approval or a rejection, by an actor, at the time it is recorded. -- **Must record a decision against a render's name, an image hash or a removal, and the commit and batch it was made on.** A removal is a decision with no image, stored as an image key of 0, which [no image is ever given](store.md#image-keys). **Must store its originating batch UUID as 16 raw bytes and exchange it as a lowercase, hyphenated UUID** (rationale). +- **Must record a decision against a render's name, an image hash or a removal, and the commit and batch it was made on.** A removal is a decision with no image, stored as an image key of 0, which [no image is ever given](store.md#image-keys). Its batch is held as [any batch ID is](#schema). - **Must keep one decision per name, hash, and commit, the one most recently recorded.** There is no history of replaced decisions. - **Must merge decisions for the same name, image hash or removal, and commit by decision time, with rejection winning an equal-time tie, and then the greater batch ID.** When the incoming time, verdict, and batch all match, the stored decision keeps its actor. Replaying a decision changes nothing (rationale). - **Must order every decision a comparison reads by that same rule, then by the greater commit SHA and image hash**, a total order, so two stores holding the same decisions read them alike, whatever order they were given them in (rationale). @@ -146,10 +146,10 @@ commit_parents(commit_key → commits.key, parent_key → commits.key) PK (comm - **Must declare every table `STRICT`**, so a value of the wrong type is refused rather than kept (rationale). - **Must leave out the CLI's local table** (`docs/specs/cli.md` → Recording only if necessary): it's in a local `store.db`, not this schema, and D1 doesn't have it. -- **Must keep the store's schema version in `schema_version`, and check it before setting anything up**, in a request of its own: a store with none of these tables gets this version, `STORE_SCHEMA_VERSION`, and one at any other version, or with some of them and no version, is refused with `StoreSchemaError`, and left as it was (rationale). Nothing migrates a store yet (`docs/specs/store.md` → Open questions). +- **Must keep the store's schema version in `schema_version`, and check it before setting anything up**, in a request of its own: a store with none of these tables gets this version, `STORE_SCHEMA_VERSION`, and one at any other version, or with some of them and no version, is refused with `StoreSchemaError`, and left as it was (rationale). - **Must then only add missing tables and indexes**, in one request. - **Must store a Git commit SHA as its 20 SHA-1 bytes or 32 SHA-256 bytes, and exchange it as full lowercase hex.** (rationale) -- **Must store a batch's ID, and the one it reused, as 16 bytes, and exchange each as a lowercase, hyphenated UUID**, as a decision's batch is (rationale). +- **Must store a batch ID as 16 bytes, and exchange it as a lowercase, hyphenated UUID**: a batch's own, the one it reused, and a decision's (rationale). - **Must declare a foreign key wherever a row's parent is always written first and held here**, as `→` shows above, so a store refuses an orphan instead of holding one (rationale). - **Never declare one on `decisions.image_key`, `decisions.batch_uuid`, or `reused_from_batch`**, since a key of 0 is a removal, a decision may name a batch this store doesn't hold, and sync may move a batch without the one it was reused from. - **Must say in `render_batches.viewport_width` and `viewport_height` the window a batch's stories lay out in, in CSS pixels, and in those columns of `renders` only a story's own, if it differs**, both or neither, so a story with neither laid out in its batch's (`docs/specs/render.md` → A story's viewport). They only size a story running live, so a comparison never reads them (rationale). **A batch reusing another's images must hold the same sizes.** diff --git a/docs/specs/renders.rationale.md b/docs/specs/renders.rationale.md index 6addd47..a8930d3 100644 --- a/docs/specs/renders.rationale.md +++ b/docs/specs/renders.rationale.md @@ -88,7 +88,7 @@ **Composite primary keys.** A render page walks the stories of one batch, and a history lookup walks the decisions of one environment and commit. `WITHOUT ROWID` stores the rows in those primary-key trees, so a range scan can retrieve the row contents directly. The reverse index on `commit_parents` serves a different walk, from a commit to the descendants whose statuses may need updating. -**Batch IDs as bytes.** A decision's batch was measured at 15.32 MB as text and 11.20 MB as bytes ([Size of the batch ID](#decisions)). A batch's own ID is in `render_batches` and again in its unique index, so it's held the same way, and one ID has one form wherever the store keeps it. +**Batch IDs as bytes.** A decision's batch is smaller as bytes ([Size of the batch ID](#decisions)). A batch's own ID is in `render_batches` and again in its unique index, so it's held the same way, and one ID has one form wherever the store keeps it. **A schema version, from the start.** Without one, a store set up by an older Selfie was found only by a statement failing on a column it lacked, which says nothing of what to do, and finds nothing if the change was to a column's type. D1 refuses `PRAGMA user_version`, so the version is a one-row table. A store that already had tables when versions came in can't be told apart from a damaged one, so it counts as older, which every store then was. The check is a request before setup's, since a request that fails partway would have set up some tables first. diff --git a/docs/specs/store.md b/docs/specs/store.md index 00db1b0..65301d7 100644 --- a/docs/specs/store.md +++ b/docs/specs/store.md @@ -143,4 +143,4 @@ Source of truth: `store/src/adapters/r2.ts`; tests in `store/test/workerd/r2.wor ### Open questions - **Removing what's kept.** Nothing removes a kept image or built Storybook, so a local store only grows, by what a built Storybook changes. Decide what may go, since a batch or a decision can still refer to it. -- **Schema migrations.** How a schema change reaches every project database. A store holds its schema version, and one at an older version is refused (`docs/specs/renders.md` → Schema), so a migration has what it needs to find one, but nothing migrates a store yet. +- **Schema migrations.** How a schema change reaches every project database, which a store's schema version can find (`docs/specs/renders.md` → Schema). diff --git a/store/src/core/built-storybooks.ts b/store/src/core/built-storybooks.ts index 35e21e6..6627f64 100644 --- a/store/src/core/built-storybooks.ts +++ b/store/src/core/built-storybooks.ts @@ -6,6 +6,7 @@ import { gunzip, gzip } from "./gzip.ts"; import { insertHashKeyStatement, lookupHashKeyStatement } from "./hash-keys.ts"; import { assertImageHash, isImageHash, sha256, toHex } from "./image-hash.ts"; import type { Sql } from "./sql.ts"; +import { uuidBytes } from "./sql-bytes.ts"; export const CREATE_BUILT_STORYBOOK_TABLES: readonly string[] = [ // A row says every file is kept, since it's written last. Its key works as an image's does. @@ -129,7 +130,7 @@ export class BuiltStorybooks { const lookup = lookupHashKeyStatement("built_storybooks", build); const rows = await this.#sql.run({ sql: `UPDATE render_batches SET storybook_key = found.key FROM (${lookup.sql}) found -WHERE render_batches.id = unhex(?3, '-') AND found.key IS NOT NULL RETURNING 1`, +WHERE render_batches.id = ${uuidBytes("?3")} AND found.key IS NOT NULL RETURNING 1`, params: [...lookup.params, batchId], idempotent: true, }); @@ -139,7 +140,7 @@ WHERE render_batches.id = unhex(?3, '-') AND found.key IS NOT NULL RETURNING 1`, /** The kept built Storybook that rendered a batch, if there is one. */ async storybookOfBatch(batchId: string): Promise { const [row] = await this.#sql.run({ - sql: "SELECT lower(hex(s.hash)) AS hash FROM render_batches r JOIN built_storybooks s ON s.key = r.storybook_key WHERE r.id = unhex(?1, '-')", + sql: `SELECT lower(hex(s.hash)) AS hash FROM render_batches r JOIN built_storybooks s ON s.key = r.storybook_key WHERE r.id = ${uuidBytes("?1")}`, params: [batchId], idempotent: true, }); diff --git a/store/src/core/render-batches.ts b/store/src/core/render-batches.ts index 6e8ffeb..591e7c3 100644 --- a/store/src/core/render-batches.ts +++ b/store/src/core/render-batches.ts @@ -2,6 +2,7 @@ import { chunks, STATEMENTS_PER_REQUEST } from "./chunks.ts"; import { missingImages, resolvedHashKey } from "./hash-keys.ts"; import { assertImageHash, truncateHexHash } from "./image-hash.ts"; import type { Sql, SqlRow, SqlStatement } from "./sql.ts"; +import { hexOrNull, uuidBytes } from "./sql-bytes.ts"; /** * The tables behind `RenderBatches`, which `initStoreSchema` creates. Anything repeated across a great @@ -56,7 +57,7 @@ export const CREATE_BATCH_TABLES: readonly string[] = [ rejected INTEGER NOT NULL CHECK (rejected IN (0, 1)), decided_at INTEGER NOT NULL, actor_key INTEGER NOT NULL REFERENCES actors(key), - batch_uuid BLOB NOT NULL CHECK (typeof(batch_uuid) = 'blob' AND length(batch_uuid) = 16), + batch_uuid BLOB NOT NULL CHECK (length(batch_uuid) = 16), PRIMARY KEY (environment_key, commit_key, story_key, image_key) ) STRICT, WITHOUT ROWID`, "CREATE INDEX IF NOT EXISTS decisions_by_image ON decisions(environment_key, story_key, image_key)", @@ -93,24 +94,26 @@ export const isBatchId = (value: string) => BATCH_ID.test(value); // As `git rev-list` is asked for: see `docs/specs/renders.md` -> Scope: approvals-sync. const MAX_REACHED_COMMITS = 1_000; -// Bytes kept for a hash or an ID, as the lowercase hex that leaves the store. `hex` makes a missing one '', so it's NULL again. -const hexOrNull = (column: string) => `NULLIF(lower(hex(${column})), '')`; - // Subqueries rather than joins, since a `RETURNING` can't join. const BATCH_COLUMNS = `lower(hex(id)) AS id_hex, (SELECT lower(hex(sha_bytes)) FROM commits WHERE key = commit_key) AS git_sha, (SELECT id FROM environments WHERE key = environment_key) AS environment, started_at, finished_at, failed_count, dirty, story_filter, ${hexOrNull("reused_from_batch")} AS reused_hex, scale, viewport_width, viewport_height, branch`; -const SELECT_BATCH = `SELECT ${BATCH_COLUMNS} FROM render_batches WHERE id = unhex(?1, '-')`; +// The batch named by ?1, found by its unique ID. +const BATCH_BY_ID = `render_batches WHERE id = ${uuidBytes("?1")}`; + +const SELECT_BATCH = `SELECT ${BATCH_COLUMNS} FROM ${BATCH_BY_ID}`; -const BATCH_KEY = "(SELECT key FROM render_batches WHERE id = unhex(?1, '-'))"; +const BATCH_KEY = `(SELECT key FROM ${BATCH_BY_ID})`; +const BATCH_ENVIRONMENT_KEY = `(SELECT environment_key FROM ${BATCH_BY_ID})`; +const BATCH_COMMIT_KEY = `(SELECT commit_key FROM ${BATCH_BY_ID})`; const commitKey = (sha: string) => `(SELECT key FROM commits WHERE sha_bytes = unhex(${sha}))`; const environmentKey = (id: string) => `(SELECT key FROM environments WHERE id = ${id})`; // The key of a finished batch named by ?2, only ever in the batch's own environment. const NAMED_BATCH_KEY = `(SELECT b.key FROM render_batches b - WHERE b.id = unhex(?2, '-') AND b.finished_at IS NOT NULL - AND b.environment_key = (SELECT environment_key FROM render_batches WHERE id = unhex(?1, '-')))`; + WHERE b.id = ${uuidBytes("?2")} AND b.finished_at IS NOT NULL + AND b.environment_key = ${BATCH_ENVIRONMENT_KEY})`; // A story and image can have a decision per commit. What reads one without history in hand wants the // newest, as `newestFirst` orders them. A batch is at one commit, so the commit's key only settles rows no store tells apart. @@ -137,7 +140,7 @@ LEFT JOIN images i ON i.key = rs.image_key LEFT JOIN images gi ON gi.key = gs.image_key ${DECISION_ON_RENDER} LEFT JOIN stories s ON s.key = rs.story_key -WHERE r.id = unhex(?1, '-')${and} AND rs.story_key > CAST(?3 AS INTEGER) +WHERE r.id = ${uuidBytes("?1")}${and} AND rs.story_key > CAST(?3 AS INTEGER) AND (CAST(?5 AS INTEGER) = 1 OR rs.failure IS NOT NULL OR rs.image_key IS NOT gs.image_key) ORDER BY rs.story_key @@ -173,10 +176,10 @@ FROM ( FROM renders WHERE batch_key = ${BATCH_KEY} ) AS c -WHERE render_batches.id = unhex(?1, '-') AND c.total = CAST(?3 AS INTEGER) +WHERE render_batches.id = ${uuidBytes("?1")} AND c.total = CAST(?3 AS INTEGER) RETURNING ${BATCH_COLUMNS}`; -const BATCH_PAGE_TAIL = `WHERE r.id = unhex(?1, '-') AND rs.story_key > CAST(?2 AS INTEGER) +const BATCH_PAGE_TAIL = `WHERE r.id = ${uuidBytes("?1")} AND rs.story_key > CAST(?2 AS INTEGER) ORDER BY rs.story_key LIMIT CAST(?3 AS INTEGER)`; @@ -210,7 +213,7 @@ ${NAMES_OF_DECISION}`; // What a batch's commit reaches, walked by key, so that a long history's SHAs never leave the database. const REACH_OF_BATCH = `WITH RECURSIVE reach(key) AS ( - SELECT commit_key FROM render_batches WHERE id = unhex(?1, '-') + SELECT commit_key FROM ${BATCH_BY_ID} UNION SELECT p.parent_key FROM reach CROSS JOIN commit_parents p ON p.commit_key = reach.key LIMIT ${MAX_REACHED_COMMITS} @@ -239,7 +242,7 @@ LIMIT CAST(?3 AS INTEGER)`; const DECISIONS_REACHED = `${REACH_OF_BATCH} ${PLACED_DECISION} FROM reach r -CROSS JOIN decisions d ON d.environment_key = (SELECT environment_key FROM render_batches WHERE id = unhex(?1, '-')) AND d.commit_key = r.key +CROSS JOIN decisions d ON d.environment_key = ${BATCH_ENVIRONMENT_KEY} AND d.commit_key = r.key CROSS JOIN commits c ON c.key = d.commit_key ${NAMES_OF_DECISION}`; @@ -249,7 +252,7 @@ WHERE branch = ${branch} AND finished_at IS NOT NULL AND environment_key = ${env ORDER BY started_at DESC LIMIT 1`; const baseReached = (columns?: string) => - newestOfBranchWhere("?2", "(SELECT environment_key FROM render_batches WHERE id = unhex(?1, '-'))", "(SELECT commit_key FROM render_batches WHERE id = unhex(?1, '-'))", "SELECT key FROM reach", columns); + newestOfBranchWhere("?2", BATCH_ENVIRONMENT_KEY, BATCH_COMMIT_KEY, "SELECT key FROM reach", columns); const BASE_REACHED = `${REACH_OF_BATCH} ${baseReached()}`; @@ -296,7 +299,7 @@ const RECORD_RENDERS = `WITH ${jsonRows("?2", ["story", "image_hash", "image_pre INSERT INTO renders(batch_key, story_key, image_key, failure, viewport_width, viewport_height) SELECT r.key, s.key, ${resolvedHashKey("images", "v.image_hash", "v.image_prefix")} AS resolved_key, v.failure, v.viewport_width, v.viewport_height FROM render_batches r CROSS JOIN v CROSS JOIN stories s ON s.id = v.story LEFT JOIN images candidate ON candidate.key = v.image_prefix -WHERE r.id = unhex(?1, '-') AND r.finished_at IS NULL AND (v.image_hash IS NULL OR resolved_key IS NOT NULL) +WHERE r.id = ${uuidBytes("?1")} AND r.finished_at IS NULL AND (v.image_hash IS NULL OR resolved_key IS NOT NULL) ON CONFLICT(batch_key, story_key) DO UPDATE SET image_key = excluded.image_key, failure = excluded.failure, viewport_width = excluded.viewport_width, viewport_height = excluded.viewport_height @@ -305,7 +308,7 @@ RETURNING 1 AS written`; // A decision with no image is on a story being gone, which is held as an image key of 0. const UPSERT_DECISION = `WITH ${jsonRows("?2", ["story", "image_hash", "image_prefix", "sha", "rejected", "decided_at", "actor", "batch_id"])} INSERT INTO decisions(environment_key, commit_key, story_key, image_key, rejected, decided_at, actor_key, batch_uuid) -SELECT ${environmentKey("?1")}, c.key, s.key, COALESCE(${resolvedHashKey("images", "v.image_hash", "v.image_prefix")}, 0), v.rejected, v.decided_at, a.key, unhex(v.batch_id, '-') +SELECT ${environmentKey("?1")}, c.key, s.key, COALESCE(${resolvedHashKey("images", "v.image_hash", "v.image_prefix")}, 0), v.rejected, v.decided_at, a.key, ${uuidBytes("v.batch_id")} FROM v CROSS JOIN commits c ON c.sha_bytes = unhex(v.sha) CROSS JOIN stories s ON s.id = v.story @@ -599,7 +602,7 @@ export class RenderBatches { const rows = await this.#sql.run({ sql: `SELECT s.id AS story, rs.viewport_width, rs.viewport_height FROM render_batches r CROSS JOIN renders rs ON rs.batch_key = r.key JOIN stories s ON s.key = rs.story_key -WHERE r.id = unhex(?1, '-') AND rs.viewport_width IS NOT NULL`, +WHERE r.id = ${uuidBytes("?1")} AND rs.viewport_width IS NOT NULL`, params: [batchId], idempotent: true, }); @@ -1023,9 +1026,7 @@ const toPlacedDecision = (row: SqlRow): PlacedDecision => ({ gitSha: row.git_sha as string, }); -// The same order as `DECISION_ON_RENDER` and the merge rule: latest first, then `rejected` before `approved`, then -// by batch, then by commit and image, all descending. A total order, so every store reads the same decisions alike, -// whatever order it was given them in. A UUID's text sorts as its bytes do. +// The same order as `DECISION_ON_RENDER` and the merge rule (`docs/specs/renders.md` -> Decisions). A UUID's text sorts as its bytes do. const descending = (a: string, b: string) => (a < b ? 1 : a > b ? -1 : 0); const newestFirst = (a: PlacedDecision, b: PlacedDecision) => b.at - a.at || b.decision.localeCompare(a.decision) || descending(a.batchId, b.batchId) || descending(a.gitSha, b.gitSha) || descending(a.imageHash ?? "", b.imageHash ?? ""); @@ -1209,7 +1210,7 @@ function insertBatchStatements({ id, gitSha, environment, startedAt, dirty, stor { // Sql binds no nulls, so an empty string stands for one. sql: `INSERT INTO render_batches(id, commit_key, environment_key, started_at, dirty, story_filter, reused_from_batch, scale, branch, viewport_width, viewport_height) -VALUES (unhex(?1, '-'), ${commitKey("?2")}, ${environmentKey("?3")}, CAST(?4 AS INTEGER), CAST(?5 AS INTEGER), NULLIF(?6, ''), unhex(NULLIF(?7, ''), '-'), ?8, NULLIF(?9, ''), CAST(?10 AS INTEGER), CAST(?11 AS INTEGER)) +VALUES (${uuidBytes("?1")}, ${commitKey("?2")}, ${environmentKey("?3")}, CAST(?4 AS INTEGER), CAST(?5 AS INTEGER), NULLIF(?6, ''), ${uuidBytes("NULLIF(?7, '')")}, ?8, NULLIF(?9, ''), CAST(?10 AS INTEGER), CAST(?11 AS INTEGER)) ON CONFLICT(id) DO NOTHING`, params: [id, gitSha, environment, startedAt, dirty ? 1 : 0, storyFilter === null ? "" : JSON.stringify(storyFilter), reusedFromBatch ?? "", scale, branch ?? "", viewport.width, viewport.height], idempotent: true, diff --git a/store/src/core/sql-bytes.ts b/store/src/core/sql-bytes.ts new file mode 100644 index 0000000..9220692 --- /dev/null +++ b/store/src/core/sql-bytes.ts @@ -0,0 +1,7 @@ +// What crosses the store as text and is kept as bytes. `Sql` binds only text and numbers, so each converts in the statement. + +/** A hyphenated UUID, such as a batch's ID, bound as `param`, as the 16 bytes it's kept as. */ +export const uuidBytes = (param: string) => `unhex(${param}, '-')`; + +/** Bytes kept for a hash or an ID, as the lowercase hex that leaves the store. `hex` makes a missing one '', so it's NULL again. */ +export const hexOrNull = (column: string) => `NULLIF(lower(hex(${column})), '')`; diff --git a/store/src/core/store.ts b/store/src/core/store.ts index 11b3c42..8490cb0 100644 --- a/store/src/core/store.ts +++ b/store/src/core/store.ts @@ -34,7 +34,8 @@ export function imageInsertStatement(hash: string): SqlStatement { export const STORE_SCHEMA_VERSION = 1; const CREATE_STORE_TABLES = [CREATE_IMAGES_TABLE, ...CREATE_BATCH_TABLES, ...CREATE_BUILT_STORYBOOK_TABLES]; -const STORE_TABLES = CREATE_STORE_TABLES.flatMap((statement) => /^CREATE TABLE IF NOT EXISTS (\w+)/.exec(statement)?.[1] ?? []); +/** Every table `initStoreSchema` creates, by name. */ +export const STORE_TABLES = CREATE_STORE_TABLES.flatMap((statement) => /^CREATE TABLE IF NOT EXISTS (\w+)/.exec(statement)?.[1] ?? []); // One row. D1 refuses `PRAGMA user_version`, so the version is a table's. const CREATE_VERSION_TABLE = "CREATE TABLE IF NOT EXISTS schema_version (only INTEGER PRIMARY KEY CHECK (only = 1), version INTEGER NOT NULL) STRICT"; @@ -49,18 +50,13 @@ export class StoreSchemaError extends Error { /** The store's version, or null if it predates versions. */ readonly found: number | null; + /** Whether a newer Selfie set it up, rather than an older one. */ + readonly newer: boolean; constructor(found: number | null) { - super( - found === null || found < STORE_SCHEMA_VERSION - ? `This store is from an older Selfie, at schema version ${found ?? "0"}, not ${STORE_SCHEMA_VERSION}.` - : `This store is from a newer Selfie, at schema version ${found}, not ${STORE_SCHEMA_VERSION}.`, - ); + super(`The store is at schema version ${found ?? "none"}, not ${STORE_SCHEMA_VERSION}.`); this.found = found; - } - - get newer(): boolean { - return this.found !== null && this.found > STORE_SCHEMA_VERSION; + this.newer = found !== null && found > STORE_SCHEMA_VERSION; } } diff --git a/store/test/render-batches.test.ts b/store/test/render-batches.test.ts index 7eb7bc1..b0aaa5f 100644 --- a/store/test/render-batches.test.ts +++ b/store/test/render-batches.test.ts @@ -4,7 +4,7 @@ import { imageInsertStatement, initStoreSchema, STORE_SCHEMA_VERSION, - StoreSchemaError, + BuiltStorybooks, decisionsThatCount, newestRenders, RenderBatches, @@ -26,6 +26,7 @@ import { pngOf } from "./support/png-builder.ts"; import { hashOf } from "./support/sql-params.ts"; import { createTempStore } from "./support/temp-store.ts"; import { sharpCodec } from "../src/adapters/sharp-codec.ts"; +import { STORE_TABLES } from "../src/core/store.ts"; const ON = { batchId: "00000000-0000-4000-8000-000000000001", gitSha: "e".repeat(40) }; @@ -581,9 +582,7 @@ describe("RenderBatches", () => { { sql: "CREATE TABLE commits (key INTEGER PRIMARY KEY, sha TEXT NOT NULL UNIQUE)" }, { sql: "INSERT INTO commits(sha) VALUES (?1)", params: [SHA_A] }, ]); - const refused = await initStoreSchema(elsewhere.sql).catch((error: unknown) => error); - expect(refused).toBeInstanceOf(StoreSchemaError); - expect(refused).toMatchObject({ found: null, newer: false }); + await expect(initStoreSchema(elsewhere.sql)).rejects.toMatchObject({ name: "StoreSchemaError", found: null, newer: false }); expect(await elsewhere.sql.run({ sql: "SELECT sha FROM commits" })).toEqual([{ sha: SHA_A }]); expect(await elsewhere.sql.run({ sql: "SELECT version FROM schema_version" })).toEqual([]); } finally { @@ -591,6 +590,11 @@ describe("RenderBatches", () => { } }); + it("lists every table it creates, so a store from before versions can't pass for a new one", async () => { + const tables = await sql.run({ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT IN ('schema_version') ORDER BY name" }); + expect(tables.map(({ name }) => name)).toEqual([...STORE_TABLES].sort()); + }); + it("refuses a store from a newer Selfie", async () => { await sql.run({ sql: "UPDATE schema_version SET version = ?1", params: [STORE_SCHEMA_VERSION + 1] }); await expect(initStoreSchema(sql)).rejects.toMatchObject({ name: "StoreSchemaError", found: STORE_SCHEMA_VERSION + 1, newer: true }); @@ -715,7 +719,7 @@ describe("RenderBatches", () => { await expect(sql.run({ sql: "INSERT INTO renders(batch_key, story_key, image_key) VALUES (CAST(?1 AS INTEGER), (SELECT key FROM stories WHERE id = 'never-rendered'), 424242)", params: [key] })).rejects.toThrow(/FOREIGN KEY/); }); - it("never scans a table, for anything a review or a sync sends", async () => { + it("never scans a table, for anything a review, a sync, or keeping images and built Storybooks sends", async () => { const { adapter: counted, sent } = counting(adapter); const model = new RenderBatches({ sql: new Sql(counted) }); const items = [rendered("a", 1), rendered("b", 2)]; @@ -738,6 +742,15 @@ describe("RenderBatches", () => { await model.receiveBatch(clean); await model.recordCommits([{ sha: SHA_B, parents: [SHA_A] }]); expect(await model.batchesReaching(SHA_A, ENV, 50)).toMatchObject([{ id: head.id }]); + const builds = new BuiltStorybooks({ sql: new Sql(counted), blob: temp.blob }); + const build = hashOf(900); + await builds.putStorybook(build, [{ path: "index.html", fileHash: await builds.putFile(new TextEncoder().encode("

")) }]); + await builds.recordBatchStorybook(head.id, build); + expect(await builds.storybookOfBatch(head.id)).toBe(build); + const store = new Store({ codec: sharpCodec, sql: new Sql(counted), blob: temp.blob }); + const { hash } = await store.putImage(pngOf({ width: 1, height: 1, pixels: new Uint8Array([9, 9, 9]) })); + await store.lookupKey(hash); + await store.missingImages([hash, hashOf(901)]); const db = new DatabaseSync(temp.path); try { @@ -746,14 +759,14 @@ describe("RenderBatches", () => { seen.add(text); // A new name may fix a foreign key that's pending, so its plan lists every table that refers to it. SQLite skips // those while none is pending, and none ever is, since every statement here writes a parent first. - if (/^INSERT INTO (environments|stories|commits|actors)\b/.test(text)) return []; + if (/^INSERT INTO (environments|stories|commits|actors|images|built_storybooks)\b/.test(text)) return []; const plan = db.prepare(`EXPLAIN QUERY PLAN ${text}`).all(...params); return plan .map(({ detail }) => String(detail)) - // Reading a statement's own VALUES or JSON list, a one-row aggregate, or the commits a walk has reached, is no table scan. + // Reading a statement's own VALUES or JSON list, a one-row aggregate or subquery, or the commits a walk has reached, is no table scan. // The primary key by environment alone is every decision there, which the plan doesn't call a scan. // So is a walk reading its own rows, each found by a key. An automatic index is built by reading the whole table. - .filter((detail) => (/\bSCAN\b/.test(detail) && !/\bSCAN (v|c|j|json_each|reach|descendants|\d+ CONSTANT ROWS?|CONSTANT ROW)\b/.test(detail)) || /USING PRIMARY KEY \(environment_key=\?\)/.test(detail) || /\bAUTOMATIC\b/.test(detail)) + .filter((detail) => (/\bSCAN\b/.test(detail) && !/\bSCAN (v|c|j|json_each|reach|descendants|\(subquery-\d+\)|\d+ CONSTANT ROWS?|CONSTANT ROW)(\s|$)/.test(detail)) || /USING PRIMARY KEY \(environment_key=\?\)/.test(detail) || /\bAUTOMATIC\b/.test(detail)) .map((detail) => `${detail} in ${text}`); }); expect(seen.size).toBeGreaterThan(10); From 0799db95f250693a20d6208dbe0ad65354d2590f Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Sat, 28 Nov 2026 13:02:26 -0800 Subject: [PATCH 6/6] Say a refused store gains an empty schema_version, which it does Co-Authored-By: Claude Opus 5.5 --- docs/specs/renders.md | 2 +- store/test/render-batches.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/specs/renders.md b/docs/specs/renders.md index b6d0632..ded1646 100644 --- a/docs/specs/renders.md +++ b/docs/specs/renders.md @@ -146,7 +146,7 @@ commit_parents(commit_key → commits.key, parent_key → commits.key) PK (comm - **Must declare every table `STRICT`**, so a value of the wrong type is refused rather than kept (rationale). - **Must leave out the CLI's local table** (`docs/specs/cli.md` → Recording only if necessary): it's in a local `store.db`, not this schema, and D1 doesn't have it. -- **Must keep the store's schema version in `schema_version`, and check it before setting anything up**, in a request of its own: a store with none of these tables gets this version, `STORE_SCHEMA_VERSION`, and one at any other version, or with some of them and no version, is refused with `StoreSchemaError`, and left as it was (rationale). +- **Must keep the store's schema version in `schema_version`, and check it before setting anything up**, in a request of its own: a store with none of these tables gets this version, `STORE_SCHEMA_VERSION`, and one at any other version, or with some of them and no version, is refused with `StoreSchemaError`, with nothing added but an empty `schema_version` (rationale). - **Must then only add missing tables and indexes**, in one request. - **Must store a Git commit SHA as its 20 SHA-1 bytes or 32 SHA-256 bytes, and exchange it as full lowercase hex.** (rationale) - **Must store a batch ID as 16 bytes, and exchange it as a lowercase, hyphenated UUID**: a batch's own, the one it reused, and a decision's (rationale). diff --git a/store/test/render-batches.test.ts b/store/test/render-batches.test.ts index b0aaa5f..00f36f4 100644 --- a/store/test/render-batches.test.ts +++ b/store/test/render-batches.test.ts @@ -573,7 +573,7 @@ describe("RenderBatches", () => { expect(await sql.run({ sql: "SELECT version FROM schema_version" })).toEqual([{ version: STORE_SCHEMA_VERSION }]); }); - it("refuses a store from before schema versions, and changes nothing in it", async () => { + it("refuses a store from before schema versions, adding nothing but an empty version table", async () => { const elsewhere = await createTempStore(); try { await elsewhere.sql.batch([