Public: anyone can read this; the crew can change it.
A snapshot's files are cut off the serving thread: an unchanged hosted forge's stream pass holds the loop 0 ms, not 0.8 s #17622
Merged 18h 12m ago, live in production
stream-off-thread → main 0 commits 1 thread · 1 unresolved
7 files
changed +391
−29
src/snapshot/cut.ts added +86
| @@ -0,0 +1,86 @@ | ||
| 1 | /** | |
| 2 | * The snapshot's cutter, one worker for one snapshot (`cut_worker.ts`): files go in by name or | |
| 3 | * descriptor, their chunks' names come back, and the main thread reads no byte of a file the | |
| 4 | * store already holds. `close` ends the worker; a job still out is refused. | |
| 5 | * | |
| 6 | * A worker that fails (an error it did not catch, a message that would not arrive, its end, or no | |
| 7 | * answer within `timeoutMs`) is ended and forgotten, and every job it held is refused with why, so | |
| 8 | * a snapshot fails rather than waits forever; the next job starts a fresh worker. | |
| 9 | */ | |
| 10 | ||
| 11 | import { during } from "../perf/jobs.ts"; | |
| 12 | import type { CutFile, CutJob, CutReply, CutSpec } from "./cut_worker.ts"; | |
| 13 | ||
| 14 | export interface Cutter { | |
| 15 | cut(file: string, fd: number | undefined, spec: CutSpec): Promise<CutFile>; | |
| 16 | close(): void; | |
| 17 | } | |
| 18 | ||
| 19 | /** | |
| 20 | * How long one file's cut may go unanswered. The largest file a snapshot cuts is the forge's own | |
| 21 | * database copy (4.3 GB on 2026-11-14), read and hashed at a few hundred MB a second. | |
| 22 | */ | |
| 23 | export const CUT_TIMEOUT_MS = 10 * 60_000; | |
| 24 | ||
| 25 | export function startCutter( | |
| 26 | options: { | |
| 27 | /** Test seam: how a worker is made; one of `cut_worker.ts`. */ | |
| 28 | readonly make?: (() => Worker) | undefined; | |
| 29 | readonly timeoutMs?: number | undefined; | |
| 30 | } = {}, | |
| 31 | ): Cutter { | |
| 32 | const timeoutMs = options.timeoutMs ?? CUT_TIMEOUT_MS; | |
| 33 | let worker: Worker | undefined; | |
| 34 | let next = 0; | |
| 35 | const waiting = new Map<number, { w: Worker; resolve: (f: CutFile) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }>(); | |
| 36 | // End `w` and refuse every job it held (every job, with none named); the next job starts another. | |
| 37 | const fail = (w: Worker | undefined, error: Error): void => { | |
| 38 | if (w !== undefined) { | |
| 39 | if (w === worker) worker = undefined; | |
| 40 | w.terminate(); | |
| 41 | } | |
| 42 | for (const [n, job] of waiting) | |
| 43 | if (w === undefined || job.w === w) { | |
| 44 | waiting.delete(n); | |
| 45 | clearTimeout(job.timer); | |
| 46 | job.reject(error); | |
| 47 | } | |
| 48 | }; | |
| 49 | const started = (): Worker => { | |
| 50 | if (worker !== undefined) return worker; | |
| 51 | const w = options.make?.() ?? new Worker(new URL("./cut_worker.ts", import.meta.url).href); | |
| 52 | w.onmessage = (e: MessageEvent<CutReply>) => { | |
| 53 | const r = e.data; | |
| 54 | const job = waiting.get(r.n); | |
| 55 | if (job === undefined) return; | |
| 56 | waiting.delete(r.n); | |
| 57 | clearTimeout(job.timer); | |
| 58 | if ("error" in r) job.reject(new Error(r.error)); | |
| 59 | else job.resolve({ bytes: r.bytes, sha256: r.sha256, chunks: r.chunks }); | |
| 60 | }; | |
| 61 | w.onerror = (e) => fail(w, new Error(`the snapshot's cutter failed: ${e.message}`)); | |
| 62 | w.onmessageerror = () => fail(w, new Error("the snapshot's cutter sent an answer that could not be read")); | |
| 63 | w.addEventListener("close", () => fail(w, new Error("the snapshot's cutter ended"))); | |
| 64 | worker = w; | |
| 65 | return w; | |
| 66 | }; | |
| 67 | return { | |
| 68 | cut: (file, fd, spec) => | |
| 69 | new Promise<CutFile>((resolve, reject) => { | |
| 70 | const n = next++; | |
| 71 | const w = started(); | |
| 72 | const timer = setTimeout( | |
| 73 | () => during("snapshot-cut-timeout", () => fail(w, new Error(`the snapshot's cutter did not answer for ${file} within ${Math.round(timeoutMs / 1000)} s`))), | |
| 74 | timeoutMs, | |
| 75 | ); | |
| 76 | waiting.set(n, { w, resolve, reject, timer }); | |
| 77 | w.postMessage({ n, file, fd, spec } satisfies CutJob); | |
| 78 | }), | |
| 79 | close: () => { | |
| 80 | const w = worker; | |
| 81 | worker = undefined; | |
| 82 | w?.terminate(); | |
| 83 | fail(undefined, new Error("the snapshot's cutter was closed")); | |
| 84 | }, | |
| 85 | }; | |
| 86 | } |
src/snapshot/cut_worker.ts added +84
| @@ -0,0 +1,84 @@ | ||
| 1 | /** | |
| 2 | * A file cut into chunks off the serving thread (`cut.ts`). Reading a file, cutting it where its | |
| 3 | * content says and hashing every byte twice (the file's SHA-256 and each chunk's) was the main | |
| 4 | * thread's work for every file of every hosted forge, every five minutes: on a runner, a forge of | |
| 5 | * 170 MiB held the loop about 1 s a pass, and production logged stalls to 1.5 s in the stream's | |
| 6 | * passes. Here it reads through one buffer, cuts and hashes, and answers the chunks' names and | |
| 7 | * lengths only: the bytes of the few chunks a store lacks are read again by the caller. | |
| 8 | */ | |
| 9 | ||
| 10 | import { closeSync, openSync, readSync } from "node:fs"; | |
| 11 | import { workerMemory } from "../perf/memory_watch.ts"; | |
| 12 | import { chunkId, contentChunker, fixedChunker, type Chunker } from "./chunks.ts"; | |
| 13 | ||
| 14 | /** How a file is cut: at fixed offsets, or where its content says under the forge's seed. */ | |
| 15 | export type CutSpec = | |
| 16 | | { readonly kind: "fixed"; readonly size: number } | |
| 17 | | { readonly kind: "content"; readonly seed: Uint8Array; readonly cut: { min: number; bits: number; max: number } }; | |
| 18 | ||
| 19 | /** | |
| 20 | * One file to cut: by its name, or by a descriptor the caller opened (read by offset, never moved). | |
| 21 | */ | |
| 22 | export interface CutJob { | |
| 23 | readonly n: number; | |
| 24 | readonly file: string; | |
| 25 | readonly fd?: number | undefined; | |
| 26 | readonly spec: CutSpec; | |
| 27 | } | |
| 28 | ||
| 29 | /** A file as it was read: its bytes, its SHA-256 and its chunks in order. */ | |
| 30 | export interface CutFile { | |
| 31 | readonly bytes: number; | |
| 32 | readonly sha256: string; | |
| 33 | readonly chunks: readonly { readonly id: string; readonly length: number }[]; | |
| 34 | } | |
| 35 | ||
| 36 | export type CutReply = ({ readonly n: number } & CutFile) | { readonly n: number; readonly error: string }; | |
| 37 | ||
| 38 | /** A file is read this much at a time, into one buffer. */ | |
| 39 | const READ_BYTES = 1_048_576; | |
| 40 | ||
| 41 | const chunkerOf = (spec: CutSpec): Chunker => | |
| 42 | spec.kind === "fixed" ? fixedChunker(spec.size) : contentChunker(spec.seed, spec.cut); | |
| 43 | ||
| 44 | /** Cut `file` (or `fd`, from offset 0) as `spec` says. */ | |
| 45 | export function cutFile(file: string, fd: number | undefined, spec: CutSpec): CutFile { | |
| 46 | const own = fd === undefined ? openSync(file, "r") : fd; | |
| 47 | try { | |
| 48 | const cutter = chunkerOf(spec); | |
| 49 | const whole = new Bun.CryptoHasher("sha256"); | |
| 50 | const chunks: { id: string; length: number }[] = []; | |
| 51 | const buf = new Uint8Array(READ_BYTES); | |
| 52 | let bytes = 0; | |
| 53 | for (;;) { | |
| 54 | const n = readSync(own, buf, 0, READ_BYTES, bytes); | |
| 55 | if (n === 0) break; | |
| 56 | const part = buf.subarray(0, n); | |
| 57 | whole.update(part); | |
| 58 | bytes += n; | |
| 59 | for (const c of cutter.push(part)) chunks.push({ id: chunkId(c), length: c.byteLength }); | |
| 60 | } | |
| 61 | for (const c of cutter.end()) chunks.push({ id: chunkId(c), length: c.byteLength }); | |
| 62 | return { bytes, sha256: whole.digest("hex"), chunks }; | |
| 63 | } finally { | |
| 64 | if (fd === undefined) closeSync(own); | |
| 65 | } | |
| 66 | } | |
| 67 | ||
| 68 | declare const self: Worker; | |
| 69 | ||
| 70 | /** | |
| 71 | * The worker's side only: imported on the main thread, this module defines the job and does | |
| 72 | * nothing. | |
| 73 | */ | |
| 74 | if (!Bun.isMainThread) { | |
| 75 | workerMemory("snapshot-cut"); | |
| 76 | self.onmessage = (e: MessageEvent<CutJob>) => { | |
| 77 | const { n, file, fd, spec } = e.data; | |
| 78 | try { | |
| 79 | postMessage({ n, ...cutFile(file, fd, spec) } satisfies CutReply); | |
| 80 | } catch (error) { | |
| 81 | postMessage({ n, error: String(error instanceof Error ? error.message : error) } satisfies CutReply); | |
| 82 | } | |
| 83 | }; | |
| 84 | } |
src/snapshot/snapshot.ts +74 −26
| @@ -37,7 +37,7 @@ | ||
| 37 | 37 | |
| 38 | 38 | import { Database } from "bun:sqlite"; |
| 39 | 39 | import { vacuumFile, vacuumInto } from "./vacuum.ts"; |
| 40 | import { createReadStream, fstatSync, lstatSync, mkdtempSync, readdirSync, rmSync, statSync } from "node:fs"; | |
| 40 | import { closeSync, createReadStream, fstatSync, lstatSync, mkdtempSync, openSync, readdirSync, readSync, rmSync, statSync } from "node:fs"; | |
| 41 | 41 | import { tmpdir } from "node:os"; |
| 42 | 42 | import { join, relative } from "node:path"; |
| 43 | 43 | import { envDataDir } from "../apps/data.ts"; |
| @@ -48,12 +48,14 @@ import { createLog } from "../kernel/log.ts"; | ||
| 48 | 48 | import { bundleRepo } from "./bundle.ts"; |
| 49 | 49 | import { copyHosted, unchanged, HostedRefusal, hostedSources, HOSTED_PREFIX, openInside, type HostedEntry, type HostedTools } from "./hosted.ts"; |
| 50 | 50 | import { countRows, type DrillCounts } from "./counts.ts"; |
| 51 | import { CHUNK_PREFIX, chunkId, chunkKey, chunkSeed, contentChunker, fixedChunker, isChunkId, packChunk, type Chunker } from "./chunks.ts"; | |
| 51 | import { CHUNK_PREFIX, chunkId, chunkKey, chunkSeed, contentChunker, CUT, FIXED_BYTES, fixedChunker, isChunkId, packChunk, type Chunker } from "./chunks.ts"; | |
| 52 | 52 | import type { PackedFile } from "./parts.ts"; |
| 53 | 53 | import { bodiesOf, type Store } from "../blob/store.ts"; |
| 54 | 54 | import { putsAtOnce } from "./line.ts"; |
| 55 | 55 | import { unwrapKey, wrapKey, WRAPPED_KEY } from "./wrap.ts"; |
| 56 | 56 | import { settler } from "./settle.ts"; |
| 57 | import { startCutter, type Cutter } from "./cut.ts"; | |
| 58 | import type { CutSpec } from "./cut_worker.ts"; | |
| 57 | 59 | import { during } from "../perf/jobs.ts"; |
| 58 | 60 | |
| 59 | 61 | const log = createLog("snapshot"); |
| @@ -351,13 +353,17 @@ export interface Snapshotter { | ||
| 351 | 353 | readonly chunks?: ChunkView | undefined; |
| 352 | 354 | /** |
| 353 | 355 | * Test seams for the collection inside one forge's pass (#17493): `settle` runs each time |
| 354 | * `settleBytes` more plain bytes were read. Default: a `settler()` every 256 MiB. | |
| 356 | * `settleBytes` more plain bytes were held on the main thread (a chunk sent, or bytes put whole); | |
| 357 | * a file's bytes the store already holds are read by the cutter's worker and never held here. | |
| 358 | * Default: a `settler()` every 256 MiB. | |
| 355 | 359 | */ |
| 356 | 360 | readonly settle?: (() => void) | undefined; |
| 357 | 361 | readonly settleBytes?: number | undefined; |
| 362 | /** Test seam: the cutter (`cut.ts`); by default one worker for this snapshot, closed with it. */ | |
| 363 | readonly cutter?: Cutter | undefined; | |
| 358 | 364 | } |
| 359 | 365 | |
| 360 | /** Plain bytes read between two collections inside one snapshot. */ | |
| 366 | /** Plain bytes held on the main thread between two collections inside one snapshot. */ | |
| 361 | 367 | const SETTLE_BYTES = 256 * 1024 * 1024; |
| 362 | 368 | |
| 363 | 369 | /** |
| @@ -514,35 +520,50 @@ export async function takeSnapshot( | ||
| 514 | 520 | // The chunks the store holds, as it lists them, and those this snapshot has handed over. |
| 515 | 521 | let there = new Set<string>(); |
| 516 | 522 | let found = 0; |
| 517 | // One chunk: its name, and its bytes to the queue unless the store has them. | |
| 523 | // One chunk, by its name: to the queue unless the store has it. `read` gives its plain bytes, | |
| 524 | // only when they must go; undefined when what it reads now is not that chunk (the file changed). | |
| 518 | 525 | const settleAt = forge.settleBytes ?? SETTLE_BYTES; |
| 519 | 526 | const settle = forge.settle ?? settler(); |
| 527 | let heldBytes = 0; | |
| 520 | 528 | let settledAt = 0; |
| 521 | const send = async (plain: Uint8Array): Promise<string> => { | |
| 522 | // A forge of several GiB cuts every chunk through fresh buffers; the collector lets them pile | |
| 523 | // up for the whole forge (#17493: the main heap 416 to 2855 MiB inside one pass), so it runs | |
| 524 | // each `settleAt` bytes read, not once per forge. | |
| 525 | if (readBytes - settledAt >= settleAt) { | |
| 526 | settledAt = readBytes; | |
| 527 | settle(); | |
| 528 | } | |
| 529 | const id = chunkId(plain); | |
| 529 | const sendNamed = async (id: string, length: number, read: () => Uint8Array): Promise<boolean> => { | |
| 530 | 530 | const key = await storedChunk(store, id); |
| 531 | 531 | if (there.has(key)) { |
| 532 | 532 | found++; |
| 533 | readBytes += plain.byteLength; | |
| 534 | return id; | |
| 533 | readBytes += length; | |
| 534 | return true; | |
| 535 | } | |
| 536 | const plain = read(); | |
| 537 | if (plain.byteLength !== length || chunkId(plain) !== id) return false; | |
| 538 | // Chunks sent cut through fresh buffers; the collector lets them pile up for the whole forge | |
| 539 | // (#17493: the main heap 416 to 2855 MiB inside one pass), so it runs each `settleAt` bytes | |
| 540 | // held here, not once per forge. | |
| 541 | heldBytes += length; | |
| 542 | if (heldBytes - settledAt >= settleAt) { | |
| 543 | settledAt = heldBytes; | |
| 544 | settle(); | |
| 535 | 545 | } |
| 536 | 546 | there.add(key); |
| 537 | 547 | const body = await packChunk(plain); |
| 538 | readBytes += plain.byteLength; | |
| 548 | readBytes += length; | |
| 539 | 549 | queuedBytes += body.byteLength; |
| 540 | 550 | sentChunks++; |
| 541 | 551 | await put(chunkKey(id), body); |
| 552 | return true; | |
| 553 | }; | |
| 554 | const send = async (plain: Uint8Array): Promise<string> => { | |
| 555 | const id = chunkId(plain); | |
| 556 | await sendNamed(id, plain.byteLength, () => plain); | |
| 542 | 557 | return id; |
| 543 | 558 | }; |
| 544 | 559 | let seed: Uint8Array | undefined; |
| 545 | 560 | type Cut = "content" | "fixed" | "bundle"; |
| 561 | const specOf = (cut: Cut): CutSpec => | |
| 562 | cut === "fixed" | |
| 563 | ? { kind: "fixed", size: forge.fixedBytes ?? FIXED_BYTES } | |
| 564 | : cut === "bundle" | |
| 565 | ? { kind: "fixed", size: BUNDLE_CHUNK_BYTES } | |
| 566 | : { kind: "content", seed: (seed ??= chunkSeed(forge.dataDir)), cut: forge.contentCut ?? CUT }; | |
| 546 | 567 | const chunker = (cut: Cut): Chunker => |
| 547 | 568 | cut === "fixed" |
| 548 | 569 | ? fixedChunker(forge.fixedBytes) |
| @@ -552,27 +573,53 @@ export async function takeSnapshot( | ||
| 552 | 573 | const listed = (path: string, bytes: number, sha256: string, chunks: string[]): void => { |
| 553 | 574 | files.push({ path, bytes, sha256, chunks }); |
| 554 | 575 | }; |
| 555 | // A file on disk, read as a stream and never held whole: the hash of what was read, and its | |
| 556 | // chunks. | |
| 557 | // With `own`, a hosted forge's file (`hosted.ts`): opened without following a link, and only when | |
| 558 | // what was opened is inside that directory. | |
| 576 | // A file on disk, cut off this thread (`cut.ts`): the worker reads it, cuts it and names its | |
| 577 | // chunks, and only the chunks the store lacks are read here, by offset, and checked against their | |
| 578 | // names. With `own`, a hosted forge's file (`hosted.ts`): opened without following a link, and | |
| 579 | // only when what was opened is inside that directory. | |
| 580 | const cutWorker = forge.cutter ?? startCutter(); | |
| 559 | 581 | const putFile = async (path: string, file: string, cut: Cut = "content", own?: string): Promise<boolean> => { |
| 560 | 582 | const fd = own === undefined ? undefined : openInside(file, own); |
| 561 | 583 | if (own === undefined ? statSync(file, { throwIfNoEntry: false })?.isFile() !== true : fd === undefined) return true; |
| 562 | const before = fd === undefined ? undefined : fstatSync(fd); | |
| 584 | const reader = fd ?? openSync(file, "r"); | |
| 585 | try { | |
| 586 | const before = fd === undefined ? undefined : fstatSync(fd); | |
| 587 | const got = await cutWorker.cut(file, fd, specOf(cut)); | |
| 588 | const chunks: string[] = []; | |
| 589 | let at = 0; | |
| 590 | for (const c of got.chunks) { | |
| 591 | const from = at; | |
| 592 | const read = (): Uint8Array => { | |
| 593 | const plain = new Uint8Array(c.length); | |
| 594 | return plain.subarray(0, readSync(reader, plain, 0, c.length, from)); | |
| 595 | }; | |
| 596 | // What is read now is not what was cut: the file changed under the cut. A hosted forge's | |
| 597 | // file says so (false, and its caller reads it again); any other is read here, whole. | |
| 598 | if (!(await sendNamed(c.id, c.length, read))) return own === undefined ? await putFileHere(path, file, cut) : false; | |
| 599 | chunks.push(c.id); | |
| 600 | at += c.length; | |
| 601 | } | |
| 602 | // A hosted forge's file that changed while it was read is not listed: false, and the caller | |
| 603 | // says so. | |
| 604 | if (before !== undefined && !unchanged(before, lstatSync(file, { throwIfNoEntry: false }), got.bytes)) return false; | |
| 605 | listed(path, got.bytes, got.sha256, chunks); | |
| 606 | return true; | |
| 607 | } finally { | |
| 608 | closeSync(reader); | |
| 609 | } | |
| 610 | }; | |
| 611 | // The same on this thread, sent as it is read: for a file that changed under its cut. | |
| 612 | const putFileHere = async (path: string, file: string, cut: Cut): Promise<boolean> => { | |
| 563 | 613 | const cutter = chunker(cut); |
| 564 | 614 | const whole = new Bun.CryptoHasher("sha256"); |
| 565 | 615 | const chunks: string[] = []; |
| 566 | 616 | let bytes = 0; |
| 567 | for await (const part of createReadStream(file, { highWaterMark: READ_BYTES, ...(fd === undefined ? {} : { fd }) }) as AsyncIterable<Uint8Array>) { | |
| 617 | for await (const part of createReadStream(file, { highWaterMark: READ_BYTES }) as AsyncIterable<Uint8Array>) { | |
| 568 | 618 | whole.update(part); |
| 569 | 619 | bytes += part.byteLength; |
| 570 | 620 | for (const c of cutter.push(part)) chunks.push(await send(c)); |
| 571 | 621 | } |
| 572 | 622 | for (const c of cutter.end()) chunks.push(await send(c)); |
| 573 | // A hosted forge's file that changed while it was read is not listed: false, and the caller | |
| 574 | // says so. | |
| 575 | if (before !== undefined && !unchanged(before, lstatSync(file, { throwIfNoEntry: false }), bytes)) return false; | |
| 576 | 623 | listed(path, bytes, whole.digest("hex"), chunks); |
| 577 | 624 | return true; |
| 578 | 625 | }; |
| @@ -836,6 +883,7 @@ export async function takeSnapshot( | ||
| 836 | 883 | }); |
| 837 | 884 | return manifest; |
| 838 | 885 | } finally { |
| 886 | if (forge.cutter === undefined) cutWorker.close(); | |
| 839 | 887 | clearInterval(ticker); |
| 840 | 888 | // Puts still running when one failed must not outlive the scratch. |
| 841 | 889 | await Promise.allSettled([...pending]); |
test/helpers/cut-failing-worker.ts added +16
| @@ -0,0 +1,16 @@ | ||
| 1 | /** | |
| 2 | * A cutter worker that fails as asked (test/snapshot-cut.test.ts): a file named `*.throw` throws | |
| 3 | * out of the handler, `*.exit` ends the worker, `*.hang` is never answered; any other is cut as | |
| 4 | * `cut_worker.ts` cuts it. | |
| 5 | */ | |
| 6 | import { cutFile, type CutJob } from "../../src/snapshot/cut_worker.ts"; | |
| 7 | ||
| 8 | declare const self: Worker; | |
| 9 | ||
| 10 | self.onmessage = (e: MessageEvent<CutJob>) => { | |
| 11 | const { n, file, fd, spec } = e.data; | |
| 12 | if (file.endsWith(".throw")) throw new Error("the worker died mid-job"); | |
| 13 | if (file.endsWith(".exit")) process.exit(1); | |
| 14 | if (file.endsWith(".hang")) return; | |
| 15 | postMessage({ n, ...cutFile(file, fd, spec) }); | |
| 16 | }; |
test/job-slices.test.ts +1
| @@ -266,6 +266,7 @@ function jobs(): Record<string, () => unknown> { | ||
| 266 | 266 | * on. |
| 267 | 267 | */ |
| 268 | 268 | const UNTIMED: Record<string, string> = { |
| 269 | "snapshot-cut-timeout": "a one-shot timer per file a snapshot cuts (snapshot/cut.ts), fired only when the cutter's worker has not answered within CUT_TIMEOUT_MS: it ends the worker and refuses the jobs it held; snapshot-cut.test.ts drives a silent worker to it", | |
| 269 | 270 | "advisory-feed": "hourly (and once 30 s after boot): one read of each repository's lockfile and two network fetches, KEV and OSV (core/advisory_feed.ts); the network is not timed here and advisory-feed.test.ts drives listenOnce with a fake fetch", |
| 270 | 271 | "series-sampler": "every 30 s: one /metrics render and one batched insert (series/store.ts record), bounded by the rows it keeps; series-explore.test.ts drives tick directly", |
| 271 | 272 | "dev-reload": "a one-shot timer, 250 ms after a change in a dev cell's tree, that asks the dev server's root until it answers: a loopback fetch, off the loop, for one cell of one person (apps/dev_hot.ts); dev-hot.test.ts drives a change and the fault it ends in", |
test/snapshot-cut.test.ts added +75
| @@ -0,0 +1,75 @@ | ||
| 1 | /** | |
| 2 | * A snapshot's files are cut off the serving thread (`cut_worker.ts`): the worker's chunks are the | |
| 3 | * chunks the main thread would have cut, by name, length and order, and the file's SHA-256 is the | |
| 4 | * same, for both cuts and across the worker's read boundary. | |
| 5 | */ | |
| 6 | import { afterAll, expect, test } from "bun:test"; | |
| 7 | import { randomBytes } from "node:crypto"; | |
| 8 | import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { chunkId, contentChunker, fixedChunker, type Chunker } from "../src/snapshot/chunks.ts"; | |
| 12 | import { startCutter } from "../src/snapshot/cut.ts"; | |
| 13 | import { cutFile, type CutSpec } from "../src/snapshot/cut_worker.ts"; | |
| 14 | ||
| 15 | const dir = mkdtempSync(join(tmpdir(), "snapshot-cut-")); | |
| 16 | afterAll(() => rmSync(dir, { recursive: true, force: true })); | |
| 17 | ||
| 18 | // Past one read (1 MiB), and not a whole number of chunks: the last chunk is short. | |
| 19 | const body = new Uint8Array(randomBytes(3 * 1_048_576 + 12_345)); | |
| 20 | const file = join(dir, "data.bin"); | |
| 21 | writeFileSync(file, body); | |
| 22 | const seed = new Uint8Array(32).fill(7); | |
| 23 | const specs: CutSpec[] = [ | |
| 24 | { kind: "fixed", size: 1_000_000 }, | |
| 25 | // Smaller than the snapshot's own cut, so 3 MiB holds many content cuts. | |
| 26 | { kind: "content", seed, cut: { min: 65_536, bits: 16, max: 524_288 } }, | |
| 27 | ]; | |
| 28 | ||
| 29 | const inMemory = (c: Chunker) => [...c.push(body), ...c.end()].map((p) => ({ id: chunkId(p), length: p.byteLength })); | |
| 30 | const expected = (spec: CutSpec) => inMemory(spec.kind === "fixed" ? fixedChunker(spec.size) : contentChunker(spec.seed, spec.cut)); | |
| 31 | const sha256 = new Bun.CryptoHasher("sha256").update(body).digest("hex"); | |
| 32 | ||
| 33 | test("the cut is the chunks the main thread would cut, and the file's own hash", () => { | |
| 34 | for (const spec of specs) { | |
| 35 | const got = cutFile(file, undefined, spec); | |
| 36 | expect(got.chunks).toEqual(expected(spec)); | |
| 37 | expect(got.chunks.length).toBeGreaterThan(1); | |
| 38 | expect(got.bytes).toBe(body.byteLength); | |
| 39 | expect(got.sha256).toBe(sha256); | |
| 40 | } | |
| 41 | }); | |
| 42 | ||
| 43 | test("through the worker the answer is the same, and a cut still out when it closes is refused", async () => { | |
| 44 | const cutter = startCutter(); | |
| 45 | try { | |
| 46 | for (const spec of specs) expect((await cutter.cut(file, undefined, spec)).chunks).toEqual(expected(spec)); | |
| 47 | const refused = (p: Promise<unknown>) => p.then(() => "answered", (e: Error) => e.message); | |
| 48 | expect(await refused(cutter.cut(join(dir, "none"), undefined, specs[0]!))).toContain("ENOENT"); | |
| 49 | const out = refused(cutter.cut(file, undefined, specs[1]!)); | |
| 50 | cutter.close(); | |
| 51 | expect(await out).toBe("the snapshot's cutter was closed"); | |
| 52 | } finally { | |
| 53 | cutter.close(); | |
| 54 | } | |
| 55 | }); | |
| 56 | ||
| 57 | test("a worker that dies, ends or goes silent mid-job refuses that job, and the next cut still answers", async () => { | |
| 58 | const url = new URL("./helpers/cut-failing-worker.ts", import.meta.url).href; | |
| 59 | const cutter = startCutter({ make: () => new Worker(url), timeoutMs: 1_000 }); | |
| 60 | const refused = (p: Promise<unknown>) => p.then(() => "answered", (e: Error) => e.message); | |
| 61 | try { | |
| 62 | for (const [ending, says] of [ | |
| 63 | ["throw", "the snapshot's cutter failed"], | |
| 64 | ["exit", "the snapshot's cutter ended"], | |
| 65 | ["hang", "did not answer"], | |
| 66 | ] as const) { | |
| 67 | // The job held when it fails is refused with why, not left waiting forever. | |
| 68 | expect(await refused(cutter.cut(`${file}.${ending}`, undefined, specs[0]!))).toContain(says); | |
| 69 | // And a fresh worker answers the next. | |
| 70 | expect((await cutter.cut(file, undefined, specs[0]!)).chunks).toEqual(expected(specs[0]!)); | |
| 71 | } | |
| 72 | } finally { | |
| 73 | cutter.close(); | |
| 74 | } | |
| 75 | }); |
test/snapshot-stream.test.ts +55 −3
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | * what the stream names, and the lag is what `streamLag` answers. |
| 5 | 5 | */ |
| 6 | 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 7 | import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; | |
| 7 | import { mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; | |
| 8 | 8 | import { rm } from "node:fs/promises"; |
| 9 | 9 | import { tmpdir } from "node:os"; |
| 10 | 10 | import { join } from "node:path"; |
| @@ -14,10 +14,11 @@ import { dirStore } from "../src/blob/store.ts"; | ||
| 14 | 14 | import { createUser } from "../src/core/users.ts"; |
| 15 | 15 | import { commitLog } from "../src/git/read.ts"; |
| 16 | 16 | import { repoDir } from "../src/git/repos.ts"; |
| 17 | import { restoreHostedInto } from "../src/snapshot/restore.ts"; | |
| 17 | import { restoreHostedInto, restoreSnapshot } from "../src/snapshot/restore.ts"; | |
| 18 | import { startCutter, type Cutter } from "../src/snapshot/cut.ts"; | |
| 18 | 19 | import { startSnapshots } from "../src/snapshot/service.ts"; |
| 19 | 20 | import { CHUNK_PREFIX } from "../src/snapshot/chunks.ts"; |
| 20 | import { pruneSnapshots, streamManifestKey, takeSnapshot, type ChunkView } from "../src/snapshot/snapshot.ts"; | |
| 21 | import { listSnapshots, pruneSnapshots, streamManifestKey, takeSnapshot, type ChunkView } from "../src/snapshot/snapshot.ts"; | |
| 21 | 22 | import { readStream, STREAM_LATE_MS, streamLag, streamPass } from "../src/snapshot/stream.ts"; |
| 22 | 23 | import type { Ctx } from "../src/http/context.ts"; |
| 23 | 24 | import { tool as systemTool } from "../src/http/mcp/tools/system.ts"; |
| @@ -157,6 +158,57 @@ describe("the stream of hosted forges", () => { | ||
| 157 | 158 | let none = 0; |
| 158 | 159 | await takeSnapshot({ ...shape(), stream: "kid", settle: () => void none++, settleBytes: 2 ** 40 }, store); |
| 159 | 160 | expect(none).toBe(0); |
| 161 | // An unchanged forge's files are read by the cutter's worker alone: no byte is held here. | |
| 162 | let held = 0; | |
| 163 | const again = await takeSnapshot({ ...shape(), stream: "kid", settle: () => void held++, settleBytes: 1 }, store); | |
| 164 | expect(again.sent?.chunks).toBeLessThan(3); | |
| 165 | // Once for each chunk it sent, and no more: the old pass collected for every chunk it read. | |
| 166 | expect(held).toBe(again.sent?.chunks ?? -1); | |
| 167 | }); | |
| 168 | ||
| 169 | test("a file that changed between its cut and its read restores as it ended, byte for byte, hosted or not", async () => { | |
| 170 | // The cut runs off this thread (`cut_worker.ts`); the chunks a store lacks are read here after. | |
| 171 | // A cutter that rewrites the file once its cut is answered is that race, every time. | |
| 172 | const log = join(child.config.dataDir, "runs", "mid.log"); | |
| 173 | const dropped = join(parent.config.dataDir, "drop", "mid.txt"); | |
| 174 | mkdirSync(join(child.config.dataDir, "runs"), { recursive: true }); | |
| 175 | mkdirSync(join(parent.config.dataDir, "drop"), { recursive: true }); | |
| 176 | const size = 600_000; | |
| 177 | for (const f of [log, dropped]) writeFileSync(f, "b".repeat(size)); | |
| 178 | const real = startCutter(); | |
| 179 | const once = new Set<string>(); | |
| 180 | const cutter: Cutter = { | |
| 181 | cut: async (file, fd, spec) => { | |
| 182 | const got = await real.cut(file, fd, spec); | |
| 183 | if ((file === log || file === dropped) && !once.has(file)) { | |
| 184 | once.add(file); | |
| 185 | writeFileSync(file, "a".repeat(size)); | |
| 186 | } | |
| 187 | return got; | |
| 188 | }, | |
| 189 | close: () => real.close(), | |
| 190 | }; | |
| 191 | try { | |
| 192 | const store = dirStore(join(root, `store-${n++}`)); | |
| 193 | // A hosted forge's file says it changed, and is read again; the forge's own is read here | |
| 194 | // whole. | |
| 195 | await takeSnapshot({ ...shape(), cutter }, store, new Date("2026-12-02T20:00:00Z")); | |
| 196 | expect([...once].sort()).toEqual([dropped, log].sort()); | |
| 197 | const [name] = (await listSnapshots(store)).map((s) => s.name); | |
| 198 | const into = join(root, "restored-mid"); | |
| 199 | await restoreSnapshot(store, name!, into, { passphrase: PASS }); | |
| 200 | expect(readFileSync(join(into, "drop", "mid.txt"), "utf8")).toBe("a".repeat(size)); | |
| 201 | // Every history file of the hosted forge, byte for byte as the source holds it now. | |
| 202 | const runs = join(child.config.dataDir, "runs"); | |
| 203 | const hostedInto = join(root, "restored-mid-hosted"); | |
| 204 | await restoreHostedInto(store, name!, "kid", hostedInto, { passphrase: PASS }); | |
| 205 | const back = join(hostedInto, "children", BODY, "runs"); | |
| 206 | const hash = (f: string) => new Bun.CryptoHasher("sha256").update(readFileSync(f)).digest("hex"); | |
| 207 | for (const f of readdirSync(runs)) expect(hash(join(back, f))).toBe(hash(join(runs, f))); | |
| 208 | expect(readFileSync(join(back, "mid.log"), "utf8")).toBe("a".repeat(size)); | |
| 209 | } finally { | |
| 210 | real.close(); | |
| 211 | } | |
| 160 | 212 | }); |
| 161 | 213 | |
| 162 | 214 | test("a refused copy keeps the last good manifest and its time, and says why (#16977)", async () => { |
new above
offline
A worker error leaves
workerset. Latercut()calls post to a dead worker and hang forever, and the snapshot hangs with them. Terminate it and clearworkerhere, and bound a job that gets no reply. Test it.