From b4b39327a91e4ddd0317d24416d3e8fd11f1b3a4 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 00:32:46 +1300 Subject: [PATCH 1/2] Storage design for the rebuild: texts by hash, page rows only for changes, groups sourced from one holder, server-side dedupe, and the efficiency checklist (sc-8868, sc-8890) --- docs/design-storage.md | 306 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 306 insertions(+) create mode 100644 docs/design-storage.md diff --git a/docs/design-storage.md b/docs/design-storage.md new file mode 100644 index 00000000..1bf129ce --- /dev/null +++ b/docs/design-storage.md @@ -0,0 +1,306 @@ +# Storage design + +How VisualCI stores builds, snapshots, pages and text, written for the rebuild on a fresh database. It doesn't depend on +a framework. It comes from sc-8868 part 2 and sc-8890: a build of a large suite rewrote every snapshot and page row +whether or not anything changed. The unfinished Loco version is on the `storage-rebuild` branch (not merged). Its +`server/migration/src/schema.sql` is a working DDL for everything below. + +## Numbers that motivated it + +Production, 3 Dec 2026, before the change: + +| Table | Rows | Size | +| -------------- | ------ | ------- | +| snapshot_pages | 49,554 | 62.2 MB | +| snapshots | 55,123 | 34.6 MB | + +- docspring/visualci alone: 176 builds and 47,755 snapshot rows, about 271 a build, nearly all unchanged. +- Page text stored inline: 119 MiB raw, compressed with Postgres's default pglz. +- The development database: 75% of page rows belonged to unchanged snapshots, with 1.7 KB of text a row. + +Nathan's questions: "for a build with zero changes and ~4000 images, can we just skip writing 4000 rows to the db?" and +"if 1 out of 4000 images changes we write the other 3999 unchanged rows as well? why do that?" + +## Principles + +1. **Content is stored once, by hash.** Files and images are blobs keyed by SHA-256, as before. Page text joins them: + one `texts` row per distinct text. +2. **A build stores only what differs from its baselines.** Rows are written for changes. Unchanged content is + referenced, never copied. +3. **The server decides what's unchanged**, from its own rows, never from a client's word. It deduplicates every + build, whichever client sent it. +4. **Readers see a whole build.** One read path (a view) gives every snapshot of a build, its own and referenced, so + baselines, review, the gallery and the API never handle references themselves. +5. **References are one hop.** A build points straight at the build that holds the rows, never at a build that points + on further. + +## Tables + +### texts + +```sql +CREATE TABLE texts ( + sha256 text PRIMARY KEY, + body text NOT NULL, -- COMPRESSION lz4 + created_at timestamptz NOT NULL DEFAULT now() +); +``` + +- **Writes:** `INSERT … SELECT * FROM UNNEST($1::text[], $2::text[]) ON CONFLICT DO NOTHING`, batched. +- **Who references it:** + - each page row's `head_text_sha` and `base_text_sha`; + - each render page's `text_sha` in `renders.pages`. The renderer still posts plain `text`, and the server stores it + and keeps only the hash. +- **Garbage collection:** a text is deleted only when it is older than 24 hours and nothing references it. The grace + period covers a build that stored a text and hasn't yet written the row that points at it. + +### snapshots + +Same columns as now, plus: + +- `group_key text NOT NULL DEFAULT ''`: the group the snapshot's name falls in. It is set at registration with the + build's grouping (`visualci_core::manifest::Grouping`: the client's `group_depth`, else all but the last two path + segments). +- `sourced boolean NOT NULL DEFAULT false`: always false in the table, true only on view rows read from another build + (see below). The model gets the flag without a second type. +- Index: `(build_id, group_key)`. + +### snapshot_pages + +A row per page is stored **only when the comparison found something**: +- an added snapshot; +- a change; +- a page within the threshold, accepted as a variant or ignored; +- pages that moved, were inserted or were removed. + +A snapshot whose every page is unchanged, in order, with the same image and text (`plain_unchanged`) stores no page +rows. + +Text columns are `head_text_sha` and `base_text_sha`, pointing at `texts`. + +Readers never query the table directly. One function, `pages_of(snapshots[], with_text)`, works in batches: + +1. It loads stored rows, and their texts, for the snapshots that have them. +2. For an unchanged or sourced snapshot it builds the pages from the snapshot itself: + - a document's render pages; + - an image's blob; + - a text snapshot's blob, normalized with its build's ignore rules, as the comparison saw it. + Each built page is `op = state = 'unchanged'`, with both sides the same. +3. A sourced snapshot's stored rows are never used: they are the holder build's comparison, not this one's. + +The build page goes through this one batched call, instead of two queries per snapshot. + +### build_groups + +```sql +CREATE TABLE build_groups ( + build_id bigint NOT NULL REFERENCES builds ON DELETE CASCADE, + key text NOT NULL, + hash text NOT NULL, + snapshot_count integer NOT NULL, + matched boolean, -- the client's group check; NULL for a group the server recorded itself + source_build_id bigint REFERENCES builds, -- the build holding this group's rows (no ON DELETE: retention keeps it) + shard integer, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (build_id, key) +); +CREATE INDEX ON build_groups (source_build_id) WHERE source_build_id IS NOT NULL; +``` + +- `matched` drives billing (one credit per matched group) and the UI's "29 of 30 groups unchanged since #8". +- `source_build_id` drives storage. +- These are separate: a client's group can match without one build holding all its baselines. Its rows are then + carried as before. + +### effective_snapshots (the view) + +```sql +CREATE VIEW effective_snapshots AS + SELECT s.*, … FROM snapshots s + UNION ALL + SELECT s.id, s.group_key, s.pid, g.build_id AS build_id, , + 'unchanged' AS state, s.id AS base_snapshot_id, NULL AS review, NULL AS error, + true AS carried_forward, NULL AS matched_environment, NULL AS baseline_id, + NULL AS matches_build_id, true AS sourced + FROM build_groups g + JOIN snapshots s ON s.build_id = g.source_build_id AND s.group_key = g.key + WHERE g.source_build_id IS NOT NULL AND s.platform <> 'visualci'; -- a build's config item is always its own +``` + +A sourced row is shown as what it is in this build: unchanged, compared with itself, not reviewed. The holder's state +and review must never appear in another build. Rules for code reading the view: + +- **Everything that lists a finished build's snapshots reads the view:** for-build lists, lookups by pid or name, + history across builds, flaky detection, and comment links. +- **Ownership checks look a pid up in the view by `(build_id, pid)`.** A sourced snapshot's pid and id are the + holder's, so a bare `find_by_pid` followed by `snapshot.build_id == build.id` is wrong. Remove that pattern. +- **Writes after a build finishes** (review flags, page actions such as "accept as variant" or "ignore") **refuse a + sourced snapshot**. Its rows belong to the holder. A sourced snapshot is unchanged, so there's never anything to act + on. +- **Baseline resolution reads the view.** An unchanged sourced row says its approved version is itself, which is the + holder's row, the same content. Base ids (`base_snapshot_id`, baseline `snapshot_id`) are always real row ids, so + they stay valid across references. +- **A check that a build or group resolves to zero rows**, run nightly, catches a broken reference. Add a test that + forbids direct reads of `snapshots` by build outside the processing code. + +## Processing a build + +1. **Register:** set `group_key`. A name sent twice with other content is a 409, as now. +2. **Check groups** (large suites, sc-8868): the server hashes the baseline's groups from its own rows and records + `matched` per group. +3. **Carried groups, sourced before writing anything:** + - Which groups: every group the client's check matched (or all of them after a whole-manifest match), and every + group a subset build didn't send. + - When a single earlier build holds all of a group's baselines (`holders` below), record + `build_groups.source_build_id` and write no snapshot rows. A manifest-matched build of 4,000 images writes one + `build_groups` row per group and nothing else. + - Only groups without such a holder are copied as rows and compared, as before. +4. **Compare** what was sent. Page rows go in only for comparisons that found something. +5. **Before deduplicating, compute** what depends on the build's own rows: what to charge, and whether it sent + anything (the empty-build check). +6. **Deduplicate on the server** (CI builds only). A group qualifies when every own row in it: + - is `unchanged`; + - has no `matched_environment`; + - has the same content and settings as its baseline row (`same_content`: name, platform, kind, format, fingerprint, + render, engine, threshold, anti-aliasing, ignore rules, environment, meta). + + If one build holds all those baselines (`holders`), then in one transaction: record the source and delete the own + rows. This runs while the build is still processing, so no other build can be anchored on it and have taken those + row ids as its base. +7. **Conclude, record auto-approvals and charge.** + +`holders(groups → base ids)` is one SQL statement over the real rows. A group qualifies when: +- every baseline row exists, has the same `group_key`, and isn't the config item; +- they're all in one build; +- that build has no other row with that `group_key`; +- none of that build's rows in the group is pending, failed or removed. + +One hop is automatic: base ids are real row ids, and a real row lives in the build that holds it. + +Local builds aren't deduplicated. They are small, they expire after a week, and their unchanged rows carry +local-approval notes that a sourced row can't show. + +## Retention and garbage collection + +- Retention keeps every build a kept build sources from: add `build_groups.source_build_id` of kept builds to the kept + set, before snapshots, renders and blobs are kept from it. Without an `ON DELETE` on `source_build_id`, deleting a + held build fails instead of silently breaking its readers. +- Texts and blobs are deleted only when they are older than 24 hours and unreferenced. +- Decide in the rebuild whether builds, snapshots and pages ever expire. Today only renders and blobs do, so row counts + grow without limit. If they will, partition `snapshots` and `snapshot_pages` from the start: by build id or by time. + +## Efficiency checklist for the new schema + +From a code audit on 3 Dec 2026. "Now" means it belongs in the first schema; the rest can follow. + +The intended check was EXPLAIN on a seeded project of 4k snapshots × 100 builds, and **it wasn't run before the plan +changed**. Run it on the rebuild's schema: the baseline resolution query, the build page, the waiting lists, and +retention. + +### Indexes (now) + +- **Foreign-key columns** (every delete of a parent scans the child without one): + - `snapshots(render_id | source_blob | base_snapshot_id | baseline_id | matches_build_id)`, partial `WHERE … IS NOT + NULL`; + - `snapshot_pages(diff_id)`; + - `renders(source_blob)` and `diffs(overlay_blob)`; + - `baselines(snapshot_id)` and `baselines(build_id)`; + - `reviews(build_id, id DESC)`: the build page and every `build_json` read the latest reviews; + - `comment_threads(build_id)`; + - the three `builds` self-references: base, superseded-by, manifest-same-as. +- **Waiting for review and whoami:** `builds (project_id, id DESC) WHERE review_state = 'pending'`. +- **Active builds** (expiry, /status, idle local builds): `builds (state) WHERE state IN ('receiving','processing')`. +- **A pull request's builds** (PR comment, changeset): `builds (project_id, pr_number, id DESC) WHERE pr_number IS NOT + NULL`. +- **Build lists:** order by `number` to use `UNIQUE (project_id, number)`, and filter the branch in SQL + (`(project_id, branch, id DESC)`), never in application code after loading 1,000 builds. +- **Baselines** (the hottest lookups): + - `(project_id, build_name, name, platform, environment, branch, id DESC)`, for the current-row check, "approved + before", "approved elsewhere" (add a `build_name` condition there) and the fallback's `name = ANY`; + - `(project_id, build_name, branch, build_id)`, for "this branch's approvals since the anchor". + - Better, and worth deciding first: a **current-baselines table** keyed by (project, suite, name, platform, + environment, branch) and updated on approval. Every one of these queries currently rebuilds "the latest row per + key" from an append-only table. +- **Render queue fairness:** `renders (project_id) WHERE state = 'rendering'`. The claim query counts each project's + running renders per candidate. +- **Age scans:** BRIN on `created_at` for builds, blobs, renders and texts. + +### Ancestry + +- The CLI sends up to 100 parent SHAs (`git rev-list --max-count=100`). The server keeps at most 200 in + `builds.parent_commits text[]`. +- Lookups are `commit_sha = ANY(…)` against `(project_id, commit_sha)` indexes: at most about 200 index probes, never a + scan. +- That holds at thousands of builds. The costs are elsewhere: + - the anchor chain walk (up to 50 hops, each loading a whole build's snapshots); + - the baselines queries above. +- An ancestor more than 100 commits back is never found, and the anchor falls back to the default branch's latest + approved build. +- Keep this shape. `bytea` SHAs would halve the width but aren't needed. + +### Credit ledger + +- Builds are charged per charge step: one row each time the charged total grows (each compare, each processing run, + finish). It is never charged per snapshot. + - Better: one row per build and kind, updated as the total grows. + - Now: add a `build_id` column (`ON DELETE SET NULL`) in place of the build named in `reference` text. +- **Gallery serves write one ledger row per image request.** Roll them up per (organization, project, day). The + table's design must allow that from the start. +- Usage history reads the newest 50 rows with no pagination. Use keyset pagination on `(organization_id, id DESC)`. +- The monthly sums run under a row lock on the organization and use `(organization_id, created_at)`. + +### Job queue + +- Loco's Postgres queue (`pg_loco_queue`) isn't in our schema. Finished jobs are never cleaned up (retention isn't + configured). +- There is no unique or debounced enqueueing: + - each build change enqueues three jobs (check, gallery purge, PR comment); + - each finished render enqueues a processing job for every build waiting on it, so a build of 1,000 PDFs gets about + 1,000 jobs, serialized by an advisory lock. +- The rebuild's queue needs: + - indexes on state and run_at; + - cleanup of finished jobs; + - unique jobs per (kind, build); + - per-organization fairness, so one huge build can't starve everyone else. The render queue already has + per-project fairness. +- The render wake-up query scans `snapshots` twice: by `render_id`, and by `source_fingerprint` across the project. + Use the render's `project_id` and the `render_id` index. + +### Caches keyed by content + +- **Renders:** `(project_id, source_fingerprint, renderer)`, where the renderer key holds the engine, DPI and version. + Deliberately per project: the fingerprint is the client's word, and another account's render under it must never be + compared. Page text moves to `texts`. +- **Diffs:** `(base_image, head_image, options_key)`, global, with the result as JSON. `result` duplicates + `changed_pixels`, `changed_fraction` and `size_changed`, which are also columns: keep one copy. +- **Contact sheets** are composed from full-size images on every call. Cache thumbnails or tiles by image hash. + +### Row width + +- **Per snapshot:** two 64-character hex hashes, a uuid, and `ignore_rules` written as + `{"json_paths":[],"text_patterns":[]}` even when empty. Store empty rules and `meta` as `{}` or NULL, and change the + manifest entry's normalization in the same step: the group hash includes the rules. +- **Per build, stored once:** `config`, `environment_info`, `stats`, `charged`, `warnings`, `parent_commits`. Don't + repeat them per snapshot. +- After sourcing, unchanged snapshots cost no rows at all, which outweighs any column-level saving. + +### Measurement + +- The only Prometheus endpoint is the renderer's. +- **Add:** + - rows and bytes per build (snapshot rows, page rows, sourced groups); + - database size by table; + - queue depth and finished-job count. +- **Alert** when rows per build or a table's growth rate jumps. +- Record, before and after a change like this one, rows and MB per build and processing time, for docspring/visualci + and the demo. + +### GitHub API use + +- Every build change enqueues a check-run update and a PR comment update. Each mints a new installation token (no + caching) and then posts or patches. The PR comment skips when its body hash is unchanged; the check run never does. +- **Bound it:** + - cache installation tokens for their hour; + - store the check run's last body hash and skip identical updates; + - debounce both per build with unique jobs. + That keeps a PR's updates proportional to real changes, not to review clicks and renders. From 563a961e9790d37f282278fd1903f853f4bbb5b8 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 02:09:00 +1300 Subject: [PATCH 2/2] Storage design: the rebuild is on Laravel Rust with a fresh database; JSON arrays until db::Array ships; texts written with a multi-row insert; Laravel's database queue --- docs/design-storage.md | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/docs/design-storage.md b/docs/design-storage.md index 1bf129ce..ed8bcbc1 100644 --- a/docs/design-storage.md +++ b/docs/design-storage.md @@ -1,9 +1,11 @@ # Storage design -How VisualCI stores builds, snapshots, pages and text, written for the rebuild on a fresh database. It doesn't depend on -a framework. It comes from sc-8868 part 2 and sc-8890: a build of a large suite rewrote every snapshot and page row -whether or not anything changed. The unfinished Loco version is on the `storage-rebuild` branch (not merged). Its -`server/migration/src/schema.sql` is a working DDL for everything below. +How VisualCI stores builds, snapshots, pages and text. It comes from sc-8868 part 2 and sc-8890: a build of a large +suite rewrote every snapshot and page row whether or not anything changed. + +VisualCI's server is being rebuilt on Laravel Rust (sc-8900) on a fresh database. No old data is carried over except +the tokens agents and CI already use, seeded at cutover. The domain tables below are +`app/database/migrations/2026_12_03_000200_create_domain_tables.rs`. The design itself doesn't depend on a framework. ## Numbers that motivated it @@ -46,7 +48,7 @@ CREATE TABLE texts ( ); ``` -- **Writes:** `INSERT … SELECT * FROM UNNEST($1::text[], $2::text[]) ON CONFLICT DO NOTHING`, batched. +- **Writes:** one multi-row `INSERT … VALUES … ON CONFLICT DO NOTHING` per batch (`app/src/storage/texts.rs`). - **Who references it:** - each page row's `head_text_sha` and `base_text_sha`; - each render page's `text_sha` in `renders.pages`. The renderer still posts plain `text`, and the server stores it @@ -228,9 +230,12 @@ retention. ### Ancestry - The CLI sends up to 100 parent SHAs (`git rev-list --max-count=100`). The server keeps at most 200 in - `builds.parent_commits text[]`. -- Lookups are `commit_sha = ANY(…)` against `(project_id, commit_sha)` indexes: at most about 200 index probes, never a - scan. + `builds.parent_commits`. + - That column is `jsonb` for now: Laravel Rust 0.1.4 has no PostgreSQL array columns. It becomes `text[]` through + `db::Array` once laravel/rust-framework#527 is released. + - `reviews.snapshot_ids` and `builds.shards_finalized` are `jsonb` for the same reason. +- Lookups are `commit_sha IN (…)`, one bound parameter per SHA (`= ANY(…)` with `db::Array` later), against the + `(project_id, commit_sha)` indexes: at most about 200 index probes, never a scan. - That holds at thousands of builds. The costs are elsewhere: - the anchor chain walk (up to 50 hops, each loading a whole build's snapshots); - the baselines queries above. @@ -251,9 +256,10 @@ retention. ### Job queue -- Loco's Postgres queue (`pg_loco_queue`) isn't in our schema. Finished jobs are never cleaned up (retention isn't - configured). -- There is no unique or debounced enqueueing: +- Today, Loco's Postgres queue (`pg_loco_queue`) isn't in our schema, and finished jobs are never cleaned up + (retention isn't configured). In the rebuild, Laravel Rust's database queue keeps jobs in a `jobs` table and deletes + each job when it finishes. Its `#[job(debounce_for = …)]` covers the debounced updates below. +- Today there is no unique or debounced enqueueing: - each build change enqueues three jobs (check, gallery purge, PR comment); - each finished render enqueues a processing job for every build waiting on it, so a build of 1,000 PDFs gets about 1,000 jobs, serialized by an advisory lock.