@gmickel/gno 2.14.0 → 2.16.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.
- package/README.md +1 -1
- package/assets/skill/cli-reference.md +4 -2
- package/assets/spa-production.json.gz +0 -0
- package/browser-extension/artifacts/{gno-browser-clipper-v2.14.0.zip → gno-browser-clipper-v2.16.0.zip} +0 -0
- package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +1 -0
- package/browser-extension/dist/manifest.json +1 -1
- package/package.json +1 -1
- package/spec/cli.md +88 -45
- package/spec/db/schema.sql +45 -0
- package/spec/output-schemas/embed-receipt.schema.json +89 -0
- package/src/cli/commands/agents/commands.ts +1 -1
- package/src/cli/commands/ask.ts +1 -1
- package/src/cli/commands/context-build.ts +1 -1
- package/src/cli/commands/embed.ts +341 -20
- package/src/cli/commands/links.ts +1 -1
- package/src/cli/commands/mcp/install.ts +2 -2
- package/src/cli/commands/mcp/status.ts +1 -1
- package/src/cli/commands/mcp/uninstall.ts +1 -1
- package/src/cli/commands/query.ts +1 -1
- package/src/cli/commands/shared.ts +4 -4
- package/src/cli/commands/skill/install.ts +1 -1
- package/src/cli/commands/skill/paths-cmd.ts +1 -1
- package/src/cli/commands/skill/uninstall.ts +1 -1
- package/src/cli/commands/status.ts +75 -58
- package/src/cli/config-cache.ts +86 -0
- package/src/cli/globals.ts +64 -0
- package/src/cli/options.ts +23 -0
- package/src/cli/program.ts +44 -37
- package/src/cli/run.ts +121 -67
- package/src/cli/runtime-health.ts +132 -122
- package/src/cli/session-binding.ts +11 -2
- package/src/config/saver.ts +8 -0
- package/src/converters/adapters/browser-export/formats.ts +25 -15
- package/src/converters/adapters/email/adapter.ts +37 -53
- package/src/converters/adapters/email/html.ts +37 -20
- package/src/converters/adapters/email/mime.ts +71 -39
- package/src/converters/adapters/ical/adapter.ts +20 -12
- package/src/converters/adapters/jsonl/adapter.ts +8 -6
- package/src/converters/adapters/shared/html-text.ts +55 -37
- package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
- package/src/converters/adapters/shared/utf8-lines.ts +69 -31
- package/src/converters/adapters/transcript/adapter.ts +12 -7
- package/src/converters/adapters/xlsx/adapter.ts +10 -7
- package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
- package/src/converters/canonicalize.ts +17 -3
- package/src/converters/native/markdown.ts +24 -17
- package/src/converters/native/plaintext.ts +5 -6
- package/src/converters/registry.ts +130 -8
- package/src/core/activation-status.ts +4 -8
- package/src/core/change-diff.ts +38 -11
- package/src/core/context-compiler.ts +17 -18
- package/src/core/context-evidence.ts +116 -25
- package/src/core/context-verifier.ts +70 -31
- package/src/core/file-lock.ts +10 -2
- package/src/core/graph-analysis.ts +3 -3
- package/src/core/link-inventory-markdown.ts +2 -2
- package/src/core/links.ts +20 -87
- package/src/core/memory-fence.ts +16 -9
- package/src/core/memory-recall.ts +168 -34
- package/src/core/path-rules.ts +143 -0
- package/src/core/section-parse.ts +16 -6
- package/src/core/typed-metadata.ts +68 -0
- package/src/core/wiki-link-syntax.ts +88 -0
- package/src/embed/backlog.ts +173 -60
- package/src/embed/batch.ts +83 -12
- package/src/embed/resume-cursor.ts +103 -0
- package/src/embed/retry.ts +41 -32
- package/src/embed/variant-backlog.ts +697 -63
- package/src/embed/variant-plan.ts +41 -45
- package/src/embed/variant-retry.ts +157 -44
- package/src/index.ts +3 -3
- package/src/ingestion/budget-error-codes.ts +13 -0
- package/src/ingestion/chunker.ts +60 -49
- package/src/ingestion/compiled-context.ts +4 -5
- package/src/ingestion/convert-file.ts +1 -1
- package/src/ingestion/document-metadata.ts +16 -9
- package/src/ingestion/excluded-ranges.ts +97 -0
- package/src/ingestion/file-processor.ts +122 -37
- package/src/ingestion/frontmatter.ts +35 -7
- package/src/ingestion/graph-reconciliation.ts +187 -51
- package/src/ingestion/language.ts +66 -61
- package/src/ingestion/position.ts +5 -5
- package/src/ingestion/prepare-file.ts +50 -29
- package/src/ingestion/record-adapter-canonical.ts +37 -26
- package/src/ingestion/record-adapter.ts +46 -26
- package/src/ingestion/record-container.ts +121 -53
- package/src/ingestion/record-path.ts +5 -2
- package/src/ingestion/source-availability/darwin-io.ts +10 -7
- package/src/ingestion/source-availability/darwin-path.ts +21 -3
- package/src/ingestion/source-availability/readers.ts +51 -0
- package/src/ingestion/strip.ts +39 -105
- package/src/ingestion/sync.ts +692 -386
- package/src/ingestion/typed-metadata.ts +10 -4
- package/src/ingestion/walker.ts +485 -158
- package/src/llm/cache.ts +128 -84
- package/src/llm/http-inference.ts +112 -35
- package/src/llm/http-policy.ts +101 -0
- package/src/llm/httpEmbedding.ts +8 -1
- package/src/llm/httpGeneration.ts +5 -1
- package/src/llm/httpRerank.ts +5 -1
- package/src/llm/inference-scope.ts +15 -2
- package/src/llm/lazy-ports.ts +33 -3
- package/src/llm/lockfile.ts +34 -7
- package/src/llm/model-cleanup.ts +24 -0
- package/src/llm/native-worker/client.ts +23 -12
- package/src/llm/native-worker/dispatcher.ts +19 -9
- package/src/llm/native-worker/embedding-identity.ts +42 -16
- package/src/llm/native-worker/entry.ts +2 -1
- package/src/llm/native-worker/owner.ts +1 -0
- package/src/llm/native-worker/ports.ts +86 -23
- package/src/llm/native-worker/protocol.ts +386 -55
- package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
- package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
- package/src/llm/nodeLlamaCpp/generation.ts +194 -30
- package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
- package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
- package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
- package/src/llm/types.ts +14 -0
- package/src/mcp/context.ts +342 -23
- package/src/mcp/http-transport.ts +21 -3
- package/src/mcp/tool-profile-types.ts +62 -0
- package/src/mcp/tool-profile.ts +32 -56
- package/src/mcp/tools/context.ts +5 -1
- package/src/mcp/tools/index.ts +269 -191
- package/src/mcp/tools/links.ts +7 -5
- package/src/mcp/tools/query.ts +60 -37
- package/src/mcp/tools/vsearch.ts +25 -14
- package/src/pipeline/answer.ts +133 -40
- package/src/pipeline/claim-verification.ts +293 -189
- package/src/pipeline/claim-verifier.ts +6 -7
- package/src/pipeline/egress-lineage.ts +37 -26
- package/src/pipeline/exclude.ts +34 -11
- package/src/pipeline/expansion.ts +233 -19
- package/src/pipeline/filters.ts +169 -33
- package/src/pipeline/graph-retrieval.ts +117 -61
- package/src/pipeline/hybrid.ts +598 -329
- package/src/pipeline/hydration.ts +86 -24
- package/src/pipeline/intent.ts +15 -7
- package/src/pipeline/owner-fusion.ts +61 -19
- package/src/pipeline/query-language.ts +15 -2
- package/src/pipeline/rerank.ts +15 -22
- package/src/pipeline/search.ts +193 -72
- package/src/pipeline/snippet.ts +15 -2
- package/src/pipeline/temporal.ts +51 -10
- package/src/pipeline/vsearch.ts +250 -152
- package/src/publish/attachment-raster.ts +2 -16
- package/src/publish/encrypted-export.ts +15 -5
- package/src/serve/browse-tree.ts +50 -42
- package/src/serve/connectors.ts +2 -1
- package/src/serve/context.ts +13 -4
- package/src/serve/doc-events.ts +3 -0
- package/src/serve/public/app.tsx +49 -21
- package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
- package/src/serve/public/components/CaptureModal.tsx +14 -10
- package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
- package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
- package/src/serve/public/globals.built.css +1 -1
- package/src/serve/public/globals.css +19 -0
- package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
- package/src/serve/public/lib/metadata-filter.ts +234 -9
- package/src/serve/public/pages/Browse.tsx +61 -27
- package/src/serve/public/pages/DocView.tsx +44 -25
- package/src/serve/public/pages/GraphView.tsx +8 -3
- package/src/serve/resident-runtime.ts +199 -48
- package/src/serve/routes/api.ts +98 -67
- package/src/serve/routes/links.ts +18 -4
- package/src/serve/server.ts +1370 -1180
- package/src/serve/spa-bundle-source.ts +52 -27
- package/src/serve/status.ts +101 -52
- package/src/serve/watch-reconciliation-fallback.ts +11 -7
- package/src/serve/watch-reconciliation-shared.ts +42 -4
- package/src/serve/watch-reconciliation.ts +21 -8
- package/src/serve/watch-service-events.ts +7 -1
- package/src/serve/watch-service-hosts.ts +3 -1
- package/src/serve/watch-service.ts +46 -21
- package/src/serve/watch-snapshot-scan.ts +6 -15
- package/src/sessions/archive.ts +20 -8
- package/src/sessions/sanitize.ts +38 -18
- package/src/sessions/service.ts +180 -102
- package/src/store/migrations/036-vector-mirror-state.ts +83 -0
- package/src/store/migrations/037-performance-indexes.ts +56 -0
- package/src/store/migrations/index.ts +4 -0
- package/src/store/sqlite/adapter.ts +1217 -651
- package/src/store/sqlite/chunking-policy.ts +15 -1
- package/src/store/sqlite/eligibility.ts +110 -70
- package/src/store/sqlite/graph-neighbors.ts +71 -46
- package/src/store/sqlite/graph-reference-state.ts +27 -3
- package/src/store/sqlite/graph-similarity.ts +59 -12
- package/src/store/sqlite/metadata-predicate.ts +123 -28
- package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
- package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
- package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
- package/src/store/types.ts +32 -0
- package/src/store/vector/eligibility.ts +39 -0
- package/src/store/vector/lazy.ts +17 -0
- package/src/store/vector/partition-index.ts +49 -47
- package/src/store/vector/proof-cache.ts +103 -0
- package/src/store/vector/sqlite-vec.ts +230 -139
- package/src/store/vector/stats.ts +29 -73
- package/src/store/vector/status.ts +151 -52
- package/src/store/vector/stored-vectors.ts +131 -45
- package/src/store/vector/types.ts +10 -0
- package/src/store/vector/variant-search.ts +771 -109
- package/src/store/vector/variants.ts +785 -144
- package/browser-extension/artifacts/gno-browser-clipper-v2.14.0.zip.sha256 +0 -1
|
@@ -4,10 +4,108 @@ 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 {
|
|
7
|
+
import { markMirrorClean } from "./partition-index";
|
|
8
|
+
import { provenOwners, vectorProofKey } from "./proof-cache";
|
|
9
|
+
import { decodeEmbedding } from "./sqlite-vec";
|
|
8
10
|
|
|
9
11
|
export const SELECTED_VECTOR_PARTITION_PREFIX = "vector_selected_partition:";
|
|
10
12
|
|
|
13
|
+
/**
|
|
14
|
+
* Index hint for collection-scoped scans of `documents`. With statistics
|
|
15
|
+
* from ANALYZE, SQLite can prefer a full scan of documents for a small
|
|
16
|
+
* collection; the collection index keeps the scan proportional to the
|
|
17
|
+
* collection. Empty when unscoped or when the index does not exist.
|
|
18
|
+
*/
|
|
19
|
+
export function collectionScanHint(
|
|
20
|
+
db: Database,
|
|
21
|
+
collection: string | undefined
|
|
22
|
+
): string {
|
|
23
|
+
if (!collection) return "";
|
|
24
|
+
return db
|
|
25
|
+
.query("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?")
|
|
26
|
+
.get("idx_documents_collection")
|
|
27
|
+
? " INDEXED BY idx_documents_collection"
|
|
28
|
+
: "";
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Index hint that makes `content_chunks` a key lookup by mirror. Statistics
|
|
33
|
+
* gathered while the table held a row or two make a scan look cheaper, and
|
|
34
|
+
* the scan then runs once per selected document over every collection's
|
|
35
|
+
* chunks. The primary key index serves both the mirror lookup and the
|
|
36
|
+
* `(mirror_hash, seq)` cursor range.
|
|
37
|
+
*/
|
|
38
|
+
export function chunkKeyHint(db: Database): string {
|
|
39
|
+
const pk = db
|
|
40
|
+
.query<{ name: string }, []>(
|
|
41
|
+
"SELECT name FROM pragma_index_list('content_chunks') WHERE origin = 'pk'"
|
|
42
|
+
)
|
|
43
|
+
.get();
|
|
44
|
+
return pk ? ` INDEXED BY "${pk.name.replaceAll('"', '""')}"` : "";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Covering index hint for document-driven `vector_owners` lookups (migration 037). */
|
|
48
|
+
export function ownerDocPartHint(db: Database): string {
|
|
49
|
+
if (
|
|
50
|
+
db
|
|
51
|
+
.query("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?")
|
|
52
|
+
.get("idx_vector_owners_doc_part")
|
|
53
|
+
) {
|
|
54
|
+
return " INDEXED BY idx_vector_owners_doc_part";
|
|
55
|
+
}
|
|
56
|
+
return "";
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Document-keyed index hint for `vector_owners`: prefers migration 037's
|
|
61
|
+
* covering index, else falls back to the primary key index so stale stats
|
|
62
|
+
* never trigger a table scan or Bloom filter.
|
|
63
|
+
*/
|
|
64
|
+
function ownerDocOrPkHint(db: Database): string {
|
|
65
|
+
const covering = ownerDocPartHint(db);
|
|
66
|
+
if (covering) return covering;
|
|
67
|
+
const pk = db
|
|
68
|
+
.query<{ name: string }, []>(
|
|
69
|
+
"SELECT name FROM pragma_index_list('vector_owners') WHERE origin = 'pk'"
|
|
70
|
+
)
|
|
71
|
+
.get();
|
|
72
|
+
return pk ? ` INDEXED BY "${pk.name.replaceAll('"', '""')}"` : "";
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Covering index hint for partition-driven `vector_owners` scans (migration 037). */
|
|
76
|
+
export function ownerPartitionVariantHint(db: Database): string {
|
|
77
|
+
return db
|
|
78
|
+
.query("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?")
|
|
79
|
+
.get("idx_vector_owners_partition_variant")
|
|
80
|
+
? " INDEXED BY idx_vector_owners_partition_variant"
|
|
81
|
+
: "";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Unique `(partition_id, variant_id)` index hint on `vector_variants`. */
|
|
85
|
+
export function variantPartitionIdHint(db: Database): string {
|
|
86
|
+
const indexes = db
|
|
87
|
+
.query<{ name: string }, []>(
|
|
88
|
+
"SELECT name FROM pragma_index_list('vector_variants')"
|
|
89
|
+
)
|
|
90
|
+
.all();
|
|
91
|
+
for (const { name } of indexes) {
|
|
92
|
+
const cols = db
|
|
93
|
+
.query<{ name: string }, []>(
|
|
94
|
+
`SELECT name FROM pragma_index_info('${name.replaceAll("'", "''")}') ORDER BY seqno`
|
|
95
|
+
)
|
|
96
|
+
.all()
|
|
97
|
+
.map((row) => row.name);
|
|
98
|
+
if (
|
|
99
|
+
cols.length === 2 &&
|
|
100
|
+
cols[0] === "partition_id" &&
|
|
101
|
+
cols[1] === "variant_id"
|
|
102
|
+
) {
|
|
103
|
+
return ` INDEXED BY "${name.replaceAll('"', '""')}"`;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return "";
|
|
107
|
+
}
|
|
108
|
+
|
|
11
109
|
export function embeddingInputHash(input: string): string {
|
|
12
110
|
return new Bun.CryptoHasher("sha256").update(input).digest("hex");
|
|
13
111
|
}
|
|
@@ -54,6 +152,10 @@ interface OwnerRow {
|
|
|
54
152
|
title: string | null;
|
|
55
153
|
}
|
|
56
154
|
|
|
155
|
+
interface CandidateRow extends OwnerRow {
|
|
156
|
+
boundHash: string | null;
|
|
157
|
+
}
|
|
158
|
+
|
|
57
159
|
interface VariantRow {
|
|
58
160
|
variant_id: number;
|
|
59
161
|
input_hash: string;
|
|
@@ -113,10 +215,13 @@ export class VectorVariantStore {
|
|
|
113
215
|
!db
|
|
114
216
|
.query("SELECT 1 FROM sqlite_master WHERE name = ?")
|
|
115
217
|
.get(this.tableName)
|
|
116
|
-
)
|
|
218
|
+
) {
|
|
117
219
|
db.run(
|
|
118
220
|
"UPDATE vector_variant_epoch SET epoch = epoch + 1 WHERE id = 1"
|
|
119
221
|
);
|
|
222
|
+
// A new, empty mirror is stale for any variants already stored.
|
|
223
|
+
this.setMirrorMark(1);
|
|
224
|
+
}
|
|
120
225
|
db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${this.tableName} USING vec0(
|
|
121
226
|
variant_id INTEGER PRIMARY KEY,
|
|
122
227
|
embedding FLOAT[${identity.dimensions}] distance_metric=cosine
|
|
@@ -178,6 +283,61 @@ export class VectorVariantStore {
|
|
|
178
283
|
.get(this.partitionId, input.inputHash);
|
|
179
284
|
}
|
|
180
285
|
|
|
286
|
+
/** BLOB-free existence check for a proven reusable vector. */
|
|
287
|
+
hasReusable(input: VectorOwnerInput): boolean {
|
|
288
|
+
this.validate(input);
|
|
289
|
+
return (
|
|
290
|
+
this.db
|
|
291
|
+
.query<{ ok: number }, [string, string]>(
|
|
292
|
+
"SELECT 1 AS ok FROM vector_variants WHERE partition_id = ? AND input_hash = ? LIMIT 1"
|
|
293
|
+
)
|
|
294
|
+
.get(this.partitionId, input.inputHash) !== null
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Batch-filter current active owners in one SQL query. */
|
|
299
|
+
filterCurrent(owners: readonly VectorOwnerInput[]): VectorOwnerInput[] {
|
|
300
|
+
if (owners.length === 0) return [];
|
|
301
|
+
const currentByKey = this.fetchCurrentByKey(owners);
|
|
302
|
+
const valid: VectorOwnerInput[] = [];
|
|
303
|
+
for (const owner of owners) {
|
|
304
|
+
const current = currentByKey.get(`${owner.documentId}:${owner.seq}`);
|
|
305
|
+
if (
|
|
306
|
+
current &&
|
|
307
|
+
current.mirrorHash === owner.mirrorHash &&
|
|
308
|
+
current.formattedInput === owner.formattedInput &&
|
|
309
|
+
current.inputHash === owner.inputHash
|
|
310
|
+
) {
|
|
311
|
+
valid.push(owner);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return valid;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Batch-validate active owners and check BLOB-free variant reusability in two
|
|
319
|
+
* SQL queries instead of 2N per-owner queries + N BLOB decodes.
|
|
320
|
+
*/
|
|
321
|
+
findReusableHashes(owners: readonly VectorOwnerInput[]): {
|
|
322
|
+
current: VectorOwnerInput[];
|
|
323
|
+
reusableHashes: Set<string>;
|
|
324
|
+
} {
|
|
325
|
+
const current = this.filterCurrent(owners);
|
|
326
|
+
const reusableHashes = new Set<string>();
|
|
327
|
+
if (current.length === 0) return { current, reusableHashes };
|
|
328
|
+
const uniqueHashes = [...new Set(current.map((owner) => owner.inputHash))];
|
|
329
|
+
const rows = this.db
|
|
330
|
+
.query<{ input_hash: string }, [string, string]>(
|
|
331
|
+
`SELECT DISTINCT input_hash FROM vector_variants
|
|
332
|
+
WHERE partition_id = ? AND input_hash IN (SELECT value FROM json_each(?))`
|
|
333
|
+
)
|
|
334
|
+
.all(this.partitionId, JSON.stringify(uniqueHashes));
|
|
335
|
+
for (const row of rows) {
|
|
336
|
+
reusableHashes.add(row.input_hash);
|
|
337
|
+
}
|
|
338
|
+
return { current, reusableHashes };
|
|
339
|
+
}
|
|
340
|
+
|
|
181
341
|
/** Returns a proven reusable vector, even before this owner has a binding. */
|
|
182
342
|
reusable(
|
|
183
343
|
input: VectorOwnerInput
|
|
@@ -189,6 +349,37 @@ export class VectorVariantStore {
|
|
|
189
349
|
: null;
|
|
190
350
|
}
|
|
191
351
|
|
|
352
|
+
private fetchCurrentByKey(
|
|
353
|
+
owners: readonly VectorOwnerInput[]
|
|
354
|
+
): Map<string, VectorOwnerInput> {
|
|
355
|
+
const uniquePairs = new Map<string, [number, number]>();
|
|
356
|
+
for (const owner of owners) {
|
|
357
|
+
const key = `${owner.documentId}:${owner.seq}`;
|
|
358
|
+
if (!uniquePairs.has(key)) {
|
|
359
|
+
uniquePairs.set(key, [owner.documentId, owner.seq]);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
const fetchedOwners = this.db
|
|
363
|
+
.query<OwnerRow, [string]>(`
|
|
364
|
+
WITH req AS (
|
|
365
|
+
SELECT
|
|
366
|
+
json_extract(value, '$[0]') AS document_id,
|
|
367
|
+
json_extract(value, '$[1]') AS seq
|
|
368
|
+
FROM json_each(?)
|
|
369
|
+
)
|
|
370
|
+
SELECT d.id AS documentId, d.mirror_hash AS mirrorHash, c.seq, c.text, d.title
|
|
371
|
+
FROM req r
|
|
372
|
+
JOIN documents d ON d.id = r.document_id AND d.active = 1
|
|
373
|
+
JOIN content_chunks c ON c.mirror_hash = d.mirror_hash AND c.seq = r.seq
|
|
374
|
+
`)
|
|
375
|
+
.all(JSON.stringify([...uniquePairs.values()]));
|
|
376
|
+
const currentByKey = new Map<string, VectorOwnerInput>();
|
|
377
|
+
for (const row of fetchedOwners) {
|
|
378
|
+
currentByKey.set(`${row.documentId}:${row.seq}`, this.input(row));
|
|
379
|
+
}
|
|
380
|
+
return currentByKey;
|
|
381
|
+
}
|
|
382
|
+
|
|
192
383
|
private validate(input: VectorOwnerInput): void {
|
|
193
384
|
const current = this.current(input.documentId, input.seq);
|
|
194
385
|
if (
|
|
@@ -223,83 +414,374 @@ export class VectorVariantStore {
|
|
|
223
414
|
this.assertWritable();
|
|
224
415
|
return this.db
|
|
225
416
|
.transaction(() =>
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
);
|
|
243
|
-
row = this.variant(owner)!;
|
|
244
|
-
}
|
|
245
|
-
if (embedding && row) {
|
|
246
|
-
this.db.run(
|
|
247
|
-
"UPDATE vector_variants SET embedding = ? WHERE variant_id = ? AND partition_id = ?",
|
|
248
|
-
[encodeEmbedding(embedding), row.variant_id, this.partitionId]
|
|
249
|
-
);
|
|
250
|
-
row = this.variant(owner)!;
|
|
251
|
-
}
|
|
252
|
-
if (this.searchAvailable) {
|
|
253
|
-
this.db.run(`DELETE FROM ${this.tableName} WHERE variant_id = ?`, [
|
|
254
|
-
row.variant_id,
|
|
255
|
-
]);
|
|
256
|
-
this.db.run(
|
|
257
|
-
`INSERT INTO ${this.tableName}(variant_id, embedding) VALUES (?, ?)`,
|
|
258
|
-
[row.variant_id, row.embedding]
|
|
259
|
-
);
|
|
260
|
-
}
|
|
261
|
-
this.db.run(
|
|
262
|
-
`INSERT INTO vector_owners(document_id, mirror_hash, seq, partition_id, variant_id)
|
|
263
|
-
VALUES (?, ?, ?, ?, ?) ON CONFLICT(document_id, seq, partition_id) DO UPDATE SET
|
|
264
|
-
mirror_hash = excluded.mirror_hash, variant_id = excluded.variant_id`,
|
|
265
|
-
[
|
|
266
|
-
owner.documentId,
|
|
267
|
-
owner.mirrorHash,
|
|
268
|
-
owner.seq,
|
|
269
|
-
this.partitionId,
|
|
270
|
-
row.variant_id,
|
|
271
|
-
]
|
|
272
|
-
);
|
|
273
|
-
return row.variant_id;
|
|
274
|
-
})
|
|
417
|
+
this.keepingMirrorMark(() => this.writeRows(rows, false))
|
|
418
|
+
)
|
|
419
|
+
.immediate();
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Atomic batch that filters to still-current owners inside the same write
|
|
424
|
+
* transaction, avoiding a separate pre-write isCurrent() pass.
|
|
425
|
+
*/
|
|
426
|
+
writeCurrent(
|
|
427
|
+
rows: { owner: VectorOwnerInput; embedding?: Float32Array }[]
|
|
428
|
+
): number[] {
|
|
429
|
+
this.assertWritable();
|
|
430
|
+
return this.db
|
|
431
|
+
.transaction(() =>
|
|
432
|
+
this.keepingMirrorMark(() => this.writeRows(rows, true))
|
|
275
433
|
)
|
|
276
434
|
.immediate();
|
|
277
435
|
}
|
|
278
436
|
|
|
437
|
+
private writeRows(
|
|
438
|
+
rows: { owner: VectorOwnerInput; embedding?: Float32Array }[],
|
|
439
|
+
skipStale: boolean
|
|
440
|
+
): number[] {
|
|
441
|
+
if (rows.length === 0) return [];
|
|
442
|
+
for (const { embedding } of rows) {
|
|
443
|
+
if (
|
|
444
|
+
embedding &&
|
|
445
|
+
(embedding.length !== this.identity.dimensions ||
|
|
446
|
+
!embedding.every(Number.isFinite))
|
|
447
|
+
) {
|
|
448
|
+
throw new Error("Invalid vector dimensions or values");
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// Batch-validate all owners in one SQL query instead of N per-row lookups.
|
|
453
|
+
const currentByKey = this.fetchCurrentByKey(rows.map(({ owner }) => owner));
|
|
454
|
+
const validRows: { owner: VectorOwnerInput; embedding?: Float32Array }[] =
|
|
455
|
+
skipStale ? [] : rows;
|
|
456
|
+
for (const row of rows) {
|
|
457
|
+
const { owner } = row;
|
|
458
|
+
const current = currentByKey.get(`${owner.documentId}:${owner.seq}`);
|
|
459
|
+
const matches =
|
|
460
|
+
!!current &&
|
|
461
|
+
current.mirrorHash === owner.mirrorHash &&
|
|
462
|
+
current.formattedInput === owner.formattedInput &&
|
|
463
|
+
current.inputHash === owner.inputHash;
|
|
464
|
+
if (!matches) {
|
|
465
|
+
if (!skipStale) {
|
|
466
|
+
throw new Error("Stale or invalid vector owner input");
|
|
467
|
+
}
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
if (skipStale) {
|
|
471
|
+
validRows.push(row);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
if (validRows.length === 0) return [];
|
|
475
|
+
|
|
476
|
+
const selectVariant = this.db.query<
|
|
477
|
+
{ variant_id: number; embedding: Uint8Array },
|
|
478
|
+
[string, string]
|
|
479
|
+
>(
|
|
480
|
+
"SELECT variant_id, embedding FROM vector_variants WHERE partition_id = ? AND input_hash = ?"
|
|
481
|
+
);
|
|
482
|
+
const insertVariant = this.db.query<
|
|
483
|
+
{ variant_id: number },
|
|
484
|
+
[string, string, Uint8Array]
|
|
485
|
+
>(
|
|
486
|
+
"INSERT INTO vector_variants(partition_id, input_hash, embedding) VALUES (?, ?, ?) RETURNING variant_id"
|
|
487
|
+
);
|
|
488
|
+
const updateVariant = this.db.query<unknown, [Uint8Array, number, string]>(
|
|
489
|
+
"UPDATE vector_variants SET embedding = ? WHERE variant_id = ? AND partition_id = ?"
|
|
490
|
+
);
|
|
491
|
+
const deleteVec = this.searchAvailable
|
|
492
|
+
? this.db.query<unknown, [number]>(
|
|
493
|
+
`DELETE FROM ${this.tableName} WHERE variant_id = ?`
|
|
494
|
+
)
|
|
495
|
+
: null;
|
|
496
|
+
const insertVec = this.searchAvailable
|
|
497
|
+
? this.db.query<unknown, [number, Uint8Array]>(
|
|
498
|
+
`INSERT INTO ${this.tableName}(variant_id, embedding) VALUES (?, ?)`
|
|
499
|
+
)
|
|
500
|
+
: null;
|
|
501
|
+
const upsertOwner = this.db.query<
|
|
502
|
+
unknown,
|
|
503
|
+
[number, string, number, string, number]
|
|
504
|
+
>(
|
|
505
|
+
`INSERT INTO vector_owners(document_id, mirror_hash, seq, partition_id, variant_id)
|
|
506
|
+
VALUES (?, ?, ?, ?, ?) ON CONFLICT(document_id, seq, partition_id) DO UPDATE SET
|
|
507
|
+
mirror_hash = excluded.mirror_hash, variant_id = excluded.variant_id`
|
|
508
|
+
);
|
|
509
|
+
|
|
510
|
+
const variantIds: number[] = [];
|
|
511
|
+
for (const { owner, embedding } of validRows) {
|
|
512
|
+
const existing = selectVariant.get(this.partitionId, owner.inputHash);
|
|
513
|
+
let variantId: number;
|
|
514
|
+
if (!existing) {
|
|
515
|
+
if (!embedding) throw new Error("Exact input variant needs embedding");
|
|
516
|
+
const blob = new Uint8Array(
|
|
517
|
+
embedding.buffer,
|
|
518
|
+
embedding.byteOffset,
|
|
519
|
+
embedding.byteLength
|
|
520
|
+
);
|
|
521
|
+
variantId = insertVariant.get(
|
|
522
|
+
this.partitionId,
|
|
523
|
+
owner.inputHash,
|
|
524
|
+
blob
|
|
525
|
+
)!.variant_id;
|
|
526
|
+
if (insertVec) {
|
|
527
|
+
try {
|
|
528
|
+
insertVec.run(variantId, blob);
|
|
529
|
+
} catch (cause) {
|
|
530
|
+
// A dirty vec0 mirror can retain an orphan row for a reused
|
|
531
|
+
// SQLite rowid after deletion; replace only on collision.
|
|
532
|
+
if (
|
|
533
|
+
deleteVec &&
|
|
534
|
+
cause instanceof Error &&
|
|
535
|
+
cause.message.includes("UNIQUE")
|
|
536
|
+
) {
|
|
537
|
+
deleteVec.run(variantId);
|
|
538
|
+
insertVec.run(variantId, blob);
|
|
539
|
+
} else {
|
|
540
|
+
throw cause;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
} else if (embedding) {
|
|
545
|
+
variantId = existing.variant_id;
|
|
546
|
+
const blob = new Uint8Array(
|
|
547
|
+
embedding.buffer,
|
|
548
|
+
embedding.byteOffset,
|
|
549
|
+
embedding.byteLength
|
|
550
|
+
);
|
|
551
|
+
updateVariant.run(blob, variantId, this.partitionId);
|
|
552
|
+
if (deleteVec && insertVec) {
|
|
553
|
+
deleteVec.run(variantId);
|
|
554
|
+
insertVec.run(variantId, blob);
|
|
555
|
+
}
|
|
556
|
+
} else {
|
|
557
|
+
variantId = existing.variant_id;
|
|
558
|
+
if (deleteVec && insertVec) {
|
|
559
|
+
deleteVec.run(variantId);
|
|
560
|
+
insertVec.run(variantId, existing.embedding);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
upsertOwner.run(
|
|
564
|
+
owner.documentId,
|
|
565
|
+
owner.mirrorHash,
|
|
566
|
+
owner.seq,
|
|
567
|
+
this.partitionId,
|
|
568
|
+
variantId
|
|
569
|
+
);
|
|
570
|
+
variantIds.push(variantId);
|
|
571
|
+
}
|
|
572
|
+
return variantIds;
|
|
573
|
+
}
|
|
574
|
+
|
|
279
575
|
/** Resolve only correct current active owners, never every document sharing a mirror. */
|
|
280
576
|
owners(variantId: number): VectorOwnerInput[] {
|
|
281
577
|
const variant = this.db
|
|
282
|
-
.query<
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
`)
|
|
578
|
+
.query<{ input_hash: string }, [string, number]>(
|
|
579
|
+
"SELECT input_hash FROM vector_variants WHERE partition_id = ? AND variant_id = ?"
|
|
580
|
+
)
|
|
286
581
|
.get(this.partitionId, variantId);
|
|
287
582
|
if (!variant) return [];
|
|
288
583
|
const rows = this.db
|
|
289
|
-
.query<
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
584
|
+
.query<OwnerRow, [string, number]>(`
|
|
585
|
+
SELECT d.id AS documentId, d.mirror_hash AS mirrorHash, c.seq, c.text, d.title
|
|
586
|
+
FROM vector_owners o
|
|
587
|
+
JOIN documents d ON d.id = o.document_id AND d.active = 1
|
|
588
|
+
AND d.mirror_hash = o.mirror_hash
|
|
589
|
+
JOIN content_chunks c ON c.mirror_hash = o.mirror_hash AND c.seq = o.seq
|
|
590
|
+
WHERE o.partition_id = ? AND o.variant_id = ?
|
|
591
|
+
`)
|
|
295
592
|
.all(this.partitionId, variantId);
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
current
|
|
301
|
-
|
|
302
|
-
|
|
593
|
+
const matched: VectorOwnerInput[] = [];
|
|
594
|
+
for (const row of rows) {
|
|
595
|
+
const current = this.input(row);
|
|
596
|
+
if (current.inputHash === variant.input_hash) {
|
|
597
|
+
matched.push(current);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
return matched;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* Active chunk rows with this partition's binding, optionally limited to
|
|
605
|
+
* one collection, as columns `documentId, mirrorHash, title, seq, text,
|
|
606
|
+
* boundHash` that `columns` and `where` refer to. The collection predicate
|
|
607
|
+
* is added only when requested: activation and unscoped passes need the
|
|
608
|
+
* whole index, and some callers' schemas have no collection column.
|
|
609
|
+
*/
|
|
610
|
+
private candidates(
|
|
611
|
+
collection: string | undefined,
|
|
612
|
+
columns: string,
|
|
613
|
+
where = ""
|
|
614
|
+
): { sql: string; params: (string | number)[] } {
|
|
615
|
+
return {
|
|
616
|
+
// CROSS JOIN keeps documents as the outer loop and the index hints keep
|
|
617
|
+
// every join a key/covering-index lookup even with stale statistics.
|
|
618
|
+
// A single correlated subquery joining vector_owners and vector_variants
|
|
619
|
+
// checks mirror_hash in the covering index and prevents SQLite from
|
|
620
|
+
// building a whole-table Bloom filter on LEFT JOIN under stale stats.
|
|
621
|
+
sql: `SELECT ${columns} FROM (
|
|
622
|
+
SELECT d.id AS documentId, d.mirror_hash AS mirrorHash, d.title AS title,
|
|
623
|
+
c.seq AS seq, c.text AS text,
|
|
624
|
+
(SELECT v.input_hash
|
|
625
|
+
FROM vector_owners o${ownerDocOrPkHint(this.db)}
|
|
626
|
+
CROSS JOIN vector_variants v${variantPartitionIdHint(this.db)}
|
|
627
|
+
ON v.partition_id = o.partition_id AND v.variant_id = o.variant_id
|
|
628
|
+
WHERE o.document_id = d.id AND o.seq = c.seq
|
|
629
|
+
AND o.partition_id = ? AND o.mirror_hash = d.mirror_hash
|
|
630
|
+
) AS boundHash
|
|
631
|
+
FROM documents d${collectionScanHint(this.db, collection)}
|
|
632
|
+
CROSS JOIN content_chunks c${chunkKeyHint(this.db)} ON c.mirror_hash = d.mirror_hash
|
|
633
|
+
WHERE d.active = 1${collection ? " AND d.collection = ?" : ""}
|
|
634
|
+
) WHERE 1${where}`,
|
|
635
|
+
params: [this.partitionId, ...(collection ? [collection] : [])],
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/** Rows with no current binding: pending without formatting or hashing. */
|
|
640
|
+
private static readonly UNBOUND = " AND boundHash IS NULL";
|
|
641
|
+
/** Rows whose binding matches the mirror: only the input hash can differ. */
|
|
642
|
+
private static readonly BOUND = " AND boundHash IS NOT NULL";
|
|
643
|
+
|
|
644
|
+
/** Bound rows whose current input no longer matches their variant (title or format change). */
|
|
645
|
+
private *staleBound(
|
|
646
|
+
collection: string | undefined,
|
|
647
|
+
proofs: Map<string, boolean>
|
|
648
|
+
): Generator<true> {
|
|
649
|
+
const { sql, params } = this.candidates(
|
|
650
|
+
collection,
|
|
651
|
+
"documentId, mirrorHash, seq, text, title, boundHash",
|
|
652
|
+
VectorVariantStore.BOUND
|
|
653
|
+
);
|
|
654
|
+
const statement = this.db.prepare<
|
|
655
|
+
OwnerRow & { boundHash: string },
|
|
656
|
+
(string | number)[]
|
|
657
|
+
>(sql);
|
|
658
|
+
try {
|
|
659
|
+
for (const row of statement.iterate(...params)) {
|
|
660
|
+
const key = vectorProofKey(
|
|
661
|
+
this.identity.model,
|
|
662
|
+
row.documentId,
|
|
663
|
+
row.mirrorHash,
|
|
664
|
+
row.seq,
|
|
665
|
+
row.boundHash
|
|
666
|
+
);
|
|
667
|
+
let valid = proofs.get(key);
|
|
668
|
+
if (valid === undefined) {
|
|
669
|
+
valid = this.input(row).inputHash === row.boundHash;
|
|
670
|
+
proofs.set(key, valid);
|
|
671
|
+
}
|
|
672
|
+
if (!valid) yield true;
|
|
673
|
+
}
|
|
674
|
+
} finally {
|
|
675
|
+
// Early exit must not leave a cached Bun statement mid-iteration.
|
|
676
|
+
statement.finalize();
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* Number of owners pending() would return across a complete pass. Unbound
|
|
682
|
+
* rows are counted in SQL; only bound rows are formatted and hashed. Both
|
|
683
|
+
* reads share one snapshot so a concurrent writer cannot hide a row.
|
|
684
|
+
*/
|
|
685
|
+
countPending(options: { collection?: string } = {}): number {
|
|
686
|
+
const collection = options.collection || undefined;
|
|
687
|
+
const inOuterTx = this.db.inTransaction;
|
|
688
|
+
const { sql, params } = this.candidates(
|
|
689
|
+
collection,
|
|
690
|
+
"count(*) AS n",
|
|
691
|
+
VectorVariantStore.UNBOUND
|
|
692
|
+
);
|
|
693
|
+
return this.db
|
|
694
|
+
.transaction(() => {
|
|
695
|
+
const proofs = provenOwners(this.db, inOuterTx);
|
|
696
|
+
let count = this.db
|
|
697
|
+
.query<{ n: number }, (string | number)[]>(sql)
|
|
698
|
+
.get(...params)!.n;
|
|
699
|
+
for (const _ of this.staleBound(collection, proofs)) count += 1;
|
|
700
|
+
return count;
|
|
701
|
+
})
|
|
702
|
+
.deferred();
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* Active chunk rows with their binding in `(document id, seq)` order,
|
|
707
|
+
* resuming after `after`. The cursor document's remaining chunks and the
|
|
708
|
+
* later documents are two statements, so each is a range on its index
|
|
709
|
+
* (`content_chunks` primary key, then the collection index or rowid) and a
|
|
710
|
+
* large document is never rescanned from its first chunk.
|
|
711
|
+
*/
|
|
712
|
+
private *ownerRows(
|
|
713
|
+
collection: string | undefined,
|
|
714
|
+
after: { documentId: number; seq: number } | undefined
|
|
715
|
+
): Generator<CandidateRow> {
|
|
716
|
+
const columns = "documentId, mirrorHash, seq, text, title, boundHash";
|
|
717
|
+
const parts = after
|
|
718
|
+
? [
|
|
719
|
+
{
|
|
720
|
+
where: " AND documentId = ? AND seq > ? ORDER BY seq",
|
|
721
|
+
params: [after.documentId, after.seq],
|
|
722
|
+
},
|
|
723
|
+
{
|
|
724
|
+
where: " AND documentId > ? ORDER BY documentId, seq",
|
|
725
|
+
params: [after.documentId],
|
|
726
|
+
},
|
|
727
|
+
]
|
|
728
|
+
: [{ where: " ORDER BY documentId, seq", params: [] as number[] }];
|
|
729
|
+
for (const part of parts) {
|
|
730
|
+
const { sql, params } = this.candidates(collection, columns, part.where);
|
|
731
|
+
const statement = this.db.prepare<CandidateRow, (string | number)[]>(sql);
|
|
732
|
+
try {
|
|
733
|
+
yield* statement.iterate(...params, ...part.params);
|
|
734
|
+
} finally {
|
|
735
|
+
// Early exit must not leave a cached Bun statement mid-iteration.
|
|
736
|
+
statement.finalize();
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
* Runs reads in one deferred transaction: every statement sees the same
|
|
743
|
+
* snapshot, so a write committed between the two cursor statements cannot
|
|
744
|
+
* make a page look like the end of the backlog.
|
|
745
|
+
*/
|
|
746
|
+
private snapshot<T>(read: () => T): T {
|
|
747
|
+
return this.db.transaction(read).deferred();
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** The row needs embedding: no current binding, or its input changed. */
|
|
751
|
+
private isPending(
|
|
752
|
+
row: CandidateRow,
|
|
753
|
+
proofs?: Map<string, boolean>,
|
|
754
|
+
input?: VectorOwnerInput
|
|
755
|
+
): boolean {
|
|
756
|
+
if (row.boundHash === null) return true;
|
|
757
|
+
const key = vectorProofKey(
|
|
758
|
+
this.identity.model,
|
|
759
|
+
row.documentId,
|
|
760
|
+
row.mirrorHash,
|
|
761
|
+
row.seq,
|
|
762
|
+
row.boundHash
|
|
763
|
+
);
|
|
764
|
+
const cached = proofs?.get(key);
|
|
765
|
+
if (cached !== undefined) return !cached;
|
|
766
|
+
const valid = (input ?? this.input(row)).inputHash === row.boundHash;
|
|
767
|
+
proofs?.set(key, valid);
|
|
768
|
+
return !valid;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/**
|
|
772
|
+
* Same answer as `pending({ limit: 1 }).length > 0`. Walks owners in order
|
|
773
|
+
* and stops at the first pending one; unbound rows are not hashed.
|
|
774
|
+
*/
|
|
775
|
+
hasPending(options: { collection?: string } = {}): boolean {
|
|
776
|
+
const inOuterTx = this.db.inTransaction;
|
|
777
|
+
return this.snapshot(() => {
|
|
778
|
+
const proofs = provenOwners(this.db, inOuterTx);
|
|
779
|
+
for (const row of this.ownerRows(
|
|
780
|
+
options.collection || undefined,
|
|
781
|
+
undefined
|
|
782
|
+
))
|
|
783
|
+
if (this.isPending(row, proofs)) return true;
|
|
784
|
+
return false;
|
|
303
785
|
});
|
|
304
786
|
}
|
|
305
787
|
|
|
@@ -308,47 +790,61 @@ export class VectorVariantStore {
|
|
|
308
790
|
options: {
|
|
309
791
|
limit?: number;
|
|
310
792
|
after?: { documentId: number; seq: number };
|
|
793
|
+
/** Only owners of active documents in this collection. */
|
|
794
|
+
collection?: string;
|
|
311
795
|
} = {}
|
|
312
796
|
): VectorOwnerInput[] {
|
|
313
797
|
const limit = options.limit ?? 1000;
|
|
314
798
|
if (!Number.isSafeInteger(limit) || limit < 1)
|
|
315
799
|
throw new Error("Invalid pending limit");
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
800
|
+
const inOuterTx = this.db.inTransaction;
|
|
801
|
+
return this.snapshot(() => {
|
|
802
|
+
const proofs = provenOwners(this.db, inOuterTx);
|
|
803
|
+
const pending: VectorOwnerInput[] = [];
|
|
804
|
+
for (const row of this.ownerRows(
|
|
805
|
+
options.collection || undefined,
|
|
806
|
+
options.after
|
|
807
|
+
)) {
|
|
808
|
+
if (row.boundHash !== null) {
|
|
809
|
+
const key = vectorProofKey(
|
|
810
|
+
this.identity.model,
|
|
811
|
+
row.documentId,
|
|
812
|
+
row.mirrorHash,
|
|
813
|
+
row.seq,
|
|
814
|
+
row.boundHash
|
|
815
|
+
);
|
|
816
|
+
if (proofs.get(key) === true) continue;
|
|
817
|
+
}
|
|
329
818
|
const input = this.input(row);
|
|
330
|
-
|
|
331
|
-
.query<
|
|
332
|
-
{ input_hash: string; mirror_hash: string },
|
|
333
|
-
[number, number, string]
|
|
334
|
-
>(`
|
|
335
|
-
SELECT v.input_hash, o.mirror_hash FROM vector_owners o
|
|
336
|
-
JOIN vector_variants v ON v.variant_id = o.variant_id AND v.partition_id = o.partition_id
|
|
337
|
-
WHERE o.document_id = ? AND o.seq = ? AND o.partition_id = ?
|
|
338
|
-
`)
|
|
339
|
-
.get(input.documentId, input.seq, this.partitionId);
|
|
340
|
-
if (
|
|
341
|
-
binding?.input_hash !== input.inputHash ||
|
|
342
|
-
binding.mirror_hash !== input.mirrorHash
|
|
343
|
-
)
|
|
344
|
-
pending.push(input);
|
|
819
|
+
if (this.isPending(row, proofs, input)) pending.push(input);
|
|
345
820
|
if (pending.length === limit) break;
|
|
346
821
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
822
|
+
return pending;
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Every current owner input in order (a forced pass), read with its IDs in
|
|
828
|
+
* one statement so a concurrent rechunk cannot empty a page.
|
|
829
|
+
*/
|
|
830
|
+
currentPage(options: {
|
|
831
|
+
limit: number;
|
|
832
|
+
after?: { documentId: number; seq: number };
|
|
833
|
+
collection?: string;
|
|
834
|
+
}): VectorOwnerInput[] {
|
|
835
|
+
if (!Number.isSafeInteger(options.limit) || options.limit < 1)
|
|
836
|
+
throw new Error("Invalid page limit");
|
|
837
|
+
return this.snapshot(() => {
|
|
838
|
+
const page: VectorOwnerInput[] = [];
|
|
839
|
+
for (const row of this.ownerRows(
|
|
840
|
+
options.collection || undefined,
|
|
841
|
+
options.after
|
|
842
|
+
)) {
|
|
843
|
+
page.push(this.input(row));
|
|
844
|
+
if (page.length === options.limit) break;
|
|
845
|
+
}
|
|
846
|
+
return page;
|
|
847
|
+
});
|
|
352
848
|
}
|
|
353
849
|
|
|
354
850
|
/** Activation is fenced by a caller-observed epoch and complete current coverage. */
|
|
@@ -357,8 +853,7 @@ export class VectorVariantStore {
|
|
|
357
853
|
.transaction(() => {
|
|
358
854
|
if (this.epoch() !== expectedEpoch)
|
|
359
855
|
throw new Error("Variant mutation epoch changed");
|
|
360
|
-
if (this.
|
|
361
|
-
throw new Error("Variant coverage incomplete");
|
|
856
|
+
if (this.hasPending()) throw new Error("Variant coverage incomplete");
|
|
362
857
|
if (!this.searchAvailable) throw new Error("Variant index unavailable");
|
|
363
858
|
const mismatch = this.db
|
|
364
859
|
.query<{ count: number }, [string]>(`
|
|
@@ -374,6 +869,8 @@ export class VectorVariantStore {
|
|
|
374
869
|
`)
|
|
375
870
|
.get(this.partitionId)!.count;
|
|
376
871
|
if (mismatch || orphans) throw new Error("Variant index inconsistent");
|
|
872
|
+
// The mirror was just verified against every stored variant.
|
|
873
|
+
this.setMirrorMark(0);
|
|
377
874
|
this.db.run(
|
|
378
875
|
`UPDATE vector_partitions SET state = 'active', activated_epoch = ? WHERE partition_id = ?`,
|
|
379
876
|
[expectedEpoch, this.partitionId]
|
|
@@ -416,23 +913,85 @@ export class VectorVariantStore {
|
|
|
416
913
|
.get(this.partitionId);
|
|
417
914
|
}
|
|
418
915
|
|
|
916
|
+
/** Whether this database tracks vec0 mirror freshness (migration 036). */
|
|
917
|
+
private mirrorTracked(): boolean {
|
|
918
|
+
return !!this.db
|
|
919
|
+
.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?")
|
|
920
|
+
.get("vector_mirror_state");
|
|
921
|
+
}
|
|
922
|
+
|
|
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 = ?"
|
|
929
|
+
)
|
|
930
|
+
.get(this.partitionId)?.dirty ?? null
|
|
931
|
+
);
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
private setMirrorMark(mark: number | null): void {
|
|
935
|
+
if (!this.mirrorTracked()) return;
|
|
936
|
+
if (mark !== 0)
|
|
937
|
+
this.db.run("DELETE FROM vector_mirror_state WHERE partition_id = ?", [
|
|
938
|
+
this.partitionId,
|
|
939
|
+
]);
|
|
940
|
+
else markMirrorClean(this.db, this.partitionId);
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/**
|
|
944
|
+
* Runs a store write that keeps vec0 in step. The vector_variants triggers
|
|
945
|
+
* 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.
|
|
948
|
+
*/
|
|
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);
|
|
954
|
+
return result;
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* vec0 mirror freshness for an activated partition: `clean` when no change
|
|
959
|
+
* to stored vectors happened outside the store since the last verified
|
|
960
|
+
* sync or activation, `dirty` otherwise (including never recorded), and
|
|
961
|
+
* `untracked` on databases without migration 036 or without sqlite-vec.
|
|
962
|
+
*/
|
|
963
|
+
mirrorState(): "clean" | "dirty" | "untracked" {
|
|
964
|
+
if (!this.searchAvailable || !this.mirrorTracked()) return "untracked";
|
|
965
|
+
// vec0 is a virtual table without triggers, so rows removed or added
|
|
966
|
+
// there directly are caught by comparing row counts (one count each).
|
|
967
|
+
// The mark and both counts are read in one snapshot.
|
|
968
|
+
return this.snapshot(() => {
|
|
969
|
+
if (this.mirrorMark() !== 0) return "dirty";
|
|
970
|
+
const stored = this.db
|
|
971
|
+
.query<{ n: number }, [string]>(
|
|
972
|
+
"SELECT count(*) AS n FROM vector_variants WHERE partition_id = ?"
|
|
973
|
+
)
|
|
974
|
+
.get(this.partitionId)!.n;
|
|
975
|
+
const mirrored = this.db
|
|
976
|
+
.query<{ n: number }, []>(`SELECT count(*) AS n FROM ${this.tableName}`)
|
|
977
|
+
.get()!.n;
|
|
978
|
+
return stored === mirrored ? "clean" : "dirty";
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
|
|
419
982
|
/** Repair materialization after storage-only backfill; never changes legacy authority. */
|
|
420
983
|
syncIndex(): void {
|
|
421
984
|
if (!this.searchAvailable) throw new Error("Variant index unavailable");
|
|
422
985
|
this.db
|
|
423
986
|
.transaction(() => {
|
|
424
987
|
this.db.exec(`DELETE FROM ${this.tableName}`);
|
|
425
|
-
|
|
426
|
-
.query
|
|
427
|
-
|
|
988
|
+
this.db
|
|
989
|
+
.query(
|
|
990
|
+
`INSERT INTO ${this.tableName}(variant_id, embedding)
|
|
991
|
+
SELECT variant_id, embedding FROM vector_variants WHERE partition_id = ?`
|
|
428
992
|
)
|
|
429
|
-
.
|
|
430
|
-
|
|
431
|
-
this.db.run(
|
|
432
|
-
`INSERT INTO ${this.tableName}(variant_id, embedding) VALUES (?, ?)`,
|
|
433
|
-
[row.variant_id, row.embedding]
|
|
434
|
-
);
|
|
435
|
-
}
|
|
993
|
+
.run(this.partitionId);
|
|
994
|
+
this.setMirrorMark(0);
|
|
436
995
|
})
|
|
437
996
|
.immediate();
|
|
438
997
|
}
|
|
@@ -441,45 +1000,127 @@ export class VectorVariantStore {
|
|
|
441
1000
|
release(documentId: number): void {
|
|
442
1001
|
this.assertWritable();
|
|
443
1002
|
this.db
|
|
444
|
-
.transaction(() =>
|
|
445
|
-
this.
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
1003
|
+
.transaction(() =>
|
|
1004
|
+
this.keepingMirrorMark(() => {
|
|
1005
|
+
this.db
|
|
1006
|
+
.query(
|
|
1007
|
+
"DELETE FROM vector_owners WHERE document_id = ? AND partition_id = ?"
|
|
1008
|
+
)
|
|
1009
|
+
.run(documentId, this.partitionId);
|
|
1010
|
+
this.removeUnowned(true);
|
|
1011
|
+
})
|
|
1012
|
+
)
|
|
451
1013
|
.immediate();
|
|
452
1014
|
}
|
|
453
1015
|
|
|
454
1016
|
collectGarbage(): number {
|
|
455
1017
|
this.assertWritable();
|
|
1018
|
+
const inOuterTx = this.db.inTransaction;
|
|
456
1019
|
return this.db
|
|
457
|
-
.transaction(() =>
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
1020
|
+
.transaction(() =>
|
|
1021
|
+
this.keepingMirrorMark(() => this.removeUnowned(inOuterTx))
|
|
1022
|
+
)
|
|
1023
|
+
.immediate();
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
private removeUnowned(inOuterTx: boolean): number {
|
|
1027
|
+
// 1. Collect variants with zero active mirror-matching owners in pure SQL
|
|
1028
|
+
// without touching any embedding BLOBs.
|
|
1029
|
+
const noActiveOwners = this.db
|
|
1030
|
+
.query<{ variant_id: number }, [string]>(`
|
|
1031
|
+
SELECT v.variant_id
|
|
1032
|
+
FROM vector_variants v
|
|
1033
|
+
WHERE v.partition_id = ?
|
|
1034
|
+
AND NOT EXISTS (
|
|
1035
|
+
SELECT 1
|
|
1036
|
+
FROM vector_owners o
|
|
1037
|
+
JOIN documents d ON d.id = o.document_id AND d.active = 1
|
|
1038
|
+
AND d.mirror_hash = o.mirror_hash
|
|
1039
|
+
JOIN content_chunks c ON c.mirror_hash = o.mirror_hash AND c.seq = o.seq
|
|
1040
|
+
WHERE o.partition_id = v.partition_id AND o.variant_id = v.variant_id
|
|
462
1041
|
)
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
1042
|
+
`)
|
|
1043
|
+
.all(this.partitionId);
|
|
1044
|
+
|
|
1045
|
+
const toRemove: number[] = noActiveOwners.map((row) => row.variant_id);
|
|
1046
|
+
|
|
1047
|
+
// 2. Stream remaining candidates ordered by variant_id (never reading
|
|
1048
|
+
// v.embedding), consulting the epoch-keyed proof cache and short-circuiting
|
|
1049
|
+
// as soon as a variant has one valid owner.
|
|
1050
|
+
const proofs = provenOwners(this.db, inOuterTx);
|
|
1051
|
+
const candidateStmt = this.db.prepare<
|
|
1052
|
+
OwnerRow & { variant_id: number; input_hash: string },
|
|
1053
|
+
[string]
|
|
1054
|
+
>(`
|
|
1055
|
+
SELECT v.variant_id, v.input_hash,
|
|
1056
|
+
d.id AS documentId, d.mirror_hash AS mirrorHash,
|
|
1057
|
+
c.seq, c.text, d.title
|
|
1058
|
+
FROM vector_variants v
|
|
1059
|
+
JOIN vector_owners o${ownerPartitionVariantHint(this.db)}
|
|
1060
|
+
ON o.partition_id = v.partition_id AND o.variant_id = v.variant_id
|
|
1061
|
+
JOIN documents d ON d.id = o.document_id AND d.active = 1
|
|
1062
|
+
AND d.mirror_hash = o.mirror_hash
|
|
1063
|
+
JOIN content_chunks c${chunkKeyHint(this.db)}
|
|
1064
|
+
ON c.mirror_hash = o.mirror_hash AND c.seq = o.seq
|
|
1065
|
+
WHERE v.partition_id = ?
|
|
1066
|
+
ORDER BY v.variant_id
|
|
1067
|
+
`);
|
|
1068
|
+
try {
|
|
1069
|
+
let currentVariantId: number | null = null;
|
|
1070
|
+
let hasValidOwner = false;
|
|
1071
|
+
for (const row of candidateStmt.iterate(this.partitionId)) {
|
|
1072
|
+
if (row.variant_id !== currentVariantId) {
|
|
1073
|
+
if (currentVariantId !== null && !hasValidOwner) {
|
|
1074
|
+
toRemove.push(currentVariantId);
|
|
1075
|
+
}
|
|
1076
|
+
currentVariantId = row.variant_id;
|
|
1077
|
+
hasValidOwner = false;
|
|
479
1078
|
}
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
1079
|
+
if (hasValidOwner) continue;
|
|
1080
|
+
const key = vectorProofKey(
|
|
1081
|
+
this.identity.model,
|
|
1082
|
+
row.documentId,
|
|
1083
|
+
row.mirrorHash,
|
|
1084
|
+
row.seq,
|
|
1085
|
+
row.input_hash
|
|
1086
|
+
);
|
|
1087
|
+
let valid = proofs.get(key);
|
|
1088
|
+
if (valid === undefined) {
|
|
1089
|
+
valid = this.input(row).inputHash === row.input_hash;
|
|
1090
|
+
proofs.set(key, valid);
|
|
1091
|
+
}
|
|
1092
|
+
if (valid) {
|
|
1093
|
+
hasValidOwner = true;
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
if (currentVariantId !== null && !hasValidOwner) {
|
|
1097
|
+
toRemove.push(currentVariantId);
|
|
1098
|
+
}
|
|
1099
|
+
} finally {
|
|
1100
|
+
candidateStmt.finalize();
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
if (toRemove.length === 0) return 0;
|
|
1104
|
+
|
|
1105
|
+
const removeJson = JSON.stringify(toRemove);
|
|
1106
|
+
if (this.searchAvailable) {
|
|
1107
|
+
this.db
|
|
1108
|
+
.query(
|
|
1109
|
+
`DELETE FROM ${this.tableName} WHERE variant_id IN (SELECT value FROM json_each(?))`
|
|
1110
|
+
)
|
|
1111
|
+
.run(removeJson);
|
|
1112
|
+
}
|
|
1113
|
+
this.db
|
|
1114
|
+
.query(
|
|
1115
|
+
"DELETE FROM vector_owners WHERE partition_id = ? AND variant_id IN (SELECT value FROM json_each(?))"
|
|
1116
|
+
)
|
|
1117
|
+
.run(this.partitionId, removeJson);
|
|
1118
|
+
this.db
|
|
1119
|
+
.query(
|
|
1120
|
+
"DELETE FROM vector_variants WHERE partition_id = ? AND variant_id IN (SELECT value FROM json_each(?))"
|
|
1121
|
+
)
|
|
1122
|
+
.run(this.partitionId, removeJson);
|
|
1123
|
+
return toRemove.length;
|
|
483
1124
|
}
|
|
484
1125
|
}
|
|
485
1126
|
|