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
6 changes: 6 additions & 0 deletions .changeset/migrate-race-309.md
Original file line number Diff line number Diff line change
@@ -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.
14 changes: 3 additions & 11 deletions packages/cloudflare/src/admin-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};

Expand Down Expand Up @@ -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);
Expand Down
16 changes: 16 additions & 0 deletions packages/storage/src/migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -52,13 +59,22 @@ 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);
}
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<boolean> {
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<string[]> {
const rows = await driver
.all<{ name: string }>(`SELECT name FROM ${MIGRATIONS_TABLE} ORDER BY name`)
Expand Down
120 changes: 120 additions & 0 deletions packages/storage/test/migrate-concurrent.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>((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();
}
});
});
9 changes: 9 additions & 0 deletions scripts/helm-smoke.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 "<title>Smoke Site</title>" || 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
Expand All @@ -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 "<title>Smoke Site</title>" || 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."
2 changes: 1 addition & 1 deletion scripts/size-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions scripts/swarm-smoke.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<title>Smoke Site</title>" || 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
Expand Down