@seanhogg/builderforce-memory 2026.10.75 → 2026.10.77
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/facts/factsHash.d.ts +27 -0
- package/dist/knowledge/facts/factsHash.d.ts.map +1 -0
- package/dist/knowledge/facts/factsHash.js +67 -0
- package/dist/knowledge/facts/factsHash.js.map +1 -0
- package/dist/knowledge/facts/fileFacts.d.ts +70 -12
- package/dist/knowledge/facts/fileFacts.d.ts.map +1 -1
- package/dist/knowledge/facts/fileFacts.js +42 -33
- package/dist/knowledge/facts/fileFacts.js.map +1 -1
- package/dist/knowledge/facts/guards.d.ts +101 -0
- package/dist/knowledge/facts/guards.d.ts.map +1 -0
- package/dist/knowledge/facts/guards.js +260 -0
- package/dist/knowledge/facts/guards.js.map +1 -0
- package/dist/knowledge/index.d.ts +9 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +7 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/rules/evaluateRules.d.ts.map +1 -1
- package/dist/knowledge/rules/evaluateRules.js +2 -1
- package/dist/knowledge/rules/evaluateRules.js.map +1 -1
- package/dist/knowledge/rules/factGraph.d.ts +2 -0
- package/dist/knowledge/rules/factGraph.d.ts.map +1 -1
- package/dist/knowledge/rules/factGraph.js +6 -2
- package/dist/knowledge/rules/factGraph.js.map +1 -1
- package/dist/knowledge/rules/factStore.d.ts +139 -0
- package/dist/knowledge/rules/factStore.d.ts.map +1 -0
- package/dist/knowledge/rules/factStore.js +252 -0
- package/dist/knowledge/rules/factStore.js.map +1 -0
- package/dist/stats/prng.d.ts +5 -1
- package/dist/stats/prng.d.ts.map +1 -1
- package/dist/stats/prng.js +11 -3
- package/dist/stats/prng.js.map +1 -1
- package/package.json +1 -1
- package/src/contract/exports.snapshot.json +14 -0
- package/src/contract/regression.prng.test.ts +126 -0
- package/src/contract/types.contract.test.ts +57 -2
- package/src/knowledge/facts/factsHash.test.ts +50 -0
- package/src/knowledge/facts/factsHash.ts +71 -0
- package/src/knowledge/facts/fileFacts.test.ts +2 -1
- package/src/knowledge/facts/fileFacts.ts +104 -36
- package/src/knowledge/facts/guards.test.ts +276 -0
- package/src/knowledge/facts/guards.ts +296 -0
- package/src/knowledge/index.ts +13 -1
- package/src/knowledge/rules/evaluateRules.ts +2 -1
- package/src/knowledge/rules/factGraph.ts +8 -2
- package/src/knowledge/rules/factStore.test.ts +303 -0
- package/src/knowledge/rules/factStore.ts +317 -0
- package/src/stats/prng.ts +11 -3
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/rules/factStore.test.ts — the FactStorePort contract (PRD 41 §B4, §B8.6) over the in-memory reference
|
|
3
|
+
* adapter: round trip, delta saves equal a scratch save, a stale `previous` never trusts identity, restored traces are
|
|
4
|
+
* honoured, an interrupted write leaves the previous manifest valid, mixed-generation loads retry, and the sweep.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { FileFacts } from '../facts/fileFacts.js';
|
|
8
|
+
import { factsHash, factsJson } from '../facts/factsHash.js';
|
|
9
|
+
import { derivedRowKey } from './evaluateRules.js';
|
|
10
|
+
import { buildFactGraph, factGraphDump, updateFactGraph } from './factGraph.js';
|
|
11
|
+
import {
|
|
12
|
+
factStoreDump, loadFactGraph, memoryFactStore, saveFactGraph, sweepFactStore, FACT_STORE_LOAD_ATTEMPTS, type FactStorePort,
|
|
13
|
+
} from './factStore.js';
|
|
14
|
+
import { emptyFacts, FIXTURE_RULES } from './rules.testkit.test-util.js';
|
|
15
|
+
|
|
16
|
+
const file = (content: string, over: Partial<FileFacts> = {}): FileFacts => ({ ...emptyFacts(content), ...over });
|
|
17
|
+
|
|
18
|
+
const tree = (): Array<readonly [string, FileFacts]> => [
|
|
19
|
+
['src/a.ts', file('ca', { imports: [{ specifier: './b', resolved: 'src/b.ts', names: [] }], exports: [{ name: 'a', kind: 'function', signatureHash: 'a' }] })],
|
|
20
|
+
['src/b.ts', file('cb', { calls: [{ callee: 'db.get', enclosing: 'b', awaited: true, inLoop: true, count: 1 }] })],
|
|
21
|
+
['src/auth.ts', file('cauth', { exports: [{ name: 'requireAuth', kind: 'function', signatureHash: 'r' }] })],
|
|
22
|
+
['src/routes.ts', file('cr', {
|
|
23
|
+
imports: [{ specifier: './a', resolved: 'src/a.ts', names: [] }],
|
|
24
|
+
entryPoints: [{ kind: 'http-route', key: 'GET /x', symbol: 'h', guards: [], inputs: [], chain: ['src/auth.ts'] }],
|
|
25
|
+
mounts: [{ prefix: '/api', target: './a', order: 1 }],
|
|
26
|
+
})],
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
const built = () => buildFactGraph(tree(), FIXTURE_RULES).graph;
|
|
30
|
+
const bFacts = () => tree()[1]![1];
|
|
31
|
+
|
|
32
|
+
describe('FactStorePort: round trip', () => {
|
|
33
|
+
it('save → load restores a graph with the same dump, at the saved version', async () => {
|
|
34
|
+
const graph = built();
|
|
35
|
+
const store = memoryFactStore();
|
|
36
|
+
const saved = await saveFactGraph(store, graph);
|
|
37
|
+
expect(saved.generation).toBe(1);
|
|
38
|
+
const loaded = await loadFactGraph(store);
|
|
39
|
+
expect([loaded.epoch, loaded.generation]).toEqual([saved.epoch, 1]);
|
|
40
|
+
expect(factGraphDump(loaded.graph)).toBe(factGraphDump(graph));
|
|
41
|
+
expect(await factStoreDump(store)).toBe(factGraphDump(graph));
|
|
42
|
+
const cheap = await loadFactGraph(store, { verify: 'manifest' });
|
|
43
|
+
expect(factGraphDump(cheap.graph)).toBe(factGraphDump(graph));
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('objects are stored as their canonical JSON under their facts hash', async () => {
|
|
47
|
+
const graph = built();
|
|
48
|
+
const store = memoryFactStore();
|
|
49
|
+
await saveFactGraph(store, graph);
|
|
50
|
+
const stored = await store.getObjects([...graph.objects.keys()]);
|
|
51
|
+
for (const [hash, facts] of graph.objects) expect(stored.get(hash)).toBe(factsJson(facts));
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('an object written before `mounts` / `uses` existed loads with them empty, under the same hash', async () => {
|
|
55
|
+
const store = memoryFactStore();
|
|
56
|
+
const old = file('old');
|
|
57
|
+
const hash = factsHash(old);
|
|
58
|
+
await store.putObjects(new Map([[hash, JSON.stringify(old)]])); // no mounts, no uses
|
|
59
|
+
const kinds = buildFactGraph([['x.ts', old]], []).graph.manifest.get('x.ts')!.kinds;
|
|
60
|
+
const { epoch } = await store.readVersion();
|
|
61
|
+
await store.writeManifest({ epoch, generation: 1, puts: new Map([['src/old.ts', { contentHash: 'old', factsHash: hash, kinds }]]), deletes: [] }, [], []);
|
|
62
|
+
const facts = (await loadFactGraph(store)).graph.objects.get(hash)!;
|
|
63
|
+
expect(facts.mounts).toEqual([]);
|
|
64
|
+
expect(facts.uses).toEqual([]);
|
|
65
|
+
expect(factsHash(facts)).toBe(hash);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
describe('FactStorePort: delta saves', () => {
|
|
70
|
+
it('an incremental save after an update equals a from-scratch save, and writes only the delta', async () => {
|
|
71
|
+
const g0 = built();
|
|
72
|
+
const incremental = memoryFactStore();
|
|
73
|
+
const s0 = await saveFactGraph(incremental, g0);
|
|
74
|
+
const g1 = updateFactGraph(g0, [{ path: 'src/b.ts', facts: { ...bFacts(), contentHash: 'cb2' } }, { path: 'src/new.ts', facts: file('cn') }], FIXTURE_RULES).graph;
|
|
75
|
+
const delta = await saveFactGraph(incremental, g1, s0);
|
|
76
|
+
expect(delta.generation).toBe(2);
|
|
77
|
+
expect(delta.puts).toEqual(['src/b.ts', 'src/new.ts']);
|
|
78
|
+
expect(delta.deletes).toEqual([]);
|
|
79
|
+
expect(delta.objects).toHaveLength(2);
|
|
80
|
+
expect(delta.derivedPuts.length).toBeLessThan(g1.derived.size);
|
|
81
|
+
|
|
82
|
+
const scratch = memoryFactStore();
|
|
83
|
+
await saveFactGraph(scratch, g1);
|
|
84
|
+
expect(await factStoreDump(incremental)).toBe(await factStoreDump(scratch));
|
|
85
|
+
expect(await factStoreDump(incremental)).toBe(factGraphDump(g1));
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('a delete removes the manifest entry and its derived rows; an unchanged graph saves nothing but the generation', async () => {
|
|
89
|
+
const g0 = built();
|
|
90
|
+
const store = memoryFactStore();
|
|
91
|
+
await saveFactGraph(store, g0);
|
|
92
|
+
const g1 = updateFactGraph(g0, [{ path: 'src/b.ts', facts: null }], FIXTURE_RULES).graph;
|
|
93
|
+
const delta = await saveFactGraph(store, g1);
|
|
94
|
+
expect(delta.deletes).toEqual(['src/b.ts']);
|
|
95
|
+
expect(delta.derivedDeletes.length).toBeGreaterThan(0);
|
|
96
|
+
expect(delta.derivedDeletes.every((k) => k.endsWith('\u0000src/b.ts'))).toBe(true);
|
|
97
|
+
expect(await factStoreDump(store)).toBe(factGraphDump(g1));
|
|
98
|
+
const again = await saveFactGraph(store, g1, delta);
|
|
99
|
+
expect([again.objects, again.puts, again.deletes, again.derivedPuts, again.derivedDeletes]).toEqual([[], [], [], [], []]);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('two writers never interleave: a stale generation or a foreign epoch is rejected', async () => {
|
|
103
|
+
const store = memoryFactStore();
|
|
104
|
+
const { epoch } = await saveFactGraph(store, built());
|
|
105
|
+
expect(() => store.writeManifest({ epoch, generation: 1, puts: new Map(), deletes: [] }, [], [])).toThrow(/fact_store_generation_conflict/);
|
|
106
|
+
expect(() => store.writeManifest({ epoch: 'other', generation: 2, puts: new Map(), deletes: [] }, [], [])).toThrow(/fact_store_generation_conflict/);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('writeManifest refuses an entry whose object is not stored', async () => {
|
|
110
|
+
const store = memoryFactStore();
|
|
111
|
+
const s = await saveFactGraph(store, built());
|
|
112
|
+
const entry = s.graph.manifest.get('src/a.ts')!;
|
|
113
|
+
expect(() => store.writeManifest({ epoch: s.epoch, generation: 2, puts: new Map([['src/z.ts', { ...entry, factsHash: 'nope' }]]), deletes: [] }, [], []))
|
|
114
|
+
.toThrow('fact_store_object_missing:nope');
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('regression (H1): another writer changed ONLY derived rows — a stale previous does not trust identity', async () => {
|
|
118
|
+
const g0 = built();
|
|
119
|
+
const store = memoryFactStore();
|
|
120
|
+
const s0 = await saveFactGraph(store, g0);
|
|
121
|
+
// Another writer: same manifest, one derived row rewritten.
|
|
122
|
+
const key = derivedRowKey('export-count', 'src/auth.ts');
|
|
123
|
+
const row = g0.derived.get(key)!;
|
|
124
|
+
await store.writeManifest({ epoch: s0.epoch, generation: 2, puts: new Map(), deletes: [] }, [{ ...row, inputs: 'tampered', findings: [] }], []);
|
|
125
|
+
// Our save, from the stale previous (generation 1), editing a different file.
|
|
126
|
+
const g1 = updateFactGraph(g0, [{ path: 'src/b.ts', facts: { ...bFacts(), contentHash: 'cb2' } }], FIXTURE_RULES).graph;
|
|
127
|
+
expect(g1.derived.get(key)).toBe(row); // identity would say "unchanged"
|
|
128
|
+
await saveFactGraph(store, g1, s0);
|
|
129
|
+
expect(await factStoreDump(store)).toBe(factGraphDump(g1));
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it('a reset store is never mistaken for the old one, even at the same generation (only the epoch tells them apart)', async () => {
|
|
133
|
+
const g0 = built();
|
|
134
|
+
const store = memoryFactStore();
|
|
135
|
+
const s0 = await saveFactGraph(store, g0);
|
|
136
|
+
expect(s0.generation).toBe(1);
|
|
137
|
+
await store.reset();
|
|
138
|
+
// The reset store reaches generation 1 again, with different derived rows than s0 saw.
|
|
139
|
+
const other = updateFactGraph(g0, [{ path: 'src/new.ts', facts: file('cn') }], FIXTURE_RULES).graph;
|
|
140
|
+
const s1 = await saveFactGraph(store, other);
|
|
141
|
+
expect(s1.generation).toBe(s0.generation);
|
|
142
|
+
expect(s1.epoch).not.toBe(s0.epoch);
|
|
143
|
+
// A save from the stale s0 (same generation, old epoch) must not trust identity: g's rows equal s0's by identity,
|
|
144
|
+
// so an identity diff would write nothing for them and leave `other`'s rows behind.
|
|
145
|
+
const g = updateFactGraph(g0, [], FIXTURE_RULES).graph;
|
|
146
|
+
await saveFactGraph(store, g, s0);
|
|
147
|
+
expect(await factStoreDump(store)).toBe(factGraphDump(g));
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
describe('FactStorePort: restored traces are honoured', () => {
|
|
152
|
+
it('load → update with no change reuses every row', async () => {
|
|
153
|
+
const store = memoryFactStore();
|
|
154
|
+
await saveFactGraph(store, built());
|
|
155
|
+
const { graph } = await loadFactGraph(store);
|
|
156
|
+
const update = updateFactGraph(graph, [], FIXTURE_RULES);
|
|
157
|
+
expect(update.trace.length).toBeGreaterThan(0);
|
|
158
|
+
expect(update.trace.filter((t) => t.outcome === 'ran')).toEqual([]);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('load → a content-only edit reruns only the content-reading row of that file (early cutoff across a restart)', async () => {
|
|
162
|
+
const store = memoryFactStore();
|
|
163
|
+
await saveFactGraph(store, built());
|
|
164
|
+
const { graph } = await loadFactGraph(store);
|
|
165
|
+
const update = updateFactGraph(graph, [{ path: 'src/b.ts', facts: { ...bFacts(), contentHash: 'cb-comment-edit' } }], FIXTURE_RULES);
|
|
166
|
+
expect(update.trace.filter((t) => t.outcome === 'ran')).toEqual([{ rule: 'content-tag', focus: 'src/b.ts', outcome: 'ran' }]);
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
describe('FactStorePort: crash safety and corruption', () => {
|
|
171
|
+
it('a write interrupted between the object puts and the manifest leaves the previous manifest valid', async () => {
|
|
172
|
+
const g0 = built();
|
|
173
|
+
const store = memoryFactStore();
|
|
174
|
+
const s0 = await saveFactGraph(store, g0);
|
|
175
|
+
const before = await factStoreDump(store);
|
|
176
|
+
|
|
177
|
+
const crashing: FactStorePort = { ...store, writeManifest: () => { throw new Error('crash'); } };
|
|
178
|
+
const g1 = updateFactGraph(g0, [{ path: 'src/new.ts', facts: file('cn') }], FIXTURE_RULES).graph;
|
|
179
|
+
await expect(saveFactGraph(crashing, g1, s0)).rejects.toThrow('crash');
|
|
180
|
+
|
|
181
|
+
expect(store.objectHashes()).toContain(g1.manifest.get('src/new.ts')!.factsHash);
|
|
182
|
+
expect(await factStoreDump(store)).toBe(before);
|
|
183
|
+
expect(factGraphDump((await loadFactGraph(store)).graph)).toBe(factGraphDump(g0));
|
|
184
|
+
|
|
185
|
+
await saveFactGraph(store, g1, s0);
|
|
186
|
+
expect(await factStoreDump(store)).toBe(factGraphDump(g1));
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it('objects are write-once', async () => {
|
|
190
|
+
const store = memoryFactStore();
|
|
191
|
+
await store.putObjects(new Map([['h', '{"a":1}']]));
|
|
192
|
+
await store.putObjects(new Map([['h', '{"a":2}']]));
|
|
193
|
+
expect((await store.getObjects(['h'])).get('h')).toBe('{"a":1}');
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
it('an object whose bytes no longer hash to its address is refused by a full load', async () => {
|
|
197
|
+
const g0 = built();
|
|
198
|
+
const store = memoryFactStore();
|
|
199
|
+
const hash = g0.manifest.get('src/auth.ts')!.factsHash;
|
|
200
|
+
await store.putObjects(new Map([[hash, factsJson(file('cauth', { exports: [{ name: 'other', kind: 'function', signatureHash: 'o' }] }))]]));
|
|
201
|
+
await saveFactGraph(store, g0);
|
|
202
|
+
await expect(loadFactGraph(store)).rejects.toThrow(`fact_store_object_corrupt:${hash}`);
|
|
203
|
+
// `manifest` verification trusts the address but still checks the kind hashes.
|
|
204
|
+
await expect(loadFactGraph(store, { verify: 'manifest' })).rejects.toThrow('fact_store_manifest_corrupt:src/auth.ts');
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it('bad JSON is fact_store_object_corrupt; the recovery is reset() and a rebuild', async () => {
|
|
208
|
+
const g0 = built();
|
|
209
|
+
const store = memoryFactStore();
|
|
210
|
+
const hash = g0.manifest.get('src/a.ts')!.factsHash;
|
|
211
|
+
await store.putObjects(new Map([[hash, '{not json']]));
|
|
212
|
+
await saveFactGraph(store, g0);
|
|
213
|
+
await expect(loadFactGraph(store)).rejects.toThrow(`fact_store_object_corrupt:${hash}`);
|
|
214
|
+
await store.reset();
|
|
215
|
+
await saveFactGraph(store, g0);
|
|
216
|
+
expect(await factStoreDump(store)).toBe(factGraphDump(g0));
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it('a derived row stored under the wrong key is fact_store_derived_corrupt', async () => {
|
|
220
|
+
const g0 = built();
|
|
221
|
+
const store = memoryFactStore();
|
|
222
|
+
await saveFactGraph(store, g0);
|
|
223
|
+
const port: FactStorePort = { ...store, derivedRows: () => new Map([['wrong', [...g0.derived.values()][0]!]]) };
|
|
224
|
+
await expect(loadFactGraph(port)).rejects.toThrow('fact_store_derived_corrupt:wrong');
|
|
225
|
+
});
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
describe('FactStorePort: mixed-generation loads', () => {
|
|
229
|
+
it('a write that lands mid-load makes the load retry, and the result is one generation', async () => {
|
|
230
|
+
const g0 = built();
|
|
231
|
+
const store = memoryFactStore();
|
|
232
|
+
const s0 = await saveFactGraph(store, g0);
|
|
233
|
+
const g1 = updateFactGraph(g0, [{ path: 'src/new.ts', facts: file('cn') }], FIXTURE_RULES).graph;
|
|
234
|
+
let fired = false;
|
|
235
|
+
const racing: FactStorePort = {
|
|
236
|
+
...store,
|
|
237
|
+
derivedRows: async () => {
|
|
238
|
+
if (!fired) { fired = true; await saveFactGraph(store, g1, s0); }
|
|
239
|
+
return store.derivedRows();
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
const loaded = await loadFactGraph(racing);
|
|
243
|
+
expect(loaded.generation).toBe(2);
|
|
244
|
+
expect(factGraphDump(loaded.graph)).toBe(factGraphDump(g1));
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
it('a store that keeps moving fails the load with a conflict after the bounded attempts', async () => {
|
|
248
|
+
const store = memoryFactStore();
|
|
249
|
+
await saveFactGraph(store, built());
|
|
250
|
+
let reads = 0;
|
|
251
|
+
const moving: FactStorePort = { ...store, readVersion: () => ({ epoch: 'e', generation: ++reads }) };
|
|
252
|
+
await expect(loadFactGraph(moving)).rejects.toThrow('fact_store_generation_conflict:load');
|
|
253
|
+
expect(reads).toBe(FACT_STORE_LOAD_ATTEMPTS);
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
describe('FactStorePort: sweep', () => {
|
|
258
|
+
it('removes only unreferenced objects and bumps the generation', async () => {
|
|
259
|
+
const g0 = built();
|
|
260
|
+
const store = memoryFactStore();
|
|
261
|
+
await saveFactGraph(store, g0);
|
|
262
|
+
await store.putObjects(new Map([['orphan', '{}']]));
|
|
263
|
+
expect(await sweepFactStore(store)).toBe(1);
|
|
264
|
+
expect(store.objectHashes()).not.toContain('orphan');
|
|
265
|
+
expect((await store.readVersion()).generation).toBe(2);
|
|
266
|
+
expect(await factStoreDump(store)).toBe(factGraphDump(g0));
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
it('a no-op sweep leaves the version unchanged', async () => {
|
|
270
|
+
const store = memoryFactStore();
|
|
271
|
+
const s0 = await saveFactGraph(store, built());
|
|
272
|
+
expect(await sweepFactStore(store)).toBe(0);
|
|
273
|
+
expect(await store.readVersion()).toEqual({ epoch: s0.epoch, generation: s0.generation });
|
|
274
|
+
// So a writer holding s0 is not disturbed by it.
|
|
275
|
+
const again = await saveFactGraph(store, s0.graph, s0);
|
|
276
|
+
expect(again.generation).toBe(s0.generation + 1);
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it('sweep vs writer:the writer\'s objects are swept, its manifest write conflicts, and the retry re-puts them', async () => {
|
|
280
|
+
const g0 = built();
|
|
281
|
+
const store = memoryFactStore();
|
|
282
|
+
const s0 = await saveFactGraph(store, g0);
|
|
283
|
+
const change = [{ path: 'src/new.ts', facts: file('cn') }];
|
|
284
|
+
const g1 = updateFactGraph(g0, change, FIXTURE_RULES).graph;
|
|
285
|
+
const newHash = g1.manifest.get('src/new.ts')!.factsHash;
|
|
286
|
+
// The sweep runs between the writer's object puts and its manifest write.
|
|
287
|
+
const raced: FactStorePort = {
|
|
288
|
+
...store,
|
|
289
|
+
writeManifest: async (delta, puts, deletes) => {
|
|
290
|
+
expect(await sweepFactStore(store)).toBe(1);
|
|
291
|
+
expect(store.objectHashes()).not.toContain(newHash);
|
|
292
|
+
return store.writeManifest(delta, puts, deletes);
|
|
293
|
+
},
|
|
294
|
+
};
|
|
295
|
+
await expect(saveFactGraph(raced, g1, s0)).rejects.toThrow(/fact_store_generation_conflict/);
|
|
296
|
+
// The documented recovery: load, re-apply the pending changes, save with the loaded version.
|
|
297
|
+
const loaded = await loadFactGraph(store);
|
|
298
|
+
const retried = updateFactGraph(loaded.graph, change, FIXTURE_RULES).graph;
|
|
299
|
+
const s1 = await saveFactGraph(store, retried, loaded);
|
|
300
|
+
expect(s1.objects).toEqual([newHash]);
|
|
301
|
+
expect(await factStoreDump(store)).toBe(factGraphDump(g1));
|
|
302
|
+
});
|
|
303
|
+
});
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/rules/factStore.ts — the FACT STORE PORT (PRD 41 §B4) and the pure functions that persist, restore and sweep
|
|
3
|
+
* a {@link FactGraph} through it. No I/O here; {@link memoryFactStore} is the in-memory reference adapter.
|
|
4
|
+
*
|
|
5
|
+
* The graph maps onto the port 1:1:
|
|
6
|
+
* - OBJECTS: each `FileFacts` as its canonical JSON (`factsJson`) under its content address `factsHash`. Write-once.
|
|
7
|
+
* - MANIFEST: path → {@link FactManifestEntry} (`factsHash`, `contentHash`, kind hashes), stamped with a
|
|
8
|
+
* {@link FactStoreVersion}: an `epoch` (a random id minted when the store is created or reset) and a `generation`
|
|
9
|
+
* bumped by every manifest write and every sweep.
|
|
10
|
+
* - DERIVED: each {@link DerivedRow} under {@link derivedRowKey}, carrying its input-hash trace (`inputs`).
|
|
11
|
+
*
|
|
12
|
+
* Commit order: objects first, then the manifest delta and the derived puts/deletes in ONE transaction (`writeManifest`,
|
|
13
|
+
* compare-and-swap on the version). A write interrupted between the two leaves the previous manifest valid — it references
|
|
14
|
+
* only objects that already existed — and at worst unreferenced objects, which {@link sweepFactStore} removes.
|
|
15
|
+
*
|
|
16
|
+
* ADAPTERS:
|
|
17
|
+
* - Node (VSIX, on-prem): the G03 SQLite store (`localRecordTransaction`): an `extracted(hash PRIMARY KEY, json)` table
|
|
18
|
+
* plus manifest, derived and version rows in one `index.sqlite`. `writeManifest` and `sweepObjects` run in ONE
|
|
19
|
+
* `BEGIN IMMEDIATE` transaction each (the write lock is taken before the version is compared, so two processes never
|
|
20
|
+
* both pass the check). Adapter-private columns (stat, git blob id) never cross the port and never enter the dump (§B8.3).
|
|
21
|
+
* - Worker: the port needs a transactional compare-and-swap over manifest + derived. Put it behind a Durable Object
|
|
22
|
+
* (transactional storage), or keep manifest + derived as ONE R2 object written with an `onlyIf` etag precondition and
|
|
23
|
+
* the objects as R2 objects under their hash. Plain KV (eventually consistent, no CAS) cannot implement this port.
|
|
24
|
+
*
|
|
25
|
+
* HOST CONTRACT (recovery):
|
|
26
|
+
* - Saves to one store are SERIALIZED within a process (one writer queue per store); the version CAS guards only against
|
|
27
|
+
* other processes.
|
|
28
|
+
* - `fact_store_generation_conflict` (another writer, or a sweep, moved the store): `loadFactGraph`, re-apply the pending
|
|
29
|
+
* `FactChange`s with `updateFactGraph`, then `saveFactGraph` with the loaded {@link StoredFactGraph}; retry a bounded
|
|
30
|
+
* number of times (e.g. 3), then give up until the next change.
|
|
31
|
+
* - `fact_store_object_missing` / `fact_store_object_corrupt` / `fact_store_manifest_corrupt` / `fact_store_derived_corrupt`:
|
|
32
|
+
* the store is a disposable cache (§B1: it rebuilds to the same bytes) — call `reset()` and rebuild from the files.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
import { canonicalJson, compareStr } from '../refs.js';
|
|
36
|
+
import { readFileFacts, type FileFacts } from '../facts/fileFacts.js';
|
|
37
|
+
import { factKindHashes, factsHash, factsJson } from '../facts/factsHash.js';
|
|
38
|
+
import { derivedRowKey, type DerivedRow } from './evaluateRules.js';
|
|
39
|
+
import { factGraphDump, sameManifestEntry, type FactGraph, type FactManifestEntry } from './factGraph.js';
|
|
40
|
+
|
|
41
|
+
/** A value or a promise of it: the SQLite adapter is synchronous, the Durable Object / R2 one is not. */
|
|
42
|
+
export type Awaitable<T> = T | Promise<T>;
|
|
43
|
+
|
|
44
|
+
/** Which store (`epoch`, minted on create and on `reset()`) and which state of it (`generation`, 0 when empty). */
|
|
45
|
+
export interface FactStoreVersion {
|
|
46
|
+
epoch: string;
|
|
47
|
+
generation: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The stored manifest: path → entry, at a version. */
|
|
51
|
+
export interface FactStoreManifest extends FactStoreVersion {
|
|
52
|
+
files: ReadonlyMap<string, FactManifestEntry>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** One manifest write: the entries put and the paths deleted, committed as `generation` (stored + 1) of `epoch`. */
|
|
56
|
+
export interface FactManifestDelta extends FactStoreVersion {
|
|
57
|
+
puts: ReadonlyMap<string, FactManifestEntry>;
|
|
58
|
+
deletes: readonly string[];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface FactStorePort {
|
|
62
|
+
/** The stored JSON of each hash present (absent hashes are left out). */
|
|
63
|
+
getObjects(hashes: readonly string[]): Awaitable<ReadonlyMap<string, string>>;
|
|
64
|
+
/** Stores objects (hash → JSON). WRITE-ONCE: an existing hash is left as it is. */
|
|
65
|
+
putObjects(objects: ReadonlyMap<string, string>): Awaitable<void>;
|
|
66
|
+
/** The version alone (cheap): what a load re-reads to detect a write that landed under it. */
|
|
67
|
+
readVersion(): Awaitable<FactStoreVersion>;
|
|
68
|
+
readManifest(): Awaitable<FactStoreManifest>;
|
|
69
|
+
/**
|
|
70
|
+
* ONE transaction: compares the version (`manifest.epoch` must be the stored epoch and `manifest.generation` the stored
|
|
71
|
+
* generation + 1, else `fact_store_generation_conflict`), checks that every put's object exists (else
|
|
72
|
+
* `fact_store_object_missing`), applies the manifest delta, puts the derived rows (by {@link derivedRowKey}) and
|
|
73
|
+
* deletes the derived keys.
|
|
74
|
+
*/
|
|
75
|
+
writeManifest(manifest: FactManifestDelta, derivedPuts: readonly DerivedRow[], derivedDeletes: readonly string[]): Awaitable<void>;
|
|
76
|
+
/** Every stored derived row by its key (bulk; the load path). */
|
|
77
|
+
derivedRows(): Awaitable<ReadonlyMap<string, DerivedRow>>;
|
|
78
|
+
/**
|
|
79
|
+
* ONE transaction: compares the version with `expected` (else `fact_store_generation_conflict`) and deletes every object
|
|
80
|
+
* the manifest does not reference; when it deleted any, it bumps the generation (a no-op sweep leaves the version as it
|
|
81
|
+
* was). Returns how many it deleted. The bump makes a writer that put objects before the sweep conflict on its
|
|
82
|
+
* `writeManifest`, so it re-puts them on retry.
|
|
83
|
+
*/
|
|
84
|
+
sweepObjects(expected: FactStoreVersion): Awaitable<number>;
|
|
85
|
+
/** Drops everything and mints a new epoch at generation 0 (the recovery for a corrupt store). */
|
|
86
|
+
reset(): Awaitable<void>;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A graph and the store version it was loaded or saved at: what a later save diffs against. */
|
|
90
|
+
export interface StoredFactGraph extends FactStoreVersion {
|
|
91
|
+
graph: FactGraph;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** What a save wrote, and the stored graph to pass as `previous` to the next save. */
|
|
95
|
+
export interface FactStoreSaveResult extends StoredFactGraph {
|
|
96
|
+
/** Objects put (hashes, sorted). */
|
|
97
|
+
objects: string[];
|
|
98
|
+
/** Manifest paths put and deleted (sorted). */
|
|
99
|
+
puts: string[];
|
|
100
|
+
deletes: string[];
|
|
101
|
+
/** Derived keys put and deleted (sorted). */
|
|
102
|
+
derivedPuts: string[];
|
|
103
|
+
derivedDeletes: string[];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const rowJson = (row: DerivedRow) => canonicalJson(row);
|
|
107
|
+
const sameVersion = (a: FactStoreVersion, b: FactStoreVersion) => a.epoch === b.epoch && a.generation === b.generation;
|
|
108
|
+
const conflict = (why: string) => new Error(`fact_store_generation_conflict:${why}`);
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Persists `graph`, writing ONLY the delta against what the store holds: the objects of new or changed manifest entries,
|
|
112
|
+
* the manifest entries that moved, the derived rows that moved and the keys that went away. Derived rows are diffed by
|
|
113
|
+
* identity against `previous.graph` (a reused row is the same object) ONLY when `previous` is at the stored epoch and
|
|
114
|
+
* generation; otherwise against the stored rows. Rejects `fact_store_generation_conflict` when another writer committed
|
|
115
|
+
* in between (see the recovery contract in the header).
|
|
116
|
+
*/
|
|
117
|
+
export async function saveFactGraph(port: FactStorePort, graph: FactGraph, previous?: StoredFactGraph): Promise<FactStoreSaveResult> {
|
|
118
|
+
const stored = await port.readManifest();
|
|
119
|
+
|
|
120
|
+
const puts = new Map<string, FactManifestEntry>();
|
|
121
|
+
for (const [path, e] of graph.manifest) if (!sameManifestEntry(e, stored.files.get(path))) puts.set(path, e);
|
|
122
|
+
const deletes = [...stored.files.keys()].filter((p) => !graph.manifest.has(p)).sort(compareStr);
|
|
123
|
+
|
|
124
|
+
const objects = [...new Set([...puts.values()].map((e) => e.factsHash))].sort(compareStr);
|
|
125
|
+
if (objects.length > 0) {
|
|
126
|
+
const jsons = new Map<string, string>();
|
|
127
|
+
for (const hash of objects) {
|
|
128
|
+
const facts = graph.objects.get(hash);
|
|
129
|
+
if (!facts) throw new Error(`fact_store_object_missing:${hash}`);
|
|
130
|
+
jsons.set(hash, factsJson(facts));
|
|
131
|
+
}
|
|
132
|
+
await port.putObjects(jsons);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const derivedPuts: DerivedRow[] = [];
|
|
136
|
+
let derivedDeletes: string[];
|
|
137
|
+
if (previous && sameVersion(previous, stored)) {
|
|
138
|
+
for (const [key, row] of graph.derived) if (previous.graph.derived.get(key) !== row) derivedPuts.push(row);
|
|
139
|
+
derivedDeletes = [...previous.graph.derived.keys()].filter((k) => !graph.derived.has(k));
|
|
140
|
+
} else {
|
|
141
|
+
const rows = await port.derivedRows();
|
|
142
|
+
for (const [key, row] of graph.derived) {
|
|
143
|
+
const prior = rows.get(key);
|
|
144
|
+
if (!prior || rowJson(prior) !== rowJson(row)) derivedPuts.push(row);
|
|
145
|
+
}
|
|
146
|
+
derivedDeletes = [...rows.keys()].filter((k) => !graph.derived.has(k));
|
|
147
|
+
}
|
|
148
|
+
derivedPuts.sort((a, b) => compareStr(derivedRowKey(a.rule, a.focus), derivedRowKey(b.rule, b.focus)));
|
|
149
|
+
derivedDeletes.sort(compareStr);
|
|
150
|
+
|
|
151
|
+
const generation = stored.generation + 1;
|
|
152
|
+
await port.writeManifest({ epoch: stored.epoch, generation, puts, deletes }, derivedPuts, derivedDeletes);
|
|
153
|
+
return {
|
|
154
|
+
epoch: stored.epoch,
|
|
155
|
+
generation,
|
|
156
|
+
graph,
|
|
157
|
+
objects,
|
|
158
|
+
puts: [...puts.keys()].sort(compareStr),
|
|
159
|
+
deletes,
|
|
160
|
+
derivedPuts: derivedPuts.map((r) => derivedRowKey(r.rule, r.focus)),
|
|
161
|
+
derivedDeletes,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export interface LoadFactGraphOptions {
|
|
166
|
+
/**
|
|
167
|
+
* `full` (default; tests, the oracle): every object must hash to its address, and every manifest entry must match its
|
|
168
|
+
* object. `manifest`: trusts the stored address and checks only each entry's content hash and kind hashes against its
|
|
169
|
+
* object (cheaper on a large store; a corruption that leaves those intact goes unnoticed).
|
|
170
|
+
*/
|
|
171
|
+
verify?: 'full' | 'manifest';
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** How many times a load retries when a write lands under it before rejecting `fact_store_generation_conflict:load`. */
|
|
175
|
+
export const FACT_STORE_LOAD_ATTEMPTS = 3;
|
|
176
|
+
|
|
177
|
+
async function loadOnce(port: FactStorePort, stored: FactStoreManifest, verify: 'full' | 'manifest'): Promise<FactGraph> {
|
|
178
|
+
const hashes = [...new Set([...stored.files.values()].map((e) => e.factsHash))].sort(compareStr);
|
|
179
|
+
const raw = await port.getObjects(hashes);
|
|
180
|
+
const objects = new Map<string, FileFacts>();
|
|
181
|
+
for (const hash of hashes) {
|
|
182
|
+
const json = raw.get(hash);
|
|
183
|
+
if (json === undefined) throw new Error(`fact_store_object_missing:${hash}`);
|
|
184
|
+
let facts: FileFacts;
|
|
185
|
+
try {
|
|
186
|
+
facts = readFileFacts(JSON.parse(json) as FileFacts);
|
|
187
|
+
} catch {
|
|
188
|
+
throw new Error(`fact_store_object_corrupt:${hash}`);
|
|
189
|
+
}
|
|
190
|
+
if (verify === 'full' && factsHash(facts) !== hash) throw new Error(`fact_store_object_corrupt:${hash}`);
|
|
191
|
+
objects.set(hash, facts);
|
|
192
|
+
}
|
|
193
|
+
const manifest = new Map<string, FactManifestEntry>();
|
|
194
|
+
for (const path of [...stored.files.keys()].sort(compareStr)) {
|
|
195
|
+
const e = stored.files.get(path)!;
|
|
196
|
+
const facts = objects.get(e.factsHash)!;
|
|
197
|
+
const entry: FactManifestEntry = { contentHash: facts.contentHash, factsHash: e.factsHash, kinds: factKindHashes(facts) };
|
|
198
|
+
if (!sameManifestEntry(e, entry)) throw new Error(`fact_store_manifest_corrupt:${path}`);
|
|
199
|
+
manifest.set(path, entry);
|
|
200
|
+
}
|
|
201
|
+
const derived = new Map<string, DerivedRow>();
|
|
202
|
+
const rows = await port.derivedRows();
|
|
203
|
+
for (const key of [...rows.keys()].sort(compareStr)) {
|
|
204
|
+
const row = rows.get(key)!;
|
|
205
|
+
if (derivedRowKey(row.rule, row.focus) !== key) throw new Error(`fact_store_derived_corrupt:${key}`);
|
|
206
|
+
derived.set(key, row);
|
|
207
|
+
}
|
|
208
|
+
return { manifest, objects, derived };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Restores the graph the store holds, with the version it was read at: the manifest, every referenced object (read through
|
|
213
|
+
* `readFileFacts`, so an object written before an additive field existed reads with that field empty) and every derived
|
|
214
|
+
* row with its trace. The result continues under `updateFactGraph` with early cutoff intact: a row whose trace still holds
|
|
215
|
+
* is reused, not rerun. The version is re-read after the rows: a write that landed mid-load (or a sweep that removed an
|
|
216
|
+
* object it was about to read) retries, up to {@link FACT_STORE_LOAD_ATTEMPTS}, so a graph never mixes generations (§B8.4).
|
|
217
|
+
* Throws the corruption errors of the header when the store itself is bad.
|
|
218
|
+
*/
|
|
219
|
+
export async function loadFactGraph(port: FactStorePort, opts: LoadFactGraphOptions = {}): Promise<StoredFactGraph> {
|
|
220
|
+
const verify = opts.verify ?? 'full';
|
|
221
|
+
for (let attempt = 0; attempt < FACT_STORE_LOAD_ATTEMPTS; attempt++) {
|
|
222
|
+
const stored = await port.readManifest();
|
|
223
|
+
let graph: FactGraph;
|
|
224
|
+
try {
|
|
225
|
+
graph = await loadOnce(port, stored, verify);
|
|
226
|
+
} catch (err) {
|
|
227
|
+
if (!sameVersion(stored, await port.readVersion())) continue;
|
|
228
|
+
throw err;
|
|
229
|
+
}
|
|
230
|
+
if (sameVersion(stored, await port.readVersion())) return { epoch: stored.epoch, generation: stored.generation, graph };
|
|
231
|
+
}
|
|
232
|
+
throw conflict('load');
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* The store's canonical dump (§B8.6, the port's `canonicalDump()`): sorted canonical JSON of the manifest, the referenced
|
|
237
|
+
* objects and the derived rows — exactly `factGraphDump` of the loaded graph, so a store and the graph it was saved from
|
|
238
|
+
* dump to the same bytes. Versions, storage layout and unreferenced objects never take part.
|
|
239
|
+
*/
|
|
240
|
+
export async function factStoreDump(port: FactStorePort): Promise<string> {
|
|
241
|
+
return factGraphDump((await loadFactGraph(port)).graph);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Removes the objects the current manifest does not reference (§B4 sweep; run when idle). Rejects
|
|
246
|
+
* `fact_store_generation_conflict` when a write lands between reading the version and the sweep; the next idle sweep
|
|
247
|
+
* catches up. Returns how many objects it deleted.
|
|
248
|
+
*/
|
|
249
|
+
export async function sweepFactStore(port: FactStorePort): Promise<number> {
|
|
250
|
+
return port.sweepObjects(await port.readVersion());
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** The in-memory reference adapter (tests, a Worker's per-request graph). Stores JSON, so a load is a real round trip. */
|
|
254
|
+
export interface MemoryFactStore extends FactStorePort {
|
|
255
|
+
/** Every stored object hash, referenced or not (sorted). */
|
|
256
|
+
objectHashes(): string[];
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
let epochCounter = 0;
|
|
260
|
+
function newEpoch(): string {
|
|
261
|
+
const uuid = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto?.randomUUID?.();
|
|
262
|
+
return uuid ?? `epoch-${Date.now().toString(36)}-${(epochCounter++).toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export function memoryFactStore(): MemoryFactStore {
|
|
266
|
+
const objects = new Map<string, string>();
|
|
267
|
+
let manifest = new Map<string, string>();
|
|
268
|
+
let derived = new Map<string, string>();
|
|
269
|
+
let epoch = newEpoch();
|
|
270
|
+
let generation = 0;
|
|
271
|
+
const check = (expected: FactStoreVersion, nextGeneration: number) => {
|
|
272
|
+
if (expected.epoch !== epoch || nextGeneration !== generation + 1) {
|
|
273
|
+
throw conflict(`${epoch}@${generation}->${expected.epoch}@${expected.generation}`);
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
return {
|
|
277
|
+
getObjects: (hashes) => new Map(hashes.filter((h) => objects.has(h)).map((h) => [h, objects.get(h)!] as const)),
|
|
278
|
+
putObjects: (puts) => { for (const [h, json] of puts) if (!objects.has(h)) objects.set(h, json); },
|
|
279
|
+
readVersion: () => ({ epoch, generation }),
|
|
280
|
+
readManifest: () => ({
|
|
281
|
+
epoch,
|
|
282
|
+
generation,
|
|
283
|
+
files: new Map([...manifest].map(([p, json]) => [p, JSON.parse(json) as FactManifestEntry] as const)),
|
|
284
|
+
}),
|
|
285
|
+
writeManifest: (delta, derivedPuts, derivedDeletes) => {
|
|
286
|
+
check(delta, delta.generation);
|
|
287
|
+
for (const e of delta.puts.values()) if (!objects.has(e.factsHash)) throw new Error(`fact_store_object_missing:${e.factsHash}`);
|
|
288
|
+
// Stage, then swap: all or nothing.
|
|
289
|
+
const next = new Map(manifest);
|
|
290
|
+
for (const [p, e] of delta.puts) next.set(p, canonicalJson(e));
|
|
291
|
+
for (const p of delta.deletes) next.delete(p);
|
|
292
|
+
const rows = new Map(derived);
|
|
293
|
+
for (const row of derivedPuts) rows.set(derivedRowKey(row.rule, row.focus), rowJson(row));
|
|
294
|
+
for (const key of derivedDeletes) rows.delete(key);
|
|
295
|
+
manifest = next;
|
|
296
|
+
derived = rows;
|
|
297
|
+
generation = delta.generation;
|
|
298
|
+
},
|
|
299
|
+
derivedRows: () => new Map([...derived].map(([k, json]) => [k, JSON.parse(json) as DerivedRow] as const)),
|
|
300
|
+
sweepObjects: (expected) => {
|
|
301
|
+
check(expected, expected.generation + 1);
|
|
302
|
+
const live = new Set([...manifest.values()].map((json) => (JSON.parse(json) as FactManifestEntry).factsHash));
|
|
303
|
+
let removed = 0;
|
|
304
|
+
for (const h of [...objects.keys()]) if (!live.has(h)) { objects.delete(h); removed++; }
|
|
305
|
+
if (removed > 0) generation += 1;
|
|
306
|
+
return removed;
|
|
307
|
+
},
|
|
308
|
+
reset: () => {
|
|
309
|
+
objects.clear();
|
|
310
|
+
manifest = new Map();
|
|
311
|
+
derived = new Map();
|
|
312
|
+
epoch = newEpoch();
|
|
313
|
+
generation = 0;
|
|
314
|
+
},
|
|
315
|
+
objectHashes: () => [...objects.keys()].sort(compareStr),
|
|
316
|
+
};
|
|
317
|
+
}
|
package/src/stats/prng.ts
CHANGED
|
@@ -6,7 +6,11 @@
|
|
|
6
6
|
|
|
7
7
|
export type Rng = () => number;
|
|
8
8
|
|
|
9
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* SplitMix32-style seed expansion to four uint32 words. Never the all-zero state (the one fixed point of
|
|
11
|
+
* xoshiro): the finaliser is a bijection on uint32 (xor-shifts and odd multipliers), and its four inputs
|
|
12
|
+
* s + k·0x9e3779b9 (k = 1..4) are distinct mod 2^32, so at most one of the four words can be 0.
|
|
13
|
+
*/
|
|
10
14
|
function seedWords(seed: number): [number, number, number, number] {
|
|
11
15
|
let s = seed >>> 0;
|
|
12
16
|
const next = () => {
|
|
@@ -20,13 +24,17 @@ function seedWords(seed: number): [number, number, number, number] {
|
|
|
20
24
|
return [next(), next(), next(), next()];
|
|
21
25
|
}
|
|
22
26
|
|
|
23
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* A deterministic RNG in [0, 1), seeded once. `seed = 0` is a valid seed. State (a, b, c, d) = (s0, s1, s2, s3)
|
|
29
|
+
* of the reference xoshiro128** (Blackman & Vigna): result = rotl(s1·5, 7)·9; t = s1 << 9 (a SHIFT, not a
|
|
30
|
+
* rotate — rotating collapsed every stream to 0 within a few hundred draws).
|
|
31
|
+
*/
|
|
24
32
|
export function createRng(seed: number): Rng {
|
|
25
33
|
let [a, b, c, d] = seedWords(seed);
|
|
26
34
|
return () => {
|
|
27
35
|
const result = (Math.imul(b, 5) << 7 | Math.imul(b, 5) >>> 25) >>> 0;
|
|
28
36
|
const out = ((result * 9) >>> 0) / 4294967296;
|
|
29
|
-
const t = (b << 9
|
|
37
|
+
const t = (b << 9) >>> 0;
|
|
30
38
|
c = (c ^ a) >>> 0;
|
|
31
39
|
d = (d ^ b) >>> 0;
|
|
32
40
|
b = (b ^ c) >>> 0;
|