Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs: troubleshoot keyword-only hybrid search and the vector legacy guard (#5824)
garrytan2548cef8e297
diff --git a/docs/TESTING.md b/docs/TESTING.mdindex dd21200673..0ae915f617 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -152,6 +152,16 @@ Search reliability has real-planner and transport regressions in`test/search-readiness-http.test.ts`. The statistics tests include owner,restricted-reader and FORCE-RLS roles; the candidate tests distinguish naturalplans from forced-HNSW controls and prove server cancellation of exact fallback.+`test/e2e/vector-plan-real-column-postgres.test.ts` is the #5824 plan proof on+the real `embedding` column: in a dedicated 64-dim database (it needs CREATEDB+and `CREATE EXTENSION vector`, so it runs under `bun run ci:local`) it first+shows the legacy-guard statement seq-scans on its fixture, then that the+emitted statement uses `idx_chunks_embedding` across a filter matrix incl. RLS+scope binding, then the stale-heavy escalation, exact-fallback and short-window+cases and every doctor `vector_plan` outcome. The PGLite side is+`test/search/vector-freshness.test.ts`; the SQL shape and lockstep are+`test/search/vector-statement.test.ts`. The opt-in reporter-scale bench is+`scripts/bench/vector-plan-5824.ts`.`test/e2e/projection-recovery-parity.test.ts` runs the shared Markdown/coderecovery, graph-edge preservation and migration-origin contracts againstPostgreSQL; their root suites cover PGLite in the unit lane. PGLite work caps neverdiff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex 09bc5a9a1c..6c297d1908 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -97,6 +97,9 @@ written up in [`RETRIEVAL_MAXPOOL_INCIDENT.md`](../incidents/RETRIEVAL_MAXPOOL_Ia JavaScript timeout can cancel its WASM work. Unresolved shortfalls appearas `vector_candidates_incomplete` in `degraded`, with scoped`vector_pool_underfilled` details in the public retrieval metadata.+ The content-freshness check runs after the HNSW candidate scan on indexed+ columns (the planner cannot estimate it and would drop the index); doctor+ `vector_plan` warns when the emitted statement still misses the index.- **Title-phrase boost** — when the normalized query is a contiguous token-runinside `page.title` (or an exact full-title match), a floor-ratio-gated,bounded multiplier fires (`applyTitleBoost`, `search.title_boost` knob). Adiff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 6046fc9bea..ba4b41477f 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -5,6 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELDoctor's embedding-dimension warning treats existing chunks as existing data even when every vector is missing. It directs the operator to a verified database backup and a brain-wide migration preview, followed only by explicitly approved total spending authorization; it never recommends forced reinitialization for that case. `test/doctor.test.ts` pins this recovery guidance.+- `src/commands/doctor/checks/vector-plan.ts` — `vector_plan` (#5824, OPS, wave check with operator resolution). Postgres only: EXPLAINs (no ANALYZE) the statement `searchVector` emits for the active embedding column with a zero vector through `PostgresEngine.explainVectorSearch` (same builder, scoped read transaction and scan settings) and warns when an HNSW-indexed column's plan does not use its HNSW index, naming the observed scans, whether the index exists and is valid (`pg_index.indisvalid`, with the create/reindex command), the 8 s candidate-budget risk and the legacy guard as rollback. Skipped on PGLite, on columns wider than the HNSW cap, and below 10,000 embedded chunks (`pg_class.reltuples` x `pg_stats.null_frac`, a bounded count when never analyzed). A configured legacy guard warns "active after restarting the owning service". Details carry a sampled stale-text fraction and point to `gbrain embed --stale` above 5%. Tested in `test/e2e/vector-plan-real-column-postgres.test.ts` (empty, small, ok, unused valid index, INVALID index, guard via env and config).- `src/commands/doctor/checks/persistence-requests.ts` — two wave checks (OPS, registered in `wave-checks.ts`). `persistence_request_indexes` (#5762) reports each managed sync request index missing, INVALID or still building (with progress) and names `gbrain repair request-indexes --apply`. `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.- `src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts` — `persistence_capacity` (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via `capacityDiagnostics`) and prints one `gbrain config set <key> <value>` per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. `parked_effects` (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its `retry-effects ... --dry-run` command. Both report `exact`/`inspected`/`truncated` details; an unreadable state is warn, never clean. Tests: `test/persistence-capacity.test.ts`, `test/persistence-effect-parking.test.ts`.- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` per source. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Test: `test/e2e/unbound-source-postgres.test.ts`.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 59ebcea875..747200a839 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -21,4 +21,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/tune-recommendations.ts` — tuning recommendations never propose enabling or tuning unavailable semantic result caching. Mode-reduction suggestions describe payload size, not expansion savings: shipped commands pin expansion independently of the bundle.-- `src/core/search/vector-pool.ts` + `vector-settings.ts` — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness instead. Settings are restored even inside caller-owned transactions.+- `src/core/search/vector-pool.ts` + `vector-settings.ts` — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness instead. Settings are restored even inside caller-owned transactions. A batch carries the raw `candidatePool` (exhaustion: a short window means the index ran dry) and an optional `eligiblePool` (candidates that passed the freshness filter outside the candidate CTE); `hasMore` receives the eligible count, defaulting to the raw one.++- `src/core/search/vector-statement.ts` — `buildVectorSearchStatement({ dialect, embedding, limit, offset, opts })` builds the vector-search SQL once for both engines, doctor `vector_plan` and the plan-proof E2E: `{ sql, exactSql, hasMoreSql, params, innerLimitIdx, innerLimit, indexed, relaxed }`. On an HNSW-indexed `embedding` column (relaxed variant) the candidate CTE carries only the model check; content freshness (`embedded_text_hash = md5(chunk_text)` or NULL) is projected as `hash_current` and filtered in `scored`, because Postgres cannot estimate that expression and drops the index when it sits in the CTE (#5824). Non-indexed columns, the legacy guard, `exactSql` and `hasMoreSql` keep the full guard inside. The pool row reports `candidate_pool` (raw) and `eligible_pool` (fresh). Since/until bounds are spelled per column (`effective_date`, then `updated_at`, then `created_at`) so each arm has column statistics. PGLite adds the timeline `stale` column; everything else is byte-identical across dialects. Also exports the extension-version probe and the transaction-local `statement_timeout` SQL the Postgres engine runs. Pinned by `test/search/vector-statement.test.ts`, `test/search/vector-freshness.test.ts` and `test/e2e/vector-plan-real-column-postgres.test.ts`.++- `src/core/search/vector-legacy-guard.ts` — one-release rollback for the #5824 statement change. `readVectorLegacyGuard(cfg, env)` reports the setting (`GBRAIN_VECTOR_LEGACY_GUARD` wins over `search.vector_legacy_guard`); `resolveVectorLegacyGuard(cfg)` latches it once per process for `hybrid/request.ts`, which passes `SearchOpts.vectorLegacyGuard` to the engines (they never read config), and prints `[gbrain] vector legacy guard active` to stderr once when on. A changed setting takes effect when the owning service restarts.diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex bd36a78ffd..253fdad8c0 100644--- a/docs/architecture/key-files/engines-1.md+++ b/docs/architecture/key-files/engines-1.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- Primary `searchVector` generation filters in both engines require the resolved model and either a current embedded-text hash or a grandfathered pre-v133 NULL hash. A budget/resume marker alone never changes a matching-model legacy vector's eligibility; known stale hashes and incompatible models remain excluded. This does not infer provenance for legacy fact vectors. `test/legacy-vector-compatibility.test.ts` and its PostgreSQL wrapper pin actual hybrid retrieval through a failed provider probe and retained migration marker without rewriting stored vectors.+- Primary `searchVector` generation filters in both engines require the resolved model and either a current embedded-text hash or a grandfathered pre-v133 NULL hash. A budget/resume marker alone never changes a matching-model legacy vector's eligibility; known stale hashes and incompatible models remain excluded. On HNSW-indexed columns the hash test runs after the candidate scan (see `search/vector-statement.ts`), so a stale chunk can occupy a candidate slot but never a result. This does not infer provenance for legacy fact vectors. `test/legacy-vector-compatibility.test.ts` and its PostgreSQL wrapper pin actual hybrid retrieval through a failed provider probe and retained migration marker without rewriting stored vectors.- `src/core/connection-manager.ts` — routes ordinary and direct Postgres pools. Supabase-shaped URLs retain automatic derivation; a valid explicit `GBRAIN_DIRECT_DATABASE_URL` or constructor override also enables dual routing for generic Postgres and PgBouncer on custom ports. The kill switch and inherited parent route stay authoritative. `describeMode()` reports the same route used by `ddl()` and `bulk()`. Regression coverage: `test/connection-manager.serial.test.ts` and the real 24-case persistence runtime matrix.diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex cebce14e2d..5db0e92779 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -137,3 +137,48 @@ though the parent connects fine, and running in-process removes thespawn entirely. The grandfather migration runs as a chunked bulk SQLpass (keyed on the page PK, soft-delete-filtered, source-safe) andcompletes in seconds on an 80K-page PGLite brain.++## Hybrid search returns only keyword hits++**Symptom.** On a large Postgres brain, `gbrain query` answers look keyword-only,+search metadata carries `vector_candidates_incomplete`, or each query takes about+8 seconds. The vector arm ran out of its 8 s candidate budget, usually because+the planner chose a sequential scan over the HNSW index (`idx_chunks_embedding`).++**Say to your agent:** *"Check whether vector search is using its index"* — the+agent runs `gbrain doctor` and reads the `vector_plan` check.++`gbrain doctor` reports `vector_plan` (Postgres only):++- `ok`: the statement vector search sends uses the HNSW index.+- skipped: PGLite, a column wider than pgvector's HNSW cap (exact scan by+ design), or fewer than 10,000 embedded chunks (a sequential scan is right+ for a small brain).+- warn, index unused: the message names the plan the planner chose and whether+ the HNSW index exists and is valid. Fix in this order: upgrade gbrain on the+ brain host (`gbrain upgrade`) and rerun `gbrain doctor`; if the index is+ missing or INVALID, run the `CREATE INDEX CONCURRENTLY` / `REINDEX INDEX+ CONCURRENTLY` command doctor prints.+- warn, stale text above 5%: run `gbrain embed --stale` so chunks edited after+ embedding get fresh vectors.+- warn, legacy guard: see below.++**Legacy guard (one-release rollback).** If vector search got slower or+returned different results right after the upgrade that moved the content+freshness check out of the HNSW candidate scan (#5824), you can restore the+previous statement while you report it:++1. The setting belongs to the process that runs searches on the brain host+ (`gbrain serve`, autopilot, job workers), never to a thin client.+2. Set it with `gbrain config set search.vector_legacy_guard true`, or export+ `GBRAIN_VECTOR_LEGACY_GUARD=1` in that service's environment (the variable+ wins over the config key).+3. Restart the owning service. It reads the setting once at its first search and+ prints `[gbrain] vector legacy guard active` to stderr.+4. Confirm with `gbrain doctor`: `vector_plan` warns "legacy guard configured …+ active after restarting the owning service".+5. Remove it once the regression is fixed: `gbrain config set+ search.vector_legacy_guard false` (or unset the variable) and restart again.++The guard is retired in the next release; that release prints a one-time notice+when the inert setting is still present.