Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions OPERATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ From a laptop, the same steps are `node ui/scripts/production.mjs preflight|depl

### Resetting a project store

The release with binary Git SHAs and decision batch UUIDs changes both D1 and the CLI's SQLite schema. To keep published batches and approvals, use a machine that still has their local store and the previous CLI.
The release that brought in schema versions (`docs/specs/renders.md` → Schema) changes both D1 and the CLI's SQLite schema: hashes, SHAs, and batch IDs held as bytes, and every table `STRICT`. A store from before it is refused until it's reset. To keep published batches and approvals, use a machine that still has their local store and the previous CLI.

1. Take the old Worker offline. Run the SQL below on each project D1 database, then deploy the new Worker. The reset discards batch history, decisions, and image and built Storybook metadata. The Worker recreates the tables on first use. The image and Storybook bytes in R2 can be reused.
1. Take the old Worker offline. Run the SQL below on each project D1 database, then deploy the new Worker. The reset discards batch history, decisions, the names they share, and image and built Storybook metadata. The Worker recreates the tables on first use. The image and Storybook bytes in R2 can be reused.
2. Once the new Worker is serving, use the **previous CLI and its intact local store** to run `selfie push <batch-id>` 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/<slug>/store.db` (default `~/.config/selfie/<slug>/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.

Expand All @@ -38,6 +38,10 @@ DROP TABLE IF EXISTS render_batches;
DROP TABLE IF EXISTS commits;
DROP TABLE IF EXISTS images;
DROP TABLE IF EXISTS built_storybooks;
DROP TABLE IF EXISTS environments;
DROP TABLE IF EXISTS stories;
DROP TABLE IF EXISTS actors;
DROP TABLE IF EXISTS schema_version;
```

The table reset preserves local notes and `render_keys`. Their old batch IDs may refer to discarded batches. Deleting the whole `store.db` also deletes the notes and render keys.
Expand Down
11 changes: 8 additions & 3 deletions cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { gitUserEmail, resolveCommit } from "./git.ts";
import { selfieHome } from "./paths.ts";
import { compareAsReviewed, openProject, type Project } from "./project.ts";
import { renderBatch, review, replyToNote, runBuild } from "./review.ts";
import { summarizeBatch } from "selfie-store";
import { StoreSchemaError, summarizeBatch } from "selfie-store";
import { pull, push, requireRemote, type Fetch } from "./sync.ts";
import { isNoteId, isNoteText, MAX_NOTE_CHARACTERS } from "selfie-ui/notes";
import { awaitFeedback, notesForAgent } from "./notes.ts";
Expand Down Expand Up @@ -155,8 +155,13 @@ async function withProject(context: Context, work: (project: Project) => Promise
}
} catch (error) {
// Nothing migrates a store yet: docs/specs/store.md -> Open questions.
if (/no such column|has no column named/.test((error as Error).message)) {
throw new SelfieError("old-store", `This project's store.db under ${selfieHome(context.env)} is from an older Selfie. For the binary Git SHA upgrade, follow https://github.com/diffplug/selfie/blob/main/OPERATIONS.md#resetting-a-project-store to preserve local notes and republish batches. If all local data is disposable, delete it and render again. (${(error as Error).message})`);
const where = `This project's store.db under ${selfieHome(context.env)}`;
if (error instanceof StoreSchemaError && error.newer) {
throw new SelfieError("newer-store", `${where} was set up by a newer Selfie. Update Selfie to use it. (${error.message})`);
}
// A missing column is one of the CLI's own tables from before a change to it.
if (error instanceof StoreSchemaError || /no such column|has no column named/.test((error as Error).message)) {
throw new SelfieError("old-store", `${where} is from an older Selfie. To keep its batches and notes, follow https://github.com/diffplug/selfie/blob/main/OPERATIONS.md#resetting-a-project-store. If all local data is disposable, delete it and render again. (${(error as Error).message})`);
}
throw error;
}
Expand Down
1 change: 1 addition & 0 deletions cli/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export type SelfieErrorCode =
| "bad-config"
| "no-config"
| "old-store"
| "newer-store"
| "build-failed"
| "no-stories"
| "head-moved"
Expand Down
16 changes: 14 additions & 2 deletions cli/test/commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,18 +212,30 @@ describe("a store from before a schema change", () => {
expect(json.error).toMatchObject({ code: "old-store", message: expect.stringContaining("delete it") });
});

test("points a text-SHA store to the reset that preserves local notes", async () => {
test("points a store from before schema versions to the reset that preserves local notes", async () => {
h.stories = [{ id: "a--one" }];
await review();
const [slug] = await readdir(h.home);
const db = new DatabaseSync(path.join(h.home, slug!, "store.db"));
db.exec("DROP INDEX commits_by_sha; ALTER TABLE commits RENAME COLUMN sha_bytes TO sha");
db.exec("DROP TABLE schema_version; DROP INDEX commits_by_sha; ALTER TABLE commits RENAME COLUMN sha_bytes TO sha");
db.close();
const { code, json } = await review();
expect(code).toBe(2);
expect(json.error).toMatchObject({ code: "old-store", message: expect.stringContaining("OPERATIONS.md#resetting-a-project-store") });
});

test("says to update Selfie for a store a newer one set up", async () => {
h.stories = [{ id: "a--one" }];
await review();
const [slug] = await readdir(h.home);
const db = new DatabaseSync(path.join(h.home, slug!, "store.db"));
db.exec("UPDATE schema_version SET version = version + 1");
db.close();
const { code, json } = await review();
expect(code).toBe(2);
expect(json.error).toMatchObject({ code: "newer-store", message: expect.stringContaining("Update Selfie") });
});

test("says so on opening one from before integer keys, which fails at making an index", async () => {
h.stories = [{ id: "a--one" }];
await review();
Expand Down
2 changes: 1 addition & 1 deletion docs/specs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ Source of truth: `cli/src/paths.ts`, `cli/src/project.ts`; tests in `cli/test/un
render/<uuid>/ One render's output, deleted when recording ends
```

- **Must report an incompatible store with a missing column as `old-store` and point to the reset instructions** (`OPERATIONS.md` → Resetting a project store).
- **Must report a store `initStoreSchema` refuses as older, or whose CLI tables lack a column, as `old-store`, and point to the reset instructions** (`OPERATIONS.md` → Resetting a project store). **Must report one it refuses as newer as `newer-store`, and say to update Selfie.**
- **Never read `<home>/d1.env`**, or anything else in `<home>` 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 `<home>`, 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.
Expand Down
13 changes: 9 additions & 4 deletions docs/specs/renders.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,10 @@ Source of truth: `RenderBatches.decide` in `store/src/core/render-batches.ts`.

A decision is an approval or a rejection, by an actor, at the time it is recorded.

- **Must record a decision against a render's name, an image hash or a removal, and the commit and batch it was made on.** A removal is a decision with no image, stored as an image key of 0, which [no image is ever given](store.md#image-keys). **Must store its originating batch UUID as 16 raw bytes and exchange it as a lowercase, hyphenated UUID** (rationale).
- **Must record a decision against a render's name, an image hash or a removal, and the commit and batch it was made on.** A removal is a decision with no image, stored as an image key of 0, which [no image is ever given](store.md#image-keys). Its batch is held as [any batch ID is](#schema).
- **Must keep one decision per name, hash, and commit, the one most recently recorded.** There is no history of replaced decisions.
- **Must merge decisions for the same name, image hash or removal, and commit by decision time, with rejection winning an equal-time tie.** When the incoming time and verdict both match, the stored decision keeps its actor and batch. Replaying a decision changes nothing (rationale).
- **Must merge decisions for the same name, image hash or removal, and commit by decision time, with rejection winning an equal-time tie, and then the greater batch ID.** When the incoming time, verdict, and batch all match, the stored decision keeps its actor. Replaying a decision changes nothing (rationale).
- **Must order every decision a comparison reads by that same rule, then by the greater commit SHA and image hash**, a total order, so two stores holding the same decisions read them alike, whatever order they were given them in (rationale).
- **Must refuse every decision in a request if any names an image this store doesn't hold**, with `unknown-image`, as a render already must, so a decision can hold the image's key (rationale). Sync sends a batch's images before its decisions (`docs/specs/sync.md` → Pushing and pulling).

## Approvals
Expand Down Expand Up @@ -127,12 +128,13 @@ What differs from what's approved isn't what a commit changed: a default branch
Source of truth: `CREATE_BATCH_TABLES` in `store/src/core/render-batches.ts`, `initStoreSchema` in `store/src/core/store.ts`.

```sql
schema_version(only PK = 1, version)
environments(key PK, id UNIQUE)
stories(key PK, id UNIQUE)
commits(key PK, sha_bytes BLOB)
UNIQUE INDEX commits_by_sha(sha_bytes)
actors(key PK, name UNIQUE)
render_batches(key PK, id UNIQUE, commit_key → commits.key, environment_key → environments.key, started_at, finished_at, failed_count, dirty, story_filter, reused_from_batch, scale, viewport_width, viewport_height, branch, storybook_key → built_storybooks.key)
render_batches(key PK, id BLOB UNIQUE, commit_key → commits.key, environment_key → environments.key, started_at, finished_at, failed_count, dirty, story_filter, reused_from_batch BLOB, scale, viewport_width, viewport_height, branch, storybook_key → built_storybooks.key)
INDEX batches_by_commit(commit_key, environment_key, started_at)
INDEX batches_by_branch(branch, environment_key, started_at)
renders(batch_key → render_batches.key, story_key → stories.key, image_key → images.key, failure, viewport_width, viewport_height) PK (batch_key, story_key) WITHOUT ROWID
Expand All @@ -142,9 +144,12 @@ commit_parents(commit_key → commits.key, parent_key → commits.key) PK (comm
INDEX commit_parents_by_parent(parent_key, commit_key)
```

- **Must declare every table `STRICT`**, so a value of the wrong type is refused rather than kept (rationale).
- **Must leave out the CLI's local table** (`docs/specs/cli.md` → Recording only if necessary): it's in a local `store.db`, not this schema, and D1 doesn't have it.
- **Must only add missing tables and indexes during setup**, in one request. A store holding only images can be opened. A store with the old text `commits.sha` column must fail setup and be recreated (rationale).
- **Must keep the store's schema version in `schema_version`, and check it before setting anything up**, in a request of its own: a store with none of these tables gets this version, `STORE_SCHEMA_VERSION`, and one at any other version, or with some of them and no version, is refused with `StoreSchemaError`, with nothing added but an empty `schema_version` (rationale).
- **Must then only add missing tables and indexes**, in one request.
- **Must store a Git commit SHA as its 20 SHA-1 bytes or 32 SHA-256 bytes, and exchange it as full lowercase hex.** (rationale)
- **Must store a batch ID as 16 bytes, and exchange it as a lowercase, hyphenated UUID**: a batch's own, the one it reused, and a decision's (rationale).
- **Must declare a foreign key wherever a row's parent is always written first and held here**, as `→` shows above, so a store refuses an orphan instead of holding one (rationale).
- **Never declare one on `decisions.image_key`, `decisions.batch_uuid`, or `reused_from_batch`**, since a key of 0 is a removal, a decision may name a batch this store doesn't hold, and sync may move a batch without the one it was reused from.
- **Must say in `render_batches.viewport_width` and `viewport_height` the window a batch's stories lay out in, in CSS pixels, and in those columns of `renders` only a story's own, if it differs**, both or neither, so a story with neither laid out in its batch's (`docs/specs/render.md` → A story's viewport). They only size a story running live, so a comparison never reads them (rationale). **A batch reusing another's images must hold the same sizes.**
Expand Down
10 changes: 7 additions & 3 deletions docs/specs/renders.rationale.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@

**Keeping no history.** A log of every decision would merge cleanly, but nothing in `selfie review` or the review UI reads one.

**Merging equal timestamps.** A rejection wins a tie with an approval so both stores report the same verdict. Later decisions still let someone change their mind, though clocks on different machines can put close decisions in the wrong order. Sync attributes an incoming decision to the authenticated writer, so the actor cannot break a tie consistently. Two approvals at the same time can still leave different batch IDs at different stores. That matters because a batch excludes its own approval when choosing its reference. Two reached approvals for different images can also tie. Reversing the supplied commit order in a local fixture changed the same render from unchanged to changed.
**Merging equal timestamps.** A rejection wins a tie with an approval so both stores report the same verdict. Later decisions still let someone change their mind, though clocks on different machines can put close decisions in the wrong order. Sync attributes an incoming decision to the authenticated writer, so the actor cannot break a tie consistently. Without more to compare, two approvals at the same time left different batch IDs at different stores, which matters because a batch excludes its own approval when choosing its reference, and two reached approvals for different images could tie, so that reversing the supplied commit order in a local fixture changed the same render from unchanged to changed. So the batch ID breaks a tie that time and verdict leave, and then, for decisions read together, the commit and the image: values every store holds alike, unlike its own keys. Which one wins doesn't matter, only that it's always the same one.

**Size of the batch ID.** A decision can arrive before its batch, so it needs a portable ID. Storing the UUID bytes saves 20 bytes of payload each time a batch ID repeats. On local SQLite 3.54.1, a compacted fixture with 20,000 SHA-1 commits and ten decisions per commit used 15.32 MB with text UUIDs and 11.20 MB with 16-byte UUIDs. Only the decision's batch ID representation varied. This measures storage. The cost of returning UUID text on reads is still open.

Expand Down Expand Up @@ -86,10 +86,14 @@

**Commit keys.** Parent edges repeat two keys, and batches and decisions also carry a commit key in their rows and indexes. In a separate fixture using hex digests, 20,000 commits, one batch and ten decisions per commit, and 19,999 parent edges, SQLite-assigned integer keys used 18.29 MB across the database. Using 53-bit digest prefixes with a full-hash check and no text index used 20.55 MB. Writing the referencing rows took 393 ms with assigned keys and 844 ms with prefixes (five-run local medians). Ancestry walks already compare integer keys.

The commit SHA index names the binary column explicitly. Setup on an older `commits` table fails at that index, before a writer can split one commit across text and binary rows. An images-only database has no commit table and gets the current schema.

**Composite primary keys.** A render page walks the stories of one batch, and a history lookup walks the decisions of one environment and commit. `WITHOUT ROWID` stores the rows in those primary-key trees, so a range scan can retrieve the row contents directly. The reverse index on `commit_parents` serves a different walk, from a commit to the descendants whose statuses may need updating.

**Batch IDs as bytes.** A decision's batch is smaller as bytes ([Size of the batch ID](#decisions)). A batch's own ID is in `render_batches` and again in its unique index, so it's held the same way, and one ID has one form wherever the store keeps it.

**A schema version, from the start.** Without one, a store set up by an older Selfie was found only by a statement failing on a column it lacked, which says nothing of what to do, and finds nothing if the change was to a column's type. D1 refuses `PRAGMA user_version`, so the version is a one-row table. A store that already had tables when versions came in can't be told apart from a damaged one, so it counts as older, which every store then was. The check is a request before setup's, since a request that fails partway would have set up some tables first.

**Strict tables.** SQLite otherwise keeps a value of any type in any column, so a hex SHA bound where bytes were meant, or a time sent as text, would be stored and then match nothing. `STRICT` can't be added to a table that exists, only by rebuilding it, so every table has it from the start. It ran in the workerd tests, on D1's engine.

**Foreign keys, before there's data.** Nothing in the store deletes yet, and every write already goes through a path that writes parents first, so these catch only bugs for now. What they're for is retention: once a batch can be deleted, they're what stop one going while something points at it. SQLite can't add a foreign key to an existing table, so waiting would mean rebuilding tables in a migration, where today it's an edit to their `CREATE` statements. Inserting 10,000 renders took 9 ms with checks and 8 ms without, in one local run. They haven't run on real D1, only on its engine in the Worker tests.

## Requests
Expand Down
Loading
Loading