@fgv/ts-agent-memory-sqlite-vec 5.1.0-42
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/.rush/temp/689b960e7e1a3b63bd68fbb91474d5c28d567861.tar.log +60 -0
- package/.rush/temp/chunked-rush-logs/ts-agent-memory-sqlite-vec.build.chunks.jsonl +9 -0
- package/.rush/temp/operation/build/all.log +9 -0
- package/.rush/temp/operation/build/log-chunks.jsonl +9 -0
- package/.rush/temp/operation/build/state.json +3 -0
- package/.rush/temp/shrinkwrap-deps.json +720 -0
- package/README.md +109 -0
- package/config/api-extractor.json +38 -0
- package/config/jest.config.json +13 -0
- package/config/rig.json +6 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/packlets/sqlite-vec-index/index.js +8 -0
- package/dist/packlets/sqlite-vec-index/index.js.map +1 -0
- package/dist/packlets/sqlite-vec-index/model.js +6 -0
- package/dist/packlets/sqlite-vec-index/model.js.map +1 -0
- package/dist/packlets/sqlite-vec-index/sqliteVecFragmentIndex.js +277 -0
- package/dist/packlets/sqlite-vec-index/sqliteVecFragmentIndex.js.map +1 -0
- package/dist/packlets/sqlite-vec-index/sqliteVecVectorIndex.js +182 -0
- package/dist/packlets/sqlite-vec-index/sqliteVecVectorIndex.js.map +1 -0
- package/dist/test/unit/sqliteVecFragmentIndex.test.js +352 -0
- package/dist/test/unit/sqliteVecFragmentIndex.test.js.map +1 -0
- package/dist/test/unit/sqliteVecVectorIndex.test.js +199 -0
- package/dist/test/unit/sqliteVecVectorIndex.test.js.map +1 -0
- package/dist/ts-agent-memory-sqlite-vec.d.ts +225 -0
- package/dist/tsdoc-metadata.json +11 -0
- package/eslint.config.js +15 -0
- package/etc/ts-agent-memory-sqlite-vec.api.md +66 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +22 -0
- package/lib/index.js.map +1 -0
- package/lib/packlets/sqlite-vec-index/index.d.ts +4 -0
- package/lib/packlets/sqlite-vec-index/index.d.ts.map +1 -0
- package/lib/packlets/sqlite-vec-index/index.js +24 -0
- package/lib/packlets/sqlite-vec-index/index.js.map +1 -0
- package/lib/packlets/sqlite-vec-index/model.d.ts +48 -0
- package/lib/packlets/sqlite-vec-index/model.d.ts.map +1 -0
- package/lib/packlets/sqlite-vec-index/model.js +7 -0
- package/lib/packlets/sqlite-vec-index/model.js.map +1 -0
- package/lib/packlets/sqlite-vec-index/sqliteVecFragmentIndex.d.ts +94 -0
- package/lib/packlets/sqlite-vec-index/sqliteVecFragmentIndex.d.ts.map +1 -0
- package/lib/packlets/sqlite-vec-index/sqliteVecFragmentIndex.js +281 -0
- package/lib/packlets/sqlite-vec-index/sqliteVecFragmentIndex.js.map +1 -0
- package/lib/packlets/sqlite-vec-index/sqliteVecVectorIndex.d.ts +80 -0
- package/lib/packlets/sqlite-vec-index/sqliteVecVectorIndex.d.ts.map +1 -0
- package/lib/packlets/sqlite-vec-index/sqliteVecVectorIndex.js +186 -0
- package/lib/packlets/sqlite-vec-index/sqliteVecVectorIndex.js.map +1 -0
- package/lib/test/unit/sqliteVecFragmentIndex.test.d.ts +2 -0
- package/lib/test/unit/sqliteVecFragmentIndex.test.d.ts.map +1 -0
- package/lib/test/unit/sqliteVecFragmentIndex.test.js +390 -0
- package/lib/test/unit/sqliteVecFragmentIndex.test.js.map +1 -0
- package/lib/test/unit/sqliteVecVectorIndex.test.d.ts +2 -0
- package/lib/test/unit/sqliteVecVectorIndex.test.d.ts.map +1 -0
- package/lib/test/unit/sqliteVecVectorIndex.test.js +237 -0
- package/lib/test/unit/sqliteVecVectorIndex.test.js.map +1 -0
- package/package.json +87 -0
- package/rush-logs/ts-agent-memory-sqlite-vec.build.cache.log +3 -0
- package/rush-logs/ts-agent-memory-sqlite-vec.build.log +9 -0
- package/src/index.ts +6 -0
- package/src/packlets/sqlite-vec-index/index.ts +8 -0
- package/src/packlets/sqlite-vec-index/model.ts +56 -0
- package/src/packlets/sqlite-vec-index/sqliteVecFragmentIndex.ts +381 -0
- package/src/packlets/sqlite-vec-index/sqliteVecVectorIndex.ts +255 -0
- package/src/test/unit/sqliteVecFragmentIndex.test.ts +466 -0
- package/src/test/unit/sqliteVecVectorIndex.test.ts +253 -0
- package/temp/build/lint/_eslint-5eVG3S6w.json +34 -0
- package/temp/build/typescript/ts_8nwakTlr.json +1 -0
- package/temp/ts-agent-memory-sqlite-vec.api.json +1167 -0
- package/temp/ts-agent-memory-sqlite-vec.api.md +66 -0
- package/tsconfig.json +8 -0
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2026 Erik Fortune
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
import { load as loadSqliteVec } from 'sqlite-vec';
|
|
6
|
+
import { captureResult, fail, succeed } from '@fgv/ts-utils';
|
|
7
|
+
import { edgeTargetKey } from '@fgv/ts-agent-memory';
|
|
8
|
+
/** Default name for the `vec0` virtual table. */
|
|
9
|
+
const DEFAULT_TABLE_NAME = 'memory_vectors';
|
|
10
|
+
/** A simple SQL identifier — the only shape allowed for the table name (it is interpolated into DDL). */
|
|
11
|
+
const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
12
|
+
/**
|
|
13
|
+
* A persistent, `sqlite-vec`-backed `IVectorIndex` for `@fgv/ts-agent-memory`.
|
|
14
|
+
*
|
|
15
|
+
* @remarks
|
|
16
|
+
* This is the **durable** counterpart to the in-memory `InMemoryCosineIndex`:
|
|
17
|
+
* embeddings live in a `sqlite-vec` `vec0` virtual table inside a `better-sqlite3`
|
|
18
|
+
* database, so they survive a process restart. A consumer that wires this index
|
|
19
|
+
* into `FileTreeMemoryStore` (instead of the in-memory index) opens an existing
|
|
20
|
+
* vault **without re-embedding it** — the vectors are already on disk. New writes
|
|
21
|
+
* still flow through the store's incremental embed-on-write path; there is no core
|
|
22
|
+
* store change.
|
|
23
|
+
*
|
|
24
|
+
* The index is keyed by the canonical `edgeTargetKey` of each record's
|
|
25
|
+
* scope-qualified `(scope, id)` address (a `TEXT PRIMARY KEY` on the `vec0` table),
|
|
26
|
+
* so two records that share a filename stem across scopes never collide. The
|
|
27
|
+
* dimension is established by the first `add` (the `vec0` column is fixed-width) and
|
|
28
|
+
* recovered from the table schema when a persistent file is reopened; every later
|
|
29
|
+
* `add`/`query` must match it or fail loudly, exactly as the in-memory index does.
|
|
30
|
+
* Similarity is cosine (`distance_metric=cosine`): the returned `score` is
|
|
31
|
+
* `1 - cosineDistance`, i.e. cosine similarity in `[-1, 1]`, higher = more similar —
|
|
32
|
+
* byte-for-byte the same scoring contract as `InMemoryCosineIndex`.
|
|
33
|
+
*
|
|
34
|
+
* Query is a brute-force `vec0` KNN scan (not an ANN structure): correct and
|
|
35
|
+
* durable, appropriate for the same "thousands of records" regime the in-memory
|
|
36
|
+
* index targets. Large-N ANN indexing is explicitly out of scope — see the README.
|
|
37
|
+
*
|
|
38
|
+
* The `better-sqlite3` `Database` is consumer-owned (bring-your-own): this index
|
|
39
|
+
* loads the `sqlite-vec` extension onto it and reads/writes the table, but never
|
|
40
|
+
* opens or closes the connection.
|
|
41
|
+
* @public
|
|
42
|
+
*/
|
|
43
|
+
export class SqliteVecVectorIndex {
|
|
44
|
+
constructor(db, table, dimension) {
|
|
45
|
+
this._db = db;
|
|
46
|
+
this._table = table;
|
|
47
|
+
this._dimension = dimension;
|
|
48
|
+
this._stmts = dimension === undefined ? undefined : this._prepare();
|
|
49
|
+
}
|
|
50
|
+
/** The number of vectors currently held. Zero before the first `add`. */
|
|
51
|
+
get size() {
|
|
52
|
+
if (this._stmts === undefined) {
|
|
53
|
+
return 0;
|
|
54
|
+
}
|
|
55
|
+
return this._stmts.count.get().c;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Family-convention factory. Loads the `sqlite-vec` extension onto the supplied
|
|
59
|
+
* `better-sqlite3` connection and, if the vector table already exists (a reopened
|
|
60
|
+
* persistent file), recovers its established dimension so no re-embedding is
|
|
61
|
+
* needed on open.
|
|
62
|
+
*
|
|
63
|
+
* @param params - See {@link ISqliteVecVectorIndexCreateParams}.
|
|
64
|
+
* @returns `Success` with the index, or `Failure` if the table name is not a
|
|
65
|
+
* simple identifier or the extension fails to load.
|
|
66
|
+
*/
|
|
67
|
+
static create(params) {
|
|
68
|
+
var _a;
|
|
69
|
+
const table = (_a = params.tableName) !== null && _a !== void 0 ? _a : DEFAULT_TABLE_NAME;
|
|
70
|
+
if (!IDENTIFIER_RE.test(table)) {
|
|
71
|
+
return Promise.resolve(fail(`sqlite-vec index: table name '${table}' is not a simple SQL identifier`));
|
|
72
|
+
}
|
|
73
|
+
return Promise.resolve(captureResult(() => {
|
|
74
|
+
loadSqliteVec(params.database);
|
|
75
|
+
const dimension = SqliteVecVectorIndex._readExistingDimension(params.database, table);
|
|
76
|
+
return new SqliteVecVectorIndex(params.database, table, dimension);
|
|
77
|
+
}).withErrorFormat((e) => `sqlite-vec index: failed to initialize: ${e}`));
|
|
78
|
+
}
|
|
79
|
+
/** {@inheritDoc IVectorIndex.add} */
|
|
80
|
+
add(target, vector) {
|
|
81
|
+
const key = edgeTargetKey(target);
|
|
82
|
+
if (vector.length === 0) {
|
|
83
|
+
return Promise.resolve(fail(`vector index: cannot add '${key}': empty vector`));
|
|
84
|
+
}
|
|
85
|
+
if (this._dimension !== undefined && vector.length !== this._dimension) {
|
|
86
|
+
return Promise.resolve(fail(`vector index: cannot add '${key}': dimension ${vector.length} does not match index dimension ${this._dimension}`));
|
|
87
|
+
}
|
|
88
|
+
return Promise.resolve(captureResult(() => {
|
|
89
|
+
if (this._stmts === undefined) {
|
|
90
|
+
this._createTable(vector.length);
|
|
91
|
+
this._dimension = vector.length;
|
|
92
|
+
this._stmts = this._prepare();
|
|
93
|
+
}
|
|
94
|
+
this._stmts.replace(key, SqliteVecVectorIndex._toBlob(vector));
|
|
95
|
+
return key;
|
|
96
|
+
}).withErrorFormat((e) => `vector index: cannot add '${key}': ${e}`));
|
|
97
|
+
}
|
|
98
|
+
/** {@inheritDoc IVectorIndex.remove} */
|
|
99
|
+
remove(target) {
|
|
100
|
+
return Promise.resolve(captureResult(() => {
|
|
101
|
+
// Idempotent: removing a target with no embedding (or before any `add`
|
|
102
|
+
// created the table) still succeeds.
|
|
103
|
+
if (this._stmts !== undefined) {
|
|
104
|
+
this._stmts.delete.run(edgeTargetKey(target));
|
|
105
|
+
}
|
|
106
|
+
return target;
|
|
107
|
+
}).withErrorFormat((e) => `vector index: cannot remove '${edgeTargetKey(target)}': ${e}`));
|
|
108
|
+
}
|
|
109
|
+
/** {@inheritDoc IVectorIndex.query} */
|
|
110
|
+
query(vector, topK) {
|
|
111
|
+
if (topK <= 0 || this._stmts === undefined) {
|
|
112
|
+
return Promise.resolve(succeed([]));
|
|
113
|
+
}
|
|
114
|
+
if (vector.length !== this._dimension) {
|
|
115
|
+
return Promise.resolve(fail(`vector index: query dimension ${vector.length} does not match index dimension ${this._dimension}`));
|
|
116
|
+
}
|
|
117
|
+
return Promise.resolve(captureResult(() => {
|
|
118
|
+
const rows = this._stmts.query.all(SqliteVecVectorIndex._toBlob(vector), topK);
|
|
119
|
+
// sqlite-vec returns rows in ascending distance (nearest first); score is
|
|
120
|
+
// `1 - cosineDistance` = cosine similarity, so descending score is preserved.
|
|
121
|
+
return rows.map((row) => ({
|
|
122
|
+
target: SqliteVecVectorIndex._parseKey(row.target_key),
|
|
123
|
+
score: 1 - row.distance
|
|
124
|
+
}));
|
|
125
|
+
}).withErrorFormat((e) => `vector index: query failed: ${e}`));
|
|
126
|
+
}
|
|
127
|
+
/** Create the `vec0` virtual table with the established dimension. */
|
|
128
|
+
_createTable(dimension) {
|
|
129
|
+
this._db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS "${this._table}" USING vec0(` +
|
|
130
|
+
`target_key TEXT PRIMARY KEY, embedding float[${dimension}] distance_metric=cosine)`);
|
|
131
|
+
}
|
|
132
|
+
/** Prepare the statements the index reuses. Requires the table to exist. */
|
|
133
|
+
_prepare() {
|
|
134
|
+
const del = this._db.prepare(`DELETE FROM "${this._table}" WHERE target_key = ?`);
|
|
135
|
+
const ins = this._db.prepare(`INSERT INTO "${this._table}"(target_key, embedding) VALUES (?, ?)`);
|
|
136
|
+
// vec0 rejects INSERT OR REPLACE on a TEXT primary key, so replace is a
|
|
137
|
+
// delete-then-insert inside a single transaction.
|
|
138
|
+
const replaceTxn = this._db.transaction((key, blob) => {
|
|
139
|
+
del.run(key);
|
|
140
|
+
ins.run(key, blob);
|
|
141
|
+
});
|
|
142
|
+
return {
|
|
143
|
+
delete: del,
|
|
144
|
+
replace: (key, blob) => {
|
|
145
|
+
replaceTxn(key, blob);
|
|
146
|
+
},
|
|
147
|
+
query: this._db.prepare(`SELECT target_key, distance FROM "${this._table}" WHERE embedding MATCH ? AND k = ?`),
|
|
148
|
+
count: this._db.prepare(`SELECT count(*) AS c FROM "${this._table}"`)
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Recover the established dimension of an existing `vec0` table from its stored
|
|
153
|
+
* `CREATE VIRTUAL TABLE` SQL (`float[<n>]`). Returns `undefined` when the table
|
|
154
|
+
* does not exist yet (a fresh database — dimension is set by the first `add`).
|
|
155
|
+
*/
|
|
156
|
+
static _readExistingDimension(db, table) {
|
|
157
|
+
const row = db
|
|
158
|
+
.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?")
|
|
159
|
+
.get(table);
|
|
160
|
+
if (row === undefined) {
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
const match = row.sql.match(/float\[(\d+)\]/);
|
|
164
|
+
return match === null ? undefined : Number(match[1]);
|
|
165
|
+
}
|
|
166
|
+
/** Pack a `Float32Array` as the little-endian byte blob `vec0` stores. Copies, so the caller may reuse its buffer. */
|
|
167
|
+
static _toBlob(vector) {
|
|
168
|
+
return new Uint8Array(Float32Array.from(vector).buffer);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Reverse `edgeTargetKey` — the canonical key is `scope\0id` with NUL
|
|
172
|
+
* excluded from both components, so the first NUL splits it unambiguously.
|
|
173
|
+
*/
|
|
174
|
+
static _parseKey(key) {
|
|
175
|
+
const nul = key.indexOf('\0');
|
|
176
|
+
return {
|
|
177
|
+
scope: key.slice(0, nul),
|
|
178
|
+
id: key.slice(nul + 1)
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
//# sourceMappingURL=sqliteVecVectorIndex.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sqliteVecVectorIndex.js","sourceRoot":"","sources":["../../../src/packlets/sqlite-vec-index/sqliteVecVectorIndex.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,IAAI,IAAI,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAU,aAAa,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EAML,aAAa,EACd,MAAM,sBAAsB,CAAC;AAG9B,iDAAiD;AACjD,MAAM,kBAAkB,GAAW,gBAAgB,CAAC;AAEpD,yGAAyG;AACzG,MAAM,aAAa,GAAW,0BAA0B,CAAC;AAQzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,OAAO,oBAAoB;IAQ/B,YAAoB,EAA0B,EAAE,KAAa,EAAE,SAA6B;QAC1F,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;QACd,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QACpB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,MAAM,GAAG,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;IACtE,CAAC;IAED,yEAAyE;IACzE,IAAW,IAAI;QACb,IAAI,IAAI,CAAC,MAAM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AU,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC;IAC1D,CAAC;IAED;;;OAGG;IACK,MAAM,CAAC,SAAS,CAAC,GAAW;QAClC,MAAM,GAAG,GAAW,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACtC,OAAO;YACL,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAA8B;YACrD,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAwB;SAC9C,CAAC;IACJ,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport type BetterSqlite3 from 'better-sqlite3';\nimport { load as loadSqliteVec } from 'sqlite-vec';\nimport { Result, captureResult, fail, succeed } from '@fgv/ts-utils';\nimport {\n IEdgeTarget,\n IVectorIndex,\n IVectorQueryHit,\n MemoryId,\n MemoryScopeKey,\n edgeTargetKey\n} from '@fgv/ts-agent-memory';\nimport { ISqliteVecVectorIndexCreateParams } from './model';\n\n/** Default name for the `vec0` virtual table. */\nconst DEFAULT_TABLE_NAME: string = 'memory_vectors';\n\n/** A simple SQL identifier — the only shape allowed for the table name (it is interpolated into DDL). */\nconst IDENTIFIER_RE: RegExp = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** One KNN row as returned by the `vec0` MATCH query. */\ninterface IKnnRow {\n readonly target_key: string;\n readonly distance: number;\n}\n\n/**\n * A persistent, `sqlite-vec`-backed `IVectorIndex` for `@fgv/ts-agent-memory`.\n *\n * @remarks\n * This is the **durable** counterpart to the in-memory `InMemoryCosineIndex`:\n * embeddings live in a `sqlite-vec` `vec0` virtual table inside a `better-sqlite3`\n * database, so they survive a process restart. A consumer that wires this index\n * into `FileTreeMemoryStore` (instead of the in-memory index) opens an existing\n * vault **without re-embedding it** — the vectors are already on disk. New writes\n * still flow through the store's incremental embed-on-write path; there is no core\n * store change.\n *\n * The index is keyed by the canonical `edgeTargetKey` of each record's\n * scope-qualified `(scope, id)` address (a `TEXT PRIMARY KEY` on the `vec0` table),\n * so two records that share a filename stem across scopes never collide. The\n * dimension is established by the first `add` (the `vec0` column is fixed-width) and\n * recovered from the table schema when a persistent file is reopened; every later\n * `add`/`query` must match it or fail loudly, exactly as the in-memory index does.\n * Similarity is cosine (`distance_metric=cosine`): the returned `score` is\n * `1 - cosineDistance`, i.e. cosine similarity in `[-1, 1]`, higher = more similar —\n * byte-for-byte the same scoring contract as `InMemoryCosineIndex`.\n *\n * Query is a brute-force `vec0` KNN scan (not an ANN structure): correct and\n * durable, appropriate for the same \"thousands of records\" regime the in-memory\n * index targets. Large-N ANN indexing is explicitly out of scope — see the README.\n *\n * The `better-sqlite3` `Database` is consumer-owned (bring-your-own): this index\n * loads the `sqlite-vec` extension onto it and reads/writes the table, but never\n * opens or closes the connection.\n * @public\n */\nexport class SqliteVecVectorIndex implements IVectorIndex {\n private readonly _db: BetterSqlite3.Database;\n private readonly _table: string;\n /** The dimension of every stored vector; `undefined` until the table exists (first `add` or a reopened non-empty file). */\n private _dimension: number | undefined;\n /** Prepared statements; created once the table exists (established or recovered). */\n private _stmts: ISqliteVecStatements | undefined;\n\n private constructor(db: BetterSqlite3.Database, table: string, dimension: number | undefined) {\n this._db = db;\n this._table = table;\n this._dimension = dimension;\n this._stmts = dimension === undefined ? undefined : this._prepare();\n }\n\n /** The number of vectors currently held. Zero before the first `add`. */\n public get size(): number {\n if (this._stmts === undefined) {\n return 0;\n }\n return (this._stmts.count.get() as { c: number }).c;\n }\n\n /**\n * Family-convention factory. Loads the `sqlite-vec` extension onto the supplied\n * `better-sqlite3` connection and, if the vector table already exists (a reopened\n * persistent file), recovers its established dimension so no re-embedding is\n * needed on open.\n *\n * @param params - See {@link ISqliteVecVectorIndexCreateParams}.\n * @returns `Success` with the index, or `Failure` if the table name is not a\n * simple identifier or the extension fails to load.\n */\n public static create(params: ISqliteVecVectorIndexCreateParams): Promise<Result<SqliteVecVectorIndex>> {\n const table: string = params.tableName ?? DEFAULT_TABLE_NAME;\n if (!IDENTIFIER_RE.test(table)) {\n return Promise.resolve(fail(`sqlite-vec index: table name '${table}' is not a simple SQL identifier`));\n }\n return Promise.resolve(\n captureResult(() => {\n loadSqliteVec(params.database);\n const dimension: number | undefined = SqliteVecVectorIndex._readExistingDimension(\n params.database,\n table\n );\n return new SqliteVecVectorIndex(params.database, table, dimension);\n }).withErrorFormat((e) => `sqlite-vec index: failed to initialize: ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.add} */\n public add(target: IEdgeTarget, vector: Float32Array): Promise<Result<string>> {\n const key: string = edgeTargetKey(target);\n if (vector.length === 0) {\n return Promise.resolve(fail(`vector index: cannot add '${key}': empty vector`));\n }\n if (this._dimension !== undefined && vector.length !== this._dimension) {\n return Promise.resolve(\n fail(\n `vector index: cannot add '${key}': dimension ${vector.length} does not match index dimension ${this._dimension}`\n )\n );\n }\n return Promise.resolve(\n captureResult(() => {\n if (this._stmts === undefined) {\n this._createTable(vector.length);\n this._dimension = vector.length;\n this._stmts = this._prepare();\n }\n this._stmts.replace(key, SqliteVecVectorIndex._toBlob(vector));\n return key;\n }).withErrorFormat((e) => `vector index: cannot add '${key}': ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.remove} */\n public remove(target: IEdgeTarget): Promise<Result<IEdgeTarget>> {\n return Promise.resolve(\n captureResult(() => {\n // Idempotent: removing a target with no embedding (or before any `add`\n // created the table) still succeeds.\n if (this._stmts !== undefined) {\n this._stmts.delete.run(edgeTargetKey(target));\n }\n return target;\n }).withErrorFormat((e) => `vector index: cannot remove '${edgeTargetKey(target)}': ${e}`)\n );\n }\n\n /** {@inheritDoc IVectorIndex.query} */\n public query(vector: Float32Array, topK: number): Promise<Result<ReadonlyArray<IVectorQueryHit>>> {\n if (topK <= 0 || this._stmts === undefined) {\n return Promise.resolve(succeed([]));\n }\n if (vector.length !== this._dimension) {\n return Promise.resolve(\n fail(\n `vector index: query dimension ${vector.length} does not match index dimension ${this._dimension}`\n )\n );\n }\n return Promise.resolve(\n captureResult<ReadonlyArray<IVectorQueryHit>>(() => {\n const rows: ReadonlyArray<IKnnRow> = this._stmts!.query.all(\n SqliteVecVectorIndex._toBlob(vector),\n topK\n ) as ReadonlyArray<IKnnRow>;\n // sqlite-vec returns rows in ascending distance (nearest first); score is\n // `1 - cosineDistance` = cosine similarity, so descending score is preserved.\n return rows.map((row) => ({\n target: SqliteVecVectorIndex._parseKey(row.target_key),\n score: 1 - row.distance\n }));\n }).withErrorFormat((e) => `vector index: query failed: ${e}`)\n );\n }\n\n /** Create the `vec0` virtual table with the established dimension. */\n private _createTable(dimension: number): void {\n this._db.exec(\n `CREATE VIRTUAL TABLE IF NOT EXISTS \"${this._table}\" USING vec0(` +\n `target_key TEXT PRIMARY KEY, embedding float[${dimension}] distance_metric=cosine)`\n );\n }\n\n /** Prepare the statements the index reuses. Requires the table to exist. */\n private _prepare(): ISqliteVecStatements {\n const del: BetterSqlite3.Statement = this._db.prepare(\n `DELETE FROM \"${this._table}\" WHERE target_key = ?`\n );\n const ins: BetterSqlite3.Statement = this._db.prepare(\n `INSERT INTO \"${this._table}\"(target_key, embedding) VALUES (?, ?)`\n );\n // vec0 rejects INSERT OR REPLACE on a TEXT primary key, so replace is a\n // delete-then-insert inside a single transaction.\n const replaceTxn: BetterSqlite3.Transaction<(key: string, blob: Uint8Array) => void> =\n this._db.transaction((key: string, blob: Uint8Array) => {\n del.run(key);\n ins.run(key, blob);\n });\n return {\n delete: del,\n replace: (key: string, blob: Uint8Array): void => {\n replaceTxn(key, blob);\n },\n query: this._db.prepare(\n `SELECT target_key, distance FROM \"${this._table}\" WHERE embedding MATCH ? AND k = ?`\n ),\n count: this._db.prepare(`SELECT count(*) AS c FROM \"${this._table}\"`)\n };\n }\n\n /**\n * Recover the established dimension of an existing `vec0` table from its stored\n * `CREATE VIRTUAL TABLE` SQL (`float[<n>]`). Returns `undefined` when the table\n * does not exist yet (a fresh database — dimension is set by the first `add`).\n */\n private static _readExistingDimension(db: BetterSqlite3.Database, table: string): number | undefined {\n const row: { sql: string } | undefined = db\n .prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?\")\n .get(table) as { sql: string } | undefined;\n if (row === undefined) {\n return undefined;\n }\n const match: RegExpMatchArray | null = row.sql.match(/float\\[(\\d+)\\]/);\n return match === null ? undefined : Number(match[1]);\n }\n\n /** Pack a `Float32Array` as the little-endian byte blob `vec0` stores. Copies, so the caller may reuse its buffer. */\n private static _toBlob(vector: Float32Array): Uint8Array {\n return new Uint8Array(Float32Array.from(vector).buffer);\n }\n\n /**\n * Reverse `edgeTargetKey` — the canonical key is `scope\\0id` with NUL\n * excluded from both components, so the first NUL splits it unambiguously.\n */\n private static _parseKey(key: string): IEdgeTarget {\n const nul: number = key.indexOf('\\0');\n return {\n scope: key.slice(0, nul) as unknown as MemoryScopeKey,\n id: key.slice(nul + 1) as unknown as MemoryId\n };\n }\n}\n\n/** The prepared statements / helpers the index reuses once its table exists. */\ninterface ISqliteVecStatements {\n readonly delete: BetterSqlite3.Statement;\n readonly replace: (key: string, blob: Uint8Array) => void;\n readonly query: BetterSqlite3.Statement;\n readonly count: BetterSqlite3.Statement;\n}\n"]}
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2026 Erik Fortune
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
import '@fgv/ts-utils-jest';
|
|
6
|
+
import BetterSqlite3 from 'better-sqlite3';
|
|
7
|
+
import * as fs from 'fs';
|
|
8
|
+
import * as os from 'os';
|
|
9
|
+
import * as path from 'path';
|
|
10
|
+
import { SqliteVecFragmentIndex } from '../../index';
|
|
11
|
+
function target(scope, id) {
|
|
12
|
+
return { scope: scope, id: id };
|
|
13
|
+
}
|
|
14
|
+
function loc(start, end) {
|
|
15
|
+
return { start, end };
|
|
16
|
+
}
|
|
17
|
+
function frag(start, end, ...values) {
|
|
18
|
+
return { locator: loc(start, end), vector: Float32Array.from(values) };
|
|
19
|
+
}
|
|
20
|
+
describe('SqliteVecFragmentIndex', () => {
|
|
21
|
+
let db;
|
|
22
|
+
beforeEach(() => {
|
|
23
|
+
db = new BetterSqlite3(':memory:');
|
|
24
|
+
});
|
|
25
|
+
afterEach(() => {
|
|
26
|
+
// Some tests close `db` themselves to exercise error paths; guard double-close.
|
|
27
|
+
if (db.open) {
|
|
28
|
+
db.close();
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
async function makeIndex() {
|
|
32
|
+
return (await SqliteVecFragmentIndex.create({ database: db })).orThrow();
|
|
33
|
+
}
|
|
34
|
+
describe('create', () => {
|
|
35
|
+
test('succeeds over a fresh database with an empty index', async () => {
|
|
36
|
+
expect(await SqliteVecFragmentIndex.create({ database: db })).toSucceedAndSatisfy((index) => {
|
|
37
|
+
expect(index.recordCount).toBe(0);
|
|
38
|
+
expect(index.fragmentCount).toBe(0);
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
test('rejects a table name that is not a simple identifier', async () => {
|
|
42
|
+
expect(await SqliteVecFragmentIndex.create({ database: db, tableName: 'bad name; DROP TABLE x' })).toFailWith(/not a simple SQL identifier/i);
|
|
43
|
+
});
|
|
44
|
+
test('fails loudly when the sqlite-vec extension cannot load (closed database)', async () => {
|
|
45
|
+
const closed = new BetterSqlite3(':memory:');
|
|
46
|
+
closed.close();
|
|
47
|
+
expect(await SqliteVecFragmentIndex.create({ database: closed })).toFailWith(/failed to initialize/i);
|
|
48
|
+
});
|
|
49
|
+
test('recovers no dimension from a pre-existing non-vec0 table of the same name', async () => {
|
|
50
|
+
db.exec('CREATE TABLE memory_fragments (foo TEXT)');
|
|
51
|
+
expect(await SqliteVecFragmentIndex.create({ database: db })).toSucceedAndSatisfy((index) => {
|
|
52
|
+
expect(index.recordCount).toBe(0);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
describe('addFragments', () => {
|
|
57
|
+
test('stores every fragment and reports the count; tracks record/fragment counts', async () => {
|
|
58
|
+
const index = await makeIndex();
|
|
59
|
+
expect(await index.addFragments(target('knowledge', 'doc-a'), [frag(0, 5, 1, 0), frag(5, 10, 0, 1)])).toSucceedWith(2);
|
|
60
|
+
expect(index.recordCount).toBe(1);
|
|
61
|
+
expect(index.fragmentCount).toBe(2);
|
|
62
|
+
});
|
|
63
|
+
test('whole-record replace — a second addFragments drops the prior fragments', async () => {
|
|
64
|
+
const index = await makeIndex();
|
|
65
|
+
const t = target('knowledge', 'doc-a');
|
|
66
|
+
(await index.addFragments(t, [frag(0, 5, 1, 0), frag(5, 10, 0, 1)])).orThrow();
|
|
67
|
+
expect(await index.addFragments(t, [frag(0, 3, 1, 1)])).toSucceedWith(1);
|
|
68
|
+
expect(index.recordCount).toBe(1);
|
|
69
|
+
expect(index.fragmentCount).toBe(1);
|
|
70
|
+
expect(await index.query(Float32Array.from([1, 1]), 5)).toSucceedAndSatisfy((hits) => {
|
|
71
|
+
expect(hits).toHaveLength(1);
|
|
72
|
+
expect(hits[0].locator).toEqual(loc(0, 3));
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
test('an empty fragments array drops an existing record', async () => {
|
|
76
|
+
const index = await makeIndex();
|
|
77
|
+
const t = target('knowledge', 'doc-a');
|
|
78
|
+
(await index.addFragments(t, [frag(0, 5, 1, 0)])).orThrow();
|
|
79
|
+
expect(await index.addFragments(t, [])).toSucceedWith(0);
|
|
80
|
+
expect(index.recordCount).toBe(0);
|
|
81
|
+
expect(index.fragmentCount).toBe(0);
|
|
82
|
+
});
|
|
83
|
+
test('an empty fragments array on a fresh index is a no-op (no table created)', async () => {
|
|
84
|
+
const index = await makeIndex();
|
|
85
|
+
expect(await index.addFragments(target('knowledge', 'doc-a'), [])).toSucceedWith(0);
|
|
86
|
+
expect(index.recordCount).toBe(0);
|
|
87
|
+
// A later real add still establishes the dimension cleanly.
|
|
88
|
+
expect(await index.addFragments(target('knowledge', 'doc-b'), [frag(0, 5, 1, 0)])).toSucceedWith(1);
|
|
89
|
+
});
|
|
90
|
+
test('same stem in different scopes are distinct entries', async () => {
|
|
91
|
+
const index = await makeIndex();
|
|
92
|
+
(await index.addFragments(target('conversations/a', 'turn-3'), [frag(0, 5, 1, 0)])).orThrow();
|
|
93
|
+
(await index.addFragments(target('conversations/b', 'turn-3'), [frag(0, 5, 0, 1)])).orThrow();
|
|
94
|
+
expect(index.recordCount).toBe(2);
|
|
95
|
+
expect(index.fragmentCount).toBe(2);
|
|
96
|
+
});
|
|
97
|
+
test('fails loudly on an empty fragment vector — and stores nothing', async () => {
|
|
98
|
+
const index = await makeIndex();
|
|
99
|
+
expect(await index.addFragments(target('knowledge', 'doc-a'), [frag(0, 5, 1, 0), frag(5, 10)])).toFailWith(/cannot add 'knowledge\0doc-a': empty fragment vector/i);
|
|
100
|
+
expect(index.recordCount).toBe(0);
|
|
101
|
+
});
|
|
102
|
+
test('fails loudly on a fragment-dimension mismatch against the established dimension', async () => {
|
|
103
|
+
const index = await makeIndex();
|
|
104
|
+
(await index.addFragments(target('knowledge', 'a'), [frag(0, 5, 1, 0)])).orThrow();
|
|
105
|
+
expect(await index.addFragments(target('knowledge', 'b'), [frag(0, 5, 1, 0, 0)])).toFailWith(/fragment dimension 3 does not match index dimension 2/i);
|
|
106
|
+
});
|
|
107
|
+
test('rejects a non-safe-integer locator offset up front (never persists an unreadable locator)', async () => {
|
|
108
|
+
const index = await makeIndex();
|
|
109
|
+
// A non-integer offset: reject before the write, with a clear message.
|
|
110
|
+
expect(await index.addFragments(target('knowledge', 'doc-a'), [frag(0.5, 5, 1, 0)])).toFailWith(/locator \[0\.5, 5\) offsets must be safe integers/i);
|
|
111
|
+
// A too-large (non-safe) integer offset is likewise rejected.
|
|
112
|
+
expect(await index.addFragments(target('knowledge', 'doc-b'), [frag(0, Number.MAX_SAFE_INTEGER + 1, 1, 0)])).toFailWith(/offsets must be safe integers/i);
|
|
113
|
+
expect(index.recordCount).toBe(0);
|
|
114
|
+
});
|
|
115
|
+
test('a failed multi-fragment add on a fresh index does not establish a dimension (all-or-nothing)', async () => {
|
|
116
|
+
const index = await makeIndex();
|
|
117
|
+
// dim 2 then dim 3 in the same batch: fails, and must NOT commit dim 2.
|
|
118
|
+
expect(await index.addFragments(target('knowledge', 'doc-1'), [frag(0, 5, 1, 0), frag(5, 10, 1, 0, 0)])).toFailWith(/fragment dimension 3 does not match index dimension 2/i);
|
|
119
|
+
expect(index.recordCount).toBe(0);
|
|
120
|
+
// A fresh dim-3 record now indexes cleanly (the index was never poisoned to dim 2).
|
|
121
|
+
expect(await index.addFragments(target('knowledge', 'doc-2'), [frag(0, 5, 1, 0, 0)])).toSucceedWith(1);
|
|
122
|
+
});
|
|
123
|
+
test('fails loudly (best-effort caller unaffected) when the underlying add throws', async () => {
|
|
124
|
+
const index = await makeIndex();
|
|
125
|
+
(await index.addFragments(target('knowledge', 'doc-a'), [frag(0, 5, 1, 0)])).orThrow();
|
|
126
|
+
db.close();
|
|
127
|
+
expect(await index.addFragments(target('knowledge', 'doc-b'), [frag(0, 5, 0, 1)])).toFailWith(/cannot add 'knowledge\0doc-b'/i);
|
|
128
|
+
});
|
|
129
|
+
test('fails loudly (never silently corrupts) when the table name collides with a non-vec0 table', async () => {
|
|
130
|
+
// A plain table already occupies the default name. `CREATE VIRTUAL TABLE IF NOT
|
|
131
|
+
// EXISTS` no-ops against it, so preparing the vector INSERT against the missing
|
|
132
|
+
// columns must fail loudly rather than corrupt state.
|
|
133
|
+
db.exec('CREATE TABLE memory_fragments (foo TEXT)');
|
|
134
|
+
const index = (await SqliteVecFragmentIndex.create({ database: db })).orThrow();
|
|
135
|
+
expect(await index.addFragments(target('knowledge', 'doc-a'), [frag(0, 5, 1, 0)])).toFailWith(/cannot add 'knowledge\0doc-a'/i);
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
describe('query', () => {
|
|
139
|
+
async function seeded() {
|
|
140
|
+
const index = await makeIndex();
|
|
141
|
+
(await index.addFragments(target('knowledge', 'doc-a'), [frag(0, 5, 1, 0), frag(5, 10, 0, 1)])).orThrow();
|
|
142
|
+
(await index.addFragments(target('knowledge', 'doc-b'), [frag(0, 5, 1, 1)])).orThrow();
|
|
143
|
+
return index;
|
|
144
|
+
}
|
|
145
|
+
test('returns fragment hits in descending score order, each carrying its locator', async () => {
|
|
146
|
+
const index = await seeded();
|
|
147
|
+
expect(await index.query(Float32Array.from([1, 0]), 3)).toSucceedAndSatisfy((hits) => {
|
|
148
|
+
expect(hits[0].target.id).toBe('doc-a');
|
|
149
|
+
expect(hits[0].locator).toEqual(loc(0, 5));
|
|
150
|
+
expect(hits[0].score).toBeCloseTo(1, 5);
|
|
151
|
+
expect(hits[1].target.id).toBe('doc-b');
|
|
152
|
+
expect(hits[1].score).toBeCloseTo(1 / Math.sqrt(2), 5);
|
|
153
|
+
expect(hits[2].target.id).toBe('doc-a');
|
|
154
|
+
expect(hits[2].locator).toEqual(loc(5, 10));
|
|
155
|
+
expect(hits[2].score).toBeCloseTo(0, 5);
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
test('truncates to topK', async () => {
|
|
159
|
+
const index = await seeded();
|
|
160
|
+
expect(await index.query(Float32Array.from([1, 0]), 2)).toSucceedAndSatisfy((hits) => {
|
|
161
|
+
expect(hits).toHaveLength(2);
|
|
162
|
+
expect(hits.map((h) => h.target.id)).toEqual(['doc-a', 'doc-b']);
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
test('maxPerRecord caps fragments per record during selection (before the topK cut)', async () => {
|
|
166
|
+
const index = await makeIndex();
|
|
167
|
+
(await index.addFragments(target('knowledge', 'doc-a'), [
|
|
168
|
+
frag(0, 5, 1, 0),
|
|
169
|
+
frag(5, 10, 0.9, 0.1),
|
|
170
|
+
frag(10, 15, 0.8, 0.2)
|
|
171
|
+
])).orThrow();
|
|
172
|
+
(await index.addFragments(target('knowledge', 'doc-b'), [frag(0, 5, 0.7, 0.3)])).orThrow();
|
|
173
|
+
// Without a cap the top-2 would be doc-a twice; maxPerRecord=1 surfaces doc-b.
|
|
174
|
+
expect(await index.query(Float32Array.from([1, 0]), 2, 1)).toSucceedAndSatisfy((hits) => {
|
|
175
|
+
expect(hits).toHaveLength(2);
|
|
176
|
+
expect(hits.map((h) => h.target.id)).toEqual(['doc-a', 'doc-b']);
|
|
177
|
+
expect(hits[0].locator).toEqual(loc(0, 5));
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
test('maxPerRecord=0 yields no hits', async () => {
|
|
181
|
+
const index = await seeded();
|
|
182
|
+
expect(await index.query(Float32Array.from([1, 0]), 5, 0)).toSucceedWith([]);
|
|
183
|
+
});
|
|
184
|
+
test('maxPerRecord larger than any record leaves the ranking unchanged', async () => {
|
|
185
|
+
const index = await seeded();
|
|
186
|
+
expect(await index.query(Float32Array.from([1, 0]), 5, 10)).toSucceedAndSatisfy((hits) => {
|
|
187
|
+
expect(hits).toHaveLength(3);
|
|
188
|
+
expect(hits[0].target.id).toBe('doc-a');
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
test('returns empty for a non-positive topK', async () => {
|
|
192
|
+
const index = await seeded();
|
|
193
|
+
expect(await index.query(Float32Array.from([1, 0]), 0)).toSucceedWith([]);
|
|
194
|
+
expect(await index.query(Float32Array.from([1, 0]), -5)).toSucceedWith([]);
|
|
195
|
+
});
|
|
196
|
+
test('returns empty before any add (no established dimension)', async () => {
|
|
197
|
+
const index = await makeIndex();
|
|
198
|
+
expect(await index.query(Float32Array.from([1, 0, 0]), 5)).toSucceedWith([]);
|
|
199
|
+
});
|
|
200
|
+
test('returns empty when a capped query runs against an emptied (but existing) table', async () => {
|
|
201
|
+
const index = await makeIndex();
|
|
202
|
+
const t = target('knowledge', 'doc-a');
|
|
203
|
+
(await index.addFragments(t, [frag(0, 5, 1, 0)])).orThrow();
|
|
204
|
+
(await index.addFragments(t, [])).orThrow(); // table now exists but holds 0 rows
|
|
205
|
+
// fetchK derives from the (zero) fragment count under a cap → short-circuits to [].
|
|
206
|
+
expect(await index.query(Float32Array.from([1, 0]), 5, 2)).toSucceedWith([]);
|
|
207
|
+
});
|
|
208
|
+
test('rejects a query vector of the wrong dimension', async () => {
|
|
209
|
+
const index = await seeded();
|
|
210
|
+
expect(await index.query(Float32Array.from([1, 0, 0]), 3)).toFailWith(/query dimension 3 does not match index dimension 2/i);
|
|
211
|
+
});
|
|
212
|
+
test('a capped query stops at topK even when more ranked rows remain', async () => {
|
|
213
|
+
// maxPerRecord makes the fetch span the full ranked set (3 fragments), but
|
|
214
|
+
// topK=1 must return exactly one hit — the top row — and stop.
|
|
215
|
+
const index = await seeded();
|
|
216
|
+
expect(await index.query(Float32Array.from([1, 0]), 1, 5)).toSucceedAndSatisfy((hits) => {
|
|
217
|
+
expect(hits).toHaveLength(1);
|
|
218
|
+
expect(hits[0].target.id).toBe('doc-a');
|
|
219
|
+
expect(hits[0].locator).toEqual(loc(0, 5));
|
|
220
|
+
});
|
|
221
|
+
});
|
|
222
|
+
test('fails loudly when the underlying query throws', async () => {
|
|
223
|
+
const index = await seeded();
|
|
224
|
+
db.close();
|
|
225
|
+
expect(await index.query(Float32Array.from([1, 0]), 3)).toFailWith(/query failed/i);
|
|
226
|
+
});
|
|
227
|
+
});
|
|
228
|
+
describe('remove', () => {
|
|
229
|
+
test('removes every fragment of a record and is reflected in subsequent queries', async () => {
|
|
230
|
+
const index = await makeIndex();
|
|
231
|
+
const a = target('knowledge', 'doc-a');
|
|
232
|
+
const b = target('knowledge', 'doc-b');
|
|
233
|
+
(await index.addFragments(a, [frag(0, 5, 1, 0), frag(5, 10, 1, 0)])).orThrow();
|
|
234
|
+
(await index.addFragments(b, [frag(0, 5, 0, 1)])).orThrow();
|
|
235
|
+
expect(await index.remove(a)).toSucceedWith(a);
|
|
236
|
+
expect(index.recordCount).toBe(1);
|
|
237
|
+
expect(index.fragmentCount).toBe(1);
|
|
238
|
+
expect(await index.query(Float32Array.from([1, 0]), 5)).toSucceedAndSatisfy((hits) => {
|
|
239
|
+
expect(hits.map((h) => h.target.id)).toEqual(['doc-b']);
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
test('is idempotent — removing a missing target succeeds', async () => {
|
|
243
|
+
const index = await makeIndex();
|
|
244
|
+
(await index.addFragments(target('knowledge', 'doc-a'), [frag(0, 5, 1, 0)])).orThrow();
|
|
245
|
+
expect(await index.remove(target('knowledge', 'missing'))).toSucceedWith(target('knowledge', 'missing'));
|
|
246
|
+
expect(index.recordCount).toBe(1);
|
|
247
|
+
});
|
|
248
|
+
test('succeeds before any add (no table yet)', async () => {
|
|
249
|
+
const index = await makeIndex();
|
|
250
|
+
expect(await index.remove(target('knowledge', 'doc-a'))).toSucceedWith(target('knowledge', 'doc-a'));
|
|
251
|
+
expect(index.recordCount).toBe(0);
|
|
252
|
+
});
|
|
253
|
+
test('fails loudly when the underlying remove throws', async () => {
|
|
254
|
+
const index = await makeIndex();
|
|
255
|
+
(await index.addFragments(target('knowledge', 'doc-a'), [frag(0, 5, 1, 0)])).orThrow();
|
|
256
|
+
db.close();
|
|
257
|
+
expect(await index.remove(target('knowledge', 'doc-a'))).toFailWith(/cannot remove 'knowledge\0doc-a'/i);
|
|
258
|
+
});
|
|
259
|
+
});
|
|
260
|
+
describe('safe-integer mode and corrupt persisted data', () => {
|
|
261
|
+
const toBlob = (...v) => new Uint8Array(Float32Array.from(v).buffer);
|
|
262
|
+
async function seededWithRow() {
|
|
263
|
+
// A valid add creates the table and establishes dim 2; corrupt rows are then
|
|
264
|
+
// inserted directly to model externally-edited / safe-integer-mode data.
|
|
265
|
+
const index = await makeIndex();
|
|
266
|
+
(await index.addFragments(target('knowledge', 'doc-a'), [frag(0, 5, 1, 0)])).orThrow();
|
|
267
|
+
return index;
|
|
268
|
+
}
|
|
269
|
+
function insertRaw(key, start, end, ...vec) {
|
|
270
|
+
db.prepare('INSERT INTO memory_fragments(target_key, embedding, start_off, end_off) VALUES (?, ?, ?, ?)').run(key, toBlob(...vec), start, end);
|
|
271
|
+
}
|
|
272
|
+
test('coerces bigint offsets (better-sqlite3 safe-integer mode) to number locators', async () => {
|
|
273
|
+
const index = await seededWithRow();
|
|
274
|
+
// Under safe-integer mode every integer column comes back as a bigint.
|
|
275
|
+
db.defaultSafeIntegers(true);
|
|
276
|
+
expect(await index.query(Float32Array.from([1, 0]), 1)).toSucceedAndSatisfy((hits) => {
|
|
277
|
+
const locator = hits[0].locator;
|
|
278
|
+
expect(locator).toEqual(loc(0, 5));
|
|
279
|
+
expect(typeof (locator === null || locator === void 0 ? void 0 : locator.start)).toBe('number');
|
|
280
|
+
expect(typeof (locator === null || locator === void 0 ? void 0 : locator.end)).toBe('number');
|
|
281
|
+
});
|
|
282
|
+
});
|
|
283
|
+
test('fails loudly when a stored offset is outside the safe-integer range', async () => {
|
|
284
|
+
const index = await seededWithRow();
|
|
285
|
+
// Safe-integer mode returns the huge offset as a bigint (no read-time throw),
|
|
286
|
+
// so the _toOffset guard is what must fire.
|
|
287
|
+
db.defaultSafeIntegers(true);
|
|
288
|
+
insertRaw('knowledge\0doc-b', BigInt(2) ** BigInt(60), BigInt(0), 0, 1);
|
|
289
|
+
expect(await index.query(Float32Array.from([0, 1]), 5)).toFailWith(/locator offset .* is not a safe integer/i);
|
|
290
|
+
});
|
|
291
|
+
test('fails loudly when a stored key is missing the NUL separator', async () => {
|
|
292
|
+
const index = await seededWithRow();
|
|
293
|
+
insertRaw('nonulkey', BigInt(0), BigInt(5), 0, 1);
|
|
294
|
+
expect(await index.query(Float32Array.from([0, 1]), 5)).toFailWith(/missing scope\/id separator/i);
|
|
295
|
+
});
|
|
296
|
+
});
|
|
297
|
+
describe('custom table name', () => {
|
|
298
|
+
test('two fragment indexes on distinct tables in one database are independent', async () => {
|
|
299
|
+
const a = (await SqliteVecFragmentIndex.create({ database: db, tableName: 'frag_a' })).orThrow();
|
|
300
|
+
const b = (await SqliteVecFragmentIndex.create({ database: db, tableName: 'frag_b' })).orThrow();
|
|
301
|
+
(await a.addFragments(target('s', 'one'), [frag(0, 5, 1, 0)])).orThrow();
|
|
302
|
+
expect(a.fragmentCount).toBe(1);
|
|
303
|
+
expect(b.fragmentCount).toBe(0);
|
|
304
|
+
});
|
|
305
|
+
});
|
|
306
|
+
describe('persistence across reopen (the durability guarantee)', () => {
|
|
307
|
+
let dir;
|
|
308
|
+
let dbPath;
|
|
309
|
+
beforeEach(() => {
|
|
310
|
+
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'svfrag-'));
|
|
311
|
+
dbPath = path.join(dir, 'fragments.db');
|
|
312
|
+
});
|
|
313
|
+
afterEach(() => {
|
|
314
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
315
|
+
});
|
|
316
|
+
test('fragments written to a file survive a close + reopen with no re-embed, dimension + locators recovered', async () => {
|
|
317
|
+
const first = new BetterSqlite3(dbPath);
|
|
318
|
+
const writeIndex = (await SqliteVecFragmentIndex.create({ database: first })).orThrow();
|
|
319
|
+
(await writeIndex.addFragments(target('knowledge', 'doc-a'), [
|
|
320
|
+
frag(0, 5, 1, 0, 0),
|
|
321
|
+
frag(5, 12, 0, 1, 0)
|
|
322
|
+
])).orThrow();
|
|
323
|
+
(await writeIndex.addFragments(target('conversations/c', 'turn-1'), [frag(0, 8, 0.9, 0.1, 0)])).orThrow();
|
|
324
|
+
first.close();
|
|
325
|
+
// Second session: a brand-new connection + index over the same file. No adds
|
|
326
|
+
// (no re-embedding) — fragments, dimension, and locators come straight off disk.
|
|
327
|
+
const second = new BetterSqlite3(dbPath);
|
|
328
|
+
const reopened = (await SqliteVecFragmentIndex.create({ database: second })).orThrow();
|
|
329
|
+
try {
|
|
330
|
+
expect(reopened.recordCount).toBe(2);
|
|
331
|
+
expect(reopened.fragmentCount).toBe(3);
|
|
332
|
+
expect(await reopened.query(Float32Array.from([1, 0, 0]), 3)).toSucceedAndSatisfy((hits) => {
|
|
333
|
+
expect(hits[0].target).toEqual(target('knowledge', 'doc-a'));
|
|
334
|
+
expect(hits[0].locator).toEqual(loc(0, 5));
|
|
335
|
+
expect(hits[0].score).toBeCloseTo(1, 5);
|
|
336
|
+
// the cross-scope target round-trips its full (scope, id) and locator
|
|
337
|
+
expect(hits[1].target).toEqual(target('conversations/c', 'turn-1'));
|
|
338
|
+
expect(hits[1].locator).toEqual(loc(0, 8));
|
|
339
|
+
});
|
|
340
|
+
// The recovered dimension is enforced on a post-reopen add.
|
|
341
|
+
expect(await reopened.addFragments(target('knowledge', 'w'), [frag(0, 4, 1, 0)])).toFailWith(/fragment dimension 2 does not match index dimension 3/i);
|
|
342
|
+
// A matching-dimension add still works and persists incrementally.
|
|
343
|
+
(await reopened.addFragments(target('knowledge', 'w'), [frag(0, 4, 0, 0, 1)])).orThrow();
|
|
344
|
+
expect(reopened.recordCount).toBe(3);
|
|
345
|
+
}
|
|
346
|
+
finally {
|
|
347
|
+
second.close();
|
|
348
|
+
}
|
|
349
|
+
});
|
|
350
|
+
});
|
|
351
|
+
});
|
|
352
|
+
//# sourceMappingURL=sqliteVecFragmentIndex.test.js.map
|