diff --git a/changelog.d/hosted-sql-text.md b/changelog.d/hosted-sql-text.md new file mode 100644 index 000000000..dcd32f17a --- /dev/null +++ b/changelog.d/hosted-sql-text.md @@ -0,0 +1,3 @@ +## Changed + +- Hosted replicas allocate fewer temporary buffers when reading resource paths and Markdown text from SQLite. diff --git a/runtime/deploy/hosted-worker/bench/resource-text.mjs b/runtime/deploy/hosted-worker/bench/resource-text.mjs new file mode 100644 index 000000000..022056615 --- /dev/null +++ b/runtime/deploy/hosted-worker/bench/resource-text.mjs @@ -0,0 +1,154 @@ +// Run with Node 24 after npm ci in runtime/deploy/hosted-worker. +// Pass the base revision's src/sql.ts as the first argument. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { performance } from "node:perf_hooks"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; +import { Miniflare, convertV4MiniflareOptions } from "miniflare"; + +function probe(before, after) { + const enc = new TextEncoder(); + const path = i => `notes/resource-${String(i).padStart(6, "0")}.md`; + function u32(n) { + const b = new Uint8Array(4); + new DataView(b.buffer).setUint32(0, n, true); + return [...b]; + } + function str(s) { + const bytes = enc.encode(s); + return [...u32(bytes.length), ...bytes]; + } + function param(v) { + if (v === null) return [0]; + if (typeof v === "string") return [3, ...str(v)]; + const b = new Uint8Array(8); + new DataView(b.buffer).setBigInt64(0, BigInt(v), true); + return [1, ...b]; + } + function request(sql, params) { + return Uint8Array.from([77,68,66,73,68,88,0,1,0,1, ...u32(1), ...str(sql), + ...u32(params.length), ...params.flatMap(param)]); + } + return class { + constructor(ctx) { this.storage = ctx.storage; } + fetch(req) { + const [action, count, repeats] = new URL(req.url).pathname.slice(1).split("/"); + const n = Number(count); + if (!this.requests) { + this.requests = []; + for (let i = 0; i <= n; i += 256) { + this.requests.push(request("SELECT path, length(CAST(doc AS BLOB)) FROM st_res WHERE (?1 IS NULL OR path > ?1) ORDER BY path LIMIT ?2", [i ? path(i - 1) : null, 256])); + if (i < n) this.requests.push(request("SELECT path, doc FROM st_res WHERE path >= ?1 AND path <= ?2 ORDER BY path", [path(i), path(Math.min(i + 255, n - 1))])); + } + } + if (action === "seed") { + this.storage.sql.exec("CREATE TABLE st_res(path TEXT PRIMARY KEY, doc TEXT NOT NULL) WITHOUT ROWID"); + this.storage.transactionSync(() => { + for (let i = 0; i < n; i++) this.storage.sql.exec("INSERT INTO st_res VALUES(?,?)", + path(i), `# Resource ${i}\n\n` + "A multilingual paragraph with café and 📝.\n".repeat(12)); + }); + for (const r of this.requests) { + const original = before(this.storage, r), candidate = after(this.storage, r); + if (original[8] !== 2 || original.length !== candidate.length || + !original.every((v, i) => candidate[i] === v)) throw Error("index replies differ or failed"); + } + return new Response("ready"); + } + if (action === "allocations") { + const counts = {}; + const encode = TextEncoder.prototype.encode; + try { + for (const [arm, run] of Object.entries({ before, after })) { + counts[arm] = 0; + TextEncoder.prototype.encode = function(text) { + counts[arm]++; + return encode.call(this, text); + }; + for (const r of this.requests) { + if (run(this.storage, r)[8] !== 2) throw Error("inventory failed"); + } + } + } finally { TextEncoder.prototype.encode = encode; } + return Response.json(counts); + } + const run = action === "before" ? before : after; + let bytes = 0; + for (let i = 0; i < Number(repeats); i++) for (const r of this.requests) { + const reply = run(this.storage, r); + if (reply[8] !== 2) throw Error("inventory failed"); + bytes += reply.length; + } + return new Response(String(bytes)); + } + }; +} + +const root = fileURLToPath(new URL("../", import.meta.url)); +const compiled = await build({ stdin: { resolveDir: root, contents: ` +import { runIndex as before } from ${JSON.stringify(resolve(process.argv[2]))}; +import { runIndex as after } from "./src/sql.ts"; +export const Probe = (${probe})(before, after); +export default { fetch(req, env) { return env.LOG.getByName(new URL(req.url).pathname.split("/")[2]).fetch(req); } }; +` }, bundle: true, write: false, format: "esm" }); +const mf = new Miniflare(convertV4MiniflareOptions({ name: "resource-text-bench", modules: true, + script: compiled.outputFiles[0].text, compatibilityDate: "2026-10-05", + durableObjects: { LOG: { className: "Probe", useSQLite: true } } })); +async function call(path) { + const r = await mf.dispatchFetch("http://bench.local/" + path); + const body = await r.text(); + assert.equal(r.status, 200, body); + return body; +} +const quantile = (samples, p) => [...samples].sort((a,b) => a-b)[Math.ceil(p*samples.length)-1].toFixed(3); +// Linux process accounting includes all workerd threads and excludes time +// spent waiting for the host to schedule the worker. +function cpuClock() { + if (process.platform !== "linux") return () => NaN; + const children = readFileSync(`/proc/self/task/${process.pid}/children`, "utf8").trim().split(/\s+/); + const workers = children.filter(pid => readFileSync(`/proc/${pid}/comm`, "utf8").trim() === "workerd"); + assert.equal(workers.length, 1); + const tickMs = 1000 / Number(execFileSync("getconf", ["CLK_TCK"])); + return () => { + const fields = readFileSync(`/proc/${workers[0]}/stat`, "utf8").split(" "); + return (Number(fields[13]) + Number(fields[14])) * tickMs; + }; +} +try { + const results = []; + for (const [rows, repeats] of [[1, 3000], [8, 1200], [4096, 5]]) { + await call(`seed/${rows}`); + const cpuMs = cpuClock(); + const samples = { before: {wall: [], cpu: []}, after: {wall: [], cpu: []} }; + for (let round = 0; round < 36; round++) { + const order = round % 2 ? ["after", "before"] : ["before", "after"]; + let bytes; + for (const arm of order) { + const cpu = cpuMs(), start = performance.now(); + const result = Number(await call(`${arm}/${rows}/${repeats}`)); + const ms = (performance.now() - start) / repeats; + const used = (cpuMs() - cpu) / repeats; + if (round >= 4) { + samples[arm].wall.push(ms); + samples[arm].cpu.push(used); + } + assert.ok(result > 0); + if (bytes !== undefined) assert.equal(bytes, result); + bytes = result; + } + } + for (const [arm, times] of Object.entries(samples)) results.push({ + rows, arm, repeats, samples: times.wall.length, + median_ms: quantile(times.wall, 0.5), p95_ms: quantile(times.wall, 0.95), + median_cpu_ms: quantile(times.cpu, 0.5), p95_cpu_ms: quantile(times.cpu, 0.95), + }); + } + // Instrumentation runs after timing, once per fixture. + for (const rows of new Set(results.map(r => r.rows))) { + const counts = JSON.parse(await call(`allocations/${rows}`)); + for (const r of results.filter(r => r.rows === rows)) r.temporary_text_arrays = counts[r.arm]; + } + console.table(results); +} finally { await mf.dispose(); } diff --git a/runtime/deploy/hosted-worker/src/sql.ts b/runtime/deploy/hosted-worker/src/sql.ts index d012eb1a2..3f4d66e23 100644 --- a/runtime/deploy/hosted-worker/src/sql.ts +++ b/runtime/deploy/hosted-worker/src/sql.ts @@ -34,6 +34,7 @@ class Fail extends Error { } } const SQL = 0, FULL = 2, OTHER = 4; +const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); class Reader { private off = 0; @@ -51,7 +52,7 @@ class Reader { str(max: number) { const n = this.u32(); if (n > max) throw new Fail(FULL, "string over budget"); - return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(this.bytes(n)); + return decoder.decode(this.bytes(n)); } end() { if (this.off !== this.b.length) throw new Fail(OTHER, "trailing bytes"); } } @@ -102,7 +103,22 @@ class Writer { this.u8(1); return this.i64(BigInt(v)); } - if (typeof v === "string") { this.u8(3); return this.bytes(utf8.encode(v)); } + if (typeof v === "string") { + this.u8(3); + const prefix = this.reserve(4); + // One byte per UTF-16 code unit is a lower bound. Use all spare + // capacity before growing for a multibyte suffix. + const start = this.reserve(v.length); + const { read, written } = utf8.encodeInto(v, this.buffer.subarray(start)); + this.length = start + written; + if (read < v.length) { + const suffix = utf8.encode(v.slice(read)); + const at = this.reserve(suffix.length); + this.buffer.set(suffix, at); + } + this.view.setUint32(prefix, this.length - start, true); + return; + } this.u8(4); this.bytes(new Uint8Array(v)); } diff --git a/runtime/deploy/hosted-worker/test/sql.test.mjs b/runtime/deploy/hosted-worker/test/sql.test.mjs index 4963958c2..6eda0b802 100644 --- a/runtime/deploy/hosted-worker/test/sql.test.mjs +++ b/runtime/deploy/hosted-worker/test/sql.test.mjs @@ -65,6 +65,50 @@ test("the complete reply fits at exactly 4 MiB and refuses the next byte", () => assert.equal(errKind(over), 2); }); +test("text cells carry their UTF-8 byte lengths across growth and spare capacity", () => { + // The initial 64-byte buffer has 22 bytes left for the first cell. Its + // surrogate pair must move together to the next buffer. + const cells = ["x".repeat(20) + "🔑", "中", "", "\uFEFFdoc", "\uD800", "a".repeat(1100), "end"]; + const reply = runIndex(storage([cells]), req([["SELECT", []]])); + assert.equal(op(reply), 2); + const view = new DataView(reply.buffer, reply.byteOffset, reply.byteLength); + let at = 37; + for (const cell of cells) { + assert.equal(reply[at++], 3); + const expected = new TextEncoder().encode(cell); + assert.equal(view.getUint32(at, true), expected.length); + at += 4; + assert.deepEqual(reply.subarray(at, at + expected.length), expected); + at += expected.length; + } + assert.equal(at, reply.length); +}); + +test("a multibyte suffix can fill the last reply byte, and the next byte is refused", () => { + const capacity = (4 << 20) - 42; + const fits = "a".repeat(capacity - 4) + "🔑"; + assert.equal(runIndex(storage([[fits]]), req([["SELECT", []]])).length, 4 << 20); + const overflow = runIndex(storage([[fits + "a"]]), req([["SELECT", []]])); + assert.equal(op(overflow), 3); + assert.equal(errKind(overflow), 2); +}); + +test("a malformed request string leaves the next UTF-8 decode independent", () => { + const bad = req([["SELECT", ["x"]]]); + bad[bad.length - 1] = 0xc3; // truncated UTF-8 sequence + const s = storage([]); + assert.equal(op(runIndex(s, bad)), 3); + assert.equal(s.execs(), 0); + let bound; + const realExec = s.sql.exec; + s.sql.exec = (sql, ...params) => { + if (sql === "SELECT") bound = params; + return realExec(sql, ...params); + }; + assert.equal(op(runIndex(s, req([["SELECT", ["\uFEFF文", "📝"]]]))), 2); + assert.deepEqual(bound, ["\uFEFF文", "📝"]); +}); + test("a REAL parameter or unsafe integer is refused before any SQL", () => { const s = storage([[1]]); assert.equal(op(runIndex(s, req([["SELECT", [1.5]]]))), 3);