@seanhogg/builderforce-memory 2026.10.47 → 2026.10.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/knowledge/modelLimiter.d.ts +2 -1
  2. package/dist/knowledge/modelLimiter.d.ts.map +1 -1
  3. package/dist/knowledge/modelLimiter.js +43 -3
  4. package/dist/knowledge/modelLimiter.js.map +1 -1
  5. package/dist/knowledge/pack/decode.d.ts +6 -2
  6. package/dist/knowledge/pack/decode.d.ts.map +1 -1
  7. package/dist/knowledge/pack/decode.js +15 -9
  8. package/dist/knowledge/pack/decode.js.map +1 -1
  9. package/dist/knowledge/pack/deflate.d.ts +1 -0
  10. package/dist/knowledge/pack/deflate.d.ts.map +1 -1
  11. package/dist/knowledge/pack/deflate.js +17 -0
  12. package/dist/knowledge/pack/deflate.js.map +1 -1
  13. package/dist/knowledge/pack/frame.d.ts +11 -0
  14. package/dist/knowledge/pack/frame.d.ts.map +1 -1
  15. package/dist/knowledge/pack/frame.js +36 -9
  16. package/dist/knowledge/pack/frame.js.map +1 -1
  17. package/dist/knowledge/pack/index.d.ts +1 -1
  18. package/dist/knowledge/pack/index.d.ts.map +1 -1
  19. package/dist/knowledge/pack/index.js +1 -1
  20. package/dist/knowledge/pack/index.js.map +1 -1
  21. package/dist/knowledge/pack/manifest.d.ts +17 -0
  22. package/dist/knowledge/pack/manifest.d.ts.map +1 -1
  23. package/dist/knowledge/pack/manifest.js +37 -8
  24. package/dist/knowledge/pack/manifest.js.map +1 -1
  25. package/dist/knowledge/pack/sections/facts.js.map +1 -1
  26. package/dist/knowledge/pack/types.d.ts +4 -3
  27. package/dist/knowledge/pack/types.d.ts.map +1 -1
  28. package/dist/knowledge/pack/types.js +2 -1
  29. package/dist/knowledge/pack/types.js.map +1 -1
  30. package/dist/knowledge/review.d.ts.map +1 -1
  31. package/dist/knowledge/review.js +16 -3
  32. package/dist/knowledge/review.js.map +1 -1
  33. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  34. package/dist/knowledge/reviewPrefetch.js +7 -2
  35. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  36. package/package.json +3 -3
  37. package/src/contract/exports.snapshot.json +3 -0
  38. package/src/contract/regression.pack.test.ts +94 -0
  39. package/src/knowledge/modelLimiter.test.ts +35 -0
  40. package/src/knowledge/modelLimiter.ts +36 -3
  41. package/src/knowledge/pack/decode.ts +15 -9
  42. package/src/knowledge/pack/deflate.ts +19 -1
  43. package/src/knowledge/pack/frame.ts +38 -8
  44. package/src/knowledge/pack/index.ts +1 -1
  45. package/src/knowledge/pack/manifest.ts +35 -5
  46. package/src/knowledge/pack/pack.guards.test.ts +2 -2
  47. package/src/knowledge/pack/sections/facts.ts +1 -1
  48. package/src/knowledge/pack/types.ts +5 -4
  49. package/src/knowledge/review.readAhead.test.ts +97 -0
  50. package/src/knowledge/review.ts +17 -3
  51. package/src/knowledge/reviewPrefetch.ts +5 -2
@@ -35,7 +35,25 @@ async function through(data: Uint8Array, transform: { readable: ReadableStream<U
35
35
  }
36
36
  }
37
37
 
