@gmickel/gno 2.16.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/SKILL.md +27 -0
  3. package/assets/skill/cli-reference.md +20 -13
  4. package/browser-extension/artifacts/{gno-browser-clipper-v2.16.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
  5. package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
  6. package/browser-extension/dist/manifest.json +1 -1
  7. package/package.json +1 -1
  8. package/spec/cli.md +42 -2
  9. package/spec/db/schema.sql +53 -1
  10. package/spec/mcp.md +9 -3
  11. package/spec/output-schemas/doctor.schema.json +27 -0
  12. package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
  13. package/spec/output-schemas/search-results.schema.json +14 -0
  14. package/spec/output-schemas/status.schema.json +22 -0
  15. package/src/cli/commands/doctor.ts +101 -29
  16. package/src/cli/commands/links.ts +29 -5
  17. package/src/cli/commands/vec.ts +180 -8
  18. package/src/cli/program.ts +43 -0
  19. package/src/config/types.ts +6 -0
  20. package/src/core/retrieval-trace-session.ts +3 -0
  21. package/src/core/retrieval-trace.ts +9 -0
  22. package/src/core/vector-partition-status.ts +13 -0
  23. package/src/embed/variant-backlog.ts +36 -2
  24. package/src/mcp/tools/links.ts +7 -1
  25. package/src/pipeline/explain.ts +17 -2
  26. package/src/pipeline/hybrid.ts +28 -1
  27. package/src/pipeline/types.ts +7 -0
  28. package/src/pipeline/vsearch.ts +19 -2
  29. package/src/serve/public/globals.built.css +1 -1
  30. package/src/serve/routes/links.ts +7 -1
  31. package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
  32. package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
  33. package/src/store/migrations/index.ts +4 -0
  34. package/src/store/sqlite/adapter.ts +117 -74
  35. package/src/store/vector/coarse-router.ts +312 -0
  36. package/src/store/vector/partition-index.ts +309 -18
  37. package/src/store/vector/proof-cache.ts +132 -26
  38. package/src/store/vector/runtime-compat.ts +6 -0
  39. package/src/store/vector/sqlite-vec.ts +43 -26
  40. package/src/store/vector/stats.ts +8 -0
  41. package/src/store/vector/status.ts +18 -1
  42. package/src/store/vector/types.ts +9 -0
  43. package/src/store/vector/v2-mirror.ts +669 -0
  44. package/src/store/vector/variant-search.ts +434 -20
  45. package/src/store/vector/variants.ts +480 -32
  46. package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +0 -1
@@ -4,9 +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";
7
+ import { isV2CompatibleDimensions, v2TableName } from "./coarse-router";
8
+ import {
9
+ hasNullCosineColumn,
10
+ isNullCosineEmbedding,
11
+ markMirrorClean,
12
+ type NullCosineMark,
13
+ probePartitionNullCosine,
14
+ } from "./partition-index";
8
15
  import { provenOwners, vectorProofKey } from "./proof-cache";
9
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";
10
27
 
11
28
  export const SELECTED_VECTOR_PARTITION_PREFIX = "vector_selected_partition:";
12
29
 
@@ -226,6 +243,18 @@ export class VectorVariantStore {
226
243
  variant_id INTEGER PRIMARY KEY,
227
244
  embedding FLOAT[${identity.dimensions}] distance_metric=cosine
228
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
+ }
229
258
  }
230
259
  }).immediate();
231
260
  }
