@gmickel/gno 2.15.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.15.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 +1 -1
- 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 +2 -2
- 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/program.ts +20 -36
- 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 +142 -60
- package/src/embed/retry.ts +39 -33
- package/src/embed/variant-backlog.ts +546 -114
- package/src/embed/variant-retry.ts +157 -48
- 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/037-performance-indexes.ts +56 -0
- package/src/store/migrations/index.ts +2 -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 +28 -45
- 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 +495 -139
- package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
|
@@ -10,6 +10,11 @@ import type {
|
|
|
10
10
|
|
|
11
11
|
import { formatDocForEmbedding } from "../../pipeline/contextual";
|
|
12
12
|
import { buildEligibleDocumentQuery } from "../sqlite/eligibility";
|
|
13
|
+
import {
|
|
14
|
+
hasNullCosineVariant,
|
|
15
|
+
provenOwners,
|
|
16
|
+
vectorProofKey,
|
|
17
|
+
} from "./proof-cache";
|
|
13
18
|
import {
|
|
14
19
|
embeddingPartitionIdentity,
|
|
15
20
|
identityPartitionId,
|
|
@@ -23,7 +28,13 @@ import {
|
|
|
23
28
|
writerConnection,
|
|
24
29
|
writerIdle,
|
|
25
30
|
} from "./sqlite-vec";
|
|
26
|
-
import {
|
|
31
|
+
import {
|
|
32
|
+
chunkKeyHint,
|
|
33
|
+
embeddingInputHash,
|
|
34
|
+
ownerDocPartHint,
|
|
35
|
+
ownerPartitionVariantHint,
|
|
36
|
+
variantPartitionIdHint,
|
|
37
|
+
} from "./variants";
|
|
27
38
|
|
|
28
39
|
/** Fallback/warning code: this runtime may not read the activated vectors. */
|
|
29
40
|
export const VECTOR_RUNTIME_INCOMPATIBLE = "vector_runtime_incompatible";
|
|
@@ -119,70 +130,299 @@ export function vectorSearchUnavailableMessage(
|
|
|
119
130
|
}`;
|
|
120
131
|
}
|
|
121
132
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
133
|
+
function hasSelectiveEligibility(options: VectorSearchOptions): boolean {
|
|
134
|
+
if (options.allowedMirrorHashes !== undefined) return true;
|
|
135
|
+
const e = options.eligibility;
|
|
136
|
+
if (!e) return false;
|
|
137
|
+
return Boolean(
|
|
138
|
+
e.collection ||
|
|
139
|
+
e.collections !== undefined ||
|
|
140
|
+
e.filter ||
|
|
141
|
+
e.tagsAny?.length ||
|
|
142
|
+
e.tagsAll?.length ||
|
|
143
|
+
e.since ||
|
|
144
|
+
e.until ||
|
|
145
|
+
e.categories?.length ||
|
|
146
|
+
e.author ||
|
|
147
|
+
e.relPathPrefix !== undefined ||
|
|
148
|
+
e.memoryScopesAny?.length ||
|
|
149
|
+
e.excludeSuperseded ||
|
|
150
|
+
e.exclude?.length ||
|
|
151
|
+
e.chunkLanguage ||
|
|
152
|
+
e.allowedMirrorHashes !== undefined
|
|
153
|
+
);
|
|
154
|
+
}
|
|
127
155
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
156
|
+
const MAX_VEC0_K = 4096;
|
|
157
|
+
const MAX_SQL_BATCH_QUERIES = 8;
|
|
158
|
+
|
|
159
|
+
interface RankedVariantRow {
|
|
160
|
+
variantId?: number;
|
|
161
|
+
mirrorHash: string;
|
|
162
|
+
seq: number;
|
|
163
|
+
inputHash: string;
|
|
164
|
+
distance: number;
|
|
165
|
+
documentIds: string;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
interface CandidateRow {
|
|
169
|
+
variantId: number;
|
|
170
|
+
mirrorHash: string;
|
|
171
|
+
seq: number;
|
|
172
|
+
inputHash: string;
|
|
173
|
+
distance: number;
|
|
174
|
+
documentIds: number[];
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function isNonZeroVector(embedding: Float32Array): boolean {
|
|
178
|
+
let sumSq = 0;
|
|
179
|
+
for (let i = 0; i < embedding.length; i++) {
|
|
180
|
+
const v = embedding[i]!;
|
|
181
|
+
if (!Number.isFinite(v)) return false;
|
|
182
|
+
sumSq += v * v;
|
|
183
|
+
}
|
|
184
|
+
return sumSq > 0 && Number.isFinite(sumSq);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function isMirrorClean(db: Database, partitionId: string): boolean {
|
|
188
|
+
if (
|
|
189
|
+
!db
|
|
190
|
+
.query(
|
|
191
|
+
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'vector_mirror_state'"
|
|
192
|
+
)
|
|
193
|
+
.get()
|
|
194
|
+
)
|
|
195
|
+
return false;
|
|
196
|
+
const row = db
|
|
197
|
+
.query<{ dirty: number }, [string]>(
|
|
198
|
+
"SELECT dirty FROM vector_mirror_state WHERE partition_id = ?"
|
|
137
199
|
)
|
|
138
|
-
.get()
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
200
|
+
.get(partitionId);
|
|
201
|
+
return row?.dirty === 0;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Exact SQLite `ORDER BY distance, mirrorHash, seq, variantId` comparator (NULLS FIRST, binary text). */
|
|
205
|
+
function compareVariantCandidates(a: CandidateRow, b: CandidateRow): number {
|
|
206
|
+
const aNull = a.distance === null;
|
|
207
|
+
const bNull = b.distance === null;
|
|
208
|
+
if (aNull !== bNull) return aNull ? -1 : 1;
|
|
209
|
+
if (!aNull && a.distance !== b.distance) return a.distance - b.distance;
|
|
210
|
+
if (a.mirrorHash < b.mirrorHash) return -1;
|
|
211
|
+
if (a.mirrorHash > b.mirrorHash) return 1;
|
|
212
|
+
if (a.seq !== b.seq) return a.seq - b.seq;
|
|
213
|
+
return a.variantId - b.variantId;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Max-heap insertion keeping the smallest `cap` candidates under `compareVariantCandidates`. */
|
|
217
|
+
function pushBoundedCandidate(
|
|
218
|
+
heap: CandidateRow[],
|
|
219
|
+
cap: number,
|
|
220
|
+
item: CandidateRow
|
|
221
|
+
): void {
|
|
222
|
+
if (heap.length < cap) {
|
|
223
|
+
heap.push(item);
|
|
224
|
+
let idx = heap.length - 1;
|
|
225
|
+
while (idx > 0) {
|
|
226
|
+
const parent = (idx - 1) >> 1;
|
|
227
|
+
if (compareVariantCandidates(heap[idx]!, heap[parent]!) <= 0) break;
|
|
228
|
+
const tmp = heap[parent]!;
|
|
229
|
+
heap[parent] = heap[idx]!;
|
|
230
|
+
heap[idx] = tmp;
|
|
231
|
+
idx = parent;
|
|
232
|
+
}
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (compareVariantCandidates(item, heap[0]!) >= 0) return;
|
|
236
|
+
heap[0] = item;
|
|
237
|
+
let idx = 0;
|
|
238
|
+
const len = heap.length;
|
|
239
|
+
for (;;) {
|
|
240
|
+
const left = idx * 2 + 1;
|
|
241
|
+
const right = left + 1;
|
|
242
|
+
let largest = idx;
|
|
243
|
+
if (left < len && compareVariantCandidates(heap[left]!, heap[largest]!) > 0)
|
|
244
|
+
largest = left;
|
|
245
|
+
if (
|
|
246
|
+
right < len &&
|
|
247
|
+
compareVariantCandidates(heap[right]!, heap[largest]!) > 0
|
|
248
|
+
)
|
|
249
|
+
largest = right;
|
|
250
|
+
if (largest === idx) break;
|
|
251
|
+
const tmp = heap[idx]!;
|
|
252
|
+
heap[idx] = heap[largest]!;
|
|
253
|
+
heap[largest] = tmp;
|
|
254
|
+
idx = largest;
|
|
144
255
|
}
|
|
145
|
-
return cache.proofs;
|
|
146
256
|
}
|
|
147
257
|
|
|
148
|
-
|
|
149
|
-
|
|
258
|
+
function createBatchOwnersStmt(db: Database) {
|
|
259
|
+
return db.query<
|
|
260
|
+
{
|
|
261
|
+
id: number;
|
|
262
|
+
mirrorHash: string;
|
|
263
|
+
seq: number;
|
|
264
|
+
title: string | null;
|
|
265
|
+
text: string;
|
|
266
|
+
},
|
|
267
|
+
[string]
|
|
268
|
+
>(`
|
|
269
|
+
WITH req AS (
|
|
270
|
+
SELECT
|
|
271
|
+
json_extract(value, '$[0]') AS document_id,
|
|
272
|
+
json_extract(value, '$[1]') AS mirror_hash,
|
|
273
|
+
json_extract(value, '$[2]') AS seq
|
|
274
|
+
FROM json_each(?)
|
|
275
|
+
)
|
|
276
|
+
SELECT r.document_id AS id, r.mirror_hash AS mirrorHash, r.seq, d.title, c.text
|
|
277
|
+
FROM req r
|
|
278
|
+
JOIN documents d ON d.id = r.document_id
|
|
279
|
+
JOIN content_chunks c ON c.mirror_hash = r.mirror_hash AND c.seq = r.seq
|
|
280
|
+
`);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function proveUnknownOwners(
|
|
284
|
+
model: string,
|
|
285
|
+
proofs: Map<string, boolean>,
|
|
286
|
+
candidateLists: readonly (readonly CandidateRow[])[],
|
|
287
|
+
batchOwners: ReturnType<typeof createBatchOwnersStmt>
|
|
288
|
+
): void {
|
|
289
|
+
const unknownByTuple = new Map<
|
|
290
|
+
string,
|
|
291
|
+
{
|
|
292
|
+
id: number;
|
|
293
|
+
mirrorHash: string;
|
|
294
|
+
seq: number;
|
|
295
|
+
inputHashes: Set<string>;
|
|
296
|
+
}
|
|
297
|
+
>();
|
|
298
|
+
for (const list of candidateLists) {
|
|
299
|
+
for (const row of list) {
|
|
300
|
+
for (const id of row.documentIds) {
|
|
301
|
+
const key = vectorProofKey(
|
|
302
|
+
model,
|
|
303
|
+
id,
|
|
304
|
+
row.mirrorHash,
|
|
305
|
+
row.seq,
|
|
306
|
+
row.inputHash
|
|
307
|
+
);
|
|
308
|
+
if (!proofs.has(key)) {
|
|
309
|
+
const tupleKey = `${id}\0${row.mirrorHash}\0${row.seq}`;
|
|
310
|
+
let entry = unknownByTuple.get(tupleKey);
|
|
311
|
+
if (!entry) {
|
|
312
|
+
entry = {
|
|
313
|
+
id,
|
|
314
|
+
mirrorHash: row.mirrorHash,
|
|
315
|
+
seq: row.seq,
|
|
316
|
+
inputHashes: new Set(),
|
|
317
|
+
};
|
|
318
|
+
unknownByTuple.set(tupleKey, entry);
|
|
319
|
+
}
|
|
320
|
+
entry.inputHashes.add(row.inputHash);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
if (unknownByTuple.size === 0) return;
|
|
326
|
+
const payload = JSON.stringify(
|
|
327
|
+
Array.from(unknownByTuple.values(), (entry) => [
|
|
328
|
+
entry.id,
|
|
329
|
+
entry.mirrorHash,
|
|
330
|
+
entry.seq,
|
|
331
|
+
])
|
|
332
|
+
);
|
|
333
|
+
const seenTuples = new Set<string>();
|
|
334
|
+
for (const owner of batchOwners.all(payload)) {
|
|
335
|
+
const tupleKey = `${owner.id}\0${owner.mirrorHash}\0${owner.seq}`;
|
|
336
|
+
seenTuples.add(tupleKey);
|
|
337
|
+
const entry = unknownByTuple.get(tupleKey);
|
|
338
|
+
if (!entry) continue;
|
|
339
|
+
const actualHash = embeddingInputHash(
|
|
340
|
+
formatDocForEmbedding(owner.text, owner.title ?? undefined, model)
|
|
341
|
+
);
|
|
342
|
+
for (const expectedHash of entry.inputHashes) {
|
|
343
|
+
proofs.set(
|
|
344
|
+
vectorProofKey(
|
|
345
|
+
model,
|
|
346
|
+
owner.id,
|
|
347
|
+
owner.mirrorHash,
|
|
348
|
+
owner.seq,
|
|
349
|
+
expectedHash
|
|
350
|
+
),
|
|
351
|
+
actualHash === expectedHash
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
for (const [tupleKey, entry] of unknownByTuple) {
|
|
356
|
+
if (seenTuples.has(tupleKey)) continue;
|
|
357
|
+
for (const expectedHash of entry.inputHashes) {
|
|
358
|
+
proofs.set(
|
|
359
|
+
vectorProofKey(
|
|
360
|
+
model,
|
|
361
|
+
entry.id,
|
|
362
|
+
entry.mirrorHash,
|
|
363
|
+
entry.seq,
|
|
364
|
+
expectedHash
|
|
365
|
+
),
|
|
366
|
+
false
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function resolveActivePartition(
|
|
150
373
|
db: Database,
|
|
151
374
|
model: string,
|
|
152
375
|
dimensions: number,
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
): VectorSearchResult[] | null {
|
|
376
|
+
embeddings: readonly Float32Array[],
|
|
377
|
+
options: VectorSearchOptions
|
|
378
|
+
): { partitionId: string; tableName: string; hasMirror: boolean } | null {
|
|
157
379
|
if (
|
|
158
380
|
!db
|
|
159
381
|
.query("SELECT 1 FROM sqlite_master WHERE name = 'vector_partitions'")
|
|
160
382
|
.get()
|
|
161
383
|
)
|
|
162
384
|
return null;
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
385
|
+
|
|
386
|
+
const hasActivatedForModel = (): boolean =>
|
|
387
|
+
Boolean(
|
|
388
|
+
db
|
|
389
|
+
.query(
|
|
390
|
+
"SELECT 1 FROM vector_partitions WHERE model = ? AND state = 'active' AND activated_epoch IS NOT NULL LIMIT 1"
|
|
391
|
+
)
|
|
392
|
+
.get(model)
|
|
393
|
+
);
|
|
394
|
+
|
|
395
|
+
const validDimensions = embeddings.every((e) => e.length === dimensions);
|
|
168
396
|
const identity = options.embeddingIdentity;
|
|
169
397
|
let partitionId: string;
|
|
170
398
|
if (options.partitionId !== undefined) {
|
|
171
399
|
const stored = db
|
|
172
|
-
.query<
|
|
173
|
-
|
|
400
|
+
.query<
|
|
401
|
+
{
|
|
402
|
+
model: string;
|
|
403
|
+
dimensions: number;
|
|
404
|
+
state: string;
|
|
405
|
+
activated_epoch: number | null;
|
|
406
|
+
},
|
|
407
|
+
[string]
|
|
408
|
+
>(
|
|
409
|
+
"SELECT model, dimensions, state, activated_epoch FROM vector_partitions WHERE partition_id = ?"
|
|
174
410
|
)
|
|
175
411
|
.get(options.partitionId);
|
|
176
412
|
if (
|
|
177
413
|
stored?.model !== model ||
|
|
178
414
|
stored.dimensions !== dimensions ||
|
|
179
|
-
|
|
415
|
+
!validDimensions
|
|
180
416
|
)
|
|
181
417
|
throw new Error("Stored vector partition does not match vector index");
|
|
418
|
+
if (stored.state !== "active" || stored.activated_epoch === null)
|
|
419
|
+
throw new Error(
|
|
420
|
+
"Selected embedding variant partition has not activated; run gno embed"
|
|
421
|
+
);
|
|
182
422
|
partitionId = options.partitionId;
|
|
183
423
|
} else {
|
|
184
424
|
if (!identity) {
|
|
185
|
-
if (
|
|
425
|
+
if (hasActivatedForModel())
|
|
186
426
|
throw new Error(
|
|
187
427
|
"Effective embedding identity unavailable after variant activation"
|
|
188
428
|
);
|
|
@@ -191,29 +431,147 @@ function searchVectorVariantsInSnapshot(
|
|
|
191
431
|
if (
|
|
192
432
|
identity.model !== model ||
|
|
193
433
|
identity.dimensions !== dimensions ||
|
|
194
|
-
|
|
434
|
+
!validDimensions
|
|
195
435
|
)
|
|
196
436
|
throw new Error("Query embedding identity does not match vector index");
|
|
197
437
|
partitionId = identityPartitionId(identity);
|
|
438
|
+
const partition = db
|
|
439
|
+
.query<{ state: string; activated_epoch: number | null }, [string]>(
|
|
440
|
+
"SELECT state, activated_epoch FROM vector_partitions WHERE partition_id = ?"
|
|
441
|
+
)
|
|
442
|
+
.get(partitionId);
|
|
443
|
+
if (partition?.state !== "active" || partition.activated_epoch === null) {
|
|
444
|
+
if (hasActivatedForModel())
|
|
445
|
+
throw new Error(
|
|
446
|
+
"Selected embedding variant partition has not activated; run gno embed"
|
|
447
|
+
);
|
|
448
|
+
return null;
|
|
449
|
+
}
|
|
198
450
|
}
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
451
|
+
const tableName = `vec_v1_${partitionId}`;
|
|
452
|
+
const hasMirror = Boolean(
|
|
453
|
+
db.query("SELECT 1 FROM sqlite_master WHERE name = ?").get(tableName)
|
|
454
|
+
);
|
|
455
|
+
return { partitionId, tableName, hasMirror };
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* Clean-mirror vec0 fast path for unfiltered searches. Returns exact top-k
|
|
460
|
+
* hits when boundary safety is mathematically proven, or `null` to fall back
|
|
461
|
+
* transparently to the authoritative `vector_variants` scan.
|
|
462
|
+
*/
|
|
463
|
+
function searchVectorVariantsViaVec0(
|
|
464
|
+
db: Database,
|
|
465
|
+
model: string,
|
|
466
|
+
partitionId: string,
|
|
467
|
+
tableName: string,
|
|
468
|
+
embedding: Float32Array,
|
|
469
|
+
k: number,
|
|
470
|
+
minScore: number | undefined,
|
|
471
|
+
proofs: Map<string, boolean>,
|
|
472
|
+
batchOwners: ReturnType<typeof createBatchOwnersStmt>
|
|
473
|
+
): VectorSearchResult[] | null {
|
|
474
|
+
if (k > MAX_VEC0_K || !isNonZeroVector(embedding)) return null;
|
|
475
|
+
const queryVector = encodeEmbedding(embedding);
|
|
476
|
+
const vecK = Math.min(MAX_VEC0_K, Math.max(k + 16, k * 2));
|
|
477
|
+
const vecRows = db
|
|
478
|
+
.query<
|
|
479
|
+
{ variantId: number; distance: number | null },
|
|
480
|
+
[Uint8Array, number]
|
|
481
|
+
>(
|
|
482
|
+
`SELECT variant_id AS variantId, distance FROM ${tableName} WHERE embedding MATCH ? AND k = ?`
|
|
202
483
|
)
|
|
203
|
-
.
|
|
204
|
-
if (
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
484
|
+
.all(queryVector, vecK);
|
|
485
|
+
if (vecRows.length === 0) return [];
|
|
486
|
+
const exhaustedMirror = vecRows.length < vecK;
|
|
487
|
+
const boundaryDistance = vecRows[vecRows.length - 1]!.distance;
|
|
488
|
+
if (
|
|
489
|
+
!exhaustedMirror &&
|
|
490
|
+
(boundaryDistance === null || Number.isNaN(boundaryDistance))
|
|
491
|
+
) {
|
|
209
492
|
return null;
|
|
210
493
|
}
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
494
|
+
const variantIds = vecRows.map((row) => row.variantId);
|
|
495
|
+
const hydrated = db
|
|
496
|
+
.query<RankedVariantRow, [Uint8Array, string, string]>(`
|
|
497
|
+
SELECT o.variant_id AS variantId, o.mirror_hash AS mirrorHash, o.seq,
|
|
498
|
+
v.input_hash AS inputHash,
|
|
499
|
+
vec_distance_cosine(v.embedding, ?) AS distance,
|
|
500
|
+
json_group_array(o.document_id) AS documentIds
|
|
501
|
+
FROM vector_owners o
|
|
502
|
+
JOIN documents d ON d.id = o.document_id AND d.active = 1 AND d.mirror_hash = o.mirror_hash
|
|
503
|
+
JOIN content_chunks c${chunkKeyHint(db)} ON c.mirror_hash = o.mirror_hash AND c.seq = o.seq
|
|
504
|
+
JOIN vector_variants v${variantPartitionIdHint(db)}
|
|
505
|
+
ON v.partition_id = o.partition_id AND v.variant_id = o.variant_id
|
|
506
|
+
WHERE o.partition_id = ?
|
|
507
|
+
AND o.variant_id IN (SELECT value FROM json_each(?))
|
|
508
|
+
GROUP BY o.variant_id, o.mirror_hash, o.seq
|
|
509
|
+
ORDER BY distance, o.mirror_hash, o.seq, o.variant_id
|
|
510
|
+
`)
|
|
511
|
+
.all(queryVector, partitionId, JSON.stringify(variantIds));
|
|
512
|
+
|
|
513
|
+
let hitMinScoreCutoff = false;
|
|
514
|
+
let cutoffDistance: number | null = null;
|
|
515
|
+
const candidateRows: CandidateRow[] = [];
|
|
516
|
+
for (const row of hydrated) {
|
|
517
|
+
if (minScore !== undefined && 1 - row.distance < minScore) {
|
|
518
|
+
hitMinScoreCutoff = true;
|
|
519
|
+
cutoffDistance = row.distance;
|
|
520
|
+
break;
|
|
521
|
+
}
|
|
522
|
+
candidateRows.push({
|
|
523
|
+
variantId: row.variantId ?? 0,
|
|
524
|
+
mirrorHash: row.mirrorHash,
|
|
525
|
+
seq: row.seq,
|
|
526
|
+
inputHash: row.inputHash,
|
|
527
|
+
distance: row.distance,
|
|
528
|
+
documentIds: JSON.parse(row.documentIds) as number[],
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
proveUnknownOwners(model, proofs, [candidateRows], batchOwners);
|
|
532
|
+
|
|
533
|
+
const results: VectorSearchResult[] = [];
|
|
534
|
+
for (const row of candidateRows) {
|
|
535
|
+
const proven = row.documentIds
|
|
536
|
+
.filter((id) =>
|
|
537
|
+
proofs.get(
|
|
538
|
+
vectorProofKey(model, id, row.mirrorHash, row.seq, row.inputHash)
|
|
539
|
+
)
|
|
540
|
+
)
|
|
541
|
+
.sort((a, b) => a - b);
|
|
542
|
+
if (proven.length === 0) continue;
|
|
543
|
+
results.push({
|
|
544
|
+
mirrorHash: row.mirrorHash,
|
|
545
|
+
seq: row.seq,
|
|
546
|
+
distance: row.distance,
|
|
547
|
+
documentIds: proven,
|
|
548
|
+
});
|
|
549
|
+
if (results.length === k) break;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
if (exhaustedMirror) return results;
|
|
553
|
+
if (
|
|
554
|
+
hitMinScoreCutoff &&
|
|
555
|
+
cutoffDistance !== null &&
|
|
556
|
+
cutoffDistance < boundaryDistance!
|
|
557
|
+
) {
|
|
558
|
+
return results;
|
|
559
|
+
}
|
|
560
|
+
if (
|
|
561
|
+
results.length === k &&
|
|
562
|
+
results[k - 1]!.distance !== null &&
|
|
563
|
+
results[k - 1]!.distance < boundaryDistance!
|
|
564
|
+
) {
|
|
565
|
+
return results;
|
|
566
|
+
}
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function buildEligibleVariantQuerySpec(
|
|
571
|
+
db: Database,
|
|
572
|
+
partitionId: string,
|
|
573
|
+
options: VectorSearchOptions
|
|
574
|
+
) {
|
|
217
575
|
const eligible = buildEligibleDocumentQuery(
|
|
218
576
|
{ ...options.eligibility, semanticMetadata: true },
|
|
219
577
|
db
|
|
@@ -228,76 +586,80 @@ function searchVectorVariantsInSnapshot(
|
|
|
228
586
|
conditions.push("o.mirror_hash IN (SELECT value FROM json_each(?))");
|
|
229
587
|
params.push(JSON.stringify(options.allowedMirrorHashes));
|
|
230
588
|
}
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
589
|
+
const selective = hasSelectiveEligibility(options);
|
|
590
|
+
const innerFrom = selective
|
|
591
|
+
? `FROM (${eligible.sql}) e
|
|
592
|
+
CROSS JOIN vector_owners o${ownerDocPartHint(db)}
|
|
593
|
+
ON o.document_id = e.id AND o.mirror_hash = e.mirror_hash`
|
|
594
|
+
: `FROM vector_owners o${ownerPartitionVariantHint(db)}
|
|
595
|
+
CROSS JOIN (${eligible.sql}) e
|
|
596
|
+
ON e.id = o.document_id AND e.mirror_hash = o.mirror_hash`;
|
|
597
|
+
return { eligible, conditions, params, innerFrom };
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
function searchVectorVariantsFromVariants(
|
|
601
|
+
db: Database,
|
|
602
|
+
model: string,
|
|
603
|
+
partitionId: string,
|
|
604
|
+
embedding: Float32Array,
|
|
605
|
+
k: number,
|
|
606
|
+
minScore: number | undefined,
|
|
607
|
+
spec: ReturnType<typeof buildEligibleVariantQuerySpec>,
|
|
608
|
+
proofs: Map<string, boolean>,
|
|
609
|
+
batchOwners: ReturnType<typeof createBatchOwnersStmt>
|
|
610
|
+
): VectorSearchResult[] {
|
|
611
|
+
const ranked = db.query<RankedVariantRow, (Uint8Array | string | number)[]>(`
|
|
612
|
+
SELECT g.variantId, g.mirrorHash, g.seq, v.input_hash AS inputHash,
|
|
244
613
|
vec_distance_cosine(v.embedding, ?) AS distance, g.documentIds
|
|
245
614
|
FROM (
|
|
246
615
|
SELECT o.variant_id AS variantId, o.mirror_hash AS mirrorHash, o.seq,
|
|
247
616
|
json_group_array(o.document_id) AS documentIds
|
|
248
|
-
|
|
249
|
-
JOIN
|
|
250
|
-
|
|
251
|
-
WHERE ${conditions.join(" AND ")}
|
|
617
|
+
${spec.innerFrom}
|
|
618
|
+
JOIN content_chunks c${chunkKeyHint(db)} ON c.mirror_hash = o.mirror_hash AND c.seq = o.seq
|
|
619
|
+
WHERE ${spec.conditions.join(" AND ")}
|
|
252
620
|
GROUP BY o.variant_id, o.mirror_hash, o.seq
|
|
253
621
|
) g
|
|
254
|
-
JOIN vector_variants v
|
|
622
|
+
CROSS JOIN vector_variants v${variantPartitionIdHint(db)}
|
|
623
|
+
ON v.partition_id = ? AND v.variant_id = g.variantId
|
|
255
624
|
ORDER BY distance, g.mirrorHash, g.seq, g.variantId LIMIT ?
|
|
256
625
|
`);
|
|
257
|
-
const owners = db.query<
|
|
258
|
-
{ id: number; title: string | null; text: string },
|
|
259
|
-
[string, number, string]
|
|
260
|
-
>(`
|
|
261
|
-
SELECT d.id, d.title, c.text FROM documents d
|
|
262
|
-
JOIN content_chunks c ON c.mirror_hash = ? AND c.seq = ?
|
|
263
|
-
WHERE d.id IN (SELECT value FROM json_each(?))
|
|
264
|
-
`);
|
|
265
|
-
// A vector counts only while it matches its owner's current formatted
|
|
266
|
-
// input. Proving candidates in rank order and skipping unproven owners
|
|
267
|
-
// returns exactly what filtering every owner before ranking would.
|
|
268
|
-
const proofs = provenOwners(db);
|
|
269
626
|
const queryVector = encodeEmbedding(embedding);
|
|
270
627
|
let limit = k;
|
|
271
628
|
let results: VectorSearchResult[] = [];
|
|
272
629
|
for (;;) {
|
|
273
630
|
const rows = ranked.all(
|
|
274
631
|
queryVector,
|
|
275
|
-
...eligible.params,
|
|
276
|
-
...params,
|
|
632
|
+
...spec.eligible.params,
|
|
633
|
+
...spec.params,
|
|
277
634
|
partitionId,
|
|
278
635
|
limit
|
|
279
636
|
);
|
|
280
|
-
|
|
637
|
+
let hitMinScoreCutoff = false;
|
|
638
|
+
const candidateRows: CandidateRow[] = [];
|
|
281
639
|
for (const row of rows) {
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
const unknown = documentIds.filter((id) => !proofs.has(key(id)));
|
|
286
|
-
if (unknown.length > 0) {
|
|
287
|
-
for (const owner of owners.all(
|
|
288
|
-
row.mirrorHash,
|
|
289
|
-
row.seq,
|
|
290
|
-
JSON.stringify(unknown)
|
|
291
|
-
)) {
|
|
292
|
-
proofs.set(
|
|
293
|
-
key(owner.id),
|
|
294
|
-
embeddingInputHash(
|
|
295
|
-
formatDocForEmbedding(owner.text, owner.title ?? undefined, model)
|
|
296
|
-
) === row.inputHash
|
|
297
|
-
);
|
|
298
|
-
}
|
|
640
|
+
if (minScore !== undefined && 1 - row.distance < minScore) {
|
|
641
|
+
hitMinScoreCutoff = true;
|
|
642
|
+
break;
|
|
299
643
|
}
|
|
300
|
-
|
|
644
|
+
candidateRows.push({
|
|
645
|
+
variantId: row.variantId ?? 0,
|
|
646
|
+
mirrorHash: row.mirrorHash,
|
|
647
|
+
seq: row.seq,
|
|
648
|
+
inputHash: row.inputHash,
|
|
649
|
+
distance: row.distance,
|
|
650
|
+
documentIds: JSON.parse(row.documentIds) as number[],
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
proveUnknownOwners(model, proofs, [candidateRows], batchOwners);
|
|
654
|
+
results = [];
|
|
655
|
+
for (const row of candidateRows) {
|
|
656
|
+
const proven = row.documentIds
|
|
657
|
+
.filter((id) =>
|
|
658
|
+
proofs.get(
|
|
659
|
+
vectorProofKey(model, id, row.mirrorHash, row.seq, row.inputHash)
|
|
660
|
+
)
|
|
661
|
+
)
|
|
662
|
+
.sort((a, b) => a - b);
|
|
301
663
|
if (proven.length === 0) continue;
|
|
302
664
|
results.push({
|
|
303
665
|
mirrorHash: row.mirrorHash,
|
|
@@ -307,13 +669,281 @@ function searchVectorVariantsInSnapshot(
|
|
|
307
669
|
});
|
|
308
670
|
if (results.length === k) break;
|
|
309
671
|
}
|
|
310
|
-
if (results.length === k || rows.length < limit) break;
|
|
672
|
+
if (results.length === k || hitMinScoreCutoff || rows.length < limit) break;
|
|
311
673
|
limit *= 4;
|
|
312
674
|
}
|
|
313
|
-
return results
|
|
314
|
-
|
|
315
|
-
|
|
675
|
+
return results;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** Null means legacy authority. Once promoted, unavailable provenance fails closed. */
|
|
679
|
+
function searchVectorVariantsInSnapshot(
|
|
680
|
+
db: Database,
|
|
681
|
+
model: string,
|
|
682
|
+
dimensions: number,
|
|
683
|
+
embedding: Float32Array,
|
|
684
|
+
k: number,
|
|
685
|
+
options: VectorSearchOptions,
|
|
686
|
+
inOuterTransaction: boolean
|
|
687
|
+
): VectorSearchResult[] | null {
|
|
688
|
+
const resolved = resolveActivePartition(
|
|
689
|
+
db,
|
|
690
|
+
model,
|
|
691
|
+
dimensions,
|
|
692
|
+
[embedding],
|
|
693
|
+
options
|
|
316
694
|
);
|
|
695
|
+
if (!resolved) return null;
|
|
696
|
+
const { partitionId, tableName, hasMirror } = resolved;
|
|
697
|
+
const spec = buildEligibleVariantQuerySpec(db, partitionId, options);
|
|
698
|
+
const minScore = options.minScore;
|
|
699
|
+
if (minScore !== undefined && Number.isNaN(minScore)) {
|
|
700
|
+
return [];
|
|
701
|
+
}
|
|
702
|
+
const batchOwners = createBatchOwnersStmt(db);
|
|
703
|
+
const proofs = provenOwners(db, inOuterTransaction);
|
|
704
|
+
|
|
705
|
+
if (
|
|
706
|
+
hasMirror &&
|
|
707
|
+
!hasSelectiveEligibility(options) &&
|
|
708
|
+
!options.eligibility?.language &&
|
|
709
|
+
isMirrorClean(db, partitionId) &&
|
|
710
|
+
!hasNullCosineVariant(db, partitionId, inOuterTransaction)
|
|
711
|
+
) {
|
|
712
|
+
const fast = searchVectorVariantsViaVec0(
|
|
713
|
+
db,
|
|
714
|
+
model,
|
|
715
|
+
partitionId,
|
|
716
|
+
tableName,
|
|
717
|
+
embedding,
|
|
718
|
+
k,
|
|
719
|
+
minScore,
|
|
720
|
+
proofs,
|
|
721
|
+
batchOwners
|
|
722
|
+
);
|
|
723
|
+
if (fast !== null) return fast;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
return searchVectorVariantsFromVariants(
|
|
727
|
+
db,
|
|
728
|
+
model,
|
|
729
|
+
partitionId,
|
|
730
|
+
embedding,
|
|
731
|
+
k,
|
|
732
|
+
minScore,
|
|
733
|
+
spec,
|
|
734
|
+
proofs,
|
|
735
|
+
batchOwners
|
|
736
|
+
);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* Batched variant search sharing one snapshot, one eligible scan (when filtered
|
|
741
|
+
* or dirty), and one batched owner proof pass across all query embeddings.
|
|
742
|
+
*/
|
|
743
|
+
function searchVectorVariantsBatchInSnapshot(
|
|
744
|
+
db: Database,
|
|
745
|
+
model: string,
|
|
746
|
+
dimensions: number,
|
|
747
|
+
embeddings: readonly Float32Array[],
|
|
748
|
+
limits: readonly number[],
|
|
749
|
+
options: VectorSearchOptions,
|
|
750
|
+
inOuterTransaction: boolean
|
|
751
|
+
): VectorSearchResult[][] | null {
|
|
752
|
+
const resolved = resolveActivePartition(
|
|
753
|
+
db,
|
|
754
|
+
model,
|
|
755
|
+
dimensions,
|
|
756
|
+
embeddings,
|
|
757
|
+
options
|
|
758
|
+
);
|
|
759
|
+
if (!resolved) return null;
|
|
760
|
+
const { partitionId, tableName, hasMirror } = resolved;
|
|
761
|
+
const spec = buildEligibleVariantQuerySpec(db, partitionId, options);
|
|
762
|
+
const minScore = options.minScore;
|
|
763
|
+
if (minScore !== undefined && Number.isNaN(minScore)) {
|
|
764
|
+
return embeddings.map(() => []);
|
|
765
|
+
}
|
|
766
|
+
const batchOwners = createBatchOwnersStmt(db);
|
|
767
|
+
const proofs = provenOwners(db, inOuterTransaction);
|
|
768
|
+
|
|
769
|
+
// Clean unfiltered mirror: use vec0 per query inside this single snapshot.
|
|
770
|
+
const canUseVec0 =
|
|
771
|
+
hasMirror &&
|
|
772
|
+
!hasSelectiveEligibility(options) &&
|
|
773
|
+
!options.eligibility?.language &&
|
|
774
|
+
isMirrorClean(db, partitionId) &&
|
|
775
|
+
!hasNullCosineVariant(db, partitionId, inOuterTransaction);
|
|
776
|
+
if (canUseVec0) {
|
|
777
|
+
return embeddings.map((embedding, i) => {
|
|
778
|
+
const k = limits[i]!;
|
|
779
|
+
const fast = searchVectorVariantsViaVec0(
|
|
780
|
+
db,
|
|
781
|
+
model,
|
|
782
|
+
partitionId,
|
|
783
|
+
tableName,
|
|
784
|
+
embedding,
|
|
785
|
+
k,
|
|
786
|
+
minScore,
|
|
787
|
+
proofs,
|
|
788
|
+
batchOwners
|
|
789
|
+
);
|
|
790
|
+
if (fast !== null) return fast;
|
|
791
|
+
return searchVectorVariantsFromVariants(
|
|
792
|
+
db,
|
|
793
|
+
model,
|
|
794
|
+
partitionId,
|
|
795
|
+
embedding,
|
|
796
|
+
k,
|
|
797
|
+
minScore,
|
|
798
|
+
spec,
|
|
799
|
+
proofs,
|
|
800
|
+
batchOwners
|
|
801
|
+
);
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// Filtered or dirty mirror: scan eligible vector_variants ONCE per chunk of up to 8 queries.
|
|
806
|
+
const allResults: VectorSearchResult[][] = Array.from<VectorSearchResult[]>({
|
|
807
|
+
length: embeddings.length,
|
|
808
|
+
});
|
|
809
|
+
for (
|
|
810
|
+
let offset = 0;
|
|
811
|
+
offset < embeddings.length;
|
|
812
|
+
offset += MAX_SQL_BATCH_QUERIES
|
|
813
|
+
) {
|
|
814
|
+
const sliceEmbeddings = embeddings.slice(
|
|
815
|
+
offset,
|
|
816
|
+
offset + MAX_SQL_BATCH_QUERIES
|
|
817
|
+
);
|
|
818
|
+
const sliceLimits = limits.slice(offset, offset + MAX_SQL_BATCH_QUERIES);
|
|
819
|
+
const count = sliceEmbeddings.length;
|
|
820
|
+
const distanceSelects = sliceEmbeddings
|
|
821
|
+
.map((_, i) => `vec_distance_cosine(v.embedding, ?) AS d${i}`)
|
|
822
|
+
.join(", ");
|
|
823
|
+
const sql = `
|
|
824
|
+
SELECT g.variantId, g.mirrorHash, g.seq, v.input_hash AS inputHash, g.documentIds,
|
|
825
|
+
${distanceSelects}
|
|
826
|
+
FROM (
|
|
827
|
+
SELECT o.variant_id AS variantId, o.mirror_hash AS mirrorHash, o.seq,
|
|
828
|
+
json_group_array(o.document_id) AS documentIds
|
|
829
|
+
${spec.innerFrom}
|
|
830
|
+
JOIN content_chunks c${chunkKeyHint(db)} ON c.mirror_hash = o.mirror_hash AND c.seq = o.seq
|
|
831
|
+
WHERE ${spec.conditions.join(" AND ")}
|
|
832
|
+
GROUP BY o.variant_id, o.mirror_hash, o.seq
|
|
833
|
+
) g
|
|
834
|
+
CROSS JOIN vector_variants v${variantPartitionIdHint(db)}
|
|
835
|
+
ON v.partition_id = ? AND v.variant_id = g.variantId
|
|
836
|
+
`;
|
|
837
|
+
const queryVectors = sliceEmbeddings.map((e) => encodeEmbedding(e));
|
|
838
|
+
const heaps: CandidateRow[][] = sliceLimits.map(() => []);
|
|
839
|
+
const caps = sliceLimits.map((k) => Math.max(k + 32, k * 2));
|
|
840
|
+
let totalEligibleRows = 0;
|
|
841
|
+
const stmt = db.prepare<
|
|
842
|
+
Record<string, unknown>,
|
|
843
|
+
(Uint8Array | string | number)[]
|
|
844
|
+
>(sql);
|
|
845
|
+
try {
|
|
846
|
+
for (const row of stmt.iterate(
|
|
847
|
+
...queryVectors,
|
|
848
|
+
...spec.eligible.params,
|
|
849
|
+
...spec.params,
|
|
850
|
+
partitionId
|
|
851
|
+
)) {
|
|
852
|
+
totalEligibleRows++;
|
|
853
|
+
const variantId = row.variantId as number;
|
|
854
|
+
const mirrorHash = row.mirrorHash as string;
|
|
855
|
+
const seq = row.seq as number;
|
|
856
|
+
const inputHash = row.inputHash as string;
|
|
857
|
+
let parsedDocIds: number[] | null = null;
|
|
858
|
+
for (let q = 0; q < count; q++) {
|
|
859
|
+
const distance = row[`d${q}`] as number;
|
|
860
|
+
const heap = heaps[q]!;
|
|
861
|
+
const cap = caps[q]!;
|
|
862
|
+
// Quick reject before JSON.parse when heap is already full with a better worst element
|
|
863
|
+
if (heap.length >= cap) {
|
|
864
|
+
const worst = heap[0]!;
|
|
865
|
+
const aNull = distance === null;
|
|
866
|
+
const bNull = worst.distance === null;
|
|
867
|
+
if (!aNull && bNull) continue;
|
|
868
|
+
if (!aNull && !bNull && distance > worst.distance) continue;
|
|
869
|
+
}
|
|
870
|
+
parsedDocIds ??= JSON.parse(row.documentIds as string) as number[];
|
|
871
|
+
pushBoundedCandidate(heap, cap, {
|
|
872
|
+
variantId,
|
|
873
|
+
mirrorHash,
|
|
874
|
+
seq,
|
|
875
|
+
inputHash,
|
|
876
|
+
distance,
|
|
877
|
+
documentIds: parsedDocIds,
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
} finally {
|
|
882
|
+
stmt.finalize();
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
const sortedCandidates: CandidateRow[][] = [];
|
|
886
|
+
const hitCutoffs: boolean[] = [];
|
|
887
|
+
for (let q = 0; q < count; q++) {
|
|
888
|
+
const heap = heaps[q]!;
|
|
889
|
+
heap.sort(compareVariantCandidates);
|
|
890
|
+
let hitCutoff = false;
|
|
891
|
+
const kept: CandidateRow[] = [];
|
|
892
|
+
for (const row of heap) {
|
|
893
|
+
if (minScore !== undefined && 1 - row.distance < minScore) {
|
|
894
|
+
hitCutoff = true;
|
|
895
|
+
break;
|
|
896
|
+
}
|
|
897
|
+
kept.push(row);
|
|
898
|
+
}
|
|
899
|
+
sortedCandidates.push(kept);
|
|
900
|
+
hitCutoffs.push(hitCutoff);
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
proveUnknownOwners(model, proofs, sortedCandidates, batchOwners);
|
|
904
|
+
|
|
905
|
+
for (let q = 0; q < count; q++) {
|
|
906
|
+
const k = sliceLimits[q]!;
|
|
907
|
+
const results: VectorSearchResult[] = [];
|
|
908
|
+
for (const row of sortedCandidates[q]!) {
|
|
909
|
+
const proven = row.documentIds
|
|
910
|
+
.filter((id) =>
|
|
911
|
+
proofs.get(
|
|
912
|
+
vectorProofKey(model, id, row.mirrorHash, row.seq, row.inputHash)
|
|
913
|
+
)
|
|
914
|
+
)
|
|
915
|
+
.sort((a, b) => a - b);
|
|
916
|
+
if (proven.length === 0) continue;
|
|
917
|
+
results.push({
|
|
918
|
+
mirrorHash: row.mirrorHash,
|
|
919
|
+
seq: row.seq,
|
|
920
|
+
distance: row.distance,
|
|
921
|
+
documentIds: proven,
|
|
922
|
+
});
|
|
923
|
+
if (results.length === k) break;
|
|
924
|
+
}
|
|
925
|
+
if (
|
|
926
|
+
results.length < k &&
|
|
927
|
+
!hitCutoffs[q] &&
|
|
928
|
+
totalEligibleRows > caps[q]!
|
|
929
|
+
) {
|
|
930
|
+
allResults[offset + q] = searchVectorVariantsFromVariants(
|
|
931
|
+
db,
|
|
932
|
+
model,
|
|
933
|
+
partitionId,
|
|
934
|
+
sliceEmbeddings[q]!,
|
|
935
|
+
k,
|
|
936
|
+
minScore,
|
|
937
|
+
spec,
|
|
938
|
+
proofs,
|
|
939
|
+
batchOwners
|
|
940
|
+
);
|
|
941
|
+
} else {
|
|
942
|
+
allResults[offset + q] = results;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
return allResults;
|
|
317
947
|
}
|
|
318
948
|
|
|
319
949
|
/** Keep eligibility, provenance validation and ranking on one SQLite snapshot. */
|
|
@@ -325,7 +955,39 @@ export function searchVectorVariants(
|
|
|
325
955
|
k: number,
|
|
326
956
|
options: VectorSearchOptions = {}
|
|
327
957
|
): VectorSearchResult[] | null {
|
|
958
|
+
const inOuterTransaction = db.inTransaction;
|
|
959
|
+
return db.transaction(() =>
|
|
960
|
+
searchVectorVariantsInSnapshot(
|
|
961
|
+
db,
|
|
962
|
+
model,
|
|
963
|
+
dimensions,
|
|
964
|
+
embedding,
|
|
965
|
+
k,
|
|
966
|
+
options,
|
|
967
|
+
inOuterTransaction
|
|
968
|
+
)
|
|
969
|
+
)();
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
/** Keep batched eligibility, provenance validation and ranking on one SQLite snapshot. */
|
|
973
|
+
export function searchVectorVariantsBatch(
|
|
974
|
+
db: Database,
|
|
975
|
+
model: string,
|
|
976
|
+
dimensions: number,
|
|
977
|
+
embeddings: readonly Float32Array[],
|
|
978
|
+
limits: readonly number[],
|
|
979
|
+
options: VectorSearchOptions = {}
|
|
980
|
+
): VectorSearchResult[][] | null {
|
|
981
|
+
const inOuterTransaction = db.inTransaction;
|
|
328
982
|
return db.transaction(() =>
|
|
329
|
-
|
|
983
|
+
searchVectorVariantsBatchInSnapshot(
|
|
984
|
+
db,
|
|
985
|
+
model,
|
|
986
|
+
dimensions,
|
|
987
|
+
embeddings,
|
|
988
|
+
limits,
|
|
989
|
+
options,
|
|
990
|
+
inOuterTransaction
|
|
991
|
+
)
|
|
330
992
|
)();
|
|
331
993
|
}
|