38
- export const deflateRaw = (data: Uint8Array): Promise<Uint8Array> =>
38
+ /** Writes `chunks` into one transform in order, draining as it goes: the parts of a split pack are inflated as ONE stream, never joined. */
39
+ async function throughChunks(chunks: readonly Uint8Array[], transform: { readable: ReadableStream<Uint8Array>; writable: WritableStream<BufferSource> }, maxBytes: number): Promise<Uint8Array> {
40
+ const writer = transform.writable.getWriter();
41
+ const wrote = (async () => {
42
+ for (const c of chunks) await writer.write(c as unknown as BufferSource);
43
+ await writer.close();
44
+ })();
45
+ wrote.catch(() => undefined);
46
+ try {
47
+ return await drain(transform.readable, maxBytes);
48
+ } finally {
49
+ await wrote.catch(() => undefined);
50
+ }
51
+ }
52
+
53
+ export const inflateRawChunks = (chunks: readonly Uint8Array[], maxBytes: number): Promise<Uint8Array> =>
54
+ throughChunks(chunks, new DecompressionStream('deflate-raw') as never, maxBytes);
55
+
56
+ export const deflateRaw =(data: Uint8Array): Promise<Uint8Array> =>
39
57
  through(data, new CompressionStream('deflate-raw') as never, Number.MAX_SAFE_INTEGER);
40
58
 
41
59
  /** Throws {@link PackTooLargeError} past `maxBytes` of output, and `Error` on a corrupt stream. */
@@ -42,12 +42,10 @@ export function writeFrame(h: FrameHeader, body: Uint8Array, storedBody: Uint8Ar
42
42
  return out.finish();
43
43
  }
44
44
 
