diff --git a/.changeset/d1-handoff-writes.md b/.changeset/d1-handoff-writes.md new file mode 100644 index 00000000..641d594a --- /dev/null +++ b/.changeset/d1-handoff-writes.md @@ -0,0 +1,11 @@ +--- +"@cloudhal/core-ts": patch +"@cloudhal/storage": patch +--- + +Graph writes caught while D1 moves (#324) are no longer lost or applied twice. When a write gets D1's transient error (a graceful handoff in a self-host cluster, a deploy or an eviction on Cloudflare), the store reads its aim back: +- the new content hash, or the operation's `op_guards` row, means it applied and is reported as a success; +- the node still at the revision it read means the write was lost, and it runs once more; +- anything else is a `ConflictError`, as for any concurrent change. + +This covers single-node CAS writes, every `OpBatch` operation, site updates and publishes, entry and page deletes, snapshots and scheduled release publishes. `@cloudhal/storage` exports `isTransientD1Error`. diff --git a/docs/guides/self-host.md b/docs/guides/self-host.md index 97b838c5..71c1c8ad 100644 --- a/docs/guides/self-host.md +++ b/docs/guides/self-host.md @@ -144,7 +144,7 @@ CI runs it against SeaweedFS and RustFS. Instances with the same `.env` and store form one installation. Each Durable Object, including the database, runs on one instance at a time, and any instance routes requests to it. A load balancer in front can send both hosts to any instance. - **Network:** the cluster port 7000 must be reachable between instances only, on a private network. Instances authenticate each other with the cluster key, but their traffic is not encrypted, so use a VPC, WireGuard, Tailscale or Docker Swarm's `encrypted` overlay. -- **Stopping:** on SIGTERM an instance hands its objects to the others and exits within 8 s. `stop_grace_period: 15s` in the compose file allows for that. A database read that was on its way to the stopping instance is retried on the new owner, so pages and Studio keep answering. A write caught in that moment fails once, and Studio shows the error. +- **Stopping:** on SIGTERM an instance hands its objects to the others and exits within 8 s. `stop_grace_period: 15s` in the compose file allows for that. A database read that was on its way to the stopping instance is retried on the new owner, so pages and Studio keep answering. A content write caught in that moment (a save, a publish, a scheduled release) reads back whether it applied and, if not, runs once more, so it is never lost or applied twice. Other writes caught then, such as an audit row or a sign-in, fail once and are repeated by the person or agent. - **A killed instance:** its objects move once its lease expires, about 20 s later. Until then, requests that need one of its objects (the database among them) fail, so run at least two instances behind a readiness-aware load balancer. - **Readiness:** use `GET /ready` on port 7000 as the readiness probe of a rolling restart. diff --git a/docs/rfcs/0047-self-host-on-workerd.md b/docs/rfcs/0047-self-host-on-workerd.md index 0eaa27a6..f3094b87 100644 --- a/docs/rfcs/0047-self-host-on-workerd.md +++ b/docs/rfcs/0047-self-host-on-workerd.md @@ -152,6 +152,7 @@ The site Worker needs the site's id in its config (`CLOUDHAL_SITE_ID`). Open que - **Liveness:** `GET /api/health` on the Studio socket (RFC-0043). - **Readiness:** `GET /ready` on the cluster port. It answers 200 while the instance serves, holds its lease and is not stopping, and 503 otherwise. - **Shutdown:** on SIGTERM workerd hands its Durable Objects to its peers, keeps accepting requests for at least 5 s, and exits within `stopTimeoutMs`, which stays at 8 s. The recipes set `stop_grace_period: 15s` (Compose and Swarm) and keep Kubernetes' 30 s grace period. +- **Writes during a handoff** (*amended 2026-11-29, #324*): a graph write that gets D1's transient error reads its aim back (`core-ts`'s `cas-settle.ts`). If the new content hash or the operation's `op_guards` row is there, it applied. If the node is still at the revision it read, it was lost and runs once more. Anything else is a `ConflictError`. Reads are retried by `D1Driver` (#290). The failover test sends draft edits through both SIGTERM handoffs and requires none to fail. - **A killed instance:** its objects move only when its lease expires, after about 20 s. The spike measured about 16 s of 500 answers for D1-backed routes, which needs at least two replicas behind a readiness-aware load balancer. ### 7a. Observability diff --git a/packages/core-ts/src/cas-settle.ts b/packages/core-ts/src/cas-settle.ts new file mode 100644 index 00000000..19559751 --- /dev/null +++ b/packages/core-ts/src/cas-settle.ts @@ -0,0 +1,104 @@ +/** + * #324: graph writes caught while D1 moves. When D1's Durable Object moves to another instance + * (a graceful handoff in a self-host cluster, a deploy or an eviction on Cloudflare), a write on + * its way gets a transient error (`isTransientD1Error`), and it may or may not have applied. Every + * graph write is a CAS anchored on content hashes (AGENTS.md rule 4), so the writer can read its + * aim back and know: + * + * - **applied:** the node has the write's new hash (an insert or update), or is gone (a delete), or + * the operation's `op_guards` row exists: report what a successful batch reports; + * - **lost:** the node is still at the revision the write read (or absent, for an insert): run the + * same statements once more; a second failure is reported as it is; + * - **moved:** anything else, someone else's write: report a CAS miss (no changes), so the caller + * raises its `ConflictError`, as for any concurrent change. + * + * No transaction and no new statement shape: one read after the error, and at most one retry. + * SQLite drivers never raise a transient error, so this never runs on them. + */ +import { + isTransientD1Error, + type RunResult, + type SqlDriver, + type SqlStatement, +} from "@cloudhal/storage"; + +/** + * What a statement writes, for the read-back: a node at a new hash (`fromRev` undefined for an + * insert), a node deleted at `fromRev` (no `hash`), or a row that exists once it is written. + */ +export type WriteAim = + | { readonly id: string; readonly hash: string; readonly fromRev?: number | undefined } + | { readonly id: string; readonly hash?: undefined; readonly fromRev: number } + | { readonly probe: SqlStatement }; + +/** A statement that carries its aim (the node statement builders attach one). */ +export type AimedStatement = SqlStatement & { readonly aim?: WriteAim | undefined }; + +export type WriteState = "applied" | "lost" | "moved"; + +/** Where the write stands after a transient error, read with the driver's retried reads. */ +export async function writeState(sql: SqlDriver, aim: WriteAim): Promise { + if ("probe" in aim) { + const row = await sql.get(aim.probe.sql, aim.probe.params ?? []); + return row ? "applied" : "lost"; + } + const row = await sql.get<{ rev: number; hash: string }>( + "SELECT rev, hash FROM nodes WHERE id = ?", + [aim.id], + ); + if (aim.hash === undefined) return !row ? "applied" : row.rev === aim.fromRev ? "lost" : "moved"; + if (row?.hash === aim.hash) return "applied"; + const untouched = aim.fromRev === undefined ? !row : row?.rev === aim.fromRev; + return untouched ? "lost" : "moved"; +} + +const aimOf = (s: SqlStatement | undefined) => (s as AimedStatement | undefined)?.aim; +const none = (n: number): RunResult[] => + Array.from({ length: n }, () => ({ changes: 0, lastRowId: null })); + +/** + * `sql.batch(statements)`, settled after a transient error by the first statement's aim. Applied: + * each aimed statement reports 1 change when its own aim is met (the batch is atomic, so the rest + * ran too) and 0 otherwise; unaimed statements report 0. Moved: every statement reports 0, a CAS + * miss. Without an aim on the first statement the error is thrown as it is. + */ +export async function casBatch( + sql: SqlDriver, + statements: readonly AimedStatement[], +): Promise { + try { + return await sql.batch(statements); + } catch (error) { + const aim = aimOf(statements[0]); + if (!aim || !isTransientD1Error(error)) throw error; + const state = await writeState(sql, aim); + if (state === "lost") return sql.batch(statements); + if (state === "moved") return none(statements.length); + return Promise.all( + statements.map(async (s) => { + const own = aimOf(s); + const met = + own === aim || (own !== undefined && (await writeState(sql, own)) === "applied"); + return { changes: met ? 1 : 0, lastRowId: null }; + }), + ); + } +} + +/** `sql.run` of one aimed statement, settled the same way. */ +export async function casRun(sql: SqlDriver, statement: AimedStatement): Promise { + const [r] = await casBatchOf(sql, statement); + return r ?? { changes: 0, lastRowId: null }; +} + +async function casBatchOf(sql: SqlDriver, statement: AimedStatement): Promise { + try { + return [await sql.run(statement.sql, statement.params ?? [])]; + } catch (error) { + const aim = aimOf(statement); + if (!aim || !isTransientD1Error(error)) throw error; + const state = await writeState(sql, aim); + if (state === "lost") return [await sql.run(statement.sql, statement.params ?? [])]; + return [{ changes: state === "applied" ? 1 : 0, lastRowId: null }]; + } +} diff --git a/packages/core-ts/src/node-sql.ts b/packages/core-ts/src/node-sql.ts index 44a5b3b6..c5ecde3f 100644 --- a/packages/core-ts/src/node-sql.ts +++ b/packages/core-ts/src/node-sql.ts @@ -2,7 +2,16 @@ * SQL building blocks for node writes: kind-aware insert / CAS / delete statements, guards, and the * operation batch that ends in `op_guards` assertion rows (RFC-0002 ยง4.3). Internal to core-ts. */ -import type { SqlDriver, SqlStatement, SqlValue } from "@cloudhal/storage"; +import { + isTransientD1Error, + type SqlDriver, + type SqlStatement, + type SqlValue, +} from "@cloudhal/storage"; +import type { AimedStatement } from "./cas-settle.ts"; + +export { casBatch, casRun } from "./cas-settle.ts"; + import { ConflictError, InvariantError, @@ -52,14 +61,16 @@ export async function insertNodeStatement( node: NodeTypes[K], ts: string, guard?: Cond, -): Promise { +): Promise { + const hash = await nodeHash(node); + const aim = { id: node.id, hash }; const values = [ node.id, siteIdOf(kind, node), kind, uniquenessKey(kind, node), node.rev, - await nodeHash(node), + hash, canonicalJson(node), ts, ts, @@ -68,11 +79,13 @@ export async function insertNodeStatement( return { sql: "INSERT INTO nodes (id, site_id, kind, key, rev, hash, body, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", params: values, + aim, }; return { sql: `INSERT INTO nodes (id, site_id, kind, key, rev, hash, body, created_at, updated_at) SELECT ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE ${guard.sql}`, params: [...values, ...guard.params], + aim, }; } @@ -82,13 +95,15 @@ export async function casUpdateStatement( next: NodeTypes[K], expectedRev: number, guard?: Cond, -): Promise { +): Promise { + const hash = await nodeHash(next); return { + aim: { id: next.id, hash, fromRev: expectedRev }, sql: `UPDATE nodes SET key = ?, rev = ?, hash = ?, body = ?, updated_at = ? WHERE id = ? AND rev = ? AND kind = ? AND site_id = ?${guard ? ` AND ${guard.sql}` : ""}`, params: [ uniquenessKey(kind, next), next.rev, - await nodeHash(next), + hash, canonicalJson(next), next.updatedAt, next.id, @@ -104,8 +119,9 @@ export function casDeleteStatement( kind: K, node: NodeTypes[K], guard?: Cond, -): SqlStatement { +): AimedStatement { return { + aim: { id: node.id, fromRev: node.rev }, sql: `DELETE FROM nodes WHERE id = ? AND rev = ? AND kind = ? AND site_id = ?${guard ? ` AND ${guard.sql}` : ""}`, params: [node.id, node.rev, kind, siteIdOf(kind, node), ...(guard?.params ?? [])], }; @@ -159,6 +175,11 @@ export class OpBatch { return this.#planned; } + /** Whether the batch ends in `op_guards` rows, the proof it applied (#324). */ + get guarded(): boolean { + return this.#expect.size > 0 || this.#absent.size > 0 || this.#conds.length > 0; + } + /** * Anchors every write of this batch on `cond` instead of on its own first write: for statements * that join another node's CAS (the site update, RFC-0038), anchored on that node's new hash. @@ -269,14 +290,19 @@ export async function runOpBatch( diagnose?: () => Promise; } = {}, ): Promise { - try { - // Sweep assertion rows older than 30 days (indexed; usually deletes nothing). - await sql.run("DELETE FROM op_guards WHERE created_at < ?", [ + // Sweep assertion rows older than 30 days (indexed; usually deletes nothing). Idempotent, and the + // next operation repeats it, so a transient failure here is never the write's (#324). + await sql + .run("DELETE FROM op_guards WHERE created_at < ?", [ new Date(Date.parse(batch.ts) - OP_GUARD_TTL_MS).toISOString(), - ]); - await sql.batch(batch.statements()); + ]) + .catch((e: unknown) => { + if (!isTransientD1Error(e)) throw e; + }); + try { + await settleOpBatch(sql, batch); } catch (e) { - if (isOpGuardViolation(e)) { + if (isOpGuardViolation(e) || e instanceof OperationMovedError) { await options.diagnose?.(); for (const p of batch.planned) { if (p.readRev === undefined) continue; @@ -289,6 +315,31 @@ export async function runOpBatch( } } +/** A transient failure after which another write had moved what the operation read (#324). */ +class OperationMovedError extends Error {} + +/** + * The batch, settled after a transient error (#324, `cas-settle.ts`): its `op_guards` rows prove it + * applied; with none, and every node it read still at that revision (and every node it inserts + * still absent), it was lost and runs once more; otherwise someone else moved a node first. + */ +async function settleOpBatch(sql: SqlDriver, batch: OpBatch): Promise { + try { + await sql.batch(batch.statements()); + } catch (e) { + if (!isTransientD1Error(e) || !batch.guarded) throw e; + const done = await sql.get("SELECT 1 AS ok FROM op_guards WHERE op_id = ? LIMIT 1", [ + batch.opId, + ]); + if (done) return; + for (const p of batch.planned) { + const row = await sql.get<{ rev: number }>("SELECT rev FROM nodes WHERE id = ?", [p.id]); + if (p.readRev === undefined ? row : row?.rev !== p.readRev) throw new OperationMovedError(); + } + await sql.batch(batch.statements()); + } +} + export function parseRows(rows: { body: string }[]): T[] { return rows.map((r) => JSON.parse(r.body) as T); } diff --git a/packages/core-ts/src/release-apply.ts b/packages/core-ts/src/release-apply.ts index 93d8b097..d80dfb68 100644 --- a/packages/core-ts/src/release-apply.ts +++ b/packages/core-ts/src/release-apply.ts @@ -40,6 +40,7 @@ import { SCHEDULER_ACTOR, } from "@cloudhal/schedules/engine"; import type { BlobStore, SqlDriver, SqlStatement } from "@cloudhal/storage"; +import { casBatch } from "./cas-settle.ts"; import { canonicalJson, nodeHash } from "./hash.ts"; import { ID_PREFIX } from "./ids.ts"; import { casUpdateStatement } from "./node-sql.ts"; @@ -352,7 +353,7 @@ export async function publishRelease( ], }, ]; - const results = await ctx.sql.batch(statements); + const results = await casBatch(ctx.sql, statements); if ((results[0]?.changes ?? 0) === 1) return { kind: "published", diff --git a/packages/core-ts/src/store.ts b/packages/core-ts/src/store.ts index 23714128..9d18d4b7 100644 --- a/packages/core-ts/src/store.ts +++ b/packages/core-ts/src/store.ts @@ -56,7 +56,7 @@ import { MEDIA_LIMITS } from "./media/types.ts"; import type { TargetRef } from "./menu.ts"; import { MenuEngine } from "./menu-store.ts"; import type { Resolution } from "./names.ts"; -import { type Cond, mapUniqueViolation, type Row } from "./node-sql.ts"; +import { type Cond, casBatch, casRun, mapUniqueViolation, type Row } from "./node-sql.ts"; import type { Creatable, NodeKind, SiteNode } from "./nodes.ts"; import { BodyProposals } from "./proposals.ts"; import type { RedirectMatch } from "./redirects.ts"; @@ -1194,8 +1194,8 @@ export class SiteGraphStore { extra: readonly SqlStatement[] = [], ): Promise<{ changes: number }> { try { - if (extra.length === 0) return await this.#sql.run(statement.sql, statement.params ?? []); - const [first] = await this.#sql.batch([statement, ...extra]); + if (extra.length === 0) return await casRun(this.#sql, statement); + const [first] = await casBatch(this.#sql, [statement, ...extra]); return { changes: first?.changes ?? 0 }; } catch (e) { throw mapUniqueViolation(e, kind, key); diff --git a/packages/core-ts/src/store/entries.ts b/packages/core-ts/src/store/entries.ts index 1b7683ae..e5164f04 100644 --- a/packages/core-ts/src/store/entries.ts +++ b/packages/core-ts/src/store/entries.ts @@ -1,6 +1,7 @@ /** Content entry writes: corrections, the block index, gates, terms, assets and path changes. */ import { assertValid, type ContentEntry } from "@cloudhal/core-contracts"; import { indexMarkdown, withoutIndex } from "../body-index.ts"; +import { casBatch } from "../cas-settle.ts"; import { prepareCorrections } from "../corrections.ts"; import { ConflictError, NotFoundError } from "../errors.ts"; import { fieldDefinitions } from "../fields/types.ts"; @@ -197,10 +198,11 @@ export class EntryEngine { if (options.dryRun) return; const lists = await planListValuesDelete(this.#ctx.sql, site, entry, this.#ctx.stamp()); const guard = leave ? ` AND ${leave.guard.sql}` : ""; - const [r] = await this.#ctx.sql.batch([ + const [r] = await casBatch(this.#ctx.sql, [ { sql: `DELETE FROM nodes WHERE id = ? AND rev = ? AND kind = 'contentEntry' AND site_id = ?${guard}`, params: [entry.id, entry.rev, entry.siteId, ...(leave?.guard.params ?? [])], + aim: { id: entry.id, fromRev: entry.rev }, }, this.#ctx.assets.dropRefsStatement(entry.id), dropEntryRefsStatement(entry.id), diff --git a/packages/core-ts/src/store/pages.ts b/packages/core-ts/src/store/pages.ts index 622a88b5..d05d7387 100644 --- a/packages/core-ts/src/store/pages.ts +++ b/packages/core-ts/src/store/pages.ts @@ -1,6 +1,7 @@ /** Page writes: create (with the site's page list), update (path changes, redirects), delete. */ import { assertValid, type Page, type Site } from "@cloudhal/core-contracts"; import { type BlockWriter, indexMarkdown, withoutIndex } from "../body-index.ts"; +import { casBatch } from "../cas-settle.ts"; import { ConflictError, NotFoundError } from "../errors.ts"; import { nodeHash } from "../hash.ts"; import { assertUnlocked } from "../holds.ts"; @@ -181,11 +182,12 @@ export class PageEngine { }; assertValid("site", nextSite); const siteHash = await nodeHash(nextSite); - const results = await this.#ctx.sql.batch([ + const results = await casBatch(this.#ctx.sql, [ await casUpdateStatement("site", nextSite, site.rev), { sql: "DELETE FROM nodes WHERE id = ? AND rev = ? AND kind = 'page' AND site_id = ? AND EXISTS (SELECT 1 FROM nodes WHERE id = ? AND hash = ?)", params: [page.id, page.rev, site.id, site.id, siteHash], + aim: { id: page.id, fromRev: page.rev }, }, this.#ctx.assets.dropRefsStatement(page.id), ]); diff --git a/packages/core-ts/src/store/sites.ts b/packages/core-ts/src/store/sites.ts index 846d29e6..346d4f22 100644 --- a/packages/core-ts/src/store/sites.ts +++ b/packages/core-ts/src/store/sites.ts @@ -2,6 +2,7 @@ import { assertValid, type Site } from "@cloudhal/core-contracts"; import type { SqlStatement } from "@cloudhal/storage"; import { checkTimeZone, isTimeZone } from "../availability.ts"; +import { casBatch, casRun } from "../cas-settle.ts"; import { type CollectionCount, type CollectionInfo, collectionRegistry } from "../collections.ts"; import { ConflictError, InvariantError, isOpGuardViolation, NotFoundError } from "../errors.ts"; import { nodeHash } from "../hash.ts"; @@ -166,9 +167,9 @@ export class SiteEngine { /** The CAS alone, or with its anchored statements; a failed `op_guards` assertion is a miss. */ async #run(s: SqlStatement, more: SqlStatement[]): Promise<{ changes: number }> { - if (more.length === 0) return this.#ctx.sql.run(s.sql, s.params ?? []); + if (more.length === 0) return casRun(this.#ctx.sql, s); try { - return (await this.#ctx.sql.batch([s, ...more]))[0] ?? { changes: 0 }; + return (await casBatch(this.#ctx.sql, [s, ...more]))[0] ?? { changes: 0 }; } catch (e) { if (isOpGuardViolation(e)) return { changes: 0 }; throw e; diff --git a/packages/core-ts/src/store/snapshots.ts b/packages/core-ts/src/store/snapshots.ts index 964ce0d5..c0e95f55 100644 --- a/packages/core-ts/src/store/snapshots.ts +++ b/packages/core-ts/src/store/snapshots.ts @@ -1,5 +1,6 @@ /** Snapshots: node refs with content hashes, bodies in the blob store, holds, asset blobs. */ import { assertValid, type NodeRef, type Snapshot } from "@cloudhal/core-contracts"; +import { casBatch } from "../cas-settle.ts"; import { BLOB_CONCURRENCY, eachLimited } from "../concurrency.ts"; import { NotFoundError } from "../errors.ts"; import { canonicalJson } from "../hash.ts"; @@ -85,8 +86,12 @@ export class SnapshotEngine { ...rows.filter((r) => r.kind === "asset").map((r) => r.body), ...heldAssets, ]); - await this.#ctx.sql.batch([ + // #324: a snapshot that exists after a transient error was written; one that does not, was not. + await casBatch(this.#ctx.sql, [ { + aim: { + probe: { sql: "SELECT 1 AS ok FROM snapshots WHERE id = ?", params: [snapshot.id] }, + }, sql: "INSERT INTO snapshots (id, site_id, parent_id, site_rev, body, created_at) VALUES (?, ?, ?, ?, ?, ?)", params: [ snapshot.id, diff --git a/packages/core-ts/src/taxonomy.ts b/packages/core-ts/src/taxonomy.ts index 4a32024e..09a89a58 100644 --- a/packages/core-ts/src/taxonomy.ts +++ b/packages/core-ts/src/taxonomy.ts @@ -29,6 +29,8 @@ import { foldName, humanizeSlug, type Resolution, resolveTermInputs, termName } import { and, type Cond, + casBatch, + casRun, casUpdateStatement, insertNodeStatement, OpBatch, @@ -275,7 +277,7 @@ export class TaxonomyEngine { async #runUnique(statement: SqlStatement, kind: string, key: string) { try { - return await this.#sql.run(statement.sql, statement.params ?? []); + return await casRun(this.#sql, statement); } catch (e) { if (isUniqueViolation(e)) throw new UniqueConstraintError(kind, key); throw e; @@ -810,9 +812,7 @@ export class TaxonomyEngine { const written = refs?.node ?? next; const statement = await casUpdateStatement("term", written, stored.rev, refs?.guard); const extra = refs?.statements(await nodeHash(written)) ?? []; - const r = extra.length - ? (await this.#sql.batch([statement, ...extra]))[0] - : await this.#sql.run(...stmt(statement)); + const [r] = await casBatch(this.#sql, [statement, ...extra]); if (r?.changes !== 1) { const rev = await this.#revOf(t.id); if (rev === stored.rev) await refs?.diagnose(); diff --git a/packages/core-ts/src/testing-handoff.ts b/packages/core-ts/src/testing-handoff.ts new file mode 100644 index 00000000..63431112 --- /dev/null +++ b/packages/core-ts/src/testing-handoff.ts @@ -0,0 +1,170 @@ +/** + * #324: graph writes caught while D1 moves, on every backend. `HandoffDriver` fails the next write + * with D1's transient error, either before the write reaches the database (it was lost) or after + * it applied (only its answer was lost), and the store must report success either way, with the + * write applied exactly once; a concurrent write in between must still be a ConflictError. + */ +import type { RunResult, SqlDriver, SqlStatement, SqlValue } from "@cloudhal/storage"; +import { dropAllTables } from "@cloudhal/storage/testing"; +import { afterAll, beforeEach, describe, expect, it } from "vitest"; +import { ConflictError } from "./errors.ts"; +import { seedStarterSite } from "./seed.ts"; +import { SiteGraphStore } from "./store.ts"; +import type { StoreFactory } from "./testing.ts"; + +type When = "before" | "after"; + +/** What workerd's D1 binding throws when the database moves under a request. */ +const lost = () => + Object.assign(new Error("D1_ERROR: Network connection lost."), { + cause: new Error("Network connection lost."), + }); + +/** A driver whose next write (`run` or `batch`, not the `op_guards` sweep) fails transiently. */ +export class HandoffDriver implements SqlDriver { + readonly name: string; + readonly #inner: SqlDriver; + #armed: { when: When; meanwhile?: () => Promise } | undefined; + shots = 0; + + constructor(inner: SqlDriver) { + this.#inner = inner; + this.name = inner.name; + } + + /** Fails the next write; `meanwhile` runs (another writer) before the failure is thrown. */ + arm(when: When, meanwhile?: () => Promise): void { + this.#armed = { when, ...(meanwhile ? { meanwhile } : {}) }; + } + + async #shoot(write: () => Promise): Promise { + const armed = this.#armed; + if (!armed) return write(); + this.#armed = undefined; + this.shots++; + if (armed.when === "after") await write(); + await armed.meanwhile?.(); + throw lost(); + } + + get>(sql: string, params?: readonly SqlValue[]) { + return this.#inner.get(sql, params); + } + all>(sql: string, params?: readonly SqlValue[]) { + return this.#inner.all(sql, params); + } + run(sql: string, params?: readonly SqlValue[]): Promise { + if (sql.startsWith("DELETE FROM op_guards")) return this.#inner.run(sql, params); + return this.#shoot(() => this.#inner.run(sql, params)); + } + batch(statements: readonly SqlStatement[]): Promise { + return this.#shoot(() => this.#inner.batch(statements)); + } + exec(sql: string): Promise { + return this.#inner.exec(sql); + } + close(): Promise { + return this.#inner.close(); + } +} + +export function handoffSuite(label: string, factory: StoreFactory): void { + describe(`graph writes across a D1 move (#324): ${label}`, () => { + let store: SiteGraphStore; + let other: SiteGraphStore; + let sql: HandoffDriver; + let siteId: string; + + beforeEach(async () => { + const made = await factory.create(); + await dropAllTables(made.sql); + sql = new HandoffDriver(made.sql); + store = new SiteGraphStore({ sql, blobs: made.blobs }); + // a second writer on the same database, untouched by the failures + other = new SiteGraphStore({ sql: made.sql, blobs: made.blobs }); + await store.init(); + siteId = (await seedStarterSite(store, { name: "Handoff", slug: "handoff" })).id; + }); + + afterAll(async () => { + await factory.dispose?.(); + }); + + const post = async () => { + const e = (await store.listContentEntries(siteId)).find((x) => x.slug === "hello-world"); + if (!e) throw new Error("no starter post"); + return e; + }; + + for (const when of ["before", "after"] as const) { + it(`an entry update lost ${when} it applied succeeds, applied once`, async () => { + const e = await post(); + sql.arm(when); + const saved = await store.updateContentEntry({ ...e, title: `Moved ${when}` }); + expect(sql.shots).toBe(1); + expect(saved.rev).toBe(e.rev + 1); + const stored = await store.getContentEntry(e.id); + expect(stored).toMatchObject({ rev: e.rev + 1, title: `Moved ${when}` }); + }); + + it(`a multi-node operation (a redirect) lost ${when} it applied succeeds, applied once`, async () => { + sql.arm(when); + await store.createRedirect({ + siteId, + from: `/old-${when}`, + to: "/about", + status: 301, + match: "exact", + reason: "manual", + }); + expect(sql.shots).toBe(1); + const mine = (await store.listRedirects(siteId)).filter((r) => r.from === `/old-${when}`); + expect(mine).toHaveLength(1); + }); + + it(`a snapshot and a publish lost ${when} they applied succeed, applied once`, async () => { + const actor = { kind: "human" as const, id: "user_01HANDOFF0001", name: "Owner" }; + sql.arm(when); + const snap = await store.createSnapshot(siteId, { actor, reason: "publish" }); + expect((await store.listSnapshots(siteId)).filter((s) => s.id === snap.id)).toHaveLength(1); + const site = await store.getSite(siteId); + sql.arm(when); + const published = await store.publish(site as NonNullable, snap.id); + expect(sql.shots).toBe(2); + expect(published.publishedSnapshotId).toBe(snap.id); + expect((await store.getSite(siteId))?.rev).toBe((site?.rev ?? 0) + 1); + }); + + it(`an entry delete lost ${when} it applied succeeds`, async () => { + const e = await post(); + sql.arm(when); + await store.deleteContentEntry(e); + expect(await store.getContentEntry(e.id)).toBeUndefined(); + }); + } + + it("a write lost while another writer moved the node is a ConflictError, as before", async () => { + const e = await post(); + sql.arm("before", async () => { + await other.updateContentEntry({ ...e, title: "Someone else" }); + }); + await expect(store.updateContentEntry({ ...e, title: "Mine" })).rejects.toBeInstanceOf( + ConflictError, + ); + expect((await store.getContentEntry(e.id))?.title).toBe("Someone else"); + }); + + it("an operation lost while another writer moved what it read is a ConflictError", async () => { + const e = await post(); + const site = await store.getSite(siteId); + sql.arm("before", async () => { + await other.updateSite({ ...(site as NonNullable), name: "Renamed" }); + }); + await expect( + store.updateSite({ ...(site as NonNullable), name: "Mine" }), + ).rejects.toBeInstanceOf(ConflictError); + expect((await store.getSite(siteId))?.name).toBe("Renamed"); + expect((await store.getContentEntry(e.id))?.rev).toBe(e.rev); + }); + }); +} diff --git a/packages/core-ts/test/handoff.test.ts b/packages/core-ts/test/handoff.test.ts new file mode 100644 index 00000000..5297c900 --- /dev/null +++ b/packages/core-ts/test/handoff.test.ts @@ -0,0 +1,25 @@ +/** #324: graph writes across a D1 move, on SQLite and Miniflare D1. */ +import { MemoryBlobStore } from "@cloudhal/storage"; +import { D1Driver } from "@cloudhal/storage/d1"; +import { BetterSqlite3Driver } from "@cloudhal/storage/sqlite"; +import { createMiniflareD1 } from "@cloudhal/storage/testing"; +import { handoffSuite } from "../src/testing-handoff.ts"; + +handoffSuite("better-sqlite3", { + create: async () => ({ + sql: await BetterSqlite3Driver.open(":memory:"), + blobs: new MemoryBlobStore(), + }), +}); + +let d1: Awaited> | undefined; +handoffSuite("Cloudflare D1 (Miniflare)", { + async create() { + d1 ??= await createMiniflareD1(); + return { sql: new D1Driver(d1.db), blobs: new MemoryBlobStore() }; + }, + async dispose() { + await d1?.dispose(); + d1 = undefined; + }, +}); diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts index ea63ac27..cc4a2f45 100644 --- a/packages/storage/src/index.ts +++ b/packages/storage/src/index.ts @@ -17,4 +17,5 @@ export { LayeredBlobStore } from "./blob/layered.ts"; export { MemoryBlobStore } from "./blob/memory.ts"; export { SqlBlobStore, type SqlBlobStoreOptions } from "./blob/sql.ts"; export * from "./migrate.ts"; +export { isReadOnlySql, isTransientD1Error } from "./sql/d1-retry.ts"; export * from "./types.ts"; diff --git a/scripts/failover-smoke.ts b/scripts/failover-smoke.ts index 6c9e44e2..b9a10140 100644 --- a/scripts/failover-smoke.ts +++ b/scripts/failover-smoke.ts @@ -14,7 +14,8 @@ * 4. The release, due while a was down, must run exactly once: one succeeded run, not early, and * the change live on every instance. a starts again on its volume and rejoins. * 5. b and then c are stopped gracefully (SIGTERM, `docker stop`) while the other two take a - * steady load: not one request may fail during the handoff, and each exits by itself within + * steady load of reads and draft edits of the post (#324): not one request or write may fail + * during the handoff, the last edit is the one stored, and each exits by itself within * the 15 s grace period. One of them owns the database after step 3, so one of the stops is a * real handoff. * 6. No instance logged a migration error (#309), and the release still has exactly one run. @@ -197,6 +198,8 @@ const siteId = env.CLOUDHAL_SITE_ID as string; const admin = { authorization: `Bearer ${env.CLOUDHAL_DEPLOY_TOKEN}` }; let cookie = ""; let releaseId = ""; +/** The starter post, which the handoffs edit as a draft (#324). */ +let postId = ""; const api = (n: Name, p: string, init: RequestInit = {}) => req(`${studio(n)}${p}`, { ...init, @@ -273,6 +276,7 @@ async function scheduleRelease(at: number): Promise { body: JSON.stringify({ ...entry, title: NEW_TITLE }), }); expect(saved.status === 200, "the draft change", saved.body); + postId = entry?.id as string; const when = { at: new Date(at).toISOString() }; const draft = await post("a", `/api/sites/${siteId}/releases`, { title: "Failover", @@ -296,11 +300,39 @@ async function runsOf(n: Name): Promise<{ state: string; startedAt?: string; tri return (r.body as { runs: { state: string; startedAt?: string; trigger?: string }[] }).runs; } -/** Steady load on `targets` while `victim` stops gracefully: not one request may fail. */ +/** A draft edit of the starter post through `n` (the live post keeps its released title). */ +async function saveDraft(n: Name, summary: string): Promise { + const path = `/api/sites/${siteId}/entries/${postId}`; + const got = await api(n, path); + if (got.status !== 200) return failed("GET entry", got); + const saved = await api(n, path, { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ ...(got.body as Record), summary }), + }); + return saved.status === 200 ? undefined : failed("PUT entry", saved); +} + +/** + * Steady load on `targets` while `victim` stops gracefully: reads on every target and draft edits + * through the first (#324), and not one may fail; the last edit is the one stored. + */ async function handoff(victim: Name, targets: Name[]): Promise { const failures: string[] = []; let requests = 0; + let writes = 0; + let lastWritten = ""; let stopping = true; + const writer = async (n: Name) => { + while (stopping) { + const summary = `handoff of ${victim}, write ${writes + 1}`; + const why = await saveDraft(n, summary); + writes++; + if (why && failures.length < 50) failures.push(`${elapsed()} ${n} write: ${why}`); + else if (!why) lastWritten = summary; + await sleep(250); + } + }; const loop = async (n: Name) => { while (stopping) { const why = await serves(n, NEW_TITLE); @@ -309,7 +341,7 @@ async function handoff(victim: Name, targets: Name[]): Promise { await sleep(100); } }; - const loops = targets.map(loop); + const loops = [...targets.map(loop), writer(targets[0] as Name)]; await sleep(3000); const started = Date.now(); await docker(["stop", "--timeout", "15", ctr(victim)], 60_000); @@ -320,8 +352,16 @@ async function handoff(victim: Name, targets: Name[]): Promise { await Promise.all(loops); const exit = await docker(["inspect", "--format", "{{.State.ExitCode}}", ctr(victim)]); expect(failures.length === 0, `requests failed while ${victim} stopped`, failures); + const stored = await api(targets[0] as Name, `/api/sites/${siteId}/entries/${postId}`); + const summary = (stored.body as { summary?: string }).summary; + expect(summary === lastWritten, "the last draft edit is the one stored", { + summary, + lastWritten, + }); expect(exit !== "137" && took < 15, `${victim} exits by itself within 15 s`, { exit, took }); - step(`${victim} stopped on SIGTERM in ${took.toFixed(1)} s; ${requests} rounds, none failed`); + step( + `${victim} stopped on SIGTERM in ${took.toFixed(1)} s; ${requests} rounds and ${writes} writes, none failed`, + ); } async function diagnostics(): Promise { diff --git a/scripts/size-baseline.json b/scripts/size-baseline.json index 20d767af..db9f92d4 100644 --- a/scripts/size-baseline.json +++ b/scripts/size-baseline.json @@ -303,7 +303,7 @@ "params": 5 }, "packages/api/src/app.ts::createApi": { - "lines": 157 + "lines": 152 }, "packages/api/src/build-turn.ts::runBuildTurn": { "lines": 260