@@ -351,7 +380,7 @@ export class VectorVariantStore {
351
380
 
352
381
  private fetchCurrentByKey(
353
382
  owners: readonly VectorOwnerInput[]
354
- ): Map<string, VectorOwnerInput> {
383
+ ): Map<string, VectorOwnerInput & { collection?: string }> {
355
384
  const uniquePairs = new Map<string, [number, number]>();
356
385
  for (const owner of owners) {
357
386
  const key = `${owner.documentId}:${owner.seq}`;
@@ -359,23 +388,30 @@ export class VectorVariantStore {
359
388
  uniquePairs.set(key, [owner.documentId, owner.seq]);
360
389
  }
361
390
  }
391
+ const includeCollection = hasV2MirrorTables(this.db);
362
392
  const fetchedOwners = this.db
363
- .query<OwnerRow, [string]>(`
393
+ .query<OwnerRow & { collection?: string }, [string]>(`
364
394
  WITH req AS (
365
395
  SELECT
366
396
  json_extract(value, '$[0]') AS document_id,
367
397
  json_extract(value, '$[1]') AS seq
368
398
  FROM json_each(?)
369
399
  )
370
- SELECT d.id AS documentId, d.mirror_hash AS mirrorHash, c.seq, c.text, d.title
400
+ SELECT d.id AS documentId, d.mirror_hash AS mirrorHash${includeCollection ? ", d.collection" : ""}, c.seq, c.text, d.title
371
401
  FROM req r
372
402
  JOIN documents d ON d.id = r.document_id AND d.active = 1
373
403
  JOIN content_chunks c ON c.mirror_hash = d.mirror_hash AND c.seq = r.seq
374
404
  `)
375
405
  .all(JSON.stringify([...uniquePairs.values()]));
376
- const currentByKey = new Map<string, VectorOwnerInput>();
406
+ const currentByKey = new Map<
407
+ string,
408
+ VectorOwnerInput & { collection?: string }
409
+ >();
377
410
  for (const row of fetchedOwners) {
378
- currentByKey.set(`${row.documentId}:${row.seq}`, this.input(row));
411
+ currentByKey.set(`${row.documentId}:${row.seq}`, {
412
+ ...this.input(row),
413
+ ...(row.collection !== undefined ? { collection: row.collection } : {}),
414
+ });
379
415
  }
380
416
  return currentByKey;
381
417
  }
@@ -414,7 +450,7 @@ export class VectorVariantStore {
414
450
  this.assertWritable();
415
451
  return this.db
416
452
  .transaction(() =>
417
- this.keepingMirrorMark(() => this.writeRows(rows, false))
453
+ this.keepingMirrorMark((mark) => this.writeRows(rows, false, mark))
418
454
  )
419
455
  .immediate();
420
456
  }
@@ -429,14 +465,18 @@ export class VectorVariantStore {
429
465
  this.assertWritable();
430
466
  return this.db
431
467
  .transaction(() =>
432
- this.keepingMirrorMark(() => this.writeRows(rows, true))
468
+ this.keepingMirrorMark((mark) => this.writeRows(rows, true, mark))
433
469
  )
434
470
  .immediate();
435
471
  }
436
472
 
437
473
  private writeRows(
438
474
  rows: { owner: VectorOwnerInput; embedding?: Float32Array }[],
439
- skipStale: boolean
475
+ skipStale: boolean,
476
+ markUpdate?: {
477
+ sawNullCosine: boolean;
478
+ nullCosineUnknown: boolean;
479
+ }
440
480
  ): number[] {
441
481
  if (rows.length === 0) return [];
442
482
  for (const { embedding } of rows) {
@@ -507,10 +547,59 @@ export class VectorVariantStore {
507
547
  mirror_hash = excluded.mirror_hash, variant_id = excluded.variant_id`
508
548
  );
509
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
+
510
598
  const variantIds: number[] = [];
511
599
  for (const { owner, embedding } of validRows) {
512
600
  const existing = selectVariant.get(this.partitionId, owner.inputHash);
513
601
  let variantId: number;
602
+ let updatedExistingEmbedding = false;
514
603
  if (!existing) {
515
604
  if (!embedding) throw new Error("Exact input variant needs embedding");
516
605
  const blob = new Uint8Array(
@@ -518,6 +607,15 @@ export class VectorVariantStore {
518
607
  embedding.byteOffset,
519
608
  embedding.byteLength
520
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
+ }
521
619
  variantId = insertVariant.get(
522
620
  this.partitionId,
523
621
  owner.inputHash,
@@ -543,11 +641,21 @@ export class VectorVariantStore {
543
641
  }
544
642
  } else if (embedding) {
545
643
  variantId = existing.variant_id;
644
+ updatedExistingEmbedding = true;
546
645
  const blob = new Uint8Array(
547
646
  embedding.buffer,
548
647
  embedding.byteOffset,
549
648
  embedding.byteLength
550
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
+ }
551
659
  updateVariant.run(blob, variantId, this.partitionId);
552
660
  if (deleteVec && insertVec) {
553
661
  deleteVec.run(variantId);
@@ -560,6 +668,17 @@ export class VectorVariantStore {
560
668
  insertVec.run(variantId, existing.embedding);
561
669
  }
562
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;
563
682
  upsertOwner.run(
564
683
  owner.documentId,
565
684
  owner.mirrorHash,
@@ -567,8 +686,54 @@ export class VectorVariantStore {
567
686
  this.partitionId,
568
687
  variantId
569
688
  );
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
+ }
570
732
  variantIds.push(variantId);
571
733
  }
734
+ if (reboundV2Candidates.length > 0) {
735
+ this.pruneV2CollectionMappings(reboundV2Candidates);
736
+ }
572
737
  return variantIds;
573
738
  }
574
739
 
@@ -870,7 +1035,20 @@ export class VectorVariantStore {
870
1035
  .get(this.partitionId)!.count;
871
1036
  if (mismatch || orphans) throw new Error("Variant index inconsistent");
872
1037
  // The mirror was just verified against every stored variant.
873
- 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
+ );
874
1052
  this.db.run(
875
1053
  `UPDATE vector_partitions SET state = 'active', activated_epoch = ? WHERE partition_id = ?`,
876
1054
  [expectedEpoch, this.partitionId]
@@ -920,37 +1098,99 @@ export class VectorVariantStore {
920
1098
  .get("vector_mirror_state");
921
1099
  }
922
1100
 
923
- /** The partition's mark: 0 clean; 1 or null (no row) dirty. */
924
- private mirrorMark(): number | null {
925
- return (
926
- this.db
927
- .query<{ dirty: number }, [string]>(
928
- "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 = ?"
929
1110
  )
930
- .get(this.partitionId)?.dirty ?? null
931
- );
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 };
932
1123
  }
933
1124
 
934
- private setMirrorMark(mark: number | null): void {
1125
+ private setMirrorMark(
1126
+ mark: number | null,
1127
+ nullCosine: NullCosineMark = null
1128
+ ): void {
935
1129
  if (!this.mirrorTracked()) return;
936
1130
  if (mark !== 0)
937
1131
  this.db.run("DELETE FROM vector_mirror_state WHERE partition_id = ?", [
938
1132
  this.partitionId,
939
1133
  ]);
940
- else markMirrorClean(this.db, this.partitionId);
1134
+ else markMirrorClean(this.db, this.partitionId, nullCosine);
941
1135
  }
942
1136
 
943
1137
  /**
944
1138
  * Runs a store write that keeps vec0 in step. The vector_variants triggers
945
1139
  * mark the partition dirty on every change; when this write also updated
946
- * vec0, the mark it found is restored, so only changes made outside the
947
- * 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.
948
1143
  */
949
- private keepingMirrorMark<T>(write: () => T): T {
950
- if (!this.searchAvailable || !this.mirrorTracked()) return write();
951
- const before = this.mirrorMark();
952
- const result = write();
953
- 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
+ }
954
1194
  return result;
955
1195
  }
956
1196
 
@@ -966,7 +1206,7 @@ export class VectorVariantStore {
966
1206
  // there directly are caught by comparing row counts (one count each).
967
1207
  // The mark and both counts are read in one snapshot.
968
1208
  return this.snapshot(() => {
969
- if (this.mirrorMark() !== 0) return "dirty";
1209
+ if (this.mirrorStateMark().dirty !== 0) return "dirty";
970
1210
  const stored = this.db
971
1211
  .query<{ n: number }, [string]>(
972
1212
  "SELECT count(*) AS n FROM vector_variants WHERE partition_id = ?"
@@ -979,6 +1219,54 @@ export class VectorVariantStore {
979
1219
  });
980
1220
  }
981
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
+
982
1270
  /** Repair materialization after storage-only backfill; never changes legacy authority. */
983
1271
  syncIndex(): void {
984
1272
  if (!this.searchAvailable) throw new Error("Variant index unavailable");
@@ -991,7 +1279,22 @@ export class VectorVariantStore {
991
1279
  SELECT variant_id, embedding FROM vector_variants WHERE partition_id = ?`
992
1280
  )
993
1281
  .run(this.partitionId);
994
- this.setMirrorMark(0);
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
+ });
995
1298
  })
996
1299
  .immediate();
997
1300
  }
@@ -1001,13 +1304,31 @@ export class VectorVariantStore {
1001
1304
  this.assertWritable();
1002
1305
  this.db
1003
1306
  .transaction(() =>
1004
- this.keepingMirrorMark(() => {
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
+ : [];
1005
1321
  this.db
1006
1322
  .query(
1007
1323
  "DELETE FROM vector_owners WHERE document_id = ? AND partition_id = ?"
1008
1324
  )
1009
1325
  .run(documentId, this.partitionId);
1010
- this.removeUnowned(true);
1326
+ if (this.removeUnowned(true) > 0) {
1327
+ mark.removedVariants = true;
1328
+ }
1329
+ if (releasedV2Candidates.length > 0) {
1330
+ this.pruneV2CollectionMappings(releasedV2Candidates);
1331
+ }
1011
1332
  })
1012
1333
  )
1013
1334
  .immediate();
@@ -1018,11 +1339,113 @@ export class VectorVariantStore {
1018
1339
  const inOuterTx = this.db.inTransaction;
1019
1340
  return this.db
1020
1341
  .transaction(() =>
1021
- this.keepingMirrorMark(() => this.removeUnowned(inOuterTx))
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
+ })
1022
1350
  )
1023
1351
  .immediate();
1024
1352
  }
1025
1353
 
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(?))`
1434
+ )
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
+
1026
1449
  private removeUnowned(inOuterTx: boolean): number {
1027
1450
  // 1. Collect variants with zero active mirror-matching owners in pure SQL
1028
1451
  // without touching any embedding BLOBs.
@@ -1110,6 +1533,31 @@ export class VectorVariantStore {
1110
1533
  )
1111
1534
  .run(removeJson);
1112
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
+ }
1113
1561
  this.db
1114
1562
  .query(
1115
1563
  "DELETE FROM vector_owners WHERE partition_id = ? AND variant_id IN (SELECT value FROM json_each(?))"
@@ -1 +0,0 @@
1
- 4aacdd5ad2205fdb41b02a4ec771b875b7fc73c771a74c4342925636b18c8729 gno-browser-clipper-v2.16.0.zip