Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): keep the HNSW plan by filtering content freshness after the candidate scan (#5824)
garrytan36583e1a7107
diff --git a/scripts/engine-sql-baseline.tsv b/scripts/engine-sql-baseline.tsvindex cfc1203adc..0383baf289 100644--- a/scripts/engine-sql-baseline.tsv+++ b/scripts/engine-sql-baseline.tsv@@ -45,7 +45,6 @@ method src/core/pglite-engine.ts PGLiteEngine.putRawDatamethod src/core/pglite-engine.ts PGLiteEngine.searchKeywordmethod src/core/pglite-engine.ts PGLiteEngine.searchKeywordChunksmethod src/core/pglite-engine.ts PGLiteEngine.searchTitles-method src/core/pglite-engine.ts PGLiteEngine.searchVectormethod src/core/pglite-engine.ts PGLiteEngine.setConfigmethod src/core/pglite-engine.ts PGLiteEngine.sweepDreamVerdictsmethod src/core/pglite-engine.ts PGLiteEngine.unsetConfig@@ -80,7 +79,6 @@ method src/core/postgres-engine.ts PostgresEngine.resolveFactsEmbeddingCastmethod src/core/postgres-engine.ts PostgresEngine.searchKeywordmethod src/core/postgres-engine.ts PostgresEngine.searchKeywordChunksmethod src/core/postgres-engine.ts PostgresEngine.searchTitles-method src/core/postgres-engine.ts PostgresEngine.searchVectormethod src/core/postgres-engine.ts PostgresEngine.setConfigmethod src/core/postgres-engine.ts PostgresEngine.sweepDreamVerdictsmethod src/core/postgres-engine.ts PostgresEngine.unsetConfigdiff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex e182ee4df0..410ce0c7bd 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -30,7 +30,7 @@ src/core/ai/gateway.ts chat 311 seed: W5 baseline, refactor wave 1 (decompositiosrc/core/bootstrap/harness.ts applyHarness 1167 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/brainstorm/orchestrator.ts _runBrainstormInner 412 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/check-resolvable.ts checkResolvable 419 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/config.ts loadConfigWithEngine 360 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)+src/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5824: search.vector_legacy_guard DB-plane mergesrc/core/context-engine.ts createGBrainContextEngine 519 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle.ts runCycle 1229 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 2ea539adb5..7765b5eaf0 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -20,10 +20,10 @@ src/core/engine.ts 2674 ratchet grown v0.46.26.0 megawave: relational/visibilitysrc/core/import-file.ts 2230 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode)src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)src/core/operations.ts 329 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base-src/core/pglite-engine.ts 3379 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts)-src/core/postgres-engine.ts 3398 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts)+src/core/pglite-engine.ts 3213 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166)+src/core/postgres-engine.ts 3242 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156)src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key-src/core/types.ts 2097 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts)+src/core/types.ts 2099 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 #5824: SearchOpts.vectorLegacyGuard rollback switchsrc/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keyssrc/commands/init.ts 1932 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-initsrc/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1525 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail readsrc/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)-src/core/config.ts 1806 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1)+src/core/config.ts 1812 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane mergesrc/core/bootstrap/harness.ts 2674 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 618 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy)diff --git a/src/core/config.ts b/src/core/config.tsindex d3d598d3c3..46de2add33 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -252,6 +252,8 @@ export interface GBrainConfig {adaptive_return_entity_max?: number;adaptive_return_other_max?: number;adaptive_return_min_keep?: number;+ /** #5824 rollback switch (search/vector-legacy-guard.ts); file > DB, env wins over both. */+ vector_legacy_guard?: boolean;};/**@@ -1153,6 +1155,8 @@ export async function loadConfigWithEngine(const n = Number(await dbStr(`search.${cap}`));if (Number.isFinite(n)) mergedSearch[cap] = n;}+ const dbVectorLegacyGuard = await dbBoolStrict('search.vector_legacy_guard');+ if (mergedSearch.vector_legacy_guard === undefined && dbVectorLegacyGuard !== undefined) mergedSearch.vector_legacy_guard = dbVectorLegacyGuard;if (Object.keys(mergedSearch).length > 0) {merged.search = mergedSearch;}@@ -1325,6 +1329,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// weak-graded query), and unlike crag_think it is reachable by remote// callers — attacker-shaped weak queries drive that spend (ship security// review). See docs/operations/spend-controls.md.+ // #5824 one-release rollback, latched per process (search/vector-legacy-guard.ts).+ 'search.vector_legacy_guard','search.adaptive_return','search.adaptive_return_entity_max','search.adaptive_return_other_max',diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex bfab6b4548..023eb50d52 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -71,8 +71,9 @@ import {} from './chronicle/ontology.ts';import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchExhausted } from './audit/batch-retry-audit.ts';import { runMigrations } from './migrate.ts';-import { hnswIndexExpected, supportsHnswIterativeScan } from './vector-index.ts';+import { supportsHnswIterativeScan } from './vector-index.ts';import { searchVectorPool, readVectorPool } from './search/vector-pool.ts';+import { buildVectorSearchStatement, VECTOR_EXTENSION_VERSION_SQL } from './search/vector-statement.ts';import { withVectorSettings } from './search/vector-settings.ts';import { PGLITE_SCHEMA_SQL, getPGLiteSchema } from './pglite-schema.ts';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';@@ -115,14 +116,11 @@ import { finalizeLastSeen } from './chronicle/last-seen.ts';import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';-import { unverifiedExtractionFragment } from './extraction-review.ts';import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';import { QUARANTINE_FILTER_FRAGMENT, quarantineFilterFragment } from './quarantine.ts';import {- normalizeEngineColumn,- buildVectorCastFragment,vectorCastSuffix,resolveActiveEmbeddingColumnFromEngine,resolveWriteColumnFromConfigRows,@@ -1725,40 +1723,14 @@ export class PGLiteEngine implements BrainEngine {async searchVector(embedding: Float32Array, opts?: SearchOpts): Promise<SearchResult[]> {const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());- const offset = opts?.offset || 0;- const vecStr = '[' + Array.from(embedding).join(',') + ']';- const detailFilter = opts?.detail === 'low' ? `AND cc.chunk_source = 'compiled_truth'` : '';-if (opts?.limit && opts.limit > searchLimitCap()) {console.warn(`[gbrain] Warning: search limit clamped from ${opts.limit} to ${searchLimitCap()}`);}-- // Two-stage CTE (v0.22): pure-distance ORDER BY in inner CTE preserves- // HNSW; outer SELECT re-ranks by raw_score * source_factor over the- // narrow candidate pool. innerLimit scales with offset to preserve the- // pagination contract. See postgres-engine.ts searchVector for rationale.- const boostMap = opts?.source_boosts ?? resolveBoostMap();- // Outer SELECT references the aliased CTE column. Aliasing the CTE as `hc`- // disambiguates the correlated subquery (`te.page_id = hc.page_id`) from- // the inner column. Without the alias, an unqualified `page_id` in the- // subquery's WHERE would lexically resolve back to `te.page_id` itself- // and degrade to `te.page_id = te.page_id` (always true), making every- // result stale=true. Codex caught this in adversarial review.- // Built on the bare `slug` output column: applied inside the `scored` CTE- // whose FROM is the single relation `hnsw_candidates`, so unqualified- // `slug` resolves cleanly (T1 per-page pool restructure).- // issue #160: guard predicate projected as `unverified_stub` in- // hnsw_candidates (parity with postgres-engine) so unverified stubs get- // factor 1.0, not the people/ 1.2x, inside the pre-LIMIT re-rank.- const sourceFactorCaseOnSlug = buildSourceFactorCase('slug', boostMap, opts?.detail, 'unverified_stub');- const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);- const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);- const resolvedColEarly = normalizeEngineColumn(opts?.embeddingColumn);- const indexed = hnswIndexExpected(resolvedColEarly.type, resolvedColEarly.dimensions);- const innerLimit = offset + Math.max(limit * 5, 100);- this.vectorIterativeScan ??= this.executeRaw<{ extversion: string }>(- `SELECT extversion FROM pg_extension WHERE extname = 'vector'`,- ).then(rows => supportsHnswIterativeScan(rows[0]?.extversion));+ // Same statement as postgres-engine (search/vector-statement.ts); the+ // PGLite dialect adds the timeline `stale` flag and has no exact fallback.+ const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding, limit, offset: opts?.offset || 0, opts });+ this.vectorIterativeScan ??= this.executeRaw<{ extversion: string }>(VECTOR_EXTENSION_VERSION_SQL)+ .then(rows => supportsHnswIterativeScan(rows[0]?.extversion));const probe = this.vectorIterativeScan;let iterative: boolean;try { iterative = await probe; }@@ -1766,154 +1738,16 @@ export class PGLiteEngine implements BrainEngine {if (this.vectorIterativeScan === probe) this.vectorIterativeScan = undefined;throw error;}- const params: unknown[] = [vecStr];- let extraFilter = '';- if (opts?.type) {- params.push(opts.type);- extraFilter += ` AND p.type = $${params.length}`;- }- if (opts?.exclude_slugs?.length) {- params.push(opts.exclude_slugs);- extraFilter += ` AND p.slug != ALL($${params.length}::text[])`;- }- if (opts?.language) {- params.push(opts.language);- extraFilter += ` AND cc.language = $${params.length}`;- }- if (opts?.symbolKind) {- params.push(opts.symbolKind);- extraFilter += ` AND cc.symbol_type = $${params.length}`;- }- // v0.33: multi-type filter for whoknows. Applied inside HNSW candidate- // CTE so the candidate pool consists only of typed pages — limit budget- // goes to person/company pages instead of being eaten by other types.- if (opts?.types && opts.types.length > 0) {- params.push(opts.types);- extraFilter += ` AND p.type = ANY($${params.length}::text[])`;- }- // v0.29.1 since/until parity (codex pass-1 #10). Filter applied INSIDE- // the inner CTE so HNSW's candidate pool already excludes out-of-range- // pages — preserves pagination contract.- if (opts?.afterDate) {- params.push(opts.afterDate);- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;- }- if (opts?.beforeDate) {- params.push(opts.beforeDate);- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;- }- // v0.34.1 (#861, F2 — P0 leak seal): source-isolation in the INNER CTE- // so HNSW candidate pool narrows before re-rank. Mirrors postgres-engine- // placement decision (codex flagged this during plan review).- if (opts?.sourceIds && opts.sourceIds.length > 0) {- params.push(opts.sourceIds);- extraFilter += ` AND p.source_id = ANY($${params.length}::text[])`;- } else if (opts?.sourceId) {- params.push(opts.sourceId);- extraFilter += ` AND p.source_id = $${params.length}`;- }-- if (resolvedColEarly.name === 'embedding') {- params.push(resolvedColEarly.embeddingModel || null);- extraFilter += ` AND ((cc.model=$${params.length} AND (cc.embedded_text_hash=md5(cc.chunk_text) OR cc.embedded_text_hash IS NULL))- OR ($${params.length}::text IS NULL AND NOT EXISTS(SELECT 1 FROM config WHERE key='embedding_migration.state')))`;- }- const innerLimitIdx = params.length;- params.push(innerLimit, limit, offset);- const innerLimitParam = `$${innerLimitIdx + 1}`;- const limitParam = `$${innerLimitIdx + 2}`;- const offsetParam = `$${innerLimitIdx + 3}`;-- // v0.26.5: visibility filter applied in the inner CTE so HNSW sees the- // same candidate count it always did. See postgres-engine.ts for rationale.- const visibilityClause = buildVisibilityClause('p', 's', opts);-- // v0.36 (D11): column routing via resolved descriptor. Engine doesn't- // read config — caller resolved at hybrid/op boundary. The cast SQL- // ($1::vector vs $1::halfvec(N)) comes from buildVectorCastFragment.- //- // v0.36 Phase 3: 'embedding_multimodal' is the unified column populated- // by `gbrain reindex --multimodal`. No modality filter — the column- // itself is the discriminator (only re-embedded rows have non-NULL).- const resolvedCol = resolvedColEarly;- const { col, castSql } = buildVectorCastFragment(resolvedCol);- let modalityFilter: string;- if (resolvedCol.name === 'embedding_image') {- modalityFilter = `AND cc.modality = 'image'`;- } else if (resolvedCol.name === 'embedding_multimodal') {- modalityFilter = '';- } else {- modalityFilter = `AND cc.modality = 'text'`;- }-- const candidateFrom = `FROM content_chunks cc- JOIN pages p ON p.id = cc.page_id- JOIN sources s ON s.id = p.source_id- WHERE cc.${col} IS NOT NULL ${modalityFilter} ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}`;- const rawQuery = `WITH hnsw_candidates AS (- SELECT- p.slug, p.id as page_id, p.title, p.type, p.source_id, p.updated_at,- p.effective_date, p.effective_date_source,- CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL- THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,- CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL- THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,- cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,- (${unverifiedExtractionFragment('p')}) AS unverified_stub,- 1 - (cc.${col} <=> ${castSql}) AS raw_score- ${candidateFrom}- ORDER BY cc.${col} <=> ${castSql}- LIMIT ${innerLimitParam}- ),- -- score as a select-list expr; inner ORDER BY stays pure-distance so- -- the HNSW index is usable.- scored AS (- SELECT *, raw_score * ${sourceFactorCaseOnSlug} AS score- FROM hnsw_candidates- ),- -- T1 (retrieval-maxpool incident): collapse to the best chunk PER PAGE- -- over the full candidate set before the user LIMIT. Shared builder with- -- postgres-engine + the keyword path so they cannot drift.- ${buildBestPerPagePoolCte('scored')},- page_results AS (- SELECT- bpp.slug, bpp.page_id, bpp.title, bpp.type, bpp.source_id,- bpp.effective_date, bpp.effective_date_source,- bpp.message_id, bpp.thread_id, bpp.source_subject,- bpp.chunk_id, bpp.chunk_index, bpp.chunk_text, bpp.chunk_source,- bpp.score,- CASE WHEN bpp.updated_at < (- SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = bpp.page_id- ) THEN true ELSE false END AS stale- FROM best_per_page bpp- -- v0.41.13: stable tiebreaker. When two chunks share a score (same- -- source-prefix boost + same cosine distance, the basis-vector + same-- -- source-prefix case in eval fixtures), older page_id wins. Without- -- this, planner choice + index presence can flip ordering between- -- master and feature branches that add unrelated indexes — see the- -- pages_dedup_idx (v95) regression that motivated this.- ORDER BY bpp.score DESC, bpp.page_id ASC, bpp.chunk_id ASC- LIMIT ${limitParam}- OFFSET ${offsetParam}- )- SELECT page_results.*, pool.candidate_pool- FROM (SELECT count(*)::int AS candidate_pool FROM hnsw_candidates) pool- LEFT JOIN page_results ON true- ORDER BY score DESC NULLS LAST, page_id ASC, chunk_id ASC`;-- const rows = await searchVectorPool(limit, innerLimit, iterative, indexed, 'pglite',+ const rows = await searchVectorPool(limit, stmt.innerLimit, iterative, stmt.indexed, 'pglite',async ({ innerLimit: requested, maxScanTuples }) => this.db.transaction(async tx => {return withVectorSettings(async (sql, values) => (await tx.query<Record<string, unknown>>(sql, values)).rows, iterative, requested, maxScanTuples, async () => {- const bound = [...params];- bound[innerLimitIdx] = requested;- return readVectorPool((await tx.query<Record<string, unknown>>(rawQuery, bound)).rows);+ const bound = [...stmt.params];+ bound[stmt.innerLimitIdx] = requested;+ return readVectorPool((await tx.query<Record<string, unknown>>(stmt.sql, bound)).rows);});}),async pool => {- const bound = [...params.slice(0, innerLimitIdx), pool + 1];- const { rows } = await this.db.query<{ eligible: number }>(`SELECT count(*)::int AS eligible FROM (- SELECT 1 ${candidateFrom} AND $1::text IS NOT NULL LIMIT $${bound.length}- ) eligible`, bound);+ const { rows } = await this.db.query<{ eligible: number }>(stmt.hasMoreSql, [...stmt.params.slice(0, stmt.innerLimitIdx), pool + 1]);return Number(rows[0].eligible) > pool;},opts?.onVectorPoolMeta,diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 9ff9cb0ea5..5777624c91 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -59,12 +59,11 @@ import { sanitizeForJsonb, sanitizeText, buildLinkRows, buildTimelineRows } fromimport { runMigrations } from './migrate.ts';import { SCHEMA_SQL } from './schema-embedded.generated.ts';import { verifySchema } from './schema-verify.ts';-import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, hnswIndexExpected, supportsHnswIterativeScan } from './vector-index.ts';-import { searchVectorPool, readVectorPool, remainingVectorBudget } from './search/vector-pool.ts';+import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, supportsHnswIterativeScan } from './vector-index.ts';+import { searchVectorPool, readVectorPool, remainingVectorBudget, type VectorPoolAttempt } from './search/vector-pool.ts';+import { buildVectorSearchStatement, SET_STATEMENT_TIMEOUT_SQL, VECTOR_EXTENSION_VERSION_SQL, type VectorSearchStatement } from './search/vector-statement.ts';import { withVectorSettings } from './search/vector-settings.ts';import {- normalizeEngineColumn,- buildVectorCastFragment,vectorCastSuffix,resolveActiveEmbeddingColumnFromEngine,resolveWriteColumnFromConfigRows,@@ -105,7 +104,6 @@ import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowTimport { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';-import { unverifiedExtractionFragment } from './extraction-review.ts';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from './engine-constants.ts';@@ -1408,226 +1406,27 @@ export class PostgresEngine implements BrainEngine {async searchVector(embedding: Float32Array, opts?: SearchOpts): Promise<SearchResult[]> {const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());- const offset = opts?.offset || 0;- const type = opts?.type;- const excludeSlugs = opts?.exclude_slugs;- const detailLow = opts?.detail === 'low';- const language = opts?.language;- const symbolKind = opts?.symbolKind;-if (opts?.limit && opts.limit > searchLimitCap()) {console.warn(`[gbrain] Warning: search limit clamped from ${opts.limit} to ${searchLimitCap()}`);}-- const vecStr = '[' + Array.from(embedding).join(',') + ']';-- // Two-stage CTE (v0.22): inner CTE keeps a pure-distance ORDER BY so- // the HNSW index stays usable. Folding source-boost into the inner- // ORDER BY would force a sequential scan over every chunk (seconds vs- // ~10ms with HNSW). Outer SELECT re-ranks the candidate pool by- // raw_score * source_factor.- //- // innerLimit scales with offset to preserve the pagination contract:- // a fixed cap of 100 would silently empty offset > 100.- const boostMap = opts?.source_boosts ?? resolveBoostMap();- // issue #160: the guard predicate is projected as `unverified_stub` in- // hnsw_candidates (frontmatter isn't otherwise available at re-rank), so- // unverified auto-extracted stubs get factor 1.0, not the people/ 1.2x.- const sourceFactorCaseOnSlug = buildSourceFactorCase('slug', boostMap, opts?.detail, 'unverified_stub');- const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);- const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);- // v0.36 (D11): column routing via resolved descriptor. Engine doesn't- // read config — caller (hybrid/op) resolved it and passed it in.- // normalizeEngineColumn accepts the legacy union (string literals,- // ResolvedColumn, undefined) and produces a canonical descriptor.- // (Hoisted above innerLimit so the escalation cap can key off the- // column's index eligibility.)- const resolvedCol = normalizeEngineColumn(opts?.embeddingColumn);- const indexed = hnswIndexExpected(resolvedCol.type, resolvedCol.dimensions);- const innerLimit = offset + Math.max(limit * 5, 100);- this.vectorIterativeScan ??= this.executeRaw<{ extversion: string }>(- `SELECT extversion FROM pg_extension WHERE extname = 'vector'`,- ).then(rows => supportsHnswIterativeScan(rows[0]?.extversion));- const probe = this.vectorIterativeScan;- let iterative: boolean;- try { iterative = await probe; }- catch (error) {- if (this.vectorIterativeScan === probe) this.vectorIterativeScan = undefined;- throw error;- }-- const params: unknown[] = [vecStr];- let typeClause = '';- if (type) {- params.push(type);- typeClause = `AND p.type = $${params.length}`;- }- // v0.33: multi-type filter for whoknows. AND-applied alongside the- // single-value `type` filter (callers can use either or both).- let typesClause = '';- if (opts?.types && opts.types.length > 0) {- params.push(opts.types);- typesClause = `AND p.type = ANY($${params.length}::text[])`;- }- let excludeSlugsClause = '';- if (excludeSlugs?.length) {- params.push(excludeSlugs);- excludeSlugsClause = `AND p.slug != ALL($${params.length}::text[])`;- }- let languageClause = '';- if (language) {- params.push(language);- languageClause = `AND cc.language = $${params.length}`;- }- let symbolKindClause = '';- if (symbolKind) {- params.push(symbolKind);- symbolKindClause = `AND cc.symbol_type = $${params.length}`;- }- // v0.29.1: since/until filter by effective date, with import-time fallback.- let afterDateClause = '';- if (opts?.afterDate) {- params.push(opts.afterDate);- afterDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;- }- let beforeDateClause = '';- if (opts?.beforeDate) {- params.push(opts.beforeDate);- beforeDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;- }- // v0.34.1 (#861, F2 — P0 leak seal): source-isolation in the INNER CTE- // specifically. Pushing the filter inside narrows the HNSW candidate set- // before re-rank; pushing it to the outer SELECT would force HNSW to- // over-fetch then post-filter, wasting candidate slots. Codex flagged- // this placement during plan review. Array form wins over scalar.- let sourceClause = '';- if (opts?.sourceIds && opts.sourceIds.length > 0) {- params.push(opts.sourceIds);- sourceClause = `AND p.source_id = ANY($${params.length}::text[])`;- } else if (opts?.sourceId) {- params.push(opts.sourceId);- sourceClause = `AND p.source_id = $${params.length}`;- }- let generationClause = '';- if (resolvedCol.name === 'embedding') {- params.push(resolvedCol.embeddingModel || null);- generationClause = `AND ((cc.model=$${params.length} AND (cc.embedded_text_hash=md5(cc.chunk_text) OR cc.embedded_text_hash IS NULL))- OR ($${params.length}::text IS NULL AND NOT EXISTS(SELECT 1 FROM config WHERE key='embedding_migration.state')))`;- }- params.push(innerLimit);- const innerLimitIdx = params.length - 1; // mutated by the escalation loop- const innerLimitParam = `$${params.length}`;- params.push(limit);- const limitParam = `$${params.length}`;- params.push(offset);- const offsetParam = `$${params.length}`;-- // v0.26.5: visibility filter applied in the inner CTE so the HNSW index- // sees the same row count it always did. Pulling the predicate to the- // outer SELECT would force the HNSW scan to over-fetch and post-filter,- // wasting candidate slots on hidden rows.- const visibilityClause = buildVisibilityClause('p', 's', opts);-- // v0.36 Phase 3: 'embedding_multimodal' is the unified column populated- // by `gbrain reindex --multimodal`. Carries BOTH text and image content- // in Voyage multimodal-3 space — no modality filter; the column itself- // is the discriminator (rows without embedding_multimodal aren't searched).- const { col, castSql } = buildVectorCastFragment(resolvedCol);- let modalityFilter: string;- if (resolvedCol.name === 'embedding_image') {- modalityFilter = `AND cc.modality = 'image'`;- } else if (resolvedCol.name === 'embedding_multimodal') {- modalityFilter = '';- } else {- modalityFilter = `AND cc.modality = 'text'`;- }-- const candidateFrom = `FROM content_chunks cc- JOIN pages p ON p.id = cc.page_id- JOIN sources s ON s.id = p.source_id- WHERE cc.${col} IS NOT NULL ${modalityFilter}- ${detailLow ? `AND cc.chunk_source = 'compiled_truth'` : ''}- ${typeClause}- ${typesClause}- ${excludeSlugsClause}- ${languageClause}- ${symbolKindClause}- ${afterDateClause}- ${beforeDateClause}- ${sourceClause}- ${generationClause}- ${hardExcludeClause}- ${visibilityClause}`;- const rawQuery = (exact: boolean) => `- WITH hnsw_candidates AS (- SELECT- p.slug, p.id as page_id, p.title, p.type, p.source_id,- p.effective_date, p.effective_date_source,- CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL- THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,- CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL- THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,- cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,- (${unverifiedExtractionFragment('p')}) AS unverified_stub,- 1 - (cc.${col} <=> ${castSql}) AS raw_score- ${candidateFrom}- ORDER BY ${exact ? '(' : ''}cc.${col} <=> ${castSql}${exact ? ') + 0' : ''}- LIMIT ${innerLimitParam}- ),- -- score computed as a select-list expr (NOT in the inner ORDER BY, which- -- must stay pure-distance so the HNSW index is usable).- scored AS (- SELECT *, raw_score * ${sourceFactorCaseOnSlug} AS score- FROM hnsw_candidates- ),- -- T1 (retrieval-maxpool incident): collapse to the best chunk PER PAGE- -- over the full candidate set before the user LIMIT, so a page's strong- -- chunk can't be crowded out of the result by weaker chunks of other- -- pages. Shared builder keeps keyword + vector × postgres + pglite in lockstep.- ${buildBestPerPagePoolCte('scored')},- page_results AS (- SELECT- slug, page_id, title, type, source_id,- effective_date, effective_date_source,- message_id, thread_id, source_subject,- chunk_id, chunk_index, chunk_text, chunk_source,- score,- false AS stale- FROM best_per_page- -- v0.41.13: stable tiebreaker for tied scores. See pglite-engine for- -- rationale (basis-vector test fixtures, planner-dependent ordering).- ORDER BY score DESC, page_id ASC, chunk_id ASC- LIMIT ${limitParam}- OFFSET ${offsetParam}- )- SELECT page_results.*, pool.candidate_pool- FROM (SELECT count(*)::int AS candidate_pool FROM hnsw_candidates) pool- LEFT JOIN page_results ON true- ORDER BY score DESC NULLS LAST, page_id ASC, chunk_id ASC- `;-- const rows = await searchVectorPool(limit, innerLimit, iterative, indexed, 'postgres',- async ({ innerLimit: requested, maxScanTuples, remainingMs, exact }) => {- const deadline = performance.now() + remainingMs;- return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async tx => {- return withVectorSettings((sql, values) => tx.unsafe(sql, values as Parameters<typeof tx.unsafe>[1]), iterative, requested, maxScanTuples, async () => {- const bound = [...params];- bound[innerLimitIdx] = exact ? null : requested;- await tx`SELECT set_config('statement_timeout', ${String(remainingVectorBudget(deadline))}, true)`;- return { ...readVectorPool(await tx.unsafe(rawQuery(exact), bound as Parameters<typeof tx.unsafe>[1])), exhausted: exact };- }, deadline);- }, { alwaysTransaction: true });+ // Two-stage CTE (v0.22): the candidate CTE keeps a pure-distance ORDER BY+ // so the HNSW index stays usable; the outer stages re-rank by source+ // factor. Statement shape, freshness placement (#5824) and pool counts+ // live in search/vector-statement.ts, shared with PGLite and doctor.+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts });+ const iterative = await this.vectorIterativeScanSupported();+ const rows = await searchVectorPool(limit, stmt.innerLimit, iterative, stmt.indexed, 'postgres',+ async attempt => {+ const batch = await this.runVectorAttempt(stmt, attempt, iterative, opts, (tx, sql, bound) => tx.unsafe(sql, bound));+ return { ...readVectorPool(batch), exhausted: attempt.exact };},async (pool, remainingMs) => {const deadline = performance.now() + remainingMs;return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async tx => {const previous = await tx`SHOW statement_timeout`;- await tx`SELECT set_config('statement_timeout', ${String(remainingVectorBudget(deadline))}, true)`;- const bound = [...params.slice(0, innerLimitIdx), pool + 1];- const rows = await tx.unsafe(`SELECT count(*)::int AS eligible FROM (- SELECT 1 ${candidateFrom} AND $1::text IS NOT NULL LIMIT $${bound.length}- ) eligible`, bound as Parameters<typeof tx.unsafe>[1]);- await tx`SELECT set_config('statement_timeout', ${previous[0].statement_timeout}, true)`;+ await tx.unsafe(SET_STATEMENT_TIMEOUT_SQL, [String(remainingVectorBudget(deadline))]);+ const rows = await tx.unsafe(stmt.hasMoreSql, [...stmt.params.slice(0, stmt.innerLimitIdx), pool + 1] as Parameters<typeof tx.unsafe>[1]);+ await tx.unsafe(SET_STATEMENT_TIMEOUT_SQL, [previous[0].statement_timeout]);return Number(rows[0].eligible) > pool;}, { alwaysTransaction: true });},@@ -1636,6 +1435,51 @@ export class PostgresEngine implements BrainEngine {return rows.map(rowToSearchResult);}+ /**+ * EXPLAIN (no ANALYZE) of the first ANN attempt `searchVector` runs for+ * these options: the same statement, bound parameters, scoped read+ * transaction and scan settings, through `tx.unsafe` (the vendored driver+ * never prepares it). Used by doctor `vector_plan` and the plan-proof E2E.+ */+ async explainVectorSearch(embedding: Float32Array, opts?: SearchOpts): Promise<Record<string, unknown>> {+ const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts });+ const iterative = await this.vectorIterativeScanSupported();+ const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: 2_000, remainingMs: 8_000, exact: false };+ const [row] = await this.runVectorAttempt(stmt, attempt, iterative, opts, (tx, sql, bound) => tx.unsafe(`EXPLAIN (FORMAT JSON) ${sql}`, bound));+ const plan = row?.['QUERY PLAN'];+ return (Array.isArray(plan) ? plan[0] : plan) as Record<string, unknown>;+ }++ private async vectorIterativeScanSupported(): Promise<boolean> {+ this.vectorIterativeScan ??= this.executeRaw<{ extversion: string }>(VECTOR_EXTENSION_VERSION_SQL)+ .then(rows => supportsHnswIterativeScan(rows[0]?.extversion));+ const probe = this.vectorIterativeScan;+ try { return await probe; }+ catch (error) {+ if (this.vectorIterativeScan === probe) this.vectorIterativeScan = undefined;+ throw error;+ }+ }++ private runVectorAttempt(+ stmt: VectorSearchStatement,+ { innerLimit, maxScanTuples, remainingMs, exact }: VectorPoolAttempt,+ iterative: boolean,+ opts: SearchOpts | undefined,+ run: (tx: ReturnType<typeof postgres>, sql: string, bound: Parameters<ReturnType<typeof postgres>['unsafe']>[1]) => Promise<Record<string, unknown>[]>,+ ): Promise<Record<string, unknown>[]> {+ const deadline = performance.now() + remainingMs;+ return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async tx => {+ return withVectorSettings((sql, values) => tx.unsafe(sql, values as Parameters<typeof tx.unsafe>[1]), iterative, innerLimit, maxScanTuples, async () => {+ const bound = [...stmt.params];+ bound[stmt.innerLimitIdx] = exact ? null : innerLimit;+ await tx.unsafe(SET_STATEMENT_TIMEOUT_SQL, [String(remainingVectorBudget(deadline))]);+ return run(tx, exact ? stmt.exactSql : stmt.sql, bound as Parameters<typeof tx.unsafe>[1]);+ }, deadline);+ }, { alwaysTransaction: true });+ }+async getEmbeddingsByChunkIds(ids: number[], column: string = 'embedding'): Promise<Map<number, Float32Array>> {return chunksImpl.getEmbeddingsByChunkIds(unscopedExecutor(this.engineSql, 'chunks: unscoped on master (EO4 inventory)'), ids, column);}diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.tsindex d720b8d6f7..00849d620b 100644--- a/src/core/search/hybrid/request.ts+++ b/src/core/search/hybrid/request.ts@@ -21,6 +21,7 @@ import { pushDegraded } from './degraded.ts';import { recordSearchTelemetry } from '../telemetry.ts';import { resolveBoostMap, resolveHardExcludes } from '../source-boost.ts';import { resolveEmbeddingColumn } from '../embedding-column.ts';+import { resolveVectorLegacyGuard } from '../vector-legacy-guard.ts';import { resolveSearchDateBounds } from '../date-bounds.ts';import { type DecideSearchContext, decideMetaFor, resolveAndLaunchDecide } from '../decide-stage.ts';import { applySearchIntent } from '../decide-retrieval.ts';@@ -225,6 +226,8 @@ export async function resolveHybridRequest(// it never has to read config. Engines normalize string-or-descriptor// via normalizeEngineColumn; the descriptor path is the strict one.embeddingColumn: resolvedCol,+ // #5824 rollback switch, latched once per process from env/config.+ vectorLegacyGuard: resolveVectorLegacyGuard(cfgForColumn),// D2 fix (fix/title-retrieval-arm, Reviewer F1): the hybrid keyword arm// is a recall arm — opt in to the engine's AND→OR zero-recall fallback.// Direct searchKeyword consumers (countMentions, link-extraction, eval)diff --git a/src/core/search/vector-legacy-guard.ts b/src/core/search/vector-legacy-guard.tsnew file mode 100644index 0000000000..d2bb2268ce--- /dev/null+++ b/src/core/search/vector-legacy-guard.ts@@ -0,0 +1,55 @@+/**+ * #5824 one-release rollback switch. When on, the vector statement keeps the+ * content-freshness guard inside the HNSW candidate CTE (the pre-fix shape,+ * which large Postgres brains plan as a sequential scan). Retired in the next+ * wave.+ *+ * Read from `GBRAIN_VECTOR_LEGACY_GUARD` (wins when set) or the config key+ * `search.vector_legacy_guard`, resolved once per process by the caller that+ * builds search options, so the owning service (serve, autopilot, worker)+ * picks a change up on restart and the hot path never re-reads config.+ */+import type { GBrainConfig } from '../config.ts';++export const VECTOR_LEGACY_GUARD_ENV = 'GBRAIN_VECTOR_LEGACY_GUARD';+export const VECTOR_LEGACY_GUARD_KEY = 'search.vector_legacy_guard';++export interface VectorLegacyGuardSetting {+ enabled: boolean;+ via: 'env' | 'config' | null;+}++function parseFlag(value: string | undefined): boolean | undefined {+ const v = value?.trim().toLowerCase();+ if (!v) return undefined;+ if (v === '1' || v === 'true' || v === 'on' || v === 'yes') return true;+ if (v === '0' || v === 'false' || v === 'off' || v === 'no') return false;+ return undefined;+}++/** What the setting says right now (doctor reports it; search uses the per-process latch). */+export function readVectorLegacyGuard(cfg: Pick<GBrainConfig, 'search'> | null | undefined, env: NodeJS.ProcessEnv = process.env): VectorLegacyGuardSetting {+ const fromEnv = parseFlag(env[VECTOR_LEGACY_GUARD_ENV]);+ if (fromEnv !== undefined) return { enabled: fromEnv, via: 'env' };+ if (cfg?.search?.vector_legacy_guard === true) return { enabled: true, via: 'config' };+ return { enabled: false, via: null };+}++let resolved: boolean | undefined;++/** First call decides for the process; logs once to stderr when the guard is active. */+export function resolveVectorLegacyGuard(cfg: Pick<GBrainConfig, 'search'> | null | undefined): boolean {+ if (resolved !== undefined) return resolved;+ const setting = readVectorLegacyGuard(cfg);+ resolved = setting.enabled;+ if (resolved) {+ console.error(`[gbrain] vector legacy guard active (${setting.via === 'env' ? VECTOR_LEGACY_GUARD_ENV : VECTOR_LEGACY_GUARD_KEY}): `+ + 'vector search keeps the pre-#5824 freshness guard inside the HNSW candidate scan; remove it after upgrading.');+ }+ return resolved;+}++/** @internal test seam */+export function _resetVectorLegacyGuardForTests(): void {+ resolved = undefined;+}diff --git a/src/core/search/vector-pool.ts b/src/core/search/vector-pool.tsindex 6200d0e899..36e05690d7 100644--- a/src/core/search/vector-pool.ts+++ b/src/core/search/vector-pool.ts@@ -2,7 +2,10 @@ import type { SearchOpts } from '../types.ts';export interface VectorPoolBatch {rows: Record<string, unknown>[];+ /** Raw candidate rows the window returned; a short window means the index ran dry. */candidatePool: number;+ /** Candidates that passed the content-freshness filter outside the CTE; defaults to `candidatePool`. */+ eligiblePool?: number;exhausted?: boolean;}@@ -45,7 +48,7 @@ export async function searchVectorPool(if (batch.candidatePool < innerLimit) {if (!indexed) return batch.rows;if (remaining() === 0) { reason = 'deadline'; break; }- if (!(await hasMore(batch.candidatePool, remaining()))) return batch.rows;+ if (!(await hasMore(batch.eligiblePool ?? batch.candidatePool, remaining()))) return batch.rows;}if (escalations >= 3 || (indexed && !iterative)) break;innerLimit = Math.min(innerLimit * 4, Math.max(initialLimit, 20_000));@@ -66,8 +69,10 @@ export async function searchVectorPool(}export function readVectorPool(rows: Record<string, unknown>[]): VectorPoolBatch {- return {+ const batch: VectorPoolBatch = {rows: rows.filter(row => row.page_id != null),candidatePool: Number(rows[0]?.candidate_pool ?? 0),};+ if (rows[0]?.eligible_pool != null) batch.eligiblePool = Number(rows[0].eligible_pool);+ return batch;}diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.tsnew file mode 100644index 0000000000..4ebc46379f--- /dev/null+++ b/src/core/search/vector-statement.ts@@ -0,0 +1,187 @@+/**+ * The vector-search statement, built once for both engines, the doctor+ * `vector_plan` check and the plan-proof E2E so the SQL they run or EXPLAIN+ * can never drift (#5824).+ *+ * Content freshness (`embedded_text_hash = md5(chunk_text)`) is an expression+ * Postgres has no statistics for. Inside the HNSW candidate CTE the planner+ * estimates it at 0.5% selectivity, expects to walk most of the index for+ * `ORDER BY embedding <=> $q LIMIT n`, and picks a sequential scan that hits+ * the vector deadline on large brains. On an HNSW-indexed column the+ * candidate CTE therefore carries only the well-estimated model check+ * (relaxed variant); freshness is projected as `hash_current` and filtered in+ * `scored`, so a stale-text chunk still never reaches results. The guarded+ * variant (freshness inside the CTE) serves non-indexed columns, the legacy+ * guard rollback, the exact fallback and the `hasMore` exhaustion witness.+ *+ * `candidate_pool` counts raw candidate rows (a full raw window escalates, a+ * short one means the index ran dry); `eligible_pool` counts the fresh ones+ * and is what `hasMore` compares against its guarded count.+ */+import type { SearchOpts } from '../types.ts';+import { hnswIndexExpected } from '../vector-index.ts';+import { unverifiedExtractionFragment } from '../extraction-review.ts';+import { buildVectorCastFragment, normalizeEngineColumn } from './embedding-column.ts';+import { resolveBoostMap, resolveHardExcludes } from './source-boost.ts';+import { buildBestPerPagePoolCte, buildHardExcludeClause, buildSourceFactorCase, buildVisibilityClause } from './sql-ranking.ts';++export const VECTOR_EXTENSION_VERSION_SQL = `SELECT extversion FROM pg_extension WHERE extname = 'vector'`;+export const SET_STATEMENT_TIMEOUT_SQL = `SELECT set_config('statement_timeout', $1, true)`;++export interface VectorSearchStatementInput {+ dialect: 'postgres' | 'pglite';+ embedding: Float32Array;+ limit: number;+ offset: number;+ opts?: SearchOpts;+}++export interface VectorSearchStatement {+ /** ANN statement; `params[innerLimitIdx]` is the candidate window. */+ sql: string;+ /** Exact scan with the full guard (`+ 0` disables the index); bind `null` at innerLimitIdx. */+ exactSql: string;+ /** Guarded eligibility witness; bind `[...params.slice(0, innerLimitIdx), pool + 1]`. */+ hasMoreSql: string;+ params: unknown[];+ innerLimitIdx: number;+ innerLimit: number;+ indexed: boolean;+ /** True when freshness moved out of the candidate CTE (indexed `embedding`, legacy guard off). */+ relaxed: boolean;+}++export function buildVectorSearchStatement(input: VectorSearchStatementInput): VectorSearchStatement {+ const { dialect, limit, offset, opts } = input;+ const resolvedCol = normalizeEngineColumn(opts?.embeddingColumn);+ const indexed = hnswIndexExpected(resolvedCol.type, resolvedCol.dimensions);+ // innerLimit scales with offset to preserve the pagination contract.+ const innerLimit = offset + Math.max(limit * 5, 100);+ // issue #160: the guard predicate is projected as `unverified_stub` so+ // unverified auto-extracted stubs get factor 1.0 inside the re-rank.+ const sourceFactorCaseOnSlug = buildSourceFactorCase('slug', opts?.source_boosts ?? resolveBoostMap(), opts?.detail, 'unverified_stub');+ const hardExcludeClause = buildHardExcludeClause('p.slug', resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes));++ const params: unknown[] = ['[' + Array.from(input.embedding).join(',') + ']'];+ const bind = (value: unknown) => { params.push(value); return `$${params.length}`; };+ const filters: string[] = [];+ if (opts?.detail === 'low') filters.push(`AND cc.chunk_source = 'compiled_truth'`);+ if (opts?.type) filters.push(`AND p.type = ${bind(opts.type)}`);+ // v0.33: multi-type filter for whoknows, AND-applied with `type`.+ if (opts?.types && opts.types.length > 0) filters.push(`AND p.type = ANY(${bind(opts.types)}::text[])`);+ if (opts?.exclude_slugs?.length) filters.push(`AND p.slug != ALL(${bind(opts.exclude_slugs)}::text[])`);+ if (opts?.language) filters.push(`AND cc.language = ${bind(opts.language)}`);+ if (opts?.symbolKind) filters.push(`AND cc.symbol_type = ${bind(opts.symbolKind)}`);+ // v0.29.1: since/until filter by effective date, with import-time fallback.+ // Spelled per column rather than as COALESCE(effective_date, updated_at,+ // created_at) <op> $n: same rows, but each arm has column statistics. The+ // planner estimates a since+until pair on the COALESCE at 0.5% and drops+ // the HNSW index exactly as it did for the freshness guard (#5824).+ const dateBound = (op: string, value: string) => {+ const bound = `${bind(value)}::text::timestamptz`;+ return `AND (p.effective_date ${op} ${bound} OR (p.effective_date IS NULL AND (p.updated_at ${op} ${bound} OR (p.updated_at IS NULL AND p.created_at ${op} ${bound}))))`;+ };+ if (opts?.afterDate) filters.push(dateBound(opts.afterDateInclusive ? '>=' : '>', opts.afterDate));+ if (opts?.beforeDate) filters.push(dateBound(opts.beforeDateInclusive ? '<=' : '<', opts.beforeDate));+ // v0.34.1 (#861): source isolation in the INNER CTE narrows the HNSW+ // candidate set before re-rank. Array form wins over scalar.+ if (opts?.sourceIds && opts.sourceIds.length > 0) filters.push(`AND p.source_id = ANY(${bind(opts.sourceIds)}::text[])`);+ else if (opts?.sourceId) filters.push(`AND p.source_id = ${bind(opts.sourceId)}`);++ let modelParam: string | undefined;+ if (resolvedCol.name === 'embedding') modelParam = bind(resolvedCol.embeddingModel || null);+ const relaxed = indexed && modelParam !== undefined && opts?.vectorLegacyGuard !== true;+ const preMigration = modelParam ? `(${modelParam}::text IS NULL AND NOT EXISTS(SELECT 1 FROM config WHERE key='embedding_migration.state'))` : '';+ const hashCurrent = `(cc.embedded_text_hash=md5(cc.chunk_text) OR cc.embedded_text_hash IS NULL)`;+ const guardedGeneration = modelParam ? `AND ((cc.model=${modelParam} AND ${hashCurrent})+ OR ${preMigration})` : '';+ const relaxedGeneration = modelParam ? `AND (cc.model=${modelParam} OR ${preMigration})` : '';++ const innerLimitParam = bind(innerLimit);+ const innerLimitIdx = params.length - 1;+ const limitParam = bind(limit);+ const offsetParam = bind(offset);++ // v0.36 Phase 3: 'embedding_multimodal' carries text and image content, so+ // the column itself is the discriminator; the others filter by modality.+ const { col, castSql } = buildVectorCastFragment(resolvedCol);+ const modalityFilter = resolvedCol.name === 'embedding_image' ? `AND cc.modality = 'image'`+ : resolvedCol.name === 'embedding_multimodal' ? '' : `AND cc.modality = 'text'`;+ // v0.26.5: visibility in the inner CTE so hidden rows never take candidate slots.+ const visibilityClause = buildVisibilityClause('p', 's', opts);+ const candidateFrom = (generation: string) => `FROM content_chunks cc+ JOIN pages p ON p.id = cc.page_id+ JOIN sources s ON s.id = p.source_id+ WHERE cc.${col} IS NOT NULL ${modalityFilter}+ ${filters.join('\n ')}+ ${generation}+ ${hardExcludeClause}+ ${visibilityClause}`;+ const freshFilter = `${modelParam}::text IS NULL OR hash_current`;++ const statement = (exact: boolean) => {+ const relax = relaxed && !exact;+ return `+ WITH hnsw_candidates AS (+ SELECT+ p.slug, p.id as page_id, p.title, p.type, p.source_id,${dialect === 'pglite' ? ' p.updated_at,' : ''}+ p.effective_date, p.effective_date_source,+ CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL+ THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,+ CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL+ THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,+ cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,+ (${unverifiedExtractionFragment('p')}) AS unverified_stub,${relax ? `+ ${hashCurrent} AS hash_current,` : ''}+ 1 - (cc.${col} <=> ${castSql}) AS raw_score+ ${candidateFrom(relax ? relaxedGeneration : guardedGeneration)}+ ORDER BY ${exact ? '(' : ''}cc.${col} <=> ${castSql}${exact ? ') + 0' : ''}+ LIMIT ${innerLimitParam}+ ),+ -- score computed as a select-list expr (NOT in the inner ORDER BY, which+ -- must stay pure-distance so the HNSW index is usable).+ scored AS (+ SELECT *, raw_score * ${sourceFactorCaseOnSlug} AS score+ FROM hnsw_candidates${relax ? `+ WHERE ${freshFilter}` : ''}+ ),+ -- Collapse to the best chunk PER PAGE over the full candidate set before+ -- the user LIMIT (shared with the keyword arm in both engines).+ ${buildBestPerPagePoolCte('scored')},+ page_results AS (+ SELECT+ bpp.slug, bpp.page_id, bpp.title, bpp.type, bpp.source_id,+ bpp.effective_date, bpp.effective_date_source,+ bpp.message_id, bpp.thread_id, bpp.source_subject,+ bpp.chunk_id, bpp.chunk_index, bpp.chunk_text, bpp.chunk_source,+ bpp.score,+ ${dialect === 'pglite' ? `CASE WHEN bpp.updated_at < (+ SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = bpp.page_id+ ) THEN true ELSE false END` : 'false'} AS stale+ FROM best_per_page bpp+ -- v0.41.13: stable tiebreaker for tied scores (planner-independent order).+ ORDER BY bpp.score DESC, bpp.page_id ASC, bpp.chunk_id ASC+ LIMIT ${limitParam}+ OFFSET ${offsetParam}+ )+ SELECT page_results.*, pool.candidate_pool, pool.eligible_pool+ FROM (SELECT count(*)::int AS candidate_pool, ${relax ? `(count(*) FILTER (WHERE ${freshFilter}))::int` : 'count(*)::int'} AS eligible_pool+ FROM hnsw_candidates) pool+ LEFT JOIN page_results ON true+ ORDER BY score DESC NULLS LAST, page_id ASC, chunk_id ASC+ `;+ };++ return {+ sql: statement(false),+ exactSql: statement(true),+ hasMoreSql: `SELECT count(*)::int AS eligible FROM (+ SELECT 1 ${candidateFrom(guardedGeneration)} AND $1::text IS NOT NULL LIMIT $${innerLimitIdx + 1}+ ) eligible`,+ params,+ innerLimitIdx,+ innerLimit,+ indexed,+ relaxed,+ };+}diff --git a/src/core/types.ts b/src/core/types.tsindex e0470d5050..d2a1131549 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1131,6 +1131,8 @@ export interface SearchOpts extends PageReadPolicy {* call, only when bounded work ended before exhaustion could be proved.*/onVectorPoolMeta?: (m: VectorPoolMeta) => void;+ /** #5824 rollback: keep the freshness guard inside the HNSW candidate CTE. Latched by the caller (search/vector-legacy-guard.ts). */+ vectorLegacyGuard?: boolean;/*** v0.42 — intent-aware adaptive return-sizing. `true` enables with config/* default caps; an object overrides caps per-call; omitted/`false` = offdiff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.tsindex d513085d8a..d523f5382d 100644--- a/test/config-search-registry.test.ts+++ b/test/config-search-registry.test.ts@@ -32,6 +32,7 @@ const DIRECTLY_READ_SINGLETONS = ['search.adaptive_return_entity_max','search.adaptive_return_other_max','search.adaptive_return_min_keep',+ 'search.vector_legacy_guard', // search/vector-legacy-guard.ts via loadConfigWithEngine'search.crag_escalation', // ops/search.ts'search.crag_think', // ops/search.ts'search.return_unit', // search/evidence-delivery.tsdiff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.jsonindex 41cc34a2c9..3e1b41599d 100644--- a/test/fixtures/goldens/exports/runtime.json+++ b/test/fixtures/goldens/exports/runtime.json@@ -221,6 +221,7 @@"executeRaw","executeRawDirect","expireFact",+ "explainVectorSearch","findAnomalies","findByTitleFuzzy","findCandidateDuplicates",@@ -332,6 +333,7 @@"rlsScopeBindingEnabled","runMigration","runUnsafe",+ "runVectorAttempt","searchKeyword","searchKeywordChunks","searchTakes",@@ -364,6 +366,7 @@"upsertChunks","upsertEventProjection","upsertFile",+ "vectorIterativeScanSupported","withReservedConnection","withScopedReadTransaction","writeContradictionsRun"diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 5944223737..872d959cbb 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -971,6 +971,7 @@"executeRaw: <T = Record<string, unknown>>(sql: string, params?: unknown[], opts?: { signal?: AbortSignal; }) => Promise<T[]>","executeRawDirect: <T = Record<string, unknown>>(sql: string, params?: unknown[], opts?: { signal?: AbortSignal; }) => Promise<T[]>","expireFact: (id: number, opts?: { supersededBy?: number; at?: Date; }) => Promise<boolean>",+ "explainVectorSearch: (embedding: Float32Array, opts?: SearchOpts) => Promise<Record<string, unknown>>","findAnomalies: (opts: AnomaliesOpts) => Promise<AnomalyResult[]>","findByTitleFuzzy: (name: string, dirPrefix?: string, minSimilarity?: number, sourceId?: string) => Promise<{ slug: string; similarity: number; } | null>","findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; }) => Promise<FactRow[]>",@@ -1079,8 +1080,10 @@"private resolveFactsEmbeddingCast","private rlsScopeBindingEnabled","private runUnsafe",+ "private runVectorAttempt","private transactionOn","private vectorIterativeScan",+ "private vectorIterativeScanSupported","private withScopedReadTransaction","purgeDeletedPages: (olderThanHours: number, opts?: { dryRun?: boolean; }) => Promise<{ slugs: string[]; count: number; pages?: { slug: string; deleted_at: Date; }[]; }>","putContradictionCacheEntry: (opts: { chunk_a_hash: string; chunk_b_hash: string; model_id: string; prompt_version: string; truncation_policy: string; verdict: Record<string, unknown>; ttl_seconds?: number; }) => Promise<void>",@@ -1277,6 +1280,7 @@"types?: string[] | undefined","until?: string | undefined","useCache?: boolean | undefined",+ "vectorLegacyGuard?: boolean | undefined","walkDepth?: number | undefined"],"name": "SearchOpts"@@ -2454,7 +2458,7 @@"retrieval_reflex_volunteer?: boolean | undefined","retrieval_reflex_window_turns?: number | undefined","schema_pack?: string | undefined",- "search?: { adaptive_return?: boolean; adaptive_return_entity_max?: number; adaptive_return_other_max?: number; adaptive_return_min_keep?: number; } | undefined",+ "search?: { adaptive_return?: boolean; adaptive_return_entity_max?: number; adaptive_return_other_max?: number; adaptive_return_min_keep?: number; vector_legacy_guard?: boolean; } | undefined","search_embedding_column?: string | undefined","self_upgrade?: { mode?: \"auto\" | \"notify\" | \"off\"; mode_prompted?: boolean; quiet_hours?: { start?: number; end?: number; tz?: string; }; failed_versions?: string[]; attempting_version?: string; last_check_ts?: number; last_applied_version?: string; } | undefined","storage?: unknown",@@ -6503,6 +6507,7 @@"types?: string[] | undefined","until?: string | undefined","useCache?: boolean | undefined",+ "vectorLegacyGuard?: boolean | undefined","walkDepth?: number | undefined"],"name": "HybridSearchOpts"@@ -7887,6 +7892,7 @@"types?: string[] | undefined","until?: string | undefined","useCache?: boolean | undefined",+ "vectorLegacyGuard?: boolean | undefined","walkDepth?: number | undefined"],"name": "SearchOpts"diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.jsonindex f82b4a4899..63a67ef97a 100644--- a/test/fixtures/goldens/sql-text/_classification.json+++ b/test/fixtures/goldens/sql-text/_classification.json@@ -11,11 +11,11 @@"out-of-scope:dream-verdicts": 3,"out-of-scope:eval-capture": 5,"out-of-scope:ingest-log": 2,- "out-of-scope:internal-helper (private; exercised through public callers)": 15,+ "out-of-scope:internal-helper (private; exercised through public callers)": 17,"out-of-scope:lifecycle (connection, pool, transaction, raw seams)": 14,"out-of-scope:no-sql-stub": 1,"out-of-scope:raw-data": 2,- "out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)": 2,+ "out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)": 3,"out-of-scope:shared-read-enrichment (already one SQL copy in search/read-enrichment.ts)": 8,"out-of-scope:stats-health (brain-wide aggregates)": 2,"pages": 33,@@ -64,6 +64,7 @@"executeRaw": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)","executeRawDirect": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)","expireFact": "facts",+ "explainVectorSearch": "out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)","findAnomalies": "salience","findByTitleFuzzy": "pages","findCandidateDuplicates": "facts",@@ -175,6 +176,7 @@"rlsScopeBindingEnabled": "out-of-scope:internal-helper (private; exercised through public callers)","runMigration": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)","runUnsafe": "out-of-scope:internal-helper (private; exercised through public callers)",+ "runVectorAttempt": "out-of-scope:internal-helper (private; exercised through public callers)","searchKeyword": "cjk-search","searchKeywordChunks": "cjk-search","searchTakes": "takes",@@ -207,6 +209,7 @@"upsertChunks": "chunks","upsertEventProjection": "timeline","upsertFile": "files",+ "vectorIterativeScanSupported": "out-of-scope:internal-helper (private; exercised through public callers)","withReservedConnection": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)","withScopedReadTransaction": "out-of-scope:internal-helper (private; exercised through public callers)","writeContradictionsRun": "takes"diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.tsindex 6f1751f3b5..a8d7928040 100644--- a/test/helpers/postgres-engine-sql-cases.ts+++ b/test/helpers/postgres-engine-sql-cases.ts@@ -74,6 +74,8 @@ export const DOMAIN_OF: Record<string, string> = {'activeEmbeddingColId': OOS.helper,'_upsertChunksOnce': OOS.helper,'_searchKeywordCJK': OOS.helper,+ 'runVectorAttempt': OOS.helper,+ 'vectorIterativeScanSupported': OOS.helper,// pages'getPage': 'pages', 'readPageSnapshot': 'pages', 'lockPageKeys': 'pages', 'findDuplicatePage': 'pages',@@ -130,7 +132,7 @@ export const DOMAIN_OF: Record<string, string> = {'searchKeyword': 'cjk-search', 'searchKeywordChunks': 'cjk-search',// out of scope- 'searchTitles': OOS.search, 'searchVector': OOS.search,+ 'searchTitles': OOS.search, 'searchVector': OOS.search, 'explainVectorSearch': OOS.search,'relationalFanout': OOS.enrichment, 'getBacklinkCounts': OOS.enrichment, 'getAdjacencyBoosts': OOS.enrichment,'getContentFlagsByPageIds': OOS.enrichment, 'getUnverifiedExtractionPageIds': OOS.enrichment,'getEffectiveDates': OOS.enrichment, 'getSalienceScores': OOS.enrichment, 'resolveAliases': OOS.enrichment,diff --git a/test/search/vector-freshness.test.ts b/test/search/vector-freshness.test.tsnew file mode 100644index 0000000000..91eed4856b--- /dev/null+++ b/test/search/vector-freshness.test.ts@@ -0,0 +1,140 @@+/**+ * #5824 correctness on PGLite: with content freshness filtered outside the+ * HNSW candidate CTE, a chunk whose text changed after embedding still never+ * reaches results, legacy NULL-hash chunks stay eligible, model mismatches+ * stay excluded, the pre-migration `$m IS NULL` branch is unchanged, and a+ * candidate window full of stale rows escalates instead of underfilling.+ * The Postgres side (plan proof, exact fallback) is+ * test/e2e/vector-plan-real-column-postgres.test.ts.+ */+import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import * as vectorPool from '../../src/core/search/vector-pool.ts';+import type { VectorPoolAttempt } from '../../src/core/search/vector-pool.ts';+import type { SearchOpts } from '../../src/core/types.ts';++const MODEL = 'test:vector-freshness';+const column = { name: 'embedding', type: 'vector' as const, dimensions: 8, embeddingModel: MODEL };+const query = new Float32Array([1, 0, 0, 0, 0, 0, 0, 0]);+type PoolMeta = Parameters<NonNullable<SearchOpts['onVectorPoolMeta']>>[0];++let engine: PGLiteEngine;+const originalPool = vectorPool.searchVectorPool;+let poolSpy: ReturnType<typeof spyOn> | undefined;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw('DROP INDEX IF EXISTS idx_chunks_embedding');+ await engine.executeRaw('ALTER TABLE content_chunks ALTER COLUMN embedding TYPE vector(8)');+ await engine.executeRaw('CREATE INDEX idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops)');+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+});++afterEach(() => {+ poolSpy?.mockRestore();+ poolSpy = undefined;+});++/** Pages `<prefix>-<i>`, one chunk each at angle `start + i * step` from the query. */+async function seed(prefix: string, count: number, start: number, step: number, chunk: { hash: 'current' | 'stale' | 'null'; model?: string }) {+ const hash = chunk.hash === 'current' ? 'md5(cc_text)' : chunk.hash === 'stale' ? `md5('text before the edit')` : 'NULL';+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)+ SELECT '${prefix}-' || i, 'default', 'note', '${prefix} ' || i, 'fixture', '00000000-0000-4000-8000-000000000001'::uuid,+ '00000000-0000-4000-8000-000000000001'::uuid, 4+ FROM generate_series(0, ${count - 1}) i`);+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding)+ SELECT id, 0, cc_text, 'compiled_truth', $1, ${hash}, ARRAY[cos(a), sin(a), 0, 0, 0, 0, 0, 0]::real[]::vector+ FROM (SELECT p.id, '${prefix} chunk text ' || p.slug AS cc_text,+ ${start} + (split_part(p.slug, '-', 2)::int) * ${step} AS a+ FROM pages p WHERE p.slug LIKE '${prefix}-%') src`, [chunk.model ?? MODEL]);+}++async function reset() {+ await engine.executeRaw('DELETE FROM content_chunks');+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw(`DELETE FROM config WHERE key = 'embedding_migration.state'`);+}++/** Records the `run` attempts searchVector hands to searchVectorPool. */+function spyAttempts(): VectorPoolAttempt[] {+ const attempts: VectorPoolAttempt[] = [];+ poolSpy = spyOn(vectorPool, 'searchVectorPool').mockImplementation((limit, initial, iterative, indexed, kind, run, hasMore, onMeta) =>+ originalPool(limit, initial, iterative, indexed, kind, async attempt => { attempts.push(attempt); return run(attempt); }, hasMore, onMeta));+ return attempts;+}++describe('vector freshness outside the candidate CTE (PGLite)', () => {+ test('stale, mismatched and NULL-hash chunks keep their exact eligibility', async () => {+ await reset();+ await seed('stale', 3, 0.001, 0.001, { hash: 'stale' });+ await seed('mismatch', 3, 0.002, 0.001, { hash: 'current', model: 'test:other-model' });+ await seed('legacy', 2, 0.01, 0.001, { hash: 'null' });+ await seed('fresh', 20, 0.05, 0.001, { hash: 'current' });+ for (const vectorLegacyGuard of [false, true]) {+ const hits = await engine.searchVector(query, { limit: 10, embeddingColumn: column, vectorLegacyGuard });+ const slugs = hits.map(hit => hit.slug);+ expect(slugs).toHaveLength(10);+ expect(slugs.slice(0, 2)).toEqual(['legacy-0', 'legacy-1']);+ expect(slugs.some(slug => slug.startsWith('stale-') || slug.startsWith('mismatch-'))).toBe(false);+ }+ }, 60_000);++ test('the pre-migration branch (no model, no migration state) is unchanged: every model and hash is eligible', async () => {+ await reset();+ await seed('stale', 2, 0.001, 0.001, { hash: 'stale' });+ await seed('mismatch', 2, 0.002, 0.001, { hash: 'current', model: 'test:other-model' });+ await seed('fresh', 10, 0.05, 0.001, { hash: 'current' });+ const preMigration = { ...column, embeddingModel: '' };+ const hits = await engine.searchVector(query, { limit: 4, embeddingColumn: preMigration });+ expect(hits.map(hit => hit.slug).sort()).toEqual(['mismatch-0', 'mismatch-1', 'stale-0', 'stale-1']);+ await engine.executeRaw(`INSERT INTO config (key, value) VALUES ('embedding_migration.state', '{}')`);+ expect(await engine.searchVector(query, { limit: 4, embeddingColumn: preMigration })).toEqual([]);+ }, 60_000);++ test('a candidate window full of stale chunks escalates and fills from current chunks', async () => {+ await reset();+ await seed('stale', 300, 0.0001, 0.0001, { hash: 'stale' });+ await seed('fresh', 30, 0.5, 0.001, { hash: 'current' });+ const attempts = spyAttempts();+ const events: PoolMeta[] = [];+ const hits = await engine.searchVector(query, { limit: 10, embeddingColumn: column, onVectorPoolMeta: meta => events.push(meta) });+ expect(hits.map(hit => hit.slug)).toEqual(Array.from({ length: 10 }, (_, i) => `fresh-${i}`));+ expect(attempts.map(attempt => attempt.innerLimit)).toEqual([100, 400]);+ expect(events).toEqual([]);++ const guarded = spyAttempts();+ const legacy = await engine.searchVector(query, { limit: 10, embeddingColumn: column, vectorLegacyGuard: true });+ expect(legacy.map(hit => hit.slug)).toEqual(hits.map(hit => hit.slug));+ expect(guarded.map(attempt => attempt.innerLimit)).toEqual([100]);+ }, 60_000);++ test('a stale wall beyond three escalations ends in the documented underfilled exit with only current chunks', async () => {+ await reset();+ await seed('stale', 6_500, 0.00001, 0.00001, { hash: 'stale' });+ await seed('fresh', 30, 0.5, 0.001, { hash: 'current' });+ const attempts = spyAttempts();+ const events: PoolMeta[] = [];+ const hits = await engine.searchVector(query, { limit: 10, embeddingColumn: column, onVectorPoolMeta: meta => events.push(meta) });+ expect(attempts.map(attempt => attempt.innerLimit)).toEqual([100, 400, 1_600, 6_400]);+ expect(hits).toEqual([]);+ expect(events).toEqual([{ underfilled: true, incomplete: true, reason: 'candidate_budget', escalations: 3, innerLimit: 6_400, candidatePool: 6_400, exactFallback: false }]);+ }, 120_000);+ test('since/until bounds keep the effective_date -> updated_at fallback and inclusivity', async () => {+ await reset();+ await seed('dated', 4, 0.01, 0.001, { hash: 'current' });+ await engine.executeRaw(`UPDATE pages SET effective_date = CASE slug+ WHEN 'dated-0' THEN '2024-01-10T00:00:00Z'::timestamptz WHEN 'dated-1' THEN NULL+ WHEN 'dated-2' THEN '2024-02-01T00:00:00Z'::timestamptz ELSE '2024-01-15T00:00:00Z'::timestamptz END,+ updated_at = CASE slug WHEN 'dated-1' THEN '2024-01-20T00:00:00Z'::timestamptz ELSE '2023-06-01T00:00:00Z'::timestamptz END`);+ const slugs = async (opts: SearchOpts) => (await engine.searchVector(query, { limit: 10, embeddingColumn: column, ...opts })).map(hit => hit.slug).sort();+ expect(await slugs({ afterDate: '2024-01-15T00:00:00Z' })).toEqual(['dated-1', 'dated-2']);+ expect(await slugs({ afterDate: '2024-01-15T00:00:00Z', afterDateInclusive: true })).toEqual(['dated-1', 'dated-2', 'dated-3']);+ expect(await slugs({ beforeDate: '2024-01-20T00:00:00Z' })).toEqual(['dated-0', 'dated-3']);+ expect(await slugs({ afterDate: '2024-01-12T00:00:00Z', beforeDate: '2024-01-20T00:00:00Z', beforeDateInclusive: true })).toEqual(['dated-1', 'dated-3']);+ }, 60_000);+});diff --git a/test/search/vector-pool.test.ts b/test/search/vector-pool.test.tsindex 6728c191c5..79d418893c 100644--- a/test/search/vector-pool.test.ts+++ b/test/search/vector-pool.test.ts@@ -98,4 +98,27 @@ describe('bounded vector candidate safety', () => {expect(events).toHaveLength(1);expect(events[0]).toMatchObject({ reason: 'deadline', candidatePool: 1, incomplete: true, exactFallback: true });});+ test('#5824: a short raw window with stale rows asks hasMore about the fresh count, not the raw count', async () => {+ // 60 raw candidates came back (window cut short), 4 of them fresh. The+ // guarded witness sees 30 fresh eligible rows: more than the 4 seen, but+ // fewer than the 60 raw rows, so comparing against the raw count would+ // stop here with 4 rows and no metadata.+ const asked: number[] = [];+ const attempts: VectorPoolAttempt[] = [];+ const events: PoolMeta[] = [];+ const rows = await searchVectorPool(10, 100, true, true, 'pglite', async attempt => {+ attempts.push(attempt);+ const first = attempts.length === 1;+ return { rows: Array.from({ length: first ? 4 : 10 }, (_, page_id) => ({ page_id })), candidatePool: first ? 60 : 400, eligiblePool: first ? 4 : 30 };+ }, async pool => { asked.push(pool); return 30 > pool; }, meta => events.push(meta));+ expect(asked).toEqual([4]);+ expect(attempts.map(a => a.innerLimit)).toEqual([100, 400]);+ expect(rows).toHaveLength(10);+ expect(events).toEqual([]);+ });++ test('#5824: eligible_pool is read next to the raw candidate_pool', () => {+ expect(readVectorPool([{ page_id: 3, candidate_pool: 100, eligible_pool: 12 }])).toEqual({+ rows: [{ page_id: 3, candidate_pool: 100, eligible_pool: 12 }], candidatePool: 100, eligiblePool: 12 });+ });});diff --git a/test/search/vector-statement.test.ts b/test/search/vector-statement.test.tsnew file mode 100644index 0000000000..babea9b026--- /dev/null+++ b/test/search/vector-statement.test.ts@@ -0,0 +1,131 @@+/**+ * #5824: the vector statement keeps the content-freshness test out of the+ * HNSW candidate CTE on indexed columns (the planner cannot estimate it and+ * drops the index), keeps it inside on non-indexed columns and under the+ * legacy guard, and always keeps it in the exact fallback and the `hasMore`+ * witness. Both engines emit the same statement apart from the PGLite+ * timeline `stale` column.+ */+import { afterEach, describe, expect, spyOn, test } from 'bun:test';+import { buildVectorSearchStatement, type VectorSearchStatementInput } from '../../src/core/search/vector-statement.ts';+import { _resetVectorLegacyGuardForTests, readVectorLegacyGuard, resolveVectorLegacyGuard } from '../../src/core/search/vector-legacy-guard.ts';+import { withEnv } from '../helpers/with-env.ts';++const MD5 = 'md5(cc.chunk_text)';+const indexedColumn = { name: 'embedding', type: 'vector' as const, dimensions: 1536, embeddingModel: 'openai:text-embedding-3-large' };+const wideColumn = { name: 'embedding', type: 'vector' as const, dimensions: 3072, embeddingModel: 'openai:text-embedding-3-large' };++function build(overrides: Partial<VectorSearchStatementInput['opts']> = {}, dialect: 'postgres' | 'pglite' = 'postgres') {+ return buildVectorSearchStatement({ dialect, embedding: new Float32Array([1, 0, 0]), limit: 10, offset: 0, opts: { embeddingColumn: indexedColumn, ...overrides } });+}++/** The WHERE of the `hnsw_candidates` CTE, between its FROM and its ORDER BY. */+function candidateWhere(sql: string): string {+ const cte = sql.slice(sql.indexOf('WITH hnsw_candidates AS ('), sql.indexOf('scored AS ('));+ return cte.slice(cte.indexOf('FROM content_chunks cc'), cte.indexOf('ORDER BY'));+}++function scoredCte(sql: string): string {+ return sql.slice(sql.indexOf('scored AS ('), sql.indexOf('best_per_page AS ('));+}++describe('vector statement freshness placement (#5824)', () => {+ test('an indexed embedding column keeps only the model check in the candidate CTE', () => {+ const stmt = build();+ expect(stmt.indexed).toBe(true);+ expect(stmt.relaxed).toBe(true);+ const where = candidateWhere(stmt.sql);+ expect(where).not.toContain(MD5);+ expect(where).toContain('AND (cc.model=$2 OR ($2::text IS NULL AND NOT EXISTS(SELECT 1 FROM config WHERE key=\'embedding_migration.state\')))');+ expect(stmt.sql).toContain(`(cc.embedded_text_hash=${MD5} OR cc.embedded_text_hash IS NULL) AS hash_current`);+ expect(scoredCte(stmt.sql)).toContain('WHERE $2::text IS NULL OR hash_current');+ expect(stmt.sql).toContain('(count(*) FILTER (WHERE $2::text IS NULL OR hash_current))::int AS eligible_pool');+ });++ test('the exact fallback and the hasMore witness keep the full guard', () => {+ const stmt = build();+ expect(candidateWhere(stmt.exactSql)).toContain(`AND ((cc.model=$2 AND (cc.embedded_text_hash=${MD5} OR cc.embedded_text_hash IS NULL))`);+ expect(stmt.exactSql).toContain(') + 0');+ expect(stmt.exactSql).not.toContain('hash_current');+ expect(stmt.hasMoreSql).toContain(`AND ((cc.model=$2 AND (cc.embedded_text_hash=${MD5} OR cc.embedded_text_hash IS NULL))`);+ expect(stmt.hasMoreSql).toContain(`LIMIT $${stmt.innerLimitIdx + 1}`);+ });++ test('a column wider than the HNSW cap keeps the guard inside the candidate CTE', () => {+ const stmt = build({ embeddingColumn: wideColumn });+ expect(stmt.indexed).toBe(false);+ expect(stmt.relaxed).toBe(false);+ expect(candidateWhere(stmt.sql)).toContain(`AND ((cc.model=$2 AND (cc.embedded_text_hash=${MD5} OR cc.embedded_text_hash IS NULL))`);+ expect(stmt.sql).not.toContain('hash_current');+ expect(stmt.sql).toContain('count(*)::int AS candidate_pool, count(*)::int AS eligible_pool');+ });++ test('the legacy guard emits the guarded variant on an indexed column', () => {+ const guarded = build({ vectorLegacyGuard: true });+ expect(guarded.indexed).toBe(true);+ expect(guarded.relaxed).toBe(false);+ expect(candidateWhere(guarded.sql)).toContain(MD5);+ expect(guarded.sql).toBe(build({ embeddingColumn: wideColumn }).sql);+ });++ test('non-text columns carry no generation guard to relax', () => {+ const stmt = build({ embeddingColumn: { name: 'embedding_image', type: 'vector', dimensions: 1024, embeddingModel: 'voyage:voyage-multimodal-3' } });+ expect(stmt.relaxed).toBe(false);+ expect(stmt.sql).not.toContain(MD5);+ expect(stmt.sql).toContain(`AND cc.modality = 'image'`);+ });++ test('Postgres and PGLite emit the same statement apart from the timeline stale column', () => {+ const opts = { type: 'note', sourceIds: ['a', 'b'], afterDate: '2026-01-01', language: 'typescript', excludePrivate: true };+ for (const vectorLegacyGuard of [false, true]) {+ const pg = build({ ...opts, vectorLegacyGuard });+ const lite = build({ ...opts, vectorLegacyGuard }, 'pglite');+ expect(lite.params).toEqual(pg.params);+ expect(lite.innerLimitIdx).toBe(pg.innerLimitIdx);+ expect(lite.hasMoreSql).toBe(pg.hasMoreSql);+ const strip = (sql: string) => sql.replace(' p.updated_at,', '').replace(/CASE WHEN bpp\.updated_at < \([\s\S]*?\) THEN true ELSE false END AS stale/, 'false AS stale');+ expect(strip(lite.sql)).toBe(pg.sql);+ }+ });++ test('parameters bind the vector, filters, model and the three limits in order', () => {+ const stmt = build({ type: 'note', sourceId: 'default', limit: 10 });+ expect(stmt.params).toEqual(['[1,0,0]', 'note', 'default', 'openai:text-embedding-3-large', 100, 10, 0]);+ expect(stmt.innerLimitIdx).toBe(4);+ expect(stmt.innerLimit).toBe(100);+ });+});++describe('vector legacy guard setting', () => {+ afterEach(() => _resetVectorLegacyGuardForTests());++ test('env wins over config, and config enables it when env is unset', async () => {+ await withEnv({ GBRAIN_VECTOR_LEGACY_GUARD: undefined }, async () => {+ expect(readVectorLegacyGuard(null)).toEqual({ enabled: false, via: null });+ expect(readVectorLegacyGuard({ search: { vector_legacy_guard: true } })).toEqual({ enabled: true, via: 'config' });+ });+ await withEnv({ GBRAIN_VECTOR_LEGACY_GUARD: '1' }, async () => {+ expect(readVectorLegacyGuard(null)).toEqual({ enabled: true, via: 'env' });+ });+ await withEnv({ GBRAIN_VECTOR_LEGACY_GUARD: '0' }, async () => {+ expect(readVectorLegacyGuard({ search: { vector_legacy_guard: true } })).toEqual({ enabled: false, via: 'env' });+ });+ });++ test('resolves once per process and logs activation once to stderr', async () => {+ const stderr = spyOn(console, 'error').mockImplementation(() => {});+ try {+ await withEnv({ GBRAIN_VECTOR_LEGACY_GUARD: 'true' }, async () => {+ expect(resolveVectorLegacyGuard(null)).toBe(true);+ expect(resolveVectorLegacyGuard(null)).toBe(true);+ });+ await withEnv({ GBRAIN_VECTOR_LEGACY_GUARD: undefined }, async () => {+ expect(resolveVectorLegacyGuard(null)).toBe(true);+ });+ expect(stderr).toHaveBeenCalledTimes(1);+ expect(String(stderr.mock.calls[0][0])).toStartWith('[gbrain] vector legacy guard active');+ } finally {+ stderr.mockRestore();+ }+ });+});