From 5f4ce1bb747579b5c19bd580d4f7100ba75b78d7 Mon Sep 17 00:00:00 2001 From: Madraka <8898640+Madraka@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:10:45 +0300 Subject: [PATCH 1/2] fix(storage): concurrent migrate() runs converge instead of throwing (#309) Instances of a fresh installation that start together on one store all read `_migrations` before any of them applies a migration. The loser's batch fails (duplicate column, or the bookkeeping row's primary key), rolls back as a whole and was thrown, although the migration was now applied: the first request on that instance failed with `StorageError: migration "0004_audit_actor_name" failed`. When a migration's batch fails, migrate() now reads its `_migrations` row again. If a peer applied it, the run moves on (the name is not in `applied`); otherwise it throws as before. At most once still rests on the primary-key row inside the same atomic batch: no interactive transaction, no lock (hard rule 4). - test/migrate-concurrent.test.ts: three and four runs gated to read the same empty state converge, on better-sqlite3 and Miniflare D1; each migration applies once (a non-idempotent INSERT is not doubled); a migration that fails on its own still throws. - admin-worker: the retry-once wrappers in ensureMigrated and SchedulerClock are gone. - helm-smoke.sh: fails when any instance logs a migration error, with two instances and after scaling to three (Parallel pod management). Closes #309 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Madraka <8898640+Madraka@users.noreply.github.com> --- .changeset/migrate-race-309.md | 6 + packages/cloudflare/src/admin-worker.ts | 14 +- packages/storage/src/migrate.ts | 16 +++ .../storage/test/migrate-concurrent.test.ts | 120 ++++++++++++++++++ scripts/helm-smoke.sh | 9 ++ scripts/size-baseline.json | 2 +- 6 files changed, 155 insertions(+), 12 deletions(-) create mode 100644 .changeset/migrate-race-309.md create mode 100644 packages/storage/test/migrate-concurrent.test.ts diff --git a/.changeset/migrate-race-309.md b/.changeset/migrate-race-309.md new file mode 100644 index 00000000..06e8a10f --- /dev/null +++ b/.changeset/migrate-race-309.md @@ -0,0 +1,6 @@ +--- +"@cloudhal/storage": patch +"@cloudhal/cloudflare": patch +--- + +`migrate()` is safe when several instances start together on one store (#309). A run that loses the race for a migration now sees the peer's `_migrations` row and moves on, instead of throwing `StorageError: migration "…" failed` from the losing instance's first request. Each migration still applies at most once: its statements and its primary-key row stay in one atomic `batch()`. A migration that is still not applied after its batch fails throws as before. The admin Worker's retry-once wrappers around `migrate()` are gone. diff --git a/packages/cloudflare/src/admin-worker.ts b/packages/cloudflare/src/admin-worker.ts index c52bd003..b50eb060 100644 --- a/packages/cloudflare/src/admin-worker.ts +++ b/packages/cloudflare/src/admin-worker.ts @@ -347,12 +347,8 @@ export function createAdminWorker(options: AdminWorkerOptions = {}) { const confirmed: SiteConfirmations = { gates: {}, fields: {} }; const ensureMigrated = async (sql: SqlDriver) => { if (migrated) return; - try { - await migrate(sql, migrations); - } catch { - // A concurrent request or isolate applied them first; a second pass sees them as done. - await migrate(sql, migrations); - } + // Safe against concurrent requests, isolates and instances: `migrate` skips what a peer applied. + await migrate(sql, migrations); migrated = true; }; @@ -605,11 +601,7 @@ export const SchedulerClock = schedulerClockClass(async (env, o) => { const e = env as AdminEnv; const sql = new D1Driver(e.DB); if (!clockMigrated) { - try { - await migrate(sql, migrations); - } catch { - await migrate(sql, migrations); - } + await migrate(sql, migrations); clockMigrated = true; } const log = (line: string) => console.log(line); diff --git a/packages/storage/src/migrate.ts b/packages/storage/src/migrate.ts index d45d706f..3baec747 100644 --- a/packages/storage/src/migrate.ts +++ b/packages/storage/src/migrate.ts @@ -23,6 +23,13 @@ export function splitStatements(sql: string): string[] { /** * Applies pending migrations in order. Each migration is one atomic `batch` (its statements plus the * bookkeeping row), so a failing migration leaves the database at the previous migration. + * + * Safe when several processes migrate one database at once (instances of a self-host cluster + * starting together, isolates of a Worker, #309). The bookkeeping row's primary key, inside the same + * atomic batch, lets each migration apply at most once. When a batch fails, the row is read again: + * if a peer applied the migration meanwhile, this run moves on to the next one (it is not in + * `applied`); only a migration that is still not applied fails the run. No interactive transaction + * and no lock: D1 has neither. */ export async function migrate( driver: SqlDriver, @@ -52,6 +59,7 @@ export async function migrate( try { await driver.batch(statements); } catch (cause) { + if (await appliedByPeer(driver, m.name)) continue; throw new StorageError(`migration "${m.name}" failed: ${(cause as Error).message}`, cause); } applied.push(m.name); @@ -59,6 +67,14 @@ export async function migrate( return { applied }; } +/** Whether `name` is in the bookkeeping table now (a peer applied it while this run read stale state). */ +async function appliedByPeer(driver: SqlDriver, name: string): Promise { + const row = await driver + .get<{ name: string }>(`SELECT name FROM ${MIGRATIONS_TABLE} WHERE name = ?`, [name]) + .catch(() => undefined); + return row !== undefined && row !== null; +} + export async function appliedMigrations(driver: SqlDriver): Promise { const rows = await driver .all<{ name: string }>(`SELECT name FROM ${MIGRATIONS_TABLE} ORDER BY name`) diff --git a/packages/storage/test/migrate-concurrent.test.ts b/packages/storage/test/migrate-concurrent.test.ts new file mode 100644 index 00000000..52a888f6 --- /dev/null +++ b/packages/storage/test/migrate-concurrent.test.ts @@ -0,0 +1,120 @@ +/** + * #309: several `migrate()` runs on one database at once (instances of a cluster starting + * together, isolates of a Worker) converge. A run that loses the race for a migration sees the + * peer's bookkeeping row and moves on; nothing is applied twice and nothing throws. + */ +import { describe, expect, it } from "vitest"; +import { migrations } from "../migrations/index.ts"; +import { appliedMigrations, migrate } from "../src/migrate.ts"; +import { BetterSqlite3Driver } from "../src/sql/better-sqlite3.ts"; +import { D1Driver } from "../src/sql/d1.ts"; +import { createMiniflareD1 } from "../src/testing.ts"; +import type { SqlDriver } from "../src/types.ts"; + +const backends = ["better-sqlite3", "D1 (Miniflare)"] as const; +type Backend = (typeof backends)[number]; + +/** One database on `backend`, and a way to close it. */ +async function database(backend: Backend) { + if (backend === "better-sqlite3") { + const driver = await BetterSqlite3Driver.open(":memory:"); + return { driver: driver as SqlDriver, dispose: () => driver.close() }; + } + const h = await createMiniflareD1(); + return { driver: new D1Driver(h.db) as SqlDriver, dispose: () => h.dispose() }; +} + +/** + * `driver`, but every run's first read of `_migrations` waits until all `n` runs have read it: + * they all start from the same applied set, the worst case of instances starting together. + */ +function racing(driver: SqlDriver, n: number): () => SqlDriver { + let read = 0; + let open: () => void = () => {}; + const gate = new Promise((resolve) => { + open = resolve; + }); + return () => { + let first = true; + return { + name: driver.name, + get: (sql, params) => driver.get(sql, params), + run: (sql, params) => driver.run(sql, params), + batch: (statements) => driver.batch(statements), + exec: (sql) => driver.exec(sql), + close: () => Promise.resolve(), + async all(sql, params) { + const rows = await driver.all(sql, params); + if (first && sql.includes("_migrations")) { + first = false; + read += 1; + if (read === n) open(); + await gate; + } + return rows as never; + }, + } satisfies SqlDriver; + }; +} + +const names = migrations.map((m) => m.name).sort(); + +/** Migrations that are not idempotent on their own: re-running one would fail or double a row. */ +const counting = [ + { name: "0001_table", sql: "CREATE TABLE counter (x INTEGER NOT NULL);" }, + { name: "0002_row", sql: "INSERT INTO counter (x) VALUES (1);" }, + { name: "0003_column", sql: "ALTER TABLE counter ADD COLUMN y INTEGER;" }, +]; + +describe("migrate: concurrent runs on one database (#309)", () => { + for (const backend of backends) + it(`three runs that read the same empty state all finish, each migration applied once (${backend})`, async () => { + const db = await database(backend); + try { + const instance = racing(db.driver, 3); + const runs = await Promise.all([1, 2, 3].map(() => migrate(instance(), migrations))); + // Every migration was applied by exactly one run; the others saw it done and moved on. + expect(runs.flatMap((r) => r.applied).sort()).toEqual(names); + expect(runs.some((r) => r.applied.length < names.length)).toBe(true); + expect(await appliedMigrations(db.driver)).toEqual(names); + // A later start sees everything applied. + expect((await migrate(db.driver, migrations)).applied).toEqual([]); + } finally { + await db.dispose(); + } + }); + + for (const backend of backends) + it(`a migration applied before or by a peer is never run again (${backend})`, async () => { + const db = await database(backend); + try { + const instance = racing(db.driver, 4); + const runs = await Promise.all([1, 2, 3, 4].map(() => migrate(instance(), counting))); + expect(runs.flatMap((r) => r.applied).sort()).toEqual(counting.map((m) => m.name)); + expect(await db.driver.all("SELECT x, y FROM counter")).toEqual([{ x: 1, y: null }]); + expect((await migrate(db.driver, counting)).applied).toEqual([]); + expect(await db.driver.all("SELECT x FROM counter")).toEqual([{ x: 1 }]); + } finally { + await db.dispose(); + } + }); + + it("a migration that fails on its own still throws while a peer applies the others", async () => { + const db = await database("better-sqlite3"); + try { + const bad = { name: "0004_bad", sql: "CREATE TABLE ok (x);\nCREATE TABLE ok (x);" }; + const instance = racing(db.driver, 2); + const runs = await Promise.allSettled([ + migrate(instance(), [...counting, bad]), + migrate(instance(), [...counting, bad]), + ]); + for (const run of runs) { + expect(run.status).toBe("rejected"); + expect(String((run as PromiseRejectedResult).reason)).toMatch(/0004_bad/); + } + expect(await appliedMigrations(db.driver)).toEqual(counting.map((m) => m.name)); + } finally { + await db.dispose(); + } + }); +}); diff --git a/scripts/helm-smoke.sh b/scripts/helm-smoke.sh index 285eaed0..7bdc33a2 100755 --- a/scripts/helm-smoke.sh +++ b/scripts/helm-smoke.sh @@ -21,6 +21,12 @@ fail() { k logs statefulset/ch-cloudhal -c cloudhal --tail=80 >&2 || true exit 1 } +# Every instance's log, for a migration that lost a race and surfaced as an error (#309). +migration_errors() { + local errs + errs=$(k logs -l app.kubernetes.io/component=cloudhal -c cloudhal --tail=-1 --prefix 2>/dev/null | grep -F 'migration "' || true) + [ -z "$errs" ] || { echo "$errs" >&2; fail "an instance logged a migration error ($1)"; } +} cleanup() { [ "$keep" = "--keep" ] || kind delete cluster --name "$cluster" >/dev/null 2>&1 || true; } trap cleanup EXIT @@ -54,6 +60,8 @@ publish=$(c -o /dev/null -w '%{http_code}' -b /tmp/jar -X POST "$origin/api/site [ "$publish" = 201 ] || fail "publish ($publish)" c http://ch-cloudhal:8788/ | grep -q "Smoke Site" || fail "the site after the publish" step "the owner signed up with the setup token; a publish is live on the next request" +migration_errors "two instances" +step "neither instance logged a migration error" if c -o /dev/null -m 4 http://ch-cloudhal-0.ch-cloudhal-peers:7000/ready; then echo "! the cluster port answered a foreign pod: this CNI does not enforce NetworkPolicy" >&2 @@ -66,6 +74,7 @@ helm --kube-context "kind-$cluster" -n "$ns" upgrade ch "$root/deploy/helm/cloud [ "$(secret CLOUDHAL_CLUSTER_KEY | shasum)" = "$key" ] || fail "the upgrade changed the cluster key" k rollout status statefulset/ch-cloudhal --timeout=600s >/dev/null || fail "scaling to three" c http://ch-cloudhal:8788/ | grep -q "Smoke Site" || fail "the site with three instances" +migration_errors "three instances" step "an upgrade kept the Secret; three instances serve the site" echo echo "Helm smoke test passed." diff --git a/scripts/size-baseline.json b/scripts/size-baseline.json index 71a446f7..1d844c8a 100644 --- a/scripts/size-baseline.json +++ b/scripts/size-baseline.json @@ -369,7 +369,7 @@ "params": 5 }, "packages/cloudflare/src/admin-worker.ts::createAdminWorker": { - "lines": 252 + "lines": 248 }, "packages/cloudflare/src/admin-worker.ts::createAdminWorker>fetch": { "lines": 190 From bffe5637b9a05de98ab8d12508e7a381d557102b Mon Sep 17 00:00:00 2001 From: Madraka <8898640+Madraka@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:24:54 +0300 Subject: [PATCH 2/2] test(ci): the Swarm smoke test fails when an instance logs a migration error (#309) Co-Authored-By: Claude Opus 5.5 Signed-off-by: Madraka <8898640+Madraka@users.noreply.github.com> --- scripts/swarm-smoke.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripts/swarm-smoke.sh b/scripts/swarm-smoke.sh index bffdb58d..9e29192b 100755 --- a/scripts/swarm-smoke.sh +++ b/scripts/swarm-smoke.sh @@ -124,6 +124,10 @@ code=$(http -s -b "$work/jar" -o /dev/null -w '%{http_code}' -X POST "$studio/ap [ "$code" = 201 ] || fail "publish ($code)" for i in 1 2 3 4; do http -s "$site/" | grep -q "Smoke Site" || fail "the site after the publish"; done step "the owner signed up; a publish is live on the next request through the routing mesh" +# Both instances started together on one empty store: neither may surface a lost migration race (#309). +errs=$(timeout 60 docker service logs --raw "${stack}_cloudhal" 2>&1 | grep -F 'migration "' || true) +[ -z "$errs" ] || { echo "$errs" >&2; fail "an instance logged a migration error"; } +step "neither instance logged a migration error" timeout 60 docker rmi "$local_tag" >/dev/null 2>&1 || true echo