@gmickel/gno 2.15.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 (218) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/SKILL.md +27 -0
  3. package/assets/skill/cli-reference.md +24 -15
  4. package/assets/spa-production.json.gz +0 -0
  5. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
  6. package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
  7. package/browser-extension/dist/manifest.json +1 -1
  8. package/package.json +1 -1
  9. package/spec/cli.md +43 -3
  10. package/spec/db/schema.sql +53 -1
  11. package/spec/mcp.md +9 -3
  12. package/spec/output-schemas/doctor.schema.json +27 -0
  13. package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
  14. package/spec/output-schemas/search-results.schema.json +14 -0
  15. package/spec/output-schemas/status.schema.json +22 -0
  16. package/src/cli/commands/agents/commands.ts +1 -1
  17. package/src/cli/commands/ask.ts +1 -1
  18. package/src/cli/commands/context-build.ts +1 -1
  19. package/src/cli/commands/doctor.ts +101 -29
  20. package/src/cli/commands/embed.ts +2 -2
  21. package/src/cli/commands/links.ts +30 -6
  22. package/src/cli/commands/mcp/install.ts +2 -2
  23. package/src/cli/commands/mcp/status.ts +1 -1
  24. package/src/cli/commands/mcp/uninstall.ts +1 -1
  25. package/src/cli/commands/query.ts +1 -1
  26. package/src/cli/commands/shared.ts +4 -4
  27. package/src/cli/commands/skill/install.ts +1 -1
  28. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  29. package/src/cli/commands/skill/uninstall.ts +1 -1
  30. package/src/cli/commands/status.ts +75 -58
  31. package/src/cli/commands/vec.ts +180 -8
  32. package/src/cli/config-cache.ts +86 -0
  33. package/src/cli/globals.ts +64 -0
  34. package/src/cli/program.ts +63 -36
  35. package/src/cli/run.ts +121 -67
  36. package/src/cli/runtime-health.ts +132 -122
  37. package/src/cli/session-binding.ts +11 -2
  38. package/src/config/saver.ts +8 -0
  39. package/src/config/types.ts +6 -0
  40. package/src/converters/adapters/browser-export/formats.ts +25 -15
  41. package/src/converters/adapters/email/adapter.ts +37 -53
  42. package/src/converters/adapters/email/html.ts +37 -20
  43. package/src/converters/adapters/email/mime.ts +71 -39
  44. package/src/converters/adapters/ical/adapter.ts +20 -12
  45. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  46. package/src/converters/adapters/shared/html-text.ts +55 -37
  47. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  48. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  49. package/src/converters/adapters/transcript/adapter.ts +12 -7
  50. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  51. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  52. package/src/converters/canonicalize.ts +17 -3
  53. package/src/converters/native/markdown.ts +24 -17
  54. package/src/converters/native/plaintext.ts +5 -6
  55. package/src/converters/registry.ts +130 -8
  56. package/src/core/activation-status.ts +4 -8
  57. package/src/core/change-diff.ts +38 -11
  58. package/src/core/context-compiler.ts +17 -18
  59. package/src/core/context-evidence.ts +116 -25
  60. package/src/core/context-verifier.ts +70 -31
  61. package/src/core/file-lock.ts +10 -2
  62. package/src/core/graph-analysis.ts +3 -3
  63. package/src/core/link-inventory-markdown.ts +2 -2
  64. package/src/core/links.ts +20 -87
  65. package/src/core/memory-fence.ts +16 -9
  66. package/src/core/memory-recall.ts +168 -34
  67. package/src/core/path-rules.ts +143 -0
  68. package/src/core/retrieval-trace-session.ts +3 -0
  69. package/src/core/retrieval-trace.ts +9 -0
  70. package/src/core/section-parse.ts +16 -6
  71. package/src/core/typed-metadata.ts +68 -0
  72. package/src/core/vector-partition-status.ts +13 -0
  73. package/src/core/wiki-link-syntax.ts +88 -0
  74. package/src/embed/backlog.ts +142 -60
  75. package/src/embed/retry.ts +39 -33
  76. package/src/embed/variant-backlog.ts +582 -116
  77. package/src/embed/variant-retry.ts +157 -48
  78. package/src/index.ts +3 -3
  79. package/src/ingestion/budget-error-codes.ts +13 -0
  80. package/src/ingestion/chunker.ts +60 -49
  81. package/src/ingestion/compiled-context.ts +4 -5
  82. package/src/ingestion/convert-file.ts +1 -1
  83. package/src/ingestion/document-metadata.ts +16 -9
  84. package/src/ingestion/excluded-ranges.ts +97 -0
  85. package/src/ingestion/file-processor.ts +122 -37
  86. package/src/ingestion/frontmatter.ts +35 -7
  87. package/src/ingestion/graph-reconciliation.ts +187 -51
  88. package/src/ingestion/language.ts +66 -61
  89. package/src/ingestion/position.ts +5 -5
  90. package/src/ingestion/prepare-file.ts +50 -29
  91. package/src/ingestion/record-adapter-canonical.ts +37 -26
  92. package/src/ingestion/record-adapter.ts +46 -26
  93. package/src/ingestion/record-container.ts +121 -53
  94. package/src/ingestion/record-path.ts +5 -2
  95. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  96. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  97. package/src/ingestion/source-availability/readers.ts +51 -0
  98. package/src/ingestion/strip.ts +39 -105
  99. package/src/ingestion/sync.ts +692 -386
  100. package/src/ingestion/typed-metadata.ts +10 -4
  101. package/src/ingestion/walker.ts +485 -158
  102. package/src/llm/cache.ts +128 -84
  103. package/src/llm/http-inference.ts +112 -35
  104. package/src/llm/http-policy.ts +101 -0
  105. package/src/llm/httpEmbedding.ts +8 -1
  106. package/src/llm/httpGeneration.ts +5 -1
  107. package/src/llm/httpRerank.ts +5 -1
  108. package/src/llm/inference-scope.ts +15 -2
  109. package/src/llm/lazy-ports.ts +33 -3
  110. package/src/llm/lockfile.ts +34 -7
  111. package/src/llm/model-cleanup.ts +24 -0
  112. package/src/llm/native-worker/client.ts +23 -12
  113. package/src/llm/native-worker/dispatcher.ts +19 -9
  114. package/src/llm/native-worker/embedding-identity.ts +42 -16
  115. package/src/llm/native-worker/entry.ts +2 -1
  116. package/src/llm/native-worker/owner.ts +1 -0
  117. package/src/llm/native-worker/ports.ts +86 -23
  118. package/src/llm/native-worker/protocol.ts +386 -55
  119. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  120. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  121. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  122. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  123. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  124. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  125. package/src/llm/types.ts +14 -0
  126. package/src/mcp/context.ts +342 -23
  127. package/src/mcp/http-transport.ts +21 -3
  128. package/src/mcp/tool-profile-types.ts +62 -0
  129. package/src/mcp/tool-profile.ts +32 -56
  130. package/src/mcp/tools/context.ts +5 -1
  131. package/src/mcp/tools/index.ts +269 -191
  132. package/src/mcp/tools/links.ts +14 -6
  133. package/src/mcp/tools/query.ts +60 -37
  134. package/src/mcp/tools/vsearch.ts +25 -14
  135. package/src/pipeline/answer.ts +133 -40
  136. package/src/pipeline/claim-verification.ts +293 -189
  137. package/src/pipeline/claim-verifier.ts +6 -7
  138. package/src/pipeline/egress-lineage.ts +37 -26
  139. package/src/pipeline/exclude.ts +34 -11
  140. package/src/pipeline/expansion.ts +233 -19
  141. package/src/pipeline/explain.ts +17 -2
  142. package/src/pipeline/filters.ts +169 -33
  143. package/src/pipeline/graph-retrieval.ts +117 -61
  144. package/src/pipeline/hybrid.ts +626 -330
  145. package/src/pipeline/hydration.ts +86 -24
  146. package/src/pipeline/intent.ts +15 -7
  147. package/src/pipeline/owner-fusion.ts +61 -19
  148. package/src/pipeline/query-language.ts +15 -2
  149. package/src/pipeline/rerank.ts +15 -22
  150. package/src/pipeline/search.ts +193 -72
  151. package/src/pipeline/snippet.ts +15 -2
  152. package/src/pipeline/temporal.ts +51 -10
  153. package/src/pipeline/types.ts +7 -0
  154. package/src/pipeline/vsearch.ts +269 -154
  155. package/src/publish/attachment-raster.ts +2 -16
  156. package/src/publish/encrypted-export.ts +15 -5
  157. package/src/serve/browse-tree.ts +50 -42
  158. package/src/serve/connectors.ts +2 -1
  159. package/src/serve/context.ts +13 -4
  160. package/src/serve/doc-events.ts +3 -0
  161. package/src/serve/public/app.tsx +49 -21
  162. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  163. package/src/serve/public/components/CaptureModal.tsx +14 -10
  164. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  165. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  166. package/src/serve/public/globals.built.css +1 -1
  167. package/src/serve/public/globals.css +19 -0
  168. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  169. package/src/serve/public/lib/metadata-filter.ts +234 -9
  170. package/src/serve/public/pages/Browse.tsx +61 -27
  171. package/src/serve/public/pages/DocView.tsx +44 -25
  172. package/src/serve/public/pages/GraphView.tsx +8 -3
  173. package/src/serve/resident-runtime.ts +199 -48
  174. package/src/serve/routes/api.ts +98 -67
  175. package/src/serve/routes/links.ts +25 -5
  176. package/src/serve/server.ts +1370 -1180
  177. package/src/serve/spa-bundle-source.ts +52 -27
  178. package/src/serve/status.ts +101 -52
  179. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  180. package/src/serve/watch-reconciliation-shared.ts +42 -4
  181. package/src/serve/watch-reconciliation.ts +21 -8
  182. package/src/serve/watch-service-events.ts +7 -1
  183. package/src/serve/watch-service-hosts.ts +3 -1
  184. package/src/serve/watch-service.ts +46 -21
  185. package/src/serve/watch-snapshot-scan.ts +6 -15
  186. package/src/sessions/archive.ts +20 -8
  187. package/src/sessions/sanitize.ts +38 -18
  188. package/src/sessions/service.ts +180 -102
  189. package/src/store/migrations/037-performance-indexes.ts +56 -0
  190. package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
  191. package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
  192. package/src/store/migrations/index.ts +6 -0
  193. package/src/store/sqlite/adapter.ts +1260 -651
  194. package/src/store/sqlite/chunking-policy.ts +15 -1
  195. package/src/store/sqlite/eligibility.ts +110 -70
  196. package/src/store/sqlite/graph-neighbors.ts +71 -46
  197. package/src/store/sqlite/graph-reference-state.ts +27 -3
  198. package/src/store/sqlite/graph-similarity.ts +59 -12
  199. package/src/store/sqlite/metadata-predicate.ts +123 -28
  200. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  201. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  202. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  203. package/src/store/types.ts +32 -0
  204. package/src/store/vector/coarse-router.ts +312 -0
  205. package/src/store/vector/eligibility.ts +39 -0
  206. package/src/store/vector/lazy.ts +17 -0
  207. package/src/store/vector/partition-index.ts +333 -59
  208. package/src/store/vector/proof-cache.ts +209 -0
  209. package/src/store/vector/runtime-compat.ts +6 -0
  210. package/src/store/vector/sqlite-vec.ts +270 -162
  211. package/src/store/vector/stats.ts +37 -73
  212. package/src/store/vector/status.ts +169 -53
  213. package/src/store/vector/stored-vectors.ts +131 -45
  214. package/src/store/vector/types.ts +19 -0
  215. package/src/store/vector/v2-mirror.ts +669 -0
  216. package/src/store/vector/variant-search.ts +1187 -111
  217. package/src/store/vector/variants.ts +964 -160
  218. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -10,6 +10,24 @@ import type {
10
10
 
11
11
  import { formatDocForEmbedding } from "../../pipeline/contextual";
12
12
  import { buildEligibleDocumentQuery } from "../sqlite/eligibility";
13
+ import {
14
+ COARSE_ROUTER_DEFAULTS,
15
+ computeCoarseK,
16
+ countScopeMirrorRows,
17
+ extractRequestedCollections,
18
+ hasNonCollectionFilter,
19
+ isV2CompatibleDimensions,
20
+ resolveVectorRoute,
21
+ v2TableName,
22
+ } from "./coarse-router";
23
+ import { hasNullCosineColumn } from "./partition-index";
24
+ import {
25
+ checkNullCosineVariant,
26
+ type NullCosineCheckResult,
27
+ persistNullCosineAfterSnapshot,
28
+ provenOwners,
29
+ vectorProofKey,
30
+ } from "./proof-cache";
13
31
  import {
14
32
  embeddingPartitionIdentity,
15
33
  identityPartitionId,
@@ -23,7 +41,14 @@ import {
23
41
  writerConnection,
24
42
  writerIdle,
25
43
  } from "./sqlite-vec";
26
- import { embeddingInputHash } from "./variants";
44
+ import { hasV2MirrorTables, hasV2Table, readV2MirrorState } from "./v2-mirror";
45
+ import {
46
+ chunkKeyHint,
47
+ embeddingInputHash,
48
+ ownerDocPartHint,
49
+ ownerPartitionVariantHint,
50
+ variantPartitionIdHint,
51
+ } from "./variants";
27
52
 
28
53
  /** Fallback/warning code: this runtime may not read the activated vectors. */
29
54
  export const VECTOR_RUNTIME_INCOMPATIBLE = "vector_runtime_incompatible";
@@ -119,70 +144,299 @@ export function vectorSearchUnavailableMessage(
119
144
  }`;
120
145
  }
121
146
 
122
- const MAX_CACHED_PROOFS = 100_000;
123
- const proofCaches = new WeakMap<
124
- Database,
125
- { marker: string; proofs: Map<string, boolean> }
126
- >();
147
+ function hasSelectiveEligibility(options: VectorSearchOptions): boolean {
148
+ if (options.allowedMirrorHashes !== undefined) return true;
149
+ const e = options.eligibility;
150
+ if (!e) return false;
151
+ return Boolean(
152
+ e.collection ||
153
+ e.collections !== undefined ||
154
+ e.filter ||
155
+ e.tagsAny?.length ||
156
+ e.tagsAll?.length ||
157
+ e.since ||
158
+ e.until ||
159
+ e.categories?.length ||
160
+ e.author ||
161
+ e.relPathPrefix !== undefined ||
162
+ e.memoryScopesAny?.length ||
163
+ e.excludeSuperseded ||
164
+ e.exclude?.length ||
165
+ e.chunkLanguage ||
166
+ e.allowedMirrorHashes !== undefined
167
+ );
168
+ }
169
+
170
+ const MAX_VEC0_K = 4096;
171
+ const MAX_SQL_BATCH_QUERIES = 8;
127
172
 
128
- /**
129
- * Input-hash proofs cached per connection. Any committed write, from this
130
- * connection or another, changes the marker and drops the cache, so a cached
131
- * proof never outlives the titles and chunk text it was computed from.
132
- */
133
- function provenOwners(db: Database): Map<string, boolean> {
134
- const { version, changes } = db
135
- .query<{ version: number; changes: number }, []>(
136
- "SELECT (SELECT data_version FROM pragma_data_version) AS version, total_changes() AS changes"
173
+ interface RankedVariantRow {
174
+ variantId?: number;
175
+ mirrorHash: string;
176
+ seq: number;
177
+ inputHash: string;
178
+ distance: number;
179
+ documentIds: string;
180
+ }
181
+
182
+ interface CandidateRow {
183
+ variantId: number;
184
+ mirrorHash: string;
185
+ seq: number;
186
+ inputHash: string;
187
+ distance: number;
188
+ documentIds: number[];
189
+ }
190
+
191
+ function isNonZeroVector(embedding: Float32Array): boolean {
192
+ let sumSq = 0;
193
+ for (let i = 0; i < embedding.length; i++) {
194
+ const v = embedding[i]!;
195
+ if (!Number.isFinite(v)) return false;
196
+ sumSq += v * v;
197
+ }
198
+ return sumSq > 0 && Number.isFinite(sumSq);
199
+ }
200
+
201
+ function isMirrorClean(db: Database, partitionId: string): boolean {
202
+ if (
203
+ !db
204
+ .query(
205
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'vector_mirror_state'"
206
+ )
207
+ .get()
208
+ )
209
+ return false;
210
+ const row = db
211
+ .query<{ dirty: number }, [string]>(
212
+ "SELECT dirty FROM vector_mirror_state WHERE partition_id = ?"
137
213
  )
138
- .get()!;
139
- const marker = `${version}:${changes}`;
140
- let cache = proofCaches.get(db);
141
- if (cache?.marker !== marker || cache.proofs.size > MAX_CACHED_PROOFS) {
142
- cache = { marker, proofs: new Map() };
143
- proofCaches.set(db, cache);
144
- }
145
- return cache.proofs;
214
+ .get(partitionId);
215
+ return row?.dirty === 0;
146
216
  }
147
217
 
148
- /** Null means legacy authority. Once promoted, unavailable provenance fails closed. */
149
- function searchVectorVariantsInSnapshot(
218
+ /** Exact SQLite `ORDER BY distance, mirrorHash, seq, variantId` comparator (NULLS FIRST, binary text). */
219
+ function compareVariantCandidates(a: CandidateRow, b: CandidateRow): number {
220
+ const aNull = a.distance === null;
221
+ const bNull = b.distance === null;
222
+ if (aNull !== bNull) return aNull ? -1 : 1;
223
+ if (!aNull && a.distance !== b.distance) return a.distance - b.distance;
224
+ if (a.mirrorHash < b.mirrorHash) return -1;
225
+ if (a.mirrorHash > b.mirrorHash) return 1;
226
+ if (a.seq !== b.seq) return a.seq - b.seq;
227
+ return a.variantId - b.variantId;
228
+ }
229
+
230
+ /** Max-heap insertion keeping the smallest `cap` candidates under `compareVariantCandidates`. */
231
+ function pushBoundedCandidate(
232
+ heap: CandidateRow[],
233
+ cap: number,
234
+ item: CandidateRow
235
+ ): void {
236
+ if (heap.length < cap) {
237
+ heap.push(item);
238
+ let idx = heap.length - 1;
239
+ while (idx > 0) {
240
+ const parent = (idx - 1) >> 1;
241
+ if (compareVariantCandidates(heap[idx]!, heap[parent]!) <= 0) break;
242
+ const tmp = heap[parent]!;
243
+ heap[parent] = heap[idx]!;
244
+ heap[idx] = tmp;
245
+ idx = parent;
246
+ }
247
+ return;
248
+ }
249
+ if (compareVariantCandidates(item, heap[0]!) >= 0) return;
250
+ heap[0] = item;
251
+ let idx = 0;
252
+ const len = heap.length;
253
+ for (;;) {
254
+ const left = idx * 2 + 1;
255
+ const right = left + 1;
256
+ let largest = idx;
257
+ if (left < len && compareVariantCandidates(heap[left]!, heap[largest]!) > 0)
258
+ largest = left;
259
+ if (
260
+ right < len &&
261
+ compareVariantCandidates(heap[right]!, heap[largest]!) > 0
262
+ )
263
+ largest = right;
264
+ if (largest === idx) break;
265
+ const tmp = heap[idx]!;
266
+ heap[idx] = heap[largest]!;
267
+ heap[largest] = tmp;
268
+ idx = largest;
269
+ }
270
+ }
271
+
272
+ function createBatchOwnersStmt(db: Database) {
273
+ return db.query<
274
+ {
275
+ id: number;
276
+ mirrorHash: string;
277
+ seq: number;
278
+ title: string | null;
279
+ text: string;
280
+ },
281
+ [string]
282
+ >(`
283
+ WITH req AS (
284
+ SELECT
285
+ json_extract(value, '$[0]') AS document_id,
286
+ json_extract(value, '$[1]') AS mirror_hash,
287
+ json_extract(value, '$[2]') AS seq
288
+ FROM json_each(?)
289
+ )
290
+ SELECT r.document_id AS id, r.mirror_hash AS mirrorHash, r.seq, d.title, c.text
291
+ FROM req r
292
+ JOIN documents d ON d.id = r.document_id
293
+ JOIN content_chunks c ON c.mirror_hash = r.mirror_hash AND c.seq = r.seq
294
+ `);
295
+ }
296
+
297
+ function proveUnknownOwners(
298
+ model: string,
299
+ proofs: Map<string, boolean>,
300
+ candidateLists: readonly (readonly CandidateRow[])[],
301
+ batchOwners: ReturnType<typeof createBatchOwnersStmt>
302
+ ): void {
303
+ const unknownByTuple = new Map<
304
+ string,
305
+ {
306
+ id: number;
307
+ mirrorHash: string;
308
+ seq: number;
309
+ inputHashes: Set<string>;
310
+ }
311
+ >();
312
+ for (const list of candidateLists) {
313
+ for (const row of list) {
314
+ for (const id of row.documentIds) {
315
+ const key = vectorProofKey(
316
+ model,
317
+ id,
318
+ row.mirrorHash,
319
+ row.seq,
320
+ row.inputHash
321
+ );
322
+ if (!proofs.has(key)) {
323
+ const tupleKey = `${id}\0${row.mirrorHash}\0${row.seq}`;
324
+ let entry = unknownByTuple.get(tupleKey);
325
+ if (!entry) {
326
+ entry = {
327
+ id,
328
+ mirrorHash: row.mirrorHash,
329
+ seq: row.seq,
330
+ inputHashes: new Set(),
331
+ };
332
+ unknownByTuple.set(tupleKey, entry);
333
+ }
334
+ entry.inputHashes.add(row.inputHash);
335
+ }
336
+ }
337
+ }
338
+ }
339
+ if (unknownByTuple.size === 0) return;
340
+ const payload = JSON.stringify(
341
+ Array.from(unknownByTuple.values(), (entry) => [
342
+ entry.id,
343
+ entry.mirrorHash,
344
+ entry.seq,
345
+ ])
346
+ );
347
+ const seenTuples = new Set<string>();
348
+ for (const owner of batchOwners.all(payload)) {
349
+ const tupleKey = `${owner.id}\0${owner.mirrorHash}\0${owner.seq}`;
350
+ seenTuples.add(tupleKey);
351
+ const entry = unknownByTuple.get(tupleKey);
352
+ if (!entry) continue;
353
+ const actualHash = embeddingInputHash(
354
+ formatDocForEmbedding(owner.text, owner.title ?? undefined, model)
355
+ );
356
+ for (const expectedHash of entry.inputHashes) {
357
+ proofs.set(
358
+ vectorProofKey(
359
+ model,
360
+ owner.id,
361
+ owner.mirrorHash,
362
+ owner.seq,
363
+ expectedHash
364
+ ),
365
+ actualHash === expectedHash
366
+ );
367
+ }
368
+ }
369
+ for (const [tupleKey, entry] of unknownByTuple) {
370
+ if (seenTuples.has(tupleKey)) continue;
371
+ for (const expectedHash of entry.inputHashes) {
372
+ proofs.set(
373
+ vectorProofKey(
374
+ model,
375
+ entry.id,
376
+ entry.mirrorHash,
377
+ entry.seq,
378
+ expectedHash
379
+ ),
380
+ false
381
+ );
382
+ }
383
+ }
384
+ }
385
+
386
+ function resolveActivePartition(
150
387
  db: Database,
151
388
  model: string,
152
389
  dimensions: number,
153
- embedding: Float32Array,
154
- k: number,
155
- options: VectorSearchOptions = {}
156
- ): VectorSearchResult[] | null {
390
+ embeddings: readonly Float32Array[],
391
+ options: VectorSearchOptions
392
+ ): { partitionId: string; tableName: string; hasMirror: boolean } | null {
157
393
  if (
158
394
  !db
159
395
  .query("SELECT 1 FROM sqlite_master WHERE name = 'vector_partitions'")
160
396
  .get()
161
397
  )
162
398
  return null;
163
- const activated = db
164
- .query(
165
- "SELECT 1 FROM vector_partitions WHERE model = ? AND state = 'active' AND activated_epoch IS NOT NULL LIMIT 1"
166
- )
167
- .get(model);
399
+
400
+ const hasActivatedForModel = (): boolean =>
401
+ Boolean(
402
+ db
403
+ .query(
404
+ "SELECT 1 FROM vector_partitions WHERE model = ? AND state = 'active' AND activated_epoch IS NOT NULL LIMIT 1"
405
+ )
406
+ .get(model)
407
+ );
408
+
409
+ const validDimensions = embeddings.every((e) => e.length === dimensions);
168
410
  const identity = options.embeddingIdentity;
169
411
  let partitionId: string;
170
412
  if (options.partitionId !== undefined) {
171
413
  const stored = db
172
- .query<{ model: string; dimensions: number }, [string]>(
173
- "SELECT model, dimensions FROM vector_partitions WHERE partition_id = ?"
414
+ .query<
415
+ {
416
+ model: string;
417
+ dimensions: number;
418
+ state: string;
419
+ activated_epoch: number | null;
420
+ },
421
+ [string]
422
+ >(
423
+ "SELECT model, dimensions, state, activated_epoch FROM vector_partitions WHERE partition_id = ?"
174
424
  )
175
425
  .get(options.partitionId);
176
426
  if (
177
427
  stored?.model !== model ||
178
428
  stored.dimensions !== dimensions ||
179
- embedding.length !== dimensions
429
+ !validDimensions
180
430
  )
181
431
  throw new Error("Stored vector partition does not match vector index");
432
+ if (stored.state !== "active" || stored.activated_epoch === null)
433
+ throw new Error(
434
+ "Selected embedding variant partition has not activated; run gno embed"
435
+ );
182
436
  partitionId = options.partitionId;
183
437
  } else {
184
438
  if (!identity) {
185
- if (activated)
439
+ if (hasActivatedForModel())
186
440
  throw new Error(
187
441
  "Effective embedding identity unavailable after variant activation"
188
442
  );
@@ -191,29 +445,147 @@ function searchVectorVariantsInSnapshot(
191
445
  if (
192
446
  identity.model !== model ||
193
447
  identity.dimensions !== dimensions ||
194
- embedding.length !== dimensions
448
+ !validDimensions
195
449
  )
196
450
  throw new Error("Query embedding identity does not match vector index");
197
451
  partitionId = identityPartitionId(identity);
452
+ const partition = db
453
+ .query<{ state: string; activated_epoch: number | null }, [string]>(
454
+ "SELECT state, activated_epoch FROM vector_partitions WHERE partition_id = ?"
455
+ )
456
+ .get(partitionId);
457
+ if (partition?.state !== "active" || partition.activated_epoch === null) {
458
+ if (hasActivatedForModel())
459
+ throw new Error(
460
+ "Selected embedding variant partition has not activated; run gno embed"
461
+ );
462
+ return null;
463
+ }
198
464
  }
199
- const partition = db
200
- .query<{ state: string; activated_epoch: number | null }, [string]>(
201
- "SELECT state, activated_epoch FROM vector_partitions WHERE partition_id = ?"
465
+ const tableName = `vec_v1_${partitionId}`;
466
+ const hasMirror = Boolean(
467
+ db.query("SELECT 1 FROM sqlite_master WHERE name = ?").get(tableName)
468
+ );
469
+ return { partitionId, tableName, hasMirror };
470
+ }
471
+
472
+ /**
473
+ * Clean-mirror vec0 fast path for unfiltered searches. Returns exact top-k
474
+ * hits when boundary safety is mathematically proven, or `null` to fall back
475
+ * transparently to the authoritative `vector_variants` scan.
476
+ */
477
+ function searchVectorVariantsViaVec0(
478
+ db: Database,
479
+ model: string,
480
+ partitionId: string,
481
+ tableName: string,
482
+ embedding: Float32Array,
483
+ k: number,
484
+ minScore: number | undefined,
485
+ proofs: Map<string, boolean>,
486
+ batchOwners: ReturnType<typeof createBatchOwnersStmt>
487
+ ): VectorSearchResult[] | null {
488
+ if (k > MAX_VEC0_K || !isNonZeroVector(embedding)) return null;
489
+ const queryVector = encodeEmbedding(embedding);
490
+ const vecK = Math.min(MAX_VEC0_K, Math.max(k + 16, k * 2));
491
+ const vecRows = db
492
+ .query<
493
+ { variantId: number; distance: number | null },
494
+ [Uint8Array, number]
495
+ >(
496
+ `SELECT variant_id AS variantId, distance FROM ${tableName} WHERE embedding MATCH ? AND k = ?`
202
497
  )
203
- .get(partitionId);
204
- if (partition?.state !== "active" || partition.activated_epoch === null) {
205
- if (activated || options.partitionId !== undefined)
206
- throw new Error(
207
- "Selected embedding variant partition has not activated; run gno embed"
208
- );
498
+ .all(queryVector, vecK);
499
+ if (vecRows.length === 0) return [];
500
+ const exhaustedMirror = vecRows.length < vecK;
501
+ const boundaryDistance = vecRows[vecRows.length - 1]!.distance;
502
+ if (
503
+ !exhaustedMirror &&
504
+ (boundaryDistance === null || Number.isNaN(boundaryDistance))
505
+ ) {
209
506
  return null;
210
507
  }
211
- const tableName = `vec_v1_${partitionId}`;
212
- if (!db.query("SELECT 1 FROM sqlite_master WHERE name = ?").get(tableName))
213
- throw new Error("Activated variant index unavailable; run gno embed");
214
- // The vec0 mirror is written in the same transactions as vector_variants and
215
- // checked at activation and by `gno vec sync`; ranking below reads only
216
- // vector_variants, so the mirror is never trusted here.
508
+ const variantIds = vecRows.map((row) => row.variantId);
509
+ const hydrated = db
510
+ .query<RankedVariantRow, [Uint8Array, string, string]>(`
511
+ SELECT o.variant_id AS variantId, o.mirror_hash AS mirrorHash, o.seq,
512
+ v.input_hash AS inputHash,
513
+ vec_distance_cosine(v.embedding, ?) AS distance,
514
+ json_group_array(o.document_id) AS documentIds
515
+ FROM vector_owners o
516
+ JOIN documents d ON d.id = o.document_id AND d.active = 1 AND d.mirror_hash = o.mirror_hash
517
+ JOIN content_chunks c${chunkKeyHint(db)} ON c.mirror_hash = o.mirror_hash AND c.seq = o.seq
518
+ JOIN vector_variants v${variantPartitionIdHint(db)}
519
+ ON v.partition_id = o.partition_id AND v.variant_id = o.variant_id
520
+ WHERE o.partition_id = ?
521
+ AND o.variant_id IN (SELECT value FROM json_each(?))
522
+ GROUP BY o.variant_id, o.mirror_hash, o.seq
523
+ ORDER BY distance, o.mirror_hash, o.seq, o.variant_id
524
+ `)
525
+ .all(queryVector, partitionId, JSON.stringify(variantIds));
526
+
527
+ let hitMinScoreCutoff = false;
528
+ let cutoffDistance: number | null = null;
529
+ const candidateRows: CandidateRow[] = [];
530
+ for (const row of hydrated) {
531
+ if (minScore !== undefined && 1 - row.distance < minScore) {
532
+ hitMinScoreCutoff = true;
533
+ cutoffDistance = row.distance;
534
+ break;
535
+ }
536
+ candidateRows.push({
537
+ variantId: row.variantId ?? 0,
538
+ mirrorHash: row.mirrorHash,
539
+ seq: row.seq,
540
+ inputHash: row.inputHash,
541
+ distance: row.distance,
542
+ documentIds: JSON.parse(row.documentIds) as number[],
543
+ });
544
+ }
545
+ proveUnknownOwners(model, proofs, [candidateRows], batchOwners);
546
+
547
+ const results: VectorSearchResult[] = [];
548
+ for (const row of candidateRows) {
549
+ const proven = row.documentIds
550
+ .filter((id) =>
551
+ proofs.get(
552
+ vectorProofKey(model, id, row.mirrorHash, row.seq, row.inputHash)
553
+ )
554
+ )
555
+ .sort((a, b) => a - b);
556
+ if (proven.length === 0) continue;
557
+ results.push({
558
+ mirrorHash: row.mirrorHash,
559
+ seq: row.seq,
560
+ distance: row.distance,
561
+ documentIds: proven,
562
+ });
563
+ if (results.length === k) break;
564
+ }
565
+
566
+ if (exhaustedMirror) return results;
567
+ if (
568
+ hitMinScoreCutoff &&
569
+ cutoffDistance !== null &&
570
+ cutoffDistance < boundaryDistance!
571
+ ) {
572
+ return results;
573
+ }
574
+ if (
575
+ results.length === k &&
576
+ results[k - 1]!.distance !== null &&
577
+ results[k - 1]!.distance < boundaryDistance!
578
+ ) {
579
+ return results;
580
+ }
581
+ return null;
582
+ }
583
+
584
+ function buildEligibleVariantQuerySpec(
585
+ db: Database,
586
+ partitionId: string,
587
+ options: VectorSearchOptions
588
+ ) {
217
589
  const eligible = buildEligibleDocumentQuery(
218
590
  { ...options.eligibility, semanticMetadata: true },
219
591
  db
@@ -228,76 +600,83 @@ function searchVectorVariantsInSnapshot(
228
600
  conditions.push("o.mirror_hash IN (SELECT value FROM json_each(?))");
229
601
  params.push(JSON.stringify(options.allowedMirrorHashes));
230
602
  }
231
- // Owner eligibility precedes ranking/LIMIT. Grouping before the distance
232
- // keeps embedding blobs out of the group sorter.
233
- const ranked = db.query<
234
- {
235
- mirrorHash: string;
236
- seq: number;
237
- inputHash: string;
238
- distance: number;
239
- documentIds: string;
240
- },
241
- (Uint8Array | string | number)[]
242
- >(`
243
- SELECT g.mirrorHash, g.seq, v.input_hash AS inputHash,
603
+ const selective = hasSelectiveEligibility(options);
604
+ const innerFrom = selective
605
+ ? `FROM (${eligible.sql}) e
606
+ CROSS JOIN vector_owners o${ownerDocPartHint(db)}
607
+ ON o.document_id = e.id AND o.mirror_hash = e.mirror_hash`
608
+ : `FROM vector_owners o${ownerPartitionVariantHint(db)}
609
+ CROSS JOIN (${eligible.sql}) e
610
+ ON e.id = o.document_id AND e.mirror_hash = o.mirror_hash`;
611
+ const chunkJoin = options.eligibility?.language
612
+ ? `JOIN content_chunks c${chunkKeyHint(db)} ON c.mirror_hash = o.mirror_hash AND c.seq = o.seq`
613
+ : "";
614
+ return { eligible, conditions, params, innerFrom, chunkJoin };
615
+ }
616
+
617
+ function searchVectorVariantsFromVariants(
618
+ db: Database,
619
+ model: string,
620
+ partitionId: string,
621
+ embedding: Float32Array,
622
+ k: number,
623
+ minScore: number | undefined,
624
+ spec: ReturnType<typeof buildEligibleVariantQuerySpec>,
625
+ proofs: Map<string, boolean>,
626
+ batchOwners: ReturnType<typeof createBatchOwnersStmt>
627
+ ): VectorSearchResult[] {
628
+ const ranked = db.query<RankedVariantRow, (Uint8Array | string | number)[]>(`
629
+ SELECT g.variantId, g.mirrorHash, g.seq, v.input_hash AS inputHash,
244
630
  vec_distance_cosine(v.embedding, ?) AS distance, g.documentIds
245
631
  FROM (
246
632
  SELECT o.variant_id AS variantId, o.mirror_hash AS mirrorHash, o.seq,
247
633
  json_group_array(o.document_id) AS documentIds
248
- FROM vector_owners o
249
- JOIN (${eligible.sql}) e ON e.id = o.document_id AND e.mirror_hash = o.mirror_hash
250
- JOIN content_chunks c ON c.mirror_hash = o.mirror_hash AND c.seq = o.seq
251
- WHERE ${conditions.join(" AND ")}
634
+ ${spec.innerFrom}
635
+ ${spec.chunkJoin}
636
+ WHERE ${spec.conditions.join(" AND ")}
252
637
  GROUP BY o.variant_id, o.mirror_hash, o.seq
253
638
  ) g
254
- JOIN vector_variants v ON v.variant_id = g.variantId AND v.partition_id = ?
639
+ CROSS JOIN vector_variants v${variantPartitionIdHint(db)}
640
+ ON v.partition_id = ? AND v.variant_id = g.variantId
255
641
  ORDER BY distance, g.mirrorHash, g.seq, g.variantId LIMIT ?
256
642
  `);
257
- const owners = db.query<
258
- { id: number; title: string | null; text: string },
259
- [string, number, string]
260
- >(`
261
- SELECT d.id, d.title, c.text FROM documents d
262
- JOIN content_chunks c ON c.mirror_hash = ? AND c.seq = ?
263
- WHERE d.id IN (SELECT value FROM json_each(?))
264
- `);
265
- // A vector counts only while it matches its owner's current formatted
266
- // input. Proving candidates in rank order and skipping unproven owners
267
- // returns exactly what filtering every owner before ranking would.
268
- const proofs = provenOwners(db);
269
643
  const queryVector = encodeEmbedding(embedding);
270
644
  let limit = k;
271
645
  let results: VectorSearchResult[] = [];
272
646
  for (;;) {
273
647
  const rows = ranked.all(
274
648
  queryVector,
275
- ...eligible.params,
276
- ...params,
649
+ ...spec.eligible.params,
650
+ ...spec.params,
277
651
  partitionId,
278
652
  limit
279
653
  );
280
- results = [];
654
+ let hitMinScoreCutoff = false;
655
+ const candidateRows: CandidateRow[] = [];
281
656
  for (const row of rows) {
282
- const documentIds = JSON.parse(row.documentIds) as number[];
283
- const key = (id: number) =>
284
- `${model}\0${id}\0${row.mirrorHash}\0${row.seq}\0${row.inputHash}`;
285
- const unknown = documentIds.filter((id) => !proofs.has(key(id)));
286
- if (unknown.length > 0) {
287
- for (const owner of owners.all(
288
- row.mirrorHash,
289
- row.seq,
290
- JSON.stringify(unknown)
291
- )) {
292
- proofs.set(
293
- key(owner.id),
294
- embeddingInputHash(
295
- formatDocForEmbedding(owner.text, owner.title ?? undefined, model)
296
- ) === row.inputHash
297
- );
298
- }
657
+ if (minScore !== undefined && 1 - row.distance < minScore) {
658
+ hitMinScoreCutoff = true;
659
+ break;
299
660
  }
300
- const proven = documentIds.filter((id) => proofs.get(key(id)));
661
+ candidateRows.push({
662
+ variantId: row.variantId ?? 0,
663
+ mirrorHash: row.mirrorHash,
664
+ seq: row.seq,
665
+ inputHash: row.inputHash,
666
+ distance: row.distance,
667
+ documentIds: JSON.parse(row.documentIds) as number[],
668
+ });
669
+ }
670
+ proveUnknownOwners(model, proofs, [candidateRows], batchOwners);
671
+ results = [];
672
+ for (const row of candidateRows) {
673
+ const proven = row.documentIds
674
+ .filter((id) =>
675
+ proofs.get(
676
+ vectorProofKey(model, id, row.mirrorHash, row.seq, row.inputHash)
677
+ )
678
+ )
679
+ .sort((a, b) => a - b);
301
680
  if (proven.length === 0) continue;
302
681
  results.push({
303
682
  mirrorHash: row.mirrorHash,
@@ -307,15 +686,664 @@ function searchVectorVariantsInSnapshot(
307
686
  });
308
687
  if (results.length === k) break;
309
688
  }
310
- if (results.length === k || rows.length < limit) break;
689
+ if (results.length === k || hitMinScoreCutoff || rows.length < limit) break;
311
690
  limit *= 4;
312
691
  }
313
- return results.filter(
314
- (row) =>
315
- options.minScore === undefined || 1 - row.distance >= options.minScore
692
+ return results;
693
+ }
694
+
695
+ function readPersistedNullCosineFlag(
696
+ db: Database,
697
+ partitionId: string
698
+ ): 0 | 1 | null {
699
+ if (!hasNullCosineColumn(db)) return null;
700
+ const row = db
701
+ .query<{ dirty: number; null_cosine: number | null }, [string]>(
702
+ "SELECT dirty, null_cosine FROM vector_mirror_state WHERE partition_id = ?"
703
+ )
704
+ .get(partitionId);
705
+ if (row?.dirty !== 0) return null;
706
+ return row.null_cosine === 0 ? 0 : row.null_cosine === 1 ? 1 : null;
707
+ }
708
+
709
+ /**
710
+ * Two-stage coarse bit search inside the active read snapshot (fn-235 §4):
711
+ * Stage 1: Hamming KNN on `vec_v2_<partitionId>` (per collection or unscoped).
712
+ * Stage 2: map rowids -> distinct `variant_id`s through `vector_partition_rows`,
713
+ * rescore exact float32 cosine against `vector_variants`, hydrate only
714
+ * eligible owners in scope (access-control boundary), run `proveUnknownOwners`,
715
+ * apply exact `minScore`, sort by `(distance, mirrorHash, seq, variantId)`.
716
+ *
717
+ * Returns `null` on underfill (fewer than `k` proven hits while Stage 1 filled
718
+ * `coarseK` and no candidate fell below `minScore`) so the caller reruns exact.
719
+ */
720
+ function searchVectorVariantsViaCoarseBit(
721
+ db: Database,
722
+ model: string,
723
+ partitionId: string,
724
+ embedding: Float32Array,
725
+ k: number,
726
+ coarseK: number,
727
+ collections: readonly string[],
728
+ minScore: number | undefined,
729
+ options: VectorSearchOptions,
730
+ proofs: Map<string, boolean>,
731
+ batchOwners: ReturnType<typeof createBatchOwnersStmt>
732
+ ): { results: VectorSearchResult[]; rescored: number } | null {
733
+ const queryVector = encodeEmbedding(embedding);
734
+ const v2Table = v2TableName(partitionId);
735
+ const rowidSet = new Set<number>();
736
+ let stage1ReturnedFull = false;
737
+
738
+ if (collections.length === 0) {
739
+ const rows = db
740
+ .query<{ rowid: number }, [Uint8Array, number]>(
741
+ `SELECT rowid FROM "${v2Table}"
742
+ WHERE coarse MATCH vec_quantize_binary(?) AND k = ?`
743
+ )
744
+ .all(queryVector, coarseK);
745
+ if (rows.length >= coarseK) stage1ReturnedFull = true;
746
+ for (const r of rows) rowidSet.add(r.rowid);
747
+ } else {
748
+ const legStmt = db.prepare<{ rowid: number }, [Uint8Array, number, string]>(
749
+ `SELECT rowid FROM "${v2Table}"
750
+ WHERE coarse MATCH vec_quantize_binary(?) AND k = ? AND collection = ?`
751
+ );
752
+ try {
753
+ for (const collection of collections) {
754
+ const rows = legStmt.all(queryVector, coarseK, collection);
755
+ if (rows.length >= coarseK) stage1ReturnedFull = true;
756
+ for (const r of rows) rowidSet.add(r.rowid);
757
+ }
758
+ } finally {
759
+ legStmt.finalize();
760
+ }
761
+ }
762
+
763
+ if (rowidSet.size === 0) {
764
+ return { results: [], rescored: 0 };
765
+ }
766
+
767
+ // Map rowids -> distinct variant_ids through plain table `vector_partition_rows`
768
+ // driven by json_each CROSS JOIN PK seeks (never passing rowids to vec0 `rowid IN`).
769
+ const variantIds = db
770
+ .query<{ variant_id: number }, [string, string]>(
771
+ `SELECT DISTINCT r.variant_id
772
+ FROM json_each(?) AS m
773
+ CROSS JOIN vector_partition_rows r ON r.id = m.value
774
+ WHERE r.partition_id = ?`
775
+ )
776
+ .all(JSON.stringify([...rowidSet]), partitionId)
777
+ .map((r) => r.variant_id);
778
+
779
+ if (variantIds.length === 0) {
780
+ return stage1ReturnedFull ? null : { results: [], rescored: 0 };
781
+ }
782
+
783
+ // Stage 2: exact float32 rescore + eligible-documents owner hydration enforcing
784
+ // the exact collection access-control boundary. CROSS JOIN pins json_each(cand)
785
+ // as the outer loop so SQLite seeks only the <= coarseK candidate variants
786
+ // instead of scanning all vector_owners in the partition.
787
+ const eligible = buildEligibleDocumentQuery(
788
+ { ...options.eligibility, semanticMetadata: true },
789
+ db
790
+ );
791
+ const hydrated = db
792
+ .query<RankedVariantRow, (Uint8Array | string | number)[]>(
793
+ `SELECT o.variant_id AS variantId, o.mirror_hash AS mirrorHash, o.seq,
794
+ v.input_hash AS inputHash,
795
+ vec_distance_cosine(v.embedding, ?) AS distance,
796
+ json_group_array(o.document_id) AS documentIds
797
+ FROM json_each(?) AS cand
798
+ CROSS JOIN vector_variants v${variantPartitionIdHint(db)}
799
+ ON v.partition_id = ? AND v.variant_id = cand.value
800
+ CROSS JOIN vector_owners o${ownerPartitionVariantHint(db)}
801
+ ON o.partition_id = v.partition_id AND o.variant_id = v.variant_id
802
+ CROSS JOIN (${eligible.sql}) e
803
+ ON e.id = o.document_id AND e.mirror_hash = o.mirror_hash
804
+ GROUP BY o.variant_id, o.mirror_hash, o.seq
805
+ ORDER BY distance, o.mirror_hash, o.seq, o.variant_id`
806
+ )
807
+ .all(
808
+ queryVector,
809
+ JSON.stringify(variantIds),
810
+ partitionId,
811
+ ...eligible.params
812
+ );
813
+
814
+ let hitMinScoreCutoff = false;
815
+ const candidateRows: CandidateRow[] = [];
816
+ for (const row of hydrated) {
817
+ if (
818
+ minScore !== undefined &&
819
+ row.distance !== null &&
820
+ 1 - row.distance < minScore
821
+ ) {
822
+ hitMinScoreCutoff = true;
823
+ break;
824
+ }
825
+ candidateRows.push({
826
+ variantId: row.variantId ?? 0,
827
+ mirrorHash: row.mirrorHash,
828
+ seq: row.seq,
829
+ inputHash: row.inputHash,
830
+ distance: row.distance,
831
+ documentIds: JSON.parse(row.documentIds) as number[],
832
+ });
833
+ }
834
+
835
+ proveUnknownOwners(model, proofs, [candidateRows], batchOwners);
836
+
837
+ const results: VectorSearchResult[] = [];
838
+ for (const row of candidateRows) {
839
+ const proven = row.documentIds
840
+ .filter((id) =>
841
+ proofs.get(
842
+ vectorProofKey(model, id, row.mirrorHash, row.seq, row.inputHash)
843
+ )
844
+ )
845
+ .sort((a, b) => a - b);
846
+ if (proven.length === 0) continue;
847
+ results.push({
848
+ mirrorHash: row.mirrorHash,
849
+ seq: row.seq,
850
+ distance: row.distance,
851
+ documentIds: proven,
852
+ });
853
+ if (results.length === k) break;
854
+ }
855
+
856
+ // Underfill: if fewer than k proven results remain, Stage 1 returned a full
857
+ // coarseK, and no candidate fell below minScore, rerun exact (never raise coarseK > 500).
858
+ if (results.length < k && stage1ReturnedFull && !hitMinScoreCutoff) {
859
+ return null;
860
+ }
861
+
862
+ return { results, rescored: variantIds.length };
863
+ }
864
+
865
+ /** Null means legacy authority. Once promoted, unavailable provenance fails closed. */
866
+ function searchVectorVariantsInSnapshot(
867
+ db: Database,
868
+ model: string,
869
+ dimensions: number,
870
+ embedding: Float32Array,
871
+ k: number,
872
+ options: VectorSearchOptions,
873
+ inOuterTransaction: boolean,
874
+ pendingPersist: { value?: NullCosineCheckResult["persistAfterSnapshot"] }
875
+ ): VectorSearchResult[] | null {
876
+ const resolved = resolveActivePartition(
877
+ db,
878
+ model,
879
+ dimensions,
880
+ [embedding],
881
+ options
882
+ );
883
+ if (!resolved) return null;
884
+ const { partitionId, tableName, hasMirror } = resolved;
885
+ const spec = buildEligibleVariantQuerySpec(db, partitionId, options);
886
+ const minScore = options.minScore;
887
+ if (minScore !== undefined && Number.isNaN(minScore)) {
888
+ return [];
889
+ }
890
+ const batchOwners = createBatchOwnersStmt(db);
891
+ const proofs = provenOwners(db, inOuterTransaction);
892
+
893
+ const collections = extractRequestedCollections(options);
894
+ const hasV2Tables = hasV2MirrorTables(db);
895
+ const mirrorRows = countScopeMirrorRows(
896
+ db,
897
+ partitionId,
898
+ collections,
899
+ hasV2Tables,
900
+ inOuterTransaction
901
+ );
902
+
903
+ // Check v1 clean unfiltered mirror eligibility (for exact-vec0 fast path).
904
+ const v1UnfilteredClean =
905
+ hasMirror &&
906
+ !hasSelectiveEligibility(options) &&
907
+ !options.eligibility?.language &&
908
+ isMirrorClean(db, partitionId);
909
+
910
+ let nullCosineFlag: 0 | 1 | null = null;
911
+ let canUseV1ExactVec0 = false;
912
+ if (v1UnfilteredClean) {
913
+ const nullCheck = checkNullCosineVariant(
914
+ db,
915
+ partitionId,
916
+ inOuterTransaction
917
+ );
918
+ if (nullCheck.persistAfterSnapshot) {
919
+ pendingPersist.value = nullCheck.persistAfterSnapshot;
920
+ }
921
+ nullCosineFlag = nullCheck.found ? 1 : 0;
922
+ canUseV1ExactVec0 = !nullCheck.found;
923
+ } else if (
924
+ !hasNonCollectionFilter(options) &&
925
+ (options.coarseVectorSearch ?? COARSE_ROUTER_DEFAULTS.enabledByDefault) &&
926
+ options.exact !== true
927
+ ) {
928
+ // Scoped coarse check: O(1) persisted PK lookup only, never triggering a scan.
929
+ nullCosineFlag = readPersistedNullCosineFlag(db, partitionId);
930
+ }
931
+
932
+ const v2State =
933
+ hasV2Tables &&
934
+ isV2CompatibleDimensions(dimensions) &&
935
+ hasV2Table(db, partitionId)
936
+ ? readV2MirrorState(db, partitionId)
937
+ : null;
938
+
939
+ const decision = resolveVectorRoute({
940
+ options,
941
+ dimensions,
942
+ queryCount: 1,
943
+ maxK: k,
944
+ collections,
945
+ mirrorRows,
946
+ v2MirrorClean: v2State?.dirty === 0,
947
+ v2CheckRecall: v2State?.checkRecall ?? null,
948
+ nullCosineFlag,
949
+ canUseV1ExactVec0,
950
+ });
951
+
952
+ if (decision.route === "coarse-bit" && decision.coarseK !== undefined) {
953
+ const coarse = searchVectorVariantsViaCoarseBit(
954
+ db,
955
+ model,
956
+ partitionId,
957
+ embedding,
958
+ k,
959
+ decision.coarseK,
960
+ collections,
961
+ minScore,
962
+ options,
963
+ proofs,
964
+ batchOwners
965
+ );
966
+ if (coarse !== null) {
967
+ options.onRoute?.({
968
+ route: "coarse-bit",
969
+ mirrorRows,
970
+ coarseK: decision.coarseK,
971
+ rescored: coarse.rescored,
972
+ });
973
+ return coarse.results;
974
+ }
975
+ // Underfill fallback to exact path.
976
+ }
977
+
978
+ if (canUseV1ExactVec0) {
979
+ const fast = searchVectorVariantsViaVec0(
980
+ db,
981
+ model,
982
+ partitionId,
983
+ tableName,
984
+ embedding,
985
+ k,
986
+ minScore,
987
+ proofs,
988
+ batchOwners
989
+ );
990
+ if (fast !== null) {
991
+ options.onRoute?.({ route: "exact-vec0", mirrorRows });
992
+ return fast;
993
+ }
994
+ }
995
+
996
+ options.onRoute?.({ route: "exact-sql", mirrorRows });
997
+ return searchVectorVariantsFromVariants(
998
+ db,
999
+ model,
1000
+ partitionId,
1001
+ embedding,
1002
+ k,
1003
+ minScore,
1004
+ spec,
1005
+ proofs,
1006
+ batchOwners
316
1007
  );
317
1008
  }
318
1009
 
1010
+ /**
1011
+ * Batched variant search sharing one snapshot, one eligible scan (when filtered
1012
+ * or dirty), and one batched owner proof pass across all query embeddings.
1013
+ */
1014
+ function searchVectorVariantsBatchInSnapshot(
1015
+ db: Database,
1016
+ model: string,
1017
+ dimensions: number,
1018
+ embeddings: readonly Float32Array[],
1019
+ limits: readonly number[],
1020
+ options: VectorSearchOptions,
1021
+ inOuterTransaction: boolean,
1022
+ pendingPersist: { value?: NullCosineCheckResult["persistAfterSnapshot"] }
1023
+ ): VectorSearchResult[][] | null {
1024
+ const resolved = resolveActivePartition(
1025
+ db,
1026
+ model,
1027
+ dimensions,
1028
+ embeddings,
1029
+ options
1030
+ );
1031
+ if (!resolved) return null;
1032
+ const { partitionId, tableName, hasMirror } = resolved;
1033
+ const spec = buildEligibleVariantQuerySpec(db, partitionId, options);
1034
+ const minScore = options.minScore;
1035
+ if (minScore !== undefined && Number.isNaN(minScore)) {
1036
+ return embeddings.map(() => []);
1037
+ }
1038
+ const batchOwners = createBatchOwnersStmt(db);
1039
+ const proofs = provenOwners(db, inOuterTransaction);
1040
+
1041
+ const collections = extractRequestedCollections(options);
1042
+ const hasV2Tables = hasV2MirrorTables(db);
1043
+ const mirrorRows = countScopeMirrorRows(
1044
+ db,
1045
+ partitionId,
1046
+ collections,
1047
+ hasV2Tables,
1048
+ inOuterTransaction
1049
+ );
1050
+
1051
+ const v1UnfilteredClean =
1052
+ hasMirror &&
1053
+ !hasSelectiveEligibility(options) &&
1054
+ !options.eligibility?.language &&
1055
+ isMirrorClean(db, partitionId);
1056
+
1057
+ let nullCosineFlag: 0 | 1 | null = null;
1058
+ let canUseV1ExactVec0 = false;
1059
+ if (v1UnfilteredClean) {
1060
+ const nullCheck = checkNullCosineVariant(
1061
+ db,
1062
+ partitionId,
1063
+ inOuterTransaction
1064
+ );
1065
+ if (nullCheck.persistAfterSnapshot) {
1066
+ pendingPersist.value = nullCheck.persistAfterSnapshot;
1067
+ }
1068
+ nullCosineFlag = nullCheck.found ? 1 : 0;
1069
+ canUseV1ExactVec0 = !nullCheck.found;
1070
+ } else if (
1071
+ !hasNonCollectionFilter(options) &&
1072
+ (options.coarseVectorSearch ?? COARSE_ROUTER_DEFAULTS.enabledByDefault) &&
1073
+ options.exact !== true
1074
+ ) {
1075
+ nullCosineFlag = readPersistedNullCosineFlag(db, partitionId);
1076
+ }
1077
+
1078
+ const v2State =
1079
+ hasV2Tables &&
1080
+ isV2CompatibleDimensions(dimensions) &&
1081
+ hasV2Table(db, partitionId)
1082
+ ? readV2MirrorState(db, partitionId)
1083
+ : null;
1084
+
1085
+ const maxK = limits.reduce((acc, val) => (val > acc ? val : acc), 0);
1086
+ const decision = resolveVectorRoute({
1087
+ options,
1088
+ dimensions,
1089
+ queryCount: embeddings.length,
1090
+ maxK,
1091
+ collections,
1092
+ mirrorRows,
1093
+ v2MirrorClean: v2State?.dirty === 0,
1094
+ v2CheckRecall: v2State?.checkRecall ?? null,
1095
+ nullCosineFlag,
1096
+ canUseV1ExactVec0,
1097
+ });
1098
+
1099
+ if (decision.route === "coarse-bit" && decision.coarseK !== undefined) {
1100
+ let totalRescored = 0;
1101
+ let allCoarseSucceeded = true;
1102
+ const out = embeddings.map((embedding, i) => {
1103
+ const k = limits[i]!;
1104
+ const queryCoarseK = computeCoarseK(k);
1105
+ const coarse = searchVectorVariantsViaCoarseBit(
1106
+ db,
1107
+ model,
1108
+ partitionId,
1109
+ embedding,
1110
+ k,
1111
+ queryCoarseK,
1112
+ collections,
1113
+ minScore,
1114
+ options,
1115
+ proofs,
1116
+ batchOwners
1117
+ );
1118
+ if (coarse !== null) {
1119
+ totalRescored += coarse.rescored;
1120
+ return coarse.results;
1121
+ }
1122
+ allCoarseSucceeded = false;
1123
+ if (canUseV1ExactVec0) {
1124
+ const fast = searchVectorVariantsViaVec0(
1125
+ db,
1126
+ model,
1127
+ partitionId,
1128
+ tableName,
1129
+ embedding,
1130
+ k,
1131
+ minScore,
1132
+ proofs,
1133
+ batchOwners
1134
+ );
1135
+ if (fast !== null) return fast;
1136
+ }
1137
+ return searchVectorVariantsFromVariants(
1138
+ db,
1139
+ model,
1140
+ partitionId,
1141
+ embedding,
1142
+ k,
1143
+ minScore,
1144
+ spec,
1145
+ proofs,
1146
+ batchOwners
1147
+ );
1148
+ });
1149
+ options.onRoute?.(
1150
+ allCoarseSucceeded
1151
+ ? {
1152
+ route: "coarse-bit",
1153
+ mirrorRows,
1154
+ coarseK: decision.coarseK,
1155
+ rescored: totalRescored,
1156
+ }
1157
+ : {
1158
+ route: canUseV1ExactVec0 ? "exact-vec0" : "exact-sql",
1159
+ mirrorRows,
1160
+ }
1161
+ );
1162
+ return out;
1163
+ }
1164
+
1165
+ if (canUseV1ExactVec0) {
1166
+ let anyFallback = false;
1167
+ const out = embeddings.map((embedding, i) => {
1168
+ const k = limits[i]!;
1169
+ const fast = searchVectorVariantsViaVec0(
1170
+ db,
1171
+ model,
1172
+ partitionId,
1173
+ tableName,
1174
+ embedding,
1175
+ k,
1176
+ minScore,
1177
+ proofs,
1178
+ batchOwners
1179
+ );
1180
+ if (fast !== null) return fast;
1181
+ anyFallback = true;
1182
+ return searchVectorVariantsFromVariants(
1183
+ db,
1184
+ model,
1185
+ partitionId,
1186
+ embedding,
1187
+ k,
1188
+ minScore,
1189
+ spec,
1190
+ proofs,
1191
+ batchOwners
1192
+ );
1193
+ });
1194
+ options.onRoute?.({
1195
+ route: anyFallback ? "exact-sql" : "exact-vec0",
1196
+ mirrorRows,
1197
+ });
1198
+ return out;
1199
+ }
1200
+
1201
+ options.onRoute?.({ route: "exact-sql", mirrorRows });
1202
+
1203
+ // Filtered or dirty mirror: scan eligible vector_variants ONCE per chunk of up to 8 queries.
1204
+ const allResults: VectorSearchResult[][] = Array.from<VectorSearchResult[]>({
1205
+ length: embeddings.length,
1206
+ });
1207
+ for (
1208
+ let offset = 0;
1209
+ offset < embeddings.length;
1210
+ offset += MAX_SQL_BATCH_QUERIES
1211
+ ) {
1212
+ const sliceEmbeddings = embeddings.slice(
1213
+ offset,
1214
+ offset + MAX_SQL_BATCH_QUERIES
1215
+ );
1216
+ const sliceLimits = limits.slice(offset, offset + MAX_SQL_BATCH_QUERIES);
1217
+ const count = sliceEmbeddings.length;
1218
+ const distanceSelects = sliceEmbeddings
1219
+ .map((_, i) => `vec_distance_cosine(v.embedding, ?) AS d${i}`)
1220
+ .join(", ");
1221
+ const sql = `
1222
+ SELECT g.variantId, g.mirrorHash, g.seq, v.input_hash AS inputHash, g.documentIds,
1223
+ ${distanceSelects}
1224
+ FROM (
1225
+ SELECT o.variant_id AS variantId, o.mirror_hash AS mirrorHash, o.seq,
1226
+ json_group_array(o.document_id) AS documentIds
1227
+ ${spec.innerFrom}
1228
+ ${spec.chunkJoin}
1229
+ WHERE ${spec.conditions.join(" AND ")}
1230
+ GROUP BY o.variant_id, o.mirror_hash, o.seq
1231
+ ) g
1232
+ CROSS JOIN vector_variants v${variantPartitionIdHint(db)}
1233
+ ON v.partition_id = ? AND v.variant_id = g.variantId
1234
+ `;
1235
+ const queryVectors = sliceEmbeddings.map((e) => encodeEmbedding(e));
1236
+ const heaps: CandidateRow[][] = sliceLimits.map(() => []);
1237
+ const caps = sliceLimits.map((k) => Math.max(k + 32, k * 2));
1238
+ let totalEligibleRows = 0;
1239
+ const stmt = db.prepare<
1240
+ Record<string, unknown>,
1241
+ (Uint8Array | string | number)[]
1242
+ >(sql);
1243
+ try {
1244
+ for (const row of stmt.iterate(
1245
+ ...queryVectors,
1246
+ ...spec.eligible.params,
1247
+ ...spec.params,
1248
+ partitionId
1249
+ )) {
1250
+ totalEligibleRows++;
1251
+ const variantId = row.variantId as number;
1252
+ const mirrorHash = row.mirrorHash as string;
1253
+ const seq = row.seq as number;
1254
+ const inputHash = row.inputHash as string;
1255
+ let parsedDocIds: number[] | null = null;
1256
+ for (let q = 0; q < count; q++) {
1257
+ const distance = row[`d${q}`] as number;
1258
+ const heap = heaps[q]!;
1259
+ const cap = caps[q]!;
1260
+ // Quick reject before JSON.parse when heap is already full with a better worst element
1261
+ if (heap.length >= cap) {
1262
+ const worst = heap[0]!;
1263
+ const aNull = distance === null;
1264
+ const bNull = worst.distance === null;
1265
+ if (!aNull && bNull) continue;
1266
+ if (!aNull && !bNull && distance > worst.distance) continue;
1267
+ }
1268
+ parsedDocIds ??= JSON.parse(row.documentIds as string) as number[];
1269
+ pushBoundedCandidate(heap, cap, {
1270
+ variantId,
1271
+ mirrorHash,
1272
+ seq,
1273
+ inputHash,
1274
+ distance,
1275
+ documentIds: parsedDocIds,
1276
+ });
1277
+ }
1278
+ }
1279
+ } finally {
1280
+ stmt.finalize();
1281
+ }
1282
+
1283
+ const sortedCandidates: CandidateRow[][] = [];
1284
+ const hitCutoffs: boolean[] = [];
1285
+ for (let q = 0; q < count; q++) {
1286
+ const heap = heaps[q]!;
1287
+ heap.sort(compareVariantCandidates);
1288
+ let hitCutoff = false;
1289
+ const kept: CandidateRow[] = [];
1290
+ for (const row of heap) {
1291
+ if (minScore !== undefined && 1 - row.distance < minScore) {
1292
+ hitCutoff = true;
1293
+ break;
1294
+ }
1295
+ kept.push(row);
1296
+ }
1297
+ sortedCandidates.push(kept);
1298
+ hitCutoffs.push(hitCutoff);
1299
+ }
1300
+
1301
+ proveUnknownOwners(model, proofs, sortedCandidates, batchOwners);
1302
+
1303
+ for (let q = 0; q < count; q++) {
1304
+ const k = sliceLimits[q]!;
1305
+ const results: VectorSearchResult[] = [];
1306
+ for (const row of sortedCandidates[q]!) {
1307
+ const proven = row.documentIds
1308
+ .filter((id) =>
1309
+ proofs.get(
1310
+ vectorProofKey(model, id, row.mirrorHash, row.seq, row.inputHash)
1311
+ )
1312
+ )
1313
+ .sort((a, b) => a - b);
1314
+ if (proven.length === 0) continue;
1315
+ results.push({
1316
+ mirrorHash: row.mirrorHash,
1317
+ seq: row.seq,
1318
+ distance: row.distance,
1319
+ documentIds: proven,
1320
+ });
1321
+ if (results.length === k) break;
1322
+ }
1323
+ if (
1324
+ results.length < k &&
1325
+ !hitCutoffs[q] &&
1326
+ totalEligibleRows > caps[q]!
1327
+ ) {
1328
+ allResults[offset + q] = searchVectorVariantsFromVariants(
1329
+ db,
1330
+ model,
1331
+ partitionId,
1332
+ sliceEmbeddings[q]!,
1333
+ k,
1334
+ minScore,
1335
+ spec,
1336
+ proofs,
1337
+ batchOwners
1338
+ );
1339
+ } else {
1340
+ allResults[offset + q] = results;
1341
+ }
1342
+ }
1343
+ }
1344
+ return allResults;
1345
+ }
1346
+
319
1347
  /** Keep eligibility, provenance validation and ranking on one SQLite snapshot. */
320
1348
  export function searchVectorVariants(
321
1349
  db: Database,
@@ -325,7 +1353,55 @@ export function searchVectorVariants(
325
1353
  k: number,
326
1354
  options: VectorSearchOptions = {}
327
1355
  ): VectorSearchResult[] | null {
328
- return db.transaction(() =>
329
- searchVectorVariantsInSnapshot(db, model, dimensions, embedding, k, options)
1356
+ const inOuterTransaction = db.inTransaction;
1357
+ const pendingPersist: {
1358
+ value?: NullCosineCheckResult["persistAfterSnapshot"];
1359
+ } = {};
1360
+ const result = db.transaction(() =>
1361
+ searchVectorVariantsInSnapshot(
1362
+ db,
1363
+ model,
1364
+ dimensions,
1365
+ embedding,
1366
+ k,
1367
+ options,
1368
+ inOuterTransaction,
1369
+ pendingPersist
1370
+ )
1371
+ )();
1372
+ if (!inOuterTransaction && pendingPersist.value) {
1373
+ persistNullCosineAfterSnapshot(writerConnection(db), pendingPersist.value);
1374
+ }
1375
+ return result;
1376
+ }
1377
+
1378
+ /** Keep batched eligibility, provenance validation and ranking on one SQLite snapshot. */
1379
+ export function searchVectorVariantsBatch(
1380
+ db: Database,
1381
+ model: string,
1382
+ dimensions: number,
1383
+ embeddings: readonly Float32Array[],
1384
+ limits: readonly number[],
1385
+ options: VectorSearchOptions = {}
1386
+ ): VectorSearchResult[][] | null {
1387
+ const inOuterTransaction = db.inTransaction;
1388
+ const pendingPersist: {
1389
+ value?: NullCosineCheckResult["persistAfterSnapshot"];
1390
+ } = {};
1391
+ const result = db.transaction(() =>
1392
+ searchVectorVariantsBatchInSnapshot(
1393
+ db,
1394
+ model,
1395
+ dimensions,
1396
+ embeddings,
1397
+ limits,
1398
+ options,
1399
+ inOuterTransaction,
1400
+ pendingPersist
1401
+ )
330
1402
  )();
1403
+ if (!inOuterTransaction && pendingPersist.value) {
1404
+ persistNullCosineAfterSnapshot(writerConnection(db), pendingPersist.value);
1405
+ }
1406
+ return result;
331
1407
  }