@gmickel/gno 2.15.0 → 2.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/assets/skill/SKILL.md +27 -0
- package/assets/skill/cli-reference.md +24 -15
- package/assets/spa-production.json.gz +0 -0
- package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
- package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
- package/browser-extension/dist/manifest.json +1 -1
- package/package.json +1 -1
- package/spec/cli.md +43 -3
- package/spec/db/schema.sql +53 -1
- package/spec/mcp.md +9 -3
- package/spec/output-schemas/doctor.schema.json +27 -0
- package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
- package/spec/output-schemas/search-results.schema.json +14 -0
- package/spec/output-schemas/status.schema.json +22 -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/doctor.ts +101 -29
- package/src/cli/commands/embed.ts +2 -2
- package/src/cli/commands/links.ts +30 -6
- 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/commands/vec.ts +180 -8
- package/src/cli/config-cache.ts +86 -0
- package/src/cli/globals.ts +64 -0
- package/src/cli/program.ts +63 -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/config/types.ts +6 -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/retrieval-trace-session.ts +3 -0
- package/src/core/retrieval-trace.ts +9 -0
- package/src/core/section-parse.ts +16 -6
- package/src/core/typed-metadata.ts +68 -0
- package/src/core/vector-partition-status.ts +13 -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 +582 -116
- 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 +14 -6
- 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/explain.ts +17 -2
- package/src/pipeline/filters.ts +169 -33
- package/src/pipeline/graph-retrieval.ts +117 -61
- package/src/pipeline/hybrid.ts +626 -330
- 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/types.ts +7 -0
- package/src/pipeline/vsearch.ts +269 -154
- 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 +25 -5
- 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/038-vector-mirror-null-cosine.ts +47 -0
- package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
- package/src/store/migrations/index.ts +6 -0
- package/src/store/sqlite/adapter.ts +1260 -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/coarse-router.ts +312 -0
- package/src/store/vector/eligibility.ts +39 -0
- package/src/store/vector/lazy.ts +17 -0
- package/src/store/vector/partition-index.ts +333 -59
- package/src/store/vector/proof-cache.ts +209 -0
- package/src/store/vector/runtime-compat.ts +6 -0
- package/src/store/vector/sqlite-vec.ts +270 -162
- package/src/store/vector/stats.ts +37 -73
- package/src/store/vector/status.ts +169 -53
- package/src/store/vector/stored-vectors.ts +131 -45
- package/src/store/vector/types.ts +19 -0
- package/src/store/vector/v2-mirror.ts +669 -0
- package/src/store/vector/variant-search.ts +1187 -111
- package/src/store/vector/variants.ts +964 -160
- package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
package/src/store/types.ts
CHANGED
|
@@ -673,6 +673,11 @@ export interface GraphReferenceDocument {
|
|
|
673
673
|
contentType: string | null;
|
|
674
674
|
}
|
|
675
675
|
|
|
676
|
+
/** Lean scalar document identity for graph reconciliation (avoids SELECT * JSON parsing). */
|
|
677
|
+
export interface GraphDocumentIdentity extends GraphReferenceDocument {
|
|
678
|
+
active: boolean;
|
|
679
|
+
}
|
|
680
|
+
|
|
676
681
|
export interface GraphFrontmatterReference {
|
|
677
682
|
edgeType: string;
|
|
678
683
|
target: string;
|
|
@@ -700,6 +705,8 @@ export interface GraphReferenceStore {
|
|
|
700
705
|
readInventory(): GraphReferenceInventory[];
|
|
701
706
|
/** Active parsed-link sources matching any old/new target candidate. */
|
|
702
707
|
incomingLinkSources(identities: GraphReferenceDocument[]): number[];
|
|
708
|
+
/** Frontmatter-relation sources targeting any of the given `#docid` strings. */
|
|
709
|
+
docidReferenceSources?(docids: readonly string[]): number[];
|
|
703
710
|
writeInventory(inventory: GraphReferenceInventory): void;
|
|
704
711
|
complete(expectedEpoch: number): void;
|
|
705
712
|
}
|
|
@@ -774,6 +781,8 @@ export interface MemoryEligibleDocumentsOptions {
|
|
|
774
781
|
/** Normalized scopes; any-intersection semantics. */
|
|
775
782
|
scopes: string[];
|
|
776
783
|
excludeSuperseded?: boolean;
|
|
784
|
+
/** Optional positive row cap (e.g. `1` for existence probes). */
|
|
785
|
+
limit?: number;
|
|
777
786
|
}
|
|
778
787
|
|
|
779
788
|
/** Minimal identity of a memory record eligible for managed recall. */
|
|
@@ -2337,6 +2346,9 @@ export interface StorePort {
|
|
|
2337
2346
|
/** Missing capability or stale state requires full graph reconciliation. */
|
|
2338
2347
|
graphReferenceStore?(): GraphReferenceStore;
|
|
2339
2348
|
|
|
2349
|
+
/** Lean scalar document identities for graph reconciliation (avoids SELECT * JSON parsing). */
|
|
2350
|
+
listGraphDocumentIdentities?(): Promise<StoreResult<GraphDocumentIdentity[]>>;
|
|
2351
|
+
|
|
2340
2352
|
/**
|
|
2341
2353
|
* Get backlinks pointing to a document.
|
|
2342
2354
|
* Uses target_ref_norm for matching (wiki=normalized title with path fallbacks, markdown=rel_path).
|
|
@@ -2492,4 +2504,24 @@ export interface StorePort {
|
|
|
2492
2504
|
collection: string,
|
|
2493
2505
|
options: { mode: "stale" | "all"; activeModel?: string }
|
|
2494
2506
|
): Promise<StoreResult<EmbeddingCleanupStats>>;
|
|
2507
|
+
|
|
2508
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
2509
|
+
// LLM Cache (optional)
|
|
2510
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
2511
|
+
|
|
2512
|
+
/**
|
|
2513
|
+
* Read a non-expired value from the persistent `llm_cache` table.
|
|
2514
|
+
* Optional: mocks or read-only custom stores may omit this method.
|
|
2515
|
+
*/
|
|
2516
|
+
getLlmCache?(key: string): Promise<StoreResult<string | null>>;
|
|
2517
|
+
|
|
2518
|
+
/**
|
|
2519
|
+
* Write a value to the persistent `llm_cache` table.
|
|
2520
|
+
* Read-only connections and write-lock contention should no-op cleanly.
|
|
2521
|
+
*/
|
|
2522
|
+
setLlmCache?(
|
|
2523
|
+
key: string,
|
|
2524
|
+
value: string,
|
|
2525
|
+
expiresAt?: string
|
|
2526
|
+
): Promise<StoreResult<void>>;
|
|
2495
2527
|
}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cost-based vector search router and centralized constants (fn-235).
|
|
3
|
+
*
|
|
4
|
+
* Every path returns exact float32 cosine distances. Small scopes and every
|
|
5
|
+
* filtered search stay on existing exact paths; large unfiltered or
|
|
6
|
+
* collection-scoped searches route to the two-stage bit coarse mirror when
|
|
7
|
+
* enabled, clean, and self-checked above the recall floor.
|
|
8
|
+
*
|
|
9
|
+
* @module src/store/vector/coarse-router
|
|
10
|
+
*/
|
|
11
|
+
import type { Database } from "bun:sqlite";
|
|
12
|
+
|
|
13
|
+
import type { VectorSearchOptions } from "./types";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Single source of truth for fn-235 router and self-check constants.
|
|
17
|
+
* Enabled by default per owner decision (2026-11-23), gated by the per-index
|
|
18
|
+
* build-time recall self-check (floor 0.95) and controllable via
|
|
19
|
+
* `coarseVectorSearch: false`.
|
|
20
|
+
*/
|
|
21
|
+
export const COARSE_ROUTER_DEFAULTS = {
|
|
22
|
+
/** Default config switch (ON; set `coarseVectorSearch: false` to disable). */
|
|
23
|
+
enabledByDefault: true,
|
|
24
|
+
/** Exact-cost budget in microseconds (100 ms). */
|
|
25
|
+
exactBudgetUs: 100_000,
|
|
26
|
+
/** Exact SQL scan per-vector fixed overhead (µs). */
|
|
27
|
+
exactFixedUsPerVec: 1.05,
|
|
28
|
+
/** Exact SQL scan per-vector per-query cosine cost (µs). */
|
|
29
|
+
exactQueryUsPerVec: 0.82,
|
|
30
|
+
/** Oversample factor: coarseK = clamp(oversampleFactor * k, minCoarseK, maxCoarseK). */
|
|
31
|
+
oversampleFactor: 25,
|
|
32
|
+
minCoarseK: 200,
|
|
33
|
+
maxCoarseK: 500,
|
|
34
|
+
/** Maximum query k eligible for two-stage routing. */
|
|
35
|
+
maxCoarseQueryK: 40,
|
|
36
|
+
/** Maximum combined stage-1 candidates across multiple collections. */
|
|
37
|
+
maxMultiCollectionCandidates: 2000,
|
|
38
|
+
/** Build-time recall self-check constants. */
|
|
39
|
+
selfCheckQueries: 16,
|
|
40
|
+
selfCheckTopK: 10,
|
|
41
|
+
selfCheckCoarseK: 200,
|
|
42
|
+
selfCheckRecallFloor: 0.95,
|
|
43
|
+
} as const;
|
|
44
|
+
|
|
45
|
+
export type VectorRouteKind = "exact-sql" | "exact-vec0" | "coarse-bit";
|
|
46
|
+
|
|
47
|
+
export interface VectorRouteInfo {
|
|
48
|
+
route: VectorRouteKind;
|
|
49
|
+
/** Number of mirror rows in scope (or total partition variants when unavailable). */
|
|
50
|
+
mirrorRows: number;
|
|
51
|
+
/** Stage-1 coarse candidate count (coarse-bit only). */
|
|
52
|
+
coarseK?: number;
|
|
53
|
+
/** Distinct variants rescored in stage 2 (coarse-bit only). */
|
|
54
|
+
rescored?: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function isV2CompatibleDimensions(dimensions: number): boolean {
|
|
58
|
+
return Number.isInteger(dimensions) && dimensions > 0 && dimensions % 8 === 0;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function v2TableName(partitionId: string): string {
|
|
62
|
+
return `vec_v2_${partitionId}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function computeCoarseK(k: number): number {
|
|
66
|
+
return Math.max(
|
|
67
|
+
COARSE_ROUTER_DEFAULTS.minCoarseK,
|
|
68
|
+
Math.min(
|
|
69
|
+
COARSE_ROUTER_DEFAULTS.maxCoarseK,
|
|
70
|
+
COARSE_ROUTER_DEFAULTS.oversampleFactor * k
|
|
71
|
+
)
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function estimateExactCostUs(
|
|
76
|
+
mirrorRows: number,
|
|
77
|
+
queryCount: number
|
|
78
|
+
): number {
|
|
79
|
+
return (
|
|
80
|
+
mirrorRows *
|
|
81
|
+
(COARSE_ROUTER_DEFAULTS.exactFixedUsPerVec +
|
|
82
|
+
COARSE_ROUTER_DEFAULTS.exactQueryUsPerVec * Math.max(1, queryCount))
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function isPartitionAboveBudget(
|
|
87
|
+
mirrorRows: number,
|
|
88
|
+
queryCount = 1
|
|
89
|
+
): boolean {
|
|
90
|
+
return (
|
|
91
|
+
estimateExactCostUs(mirrorRows, queryCount) >
|
|
92
|
+
COARSE_ROUTER_DEFAULTS.exactBudgetUs
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Extract the collection scope requested by `options.eligibility`, or `[]` when
|
|
98
|
+
* unscoped. Deduplicates preserving order.
|
|
99
|
+
*/
|
|
100
|
+
export function extractRequestedCollections(
|
|
101
|
+
options: VectorSearchOptions
|
|
102
|
+
): string[] {
|
|
103
|
+
const e = options.eligibility;
|
|
104
|
+
if (!e) return [];
|
|
105
|
+
const raw = e.collections?.length
|
|
106
|
+
? e.collections
|
|
107
|
+
: e.collection
|
|
108
|
+
? [e.collection]
|
|
109
|
+
: [];
|
|
110
|
+
return [...new Set(raw)];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Rule 1 predicate: true when ANY filter beyond `collection` / `collections` is
|
|
115
|
+
* present. Matches `hasSelectiveEligibility` plus `eligibility.language` with
|
|
116
|
+
* `collection`/`collections` removed, ignoring `excludeMetadata` and
|
|
117
|
+
* `semanticMetadata` mode flags.
|
|
118
|
+
*/
|
|
119
|
+
export function hasNonCollectionFilter(options: VectorSearchOptions): boolean {
|
|
120
|
+
if (options.allowedMirrorHashes !== undefined) return true;
|
|
121
|
+
const e = options.eligibility;
|
|
122
|
+
if (!e) return false;
|
|
123
|
+
return Boolean(
|
|
124
|
+
e.language ||
|
|
125
|
+
e.memoryScopesAny?.length ||
|
|
126
|
+
e.excludeSuperseded ||
|
|
127
|
+
e.relPathPrefix ||
|
|
128
|
+
e.tagsAll?.length ||
|
|
129
|
+
e.tagsAny?.length ||
|
|
130
|
+
e.since ||
|
|
131
|
+
e.until ||
|
|
132
|
+
e.categories?.length ||
|
|
133
|
+
e.author ||
|
|
134
|
+
e.filter ||
|
|
135
|
+
e.exclude?.length
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Per-connection epoch-keyed cache for indexed `vector_partition_rows` counts.
|
|
140
|
+
const mirrorCountCaches = new WeakMap<
|
|
141
|
+
Database,
|
|
142
|
+
{ epoch: number; counts: Map<string, number> }
|
|
143
|
+
>();
|
|
144
|
+
|
|
145
|
+
function readVariantEpoch(db: Database): number | null {
|
|
146
|
+
try {
|
|
147
|
+
const row = db
|
|
148
|
+
.query<{ epoch: number }, []>(
|
|
149
|
+
"SELECT epoch FROM vector_variant_epoch WHERE id = 1"
|
|
150
|
+
)
|
|
151
|
+
.get();
|
|
152
|
+
return row ? row.epoch : null;
|
|
153
|
+
} catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Indexed row count `N` in `vector_partition_rows` for the scanned scope
|
|
160
|
+
* (unscoped, single collection, or multiple collections), cached per connection
|
|
161
|
+
* on `vector_variant_epoch.epoch` when not inside an uncommitted outer tx.
|
|
162
|
+
* Falls back to `vector_variants` count when `vector_partition_rows` is absent.
|
|
163
|
+
*/
|
|
164
|
+
export function countScopeMirrorRows(
|
|
165
|
+
db: Database,
|
|
166
|
+
partitionId: string,
|
|
167
|
+
collections: readonly string[],
|
|
168
|
+
hasV2Tables: boolean,
|
|
169
|
+
inOuterTransaction: boolean
|
|
170
|
+
): number {
|
|
171
|
+
const cacheKey = `${partitionId}\0${hasV2Tables ? "v2" : "v1"}\0${[...collections].sort().join("\0")}`;
|
|
172
|
+
let cache: { epoch: number; counts: Map<string, number> } | undefined;
|
|
173
|
+
if (!inOuterTransaction) {
|
|
174
|
+
const epoch = readVariantEpoch(db);
|
|
175
|
+
if (epoch !== null) {
|
|
176
|
+
cache = mirrorCountCaches.get(db);
|
|
177
|
+
if (cache?.epoch !== epoch || cache.counts.size > 4096) {
|
|
178
|
+
cache = { epoch, counts: new Map() };
|
|
179
|
+
mirrorCountCaches.set(db, cache);
|
|
180
|
+
}
|
|
181
|
+
const hit = cache.counts.get(cacheKey);
|
|
182
|
+
if (hit !== undefined) return hit;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
let count = 0;
|
|
187
|
+
if (hasV2Tables) {
|
|
188
|
+
if (collections.length === 0) {
|
|
189
|
+
count =
|
|
190
|
+
db
|
|
191
|
+
.query<{ n: number }, [string]>(
|
|
192
|
+
"SELECT COUNT(*) AS n FROM vector_partition_rows WHERE partition_id = ?"
|
|
193
|
+
)
|
|
194
|
+
.get(partitionId)?.n ?? 0;
|
|
195
|
+
} else if (collections.length === 1) {
|
|
196
|
+
count =
|
|
197
|
+
db
|
|
198
|
+
.query<{ n: number }, [string, string]>(
|
|
199
|
+
"SELECT COUNT(*) AS n FROM vector_partition_rows WHERE partition_id = ? AND collection = ?"
|
|
200
|
+
)
|
|
201
|
+
.get(partitionId, collections[0]!)?.n ?? 0;
|
|
202
|
+
} else {
|
|
203
|
+
count =
|
|
204
|
+
db
|
|
205
|
+
.query<{ n: number }, [string, string]>(
|
|
206
|
+
`SELECT COUNT(*) AS n FROM vector_partition_rows
|
|
207
|
+
WHERE partition_id = ?
|
|
208
|
+
AND collection IN (SELECT value FROM json_each(?))`
|
|
209
|
+
)
|
|
210
|
+
.get(partitionId, JSON.stringify(collections))?.n ?? 0;
|
|
211
|
+
}
|
|
212
|
+
} else {
|
|
213
|
+
count =
|
|
214
|
+
db
|
|
215
|
+
.query<{ n: number }, [string]>(
|
|
216
|
+
"SELECT COUNT(*) AS n FROM vector_variants WHERE partition_id = ?"
|
|
217
|
+
)
|
|
218
|
+
.get(partitionId)?.n ?? 0;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
cache?.counts.set(cacheKey, count);
|
|
222
|
+
return count;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export interface RouteDecisionInput {
|
|
226
|
+
options: VectorSearchOptions;
|
|
227
|
+
dimensions: number;
|
|
228
|
+
queryCount: number;
|
|
229
|
+
maxK: number;
|
|
230
|
+
collections: readonly string[];
|
|
231
|
+
mirrorRows: number;
|
|
232
|
+
/** Whether the v2 bit mirror exists and is clean (`dirty = 0`). */
|
|
233
|
+
v2MirrorClean: boolean;
|
|
234
|
+
/** Stored self-check recall, or null when unchecked. */
|
|
235
|
+
v2CheckRecall: number | null;
|
|
236
|
+
/** Persisted null_cosine flag (0 = known none, 1 = has null, null = unknown). */
|
|
237
|
+
nullCosineFlag: 0 | 1 | null;
|
|
238
|
+
/** Whether existing unscoped v1 exact-vec0 fast path is eligible. */
|
|
239
|
+
canUseV1ExactVec0: boolean;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export interface RouteDecision {
|
|
243
|
+
route: VectorRouteKind;
|
|
244
|
+
coarseK?: number;
|
|
245
|
+
reason: string;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Evaluate fn-235 router Rules 1–5 deterministically for a single or batched search.
|
|
250
|
+
*/
|
|
251
|
+
export function resolveVectorRoute(input: RouteDecisionInput): RouteDecision {
|
|
252
|
+
const exactRoute: VectorRouteKind = input.canUseV1ExactVec0
|
|
253
|
+
? "exact-vec0"
|
|
254
|
+
: "exact-sql";
|
|
255
|
+
|
|
256
|
+
// Rule 1: any filter beyond collection/collections -> exact SQL scan
|
|
257
|
+
if (hasNonCollectionFilter(input.options)) {
|
|
258
|
+
return { route: "exact-sql", reason: "filtered" };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Rule 2: explicit exact override, switch off, unsupported dims, missing/dirty/unchecked/below-floor v2, or null_cosine !== 0
|
|
262
|
+
if (input.options.exact === true) {
|
|
263
|
+
return { route: exactRoute, reason: "exact-override" };
|
|
264
|
+
}
|
|
265
|
+
const coarseEnabled =
|
|
266
|
+
input.options.coarseVectorSearch ?? COARSE_ROUTER_DEFAULTS.enabledByDefault;
|
|
267
|
+
if (!coarseEnabled) {
|
|
268
|
+
return { route: exactRoute, reason: "coarse-disabled" };
|
|
269
|
+
}
|
|
270
|
+
if (!isV2CompatibleDimensions(input.dimensions)) {
|
|
271
|
+
return { route: exactRoute, reason: "unsupported-dimensions" };
|
|
272
|
+
}
|
|
273
|
+
if (!input.v2MirrorClean) {
|
|
274
|
+
return { route: exactRoute, reason: "v2-mirror-unavailable" };
|
|
275
|
+
}
|
|
276
|
+
if (
|
|
277
|
+
input.v2CheckRecall === null ||
|
|
278
|
+
input.v2CheckRecall < COARSE_ROUTER_DEFAULTS.selfCheckRecallFloor
|
|
279
|
+
) {
|
|
280
|
+
return { route: exactRoute, reason: "v2-self-check-not-passed" };
|
|
281
|
+
}
|
|
282
|
+
if (input.nullCosineFlag !== 0) {
|
|
283
|
+
return { route: exactRoute, reason: "null-cosine-not-zero" };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Rule 3: estimated exact cost within 100 ms budget -> existing exact paths
|
|
287
|
+
if (
|
|
288
|
+
estimateExactCostUs(input.mirrorRows, input.queryCount) <=
|
|
289
|
+
COARSE_ROUTER_DEFAULTS.exactBudgetUs
|
|
290
|
+
) {
|
|
291
|
+
return { route: exactRoute, reason: "within-exact-budget" };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// Rule 4: k > maxCoarseQueryK (40) -> existing exact paths
|
|
295
|
+
if (input.maxK > COARSE_ROUTER_DEFAULTS.maxCoarseQueryK) {
|
|
296
|
+
return { route: exactRoute, reason: "k-above-max-coarse" };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const coarseK = computeCoarseK(input.maxK);
|
|
300
|
+
|
|
301
|
+
// Multi-collection candidate cap: collections.length * coarseK > 2000 -> exact
|
|
302
|
+
if (
|
|
303
|
+
input.collections.length > 1 &&
|
|
304
|
+
input.collections.length * coarseK >
|
|
305
|
+
COARSE_ROUTER_DEFAULTS.maxMultiCollectionCandidates
|
|
306
|
+
) {
|
|
307
|
+
return { route: exactRoute, reason: "multi-collection-cap" };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// Rule 5: two-stage bit coarse + exact float32 rescore
|
|
311
|
+
return { route: "coarse-bit", coarseK, reason: "coarse-bit" };
|
|
312
|
+
}
|
|
@@ -34,3 +34,42 @@ export function buildEligibleVectorQuery(
|
|
|
34
34
|
params,
|
|
35
35
|
};
|
|
36
36
|
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Set-driven eligible `(mirror_hash, seq)` domain for legacy vector search:
|
|
40
|
+
* deduplicates eligible `mirror_hash`es first and joins into `content_chunks`
|
|
41
|
+
* and `content_vectors` by key instead of scanning every vector row.
|
|
42
|
+
*/
|
|
43
|
+
export function buildEligibleVectorChunksQuery(
|
|
44
|
+
db: Database,
|
|
45
|
+
options: VectorSearchOptions
|
|
46
|
+
): { sql: string; params: (string | number)[] } {
|
|
47
|
+
const eligibility = options.eligibility ?? {};
|
|
48
|
+
const owners = buildEligibleDocumentQuery(
|
|
49
|
+
{ ...eligibility, semanticMetadata: true },
|
|
50
|
+
db
|
|
51
|
+
);
|
|
52
|
+
const mirrorConditions: string[] = [];
|
|
53
|
+
const params: (string | number)[] = [...owners.params];
|
|
54
|
+
if (options.allowedMirrorHashes !== undefined) {
|
|
55
|
+
mirrorConditions.push("em.mirror_hash IN (SELECT value FROM json_each(?))");
|
|
56
|
+
params.push(JSON.stringify(options.allowedMirrorHashes));
|
|
57
|
+
}
|
|
58
|
+
const chunkConditions: string[] = [];
|
|
59
|
+
if (eligibility.language) {
|
|
60
|
+
chunkConditions.push("cc.language = ?");
|
|
61
|
+
params.push(eligibility.language);
|
|
62
|
+
}
|
|
63
|
+
const mirrorFilter = mirrorConditions.length
|
|
64
|
+
? ` AND ${mirrorConditions.join(" AND ")}`
|
|
65
|
+
: "";
|
|
66
|
+
const chunkWhere = chunkConditions.length
|
|
67
|
+
? ` WHERE ${chunkConditions.join(" AND ")}`
|
|
68
|
+
: "";
|
|
69
|
+
return {
|
|
70
|
+
sql: `SELECT cc.mirror_hash, cc.seq
|
|
71
|
+
FROM (SELECT DISTINCT mirror_hash FROM (${owners.sql})) em
|
|
72
|
+
JOIN content_chunks cc ON cc.mirror_hash = em.mirror_hash${mirrorFilter}${chunkWhere}`,
|
|
73
|
+
params,
|
|
74
|
+
};
|
|
75
|
+
}
|
package/src/store/vector/lazy.ts
CHANGED
|
@@ -72,6 +72,23 @@ export async function createLazyVectorIndex(
|
|
|
72
72
|
async searchNearest(embedding, k, options) {
|
|
73
73
|
return (await get()).searchNearest(embedding, k, options);
|
|
74
74
|
},
|
|
75
|
+
async searchNearestBatch(embeddings, limits, options) {
|
|
76
|
+
const port = await get();
|
|
77
|
+
if (port.searchNearestBatch) {
|
|
78
|
+
return port.searchNearestBatch(embeddings, limits, options);
|
|
79
|
+
}
|
|
80
|
+
const results = [];
|
|
81
|
+
for (let i = 0; i < embeddings.length; i++) {
|
|
82
|
+
const res = await port.searchNearest(
|
|
83
|
+
embeddings[i]!,
|
|
84
|
+
limits[i]!,
|
|
85
|
+
options
|
|
86
|
+
);
|
|
87
|
+
if (!res.ok) return res;
|
|
88
|
+
results.push(res.value);
|
|
89
|
+
}
|
|
90
|
+
return { ok: true as const, value: results };
|
|
91
|
+
},
|
|
75
92
|
async rebuildVecIndex() {
|
|
76
93
|
return (await get()).rebuildVecIndex();
|
|
77
94
|
},
|