From 32cbca4475b91748be47157246300d008e8e28fb Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:28:21 -0600 Subject: [PATCH 1/2] spike(id): probe D1 journal sessions --- pkgs/id/worker-poc/d1-journal-poc/README.md | 38 +++ pkgs/id/worker-poc/d1-journal-poc/smoke.mjs | 258 ++++++++++++++++++ pkgs/id/worker-poc/d1-journal-poc/worker.mjs | 207 ++++++++++++++ .../worker-poc/d1-journal-poc/wrangler.toml | 10 + 4 files changed, 513 insertions(+) create mode 100644 pkgs/id/worker-poc/d1-journal-poc/README.md create mode 100644 pkgs/id/worker-poc/d1-journal-poc/smoke.mjs create mode 100644 pkgs/id/worker-poc/d1-journal-poc/worker.mjs create mode 100644 pkgs/id/worker-poc/d1-journal-poc/wrangler.toml diff --git a/pkgs/id/worker-poc/d1-journal-poc/README.md b/pkgs/id/worker-poc/d1-journal-poc/README.md new file mode 100644 index 000000000..bce9c4d19 --- /dev/null +++ b/pkgs/id/worker-poc/d1-journal-poc/README.md @@ -0,0 +1,38 @@ +# Local D1 journal-fit PoC + +From `pkgs/id/worker-poc`, run the whole smoke with: + +```sh +node d1-journal-poc/smoke.mjs +``` + +It needs Node.js 22 or newer and `wrangler` available on `PATH`. The harness +starts its own local Wrangler Worker on a free ephemeral port, gives it a +unique temporary D1 persistence directory, and stops/removes both on exit. Its +separate config is always used with `--local`; the placeholder database ID is +not a remote database configuration. It does not use the existing Worker-PoC +Wrangler config or its Durable Object database. + +The Worker stores submitted newline-terminated JSONL bytes directly as a D1 +BLOB, assigning a per-world ordinal with an explicit `ORDER BY ordinal ASC` +when reading snapshots and tails. The smoke uses one synthetic world and the +current journal header version 1 (`created` and `caps_granted` entries). It +checks that a bookmark from an append is carried to a separate request and +that snapshot bytes plus a later tail are exactly the submitted JSONL bytes. + +## Scope and limits + +- It assumes #806's single writer per world. This is an ordinal-allocation + fit probe, not a multi-writer conflict protocol. +- #5863's storage contract is still open; this schema is only for this PoC. +- There is no signature verification implementation here. The probe checks + exact-byte storage and ordering only. +- A D1 bookmark is a read-consistency token, distinct from the stream cursor. + This PoC's stream cursor is only the last returned ordinal; it is not the + proposed production ordinal-plus-digest cursor. +- D1 documents `withSession()` sequential consistency and bookmark use across + requests as a provider contract: + [D1 `withSession`](https://developers.cloudflare.com/d1/worker-api/d1-database/#withsession) + and [D1 read replication](https://developers.cloudflare.com/d1/best-practices/read-replication/). + Local Wrangler cannot prove regional replica routing, production + `served_by_region`/`served_by_primary`, or production replica behavior. diff --git a/pkgs/id/worker-poc/d1-journal-poc/smoke.mjs b/pkgs/id/worker-poc/d1-journal-poc/smoke.mjs new file mode 100644 index 000000000..0cc2a1fb0 --- /dev/null +++ b/pkgs/id/worker-poc/d1-journal-poc/smoke.mjs @@ -0,0 +1,258 @@ +// Local Wrangler D1 journal-fit smoke. Run from worker-poc: +// node d1-journal-poc/smoke.mjs +// Requires Node >=22 and `wrangler` on PATH. Uses only a unique temporary +// persistence directory; it does not use or configure the main worker-poc D1. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { setTimeout as delay } from "node:timers/promises"; + +const pocDir = path.dirname(fileURLToPath(import.meta.url)); +const workerPocDir = path.resolve(pocDir, ".."); +const configPath = path.join(pocDir, "wrangler.toml"); +const worldId = "d1-journal-poc-world"; +const maxCapturedLogChars = 60_000; + +let child; +let childClosed; +let childFailure; +let stdout = ""; +let stderr = ""; +let stopPromise; +let stateDir; +let interruptedBy; +const interrupt = new AbortController(); + +function appendLog(existing, chunk) { + return (existing + chunk.toString()).slice(-maxCapturedLogChars); +} + +function captureLogs(processHandle) { + processHandle.stdout.on("data", (chunk) => { + stdout = appendLog(stdout, chunk); + }); + processHandle.stderr.on("data", (chunk) => { + stderr = appendLog(stderr, chunk); + }); + processHandle.on("error", (error) => { + childFailure = error; + }); + childClosed = new Promise((resolve) => { + processHandle.once("close", (code, signal) => resolve({ code, signal })); + }); +} + +function signalProcessGroup(signal) { + if (!child || child.pid === undefined) return; + try { + if (process.platform !== "win32") process.kill(-child.pid, signal); + else child.kill(signal); + } catch (error) { + if (error?.code !== "ESRCH") throw error; + } +} + +async function stopServer() { + if (!child || !childClosed) return; + if (stopPromise) return stopPromise; + stopPromise = (async () => { + signalProcessGroup("SIGTERM"); + let timeout; + const graceful = await Promise.race([ + childClosed.then(() => true), + new Promise((resolve) => { + timeout = setTimeout(() => resolve(false), 5_000); + }), + ]); + clearTimeout(timeout); + if (!graceful) { + signalProcessGroup("SIGKILL"); + await childClosed; + } + })(); + return stopPromise; +} + +async function freePort() { + const server = createServer(); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address(); + assert(address && typeof address === "object"); + const { port } = address; + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); + return port; +} + +function abortSignal() { + return AbortSignal.any([interrupt.signal, AbortSignal.timeout(5_000)]); +} + +function serverLogs() { + return [stdout && `Wrangler stdout:\n${stdout}`, stderr && `Wrangler stderr:\n${stderr}`] + .filter(Boolean) + .join("\n"); +} + +async function waitForServer(baseUrl) { + const deadline = Date.now() + 45_000; + while (Date.now() < deadline) { + if (childFailure) throw childFailure; + if (child.exitCode !== null || child.signalCode !== null) { + throw new Error(`Wrangler exited before becoming ready (${serverLogs()})`); + } + try { + const response = await fetch(`${baseUrl}/health`, { signal: abortSignal() }); + if (response.ok && (await response.text()) === "ok") return; + } catch (error) { + if (interrupt.signal.aborted) throw error; + } + await delay(200); + } + throw new Error(`Timed out waiting for local Wrangler (${serverLogs()})`); +} + +async function responseError(response) { + const text = await response.text(); + return `${response.status} ${response.statusText}: ${text}`; +} + +async function append(baseUrl, bytes) { + const response = await fetch(`${baseUrl}/append`, { + method: "POST", + headers: { "content-type": "application/x-ndjson" }, + body: bytes, + signal: abortSignal(), + }); + if (!response.ok) assert.fail(`append failed: ${await responseError(response)}`); + return response.json(); +} + +async function readJsonl(response, label) { + if (!response.ok) assert.fail(`${label} failed: ${await responseError(response)}`); + const bytes = Buffer.from(await response.arrayBuffer()); + const first = Number(response.headers.get("x-journal-first-ordinal")); + const last = Number(response.headers.get("x-journal-last-ordinal")); + const count = Number(response.headers.get("x-journal-entry-count")); + const cursor = Number(response.headers.get("x-journal-stream-cursor")); + assert(Number.isSafeInteger(first) && first >= 0, `${label}: missing first ordinal`); + assert(Number.isSafeInteger(last) && last >= 0, `${label}: missing last ordinal`); + assert(Number.isSafeInteger(count) && count >= 0, `${label}: missing entry count`); + assert.equal(cursor, last, `${label}: stream cursor should name the last returned ordinal`); + if (count > 0) assert.equal(last - first + 1, count, `${label}: ordinal range contains a gap`); + return { bytes, first, last, count, cursor }; +} + +async function main() { + stateDir = await mkdtemp(path.join(os.tmpdir(), "id-d1-journal-poc-")); + const persistDir = path.join(stateDir, "wrangler-state"); + const port = await freePort(); + const baseUrl = `http://127.0.0.1:${port}`; + child = spawn( + "wrangler", + [ + "dev", + "--local", + "--ip", + "127.0.0.1", + "--port", + String(port), + "--persist-to", + persistDir, + "--config", + configPath, + ], + { + cwd: workerPocDir, + detached: process.platform !== "win32", + env: { ...process.env, WRANGLER_SEND_METRICS: "false" }, + stdio: ["ignore", "pipe", "pipe"], + }, + ); + captureLogs(child); + await waitForServer(baseUrl); + + const entries = [ + Buffer.from(`{"entry":"created","world_id":"${worldId}","version":1}\n`), + Buffer.from('{"entry":"caps_granted","granted":[]}\n'), + // Different legal whitespace makes byte preservation observable: the + // Worker must store and return the submitted bytes, not reserialize JSON. + Buffer.from('{ "entry": "caps_granted", "granted": [ ] }\n'), + ]; + + const firstAppend = await append(baseUrl, entries[0]); + const secondAppend = await append(baseUrl, entries[1]); + assert.equal(firstAppend.ordinal, 1, "first entry should have ordinal 1"); + assert.equal(secondAppend.ordinal, 2, "ordinals should increase monotonically"); + assert.equal(typeof secondAppend.bookmark, "string"); + assert(secondAppend.bookmark.length > 0, "append should return a D1 session bookmark"); + + // This is a distinct HTTP request and therefore a fresh D1 session. The + // append bookmark must make the just-written prefix visible to it. + const snapshotResponse = await fetch(`${baseUrl}/snapshot`, { + headers: { "x-d1-bookmark": secondAppend.bookmark }, + signal: abortSignal(), + }); + const snapshot = await readJsonl(snapshotResponse, "bookmark snapshot"); + assert.equal(snapshot.first, 1); + assert.equal(snapshot.last, 2); + assert.equal(snapshot.count, 2); + assert.deepEqual(snapshot.bytes, Buffer.concat(entries.slice(0, 2)), "snapshot must be byte-identical JSONL"); + + const thirdAppend = await append(baseUrl, entries[2]); + assert.equal(thirdAppend.ordinal, 3, "later append should follow the snapshot cursor"); + + const tailResponse = await fetch(`${baseUrl}/tail?after=${snapshot.cursor}`, { + headers: { "x-d1-bookmark": thirdAppend.bookmark }, + signal: abortSignal(), + }); + const tail = await readJsonl(tailResponse, "ordered tail"); + assert.equal(tail.first, snapshot.cursor + 1, "tail should start immediately after the snapshot"); + assert.equal(tail.last, 3); + assert.equal(tail.count, 1); + assert.deepEqual(tail.bytes, entries[2], "tail must return the exact appended bytes"); + assert.deepEqual( + Buffer.concat([snapshot.bytes, tail.bytes]), + Buffer.concat(entries), + "snapshot plus ordered tail must have no duplicate, gap, or reorder", + ); + + console.log("D1 journal-fit smoke: PASS"); + console.log(" append ordinals: 1, 2, 3"); + console.log(" bookmark carried to a fresh request: read-your-write PASS"); + console.log(" snapshot + ordered tail: byte-identical JSONL, no gap/duplicate/reorder"); +} + +function onSignal(signal) { + interruptedBy = signal; + interrupt.abort(new Error(`interrupted by ${signal}`)); + void stopServer(); +} + +process.once("SIGINT", onSignal); +process.once("SIGTERM", onSignal); + +try { + await main(); +} catch (error) { + if (!interruptedBy) { + console.error(`D1 journal-fit smoke: FAIL: ${error?.stack ?? error}`); + const logs = serverLogs(); + if (logs) console.error(logs); + process.exitCode = 1; + } else { + process.exitCode = interruptedBy === "SIGINT" ? 130 : 143; + } +} finally { + process.removeListener("SIGINT", onSignal); + process.removeListener("SIGTERM", onSignal); + await stopServer(); + if (stateDir) await rm(stateDir, { recursive: true, force: true }); +} diff --git a/pkgs/id/worker-poc/d1-journal-poc/worker.mjs b/pkgs/id/worker-poc/d1-journal-poc/worker.mjs new file mode 100644 index 000000000..e864e96d1 --- /dev/null +++ b/pkgs/id/worker-poc/d1-journal-poc/worker.mjs @@ -0,0 +1,207 @@ +const WORLD_ID = "d1-journal-poc-world"; +const JOURNAL_VERSION = 1; + +const CREATE_TABLE = ` + CREATE TABLE IF NOT EXISTS journal_entries ( + world_id TEXT NOT NULL, + ordinal INTEGER NOT NULL CHECK (ordinal > 0), + entry_bytes BLOB NOT NULL, + PRIMARY KEY (world_id, ordinal) + ) +`; + +let schemaReady; + +class HttpError extends Error { + constructor(status, message) { + super(message); + this.status = status; + } +} + +async function ensureSchema(db) { + if (!schemaReady) schemaReady = db.prepare(CREATE_TABLE).run(); + try { + await schemaReady; + } catch (error) { + schemaReady = undefined; + throw error; + } +} + +function jsonResponse(value, status = 200) { + return new Response(JSON.stringify(value), { + status, + headers: { "content-type": "application/json; charset=utf-8" }, + }); +} + +function parseEntryBytes(bytes) { + if (bytes.length < 2 || bytes[bytes.length - 1] !== 0x0a) { + throw new HttpError(400, "expected one newline-terminated JSONL entry"); + } + if (bytes.subarray(0, -1).includes(0x0a)) { + throw new HttpError(400, "expected exactly one JSONL entry per append"); + } + + let entry; + try { + const line = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, -1)); + entry = JSON.parse(line); + } catch { + throw new HttpError(400, "entry must be valid UTF-8 JSON"); + } + + if (!entry || typeof entry !== "object" || Array.isArray(entry)) { + throw new HttpError(400, "entry must be a JSON object"); + } + if (entry.entry === "created") { + if (entry.world_id !== WORLD_ID || entry.version !== JOURNAL_VERSION) { + throw new HttpError(400, "created entry must name the synthetic world and journal version 1"); + } + } else if (entry.entry === "caps_granted") { + if (!Array.isArray(entry.granted) || entry.granted.some((name) => typeof name !== "string")) { + throw new HttpError(400, "caps_granted entry must contain a string array"); + } + } else { + throw new HttpError(400, "POC accepts only created and caps_granted entries"); + } + + return bytes; +} + +function sessionFor(db, request) { + const bookmark = request.headers.get("x-d1-bookmark"); + return bookmark ? db.withSession(bookmark) : db.withSession(); +} + +async function readRows(session, after) { + const result = await session + .prepare( + `SELECT ordinal, entry_bytes + FROM journal_entries + WHERE world_id = ? AND ordinal > ? + ORDER BY ordinal ASC`, + ) + .bind(WORLD_ID, after) + .all(); + return result.results ?? []; +} + +function blobBytes(value) { + if (value instanceof ArrayBuffer) return new Uint8Array(value); + if (ArrayBuffer.isView(value)) { + return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + } + // The local Wrangler D1 runtime currently exposes a returned BLOB as a + // number array; accept it only when every element is a byte. + if ( + Array.isArray(value) && + value.every((byte) => Number.isInteger(byte) && byte >= 0 && byte <= 0xff) + ) { + return Uint8Array.from(value); + } + throw new Error("D1 returned a non-BLOB journal value"); +} + +function jsonlResponse(rows, emptyCursor = 0) { + const chunks = rows.map((row) => blobBytes(row.entry_bytes)); + const byteLength = chunks.reduce((total, chunk) => total + chunk.byteLength, 0); + const bytes = new Uint8Array(byteLength); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + + const firstOrdinal = rows.length ? Number(rows[0].ordinal) : 0; + const lastOrdinal = rows.length ? Number(rows[rows.length - 1].ordinal) : emptyCursor; + return new Response(bytes, { + headers: { + "content-type": "application/x-ndjson; charset=utf-8", + "x-journal-first-ordinal": String(firstOrdinal), + "x-journal-last-ordinal": String(lastOrdinal), + "x-journal-entry-count": String(rows.length), + // This POC's stream cursor is an ordinal; it is not a D1 bookmark. + "x-journal-stream-cursor": String(lastOrdinal), + }, + }); +} + +function parseAfter(url) { + const raw = url.searchParams.get("after") ?? "0"; + const after = Number(raw); + if (!Number.isSafeInteger(after) || after < 0) { + throw new HttpError(400, "after must be a non-negative safe integer"); + } + return after; +} + +export default { + async fetch(request, env) { + const url = new URL(request.url); + if (request.method === "GET" && url.pathname === "/health") { + return new Response("ok"); + } + + try { + if (request.method === "POST" && url.pathname === "/append") { + await ensureSchema(env.DB); + const bytes = parseEntryBytes(new Uint8Array(await request.arrayBuffer())); + const entryBytes = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength); + // #806 assumes one journal writer per world. The INSERT allocates its + // next ordinal from that world's durable tail and returns it atomically. + const session = env.DB.withSession("first-primary"); + const inserted = await session + .prepare( + `INSERT INTO journal_entries (world_id, ordinal, entry_bytes) + VALUES (?, (SELECT COALESCE(MAX(ordinal), 0) + 1 + FROM journal_entries WHERE world_id = ?), ?)`, + ) + .bind(WORLD_ID, WORLD_ID, entryBytes) + .run(); + // Re-query the last inserted ordinal under the same session to return it. + const last = await session + .prepare( + `SELECT ordinal FROM journal_entries + WHERE world_id = ? AND rowid = ?`, + ) + .bind(WORLD_ID, inserted.meta.last_row_id) + .first(); + const bookmarkResult = session.getBookmark(); + const bookmark = + typeof bookmarkResult === "string" ? bookmarkResult : bookmarkResult?.bookmark; + if (!last || typeof bookmark !== "string" || bookmark.length === 0) { + throw new Error("D1 append did not return an ordinal and session bookmark"); + } + return jsonResponse({ world_id: WORLD_ID, ordinal: Number(last.ordinal), bookmark }); + } + + if (request.method === "GET" && url.pathname === "/snapshot") { + await ensureSchema(env.DB); + const rows = await sessionFor(env.DB, request) + .prepare( + `SELECT ordinal, entry_bytes + FROM journal_entries + WHERE world_id = ? + ORDER BY ordinal ASC`, + ) + .bind(WORLD_ID) + .all(); + return jsonlResponse(rows.results ?? []); + } + + if (request.method === "GET" && url.pathname === "/tail") { + await ensureSchema(env.DB); + const after = parseAfter(url); + const rows = await readRows(sessionFor(env.DB, request), after); + return jsonlResponse(rows, after); + } + + return jsonResponse({ error: "not found" }, 404); + } catch (error) { + const status = error instanceof HttpError ? error.status : 500; + return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, status); + } + }, +}; diff --git a/pkgs/id/worker-poc/d1-journal-poc/wrangler.toml b/pkgs/id/worker-poc/d1-journal-poc/wrangler.toml new file mode 100644 index 000000000..d17c57270 --- /dev/null +++ b/pkgs/id/worker-poc/d1-journal-poc/wrangler.toml @@ -0,0 +1,10 @@ +name = "id-d1-journal-poc" +main = "worker.mjs" +compatibility_date = "2025-03-01" + +# This placeholder ID is used only by local Wrangler with --local. The smoke +# always supplies its own temporary --persist-to directory and never deploys. +[[d1_databases]] +binding = "DB" +database_name = "id-d1-journal-poc" +database_id = "00000000-0000-0000-0000-000000000001" From 8836caffecd57e1f5199842a0f31f7d4a708899f Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Thu, 12 Nov 2026 12:54:49 -0600 Subject: [PATCH 2/2] fix(id): reject unsupported arguments in D1 journal smoke (#5864) Codex P1 on PR #6350: the standalone smoke harness silently ran the full workflow when invoked with an unsupported option. Declare the zero-argument interface in the header and reject any supplied argument with a usage error naming it (exit 2) before creating temporary state or starting Wrangler. Verified: --dry-run exits 2 with usage; plain run still PASSes. --- pkgs/id/worker-poc/d1-journal-poc/smoke.mjs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/pkgs/id/worker-poc/d1-journal-poc/smoke.mjs b/pkgs/id/worker-poc/d1-journal-poc/smoke.mjs index 0cc2a1fb0..11be471f6 100644 --- a/pkgs/id/worker-poc/d1-journal-poc/smoke.mjs +++ b/pkgs/id/worker-poc/d1-journal-poc/smoke.mjs @@ -1,5 +1,8 @@ // Local Wrangler D1 journal-fit smoke. Run from worker-poc: // node d1-journal-poc/smoke.mjs +// Interface: zero arguments. This harness takes no options and no +// positional arguments; anything supplied is a usage error (see the +// argument check below, which runs before any side effects). // Requires Node >=22 and `wrangler` on PATH. Uses only a unique temporary // persistence directory; it does not use or configure the main worker-poc D1. import assert from "node:assert/strict"; @@ -12,6 +15,18 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { setTimeout as delay } from "node:timers/promises"; +// Zero-argument interface: reject any supplied argument before the +// harness creates temporary state or starts Wrangler. +const suppliedArgs = process.argv.slice(2); +if (suppliedArgs.length > 0) { + console.error( + "usage: node d1-journal-poc/smoke.mjs (no arguments; unexpected argument: " + + suppliedArgs[0] + + ")", + ); + process.exit(2); +} + const pocDir = path.dirname(fileURLToPath(import.meta.url)); const workerPocDir = path.resolve(pocDir, ".."); const configPath = path.join(pocDir, "wrangler.toml");