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
11 changes: 11 additions & 0 deletions .changeset/d1-handoff-writes.md
Original file line number Diff line number Diff line change
@@ -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`.
2 changes: 1 addition & 1 deletion docs/guides/self-host.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
1 change: 1 addition & 0 deletions docs/rfcs/0047-self-host-on-workerd.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
104 changes: 104 additions & 0 deletions packages/core-ts/src/cas-settle.ts
Original file line number Diff line number Diff line change
@@ -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<WriteState> {
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<RunResult[]> {
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<RunResult> {
const [r] = await casBatchOf(sql, statement);
return r ?? { changes: 0, lastRowId: null };
}

async function casBatchOf(sql: SqlDriver, statement: AimedStatement): Promise<RunResult[]> {
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 }];
}
}
75 changes: 63 additions & 12 deletions packages/core-ts/src/node-sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -52,14 +61,16 @@ export async function insertNodeStatement<K extends NodeKind>(
node: NodeTypes[K],
ts: string,
guard?: Cond,
): Promise<SqlStatement> {
): Promise<AimedStatement> {
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,
Expand All @@ -68,11 +79,13 @@ export async function insertNodeStatement<K extends NodeKind>(
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,
};
}

Expand All @@ -82,13 +95,15 @@ export async function casUpdateStatement<K extends NodeKind>(
next: NodeTypes[K],
expectedRev: number,
guard?: Cond,
): Promise<SqlStatement> {
): Promise<AimedStatement> {
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,
Expand All @@ -104,8 +119,9 @@ export function casDeleteStatement<K extends NodeKind>(
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 ?? [])],
};
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -269,14 +290,19 @@ export async function runOpBatch(
diagnose?: () => Promise<void>;
} = {},
): Promise<void> {
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;
Expand All @@ -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<void> {
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<T>(rows: { body: string }[]): T[] {
return rows.map((r) => JSON.parse(r.body) as T);
}
Expand Down
3 changes: 2 additions & 1 deletion packages/core-ts/src/release-apply.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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",
Expand Down
6 changes: 3 additions & 3 deletions packages/core-ts/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
Expand Down
4 changes: 3 additions & 1 deletion packages/core-ts/src/store/entries.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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),
Expand Down
4 changes: 3 additions & 1 deletion packages/core-ts/src/store/pages.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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),
]);
Expand Down
5 changes: 3 additions & 2 deletions packages/core-ts/src/store/sites.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down
Loading