@seanhogg/builderforce-memory 2026.10.45 → 2026.10.47
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/README.md +21 -0
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +13 -7
- 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 +25 -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/index.d.ts +5 -3
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +2 -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/pack/crc32.d.ts +7 -0
- package/dist/knowledge/pack/crc32.d.ts.map +1 -0
- package/dist/knowledge/pack/crc32.js +22 -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 +66 -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 +26 -0
- package/dist/knowledge/pack/encode.d.ts.map +1 -0
- package/dist/knowledge/pack/encode.js +86 -0
- package/dist/knowledge/pack/encode.js.map +1 -0
- package/dist/knowledge/pack/extrDiff.d.ts +26 -0
- package/dist/knowledge/pack/extrDiff.d.ts.map +1 -0
- package/dist/knowledge/pack/extrDiff.js +129 -0
- package/dist/knowledge/pack/extrDiff.js.map +1 -0
- package/dist/knowledge/pack/frame.d.ts +45 -0
- package/dist/knowledge/pack/frame.d.ts.map +1 -0
- package/dist/knowledge/pack/frame.js +101 -0
- package/dist/knowledge/pack/frame.js.map +1 -0
- package/dist/knowledge/pack/hex.d.ts +7 -0
- package/dist/knowledge/pack/hex.d.ts.map +1 -0
- package/dist/knowledge/pack/hex.js +17 -0
- package/dist/knowledge/pack/hex.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 +200 -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 +172 -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 +227 -0
- package/dist/knowledge/pack/sections/rows.js.map +1 -0
- package/dist/knowledge/pack/strings.d.ts +43 -0
- package/dist/knowledge/pack/strings.d.ts.map +1 -0
- package/dist/knowledge/pack/strings.js +117 -0
- package/dist/knowledge/pack/strings.js.map +1 -0
- package/dist/knowledge/pack/types.d.ts +118 -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 +57 -0
- package/dist/knowledge/pack/varint.d.ts.map +1 -0
- package/dist/knowledge/pack/varint.js +145 -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 +41 -1
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts +10 -2
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +60 -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/package.json +8 -3
- package/src/contract/dist.contract.test.ts +44 -0
- package/src/contract/exports.contract.test.ts +90 -0
- package/src/contract/exports.snapshot.json +605 -0
- package/src/contract/pack.contract.test.ts +31 -0
- package/src/contract/regression.review.test.ts +236 -0
- package/src/contract/regression.store.test.ts +84 -0
- package/src/contract/types.contract.test.ts +183 -0
- package/src/knowledge/build.ts +11 -5
- package/src/knowledge/extractFile.ts +28 -6
- package/src/knowledge/extractJob.ts +26 -7
- package/src/knowledge/index.ts +5 -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/pack/crc32.ts +21 -0
- package/src/knowledge/pack/decode.ts +60 -0
- package/src/knowledge/pack/deflate.ts +43 -0
- package/src/knowledge/pack/encode.ts +89 -0
- package/src/knowledge/pack/extrDiff.ts +116 -0
- package/src/knowledge/pack/frame.ts +94 -0
- package/src/knowledge/pack/hex.ts +17 -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 +109 -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 +151 -0
- package/src/knowledge/pack/sections/facts.ts +126 -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 +126 -0
- package/src/knowledge/pack/types.ts +97 -0
- package/src/knowledge/pack/varint.ts +145 -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 +38 -1
- package/src/knowledge/reviewPrefetch.ts +60 -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 +12 -0
- package/src/knowledge/testkit.test-util.ts +13 -2
|
@@ -12,7 +12,10 @@
|
|
|
12
12
|
import type { SourceDocument } from '../ingest/types.js';
|
|
13
13
|
import type { KnowledgePack, KnowledgeStore, NodeRef, ReviewArgs } from './model.js';
|
|
14
14
|
import { extractFileDetailed, type FileExtraction } from './extractFile.js';
|
|
15
|
+
import { BinaryContent } from './extractJob.js';
|
|
15
16
|
import { judgesPack } from './reviewJudge.js';
|
|
17
|
+
import { createDeadlines } from './jobDeadline.js';
|
|
18
|
+
import { createModelLimiter } from './modelLimiter.js';
|
|
16
19
|
import { Lanes, reasonOf, type ReviewStep } from './reviewRunModel.js';
|
|
17
20
|
import { isBinaryText, type ComposedPacks } from './sources.js';
|
|
18
21
|
|
|
@@ -21,9 +24,9 @@ export type Prefetch = (
|
|
|
21
24
|
| { kind: 'read-error'; reason: string }
|
|
22
25
|
| { kind: 'binary' }
|
|
23
26
|
| { kind: 'none' }
|
|
24
|
-
| { kind: 'extracted'; doc
|
|
27
|
+
| { kind: 'extracted'; doc?: SourceDocument; extraction: FileExtraction }
|
|
25
28
|
| { kind: 'failed'; reason: string }
|
|
26
|
-
) & { ms: number; lane: number };
|
|
29
|
+
) & { ms: number; lane: number; parts?: NonNullable<ReviewStep['parts']> };
|
|
27
30
|
|
|
28
31
|
export interface PrefetchContext {
|
|
29
32
|
args: ReviewArgs;
|
|
@@ -34,8 +37,10 @@ export interface PrefetchContext {
|
|
|
34
37
|
store: KnowledgeStore;
|
|
35
38
|
composed: ComposedPacks;
|
|
36
39
|
knownKeys: ReadonlyMap<string, NodeRef>;
|
|
37
|
-
/** Lanes = the read-ahead width. */
|
|
40
|
+
/** Lanes = the read-ahead width: files read and extracted ahead of the writer. */
|
|
38
41
|
width: number;
|
|
42
|
+
/** Files in the extract stage at once (the pool's width); default `width`. */
|
|
43
|
+
extractWidth?: number;
|
|
39
44
|
}
|
|
40
45
|
|
|
41
46
|
/** A {@link Prefetch} before its timing is stamped. */
|
|
@@ -43,7 +48,7 @@ type Outcome = Prefetch extends infer P ? (P extends unknown ? Omit<P, 'ms' | 'l
|
|
|
43
48
|
|
|
44
49
|
/** The extract step event of a settled job. */
|
|
45
50
|
export function extractStepOf(path: string, job: Prefetch): ReviewStep {
|
|
46
|
-
const base = { path, phase: 'extract' as const, ms: job.ms, lane: job.lane };
|
|
51
|
+
const base = { path, phase: 'extract' as const, ms: job.ms, lane: job.lane, ...(job.parts && Object.keys(job.parts).length > 0 ? { parts: job.parts } : {}) };
|
|
47
52
|
switch (job.kind) {
|
|
48
53
|
case 'read-error': return { ...base, outcome: 'failed', reason: `read: ${job.reason}` };
|
|
49
54
|
case 'failed': return { ...base, outcome: 'failed', reason: job.reason };
|
|
@@ -53,34 +58,65 @@ export function extractStepOf(path: string, job: Prefetch): ReviewStep {
|
|
|
53
58
|
}
|
|
54
59
|
}
|
|
55
60
|
|
|
61
|
+
/** The failure reason of a file whose bytes no longer match the planned hash. */
|
|
62
|
+
export const CHANGED_SINCE_PLAN = 'changed since plan';
|
|
63
|
+
|
|
64
|
+
/** Per-job ceilings of the extract path (PRD 41 A10 rule 2). */
|
|
65
|
+
export const DEFAULT_READ_TIMEOUT_MS = 5_000;
|
|
66
|
+
export const DEFAULT_EXTRACT_TIMEOUT_MS = 10_000;
|
|
67
|
+
|
|
56
68
|
export function createPrefetch(c: PrefetchContext): (f: { path: string; hash: string }) => Promise<Prefetch> {
|
|
57
|
-
|
|
58
|
-
|
|
69
|
+
// A lane is a worker: taken while the file holds an extract slot. The extract stage holds at most `extractWidth` at once, so the
|
|
70
|
+
// extract deadline counts from the moment a job holds a slot, never from its wait in line (the limiter is used as a plain semaphore).
|
|
71
|
+
const lanes = new Lanes(c.extractWidth ?? c.width);
|
|
72
|
+
const extractSlots = createModelLimiter(c.extractWidth ?? c.width);
|
|
73
|
+
const withDeadline = createDeadlines(c.signal);
|
|
74
|
+
const readMs = c.args.timeouts?.readMs ?? DEFAULT_READ_TIMEOUT_MS;
|
|
75
|
+
const extractMs = c.args.timeouts?.extractMs ?? DEFAULT_EXTRACT_TIMEOUT_MS;
|
|
76
|
+
// Judging is a later pass in a mechanical review: no sections are wanted from the pool.
|
|
77
|
+
const wantsSections = (pack: KnowledgePack) => !c.args.mechanical && judgesPack(c.args.judgement, pack);
|
|
78
|
+
const byPool = !!c.args.extractPool && !!c.args.deferRead;
|
|
59
79
|
|
|
60
|
-
const run = async (f: { path: string; hash: string }): Promise<Outcome> => {
|
|
61
|
-
let doc: SourceDocument;
|
|
62
|
-
|
|
80
|
+
const run = async (f: { path: string; hash: string }, parts: NonNullable<ReviewStep['parts']>, held: { lane: number }): Promise<Outcome> => {
|
|
81
|
+
let doc: SourceDocument | undefined;
|
|
82
|
+
const t0 = Date.now();
|
|
83
|
+
if (!byPool) {
|
|
84
|
+
try { doc = await withDeadline(readMs, (signal) => c.args.source.read(f.path, signal)); } catch (error) {
|
|
85
|
+
return { kind: 'read-error', reason: reasonOf(error) };
|
|
86
|
+
}
|
|
87
|
+
parts.readMs = Date.now() - t0;
|
|
88
|
+
}
|
|
63
89
|
try {
|
|
64
|
-
if (doc.content.kind === 'text' && isBinaryText(doc.content.text)) return { kind: 'binary' };
|
|
65
|
-
const extraction = await
|
|
66
|
-
|
|
90
|
+
if (doc && doc.content.kind === 'text' && isBinaryText(doc.content.text)) return { kind: 'binary' };
|
|
91
|
+
const extraction = await extractSlots.run(async () => {
|
|
92
|
+
held.lane = lanes.take();
|
|
93
|
+
try { return await withDeadline(extractMs, (signal) => extractFileDetailed({
|
|
94
|
+
rootId: c.rootId, path: f.path, hash: f.hash, ...(doc ? { doc } : {}), packs: c.packs, store: c.store, composed: c.composed,
|
|
67
95
|
knownKeys: c.knownKeys, writeCache: false,
|
|
68
|
-
|
|
96
|
+
onTiming: (t) => { parts.lookupMs = t.lookupMs; parts.poolMs = t.poolMs; },
|
|
97
|
+
...(c.args.extractPool ? { pool: c.args.extractPool, signal, wantsSections, ...(byPool ? { readByPool: true } : {}) } : {}),
|
|
98
|
+
})); } finally { lanes.free(held.lane); }
|
|
69
99
|
});
|
|
70
|
-
|
|
71
|
-
|
|
100
|
+
if (!extraction) return { kind: 'none' };
|
|
101
|
+
// Binary and no-pack files are decided above and never hash-checked (as in the host worker). For a file that WILL be
|
|
102
|
+
// stored, the bytes read must be the bytes planned: hashed once, from the text already in hand. The review writes the
|
|
103
|
+
// extract cache only for an 'extracted' job, so nothing is stored under the stale hash.
|
|
104
|
+
const hashOf = c.args.source.hashOf;
|
|
105
|
+
if (hashOf && doc && doc.content.kind === 'text' && hashOf(doc.content.text) !== f.hash) return { kind: 'failed', reason: CHANGED_SINCE_PLAN };
|
|
106
|
+
return { kind: 'extracted', ...(doc ? { doc } : {}), extraction };
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (error instanceof BinaryContent) return { kind: 'binary' };
|
|
109
|
+
return { kind: 'failed', reason: reasonOf(error) };
|
|
110
|
+
}
|
|
72
111
|
};
|
|
73
112
|
|
|
74
113
|
return async (f) => {
|
|
75
|
-
const lane = lanes.take();
|
|
76
114
|
const t0 = Date.now();
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
lanes.free(lane);
|
|
84
|
-
}
|
|
115
|
+
const parts: NonNullable<ReviewStep['parts']> = {};
|
|
116
|
+
const held = { lane: 0 };
|
|
117
|
+
const out = await run(f, parts, held);
|
|
118
|
+
const job = { ...out, ms: Date.now() - t0, lane: held.lane, parts } as Prefetch;
|
|
119
|
+
c.args.onStep?.(extractStepOf(f.path, job));
|
|
120
|
+
return job;
|
|
85
121
|
};
|
|
86
122
|
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* The pure run recorder (PRD 41 A8): phases, lanes, the step ring, failures, rate and ETA.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import { applyRunEvent, REVIEW_RUN_STEP_RING, runEta, runRate, startRun, type ReviewRunEvent } from './reviewRun.js';
|
|
6
|
+
import { applyRunEvent, failuresOf, failureTotal, REVIEW_RUN_FAILURE_CHUNK, REVIEW_RUN_STEP_RING, runEta, runRate, startRun, type ReviewRunEvent } from './reviewRun.js';
|
|
7
7
|
import type { ReviewStep } from './reviewRunModel.js';
|
|
8
8
|
|
|
9
9
|
const step = (i: number, extra: Partial<ReviewStep> = {}): ReviewStep => ({ path: `f${i}.md`, phase: 'extract', ms: 10, outcome: 'ok', lane: i % 2, ...extra });
|
|
@@ -40,8 +40,25 @@ describe('reviewRun reducer', () => {
|
|
|
40
40
|
expect(run.steps).toHaveLength(REVIEW_RUN_STEP_RING);
|
|
41
41
|
expect(run.steps[0]!.path).toBe('f50.md');
|
|
42
42
|
expect(run.steps.at(-1)!.path).toBe('f249.md');
|
|
43
|
-
expect(run.
|
|
44
|
-
expect(run
|
|
43
|
+
expect(failuresOf(run).map((f) => f.reason)).toEqual(['boom 0', 'boom 50', 'boom 100', 'boom 150', 'boom 200']);
|
|
44
|
+
expect(failuresOf(run)[0]).toEqual({ path: 'f0.md', phase: 'extract', reason: 'boom 0' });
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('keeps failures in chunks: an append copies the last chunk and the chunk list, never every failure, and the input run is untouched', () => {
|
|
48
|
+
let run = run0();
|
|
49
|
+
const N = 20_000;
|
|
50
|
+
const t0 = Date.now();
|
|
51
|
+
for (let i = 0; i < N; i++) {
|
|
52
|
+
const before = run.failures;
|
|
53
|
+
const sizes = before.map((c) => c.length);
|
|
54
|
+
run = applyRunEvent(run, { type: 'step', step: step(i, { outcome: 'failed', reason: 'timeout' }) }, 2000 + i);
|
|
55
|
+
if (i % 5000 === 0) expect(before.map((c) => c.length)).toEqual(sizes); // the previous run's chunks did not grow
|
|
56
|
+
}
|
|
57
|
+
expect(failureTotal(run)).toBe(N);
|
|
58
|
+
expect(run.failures.every((c) => c.length <= REVIEW_RUN_FAILURE_CHUNK)).toBe(true);
|
|
59
|
+
expect(run.failures).toHaveLength(Math.ceil(N / REVIEW_RUN_FAILURE_CHUNK));
|
|
60
|
+
expect(failuresOf(run).map((f) => f.path)[N - 1]).toBe(`f${N - 1}.md`);
|
|
61
|
+
expect(Date.now() - t0).toBeLessThan(5_000); // linear: 20,000 whole-array copies would take far longer
|
|
45
62
|
});
|
|
46
63
|
|
|
47
64
|
it('keeps an ended phase ended on a stale event, and reopens it only when the total grows', () => {
|
|
@@ -16,6 +16,11 @@ export type ReviewRunOutcome = 'done' | 'stopped' | 'failed';
|
|
|
16
16
|
/** How many of the latest steps a run keeps (failures are kept whole). */
|
|
17
17
|
export const REVIEW_RUN_STEP_RING = 200;
|
|
18
18
|
|
|
19
|
+
/** Failures are kept in chunks of at most this many, so appending copies one chunk and the outer list, never every failure. */
|
|
20
|
+
export const REVIEW_RUN_FAILURE_CHUNK = 256;
|
|
21
|
+
|
|
22
|
+
export type ReviewFailureChunks = readonly (readonly ReviewFailure[])[];
|
|
23
|
+
|
|
19
24
|
export interface ReviewRunPhase {
|
|
20
25
|
phase: ReviewPhase;
|
|
21
26
|
startedAt: number;
|
|
@@ -46,7 +51,8 @@ export interface ReviewRun {
|
|
|
46
51
|
lanes: ReviewRunLane[];
|
|
47
52
|
/** The last {@link REVIEW_RUN_STEP_RING} steps, oldest first. */
|
|
48
53
|
steps: ReviewStep[];
|
|
49
|
-
|
|
54
|
+
/** Every failure, in chunks (see {@link REVIEW_RUN_FAILURE_CHUNK}); read it through {@link failuresOf}. */
|
|
55
|
+
failures: ReviewFailureChunks;
|
|
50
56
|
outcome?: ReviewRunOutcome;
|
|
51
57
|
report?: ReviewReport;
|
|
52
58
|
}
|
|
@@ -76,7 +82,7 @@ function withProgress(phases: ReviewRunPhase[], p: ReviewProgress, at: number):
|
|
|
76
82
|
return phases.map((x, j) => (j === i ? next : x));
|
|
77
83
|
}
|
|
78
84
|
|
|
79
|
-
const PHASE_ORDER: readonly ReviewPhase[] = ['plan', 'extract', 'resolve', 'judge', 'compare', 'write', 'index', 'done'];
|
|
85
|
+
const PHASE_ORDER: readonly ReviewPhase[] = ['plan', 'extract', 'resolve', 'judge', 'compare', 'write', 'index', 'mapped', 'done'];
|
|
80
86
|
|
|
81
87
|
/** Lanes are keyed by phase and id: extract workers and judge lanes are different workers. */
|
|
82
88
|
function withLane(lanes: ReviewRunLane[], step: ReviewStep): ReviewRunLane[] {
|
|
@@ -90,6 +96,19 @@ function withLane(lanes: ReviewRunLane[], step: ReviewStep): ReviewRunLane[] {
|
|
|
90
96
|
.sort((a, b) => PHASE_ORDER.indexOf(a.phase) - PHASE_ORDER.indexOf(b.phase) || a.id - b.id);
|
|
91
97
|
}
|
|
92
98
|
|
|
99
|
+
/** The chunks with `f` appended: copies the last chunk and the outer list only (linear over a run of thousands of failures). */
|
|
100
|
+
function withFailure(chunks: ReviewFailureChunks, f: ReviewFailure): ReviewFailureChunks {
|
|
101
|
+
const last = chunks[chunks.length - 1];
|
|
102
|
+
if (last && last.length < REVIEW_RUN_FAILURE_CHUNK) return [...chunks.slice(0, -1), [...last, f]];
|
|
103
|
+
return [...chunks, [f]];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Every failure of the run, oldest first (for readers; the run keeps them in chunks). */
|
|
107
|
+
export const failuresOf = (run: Pick<ReviewRun, 'failures'>): ReviewFailure[] => run.failures.flat();
|
|
108
|
+
|
|
109
|
+
/** How many failures the run holds. */
|
|
110
|
+
export const failureTotal = (run: Pick<ReviewRun, 'failures'>): number => run.failures.reduce((n, c) => n + c.length, 0);
|
|
111
|
+
|
|
93
112
|
/** Folds one event into the run; the input run is never mutated. */
|
|
94
113
|
export function applyRunEvent(run: ReviewRun, event: ReviewRunEvent, at: number): ReviewRun {
|
|
95
114
|
const base = { ...run, updatedAt: at };
|
|
@@ -105,7 +124,7 @@ export function applyRunEvent(run: ReviewRun, event: ReviewRunEvent, at: number)
|
|
|
105
124
|
...base,
|
|
106
125
|
lanes: withLane(run.lanes, s),
|
|
107
126
|
steps: [...run.steps, s].slice(-REVIEW_RUN_STEP_RING),
|
|
108
|
-
failures: s.outcome === 'failed' ?
|
|
127
|
+
failures: s.outcome === 'failed' ? withFailure(run.failures, { path: s.path, phase: s.phase, reason: s.reason ?? 'failed' }) : run.failures,
|
|
109
128
|
};
|
|
110
129
|
}
|
|
111
130
|
case 'end':
|
|
@@ -116,10 +135,13 @@ export function applyRunEvent(run: ReviewRun, event: ReviewRunEvent, at: number)
|
|
|
116
135
|
}
|
|
117
136
|
}
|
|
118
137
|
|
|
119
|
-
|
|
138
|
+
/** What the rate and the ETA read of a run (a restated run record qualifies too). */
|
|
139
|
+
export type RunClock = Pick<ReviewRun, 'phases' | 'endedAt' | 'updatedAt'>;
|
|
140
|
+
|
|
141
|
+
const phaseOf = (run: RunClock, phase: ReviewPhase): ReviewRunPhase | undefined => run.phases.find((p) => p.phase === phase);
|
|
120
142
|
|
|
121
143
|
/** Items per second a phase has sustained so far; 0 when it has not started or no time has passed. */
|
|
122
|
-
export function runRate(run:
|
|
144
|
+
export function runRate(run: RunClock, phase: ReviewPhase): number {
|
|
123
145
|
const p = phaseOf(run, phase);
|
|
124
146
|
if (!p) return 0;
|
|
125
147
|
const ms = (p.endedAt ?? run.endedAt ?? run.updatedAt) - p.startedAt;
|
|
@@ -127,7 +149,7 @@ export function runRate(run: ReviewRun, phase: ReviewPhase): number {
|
|
|
127
149
|
}
|
|
128
150
|
|
|
129
151
|
/** Milliseconds until a phase finishes at its measured rate; 0 when it is complete, undefined when it cannot be told. */
|
|
130
|
-
export function runEta(run:
|
|
152
|
+
export function runEta(run: RunClock, phase: ReviewPhase): number | undefined {
|
|
131
153
|
const p = phaseOf(run, phase);
|
|
132
154
|
if (!p) return undefined;
|
|
133
155
|
const remaining = p.total - p.done;
|
|
@@ -135,3 +157,8 @@ export function runEta(run: ReviewRun, phase: ReviewPhase): number | undefined {
|
|
|
135
157
|
const rate = runRate(run, phase);
|
|
136
158
|
return rate > 0 ? Math.round((remaining / rate) * 1000) : undefined;
|
|
137
159
|
}
|
|
160
|
+
|
|
161
|
+
/** The `n` slowest steps of the run's ring, longest first (ties by path), each with its reason: a stall names itself. */
|
|
162
|
+
export function slowestSteps(run: Pick<ReviewRun, 'steps'>, n: number): ReviewStep[] {
|
|
163
|
+
return [...run.steps].sort((a, b) => b.ms - a.ms || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)).slice(0, Math.max(0, n));
|
|
164
|
+
}
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
* per-file step events a review emits, and the failures it records instead of throwing.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
/** `mapped` (PRD 41 A10): the mechanical pass is over and the map is complete; judging, if any is owed, follows. */
|
|
7
|
+
export type ReviewPhase = 'plan' | 'extract' | 'resolve' | 'judge' | 'compare' | 'write' | 'index' | 'mapped' | 'done';
|
|
7
8
|
|
|
8
9
|
export type ReviewStepOutcome = 'ok' | 'cached' | 'skipped' | 'failed';
|
|
9
10
|
|
|
@@ -18,6 +19,8 @@ export interface ReviewStep {
|
|
|
18
19
|
outcome: ReviewStepOutcome;
|
|
19
20
|
reason?: string;
|
|
20
21
|
lane?: number;
|
|
22
|
+
/** Where an extract step's time went (PRD 41 A10), so a stall names itself: the file read, the cache lookup, the pool job. */
|
|
23
|
+
parts?: { readMs?: number; lookupMs?: number; poolMs?: number };
|
|
21
24
|
}
|
|
22
25
|
|
|
23
26
|
/** A file a review could not finish: its prior knowledge and manifest hash are kept, so the next review retries it. */
|
|
@@ -23,7 +23,9 @@ function counting(): Counting {
|
|
|
23
23
|
return p;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
const
|
|
26
|
+
const settle = (): Promise<void> => new Promise((r) => setTimeout(r, 0));
|
|
27
|
+
|
|
28
|
+
const SCOPE ={ rootId: 'r', title: 'R', packs: ['docs'] };
|
|
27
29
|
|
|
28
30
|
function setup(checkpointMs = 30_000) {
|
|
29
31
|
const persistence = counting();
|
|
@@ -70,9 +72,11 @@ describe('LocalSnapshotStore.batched', () => {
|
|
|
70
72
|
expect(persistence.writes).toBe(0);
|
|
71
73
|
clock.ms = 1000;
|
|
72
74
|
await store.putExtracted('c', []);
|
|
75
|
+
await settle(); // the checkpoint runs in the background (PRD 41 A10)
|
|
73
76
|
expect(persistence.writes).toBe(1);
|
|
74
77
|
clock.ms = 1500;
|
|
75
78
|
await store.putExtracted('d', []);
|
|
79
|
+
await settle();
|
|
76
80
|
expect(persistence.writes).toBe(1);
|
|
77
81
|
expect(Object.keys(JSON.parse(persistence.value!).extracted)).toEqual(['a', 'b', 'c']);
|
|
78
82
|
});
|
|
@@ -123,18 +127,36 @@ describe('LocalSnapshotStore.batched', () => {
|
|
|
123
127
|
})).rejects.toThrow('disk full');
|
|
124
128
|
});
|
|
125
129
|
|
|
126
|
-
it('a failed checkpoint
|
|
130
|
+
it('a failed background checkpoint does not fail the mutation: the batch end writes what it held', async () => {
|
|
127
131
|
const { persistence, clock, store } = setup(1000);
|
|
128
132
|
await store.batched(async () => {
|
|
129
133
|
await store.putExtracted('a', []);
|
|
130
134
|
persistence.failWrites = true;
|
|
131
135
|
clock.ms = 2000;
|
|
132
|
-
await
|
|
136
|
+
await store.putExtracted('b', []);
|
|
137
|
+
await settle();
|
|
133
138
|
persistence.failWrites = false;
|
|
134
139
|
});
|
|
135
140
|
expect(JSON.parse(persistence.value!).extracted).toHaveProperty('b');
|
|
136
141
|
});
|
|
137
142
|
|
|
143
|
+
it('reads do not wait for a checkpoint write (a large snapshot must not stall getExtracted)', async () => {
|
|
144
|
+
const { persistence, clock, store } = setup(1000);
|
|
145
|
+
let release!: () => void;
|
|
146
|
+
const gate = new Promise<void>((r) => { release = r; });
|
|
147
|
+
const write = persistence.write;
|
|
148
|
+
persistence.write = async (s) => { await gate; await write(s); };
|
|
149
|
+
await store.batched(async () => {
|
|
150
|
+
await store.putExtracted('a', []);
|
|
151
|
+
clock.ms = 5000;
|
|
152
|
+
await store.putExtracted('b', []); // starts a checkpoint that stays in flight
|
|
153
|
+
expect(await store.getExtracted('a')).toEqual([]);
|
|
154
|
+
await store.putExtracted('c', []); // and mutations still apply in memory
|
|
155
|
+
expect(await store.getExtracted('c')).toEqual([]);
|
|
156
|
+
release();
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
|
|
138
160
|
it('nested and overlapping batches flush once, at the outermost end', async () => {
|
|
139
161
|
const { persistence, store } = setup();
|
|
140
162
|
await store.batched(async () => {
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/stores/localSnapshotStore.extractedLog.test.ts
|
|
3
|
+
* PRD 41 A10 rules 6-7: the extract cache lives in an append-only log, reads never wait on a pending
|
|
4
|
+
* snapshot write, and `markStale` touches only the relations of its path.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Extracted, StoredFact, StoredRelation } from '../model.js';
|
|
8
|
+
import type { ExtractedLogPersistence, SnapshotPersistence } from './localSnapshotStore.js';
|
|
9
|
+
import { LocalSnapshotStore } from './localSnapshotStore.js';
|
|
10
|
+
|
|
11
|
+
interface Rig {
|
|
12
|
+
snap: SnapshotPersistence & { value?: string; writes: number; gate?: Promise<void> };
|
|
13
|
+
log: ExtractedLogPersistence & { text?: string; appends: string[] };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function rig(): Rig {
|
|
17
|
+
const snap: Rig['snap'] = {
|
|
18
|
+
writes: 0,
|
|
19
|
+
async read() { return snap.value; },
|
|
20
|
+
async write(s: string) { if (snap.gate) await snap.gate; snap.writes += 1; snap.value = s; },
|
|
21
|
+
};
|
|
22
|
+
const log: Rig['log'] = {
|
|
23
|
+
appends: [],
|
|
24
|
+
async read() { return log.text; },
|
|
25
|
+
async append(t: string) { log.appends.push(t); log.text = (log.text ?? '') + t; },
|
|
26
|
+
};
|
|
27
|
+
return { snap, log };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const SCOPE = { rootId: 'r', title: 'R', packs: ['docs'] };
|
|
31
|
+
const ex = (n: string) => [{ name: n }] as unknown as Extracted[];
|
|
32
|
+
const mk = (r: Rig, now = 'T') => new LocalSnapshotStore(r.snap, { extractedLog: r.log, now: () => now });
|
|
33
|
+
|
|
34
|
+
describe('LocalSnapshotStore extractedLog', () => {
|
|
35
|
+
it('keeps extracted out of the snapshot and appends only the new entries', async () => {
|
|
36
|
+
const r = rig();
|
|
37
|
+
const store = mk(r);
|
|
38
|
+
await store.putExtracted('h1', ex('a'));
|
|
39
|
+
await store.putExtracted('h2', ex('b'));
|
|
40
|
+
expect(r.log.appends).toHaveLength(2);
|
|
41
|
+
expect(r.log.appends[0]).toBe(`${JSON.stringify({ h: 'h1', e: ex('a') })}\n`);
|
|
42
|
+
expect(r.log.appends[1]).not.toContain('h1');
|
|
43
|
+
expect(r.snap.writes).toBe(0);
|
|
44
|
+
await store.write({ scope: SCOPE, facts: [], relations: [] });
|
|
45
|
+
expect(JSON.parse(r.snap.value!)).not.toHaveProperty('extracted');
|
|
46
|
+
expect(r.log.appends).toHaveLength(2);
|
|
47
|
+
expect(await mk(r).getExtracted('h2')).toEqual(ex('b'));
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('batches appends to the batch end', async () => {
|
|
51
|
+
const r = rig();
|
|
52
|
+
const store = mk(r);
|
|
53
|
+
await store.batched(async () => {
|
|
54
|
+
await store.putExtracted('h1', ex('a'));
|
|
55
|
+
await store.putExtracted('h2', ex('b'));
|
|
56
|
+
expect(r.log.appends).toHaveLength(0);
|
|
57
|
+
expect(await store.getExtracted('h1')).toEqual(ex('a'));
|
|
58
|
+
});
|
|
59
|
+
expect(r.log.appends).toHaveLength(1);
|
|
60
|
+
expect(r.log.appends[0]!.trim().split('\n')).toHaveLength(2);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('migrates an old snapshot carrying extracted into the log once and drops it from the next write', async () => {
|
|
64
|
+
const r = rig();
|
|
65
|
+
r.snap.value = JSON.stringify({ version: 1, scopes: [], facts: {}, relations: {}, extracted: { old: ex('o') } });
|
|
66
|
+
const store = mk(r);
|
|
67
|
+
expect(await store.getExtracted('old')).toEqual(ex('o'));
|
|
68
|
+
await store.putExtracted('new', ex('n'));
|
|
69
|
+
expect(r.log.appends).toHaveLength(1);
|
|
70
|
+
expect(r.log.text).toContain('"h":"old"');
|
|
71
|
+
expect(r.log.text).toContain('"h":"new"');
|
|
72
|
+
expect(JSON.parse(r.snap.value!)).not.toHaveProperty('extracted');
|
|
73
|
+
await store.putExtracted('new2', ex('n2'));
|
|
74
|
+
expect(r.log.text!.match(/"h":"old"/g)).toHaveLength(1);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('ignores a torn trailing line and appends on a fresh line', async () => {
|
|
78
|
+
const r = rig();
|
|
79
|
+
r.log.text = `${JSON.stringify({ h: 'a', e: ex('a') })}\n{"h":"b","e":[{"na`;
|
|
80
|
+
const store = mk(r);
|
|
81
|
+
expect(await store.getExtracted('a')).toEqual(ex('a'));
|
|
82
|
+
expect(await store.getExtracted('b')).toBeUndefined();
|
|
83
|
+
await store.putExtracted('c', ex('c'));
|
|
84
|
+
const again = mk(r);
|
|
85
|
+
expect(await again.getExtracted('c')).toEqual(ex('c'));
|
|
86
|
+
expect(await again.getExtracted('a')).toEqual(ex('a'));
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('lets the last line for a hash win', async () => {
|
|
90
|
+
const r = rig();
|
|
91
|
+
r.log.text = `${JSON.stringify({ h: 'a', e: ex('first') })}\n${JSON.stringify({ h: 'a', e: ex('second') })}\n`;
|
|
92
|
+
expect(await mk(r).getExtracted('a')).toEqual(ex('second'));
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('does not block getExtracted while a snapshot write is pending', async () => {
|
|
96
|
+
const r = rig();
|
|
97
|
+
let release!: () => void;
|
|
98
|
+
const store = mk(r);
|
|
99
|
+
await store.putExtracted('h1', ex('a'));
|
|
100
|
+
r.snap.gate = new Promise<void>((res) => { release = res; });
|
|
101
|
+
const pending = store.write({ scope: SCOPE, facts: [], relations: [] });
|
|
102
|
+
await new Promise((res) => setTimeout(res, 0));
|
|
103
|
+
expect(await store.getExtracted('h1')).toEqual(ex('a'));
|
|
104
|
+
expect(r.snap.writes).toBe(0);
|
|
105
|
+
release();
|
|
106
|
+
await pending;
|
|
107
|
+
expect(r.snap.writes).toBe(1);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('markStale touches only the relations of that path and matches the old full-scan result', async () => {
|
|
111
|
+
const fact = (key: string): StoredFact => ({ key, origin: 'mechanical' } as unknown as StoredFact);
|
|
112
|
+
const rel = (from: string, to: string, origin: string, sourceHash: string, staleAt?: string): StoredRelation =>
|
|
113
|
+
({ from, to, kind: 'refs', origin, sourceHash, ...(staleAt ? { staleAt } : {}) } as unknown as StoredRelation);
|
|
114
|
+
const rels = [
|
|
115
|
+
rel('src:r::a.md#1', 'src:r::b.md', 'model', 'old'),
|
|
116
|
+
rel('src:r::c.md', 'src:r::a.md', 'model', 'old'),
|
|
117
|
+
rel('src:r::a.md', 'src:r::d.md', 'model', 'cur'),
|
|
118
|
+
rel('src:r::a.md', 'src:r::e.md', 'mechanical', 'old'),
|
|
119
|
+
rel('src:r::a.md', 'src:r::f.md', 'model', 'old', 'EARLIER'),
|
|
120
|
+
rel('src:r::x.md', 'src:r::y.md', 'model', 'old'),
|
|
121
|
+
rel('doc:1', 'src:r::a.md#9', 'model', 'old'),
|
|
122
|
+
];
|
|
123
|
+
const expected = rels.map((x) => {
|
|
124
|
+
const on = (ref: string) => ref.startsWith('src:r::a.md');
|
|
125
|
+
return x.origin === 'model' && !x.staleAt && x.sourceHash !== 'cur' && (on(x.from) || on(x.to))
|
|
126
|
+
? { ...x, staleAt: 'T' } : x;
|
|
127
|
+
});
|
|
128
|
+
const r = rig();
|
|
129
|
+
const store = mk(r);
|
|
130
|
+
await store.write({ scope: SCOPE, facts: [fact('k2'), fact('k1')], relations: rels });
|
|
131
|
+
await store.markStale({ rootId: 'r' }, 'src:r::a.md#2' as never, 'cur');
|
|
132
|
+
const byKey = (a: StoredRelation, b: StoredRelation) => `${a.from}${a.to}`.localeCompare(`${b.from}${b.to}`);
|
|
133
|
+
expect([...(await store.relations({ rootId: 'r' }))].sort(byKey)).toEqual([...expected].sort(byKey));
|
|
134
|
+
expect((await store.facts({ rootId: 'r' })).map((f) => f.key)).toEqual(['k2', 'k1']);
|
|
135
|
+
const saved = JSON.parse(r.snap.value!) as { facts: { r: StoredFact[] } };
|
|
136
|
+
expect(saved.facts.r.map((f) => f.key)).toEqual(['k1', 'k2']);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it('writes a batch as ONE append of complete lines', async () => {
|
|
140
|
+
const r = rig();
|
|
141
|
+
const store = mk(r);
|
|
142
|
+
await store.batched(async () => {
|
|
143
|
+
await store.putExtracted('h1', ex('a'));
|
|
144
|
+
await store.putExtracted('h2', ex('b'));
|
|
145
|
+
});
|
|
146
|
+
expect(r.log.appends).toHaveLength(1);
|
|
147
|
+
expect(r.log.appends[0]!.endsWith('\n')).toBe(true);
|
|
148
|
+
for (const line of r.log.appends[0]!.trim().split('\n')) expect(() => JSON.parse(line)).not.toThrow();
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it('drops a torn or unparseable line without losing the lines around it', async () => {
|
|
152
|
+
const r = rig();
|
|
153
|
+
r.log.text = `${JSON.stringify({ h: 'a', e: ex('a') })}\n{"h":"x","e":[{"na\n${JSON.stringify({ h: 'c', e: ex('c') })}\nnot json\n`;
|
|
154
|
+
const store = mk(r);
|
|
155
|
+
expect(await store.getExtracted('a')).toEqual(ex('a'));
|
|
156
|
+
expect(await store.getExtracted('c')).toEqual(ex('c'));
|
|
157
|
+
expect(await store.getExtracted('x')).toBeUndefined();
|
|
158
|
+
expect(Object.keys(await store.extractedEntries())).toEqual(['a', 'c']);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('a failed append marks the log torn: the retry starts on a fresh line and nothing is lost', async () => {
|
|
162
|
+
const r = rig();
|
|
163
|
+
let fail = true;
|
|
164
|
+
r.log.append = async (t: string) => {
|
|
165
|
+
r.log.appends.push(t);
|
|
166
|
+
if (fail) { r.log.text = (r.log.text ?? '') + t.slice(0, 10); throw new Error('disk full'); } // a partial line landed
|
|
167
|
+
r.log.text = (r.log.text ?? '') + t;
|
|
168
|
+
};
|
|
169
|
+
const store = mk(r);
|
|
170
|
+
await expect(store.putExtracted('h1', ex('a'))).rejects.toThrow('disk full');
|
|
171
|
+
fail = false;
|
|
172
|
+
await store.putExtracted('h2', ex('b'));
|
|
173
|
+
expect(r.log.appends[1]!.startsWith('\n')).toBe(true);
|
|
174
|
+
const again = mk(r);
|
|
175
|
+
expect(await again.getExtracted('h1')).toEqual(ex('a'));
|
|
176
|
+
expect(await again.getExtracted('h2')).toEqual(ex('b'));
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it('does not re-append an identical entry, but appends a changed one', async () => {
|
|
180
|
+
const r = rig();
|
|
181
|
+
const store = mk(r);
|
|
182
|
+
await store.putExtracted('h1', ex('a'));
|
|
183
|
+
await store.putExtracted('h1', ex('a'));
|
|
184
|
+
expect(r.log.appends).toHaveLength(1);
|
|
185
|
+
await store.putExtracted('h1', ex('changed'));
|
|
186
|
+
expect(r.log.appends).toHaveLength(2);
|
|
187
|
+
// An entry the log already held at load is not re-appended either.
|
|
188
|
+
const reloaded = mk(r);
|
|
189
|
+
await reloaded.putExtracted('h1', ex('changed'));
|
|
190
|
+
expect(r.log.appends).toHaveLength(2);
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
it('does not rewrite the snapshot for an identical entry when there is no log', async () => {
|
|
194
|
+
const snap = rig().snap;
|
|
195
|
+
const store = new LocalSnapshotStore(snap, { now: () => 'T' });
|
|
196
|
+
await store.putExtracted('h1', ex('a'));
|
|
197
|
+
await store.putExtracted('h1', ex('a'));
|
|
198
|
+
expect(snap.writes).toBe(1);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it('compacts the log on load when dead bytes exceed live bytes, and only with a `replace` port', async () => {
|
|
202
|
+
const r = rig();
|
|
203
|
+
const lines = [1, 2, 3, 4].map((n) => `${JSON.stringify({ h: 'a', e: ex(`v${n}`) })}\n`);
|
|
204
|
+
r.log.text = `${lines.join('')}${JSON.stringify({ h: 'b', e: ex('b') })}\ntorn{"h"\n`;
|
|
205
|
+
const withoutReplace = mk(r);
|
|
206
|
+
expect(await withoutReplace.getExtracted('a')).toEqual(ex('v4'));
|
|
207
|
+
expect(r.log.text).toContain('v1');
|
|
208
|
+
|
|
209
|
+
const replaced: string[] = [];
|
|
210
|
+
r.log.replace = async (t: string) => { replaced.push(t); r.log.text = t; };
|
|
211
|
+
const store = mk(r);
|
|
212
|
+
expect(await store.getExtracted('a')).toEqual(ex('v4'));
|
|
213
|
+
expect(replaced).toHaveLength(1);
|
|
214
|
+
expect(replaced[0]).toBe(`${lines[3]}${JSON.stringify({ h: 'b', e: ex('b') })}\n`);
|
|
215
|
+
expect(await mk(r).getExtracted('b')).toEqual(ex('b'));
|
|
216
|
+
expect(replaced).toHaveLength(1); // now all live: nothing more to compact
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it('does not compact a log that is mostly live', async () => {
|
|
220
|
+
const r = rig();
|
|
221
|
+
r.log.text = `${JSON.stringify({ h: 'a', e: ex('a') })}\n${JSON.stringify({ h: 'b', e: ex('b') })}\n`;
|
|
222
|
+
const replaced: string[] = [];
|
|
223
|
+
r.log.replace = async (t: string) => { replaced.push(t); };
|
|
224
|
+
await mk(r).getExtracted('a');
|
|
225
|
+
expect(replaced).toHaveLength(0);
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it('a failed background checkpoint backs off by checkpointMs instead of retrying on every mutation', async () => {
|
|
229
|
+
const r = rig();
|
|
230
|
+
let attempts = 0;
|
|
231
|
+
r.snap.write = async () => { attempts += 1; throw new Error('disk full'); };
|
|
232
|
+
const clock = { ms: 0 };
|
|
233
|
+
const store = new LocalSnapshotStore(r.snap, { extractedLog: r.log, now: () => 'T', checkpointMs: 1000, nowMs: () => clock.ms });
|
|
234
|
+
const settle = () => new Promise((res) => setTimeout(res, 0));
|
|
235
|
+
const touch = (n: number) => store.write({ scope: { ...SCOPE, title: `t${n}` }, facts: [], relations: [] });
|
|
236
|
+
await expect(store.batched(async () => {
|
|
237
|
+
clock.ms = 1000;
|
|
238
|
+
await touch(1);
|
|
239
|
+
await settle();
|
|
240
|
+
expect(attempts).toBe(1);
|
|
241
|
+
clock.ms = 1500;
|
|
242
|
+
await touch(2);
|
|
243
|
+
await settle();
|
|
244
|
+
expect(attempts).toBe(1); // inside the backoff window
|
|
245
|
+
clock.ms = 2000;
|
|
246
|
+
await touch(3);
|
|
247
|
+
await settle();
|
|
248
|
+
expect(attempts).toBe(2);
|
|
249
|
+
})).rejects.toThrow('disk full'); // the batch end still reports the unwritten snapshot
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it('keeps a snapshot that does not parse aside, then starts empty rather than silently dropping it', async () => {
|
|
253
|
+
const r = rig();
|
|
254
|
+
r.snap.value = '{"version":1,"scopes":[';
|
|
255
|
+
const kept: string[] = [];
|
|
256
|
+
r.snap.keepAside = async (t: string) => { kept.push(t); };
|
|
257
|
+
const store = mk(r);
|
|
258
|
+
expect(await store.scopes()).toEqual([]);
|
|
259
|
+
expect(kept).toEqual(['{"version":1,"scopes":[']);
|
|
260
|
+
await store.write({ scope: SCOPE, facts: [], relations: [] });
|
|
261
|
+
expect(await mk(r).scopes()).toHaveLength(1);
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
it('still starts empty when keepAside itself fails', async () => {
|
|
265
|
+
const r = rig();
|
|
266
|
+
r.snap.value = 'garbage';
|
|
267
|
+
r.snap.keepAside = async () => { throw new Error('read-only'); };
|
|
268
|
+
expect(await mk(r).scopes()).toEqual([]);
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
it('extractedEntries reads the log, else the snapshot\'s legacy extracted', async () => {
|
|
272
|
+
const r = rig();
|
|
273
|
+
r.log.text = `${JSON.stringify({ h: 'a', e: ex('a') })}\n`;
|
|
274
|
+
r.snap.value = JSON.stringify({ version: 1, scopes: [], facts: {}, relations: {}, extracted: { old: ex('o') } });
|
|
275
|
+
expect(await mk(r).extractedEntries()).toEqual({ a: ex('a'), old: ex('o') });
|
|
276
|
+
const plain = rig();
|
|
277
|
+
plain.snap.value = r.snap.value;
|
|
278
|
+
expect(await new LocalSnapshotStore(plain.snap, {}).extractedEntries()).toEqual({ old: ex('o') });
|
|
279
|
+
});
|
|
280
|
+
});
|