45
- /**
46
- * Splits a frame into header fields, the stored (possibly deflated) body, the header's bytes, and the CRC the
47
- * trailer claims. The caller checks `crc32(decodedBody, crc32(headerBytes)) === crc` once it has inflated.
48
- */
49
- export function readFrame(bytes: Uint8Array): { header: FrameHeader; headerBytes: Uint8Array; stored: Uint8Array; crc: number } {
50
- if (bytes.length < 4 + 2 + 1 + 1 + 32 + 4) throw new PackFormatError('truncated frame');
45
+ const MIN_FRAME = 4 + 2 + 1 + 1 + 32 + 4;
46
+
47
+ /** The header alone: magic through digest. `bytes` may be just the first part of a split pack. */
48
+ export function readHeader(bytes: Uint8Array): { header: FrameHeader; headerBytes: Uint8Array } {
51
49
  const r = new ByteReader(bytes);
52
50
  for (const m of MAGIC) if (r.u8() !== m) throw new PackFormatError('not a BFKP pack (bad magic)');
53
51
  const version = r.u8();
@@ -56,10 +54,42 @@ export function readFrame(bytes: Uint8Array): { header: FrameHeader; headerBytes
56
54
  const rootId = r.str();
57
55
  const baseGeneration = r.varint();
58
56
  const targetDigest = toHex(r.bytes(32));
59
- const headerBytes = bytes.subarray(0, r.offset);
57
+ return { header: { flags, rootId, baseGeneration, targetDigest }, headerBytes: bytes.subarray(0, r.offset) };
58
+ }
59
+
60
+ /**
61
+ * Splits a frame into header fields, the stored (possibly deflated) body, the header's bytes, and the CRC the
62
+ * trailer claims. The caller checks `crc32(decodedBody, crc32(headerBytes)) === crc` once it has inflated.
63
+ */
64
+ export function readFrame(bytes: Uint8Array): { header: FrameHeader; headerBytes: Uint8Array; stored: Uint8Array; crc: number } {
65
+ if (bytes.length < MIN_FRAME) throw new PackFormatError('truncated frame');
66
+ const { header, headerBytes } = readHeader(bytes);
67
+ const r = new ByteReader(bytes);
68
+ r.bytes(headerBytes.length);
60
69
  if (r.remaining < 4) throw new PackFormatError('truncated frame');
61
70
  const stored = r.bytes(r.remaining - 4);
62
- return { header: { flags, rootId, baseGeneration, targetDigest }, headerBytes, stored, crc: r.u32le() };
71
+ return { header, headerBytes, stored, crc: r.u32le() };
72
+ }
73
+
74
+ /** Parts that can be read as a frame without joining: a first part that holds the whole header and a last part that holds the trailer. */
75
+ const HEADER_ROOM = 4096;
76
+ export function readFrameParts(parts: readonly Uint8Array[]): { header: FrameHeader; headerBytes: Uint8Array; stored: Uint8Array[]; crc: number } {
77
+ const first = parts[0], last = parts[parts.length - 1];
78
+ if (parts.length < 2 || !first || !last || first.length < HEADER_ROOM || last.length < 4) return singleFrame(parts);
79
+ const { header, headerBytes } = readHeader(first);
80
+ const trailer = last.subarray(last.length - 4);
81
+ const stored = parts.map((p, i) => {
82
+ const from = i === 0 ? headerBytes.length : 0;
83
+ const to = i === parts.length - 1 ? p.length - 4 : p.length;
84
+ return p.subarray(from, to);
85
+ });
86
+ const crc = (trailer[0]! | (trailer[1]! << 8) | (trailer[2]! << 16) | (trailer[3]! << 24)) >>> 0;
87
+ return { header, headerBytes, stored, crc };
88
+ }
89
+
90
+ function singleFrame(parts: readonly Uint8Array[]): { header: FrameHeader; headerBytes: Uint8Array; stored: Uint8Array[]; crc: number } {
91
+ const f = readFrame(joinParts(parts));
92
+ return { ...f, stored: [f.stored] };
63
93
  }
64
94
 
65
95
  export function writeSection(w: ByteWriter, tag: number, bytes: Uint8Array): void {
@@ -20,7 +20,7 @@ export type {
20
20
  export { diffEntries, applyEntryDiffs, diffEntry, applyEntryDiff, deepEqual } from './extrDiff.js';
21
21
  export {
22
22
  MANIFEST_BUCKETS, manifestTree, bucketOf, keyHash, differingBuckets, leafDelta, rootLeaves, rootDigestOf,
23
- fileLeafKey, factLeafKey, relationLeafKey, factDigest, relationDigest,
23
+ fileLeafKey, factLeafKey, relationLeafKey, parseRelationLeafKey, factDigest, relationDigest, bucketDigest, rootDigestOfBuckets,
24
24
  } from './manifest.js';
25
25
  export type { ManifestTree, LeafDelta, RootRows } from './manifest.js';
26
26
  export { jsonBytesOf } from './jsonSize.js';
@@ -37,6 +37,21 @@ export interface ManifestTree {
37
37
 
38
38
  const cmp = (a: ManifestLeaf, b: ManifestLeaf): number => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
39
39
 
40
+ /**
41
+ * The digest of ONE bucket: the hash of its leaves sorted by key (an empty bucket has a fixed digest). The server keeps
42
+ * these per bucket, so a pack recomputes only the buckets it touched.
43
+ */
44
+ export function bucketDigest(leaves: readonly ManifestLeaf[]): string {
45
+ if (leaves.length === 0) return EMPTY_BUCKET;
46
+ return sha256Hex([...leaves].sort(cmp).map((l) => `${l.key}\u0000${l.digest}\n`).join(''));
47
+ }
48
+
49
+ /** The root digest from the `MANIFEST_BUCKETS` bucket digests (hex), in bucket order. */
50
+ export function rootDigestOfBuckets(digests: readonly string[]): string {
51
+ if (digests.length !== MANIFEST_BUCKETS) throw new Error(`a root digest takes ${MANIFEST_BUCKETS} bucket digests, got ${digests.length}`);
52
+ return sha256Hex(digests.join(''));
53
+ }
54
+
40
55
  export function manifestTree(leaves: readonly ManifestLeaf[]): ManifestTree {
41
56
  const grouped = new Map<number, ManifestLeaf[]>();
42
57
  for (const l of leaves) {
@@ -47,11 +62,10 @@ export function manifestTree(leaves: readonly ManifestLeaf[]): ManifestTree {
47
62
  const buckets: string[] = new Array(MANIFEST_BUCKETS);
48
63
  for (let b = 0; b < MANIFEST_BUCKETS; b++) {
49
64
  const list = grouped.get(b);
50
- if (!list) { buckets[b] = EMPTY_BUCKET; continue; }
51
- list.sort(cmp);
52
- buckets[b] = sha256Hex(list.map((l) => `${l.key}\u0000${l.digest}\n`).join(''));
65
+ if (list) list.sort(cmp);
66
+ buckets[b] = bucketDigest(list ?? []);
53
67
  }
54
- return { root: sha256Hex(buckets.join('')), buckets, leaves: grouped };
68
+ return { root: rootDigestOfBuckets(buckets), buckets, leaves: grouped };
55
69
  }
56
70
 
57
71
  /** The bucket ids whose digests differ (or are missing on one side). */
@@ -69,7 +83,23 @@ export function fileLeafKey(path: string, hash: string): string {
69
83
  }
70
84
 
71
85
  export const factLeafKey = (key: string): string => `a:${key}`;
72
- export const relationLeafKey = (r: { from: string; to: string; kind: string }): string => `r:${r.from}\u0000${r.to}\u0000${r.kind}`;
86
+ /**
87
+ * A relation's leaf key: `r:` + the JSON array `[from, to, kind]`. Printable and unambiguous: Postgres `text` and
88
+ * `jsonb` reject NUL, which the earlier `from␀to␀kind` form contained.
89
+ */
90
+ export const relationLeafKey = (r: { from: string; to: string; kind: string }): string => `r:${JSON.stringify([r.from, r.to, r.kind])}`;
91
+
92
+ /** The inverse of {@link relationLeafKey}; null when `key` is not a relation leaf key. The ONE parser. */
93
+ export function parseRelationLeafKey(key: string): { from: string; to: string; kind: string } | null {
94
+ if (!key.startsWith('r:')) return null;
95
+ try {
96
+ const v: unknown = JSON.parse(key.slice(2));
97
+ if (Array.isArray(v) && v.length === 3 && v.every((s) => typeof s === 'string')) {
98
+ return { from: v[0] as string, to: v[1] as string, kind: v[2] as string };
99
+ }
100
+ } catch { /* not JSON: not a relation key */ }
101
+ return null;
102
+ }
73
103
 
74
104
  /** The digest of what a fact says: its key, text and provenance kind. Importance and timestamps are the server's to score. */
75
105
  export const factDigest = (f: Pick<StoredFact, 'key' | 'content' | 'origin'>): string => sha256Hex(JSON.stringify([f.key, f.content, f.origin]));
@@ -50,8 +50,8 @@ describe('BFKP guards', () => {
50
50
  await expect(decodePack(bomb, { maxDecodedBytes: 1024 * 1024 })).rejects.toThrow(PackTooLargeError);
51
51
  });
52
52
 
53
- it('applies the 64 MB default cap', async () => {
54
- const body = new Uint8Array(65 * 1024 * 1024);
53
+ it('applies the 24 MB default cap (sized for a 128 MB Worker)', async () => {
54
+ const body = new Uint8Array(25 * 1024 * 1024);
55
55
  const bomb = writeFrame({ flags: FLAG_DEFLATED, rootId: 'r', baseGeneration: 0, targetDigest: ZERO_DIGEST }, body, await deflateRaw(body));
56
56
  await expect(decodePack(bomb)).rejects.toThrow(PackTooLargeError);
57
57
  }, 60_000);
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import type { NodeRef, StoredFact, StoredRelation } from '../types.js';
7
- import { boundedCount, ByteReader, ByteWriter, PackFormatError } from '../varint.js';
7
+ import { boundedCount, ByteReader, ByteWriter } from '../varint.js';
8
8
  import { EDGE_KINDS, STORED_ORIGINS, readEnum, readWord, writeEnum, writeWord, type SectionCodec } from './columns.js';
9
9
  import { assertFlagsKnown } from './extrLists.js';
10
10
  import { TAG } from './rows.js';
@@ -72,11 +72,11 @@ export const ZERO_DIGEST = '0'.repeat(64);
72
72
 
73
73
  /** A pack's decoded counts, for guards before any work. */
74
74
  export interface PackLimits {
75
- /** Bytes the body may inflate to (default 64 MB). */
75
+ /** Bytes the body may inflate to (default 24 MB). */
76
76
  maxDecodedBytes: number;
77
- /** Strings in the table (default 2,000,000). */
77
+ /** Strings in the table (default 400,000). */
78
78
  maxStrings: number;
79
- /** Rows in any one section (default 1,000,000). */
79
+ /** Rows in the whole pack (default 200,000). */
80
80
  maxRows: number;
81
81
  }
82
82
 
@@ -87,7 +87,8 @@ export interface PackLimits {
87
87
  */
88
88
  export interface ReadLimits extends PackLimits { budget: Budget }
89
89
 
90
- export const DEFAULT_PACK_LIMITS: PackLimits = { maxDecodedBytes: 64 * 1024 * 1024, maxStrings: 2_000_000, maxRows: 1_000_000 };
90
+ /** Sized for a 128 MB Worker: the decoded pack, its string table and its rows all live in memory at once. A client cuts a pack below these. */
91
+ export const DEFAULT_PACK_LIMITS: PackLimits = { maxDecodedBytes: 24 * 1024 * 1024, maxStrings: 400_000, maxRows: 200_000 };
91
92
 
92
93
  /** The decoded body inflated past `maxDecodedBytes`: the server answers 413 `pack_too_large`. */
93
94
  export class PackTooLargeError extends Error {
@@ -0,0 +1,97 @@
1
+ /**
2
+ * src/knowledge/review.readAhead.test.ts
3
+ * A pool that reads files itself runs a wide read-ahead window, so one slow head file does not stall the
4
+ * other workers; and Stop settles the review at once however many jobs are queued behind the slot limiter.
5
+ */
6
+
7
+ import { jest } from '@jest/globals';
8
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
9
+ import { extractJob, type ExtractJob, type ExtractPool } from './extractJob.js';
10
+ import { DOCS_PACK } from './packs/docs.js';
11
+ import { reviewDirectory } from './review.js';
12
+ import { LocalSnapshotStore } from './stores/localSnapshotStore.js';
13
+ import { args, fakeJudge, memPersistence, memSource } from './testkit.test-util.js';
14
+
15
+ const FILE_COUNT = 400;
16
+ const files = (): Record<string, string> =>
17
+ Object.fromEntries(Array.from({ length: FILE_COUNT }, (_, i) => [`d${String(i).padStart(4, '0')}.md`, `# T${i}\nbody ${i}\n`]));
18
+
19
+ /** A pool that reads the file itself (a `readByPool` job), then extracts it. */
20
+ function readingPool(source: ReturnType<typeof memSource>, hold: (job: ExtractJob, started: number) => Promise<void>): { pool: ExtractPool; started: () => number } {
21
+ let started = 0;
22
+ return {
23
+ started: () => started,
24
+ pool: async (job, signal) => {
25
+ started += 1;
26
+ // Like the host pool: a stopped review rejects the job with an AbortError.
27
+ const aborted = new Promise<never>((_, reject) => {
28
+ const stop = (): void => reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
29
+ if (signal?.aborted) stop(); else signal?.addEventListener('abort', stop, { once: true });
30
+ });
31
+ aborted.catch(() => undefined);
32
+ await Promise.race([hold(job, started), aborted]);
33
+ const doc = await source.read(job.readByPool!.path);
34
+ const { readByPool: _drop, ...rest } = job;
35
+ return extractJob({ ...rest, doc } as ExtractJob, [DOCS_PACK]);
36
+ },
37
+ };
38
+ }
39
+
40
+ describe('read-ahead with a pool that reads', () => {
41
+ afterEach(() => jest.useRealTimers());
42
+
43
+ it('regression: one slow head file does not stop the other files being extracted beyond 64 ahead', async () => {
44
+ const source = memSource(files());
45
+ const head = 'd0000.md';
46
+ let startedWhenHeadSettled = 0;
47
+ let release!: () => void;
48
+ const gate = new Promise<void>((r) => { release = r; });
49
+ const { pool, started } = readingPool(source, async (job, n) => {
50
+ if (job.path === head) {
51
+ // The head settles only once well over 64 other files have started.
52
+ await Promise.race([gate, new Promise<void>((r) => setTimeout(r, 500))]);
53
+ startedWhenHeadSettled = started();
54
+ } else if (n > 100) release();
55
+ });
56
+ const report = await reviewDirectory(args(source, new LocalSnapshotStore(memPersistence()), new InMemoryIngestManifest(), {
57
+ judgement: fakeJudge(), mechanical: true, extractPool: pool, deferRead: true, concurrency: 8,
58
+ }));
59
+ expect(report.aborted).toBe(false);
60
+ expect(startedWhenHeadSettled - 1).toBeGreaterThan(64);
61
+ }, 15_000);
62
+
63
+ it('a judging (non-mechanical) review keeps the narrow window: at most 64 files ahead of a slow head', async () => {
64
+ const source = memSource(files());
65
+ const head = 'd0000.md';
66
+ let startedWhenHeadSettled = 0;
67
+ const { pool, started } = readingPool(source, async (job) => {
68
+ if (job.path === head) {
69
+ // Hold the head long enough for the window to fill, then record how far ahead the others got.
70
+ await new Promise<void>((r) => setTimeout(r, 300));
71
+ startedWhenHeadSettled = started();
72
+ }
73
+ });
74
+ const report = await reviewDirectory(args(source, new LocalSnapshotStore(memPersistence()), new InMemoryIngestManifest(), {
75
+ judgement: fakeJudge(), extractPool: pool, deferRead: true, concurrency: 8,
76
+ }));
77
+ expect(report.aborted).toBe(false);
78
+ expect(startedWhenHeadSettled - 1).toBeLessThanOrEqual(64);
79
+ });
80
+
81
+ it('regression: Stop settles the review at once with hundreds of jobs queued behind the slots', async () => {
82
+ jest.useFakeTimers();
83
+ const source = memSource(files());
84
+ const ctl = new AbortController();
85
+ // Every pool job hangs until its signal aborts (an AbortError, as the host pool does); queued limiter waiters must not hold up the settle.
86
+ const { pool, started } = readingPool(source, () => new Promise<void>(() => undefined));
87
+ const run = reviewDirectory(args(source, new LocalSnapshotStore(memPersistence()), new InMemoryIngestManifest(), {
88
+ judgement: fakeJudge(), mechanical: true, extractPool: pool, deferRead: true, concurrency: 8, signal: ctl.signal,
89
+ }));
90
+ await jest.advanceTimersByTimeAsync(50);
91
+ expect(started()).toBe(8);
92
+ ctl.abort();
93
+ // No timer is advanced past the 10 s extract deadline: the stop alone settles every in-flight and queued job.
94
+ const report = await run;
95
+ expect(report.aborted).toBe(true);
96
+ });
97
+ });
@@ -46,6 +46,22 @@ import { compareNew, pendingClaims, saveAwaiting } from './reviewCompare.js';
46
46
  import { factsWithoutAnchor, StoredIndex } from './reviewStored.js';
47
47
  import { canonicalJson, compareStr, srcRef } from './refs.js';
48
48
 
49
+ /** Read-ahead window for a MECHANICAL review with a pool that reads files itself: wide enough to buffer finished results behind one slow head file. Real extraction width is bounded separately (the extract-slot limiter in reviewPrefetch). */
50
+ const POOL_READ_AHEAD_DEFAULT = 256;
51
+ const POOL_READ_AHEAD_MAX = 512;
52
+
53
+ /** Files read and extracted ahead of the ordered writer. */
54
+ function readAheadOf(args: ReviewArgs, concurrency: number): number {
55
+ if (!args.extractPool) return concurrency;
56
+ // Wide only for a mechanical pool-reads run: each settled prefetch then holds just the small extracted output.
57
+ // A judging review keeps each settled file's parsed sections in memory, so it keeps the narrow window.
58
+ if (args.deferRead && args.mechanical) {
59
+ const want = Math.floor(args.readAhead ?? Math.max(POOL_READ_AHEAD_DEFAULT, concurrency * 32)) || concurrency;
60
+ return Math.min(POOL_READ_AHEAD_MAX, Math.max(concurrency, want));
61
+ }
62
+ return Math.min(64, Math.max(concurrency, Math.floor(args.readAhead ?? Math.max(32, concurrency * 4)) || concurrency));
63
+ }
64
+
49
65
  /** One changed file between dispatch and the ordered writer: what its prefetch found and its judging in flight. */
50
66
  interface Slot {
51
67
  f: { path: string; hash: string };
@@ -153,9 +169,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
153
169
  // Judging runs `judgeWidth` files at once; ONE writer (`applyFile`) consumes them strictly in plan order.
154
170
  const concurrency = Math.min(32, Math.max(1, Math.floor(args.concurrency ?? DEFAULT_REVIEW_CONCURRENCY) || 1));
155
171
  // Read-ahead is wider than the pool (PRD 41 A10 rule 8) so workers never wait for the ordered writer.
156
- const readAhead = args.extractPool
157
- ? Math.min(64, Math.max(concurrency, Math.floor(args.readAhead ?? Math.max(32, concurrency * 4)) || concurrency))
158
- : concurrency;
172
+ const readAhead = readAheadOf(args, concurrency);
159
173
  const judgeWidth = Math.min(concurrency, Math.min(16, Math.max(1, Math.floor(args.judgeConcurrency ?? DEFAULT_REVIEW_JUDGE_CONCURRENCY) || 1)));
160
174
  // The run's own stop: the caller's abort relays into it, and a thrown error (a local store failure) aborts it,
161
175
  // so queued and in-flight judge calls and pool jobs stop and nothing outlives the run.
@@ -78,6 +78,8 @@ export function createPrefetch(c: PrefetchContext): (f: { path: string; hash: st
78
78
  const byPool = !!c.args.extractPool && !!c.args.deferRead;
79
79
 
80
80
  const run = async (f: { path: string; hash: string }, parts: NonNullable<ReviewStep['parts']>, held: { lane: number }): Promise<Outcome> => {
81
+ // A stopped run starts nothing: a job that has not begun settles at once. Once the read has begun the job finishes (its slot wait below is signal-free for a file already read).
82
+ if (c.signal.aborted) return { kind: 'failed', reason: reasonOf(c.signal.reason) };
81
83
  let doc: SourceDocument | undefined;
82
84
  const t0 = Date.now();
83
85
  if (!byPool) {
@@ -96,7 +98,7 @@ export function createPrefetch(c: PrefetchContext): (f: { path: string; hash: st
96
98
  onTiming: (t) => { parts.lookupMs = t.lookupMs; parts.poolMs = t.poolMs; },
97
99
  ...(c.args.extractPool ? { pool: c.args.extractPool, signal, wantsSections, ...(byPool ? { readByPool: true } : {}) } : {}),
98
100
  })); } finally { lanes.free(held.lane); }
99
- });
101
+ }, byPool ? c.signal : undefined);
100
102
  if (!extraction) return { kind: 'none' };
101
103
  // Binary and no-pack files are decided above and never hash-checked (as in the host worker). For a file that WILL be
102
104
  // stored, the bytes read must be the bytes planned: hashed once, from the text already in hand. The review writes the
@@ -116,7 +118,8 @@ export function createPrefetch(c: PrefetchContext): (f: { path: string; hash: st
116
118
  const held = { lane: 0 };
117
119
  const out = await run(f, parts, held);
118
120
  const job = { ...out, ms: Date.now() - t0, lane: held.lane, parts } as Prefetch;
119
- c.args.onStep?.(extractStepOf(f.path, job));
121
+ // A job that ended only because the run was stopped is not a failed file: one Stop must not emit hundreds of failed steps. A job that finished normally still reports.
122
+ if (!(c.signal.aborted && job.kind === 'failed')) c.args.onStep?.(extractStepOf(f.path, job));
120
123
  return job;
121
124
  };
122
125
  }