@seanhogg/builderforce-memory 2026.10.44 → 2026.10.46
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.
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +34 -2
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/extractFile.d.ts +9 -1
- package/dist/knowledge/extractFile.d.ts.map +1 -1
- package/dist/knowledge/extractFile.js +22 -5
- package/dist/knowledge/extractFile.js.map +1 -1
- package/dist/knowledge/extractJob.d.ts +30 -5
- package/dist/knowledge/extractJob.d.ts.map +1 -1
- package/dist/knowledge/extractJob.js +9 -1
- package/dist/knowledge/extractJob.js.map +1 -1
- package/dist/knowledge/findings.d.ts.map +1 -1
- package/dist/knowledge/findings.js +9 -1
- package/dist/knowledge/findings.js.map +1 -1
- package/dist/knowledge/index.d.ts +7 -4
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +3 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/jobDeadline.d.ts +17 -0
- package/dist/knowledge/jobDeadline.d.ts.map +1 -0
- package/dist/knowledge/jobDeadline.js +46 -0
- package/dist/knowledge/jobDeadline.js.map +1 -0
- package/dist/knowledge/judgeCalls.d.ts +16 -0
- package/dist/knowledge/judgeCalls.d.ts.map +1 -1
- package/dist/knowledge/judgeCalls.js +20 -1
- package/dist/knowledge/judgeCalls.js.map +1 -1
- package/dist/knowledge/judgePriority.d.ts +22 -0
- package/dist/knowledge/judgePriority.d.ts.map +1 -0
- package/dist/knowledge/judgePriority.js +28 -0
- package/dist/knowledge/judgePriority.js.map +1 -0
- package/dist/knowledge/model.d.ts +57 -0
- package/dist/knowledge/model.d.ts.map +1 -1
- package/dist/knowledge/outline.d.ts.map +1 -1
- package/dist/knowledge/outline.js +14 -1
- package/dist/knowledge/outline.js.map +1 -1
- package/dist/knowledge/pack/crc32.d.ts +3 -0
- package/dist/knowledge/pack/crc32.d.ts.map +1 -0
- package/dist/knowledge/pack/crc32.js +18 -0
- package/dist/knowledge/pack/crc32.js.map +1 -0
- package/dist/knowledge/pack/decode.d.ts +14 -0
- package/dist/knowledge/pack/decode.d.ts.map +1 -0
- package/dist/knowledge/pack/decode.js +64 -0
- package/dist/knowledge/pack/decode.js.map +1 -0
- package/dist/knowledge/pack/deflate.d.ts +9 -0
- package/dist/knowledge/pack/deflate.d.ts.map +1 -0
- package/dist/knowledge/pack/deflate.js +45 -0
- package/dist/knowledge/pack/deflate.js.map +1 -0
- package/dist/knowledge/pack/encode.d.ts +17 -0
- package/dist/knowledge/pack/encode.d.ts.map +1 -0
- package/dist/knowledge/pack/encode.js +79 -0
- package/dist/knowledge/pack/encode.js.map +1 -0
- package/dist/knowledge/pack/extrDiff.d.ts +23 -0
- package/dist/knowledge/pack/extrDiff.d.ts.map +1 -0
- package/dist/knowledge/pack/extrDiff.js +0 -0
- package/dist/knowledge/pack/extrDiff.js.map +1 -0
- package/dist/knowledge/pack/frame.d.ts +37 -0
- package/dist/knowledge/pack/frame.d.ts.map +1 -0
- package/dist/knowledge/pack/frame.js +94 -0
- package/dist/knowledge/pack/frame.js.map +1 -0
- package/dist/knowledge/pack/index.d.ts +19 -0
- package/dist/knowledge/pack/index.d.ts.map +1 -0
- package/dist/knowledge/pack/index.js +17 -0
- package/dist/knowledge/pack/index.js.map +1 -0
- package/dist/knowledge/pack/jsonSize.d.ts +5 -0
- package/dist/knowledge/pack/jsonSize.d.ts.map +1 -0
- package/dist/knowledge/pack/jsonSize.js +8 -0
- package/dist/knowledge/pack/jsonSize.js.map +1 -0
- package/dist/knowledge/pack/manifest.d.ts +66 -0
- package/dist/knowledge/pack/manifest.d.ts.map +1 -0
- package/dist/knowledge/pack/manifest.js +104 -0
- package/dist/knowledge/pack/manifest.js.map +1 -0
- package/dist/knowledge/pack/sections/columns.d.ts +32 -0
- package/dist/knowledge/pack/sections/columns.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/columns.js +53 -0
- package/dist/knowledge/pack/sections/columns.js.map +1 -0
- package/dist/knowledge/pack/sections/extr.d.ts +8 -0
- package/dist/knowledge/pack/sections/extr.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/extr.js +99 -0
- package/dist/knowledge/pack/sections/extr.js.map +1 -0
- package/dist/knowledge/pack/sections/extrLists.d.ts +23 -0
- package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/extrLists.js +194 -0
- package/dist/knowledge/pack/sections/extrLists.js.map +1 -0
- package/dist/knowledge/pack/sections/facts.d.ts +8 -0
- package/dist/knowledge/pack/sections/facts.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/facts.js +167 -0
- package/dist/knowledge/pack/sections/facts.js.map +1 -0
- package/dist/knowledge/pack/sections/index.d.ts +6 -0
- package/dist/knowledge/pack/sections/index.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/index.js +9 -0
- package/dist/knowledge/pack/sections/index.js.map +1 -0
- package/dist/knowledge/pack/sections/rows.d.ts +31 -0
- package/dist/knowledge/pack/sections/rows.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/rows.js +226 -0
- package/dist/knowledge/pack/sections/rows.js.map +1 -0
- package/dist/knowledge/pack/strings.d.ts +39 -0
- package/dist/knowledge/pack/strings.d.ts.map +1 -0
- package/dist/knowledge/pack/strings.js +115 -0
- package/dist/knowledge/pack/strings.js.map +1 -0
- package/dist/knowledge/pack/types.d.ts +109 -0
- package/dist/knowledge/pack/types.d.ts.map +1 -0
- package/dist/knowledge/pack/types.js +17 -0
- package/dist/knowledge/pack/types.js.map +1 -0
- package/dist/knowledge/pack/varint.d.ts +50 -0
- package/dist/knowledge/pack/varint.d.ts.map +1 -0
- package/dist/knowledge/pack/varint.js +141 -0
- package/dist/knowledge/pack/varint.js.map +1 -0
- package/dist/knowledge/partitions.d.ts +1 -1
- package/dist/knowledge/partitions.d.ts.map +1 -1
- package/dist/knowledge/partitions.js +6 -1
- package/dist/knowledge/partitions.js.map +1 -1
- package/dist/knowledge/review.d.ts.map +1 -1
- package/dist/knowledge/review.js +58 -16
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewJudge.d.ts +8 -1
- package/dist/knowledge/reviewJudge.d.ts.map +1 -1
- package/dist/knowledge/reviewJudge.js +14 -8
- package/dist/knowledge/reviewJudge.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +35 -1
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts +8 -2
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +50 -25
- package/dist/knowledge/reviewPrefetch.js.map +1 -1
- package/dist/knowledge/reviewRun.d.ts +15 -3
- package/dist/knowledge/reviewRun.d.ts.map +1 -1
- package/dist/knowledge/reviewRun.js +19 -2
- package/dist/knowledge/reviewRun.js.map +1 -1
- package/dist/knowledge/reviewRunModel.d.ts +8 -1
- package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
- package/dist/knowledge/reviewRunModel.js.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.d.ts +72 -6
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +279 -75
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/dist/knowledge/systems.d.ts +18 -0
- package/dist/knowledge/systems.d.ts.map +1 -0
- package/dist/knowledge/systems.js +29 -0
- package/dist/knowledge/systems.js.map +1 -0
- package/package.json +7 -3
- package/src/knowledge/build.ts +31 -3
- package/src/knowledge/extractFile.ts +26 -6
- package/src/knowledge/extractJob.ts +26 -7
- package/src/knowledge/findings.ts +9 -1
- package/src/knowledge/index.ts +7 -3
- package/src/knowledge/jobDeadline.ts +43 -0
- package/src/knowledge/judgeCalls.ts +19 -2
- package/src/knowledge/judgePriority.ts +36 -0
- package/src/knowledge/model.ts +49 -0
- package/src/knowledge/outline.test.ts +50 -0
- package/src/knowledge/outline.ts +15 -1
- package/src/knowledge/pack/crc32.ts +17 -0
- package/src/knowledge/pack/decode.ts +58 -0
- package/src/knowledge/pack/deflate.ts +43 -0
- package/src/knowledge/pack/encode.ts +81 -0
- package/src/knowledge/pack/extrDiff.ts +0 -0
- package/src/knowledge/pack/frame.ts +86 -0
- package/src/knowledge/pack/index.ts +26 -0
- package/src/knowledge/pack/jsonSize.ts +11 -0
- package/src/knowledge/pack/manifest.ts +128 -0
- package/src/knowledge/pack/pack.guards.test.ts +77 -0
- package/src/knowledge/pack/pack.reconcile.test.ts +96 -0
- package/src/knowledge/pack/pack.roundtrip.test.ts +50 -0
- package/src/knowledge/pack/pack.size.test.ts +22 -0
- package/src/knowledge/pack/pack.testkit.test-util.ts +90 -0
- package/src/knowledge/pack/sections/columns.ts +61 -0
- package/src/knowledge/pack/sections/extr.ts +90 -0
- package/src/knowledge/pack/sections/extrLists.ts +147 -0
- package/src/knowledge/pack/sections/facts.ts +123 -0
- package/src/knowledge/pack/sections/index.ts +13 -0
- package/src/knowledge/pack/sections/rows.ts +184 -0
- package/src/knowledge/pack/strings.ts +123 -0
- package/src/knowledge/pack/types.ts +89 -0
- package/src/knowledge/pack/varint.ts +138 -0
- package/src/knowledge/partitions.test.ts +4 -0
- package/src/knowledge/partitions.ts +3 -1
- package/src/knowledge/review.throughput.test.ts +122 -0
- package/src/knowledge/review.ts +54 -16
- package/src/knowledge/review.twoPass.test.ts +224 -0
- package/src/knowledge/reviewJudge.ts +19 -8
- package/src/knowledge/reviewModel.ts +32 -1
- package/src/knowledge/reviewPrefetch.ts +51 -24
- package/src/knowledge/reviewRun.test.ts +20 -3
- package/src/knowledge/reviewRun.ts +33 -6
- package/src/knowledge/reviewRunModel.ts +4 -1
- package/src/knowledge/stores/localSnapshotStore.batched.test.ts +25 -3
- package/src/knowledge/stores/localSnapshotStore.extractedLog.test.ts +280 -0
- package/src/knowledge/stores/localSnapshotStore.ts +283 -76
- package/src/knowledge/systems.test.ts +119 -0
- package/src/knowledge/systems.ts +32 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/review.throughput.test.ts — PRD 41 A10 Accept: a 20,000-file folder is MAPPED by pass 1
|
|
3
|
+
* (`mechanical`) without a model call, through a pool of width 4, in time that measures the pipeline's own overhead (60 s is the CI ceiling,
|
|
4
|
+
* not the goal), and neither a slow snapshot checkpoint nor a 30,000-op replica queue with a slow durable write is waited on inside a file's step.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
|
|
8
|
+
import { extractJob, type ExtractPool } from './extractJob.js';
|
|
9
|
+
import { DOCS_PACK } from './packs/docs.js';
|
|
10
|
+
import type { KnowledgePack, KnowledgeStore, ReviewProgress } from './model.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 TS_FILES = 19_800;
|
|
16
|
+
const MD_FILES = 200;
|
|
17
|
+
const TOTAL = TS_FILES + MD_FILES;
|
|
18
|
+
const CEILING_MS = 60_000;
|
|
19
|
+
|
|
20
|
+
/** A code-ish pack with no judgement: every `.ts` is one file node. */
|
|
21
|
+
const TS_PACK: KnowledgePack = {
|
|
22
|
+
id: 'ts', parsers: [{ id: 'ts', accepts: (s) => s.id.endsWith('.ts'), parse: () => [] }],
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
function fixture(): Record<string, string> {
|
|
26
|
+
const out: Record<string, string> = {};
|
|
27
|
+
for (let i = 0; i < TS_FILES; i++) out[`src/m${Math.floor(i / 100)}/f${i}.ts`] = `export const v${i} = ${i};\n`;
|
|
28
|
+
for (let i = 0; i < MD_FILES; i++) out[`docs/d${i}.md`] = `# D${i}\nbody ${i}\n`;
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A pool of width 4 that extracts in-process, one job per tick, and records how many jobs it held at once. */
|
|
33
|
+
function fakePool(): { pool: ExtractPool; peak: () => number; calls: () => number } {
|
|
34
|
+
let busy = 0, peak = 0, calls = 0;
|
|
35
|
+
const packs = [TS_PACK, DOCS_PACK];
|
|
36
|
+
return {
|
|
37
|
+
peak: () => peak, calls: () => calls,
|
|
38
|
+
pool: async (job) => {
|
|
39
|
+
busy += 1; calls += 1; peak = Math.max(peak, busy);
|
|
40
|
+
await Promise.resolve();
|
|
41
|
+
const out = extractJob(job, packs);
|
|
42
|
+
busy -= 1;
|
|
43
|
+
return out;
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
describe('pass 1 throughput (PRD 41 A10)', () => {
|
|
49
|
+
it('maps 20,000 files with no model call through a pool of width 4 within the CI ceiling', async () => {
|
|
50
|
+
const judge = fakeJudge();
|
|
51
|
+
const { pool, peak, calls } = fakePool();
|
|
52
|
+
const phases: string[] = [];
|
|
53
|
+
const events: ReviewProgress[] = [];
|
|
54
|
+
const t0 = Date.now();
|
|
55
|
+
const report = await reviewDirectory(args(memSource(fixture()), new LocalSnapshotStore(memPersistence()), new InMemoryIngestManifest(), {
|
|
56
|
+
packs: [TS_PACK, DOCS_PACK], judgement: judge, mechanical: true, extractPool: pool, concurrency: 4,
|
|
57
|
+
onProgress: (p) => { events.push(p); if (phases[phases.length - 1] !== p.phase) phases.push(p.phase); },
|
|
58
|
+
}));
|
|
59
|
+
const elapsed = Date.now() - t0;
|
|
60
|
+
|
|
61
|
+
expect(judge.requests).toHaveLength(0);
|
|
62
|
+
expect(report.aborted).toBe(false);
|
|
63
|
+
expect(report.failures).toEqual([]);
|
|
64
|
+
expect(report.extracted).toBe(TOTAL);
|
|
65
|
+
expect(calls()).toBe(TOTAL);
|
|
66
|
+
expect(peak()).toBeLessThanOrEqual(4);
|
|
67
|
+
expect(report.awaitingJudge).toHaveLength(MD_FILES); // the docs are judged later; code never is
|
|
68
|
+
expect(report.awaitingJudgeCount).toBe(MD_FILES);
|
|
69
|
+
// The map is complete: memory's last word is `done` after every file reached extract and write.
|
|
70
|
+
expect(phases[phases.length - 1]).toBe('done');
|
|
71
|
+
expect(events.filter((e) => e.phase === 'write')).toHaveLength(TOTAL);
|
|
72
|
+
expect(elapsed).toBeLessThan(CEILING_MS);
|
|
73
|
+
}, 120_000);
|
|
74
|
+
|
|
75
|
+
it('does not wait for a snapshot checkpoint or a 30,000-op replica queue inside a file\'s step', async () => {
|
|
76
|
+
let release!: () => void;
|
|
77
|
+
const gate = new Promise<void>((r) => { release = r; });
|
|
78
|
+
const durable = memPersistence();
|
|
79
|
+
const write = durable.write;
|
|
80
|
+
let started = 0;
|
|
81
|
+
// Every durable write (the snapshot's checkpoints, the queue's saves) hangs until the run has applied its last file.
|
|
82
|
+
durable.write = async (s) => { started += 1; await gate; await write(s); };
|
|
83
|
+
const local = new LocalSnapshotStore(durable, { checkpointMs: 1 });
|
|
84
|
+
|
|
85
|
+
// The replica queue as the A7 wrapper uses it: 30,000 ops already queued, a durable save that is slow, and an `enqueue` that only appends.
|
|
86
|
+
const queue = { ops: Array.from({ length: 30_000 }, (_, i) => `op${i}`), saves: 0, enqueues: 0 };
|
|
87
|
+
const save = async (): Promise<void> => { queue.saves += 1; await gate; };
|
|
88
|
+
let saving: Promise<void> | undefined;
|
|
89
|
+
const enqueue = (op: string): void => {
|
|
90
|
+
queue.ops.push(op); queue.enqueues += 1;
|
|
91
|
+
saving ??= save().finally(() => { saving = undefined; }); // at most one save in flight; never awaited by a step
|
|
92
|
+
};
|
|
93
|
+
const replicated: KnowledgeStore = {
|
|
94
|
+
scopes: () => local.scopes(), facts: (s) => local.facts(s), relations: (s) => local.relations(s),
|
|
95
|
+
getExtracted: (h) => local.getExtracted(h),
|
|
96
|
+
batched: (work) => local.batched(work),
|
|
97
|
+
async write(batch) { await local.write(batch); enqueue(`w:${batch.facts.length}`); },
|
|
98
|
+
async markStale(scope, ref, hash) { await local.markStale(scope, ref, hash); enqueue(`s:${ref}`); },
|
|
99
|
+
async putExtracted(hash, ex) { await local.putExtracted(hash, ex); enqueue(`x:${hash}`); },
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const files = fixture();
|
|
103
|
+
const small = Object.fromEntries(Object.entries(files).slice(0, 3_000));
|
|
104
|
+
const { pool } = fakePool();
|
|
105
|
+
let lastWrite = 0;
|
|
106
|
+
const total = Object.keys(small).length;
|
|
107
|
+
const report = await reviewDirectory(args(memSource(small), replicated, new InMemoryIngestManifest(), {
|
|
108
|
+
packs: [TS_PACK, DOCS_PACK], judgement: fakeJudge(), mechanical: true, extractPool: pool, concurrency: 4,
|
|
109
|
+
onProgress: (p) => {
|
|
110
|
+
if (p.phase !== 'write') return;
|
|
111
|
+
lastWrite = p.done + 1;
|
|
112
|
+
if (lastWrite === total) release(); // had a step awaited a pending durable write, this would never be reached
|
|
113
|
+
},
|
|
114
|
+
}));
|
|
115
|
+
|
|
116
|
+
expect(lastWrite).toBe(total);
|
|
117
|
+
expect(report.extracted).toBe(total);
|
|
118
|
+
expect(started).toBeGreaterThan(0); // checkpoints really were pending while files were applied
|
|
119
|
+
expect(queue.enqueues).toBeGreaterThan(total);
|
|
120
|
+
expect(queue.saves).toBeLessThanOrEqual(1 + Math.ceil(queue.enqueues / 500)); // saves are batched, not per op
|
|
121
|
+
}, 120_000);
|
|
122
|
+
});
|
package/src/knowledge/review.ts
CHANGED
|
@@ -38,7 +38,8 @@ import {
|
|
|
38
38
|
type CompareOutcome, type JudgeBudget,
|
|
39
39
|
} from './judge.js';
|
|
40
40
|
import { createModelLimiter } from './modelLimiter.js';
|
|
41
|
-
import {
|
|
41
|
+
import { JudgeBreaker } from './judgeCalls.js';
|
|
42
|
+
import { applyJudge, judgesPack, splitSections, startJudge, type JudgeJob } from './reviewJudge.js';
|
|
42
43
|
import { createPrefetch, type Prefetch } from './reviewPrefetch.js';
|
|
43
44
|
import { Lanes } from './reviewRunModel.js';
|
|
44
45
|
import { compareNew, pendingClaims, saveAwaiting } from './reviewCompare.js';
|
|
@@ -76,7 +77,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
76
77
|
const progress = (p: Parameters<NonNullable<ReviewArgs['onProgress']>>[0]) => args.onProgress?.(p);
|
|
77
78
|
const report: ReviewReport = {
|
|
78
79
|
rootId, digest: '', extracted: 0, judged: 0, unjudged: 0, invalidJudgements: 0,
|
|
79
|
-
factsWritten: 0, relationsWritten: 0, staleMarked: 0, readErrors: 0, extractErrors: 0, failures: [], aborted: false, durationMs: 0,
|
|
80
|
+
factsWritten: 0, relationsWritten: 0, staleMarked: 0, readErrors: 0, extractErrors: 0, failures: [], awaitingJudge: [], aborted: false, durationMs: 0,
|
|
80
81
|
};
|
|
81
82
|
|
|
82
83
|
const detail = args.plan
|
|
@@ -96,6 +97,8 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
96
97
|
used: 0, now,
|
|
97
98
|
};
|
|
98
99
|
const batch = new JudgedBatch();
|
|
100
|
+
const breaker = new JudgeBreaker();
|
|
101
|
+
const owedJudge: string[] = [];
|
|
99
102
|
const judgedPrior = await manifestMap(manifest, judgedManifestKey(rootId));
|
|
100
103
|
const judgedNow = new Map(judgedPrior);
|
|
101
104
|
const filesNow = new Map(detail.prior);
|
|
@@ -134,17 +137,25 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
134
137
|
};
|
|
135
138
|
|
|
136
139
|
const changed = detail.files.filter((f) => f.changed);
|
|
140
|
+
// `only` (pass 2) narrows what this run works on; the other changed files are untouched and stay owed (owedAfterRun sees them all).
|
|
141
|
+
// Pass 2 works in the order it was given (priority), so a model-call ceiling is spent on the most important files first.
|
|
142
|
+
const byPath = new Map(changed.map((f) => [f.path, f] as const));
|
|
143
|
+
const work = args.only ? args.only.flatMap((p) => byPath.get(p) ?? []) : changed;
|
|
137
144
|
// Changed files this run finished (or had nothing to do for); an owed file not in it stays owed,
|
|
138
145
|
// at the model calls it still costs where this run could measure that (see owedFiles.ts).
|
|
139
146
|
const finished = new Set<string>();
|
|
140
147
|
const measured = new Map<string, number>();
|
|
141
148
|
// One bulk fetch of the extract cache for the whole run instead of a round trip per file.
|
|
142
|
-
const hashes = [...new Set(
|
|
149
|
+
const hashes = [...new Set(work.map((f) => f.hash))];
|
|
143
150
|
if (hashes.length > 0) await store.preloadExtracted?.(hashes);
|
|
144
151
|
// Read + binary check + extract run ahead with bounded concurrency (extraction only reads `knownKeys`,
|
|
145
152
|
// fixed above, and the content-hash extract cache); with `args.extractPool` the width is the pool's.
|
|
146
153
|
// Judging runs `judgeWidth` files at once; ONE writer (`applyFile`) consumes them strictly in plan order.
|
|
147
154
|
const concurrency = Math.min(32, Math.max(1, Math.floor(args.concurrency ?? DEFAULT_REVIEW_CONCURRENCY) || 1));
|
|
155
|
+
// 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;
|
|
148
159
|
const judgeWidth = Math.min(concurrency, Math.min(16, Math.max(1, Math.floor(args.judgeConcurrency ?? DEFAULT_REVIEW_JUDGE_CONCURRENCY) || 1)));
|
|
149
160
|
// The run's own stop: the caller's abort relays into it, and a thrown error (a local store failure) aborts it,
|
|
150
161
|
// so queued and in-flight judge calls and pool jobs stop and nothing outlives the run.
|
|
@@ -156,9 +167,10 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
156
167
|
const relay = () => { if (inWriter) cut = true; stopper.abort(signal?.reason); };
|
|
157
168
|
if (signal?.aborted) relay(); else signal?.addEventListener('abort', relay, { once: true });
|
|
158
169
|
const runSignal = stopper.signal;
|
|
159
|
-
const prefetch = createPrefetch({ args, signal: runSignal, rootId, packs, store, composed, knownKeys, width: concurrency });
|
|
170
|
+
const prefetch = createPrefetch({ args, signal: runSignal, rootId, packs, store, composed, knownKeys, width: readAhead, extractWidth: concurrency });
|
|
160
171
|
const dispatch = {
|
|
161
|
-
|
|
172
|
+
// A mechanical run (pass 1) makes no model call: judged files stay owed.
|
|
173
|
+
port: args.mechanical ? undefined : args.judgement, signal: runSignal, breaker, budget, judgedPrior, lanes: new Lanes(judgeWidth),
|
|
162
174
|
limiter: createModelLimiter(args.maxModelCalls ?? JUDGE_CONCURRENCY),
|
|
163
175
|
};
|
|
164
176
|
const judgeCtx = { batch, entities, stored, judgedNow, newClaims, measured, detail, report, ...(args.onStep ? { onStep: args.onStep } : {}) };
|
|
@@ -170,7 +182,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
170
182
|
* applied even after an abort — the work is done, so it is kept.
|
|
171
183
|
*/
|
|
172
184
|
const applyInner = async ({ f, i, job, judge }: Slot): Promise<boolean> => {
|
|
173
|
-
progress({ phase: 'extract', done: i, total:
|
|
185
|
+
progress({ phase: 'extract', done: i, total: work.length, path: f.path });
|
|
174
186
|
// A read that throws (permissions, a lock, a race with a delete) or an extraction that throws says nothing
|
|
175
187
|
// about the file: skipped with its knowledge and manifest hash intact, tried again next review.
|
|
176
188
|
if (job.kind === 'read-error' || job.kind === 'failed') {
|
|
@@ -192,24 +204,44 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
192
204
|
// The extract cache is written HERE, in plan order, so the cache, the counts and the order match a sequential run.
|
|
193
205
|
if (!job.extraction.cached) await putExtract(store, f.hash, job.extraction.extracted);
|
|
194
206
|
let complete = true;
|
|
207
|
+
let deferred = false;
|
|
208
|
+
if (args.mechanical && judgesPack(args.judgement, job.extraction.pack)) {
|
|
209
|
+
// Pass 1: the map has this file; its judgement is pass 2's. With sections at hand (in-thread parse) a file whose sections are all
|
|
210
|
+
// still judged costs no model call: its facts are refreshed and it is complete. A pool returns none in a mechanical run, so those files are
|
|
211
|
+
// owed and pass 2 finds nothing to judge (a cache hit, no call).
|
|
212
|
+
const { reuse, toJudge } = splitSections(judgedPrior, job.extraction);
|
|
213
|
+
if (job.extraction.sections.length > 0 && toJudge.length === 0) {
|
|
214
|
+
for (const ref of reuse) stored.refresh(ref, f.path, f.hash, batch, entities);
|
|
215
|
+
} else {
|
|
216
|
+
complete = false;
|
|
217
|
+
deferred = true;
|
|
218
|
+
owedJudge.push(f.path);
|
|
219
|
+
measured.set(f.path, Math.max(1, toJudge.length));
|
|
220
|
+
}
|
|
221
|
+
}
|
|
195
222
|
if (judge) {
|
|
196
|
-
progress({ phase: 'judge', done: i, total:
|
|
223
|
+
progress({ phase: 'judge', done: i, total: work.length, path: f.path });
|
|
197
224
|
inWriter = false; // waiting for the model calls is not the writer working
|
|
198
225
|
const outcome = await applyJudge(judgeCtx, f, judge);
|
|
199
226
|
inWriter = true;
|
|
200
227
|
if (outcome === 'aborted') return false;
|
|
201
228
|
if (outcome === 'failed') {
|
|
229
|
+
owedJudge.push(f.path);
|
|
202
230
|
// Judging failed as a whole: leave the file exactly as it was (facts, manifest hash, owed) so the next review retries it.
|
|
203
231
|
measured.set(f.path, owedCalls(detail.extractor, f.path));
|
|
204
232
|
return true;
|
|
205
233
|
}
|
|
206
234
|
complete = outcome.complete;
|
|
235
|
+
if (!complete) owedJudge.push(f.path);
|
|
207
236
|
}
|
|
208
|
-
progress({ phase: 'write', done: i, total:
|
|
237
|
+
progress({ phase: 'write', done: i, total: work.length, path: f.path });
|
|
209
238
|
const t0 = now();
|
|
210
239
|
await write();
|
|
211
|
-
|
|
212
|
-
|
|
240
|
+
// An owed file keeps its old judgement current until pass 2 replaces it: nothing of it is marked stale yet.
|
|
241
|
+
if (!deferred) {
|
|
242
|
+
await store.markStale(scope, srcRef(rootId, f.path), f.hash);
|
|
243
|
+
report.staleMarked += 1;
|
|
244
|
+
}
|
|
213
245
|
args.onStep?.({ path: f.path, phase: 'write', ms: now() - t0, outcome: 'ok' });
|
|
214
246
|
if (complete) { filesNow.set(f.path, f.hash); finished.add(f.path); }
|
|
215
247
|
return true;
|
|
@@ -226,7 +258,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
226
258
|
};
|
|
227
259
|
let completed = false;
|
|
228
260
|
try {
|
|
229
|
-
for await (const { item: f, i, result } of prefetchOrdered(
|
|
261
|
+
for await (const { item: f, i, result } of prefetchOrdered(work, readAhead, prefetch, runSignal)) {
|
|
230
262
|
if (result.status === 'rejected') throw result.reason; // a prefetch job settles to a Prefetch; this is a broken invariant
|
|
231
263
|
const job = result.value;
|
|
232
264
|
queue.push({ f, i, job, judge: job.kind === 'extracted' ? startJudge(dispatch, f, job.extraction) : undefined });
|
|
@@ -239,9 +271,10 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
239
271
|
signal?.removeEventListener('abort', relay);
|
|
240
272
|
await Promise.allSettled(queue.map((s) => s.judge?.result)); // nothing outlives the run
|
|
241
273
|
}
|
|
242
|
-
if (applied <
|
|
274
|
+
if (applied < work.length) report.aborted = true;
|
|
243
275
|
|
|
244
|
-
|
|
276
|
+
// Pass 2 (`only`) is judging alone: the map pass already retired the removed files and ran the analyzers.
|
|
277
|
+
if (!report.aborted && !args.only) {
|
|
245
278
|
await retire(detail.plan.removed);
|
|
246
279
|
// Analyzers run in parallel and a failing one never aborts the review — its extracted
|
|
247
280
|
// output is simply not stored (the file-level facts above are already durable), so a
|
|
@@ -264,7 +297,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
264
297
|
const wantsCompare = packs.some((p) => p.judgement?.contradictions);
|
|
265
298
|
const canCompare = wantsCompare && !!args.judgement && !!args.similar;
|
|
266
299
|
let outcome: CompareOutcome | undefined;
|
|
267
|
-
if (!report.aborted && canCompare) {
|
|
300
|
+
if (!report.aborted && canCompare && !args.mechanical) {
|
|
268
301
|
outcome = await compareNew({
|
|
269
302
|
args, pending: newClaims, known: stored.facts, budget, batch,
|
|
270
303
|
onPairs: (total) => progress({ phase: 'compare', done: 0, total }),
|
|
@@ -281,8 +314,13 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
281
314
|
await write();
|
|
282
315
|
await flush();
|
|
283
316
|
// No pack asks for contradictions: nothing waits, and an earlier run's awaiting set is left as it was.
|
|
284
|
-
if (wantsCompare) await saveAwaiting(manifest, rootId, newClaims, outcome);
|
|
317
|
+
if (wantsCompare && !args.mechanical) await saveAwaiting(manifest, rootId, newClaims, outcome);
|
|
285
318
|
|
|
319
|
+
// Pass 2: what is still owed is every file of its slice it did not finish (an abort leaves the unreached ones owed too).
|
|
320
|
+
report.awaitingJudge = args.only ? work.filter((f) => !finished.has(f.path)).map((f) => f.path) : owedJudge;
|
|
321
|
+
report.awaitingJudgeCount = report.awaitingJudge.length;
|
|
322
|
+
report.judgedFiles = args.only ? work.length - report.awaitingJudge.length : 0;
|
|
323
|
+
if (breaker.stopped) report.judgeStopped = breaker.stopped;
|
|
286
324
|
report.judged = batch.judged;
|
|
287
325
|
report.unjudged = batch.unjudged;
|
|
288
326
|
report.invalidJudgements = batch.invalid;
|
|
@@ -296,6 +334,6 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
296
334
|
}));
|
|
297
335
|
await write(report.aborted ? scopeRecord : { ...scopeRecord, lastDigest: report.digest, lastReviewedAt: new Date(now()).toISOString() });
|
|
298
336
|
report.durationMs = now() - started;
|
|
299
|
-
progress({ phase: 'done', done:
|
|
337
|
+
progress({ phase: 'done', done: work.length, total: work.length });
|
|
300
338
|
return report;
|
|
301
339
|
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/review.twoPass.test.ts — PRD 41 A10: the map is complete without the model (pass 1,
|
|
3
|
+
* `mechanical`), judging follows in priority order within a budget (pass 2, `only`), the next run judges only what
|
|
4
|
+
* is still owed, a hanging job is a `timeout` failure that never stalls the run, and consecutive provider failures
|
|
5
|
+
* stop judging with the sections left owed.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { hashText } from '../ingest/hash.js';
|
|
9
|
+
import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
|
|
10
|
+
import { DOCS_PACK } from './packs/docs.js';
|
|
11
|
+
import { extractJob } from './extractJob.js';
|
|
12
|
+
import type { ExtractPool } from './extractJob.js';
|
|
13
|
+
import { orderForJudging } from './judgePriority.js';
|
|
14
|
+
import { reviewDirectory } from './review.js';
|
|
15
|
+
import { applyRunEvent, slowestSteps, startRun } from './reviewRun.js';
|
|
16
|
+
import { LocalSnapshotStore } from './stores/localSnapshotStore.js';
|
|
17
|
+
import { args, fakeJudge, memPersistence, memSource, memStore, quietPack, ROOT, stateOf } from './testkit.test-util.js';
|
|
18
|
+
import type { ReviewStep } from './reviewRunModel.js';
|
|
19
|
+
|
|
20
|
+
const N = 6;
|
|
21
|
+
const files = () => Object.fromEntries(Array.from({ length: N }, (_, i) => [`d${i}.md`, `# T${i}\nbody ${i}\n`]));
|
|
22
|
+
const byKey = (a: { key: string }, b: { key: string }) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
23
|
+
const factsOf = async (store: ReturnType<typeof memStore>) => [...(await store.facts({ rootId: ROOT }))].sort(byKey);
|
|
24
|
+
|
|
25
|
+
describe('two-pass review', () => {
|
|
26
|
+
it('pass 1 makes no model call, completes the extract cache and lists every judged file as awaiting judgement', async () => {
|
|
27
|
+
const judge = fakeJudge();
|
|
28
|
+
const store = memStore();
|
|
29
|
+
const manifest = new InMemoryIngestManifest();
|
|
30
|
+
const report = await reviewDirectory(args(memSource(files()), store, manifest, { judgement: judge, mechanical: true, packs: [quietPack] }));
|
|
31
|
+
expect(judge.requests).toHaveLength(0);
|
|
32
|
+
expect(report.awaitingJudge).toEqual(Object.keys(files()));
|
|
33
|
+
expect(report.extracted).toBe(N);
|
|
34
|
+
expect(await factsOf(store)).toEqual([]);
|
|
35
|
+
expect(await store.getExtracted(hashText(files()['d0.md']!))).toBeDefined(); // the map has the file
|
|
36
|
+
expect((await stateOf(manifest)).owed).toEqual(Object.keys(files()));
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('pass 2 judges only the files named, and the next run judges only what is still owed', async () => {
|
|
40
|
+
const judge = fakeJudge();
|
|
41
|
+
const store = memStore();
|
|
42
|
+
const manifest = new InMemoryIngestManifest();
|
|
43
|
+
const source = memSource(files());
|
|
44
|
+
const base = { judgement: judge, packs: [quietPack] };
|
|
45
|
+
await reviewDirectory(args(source, store, manifest, { ...base, mechanical: true }));
|
|
46
|
+
const first = await reviewDirectory(args(source, store, manifest, { ...base, only: ['d3.md', 'd1.md'] }));
|
|
47
|
+
const judgedFirst = new Set(judge.requests.flatMap((r) => r.items.map((it) => it.ref as string)));
|
|
48
|
+
expect(judgedFirst.size).toBe(2);
|
|
49
|
+
expect([...judgedFirst].every((r) => r.includes('d1.md') || r.includes('d3.md'))).toBe(true);
|
|
50
|
+
expect((await stateOf(manifest)).owed).toEqual(['d0.md', 'd2.md', 'd4.md', 'd5.md']);
|
|
51
|
+
expect(first.judged).toBe(2);
|
|
52
|
+
|
|
53
|
+
judge.requests.length = 0;
|
|
54
|
+
const next = await reviewDirectory(args(source, store, manifest, base));
|
|
55
|
+
const judgedNext = judge.requests.flatMap((r) => r.items.map((it) => it.ref as string));
|
|
56
|
+
expect(judgedNext).toHaveLength(4);
|
|
57
|
+
expect(judgedNext.some((r) => r.includes('d1.md') || r.includes('d3.md'))).toBe(false);
|
|
58
|
+
expect(next.judged).toBe(4);
|
|
59
|
+
expect((await stateOf(manifest)).owed).toEqual([]);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('mechanical pass then pass 2 over every file stores the same facts as one sequential pass', async () => {
|
|
63
|
+
const single = memStore();
|
|
64
|
+
await reviewDirectory(args(memSource(files()), single, new InMemoryIngestManifest(), { judgement: fakeJudge(), packs: [quietPack], concurrency: 1, judgeConcurrency: 1 }));
|
|
65
|
+
|
|
66
|
+
const two = memStore();
|
|
67
|
+
const manifest = new InMemoryIngestManifest();
|
|
68
|
+
const source = memSource(files());
|
|
69
|
+
await reviewDirectory(args(source, two, manifest, { judgement: fakeJudge(), packs: [quietPack], mechanical: true, concurrency: 4 }));
|
|
70
|
+
await reviewDirectory(args(source, two, manifest, { judgement: fakeJudge(), packs: [quietPack], only: Object.keys(files()), concurrency: 4 }));
|
|
71
|
+
expect(await factsOf(two)).toEqual(await factsOf(single));
|
|
72
|
+
const relKey = (r: { from: string; to: string; kind: string }) => `${r.from}|${r.to}|${r.kind}`;
|
|
73
|
+
const sorted = async (st: ReturnType<typeof memStore>) => [...(await st.relations({ rootId: ROOT }))].sort((a, b) => (relKey(a) < relKey(b) ? -1 : 1));
|
|
74
|
+
expect(await sorted(two)).toEqual(await sorted(single));
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe('pass 1 owes only what costs a model call, and a partial budget stores what a sequential run stores', () => {
|
|
79
|
+
const K = 3;
|
|
80
|
+
const bytesOf = (p: { value?: string }) => {
|
|
81
|
+
const snap = JSON.parse(p.value!) as { scopes: Array<Record<string, unknown>> };
|
|
82
|
+
for (const sc of snap.scopes) delete sc.lastReviewedAt; // the wall clock of the run
|
|
83
|
+
return JSON.stringify(snap);
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
it('mechanical + pass 2 over the first K files equals one sequential run with a budget of K calls, byte for byte', async () => {
|
|
87
|
+
const seq = memPersistence();
|
|
88
|
+
await reviewDirectory(args(memSource(files()), new LocalSnapshotStore(seq, { now: () => 'T' }), new InMemoryIngestManifest(), {
|
|
89
|
+
judgement: fakeJudge(), packs: [quietPack], concurrency: 1, judgeConcurrency: 1, budget: { modelCalls: K, ms: 60_000 },
|
|
90
|
+
}));
|
|
91
|
+
|
|
92
|
+
const two = memPersistence();
|
|
93
|
+
const store = new LocalSnapshotStore(two, { now: () => 'T' });
|
|
94
|
+
const manifest = new InMemoryIngestManifest();
|
|
95
|
+
const source = memSource(files());
|
|
96
|
+
await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge(), packs: [quietPack], mechanical: true }));
|
|
97
|
+
await reviewDirectory(args(source, store, manifest, {
|
|
98
|
+
judgement: fakeJudge(), packs: [quietPack], only: Object.keys(files()).slice(0, K), budget: { modelCalls: K, ms: 60_000 },
|
|
99
|
+
}));
|
|
100
|
+
expect(bytesOf(two)).toEqual(bytesOf(seq));
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('a re-review of files whose sections are all still judged owes nothing and calls no model', async () => {
|
|
104
|
+
const store = memStore();
|
|
105
|
+
const manifest = new InMemoryIngestManifest();
|
|
106
|
+
const source = memSource(files());
|
|
107
|
+
await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge(), packs: [quietPack] }));
|
|
108
|
+
const judge = fakeJudge();
|
|
109
|
+
const report = await reviewDirectory(args(source, store, manifest, { judgement: judge, packs: [quietPack], mechanical: true, force: true }));
|
|
110
|
+
expect(judge.requests).toHaveLength(0);
|
|
111
|
+
expect(report.awaitingJudge).toEqual([]);
|
|
112
|
+
expect((await stateOf(manifest)).owed).toEqual([]);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('pass 2 follows the order it is given and reports what it left owed, unreached files included', async () => {
|
|
116
|
+
const judge = fakeJudge();
|
|
117
|
+
const store = memStore();
|
|
118
|
+
const manifest = new InMemoryIngestManifest();
|
|
119
|
+
const source = memSource(files());
|
|
120
|
+
const base = { judgement: judge, packs: [quietPack] };
|
|
121
|
+
await reviewDirectory(args(source, store, manifest, { ...base, mechanical: true }));
|
|
122
|
+
const order = ['d4.md', 'd0.md', 'd2.md'];
|
|
123
|
+
const report = await reviewDirectory(args(source, store, manifest, { ...base, only: order, concurrency: 1, judgeConcurrency: 1, budget: { modelCalls: 1, ms: 60_000 } }));
|
|
124
|
+
expect(judge.requests.map((r) => r.items[0]!.ref)).toEqual(['src:r::d4.md#'].map((p) => expect.stringContaining(p)));
|
|
125
|
+
expect(report.judgedFiles).toBe(1);
|
|
126
|
+
expect(report.awaitingJudge).toEqual(['d0.md', 'd2.md']);
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe('per-job timeouts', () => {
|
|
131
|
+
const hang = (path: string): ExtractPool => (job, signal) =>
|
|
132
|
+
job.path === path
|
|
133
|
+
? new Promise((_, reject) => signal?.addEventListener('abort', () => reject(new Error('aborted')), { once: true }))
|
|
134
|
+
: Promise.resolve(extractJob(job, [DOCS_PACK]));
|
|
135
|
+
|
|
136
|
+
it('a hanging extractor is one timeout failure (its worker told to stop) and the run continues', async () => {
|
|
137
|
+
const steps: ReviewStep[] = [];
|
|
138
|
+
const started = Date.now();
|
|
139
|
+
const report = await reviewDirectory(args(memSource(files()), memStore(), new InMemoryIngestManifest(), {
|
|
140
|
+
extractPool: hang('d2.md'), concurrency: 2, timeouts: { extractMs: 60 }, onStep: (s) => steps.push(s),
|
|
141
|
+
}));
|
|
142
|
+
expect(Date.now() - started).toBeLessThan(5_000);
|
|
143
|
+
expect(report.aborted).toBe(false);
|
|
144
|
+
expect(report.extractErrors).toBe(1);
|
|
145
|
+
expect(report.failures).toEqual([{ path: 'd2.md', phase: 'extract', reason: 'timeout' }]);
|
|
146
|
+
expect(report.extracted).toBe(N - 1);
|
|
147
|
+
expect(steps.filter((s) => s.phase === 'extract' && s.outcome === 'failed').map((s) => s.reason)).toEqual(['timeout']);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it('a read that never returns is a failed read with a timeout and the file keeps its prior state', async () => {
|
|
151
|
+
const source = memSource(files());
|
|
152
|
+
const read = source.read.bind(source);
|
|
153
|
+
source.read = (path) => (path === 'd1.md' ? new Promise(() => undefined) : read(path));
|
|
154
|
+
const report = await reviewDirectory(args(source, memStore(), new InMemoryIngestManifest(), { timeouts: { readMs: 40 } }));
|
|
155
|
+
expect(report.readErrors).toBe(1);
|
|
156
|
+
expect(report.failures).toEqual([{ path: 'd1.md', phase: 'extract', reason: 'read: timeout' }]);
|
|
157
|
+
expect(report.extracted).toBe(N - 1);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it('queued jobs are not timed out while they wait for a pool slot', async () => {
|
|
161
|
+
let busy = 0, peak = 0;
|
|
162
|
+
const slow: ExtractPool = async (job) => {
|
|
163
|
+
busy += 1; peak = Math.max(peak, busy);
|
|
164
|
+
await new Promise((r) => setTimeout(r, 30));
|
|
165
|
+
busy -= 1;
|
|
166
|
+
return extractJob(job, [DOCS_PACK]);
|
|
167
|
+
};
|
|
168
|
+
const report = await reviewDirectory(args(memSource(files()), memStore(), new InMemoryIngestManifest(), {
|
|
169
|
+
extractPool: slow, concurrency: 1, readAhead: 6, timeouts: { extractMs: 200 },
|
|
170
|
+
}));
|
|
171
|
+
expect(peak).toBe(1);
|
|
172
|
+
expect(report.failures).toEqual([]);
|
|
173
|
+
expect(report.extracted).toBe(N);
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
describe('judge breaker', () => {
|
|
178
|
+
it('stops judging after consecutive failures; the unjudged sections stay owed and the next run judges them', async () => {
|
|
179
|
+
let fail = true;
|
|
180
|
+
const calls: string[] = [];
|
|
181
|
+
const judge = {
|
|
182
|
+
async judge(req: Parameters<ReturnType<typeof fakeJudge>['judge']>[0]) {
|
|
183
|
+
calls.push(req.items[0]!.ref as string);
|
|
184
|
+
if (fail) throw new Error('judge: timeout after 60s');
|
|
185
|
+
return fakeJudge().judge(req);
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
const store = memStore();
|
|
189
|
+
const manifest = new InMemoryIngestManifest();
|
|
190
|
+
const source = memSource(files());
|
|
191
|
+
const report = await reviewDirectory(args(source, store, manifest, { judgement: judge, packs: [quietPack], concurrency: 1, judgeConcurrency: 1 }));
|
|
192
|
+
expect(calls.length).toBe(5);
|
|
193
|
+
expect(report.judgeStopped).toMatch(/5 model calls failed in a row/);
|
|
194
|
+
expect(report.judged).toBe(0);
|
|
195
|
+
expect((await stateOf(manifest)).owed).toEqual(Object.keys(files()));
|
|
196
|
+
|
|
197
|
+
fail = false;
|
|
198
|
+
calls.length = 0;
|
|
199
|
+
const next = await reviewDirectory(args(source, store, manifest, { judgement: judge, packs: [quietPack] }));
|
|
200
|
+
expect(next.judged).toBe(N);
|
|
201
|
+
expect((await stateOf(manifest)).owed).toEqual([]);
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
describe('judge priority and the slowest steps', () => {
|
|
206
|
+
it('orders entry points, then inbound references (most first), then recent, then the rest, ties by path', () => {
|
|
207
|
+
const paths = ['z.md', 'b.md', 'a.md', 'recent.md', 'hub.md', 'README.md', 'few.md'];
|
|
208
|
+
const order = orderForJudging(paths, {
|
|
209
|
+
entry: (p) => p === 'README.md',
|
|
210
|
+
inbound: new Map([['hub.md', 9], ['few.md', 2]]),
|
|
211
|
+
recent: new Set(['recent.md']),
|
|
212
|
+
});
|
|
213
|
+
expect(order).toEqual(['README.md', 'hub.md', 'few.md', 'recent.md', 'a.md', 'b.md', 'z.md']);
|
|
214
|
+
expect(paths[0]).toBe('z.md');
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
it('slowestSteps lists the longest steps first with their reasons', () => {
|
|
218
|
+
let run = startRun({ id: 'r', root: ROOT, kind: 'review', at: 0 });
|
|
219
|
+
for (const [path, ms, reason] of [['a', 5, undefined], ['b', 9000, 'timeout'], ['c', 300, undefined]] as const) {
|
|
220
|
+
run = applyRunEvent(run, { type: 'step', step: { path, phase: 'extract', ms, outcome: reason ? 'failed' : 'ok', ...(reason ? { reason } : {}) } }, 1);
|
|
221
|
+
}
|
|
222
|
+
expect(slowestSteps(run, 2).map((s) => [s.path, s.reason])).toEqual([['b', 'timeout'], ['c', undefined]]);
|
|
223
|
+
});
|
|
224
|
+
});
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
import { hashText } from '../ingest/hash.js';
|
|
20
20
|
import { SECTION_INDEX_BADGE } from '../ingest/docsExtract.js';
|
|
21
21
|
import { budgetLeft, type JudgeBudget, type JudgedBatch, type SectionToJudge } from './judge.js';
|
|
22
|
-
import { applyAnswers, callSections, type SectionAnswer } from './judgeCalls.js';
|
|
22
|
+
import { applyAnswers, callSections, type JudgeBreaker, type SectionAnswer } from './judgeCalls.js';
|
|
23
23
|
import type { FileExtraction } from './extractFile.js';
|
|
24
24
|
import type { KnowledgePack, NodeRef, ReviewArgs, ReviewReport, StoredFact } from './model.js';
|
|
25
25
|
import type { ModelLimiter } from './modelLimiter.js';
|
|
@@ -55,23 +55,34 @@ export interface JudgeDispatch {
|
|
|
55
55
|
judgedPrior: ReadonlyMap<string, string>;
|
|
56
56
|
lanes: Lanes;
|
|
57
57
|
limiter: ModelLimiter;
|
|
58
|
+
/** Stops judging for the run after consecutive provider failures. */
|
|
59
|
+
breaker?: JudgeBreaker;
|
|
58
60
|
}
|
|
59
61
|
|
|
60
|
-
/**
|
|
61
|
-
export function
|
|
62
|
+
/** The sections of a file the model has to judge (changed text) and those whose judgement is still current. */
|
|
63
|
+
export function splitSections(
|
|
64
|
+
judgedPrior: ReadonlyMap<string, string>, extraction: FileExtraction,
|
|
65
|
+
): { reuse: NodeRef[]; toJudge: SectionToJudge[] } {
|
|
62
66
|
const { extracted: ex, sections, pack } = extraction;
|
|
63
|
-
const
|
|
64
|
-
if (!port || !judgesPack(port, pack)) return undefined;
|
|
65
|
-
const kinds = new Set(pack.judgement!.nodeKinds);
|
|
67
|
+
const kinds = new Set(pack.judgement?.nodeKinds ?? []);
|
|
66
68
|
const reuse: NodeRef[] = [];
|
|
67
69
|
const toJudge: SectionToJudge[] = [];
|
|
68
70
|
for (const node of ex.nodes) {
|
|
69
71
|
const index = node.badges?.[SECTION_INDEX_BADGE];
|
|
70
72
|
const text = typeof index === 'number' ? sections[index]?.text : undefined;
|
|
71
73
|
if (!kinds.has(node.kind) || !text) continue;
|
|
72
|
-
if (
|
|
74
|
+
if (judgedPrior.get(node.ref) === hashText(text)) reuse.push(node.ref);
|
|
73
75
|
else toJudge.push({ ref: node.ref, text });
|
|
74
76
|
}
|
|
77
|
+
return { reuse, toJudge };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Starts judging a file's changed sections; undefined when its pack asks for no judgement (or there is no port). */
|
|
81
|
+
export function startJudge(d: JudgeDispatch, f: { path: string; hash: string }, extraction: FileExtraction): JudgeJob | undefined {
|
|
82
|
+
const { pack } = extraction;
|
|
83
|
+
const port = d.port;
|
|
84
|
+
if (!port || !judgesPack(port, pack)) return undefined;
|
|
85
|
+
const { reuse, toJudge } = splitSections(d.judgedPrior, extraction);
|
|
75
86
|
// Reserved now, in plan order: this file's calls come out of the shared budget before any later file's.
|
|
76
87
|
const allot = budgetLeft(d.budget) ? Math.min(toJudge.length, Math.max(0, d.budget.modelCalls - d.budget.used)) : 0;
|
|
77
88
|
d.budget.used += allot;
|
|
@@ -81,7 +92,7 @@ export function startJudge(d: JudgeDispatch, f: { path: string; hash: string },
|
|
|
81
92
|
const lane = d.lanes.take();
|
|
82
93
|
const t0 = Date.now();
|
|
83
94
|
try {
|
|
84
|
-
const r = await callSections({ port, fileHash: f.hash, sections: toJudge, budget: slice, limiter: d.limiter, signal: d.signal });
|
|
95
|
+
const r = await callSections({ port, fileHash: f.hash, sections: toJudge, budget: slice, limiter: d.limiter, signal: d.signal, ...(d.breaker ? { breaker: d.breaker } : {}) });
|
|
85
96
|
// Every call that was made failed: the provider is refusing us (key, quota, network), not the file.
|
|
86
97
|
if (r.answers.length === 0 && r.errors > 0) {
|
|
87
98
|
return { status: 'error', reason: `judge: ${r.firstError ?? 'model call failed'}`, ms: Date.now() - t0, lane };
|
|
@@ -15,7 +15,8 @@ export interface DirectorySource {
|
|
|
15
15
|
rootId: string;
|
|
16
16
|
title: string;
|
|
17
17
|
list(): AsyncIterable<{ path: string; hash: string; size: number }>;
|
|
18
|
-
read(
|
|
18
|
+
/** `signal` aborts the read when the review gives up on it (a per-job timeout, a stop); a source that cannot cancel may ignore it. */
|
|
19
|
+
read(path: string, signal?: AbortSignal): Promise<SourceDocument>;
|
|
19
20
|
watch?(cb: (paths: string[]) => void): () => void;
|
|
20
21
|
}
|
|
21
22
|
|
|
@@ -29,6 +30,8 @@ export interface ReviewPlan {
|
|
|
29
30
|
skipped: Array<{ path: string; reason: 'ignored' | 'binary' | 'too-large' | 'no-pack' }>;
|
|
30
31
|
/** ≈ judgement calls for changed files (sections of judged kinds). */
|
|
31
32
|
estimatedModelCalls: number;
|
|
33
|
+
/** The file budget of the judge pass this run will run after the map is complete (PRD 41 A10); set by the host, so the confirm chip states it. */
|
|
34
|
+
judgeFiles?: number;
|
|
32
35
|
}
|
|
33
36
|
|
|
34
37
|
export interface ReviewProgress {
|
|
@@ -59,6 +62,17 @@ export interface ReviewReport {
|
|
|
59
62
|
extractErrors: number;
|
|
60
63
|
/** Every file this run could not finish (read, extract, judge), with why. */
|
|
61
64
|
failures: ReviewFailure[];
|
|
65
|
+
/**
|
|
66
|
+
* Files still owed model judgement after this run (PRD 41 A10): in a `mechanical` run every file of a judged pack
|
|
67
|
+
* with a section to judge; otherwise the files a budget cut or a failed call left. Plan order.
|
|
68
|
+
*/
|
|
69
|
+
awaitingJudge: string[];
|
|
70
|
+
/** How many files are awaiting judgement: the ONLY form that leaves memory — hosts persist and send this, never the path list. */
|
|
71
|
+
awaitingJudgeCount?: number;
|
|
72
|
+
/** Pass 2 (`only`): files of the slice judged to completion. */
|
|
73
|
+
judgedFiles?: number;
|
|
74
|
+
/** Judging was stopped for this run after consecutive provider failures (A10 rule 9); the files stay owed. */
|
|
75
|
+
judgeStopped?: string;
|
|
62
76
|
aborted: boolean;
|
|
63
77
|
durationMs: number;
|
|
64
78
|
}
|
|
@@ -105,6 +119,23 @@ export interface ReviewArgs {
|
|
|
105
119
|
* A result without the file's exact `sourceRef` fails that file's extraction (prior knowledge kept).
|
|
106
120
|
*/
|
|
107
121
|
extractPool?: ExtractPool;
|
|
122
|
+
/**
|
|
123
|
+
* Pass 1 of a two-pass review (PRD 41 A10): read, extract, write — no model call. A file whose pack asks for
|
|
124
|
+
* judgement and has sections to judge stays OWED (manifest hash unchanged) and is listed in `report.awaitingJudge`;
|
|
125
|
+
* the map is complete without it. A later run without `mechanical` (pass 2) judges it.
|
|
126
|
+
*/
|
|
127
|
+
mechanical?: boolean;
|
|
128
|
+
/** Restrict the run to these changed paths (pass 2: the prioritized, budgeted slice). Other changed files are untouched and stay owed. */
|
|
129
|
+
only?: readonly string[];
|
|
130
|
+
/**
|
|
131
|
+
* With an `extractPool`: the pool reads each file itself (PRD 41 A10 rule 8) — the job carries the path and the planned hash,
|
|
132
|
+
* the main thread neither reads nor copies the text, and a binary file comes back as `binary`. The pool must support `readByPool` jobs.
|
|
133
|
+
*/
|
|
134
|
+
deferRead?: boolean;
|
|
135
|
+
/** Files read and extracted ahead of the writer (default: the pool's width times 4, 32..64, with a pool; else `concurrency`). Wider than the pool, so workers never wait for the writer. */
|
|
136
|
+
readAhead?: number;
|
|
137
|
+
/** Per-job ceilings in ms for the extract path (PRD 41 A10): reads 5000, extract (pool dispatch included) 10000. A job over its ceiling is a failed step with reason `timeout`. */
|
|
138
|
+
timeouts?: { readMs?: number; extractMs?: number };
|
|
108
139
|
/** One event per file per phase, as it happens (PRD 41 A8). */
|
|
109
140
|
onStep?(step: ReviewStep): void;
|
|
110
141
|
onProgress?(p: ReviewProgress): void;
|