@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
@@ -4,8 +4,26 @@ import type { Database } from "bun:sqlite";
4
4
  import type { VectorOwnerInput, VectorVariantIdentity } from "./types";
5
5
 
6
6
  import { formatDocForEmbedding } from "../../pipeline/contextual";
7
- import { markMirrorClean } from "./partition-index";
8
- import { decodeEmbedding, encodeEmbedding } from "./sqlite-vec";
7
+ import { isV2CompatibleDimensions, v2TableName } from "./coarse-router";
8
+ import {
9
+ hasNullCosineColumn,
10
+ isNullCosineEmbedding,
11
+ markMirrorClean,
12
+ type NullCosineMark,
13
+ probePartitionNullCosine,
14
+ } from "./partition-index";
15
+ import { provenOwners, vectorProofKey } from "./proof-cache";
16
+ import { decodeEmbedding } from "./sqlite-vec";
17
+ import {
18
+ ensureV2Table,
19
+ hasV2MirrorTables,
20
+ hasV2Table,
21
+ markV2MirrorClean,
22
+ readV2MirrorState,
23
+ runV2RecallSelfCheck,
24
+ syncV2PartitionMirrorInTx,
25
+ v2MirrorFreshnessState,
26
+ } from "./v2-mirror";
9
27
 
10
28
  export const SELECTED_VECTOR_PARTITION_PREFIX = "vector_selected_partition:";
11
29
 
@@ -43,6 +61,68 @@ export function chunkKeyHint(db: Database): string {
43
61
  return pk ? ` INDEXED BY "${pk.name.replaceAll('"', '""')}"` : "";
44
62
  }
45
63
 
64
+ /** Covering index hint for document-driven `vector_owners` lookups (migration 037). */
65
+ export function ownerDocPartHint(db: Database): string {
66
+ if (
67
+ db
68
+ .query("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?")
69
+ .get("idx_vector_owners_doc_part")
70
+ ) {
71
+ return " INDEXED BY idx_vector_owners_doc_part";
72
+ }
73
+ return "";
74
+ }
75
+
76
+ /**
77
+ * Document-keyed index hint for `vector_owners`: prefers migration 037's
78
+ * covering index, else falls back to the primary key index so stale stats
79
+ * never trigger a table scan or Bloom filter.
80
+ */
81
+ function ownerDocOrPkHint(db: Database): string {
82
+ const covering = ownerDocPartHint(db);
83
+ if (covering) return covering;
84
+ const pk = db
85
+ .query<{ name: string }, []>(
86
+ "SELECT name FROM pragma_index_list('vector_owners') WHERE origin = 'pk'"
87
+ )
88
+ .get();
89
+ return pk ? ` INDEXED BY "${pk.name.replaceAll('"', '""')}"` : "";
90
+ }
91
+
92
+ /** Covering index hint for partition-driven `vector_owners` scans (migration 037). */
93
+ export function ownerPartitionVariantHint(db: Database): string {
94
+ return db
95
+ .query("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?")
96
+ .get("idx_vector_owners_partition_variant")
97
+ ? " INDEXED BY idx_vector_owners_partition_variant"
98
+ : "";
99
+ }
100
+
101
+ /** Unique `(partition_id, variant_id)` index hint on `vector_variants`. */
102
+ export function variantPartitionIdHint(db: Database): string {
103
+ const indexes = db
104
+ .query<{ name: string }, []>(
105
+ "SELECT name FROM pragma_index_list('vector_variants')"
106
+ )
107
+ .all();
108
+ for (const { name } of indexes) {
109
+ const cols = db
110
+ .query<{ name: string }, []>(
111
+ `SELECT name FROM pragma_index_info('${name.replaceAll("'", "''")}') ORDER BY seqno`
112
+ )
113
+ .all()
114
+ .map((row) => row.name);
115
+ if (
116
+ cols.length === 2 &&
117
+ cols[0] === "partition_id" &&
118
+ cols[1] === "variant_id"
119
+ ) {
120
+ return ` INDEXED BY "${name.replaceAll('"', '""')}"`;
121
+ }
122
+ }
123
+ return "";
124
+ }
125
+
46
126
  export function embeddingInputHash(input: string): string {
47
127
  return new Bun.CryptoHasher("sha256").update(input).digest("hex");
48
128
  }
