@seanhogg/builderforce-memory 2026.10.55 → 2026.10.56
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/index.d.ts +2 -2
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +1 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/stores/extractLogWriter.d.ts +26 -0
- package/dist/knowledge/stores/extractLogWriter.d.ts.map +1 -0
- package/dist/knowledge/stores/extractLogWriter.js +60 -0
- package/dist/knowledge/stores/extractLogWriter.js.map +1 -0
- package/dist/knowledge/stores/localSnapshotStore.d.ts +48 -39
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +137 -179
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/dist/knowledge/stores/rowDelta.d.ts +97 -0
- package/dist/knowledge/stores/rowDelta.d.ts.map +1 -0
- package/dist/knowledge/stores/rowDelta.js +141 -0
- package/dist/knowledge/stores/rowDelta.js.map +1 -0
- package/dist/knowledge/stores/rowMemory.d.ts +31 -0
- package/dist/knowledge/stores/rowMemory.d.ts.map +1 -0
- package/dist/knowledge/stores/rowMemory.js +85 -0
- package/dist/knowledge/stores/rowMemory.js.map +1 -0
- package/dist/knowledge/stores/rowSync.d.ts +56 -0
- package/dist/knowledge/stores/rowSync.d.ts.map +1 -0
- package/dist/knowledge/stores/rowSync.js +119 -0
- package/dist/knowledge/stores/rowSync.js.map +1 -0
- package/dist/knowledge/stores/snapshotFormat.d.ts +17 -0
- package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -1
- package/dist/knowledge/stores/snapshotFormat.js +19 -0
- package/dist/knowledge/stores/snapshotFormat.js.map +1 -1
- package/package.json +3 -3
- package/src/contract/exports.snapshot.json +1 -0
- package/src/contract/regression.rows.test.ts +377 -0
- package/src/contract/types.contract.test.ts +28 -4
- package/src/knowledge/index.ts +4 -2
- package/src/knowledge/stores/extractLogWriter.ts +57 -0
- package/src/knowledge/stores/localSnapshotStore.ts +138 -168
- package/src/knowledge/stores/rowDelta.test.ts +91 -0
- package/src/knowledge/stores/rowDelta.ts +166 -0
- package/src/knowledge/stores/rowMemory.ts +82 -0
- package/src/knowledge/stores/rowSync.ts +118 -0
- package/src/knowledge/stores/snapshotFormat.ts +30 -0
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.rows.test.ts — the row-persisted LocalSnapshotStore (PRD 41 B4, G03), each invariant pinned by one
|
|
3
|
+
* test named `regression: <what broke>`. The host here is a fake `RowPersistence`: a map-backed "database" that records every
|
|
4
|
+
* change it is given and can be held, failed, told another writer changed it, or made to return `reloaded`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Extracted, NodeRef, ScopeRecord, StoredFact, StoredRelation } from '../knowledge/model.js';
|
|
8
|
+
import { canonicalDump, LocalSnapshotStore, type KnowledgeSnapshot, type RowChange, type RowPersistence } from '../knowledge/stores/localSnapshotStore.js';
|
|
9
|
+
import { memPersistence } from '../knowledge/testkit.test-util.js';
|
|
10
|
+
|
|
11
|
+
const SCOPE: ScopeRecord = { rootId: 'a', title: 'A', packs: ['docs'] };
|
|
12
|
+
const fact = (key: string, content = 'c'): StoredFact => ({ key, content, source: 's', importance: 0.5, origin: 'model', fileAnchors: [] });
|
|
13
|
+
const rel = (from: string, to: string, kind: string): StoredRelation => ({ from: from as NodeRef, to: to as NodeRef, kind, weight: 1, origin: 'model', sourceHash: 'h1' });
|
|
14
|
+
const ex = (name: string) => [{ name }] as unknown as Extracted[];
|
|
15
|
+
const deferred = () => { let resolve!: () => void; const promise = new Promise<void>((r) => { resolve = r; }); return { promise, resolve }; };
|
|
16
|
+
const settle = async () => { for (let i = 0; i < 5; i++) await new Promise((r) => setImmediate(r)); };
|
|
17
|
+
|
|
18
|
+
interface Db {
|
|
19
|
+
scopes: Map<string, ScopeRecord>;
|
|
20
|
+
facts: Map<string, StoredFact>;
|
|
21
|
+
relations: Map<string, StoredRelation>;
|
|
22
|
+
extracted: Map<string, Extracted[]>;
|
|
23
|
+
recheck: Set<string>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface FakeRows extends RowPersistence {
|
|
27
|
+
db: Db;
|
|
28
|
+
applies: RowChange[];
|
|
29
|
+
generation: number;
|
|
30
|
+
loads: number;
|
|
31
|
+
checks: number;
|
|
32
|
+
bodyReads: string[];
|
|
33
|
+
/** Holds every `apply` (after recording it) until resolved. */
|
|
34
|
+
hold?: ReturnType<typeof deferred>;
|
|
35
|
+
failNext: number;
|
|
36
|
+
/** Another writer's change: run after an apply merged, its result is returned as `reloaded`. */
|
|
37
|
+
reload?: () => KnowledgeSnapshot;
|
|
38
|
+
/** `changedElsewhere` answers true once. */
|
|
39
|
+
changed: boolean;
|
|
40
|
+
/** `load` leaves extract bodies out (they load lazily). */
|
|
41
|
+
lazyBodies: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const fkey = (root: string, key: string) => `${root}\u0000${key}`;
|
|
45
|
+
const rkey = (root: string, from: string, to: string, kind: string) => `${root}\u0000${from}\u0000${to}\u0000${kind}`;
|
|
46
|
+
|
|
47
|
+
function snapshotOf(db: Db, withExtracted = true): KnowledgeSnapshot {
|
|
48
|
+
const facts: Record<string, StoredFact[]> = {};
|
|
49
|
+
const relations: Record<string, StoredRelation[]> = {};
|
|
50
|
+
for (const [k, f] of db.facts) (facts[k.split('\u0000')[0]!] ??= []).push(f);
|
|
51
|
+
for (const [k, r] of db.relations) (relations[k.split('\u0000')[0]!] ??= []).push(r);
|
|
52
|
+
return {
|
|
53
|
+
version: 1, scopes: [...db.scopes.values()], facts, relations,
|
|
54
|
+
...(withExtracted ? { extracted: Object.fromEntries(db.extracted) } : {}),
|
|
55
|
+
...(db.recheck.size ? { recheck: [...db.recheck] } : {}),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function fakeRows(): FakeRows {
|
|
60
|
+
const db: Db = { scopes: new Map(), facts: new Map(), relations: new Map(), extracted: new Map(), recheck: new Set() };
|
|
61
|
+
const f: FakeRows = {
|
|
62
|
+
db, applies: [], generation: 0, loads: 0, checks: 0, bodyReads: [], failNext: 0, changed: false, lazyBodies: false,
|
|
63
|
+
async load() { f.loads += 1; return snapshotOf(db, !f.lazyBodies); },
|
|
64
|
+
async apply(change) {
|
|
65
|
+
f.applies.push(change);
|
|
66
|
+
if (f.hold) await f.hold.promise;
|
|
67
|
+
if (f.failNext > 0) { f.failNext -= 1; throw new Error('disk full'); }
|
|
68
|
+
const { upserts: u, deletes: d } = change;
|
|
69
|
+
for (const s of u.scopes) db.scopes.set(s.rootId, s);
|
|
70
|
+
for (const [root, x] of u.facts) db.facts.set(fkey(root, x.key), x);
|
|
71
|
+
for (const [root, r] of u.relations) db.relations.set(rkey(root, r.from, r.to, r.kind), r);
|
|
72
|
+
for (const [h, e] of u.extracted) db.extracted.set(h, e);
|
|
73
|
+
for (const h of u.recheck) db.recheck.add(h);
|
|
74
|
+
for (const id of d.scopes) db.scopes.delete(id);
|
|
75
|
+
for (const [root, key] of d.facts) db.facts.delete(fkey(root, key));
|
|
76
|
+
for (const [root, from, to, kind] of d.relations) db.relations.delete(rkey(root, from, to, kind));
|
|
77
|
+
for (const h of d.extracted) db.extracted.delete(h);
|
|
78
|
+
for (const h of d.recheck) db.recheck.delete(h);
|
|
79
|
+
f.generation += 1;
|
|
80
|
+
const reload = f.reload;
|
|
81
|
+
f.reload = undefined;
|
|
82
|
+
return { generation: f.generation, ...(reload ? { reloaded: reload() } : {}) };
|
|
83
|
+
},
|
|
84
|
+
async loadAllExtracted() { return Object.fromEntries(db.extracted); },
|
|
85
|
+
async loadExtracted(hash) { f.bodyReads.push(hash); return db.extracted.get(hash); },
|
|
86
|
+
async changedElsewhere() { f.checks += 1; const c = f.changed; f.changed = false; return c; },
|
|
87
|
+
};
|
|
88
|
+
return f;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
const rowStore = (rows: RowPersistence) => new LocalSnapshotStore(undefined, { rows, now: () => 'T' });
|
|
93
|
+
const loadedFrom = (snap: KnowledgeSnapshot) => {
|
|
94
|
+
const p = memPersistence();
|
|
95
|
+
p.value = JSON.stringify(snap);
|
|
96
|
+
return new LocalSnapshotStore(p, { now: () => 'T' });
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
function prng(seed: number): () => number {
|
|
100
|
+
return () => {
|
|
101
|
+
seed = (seed + 0x6d2b79f5) | 0;
|
|
102
|
+
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
|
|
103
|
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
104
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The seeded op sequence both kinds of store run: facts, relations, scopes, extracted, recheck (with clears), stale marks, reads, some inside `batched`. */
|
|
109
|
+
async function driveOps(store: LocalSnapshotStore, seed: number, steps: number, between?: (rand: () => number, pick: (n: number) => number) => void): Promise<void> {
|
|
110
|
+
const rand = prng(seed);
|
|
111
|
+
const pick = (n: number) => Math.floor(rand() * n);
|
|
112
|
+
const op = async () => {
|
|
113
|
+
const kind = pick(8);
|
|
114
|
+
if (kind <= 2) {
|
|
115
|
+
await store.write({
|
|
116
|
+
scope: { ...SCOPE, ...(rand() < 0.5 ? { lastDigest: `d${pick(9)}` } : {}) },
|
|
117
|
+
facts: Array.from({ length: pick(4) }, () => fact(`claim:k${pick(6)}`, `v${pick(99)}`)),
|
|
118
|
+
relations: Array.from({ length: pick(3) }, () => rel(`fact:claim:k${pick(6)}`, `src:a::f${pick(4)}.md#s`, ['about', 'mentions'][pick(2)]!)),
|
|
119
|
+
});
|
|
120
|
+
} else if (kind === 3) await store.markStale({ rootId: 'a' }, `src:a::f${pick(4)}.md#s` as NodeRef, `h${pick(3)}`);
|
|
121
|
+
else if (kind === 4) await store.putExtracted(`x${pick(8)}`, ex(`e${pick(5)}`));
|
|
122
|
+
else if (kind === 5) await store.markRecheck([`h${pick(5)}`, `h${pick(5)}`]);
|
|
123
|
+
else if (kind === 6) await store.clearRecheck([`h${pick(5)}`]);
|
|
124
|
+
else await store.facts({ rootId: 'a' });
|
|
125
|
+
};
|
|
126
|
+
for (let i = 0; i < steps; i++) {
|
|
127
|
+
between?.(rand, pick);
|
|
128
|
+
try {
|
|
129
|
+
if (rand() < 0.3) await store.batched(async () => { for (let j = 0; j < 5; j++) await op(); });
|
|
130
|
+
else await op();
|
|
131
|
+
} catch (err) {
|
|
132
|
+
if (!between) throw err; // only the fuzz injects failures
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const sameAsHost = async (store: LocalSnapshotStore, rows: FakeRows) => expect(await canonicalDump(store)).toBe(await canonicalDump(loadedFrom(snapshotOf(rows.db))));
|
|
138
|
+
|
|
139
|
+
describe('regression: row persistence', () => {
|
|
140
|
+
it('regression: after N random mutations the rows the host accumulated equal the canonical dump', async () => {
|
|
141
|
+
const rows = fakeRows();
|
|
142
|
+
const store = rowStore(rows);
|
|
143
|
+
await driveOps(store, 20261108, 90);
|
|
144
|
+
const dump = await canonicalDump(store);
|
|
145
|
+
expect(dump).toContain('"facts"');
|
|
146
|
+
expect(dump).toContain('"recheck"');
|
|
147
|
+
await sameAsHost(store, rows); // the accumulated rows
|
|
148
|
+
expect(await canonicalDump(rowStore(rows))).toBe(dump); // and a second store loading them
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it('regression: parity oracle: the same op sequence on a snapshot-persisted store and a row store gives byte-equal dumps', async () => {
|
|
152
|
+
for (const seed of [1, 2, 3]) {
|
|
153
|
+
const classic = new LocalSnapshotStore(memPersistence(), { now: () => 'T' });
|
|
154
|
+
const rowed = rowStore(fakeRows());
|
|
155
|
+
await driveOps(classic, seed, 60);
|
|
156
|
+
await driveOps(rowed, seed, 60);
|
|
157
|
+
expect(await canonicalDump(rowed)).toBe(await canonicalDump(classic));
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('regression: fuzz: failed applies, `reloaded` and another writer changing the store, interleaved with the ops, never lose or reorder this window\'s rows', async () => {
|
|
162
|
+
for (const seed of [11, 12, 13, 14]) {
|
|
163
|
+
const rows = fakeRows();
|
|
164
|
+
const store = rowStore(rows);
|
|
165
|
+
let other = 0;
|
|
166
|
+
const theirs = () => { const key = `claim:o${other++}`; rows.db.facts.set(fkey('b', key), fact(key)); };
|
|
167
|
+
await driveOps(store, seed, 80, (rand) => {
|
|
168
|
+
const r = rand();
|
|
169
|
+
if (r < 0.15) rows.failNext = 1;
|
|
170
|
+
else if (r < 0.3) rows.reload = () => { theirs(); return snapshotOf(rows.db); };
|
|
171
|
+
else if (r < 0.45) { theirs(); rows.changed = true; }
|
|
172
|
+
});
|
|
173
|
+
rows.failNext = 0;
|
|
174
|
+
rows.reload = undefined;
|
|
175
|
+
await store.write({ scope: SCOPE, facts: [], relations: [] }); // flush whatever a failure left marked
|
|
176
|
+
rows.changed = true;
|
|
177
|
+
await store.scopes(); // pick up the other writer's last change
|
|
178
|
+
await sameAsHost(store, rows);
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it('regression: a changed-elsewhere read that races an apply cannot drop the rows that apply commits', async () => {
|
|
183
|
+
const rows = fakeRows();
|
|
184
|
+
const store = rowStore(rows);
|
|
185
|
+
await store.facts({ rootId: 'a' });
|
|
186
|
+
rows.hold = deferred();
|
|
187
|
+
const write = store.write({ scope: SCOPE, facts: [fact('claim:mine')], relations: [] });
|
|
188
|
+
await settle();
|
|
189
|
+
rows.db.facts.set(fkey('b', 'claim:theirs'), fact('claim:theirs'));
|
|
190
|
+
rows.changed = true;
|
|
191
|
+
const read = store.facts({ rootId: 'b' });
|
|
192
|
+
await settle();
|
|
193
|
+
rows.hold.resolve();
|
|
194
|
+
await Promise.all([write, read]);
|
|
195
|
+
await store.scopes();
|
|
196
|
+
expect((await store.facts({ rootId: 'a' })).map((x) => x.key)).toEqual(['claim:mine']);
|
|
197
|
+
expect((await store.facts({ rootId: 'b' })).map((x) => x.key)).toEqual(['claim:theirs']);
|
|
198
|
+
await sameAsHost(store, rows);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it('regression: a read during a held apply resolves without waiting for it', async () => {
|
|
202
|
+
const rows = fakeRows();
|
|
203
|
+
const store = rowStore(rows);
|
|
204
|
+
await store.facts({ rootId: 'a' });
|
|
205
|
+
rows.checks = 0;
|
|
206
|
+
rows.hold = deferred();
|
|
207
|
+
const write = store.write({ scope: SCOPE, facts: [fact('claim:1')], relations: [] });
|
|
208
|
+
await settle();
|
|
209
|
+
rows.changed = true;
|
|
210
|
+
expect((await store.facts({ rootId: 'a' })).map((x) => x.key)).toEqual(['claim:1']); // resolves while the apply is held
|
|
211
|
+
expect(rows.checks).toBe(0); // no check was made behind the apply
|
|
212
|
+
rows.hold.resolve();
|
|
213
|
+
await write;
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
it('regression: a reload arriving while a failed apply is restored keeps the restored rows, and the next apply persists them', async () => {
|
|
217
|
+
const rows = fakeRows();
|
|
218
|
+
const store = rowStore(rows);
|
|
219
|
+
await store.facts({ rootId: 'a' });
|
|
220
|
+
rows.hold = deferred();
|
|
221
|
+
rows.failNext = 1;
|
|
222
|
+
const write = store.write({ scope: SCOPE, facts: [fact('claim:mine')], relations: [] });
|
|
223
|
+
await settle();
|
|
224
|
+
rows.db.facts.set(fkey('b', 'claim:theirs'), fact('claim:theirs'));
|
|
225
|
+
rows.changed = true;
|
|
226
|
+
const read = store.facts({ rootId: 'b' });
|
|
227
|
+
expect(await read).toEqual([]); // answered from memory while the apply was in flight
|
|
228
|
+
rows.hold.resolve();
|
|
229
|
+
await expect(write).rejects.toThrow('disk full');
|
|
230
|
+
expect((await store.facts({ rootId: 'b' })).map((x) => x.key)).toEqual(['claim:theirs']); // the next read reloads
|
|
231
|
+
expect((await store.facts({ rootId: 'a' })).map((x) => x.key)).toEqual(['claim:mine']); // restored marks survived the reload
|
|
232
|
+
await store.markRecheck(['x']);
|
|
233
|
+
expect(rows.db.facts.has(fkey('a', 'claim:mine'))).toBe(true);
|
|
234
|
+
await sameAsHost(store, rows);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it('regression: a dump or extractedEntries with lazy bodies reads them all through loadAllExtracted, and throws without it', async () => {
|
|
238
|
+
const rows = fakeRows();
|
|
239
|
+
rows.lazyBodies = true;
|
|
240
|
+
rows.db.extracted.set('h9', ex('nine'));
|
|
241
|
+
const store = rowStore(rows);
|
|
242
|
+
await store.putExtracted('mem', ex('m'));
|
|
243
|
+
expect(Object.keys(await store.extractedEntries()).sort()).toEqual(['h9', 'mem']);
|
|
244
|
+
expect(await canonicalDump(store)).toContain('"h9"');
|
|
245
|
+
|
|
246
|
+
const bare = fakeRows();
|
|
247
|
+
delete bare.loadAllExtracted;
|
|
248
|
+
const partial = rowStore(bare);
|
|
249
|
+
await expect(partial.extractedEntries()).rejects.toThrow('knowledge_dump_needs_all_bodies');
|
|
250
|
+
await expect(canonicalDump(partial)).rejects.toThrow('knowledge_dump_needs_all_bodies');
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
it('regression: preloadExtracted reads the missing bodies once; a miss is remembered until the hash is put', async () => {
|
|
254
|
+
const rows = fakeRows();
|
|
255
|
+
rows.lazyBodies = true;
|
|
256
|
+
for (const h of ['h1', 'h2']) rows.db.extracted.set(h, ex(h));
|
|
257
|
+
const store = rowStore(rows);
|
|
258
|
+
await store.preloadExtracted(['h1', 'h2', 'h1', 'zz']);
|
|
259
|
+
expect([...rows.bodyReads].sort()).toEqual(['h1', 'h2', 'zz']);
|
|
260
|
+
expect(await store.getExtracted('h2')).toEqual(ex('h2'));
|
|
261
|
+
expect(await store.getExtracted('zz')).toBeUndefined();
|
|
262
|
+
expect(rows.bodyReads).toHaveLength(3); // nothing read again
|
|
263
|
+
await store.putExtracted('zz', ex('z'));
|
|
264
|
+
expect(await store.getExtracted('zz')).toEqual(ex('z'));
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it('regression: a mutation made while apply is pending is persisted by the next apply', async () => {
|
|
268
|
+
const rows = fakeRows();
|
|
269
|
+
const store = rowStore(rows);
|
|
270
|
+
rows.hold = deferred();
|
|
271
|
+
const first = store.write({ scope: SCOPE, facts: [fact('claim:1')], relations: [] });
|
|
272
|
+
await settle();
|
|
273
|
+
expect(rows.applies).toHaveLength(1);
|
|
274
|
+
const second = store.write({ scope: SCOPE, facts: [fact('claim:2')], relations: [] });
|
|
275
|
+
await settle();
|
|
276
|
+
rows.hold.resolve();
|
|
277
|
+
await Promise.all([first, second]);
|
|
278
|
+
expect(rows.applies).toHaveLength(2);
|
|
279
|
+
expect(rows.applies[0]!.upserts.facts.map(([, x]) => x.key)).toEqual(['claim:1']);
|
|
280
|
+
expect(rows.applies[1]!.upserts.facts.map(([, x]) => x.key)).toEqual(['claim:2']);
|
|
281
|
+
expect([...rows.db.facts.values()].map((x) => x.key).sort()).toEqual(['claim:1', 'claim:2']);
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
it('regression: a rejected apply loses nothing: the retry persists the failed rows with the newer value of a row marked since', async () => {
|
|
285
|
+
const rows = fakeRows();
|
|
286
|
+
const store = rowStore(rows);
|
|
287
|
+
rows.failNext = 1;
|
|
288
|
+
await expect(store.write({ scope: SCOPE, facts: [fact('claim:1', 'old'), fact('claim:2')], relations: [rel('fact:claim:1', 'src:a::f.md#s', 'about')] })).rejects.toThrow('disk full');
|
|
289
|
+
expect(rows.db.facts.size).toBe(0);
|
|
290
|
+
await store.markRecheck(['h1']); // a later mutation: persists, and carries the failed rows with it
|
|
291
|
+
await store.write({ scope: SCOPE, facts: [fact('claim:1', 'new')], relations: [] });
|
|
292
|
+
expect([...rows.db.facts.values()].map((x) => [x.key, x.content]).sort()).toEqual([['claim:1', 'new'], ['claim:2', 'c']]);
|
|
293
|
+
expect(rows.db.relations.size).toBe(1);
|
|
294
|
+
expect(rows.db.scopes.has('a')).toBe(true);
|
|
295
|
+
expect([...rows.db.recheck]).toEqual(['h1']);
|
|
296
|
+
expect(await canonicalDump(loadedFrom(snapshotOf(rows.db)))).toBe(await canonicalDump(store));
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it('regression: recheck survives a reload', async () => {
|
|
300
|
+
const rows = fakeRows();
|
|
301
|
+
const store = rowStore(rows);
|
|
302
|
+
await store.markRecheck(['h2', 'h1', 'h3']);
|
|
303
|
+
await store.clearRecheck(['h2']);
|
|
304
|
+
expect(rows.applies.at(-1)!.deletes.recheck).toEqual(['h2']);
|
|
305
|
+
expect(await rowStore(rows).recheckHashes()).toEqual(['h1', 'h3']);
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
it('regression: `reloaded` replaces memory, and a mark made while apply was pending survives in memory and is persisted next', async () => {
|
|
309
|
+
const rows = fakeRows();
|
|
310
|
+
const store = rowStore(rows);
|
|
311
|
+
await store.write({ scope: SCOPE, facts: [fact('claim:gone')], relations: [] });
|
|
312
|
+
rows.hold = deferred();
|
|
313
|
+
// Another window: deletes `claim:gone`, adds `claim:other`. Its rows come back with this window's apply.
|
|
314
|
+
rows.reload = () => { rows.db.facts.delete(fkey('a', 'claim:gone')); rows.db.facts.set(fkey('a', 'claim:other'), fact('claim:other')); return snapshotOf(rows.db); };
|
|
315
|
+
const first = store.write({ scope: SCOPE, facts: [fact('claim:1')], relations: [] });
|
|
316
|
+
await settle();
|
|
317
|
+
const second = store.write({ scope: SCOPE, facts: [fact('claim:2')], relations: [] }); // marked during the apply
|
|
318
|
+
await settle();
|
|
319
|
+
rows.hold.resolve();
|
|
320
|
+
await Promise.all([first, second]);
|
|
321
|
+
const keys = (await store.facts({ rootId: 'a' })).map((x) => x.key).sort();
|
|
322
|
+
expect(keys).toEqual(['claim:1', 'claim:2', 'claim:other']); // replaced (gone is gone, other is here), claim:2 not lost
|
|
323
|
+
expect(rows.applies.at(-1)!.upserts.facts.map(([, x]) => x.key)).toEqual(['claim:2']);
|
|
324
|
+
expect([...rows.db.facts.values()].map((x) => x.key).sort()).toEqual(keys);
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
it('regression: `reloaded` rebuilds the relations-by-path index, so markStale finds a relation another window wrote', async () => {
|
|
328
|
+
const rows = fakeRows();
|
|
329
|
+
const store = rowStore(rows);
|
|
330
|
+
rows.reload = () => { rows.db.relations.set(rkey('a', 'fact:claim:9', 'src:a::z.md#s', 'about'), rel('fact:claim:9', 'src:a::z.md#s', 'about')); return snapshotOf(rows.db); };
|
|
331
|
+
await store.write({ scope: SCOPE, facts: [], relations: [] });
|
|
332
|
+
await store.markStale({ rootId: 'a' }, 'src:a::z.md#s', 'other-hash');
|
|
333
|
+
expect((await store.relations({ rootId: 'a' }))[0]!.staleAt).toBe('T');
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
it('regression: when another writer changed the store, a read reloads first (one check in flight, none inside a batch)', async () => {
|
|
337
|
+
const rows = fakeRows();
|
|
338
|
+
const store = rowStore(rows);
|
|
339
|
+
await store.facts({ rootId: 'a' });
|
|
340
|
+
rows.checks = 0;
|
|
341
|
+
rows.db.facts.set(fkey('a', 'claim:theirs'), fact('claim:theirs'));
|
|
342
|
+
rows.changed = true;
|
|
343
|
+
const reads = await Promise.all([1, 2, 3, 4, 5].map(() => store.facts({ rootId: 'a' })));
|
|
344
|
+
expect(rows.checks).toBe(1);
|
|
345
|
+
expect(reads.every((r) => r.map((x) => x.key).join() === 'claim:theirs')).toBe(true);
|
|
346
|
+
|
|
347
|
+
rows.db.facts.set(fkey('a', 'claim:later'), fact('claim:later'));
|
|
348
|
+
rows.changed = true;
|
|
349
|
+
rows.checks = 0;
|
|
350
|
+
await store.batched(async () => { expect((await store.facts({ rootId: 'a' })).map((x) => x.key)).toEqual(['claim:theirs']); });
|
|
351
|
+
expect(rows.checks).toBe(0);
|
|
352
|
+
expect((await store.facts({ rootId: 'a' })).map((x) => x.key).sort()).toEqual(['claim:later', 'claim:theirs']); // the next read outside the batch sees it
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
it('regression: an extract body missing from memory is read through loadExtracted once, and kept', async () => {
|
|
356
|
+
const rows = fakeRows();
|
|
357
|
+
rows.lazyBodies = true;
|
|
358
|
+
rows.db.extracted.set('h9', ex('nine'));
|
|
359
|
+
const store = rowStore(rows);
|
|
360
|
+
expect(await store.getExtracted('h9')).toEqual(ex('nine'));
|
|
361
|
+
expect(await store.getExtracted('h9')).toEqual(ex('nine'));
|
|
362
|
+
expect(await store.getExtracted('nope')).toBeUndefined();
|
|
363
|
+
expect(rows.bodyReads).toEqual(['h9', 'nope']);
|
|
364
|
+
await store.putExtracted('h9', ex('nine')); // the same body: no row written
|
|
365
|
+
expect(rows.applies).toHaveLength(0);
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
it('regression: without rows the store writes the same bytes as the dump, and needs one of the two ports', async () => {
|
|
369
|
+
const p = memPersistence();
|
|
370
|
+
const store = new LocalSnapshotStore(p, { now: () => 'T' });
|
|
371
|
+
await store.write({ scope: SCOPE, facts: [fact('claim:1')], relations: [rel('fact:claim:1', 'src:a::f.md#s', 'about')] });
|
|
372
|
+
await store.putExtracted('h1', ex('one'));
|
|
373
|
+
await store.markRecheck(['h1']);
|
|
374
|
+
expect(await canonicalDump(store)).toBe(p.value);
|
|
375
|
+
expect(() => new (LocalSnapshotStore as unknown as new (p: undefined, o: object) => unknown)(undefined, {})).toThrow();
|
|
376
|
+
});
|
|
377
|
+
});
|
|
@@ -16,8 +16,9 @@ import type {
|
|
|
16
16
|
Extracted, ExtractJob, ExtractJobResult, GraphApp, GraphOutline, GraphReadSkip, GraphSystem, KEdge, KNode, KnowledgeGraph, KnowledgeStore,
|
|
17
17
|
OutlineFile, ReviewFailure, ReviewFailureChunks, ReviewPhase, ReviewReport, ReviewRun, ReviewRunPhase, ReviewStep, ScopeRecord,
|
|
18
18
|
StoredFact, StoredRelation, ExtractedLogPersistence, KnowledgeSnapshot, LocalSnapshotStoreOptions, SnapshotPersistence,
|
|
19
|
+
RowChange, RowPersistence,
|
|
19
20
|
} from '../knowledge/index.js';
|
|
20
|
-
import { ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore, type ExtractorState } from '../knowledge/index.js';
|
|
21
|
+
import { canonicalDump, ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore, type ExtractorState } from '../knowledge/index.js';
|
|
21
22
|
|
|
22
23
|
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
|
|
23
24
|
type Expect<T extends true> = T;
|
|
@@ -143,14 +144,37 @@ export const batchedHostStore = {
|
|
|
143
144
|
export type LocalSnapshotStore_is_a_KnowledgeStore = Expect<Equal<LocalSnapshotStore extends KnowledgeStore ? true : false, true>>;
|
|
144
145
|
export type LocalSnapshotStore_public_methods = Expect<Equal<
|
|
145
146
|
keyof LocalSnapshotStore,
|
|
146
|
-
'batched' | 'scopes' | 'facts' | 'relations' | 'write' | 'markStale' | 'getExtracted' | 'extractedEntries' | 'putExtracted' | 'markRecheck' | 'recheckHashes' | 'clearRecheck' | 'hasRecheck'
|
|
147
|
+
'batched' | 'scopes' | 'facts' | 'relations' | 'write' | 'markStale' | 'getExtracted' | 'extractedEntries' | 'preloadExtracted' | 'putExtracted' | 'markRecheck' | 'recheckHashes' | 'clearRecheck' | 'hasRecheck'
|
|
147
148
|
>>;
|
|
148
149
|
export type LocalSnapshotStore_extractedEntries = Expect<Equal<LocalSnapshotStore['extractedEntries'], () => Promise<Record<string, Extracted[]>>>>;
|
|
149
150
|
export type LocalSnapshotStore_constructor = Expect<Equal<
|
|
150
151
|
ConstructorParameters<typeof LocalSnapshotStore>, [persistence: SnapshotPersistence, opts?: LocalSnapshotStoreOptions]
|
|
151
152
|
>>;
|
|
152
|
-
|
|
153
|
-
export type
|
|
153
|
+
// Two overloads: the snapshot-persisted one (the last, so `Parameters` reads it) and the row-persisted one (`undefined` + `opts.rows`).
|
|
154
|
+
export type localSnapshotStore_factory = Expect<Equal<Parameters<typeof localSnapshotStore>, [persistence: SnapshotPersistence, opts?: LocalSnapshotStoreOptions]>>;
|
|
155
|
+
export type localSnapshotStore_factory_returns = Expect<Equal<ReturnType<typeof localSnapshotStore>, LocalSnapshotStore>>;
|
|
156
|
+
export const rowPersistedStore = (rows: RowPersistence): LocalSnapshotStore => localSnapshotStore(undefined, { rows });
|
|
157
|
+
export const rowPersistedStoreByConstructor = (rows: RowPersistence): LocalSnapshotStore => new LocalSnapshotStore(undefined, { rows });
|
|
158
|
+
export const dumpsAStore = (store: LocalSnapshotStore): Promise<string> => canonicalDump(store);
|
|
159
|
+
export type LocalSnapshotStoreOptions_keys = Expect<Equal<keyof LocalSnapshotStoreOptions, 'extractedLog' | 'rows' | 'now' | 'checkpointMs' | 'nowMs'>>;
|
|
160
|
+
export type RowChange_shape = Expect<Equal<RowChange, {
|
|
161
|
+
upserts: {
|
|
162
|
+
scopes: ScopeRecord[]; facts: Array<[rootId: string, fact: StoredFact]>; relations: Array<[rootId: string, relation: StoredRelation]>;
|
|
163
|
+
extracted: Array<[hash: string, entries: Extracted[]]>; recheck: string[];
|
|
164
|
+
};
|
|
165
|
+
deletes: {
|
|
166
|
+
scopes: string[]; facts: Array<[rootId: string, key: string]>;
|
|
167
|
+
relations: Array<[rootId: string, from: string, to: string, kind: string]>;
|
|
168
|
+
extracted: string[]; recheck: string[];
|
|
169
|
+
};
|
|
170
|
+
}>>;
|
|
171
|
+
export type RowPersistence_ports = Expect<Equal<RowPersistence, {
|
|
172
|
+
load(): Promise<KnowledgeSnapshot | undefined>;
|
|
173
|
+
apply(change: RowChange): Promise<{ generation: number; reloaded?: KnowledgeSnapshot }>;
|
|
174
|
+
loadAllExtracted?(): Promise<Record<string, Extracted[]>>;
|
|
175
|
+
loadExtracted?(hash: string): Promise<Extracted[] | undefined>;
|
|
176
|
+
changedElsewhere?(): Promise<boolean>;
|
|
177
|
+
}>>;
|
|
154
178
|
export type SnapshotPersistence_ports = Expect<Equal<
|
|
155
179
|
SnapshotPersistence,
|
|
156
180
|
{ read(): Promise<string | undefined>; write(snapshot: string): Promise<void>; keepAside?(text: string): Promise<void> }
|
package/src/knowledge/index.ts
CHANGED
|
@@ -72,8 +72,10 @@ export {
|
|
|
72
72
|
} from './refs.js';
|
|
73
73
|
export { DOCS_PACK, DOCS_PACK_ID, brokenLinkRule, orphanDocumentRule, contradictionRule } from './packs/docs.js';
|
|
74
74
|
export { frontMatterOf, SECTION_INDEX_BADGE } from '../ingest/docsExtract.js';
|
|
75
|
-
export { LocalSnapshotStore, localSnapshotStore } from './stores/localSnapshotStore.js';
|
|
76
|
-
export type {
|
|
75
|
+
export { LocalSnapshotStore, localSnapshotStore, canonicalDump } from './stores/localSnapshotStore.js';
|
|
76
|
+
export type {
|
|
77
|
+
SnapshotPersistence, KnowledgeSnapshot, LocalSnapshotStoreOptions, ExtractedLogPersistence, RowPersistence, RowChange,
|
|
78
|
+
} from './stores/localSnapshotStore.js';
|
|
77
79
|
|
|
78
80
|
// The knowledge index (search, expand, near-duplicate pairs) ships on the same subpath.
|
|
79
81
|
export * from '../retrieval/knowledge-index/index.js';
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/stores/extractLogWriter.ts — the write side of the extract cache's append-only log (PRD 41 A10 rule 7), moved
|
|
3
|
+
* out of {@link LocalSnapshotStore}. It owns what is not yet appended and whether the log's last line is torn; the store
|
|
4
|
+
* owns WHEN to flush (inside `persistIfDirty`). No behaviour of its own beyond the log port.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Extracted } from '../model.js';
|
|
8
|
+
import type { ExtractedLogPersistence } from './localSnapshotStore.js';
|
|
9
|
+
import { parseLog } from './snapshotFormat.js';
|
|
10
|
+
|
|
11
|
+
export class ExtractLogWriter {
|
|
12
|
+
/** Entries not yet appended. */
|
|
13
|
+
private pending = new Map<string, Extracted[]>();
|
|
14
|
+
/** The log's last line is torn (no newline), so the next append starts on a fresh line. */
|
|
15
|
+
private torn = false;
|
|
16
|
+
|
|
17
|
+
constructor(private readonly port: ExtractedLogPersistence) {}
|
|
18
|
+
|
|
19
|
+
read(): Promise<string | undefined> { return this.port.read(); }
|
|
20
|
+
|
|
21
|
+
/** Queues an entry for the next {@link flush}. */
|
|
22
|
+
queue(hash: string, entries: Extracted[]): void { this.pending.set(hash, entries); }
|
|
23
|
+
|
|
24
|
+
/** Fills `into` from the log's text (last line per hash wins) and compacts the log when dead bytes exceed live bytes. */
|
|
25
|
+
async load(text: string | undefined, into: Map<string, Extracted[]>): Promise<void> {
|
|
26
|
+
const parsed = parseLog(text);
|
|
27
|
+
for (const [h, e] of parsed.entries) into.set(h, e);
|
|
28
|
+
this.torn = !!text && !text.endsWith('\n');
|
|
29
|
+
// Needs the port's `replace`; a failure is ignored (the log stays correct, only larger). Another window appending between
|
|
30
|
+
// this read and the replace loses those lines from the cache — a cache miss, re-extracted next review.
|
|
31
|
+
if (!this.port.replace || parsed.deadBytes <= parsed.liveBytes) return;
|
|
32
|
+
try {
|
|
33
|
+
await this.port.replace([...parsed.liveLines.values()].join(''));
|
|
34
|
+
this.torn = false;
|
|
35
|
+
} catch { /* keep the uncompacted log */ }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Appends the not-yet-logged entries as ONE `append` of complete lines. A failed append keeps them pending and marks the
|
|
40
|
+
* log torn (it may hold a partial line), so the next append starts on a fresh line.
|
|
41
|
+
*/
|
|
42
|
+
async flush(): Promise<void> {
|
|
43
|
+
if (this.pending.size === 0) return;
|
|
44
|
+
const batch = this.pending;
|
|
45
|
+
this.pending = new Map();
|
|
46
|
+
let text = this.torn ? '\n' : '';
|
|
47
|
+
for (const [h, e] of batch) text += `${JSON.stringify({ h, e })}\n`;
|
|
48
|
+
try {
|
|
49
|
+
await this.port.append(text);
|
|
50
|
+
this.torn = false;
|
|
51
|
+
} catch (err) {
|
|
52
|
+
this.torn = true;
|
|
53
|
+
for (const [h, e] of batch) if (!this.pending.has(h)) this.pending.set(h, e);
|
|
54
|
+
throw err;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|