Public: anyone can read this; the crew can change it.

Migrations are files with names: two pulls add two files and never collide #943

Closed opened this in answer to
Closed without merging

steward/783-named-migrations → main 4 commits

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +459 −53
docs/ARCHITECTURE.md +17 −8
@@ -146,10 +146,15 @@ curate, never implement.
146146
147147 ## Data & state model
148148
149 SQLite (`bun:sqlite`), WAL mode, foreign keys on, migrations tracked by a
150 hash of their text in `schema_migration` (`kernel/migrate.ts`), so a preview
151 that keeps its data across a rebase never runs one twice; `user_version`
152 still counts them. The schema is deliberately small — tables earn their place:
149 SQLite (`bun:sqlite`), WAL mode, foreign keys on. A migration is a file,
150 `src/core/migrations/<YYYY-MM-DD-slug>.sql` (#783): two pulls that each add
151 one add two files and never collide, and they apply in name order after the
152 closed legacy list in `core/schema.ts` (`legacy-001` to `legacy-070`).
153 Applied migrations are tracked by a hash of their text, with their name, in
154 `schema_migration` (`kernel/migrate.ts`), so a preview that keeps its data
155 across a rebase never runs one twice, and data one migration ahead of its
156 code — a preview copied from a newer branch, the old process of a roll —
157 boots and names what it does not know instead of refusing.
153158
154159 - `user` (humans and bots; bots are just users with narrower tokens)
155160 - `session` (cookie auth for the web)
@@ -169,10 +174,14 @@ row — and removing or renaming waits for the release after the last one
169174 that read it (add now, remove next release; a rename is two releases).
170175 `notAdditive` (`kernel/migrate.ts`) names a drop, a rename, a rebuild or a
171176 NOT NULL column without a default, and `test/schema-additive.test.ts`
172 refuses one in any migration newer than the two newest releases recorded in
173 `src/core/releases.json`, which the release agent bumps when it cuts one.
174 An old process that restarts mid-roll refuses a database ahead of it
175 (`user_version`), as it always has.
177 refuses one in any migration the older of the two newest releases recorded
178 in `src/core/releases.json` did not ship. The release agent runs
179 `bun scripts/schema-release.ts <version>` when it cuts one: it records the
180 release's migrations by name and locks each one's text, and
181 `test/schema-named.test.ts` refuses an edit to a locked migration.
182 An old process that restarts mid-roll boots on the database the new one
183 migrated and names the migrations it does not know; a build from before
184 named migrations still refuses it (`user_version`).
176185
177186 State transitions use compare-and-swap (`UPDATE … WHERE state = ?`), and every
178187 transition writes its event row in the same transaction. On boot, a
scripts/gate.ts +1
@@ -99,6 +99,7 @@ export const GATE: readonly string[] = [
9999 "test/migrate.test.ts",
100100 "test/schema-additive.test.ts",
101101 "test/schema-migrations.test.ts",
102 "test/schema-named.test.ts",
102103 "test/vitals.test.ts",
103104 "test/version.test.ts",
104105 "test/watches.test.ts",
scripts/schema-release.ts added +35
@@ -0,0 +1,35 @@
1 /**
2 * The release agent's one step for the schema, when it cuts a release:
3 * `bun scripts/schema-release.ts <version>`. It records in
4 * `src/core/releases.json` which migrations the release ships (by name,
5 * newest release first) and locks each one's text by its id, so a test
6 * refuses an edit to a migration that has shipped (#783) and the additive
7 * rule (#875) knows which migrations a roll can meet. Run it once per
8 * release; running it again for the same version changes nothing.
9 */
10 import { writeFileSync } from "node:fs";
11 import { join } from "node:path";
12 import releases from "../src/core/releases.json" with { type: "json" };
13 import { namedMigrations } from "../src/core/schema.ts";
14 import { migrationId } from "../src/kernel/migrate.ts";
15
16 const version = process.argv[2];
17 if (version === undefined || !/^\d+\.\d+\.\d+$/.test(version)) {
18 console.error("usage: bun scripts/schema-release.ts <version, like 0.7.53>");
19 process.exit(2);
20 }
21 const record = releases as {
22 note: string;
23 releases: { version: string; migrations?: number; names?: string[] }[];
24 locked: Record<string, string>;
25 };
26 const locked = { ...record.locked };
27 for (const m of namedMigrations) locked[m.name] = migrationId(m.sql);
28 const entries = record.releases.some((r) => r.version === version)
29 ? record.releases
30 : [{ version, names: namedMigrations.map((m) => m.name) }, ...record.releases];
31 writeFileSync(
32 join(import.meta.dir, "..", "src", "core", "releases.json"),
33 `${JSON.stringify({ ...record, releases: entries, locked }, null, 2)}\n`,
34 );
35 console.log(`${version}: ${namedMigrations.length} migrations recorded and locked`);
src/app.ts +2 −2
@@ -9,7 +9,7 @@ import type { Database } from "bun:sqlite";
99 import type { Decider } from "./crew/decide.ts";
1010 import { mkdirSync } from "node:fs";
1111 import { join, resolve } from "node:path";
12 import { migrations } from "./core/schema.ts";
12 import { namedMigrations } from "./core/schema.ts";
1313 import { EventBus } from "./core/events.ts";
1414 import { follow } from "./core/following.ts";
1515 import { enqueueForEvent } from "./core/webhooks.ts";
@@ -137,7 +137,7 @@ export function createApp(config: ForgeConfig): App {
137137 const reposRoot = join(dataDir, "repos");
138138 mkdirSync(reposRoot, { recursive: true });
139139
140 const db = openDb(join(dataDir, "forge.db"), migrations);
140 const db = openDb(join(dataDir, "forge.db"), namedMigrations);
141141 const bus = new EventBus(db);
142142
143143 // Every event durably enqueues webhook deliveries; the worker (main.ts)
src/core/releases.json +79 −2
@@ -1,4 +1,81 @@
11 {
2 "note": "The migration count each release shipped with, newest first. The release agent adds the new release here when it cuts one. Every migration past the older of the two newest counts must be additive (test/schema-additive.test.ts, notAdditive in src/kernel/migrate.ts): the old process keeps serving on the same database while the new one rolls in.",
3 "releases": [{ "version": "0.7.52", "migrations": 57 }]
2 "note": "Which migrations each release shipped, newest first, and the text of every migration on main locked by its id. The release agent runs `bun scripts/schema-release.ts <version>` when it cuts a release; nothing else edits this file. A release written as `migrations: N` shipped legacy-001 to legacy-N. test/schema-named.test.ts refuses an edit to a locked migration; test/schema-additive.test.ts holds every migration the two newest releases did not ship to the additive rule.",
3 "releases": [
4 {
5 "version": "0.7.52",
6 "migrations": 57
7 }
8 ],
9 "locked": {
10 "legacy-001": "b6c433603a3fe1c2e79b9d66fe9bc3bc67f403d0f815a9f81dc16a00ef245da5",
11 "legacy-002": "5af40c718d7c91c0340d2e1609ecc2edd69a91373e33d78ea561f4ef4de700e1",
12 "legacy-003": "6a53fb594a0bc023a80948c2cde3500a37a95aafe30a896b157794aee1998094",
13 "legacy-004": "9c323d30f8afb5b5e0b26dece297d88e41c758f21bf8155c9cc32d9df7d61609",
14 "legacy-005": "90ac9619b147b5818762c74e97da40fba00fdfe77071b642ddf4bb45b279f927",
15 "legacy-006": "f5bcf371354ab8e32c71e33c220a5d1e9554b4a6bb5b202922a47a07aa645979",
16 "legacy-007": "97d11a5e8f8d14bd1b4c8027201f6d286bf480d61c7d116ef3abcfa87d4824e8",
17 "legacy-008": "ae3db8d70c0890e72362e4c4e246eb4cf34e66354de622338015b5276b22eefb",
18 "legacy-009": "5e8796b669bca4271907987f88fab4f37e230247b5f49465a00ce14fedd1666a",
19 "legacy-010": "37d793621278ccb06b0f0e3c9c4f5996fddc10ac4532a24c5ed5fdee5273a931",
20 "legacy-011": "a8d5bac07bdbd8eaa77a73e0344dd3b8233fea0791084b247a4d5c85288d5344",
21 "legacy-012": "6aa333646f3751566cab4892f957e4aa7ffbfd8750fa3e1b76f514eaa46a6e57",
22 "legacy-013": "54c0f87c1f3bbbabf131b1722d811f915c536a752d2ebbdcec3a0fccbe22b6d7",
23 "legacy-014": "3508216ce82bf466b5fe9e07bc69dd10c5ddf1d3cbd7e95c1daa7027ab480747",
24 "legacy-015": "8949dbd4c0c38431d02cc9818827b68a3f196265624df9d100afc9a0974f84ad",
25 "legacy-016": "af46f93cd74f18e640fd0a91e02dac0c31a5a52c4d354bcdb2856e21b23e234e",
26 "legacy-017": "69ca4560ae58d18ee836d835555d436a5ea2a48e79a1467e51b1f937172b7173",
27 "legacy-018": "eca89f69fee4c278d27e8764d08ac49a3e5bdeefc54a29e22098a7110daaac2a",
28 "legacy-019": "1217cffaad87574c9b786de2cae43e6638a3803b6df75f0e4df5ea16bb895376",
29 "legacy-020": "5f8a0b647e9060606e21eb4a982d1815225ffc365e145eb9471c297c3343af2f",
30 "legacy-021": "85a05853ae9e636049597fe9036ac536ba3efac6bca66496b6cd75e52a70fc25",
31 "legacy-022": "b5e6e4d873686180dd9e76bab6ce0f9ef402a3444d96f2706d62c07cc18e80a3",
32 "legacy-023": "86890cbc353427bd6abe535a5ea2cad2661d437ed285407099b73d484e72071a",
33 "legacy-024": "1f9049bb4d0a0843dee7975f6b6201d396ac2e6bc4a155b8c66d65dff47efad5",
34 "legacy-025": "77a8887bfb3309ca024bbd9430240d716454fae860383a6d02e95d8e47223cfa",
35 "legacy-026": "85b5a7e228cefb1689c48f6e7862b9539f80d9c4240263a7e428716ccacf123b",
36 "legacy-027": "e43e6b3d4fadba7e03dfb6bb54406ac90326823e9fb8f56b127a551bf4f8ae5f",
37 "legacy-028": "8b3ff15d07875635f1a5d378f09b0a432fa5650272b621bf1f1ba47c352c2d79",
38 "legacy-029": "b4d8527a8a9e5002d2a2b3012fe064c365c180b680a59bb2d19db718f3ec9ad0",
39 "legacy-030": "727ee2c2371a095738a3df1079d8f4f98234b695f84d63466d98444a681f0f31",
40 "legacy-031": "a62ab5826175af737f7b56c2d209ecf61d1bcad1707d0db625ee152bea8cc70f",
41 "legacy-032": "fa420e16fc6a7723092944018cea038e29bfed19d1cb4c7729fbcb708bf96b69",
42 "legacy-033": "321bf75d987ac60b6a0dd58b12d461c1758be11a14e84edc8d071ca49ad3ee0d",
43 "legacy-034": "2c31a3db69e0e7cb1167ed3efa2d2a496532da896bc90e39979f4793cb70cd49",
44 "legacy-035": "fe01b3e75c1f9d4cae068fdb696949ac2691cde2796edb513a175eed3ef2162c",
45 "legacy-036": "dc1c385f26c13547e79eecafaa830a4adc0f4ff0d4856b95e6a50d075f0c94e9",
46 "legacy-037": "d5d815aa3bef5e1f4cceb114771cf1a3e57931fdc21235da9208c0122ab93d7b",
47 "legacy-038": "2445f7d024399cc6f27248ad91ac6693369f6dfbcbd96702e91f1cf7ff022f59",
48 "legacy-039": "cc3a57567f75490d5607e43097ecefc00bf3dc9529304be8874ae697a6231ee7",
49 "legacy-040": "ebe243edc22f30a29b6950e0f8cfce4c7ba346d11f7a4a4c61e4a08298b14965",
50 "legacy-041": "15b995bb9dcfcb16aa9dbee69372ede8e1dcee56857dfa06e5deb2a583520569",
51 "legacy-042": "f56c85102d0ce700a5a3eb958a0134f47a3a0f0cfa1e60c37e0167d2be802012",
52 "legacy-043": "d9949e799843d1221644af17544e4f80fd4e60232c101186432dae0b7d1d2057",
53 "legacy-044": "4f24a266d54eae3910da18f620e396b29b406ac4d993c13158875ce7590687c9",
54 "legacy-045": "ce0cf0b16b9094766362a288b9b984a00e8394b5b4821f370acf863b308ace61",
55 "legacy-046": "96917061cb4b064779a15dba9cbac82c4cba9ff2aefd71acd229e6aca4273190",
56 "legacy-047": "be5336004ba3141e71809194b65eb333866a678c5f2bb65c16be8681c65b63e7",
57 "legacy-048": "21c01ec3f30ef0e7f55a293601e95db31c1437f3da33ecf46036d9a425e5a96d",
58 "legacy-049": "a29d814f26ba38e871e7271cd955f14022ff923299b7a3af1ba85866f07221e2",
59 "legacy-050": "28be9094e981e547f7f3bd1eaa4b0fd87acf346ccc1188469341c262901de488",
60 "legacy-051": "e3e9f27841b17e3951e627680cdfcca30e366bc687d8fd6f4c3b56a9661a5b2a",
61 "legacy-052": "922ee458bbc52f0d6a9938e36ff09494066a8cb557bd7788495d259c9b335f39",
62 "legacy-053": "1e64971a56d0c0e16ec513cc506bc3a637efe843092d8a8cc99753a6c77a32e8",
63 "legacy-054": "7670ecd442c0f1a1e23e878fe5e8accb4fd29a58c6bf3b27841a1c2a062352e6",
64 "legacy-055": "8a0da478bdb878d0b0bf29d5824735ac3e67a6a504877abaff81bcf36d282597",
65 "legacy-056": "be08ec2eab632260848ed4c9951291907ace5bd81c514c4e3e53cd6cd0ab85cb",
66 "legacy-057": "15000df57c5e4f686dc91bb0c937d9484a4466bc424be5b7570c22d4f820c7d4",
67 "legacy-058": "32b86a5f3074b1bce792e99aadc1f432b8ccff508703c9fcf6fa3ae537ad4eb4",
68 "legacy-059": "4b7829c5fc97384cb4d5d9005168288eeab9419003552d8051ec5561bc9ef242",
69 "legacy-060": "7d2319f66c78239cc662477d4ceda2ac50fd670342ebd69db1b7736041c1ed47",
70 "legacy-061": "7d4b174818752723caaef32300a0a21783e1db9aca6b72334a44dd7ca092fd1f",
71 "legacy-062": "57c2dc3400fc1e2db9acf86f2eb0231561e8e6ed87b54770a9d79493137cfe0e",
72 "legacy-063": "7721b2146736a958a08eb3e6f77b5ea6e179fd920dfc94e9a9ae98c88ce4eaba",
73 "legacy-064": "e15834cc1c7e45a58f4849cbad2ee5b627c3ad895c716030431b4961a47f30e9",
74 "legacy-065": "46d20691683748274ff0aeab0cd8d2640bb3f0427a4a3235e6a8b828ab0d2396",
75 "legacy-066": "782bfde34aac27ea01782ae22bbf3152e6f32925443e5ce212594f29402af0ff",
76 "legacy-067": "c2f5bf838522142e42b047e400b6725f711bd0280536a8c143aa5f30a8f24ad9",
77 "legacy-068": "1a92482c52858a1a326539c0aa1ed9c94d52dd9a2f274c7645a44c4a8840b2a2",
78 "legacy-069": "b266f8f36f9a9a2382e7c5107dc9c5ce70a0c097ad8f5dc0c3f53f893c7a3476",
79 "legacy-070": "be9c7af107676fee4a652dc45580c817309a917211dc90435eb94fa5e2a46e45"
80 }
481 }
src/core/schema.ts +52 −4
@@ -1,10 +1,29 @@
11 /**
2 * The whole schema, as linear migrations. Append-only: released migrations
3 * are immutable history, exactly like commits. The database is an index over
4 * truth that lives in git wherever possible — small on purpose.
2 * The whole schema, as migrations. Released migrations are immutable
3 * history, exactly like commits. The database is an index over truth that
4 * lives in git wherever possible — small on purpose.
5 *
6 * A new migration is a file: `src/core/migrations/<YYYY-MM-DD-slug>.sql`
7 * (#783). Two pulls that each add one add two files, so neither collides
8 * with the other, and they apply in name order after the legacy list below.
9 * That list — the positional migrations the forge grew with, `legacy-001`
10 * to `legacy-070` — is closed: nothing is appended to it
11 * (`test/schema-named.test.ts`). Every migration only adds
12 * (`test/schema-additive.test.ts`), and one that has shipped is never
13 * edited (`src/core/releases.json`'s lock).
514 */
615
7 export const migrations: readonly string[] = [
16 import { readdirSync, readFileSync } from "node:fs";
17 import { join } from "node:path";
18 import type { NamedMigration } from "../kernel/migrate.ts";
19
20 /** How many legacy migrations there are, for ever. */
21 export const LEGACY_COUNT = 70;
22
23 /** A named migration's file name: the date it was written, then what it does. */
24 export const MIGRATION_NAME = /^\d{4}-\d{2}-\d{2}-[a-z0-9]+(?:-[a-z0-9]+)*$/;
25
26 const legacyMigrations: readonly string[] = [
827 // 1 — foundation: users, sessions, tokens, repos, events, webhooks
928 `
1029 CREATE TABLE user (
@@ -1541,3 +1560,32 @@ export const migrations: readonly string[] = [
15411560 END;
15421561 `,
15431562 ];
1563
1564 /** The directory a new migration goes in, one `.sql` file each. */
1565 export const MIGRATIONS_DIR = join(import.meta.dir, "migrations");
1566
1567 /** The named migrations in `dir`, in name order — which is the order they apply. */
1568 export function namedOnDisk(dir = MIGRATIONS_DIR): NamedMigration[] {
1569 let files: string[];
1570 try {
1571 files = readdirSync(dir).filter((f) => f.endsWith(".sql"));
1572 } catch {
1573 return [];
1574 }
1575 return files.sort().map((file) => ({
1576 name: file.slice(0, -".sql".length),
1577 sql: readFileSync(join(dir, file), "utf8"),
1578 }));
1579 }
1580
1581 /** Every migration, legacy first, each with its name. */
1582 export const namedMigrations: readonly NamedMigration[] = [
1583 ...legacyMigrations.map((sql, i) => ({
1584 name: `legacy-${String(i + 1).padStart(3, "0")}`,
1585 sql,
1586 })),
1587 ...namedOnDisk(),
1588 ];
1589
1590 /** The same, as text alone, for whatever reads the schema as a list. */
1591 export const migrations: readonly string[] = namedMigrations.map((m) => m.sql);
src/kernel/db.ts +13 −3
@@ -6,7 +6,8 @@
66 */
77
88 import { Database } from "bun:sqlite";
9 import { migrate } from "./migrate.ts";
9 import { createLog } from "./log.ts";
10 import { migrate, type NamedMigration } from "./migrate.ts";
1011
1112 /**
1213 * How long a writer waits for another writer before giving up. Long by
@@ -33,10 +34,19 @@ const CACHE_KIB = 64 * 1024;
3334 */
3435 const MMAP_BYTES = 512 * 1024 * 1024;
3536
36 export function openDb(path: string, migrations: readonly string[]): Database {
37 export function openDb(
38 path: string,
39 migrations: readonly (string | NamedMigration)[],
40 ): Database {
3741 const db = new Database(path, { create: true, strict: true });
3842 applyPragmas(db);
39 migrate(db, migrations);
43 const { unknown } = migrate(db, migrations);
44 // Data one migration ahead of this build — a preview copied from a
45 // newer branch, the old process of a roll — is served, and said once.
46 if (unknown.length > 0)
47 createLog("db").warn("database has migrations this build does not know", {
48 migrations: unknown.join(", "),
49 });
4050 return db;
4151 }
4252
src/kernel/migrate.ts +84 −19
@@ -21,7 +21,8 @@
2121 *
2222 * `user_version` is still written — the count of applied migrations — so a
2323 * build from before this table refuses a database that is ahead of it the
24 * way it always did.
24 * way it always did. A build from after it boots on one and names what it
25 * does not know (`migrate`'s `unknown`, #783): every migration only adds.
2526 */
2627
2728 import type { Database } from "bun:sqlite";
@@ -39,10 +40,39 @@ export function migrationId(sql: string): string {
3940 return sha256(sql.replace(/\s+/g, " ").trim());
4041 }
4142
42 export function migrate(db: Database, migrations: readonly string[]): void {
43 const ids = migrations.map((sql, i) => {
44 if (sql.trim() === "")
45 defect("db.migration_missing", `migration ${i + 1} is empty`);
43 /**
44 * A migration with its name (#783): `src/core/migrations/<name>.sql`, or
45 * `legacy-NNN` for one of the positional list it grew out of. The name is
46 * what a person and a message say; the text is still what identifies it.
47 */
48 export interface NamedMigration {
49 readonly name: string;
50 readonly sql: string;
51 }
52
53 /** What a boot found applied that this build does not know, by name. */
54 export interface MigrateOutcome {
55 readonly unknown: readonly string[];
56 }
57
58 /**
59 * Apply what this database has not applied, in order, marking each row with
60 * whether it only added (`notAdditive`, judged as it is applied). Migrations
61 * recorded that this build does not know — a preview's copied data one
62 * branch ahead, the old process of a roll on the new one's database — are
63 * served on and named when every one is marked additive, and refused
64 * otherwise: this build cannot see what they did, only that mark.
65 */
66 export function migrate(
67 db: Database,
68 migrations: readonly (string | NamedMigration)[],
69 ): MigrateOutcome {
70 const list = migrations.map((m, i) =>
71 typeof m === "string" ? { name: `migration ${i + 1}`, sql: m } : m,
72 );
73 const sqls = list.map((m) => m.sql);
74 const ids = list.map(({ name, sql }) => {
75 if (sql.trim() === "") defect("db.migration_missing", `${name} is empty`);
4676 return migrationId(sql);
4777 });
4878 const seen = new Set<string>();
@@ -50,22 +80,17 @@ export function migrate(db: Database, migrations: readonly string[]): void {
5080 if (seen.has(id))
5181 defect(
5282 "db.migration_duplicate",
53 `migration ${i + 1} repeats an earlier one word for word — it would never run`,
83 `${list[i]!.name} repeats an earlier one word for word — it would never run`,
5484 );
5585 seen.add(id);
5686 });
5787
58 const applied = appliedIds(db, migrations, ids);
59 if (applied.size > migrations.length) {
60 defect(
61 "db.future_schema",
62 `database has applied ${applied.size} migrations, this build only knows ${migrations.length} — refusing to run`,
63 );
64 }
65 for (let i = 0; i < migrations.length; i++) {
88 const applied = appliedIds(db, sqls, ids);
89 const known = new Set(ids);
90 for (let i = 0; i < list.length; i++) {
6691 const id = ids[i]!;
6792 if (applied.has(id)) continue;
68 const sql = migrations[i]!;
93 const { name, sql } = list[i]!;
6994 db.transaction(() => {
7095 for (const statement of statements(sql)) {
7196 try {
@@ -73,19 +98,48 @@ export function migrate(db: Database, migrations: readonly string[]): void {
7398 } catch (error) {
7499 defect(
75100 "db.migration_failed",
76 `migration ${i + 1} failed at ${quote(statement)}: ${messageOf(error)}`,
101 `${name} failed at ${quote(statement)}: ${messageOf(error)}`,
77102 error,
78103 );
79104 }
80105 }
106 // Whether it only added, judged by the build that applied it: a build
107 // that meets this row without knowing it serves on it only if so.
81108 db.query(
82 "INSERT INTO schema_migration (id, position, applied_at) VALUES (?1, ?2, ?3)",
83 ).run(id, i + 1, new Date().toISOString());
109 "INSERT INTO schema_migration (id, position, applied_at, name, additive) VALUES (?1, ?2, ?3, ?4, ?5)",
110 ).run(
111 id,
112 i + 1,
113 new Date().toISOString(),
114 name,
115 notAdditive(sql).length === 0 ? 1 : 0,
116 );
84117 applied.add(id);
85118 // PRAGMA can't be parameterized; the value is a count, not input.
86119 db.exec(`PRAGMA user_version = ${applied.size}`);
87120 })();
88121 }
122 const strangers = db
123 .query<
124 { id: string; name: string | null; position: number; additive: number | null },
125 []
126 >("SELECT id, name, position, additive FROM schema_migration ORDER BY position")
127 .all()
128 .filter((row) => !known.has(row.id));
129 const called = (row: { id: string; name: string | null; position: number }) =>
130 row.name ?? `migration ${row.position} (${row.id.slice(0, 8)})`;
131 // Served on only when the build that applied it found it additive: this
132 // build cannot see what an unknown migration did, so it trusts that mark
133 // and nothing else — a row without one (written before the mark existed)
134 // or marked as dropping, renaming or rebuilding is refused, as data ahead
135 // always was.
136 const unsafe = strangers.filter((row) => row.additive !== 1);
137 if (unsafe.length > 0)
138 defect(
139 "db.future_schema",
140 `database has migrations this build does not know and cannot serve under: ${unsafe.map(called).join(", ")} — refusing to run`,
141 );
142 return { unknown: strangers.map(called) };
89143 }
90144
91145 /**
@@ -115,7 +169,9 @@ function appliedIds(
115169 db.exec(`CREATE TABLE schema_migration (
116170 id TEXT PRIMARY KEY,
117171 position INTEGER NOT NULL,
118 applied_at TEXT NOT NULL
172 applied_at TEXT NOT NULL,
173 name TEXT,
174 additive INTEGER
119175 )`);
120176 const insert = db.query(
121177 "INSERT INTO schema_migration (id, position, applied_at) VALUES (?1, ?2, ?3)",
@@ -126,6 +182,15 @@ function appliedIds(
126182 insert.run(ids[i]!, i + 1, at);
127183 })();
128184 }
185 // The runner's own table gained a name for each row (#783); a database
186 // from before has none on the rows it already wrote.
187 const columns = db
188 .query<{ name: string }, []>("PRAGMA table_info(schema_migration)")
189 .all();
190 if (!columns.some((c) => c.name === "name"))
191 db.exec("ALTER TABLE schema_migration ADD COLUMN name TEXT");
192 if (!columns.some((c) => c.name === "additive"))
193 db.exec("ALTER TABLE schema_migration ADD COLUMN additive INTEGER");
129194 return new Set(
130195 db
131196 .query<{ id: string }, []>("SELECT id FROM schema_migration")
test/schema-additive.test.ts +22 −13
@@ -6,7 +6,7 @@
66 */
77 import { describe, expect, test } from "bun:test";
88 import releases from "../src/core/releases.json" with { type: "json" };
9 import { migrations } from "../src/core/schema.ts";
9 import { namedMigrations } from "../src/core/schema.ts";
1010 import { notAdditive } from "../src/kernel/migrate.ts";
1111
1212 describe("migrations are additive across a roll", () => {
@@ -59,21 +59,30 @@ describe("migrations are additive across a roll", () => {
5959 expect(notAdditive(sql)).toEqual([]);
6060 });
6161
62 test("every migration newer than the releases still in play is additive", () => {
63 const counts = releases.releases.slice(0, 2).map((r) => r.migrations);
64 expect(counts.length).toBeGreaterThan(0);
65 const floor = Math.min(...counts);
66 expect(floor).toBeLessThanOrEqual(migrations.length);
67 const offenders = migrations
68 .map((sql, i) => ({ n: i + 1, problems: notAdditive(sql) }))
69 .slice(floor)
62 /** The migrations a recorded release shipped, by name. */
63 const shipped = (r: { migrations?: number; names?: string[] }): Set<string> =>
64 new Set(
65 r.names ??
66 Array.from({ length: r.migrations ?? 0 }, (_, i) =>
67 `legacy-${String(i + 1).padStart(3, "0")}`,
68 ),
69 );
70
71 test("every migration the two newest releases did not both ship is additive", () => {
72 const recent = (releases.releases as { migrations?: number; names?: string[] }[]).slice(0, 2);
73 expect(recent.length).toBeGreaterThan(0);
74 // What the older of the two shipped is what an old process can be.
75 const floor = shipped(recent[recent.length - 1]!);
76 const offenders = namedMigrations
77 .filter((m) => !floor.has(m.name))
78 .map((m) => ({ name: m.name, problems: notAdditive(m.sql) }))
7079 .filter((m) => m.problems.length > 0);
7180 expect(offenders).toEqual([]);
7281 });
7382
74 test("the release record is newest first and never ahead of the schema", () => {
75 const counts = releases.releases.map((r) => r.migrations);
76 expect([...counts].sort((a, b) => b - a)).toEqual(counts);
77 for (const c of counts) expect(c).toBeLessThanOrEqual(migrations.length);
83 test("the release record names only migrations that exist", () => {
84 const names = new Set(namedMigrations.map((m) => m.name));
85 for (const r of releases.releases as { migrations?: number; names?: string[] }[])
86 for (const name of shipped(r)) expect(names.has(name)).toBe(true);
7887 });
7988 });
test/schema-migrations.test.ts +2 −2
@@ -147,9 +147,9 @@ describe("a preview booting on copied data", () => {
147147 db.close();
148148 });
149149
150 test("data ahead of this build is still refused", () => {
150 test("data ahead of this build boots: every migration only adds (#783)", () => {
151151 const path = production(["CREATE TABLE a (x INTEGER)", "CREATE TABLE b (y INTEGER)"]);
152 expect(() => openDb(path, ["CREATE TABLE a (x INTEGER)"])).toThrow(ForgeError);
152 expect(() => openDb(path, ["CREATE TABLE a (x INTEGER)"]).close()).not.toThrow();
153153 });
154154 });
155155
test/schema-named.test.ts added +152
@@ -0,0 +1,152 @@
1 /**
2 * Migrations are files with names (#783), so two pulls can each add one
3 * without colliding: they apply in name order, in either order of landing,
4 * and data one migration ahead of its code boots and says what it does not
5 * know. The legacy list is closed, and a migration that is locked in the
6 * release record is never edited.
7 */
8 import { afterAll, describe, expect, test } from "bun:test";
9 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { Database } from "bun:sqlite";
13 import { ForgeError } from "../src/kernel/error.ts";
14 import releases from "../src/core/releases.json" with { type: "json" };
15 import {
16 LEGACY_COUNT,
17 MIGRATION_NAME,
18 namedMigrations,
19 namedOnDisk,
20 } from "../src/core/schema.ts";
21 import { openDb } from "../src/kernel/db.ts";
22 import { migrate, migrationId, type NamedMigration } from "../src/kernel/migrate.ts";
23
24 const root = mkdtempSync(join(tmpdir(), "forge-named-"));
25 afterAll(() => rmSync(root, { recursive: true, force: true }));
26 let n = 0;
27 const path = (): string => join(root, `db-${++n}`);
28
29 const has = (db: Database, table: string): boolean =>
30 db
31 .query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1")
32 .get(table) !== null;
33
34 const base: NamedMigration[] = [{ name: "legacy-001", sql: "CREATE TABLE root (id TEXT)" }];
35 const a: NamedMigration = { name: "2026-10-06-a-note", sql: "CREATE TABLE a_note (id TEXT)" };
36 const b: NamedMigration = { name: "2026-10-07-b-note", sql: "CREATE TABLE b_note (id TEXT)" };
37
38 describe("named migrations", () => {
39 test("the legacy list is closed: a new migration is a file", () => {
40 const legacy = namedMigrations.filter((m) => m.name.startsWith("legacy-"));
41 expect(legacy.length).toBe(LEGACY_COUNT);
42 expect(namedMigrations.slice(0, LEGACY_COUNT)).toEqual(legacy);
43 });
44
45 test("every named migration's file name is a date and a slug, once, in order", () => {
46 const named = namedMigrations.slice(LEGACY_COUNT).map((m) => m.name);
47 for (const name of named) expect(name).toMatch(MIGRATION_NAME);
48 expect(new Set(named).size).toBe(named.length);
49 expect([...named].sort()).toEqual(named);
50 });
51
52 test("a migration locked in the release record is never edited", () => {
53 const now = new Map(namedMigrations.map((m) => [m.name, migrationId(m.sql)]));
54 const changed = Object.entries(releases.locked)
55 .filter(([name, id]) => now.get(name) !== id)
56 .map(([name]) => name);
57 expect(changed).toEqual([]);
58 });
59
60 test("two migrations added on separate branches both apply, whichever landed first", () => {
61 const merged = [...base, a, b];
62 // A database that has a's branch, and one that has b's.
63 for (const branch of [[...base, a], [...base, b]]) {
64 const file = path();
65 openDb(file, branch).close();
66 const db = openDb(file, merged);
67 expect(has(db, "a_note")).toBe(true);
68 expect(has(db, "b_note")).toBe(true);
69 const names = (
70 db.query("SELECT name FROM schema_migration ORDER BY position").all() as {
71 name: string | null;
72 }[]
73 ).map((r) => r.name);
74 expect(names).toContain(a.name);
75 expect(names).toContain(b.name);
76 db.close();
77 }
78 });
79
80 test("data one migration ahead of its code boots and names what it does not know", () => {
81 const file = path();
82 openDb(file, [...base, a, b]).close();
83 const db = new Database(file);
84 const outcome = migrate(db, [...base, a]);
85 expect(outcome.unknown).toEqual([b.name]);
86 db.close();
87 // And one behind takes what it is missing.
88 const behind = path();
89 openDb(behind, base).close();
90 const caught = openDb(behind, [...base, a, b]);
91 expect(has(caught, "b_note")).toBe(true);
92 caught.close();
93 });
94
95 test("a database written before names had any boots and keeps its history", () => {
96 const file = path();
97 const old = new Database(file);
98 old.exec(`CREATE TABLE schema_migration (
99 id TEXT PRIMARY KEY, position INTEGER NOT NULL, applied_at TEXT NOT NULL)`);
100 old.exec("CREATE TABLE root (id TEXT)");
101 old
102 .query("INSERT INTO schema_migration (id, position, applied_at) VALUES (?1, 1, 'then')")
103 .run(migrationId(base[0]!.sql));
104 old.close();
105 const db = openDb(file, [...base, a]);
106 expect(has(db, "a_note")).toBe(true);
107 const rows = db
108 .query("SELECT position, name FROM schema_migration ORDER BY position")
109 .all() as { position: number; name: string | null }[];
110 expect(rows).toEqual([
111 { position: 1, name: null },
112 { position: 2, name: a.name },
113 ]);
114 db.close();
115 });
116
117 test("a migration is a .sql file in the directory, read in name order", () => {
118 const dir = join(root, "migrations");
119 mkdirSync(dir);
120 writeFileSync(join(dir, `${b.name}.sql`), b.sql);
121 writeFileSync(join(dir, `${a.name}.sql`), a.sql);
122 writeFileSync(join(dir, "notes.txt"), "not a migration");
123 expect(namedOnDisk(dir)).toEqual([a, b]);
124 expect(namedOnDisk(join(root, "nowhere"))).toEqual([]);
125 });
126
127 test("data ahead by a migration that did not only add is refused", () => {
128 const drop: NamedMigration = {
129 name: "2026-10-08-drop-root",
130 sql: "CREATE TABLE root_next (id TEXT); DROP TABLE root",
131 };
132 const file = path();
133 openDb(file, [...base, a, drop]).close();
134 const marks = new Database(file);
135 expect(
136 marks.query("SELECT additive FROM schema_migration WHERE name = ?1").get(drop.name),
137 ).toEqual({ additive: 0 });
138 marks.close();
139 expect(() => openDb(file, [...base, a])).toThrow(ForgeError);
140 });
141
142 test("an unknown row from before the mark existed is refused, not trusted", () => {
143 const file = path();
144 openDb(file, [...base, a, b]).close();
145 const db = new Database(file);
146 db.query("UPDATE schema_migration SET additive = NULL WHERE name = ?1").run(b.name);
147 db.close();
148 expect(() => openDb(file, [...base, a])).toThrow(ForgeError);
149 // Known to this build, the same row is simply applied history.
150 expect(() => openDb(file, [...base, a, b]).close()).not.toThrow();
151 });
152 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs