@seanhogg/builderforce-memory 2026.10.54 → 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/owedFiles.d.ts +2 -1
- package/dist/knowledge/owedFiles.d.ts.map +1 -1
- package/dist/knowledge/owedFiles.js.map +1 -1
- package/dist/knowledge/review.js +3 -2
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewFailure.d.ts +4 -2
- package/dist/knowledge/reviewFailure.d.ts.map +1 -1
- package/dist/knowledge/reviewFailure.js +7 -4
- package/dist/knowledge/reviewFailure.js.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +1 -1
- package/dist/knowledge/reviewPrefetch.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.recheck.test.ts +70 -8
- package/src/contract/regression.rows.test.ts +377 -0
- package/src/contract/types.contract.test.ts +33 -5
- package/src/knowledge/index.ts +4 -2
- package/src/knowledge/owedFiles.ts +2 -1
- package/src/knowledge/review.ordered.test.ts +7 -3
- package/src/knowledge/review.ts +2 -2
- package/src/knowledge/reviewFailure.ts +8 -5
- package/src/knowledge/reviewPrefetch.ts +1 -1
- 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
package/src/knowledge/review.ts
CHANGED
|
@@ -175,7 +175,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
175
175
|
/** Files that failed for a reason that says nothing final about them, at the manifest's own bytes: owed, so the next review retries them. */
|
|
176
176
|
const unreadable = new Set<string>();
|
|
177
177
|
/** Consecutive transient failures by path at one hash (saved beside the owed record). */
|
|
178
|
-
const failures = new Map(detail.extractor.failures);
|
|
178
|
+
const failures = new Map(detail.extractor.failures ?? []);
|
|
179
179
|
const measured = new Map<string, number>();
|
|
180
180
|
// Read + binary check + extract run ahead with bounded concurrency (extraction only reads `knownKeys`,
|
|
181
181
|
// fixed above, and the content-hash extract cache); with `args.extractPool` the width is the pool's.
|
|
@@ -218,7 +218,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
218
218
|
measured.set(f.path, owedCalls(detail.extractor, f.path)); // learns nothing: keep what it was owed
|
|
219
219
|
// The ONE failure path (reviewFailure.ts): a transient failure keeps the re-check request and makes the file owed; only a proven-final
|
|
220
220
|
// one (or the third in a row at the same bytes) is answered with a terminal `[]`.
|
|
221
|
-
await recordFailure({ store, detail, stopped: () => runSignal.aborted, unreadable, failures, settledRecheck }, f, job);
|
|
221
|
+
if (await recordFailure({ store, detail, stopped: () => runSignal.aborted, unreadable, failures, settledRecheck }, f, job)) finished.add(f.path); // final: settled, not re-read while its bytes stand
|
|
222
222
|
return true;
|
|
223
223
|
}
|
|
224
224
|
failures.delete(f.path); // it read and extracted (or was decided): the run of failures at this hash ends
|
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
* - final: the manifest's bytes are gone (the hash moved), or the parser/extractor threw on them. `[]` is stored under the manifest's hash
|
|
8
8
|
* and the request is settled — unless an unchanged planned file still carries that hash (its content is readable: do not hide it);
|
|
9
9
|
* - transient at the manifest's own bytes: the request is kept and the path is made OWED, so the next normal review retries it;
|
|
10
|
-
* after {@link MAX_TRANSIENT_FAILURES} in a row at the same hash it is treated as final, so a file that never reads cannot hold a root forever
|
|
10
|
+
* after {@link MAX_TRANSIENT_FAILURES} in a row at the same hash it is treated as final, so a file that never reads cannot hold a root forever.
|
|
11
|
+
* A final failure is STICKY: the review counts the file as settled, so it is not re-read (or re-reported) until its bytes change or the extractor version moves;
|
|
11
12
|
* - never anything when the run was stopped.
|
|
12
13
|
*/
|
|
13
14
|
|
|
@@ -30,9 +31,10 @@ export interface FailureContext {
|
|
|
30
31
|
settledRecheck: (hash: string) => Promise<void>;
|
|
31
32
|
}
|
|
32
33
|
|
|
33
|
-
|
|
34
|
+
/** True when the failure was recorded as FINAL: the review then counts the file as settled, so it is not re-read (and re-reported) while its bytes stay as they are. */
|
|
35
|
+
export async function recordFailure(ctx: FailureContext, f: { path: string; hash: string }, job: Extract<Prefetch, { kind: 'read-error' | 'failed' }>): Promise<boolean> {
|
|
34
36
|
const known = ctx.detail.prior.get(f.path);
|
|
35
|
-
if (!known || ctx.stopped()) return;
|
|
37
|
+
if (!known || ctx.stopped()) return false;
|
|
36
38
|
const transient = job.kind === 'read-error' || job.transient === true;
|
|
37
39
|
if (known === f.hash && transient) {
|
|
38
40
|
const prev = ctx.failures.get(f.path);
|
|
@@ -40,12 +42,13 @@ export async function recordFailure(ctx: FailureContext, f: { path: string; hash
|
|
|
40
42
|
if (count < MAX_TRANSIENT_FAILURES) {
|
|
41
43
|
ctx.failures.set(f.path, { hash: known, count });
|
|
42
44
|
ctx.unreadable.add(f.path);
|
|
43
|
-
return;
|
|
45
|
+
return false;
|
|
44
46
|
}
|
|
45
47
|
}
|
|
46
48
|
ctx.failures.delete(f.path);
|
|
47
49
|
// An unchanged planned file that still carries `known` is readable content: a terminal `[]` would hide it.
|
|
48
|
-
if (ctx.detail.files.some((g) => g.path !== f.path && !g.changed && g.hash === known)) return;
|
|
50
|
+
if (ctx.detail.files.some((g) => g.path !== f.path && !g.changed && g.hash === known)) return true;
|
|
49
51
|
await putNoExtract(ctx.store, known);
|
|
50
52
|
await ctx.settledRecheck(known);
|
|
53
|
+
return true;
|
|
51
54
|
}
|
|
@@ -109,7 +109,7 @@ export function createPrefetch(c: PrefetchContext): (f: { path: string; hash: st
|
|
|
109
109
|
if (error instanceof BinaryContent) return { kind: 'binary' };
|
|
110
110
|
// Transient UNLESS proven final: only the parser or extractor throwing on these bytes (ExtractFailed) is. A read, a timeout, a crashed or
|
|
111
111
|
// disposed worker, a failing store, a stop: all say nothing final about the file.
|
|
112
|
-
return { kind: 'failed', reason: reasonOf(error), ...(error instanceof ExtractFailed && !c.signal.aborted ? {} : { transient: true as const }) };
|
|
112
|
+
return { kind: 'failed', reason: reasonOf(error), ...((error instanceof ExtractFailed || (error as { name?: unknown } | null)?.name === 'ExtractFailed') && !c.signal.aborted ? {} : { transient: true as const }) };
|
|
113
113
|
}
|
|
114
114
|
};
|
|
115
115
|
|
|
@@ -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
|
+
}
|
|
@@ -14,17 +14,24 @@
|
|
|
14
14
|
* inside a run; outside one, each awaited mutation has persisted when it resolves.
|
|
15
15
|
*
|
|
16
16
|
* PRD 41 A10: reads come from memory once loaded (never behind the mutation queue); rows live in
|
|
17
|
-
* per-root maps updated incrementally; with the optional `extractedLog` port the
|
|
18
|
-
* an append-only JSON Lines file instead of part of the snapshot.
|
|
17
|
+
* per-root maps (rowMemory.ts) updated incrementally; with the optional `extractedLog` port the
|
|
18
|
+
* extract cache is an append-only JSON Lines file (extractLogWriter.ts) instead of part of the snapshot.
|
|
19
|
+
*
|
|
20
|
+
* PRD 41 B4 (G03): with `opts.rows` ({@link RowPersistence}) the store persists only the rows that changed
|
|
21
|
+
* (dirty keys in rowDelta.ts) and `persistence` / `extractedLog` are not used. Construct it as
|
|
22
|
+
* `new LocalSnapshotStore(undefined, { rows })`; a `persistence` given beside `rows` is ignored.
|
|
19
23
|
*/
|
|
20
24
|
|
|
21
|
-
import type {
|
|
22
|
-
Extracted, KnowledgeStore, NodeRef, Scope, ScopeRecord, StoredFact, StoredRelation,
|
|
23
|
-
} from '../model.js';
|
|
25
|
+
import type { Extracted, KnowledgeStore, NodeRef, Scope, ScopeRecord, StoredFact, StoredRelation } from '../model.js';
|
|
24
26
|
import { canonicalJson, compareStr, pathOfRef } from '../refs.js';
|
|
25
|
-
import {
|
|
27
|
+
import { ExtractLogWriter } from './extractLogWriter.js';
|
|
28
|
+
import type { RowDelta, RowPersistence } from './rowDelta.js';
|
|
29
|
+
import { RowMemory } from './rowMemory.js';
|
|
30
|
+
import { RowSync } from './rowSync.js';
|
|
31
|
+
import { emptySnapshot, parse, stripUndefined, type KnowledgeSnapshot } from './snapshotFormat.js';
|
|
26
32
|
|
|
27
33
|
export type { KnowledgeSnapshot } from './snapshotFormat.js';
|
|
34
|
+
export type { RowChange, RowPersistence } from './rowDelta.js';
|
|
28
35
|
|
|
29
36
|
export interface SnapshotPersistence {
|
|
30
37
|
read(): Promise<string | undefined>;
|
|
@@ -46,8 +53,10 @@ export interface ExtractedLogPersistence {
|
|
|
46
53
|
}
|
|
47
54
|
|
|
48
55
|
export interface LocalSnapshotStoreOptions {
|
|
49
|
-
/** When given, the extract cache lives in this log and the snapshot omits `extracted`. */
|
|
56
|
+
/** When given, the extract cache lives in this log and the snapshot omits `extracted`. Ignored with `rows`. */
|
|
50
57
|
extractedLog?: ExtractedLogPersistence;
|
|
58
|
+
/** Row-level persistence (a SQLite file): only changed rows are written; `SnapshotPersistence` and `extractedLog` are not used. */
|
|
59
|
+
rows?: RowPersistence;
|
|
51
60
|
/** ISO clock for `staleAt`. Default `new Date().toISOString()`. */
|
|
52
61
|
now?(): string;
|
|
53
62
|
/** Inside `batched`, a mutation persists when this many ms passed since the last write (a crash loses at most this much). Default 30_000. */
|
|
@@ -56,27 +65,17 @@ export interface LocalSnapshotStoreOptions {
|
|
|
56
65
|
nowMs?(): number;
|
|
57
66
|
}
|
|
58
67
|
|
|
59
|
-
const relKey = (r: Pick<StoredRelation, 'from' | 'to' | 'kind'>) => `${r.from}\u0000${r.to}\u0000${r.kind}`;
|
|
60
|
-
|
|
61
|
-
type Index = Map<string, Set<string>>;
|
|
62
|
-
|
|
63
68
|
export class LocalSnapshotStore implements KnowledgeStore {
|
|
64
69
|
private loaded = false;
|
|
65
70
|
private loading: Promise<void> | undefined;
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
private readonly
|
|
69
|
-
private readonly
|
|
70
|
-
/**
|
|
71
|
-
private readonly
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
private readonly recheck = new Set<string>();
|
|
75
|
-
/** Extract entries not yet appended to the log. */
|
|
76
|
-
private pending = new Map<string, Extracted[]>();
|
|
77
|
-
/** The log's last line is torn (no newline), so the next append starts on a fresh line. */
|
|
78
|
-
private logTorn = false;
|
|
79
|
-
private readonly log: ExtractedLogPersistence | undefined;
|
|
71
|
+
/** Per-root rows and the extract cache (PRD 41 A10 rule 7). */
|
|
72
|
+
private mem = new RowMemory();
|
|
73
|
+
private readonly log: ExtractLogWriter | undefined;
|
|
74
|
+
private readonly rows: RowPersistence | undefined;
|
|
75
|
+
/** Row mode only: writes the changed rows, reloads, reads bodies lazily (rowSync.ts). */
|
|
76
|
+
private readonly sync: RowSync | undefined;
|
|
77
|
+
/** Row mode only: the keys changed since the last `apply`. */
|
|
78
|
+
private readonly delta: RowDelta | undefined;
|
|
80
79
|
/** Serializes mutations so two writers never interleave a read-modify-write. */
|
|
81
80
|
private queue: Promise<unknown> = Promise.resolve();
|
|
82
81
|
private readonly now: () => string;
|
|
@@ -89,14 +88,26 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
89
88
|
private persistedAt = 0;
|
|
90
89
|
/** Serializes snapshot writes; never rejects. */
|
|
91
90
|
private persisting: Promise<void> = Promise.resolve();
|
|
91
|
+
/** Steps queued or running on the persist chain. */
|
|
92
|
+
private steps = 0;
|
|
92
93
|
/** A background checkpoint in flight (at most one). */
|
|
93
94
|
private checkpointing: Promise<void> | undefined;
|
|
94
95
|
|
|
95
|
-
|
|
96
|
+
/** Row-persisted: no whole-snapshot port; only changed rows are written through `opts.rows`. */
|
|
97
|
+
constructor(persistence: undefined, opts: LocalSnapshotStoreOptions & { rows: RowPersistence });
|
|
98
|
+
/** Snapshot-persisted (the default): the whole canonical snapshot is written through `persistence`. */
|
|
99
|
+
constructor(persistence: SnapshotPersistence, opts?: LocalSnapshotStoreOptions);
|
|
100
|
+
constructor(private readonly persistence: SnapshotPersistence | undefined, opts: LocalSnapshotStoreOptions = {}) {
|
|
101
|
+
this.rows = opts.rows;
|
|
102
|
+
if (!this.rows && !persistence) throw new Error('LocalSnapshotStore: give a SnapshotPersistence or opts.rows');
|
|
103
|
+
this.sync = this.rows && new RowSync(this.rows, {
|
|
104
|
+
mem: () => this.mem, setMem: (m) => { this.mem = m; }, enqueue: (t) => this.enqueue(t), chain: (s) => this.onChain(s), inBatch: () => this.depth > 0, busy: () => this.steps > 0,
|
|
105
|
+
});
|
|
106
|
+
this.delta = this.sync?.delta;
|
|
96
107
|
this.now = opts.now ?? (() => new Date().toISOString());
|
|
97
108
|
this.nowMs = opts.nowMs ?? Date.now;
|
|
98
109
|
this.checkpointMs = opts.checkpointMs ?? 30_000;
|
|
99
|
-
this.log = opts.extractedLog;
|
|
110
|
+
this.log = !this.rows && opts.extractedLog ? new ExtractLogWriter(opts.extractedLog) : undefined;
|
|
100
111
|
}
|
|
101
112
|
|
|
102
113
|
/** Loads once; every later call is a no-op, so reads never wait on the mutation queue after the first. */
|
|
@@ -106,86 +117,51 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
106
117
|
return this.loading;
|
|
107
118
|
}
|
|
108
119
|
|
|
120
|
+
/** What a read waits for: the first load, then (row mode) a reload when another writer changed the store. */
|
|
121
|
+
private async fresh(): Promise<void> {
|
|
122
|
+
await this.load();
|
|
123
|
+
await this.sync?.sync();
|
|
124
|
+
}
|
|
125
|
+
|
|
109
126
|
private async doLoad(): Promise<void> {
|
|
110
|
-
const snapText = await this.persistence.read();
|
|
111
127
|
let snap: KnowledgeSnapshot;
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
await this.persistence
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
}
|
|
126
|
-
for (const [rootId, rows] of Object.entries(snap.relations)) {
|
|
127
|
-
this.relsOf(rootId);
|
|
128
|
-
if (Array.isArray(rows)) for (const r of rows) this.putRelation(rootId, r);
|
|
128
|
+
let logText: string | undefined;
|
|
129
|
+
if (this.rows) {
|
|
130
|
+
snap = (await this.rows.load()) ?? emptySnapshot();
|
|
131
|
+
} else {
|
|
132
|
+
const snapText = await this.persistence!.read();
|
|
133
|
+
try {
|
|
134
|
+
snap = parse(snapText);
|
|
135
|
+
} catch {
|
|
136
|
+
// Unreadable: never silently replaced. Its bytes are kept aside, then the store starts empty (the next review rebuilds).
|
|
137
|
+
await this.persistence!.keepAside?.(snapText!).catch(() => undefined);
|
|
138
|
+
snap = emptySnapshot();
|
|
139
|
+
}
|
|
140
|
+
logText = this.log ? await this.log.read() : undefined;
|
|
129
141
|
}
|
|
142
|
+
this.mem.fill(snap, !this.log);
|
|
130
143
|
if (this.log) {
|
|
131
|
-
|
|
132
|
-
for (const [h, e] of parsed.entries) this.extracted.set(h, e);
|
|
133
|
-
this.logTorn = !!logText && !logText.endsWith('\n');
|
|
134
|
-
await this.compactLog(parsed);
|
|
144
|
+
await this.log.load(logText, this.mem.extracted);
|
|
135
145
|
// An old snapshot still carrying the cache: move it into the log once; the next snapshot write omits it.
|
|
136
146
|
const legacy = Object.entries(snap.extracted ?? {});
|
|
137
147
|
if (legacy.length) {
|
|
138
148
|
for (const [h, e] of legacy) {
|
|
139
|
-
if (this.extracted.has(h)) continue;
|
|
140
|
-
this.extracted.set(h, e);
|
|
141
|
-
this.
|
|
149
|
+
if (this.mem.extracted.has(h)) continue;
|
|
150
|
+
this.mem.extracted.set(h, e);
|
|
151
|
+
this.log.queue(h, e);
|
|
142
152
|
}
|
|
143
153
|
this.dirty = true;
|
|
144
154
|
}
|
|
145
|
-
} else {
|
|
146
|
-
for (const [h, e] of Object.entries(snap.extracted ?? {})) this.extracted.set(h, e);
|
|
147
155
|
}
|
|
148
156
|
this.loaded = true;
|
|
149
157
|
}
|
|
150
158
|
|
|
151
|
-
/**
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
if (!this.log?.replace || parsed.deadBytes <= parsed.liveBytes) return;
|
|
158
|
-
try {
|
|
159
|
-
await this.log.replace([...parsed.liveLines.values()].join(''));
|
|
160
|
-
this.logTorn = false;
|
|
161
|
-
} catch { /* keep the uncompacted log */ }
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
private factsOf(rootId: string): Map<string, StoredFact> {
|
|
165
|
-
let m = this.factMaps.get(rootId);
|
|
166
|
-
if (!m) this.factMaps.set(rootId, m = new Map());
|
|
167
|
-
return m;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
private relsOf(rootId: string): Map<string, StoredRelation> {
|
|
171
|
-
let m = this.relMaps.get(rootId);
|
|
172
|
-
if (!m) this.relMaps.set(rootId, m = new Map());
|
|
173
|
-
return m;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/** Upserts a relation and indexes it under the source paths of both ends. */
|
|
177
|
-
private putRelation(rootId: string, r: StoredRelation): void {
|
|
178
|
-
const key = relKey(r);
|
|
179
|
-
this.relsOf(rootId).set(key, r);
|
|
180
|
-
let idx = this.relByPath.get(rootId);
|
|
181
|
-
if (!idx) this.relByPath.set(rootId, idx = new Map());
|
|
182
|
-
for (const ref of [r.from, r.to]) {
|
|
183
|
-
const p = pathOfRef(ref);
|
|
184
|
-
if (p === undefined) continue;
|
|
185
|
-
let keys = idx.get(p);
|
|
186
|
-
if (!keys) idx.set(p, keys = new Set());
|
|
187
|
-
keys.add(key);
|
|
188
|
-
}
|
|
159
|
+
/** Runs a step after the previous persist step (one at a time); the chain itself never rejects. */
|
|
160
|
+
private onChain<T>(step: () => Promise<T>): Promise<T> {
|
|
161
|
+
const run = this.persisting.then(step);
|
|
162
|
+
this.steps += 1;
|
|
163
|
+
this.persisting = run.then(() => undefined, () => undefined).then(() => { this.steps -= 1; });
|
|
164
|
+
return run;
|
|
189
165
|
}
|
|
190
166
|
|
|
191
167
|
private enqueue<T>(task: () => Promise<T>): Promise<T> {
|
|
@@ -195,48 +171,26 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
195
171
|
}
|
|
196
172
|
|
|
197
173
|
/**
|
|
198
|
-
* Appends
|
|
199
|
-
*
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const batch = this.pending;
|
|
204
|
-
this.pending = new Map();
|
|
205
|
-
let text = this.logTorn ? '\n' : '';
|
|
206
|
-
for (const [h, e] of batch) text += `${JSON.stringify({ h, e })}\n`;
|
|
207
|
-
try {
|
|
208
|
-
await this.log.append(text);
|
|
209
|
-
this.logTorn = false;
|
|
210
|
-
} catch (err) {
|
|
211
|
-
this.logTorn = true;
|
|
212
|
-
for (const [h, e] of batch) if (!this.pending.has(h)) this.pending.set(h, e);
|
|
213
|
-
throw err;
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* Appends new extract entries, then writes the snapshot if memory is ahead of it, one write at a time. It
|
|
219
|
-
* runs OUTSIDE the mutation queue: a write of a large snapshot (serialize + disk) must never hold up reads or
|
|
220
|
-
* the next mutation's in-memory apply (PRD 41 A10 — it did: every `getExtracted` waited out each checkpoint).
|
|
221
|
-
* The log goes first, so a snapshot that dropped a migrated cache never outlives its entries. A failed
|
|
222
|
-
* write leaves the snapshot dirty, so the next one retries it.
|
|
174
|
+
* Appends new extract entries, then writes the snapshot (or, in row mode, the changed rows) if memory is ahead of it,
|
|
175
|
+
* one write at a time. It runs OUTSIDE the mutation queue: a write of a large snapshot (serialize + disk) must never
|
|
176
|
+
* hold up reads or the next mutation's in-memory apply (PRD 41 A10 — it did: every `getExtracted` waited out each
|
|
177
|
+
* checkpoint). The log goes first, so a snapshot that dropped a migrated cache never outlives its entries. A failed
|
|
178
|
+
* write leaves the store dirty, so the next one retries it.
|
|
223
179
|
*/
|
|
224
180
|
private persistIfDirty(): Promise<void> {
|
|
225
|
-
|
|
181
|
+
return this.onChain(async () => {
|
|
226
182
|
if (!this.loaded) return;
|
|
227
|
-
await this.
|
|
183
|
+
await this.log?.flush();
|
|
228
184
|
if (!this.dirty) return;
|
|
229
185
|
this.dirty = false;
|
|
230
186
|
try {
|
|
231
|
-
await this.persistence
|
|
187
|
+
await (this.sync ? this.sync.apply() : this.persistence!.write(this.mem.serialize(this.log ? undefined : this.mem.extracted)));
|
|
232
188
|
} catch (err) {
|
|
233
189
|
this.dirty = true;
|
|
234
190
|
throw err;
|
|
235
191
|
}
|
|
236
192
|
this.persistedAt = this.nowMs();
|
|
237
193
|
});
|
|
238
|
-
this.persisting = run.catch(() => undefined);
|
|
239
|
-
return run;
|
|
240
194
|
}
|
|
241
195
|
|
|
242
196
|
/**
|
|
@@ -285,18 +239,18 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
285
239
|
}
|
|
286
240
|
|
|
287
241
|
async scopes(): Promise<ScopeRecord[]> {
|
|
288
|
-
await this.
|
|
289
|
-
return [...this.
|
|
242
|
+
await this.fresh();
|
|
243
|
+
return [...this.mem.scopes];
|
|
290
244
|
}
|
|
291
245
|
|
|
292
246
|
async facts(scope: Scope): Promise<StoredFact[]> {
|
|
293
|
-
await this.
|
|
294
|
-
return [...(this.
|
|
247
|
+
await this.fresh();
|
|
248
|
+
return [...(this.mem.facts.get(scope.rootId)?.values() ?? [])];
|
|
295
249
|
}
|
|
296
250
|
|
|
297
251
|
async relations(scope: Scope): Promise<StoredRelation[]> {
|
|
298
|
-
await this.
|
|
299
|
-
return [...(this.
|
|
252
|
+
await this.fresh();
|
|
253
|
+
return [...(this.mem.relations.get(scope.rootId)?.values() ?? [])];
|
|
300
254
|
}
|
|
301
255
|
|
|
302
256
|
write(batch: { scope: ScopeRecord; facts: StoredFact[]; relations: StoredRelation[] }): Promise<void> {
|
|
@@ -304,14 +258,15 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
304
258
|
if (bad) return Promise.reject(new Error('knowledge: extracted output is never stored'));
|
|
305
259
|
return this.mutate(() => {
|
|
306
260
|
const rootId = batch.scope.rootId;
|
|
307
|
-
const prior = this.
|
|
261
|
+
const prior = this.mem.scopes.find((x) => x.rootId === rootId);
|
|
308
262
|
const merged: ScopeRecord = { ...(prior ?? {}), ...stripUndefined(batch.scope) } as ScopeRecord;
|
|
309
|
-
this.
|
|
263
|
+
this.mem.scopes = [...this.mem.scopes.filter((x) => x.rootId !== rootId), merged];
|
|
264
|
+
this.delta?.mark('scopes', [rootId]);
|
|
310
265
|
|
|
311
|
-
const facts = this.factsOf(rootId);
|
|
312
|
-
for (const f of batch.facts) facts.set(f.key, { ...f });
|
|
313
|
-
this.relsOf(rootId);
|
|
314
|
-
for (const r of batch.relations) this.putRelation(rootId, { ...r });
|
|
266
|
+
const facts = this.mem.factsOf(rootId);
|
|
267
|
+
for (const f of batch.facts) { facts.set(f.key, { ...f }); this.delta?.mark('facts', [rootId, f.key]); }
|
|
268
|
+
this.mem.relsOf(rootId);
|
|
269
|
+
for (const r of batch.relations) { this.mem.putRelation(rootId, { ...r }); this.delta?.mark('relations', [rootId, r.from, r.to, r.kind]); }
|
|
315
270
|
});
|
|
316
271
|
}
|
|
317
272
|
|
|
@@ -319,77 +274,92 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
319
274
|
const path = pathOfRef(sourceRef);
|
|
320
275
|
return this.mutate(() => {
|
|
321
276
|
const at = this.now();
|
|
322
|
-
const rels = this.relsOf(scope.rootId);
|
|
323
|
-
const keys = path === undefined ? undefined : this.
|
|
277
|
+
const rels = this.mem.relsOf(scope.rootId);
|
|
278
|
+
const keys = path === undefined ? undefined : this.mem.relationKeysAt(scope.rootId, path);
|
|
324
279
|
for (const key of keys ?? []) {
|
|
325
280
|
const r = rels.get(key);
|
|
326
|
-
if (r && r.origin === 'model' && !r.staleAt && r.sourceHash !== currentHash)
|
|
281
|
+
if (r && r.origin === 'model' && !r.staleAt && r.sourceHash !== currentHash) {
|
|
282
|
+
rels.set(key, { ...r, staleAt: at });
|
|
283
|
+
this.delta?.mark('relations', [scope.rootId, r.from, r.to, r.kind]);
|
|
284
|
+
}
|
|
327
285
|
}
|
|
328
286
|
});
|
|
329
287
|
}
|
|
330
288
|
|
|
289
|
+
/** The cached entries of a content hash. In row mode a hash not in memory is read through `rows.loadExtracted` and kept. */
|
|
331
290
|
async getExtracted(hash: string): Promise<Extracted[] | undefined> {
|
|
332
|
-
await this.
|
|
333
|
-
return this.extracted.get(hash);
|
|
291
|
+
await this.fresh();
|
|
292
|
+
return this.sync ? this.sync.body(hash) : this.mem.extracted.get(hash);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Row mode: reads the bodies of these hashes through `rows.loadExtracted`, a chunk at a time. Otherwise a no-op (everything is in memory). */
|
|
296
|
+
async preloadExtracted(hashes: readonly string[]): Promise<void> {
|
|
297
|
+
if (!this.sync) return;
|
|
298
|
+
await this.fresh();
|
|
299
|
+
await this.sync.preload(hashes);
|
|
334
300
|
}
|
|
335
301
|
|
|
336
302
|
/** Asks the next review to re-check the files with these content hashes (persisted until {@link clearRecheck}). */
|
|
337
303
|
markRecheck(hashes: readonly string[]): Promise<void> {
|
|
338
304
|
// The snapshot is dirty only when the set really changed (a repeated mark costs no write).
|
|
339
|
-
return this.mutate(() => {
|
|
305
|
+
return this.mutate(() => {
|
|
306
|
+
for (const h of hashes) if (!this.mem.recheck.has(h)) { this.mem.recheck.add(h); this.dirty = true; this.delta?.mark('recheck', [h]); }
|
|
307
|
+
}, false);
|
|
340
308
|
}
|
|
341
309
|
|
|
342
310
|
async hasRecheck(hash: string): Promise<boolean> {
|
|
343
|
-
await this.
|
|
344
|
-
return this.recheck.has(hash);
|
|
311
|
+
await this.fresh();
|
|
312
|
+
return this.mem.recheck.has(hash);
|
|
345
313
|
}
|
|
346
314
|
|
|
347
315
|
async recheckHashes(): Promise<string[]> {
|
|
348
|
-
await this.
|
|
349
|
-
return [...this.recheck].sort(compareStr);
|
|
316
|
+
await this.fresh();
|
|
317
|
+
return [...this.mem.recheck].sort(compareStr);
|
|
350
318
|
}
|
|
351
319
|
|
|
352
320
|
/** Forgets hashes a review has handled. */
|
|
353
321
|
clearRecheck(hashes: readonly string[]): Promise<void> {
|
|
354
|
-
return this.mutate(() => {
|
|
322
|
+
return this.mutate(() => {
|
|
323
|
+
for (const h of hashes) if (this.mem.recheck.delete(h)) { this.dirty = true; this.delta?.mark('recheck', [h], true); }
|
|
324
|
+
}, false);
|
|
355
325
|
}
|
|
356
326
|
|
|
357
|
-
/** Every cached entry by content hash (the log's, else the snapshot's `extracted`), for a host that packs the cache. */
|
|
327
|
+
/** Every cached entry by content hash (the log's, else the snapshot's `extracted`), for a host that packs the cache. Row mode reads ALL bodies through `loadAllExtracted` (memory wins) and throws without it: never a partial map. */
|
|
358
328
|
async extractedEntries(): Promise<Record<string, Extracted[]>> {
|
|
359
|
-
await this.
|
|
360
|
-
return Object.fromEntries(this.extracted);
|
|
329
|
+
await this.fresh();
|
|
330
|
+
return Object.fromEntries(this.sync ? await this.sync.allBodies() : this.mem.extracted);
|
|
361
331
|
}
|
|
362
332
|
|
|
363
333
|
putExtracted(hash: string, extracted: Extracted[]): Promise<void> {
|
|
364
334
|
return this.mutate(() => {
|
|
365
335
|
// The same entry again (a second pass re-puts what the first stored) is skipped: no append, no dirty snapshot.
|
|
366
|
-
const prior = this.extracted.get(hash);
|
|
336
|
+
const prior = this.mem.extracted.get(hash);
|
|
367
337
|
if (prior && canonicalJson(prior) === canonicalJson(extracted)) return;
|
|
368
|
-
this.extracted.set(hash, extracted);
|
|
369
|
-
|
|
338
|
+
this.mem.extracted.set(hash, extracted);
|
|
339
|
+
this.sync?.forget(hash);
|
|
340
|
+
this.delta?.mark('extracted', [hash]);
|
|
341
|
+
if (this.log) this.log.queue(hash, extracted);
|
|
370
342
|
else this.dirty = true;
|
|
371
343
|
}, false);
|
|
372
344
|
}
|
|
373
345
|
|
|
374
|
-
/**
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
scopes: [...this.scopeList].sort((a, b) => compareStr(a.rootId, b.rootId)),
|
|
381
|
-
facts: rows(this.factMaps, (a, b) => compareStr(a.key, b.key)),
|
|
382
|
-
relations: rows(this.relMaps, (a, b) => compareStr(relKey(a), relKey(b))),
|
|
383
|
-
...(this.log ? {} : { extracted: Object.fromEntries(this.extracted) }),
|
|
384
|
-
...(this.recheck.size > 0 ? { recheck: [...this.recheck].sort(compareStr) } : {}),
|
|
385
|
-
});
|
|
346
|
+
/** See {@link canonicalDump}. Static so it can reach private state without widening the instance's public surface. */
|
|
347
|
+
static async dumpOf(store: LocalSnapshotStore): Promise<string> {
|
|
348
|
+
await store.fresh();
|
|
349
|
+
if (!store.sync) return store.mem.serialize(store.log ? undefined : store.mem.extracted);
|
|
350
|
+
const bodies = await store.sync.allBodies();
|
|
351
|
+
return store.mem.serialize(bodies);
|
|
386
352
|
}
|
|
387
353
|
}
|
|
388
354
|
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
355
|
+
/**
|
|
356
|
+
* The canonical text of a store's rows: byte-equal to what a snapshot-persisted store writes (without `extractedLog`, the
|
|
357
|
+
* extract cache included). The projection `packPush` / `portablePack` read. Row mode reads every body through `loadAllExtracted` and throws `knowledge_dump_needs_all_bodies` without it.
|
|
358
|
+
*/
|
|
359
|
+
export const canonicalDump = (store: LocalSnapshotStore): Promise<string> => LocalSnapshotStore.dumpOf(store);
|
|
392
360
|
|
|
393
|
-
function
|
|
394
|
-
|
|
361
|
+
export function localSnapshotStore(persistence: undefined, opts: LocalSnapshotStoreOptions & { rows: RowPersistence }): LocalSnapshotStore;
|
|
362
|
+
export function localSnapshotStore(persistence: SnapshotPersistence, opts?: LocalSnapshotStoreOptions): LocalSnapshotStore;
|
|
363
|
+
export function localSnapshotStore(persistence: SnapshotPersistence | undefined, opts?: LocalSnapshotStoreOptions): LocalSnapshotStore {
|
|
364
|
+
return new LocalSnapshotStore(persistence as SnapshotPersistence, opts);
|
|
395
365
|
}
|