@@ -91,7 +171,6 @@ interface OwnerRow {
91
171
 
92
172
  interface CandidateRow extends OwnerRow {
93
173
  boundHash: string | null;
94
- boundMirror: string | null;
95
174
  }
96
175
 
97
176
  interface VariantRow {
@@ -164,6 +243,18 @@ export class VectorVariantStore {
164
243
  variant_id INTEGER PRIMARY KEY,
165
244
  embedding FLOAT[${identity.dimensions}] distance_metric=cosine
166
245
  )`);
246
+ if (
247
+ hasV2MirrorTables(db) &&
248
+ isV2CompatibleDimensions(identity.dimensions)
249
+ ) {
250
+ if (!hasV2Table(db, this.partitionId)) {
251
+ db.run(
252
+ "DELETE FROM vector_mirror_v2_state WHERE partition_id = ?",
253
+ [this.partitionId]
254
+ );
255
+ }
256
+ ensureV2Table(db, this.partitionId, identity.dimensions);
257
+ }
167
258
  }
168
259
  }).immediate();
169
260
  }
@@ -221,6 +312,61 @@ export class VectorVariantStore {
221
312
  .get(this.partitionId, input.inputHash);
222
313
  }
223
314
 
315
+ /** BLOB-free existence check for a proven reusable vector. */
316
+ hasReusable(input: VectorOwnerInput): boolean {
317
+ this.validate(input);
318
+ return (
319
+ this.db
320
+ .query<{ ok: number }, [string, string]>(
321
+ "SELECT 1 AS ok FROM vector_variants WHERE partition_id = ? AND input_hash = ? LIMIT 1"
322
+ )
323
+ .get(this.partitionId, input.inputHash) !== null
324
+ );
325
+ }
326
+
327
+ /** Batch-filter current active owners in one SQL query. */
328
+ filterCurrent(owners: readonly VectorOwnerInput[]): VectorOwnerInput[] {
329
+ if (owners.length === 0) return [];
330
+ const currentByKey = this.fetchCurrentByKey(owners);
331
+ const valid: VectorOwnerInput[] = [];
332
+ for (const owner of owners) {
333
+ const current = currentByKey.get(`${owner.documentId}:${owner.seq}`);
334
+ if (
335
+ current &&
336
+ current.mirrorHash === owner.mirrorHash &&
337
+ current.formattedInput === owner.formattedInput &&
338
+ current.inputHash === owner.inputHash
339
+ ) {
340
+ valid.push(owner);
341
+ }
342
+ }
343
+ return valid;
344
+ }
345
+
346
+ /**
347
+ * Batch-validate active owners and check BLOB-free variant reusability in two
348
+ * SQL queries instead of 2N per-owner queries + N BLOB decodes.
349
+ */
350
+ findReusableHashes(owners: readonly VectorOwnerInput[]): {
351
+ current: VectorOwnerInput[];
352
+ reusableHashes: Set<string>;
353
+ } {
354
+ const current = this.filterCurrent(owners);
355
+ const reusableHashes = new Set<string>();
356
+ if (current.length === 0) return { current, reusableHashes };
357
+ const uniqueHashes = [...new Set(current.map((owner) => owner.inputHash))];
358
+ const rows = this.db
359
+ .query<{ input_hash: string }, [string, string]>(
360
+ `SELECT DISTINCT input_hash FROM vector_variants
361
+ WHERE partition_id = ? AND input_hash IN (SELECT value FROM json_each(?))`
362
+ )
363
+ .all(this.partitionId, JSON.stringify(uniqueHashes));
364
+ for (const row of rows) {
365
+ reusableHashes.add(row.input_hash);
366
+ }
367
+ return { current, reusableHashes };
368
+ }
369
+
224
370
  /** Returns a proven reusable vector, even before this owner has a binding. */
225
371
  reusable(
226
372
  input: VectorOwnerInput
@@ -232,6 +378,44 @@ export class VectorVariantStore {
232
378
  : null;
233
379
  }
234
380
 
381
+ private fetchCurrentByKey(
382
+ owners: readonly VectorOwnerInput[]
383
+ ): Map<string, VectorOwnerInput & { collection?: string }> {
384
+ const uniquePairs = new Map<string, [number, number]>();
385
+ for (const owner of owners) {
386
+ const key = `${owner.documentId}:${owner.seq}`;
387
+ if (!uniquePairs.has(key)) {
388
+ uniquePairs.set(key, [owner.documentId, owner.seq]);
389
+ }
390
+ }
391
+ const includeCollection = hasV2MirrorTables(this.db);
392
+ const fetchedOwners = this.db
393
+ .query<OwnerRow & { collection?: string }, [string]>(`
394
+ WITH req AS (
395
+ SELECT
396
+ json_extract(value, '$[0]') AS document_id,
397
+ json_extract(value, '$[1]') AS seq
398
+ FROM json_each(?)
399
+ )
400
+ SELECT d.id AS documentId, d.mirror_hash AS mirrorHash${includeCollection ? ", d.collection" : ""}, c.seq, c.text, d.title
401
+ FROM req r
402
+ JOIN documents d ON d.id = r.document_id AND d.active = 1
403
+ JOIN content_chunks c ON c.mirror_hash = d.mirror_hash AND c.seq = r.seq
404
+ `)
405
+ .all(JSON.stringify([...uniquePairs.values()]));
406
+ const currentByKey = new Map<
407
+ string,
408
+ VectorOwnerInput & { collection?: string }
409
+ >();
410
+ for (const row of fetchedOwners) {
411
+ currentByKey.set(`${row.documentId}:${row.seq}`, {
412
+ ...this.input(row),
413
+ ...(row.collection !== undefined ? { collection: row.collection } : {}),
414
+ });
415
+ }
416
+ return currentByKey;
417
+ }
418
+
235
419
  private validate(input: VectorOwnerInput): void {
236
420
  const current = this.current(input.documentId, input.seq);
237
421
  if (
@@ -265,144 +449,368 @@ export class VectorVariantStore {
265
449
  ): number[] {
266
450
  this.assertWritable();
267
451
  return this.db
268
- .transaction(() => this.keepingMirrorMark(() => this.writeRows(rows)))
452
+ .transaction(() =>
453
+ this.keepingMirrorMark((mark) => this.writeRows(rows, false, mark))
454
+ )
269
455
  .immediate();
270
456
  }
271
457
 
272
- private writeRows(
458
+ /**
459
+ * Atomic batch that filters to still-current owners inside the same write
460
+ * transaction, avoiding a separate pre-write isCurrent() pass.
461
+ */
462
+ writeCurrent(
273
463
  rows: { owner: VectorOwnerInput; embedding?: Float32Array }[]
274
464
  ): number[] {
275
- return rows.map(({ owner, embedding }) => {
276
- this.validate(owner);
465
+ this.assertWritable();
466
+ return this.db
467
+ .transaction(() =>
468
+ this.keepingMirrorMark((mark) => this.writeRows(rows, true, mark))
469
+ )
470
+ .immediate();
471
+ }
472
+
473
+ private writeRows(
474
+ rows: { owner: VectorOwnerInput; embedding?: Float32Array }[],
475
+ skipStale: boolean,
476
+ markUpdate?: {
477
+ sawNullCosine: boolean;
478
+ nullCosineUnknown: boolean;
479
+ }
480
+ ): number[] {
481
+ if (rows.length === 0) return [];
482
+ for (const { embedding } of rows) {
277
483
  if (
278
484
  embedding &&
279
485
  (embedding.length !== this.identity.dimensions ||
280
486
  !embedding.every(Number.isFinite))
281
- )
487
+ ) {
282
488
  throw new Error("Invalid vector dimensions or values");
283
- let row = this.variant(owner);
284
- if (!row) {
285
- if (!embedding) throw new Error("Exact input variant needs embedding");
286
- this.db.run(
287
- `INSERT INTO vector_variants(partition_id, input_hash, embedding)
288
- VALUES (?, ?, ?)`,
289
- [this.partitionId, owner.inputHash, encodeEmbedding(embedding)]
290
- );
291
- row = this.variant(owner)!;
292
489
  }
293
- if (embedding && row) {
294
- this.db.run(
295
- "UPDATE vector_variants SET embedding = ? WHERE variant_id = ? AND partition_id = ?",
296
- [encodeEmbedding(embedding), row.variant_id, this.partitionId]
297
- );
298
- row = this.variant(owner)!;
490
+ }
491
+
492
+ // Batch-validate all owners in one SQL query instead of N per-row lookups.
493
+ const currentByKey = this.fetchCurrentByKey(rows.map(({ owner }) => owner));
494
+ const validRows: { owner: VectorOwnerInput; embedding?: Float32Array }[] =
495
+ skipStale ? [] : rows;
496
+ for (const row of rows) {
497
+ const { owner } = row;
498
+ const current = currentByKey.get(`${owner.documentId}:${owner.seq}`);
499
+ const matches =
500
+ !!current &&
501
+ current.mirrorHash === owner.mirrorHash &&
502
+ current.formattedInput === owner.formattedInput &&
503
+ current.inputHash === owner.inputHash;
504
+ if (!matches) {
505
+ if (!skipStale) {
506
+ throw new Error("Stale or invalid vector owner input");
507
+ }
508
+ continue;
299
509
  }
300
- if (this.searchAvailable) {
301
- this.db.run(`DELETE FROM ${this.tableName} WHERE variant_id = ?`, [
302
- row.variant_id,
303
- ]);
304
- this.db.run(
305
- `INSERT INTO ${this.tableName}(variant_id, embedding) VALUES (?, ?)`,
306
- [row.variant_id, row.embedding]
307
- );
510
+ if (skipStale) {
511
+ validRows.push(row);
308
512
  }
309
- this.db.run(
310
- `INSERT INTO vector_owners(document_id, mirror_hash, seq, partition_id, variant_id)
311
- VALUES (?, ?, ?, ?, ?) ON CONFLICT(document_id, seq, partition_id) DO UPDATE SET
312
- mirror_hash = excluded.mirror_hash, variant_id = excluded.variant_id`,
313
- [
314
- owner.documentId,
315
- owner.mirrorHash,
316
- owner.seq,
513
+ }
514
+ if (validRows.length === 0) return [];
515
+
516
+ const selectVariant = this.db.query<
517
+ { variant_id: number; embedding: Uint8Array },
518
+ [string, string]
519
+ >(
520
+ "SELECT variant_id, embedding FROM vector_variants WHERE partition_id = ? AND input_hash = ?"
521
+ );
522
+ const insertVariant = this.db.query<
523
+ { variant_id: number },
524
+ [string, string, Uint8Array]
525
+ >(
526
+ "INSERT INTO vector_variants(partition_id, input_hash, embedding) VALUES (?, ?, ?) RETURNING variant_id"
527
+ );
528
+ const updateVariant = this.db.query<unknown, [Uint8Array, number, string]>(
529
+ "UPDATE vector_variants SET embedding = ? WHERE variant_id = ? AND partition_id = ?"
530
+ );
531
+ const deleteVec = this.searchAvailable
532
+ ? this.db.query<unknown, [number]>(
533
+ `DELETE FROM ${this.tableName} WHERE variant_id = ?`
534
+ )
535
+ : null;
536
+ const insertVec = this.searchAvailable
537
+ ? this.db.query<unknown, [number, Uint8Array]>(
538
+ `INSERT INTO ${this.tableName}(variant_id, embedding) VALUES (?, ?)`
539
+ )
540
+ : null;
541
+ const upsertOwner = this.db.query<
542
+ unknown,
543
+ [number, string, number, string, number]
544
+ >(
545
+ `INSERT INTO vector_owners(document_id, mirror_hash, seq, partition_id, variant_id)
546
+ VALUES (?, ?, ?, ?, ?) ON CONFLICT(document_id, seq, partition_id) DO UPDATE SET
547
+ mirror_hash = excluded.mirror_hash, variant_id = excluded.variant_id`
548
+ );
549
+
550
+ const maintainV2 =
551
+ this.searchAvailable &&
552
+ hasV2MirrorTables(this.db) &&
553
+ isV2CompatibleDimensions(this.identity.dimensions) &&
554
+ hasV2Table(this.db, this.partitionId);
555
+ const v2Table = maintainV2 ? v2TableName(this.partitionId) : null;
556
+ const selectV2Row = maintainV2
557
+ ? this.db.query<{ id: number }, [string, string, number]>(
558
+ "SELECT id FROM vector_partition_rows WHERE partition_id = ? AND collection = ? AND variant_id = ?"
559
+ )
560
+ : null;
561
+ const insertV2Map = maintainV2
562
+ ? this.db.query<{ id: number }, [string, string, number]>(
563
+ `INSERT INTO vector_partition_rows(partition_id, collection, variant_id)
564
+ VALUES (?, ?, ?) RETURNING id`
565
+ )
566
+ : null;
567
+ const listV2RowsForVariant = maintainV2
568
+ ? this.db.query<{ id: number }, [string, number]>(
569
+ "SELECT id FROM vector_partition_rows WHERE partition_id = ? AND variant_id = ?"
570
+ )
571
+ : null;
572
+ const deleteV2Vec = v2Table
573
+ ? this.db.query<unknown, [number]>(
574
+ `DELETE FROM "${v2Table}" WHERE rowid = ?`
575
+ )
576
+ : null;
577
+ const insertV2VecFromRow = v2Table
578
+ ? this.db.query<unknown, [number]>(
579
+ `INSERT INTO "${v2Table}"(rowid, collection, coarse)
580
+ SELECT r.id, r.collection, vec_quantize_binary(v.embedding)
581
+ FROM vector_partition_rows r
582
+ JOIN vector_variants v
583
+ ON v.partition_id = r.partition_id AND v.variant_id = r.variant_id
584
+ WHERE r.id = ?`
585
+ )
586
+ : null;
587
+
588
+ const selectPrevOwnerVariant = maintainV2
589
+ ? this.db.query<{ variant_id: number }, [number, number, string]>(
590
+ "SELECT variant_id FROM vector_owners WHERE document_id = ? AND seq = ? AND partition_id = ?"
591
+ )
592
+ : null;
593
+ const reboundV2Candidates: Array<{
594
+ collection: string;
595
+ variantId: number;
596
+ }> = [];
597
+
598
+ const variantIds: number[] = [];
599
+ for (const { owner, embedding } of validRows) {
600
+ const existing = selectVariant.get(this.partitionId, owner.inputHash);
601
+ let variantId: number;
602
+ let updatedExistingEmbedding = false;
603
+ if (!existing) {
604
+ if (!embedding) throw new Error("Exact input variant needs embedding");
605
+ const blob = new Uint8Array(
606
+ embedding.buffer,
607
+ embedding.byteOffset,
608
+ embedding.byteLength
609
+ );
610
+ if (markUpdate) {
611
+ if (this.searchAvailable) {
612
+ if (isNullCosineEmbedding(this.db, blob)) {
613
+ markUpdate.sawNullCosine = true;
614
+ }
615
+ } else {
616
+ markUpdate.nullCosineUnknown = true;
617
+ }
618
+ }
619
+ variantId = insertVariant.get(
317
620
  this.partitionId,
318
- row.variant_id,
319
- ]
621
+ owner.inputHash,
622
+ blob
623
+ )!.variant_id;
624
+ if (insertVec) {
625
+ try {
626
+ insertVec.run(variantId, blob);
627
+ } catch (cause) {
628
+ // A dirty vec0 mirror can retain an orphan row for a reused
629
+ // SQLite rowid after deletion; replace only on collision.
630
+ if (
631
+ deleteVec &&
632
+ cause instanceof Error &&
633
+ cause.message.includes("UNIQUE")
634
+ ) {
635
+ deleteVec.run(variantId);
636
+ insertVec.run(variantId, blob);
637
+ } else {
638
+ throw cause;
639
+ }
640
+ }
641
+ }
642
+ } else if (embedding) {
643
+ variantId = existing.variant_id;
644
+ updatedExistingEmbedding = true;
645
+ const blob = new Uint8Array(
646
+ embedding.buffer,
647
+ embedding.byteOffset,
648
+ embedding.byteLength
649
+ );
650
+ if (markUpdate) {
651
+ if (this.searchAvailable) {
652
+ if (isNullCosineEmbedding(this.db, blob)) {
653
+ markUpdate.sawNullCosine = true;
654
+ }
655
+ } else {
656
+ markUpdate.nullCosineUnknown = true;
657
+ }
658
+ }
659
+ updateVariant.run(blob, variantId, this.partitionId);
660
+ if (deleteVec && insertVec) {
661
+ deleteVec.run(variantId);
662
+ insertVec.run(variantId, blob);
663
+ }
664
+ } else {
665
+ variantId = existing.variant_id;
666
+ if (deleteVec && insertVec) {
667
+ deleteVec.run(variantId);
668
+ insertVec.run(variantId, existing.embedding);
669
+ }
670
+ }
671
+ const ownerCollection = maintainV2
672
+ ? currentByKey.get(`${owner.documentId}:${owner.seq}`)?.collection
673
+ : undefined;
674
+ const prevOwnerVariantId =
675
+ selectPrevOwnerVariant && ownerCollection
676
+ ? selectPrevOwnerVariant.get(
677
+ owner.documentId,
678
+ owner.seq,
679
+ this.partitionId
680
+ )?.variant_id
681
+ : undefined;
682
+ upsertOwner.run(
683
+ owner.documentId,
684
+ owner.mirrorHash,
685
+ owner.seq,
686
+ this.partitionId,
687
+ variantId
320
688
  );
321
- return row.variant_id;
322
- });
689
+ if (
690
+ maintainV2 &&
691
+ selectV2Row &&
692
+ insertV2Map &&
693
+ listV2RowsForVariant &&
694
+ deleteV2Vec &&
695
+ insertV2VecFromRow
696
+ ) {
697
+ if (ownerCollection) {
698
+ if (
699
+ prevOwnerVariantId !== undefined &&
700
+ prevOwnerVariantId !== variantId
701
+ ) {
702
+ reboundV2Candidates.push({
703
+ collection: ownerCollection,
704
+ variantId: prevOwnerVariantId,
705
+ });
706
+ }
707
+ const existingMap = selectV2Row.get(
708
+ this.partitionId,
709
+ ownerCollection,
710
+ variantId
711
+ );
712
+ if (!existingMap) {
713
+ const inserted = insertV2Map.get(
714
+ this.partitionId,
715
+ ownerCollection,
716
+ variantId
717
+ )!;
718
+ deleteV2Vec.run(inserted.id);
719
+ insertV2VecFromRow.run(inserted.id);
720
+ }
721
+ }
722
+ if (updatedExistingEmbedding) {
723
+ for (const row of listV2RowsForVariant.all(
724
+ this.partitionId,
725
+ variantId
726
+ )) {
727
+ deleteV2Vec.run(row.id);
728
+ insertV2VecFromRow.run(row.id);
729
+ }
730
+ }
731
+ }
732
+ variantIds.push(variantId);
733
+ }
734
+ if (reboundV2Candidates.length > 0) {
735
+ this.pruneV2CollectionMappings(reboundV2Candidates);
736
+ }
737
+ return variantIds;
323
738
  }
324
739
 
325
740
  /** Resolve only correct current active owners, never every document sharing a mirror. */
326
741
  owners(variantId: number): VectorOwnerInput[] {
327
742
  const variant = this.db
328
- .query<VariantRow, [string, number]>(`
329
- SELECT variant_id, input_hash, embedding FROM vector_variants
330
- WHERE partition_id = ? AND variant_id = ?
331
- `)
743
+ .query<{ input_hash: string }, [string, number]>(
744
+ "SELECT input_hash FROM vector_variants WHERE partition_id = ? AND variant_id = ?"
745
+ )
332
746
  .get(this.partitionId, variantId);
333
747
  if (!variant) return [];
334
748
  const rows = this.db
335
- .query<
336
- { document_id: number; seq: number; mirror_hash: string },
337
- [string, number]
338
- >(`
339
- SELECT document_id, seq, mirror_hash FROM vector_owners WHERE partition_id = ? AND variant_id = ?
340
- `)
749
+ .query<OwnerRow, [string, number]>(`
750
+ SELECT d.id AS documentId, d.mirror_hash AS mirrorHash, c.seq, c.text, d.title
751
+ FROM vector_owners o
752
+ JOIN documents d ON d.id = o.document_id AND d.active = 1
753
+ AND d.mirror_hash = o.mirror_hash
754
+ JOIN content_chunks c ON c.mirror_hash = o.mirror_hash AND c.seq = o.seq
755
+ WHERE o.partition_id = ? AND o.variant_id = ?
756
+ `)
341
757
  .all(this.partitionId, variantId);
342
- return rows.flatMap((row) => {
343
- const current = this.current(row.document_id, row.seq);
344
- return current &&
345
- current.mirrorHash === row.mirror_hash &&
346
- current.inputHash === variant.input_hash
347
- ? [current]
348
- : [];
349
- });
758
+ const matched: VectorOwnerInput[] = [];
759
+ for (const row of rows) {
760
+ const current = this.input(row);
761
+ if (current.inputHash === variant.input_hash) {
762
+ matched.push(current);
763
+ }
764
+ }
765
+ return matched;
350
766
  }
351
767
 
352
768
  /**
353
769
  * Active chunk rows with this partition's binding, optionally limited to
354
770
  * one collection, as columns `documentId, mirrorHash, title, seq, text,
355
- * boundMirror, boundHash` that `columns` and `where` refer to. The
356
- * collection predicate is added only when requested: activation and
357
- * unscoped passes need the whole index, and some callers' schemas have no
358
- * collection column.
771
+ * boundHash` that `columns` and `where` refer to. The collection predicate
772
+ * is added only when requested: activation and unscoped passes need the
773
+ * whole index, and some callers' schemas have no collection column.
359
774
  */
360
775
  private candidates(
361
776
  collection: string | undefined,
362
777
  columns: string,
363
778
  where = ""
364
779
  ): { sql: string; params: (string | number)[] } {
365
- const owner = `FROM vector_owners o
366
- WHERE o.document_id = d.id AND o.seq = c.seq AND o.partition_id = ?`;
367
780
  return {
368
- // CROSS JOIN keeps documents as the outer loop and the index hint
369
- // makes a scoped scan start from the collection index, even when
370
- // statistics favour walking content_chunks or scanning documents; the
371
- // chunk hint keeps each document's chunks a key lookup by mirror.
372
- // Each binding column is a correlated subquery on the full owner key,
373
- // so it is only primary-key lookups for the scoped chunks (a few per
374
- // chunk, never a pass over other bindings). As a LEFT JOIN, statistics
375
- // gathered while vector_owners was nearly empty made SQLite scan it, or
376
- // build a Bloom filter over every owner, for a small collection.
781
+ // CROSS JOIN keeps documents as the outer loop and the index hints keep
782
+ // every join a key/covering-index lookup even with stale statistics.
783
+ // A single correlated subquery joining vector_owners and vector_variants
784
+ // checks mirror_hash in the covering index and prevents SQLite from
785
+ // building a whole-table Bloom filter on LEFT JOIN under stale stats.
377
786
  sql: `SELECT ${columns} FROM (
378
787
  SELECT d.id AS documentId, d.mirror_hash AS mirrorHash, d.title AS title,
379
788
  c.seq AS seq, c.text AS text,
380
- (SELECT o.mirror_hash ${owner}) AS boundMirror,
381
- (SELECT v.input_hash FROM vector_variants v
382
- WHERE v.partition_id = ? AND v.variant_id = (SELECT o.variant_id ${owner})
789
+ (SELECT v.input_hash
790
+ FROM vector_owners o${ownerDocOrPkHint(this.db)}
791
+ CROSS JOIN vector_variants v${variantPartitionIdHint(this.db)}
792
+ ON v.partition_id = o.partition_id AND v.variant_id = o.variant_id
793
+ WHERE o.document_id = d.id AND o.seq = c.seq
794
+ AND o.partition_id = ? AND o.mirror_hash = d.mirror_hash
383
795
  ) AS boundHash
384
796
  FROM documents d${collectionScanHint(this.db, collection)}
385
797
  CROSS JOIN content_chunks c${chunkKeyHint(this.db)} ON c.mirror_hash = d.mirror_hash
386
798
  WHERE d.active = 1${collection ? " AND d.collection = ?" : ""}
387
799
  ) WHERE 1${where}`,
388
- params: [
389
- this.partitionId,
390
- this.partitionId,
391
- this.partitionId,
392
- ...(collection ? [collection] : []),
393
- ],
800
+ params: [this.partitionId, ...(collection ? [collection] : [])],
394
801
  };
395
802
  }
396
803
 
397
804
  /** Rows with no current binding: pending without formatting or hashing. */
398
- private static readonly UNBOUND =
399
- " AND (boundHash IS NULL OR boundMirror IS NOT mirrorHash)";
805
+ private static readonly UNBOUND = " AND boundHash IS NULL";
400
806
  /** Rows whose binding matches the mirror: only the input hash can differ. */
401
- private static readonly BOUND =
402
- " AND boundHash IS NOT NULL AND boundMirror IS mirrorHash";
807
+ private static readonly BOUND = " AND boundHash IS NOT NULL";
403
808
 
404
809
  /** Bound rows whose current input no longer matches their variant (title or format change). */
405
- private *staleBound(collection: string | undefined): Generator<true> {
810
+ private *staleBound(
811
+ collection: string | undefined,
812
+ proofs: Map<string, boolean>
813
+ ): Generator<true> {
406
814
  const { sql, params } = this.candidates(
407
815
  collection,
408
816
  "documentId, mirrorHash, seq, text, title, boundHash",
@@ -413,8 +821,21 @@ export class VectorVariantStore {
413
821
  (string | number)[]
414
822
  >(sql);
415
823
  try {
416
- for (const row of statement.iterate(...params))
417
- if (this.input(row).inputHash !== row.boundHash) yield true;
824
+ for (const row of statement.iterate(...params)) {
825
+ const key = vectorProofKey(
826
+ this.identity.model,
827
+ row.documentId,
828
+ row.mirrorHash,
829
+ row.seq,
830
+ row.boundHash
831
+ );
832
+ let valid = proofs.get(key);
833
+ if (valid === undefined) {
834
+ valid = this.input(row).inputHash === row.boundHash;
835
+ proofs.set(key, valid);
836
+ }
837
+ if (!valid) yield true;
838
+ }
418
839
  } finally {
419
840
  // Early exit must not leave a cached Bun statement mid-iteration.
420
841
  statement.finalize();
@@ -428,6 +849,7 @@ export class VectorVariantStore {
428
849
  */
429
850
  countPending(options: { collection?: string } = {}): number {
430
851
  const collection = options.collection || undefined;
852
+ const inOuterTx = this.db.inTransaction;
431
853
  const { sql, params } = this.candidates(
432
854
  collection,
433
855
  "count(*) AS n",
@@ -435,10 +857,11 @@ export class VectorVariantStore {
435
857
  );
436
858
  return this.db
437
859
  .transaction(() => {
860
+ const proofs = provenOwners(this.db, inOuterTx);
438
861
  let count = this.db
439
862
  .query<{ n: number }, (string | number)[]>(sql)
440
863
  .get(...params)!.n;
441
- for (const _ of this.staleBound(collection)) count += 1;
864
+ for (const _ of this.staleBound(collection, proofs)) count += 1;
442
865
  return count;
443
866
  })
444
867
  .deferred();
@@ -455,8 +878,7 @@ export class VectorVariantStore {
455
878
  collection: string | undefined,
456
879
  after: { documentId: number; seq: number } | undefined
457
880
  ): Generator<CandidateRow> {
458
- const columns =
459
- "documentId, mirrorHash, seq, text, title, boundHash, boundMirror";
881
+ const columns = "documentId, mirrorHash, seq, text, title, boundHash";
460
882
  const parts = after
461
883
  ? [
462
884
  {
@@ -491,10 +913,24 @@ export class VectorVariantStore {
491
913
  }
492
914
 
493
915
  /** The row needs embedding: no current binding, or its input changed. */
494
- private isPending(row: CandidateRow, input?: VectorOwnerInput): boolean {
495
- if (row.boundHash === null || row.boundMirror !== row.mirrorHash)
496
- return true;
497
- return (input ?? this.input(row)).inputHash !== row.boundHash;
916
+ private isPending(
917
+ row: CandidateRow,
918
+ proofs?: Map<string, boolean>,
919
+ input?: VectorOwnerInput
920
+ ): boolean {
921
+ if (row.boundHash === null) return true;
922
+ const key = vectorProofKey(
923
+ this.identity.model,
924
+ row.documentId,
925
+ row.mirrorHash,
926
+ row.seq,
927
+ row.boundHash
928
+ );
929
+ const cached = proofs?.get(key);
930
+ if (cached !== undefined) return !cached;
931
+ const valid = (input ?? this.input(row)).inputHash === row.boundHash;
932
+ proofs?.set(key, valid);
933
+ return !valid;
498
934
  }
499
935
 
500
936
  /**
@@ -502,12 +938,14 @@ export class VectorVariantStore {
502
938
  * and stops at the first pending one; unbound rows are not hashed.
503
939
  */
504
940
  hasPending(options: { collection?: string } = {}): boolean {
941
+ const inOuterTx = this.db.inTransaction;
505
942
  return this.snapshot(() => {
943
+ const proofs = provenOwners(this.db, inOuterTx);
506
944
  for (const row of this.ownerRows(
507
945
  options.collection || undefined,
508
946
  undefined
509
947
  ))
510
- if (this.isPending(row)) return true;
948
+ if (this.isPending(row, proofs)) return true;
511
949
  return false;
512
950
  });
513
951
  }
@@ -524,14 +962,26 @@ export class VectorVariantStore {
524
962
  const limit = options.limit ?? 1000;
525
963
  if (!Number.isSafeInteger(limit) || limit < 1)
526
964
  throw new Error("Invalid pending limit");
965
+ const inOuterTx = this.db.inTransaction;
527
966
  return this.snapshot(() => {
967
+ const proofs = provenOwners(this.db, inOuterTx);
528
968
  const pending: VectorOwnerInput[] = [];
529
969
  for (const row of this.ownerRows(
530
970
  options.collection || undefined,
531
971
  options.after
532
972
  )) {
973
+ if (row.boundHash !== null) {
974
+ const key = vectorProofKey(
975
+ this.identity.model,
976
+ row.documentId,
977
+ row.mirrorHash,
978
+ row.seq,
979
+ row.boundHash
980
+ );
981
+ if (proofs.get(key) === true) continue;
982
+ }
533
983
  const input = this.input(row);
534
- if (this.isPending(row, input)) pending.push(input);
984
+ if (this.isPending(row, proofs, input)) pending.push(input);
535
985
  if (pending.length === limit) break;
536
986
  }
537
987
  return pending;
@@ -585,7 +1035,20 @@ export class VectorVariantStore {
585
1035
  .get(this.partitionId)!.count;
586
1036
  if (mismatch || orphans) throw new Error("Variant index inconsistent");
587
1037
  // The mirror was just verified against every stored variant.
588
- this.setMirrorMark(0);
1038
+ const nullCosine: 0 | 1 = probePartitionNullCosine(
1039
+ this.db,
1040
+ this.partitionId
1041
+ )
1042
+ ? 1
1043
+ : 0;
1044
+ this.setMirrorMark(0, nullCosine);
1045
+ // Build/sync the v2 bit coarse mirror alongside activation when supported;
1046
+ // unsupported dimensions or pre-v39 schemas are no-ops and never block activation.
1047
+ syncV2PartitionMirrorInTx(
1048
+ this.db,
1049
+ this.partitionId,
1050
+ this.identity.dimensions
1051
+ );
589
1052
  this.db.run(
590
1053
  `UPDATE vector_partitions SET state = 'active', activated_epoch = ? WHERE partition_id = ?`,
591
1054
  [expectedEpoch, this.partitionId]
@@ -635,37 +1098,99 @@ export class VectorVariantStore {
635
1098
  .get("vector_mirror_state");
636
1099
  }
637
1100
 
638
- /** The partition's mark: 0 clean; 1 or null (no row) dirty. */
639
- private mirrorMark(): number | null {
640
- return (
641
- this.db
642
- .query<{ dirty: number }, [string]>(
643
- "SELECT dirty FROM vector_mirror_state WHERE partition_id = ?"
1101
+ /** The partition's mark: dirty (0 clean; 1 or null dirty) and persisted null_cosine flag. */
1102
+ private mirrorStateMark(): {
1103
+ dirty: number | null;
1104
+ nullCosine: NullCosineMark;
1105
+ } {
1106
+ if (hasNullCosineColumn(this.db)) {
1107
+ const row = this.db
1108
+ .query<{ dirty: number; null_cosine: number | null }, [string]>(
1109
+ "SELECT dirty, null_cosine FROM vector_mirror_state WHERE partition_id = ?"
644
1110
  )
645
- .get(this.partitionId)?.dirty ?? null
646
- );
1111
+ .get(this.partitionId);
1112
+ if (!row) return { dirty: null, nullCosine: null };
1113
+ const nullCosine: NullCosineMark =
1114
+ row.null_cosine === 0 ? 0 : row.null_cosine === 1 ? 1 : null;
1115
+ return { dirty: row.dirty, nullCosine };
1116
+ }
1117
+ const row = this.db
1118
+ .query<{ dirty: number }, [string]>(
1119
+ "SELECT dirty FROM vector_mirror_state WHERE partition_id = ?"
1120
+ )
1121
+ .get(this.partitionId);
1122
+ return { dirty: row?.dirty ?? null, nullCosine: null };
647
1123
  }
648
1124
 
649
- private setMirrorMark(mark: number | null): void {
1125
+ private setMirrorMark(
1126
+ mark: number | null,
1127
+ nullCosine: NullCosineMark = null
1128
+ ): void {
650
1129
  if (!this.mirrorTracked()) return;
651
1130
  if (mark !== 0)
652
1131
  this.db.run("DELETE FROM vector_mirror_state WHERE partition_id = ?", [
653
1132
  this.partitionId,
654
1133
  ]);
655
- else markMirrorClean(this.db, this.partitionId);
1134
+ else markMirrorClean(this.db, this.partitionId, nullCosine);
656
1135
  }
657
1136
 
658
1137
  /**
659
1138
  * Runs a store write that keeps vec0 in step. The vector_variants triggers
660
1139
  * mark the partition dirty on every change; when this write also updated
661
- * vec0, the mark it found is restored, so only changes made outside the
662
- * store leave the mirror marked stale.
1140
+ * vec0, the mark it found is restored (updating `null_cosine` from exact
1141
+ * SQL checks on written embeddings or clearing `1 -> NULL` after deletions),
1142
+ * so only changes made outside the store leave the mirror marked stale.
663
1143
  */
664
- private keepingMirrorMark<T>(write: () => T): T {
665
- if (!this.searchAvailable || !this.mirrorTracked()) return write();
666
- const before = this.mirrorMark();
667
- const result = write();
668
- this.setMirrorMark(before);
1144
+ private keepingMirrorMark<T>(
1145
+ write: (mark: {
1146
+ sawNullCosine: boolean;
1147
+ nullCosineUnknown: boolean;
1148
+ removedVariants: boolean;
1149
+ }) => T
1150
+ ): T {
1151
+ const mark = {
1152
+ sawNullCosine: false,
1153
+ nullCosineUnknown: false,
1154
+ removedVariants: false,
1155
+ };
1156
+ if (!this.searchAvailable || !this.mirrorTracked()) return write(mark);
1157
+ const before = this.mirrorStateMark();
1158
+ const trackV2 =
1159
+ hasV2MirrorTables(this.db) &&
1160
+ isV2CompatibleDimensions(this.identity.dimensions) &&
1161
+ hasV2Table(this.db, this.partitionId);
1162
+ const beforeV2 = trackV2
1163
+ ? readV2MirrorState(this.db, this.partitionId)
1164
+ : null;
1165
+ const result = write(mark);
1166
+ if (before.dirty !== 0) {
1167
+ this.setMirrorMark(before.dirty);
1168
+ } else {
1169
+ let nextNullCosine: NullCosineMark;
1170
+ if (mark.sawNullCosine) {
1171
+ nextNullCosine = 1;
1172
+ } else if (mark.nullCosineUnknown) {
1173
+ nextNullCosine = null;
1174
+ } else if (mark.removedVariants && before.nullCosine === 1) {
1175
+ nextNullCosine = null;
1176
+ } else {
1177
+ nextNullCosine = before.nullCosine;
1178
+ }
1179
+ this.setMirrorMark(0, nextNullCosine);
1180
+ }
1181
+ if (trackV2 && beforeV2?.dirty === 0) {
1182
+ const preservedCheck =
1183
+ beforeV2.checkRecall !== null &&
1184
+ beforeV2.checkQueries !== null &&
1185
+ beforeV2.checkCoarseK !== null
1186
+ ? {
1187
+ recall: beforeV2.checkRecall,
1188
+ queries: beforeV2.checkQueries,
1189
+ coarseK: beforeV2.checkCoarseK,
1190
+ }
1191
+ : null;
1192
+ markV2MirrorClean(this.db, this.partitionId, preservedCheck);
1193
+ }
669
1194
  return result;
670
1195
  }
671
1196
 
@@ -681,7 +1206,7 @@ export class VectorVariantStore {
681
1206
  // there directly are caught by comparing row counts (one count each).
682
1207
  // The mark and both counts are read in one snapshot.
683
1208
  return this.snapshot(() => {
684
- if (this.mirrorMark() !== 0) return "dirty";
1209
+ if (this.mirrorStateMark().dirty !== 0) return "dirty";
685
1210
  const stored = this.db
686
1211
  .query<{ n: number }, [string]>(
687
1212
  "SELECT count(*) AS n FROM vector_variants WHERE partition_id = ?"
@@ -694,24 +1219,82 @@ export class VectorVariantStore {
694
1219
  });
695
1220
  }
696
1221
 
1222
+ /**
1223
+ * V2 bit coarse mirror freshness alongside `mirrorState()`, so an upgraded
1224
+ * index with a clean `vec_v1` and a missing or dirty `vec_v2` gets its v2
1225
+ * mirror built at the end of the next `gno embed`.
1226
+ */
1227
+ v2MirrorState(): "clean" | "dirty" | "missing" | "unsupported" {
1228
+ if (!this.searchAvailable) return "missing";
1229
+ return this.snapshot(() =>
1230
+ v2MirrorFreshnessState(
1231
+ this.db,
1232
+ this.partitionId,
1233
+ this.identity.dimensions,
1234
+ this.searchAvailable
1235
+ )
1236
+ );
1237
+ }
1238
+
1239
+ /** Sync only the v2 bit coarse mirror and run recall self-check when eligible. */
1240
+ syncV2Index(): void {
1241
+ if (!this.searchAvailable) throw new Error("Variant index unavailable");
1242
+ this.db
1243
+ .transaction(() => {
1244
+ syncV2PartitionMirrorInTx(
1245
+ this.db,
1246
+ this.partitionId,
1247
+ this.identity.dimensions
1248
+ );
1249
+ runV2RecallSelfCheck(this.db, {
1250
+ partitionId: this.partitionId,
1251
+ dimensions: this.identity.dimensions,
1252
+ });
1253
+ })
1254
+ .immediate();
1255
+ }
1256
+
1257
+ /** Run the build-time recall self-check when above budget and unchecked. */
1258
+ ensureV2RecallSelfCheck(): void {
1259
+ if (!this.searchAvailable) return;
1260
+ this.db
1261
+ .transaction(() => {
1262
+ runV2RecallSelfCheck(this.db, {
1263
+ partitionId: this.partitionId,
1264
+ dimensions: this.identity.dimensions,
1265
+ });
1266
+ })
1267
+ .immediate();
1268
+ }
1269
+
697
1270
  /** Repair materialization after storage-only backfill; never changes legacy authority. */
698
1271
  syncIndex(): void {
699
1272
  if (!this.searchAvailable) throw new Error("Variant index unavailable");
700
1273
  this.db
701
1274
  .transaction(() => {
702
1275
  this.db.exec(`DELETE FROM ${this.tableName}`);
703
- const rows = this.db
704
- .query<VariantRow, [string]>(
705
- "SELECT variant_id, input_hash, embedding FROM vector_variants WHERE partition_id = ?"
1276
+ this.db
1277
+ .query(
1278
+ `INSERT INTO ${this.tableName}(variant_id, embedding)
1279
+ SELECT variant_id, embedding FROM vector_variants WHERE partition_id = ?`
706
1280
  )
707
- .iterate(this.partitionId);
708
- for (const row of rows) {
709
- this.db.run(
710
- `INSERT INTO ${this.tableName}(variant_id, embedding) VALUES (?, ?)`,
711
- [row.variant_id, row.embedding]
712
- );
713
- }
714
- this.setMirrorMark(0);
1281
+ .run(this.partitionId);
1282
+ const nullCosine: 0 | 1 = probePartitionNullCosine(
1283
+ this.db,
1284
+ this.partitionId
1285
+ )
1286
+ ? 1
1287
+ : 0;
1288
+ this.setMirrorMark(0, nullCosine);
1289
+ syncV2PartitionMirrorInTx(
1290
+ this.db,
1291
+ this.partitionId,
1292
+ this.identity.dimensions
1293
+ );
1294
+ runV2RecallSelfCheck(this.db, {
1295
+ partitionId: this.partitionId,
1296
+ dimensions: this.identity.dimensions,
1297
+ });
715
1298
  })
716
1299
  .immediate();
717
1300
  }
@@ -721,12 +1304,31 @@ export class VectorVariantStore {
721
1304
  this.assertWritable();
722
1305
  this.db
723
1306
  .transaction(() =>
724
- this.keepingMirrorMark(() => {
725
- this.db.run(
726
- "DELETE FROM vector_owners WHERE document_id = ? AND partition_id = ?",
727
- [documentId, this.partitionId]
728
- );
729
- this.collectGarbage();
1307
+ this.keepingMirrorMark((mark) => {
1308
+ const releasedV2Candidates = hasV2MirrorTables(this.db)
1309
+ ? this.db
1310
+ .query<
1311
+ { collection: string; variantId: number },
1312
+ [number, string]
1313
+ >(
1314
+ `SELECT DISTINCT d.collection, o.variant_id AS variantId
1315
+ FROM vector_owners o
1316
+ JOIN documents d ON d.id = o.document_id
1317
+ WHERE o.document_id = ? AND o.partition_id = ?`
1318
+ )
1319
+ .all(documentId, this.partitionId)
1320
+ : [];
1321
+ this.db
1322
+ .query(
1323
+ "DELETE FROM vector_owners WHERE document_id = ? AND partition_id = ?"
1324
+ )
1325
+ .run(documentId, this.partitionId);
1326
+ if (this.removeUnowned(true) > 0) {
1327
+ mark.removedVariants = true;
1328
+ }
1329
+ if (releasedV2Candidates.length > 0) {
1330
+ this.pruneV2CollectionMappings(releasedV2Candidates);
1331
+ }
730
1332
  })
731
1333
  )
732
1334
  .immediate();
@@ -734,37 +1336,239 @@ export class VectorVariantStore {
734
1336
 
735
1337
  collectGarbage(): number {
736
1338
  this.assertWritable();
1339
+ const inOuterTx = this.db.inTransaction;
737
1340
  return this.db
738
- .transaction(() => this.keepingMirrorMark(() => this.removeUnowned()))
1341
+ .transaction(() =>
1342
+ this.keepingMirrorMark((mark) => {
1343
+ const removed = this.removeUnowned(inOuterTx);
1344
+ if (removed > 0) {
1345
+ mark.removedVariants = true;
1346
+ }
1347
+ this.pruneAllStaleV2CollectionMappings();
1348
+ return removed;
1349
+ })
1350
+ )
739
1351
  .immediate();
740
1352
  }
741
1353
 
742
- private removeUnowned(): number {
743
- {
744
- let removed = 0;
745
- const rows = this.db
746
- .query<{ variant_id: number }, [string]>(
747
- "SELECT variant_id FROM vector_variants WHERE partition_id = ?"
1354
+ /**
1355
+ * Remove targeted `(collection, variant_id)` v2 mirror rows when no remaining
1356
+ * `vector_owners` row in that collection references the variant (e.g. after a
1357
+ * document release or owner rebind while another collection still owns the variant).
1358
+ */
1359
+ private pruneV2CollectionMappings(
1360
+ candidates: Array<{ collection: string; variantId: number }>
1361
+ ): void {
1362
+ if (!hasV2MirrorTables(this.db) || candidates.length === 0) return;
1363
+ const seen = new Set<string>();
1364
+ const hasOwnerInCollection = this.db.query<
1365
+ { ok: number },
1366
+ [string, number, string]
1367
+ >(
1368
+ `SELECT 1 AS ok
1369
+ FROM vector_owners o
1370
+ JOIN documents d ON d.id = o.document_id
1371
+ WHERE o.partition_id = ? AND o.variant_id = ? AND d.collection = ?
1372
+ LIMIT 1`
1373
+ );
1374
+ const selectMappingRow = this.db.query<
1375
+ { id: number },
1376
+ [string, string, number]
1377
+ >(
1378
+ `SELECT id FROM vector_partition_rows
1379
+ WHERE partition_id = ? AND collection = ? AND variant_id = ?`
1380
+ );
1381
+ const staleIds: number[] = [];
1382
+ for (const { collection, variantId } of candidates) {
1383
+ const key = `${collection}\0${variantId}`;
1384
+ if (seen.has(key)) continue;
1385
+ seen.add(key);
1386
+ if (hasOwnerInCollection.get(this.partitionId, variantId, collection)) {
1387
+ continue;
1388
+ }
1389
+ const row = selectMappingRow.get(this.partitionId, collection, variantId);
1390
+ if (row) staleIds.push(row.id);
1391
+ }
1392
+ this.deleteV2MappingRowIds(staleIds);
1393
+ }
1394
+
1395
+ /**
1396
+ * Sweep any `(collection, variant_id)` v2 mirror rows whose variant or
1397
+ * collection-scoped ownership is no longer present in `vector_owners`.
1398
+ */
1399
+ private pruneAllStaleV2CollectionMappings(): void {
1400
+ if (!hasV2MirrorTables(this.db)) return;
1401
+ const staleIds = this.db
1402
+ .query<{ id: number }, [string]>(
1403
+ `SELECT r.id
1404
+ FROM vector_partition_rows r
1405
+ WHERE r.partition_id = ?
1406
+ AND (
1407
+ NOT EXISTS (
1408
+ SELECT 1 FROM vector_variants v
1409
+ WHERE v.partition_id = r.partition_id AND v.variant_id = r.variant_id
1410
+ )
1411
+ OR NOT EXISTS (
1412
+ SELECT 1 FROM vector_owners o
1413
+ JOIN documents d ON d.id = o.document_id
1414
+ WHERE o.partition_id = r.partition_id
1415
+ AND o.variant_id = r.variant_id
1416
+ AND d.collection = r.collection
1417
+ )
1418
+ )`
1419
+ )
1420
+ .all(this.partitionId)
1421
+ .map((r) => r.id);
1422
+ this.deleteV2MappingRowIds(staleIds);
1423
+ }
1424
+
1425
+ private deleteV2MappingRowIds(ids: number[]): void {
1426
+ if (ids.length === 0) return;
1427
+ const idsJson = JSON.stringify(ids);
1428
+ const v2Exists = hasV2Table(this.db, this.partitionId);
1429
+ if (this.searchAvailable && v2Exists) {
1430
+ const v2Tbl = v2TableName(this.partitionId);
1431
+ this.db
1432
+ .query(
1433
+ `DELETE FROM "${v2Tbl}" WHERE rowid IN (SELECT value FROM json_each(?))`
748
1434
  )
749
- .all(this.partitionId);
750
- for (const { variant_id: id } of rows) {
751
- if (this.owners(id).length) continue;
752
- if (this.searchAvailable)
753
- this.db.run(`DELETE FROM ${this.tableName} WHERE variant_id = ?`, [
754
- id,
755
- ]);
756
- this.db.run(
757
- "DELETE FROM vector_owners WHERE partition_id = ? AND variant_id = ?",
758
- [this.partitionId, id]
759
- );
760
- this.db.run(
761
- "DELETE FROM vector_variants WHERE partition_id = ? AND variant_id = ?",
762
- [this.partitionId, id]
1435
+ .run(idsJson);
1436
+ }
1437
+ this.db
1438
+ .query(
1439
+ "DELETE FROM vector_partition_rows WHERE id IN (SELECT value FROM json_each(?))"
1440
+ )
1441
+ .run(idsJson);
1442
+ if (!this.searchAvailable && v2Exists) {
1443
+ this.db.run("DELETE FROM vector_mirror_v2_state WHERE partition_id = ?", [
1444
+ this.partitionId,
1445
+ ]);
1446
+ }
1447
+ }
1448
+
1449
+ private removeUnowned(inOuterTx: boolean): number {
1450
+ // 1. Collect variants with zero active mirror-matching owners in pure SQL
1451
+ // without touching any embedding BLOBs.
1452
+ const noActiveOwners = this.db
1453
+ .query<{ variant_id: number }, [string]>(`
1454
+ SELECT v.variant_id
1455
+ FROM vector_variants v
1456
+ WHERE v.partition_id = ?
1457
+ AND NOT EXISTS (
1458
+ SELECT 1
1459
+ FROM vector_owners o
1460
+ JOIN documents d ON d.id = o.document_id AND d.active = 1
1461
+ AND d.mirror_hash = o.mirror_hash
1462
+ JOIN content_chunks c ON c.mirror_hash = o.mirror_hash AND c.seq = o.seq
1463
+ WHERE o.partition_id = v.partition_id AND o.variant_id = v.variant_id
1464
+ )
1465
+ `)
1466
+ .all(this.partitionId);
1467
+
1468
+ const toRemove: number[] = noActiveOwners.map((row) => row.variant_id);
1469
+
1470
+ // 2. Stream remaining candidates ordered by variant_id (never reading
1471
+ // v.embedding), consulting the epoch-keyed proof cache and short-circuiting
1472
+ // as soon as a variant has one valid owner.
1473
+ const proofs = provenOwners(this.db, inOuterTx);
1474
+ const candidateStmt = this.db.prepare<
1475
+ OwnerRow & { variant_id: number; input_hash: string },
1476
+ [string]
1477
+ >(`
1478
+ SELECT v.variant_id, v.input_hash,
1479
+ d.id AS documentId, d.mirror_hash AS mirrorHash,
1480
+ c.seq, c.text, d.title
1481
+ FROM vector_variants v
1482
+ JOIN vector_owners o${ownerPartitionVariantHint(this.db)}
1483
+ ON o.partition_id = v.partition_id AND o.variant_id = v.variant_id
1484
+ JOIN documents d ON d.id = o.document_id AND d.active = 1
1485
+ AND d.mirror_hash = o.mirror_hash
1486
+ JOIN content_chunks c${chunkKeyHint(this.db)}
1487
+ ON c.mirror_hash = o.mirror_hash AND c.seq = o.seq
1488
+ WHERE v.partition_id = ?
1489
+ ORDER BY v.variant_id
1490
+ `);
1491
+ try {
1492
+ let currentVariantId: number | null = null;
1493
+ let hasValidOwner = false;
1494
+ for (const row of candidateStmt.iterate(this.partitionId)) {
1495
+ if (row.variant_id !== currentVariantId) {
1496
+ if (currentVariantId !== null && !hasValidOwner) {
1497
+ toRemove.push(currentVariantId);
1498
+ }
1499
+ currentVariantId = row.variant_id;
1500
+ hasValidOwner = false;
1501
+ }
1502
+ if (hasValidOwner) continue;
1503
+ const key = vectorProofKey(
1504
+ this.identity.model,
1505
+ row.documentId,
1506
+ row.mirrorHash,
1507
+ row.seq,
1508
+ row.input_hash
763
1509
  );
764
- removed++;
1510
+ let valid = proofs.get(key);
1511
+ if (valid === undefined) {
1512
+ valid = this.input(row).inputHash === row.input_hash;
1513
+ proofs.set(key, valid);
1514
+ }
1515
+ if (valid) {
1516
+ hasValidOwner = true;
1517
+ }
1518
+ }
1519
+ if (currentVariantId !== null && !hasValidOwner) {
1520
+ toRemove.push(currentVariantId);
765
1521
  }
766
- return removed;
1522
+ } finally {
1523
+ candidateStmt.finalize();
1524
+ }
1525
+
1526
+ if (toRemove.length === 0) return 0;
1527
+
1528
+ const removeJson = JSON.stringify(toRemove);
1529
+ if (this.searchAvailable) {
1530
+ this.db
1531
+ .query(
1532
+ `DELETE FROM ${this.tableName} WHERE variant_id IN (SELECT value FROM json_each(?))`
1533
+ )
1534
+ .run(removeJson);
767
1535
  }
1536
+ if (hasV2MirrorTables(this.db)) {
1537
+ const v2RowIds = this.db
1538
+ .query<{ id: number }, [string, string]>(
1539
+ `SELECT id FROM vector_partition_rows
1540
+ WHERE partition_id = ?
1541
+ AND variant_id IN (SELECT value FROM json_each(?))`
1542
+ )
1543
+ .all(this.partitionId, removeJson);
1544
+ if (v2RowIds.length > 0) {
1545
+ const v2IdsJson = JSON.stringify(v2RowIds.map((r) => r.id));
1546
+ if (this.searchAvailable && hasV2Table(this.db, this.partitionId)) {
1547
+ const v2Tbl = v2TableName(this.partitionId);
1548
+ this.db
1549
+ .query(
1550
+ `DELETE FROM "${v2Tbl}" WHERE rowid IN (SELECT value FROM json_each(?))`
1551
+ )
1552
+ .run(v2IdsJson);
1553
+ }
1554
+ this.db
1555
+ .query(
1556
+ "DELETE FROM vector_partition_rows WHERE id IN (SELECT value FROM json_each(?))"
1557
+ )
1558
+ .run(v2IdsJson);
1559
+ }
1560
+ }
1561
+ this.db
1562
+ .query(
1563
+ "DELETE FROM vector_owners WHERE partition_id = ? AND variant_id IN (SELECT value FROM json_each(?))"
1564
+ )
1565
+ .run(this.partitionId, removeJson);
1566
+ this.db
1567
+ .query(
1568
+ "DELETE FROM vector_variants WHERE partition_id = ? AND variant_id IN (SELECT value FROM json_each(?))"
1569
+ )
1570
+ .run(this.partitionId, removeJson);
1571
+ return toRemove.length;
768
1572
  }
769
1573
  }
770
1574