diff --git a/OPERATIONS.md b/OPERATIONS.md index 479d1b1..0ff8009 100644 --- a/OPERATIONS.md +++ b/OPERATIONS.md @@ -22,6 +22,26 @@ The app keeps its data in three places: From a laptop, the same steps are `node ui/scripts/production.mjs preflight|deploy|smoke`, with the environment the workflow sets. +### 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. + +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. +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. + +```sql +DROP TABLE IF EXISTS decisions; +DROP TABLE IF EXISTS renders; +DROP TABLE IF EXISTS commit_parents; +DROP TABLE IF EXISTS render_batches; +DROP TABLE IF EXISTS commits; +DROP TABLE IF EXISTS images; +DROP TABLE IF EXISTS built_storybooks; +``` + +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. + ## Logs `selfie-app` keeps what it logs in Workers Logs (`[observability]` in `ui/wrangler.toml`), for 3 days on the Workers Free plan and 7 on Paid: in the dashboard, **Workers & Pages → selfie-app → Logs**. It doesn't keep a line for every request, only what the code logs, which is mostly errors. diff --git a/cli/src/cli.ts b/cli/src/cli.ts index 91f702c..12be33f 100644 --- a/cli/src/cli.ts +++ b/cli/src/cli.ts @@ -156,7 +156,7 @@ 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, and nothing migrates it yet, so delete it and render again. (${(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})`); } throw error; } diff --git a/cli/test/commands.test.ts b/cli/test/commands.test.ts index 262d1a6..be51215 100644 --- a/cli/test/commands.test.ts +++ b/cli/test/commands.test.ts @@ -212,6 +212,18 @@ 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 () => { + 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.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 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 191a536..32d39dd 100644 --- a/docs/specs/cli.md +++ b/docs/specs/cli.md @@ -77,6 +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). - **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 47f42b0..ca0ca29 100644 --- a/docs/specs/renders.md +++ b/docs/specs/renders.md @@ -77,9 +77,9 @@ 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 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 a decision from another store by its own time, latest first, then `rejected` before `approved`, and never by who made it**, so two stores reach one verdict whichever order they hear in, a person changing their mind still works, and sending a decision twice changes nothing. It keeps its commit and batch there, so history reaches it as it would here. +- **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 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 @@ -129,22 +129,24 @@ Source of truth: `CREATE_BATCH_TABLES` in `store/src/core/render-batches.ts`, `i ```sql environments(key PK, id UNIQUE) stories(key PK, id UNIQUE) -commits(key PK, sha 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) 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 -decisions(environment_key → environments.key, commit_key → commits.key, story_key → stories.key, image_key, rejected, decided_at, actor_key → actors.key, batch_id) PK (environment_key, commit_key, story_key, image_key) WITHOUT ROWID +decisions(environment_key → environments.key, commit_key → commits.key, story_key → stories.key, image_key, rejected, decided_at, actor_key → actors.key, batch_uuid BLOB) PK (environment_key, commit_key, story_key, image_key) WITHOUT ROWID INDEX decisions_by_image(environment_key, story_key, image_key) commit_parents(commit_key → commits.key, parent_key → commits.key) PK (commit_key, parent_key) WITHOUT ROWID INDEX commit_parents_by_parent(parent_key, commit_key) ``` - **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 what is missing:** `initStoreSchema` is one request of `CREATE ... IF NOT EXISTS`, so running it upgrades a store holding only images. It changes no existing table, and there is no version number. Any other change needs `docs/specs/store.md` → Open questions decided first. `render_batches.reused_from_batch`, the rename of its tables and columns (`docs/specs/cli.rationale.md`), and its foreign keys are the exceptions, made before any project database existed (rationale): `CREATE TABLE IF NOT EXISTS` doesn't add it to an older store, whose reviews and accepts fail with exit 2 until the store is recreated. +- **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 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_id`, 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. +- **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.** - **Must hold what repeats across a great many rows once, by an integer key, and never let a key leave the store**, as with image keys (rationale). A batch's `id`, a story's ID, a commit's SHA, an environment's ID, an actor's name, and an image's hash are what leave it. **Must give a name its key in the same request, before the first row that uses it.** - **May list a batch's pages in any order**, and `next` only says where the next one starts. A comparison lists stories by name. @@ -167,6 +169,8 @@ Open: - **Squash and rebase merges.** Out of scope for now. Supporting them would need a commit's history to also reach the commits of any pull request merged at one of its ancestors, and a pull request tied to its merge commit when it merges. - **Known limit: history stops at 1,000 commits.** A story whose newest approval is further back has no reference, and reads as added. It's accepted for now, and a cache will replace it. Only approvals count, so this starts to matter 1,000 commits after a project's first approval, however long its history was before that. +- **Equal-time approvals.** Two approvals of the same image at the same commit in the same millisecond can leave stores with different originating batch IDs. A batch excludes its own approval, so this can change its reference. When approvals of different images tie in reachable history, commit order can also change the reference. A portable tie-break is deferred. +- **Decision history size on D1.** `decisionsAt` and `compareReached` read reachable decisions before reducing them. When one query result exceeds D1's 50 MB limit, sync or comparison can fail. Bounding those queries is deferred. - Whether the reference needs a derived table for the cloud. Locally it doesn't (rationale). If it does, that table can always be rebuilt, and is never a source of truth. - A shallow clone can't walk its history, so CI needs a full clone. - An approval on a branch with no commits of its own lands on a commit the default branch also has, so it counts there too. diff --git a/docs/specs/renders.rationale.md b/docs/specs/renders.rationale.md index 73dd8bd..7a8a3f6 100644 --- a/docs/specs/renders.rationale.md +++ b/docs/specs/renders.rationale.md @@ -44,6 +44,10 @@ **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. + +**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. + ## Approvals **History, not a promoted set.** Asking someone to accept a batch on a clean default branch made them render again after a merge, to end up with what they'd already approved. Working it out from history asks nothing at a merge, since a batch there finds the approvals its branch brought. @@ -78,6 +82,14 @@ ## Schema +**Commit digests.** A SHA-1 takes 20 bytes and a SHA-256 takes 32. Git and sync already supply lowercase hex. Converting the incoming value with `unhex` lets SQLite seek directly on the indexed BLOB. For 20,000 SHA-1 commits, the compacted table and unique index used 1.95 MB with hex text, 1.43 MB with unpadded Base64, and 1.15 MB with raw bytes. Batched inserts from hex took 9.4, 10.7, and 9.6 ms respectively on local SQLite. These figures cover commit identities only. + +**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. + **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 @@ -94,13 +106,15 @@ D1's docs say a database runs one query at a time, so a batch this size holds up others for as long as it runs. No test measured concurrent load. -**Statement size.** A record statement holds 49 renders as one JSON parameter, which is what the 100 bound parameters allowed when each took a story and either a hash or a failure, so a request stays the size that was measured. JSON can also say null, which a bound parameter here can't, and its SQL is one constant string. At its worst, 49 failures at 2,000 characters, the parameter is about 100 KB of ASCII, and hasn't run on real D1. +**Statement size.** A record statement holds 49 renders as one JSON parameter, which is what the 100 bound parameters allowed when each took a story and either a hash or a failure, which established the batch size. Each image hash now also carries its integer prefix. JSON can also say null, which a bound parameter here can't, and its SQL is one constant string. At its worst, 49 failures at 2,000 characters, the parameter is about 100 KB of ASCII, and hasn't run on real D1. **Finding a decision by its image.** A decision's primary key starts with its commit, so a lookup by story and image needs `decisions_by_image`. With no statistics SQLite picks the primary key anyway, by environment alone, and calling that a `SEARCH` hides it from a check for scans. At 100,000 decisions a page of 500 renders took 2,080 ms that way and 0.8 ms with the index named, in one local run, and 0.7 ms at 499,800. `ANALYZE` also fixes the plan, but nothing runs it. Real D1 hasn't run `INDEXED BY`, so its plan there is unproven. -**Request size.** A 10,000 render batch is 205 statements and 1.27 MB with 30 character story IDs, against the store's 2,000 statement batch (`store.rationale.md` → D1 REST adapter). 400 statements is a judgment call inside what was measured. A failure-heavy request grows with the 2,000 character limit, and at its worst, 400 statements of 49 failures at that length, would be about 39 MB. That size was not tested. +Many decisions on one image have a different cost. With 1,000 decisions on the same story and image across commits, the named-baseline query took 69 ms for one changed render. A prototype ordering the index by decision time, verdict and commit after the existing lookup columns, then selecting the first row, took 0.11 ms (seven-run local medians). Both returned the same decision on this fixture. Equal-time ordering across stores is a separate question ([Decisions](#decisions)). + +**Request size.** Before image lookups included their prefixes, a 10,000 render batch measured 205 statements and 1.27 MB with 30 character story IDs, against the store's 2,000 statement batch (`store.rationale.md` → D1 REST adapter). 400 statements is a judgment call inside what was measured. A failure-heavy request grows with the 2,000 character limit, and at its worst, 400 statements of 49 failures at that length, would be about 39 MB. That size was not tested. -**Page size.** Pages of 5,000 rows, at about 290 bytes a row and 1.44 MB a page, returned without trouble. No larger page was tested, and D1's docs state no limit on a response. +**Page size.** Pages of 5,000 rows, at about 290 bytes a row and 1.44 MB a page, returned without trouble. Cloudflare caps a query result at 50 MB. Render pages have a row limit, but `decisionsAt` and `compareReached` read the entire reached decision history before the application reduces it. In a local fixture, 5,000 stories approved at 70 commits produced 350,000 decisions with 66.1 MB of string values alone. Only 10,000 decisions survived the sync cutoff. [D1 limits](https://developers.cloudflare.com/d1/platform/limits/) **Schema on D1.** `WITHOUT ROWID`, `UPDATE ... FROM`, `WITH ... INSERT`, and `RETURNING` from an upsert all ran on real D1. @@ -111,7 +125,3 @@ D1's docs say a database runs one query at a time, so a batch this size holds up - **Writes.** D1 lists $1.00 per million rows written, so about $30 a month. It also lists the first 50 million a month as included on the paid plan, so a project this size alone pays nothing until others use up that allowance. - **Storage.** About 1.37 GB a month assumes about 46 bytes a row. Local SQLite measured 39 bytes a row by file growth with 30 character story IDs, which would be 1.17 GB a month and about 256 days to the limit. D1's own overhead was not measured. - **The limit.** D1's docs list 10 GB per database on the paid plan and 500 MB on the free plan, as checked 2026-11. On the free plan this rate reaches the limit in about 11 days. - -## Decisions - -**How two stores agree.** A decision is the only thing that two stores can hold differently, since images are named by their hash and a finished batch never changes. Latest wins, which needs no schema change, since each row already holds its time, actor, and decision. A tie has to come out the same in either order, so a rejection beats an approval, since that's the mistake that's cheaper to make. The author isn't compared: a decision's author can differ between stores, since the cloud names who pushed it, so comparing it could hand a decision to someone who only re-pushed it. Clocks can differ, which only matters if two people decide on one image within that difference. diff --git a/docs/specs/store.md b/docs/specs/store.md index 3d844c2..2284a3e 100644 --- a/docs/specs/store.md +++ b/docs/specs/store.md @@ -35,13 +35,13 @@ A WebP's alpha bit is only a hint, so a file with it clear may still hold alpha, ## Image keys -Source of truth: `store/src/core/store.ts`. +Source of truth: `store/src/core/hash-keys.ts` and `store/src/core/store.ts`. -- **Must assign the image's positive key when its hash truncated to the safe positive integer range is unclaimed.** The range is 1 to 2^53 − 1, and the truncated value is the hash's first 53 bits, read big-endian. +- **Must assign the image's positive key when its hash truncated to the safe positive integer range is unclaimed.** The range is 1 to 2^53 − 1, and the truncated value is the hash's first 53 bits, read big-endian (rationale). - **Must assign the next monotonic negative key, starting at −1, when the truncated value is claimed by a different image or is 0.** A negative key is what marks a collision; there is no separate collision table. - **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 compare the full image hash on every lookup**, so a colliding image never resolves to another image's 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). - **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. @@ -142,4 +142,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. Until then a change may only add tables and indexes, through `initStoreSchema`, with one exception made before any project database existed (`docs/specs/renders.md` → Schema). +- **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. diff --git a/docs/specs/store.rationale.md b/docs/specs/store.rationale.md index d30e893..24a6e0a 100644 --- a/docs/specs/store.rationale.md +++ b/docs/specs/store.rationale.md @@ -30,6 +30,12 @@ A color profile is why the chunk rule isn't only tidiness: it would change a has **The pixel limit.** 100,000,000 is a judgment call. +## Image keys + +The first 53 bits fit exactly in a JavaScript number. Separate stores usually assign the same positive key, but two images with the same prefix can arrive in opposite orders. Negative keys let both stores keep both images. Only the full SHA-256 travels between them. The built Storybook table uses the same allocator with its own key space. + +**Cost of the full-hash index.** Each positive key already locates the row that can confirm a hash. Bulk reads send each hash with its prefix. An insert checks that row for a conflicting hash, so a retry can use the same primary key. With 100,000 distinct SHA-256 values, local SQLite used 16.10 MB after compaction with `UNIQUE(hash)` and 8.07 MB with only the integer primary key. Inserting the hashes in one transaction took 448 ms and 247 ms, respectively. Checking that all images were present in groups of 1,000 took 36 ms and 33 ms. These are five-run medians on an in-memory database using the old and new store statements with prepared inputs. They exclude JSON construction, blob I/O and network time. Hosted D1 timings for this layout are still open. + ## Storage **Format in the bytes, not in a column.** PNG, WebP, and JPEG XL all open with a fixed signature, so reading the first bytes needs no schema change and can't drift from what's stored. A column would need a migration ([Open questions](store.md#open-questions)), and a suffix on the blob key would make `has` check every format. diff --git a/store/src/core/built-storybooks.ts b/store/src/core/built-storybooks.ts index 7ecd0b3..3275af6 100644 --- a/store/src/core/built-storybooks.ts +++ b/store/src/core/built-storybooks.ts @@ -3,15 +3,15 @@ // bytes, and a file goes from upload to a browser as it's kept. See docs/specs/store.md -> Built Storybooks. import type { Blobs } from "./blob.ts"; import { gunzip, gzip } from "./gzip.ts"; -import { insertHashKeyStatement } from "./hash-keys.ts"; -import { assertImageHash, fromHex, isImageHash, sha256, toHex, truncateHash } from "./image-hash.ts"; +import { insertHashKeyStatement, lookupHashKeyStatement } from "./hash-keys.ts"; +import { assertImageHash, isImageHash, sha256, toHex } from "./image-hash.ts"; import type { Sql } from "./sql.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. `CREATE TABLE IF NOT EXISTS built_storybooks ( key INTEGER PRIMARY KEY, - hash TEXT NOT NULL UNIQUE + hash TEXT NOT NULL )`, ]; @@ -44,8 +44,8 @@ export class BuiltStorybooks { /** Whether every file of this built Storybook is here, from the table alone. Never true of one that's only partly written. */ async has(build: string): Promise { assertImageHash(build); - const rows = await this.#sql.run({ sql: "SELECT 1 AS found FROM built_storybooks WHERE hash = ?1", params: [build], idempotent: true }); - return rows.length > 0; + const [row] = await this.#sql.run(lookupHashKeyStatement("built_storybooks", build)); + return row?.key != null; } /** Keeps a file, gzipped, if it isn't here already, and says what to call it: the hash of its bytes as built. */ @@ -92,7 +92,7 @@ export class BuiltStorybooks { const manifest: StorybookManifest = Object.fromEntries(files.map(({ path, fileHash }) => [path, fileHash])); await this.#blob.put(manifestBlobKey(build), new TextEncoder().encode(JSON.stringify(manifest))); } - await this.#sql.run(insertHashKeyStatement("built_storybooks", build, truncateHash(fromHex(build)))); + await this.#sql.run(insertHashKeyStatement("built_storybooks", build)); } /** @@ -126,9 +126,11 @@ export class BuiltStorybooks { /** Says which kept built Storybook rendered a batch. Refuses a batch or a built Storybook this store doesn't hold. */ async recordBatchStorybook(batchId: string, build: string): Promise { assertImageHash(build); + const lookup = lookupHashKeyStatement("built_storybooks", build); const rows = await this.#sql.run({ - sql: "UPDATE render_batches SET storybook_key = s.key FROM built_storybooks s WHERE s.hash = ?2 AND render_batches.id = ?1 RETURNING id", - params: [batchId, build], + 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`, + params: [...lookup.params, batchId], idempotent: true, }); if (rows.length === 0) throw new RangeError(`This store doesn't hold both batch ${batchId} and built Storybook ${build}`); diff --git a/store/src/core/hash-keys.ts b/store/src/core/hash-keys.ts index 61cfd09..4b09f93 100644 --- a/store/src/core/hash-keys.ts +++ b/store/src/core/hash-keys.ts @@ -1,39 +1,63 @@ import { chunks, STATEMENTS_PER_REQUEST } from "./chunks.ts"; +import { truncateHexHash } from "./image-hash.ts"; import type { Sql, SqlStatement } from "./sql.ts"; // As one bound parameter. const HASHES_PER_STATEMENT = 1_000; -/** - * Gives a hash its key in `images` or `built_storybooks`: its truncated value, or if that's taken, or - * 0, the next negative key. One statement, so concurrent inserts of the same or colliding hashes cannot - * interleave. The CASTs make a string parameter behave like a number: without them a string '0' gets - * key 0. Numbered parameters because D1 does not support named ones. Idempotent: a second batch hits - * ON CONFLICT and returns the key the first assigned. See `docs/specs/store.md` -> Image keys. - * - * A future delete must handle this: the next negative key is derived from the lowest key present, so - * deleting the row holding it would let that key be reused. - */ -export const insertHashKeyStatement = (table: "images" | "built_storybooks", hash: string, truncated: number): SqlStatement => ({ - sql: `INSERT INTO ${table}(key, hash) -SELECT CASE WHEN CAST(?1 AS INTEGER) = 0 OR EXISTS(SELECT 1 FROM ${table} WHERE key = CAST(?1 AS INTEGER)) - THEN (SELECT MIN(COALESCE(MIN(key), 0), 0) - 1 FROM ${table}) - ELSE CAST(?1 AS INTEGER) END, ?2 -WHERE true -ON CONFLICT(hash) DO UPDATE SET hash = excluded.hash +type HashTable = "images" | "built_storybooks"; + +// The caller joins the row at the hash prefix as 'candidate'. Only an occupied prefix or zero +// 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 + WHEN candidate.key IS NOT NULL OR ${prefix} = 0 THEN + (SELECT collision.key FROM ${table} collision WHERE collision.key < 0 AND collision.hash = ${hash}) + END`; +} + +export function lookupHashKeyStatement(table: HashTable, hash: string) { + return { + sql: `SELECT ${resolvedHashKey(table, "?2", "CAST(?1 AS INTEGER)")} AS key +FROM (SELECT 1) LEFT JOIN ${table} candidate ON candidate.key = ?1`, + params: [truncateHexHash(hash), hash], + idempotent: true, + } satisfies SqlStatement; +} + +/** Choose and claim the key in one statement. A replay returns the same positive or negative key. */ +export function insertHashKeyStatement(table: HashTable, hash: string): SqlStatement { + const prefix = "CAST(?1 AS INTEGER)"; + 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 + ) 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) +ON CONFLICT(key) DO UPDATE SET hash = excluded.hash RETURNING key`, - params: [truncated, hash], - idempotent: true, -}); + params: [truncateHexHash(hash), hash], + idempotent: true, + }; +} + +export function imageKeysStatement(hashes: readonly string[], missingOnly = false): SqlStatement { + const key = resolvedHashKey("images", "j.key", "j.value"); + return { + sql: `SELECT j.key AS hash${missingOnly ? "" : `, ${key} AS key`} +FROM json_each(?1) j LEFT JOIN images candidate ON candidate.key = j.value +${missingOnly ? `WHERE (${key}) IS NULL` : ""}`, + params: [JSON.stringify(Object.fromEntries(hashes.map((hash) => [hash, truncateHexHash(hash)])))], + idempotent: true, + }; +} /** Which of these images this store doesn't hold, each once, in the order given. */ export async function missingImages(sql: Sql, hashes: readonly string[]): Promise { const distinct = [...new Set(hashes)]; - const statements = chunks(distinct, HASHES_PER_STATEMENT).map((group) => ({ - sql: "SELECT j.value AS hash FROM json_each(?1) j LEFT JOIN images i ON i.hash = j.value WHERE i.key IS NULL", - params: [JSON.stringify(group)], - idempotent: true, - })); + const statements = chunks(distinct, HASHES_PER_STATEMENT).map((group) => imageKeysStatement(group, true)); const missing = new Set(); for (const request of chunks(statements, STATEMENTS_PER_REQUEST)) { for (const rows of await sql.batch(request)) for (const row of rows) missing.add(row.hash as string); diff --git a/store/src/core/image-hash.ts b/store/src/core/image-hash.ts index 188ae64..c3c47ef 100644 --- a/store/src/core/image-hash.ts +++ b/store/src/core/image-hash.ts @@ -22,6 +22,11 @@ export function truncateHash(digest: Uint8Array): number { return value * 32 + (digest[6]! >>> 3); } +/** The same 53-bit prefix from hex: 13 whole digits, then the high bit of the next digit. */ +export function truncateHexHash(hash: string): number { + return Number.parseInt(hash.slice(0, 13), 16) * 2 + (Number.parseInt(hash[13]!, 16) >>> 3); +} + export function toHex(digest: Uint8Array): string { let hex = ""; for (const byte of digest) { diff --git a/store/src/core/render-batches.ts b/store/src/core/render-batches.ts index 32abe95..903a2de 100644 --- a/store/src/core/render-batches.ts +++ b/store/src/core/render-batches.ts @@ -1,6 +1,6 @@ import { chunks, STATEMENTS_PER_REQUEST } from "./chunks.ts"; -import { missingImages } from "./hash-keys.ts"; -import { assertImageHash } from "./image-hash.ts"; +import { missingImages, resolvedHashKey } from "./hash-keys.ts"; +import { assertImageHash, truncateHexHash } from "./image-hash.ts"; import type { Sql, SqlRow, SqlStatement } from "./sql.ts"; /** @@ -12,7 +12,8 @@ import type { Sql, SqlRow, SqlStatement } from "./sql.ts"; 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 commits (key INTEGER PRIMARY KEY, sha TEXT NOT NULL UNIQUE)", + "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 render_batches ( key INTEGER PRIMARY KEY, @@ -55,7 +56,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_id TEXT NOT NULL, + 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`, "CREATE INDEX IF NOT EXISTS decisions_by_image ON decisions(environment_key, story_key, image_key)", @@ -93,14 +94,14 @@ export const isBatchId = (value: string) => BATCH_ID.test(value); const MAX_REACHED_COMMITS = 1_000; // Subqueries rather than joins, since a `RETURNING` can't join. -const BATCH_COLUMNS = `id, (SELECT sha FROM commits WHERE key = commit_key) AS git_sha, +const BATCH_COLUMNS = `id, (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`; const SELECT_BATCH = `SELECT ${BATCH_COLUMNS} FROM render_batches WHERE id = ?1`; const BATCH_KEY = "(SELECT key FROM render_batches WHERE id = ?1)"; -const commitKey = (sha: string) => `(SELECT key FROM commits WHERE sha = ${sha})`; +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. @@ -192,7 +193,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, d.batch_id, c.sha AS git_sha`; +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 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`; @@ -200,7 +201,7 @@ LEFT JOIN images i ON i.key = d.image_key`; // 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. const DECISIONS_AT = `${PLACED_DECISION} FROM json_each(?2) j -CROSS JOIN commits c ON c.sha = j.value +CROSS JOIN commits c ON c.sha_bytes = unhex(j.value) CROSS JOIN decisions d ON d.environment_key = ${environmentKey("?1")} AND d.commit_key = c.key ${NAMES_OF_DECISION}`; @@ -258,7 +259,7 @@ const AGAINST_BASE_REACHED = Object.fromEntries( ) as ReturnType; // A commit this store has never heard of has no batch to leave out, and no key, which no commit is given as 0. -const BASE_AMONG = newestOfBranchWhere("?1", environmentKey("?2"), `COALESCE(${commitKey("?3")}, 0)`, "SELECT c.key FROM json_each(?4) j CROSS JOIN commits c ON c.sha = j.value"); +const BASE_AMONG = newestOfBranchWhere("?1", environmentKey("?2"), `COALESCE(${commitKey("?3")}, 0)`, "SELECT c.key FROM json_each(?4) j CROSS JOIN commits c ON c.sha_bytes = unhex(j.value)"); // ?2 names the baseline: a batch for `AGAINST_BATCH`, and the default branch for `AGAINST_BASE_REACHED`. const comparedPage = (against: ReturnType, batchId: string, baseline: string, after: string, includeUnchanged: boolean): SqlStatement => ({ @@ -274,7 +275,7 @@ const removedPage = (against: ReturnType, batchId: string, const rendersPage = (batchId: string, after: string): SqlStatement => ({ sql: READ_RENDERS_PAGE, params: [batchId, after, ROWS_PER_PAGE], idempotent: true }); -const COMMITS_OF_BRANCH = `SELECT DISTINCT c.sha AS git_sha FROM render_batches r JOIN commits c ON c.key = r.commit_key +const COMMITS_OF_BRANCH = `SELECT DISTINCT lower(hex(c.sha_bytes)) AS git_sha FROM render_batches r JOIN commits c ON c.key = r.commit_key WHERE r.branch = ?1 AND r.environment_key = ${environmentKey("?2")} AND r.started_at BETWEEN CAST(?3 AS INTEGER) AND CAST(?4 AS INTEGER)`; const COUNT_RENDERS = `SELECT COUNT(*) AS total FROM renders @@ -288,38 +289,39 @@ const jsonRows = (parameter: string, columns: readonly string[]) => `v(${columns // A row with a hash the images table lacks, or a finished batch, matches nothing, so the // statement returns too few rows, which is how `recordRenders` knows. -const RECORD_RENDERS = `WITH ${jsonRows("?2", ["story", "image_hash", "failure", "viewport_width", "viewport_height"])} +const RECORD_RENDERS = `WITH ${jsonRows("?2", ["story", "image_hash", "image_prefix", "failure", "viewport_width", "viewport_height"])} INSERT INTO renders(batch_key, story_key, image_key, failure, viewport_width, viewport_height) -SELECT r.key, s.key, i.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 i ON i.hash = v.image_hash -WHERE r.id = ?1 AND r.finished_at IS NULL AND (v.image_hash IS NULL OR i.key IS NOT NULL) +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) 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 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", "sha", "rejected", "decided_at", "actor", "batch_id"])} -INSERT INTO decisions(environment_key, commit_key, story_key, image_key, rejected, decided_at, actor_key, batch_id) -SELECT ${environmentKey("?1")}, c.key, s.key, COALESCE(i.key, 0), v.rejected, v.decided_at, a.key, v.batch_id +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, '-') FROM v -CROSS JOIN commits c ON c.sha = v.sha +CROSS JOIN commits c ON c.sha_bytes = unhex(v.sha) CROSS JOIN stories s ON s.id = v.story CROSS JOIN actors a ON a.name = v.actor -LEFT JOIN images i ON i.hash = v.image_hash +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_id = excluded.batch_id`; + rejected = excluded.rejected, decided_at = excluded.decided_at, actor_key = excluded.actor_key, batch_uuid = excluded.batch_uuid`; const MERGE_DECISION = `${UPSERT_DECISION} WHERE (excluded.decided_at, excluded.rejected) > (decisions.decided_at, decisions.rejected)`; -const NAME_COLUMNS = { environments: "id", stories: "id", commits: "sha", actors: "name" } as const; +const NAME_COLUMNS = { environments: "id", stories: "id", commits: "sha_bytes", actors: "name" } as const; /** Gives these their keys, if they have none. Safe to send again, and writes nothing for a name already here. */ function nameStatements(table: keyof typeof NAME_COLUMNS, names: readonly string[]): SqlStatement[] { const column = NAME_COLUMNS[table]; + const value = table === "commits" ? "unhex(value)" : "value"; return chunks([...new Set(names)], NAMES_PER_STATEMENT).map((group) => ({ - sql: `INSERT INTO ${table}(${column}) SELECT value FROM json_each(?1) WHERE true ON CONFLICT(${column}) DO NOTHING`, + sql: `INSERT INTO ${table}(${column}) SELECT ${value} FROM json_each(?1) WHERE true ON CONFLICT(${column}) DO NOTHING`, params: [JSON.stringify(group)], idempotent: true, })); @@ -792,8 +794,8 @@ ORDER BY started_at DESC, key DESC`, ...chunks(edges, NAMES_PER_STATEMENT).map((group) => ({ sql: `INSERT INTO commit_parents(commit_key, parent_key) SELECT c.key, p.key FROM json_each(?1) j -CROSS JOIN commits c ON c.sha = json_extract(j.value, '$[0]') -CROSS JOIN commits p ON p.sha = json_extract(j.value, '$[1]') +CROSS JOIN commits c ON c.sha_bytes = unhex(json_extract(j.value, '$[0]')) +CROSS JOIN commits p ON p.sha_bytes = unhex(json_extract(j.value, '$[1]')) WHERE true ON CONFLICT(commit_key, parent_key) DO NOTHING`, params: [JSON.stringify(group)], idempotent: true, @@ -872,7 +874,10 @@ WHERE true ON CONFLICT(commit_key, parent_key) DO NOTHING`, ...nameStatements("stories", decisions.map(({ story }) => story)), ...chunks(decisions, DECISIONS_PER_STATEMENT).map((group) => ({ sql: upsert, - params: [environment, JSON.stringify(group.map(({ story, imageHash, gitSha, decision, at, actor, batchId }) => [story, imageHash, gitSha, decision === "rejected" ? 1 : 0, at, actor, batchId]))], + params: [environment, JSON.stringify(group.map(({ story, imageHash, gitSha, decision, at, actor, batchId }) => [ + story, imageHash, imageHash === null ? null : truncateHexHash(imageHash), + gitSha, decision === "rejected" ? 1 : 0, at, actor, batchId, + ]))], idempotent: true, })), ]; @@ -945,7 +950,10 @@ function recordStatements(batchId: string, renders: readonly RecordedRender[]): ...chunks(renders, RENDERS_PER_STATEMENT).map((group) => ({ statement: { sql: RECORD_RENDERS, - params: [batchId, JSON.stringify(group.map(({ story, imageHash, failure, viewport }) => [story, imageHash ?? null, failure === undefined ? null : cleanMessage(failure), viewport?.width ?? null, viewport?.height ?? null]))], + params: [batchId, JSON.stringify(group.map(({ story, imageHash, failure, viewport }) => [ + story, imageHash ?? null, imageHash === undefined ? null : truncateHexHash(imageHash), + failure === undefined ? null : cleanMessage(failure), viewport?.width ?? null, viewport?.height ?? null, + ]))], idempotent: true, }, rows: group.length, @@ -997,17 +1005,21 @@ function toBatch(row: SqlRow): RenderBatch { }; } -// The same order as `DECISION_ON_RENDER` and the merge rule: latest first, then `rejected` before `approved`. +function uuidFromHex(hex: string): string { + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + const toPlacedDecision = (row: SqlRow): PlacedDecision => ({ story: row.story as string, imageHash: row.image_hash as string | null, decision: row.decision as DecisionKind, actor: row.actor as string, at: row.decided_at as number, - batchId: row.batch_id as string, + batchId: uuidFromHex(row.batch_hex as string), 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); /** diff --git a/store/src/core/store.ts b/store/src/core/store.ts index 2082164..ab7316c 100644 --- a/store/src/core/store.ts +++ b/store/src/core/store.ts @@ -2,15 +2,13 @@ import type { Blobs } from "./blob.ts"; import { chunks, mapConcurrently } from "./chunks.ts"; import { assertImageHash, - fromHex, SHA256_BYTES, sha256, toHex, - truncateHash, type HashFunction, } from "./image-hash.ts"; import { checkImageFile, decodeImage, webpToKeep, type ImageCodec } from "./image-file.ts"; -import { insertHashKeyStatement, missingImages } from "./hash-keys.ts"; +import { imageKeysStatement, insertHashKeyStatement, lookupHashKeyStatement, missingImages } from "./hash-keys.ts"; import { encodePam, type RawImage } from "./pam.ts"; import { CREATE_BATCH_TABLES } from "./render-batches.ts"; import { CREATE_BUILT_STORYBOOK_TABLES } from "./built-storybooks.ts"; @@ -18,27 +16,18 @@ 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 UNIQUE + hash TEXT NOT NULL )`; -const SELECT_IMAGE_KEY = "SELECT key FROM images WHERE hash = ?1"; - -// Each group's lookup and each group's inserts are one request on D1, whose API limit -// every project shares. A group this size stays far inside what real D1 was measured -// to accept in one batch, and its lookup fits the limit of 100 bound parameters. +// Bound each group of blob writes and SQL inserts sent in one request. const IMAGES_PER_GROUP = 100; -const findKeysStatement = (hashes: readonly string[]): SqlStatement => ({ - sql: `SELECT key, hash FROM images WHERE hash IN (${hashes.map((_, i) => `?${i + 1}`).join(", ")})`, - params: hashes, - idempotent: true, -}); // Encoding is most of a first review. Each one holds a whole image, so this also bounds memory. const BLOBS_AT_ONCE = 4; -/** The insert statement for one image, given its hash and its truncated hash. */ -export function imageInsertStatement(hash: string, truncated: number): SqlStatement { - return insertHashKeyStatement("images", hash, truncated); +/** The insert statement for one image, given its full hash. */ +export function imageInsertStatement(hash: string): SqlStatement { + return insertHashKeyStatement("images", hash); } /** @@ -107,7 +96,7 @@ export class ReceivingStore { // Bytes first, as ever, so a row always means the bytes exist. const blobKey = imageBlobKey(hash); if (!(await this.blob.has(blobKey))) await this.blob.put(blobKey, file); - const [row] = await this.sql.run(imageInsertStatement(hash, truncateHash(fromHex(hash)))); + const [row] = await this.sql.run(imageInsertStatement(hash)); return { hash, key: checkedKey(row?.key) }; } @@ -120,14 +109,8 @@ export class ReceivingStore { /** This store's key for an image hash, or null if the image is not stored. */ async lookupKey(hash: string): Promise { assertImageHash(hash); - // By the full hash, never by truncated value: a colliding image must not - // resolve to the key of the image that claimed that value first. - const [row] = await this.sql.run({ - sql: SELECT_IMAGE_KEY, - params: [hash], - idempotent: true, - }); - return row === undefined ? null : (row.key as number); + const [row] = await this.sql.run(lookupHashKeyStatement("images", hash)); + return row?.key == null ? null : checkedKey(row.key); } /** @@ -184,13 +167,13 @@ export class Store extends ReceivingStore { async #putGroup(files: readonly Uint8Array[], expectedHash?: string): Promise { const hashes: string[] = []; - const firstByHash = new Map(); + const firstByHash = new Map(); for (const file of files) { const digest = await this.#digestOf(file); const hash = toHex(digest); if (expectedHash !== undefined && hash !== expectedHash) throw new ImageHashMismatchError(hash, expectedHash); hashes.push(hash); - if (!firstByHash.has(hash)) firstByHash.set(hash, { file, digest }); + if (!firstByHash.has(hash)) firstByHash.set(hash, file); } // A row means the bytes exist, since they are always written first. @@ -198,14 +181,12 @@ export class Store extends ReceivingStore { const missing = [...firstByHash].filter(([hash]) => !keys.has(hash)); // Bytes first: a failure here or later can orphan bytes, but can never leave a row without them. - await mapConcurrently(missing, BLOBS_AT_ONCE, async ([hash, { file }]) => { + await mapConcurrently(missing, BLOBS_AT_ONCE, async ([hash, file]) => { const blobKey = imageBlobKey(hash); if (!(await this.blob.has(blobKey))) await this.blob.put(blobKey, await this.#fileToKeep(file, hash)); }); if (missing.length > 0) { - const statements = missing.map(([hash, { digest }]) => - imageInsertStatement(hash, truncateHash(digest)), - ); + const statements = missing.map(([hash]) => imageInsertStatement(hash)); const results = await this.sql.batch(statements); results.forEach((rows, i) => keys.set(missing[i]![0], checkedKey(rows[0]?.key))); } @@ -230,8 +211,8 @@ export class Store extends ReceivingStore { /** The key of each of these distinct hashes that has a row. */ async #findKeys(hashes: readonly string[]): Promise> { - const rows = await this.sql.run(findKeysStatement(hashes)); - return new Map(rows.map((row) => [row.hash as string, checkedKey(row.key)])); + const rows = await this.sql.run(imageKeysStatement(hashes)); + return new Map(rows.filter((row) => row.key !== null).map((row) => [row.hash as string, checkedKey(row.key)])); } /** diff --git a/store/test/approvals-from-history.test.ts b/store/test/approvals-from-history.test.ts index 27bf3bf..3df306e 100644 --- a/store/test/approvals-from-history.test.ts +++ b/store/test/approvals-from-history.test.ts @@ -159,7 +159,7 @@ describe("on a store", () => { const finished = async (gitSha: string, stories: Record) => { const entries = Object.entries(stories); const hashes = entries.map(([, image]) => hashOf(image)); - await temp.sql.batch(entries.map(([, image]) => imageInsertStatement(hashOf(image), image))); + await temp.sql.batch(entries.map(([, image]) => imageInsertStatement(hashOf(image)))); const batch = await batches.beginBatch({ gitSha, environment: ENV, scale: 1, viewport: { width: 1200, height: 900 }, dirty: false, branch: "topic" }); await batches.recordRenders(batch.id, entries.map(([story], at) => ({ story, imageHash: hashes[at]! }))); await batches.finishBatch(batch.id, entries.length); @@ -198,7 +198,7 @@ describe("on a store", () => { const [BASE, FEATURE, MERGE, LATER, FOLLOWUP] = ["a".repeat(40), "b".repeat(40), "c".repeat(40), "d".repeat(40), "f".repeat(40)] as const; const on = async (gitSha: string, branch: string, stories: Record) => { const entries = Object.entries(stories); - await temp.sql.batch(entries.map(([, image]) => imageInsertStatement(hashOf(image), image))); + await temp.sql.batch(entries.map(([, image]) => imageInsertStatement(hashOf(image)))); const batch = await batches.beginBatch({ gitSha, environment: ENV, scale: 1, viewport: { width: 1200, height: 900 }, dirty: false, branch }); await batches.recordRenders(batch.id, entries.map(([story, image]) => ({ story, imageHash: hashOf(image) }))); await batches.finishBatch(batch.id, entries.length); diff --git a/store/test/built-storybooks.test.ts b/store/test/built-storybooks.test.ts index 03a4d39..c9d31f5 100644 --- a/store/test/built-storybooks.test.ts +++ b/store/test/built-storybooks.test.ts @@ -117,6 +117,8 @@ describe("BuiltStorybooks", () => { await keep(colliding, { "index.html": "two" }); expect(await keyOf(first)).toBe(truncateHash(fromHex(first))); expect(await keyOf(colliding)).toBe(-1); + await builds.recordBatchStorybook(batch, colliding); + expect(await builds.storybookOfBatch(batch)).toBe(colliding); await keep(first, { "index.html": "again" }); expect(await keyOf(first)).toBe(truncateHash(fromHex(first))); }); diff --git a/store/test/contract/render-batches-contract.ts b/store/test/contract/render-batches-contract.ts index 5a2ffe0..26fd977 100644 --- a/store/test/contract/render-batches-contract.ts +++ b/store/test/contract/render-batches-contract.ts @@ -82,7 +82,7 @@ export function describeBatchContract( batches = new RenderBatches({ sql }); await initStoreSchema(sql); await sql.batch( - Array.from({ length: 12 }, (_, i) => imageInsertStatement(hashOf(i + 1), 1000 + i)), + Array.from({ length: 12 }, (_, i) => imageInsertStatement(hashOf(i + 1))), ); const first = await batches.beginBatch({ gitSha: SHA_0, environment: "shared", scale: 1, viewport: { width: 1200, height: 900 }, dirty: false, }); @@ -123,6 +123,35 @@ export function describeBatchContract( await database?.destroy(); }); + it("keeps Git SHAs as 20 or 32 bytes and returns full lowercase hex", async () => { + const short = "00abcdef".repeat(5); + const long = short + "fedcba".repeat(4); + await batches.recordCommits([{ sha: long, parents: [short] }]); + const options = { environment: "binary-shas", scale: 1, viewport: { width: 800, height: 600 }, dirty: false }; + for (const gitSha of [short, long]) { + const batch = await batches.beginBatch({ ...options, gitSha }); + expect((await batches.finishBatch(batch.id, 0)).gitSha).toBe(gitSha); + expect((await batches.batchesAt(gitSha, options.environment)).map(({ id }) => id)).toEqual([batch.id]); + } + const sql = new Sql(withParamMode(database.connect(), mode)); + expect(await sql.run({ + sql: "SELECT typeof(sha_bytes) AS kind, length(sha_bytes) AS bytes FROM commits WHERE sha_bytes IN (unhex(?1), unhex(?2)) ORDER BY bytes", + params: [short, long], + })).toEqual([{ kind: "blob", bytes: 20 }, { kind: "blob", bytes: 32 }]); + expect((await batches.batchesReaching(short, options.environment, 1)).map(({ gitSha }) => gitSha)).toEqual([long]); + }); + + 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 }; + await batches.mergeDecisions("binary-uuid", [placed]); + const sql = new Sql(withParamMode(database.connect(), mode)); + expect(await sql.run({ + sql: "SELECT typeof(batch_uuid) AS kind, hex(batch_uuid) AS bytes FROM decisions WHERE environment_key = (SELECT key FROM environments WHERE id = 'binary-uuid')", + })).toEqual([{ kind: "blob", bytes: "00112233445566778899AABBCCDDEEFF" }]); + expect(await batches.decisionsAt("binary-uuid", [ON.gitSha])).toEqual([placed]); + }); + it("gives each difference its state, and counts what is unchanged", async () => { const { batch, renders: compared, unchangedCount } = await batches.compareWithBatch(headBatch, baseline); expect(batch).toMatchObject({ status: "failed", failedCount: 1 }); diff --git a/store/test/contract/sql-contract.ts b/store/test/contract/sql-contract.ts index b2b169e..26a74d1 100644 --- a/store/test/contract/sql-contract.ts +++ b/store/test/contract/sql-contract.ts @@ -10,7 +10,6 @@ import { hashOf, insertedKey, withParamMode, - type ImageRow, type ParamMode, } from "../support/sql-params.ts"; @@ -23,7 +22,7 @@ export interface SqlTestDatabase { * each workload's keys in order. The factory must make the statements really * overlap and prove it, since these tests pass trivially if they run in turn. */ - insertConcurrently(workloads: ImageRow[][], mode: ParamMode): Promise; + insertConcurrently(workloads: string[][], mode: ParamMode): Promise; destroy(): Promise; } @@ -41,11 +40,11 @@ export function describeSqlContract(name: string, factory: SqlAdapterFactory): v let sql: Sql; const connect = async () => new Sql(withParamMode(await database.connect(), mode)); - const insert = async (row: ImageRow) => { - return insertedKey(await sql.run(imageInsertStatement(row.hash, row.truncated))); + 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 insertConcurrently = (workloads: ImageRow[][]) => + const insertConcurrently = (workloads: string[][]) => database.insertConcurrently(workloads, mode); beforeEach(async () => { @@ -160,68 +159,67 @@ export function describeSqlContract(name: string, factory: SqlAdapterFactory): v describe("image insert", () => { it("assigns the truncated value as the key when it is unclaimed", async () => { - expect(await insert({ hash: hashOf(1), truncated: 12345 })).toBe(12345); + expect(await insert(hashOf(1, 12345))).toBe(12345); }); it("accepts both ends of the positive range", async () => { - expect(await insert({ hash: hashOf(1), truncated: 1 })).toBe(1); - expect(await insert({ hash: hashOf(2), truncated: MAX_KEY })).toBe(MAX_KEY); + expect(await insert(hashOf(1, 1))).toBe(1); + expect(await insert(hashOf(2, MAX_KEY))).toBe(MAX_KEY); }); it("stores the key as an integer and the hash as text", async () => { - await insert({ hash: hashOf(1), truncated: 7 }); + 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" }]); }); it("assigns monotonic negative keys from -1 when the value is claimed", async () => { - expect(await insert({ hash: hashOf(1), truncated: 500 })).toBe(500); - expect(await insert({ hash: hashOf(2), truncated: 500 })).toBe(-1); - expect(await insert({ hash: hashOf(3), truncated: 500 })).toBe(-2); + expect(await insert(hashOf(1, 500))).toBe(500); + expect(await insert(hashOf(2, 500))).toBe(-1); + expect(await insert(hashOf(3, 500))).toBe(-2); }); it("assigns a negative key when the truncated value is 0", async () => { - expect(await insert({ hash: hashOf(1), truncated: 0 })).toBe(-1); - expect(await insert({ hash: hashOf(2), truncated: 0 })).toBe(-2); + expect(await insert(hashOf(1, 0))).toBe(-1); + expect(await insert(hashOf(2, 0))).toBe(-2); const keys = await sql.run({ sql: "SELECT key FROM images WHERE key = 0" }); expect(keys).toEqual([]); }); it("shares one negative sequence across different collisions", async () => { - await insert({ hash: hashOf(1), truncated: 10 }); - await insert({ hash: hashOf(2), truncated: 20 }); - expect(await insert({ hash: hashOf(3), truncated: 10 })).toBe(-1); - expect(await insert({ hash: hashOf(4), truncated: 20 })).toBe(-2); - expect(await insert({ hash: hashOf(5), truncated: 0 })).toBe(-3); + await insert(hashOf(1, 10)); + await insert(hashOf(2, 20)); + expect(await insert(hashOf(3, 10))).toBe(-1); + expect(await insert(hashOf(4, 20))).toBe(-2); + expect(await insert(hashOf(5, 0))).toBe(-3); }); it("returns the existing key on reinsert, positive or negative", async () => { - await insert({ hash: hashOf(1), truncated: 500 }); - await insert({ hash: hashOf(2), truncated: 500 }); - await insert({ hash: hashOf(3), truncated: 0 }); - expect(await insert({ hash: hashOf(1), truncated: 500 })).toBe(500); - expect(await insert({ hash: hashOf(2), truncated: 500 })).toBe(-1); - expect(await insert({ hash: hashOf(3), truncated: 0 })).toBe(-2); + await insert(hashOf(1, 500)); + await insert(hashOf(2, 500)); + await insert(hashOf(3, 0)); + expect(await insert(hashOf(1, 500))).toBe(500); + expect(await insert(hashOf(2, 500))).toBe(-1); + expect(await insert(hashOf(3, 0))).toBe(-2); expect(await allRows()).toHaveLength(3); }); it("does not spend a negative key on a reinsert", async () => { - await insert({ hash: hashOf(1), truncated: 500 }); - await insert({ hash: hashOf(2), truncated: 500 }); - await insert({ hash: hashOf(2), truncated: 500 }); - expect(await insert({ hash: hashOf(3), truncated: 500 })).toBe(-2); + await insert(hashOf(1, 500)); + await insert(hashOf(2, 500)); + await insert(hashOf(2, 500)); + expect(await insert(hashOf(3, 500))).toBe(-2); }); - it("returns the existing key whatever truncated value arrives with the hash", async () => { - expect(await insert({ hash: hashOf(1), truncated: 500 })).toBe(500); - expect(await insert({ hash: hashOf(2), truncated: 600 })).toBe(600); - expect(await insert({ hash: hashOf(1), truncated: 600 })).toBe(500); + it("stores images and built Storybooks without a secondary index", async () => { + expect(await sql.run({ sql: "PRAGMA index_list(images)" })).toEqual([]); + expect(await sql.run({ sql: "PRAGMA index_list(built_storybooks)" })).toEqual([]); }); it("sees rows written by another connection", async () => { const other = await connect(); - expect(insertedKey(await other.run(imageInsertStatement(hashOf(1), 500)))).toBe(500); - expect(await insert({ hash: hashOf(2), truncated: 500 })).toBe(-1); + expect(insertedKey(await other.run(imageInsertStatement(hashOf(1, 500))))).toBe(500); + expect(await insert(hashOf(2, 500))).toBe(-1); }); }); @@ -240,14 +238,14 @@ export function describeSqlContract(name: string, factory: SqlAdapterFactory): v }; /** Every worker got one key per image, and the table holds exactly those. */ - const expectOneKeyPerImage = async (workloads: ImageRow[][], results: number[][]) => { + const expectOneKeyPerImage = async (workloads: string[][], results: number[][]) => { const keyOf = new Map(); workloads.forEach((rows, w) => { - rows.forEach((row, i) => { + rows.forEach((hash, i) => { const key = results[w]?.[i]; if (key === undefined) throw new Error("Missing key"); - if (keyOf.has(row.hash)) expect(key).toBe(keyOf.get(row.hash)); - keyOf.set(row.hash, key); + if (keyOf.has(hash)) expect(key).toBe(keyOf.get(hash)); + keyOf.set(hash, key); }); }); const stored = await allRows(); @@ -258,15 +256,15 @@ export function describeSqlContract(name: string, factory: SqlAdapterFactory): v it("gives every connection the same key for the same image", async () => { const workloads = Array.from({ length: WORKERS }, () => - Array.from({ length: 50 }, () => ({ hash: hashOf(1), truncated: 500 })), + Array.from({ length: 50 }, () => hashOf(1, 500)), ); const results = await insertConcurrently(workloads); const keyOf = await expectOneKeyPerImage(workloads, results); - expect(keyOf.get(hashOf(1))).toBe(500); + expect(keyOf.get(hashOf(1, 500))).toBe(500); }); it("gives colliding images one positive key and gapless negative keys", async () => { - const images = Array.from({ length: 50 }, (_, i) => ({ hash: hashOf(i + 1), truncated: 500 })); + const images = Array.from({ length: 50 }, (_, i) => hashOf(i + 1, 500)); const workloads = Array.from({ length: WORKERS }, (_, w) => shuffled(images, w + 1)); const results = await insertConcurrently(workloads); const keyOf = await expectOneKeyPerImage(workloads, results); @@ -275,7 +273,7 @@ export function describeSqlContract(name: string, factory: SqlAdapterFactory): v }); it("gives images with truncated value 0 only negative keys", async () => { - const images = Array.from({ length: 20 }, (_, i) => ({ hash: hashOf(i + 1), truncated: 0 })); + const images = Array.from({ length: 20 }, (_, i) => hashOf(i + 1, 0)); const workloads = Array.from({ length: WORKERS }, (_, w) => shuffled(images, w + 1)); const results = await insertConcurrently(workloads); const keyOf = await expectOneKeyPerImage(workloads, results); @@ -285,11 +283,7 @@ export function describeSqlContract(name: string, factory: SqlAdapterFactory): v }); it("handles a mix of distinct, colliding, and repeated images", async () => { - const images = Array.from({ length: 200 }, (_, i) => ({ - hash: hashOf(i + 1), - // Every value is shared by up to four images, so most inserts contend on a claim. - truncated: 1000 + Math.floor(i / 4), - })); + const images = Array.from({ length: 200 }, (_, i) => hashOf(i + 1, 1000 + Math.floor(i / 4))); const workloads = Array.from({ length: WORKERS }, (_, w) => shuffled(images, w + 1)); const results = await insertConcurrently(workloads); const keyOf = await expectOneKeyPerImage(workloads, results); diff --git a/store/test/d1-rest.real.test.ts b/store/test/d1-rest.real.test.ts index 0135eb2..b5e0622 100644 --- a/store/test/d1-rest.real.test.ts +++ b/store/test/d1-rest.real.test.ts @@ -9,7 +9,7 @@ import { describeSqlContract } from "./contract/sql-contract.ts"; import type { D1Harness } from "./support/d1-harness.ts"; import { d1Harness } from "./support/real-d1.ts"; import { pngOf } from "./support/png-builder.ts"; -import { hashOf, insertedKey, withParamMode, type ImageRow } from "./support/sql-params.ts"; +import { hashOf, insertedKey, withParamMode } from "./support/sql-params.ts"; import { createTempStore } from "./support/temp-store.ts"; import { sharpCodec } from "../src/adapters/sharp-codec.ts"; @@ -44,13 +44,13 @@ describe.skipIf(!ENABLED)("real D1 (opt-in: pnpm test:d1)", () => { insertConcurrently: async (workloads, mode) => { const { result, peak } = await measureOverlap(() => Promise.all( - workloads.map(async (rows: ImageRow[]) => { + workloads.map(async (rows: string[]) => { const sql = new Sql(withParamMode(connect(), mode)); const keys: number[] = []; for (let i = 0; i < rows.length; i += INSERTS_PER_REQUEST) { const chunk = rows.slice(i, i + INSERTS_PER_REQUEST); const batch = await sql.batch( - chunk.map((row) => imageInsertStatement(row.hash, row.truncated)), + chunk.map(imageInsertStatement), ); keys.push(...batch.map((rows) => insertedKey(rows))); } @@ -84,14 +84,14 @@ describe.skipIf(!ENABLED)("real D1 (opt-in: pnpm test:d1)", () => { const WORKERS = 4; const PER_WORKER = 5; const owners = new Map(); - await new Sql(harness.connect()).run(imageInsertStatement(hashOf(1), 500)); + await new Sql(harness.connect()).run(imageInsertStatement(hashOf(1, 500))); const { peak } = await harness.measureOverlap(async () => { await Promise.all( Array.from({ length: WORKERS }, async (_, worker) => { const sql = new Sql(harness.connect()); for (let i = 0; i < PER_WORKER; i++) { - const statement = imageInsertStatement(hashOf(100 * (worker + 1) + i), 500); + const statement = imageInsertStatement(hashOf(100 * (worker + 1) + i, 500)); owners.set(insertedKey(await sql.run(statement)), worker); } }), @@ -116,7 +116,7 @@ describe.skipIf(!ENABLED)("real D1 (opt-in: pnpm test:d1)", () => { return response; }), ); - const rows = await sql.run(imageInsertStatement(hashOf(1), 500)); + const rows = await sql.run(imageInsertStatement(hashOf(1, 500))); expect(insertedKey(rows)).toBe(500); expect(lost).toBe(2); const stored = await new Sql(harness.connect()).run({ sql: "SELECT key FROM images" }); diff --git a/store/test/d1-rest.test.ts b/store/test/d1-rest.test.ts index c472488..d5a41cc 100644 --- a/store/test/d1-rest.test.ts +++ b/store/test/d1-rest.test.ts @@ -353,7 +353,6 @@ describe("D1RestAdapter replay against a real SQL engine", () => { async function losingResponses(shouldLose: (request: number) => boolean) { temp = await createTempStore(); const engine = temp.connect(); - const sent: SqlStatement[] = []; let requests = 0; const adapter = new D1RestAdapter({ accountId: "a", @@ -362,38 +361,37 @@ describe("D1RestAdapter replay against a real SQL engine", () => { sleep: async () => {}, fetch: async (_, init) => { const { batch } = JSON.parse(String(init?.body)) as { batch: SqlStatement[] }; - sent.push(...batch); const rows = await engine.batch(batch); if (shouldLose(requests++)) throw new TypeError("fetch failed"); return ok(...rows); }, }); - return { sql: new Sql(adapter), sent, requests: () => requests }; + return { sql: new Sql(adapter), requests: () => requests }; } it("keeps one key and spends no negative key when an image insert is replayed", async () => { const { sql, requests } = await losingResponses((request) => request < 2); - expect(await sql.run(imageInsertStatement(hashOf(1), 500))).toEqual([{ key: 500 }]); + expect(await sql.run(imageInsertStatement(hashOf(1, 500)))).toEqual([{ key: 500 }]); expect(requests()).toBe(3); - expect(await sql.run(imageInsertStatement(hashOf(2), 500))).toEqual([{ key: -1 }]); - expect(await sql.run(imageInsertStatement(hashOf(3), 500))).toEqual([{ key: -2 }]); + expect(await sql.run(imageInsertStatement(hashOf(2, 500)))).toEqual([{ key: -1 }]); + expect(await sql.run(imageInsertStatement(hashOf(3, 500)))).toEqual([{ key: -2 }]); }); it("marks everything the store sends as idempotent, so a lost response never fails it", async () => { // Every first try of each statement loses its response. - const { sql, sent } = await losingResponses((request) => request % 2 === 0); + const { sql, requests } = await losingResponses((request) => request % 2 === 0); await initStoreSchema(sql); 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); - // Twice each: the schema's 14 statements, and the put's lookup, insert, and lookup. - expect(sent).toHaveLength(34); + // Schema setup, the put's lookup and insert, and the final lookup each replay once. + expect(requests()).toBe(8); }); it("resends everything the render model sends, so a lost response never fails it", async () => { const { sql } = await losingResponses((request) => request % 2 === 0); await initStoreSchema(sql); - await sql.run(imageInsertStatement(hashOf(1), 500)); + await sql.run(imageInsertStatement(hashOf(1))); const batches = new RenderBatches({ sql }); const environment = "env"; const gitSha = "a".repeat(40); diff --git a/store/test/render-batches.test.ts b/store/test/render-batches.test.ts index d5e2b2d..c6e52a6 100644 --- a/store/test/render-batches.test.ts +++ b/store/test/render-batches.test.ts @@ -108,7 +108,7 @@ describe("RenderBatches", () => { sql = new Sql(adapter); clock = 1_000; batches = new RenderBatches({ sql, now: () => clock++ }); - await sql.batch(Array.from({ length: 40 }, (_, i) => imageInsertStatement(hashOf(i + 1), i + 1))); + await sql.batch(Array.from({ length: 40 }, (_, i) => imageInsertStatement(hashOf(i + 1)))); }); afterEach(async () => { @@ -494,9 +494,9 @@ describe("RenderBatches", () => { }); it("compares images with colliding truncated hashes by their full hash", async () => { - const a = hashOf(50_001); - const b = hashOf(50_002); - await sql.batch([imageInsertStatement(a, 500), imageInsertStatement(b, 500)]); + const a = hashOf(50_001, 500); + const b = hashOf(50_002, 500); + await sql.batch([imageInsertStatement(a), imageInsertStatement(b)]); const baseline = await recordBatch(SHA_A, [{ story: "x", imageHash: a }]); const head = await recordBatch(SHA_B, [{ story: "x", imageHash: b }]); expect(await statesOf(head.id, baseline.id)).toEqual({ x: "changed" }); @@ -564,6 +564,16 @@ 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("adds its tables to a store that holds only images, and can run again", async () => { const elsewhere = await createTempStore(); try { @@ -572,7 +582,7 @@ describe("RenderBatches", () => { sql: `DROP TABLE ${table}`, })), ); - await elsewhere.sql.run(imageInsertStatement(hashOf(1), 1)); + await elsewhere.sql.run(imageInsertStatement(hashOf(1))); await initStoreSchema(elsewhere.sql); await initStoreSchema(elsewhere.sql); const model = new RenderBatches({ sql: elsewhere.sql }); @@ -676,7 +686,7 @@ describe("RenderBatches", () => { it("refuses a row whose batch or image isn't here, as D1 does", async () => { const sql = new Sql(adapter); 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_id) VALUES (424242, 424242, 424242, 0, 0, 1, 424242, 'x')" })).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 }]; await sql.run({ sql: "INSERT INTO stories(id) VALUES ('never-rendered')" }); diff --git a/store/test/sqlite.test.ts b/store/test/sqlite.test.ts index 1f05acd..f4e495e 100644 --- a/store/test/sqlite.test.ts +++ b/store/test/sqlite.test.ts @@ -17,10 +17,7 @@ describe("SqliteAdapter across threads", () => { // Guards the contract's concurrency tests: they prove nothing unless the // workers are really running at the same time. it("runs the workers' inserts at the same time", async () => { - const images = Array.from({ length: 300 }, (_, i) => ({ - hash: hashOf(i + 1), - truncated: 500, - })); + const images = Array.from({ length: 300 }, (_, i) => hashOf(i + 1, 500)); const outputs = await runInsertWorkers(temp.path, [images, images, images, images], "number"); const latestStart = Math.max(...outputs.map((output) => output.startedAt)); const earliestFinish = Math.min(...outputs.map((output) => output.finishedAt)); diff --git a/store/test/store.test.ts b/store/test/store.test.ts index d4a719f..716f00f 100644 --- a/store/test/store.test.ts +++ b/store/test/store.test.ts @@ -4,6 +4,8 @@ import { Blobs, encodePam, ImageDecodeError, + imageInsertStatement, + type SqlStatement, Sql, sha256, ImageHashMismatchError, @@ -41,7 +43,7 @@ describe("Store", () => { const failingInserts = () => new Sql({ execute: (statements) => - statements[0]!.sql.startsWith("SELECT") + !statements[0]!.sql.startsWith("INSERT") ? Promise.resolve([[]]) : Promise.reject(new Error("sql down")), }); @@ -205,10 +207,7 @@ describe("Store", () => { it("reports a row with no bytes rather than treating it as absent", async () => { const store = newStore(); const hash = "ab".repeat(32); - await temp.sql.run({ - sql: "INSERT INTO images(key, hash) VALUES (CAST(?1 AS INTEGER), ?2)", - params: [5, hash], - }); + await temp.sql.run(imageInsertStatement(hash)); await expect(store.getImage(hash)).rejects.toThrow("no bytes"); }); }); @@ -242,8 +241,8 @@ describe("Store", () => { codec: sharpCodec, sql: new Sql({ execute: async (statements) => { - if (statements[0]!.sql.startsWith("SELECT")) { - requests.push(`lookup ${statements[0]!.params!.length}`); + if (!statements[0]!.sql.startsWith("INSERT")) { + requests.push(`lookup ${Object.keys(JSON.parse(String(statements[0]!.params![0]))).length}`); return [[]]; } requests.push(`insert ${statements.length}`); @@ -296,10 +295,10 @@ describe("Store", () => { }); it("looks up only what's new, and inserts a repeat once", async () => { - const seen: { sql: string; params: number }[] = []; + const seen: SqlStatement[] = []; const counting = new Sql({ execute: (statements) => { - seen.push(...statements.map(({ sql, params = [] }) => ({ sql, params: params.length }))); + seen.push(...statements); return temp.connect().batch(statements); }, }); @@ -309,8 +308,9 @@ describe("Store", () => { const stored = await store.putImages([file(1), file(2), file(2)]); expect(stored[0]).toEqual(first); expect(stored[1]).toEqual(stored[2]); - expect(seen.map(({ sql }) => sql.slice(0, 6))).toEqual(["SELECT", "INSERT"]); - expect(seen[0]!.params).toBe(2); + expect(seen).toHaveLength(2); + expect(Object.keys(JSON.parse(String(seen[0]!.params![0])))).toHaveLength(2); + expect(seen[1]!.sql).toMatch(/^INSERT INTO images/); }); it("decodes a whole group before writing any of it", async () => { @@ -421,6 +421,13 @@ describe("Store", () => { expect(await store.missingImages([])).toEqual([]); }); + it("confirms all hashes when several share a positive or zero prefix", async () => { + const store = storeWith({ 1: 500, 2: 500, 3: 0 }); + const [first, collision, zero] = await store.putImages([file(1), file(2), file(3)]); + const absent = [first!.hash, zero!.hash].map((hash) => hash.slice(0, -2) + "ff"); + expect(await store.missingImages([collision!.hash, absent[0]!, first!.hash, zero!.hash, absent[1]!])).toEqual(absent); + }); + it("refuses what isn't a hash", async () => { await expect(storeWith({}).missingImages(["nope"])).rejects.toThrow(); }); diff --git a/store/test/support/sql-params.ts b/store/test/support/sql-params.ts index 66bfa2b..36d183c 100644 --- a/store/test/support/sql-params.ts +++ b/store/test/support/sql-params.ts @@ -6,15 +6,9 @@ import type { SqlAdapter, SqlRow } from "../../src/core/index.ts"; */ export type ParamMode = "number" | "string"; -/** One row to insert into `images`: an image's hash, and that hash truncated to 53 bits. */ -export interface ImageRow { - readonly hash: string; - readonly truncated: number; -} - -/** A valid image hash, distinct for each number. */ -export function hashOf(n: number): string { - return n.toString(16).padStart(64, "0"); +/** A valid SHA-256 with a chosen 53-bit prefix and a distinct suffix. */ +export function hashOf(n: number, prefix = n): string { + return ((BigInt(prefix) << 203n) | BigInt(n)).toString(16).padStart(64, "0"); } /** The key from an image insert's rows. Throws rather than asserts, since worker threads use this too. */ diff --git a/store/test/support/sqlite-insert-worker.ts b/store/test/support/sqlite-insert-worker.ts index 733b7d0..7f4005e 100644 --- a/store/test/support/sqlite-insert-worker.ts +++ b/store/test/support/sqlite-insert-worker.ts @@ -23,8 +23,8 @@ if (Atomics.add(gate, 0, 1) + 1 === parties) { const startedAt = performance.timeOrigin + performance.now(); const keys: number[] = []; -for (const row of rows) { - keys.push(insertedKey(await sql.run(imageInsertStatement(row.hash, row.truncated)))); +for (const hash of rows) { + keys.push(insertedKey(await sql.run(imageInsertStatement(hash)))); } const finishedAt = performance.timeOrigin + performance.now(); diff --git a/store/test/support/sqlite-workers.ts b/store/test/support/sqlite-workers.ts index c2749d1..4556b54 100644 --- a/store/test/support/sqlite-workers.ts +++ b/store/test/support/sqlite-workers.ts @@ -1,9 +1,9 @@ import { Worker } from "node:worker_threads"; -import type { ImageRow, ParamMode } from "./sql-params.ts"; +import type { ParamMode } from "./sql-params.ts"; export interface WorkerInput { readonly path: string; - readonly rows: readonly ImageRow[]; + readonly rows: readonly string[]; readonly mode: ParamMode; readonly parties: number; readonly barrier: SharedArrayBuffer; @@ -18,7 +18,7 @@ export interface WorkerOutput { /** Runs each workload on its own thread and connection, starting them together. */ export function runInsertWorkers( path: string, - workloads: readonly (readonly ImageRow[])[], + workloads: readonly (readonly string[])[], mode: ParamMode, ): Promise { const barrier = new SharedArrayBuffer(4); diff --git a/ui/test/workerd/sync.workerd.test.ts b/ui/test/workerd/sync.workerd.test.ts index 1770b42..96c1ae8 100644 --- a/ui/test/workerd/sync.workerd.test.ts +++ b/ui/test/workerd/sync.workerd.test.ts @@ -11,7 +11,7 @@ import { createSyncApi, type SyncAccess } from "../../src/server/sync.ts"; const ON = { batchId: "00000000-0000-4000-8000-000000000001", gitSha: "e".repeat(40) }; const SHA = "a".repeat(40); -const NEXT_SHA = "b".repeat(40); +const NEXT_SHA = "00abcdef".repeat(8); const ENV = "container-linux-arm64-0123456789abcdef"; const FIRST = "11111111-1111-4111-8111-111111111111"; const SECOND = "22222222-2222-4222-8222-222222222222";