Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): text-space cosine re-score in SQL with the JavaScript rules (LHF wave 2 item 3)
garrytan55b4a6879976
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 4025361b60..829e3222fe 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -35,7 +35,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/graph-signals.ts` — per-query graph-signals helper. `applyGraphSignals(results, engine, opts)` runs as the 4th post-fusion stage (after backlink/salience/recency). Three boosts: `ADJACENCY_BOOST=1.05` (page linked from 2+ OTHER top-K results — local hub for THIS query), `CROSS_SOURCE_BOOST=1.10` (page linked from 2+ DIFFERENT sources — corroborated across team brains, dormant in single-source brains), `SESSION_DEMOTE=0.95` (3+ results from same chat session — keep the highest-scoring at full score, demote the rest). All three inherit the floor-ratio gate preventing weak pages from being boosted past strong ones via popularity. `computeScoreDistribution(results)` emits min/p25/p50/p75/p95/max + `reorder_band_width`. `sessionPrefix(slug)` extracts the chat-session anchor (`chat/2026-05-15-...`). Pure `pairedBootstrapPValue(deltas, resamples, rng)` exported for eval gates. Test seam via `adjacencyFn` DI. Fail-open: any error logs via `logGraphSignalsFailure` (JSONL audit via `audit-writer`) and returns the input array unchanged. Pinned by `test/search/graph-signals.test.ts` (incl. the IRON-RULE floor-gate guard). The atoms/ namespace is excluded from session diversification even when a later segment resembles a date or chat marker; daily, meeting and transcript siblings retain their existing demotion.-- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`, and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_search, filtered short pools need an exhaustion witness, and Postgres alone can use one exact fallback inside the remaining deadline. Hybrid and direct image query paths publish the scoped details and recall-affecting degraded stage; an exhausted genuine small corpus does not emit a false warning. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`. Both identity injections (alias hop and exact-lookup tier) take one `IdentityTierOpts` built once per request and skip any slug `isExcludedIdentity` rejects: caller `exclude_slugs` plus the resolved prefix excludes (`resolveHardExcludes`: defaults, `GBRAIN_SEARCH_EXCLUDE`, per-call prefixes, minus `include_slug_prefixes`), on all three return paths. Opt-in single-token hop (#5428; per-call `aliasTokenHop` or brain config `search.alias_token_hop=true`, read in the mode snapshot): when the whole query is not an alias, a query token that is the alias of exactly one person/company identity page (`isIdentityEntity`) moves that page to the front or injects it, at most two pages, order-preserving for the rest. Both post-rerank identity tiers (alias hop, `applyExactLookupTier`) are ORDER-PRESERVING: identity rows move to the front and every other row keeps its input (reranked) order — never a global re-sort by `score`, which is still the fusion score after reranking; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired — on an exact slug/title match OR a title / slug tail mentioned inside the query (`isTitleMentionedInQuery`), and `applyAliasMentionBoost` gives the same bounded boost to a present row whose declared alias occurs in the query (one batched `resolveAliases` over 1–5-token query n-grams, fail-open). **Fusion is page-grain:** `rrfFusion`/`rrfFusionWeighted` sum each list's vote per page `(source_id, slug)` (a list counts a page once, at its best rank) and the page's LEAD chunk (largest own vote; ties to the first list, a vector arm) carries the page's summed score while the page's other chunks keep their own votes — giving every chunk the page score let a page's second chunk crowd other pages out of chunk-limited results. Every arm is page-grain with its own representative chunk, so chunk-keyed fusion split a page's cross-arm agreement. **Detail:** only an EXPLICIT `detail: 'low'` hard-filters every arm to compiled truth (with the 2x boost and the zero-result escalation); an auto-detected `low` (entity intent) passes no SQL filter and applies `AUTO_LOW_COMPILED_TRUTH_TILT` (1.2x) via `compiledTruthFusionBoost`. The engine opts rebuild forwards `exclude_slugs`, `exclude_slug_prefixes` and `include_slug_prefixes` to every arm. A rejected keyword or title arm fails open and stamps `keyword_arm_failed` / `title_arm_failed` (reason `timeout | provider_error`) in `meta.degraded`, so MCP callers can tell a partial read from a clean miss. In `both` modality `cosineReScore` rescores image-arm rows in the image space (`embedding_image`, multimodal query vector); text rows keep the text column. The intent identity boosts (exact/mentioned title or slug, mentioned alias) run through one `applyIdentityBoosts` closure on the fused path and both keyword-only paths. Under unified multimodal routing the cosine rescore hydrates `embedding_multimodal` (the space the query was embedded in), and `cosineSimilarity` returns 0 for vectors of different lengths. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).+- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` (`search/cosine-rescore.ts`) scores the active column in SQL with the JS rules (a failure falls back to JS and sets `cosine_rescore`), and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_search, filtered short pools need an exhaustion witness, and Postgres alone can use one exact fallback inside the remaining deadline. Hybrid and direct image query paths publish the scoped details and recall-affecting degraded stage; an exhausted genuine small corpus does not emit a false warning. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`. Both identity injections (alias hop and exact-lookup tier) take one `IdentityTierOpts` built once per request and skip any slug `isExcludedIdentity` rejects: caller `exclude_slugs` plus the resolved prefix excludes (`resolveHardExcludes`: defaults, `GBRAIN_SEARCH_EXCLUDE`, per-call prefixes, minus `include_slug_prefixes`), on all three return paths. Opt-in single-token hop (#5428; per-call `aliasTokenHop` or brain config `search.alias_token_hop=true`, read in the mode snapshot): when the whole query is not an alias, a query token that is the alias of exactly one person/company identity page (`isIdentityEntity`) moves that page to the front or injects it, at most two pages, order-preserving for the rest. Both post-rerank identity tiers (alias hop, `applyExactLookupTier`) are ORDER-PRESERVING: identity rows move to the front and every other row keeps its input (reranked) order — never a global re-sort by `score`, which is still the fusion score after reranking; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired — on an exact slug/title match OR a title / slug tail mentioned inside the query (`isTitleMentionedInQuery`), and `applyAliasMentionBoost` gives the same bounded boost to a present row whose declared alias occurs in the query (one batched `resolveAliases` over 1–5-token query n-grams, fail-open). **Fusion is page-grain:** `rrfFusion`/`rrfFusionWeighted` sum each list's vote per page `(source_id, slug)` (a list counts a page once, at its best rank) and the page's LEAD chunk (largest own vote; ties to the first list, a vector arm) carries the page's summed score while the page's other chunks keep their own votes — giving every chunk the page score let a page's second chunk crowd other pages out of chunk-limited results. Every arm is page-grain with its own representative chunk, so chunk-keyed fusion split a page's cross-arm agreement. **Detail:** only an EXPLICIT `detail: 'low'` hard-filters every arm to compiled truth (with the 2x boost and the zero-result escalation); an auto-detected `low` (entity intent) passes no SQL filter and applies `AUTO_LOW_COMPILED_TRUTH_TILT` (1.2x) via `compiledTruthFusionBoost`. The engine opts rebuild forwards `exclude_slugs`, `exclude_slug_prefixes` and `include_slug_prefixes` to every arm. A rejected keyword or title arm fails open and stamps `keyword_arm_failed` / `title_arm_failed` (reason `timeout | provider_error`) in `meta.degraded`, so MCP callers can tell a partial read from a clean miss. In `both` modality `cosineReScore` rescores image-arm rows in the image space (`embedding_image`, multimodal query vector); text rows keep the text column. The intent identity boosts (exact/mentioned title or slug, mentioned alias) run through one `applyIdentityBoosts` closure on the fused path and both keyword-only paths. Under unified multimodal routing the cosine rescore hydrates `embedding_multimodal` (the space the query was embedded in), and `cosineSimilarity` returns 0 for vectors of different lengths. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). `hybridSearch` and `hybridSearchCached` are short orchestrators over the named stages in `src/core/search/hybrid/` (next entry); the file keeps the post-fusion boosts, RRF, cosine rescore, the cache-write drainer and the public helpers.- `src/core/search/hybrid/` — hybridSearch pipeline stages. `startVectorSide` runs modality, expansion and the vector arms alongside the lexical and relational arms (`runLexicalAndRelational`) on its own timer branch, `degraded` list and `vectorPoolMetaSink`; `joinVectorSide` merges its stamps and `expansionApplied` after the lexical ones, so `degraded[]` keeps the sequential order. Every other stage runs in a fixed order: `request.ts` (`resolveHybridRequest` builds a `HybridRequest` once: mode, embedding column, limits (per-arm pool from `perArmPoolLimit` in `src/core/search/eval-pool-depth.ts`: today's max(2·limit, floor, offset+limit) capped at 100 unless an eval sets `--eval-pool-depth`), intent, `searchOpts`, identity-tier opts, and the accumulators `vectorPoolUnderfill` / `expansionApplied` / `lastResultsCount` / `lastRank1Score` that stages write only as `req.<field>`; `emitHybridMeta`, `applyIdentityBoosts`), `arms.ts` (lexical, relational, modality + expansion, vector arms), `keyword-only.ts` (the no-provider and all-vector-arms-empty return paths; `opts.decide.keywordOnly`, the System One S6 fire retrieval, takes the no-provider path on purpose without the vector-unavailable degraded marker or warning), `rank.ts` (fusion + post-fusion boosts, A2 expansion, rerank + relational pin, identity tiers + adaptive return + autocut + relational slot, main return), `cache-stages.ts` (hybridSearchCached mode resolution, semantic-cache handle, skip gate, hit path; the result cache stays hard-disabled), `degraded.ts`, `effective-modes.ts`, `rerank-gate.ts` (the W3 pre-rerank grade; see the `crag.ts` entry in Core Search 2/2). The orchestrators wrap each stage in `req.timer` / `opts._timings` (stage-timings.ts). Stages import public helpers back from `hybrid.ts` at call time only (the `exact-lookup.ts` pattern); `hybrid.ts` exports nothing new. Pinned by `test/hybrid-golden.test.ts` (exact `(id, score)`, cold and warm).diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 901e94570e..dd3bb36bc8 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -1024,6 +1024,26 @@ export async function getEmbeddingsByChunkIds(exec: LegacyUnscopedRead, ids: numreturn result;}+/**+ * The text-space cosine re-score in SQL (`search/cosine-rescore.ts`): one+ * `(id, cosine)` row per hydrated chunk, the rows `getEmbeddingsByChunkIds`+ * returns (same active column, halfvec read exactly as vector, same+ * visibility). A hydrated vector whose dimensions differ from the query's,+ * or a zero-norm vector or query, scores 0 without reaching the operator, as+ * `cosineSimilarity` does; an absent or invisible chunk returns no row.+ */+export function cosineByChunkIdsStatement(ids: number[], column: string, query: Float32Array): { text: string; params: unknown[] } {+ if (!COLUMN_NAME_REGEX.test(column)) throw new EmbeddingColumnNotRegisteredError(column, []);+ const col = trustedSql(`cc.${quoteIdentifier(column)}`);+ const q = `[${Array.from(query).join(',')}]`;+ return renderFragment(sqlFragment`+ SELECT cc.id, CASE WHEN vector_dims(${col}::vector) <> ${query.length}::int OR vector_norm(${col}::vector) = 0 OR vector_norm(${q}::vector) = 0+ THEN 0::float8 ELSE 1 - (${col}::vector <=> ${q}::vector) END AS cosine+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE cc.id = ANY(${ids}::int[]) AND ${col} IS NOT NULL AND ${trustedSql(chunkVisibleFilter('p', 'cc'))}+ `);+}+/*** Evidence delivery: ONE batched read of chunk_index windows, keyed by* page_id. Every requested page is re-authorized with the search legs'diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 0fd0c290f8..88d4d32c57 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -467,6 +467,7 @@ async function buildRetrievalResponseMeta(...(m.answerability ? { answerability: m.answerability } : {}),...(m.relational_plan ? { relational_plan: m.relational_plan } : {}),...(m.rerank_gate ? { rerank_gate: m.rerank_gate } : {}),+ ...(m.cosine_rescore ? { cosine_rescore: m.cosine_rescore } : {}),} : {}),...((m?.degraded !== undefined || degraded.length > 0) ? { degraded } : {}),projection_readiness: readiness,diff --git a/src/core/search/cosine-rescore.ts b/src/core/search/cosine-rescore.tsnew file mode 100644index 0000000000..86eb498247--- /dev/null+++ b/src/core/search/cosine-rescore.ts@@ -0,0 +1,117 @@+/**+ * Cosine re-score after fusion: blend each row's normalized RRF score with+ * the raw cosine between the query and its chunk embedding.+ *+ * Text-space cosines are computed in SQL (LHF wave 2 item 3,+ * `cosineByChunkIdsStatement` in engine-sql/chunks.ts): shipping about a+ * hundred full embeddings to JavaScript was nearly all of the `fuse` stage.+ * The statement keeps the JavaScript rules: a row is hydrated when its chunk+ * is visible and has an embedding in the column; a hydrated vector with other+ * dimensions or zero norm scores 0; an unhydrated row blends with cosine 0;+ * and when nothing hydrates the rows come back untouched. If the statement+ * fails, this search falls back to hydrating the vectors and computing in+ * JavaScript (logged once per process with the SQLSTATE, and reported to the+ * caller through `onFallback`). The image space ('both' mode) stays in+ * JavaScript.+ */+import type { BrainEngine } from '../engine.ts';+import type { SearchResult } from '../types.ts';+import { cosineByChunkIdsStatement } from '../engine-sql/chunks.ts';+import { warnOncePerProcess } from '../utils.ts';++const DEBUG = process.env.GBRAIN_SEARCH_DEBUG === '1';++/** Text-space cosines by chunk id, computed by the database; absent ids did not hydrate. */+async function sqlCosines(engine: BrainEngine, ids: number[], column: string, query: Float32Array): Promise<Map<number, number>> {+ const { text, params } = cosineByChunkIdsStatement(ids, column, query);+ const rows = await engine.executeRaw<{ id: number; cosine: number }>(text, params);+ return new Map(rows.map(row => [Number(row.id), Number(row.cosine)]));+}++/** Text-space cosines by chunk id through the JavaScript path (hydrate, then `cosineSimilarity`). */+async function jsCosines(engine: BrainEngine, ids: number[], column: string, query: Float32Array): Promise<Map<number, number>> {+ const embeddings = await engine.getEmbeddingsByChunkIds(ids, column);+ return new Map([...embeddings].map(([id, embedding]) => [id, cosineSimilarity(query, embedding)]));+}++export async function cosineReScore(+ engine: BrainEngine,+ results: SearchResult[],+ queryEmbedding: Float32Array,+ column: string = 'embedding',+ imageSpace?: { queryEmbedding: Float32Array; column: string },+ attribute = false,+ onFallback?: () => void,+): Promise<SearchResult[]> {+ // 'both' mode: image-arm rows live in the image space (image column,+ // multimodal query vector); everything else in the text space.+ const inImageSpace = (r: SearchResult): boolean => imageSpace !== undefined && r.modality === 'image';+ const idsFor = (image: boolean) => results+ .filter(r => inImageSpace(r) === image)+ .map(r => r.chunk_id)+ .filter((id): id is number => id != null);+ const chunkIds = idsFor(false);+ const imageChunkIds = idsFor(true);++ if (chunkIds.length === 0 && imageChunkIds.length === 0) return results;++ let cosines = new Map<number, number>();+ let imageCosines = new Map<number, number>();+ try {+ // v0.36 (D9): score in the active column so rescore happens in the+ // same embedding space the HNSW just ranked in.+ if (chunkIds.length > 0) {+ try {+ cosines = await sqlCosines(engine, chunkIds, column, queryEmbedding);+ } catch (err) {+ const sqlstate = (err as { code?: unknown } | null)?.code;+ warnOncePerProcess('cosine-rescore-sql-fallback',+ `[gbrain] cosine re-score in SQL failed (SQLSTATE ${typeof sqlstate === 'string' ? sqlstate : 'unknown'}); computing it in JavaScript for this process's failing searches.`);+ onFallback?.();+ cosines = await jsCosines(engine, chunkIds, column, queryEmbedding);+ }+ }+ if (imageSpace && imageChunkIds.length > 0) {+ imageCosines = await jsCosines(engine, imageChunkIds, imageSpace.column, imageSpace.queryEmbedding);+ }+ } catch {+ // DB error is non-fatal, return results without re-scoring+ return results;+ }++ if (cosines.size === 0 && imageCosines.size === 0) return results;++ // Normalize RRF scores to 0-1 for blending+ const maxRrf = Math.max(...results.map(r => r.score));++ return results.map(r => {+ // #3695: a row with no hydrated chunk embedding (the synthetic chunkless+ // row for an embed_skip'd oversized page, or a chunk whose embedding did+ // not hydrate) goes through the same blend with cosine 0, so it never+ // keeps its raw post-RRF score next to rows on the blended [0, 1] scale.+ const cosine = r.chunk_id != null ? ((inImageSpace(r) ? imageCosines : cosines).get(r.chunk_id) ?? 0) : 0;+ const normRrf = maxRrf > 0 ? r.score / maxRrf : 0;+ const blended = 0.7 * normRrf + 0.3 * cosine;++ if (DEBUG) {+ console.error(`[search-debug] ${r.slug}:${r.chunk_id} cosine=${cosine.toFixed(4)} norm_rrf=${normRrf.toFixed(4)} blended=${blended.toFixed(4)}`);+ }++ // v0.46.15: stamp the raw cosine — evidence + --explain read it.+ return { ...r, score: blended, cosine, ...(attribute ? { blend_norm_rrf: normRrf } : {}) };+ }).sort((a, b) => b.score - a.score);+}++export function cosineSimilarity(a: Float32Array, b: Float32Array): number {+ // Vectors from different embedding spaces are incomparable: a length+ // mismatch used to yield a truncated dot product or NaN.+ if (a.length !== b.length) return 0;+ let dot = 0, magA = 0, magB = 0;+ for (let i = 0; i < a.length; i++) {+ dot += a[i] * b[i];+ magA += a[i] * a[i];+ magB += b[i] * b[i];+ }+ const denom = Math.sqrt(magA) * Math.sqrt(magB);+ return denom === 0 ? 0 : dot / denom;+}diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex f8d522f558..a8ba0b211c 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -1558,91 +1558,5 @@ export function rrfFusion(lists: SearchResult[][], k: number, applyBoost = true): { ...result, score });}-/**- * Cosine re-scoring: blend RRF score with query-chunk cosine similarity.- * Runs before dedup so semantically better chunks survive.- *- * Exported (only) for direct unit testing of the chunkless-row blend fix- * (#3695) — not part of the public search API surface.- */-export async function cosineReScore(- engine: BrainEngine,- results: SearchResult[],- queryEmbedding: Float32Array,- column: string = 'embedding',- imageSpace?: { queryEmbedding: Float32Array; column: string },- attribute = false,-): Promise<SearchResult[]> {- // 'both' mode: image-arm rows live in the image space (image column,- // multimodal query vector); everything else in the text space.- const inImageSpace = (r: SearchResult): boolean => imageSpace !== undefined && r.modality === 'image';- const idsFor = (image: boolean) => results- .filter(r => inImageSpace(r) === image)- .map(r => r.chunk_id)- .filter((id): id is number => id != null);- const chunkIds = idsFor(false);- const imageChunkIds = idsFor(true);-- if (chunkIds.length === 0 && imageChunkIds.length === 0) return results;-- let embeddingMap: Map<number, Float32Array>;- let imageEmbeddingMap = new Map<number, Float32Array>();- try {- // v0.36 (D9): hydrate from the active column so rescore happens in- // the same embedding space the HNSW just ranked in. Without this,- // a Voyage HNSW retrieval would HNSW-rank against Voyage vectors but- // rescore against OpenAI vectors → NaN or wrong rankings.- embeddingMap = chunkIds.length > 0 ? await engine.getEmbeddingsByChunkIds(chunkIds, column) : new Map();- if (imageSpace && imageChunkIds.length > 0) {- imageEmbeddingMap = await engine.getEmbeddingsByChunkIds(imageChunkIds, imageSpace.column);- }- } catch {- // DB error is non-fatal, return results without re-scoring- return results;- }-- if (embeddingMap.size === 0 && imageEmbeddingMap.size === 0) return results;-- // Normalize RRF scores to 0-1 for blending- const maxRrf = Math.max(...results.map(r => r.score));-- return results.map(r => {- // v0.46.28.0 (#3695): a row with no hydratable chunk embedding (the- // synthetic chunkless row for an embed_skip'd oversized page, or a- // chunk_id whose embedding didn't hydrate) used to return `r` untouched- // — keeping its RAW post-RRF score on a [0, ~2.0] scale while every- // other row got compressed onto the [0, 1.0] blended scale below. That- // gave chunkless rows a structural 2x head start (#3695's reported- // symptom: an empty-snippet embed_skip page outranking on-point- // results). Route it through the SAME blend with cosine=0 instead of- // excluding it — excluding would make embed_skip pages unsearchable,- // a different (undesired) behavior change.- const image = inImageSpace(r);- const chunkEmb = r.chunk_id != null ? (image ? imageEmbeddingMap : embeddingMap).get(r.chunk_id) : undefined;- const cosine = chunkEmb ? cosineSimilarity(image ? imageSpace!.queryEmbedding : queryEmbedding, chunkEmb) : 0;- const normRrf = maxRrf > 0 ? r.score / maxRrf : 0;- const blended = 0.7 * normRrf + 0.3 * cosine;-- if (DEBUG) {- console.error(`[search-debug] ${r.slug}:${r.chunk_id} cosine=${cosine.toFixed(4)} norm_rrf=${normRrf.toFixed(4)} blended=${blended.toFixed(4)}`);- }-- // v0.46.15: stamp the raw cosine — evidence + --explain read it (the- // hydration map is already paid for; zero extra probes).- return { ...r, score: blended, cosine, ...(attribute ? { blend_norm_rrf: normRrf } : {}) };- }).sort((a, b) => b.score - a.score);-}--export function cosineSimilarity(a: Float32Array, b: Float32Array): number {- // Vectors from different embedding spaces are incomparable: a length- // mismatch used to yield a truncated dot product or NaN.- if (a.length !== b.length) return 0;- let dot = 0, magA = 0, magB = 0;- for (let i = 0; i < a.length; i++) {- dot += a[i] * b[i];- magA += a[i] * a[i];- magB += b[i] * b[i];- }- const denom = Math.sqrt(magA) * Math.sqrt(magB);- return denom === 0 ? 0 : dot / denom;-}+/** Cosine re-scoring (search/cosine-rescore.ts); re-exported for the existing importers. */+export { cosineReScore, cosineSimilarity } from './cosine-rescore.ts';diff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.tsindex 0aa07975bf..2d2ca7ccc5 100644--- a/src/core/search/hybrid/rank.ts+++ b/src/core/search/hybrid/rank.ts@@ -156,7 +156,7 @@ export async function fuseArms(fused = await cosineReScore(engine, fused, queryEmbedding, unifiedDone ? 'embedding_multimodal' : resolvedCol.name,imageQueryEmbedding && !unifiedDone ? { queryEmbedding: imageQueryEmbedding, column: 'embedding_image' } : undefined,- attribute,+ attribute, () => { req.cosineRescore = 'js_fallback'; },);}@@ -511,6 +511,7 @@ export async function finalizeHybridResults(...(keywordArmConfidence ? { keyword_arm_confidence: keywordArmConfidence } : {}),metadata_boost_gate: metadataBoostGate,...(rerankGate ? { rerank_gate: rerankGate } : {}),+ ...(req.cosineRescore ? { cosine_rescore: req.cosineRescore } : {}),});return budgeted;}diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.tsindex 34c8871637..2505f3eba3 100644--- a/src/core/search/hybrid/request.ts+++ b/src/core/search/hybrid/request.ts@@ -78,6 +78,8 @@ export interface HybridRequest {vectorPoolUnderfill: HybridSearchMeta['vector_pool_underfilled'];/** #5989: the last bounded CJK keyword arm outcome. */keywordCandidates?: HybridSearchMeta['keyword_candidates'];+ /** Set when the cosine re-score fell back from SQL to JavaScript (search/cosine-rescore.ts). */+ cosineRescore?: HybridSearchMeta['cosine_rescore'];/** v0.25.0: whether query expansion actually produced variants (onMeta). */expansionApplied: boolean;/** Telemetry counters set at each return path before emitHybridMeta. */diff --git a/src/core/types.ts b/src/core/types.tsindex 8542a010c0..6882a68070 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -2221,6 +2221,8 @@ export interface HybridSearchMeta {* only when `search.reranker.gate` is not `off`.*/rerank_gate?: import('./search/hybrid/rerank-gate.ts').RerankGateMeta;+ /** `js_fallback` when the SQL cosine re-score failed and this search computed it in JavaScript (search/cosine-rescore.ts). */+ cosine_rescore?: 'js_fallback';/*** v0.32.x (search-lite): token budget enforcement metadata. Omitted when* no budget was applied (backward-compatible with pre-search-litediff --git a/test/e2e/cosine-rescore-sql-postgres.test.ts b/test/e2e/cosine-rescore-sql-postgres.test.tsnew file mode 100644index 0000000000..9dfbe834b8--- /dev/null+++ b/test/e2e/cosine-rescore-sql-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../search/cosine-rescore-sql.test.ts'));diff --git a/test/search/cosine-rescore-sql.test.ts b/test/search/cosine-rescore-sql.test.tsnew file mode 100644index 0000000000..a582eceb62--- /dev/null+++ b/test/search/cosine-rescore-sql.test.ts@@ -0,0 +1,163 @@+/**+ * LHF wave 2 item 3: the text-space cosine re-score runs in SQL and keeps+ * the JavaScript rules. Every case runs the SQL path on a real engine and the+ * JavaScript path (the same engine with the SQL statement failing) and+ * compares them: hydrated zero-norm and dimension-mismatched vectors score 0,+ * absent and invisible chunks stay unhydrated (cosine 0 in the blend), the+ * all-missing set comes back untouched, halfvec reads as its exact float4+ * values, the image space keeps the JavaScript path, and rows near the 0.8+ * evidence floor agree within tolerance. Measured differences are printed.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { SearchResult } from '../../src/core/types.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';+import { cosineReScore, cosineSimilarity } from '../../src/core/search/cosine-rescore.ts';+import { _resetWarnOnceForTests } from '../../src/core/utils.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';++const COSINE_TOLERANCE = 5e-6;+const SCORE_TOLERANCE = 2e-6;+const SLUGS = ['notes/random-a', 'notes/random-b', 'notes/near-floor', 'notes/zero', 'notes/missing', 'notes/deleted', 'notes/image'] as const;++function vectors(dims: number) {+ let seed = 7;+ const rand = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648) - 0.5;+ const random = () => Float32Array.from({ length: dims }, rand);+ const query = random();+ const qNorm = Math.hypot(...query);+ const orth = random();+ const dot = orth.reduce((s, x, i) => s + x * query[i]!, 0);+ for (let i = 0; i < dims; i++) orth[i] = orth[i]! - dot * query[i]! / (qNorm * qNorm);+ const oNorm = Math.hypot(...orth);+ const nearFloor = Float32Array.from({ length: dims }, (_, i) => 0.8 * query[i]! / qNorm + 0.6 * orth[i]! / oNorm);+ return { query, a: random(), b: random(), nearFloor, zero: new Float32Array(dims) };+}++const literal = (v: Float32Array) => `[${Array.from(v).join(',')}]`;+const failingSql = (engine: BrainEngine): BrainEngine => Object.assign(Object.create(engine), {+ executeRaw: async () => { throw Object.assign(new Error('forced'), { code: 'XX000' }); },+}) as BrainEngine;++for (const kind of testBackends()) {+ describe(`cosine re-score in SQL keeps the JavaScript rules (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let ids: Record<string, number>;+ let v: ReturnType<typeof vectors>;+ let imageVector: Float32Array;+ const diffs = { cosine: 0, score: 0 };++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }+ for (const slug of SLUGS) {+ await importFromContent(engine, slug, serializeMarkdown({}, `${slug} body text`, '', { type: 'note', title: slug, tags: [] }), { noEmbed: true, forceRechunk: true });+ }+ const rows = await engine.executeRaw<{ slug: string; id: number }>(`SELECT p.slug, cc.id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id`);+ ids = Object.fromEntries(rows.map(r => [r.slug, Number(r.id)]));+ const [{ dims }] = await engine.executeRaw<{ dims: number }>(+ `SELECT atttypmod AS dims FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding'`);+ v = vectors(Number(dims));+ const [{ dims: imageDims }] = await engine.executeRaw<{ dims: number }>(+ `SELECT atttypmod AS dims FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding_image'`);+ imageVector = vectors(Number(imageDims)).a;+ await engine.executeRaw(`ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_half halfvec(${Number(dims)})`);+ const set = async (slug: string, vec: Float32Array) => engine.executeRaw(+ `UPDATE content_chunks SET embedding = $1::vector, embedding_half = $1::vector::halfvec WHERE id = $2`, [literal(vec), ids[slug]]);+ await set('notes/random-a', v.a);+ await set('notes/random-b', v.b);+ await set('notes/near-floor', v.nearFloor);+ await set('notes/zero', v.zero);+ await set('notes/deleted', v.a);+ await set('notes/image', v.b);+ await engine.executeRaw(`UPDATE content_chunks SET embedding_image = $1::vector WHERE id = $2`, [literal(imageVector), ids['notes/image']]);+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'notes/deleted'`);+ }, 120_000);+ afterAll(async () => {+ console.log(`[cosine-rescore-sql ${kind}] max |SQL - JS|: cosine ${diffs.cosine.toExponential(2)}, score ${diffs.score.toExponential(2)}`);+ await close?.();+ });++ const rows = (slugs: readonly string[], modality?: Record<string, 'image'>): SearchResult[] => slugs.map((slug, i) => ({+ slug, page_id: i + 1, title: slug, type: 'note', chunk_text: slug, chunk_source: 'compiled_truth',+ chunk_id: ids[slug] ?? null, chunk_index: 0, score: 1 - i * 0.05, stale: false, ...(modality?.[slug] ? { modality: modality[slug] } : {}),+ } as SearchResult));++ async function both(input: SearchResult[], query: Float32Array, column = 'embedding', imageSpace?: { queryEmbedding: Float32Array; column: string }) {+ let fellBack = false;+ const sql = await cosineReScore(engine, input, query, column, imageSpace, false, () => { fellBack = true; });+ expect(fellBack).toBe(false);+ const warn = spyOn(console, 'warn').mockImplementation(() => {});+ const js = await cosineReScore(failingSql(engine), input, query, column, imageSpace);+ warn.mockRestore();+ expect(sql.map(r => r.slug).sort()).toEqual(js.map(r => r.slug).sort());+ for (const r of sql) {+ const j = js.find(x => x.slug === r.slug)!;+ const dc = Math.abs((r.cosine ?? 0) - (j.cosine ?? 0)), ds = Math.abs(r.score - j.score);+ diffs.cosine = Math.max(diffs.cosine, dc); diffs.score = Math.max(diffs.score, ds);+ expect(dc).toBeLessThanOrEqual(COSINE_TOLERANCE);+ expect(ds).toBeLessThanOrEqual(SCORE_TOLERANCE);+ }+ for (let i = 0; i < sql.length; i++) {+ if (sql[i]!.slug !== js[i]!.slug) expect(Math.abs(sql[i]!.score - js[i]!.score)).toBeLessThanOrEqual(SCORE_TOLERANCE);+ }+ return { sql, js };+ }++ test('random, zero-norm, missing and invisible chunks', async () => {+ const { sql } = await both(rows(['notes/random-a', 'notes/random-b', 'notes/zero', 'notes/missing', 'notes/deleted']), v.query);+ const by = Object.fromEntries(sql.map(r => [r.slug, r]));+ expect(by['notes/random-a']!.cosine).toBeCloseTo(cosineSimilarity(v.query, v.a), 5);+ expect(by['notes/zero']!.cosine).toBe(0);+ expect(by['notes/missing']!.cosine).toBe(0);+ expect(by['notes/deleted']!.cosine).toBe(0);+ });++ test('the all-missing set and a chunkless row come back untouched', async () => {+ const input = [...rows(['notes/missing', 'notes/deleted']), { ...rows(['notes/random-a'])[0]!, chunk_id: null } as unknown as SearchResult];+ expect(await cosineReScore(engine, input, v.query)).toBe(input);+ });++ test('a query of other dimensions or zero norm scores every hydrated row 0', async () => {+ for (const query of [v.query.slice(1), new Float32Array(v.query.length)]) {+ const { sql } = await both(rows(['notes/random-a', 'notes/near-floor', 'notes/missing']), query);+ expect(sql.every(r => r.cosine === 0)).toBe(true);+ expect(sql.map(r => r.slug)).toEqual(['notes/random-a', 'notes/near-floor', 'notes/missing']);+ }+ });++ test('a halfvec column reads its exact float4 values', async () => {+ await both(rows(['notes/random-a', 'notes/random-b', 'notes/near-floor', 'notes/zero', 'notes/missing']), v.query, 'embedding_half');+ });++ test('the image space keeps the JavaScript path beside SQL text rows', async () => {+ const { sql } = await both(rows(['notes/random-a', 'notes/image'], { 'notes/image': 'image' }), v.query, 'embedding', { queryEmbedding: imageVector, column: 'embedding_image' });+ expect(sql.find(r => r.slug === 'notes/image')!.cosine).toBeCloseTo(1, 6);+ });++ test('rows at the 0.8 evidence floor agree within tolerance', async () => {+ const { sql, js } = await both(rows(['notes/near-floor', 'notes/random-a']), v.query);+ const s = sql.find(r => r.slug === 'notes/near-floor')!.cosine!, j = js.find(r => r.slug === 'notes/near-floor')!.cosine!;+ expect(Math.abs(s - 0.8)).toBeLessThan(1e-5);+ if ((s >= 0.8) !== (j >= 0.8)) console.log(`[cosine-rescore-sql ${kind}] 0.8 floor flip within tolerance: SQL ${s} JS ${j}`);+ });++ test('a failed statement falls back to JavaScript, warns once with the SQLSTATE and reports it', async () => {+ _resetWarnOnceForTests();+ const warn = spyOn(console, 'warn').mockImplementation(() => {});+ let fallbacks = 0;+ const input = rows(['notes/random-a', 'notes/random-b']);+ const first = await cosineReScore(failingSql(engine), input, v.query, 'embedding', undefined, false, () => { fallbacks++; });+ await cosineReScore(failingSql(engine), input, v.query, 'embedding', undefined, false, () => { fallbacks++; });+ const messages = warn.mock.calls.map(c => String(c[0]));+ warn.mockRestore();+ expect(fallbacks).toBe(2);+ expect(messages.filter(m => m.includes('cosine re-score in SQL failed'))).toEqual([expect.stringContaining('SQLSTATE XX000')]);+ expect(first.find(r => r.slug === 'notes/random-a')!.cosine).toBeCloseTo(cosineSimilarity(v.query, v.a), 6);+ });+ });+}