Skip to content
Closed
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
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
31 changes: 27 additions & 4 deletions pkgs/cold-store-reaper/worker/dist/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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("");
Expand Down Expand Up @@ -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,
Expand Down
40 changes: 34 additions & 6 deletions pkgs/cold-store-reaper/worker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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,
Expand Down
72 changes: 70 additions & 2 deletions pkgs/cold-store-reaper/worker/test/run-local-proof.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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)), "..", "..");

Expand Down Expand Up @@ -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",
);