diff --git a/.jules/bolt.md b/.jules/bolt.md index 77230b4149..24f694ac15 100644 --- a/.jules/bolt.md +++ b/.jules/bolt.md @@ -23,3 +23,7 @@ **Learning:** `renderWorldSurface` in `pkgs/id/web/src/world-surface.ts` validated every cell of a 120x50 world frame with `Intl.Segmenter.segment()` plus the unicode-width regexes (`\p{Mn}`, `\p{Grapheme_Extend}`) — ~120k segmentations per second at 20 frames/s. On the ASCII path this is pure overhead: a single code unit in U+0020..U+007E is always exactly one grapheme and one column wide. Measured in Bun/JSC, per-frame validation + colour CPU for a full 6000-cell frame fell from 60–169 ms to 2–3 ms (30–55x). Full-render timings in happy-dom are useless for judging this: element creation dominates (hundreds of ms with 4x run-to-run noise) and is unchanged by the fix. **Action:** In hot render loops, fingerprint the common value class (ASCII / single code unit) and take a constant-time fast path before calling Intl or unicode-regex machinery; keep the general path for everything else. Benchmark the CPU component with `document.createElement` stubbed, not happy-dom's DOM. +## 2026-11-05 - [Stream cold-store frames when Drive ignores Range] + +**Learning:** The rehydrator normally requests one zstd frame from Drive, but Drive can answer a range request with `200` and the entire concatenated bundle. Calling `arrayBuffer()` and then slicing made temporary memory scale with bundle size, not the requested object size (#6182). +**Action:** On the `200` fallback, consume the body incrementally, discard bytes before the frame, copy only the requested frame, and cancel at its end; preserve exact-length, decompression, and hash checks. Keep the existing `206` path unchanged. diff --git a/pkgs/cold-store-reaper/worker/dist/worker.js b/pkgs/cold-store-reaper/worker/dist/worker.js index 1bdd091747..0ff99afb31 100644 --- a/pkgs/cold-store-reaper/worker/dist/worker.js +++ b/pkgs/cold-store-reaper/worker/dist/worker.js @@ -643,6 +643,32 @@ function jsonResponse(obj, status = 200) { function errorResponse(message, status) { return jsonResponse({ error: message }, status); } +async function readFrameFromStream(body, offset, frameLength) { + const reader = body?.getReader(); + if (!reader) return new Uint8Array(); + const frame = new Uint8Array(frameLength); + let position = 0; + let copied = 0; + try { + while (copied < frameLength) { + const { done, value } = await reader.read(); + if (done) break; + const chunkStart = position; + position += value.byteLength; + const start = Math.max(offset, chunkStart); + const end = Math.min(offset + frameLength, position); + if (start < end) { + frame.set(value.subarray(start - chunkStart, end - chunkStart), copied); + copied += end - start; + } + } + if (copied === frameLength) await reader.cancel().catch(() => { + }); + } finally { + reader.releaseLock(); + } + return copied === frameLength ? frame : frame.slice(0, copied); +} async function sha256Hex(bytes) { const digest = await crypto.subtle.digest("SHA-256", bytes); return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); @@ -722,10 +748,7 @@ var BundleFlight = class { if (resp.status !== 206 && resp.status !== 200) { throw new HttpError(502, `drive range download failed (HTTP ${resp.status})`); } - let frame = new Uint8Array(await resp.arrayBuffer()); - if (resp.status === 200) { - frame = frame.slice(offset, offset + frame_length); - } + const frame = resp.status === 200 ? await readFrameFromStream(resp.body, offset, frame_length) : new Uint8Array(await resp.arrayBuffer()); if (frame.length !== frame_length) { throw new HttpError( 502, diff --git a/pkgs/cold-store-reaper/worker/src/index.js b/pkgs/cold-store-reaper/worker/src/index.js index 22831db745..180406b129 100644 --- a/pkgs/cold-store-reaper/worker/src/index.js +++ b/pkgs/cold-store-reaper/worker/src/index.js @@ -40,6 +40,36 @@ function errorResponse(message, status) { return jsonResponse({ error: message }, status); } +// Drive sometimes ignores Range and streams the whole bundle. Discard the +// prefix and retain only the requested frame; cancel at its end so neither +// the bundle tail nor an ArrayBuffer copy is kept in memory. +async function readFrameFromStream(body, offset, frameLength) { + const reader = body?.getReader(); + if (!reader) return new Uint8Array(); + + const frame = new Uint8Array(frameLength); + let position = 0; + let copied = 0; + try { + while (copied < frameLength) { + const { done, value } = await reader.read(); + if (done) break; + const chunkStart = position; + position += value.byteLength; + const start = Math.max(offset, chunkStart); + const end = Math.min(offset + frameLength, position); + if (start < end) { + frame.set(value.subarray(start - chunkStart, end - chunkStart), copied); + copied += end - start; + } + } + if (copied === frameLength) await reader.cancel().catch(() => {}); + } finally { + reader.releaseLock(); + } + return copied === frameLength ? frame : frame.slice(0, copied); +} + async function sha256Hex(bytes) { const digest = await crypto.subtle.digest("SHA-256", bytes); return [...new Uint8Array(digest)] @@ -132,12 +162,10 @@ export class BundleFlight { if (resp.status !== 206 && resp.status !== 200) { throw new HttpError(502, `drive range download failed (HTTP ${resp.status})`); } - let frame = new Uint8Array(await resp.arrayBuffer()); - if (resp.status === 200) { - // Drive ignored the Range header and sent the whole bundle: slice out - // exactly the member's frame before doing anything with it. - frame = frame.slice(offset, offset + frame_length); - } + const frame = + resp.status === 200 + ? await readFrameFromStream(resp.body, offset, frame_length) + : new Uint8Array(await resp.arrayBuffer()); if (frame.length !== frame_length) { throw new HttpError( 502, diff --git a/pkgs/cold-store-reaper/worker/test/run-local-proof.mjs b/pkgs/cold-store-reaper/worker/test/run-local-proof.mjs index 4ea2f02320..9d4e46af39 100644 --- a/pkgs/cold-store-reaper/worker/test/run-local-proof.mjs +++ b/pkgs/cold-store-reaper/worker/test/run-local-proof.mjs @@ -9,6 +9,7 @@ // // Exits non-zero on any mismatch; prints PASS on success. +import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { createHash } from "node:crypto"; import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; @@ -17,6 +18,7 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { decompressFrame } from "../src/decoder.js"; +import { BundleFlight } from "../src/index.js"; const pkgDir = join(dirname(fileURLToPath(import.meta.url)), "..", ".."); @@ -76,7 +78,73 @@ if (!plain.equals(sample)) { console.error("FAIL: decoded bytes differ from the packed sample"); process.exit(1); } + +const originalFetch = globalThis.fetch; +const flight = new BundleFlight( + { storage: { get: async () => ({ token: "proof", expires_at_ms: Date.now() + 3_600_000 }) } }, + {}, +); +const job = { + drive_file_id: "proof", + offset: info.offset, + frame_length: info.length, + sha256: info.hash, + bundle_id: "proof", +}; +const rehydrate = async (status, body, sha256 = info.hash, offset = info.offset) => { + globalThis.fetch = async () => new Response(body, { status }); + try { + return await flight.rehydrate({ ...job, sha256, offset }); + } finally { + globalThis.fetch = originalFetch; + } +}; + +let pulls = 0; +let cancelled = false; +let tailChunks = 0; +let prefixBytes = 0; +let frameSent = false; +const streamOffset = 2 * 1024 * 1024; +const frameChunk = bundle.subarray(info.offset, info.offset + info.length); +const ignoredRangeBody = new ReadableStream( + { + pull(controller) { + pulls += 1; + if (prefixBytes < streamOffset) { + const length = Math.min(64 * 1024, streamOffset - prefixBytes); + prefixBytes += length; + controller.enqueue(new Uint8Array(length)); + } else if (!frameSent) { + frameSent = true; + controller.enqueue(frameChunk); + } else { + tailChunks += 1; + controller.enqueue(new Uint8Array(64 * 1024)); + } + }, + cancel() { + cancelled = true; + }, + }, + { highWaterMark: 0 }, +); +const streamed = await rehydrate(200, ignoredRangeBody, info.hash, streamOffset); +assert.deepEqual(Buffer.from(streamed.bytes), sample); +assert.equal(cancelled, true, "ignored-Range stream should be cancelled after the frame"); +assert.equal(pulls, streamOffset / (64 * 1024) + 1); +assert.equal(tailChunks, 0, "ignored-Range stream should not read the bundle tail"); + +const ranged = await rehydrate(206, frame); +assert.deepEqual(Buffer.from(ranged.bytes), sample); +await assert.rejects( + rehydrate(200, bundle.subarray(0, info.offset + info.length - 1)), + /drive range download short:/, +); +await assert.rejects(rehydrate(206, frame, "0".repeat(64)), /sha256 mismatch/); +await assert.rejects(rehydrate(206, new Uint8Array(info.length)), /zstd frame decompression failed/); + console.log( - `PASS: frame at offset ${info.offset} (${info.length} bytes) decoded via ` + - `src/decoder.js (fzstd) and sha256-verified against the manifest (${digest.slice(0, 16)}...)`, + `PASS: frame at offset ${info.offset} (${info.length} bytes) decoded and hash-verified; ` + + "ignored-Range stream stopped at the frame; 206, truncation, malformed-frame, and hash checks passed", );