@seanhogg/builderforce-memory 2026.10.29 → 2026.10.30
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/retrieval/knowledge-index/cascade.d.ts +7 -5
- package/dist/retrieval/knowledge-index/cascade.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/cascade.js +42 -28
- package/dist/retrieval/knowledge-index/cascade.js.map +1 -1
- package/dist/retrieval/knowledge-index/compact.d.ts +4 -0
- package/dist/retrieval/knowledge-index/compact.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/compact.js +12 -4
- package/dist/retrieval/knowledge-index/compact.js.map +1 -1
- package/dist/retrieval/knowledge-index/digest.d.ts +2 -1
- package/dist/retrieval/knowledge-index/digest.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/digest.js +5 -3
- package/dist/retrieval/knowledge-index/digest.js.map +1 -1
- package/dist/retrieval/knowledge-index/index.d.ts +8 -4
- package/dist/retrieval/knowledge-index/index.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/index.js +6 -4
- package/dist/retrieval/knowledge-index/index.js.map +1 -1
- package/dist/retrieval/knowledge-index/pairs.d.ts +7 -5
- package/dist/retrieval/knowledge-index/pairs.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/pairs.js +30 -16
- package/dist/retrieval/knowledge-index/pairs.js.map +1 -1
- package/dist/retrieval/knowledge-index/scan.d.ts +39 -0
- package/dist/retrieval/knowledge-index/scan.d.ts.map +1 -0
- package/dist/retrieval/knowledge-index/scan.js +104 -0
- package/dist/retrieval/knowledge-index/scan.js.map +1 -0
- package/dist/retrieval/knowledge-index/serialize.d.ts +9 -4
- package/dist/retrieval/knowledge-index/serialize.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/serialize.js +19 -7
- package/dist/retrieval/knowledge-index/serialize.js.map +1 -1
- package/dist/retrieval/knowledge-index/state.d.ts +5 -1
- package/dist/retrieval/knowledge-index/state.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/state.js +5 -0
- package/dist/retrieval/knowledge-index/state.js.map +1 -1
- package/dist/retrieval/knowledge-index/traverse.d.ts +4 -0
- package/dist/retrieval/knowledge-index/traverse.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/traverse.js +2 -2
- package/dist/retrieval/knowledge-index/traverse.js.map +1 -1
- package/dist/retrieval/knowledge-index/types.d.ts +10 -1
- package/dist/retrieval/knowledge-index/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/retrieval/knowledge-index/cascade.ts +40 -26
- package/src/retrieval/knowledge-index/compact.ts +12 -4
- package/src/retrieval/knowledge-index/digest.ts +5 -3
- package/src/retrieval/knowledge-index/index.ts +10 -6
- package/src/retrieval/knowledge-index/pairs.ts +33 -18
- package/src/retrieval/knowledge-index/scan.ts +101 -0
- package/src/retrieval/knowledge-index/serialize.ts +19 -7
- package/src/retrieval/knowledge-index/state.ts +9 -1
- package/src/retrieval/knowledge-index/traverse.ts +2 -2
- package/src/retrieval/knowledge-index/types.ts +11 -1
|
@@ -2,15 +2,16 @@
|
|
|
2
2
|
* The knowledge index — a deterministic, LEANN-style index over knowledge-graph
|
|
3
3
|
* cards (design: Builderforce.ai/docs/design/deterministic-knowledge-index.md).
|
|
4
4
|
*
|
|
5
|
-
* Exact → lexical → dense cascade; int8 codes with integer traversal;
|
|
6
|
-
*
|
|
5
|
+
* Exact → lexical → dense cascade; int8 codes with integer traversal; below
|
|
6
|
+
* `exactBelow` cards an exact int8 scan, at or above it a high-degree-preserving
|
|
7
|
+
* pruned graph stored as CSR; float vectors recomputed
|
|
7
8
|
* only for the candidates being reranked. Every result is a pure function of
|
|
8
9
|
* `(digest(), query, opts)`.
|
|
9
10
|
*
|
|
10
11
|
* Runs in a Worker, the browser and Node: no Node-only API anywhere.
|
|
11
12
|
*/
|
|
12
13
|
|
|
13
|
-
import type { EmbedderPort, GraphNeighbours, IndexDoc, IndexHit, IndexParams, IndexTier, KnowledgeIndex, SimilarPair } from './types.js';
|
|
14
|
+
import type { EmbedderPort, GraphNeighbours, IndexDoc, IndexHit, IndexMode, IndexParams, IndexTier, KnowledgeIndex, SimilarPair } from './types.js';
|
|
14
15
|
import { availableTiers, canonicalKeys, createState, denseReady, graphNode, indexKeys, type DocEntry, type IndexState } from './state.js';
|
|
15
16
|
import { EmbeddingCache } from './embeddings.js';
|
|
16
17
|
import { cascadeSearch, denseCandidates, type SearchContext } from './cascade.js';
|
|
@@ -117,16 +118,18 @@ class DeterministicKnowledgeIndex implements KnowledgeIndex {
|
|
|
117
118
|
/** Diagnostics: stored bytes of the int8 codes and the CSR graph, against float32. */
|
|
118
119
|
storage(): KnowledgeIndexStorage {
|
|
119
120
|
const c = this._state.compacted;
|
|
120
|
-
if (!c) return { nodes: 0, codeBytes: 0, graphBytes: 0, float32Bytes: 0 };
|
|
121
|
+
if (!c) return { mode: null, nodes: 0, codeBytes: 0, graphBytes: 0, float32Bytes: 0 };
|
|
121
122
|
let codeBytes = 0;
|
|
122
123
|
for (const code of c.codes) codeBytes += code?.byteLength ?? 0;
|
|
123
124
|
let graphBytes = 0;
|
|
124
125
|
for (const l of c.graph.layers) graphBytes += (l.nodes?.byteLength ?? 0) + l.offsets.byteLength + l.neighbours.byteLength;
|
|
125
|
-
return { nodes: c.ids.length, codeBytes, graphBytes, float32Bytes: c.ids.length * this._state.dims * 4 };
|
|
126
|
+
return { mode: c.mode, nodes: c.ids.length, codeBytes, graphBytes, float32Bytes: c.ids.length * this._state.dims * 4 };
|
|
126
127
|
}
|
|
127
128
|
}
|
|
128
129
|
|
|
129
130
|
export interface KnowledgeIndexStorage {
|
|
131
|
+
/** How the dense tier searches the codes; null before the first compaction with an embedder. */
|
|
132
|
+
mode: IndexMode | null;
|
|
130
133
|
nodes: number;
|
|
131
134
|
codeBytes: number;
|
|
132
135
|
graphBytes: number;
|
|
@@ -154,7 +157,8 @@ export function loadKnowledgeIndex(bytes: Uint8Array, embedder?: EmbedderPort):
|
|
|
154
157
|
return new DeterministicKnowledgeIndex(deserializeState(bytes), embedder);
|
|
155
158
|
}
|
|
156
159
|
|
|
157
|
-
export type { EmbedderPort, GraphNeighbours, IndexDoc, IndexHit, IndexParams, IndexTier, KnowledgeIndex, SimilarPair } from './types.js';
|
|
160
|
+
export type { EmbedderPort, GraphNeighbours, IndexDoc, IndexHit, IndexMode, IndexParams, IndexTier, KnowledgeIndex, SimilarPair } from './types.js';
|
|
161
|
+
export { EXACT_PAIR_BUDGET } from './scan.js';
|
|
158
162
|
export { DEFAULT_INDEX_PARAMS } from './state.js';
|
|
159
163
|
export { codeTokenize } from './tokenize.js';
|
|
160
164
|
export { hashDocText } from './digest.js';
|
|
@@ -2,11 +2,13 @@
|
|
|
2
2
|
* pairs.ts — near-duplicate pairs over the int8 codes (the Duplication lens,
|
|
3
3
|
* review-time entity resolution, contradiction candidates).
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
* the compacted graph's edges on every layer rather than all n² pairs.
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
5
|
+
* Graph mode: near-duplicates are each other's nearest neighbours, so the candidate
|
|
6
|
+
* pairs are the compacted graph's edges on every layer rather than all n² pairs.
|
|
7
|
+
* Exact mode (no graph): {@link exactPairCandidates} — all pairs while they fit
|
|
8
|
+
* `EXACT_PAIR_BUDGET`, deterministic sign-bit blocking above it, never more
|
|
9
|
+
* than the budget. Similarity is {@link cosineInt8} (exact integers,
|
|
10
|
+
* correctly-rounded sqrt/division). The order is total: similarity (quantized
|
|
11
|
+
* 1e-4) descending, then `a`, then `b`, and `a < b` by id in every pair.
|
|
10
12
|
*
|
|
11
13
|
* Cards not yet compacted, and lean-mode nodes whose codes were dropped, are not
|
|
12
14
|
* paired until the next compaction (the call is synchronous; it never embeds).
|
|
@@ -14,9 +16,10 @@
|
|
|
14
16
|
|
|
15
17
|
import { compareIds, quantizeScore, DENSE_SCORE_QUANTUM } from '../order.js';
|
|
16
18
|
import type { SimilarPair } from './types.js';
|
|
17
|
-
import { graphNode, type IndexState } from './state.js';
|
|
19
|
+
import { graphNode, type Compacted, type IndexState } from './state.js';
|
|
18
20
|
import { neighboursOf } from './csr.js';
|
|
19
21
|
import { cosineInt8 } from './quantize.js';
|
|
22
|
+
import { exactPairCandidates } from './scan.js';
|
|
20
23
|
|
|
21
24
|
export interface SimilarPairsOptions {
|
|
22
25
|
minSimilarity: number;
|
|
@@ -24,15 +27,10 @@ export interface SimilarPairsOptions {
|
|
|
24
27
|
idPrefix?: string;
|
|
25
28
|
}
|
|
26
29
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
if (!c || opts.maxPairs <= 0) return [];
|
|
30
|
-
const prefix = opts.idPrefix ?? '';
|
|
31
|
-
const usable = (node: number) =>
|
|
32
|
-
!!c.codes[node] && c.ids[node]!.startsWith(prefix) && graphNode(state, c.ids[node]!) === node;
|
|
33
|
-
|
|
30
|
+
/** Graph mode: every edge on every layer between two usable nodes, once, as `[lo, hi]`. */
|
|
31
|
+
function graphPairCandidates(c: Compacted, usable: (node: number) => boolean): Array<[number, number]> {
|
|
34
32
|
const seen = new Set<string>();
|
|
35
|
-
const
|
|
33
|
+
const out: Array<[number, number]> = [];
|
|
36
34
|
for (let a = 0; a < c.ids.length; a++) {
|
|
37
35
|
if (!usable(a)) continue;
|
|
38
36
|
for (const layer of c.graph.layers) {
|
|
@@ -43,13 +41,30 @@ export function similarPairs(state: IndexState, opts: SimilarPairsOptions): Simi
|
|
|
43
41
|
const key = `${lo}:${hi}`;
|
|
44
42
|
if (seen.has(key)) continue;
|
|
45
43
|
seen.add(key);
|
|
46
|
-
|
|
47
|
-
if (similarity >= opts.minSimilarity) {
|
|
48
|
-
pairs.push({ a: c.ids[lo]!, b: c.ids[hi]!, similarity, q: quantizeScore(similarity, DENSE_SCORE_QUANTUM) });
|
|
49
|
-
}
|
|
44
|
+
out.push([lo, hi]);
|
|
50
45
|
}
|
|
51
46
|
}
|
|
52
47
|
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function similarPairs(state: IndexState, opts: SimilarPairsOptions): SimilarPair[] {
|
|
52
|
+
const c = state.compacted;
|
|
53
|
+
if (!c || opts.maxPairs <= 0) return [];
|
|
54
|
+
const prefix = opts.idPrefix ?? '';
|
|
55
|
+
const usable = (node: number) =>
|
|
56
|
+
!!c.codes[node] && c.ids[node]!.startsWith(prefix) && graphNode(state, c.ids[node]!) === node;
|
|
57
|
+
|
|
58
|
+
const candidates = c.mode === 'exact'
|
|
59
|
+
? exactPairCandidates(c.codes, c.ids.map((_, node) => node).filter(usable), state.dims)
|
|
60
|
+
: graphPairCandidates(c, usable);
|
|
61
|
+
const pairs: Array<SimilarPair & { q: number }> = [];
|
|
62
|
+
for (const [lo, hi] of candidates) {
|
|
63
|
+
const similarity = cosineInt8(c.codes[lo]!, c.codes[hi]!);
|
|
64
|
+
if (similarity >= opts.minSimilarity) {
|
|
65
|
+
pairs.push({ a: c.ids[lo]!, b: c.ids[hi]!, similarity, q: quantizeScore(similarity, DENSE_SCORE_QUANTUM) });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
53
68
|
return pairs
|
|
54
69
|
.sort((x, y) => (y.q - x.q) || compareIds(x.a, y.a) || compareIds(x.b, y.b))
|
|
55
70
|
.slice(0, opts.maxPairs)
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* scan.ts — exact mode: the dense tier and `similarPairs` with no graph.
|
|
3
|
+
*
|
|
4
|
+
* Below `exactBelow` cards an HNSW graph costs more to build than it saves, so
|
|
5
|
+
* `compact()` builds none and these replace the walk:
|
|
6
|
+
*
|
|
7
|
+
* - {@link scanCodes}: an exact integer dot product against every live int8 code,
|
|
8
|
+
* the best `n` kept with ties on node index (= id order). Same order as the
|
|
9
|
+
* graph walk's candidates, so the float rerank after it is unchanged.
|
|
10
|
+
* - {@link exactPairCandidates}: the node pairs `similarPairs` scores. All pairs
|
|
11
|
+
* while there are at most {@link EXACT_PAIR_BUDGET}; above that, deterministic
|
|
12
|
+
* sign-bit blocking (see the function), capped at the same budget.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { graphNode, type Compacted, type IndexState } from './state.js';
|
|
16
|
+
import { dotInt8 } from './quantize.js';
|
|
17
|
+
import { before, insertOrdered, type GraphCandidate } from './traverse.js';
|
|
18
|
+
|
|
19
|
+
/** The most node pairs `similarPairs` scores in exact mode. */
|
|
20
|
+
export const EXACT_PAIR_BUDGET = 250_000;
|
|
21
|
+
/** Blocking tables: a pair is a candidate when it shares a bucket in any one of them. */
|
|
22
|
+
export const PAIR_BLOCK_TABLES = 8;
|
|
23
|
+
/** Sign bits per table (2^bits buckets each). */
|
|
24
|
+
export const PAIR_BLOCK_BITS = 10;
|
|
25
|
+
/** Within a bucket, each node is paired with at most this many following members (id order). */
|
|
26
|
+
export const PAIR_BLOCK_WINDOW = 32;
|
|
27
|
+
|
|
28
|
+
/** The best `n` live coded nodes by integer dot product with `qc`, in {@link before} order. */
|
|
29
|
+
export function scanCodes(state: IndexState, c: Compacted, qc: Int8Array, n: number): GraphCandidate[] {
|
|
30
|
+
const top: GraphCandidate[] = [];
|
|
31
|
+
if (n <= 0) return top;
|
|
32
|
+
for (let node = 0; node < c.ids.length; node++) {
|
|
33
|
+
const code = c.codes[node];
|
|
34
|
+
if (!code || graphNode(state, c.ids[node]!) !== node) continue;
|
|
35
|
+
const cand = { node, score: dotInt8(qc, code) };
|
|
36
|
+
if (top.length < n || before(cand, top[top.length - 1]!)) {
|
|
37
|
+
insertOrdered(top, cand);
|
|
38
|
+
if (top.length > n) top.pop();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return top;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The dimensions table `t` reads its sign bits from, spread evenly across `dims`. */
|
|
45
|
+
function blockDims(t: number, dims: number): number[] {
|
|
46
|
+
const stride = Math.max(1, Math.floor(dims / (PAIR_BLOCK_TABLES * PAIR_BLOCK_BITS)));
|
|
47
|
+
return Array.from({ length: PAIR_BLOCK_BITS }, (_, j) => ((t * PAIR_BLOCK_BITS + j) * stride) % dims);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Candidate `[lo, hi]` node pairs (lo < hi) among `nodes` (ascending, all coded).
|
|
52
|
+
*
|
|
53
|
+
* When every pair fits in {@link EXACT_PAIR_BUDGET} (about 700 nodes), every pair is
|
|
54
|
+
* a candidate. Above that, each of {@link PAIR_BLOCK_TABLES} tables buckets the nodes
|
|
55
|
+
* by the signs of {@link PAIR_BLOCK_BITS} fixed code dimensions; a near-duplicate
|
|
56
|
+
* agrees on almost every sign, so it lands with its twin in at least one table.
|
|
57
|
+
* Inside a bucket a node is paired with its next {@link PAIR_BLOCK_WINDOW} members.
|
|
58
|
+
* Tables run in order, buckets in key order, members in node order, and generation
|
|
59
|
+
* stops at the budget — so the candidates are a pure function of the codes, and the
|
|
60
|
+
* cost is at most `EXACT_PAIR_BUDGET` cosine evaluations whatever the size.
|
|
61
|
+
*/
|
|
62
|
+
export function exactPairCandidates(
|
|
63
|
+
codes: ReadonlyArray<Int8Array | undefined>,
|
|
64
|
+
nodes: readonly number[],
|
|
65
|
+
dims: number,
|
|
66
|
+
): Array<[number, number]> {
|
|
67
|
+
const out: Array<[number, number]> = [];
|
|
68
|
+
const n = nodes.length;
|
|
69
|
+
if ((n * (n - 1)) / 2 <= EXACT_PAIR_BUDGET) {
|
|
70
|
+
for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) out.push([nodes[i]!, nodes[j]!]);
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
if (dims <= 0) return out;
|
|
74
|
+
const seen = new Set<number>();
|
|
75
|
+
for (let t = 0; t < PAIR_BLOCK_TABLES; t++) {
|
|
76
|
+
const bits = blockDims(t, dims);
|
|
77
|
+
const buckets = new Map<number, number[]>();
|
|
78
|
+
for (const node of nodes) {
|
|
79
|
+
const code = codes[node]!;
|
|
80
|
+
let key = 0;
|
|
81
|
+
for (const d of bits) key = key * 2 + ((code[d] ?? 0) > 0 ? 1 : 0);
|
|
82
|
+
const members = buckets.get(key);
|
|
83
|
+
if (members) members.push(node);
|
|
84
|
+
else buckets.set(key, [node]);
|
|
85
|
+
}
|
|
86
|
+
for (const key of [...buckets.keys()].sort((a, b) => a - b)) {
|
|
87
|
+
const members = buckets.get(key)!;
|
|
88
|
+
for (let i = 0; i < members.length; i++) {
|
|
89
|
+
const end = Math.min(members.length, i + 1 + PAIR_BLOCK_WINDOW);
|
|
90
|
+
for (let j = i + 1; j < end; j++) {
|
|
91
|
+
const pairKey = members[i]! * codes.length + members[j]!;
|
|
92
|
+
if (seen.has(pairKey)) continue;
|
|
93
|
+
seen.add(pairKey);
|
|
94
|
+
out.push([members[i]!, members[j]!]);
|
|
95
|
+
if (out.length >= EXACT_PAIR_BUDGET) return out;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* serialize.ts — the versioned binary form of an index state.
|
|
3
3
|
*
|
|
4
|
-
* Layout (little-endian, via `bytes.ts`):
|
|
4
|
+
* Layout (little-endian, via `bytes.ts`), version 2:
|
|
5
5
|
* magic "BFKI" · u32 version
|
|
6
|
-
* fingerprint · dims · scale · params
|
|
6
|
+
* fingerprint · dims · scale · params (`writeParams`, ending in `exactBelow`)
|
|
7
7
|
* docs (id order): id · text · hash · keys · optional pending float vector
|
|
8
|
-
* u8 compacted? →
|
|
8
|
+
* u8 compacted? → u8 mode (1 exact, 0 graph) · node ids · node hashes · hubs ·
|
|
9
|
+
* code-present flags · codes · graph (empty in exact mode)
|
|
10
|
+
*
|
|
11
|
+
* Version 1 (2026.10.29) had no `exactBelow` and no mode byte; every v1 index was a
|
|
12
|
+
* graph. It still loads: as graph mode, with `exactBelow` 0 so a later `compact()`
|
|
13
|
+
* keeps building the graph it was made with. Writing is always the current version.
|
|
9
14
|
*
|
|
10
15
|
* Texts travel with the index because the lexical tier, the recompute path and a
|
|
11
16
|
* re-embed under a new fingerprint all need them. Loading rebuilds the derived
|
|
@@ -20,7 +25,9 @@ import { ByteReader, ByteWriter } from './bytes.js';
|
|
|
20
25
|
import { writeGraph, writeParams } from './digest.js';
|
|
21
26
|
|
|
22
27
|
const MAGIC = [0x42, 0x46, 0x4b, 0x49]; // "BFKI"
|
|
23
|
-
export const SERIALIZE_VERSION =
|
|
28
|
+
export const SERIALIZE_VERSION = 2;
|
|
29
|
+
/** The oldest version `deserializeState` still reads. */
|
|
30
|
+
const MIN_READ_VERSION = 1;
|
|
24
31
|
|
|
25
32
|
export function serializeState(state: IndexState): Uint8Array {
|
|
26
33
|
const w = new ByteWriter();
|
|
@@ -41,6 +48,7 @@ export function serializeState(state: IndexState): Uint8Array {
|
|
|
41
48
|
const c = state.compacted;
|
|
42
49
|
w.u8(c ? 1 : 0);
|
|
43
50
|
if (c) {
|
|
51
|
+
w.u8(c.mode === 'exact' ? 1 : 0);
|
|
44
52
|
w.u32(c.ids.length);
|
|
45
53
|
for (let i = 0; i < c.ids.length; i++) w.str(c.ids[i]!).str(c.hashes[i]!);
|
|
46
54
|
w.bytes(c.hubs);
|
|
@@ -51,7 +59,7 @@ export function serializeState(state: IndexState): Uint8Array {
|
|
|
51
59
|
return w.finish();
|
|
52
60
|
}
|
|
53
61
|
|
|
54
|
-
function readParams(r: ByteReader): IndexParams {
|
|
62
|
+
function readParams(r: ByteReader, version: number): IndexParams {
|
|
55
63
|
return {
|
|
56
64
|
m: r.u32(),
|
|
57
65
|
efConstruction: r.u32(),
|
|
@@ -60,6 +68,8 @@ function readParams(r: ByteReader): IndexParams {
|
|
|
60
68
|
rerankFactor: r.u32(),
|
|
61
69
|
lean: r.u8() === 1,
|
|
62
70
|
rrfK: r.u32(),
|
|
71
|
+
// v1 indexes were always graphs: keep building one.
|
|
72
|
+
exactBelow: version >= 2 ? r.u32() : 0,
|
|
63
73
|
};
|
|
64
74
|
}
|
|
65
75
|
|
|
@@ -68,12 +78,12 @@ export function deserializeState(bytes: Uint8Array): IndexState {
|
|
|
68
78
|
const magic = r.raw(4);
|
|
69
79
|
if (MAGIC.some((b, i) => magic[i] !== b)) throw new Error('knowledge-index: not a serialized index');
|
|
70
80
|
const version = r.u32();
|
|
71
|
-
if (version
|
|
81
|
+
if (version < MIN_READ_VERSION || version > SERIALIZE_VERSION) throw new Error(`knowledge-index: unsupported version ${version}`);
|
|
72
82
|
|
|
73
83
|
const fingerprint = r.str();
|
|
74
84
|
const dims = r.u32();
|
|
75
85
|
const scale = r.f64();
|
|
76
|
-
const state = createState(readParams(r));
|
|
86
|
+
const state = createState(readParams(r, version));
|
|
77
87
|
Object.assign(state, { fingerprint, dims, scale });
|
|
78
88
|
|
|
79
89
|
const docCount = r.u32();
|
|
@@ -88,6 +98,7 @@ export function deserializeState(bytes: Uint8Array): IndexState {
|
|
|
88
98
|
}
|
|
89
99
|
|
|
90
100
|
if (r.u8() === 1) {
|
|
101
|
+
const mode: Compacted['mode'] = version >= 2 && r.u8() === 1 ? 'exact' : 'graph';
|
|
91
102
|
const n = r.u32();
|
|
92
103
|
const ids: string[] = [];
|
|
93
104
|
const hashes: string[] = [];
|
|
@@ -112,6 +123,7 @@ export function deserializeState(bytes: Uint8Array): IndexState {
|
|
|
112
123
|
layers.push(l === 0 ? { offsets, neighbours } : { nodes, offsets, neighbours });
|
|
113
124
|
}
|
|
114
125
|
state.compacted = {
|
|
126
|
+
mode,
|
|
115
127
|
ids,
|
|
116
128
|
hashes,
|
|
117
129
|
codes,
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* so `digest()` can name it and `serialize()` can carry it.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import type { EmbedderPort, IndexParams, IndexTier } from './types.js';
|
|
7
|
+
import type { EmbedderPort, IndexMode, IndexParams, IndexTier } from './types.js';
|
|
8
8
|
import type { CsrGraph } from './csr.js';
|
|
9
9
|
import { LexicalIndex } from './lexical.js';
|
|
10
10
|
import { foldKey } from './tokenize.js';
|
|
@@ -17,6 +17,7 @@ export const DEFAULT_INDEX_PARAMS: Readonly<IndexParams> = Object.freeze({
|
|
|
17
17
|
rerankFactor: 4,
|
|
18
18
|
lean: false,
|
|
19
19
|
rrfK: 60,
|
|
20
|
+
exactBelow: 20000,
|
|
20
21
|
});
|
|
21
22
|
|
|
22
23
|
/** One live card. `vec` is its unit float embedding while it is not yet in the graph. */
|
|
@@ -31,6 +32,8 @@ export interface DocEntry {
|
|
|
31
32
|
|
|
32
33
|
/** The canonical, id-ordered snapshot written by `compact()`. Node index = rank of its id. */
|
|
33
34
|
export interface Compacted {
|
|
35
|
+
/** `exact`: no graph (empty `graph`, zero `hubs`, every code kept); `graph`: HNSW over the codes. */
|
|
36
|
+
mode: IndexMode;
|
|
34
37
|
ids: string[];
|
|
35
38
|
/** The doc hash each node was coded from; a node whose doc changed is stale. */
|
|
36
39
|
hashes: string[];
|
|
@@ -97,6 +100,11 @@ export function graphNode(state: IndexState, id: string): number {
|
|
|
97
100
|
return state.docs.get(id)?.hash === c.hashes[node] ? node : -1;
|
|
98
101
|
}
|
|
99
102
|
|
|
103
|
+
/** The search mode a compaction of `size` cards uses under `params`. */
|
|
104
|
+
export function modeFor(params: IndexParams, size: number): IndexMode {
|
|
105
|
+
return size < params.exactBelow ? 'exact' : 'graph';
|
|
106
|
+
}
|
|
107
|
+
|
|
100
108
|
/** Whether `embedder` may produce vectors comparable with the stored ones. */
|
|
101
109
|
export function denseReady(state: IndexState, embedder: EmbedderPort | undefined): embedder is EmbedderPort {
|
|
102
110
|
return !!embedder && embedder.fingerprint === state.fingerprint && embedder.dims === state.dims;
|
|
@@ -26,12 +26,12 @@ export interface GraphCandidate {
|
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
/** Higher score first, then lower node index. */
|
|
29
|
-
function before(a: GraphCandidate, b: GraphCandidate): boolean {
|
|
29
|
+
export function before(a: GraphCandidate, b: GraphCandidate): boolean {
|
|
30
30
|
return a.score > b.score || (a.score === b.score && a.node < b.node);
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
/** Inserts `c` into `list`, kept in {@link before} order. */
|
|
34
|
-
function insertOrdered(list: GraphCandidate[], c: GraphCandidate): void {
|
|
34
|
+
export function insertOrdered(list: GraphCandidate[], c: GraphCandidate): void {
|
|
35
35
|
let lo = 0;
|
|
36
36
|
let hi = list.length;
|
|
37
37
|
while (lo < hi) {
|
|
@@ -45,12 +45,22 @@ export interface IndexParams {
|
|
|
45
45
|
hubShare: number;
|
|
46
46
|
/** Dense candidates = k * rerankFactor, recomputed in float and reranked. Default 4. */
|
|
47
47
|
rerankFactor: number;
|
|
48
|
-
/** Drop int8 codes of non-hub nodes and recompute on the search path. Default false. */
|
|
48
|
+
/** Drop int8 codes of non-hub nodes and recompute on the search path. Graph mode only; ignored in exact mode. Default false. */
|
|
49
49
|
lean: boolean;
|
|
50
50
|
/** RRF constant. Default 60. */
|
|
51
51
|
rrfK: number;
|
|
52
|
+
/**
|
|
53
|
+
* Below this many cards, `compact()` builds no graph: the dense tier is an exact
|
|
54
|
+
* integer scan over every int8 code (no construction cost, trivially deterministic).
|
|
55
|
+
* At or above it, the HNSW graph is built. 0 always builds the graph. A u32
|
|
56
|
+
* (it is serialized and hashed as one). Default 20000.
|
|
57
|
+
*/
|
|
58
|
+
exactBelow: number;
|
|
52
59
|
}
|
|
53
60
|
|
|
61
|
+
/** How the compacted codes are searched: an exact int8 scan, or the HNSW graph. */
|
|
62
|
+
export type IndexMode = 'exact' | 'graph';
|
|
63
|
+
|
|
54
64
|
export interface SimilarPair {
|
|
55
65
|
a: string;
|
|
56
66
|
b: string;
|