@gmickel/gno 2.16.0 → 2.17.0

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.
Files changed (46) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/SKILL.md +27 -0
  3. package/assets/skill/cli-reference.md +20 -13
  4. package/browser-extension/artifacts/{gno-browser-clipper-v2.16.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
  5. package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
  6. package/browser-extension/dist/manifest.json +1 -1
  7. package/package.json +1 -1
  8. package/spec/cli.md +42 -2
  9. package/spec/db/schema.sql +53 -1
  10. package/spec/mcp.md +9 -3
  11. package/spec/output-schemas/doctor.schema.json +27 -0
  12. package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
  13. package/spec/output-schemas/search-results.schema.json +14 -0
  14. package/spec/output-schemas/status.schema.json +22 -0
  15. package/src/cli/commands/doctor.ts +101 -29
  16. package/src/cli/commands/links.ts +29 -5
  17. package/src/cli/commands/vec.ts +180 -8
  18. package/src/cli/program.ts +43 -0
  19. package/src/config/types.ts +6 -0
  20. package/src/core/retrieval-trace-session.ts +3 -0
  21. package/src/core/retrieval-trace.ts +9 -0
  22. package/src/core/vector-partition-status.ts +13 -0
  23. package/src/embed/variant-backlog.ts +36 -2
  24. package/src/mcp/tools/links.ts +7 -1
  25. package/src/pipeline/explain.ts +17 -2
  26. package/src/pipeline/hybrid.ts +28 -1
  27. package/src/pipeline/types.ts +7 -0
  28. package/src/pipeline/vsearch.ts +19 -2
  29. package/src/serve/public/globals.built.css +1 -1
  30. package/src/serve/routes/links.ts +7 -1
  31. package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
  32. package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
  33. package/src/store/migrations/index.ts +4 -0
  34. package/src/store/sqlite/adapter.ts +117 -74
  35. package/src/store/vector/coarse-router.ts +312 -0
  36. package/src/store/vector/partition-index.ts +309 -18
  37. package/src/store/vector/proof-cache.ts +132 -26
  38. package/src/store/vector/runtime-compat.ts +6 -0
  39. package/src/store/vector/sqlite-vec.ts +43 -26
  40. package/src/store/vector/stats.ts +8 -0
  41. package/src/store/vector/status.ts +18 -1
  42. package/src/store/vector/types.ts +9 -0
  43. package/src/store/vector/v2-mirror.ts +669 -0
  44. package/src/store/vector/variant-search.ts +434 -20
  45. package/src/store/vector/variants.ts +480 -32
  46. package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +0 -1
@@ -0,0 +1,669 @@
1
+ /**
2
+ * V2 bit coarse `vec0` mirror lifecycle and build-time recall self-check (fn-235).
3
+ *
4
+ * Maintains `vec_v2_<partitionId>` (`collection TEXT PARTITION KEY`, `coarse bit[dims]`),
5
+ * `vector_partition_rows`, and `vector_mirror_v2_state` purely in SQL from
6
+ * `vector_variants` and `vector_owners` without re-embedding and without moving
7
+ * embedding BLOBs into JS during builds.
8
+ *
9
+ * @module src/store/vector/v2-mirror
10
+ */
11
+ import type { Database } from "bun:sqlite";
12
+
13
+ import {
14
+ COARSE_ROUTER_DEFAULTS,
15
+ isPartitionAboveBudget,
16
+ isV2CompatibleDimensions,
17
+ v2TableName,
18
+ } from "./coarse-router";
19
+
20
+ export interface V2MirrorStateRow {
21
+ dirty: number;
22
+ checkRecall: number | null;
23
+ checkQueries: number | null;
24
+ checkCoarseK: number | null;
25
+ }
26
+
27
+ export interface V2MirrorStatusInfo {
28
+ state: "clean" | "dirty" | "missing" | "unsupported";
29
+ checkRecall: number | null;
30
+ checkQueries: number | null;
31
+ checkCoarseK: number | null;
32
+ belowFloor: boolean;
33
+ }
34
+
35
+ export interface V2SyncCounts {
36
+ added: number;
37
+ removed: number;
38
+ skipped?: boolean;
39
+ }
40
+
41
+ export interface V2RecallCheckResult {
42
+ ran: boolean;
43
+ recall: number | null;
44
+ queries: number;
45
+ coarseK: number;
46
+ reason?: string;
47
+ }
48
+
49
+ export function hasV2MirrorTables(db: Database): boolean {
50
+ const row = db
51
+ .query<{ c: number }, []>(
52
+ `SELECT COUNT(*) AS c FROM sqlite_master
53
+ WHERE type = 'table'
54
+ AND name IN ('vector_partition_rows', 'vector_mirror_v2_state')`
55
+ )
56
+ .get();
57
+ return (row?.c ?? 0) === 2;
58
+ }
59
+
60
+ export function hasV2Table(db: Database, partitionId: string): boolean {
61
+ return Boolean(
62
+ db
63
+ .query(
64
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1"
65
+ )
66
+ .get(v2TableName(partitionId))
67
+ );
68
+ }
69
+
70
+ export function readV2MirrorState(
71
+ db: Database,
72
+ partitionId: string
73
+ ): V2MirrorStateRow | null {
74
+ if (!hasV2MirrorTables(db)) return null;
75
+ const row = db
76
+ .query<
77
+ {
78
+ dirty: number;
79
+ check_recall: number | null;
80
+ check_queries: number | null;
81
+ check_coarse_k: number | null;
82
+ },
83
+ [string]
84
+ >(
85
+ `SELECT dirty, check_recall, check_queries, check_coarse_k
86
+ FROM vector_mirror_v2_state
87
+ WHERE partition_id = ?`
88
+ )
89
+ .get(partitionId);
90
+ if (!row) return null;
91
+ return {
92
+ dirty: row.dirty,
93
+ checkRecall: row.check_recall,
94
+ checkQueries: row.check_queries,
95
+ checkCoarseK: row.check_coarse_k,
96
+ };
97
+ }
98
+
99
+ export function markV2MirrorClean(
100
+ db: Database,
101
+ partitionId: string,
102
+ check: { recall: number; queries: number; coarseK: number } | null = null
103
+ ): void {
104
+ if (!hasV2MirrorTables(db)) return;
105
+ db.run(
106
+ `INSERT OR REPLACE INTO vector_mirror_v2_state
107
+ (partition_id, dirty, check_recall, check_queries, check_coarse_k)
108
+ VALUES (?, 0, ?, ?, ?)`,
109
+ [
110
+ partitionId,
111
+ check?.recall ?? null,
112
+ check?.queries ?? null,
113
+ check?.coarseK ?? null,
114
+ ]
115
+ );
116
+ }
117
+
118
+ export function ensureV2Table(
119
+ db: Database,
120
+ partitionId: string,
121
+ dimensions: number
122
+ ): boolean {
123
+ if (!isV2CompatibleDimensions(dimensions)) return false;
124
+ const table = v2TableName(partitionId);
125
+ db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS "${table}" USING vec0(
126
+ collection TEXT PARTITION KEY,
127
+ coarse bit[${dimensions}]
128
+ )`);
129
+ return true;
130
+ }
131
+
132
+ /**
133
+ * Inspect v2 mirror freshness for a partition (parallel to v1's `mirrorState()`).
134
+ */
135
+ export function v2MirrorFreshnessState(
136
+ db: Database,
137
+ partitionId: string,
138
+ dimensions: number,
139
+ searchAvailable: boolean
140
+ ): "clean" | "dirty" | "missing" | "unsupported" {
141
+ if (!isV2CompatibleDimensions(dimensions)) return "unsupported";
142
+ if (!searchAvailable || !hasV2MirrorTables(db)) return "missing";
143
+ const table = v2TableName(partitionId);
144
+ if (!hasV2Table(db, partitionId)) return "missing";
145
+ const state = readV2MirrorState(db, partitionId);
146
+ if (state?.dirty !== 0) return "dirty";
147
+ const mapped =
148
+ db
149
+ .query<{ n: number }, [string]>(
150
+ "SELECT COUNT(*) AS n FROM vector_partition_rows WHERE partition_id = ?"
151
+ )
152
+ .get(partitionId)?.n ?? 0;
153
+ const mirrored =
154
+ db.query<{ n: number }, []>(`SELECT COUNT(*) AS n FROM "${table}"`).get()
155
+ ?.n ?? 0;
156
+ return mapped === mirrored ? "clean" : "dirty";
157
+ }
158
+
159
+ /**
160
+ * Report v2 mirror status for `gno status` and `gno doctor` without loading sqlite-vec.
161
+ */
162
+ export function getV2MirrorStatus(
163
+ db: Database,
164
+ partitionId: string,
165
+ dimensions: number
166
+ ): V2MirrorStatusInfo {
167
+ if (!isV2CompatibleDimensions(dimensions)) {
168
+ return {
169
+ state: "unsupported",
170
+ checkRecall: null,
171
+ checkQueries: null,
172
+ checkCoarseK: null,
173
+ belowFloor: false,
174
+ };
175
+ }
176
+ if (!hasV2MirrorTables(db) || !hasV2Table(db, partitionId)) {
177
+ return {
178
+ state: "missing",
179
+ checkRecall: null,
180
+ checkQueries: null,
181
+ checkCoarseK: null,
182
+ belowFloor: false,
183
+ };
184
+ }
185
+ const state = readV2MirrorState(db, partitionId);
186
+ const checkRecall = state?.checkRecall ?? null;
187
+ const belowFloor =
188
+ checkRecall !== null &&
189
+ checkRecall < COARSE_ROUTER_DEFAULTS.selfCheckRecallFloor;
190
+ return {
191
+ state: state?.dirty === 0 ? "clean" : "dirty",
192
+ checkRecall,
193
+ checkQueries: state?.checkQueries ?? null,
194
+ checkCoarseK: state?.checkCoarseK ?? null,
195
+ belowFloor,
196
+ };
197
+ }
198
+
199
+ /**
200
+ * Incrementally sync `vector_partition_rows` and `vec_v2_<partitionId>` from
201
+ * `vector_owners` + `vector_variants` purely in SQL (caller holds sqlite-vec
202
+ * loaded; runs inside caller's transaction or starts an immediate tx).
203
+ */
204
+ export function syncV2PartitionMirrorInTx(
205
+ db: Database,
206
+ partitionId: string,
207
+ dimensions: number
208
+ ): V2SyncCounts {
209
+ if (!hasV2MirrorTables(db) || !isV2CompatibleDimensions(dimensions)) {
210
+ return { added: 0, removed: 0, skipped: true };
211
+ }
212
+ const tableExisted = hasV2Table(db, partitionId);
213
+ ensureV2Table(db, partitionId, dimensions);
214
+ const table = v2TableName(partitionId);
215
+ const prior = readV2MirrorState(db, partitionId);
216
+
217
+ // 1. Remove mapping rows whose (collection, variant_id) is no longer owned
218
+ // in this partition or whose variant was deleted.
219
+ const staleRows = db
220
+ .query<{ id: number }, [string]>(
221
+ `SELECT r.id
222
+ FROM vector_partition_rows r
223
+ WHERE r.partition_id = ?
224
+ AND (
225
+ NOT EXISTS (
226
+ SELECT 1 FROM vector_variants v
227
+ WHERE v.partition_id = r.partition_id AND v.variant_id = r.variant_id
228
+ )
229
+ OR NOT EXISTS (
230
+ SELECT 1 FROM vector_owners o
231
+ JOIN documents d ON d.id = o.document_id
232
+ WHERE o.partition_id = r.partition_id
233
+ AND o.variant_id = r.variant_id
234
+ AND d.collection = r.collection
235
+ )
236
+ )`
237
+ )
238
+ .all(partitionId);
239
+
240
+ let removed = 0;
241
+ if (staleRows.length > 0) {
242
+ const staleIdsJson = JSON.stringify(staleRows.map((r) => r.id));
243
+ db.query(
244
+ `DELETE FROM "${table}" WHERE rowid IN (SELECT value FROM json_each(?))`
245
+ ).run(staleIdsJson);
246
+ db.query(
247
+ `DELETE FROM vector_partition_rows WHERE id IN (SELECT value FROM json_each(?))`
248
+ ).run(staleIdsJson);
249
+ removed += staleRows.length;
250
+ }
251
+
252
+ // 2. Remove orphan rowids in vec_v2 absent from vector_partition_rows.
253
+ const orphanVecIds = db
254
+ .query<{ rowid: number }, [string]>(
255
+ `SELECT x.rowid AS rowid
256
+ FROM "${table}" x
257
+ WHERE NOT EXISTS (
258
+ SELECT 1 FROM vector_partition_rows r
259
+ WHERE r.partition_id = ? AND r.id = x.rowid
260
+ )`
261
+ )
262
+ .all(partitionId);
263
+ if (orphanVecIds.length > 0) {
264
+ db.query(
265
+ `DELETE FROM "${table}" WHERE rowid IN (SELECT value FROM json_each(?))`
266
+ ).run(JSON.stringify(orphanVecIds.map((r) => r.rowid)));
267
+ removed += orphanVecIds.length;
268
+ }
269
+
270
+ // 3. Insert missing (collection, variant_id) pairs into vector_partition_rows.
271
+ db.run(
272
+ `INSERT OR IGNORE INTO vector_partition_rows (partition_id, collection, variant_id)
273
+ SELECT DISTINCT o.partition_id, d.collection, o.variant_id
274
+ FROM vector_owners o
275
+ JOIN documents d ON d.id = o.document_id
276
+ JOIN vector_variants v ON v.partition_id = o.partition_id AND v.variant_id = o.variant_id
277
+ WHERE o.partition_id = ?`,
278
+ [partitionId]
279
+ );
280
+
281
+ // 4. Materialize any mapping rows not yet present in vec_v2 purely in SQL.
282
+ // Collect missing rowids first so the INSERT ... SELECT does not self-reference
283
+ // the vec0 table: SQLite's Halloween-protection temp B-tree would strip
284
+ // sqlite-vec's bit subtype from `vec_quantize_binary(v.embedding)`.
285
+ const missingIds = db
286
+ .query<{ id: number }, [string]>(
287
+ `SELECT r.id
288
+ FROM vector_partition_rows r
289
+ WHERE r.partition_id = ?
290
+ AND NOT EXISTS (SELECT 1 FROM "${table}" x WHERE x.rowid = r.id)`
291
+ )
292
+ .all(partitionId)
293
+ .map((row) => row.id);
294
+
295
+ if (missingIds.length > 0) {
296
+ // Batch to keep JSON parameter bounded on very large backfills.
297
+ const CHUNK = 50_000;
298
+ const insertStmt = db.prepare<unknown, [string]>(
299
+ `INSERT INTO "${table}"(rowid, collection, coarse)
300
+ SELECT r.id, r.collection, vec_quantize_binary(v.embedding)
301
+ FROM json_each(?) AS m
302
+ JOIN vector_partition_rows r ON r.id = m.value
303
+ JOIN vector_variants v
304
+ ON v.partition_id = r.partition_id AND v.variant_id = r.variant_id`
305
+ );
306
+ try {
307
+ for (let i = 0; i < missingIds.length; i += CHUNK) {
308
+ insertStmt.run(JSON.stringify(missingIds.slice(i, i + CHUNK)));
309
+ }
310
+ } finally {
311
+ insertStmt.finalize();
312
+ }
313
+ }
314
+ const missingCount = missingIds.length;
315
+
316
+ // If the mirror was previously dirty or missing, clear stored self-check so
317
+ // the recall check re-runs on the repaired mirror; otherwise preserve it.
318
+ const preserveCheck =
319
+ tableExisted &&
320
+ prior?.dirty === 0 &&
321
+ missingCount === 0 &&
322
+ removed === 0 &&
323
+ prior.checkRecall !== null &&
324
+ prior.checkQueries !== null &&
325
+ prior.checkCoarseK !== null
326
+ ? {
327
+ recall: prior.checkRecall,
328
+ queries: prior.checkQueries,
329
+ coarseK: prior.checkCoarseK,
330
+ }
331
+ : null;
332
+
333
+ markV2MirrorClean(db, partitionId, preserveCheck);
334
+ return { added: missingCount, removed };
335
+ }
336
+
337
+ /**
338
+ * Full drop + recreate + pure-SQL repopulation of `vec_v2_<partitionId>`.
339
+ */
340
+ export function rebuildV2PartitionMirrorInTx(
341
+ db: Database,
342
+ partitionId: string,
343
+ dimensions: number
344
+ ): number {
345
+ if (!hasV2MirrorTables(db) || !isV2CompatibleDimensions(dimensions)) {
346
+ return 0;
347
+ }
348
+ const table = v2TableName(partitionId);
349
+ db.exec(`DROP TABLE IF EXISTS "${table}"`);
350
+ db.run("DELETE FROM vector_partition_rows WHERE partition_id = ?", [
351
+ partitionId,
352
+ ]);
353
+ ensureV2Table(db, partitionId, dimensions);
354
+
355
+ db.run(
356
+ `INSERT OR IGNORE INTO vector_partition_rows (partition_id, collection, variant_id)
357
+ SELECT DISTINCT o.partition_id, d.collection, o.variant_id
358
+ FROM vector_owners o
359
+ JOIN documents d ON d.id = o.document_id
360
+ JOIN vector_variants v ON v.partition_id = o.partition_id AND v.variant_id = o.variant_id
361
+ WHERE o.partition_id = ?`,
362
+ [partitionId]
363
+ );
364
+
365
+ db.run(
366
+ `INSERT INTO "${table}"(rowid, collection, coarse)
367
+ SELECT r.id, r.collection, vec_quantize_binary(v.embedding)
368
+ FROM vector_partition_rows r
369
+ JOIN vector_variants v
370
+ ON v.partition_id = r.partition_id AND v.variant_id = r.variant_id
371
+ WHERE r.partition_id = ?`,
372
+ [partitionId]
373
+ );
374
+
375
+ const count =
376
+ db
377
+ .query<{ n: number }, [string]>(
378
+ "SELECT COUNT(*) AS n FROM vector_partition_rows WHERE partition_id = ?"
379
+ )
380
+ .get(partitionId)?.n ?? 0;
381
+
382
+ markV2MirrorClean(db, partitionId, null);
383
+ return count;
384
+ }
385
+
386
+ /**
387
+ * Drop v2 table, mapping rows, and state row for a partition (used by drop/re-key).
388
+ */
389
+ export function dropV2PartitionMirrorInTx(
390
+ db: Database,
391
+ partitionId: string
392
+ ): void {
393
+ const table = v2TableName(partitionId);
394
+ db.exec(`DROP TABLE IF EXISTS "${table}"`);
395
+ if (hasV2MirrorTables(db)) {
396
+ db.run("DELETE FROM vector_partition_rows WHERE partition_id = ?", [
397
+ partitionId,
398
+ ]);
399
+ db.run("DELETE FROM vector_mirror_v2_state WHERE partition_id = ?", [
400
+ partitionId,
401
+ ]);
402
+ }
403
+ }
404
+
405
+ interface TopKHeapEntry {
406
+ variantId: number;
407
+ distance: number;
408
+ }
409
+
410
+ function pushTopK(
411
+ heap: TopKHeapEntry[],
412
+ entry: TopKHeapEntry,
413
+ k: number
414
+ ): void {
415
+ if (heap.length < k) {
416
+ heap.push(entry);
417
+ if (heap.length === k) {
418
+ heap.sort((a, b) => a.distance - b.distance || a.variantId - b.variantId);
419
+ }
420
+ return;
421
+ }
422
+ const worst = heap[k - 1]!;
423
+ if (
424
+ entry.distance < worst.distance ||
425
+ (entry.distance === worst.distance && entry.variantId < worst.variantId)
426
+ ) {
427
+ // Insertion into small sorted array (k = 10) is faster than binary heap overhead.
428
+ let i = k - 1;
429
+ while (
430
+ i > 0 &&
431
+ (entry.distance < heap[i - 1]!.distance ||
432
+ (entry.distance === heap[i - 1]!.distance &&
433
+ entry.variantId < heap[i - 1]!.variantId))
434
+ ) {
435
+ heap[i] = heap[i - 1]!;
436
+ i -= 1;
437
+ }
438
+ heap[i] = entry;
439
+ }
440
+ }
441
+
442
+ /**
443
+ * Build-time recall self-check (fn-235 §2 & R5).
444
+ *
445
+ * Samples 16 stored vectors evenly across `variant_id`, computes their exact
446
+ * top-10 in ONE streaming SQL pass over `vector_variants` (zero embedding BLOBs
447
+ * cross into JS during the scan), runs the same 16 through the two-stage bit
448
+ * path at `coarseK = 200`, and persists mean recall@10 in `vector_mirror_v2_state`.
449
+ *
450
+ * Skips when:
451
+ * - v2 mirror is missing, dirty, or unsupported dimensions
452
+ * - `check_recall` is already populated (unless `force: true`)
453
+ * - partition is within the exact-cost budget (unless `bypassBudget: true` for tests)
454
+ * Never loads an embedding model.
455
+ */
456
+ export function runV2RecallSelfCheck(
457
+ db: Database,
458
+ partition: { partitionId: string; dimensions: number },
459
+ options: { force?: boolean; bypassBudget?: boolean } = {}
460
+ ): V2RecallCheckResult {
461
+ const { partitionId, dimensions } = partition;
462
+ const maxQueries = COARSE_ROUTER_DEFAULTS.selfCheckQueries;
463
+ const topK = COARSE_ROUTER_DEFAULTS.selfCheckTopK;
464
+ const coarseK = COARSE_ROUTER_DEFAULTS.selfCheckCoarseK;
465
+
466
+ if (
467
+ !hasV2MirrorTables(db) ||
468
+ !isV2CompatibleDimensions(dimensions) ||
469
+ !hasV2Table(db, partitionId)
470
+ ) {
471
+ return {
472
+ ran: false,
473
+ recall: null,
474
+ queries: 0,
475
+ coarseK,
476
+ reason: "v2-unavailable",
477
+ };
478
+ }
479
+
480
+ const state = readV2MirrorState(db, partitionId);
481
+ if (state?.dirty !== 0) {
482
+ return { ran: false, recall: null, queries: 0, coarseK, reason: "dirty" };
483
+ }
484
+ if (!options.force && state.checkRecall !== null) {
485
+ return {
486
+ ran: false,
487
+ recall: state.checkRecall,
488
+ queries: state.checkQueries ?? 0,
489
+ coarseK: state.checkCoarseK ?? coarseK,
490
+ reason: "already-checked",
491
+ };
492
+ }
493
+
494
+ const totalMirrorRows =
495
+ db
496
+ .query<{ n: number }, [string]>(
497
+ "SELECT COUNT(*) AS n FROM vector_partition_rows WHERE partition_id = ?"
498
+ )
499
+ .get(partitionId)?.n ?? 0;
500
+
501
+ if (!options.bypassBudget && !isPartitionAboveBudget(totalMirrorRows, 1)) {
502
+ return {
503
+ ran: false,
504
+ recall: null,
505
+ queries: 0,
506
+ coarseK,
507
+ reason: "under-budget",
508
+ };
509
+ }
510
+
511
+ // Distinct variant count in v2 mirror (we only evaluate variants present in the mirror).
512
+ const distinctVariants =
513
+ db
514
+ .query<{ n: number }, [string]>(
515
+ `SELECT COUNT(DISTINCT variant_id) AS n
516
+ FROM vector_partition_rows
517
+ WHERE partition_id = ?`
518
+ )
519
+ .get(partitionId)?.n ?? 0;
520
+
521
+ if (distinctVariants === 0) {
522
+ return { ran: false, recall: null, queries: 0, coarseK, reason: "empty" };
523
+ }
524
+
525
+ // Sample up to 16 stored vectors spread evenly over variant_id.
526
+ const sampleCount = Math.min(maxQueries, distinctVariants);
527
+ const stride = Math.max(1, Math.floor(distinctVariants / sampleCount));
528
+ const samples: Array<{ variantId: number; blob: Uint8Array }> = [];
529
+ const sampleStmt = db.prepare<
530
+ { variant_id: number; embedding: Uint8Array },
531
+ [string, number]
532
+ >(
533
+ `SELECT v.variant_id, v.embedding
534
+ FROM vector_variants v
535
+ WHERE v.partition_id = ?
536
+ AND EXISTS (
537
+ SELECT 1 FROM vector_partition_rows r
538
+ WHERE r.partition_id = v.partition_id AND r.variant_id = v.variant_id
539
+ )
540
+ ORDER BY v.variant_id
541
+ LIMIT 1 OFFSET ?`
542
+ );
543
+ for (let i = 0; i < sampleCount; i++) {
544
+ const row = sampleStmt.get(partitionId, i * stride);
545
+ if (!row) break;
546
+ // Copy buffer so subsequent statement steps never alias the same backing store.
547
+ const blob = new Uint8Array(row.embedding.byteLength);
548
+ blob.set(row.embedding);
549
+ samples.push({ variantId: row.variant_id, blob });
550
+ }
551
+ sampleStmt.finalize();
552
+
553
+ if (samples.length === 0) {
554
+ return { ran: false, recall: null, queries: 0, coarseK, reason: "empty" };
555
+ }
556
+
557
+ // Compute exact top-10 for all sampled queries in ONE streaming pass over vector_variants.
558
+ const effectiveK = Math.min(topK, distinctVariants);
559
+ const distanceCols = samples
560
+ .map((_, i) => `vec_distance_cosine(v.embedding, ?) AS d${i}`)
561
+ .join(", ");
562
+ const streamSql = `
563
+ SELECT v.variant_id AS variantId, ${distanceCols}
564
+ FROM vector_variants v
565
+ WHERE v.partition_id = ?
566
+ AND EXISTS (
567
+ SELECT 1 FROM vector_partition_rows r
568
+ WHERE r.partition_id = v.partition_id AND r.variant_id = v.variant_id
569
+ )
570
+ `;
571
+ const heaps: TopKHeapEntry[][] = samples.map(() => []);
572
+ const streamStmt = db.prepare<
573
+ Record<string, number | null>,
574
+ (Uint8Array | string)[]
575
+ >(streamSql);
576
+ try {
577
+ for (const row of streamStmt.iterate(
578
+ ...samples.map((s) => s.blob),
579
+ partitionId
580
+ )) {
581
+ const variantId = row.variantId as number;
582
+ for (let q = 0; q < samples.length; q++) {
583
+ const d = row[`d${q}`];
584
+ if (d === null || d === undefined || Number.isNaN(d)) continue;
585
+ pushTopK(heaps[q]!, { variantId, distance: d }, effectiveK);
586
+ }
587
+ }
588
+ } finally {
589
+ streamStmt.finalize();
590
+ }
591
+
592
+ for (const h of heaps) {
593
+ h.sort((a, b) => a.distance - b.distance || a.variantId - b.variantId);
594
+ }
595
+
596
+ // Run the same sampled queries through the two-stage bit path at coarseK = 200.
597
+ const table = v2TableName(partitionId);
598
+ const effectiveCoarseK = Math.min(coarseK, totalMirrorRows);
599
+ const stage1Stmt = db.prepare<{ rowid: number }, [Uint8Array, number]>(
600
+ `SELECT rowid FROM "${table}" WHERE coarse MATCH vec_quantize_binary(?) AND k = ?`
601
+ );
602
+ const stage2Stmt = db.prepare<
603
+ { variantId: number; distance: number | null },
604
+ [string, string, Uint8Array, string, number]
605
+ >(
606
+ `WITH cand AS (
607
+ SELECT DISTINCT r.variant_id AS variant_id
608
+ FROM json_each(?) AS m
609
+ CROSS JOIN vector_partition_rows r ON r.id = m.value
610
+ WHERE r.partition_id = ?
611
+ )
612
+ SELECT v.variant_id AS variantId, vec_distance_cosine(v.embedding, ?) AS distance
613
+ FROM cand
614
+ CROSS JOIN vector_variants v
615
+ ON v.partition_id = ? AND v.variant_id = cand.variant_id
616
+ ORDER BY distance ASC NULLS LAST, v.variant_id ASC
617
+ LIMIT ?`
618
+ );
619
+
620
+ let totalRecall = 0;
621
+ let evaluated = 0;
622
+ try {
623
+ for (let q = 0; q < samples.length; q++) {
624
+ const exactTop = heaps[q]!;
625
+ if (exactTop.length === 0) continue;
626
+ const exactSet = new Set(exactTop.map((e) => e.variantId));
627
+ const rowids = stage1Stmt
628
+ .all(samples[q]!.blob, effectiveCoarseK)
629
+ .map((r) => r.rowid);
630
+ if (rowids.length === 0) {
631
+ evaluated += 1;
632
+ continue;
633
+ }
634
+ const approxTop = stage2Stmt.all(
635
+ JSON.stringify(rowids),
636
+ partitionId,
637
+ samples[q]!.blob,
638
+ partitionId,
639
+ effectiveK
640
+ );
641
+ let hits = 0;
642
+ for (const hit of approxTop) {
643
+ if (exactSet.has(hit.variantId)) hits += 1;
644
+ }
645
+ totalRecall += hits / exactSet.size;
646
+ evaluated += 1;
647
+ }
648
+ } finally {
649
+ stage1Stmt.finalize();
650
+ stage2Stmt.finalize();
651
+ }
652
+
653
+ const meanRecall = evaluated > 0 ? totalRecall / evaluated : 0;
654
+
655
+ // Persist into vector_mirror_v2_state only if the mirror is still clean.
656
+ db.run(
657
+ `UPDATE vector_mirror_v2_state
658
+ SET check_recall = ?, check_queries = ?, check_coarse_k = ?
659
+ WHERE partition_id = ? AND dirty = 0`,
660
+ [meanRecall, evaluated, coarseK, partitionId]
661
+ );
662
+
663
+ return {
664
+ ran: true,
665
+ recall: meanRecall,
666
+ queries: evaluated,
667
+ coarseK,
668
+ };
669
+ }