Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): skip a keyword statement that just hit the statement timeout (#6495)
garrytan482a48a01ed9
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex 1cf3c7017a..02ca702e86 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -55,4 +55,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/schema-migrations/v232-fts-cjk-boundary.ts` — #6370, handler-only and idempotent: creates `gbrain_fts_input`, recreates both search_vector trigger functions under `getFtsLanguage()` with the shared builders, then rebuilds only pages (`title`/`timeline`) and chunks (`chunk_text`/`doc_comment`/`symbol_name_qualified`) matching `FTS_CJK_BOUNDARY_REGEX` through `search-vector-backfill.ts` (checkpoints `fts_cjk_pages`/`fts_cjk_content_chunks`, cleared at the end); every other row's vector is byte-identical under the helper and is not touched. Pinned by `test/fts-cjk-boundary.test.ts` and `test/e2e/fts-cjk-boundary-postgres.test.ts`.- `src/core/schema-migrations/v245-page-search-vector-bounded-timeline.ts` — Large pages, handler-only and idempotent: recreates the pages search_vector trigger function under `getFtsLanguage()` with the bounded timeline (`PAGE_TIMELINE_FTS_MAX_CHARS`) and entries (`PAGE_TIMELINE_ENTRIES_FTS_MAX_CHARS`) cuts, then rebuilds only pages whose timeline is longer than half the timeline cap through `search-vector-backfill.ts` (checkpoint `page_vector_bounded_timeline`, cleared at the end); shorter timelines index byte-identically and are not touched. Pinned by `test/large-pages/page-timeline-tsvector-bound.test.ts` and `test/e2e/page-timeline-tsvector-bound-postgres.test.ts`.-- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts`, `postgres-engine/init-schema-lock.ts`, `postgres-engine/keyword-statement-timeout.ts` (#6495: `KEYWORD_STATEMENT_TIMEOUT_KEY` = `search.keyword_statement_timeout_ms`, default 8000, range 1000-60000; `keywordStatementTimeoutMs` accepts an integer in range, `resolveKeywordStatementTimeoutMs(file, db)` applies file > DB > default, `keywordStatementTimeoutValueProblem` is the `config set` refusal text, and `loadKeywordStatementTimeout(reader, fileValue)` yields the `<ms>ms` setting one connection binds; pinned by `test/keyword-statement-timeout-knob-6495.test.ts` on a recording handle and, with DATABASE_URL, on a real Postgres whose locked tables make each statement wait until the bound cancels it), `postgres-engine/schema-lock-timeout.ts` (#5227: `resolveSchemaLockTimeoutMs` reads `GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS`, default 60 s; `withSchemaLockTimeout` sets a session-level `lock_timeout` on the reserved DDL backend and restores the prior value on release, used by the `schema.sql` replay in `postgres-engine.ts` and the `transaction: false` path of `migrate.ts`, while a transaction-wrapped migration binds the same wait with `SET LOCAL`; `schemaDiagnosticConnection` opens a one-backend connection that samples `pg_blocking_pids()` of the waiting backend while the wait is active so `schemaLockBlockedError` names blockers by pid, application, state and transaction age, never query text; `init-schema-retry.ts` retries `schema_lock_blocked` / SQLSTATE 55P03 with a short backoff; handler migrations and the post-migration `verifySchema` run outside the bound) and `postgres-engine/search-settings.ts` (search transactions run with `jit = off`), `postgres-engine/reserved-transactions.ts` (`withReservedConnection` lends its connection a `transaction()`; BEGIN and SAVEPOINT go out with the statements after them, and a COMMIT answered with ROLLBACK throws), `postgres-engine/transaction-abort.ts` (`transaction(fn, { signal })`: an abort discards the transaction's connection through the begin handle's `discard()`, so the server rolls the transaction back and the caller gets an `AbortError` with the driver's `CONNECTION_CLOSED` as `cause`; an already-aborted signal rejects before BEGIN); the forward-reference bootstrap lives once in `engine-sql/bootstrap.ts` for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.+- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts`, `postgres-engine/init-schema-lock.ts`, `postgres-engine/keyword-statement-timeout.ts` (#6495: `KEYWORD_STATEMENT_TIMEOUT_KEY` = `search.keyword_statement_timeout_ms`, default 8000, range 1000-60000; `keywordStatementTimeoutMs` accepts an integer in range, `resolveKeywordStatementTimeoutMs(file, db)` applies file > DB > default, `keywordStatementTimeoutValueProblem` is the `config set` refusal text, and `loadKeywordStatementTimeout(reader, fileValue)` yields the `<ms>ms` setting one connection binds; pinned by `test/keyword-statement-timeout-knob-6495.test.ts` on a recording handle and, with DATABASE_URL, on a real Postgres whose locked tables make each statement wait until the bound cancels it), `postgres-engine/keyword-timeout-cache.ts` (#6495 negative cache: `KeywordTimeoutNegativeCache.run(enabled, db, keyParts, exec)` wraps `searchKeyword`'s strict and relaxed statements when hybrid's keyword arm opts in with `SearchOpts.keywordTimeoutCache`; the key hashes the statement text, its parameters, the RLS source scope and the statement timeout, so only the exact statement is skipped; a genuine statement-timeout 57014, never a user cancel, records an entry for `search.keyword_timeout_negative_cache_seconds` (default 600, 0 = off, read once on the first timeout) and later identical runs throw `KeywordSkippedAfterTimeoutError` (code `keyword_skipped_after_timeout`, arm reason `skipped_after_timeout`) without a statement; at most 256 entries per engine; each timeout writes one bounded `search.keyword_timeout_stats` row that doctor `keyword_plan` reads; pinned by `test/keyword-timeout-negative-cache-6495.test.ts`), `postgres-engine/schema-lock-timeout.ts` (#5227: `resolveSchemaLockTimeoutMs` reads `GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS`, default 60 s; `withSchemaLockTimeout` sets a session-level `lock_timeout` on the reserved DDL backend and restores the prior value on release, used by the `schema.sql` replay in `postgres-engine.ts` and the `transaction: false` path of `migrate.ts`, while a transaction-wrapped migration binds the same wait with `SET LOCAL`; `schemaDiagnosticConnection` opens a one-backend connection that samples `pg_blocking_pids()` of the waiting backend while the wait is active so `schemaLockBlockedError` names blockers by pid, application, state and transaction age, never query text; `init-schema-retry.ts` retries `schema_lock_blocked` / SQLSTATE 55P03 with a short backoff; handler migrations and the post-migration `verifySchema` run outside the bound) and `postgres-engine/search-settings.ts` (search transactions run with `jit = off`), `postgres-engine/reserved-transactions.ts` (`withReservedConnection` lends its connection a `transaction()`; BEGIN and SAVEPOINT go out with the statements after them, and a COMMIT answered with ROLLBACK throws), `postgres-engine/transaction-abort.ts` (`transaction(fn, { signal })`: an abort discards the transaction's connection through the begin handle's `discard()`, so the server rolls the transaction back and the caller gets an `AbortError` with the driver's `CONNECTION_CLOSED` as `cause`; an already-aborted signal rejects before BEGIN); the forward-reference bootstrap lives once in `engine-sql/bootstrap.ts` for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex a763f639b9..fb68f852d3 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1796,6 +1796,16 @@ More: [docs/guides/company-brain-ingestion.md#resume-and-verify](../../docs/guidMore: [docs/guides/multi-language-fts.md#cjk-keyword-budget](../../docs/guides/multi-language-fts.md#cjk-keyword-budget)+### keyword_skipped_after_timeout++<a id="keyword_skipped_after_timeout"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Hybrid search's Postgres keyword arm skipped a statement that hit the keyword statement timeout within the negative-cache TTL; the search reports keyword_arm_failed with reason skipped_after_timeout and the vector arm still answers. | Running the same broad keyword statement again would hold a backend for the whole search.keyword_statement_timeout_ms and fail the same way. The skip covers that exact statement and scope only, lasts search.keyword_timeout_negative_cache_seconds (default 600, 0 turns it off) and is per serving process. A skipped keyword arm is not evidence of absence. | Narrow the search (source_id, types, since or until) to run keyword search now, or wait for the entry to expire; the user may raise search.keyword_statement_timeout_ms or change the TTL. Run: gbrain doctor --only keyword_plan --json | agent | `gbrain doctor --only keyword_plan --json` | 1 | no |++More: [docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain](../../docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain)+### knock_on_exhausted<a id="knock_on_exhausted"></a>diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 4252bc1e87..21c511542f 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -60,7 +60,7 @@| [`dream_paid_loop`, or dream keeps skipping one transcript](#dream-paid-loop) | fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'` | agent, after the user agrees | `paid` (the key is retried) | `gbrain doctor --only dream_paid_loop --json` || [A page exists (`gbrain get <slug>` returns it) but search never finds text from it](memory-boundaries.md#large-pages) | find the cause: `gbrain reindex --oversized --dry-run --json` lists pages stored before the upgrade with a size-based `embed_skip` marker (run it without `--dry-run` to keyword-index them, free); a page above an operator-lowered `content_sanity.bytes_block` keeps its marker until the operator raises or unsets it; a page the content-quality gate quarantined as junk shows in `gbrain quarantine list`, and `gbrain quarantine clear <slug>` re-checks it once the user agrees; a file over the 24 MiB page ceiling was never stored ([`file_too_large`](write-refusals.md#file_too_large)). Embedding the re-indexed pages is a separate paid step: `gbrain embed --held --max-usd <N>` | agent for the reindex; the user decides embedding spend, a `bytes_block` change and a quarantine clear | none for the reindex (CPU only); `paid` for `gbrain embed` | `gbrain reindex --oversized --dry-run --json` lists nothing; `gbrain doctor --json`; `gbrain search "<phrase from deep in the page>"` returns the page || [Search answers look keyword-only on a large Postgres brain](#hybrid-search-returns-only-keyword-hits) | read doctor's `vector_plan`; run the index command it prints | brain host | none | `gbrain doctor --only vector_plan --json` |-| [Broad keyword queries take about 8 s and come back vector-only (`keyword_arm_failed`) on a large Postgres brain](#keyword-search-times-out-on-a-large-postgres-brain) | read doctor's `keyword_plan`; narrow with `--source-id`, or raise `search.keyword_statement_timeout_ms` on the brain host and restart the serving process | brain host | none | `gbrain doctor --only keyword_plan --json` |+| [Broad keyword queries take about 8 s and come back vector-only (`keyword_arm_failed`, or `skipped_after_timeout` for 10 minutes after a timeout) on a large Postgres brain](#keyword-search-times-out-on-a-large-postgres-brain) | read doctor's `keyword_plan`; narrow with `--source-id`, or raise `search.keyword_statement_timeout_ms` on the brain host and restart the serving process | brain host | none | `gbrain doctor --only keyword_plan --json` || A second `gbrain serve` cannot open the brain | the readiness `harness_wiring` fix: every session shares one `gbrain serve --http` | user | `persistent_install`, `credentials` | `gbrain doctor --only harness_wiring --json` || `harness_wiring` reports `http_serve_unreachable` or `http_serve_unhealthy` for an HTTP registration | nothing automatic: doctor probed the registered `/health` without credentials and the endpoint did not answer as a healthy gbrain server; check the URL in the harness config and the server it points at (a hosted brain is its operator's). A `wired_running` verdict with `mcp_access: unverified` proves a listener only: confirm tools in a new session | user | none | `gbrain doctor --only harness_wiring --json` || A tool the fix names is missing after a serve recovered | restart the gbrain MCP server in the harness, or start a new session ([why](../protocol/AGENT_OPERATOR_v1.md#tool-catalog-changes-toolslist_changed)) | user | none | list the tools again |@@ -501,6 +501,32 @@ most of the corpus still reads and ranks every match, so prefer narrowing withcandidate set that will answer broad terms from a capped set instead offailing open.+**A timed-out keyword search is skipped for 10 minutes.** After hybrid search's+keyword statement hits the bound, a serving process (`gbrain serve`, an MCP+session) skips that exact statement for+`search.keyword_timeout_negative_cache_seconds` (integer seconds, default 600,+range 0 to 86400, 0 turns it off) instead of holding a backend for the whole+bound again. The skipped search answers from the vector arm at once and its+metadata carries `keyword_arm_failed` with reason `skipped_after_timeout`+(error code `keyword_skipped_after_timeout` in `gbrain errors`). The skip+covers the same statement only: the same terms with the same source scope,+types, dates, slug filters, visibility and trust floor of the caller, and the+same keyword bound. A narrower query (another `--source-id`, `--types`,+`--since`) still runs keyword search, another brain is never affected, and+the skip ends by itself when the entry expires, so a brief contention spike+recovers without anyone acting. A call with `use_cache: false` runs the+statement anyway.++Limits: the cache lives in the serving process's memory, so a one-shot CLI+command (`gbrain search …`) starts with an empty cache and gains nothing from+it, and a restart clears it. The TTL is read on the first timeout after the+process starts; a changed value takes effect after a restart. Each timeout+writes one counter row (`search.keyword_timeout_stats`: timeouts, skips counted+since the previous timeout, last timeout time), never one per search, and+`gbrain doctor --only keyword_plan --json` reports it under+`details.negative_cache`. Postgres only: PGLite has no keyword statement+timeout.+## Global maintenance timeouts**Doctor warns `global_maintenance_timeouts`, or late maintenance phasesdiff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex c58a9fa4cc..3b084c9acf 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -400,6 +400,8 @@ Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. Best for exaEvery call also reports how many pages match the query's keywords (`keyword_total`, `keyword_truncated`; "10000+" past 10,000) in one line after the rows. That count covers keyword (full-text) matches only, not the ranked rows. To list every one of those pages, pass `match: "keyword"`: rows come one per page in keyword-score order with `total`, `truncated` and `next`, a ready-to-send argument object; keep calling with `next` until it is absent. A page whose text did not fit `token_budget` still gets a row, with `evidence_omitted: true`. If the count times out, the line says it is unavailable (degraded stage `keyword_count_unavailable`), never zero.+On a large Postgres brain a broad keyword statement can hit the keyword time limit; the response's degraded stages then carry `keyword_arm_failed` with reason `timeout`, and for the next 10 minutes (`search.keyword_timeout_negative_cache_seconds`, 0 = off) the same search in the same serving process reports reason `skipped_after_timeout` at once instead of waiting again. Vector hits still come back. A skipped keyword arm is not evidence of absence: narrow the search (`source_id`, `types`, `since` or `until`) to run keyword matching, and `gbrain doctor --only keyword_plan --json` on the brain host reports the bound and the recorded timeouts. The same applies to `query`.+| Parameter | Type | Guidance || --- | --- | --- || `query` (required) | string | Search text. Exact tokens, names, and structured-field values work best here (e.g. 'acme-example series A'), since this op does no LLM expansion. This is the search text param — there is no `text` or `q` param. |diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 03787a67cf..7fbefbdcec 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -21,9 +21,9 @@ src/core/import-file.ts 2032 ratchet +2: pre-publication withdrawal validation;src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 240 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; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)src/core/pglite-engine.ts 3043 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import-src/core/postgres-engine.ts 3060 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); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import+src/core/postgres-engine.ts 3063 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); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts)src/core/search/hybrid.ts 1648 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +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; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)-src/core/types.ts 2315 ratchet +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +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 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts)+src/core/types.ts 2319 ratchet +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +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 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc linesrc/core/minions/queue.ts 2528 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 keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)src/commands/init.ts 1884 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); 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-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts)src/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 1587 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 1932 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 read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 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); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 1979 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +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); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts)+src/core/config.ts 1980 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +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); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS rowsrc/core/persistence/sync-run.ts 1690 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts)src/core/bootstrap/harness.ts 2615 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); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent blocksrc/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 optiondiff --git a/src/commands/config/keyword-timeout-value.ts b/src/commands/config/keyword-timeout-value.tsindex ca97c1fccd..c50d908b35 100644--- a/src/commands/config/keyword-timeout-value.ts+++ b/src/commands/config/keyword-timeout-value.ts@@ -1,7 +1,8 @@/**- * `config set` value check for `search.keyword_statement_timeout_ms` (#6495):- * nothing is written when the value is outside the range the Postgres engine- * would accept, because a stored value outside it reads as the default.+ * `config set` value checks for `search.keyword_statement_timeout_ms` and+ * `search.keyword_timeout_negative_cache_seconds` (#6495): nothing is written+ * when the value is outside the range the Postgres engine would accept,+ * because a stored value outside it reads as the default.*/import { exitCliError, usageError } from '../../cli/cli-error.ts';import {@@ -10,8 +11,22 @@ import {KEYWORD_STATEMENT_TIMEOUT_MAX_MS,keywordStatementTimeoutValueProblem,} from '../../core/postgres-engine/keyword-statement-timeout.ts';+import {+ KEYWORD_TIMEOUT_NEGATIVE_CACHE_DEFAULT_S,+ KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY,+ KEYWORD_TIMEOUT_NEGATIVE_CACHE_MAX_S,+ keywordTimeoutNegativeCacheValueProblem,+} from '../../core/postgres-engine/keyword-timeout-cache.ts';export function refuseInvalidKeywordTimeoutValue(key: string, value: string): void {+ if (key === KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY) {+ const problem = keywordTimeoutNegativeCacheValueProblem(value);+ if (!problem) return;+ exitCliError(usageError(problem, `Re-run with an integer number of seconds, e.g. gbrain config set ${KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY} ${KEYWORD_TIMEOUT_NEGATIVE_CACHE_DEFAULT_S} (0 turns the cache off; the cap is ${KEYWORD_TIMEOUT_NEGATIVE_CACHE_MAX_S}).`, {+ why: 'The Postgres engine treats a value outside 0..86400 as the default (600 seconds), so writing it would change nothing.',+ fix: { argv: ['gbrain', 'config', 'get', key], consent: [], actor: 'agent', why: 'Shows the value in effect; nothing was written.', requires_exclusive: false },+ }), 'config');+ }if (key !== KEYWORD_STATEMENT_TIMEOUT_KEY) return;const problem = keywordStatementTimeoutValueProblem(value);if (!problem) return;diff --git a/src/commands/doctor/checks/keyword-plan.ts b/src/commands/doctor/checks/keyword-plan.tsindex 3c754fdd53..97bec866b2 100644--- a/src/commands/doctor/checks/keyword-plan.ts+++ b/src/commands/doctor/checks/keyword-plan.ts@@ -11,7 +11,11 @@* times out or already spends more than half the configured bound.** It names the knob and its range, says that one canary term is not workload- * coverage, and never reports a timed-out count as "no matches". Skipped on+ * coverage, and never reports a timed-out count as "no matches". It also+ * reads the keyword timeout counter the engine writes once per statement+ * timeout (`search.keyword_timeout_stats`, postgres-engine/keyword-timeout-cache.ts)+ * into `details.negative_cache` and, when timeouts were recorded, names them+ * and the skip TTL in the message. Skipped on* PGLite (no statement timeout), below 10,000 chunks (`pg_class.reltuples`)* and when the planner has no statistics for the column.*/@@ -24,6 +28,13 @@ import {KEYWORD_STATEMENT_TIMEOUT_MIN_MS,resolveKeywordStatementTimeoutMs,} from '../../../core/postgres-engine/keyword-statement-timeout.ts';+import {+ KEYWORD_TIMEOUT_NEGATIVE_CACHE_DEFAULT_S,+ KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY,+ KEYWORD_TIMEOUT_STATS_KEY,+ keywordTimeoutNegativeCacheSeconds,+ parseKeywordTimeoutStats,+} from '../../../core/postgres-engine/keyword-timeout-cache.ts';import { isStatementTimeoutError } from '../../../core/retry-matcher.ts';import { buildKeywordCountStatement } from '../../../core/search/keyword-statement.ts';@@ -102,15 +113,23 @@ export async function keywordPlanCheck(engine: BrainEngine, probe: KeywordPlanPrconst cfg = await loadConfigWithEngine(engine).catch(() => loadConfig());const timeoutMs = resolveKeywordStatementTimeoutMs(cfg?.search?.keyword_statement_timeout_ms, undefined);const knob = `${KEYWORD_STATEMENT_TIMEOUT_KEY} = ${timeoutMs} ms (range ${KEYWORD_STATEMENT_TIMEOUT_MIN_MS}-${KEYWORD_STATEMENT_TIMEOUT_MAX_MS})`;- const base = { timeout_ms: timeoutMs, canary_timeout_ms: KEYWORD_PLAN_CANARY_TIMEOUT_MS, docs: DOCS };+ const read = async (key: string) => { try { return await engine.getConfig(key); } catch { return null; } };+ const stats = parseKeywordTimeoutStats(await read(KEYWORD_TIMEOUT_STATS_KEY));+ const ttlSeconds = keywordTimeoutNegativeCacheSeconds(await read(KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY)) ?? KEYWORD_TIMEOUT_NEGATIVE_CACHE_DEFAULT_S;+ const negativeCache = { ttl_seconds: ttlSeconds, timeouts: stats?.timeouts ?? 0, skips: stats?.skips ?? 0, last_timeout_at: stats?.last_timeout_at ?? null };+ const recorded = negativeCache.timeouts > 0+ ? ` Hybrid search's keyword arm hit this bound ${negativeCache.timeouts} time(s) (last ${negativeCache.last_timeout_at ?? 'unknown'}); ${negativeCache.skips} later search(es) skipped the timed-out statement (counted at each timeout write). `+ + (ttlSeconds > 0 ? `A serving process skips the exact statement that timed out for ${ttlSeconds} s (${KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY}; 0 turns it off), reporting keyword_arm_failed: skipped_after_timeout.` : `The skip is off (${KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY} = 0).`)+ : '';+ const base = { timeout_ms: timeoutMs, canary_timeout_ms: KEYWORD_PLAN_CANARY_TIMEOUT_MS, docs: DOCS, negative_cache: negativeCache };const chunks = await probe.chunkEstimate();if (chunks < KEYWORD_PLAN_MIN_CHUNKS) {- return { name, status: 'ok', message: `Skipped: fewer than ${KEYWORD_PLAN_MIN_CHUNKS} chunks by the planner's estimate; the keyword statements finish well inside ${knob}.`,+ return { name, status: 'ok', message: `Skipped: fewer than ${KEYWORD_PLAN_MIN_CHUNKS} chunks by the planner's estimate; the keyword statements finish well inside ${knob}.${recorded}`,details: { ...base, outcome: 'skipped', reason: 'small_brain' } };}const canary = await probe.canary();if (!canary) {- return { name, status: 'ok', message: `Skipped: the planner has no statistics for content_chunks.search_vector yet (run ANALYZE content_chunks on the brain host, or let the next sync refresh them); the keyword bound is ${knob}.`,+ return { name, status: 'ok', message: `Skipped: the planner has no statistics for content_chunks.search_vector yet (run ANALYZE content_chunks on the brain host, or let the next sync refresh them); the keyword bound is ${knob}.${recorded}`,details: { ...base, outcome: 'skipped', reason: 'no_statistics' } };}const percent = `${(canary.share * 100).toFixed(1)}%`;@@ -121,15 +140,15 @@ export async function keywordPlanCheck(engine: BrainEngine, probe: KeywordPlanPrif (count.outcome === 'timed_out') {return { name, status: 'warn', details: { ...details, outcome: 'canary_timed_out' },message: `Keyword search's commonest term "${canary.term}" (about ${percent} of chunks) did not finish a strict page count within ${count.ms} ms, so broad keyword queries on this brain are likely to hit ${knob} and fail open to the vector arm (keyword_arm_failed). `- + `A timed-out count is never "no matches". Raising the knob (gbrain config set ${KEYWORD_STATEMENT_TIMEOUT_KEY} <ms>, then restart the serving process) buys time, not a cheaper statement: ranking cost grows with the number of matching chunks (#6495); narrow queries to one source (gbrain search --source-id <id>, MCP source_id). Plan: ${scans.join(', ') || 'unavailable'}. ${coverage}` };+ + `A timed-out count is never "no matches". Raising the knob (gbrain config set ${KEYWORD_STATEMENT_TIMEOUT_KEY} <ms>, then restart the serving process) buys time, not a cheaper statement: ranking cost grows with the number of matching chunks (#6495); narrow queries to one source (gbrain search --source-id <id>, MCP source_id). Plan: ${scans.join(', ') || 'unavailable'}. ${coverage}${recorded}` };}if (count.ms > timeoutMs / 2) {return { name, status: 'warn', details: { ...details, outcome: 'canary_slow' },message: `Keyword search's commonest term "${canary.term}" (about ${percent} of chunks) took ${count.ms} ms for a strict page count, more than half of ${knob}; a slightly broader query or a busier host will hit the bound and fail open to the vector arm (keyword_arm_failed). `- + `A timed-out count is never "no matches". Raising the knob (gbrain config set ${KEYWORD_STATEMENT_TIMEOUT_KEY} <ms>, then restart the serving process) buys time, not a cheaper statement (#6495); narrow queries to one source (gbrain search --source-id <id>, MCP source_id). Plan: ${scans.join(', ') || 'unavailable'}. ${coverage}` };+ + `A timed-out count is never "no matches". Raising the knob (gbrain config set ${KEYWORD_STATEMENT_TIMEOUT_KEY} <ms>, then restart the serving process) buys time, not a cheaper statement (#6495); narrow queries to one source (gbrain search --source-id <id>, MCP source_id). Plan: ${scans.join(', ') || 'unavailable'}. ${coverage}${recorded}` };}return { name, status: 'ok', details: { ...details, outcome: 'ok' },- message: `Keyword search's commonest term "${canary.term}" (about ${percent} of chunks) counted ${count.pages} page(s) in ${count.ms} ms, inside half of ${knob}. Plan: ${scans.join(', ') || 'unavailable'}. ${coverage}` };+ message: `Keyword search's commonest term "${canary.term}" (about ${percent} of chunks) counted ${count.pages} page(s) in ${count.ms} ms, inside half of ${knob}. Plan: ${scans.join(', ') || 'unavailable'}. ${coverage}${recorded}` };} catch (error) {return { name, status: 'warn', message: `Keyword plan could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,details: { health: 'unknown', docs: DOCS } };diff --git a/src/core/config.ts b/src/core/config.tsindex 5640cb2abc..e270874599 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1385,6 +1385,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.hnsw_iterative_scan','search.cjk_keyword_deadline_ms','search.keyword_statement_timeout_ms',+ 'search.keyword_timeout_negative_cache_seconds', // #6495: seconds, default 600, 0 = off (postgres-engine/keyword-timeout-cache.ts)'search.adaptive_return','search.adaptive_return_entity_max','search.adaptive_return_other_max',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 01178a9914..e094feccf9 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -389,6 +389,7 @@ export const CODES = {suggestion: 'Read gbrain sync status --source <id> --json: last_error.root_cause names the request that keeps failing. Fix that request, or raise sync.knock_on_refreeze_limit / sync.knock_on_run_limit, then rerun the same sync.',fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Names the root request, its page and error; read-only.' } },keyword_candidates_incomplete: { class: 'unavailable', summary: "Hybrid search's CJK keyword arm hit its deadline or candidate cap on a large corpus, so some keyword matches can be missing.", why: 'The CJK fallback is an unindexed LIKE scan; the arm is bounded so a large brain cannot stall every hybrid search. An incomplete keyword search is not evidence of absence.', docs: 'docs/guides/multi-language-fts.md#cjk-keyword-budget', suggestion: 'Narrow the search with --source-id (MCP source_id), or ask the user to raise search.cjk_keyword_deadline_ms.', fix: { argv: ['gbrain', 'config', 'get', 'search.cjk_keyword_deadline_ms'], consent: [], actor: 'agent', why: 'Shows the deadline in effect (unset means 3000 ms); read-only.', requires_exclusive: false } },+ keyword_skipped_after_timeout: { class: 'unavailable', summary: "Hybrid search's Postgres keyword arm skipped a statement that hit the keyword statement timeout within the negative-cache TTL; the search reports keyword_arm_failed with reason skipped_after_timeout and the vector arm still answers.", why: 'Running the same broad keyword statement again would hold a backend for the whole search.keyword_statement_timeout_ms and fail the same way. The skip covers that exact statement and scope only, lasts search.keyword_timeout_negative_cache_seconds (default 600, 0 turns it off) and is per serving process. A skipped keyword arm is not evidence of absence.', docs: 'docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain', suggestion: 'Narrow the search (source_id, types, since or until) to run keyword search now, or wait for the entry to expire; the user may raise search.keyword_statement_timeout_ms or change the TTL.', fix: { argv: ['gbrain', 'doctor', '--only', 'keyword_plan', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the keyword statement bound, the recorded keyword timeouts and skips, and whether broad terms can be ranked inside the bound.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'keyword_plan', '--json'] } } },projection_pending: { class: 'retryable', summary: "The current text projection is not ready." },provenance_required: { class: 'caller', summary: "provenance is required and must be non-empty." },publication_pending: { class: 'retryable', summary: "The catalog adoption is accepted but not fully committed." },diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsindex 0d1d9f0612..93450ebab3 100644--- a/src/core/interop-notices.ts+++ b/src/core/interop-notices.ts@@ -120,6 +120,16 @@ function rerankFix(reason: RerankFailedReason, retry?: { op: string; args: Recorreturn { ...doctorFix(why), verify: RERANKER_HEALTH_VERIFY };}+/** #6495: `keyword_arm_failed` with reason `skipped_after_timeout` (postgres-engine/keyword-timeout-cache.ts). */+const KEYWORD_SKIPPED_WHY = 'the keyword arm was skipped: this exact keyword search hit the keyword statement timeout (search.keyword_statement_timeout_ms) within the last search.keyword_timeout_negative_cache_seconds (default 600 seconds), so the brain did not wait for the timeout again; a narrower query (source_id, types, since or until) runs keyword search, and the skip ends by itself when the entry expires';+const KEYWORD_PLAN_VERIFY = { argv: ['gbrain', 'doctor', '--only', 'keyword_plan', '--json'] };+function keywordPlanFix(): Action {+ return {+ argv: KEYWORD_PLAN_VERIFY.argv, consent: [], actor: 'agent', requires_exclusive: false, verify: KEYWORD_PLAN_VERIFY,+ why: "Read-only: doctor's keyword_plan reports the keyword statement bound, how many keyword timeouts and skips this brain recorded, and whether broad terms can be ranked inside the bound; raising the bound or the cache TTL is the user's call.",+ };+}+/** Doctor on the brain host; `run_doctor` where callable (renderAction drops it otherwise). */export function doctorFix(why: string): Action {return { argv: ['gbrain', 'doctor', '--json'], mcp: { tool: 'run_doctor', arguments: {} }, consent: [], actor: 'agent', why, requires_exclusive: false };@@ -157,16 +167,18 @@ export function degradedRecallNotice(const pairs = [...new Set(entries.filter(s => names.includes(s.stage as RecallStage)).map(s => `${s.stage}:${s.reason ?? ''}`))].sort();const persistent = pairs.every(p => CONFIGURATION_PERSISTENT_STAGES.has(p));const rerank = names.includes('rerank_failed') ? rerankReason(entries.find(s => s.stage === 'rerank_failed')?.reason) : undefined;- const labels = names.map(n => (n === 'rerank_failed' ? `rerank_failed: ${rerank}` : n));+ const keywordSkipped = entries.some(s => s.stage === 'keyword_arm_failed' && s.reason === 'skipped_after_timeout');+ const labels = names.map(n => (n === 'rerank_failed' ? `rerank_failed: ${rerank}` : n === 'keyword_arm_failed' && keywordSkipped ? 'keyword_arm_failed: skipped_after_timeout' : n));const whys = names.map(n => (n === 'rerank_failed'? `reranking failed because ${RERANK_REASON_WHY[rerank!]}, so results keep their fused order (fallback: fused_order${opts.rerankDegradedCalls ? `; reranker-degraded calls this session: ${opts.rerankDegradedCalls}` : ''})`- : DEGRADED_STAGE_GUIDANCE[n].why));+ : n === 'keyword_arm_failed' && keywordSkipped ? KEYWORD_SKIPPED_WHY : DEGRADED_STAGE_GUIDANCE[n].why));const guidance = names.map(n => DEGRADED_STAGE_GUIDANCE[n]);const fixKind: StageFix = guidance.some(g => g.fix === 'embeddings') ? 'embeddings' : guidance.some(g => g.fix === 'doctor') ? 'doctor' : null;const byChoice = opts.optedOut || entries.some(s => s.reason === 'embedding_disabled');const emb = fixKind === 'embeddings' ? (byChoice ? { byChoice: true } as { fix?: Action; byChoice: boolean } : embeddingsFix(opts.config, opts.transport)) : undefined;+ const onlyKeywordNeedsDoctor = keywordSkipped && names.every(n => n === 'keyword_arm_failed' || DEGRADED_STAGE_GUIDANCE[n].fix !== 'doctor');const fix = emb ? emb.fix- : fixKind === 'doctor' ? doctorFix('Doctor names the failing retrieval dependency and its fix.')+ : fixKind === 'doctor' ? (onlyKeywordNeedsDoctor ? keywordPlanFix() : doctorFix('Doctor names the failing retrieval dependency and its fix.')): rerank ? rerankFix(rerank, opts.retry) : undefined;const choice = emb?.byChoice ? ' This brain was set up keyword-only by the user\'s choice; mention it only if the user asks why something was not found. No query text was sent to an embedding provider. If the user wants semantic search, `gbrain doctor --json` names the enable command; turning it on needs their consent.' : '';return {diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 129239a575..aad3fc4335 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -140,6 +140,7 @@ import type { EmbeddingState, EmbeddingStateCounts, EmbeddingStateRow } from './import * as chunksImpl from './engine-sql/chunks.ts';import { hasCJK } from './cjk.ts';import { searchKeywordCJK as searchKeywordCJKImpl } from './engine-sql/cjk-search.ts';+import { KeywordTimeoutNegativeCache } from './postgres-engine/keyword-timeout-cache.ts';import * as titlesImpl from './engine-sql/titles.ts';import * as keywordPagesImpl from './engine-sql/keyword-pages.ts';import type { CjkKeywordCtx } from './search/cjk-keyword-sql.ts';@@ -190,6 +191,7 @@ export function getPostgresSchema(export class PostgresEngine implements BrainEngine {private vectorIterativeScan?: Promise<boolean>;private keywordStatementTimeout?: Promise<string>;+ private keywordTimeouts = new KeywordTimeoutNegativeCache();private readonly vectorScope = vectorScopeLoader(() => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL), ids => this.executeRaw<ScopeChunkCount>(SCOPE_CHUNKS_SQL, [ids]));/** Transaction clones keep chunk invalidation and replacement atomic. */private _chunkWritesInTransaction = false;@@ -1133,7 +1135,8 @@ export class PostgresEngine implements BrainEngine {// wrap is identical to master's; flag on → set_config('app.scopes')// shares the same transaction as the timeout.const statementTimeout = await this.keywordStatementTimeoutSetting();- const runKeyword = (queryText: string, relaxed = false) =>+ const runKeyword = (queryText: string, relaxed = false) => this.keywordTimeouts.run(opts?.keywordTimeoutCache === true, this,+ [statementTimeout, relaxed, rawQuery, collapseWebsearchDashRuns(queryText), params.slice(1), opts?.sourceIds ?? null, opts?.sourceId ?? null], () =>this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {await tx`SELECT set_config('statement_timeout', ${statementTimeout}, true)`;const previous = relaxed ? await tx`SHOW enable_seqscan` : [];@@ -1143,7 +1146,7 @@ export class PostgresEngine implements BrainEngine {const rows = await tx.unsafe(rawQuery, boundParams as Parameters<typeof tx.unsafe>[1]);if (relaxed) await tx`SELECT set_config('enable_seqscan', ${previous[0].enable_seqscan}, true)`;return rows;- }, { alwaysTransaction: true, jitOff: true });+ }, { alwaysTransaction: true, jitOff: true }));let rows = await runKeyword(query);// D2 fix (fix/title-retrieval-arm): websearch AND semantics at chunk// grain mean one non-co-occurring token zeroes keyword recall. When thediff --git a/src/core/postgres-engine/keyword-timeout-cache.ts b/src/core/postgres-engine/keyword-timeout-cache.tsnew file mode 100644index 0000000000..65be0054b7--- /dev/null+++ b/src/core/postgres-engine/keyword-timeout-cache.ts@@ -0,0 +1,158 @@+/**+ * #6495 keyword timeout negative cache: after hybrid search's keyword arm+ * hits the Postgres statement timeout (SQLSTATE 57014 from+ * `search.keyword_statement_timeout_ms`), the engine remembers that exact+ * statement for `search.keyword_timeout_negative_cache_seconds` (default 600,+ * 0 = off) and, until the entry expires, refuses to run it again with+ * `KeywordSkippedAfterTimeoutError` instead of holding a backend for the full+ * timeout once more. The arm reports `keyword_arm_failed` with reason+ * `skipped_after_timeout` and the vector arm still answers.+ *+ * What makes two searches "the same": the key is a hash of the statement+ * text, every bound parameter (the tsquery text, types, dates, slug+ * exclusions, limits), the RLS source scope and the statement timeout in+ * effect. The visibility and trust floor of the caller live in the statement+ * text, so a narrower, differently scoped or differently trusted query is a+ * different key and still runs. The strict statement and the relaxed (OR)+ * retry are separate keys. Each engine instance (one per brain) owns its+ * cache, so another brain in the same process is never affected.+ *+ * Admission: only a genuine statement-timeout diagnostic records an entry;+ * a user or admin cancel (`canceling statement due to user request`), a lock+ * timeout or a connection failure never does. Entries expire at the TTL, so a+ * transient contention spike recovers by itself, and the map is bounded+ * (MAX_ENTRIES, oldest dropped first). A caller that passes `useCache: false`+ * to hybrid search does not consult the cache.+ *+ * Cost: a search that never times out does nothing extra (no statement, no+ * config read). The TTL is read once, on the first timeout after the engine+ * is created; each timeout then writes one bounded counter row+ * (`search.keyword_timeout_stats`: timeouts, skips counted since the previous+ * write, last timeout time), never one per search. Doctor `keyword_plan`+ * reads it. The cache lives in process memory, so `gbrain serve` and MCP+ * sessions benefit; a one-shot CLI command starts empty.+ *+ * Postgres only: PGLite runs keyword search with no statement timeout.+ */+import { createHash } from 'node:crypto';++export const KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY = 'search.keyword_timeout_negative_cache_seconds';+export const KEYWORD_TIMEOUT_NEGATIVE_CACHE_DEFAULT_S = 600;+export const KEYWORD_TIMEOUT_NEGATIVE_CACHE_MAX_S = 86_400;+/** The bounded counter row a timeout writes and doctor `keyword_plan` reads (not a `config set` key). */+export const KEYWORD_TIMEOUT_STATS_KEY = 'search.keyword_timeout_stats';+export const KEYWORD_TIMEOUT_NEGATIVE_CACHE_MAX_ENTRIES = 256;+const COUNTER_CAP = 1_000_000_000;++/** The configured seconds when `raw` is an integer in 0..86400, else undefined. */+export function keywordTimeoutNegativeCacheSeconds(raw: unknown): number | undefined {+ if (raw === undefined || raw === null || raw === '') return undefined;+ const n = typeof raw === 'string' ? Number(raw.trim()) : Number(raw);+ return Number.isInteger(n) && n >= 0 && n <= KEYWORD_TIMEOUT_NEGATIVE_CACHE_MAX_S ? n : undefined;+}++/** `config set` refusal text, or null when the value is valid. */+export function keywordTimeoutNegativeCacheValueProblem(value: string): string | null {+ return keywordTimeoutNegativeCacheSeconds(value) !== undefined+ ? null+ : `${KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY} must be an integer number of seconds from 0 (off) to ${KEYWORD_TIMEOUT_NEGATIVE_CACHE_MAX_S} (got '${value}'). Nothing was written.`;+}++/** A genuine `statement_timeout` cancel: SQLSTATE 57014 with the timeout diagnostic, never a user or admin cancel. */+export function isGenuineStatementTimeout(error: unknown): boolean {+ if (!error || typeof error !== 'object') return false;+ const { code, message } = error as { code?: unknown; message?: unknown };+ return code === '57014' && typeof message === 'string' && /due to statement timeout/i.test(message);+}++/** Thrown instead of running a keyword statement that timed out within the TTL. */+export class KeywordSkippedAfterTimeoutError extends Error {+ readonly code = 'keyword_skipped_after_timeout';+ constructor(readonly retryAfterSeconds: number) {+ super(`keyword statement skipped: the same statement hit the keyword statement timeout and is skipped for ${retryAfterSeconds}s more (${KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY})`);+ this.name = 'KeywordSkippedAfterTimeoutError';+ }+}++export function isKeywordSkippedAfterTimeout(error: unknown): error is KeywordSkippedAfterTimeoutError {+ return error instanceof KeywordSkippedAfterTimeoutError;+}++export interface KeywordTimeoutStats { timeouts: number; skips: number; last_timeout_at: string | null }++/** Parse the counter row; anything unreadable is no record. */+export function parseKeywordTimeoutStats(raw: string | null | undefined): KeywordTimeoutStats | null {+ if (!raw) return null;+ try {+ const v = JSON.parse(raw) as Partial<KeywordTimeoutStats>;+ const count = (n: unknown) => (typeof n === 'number' && Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0);+ return { timeouts: count(v.timeouts), skips: count(v.skips), last_timeout_at: typeof v.last_timeout_at === 'string' ? v.last_timeout_at : null };+ } catch {+ return null;+ }+}++// engine-sql-ok: Postgres-only counter row the keyword timeout cache writes once per statement timeout (keys inlined; scalar binds); PGLite has no keyword statement timeout+export const KEYWORD_TIMEOUT_TTL_CONFIG_SQL = `SELECT value FROM config WHERE key = '${KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY}'`;+// engine-sql-ok: one upsert per statement timeout; the counters stay bounded by COUNTER_CAP and a malformed row restarts at zero+export const KEYWORD_TIMEOUT_STATS_UPSERT_SQL = `INSERT INTO config (key, value)+ VALUES ('${KEYWORD_TIMEOUT_STATS_KEY}', json_build_object('timeouts', 1, 'skips', LEAST($1::bigint, ${COUNTER_CAP}), 'last_timeout_at', $2::text)::text)+ ON CONFLICT (key) DO UPDATE SET value = json_build_object(+ 'timeouts', LEAST(CASE WHEN config.value ~ '"timeouts"[[:space:]]*:[[:space:]]*[0-9]+' THEN substring(config.value from '"timeouts"[[:space:]]*:[[:space:]]*([0-9]+)')::numeric ELSE 0 END + 1, ${COUNTER_CAP}),+ 'skips', LEAST(CASE WHEN config.value ~ '"skips"[[:space:]]*:[[:space:]]*[0-9]+' THEN substring(config.value from '"skips"[[:space:]]*:[[:space:]]*([0-9]+)')::numeric ELSE 0 END + $1::bigint, ${COUNTER_CAP}),+ 'last_timeout_at', $2::text)::text`;++export interface KeywordTimeoutDb { executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> }++/** One engine's negative cache (see the module comment). */+export class KeywordTimeoutNegativeCache {+ private entries = new Map<string, number>();+ private ttlMs?: Promise<number>;+ private pendingSkips = 0;++ constructor(private readonly now: () => number = Date.now) {}++ /**+ * Run one keyword statement. With `enabled` false (no hybrid opt-in, or a+ * fresh search) this is `exec()`. Otherwise a key recorded within its TTL+ * throws KeywordSkippedAfterTimeoutError without running anything, and a+ * genuine statement timeout records the key before the error propagates.+ */+ async run<T>(enabled: boolean, db: KeywordTimeoutDb, keyParts: unknown[], exec: () => Promise<T>): Promise<T> {+ if (!enabled) return exec();+ const key = createHash('sha256').update(JSON.stringify(keyParts)).digest('hex');+ const expiresAt = this.entries.get(key);+ if (expiresAt !== undefined) {+ const remaining = expiresAt - this.now();+ if (remaining > 0) {+ this.pendingSkips++;+ throw new KeywordSkippedAfterTimeoutError(Math.ceil(remaining / 1000));+ }+ this.entries.delete(key);+ }+ try {+ return await exec();+ } catch (error) {+ if (isGenuineStatementTimeout(error)) await this.recordTimeout(key, db);+ throw error;+ }+ }++ private async recordTimeout(key: string, db: KeywordTimeoutDb): Promise<void> {+ const ttlMs = await (this.ttlMs ??= db.executeRaw<{ value: string }>(KEYWORD_TIMEOUT_TTL_CONFIG_SQL)+ .then(rows => (keywordTimeoutNegativeCacheSeconds(rows[0]?.value) ?? KEYWORD_TIMEOUT_NEGATIVE_CACHE_DEFAULT_S) * 1000)+ .catch(() => KEYWORD_TIMEOUT_NEGATIVE_CACHE_DEFAULT_S * 1000));+ if (ttlMs > 0) {+ this.entries.delete(key);+ this.entries.set(key, this.now() + ttlMs);+ for (const oldest of this.entries.keys()) {+ if (this.entries.size <= KEYWORD_TIMEOUT_NEGATIVE_CACHE_MAX_ENTRIES) break;+ this.entries.delete(oldest);+ }+ }+ const skips = this.pendingSkips;+ this.pendingSkips = 0;+ await db.executeRaw(KEYWORD_TIMEOUT_STATS_UPSERT_SQL, [skips, new Date(this.now()).toISOString()])+ .catch(() => { this.pendingSkips += skips; });+ }+}diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.tsindex c29ba26f45..86ef36b253 100644--- a/src/core/search/hybrid/arms.ts+++ b/src/core/search/hybrid/arms.ts@@ -14,6 +14,7 @@ import { type VectorArm, pushVectorList } from '../fusion-lists.ts';import { buildRelationalArm } from '../relational-recall.ts';import { isAmbiguousModalityQuery } from '../query-intent.ts';import { isDbAccessFailure } from '../../pg-access-classify.ts';+import { isKeywordSkippedAfterTimeout } from '../../postgres-engine/keyword-timeout-cache.ts';import { isTimeoutError, pushDegraded } from './degraded.ts';import { markKeywordHits } from '../evidence.ts';import { resolveEffectiveRecency, resolveEffectiveSalience } from './effective-modes.ts';@@ -76,8 +77,13 @@ export async function runLexicalArms(req: HybridRequest, earlyModality: ModalityearlyModality === 'image'? [[], []]: await Promise.all([- req.timer.overlap('keyword_arm', engine.searchKeyword(query, searchOpts)).catch((err: unknown) => {+ req.timer.overlap('keyword_arm', engine.searchKeyword(query, opts?.useCache === false ? searchOpts : { ...searchOpts, keywordTimeoutCache: true })).catch((err: unknown) => {if (isDatetimeInputError(err)) throw err;+ if (isKeywordSkippedAfterTimeout(err)) {+ pushDegraded(degraded, 'keyword_arm_failed', 'skipped_after_timeout');+ warnOncePerProcess('search-keyword-arm-skipped', `[gbrain] searchKeyword arm skipped (fail-open): ${err.message}`);+ return [] as SearchResult[];+ }if (isDbAccessFailure(err)) keywordAccessError = err;pushDegraded(degraded, 'keyword_arm_failed', isTimeoutError(err) ? 'timeout' : 'provider_error');warnOncePerProcess(diff --git a/src/core/types.ts b/src/core/types.tsindex 16dff0bd0a..d798758a97 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1333,6 +1333,8 @@ export interface SearchOpts extends PageReadPolicy {* ignores this flag.*/orFallback?: boolean;+ /** #6495: hybrid's keyword arm opts in to the Postgres keyword timeout negative cache (postgres-engine/keyword-timeout-cache.ts); PGLite ignores it. */+ keywordTimeoutCache?: boolean;/** Keyword `score` query (websearch syntax) while `query` decides the matches (alias fan-out); ignored on the CJK path. */rankQuery?: string;/**@@ -1424,6 +1426,7 @@ export interface SearchOpts extends PageReadPolicy {* call. When undefined, the cache decision falls back to global config* (search.cache.enabled, default true). Set to `false` to force a fresh* search; set to `true` to opt in even when global config has it off.+ * `false` also bypasses the keyword timeout negative cache (#6495).*/useCache?: boolean;/**@@ -2091,6 +2094,7 @@ export const DEGRADED_REASONS = ['iterative_scan_unavailable','egress_denied', // System One: the Jev reranker skipped a query with a candidate from decide.egress.deny_sources'embedding_disabled', // the brain opted out of embedding: the query text was never sent to the provider+ 'skipped_after_timeout', // #6495: keyword_arm_failed; the same keyword statement timed out within search.keyword_timeout_negative_cache_seconds] as const;export type DegradedReason = (typeof DEGRADED_REASONS)[number];diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.tsindex 4f812dcbe3..1a7deb6dfc 100644--- a/test/config-search-registry.test.ts+++ b/test/config-search-registry.test.ts@@ -38,6 +38,7 @@ const DIRECTLY_READ_SINGLETONS = ['search.hnsw_iterative_scan', // search/hnsw-iterative-scan.ts via loadConfigWithEngine'search.cjk_keyword_deadline_ms', // search/cjk-keyword-deadline.ts via loadConfigWithEngine'search.keyword_statement_timeout_ms', // postgres-engine/keyword-statement-timeout.ts (engine.getConfig once per connection) + loadConfigWithEngine+ 'search.keyword_timeout_negative_cache_seconds', // postgres-engine/keyword-timeout-cache.ts (read on the first keyword timeout)'search.crag_escalation', // ops/search.ts'search.alias_fanout_max', // search/alias-fanout.ts'search.demote_generated', // search/provenance-demotion.tsdiff --git a/test/keyword-timeout-negative-cache-6495.test.ts b/test/keyword-timeout-negative-cache-6495.test.tsnew file mode 100644index 0000000000..17b496434e--- /dev/null+++ b/test/keyword-timeout-negative-cache-6495.test.ts@@ -0,0 +1,376 @@+/**+ * #6495: the Postgres keyword timeout negative cache.+ *+ * Contract protected: after hybrid search's keyword statement hits the+ * statement timeout (a genuine 57014 timeout diagnostic, never a user+ * cancel), the same statement with the same parameters and scope is skipped+ * for `search.keyword_timeout_negative_cache_seconds` (default 600, 0 = off)+ * and the keyword arm reports `keyword_arm_failed: skipped_after_timeout`+ * instead of waiting for the timeout again. A narrower or differently scoped+ * query, another brain, a fresh search (`useCache: false`) and every caller+ * that did not opt in still run. A search that never times out costs no extra+ * statement; each timeout writes one bounded counter row that doctor+ * `keyword_plan` reads. Regression that fails it: master re-runs the timed-out+ * statement on every search and holds a backend for the whole bound again.+ *+ * Unit arm: the real engine method over an injected executor (the scoped+ * read transaction yields a recording handle whose keyword statement can be+ * made to time out). Postgres arm (DATABASE_URL): a session holding ACCESS+ * EXCLUSIVE on the searched tables makes the keyword statement wait until+ * Postgres cancels it, and the counter upsert runs on a real config table.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import postgres from '#postgres';+import type { BrainEngine } from '../src/core/engine.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import {+ KEYWORD_TIMEOUT_NEGATIVE_CACHE_DEFAULT_S,+ KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY,+ KEYWORD_TIMEOUT_NEGATIVE_CACHE_MAX_ENTRIES,+ KEYWORD_TIMEOUT_STATS_KEY,+ KeywordSkippedAfterTimeoutError,+ KeywordTimeoutNegativeCache,+ isGenuineStatementTimeout,+ keywordTimeoutNegativeCacheValueProblem,+ parseKeywordTimeoutStats,+} from '../src/core/postgres-engine/keyword-timeout-cache.ts';+import { KEYWORD_STATEMENT_TIMEOUT_KEY } from '../src/core/postgres-engine/keyword-statement-timeout.ts';+import { runLexicalArms } from '../src/core/search/hybrid/arms.ts';+import { UNTIMED } from '../src/core/search/stage-timings.ts';+import { degradedRecallNotice } from '../src/core/interop-notices.ts';+import { keywordPlanCheck, type KeywordPlanProbe } from '../src/commands/doctor/checks/keyword-plan.ts';+import { CODES } from '../src/core/error-registry.ts';+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';+import type { DegradedStageEntry, SearchOpts, SearchResult } from '../src/core/types.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const TIMEOUT = Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });+const USER_CANCEL = Object.assign(new Error('canceling statement due to user request'), { code: '57014' });+const CACHE: SearchOpts = { keywordTimeoutCache: true };++interface Harness {+ engine: PostgresEngine;+ /** Keyword statements that reached the executor. */+ statements: () => number;+ /** Every statement and config read/write, in order. */+ all: string[];+ /** The next keyword statement(s) fail with this error; relaxed-only when `relaxedOnly`. */+ failNext: (error: Error | null, opts?: { relaxedOnly?: boolean }) => void;+ setClock: (ms: number) => void;+}++/** A PostgresEngine whose scoped read transactions run over a recording handle; the keyword statement can be made to fail. */+function harness(opts: { ttl?: string | null } = {}): Harness {+ const engine = new PostgresEngine();+ const all: string[] = [];+ let keywordStatements = 0;+ let failure: Error | null = null;+ let relaxedOnly = false;+ let clock = 1_000_000;+ let inRelaxed = false;+ const tx = Object.assign(+ async (strings: TemplateStringsArray, ..._values: unknown[]) => {+ const sql = strings.join('$');+ all.push(sql);+ if (/SET LOCAL enable_seqscan = off/.test(sql)) inRelaxed = true;+ return /SHOW enable_seqscan/i.test(sql) ? [{ enable_seqscan: 'on' }] : [];+ },+ {+ unsafe: async (sql: string) => {+ all.push(sql);+ keywordStatements++;+ const relaxed = inRelaxed;+ inRelaxed = false;+ if (failure && (!relaxedOnly || relaxed)) throw failure;+ return [];+ },+ },+ );+ const priv = engine as unknown as {+ withScopedReadTransaction: (ids: unknown, id: unknown, cb: (tx: unknown) => Promise<unknown>) => Promise<unknown>;+ executeRaw: (sql: string, params?: unknown[]) => Promise<unknown[]>;+ _savedConfig: Record<string, unknown> | undefined;+ _pageTransaction: boolean;+ keywordTimeouts: KeywordTimeoutNegativeCache;+ };+ priv.withScopedReadTransaction = (_ids, _id, cb) => cb(tx);+ priv.executeRaw = async (sql) => {+ all.push(sql);+ if (sql.includes(KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY)) return opts.ttl == null ? [] : [{ value: opts.ttl }];+ if (sql.includes(KEYWORD_STATEMENT_TIMEOUT_KEY)) return [];+ return [];+ };+ priv._savedConfig = { keyword_statement_timeout_ms: 8000 };+ priv._pageTransaction = true;+ priv.keywordTimeouts = new KeywordTimeoutNegativeCache(() => clock);+ return {+ engine,+ all,+ statements: () => keywordStatements,+ failNext: (error, o) => { failure = error; relaxedOnly = o?.relaxedOnly ?? false; },+ setClock: (ms) => { clock = ms; },+ };+}++async function outcome(run: () => Promise<unknown>): Promise<string> {+ try {+ await run();+ return 'ran';+ } catch (error) {+ return error instanceof KeywordSkippedAfterTimeoutError ? 'skipped' : String((error as { code?: string }).code ?? (error as Error).message);+ }+}++describe('keyword timeout negative cache: the engine runner', () => {+ test('after a recorded statement timeout the same statement is skipped without running', async () => {+ const h = harness();+ h.failNext(TIMEOUT);+ expect(await outcome(() => h.engine.searchKeyword('contract terms', CACHE))).toBe('57014');+ expect(h.statements()).toBe(1);+ expect(await outcome(() => h.engine.searchKeyword('contract terms', CACHE))).toBe('skipped');+ expect(h.statements()).toBe(1);+ const error = await h.engine.searchKeyword('contract terms', CACHE).catch((e: unknown) => e) as KeywordSkippedAfterTimeoutError;+ expect(error.code).toBe('keyword_skipped_after_timeout');+ expect(error.retryAfterSeconds).toBe(KEYWORD_TIMEOUT_NEGATIVE_CACHE_DEFAULT_S);+ });++ test('a narrower or differently scoped query after an unscoped timeout still runs', async () => {+ const h = harness();+ h.failNext(TIMEOUT);+ await outcome(() => h.engine.searchKeyword('contract terms', CACHE));+ h.failNext(null);+ expect(await outcome(() => h.engine.searchKeyword('contract terms', { ...CACHE, sourceId: 'alpha' }))).toBe('ran');+ expect(await outcome(() => h.engine.searchKeyword('contract terms', { ...CACHE, sourceIds: ['alpha', 'beta'] }))).toBe('ran');+ expect(await outcome(() => h.engine.searchKeyword('contract terms', { ...CACHE, types: ['person'] }))).toBe('ran');+ expect(await outcome(() => h.engine.searchKeyword('contract terms', { ...CACHE, afterDate: '2026-01-01' }))).toBe('ran');+ expect(await outcome(() => h.engine.searchKeyword('contract terms', { ...CACHE, excludePrivate: true }))).toBe('ran');+ expect(await outcome(() => h.engine.searchKeyword('contract terms acme', CACHE))).toBe('ran');+ expect(h.statements()).toBe(7);+ });++ test('a second brain is unaffected', async () => {+ const a = harness();+ const b = harness();+ a.failNext(TIMEOUT);+ await outcome(() => a.engine.searchKeyword('contract terms', CACHE));+ expect(await outcome(() => a.engine.searchKeyword('contract terms', CACHE))).toBe('skipped');+ expect(await outcome(() => b.engine.searchKeyword('contract terms', CACHE))).toBe('ran');+ });++ test('a user or admin cancel is never cached; callers that did not opt in always run', async () => {+ const h = harness();+ h.failNext(USER_CANCEL);+ await outcome(() => h.engine.searchKeyword('contract terms', CACHE));+ expect(await outcome(() => h.engine.searchKeyword('contract terms', CACHE))).toBe('57014');+ expect(h.statements()).toBe(2);+ h.failNext(TIMEOUT);+ await outcome(() => h.engine.searchKeyword('contract terms', CACHE));+ h.failNext(null);+ expect(await outcome(() => h.engine.searchKeyword('contract terms'))).toBe('ran');+ expect(isGenuineStatementTimeout(TIMEOUT)).toBe(true);+ expect(isGenuineStatementTimeout(USER_CANCEL)).toBe(false);+ expect(isGenuineStatementTimeout(Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' }))).toBe(false);+ });++ test('entries expire at the TTL, so a transient spike recovers on its own; TTL 0 turns the skip off', async () => {+ const h = harness({ ttl: '60' });+ h.failNext(TIMEOUT);+ await outcome(() => h.engine.searchKeyword('contract terms', CACHE));+ h.failNext(null);+ h.setClock(1_000_000 + 59_000);+ expect(await outcome(() => h.engine.searchKeyword('contract terms', CACHE))).toBe('skipped');+ h.setClock(1_000_000 + 60_000);+ expect(await outcome(() => h.engine.searchKeyword('contract terms', CACHE))).toBe('ran');++ const off = harness({ ttl: '0' });+ off.failNext(TIMEOUT);+ await outcome(() => off.engine.searchKeyword('contract terms', CACHE));+ expect(await outcome(() => off.engine.searchKeyword('contract terms', CACHE))).toBe('57014');+ });++ test('the strict statement and the relaxed (OR) retry are cached separately', async () => {+ const h = harness();+ h.failNext(TIMEOUT, { relaxedOnly: true });+ expect(await outcome(() => h.engine.searchKeyword('contract terms', { ...CACHE, orFallback: true }))).toBe('57014');+ expect(h.statements()).toBe(2);+ expect(await outcome(() => h.engine.searchKeyword('contract terms', { ...CACHE, orFallback: true }))).toBe('skipped');+ expect(h.statements()).toBe(3);+ expect(await outcome(() => h.engine.searchKeyword('contract terms', CACHE))).toBe('ran');+ });++ test('zero extra statements per search; one TTL read and one counter write per timeout', async () => {+ const h = harness();+ await h.engine.searchKeyword('contract terms', CACHE);+ const perSearch = h.all.length;+ await h.engine.searchKeyword('contract terms', CACHE);+ await h.engine.searchKeyword('contract terms');+ expect(h.all.length).toBe(perSearch * 3);+ expect(h.all.filter(sql => sql.includes('search.keyword_timeout'))).toEqual([]);++ h.failNext(TIMEOUT);+ await outcome(() => h.engine.searchKeyword('contract terms', CACHE));+ await outcome(() => h.engine.searchKeyword('contract terms', CACHE));+ await outcome(() => h.engine.searchKeyword('contract terms', CACHE));+ await outcome(() => h.engine.searchKeyword('broad words', CACHE));+ const cacheSql = h.all.filter(sql => sql.includes('search.keyword_timeout'));+ expect(cacheSql.filter(sql => sql.includes(KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY))).toHaveLength(1);+ expect(cacheSql.filter(sql => sql.includes(KEYWORD_TIMEOUT_STATS_KEY))).toHaveLength(2);+ });++ test('the entry count is bounded', async () => {+ const cache = new KeywordTimeoutNegativeCache(() => 0);+ const db = { executeRaw: async () => [] as never[] };+ for (let i = 0; i < KEYWORD_TIMEOUT_NEGATIVE_CACHE_MAX_ENTRIES + 50; i++) {+ await cache.run(true, db, [i], () => Promise.reject(TIMEOUT)).catch(() => {});+ }+ expect((cache as unknown as { entries: Map<string, number> }).entries.size).toBe(KEYWORD_TIMEOUT_NEGATIVE_CACHE_MAX_ENTRIES);+ expect(await cache.run(true, db, [0], async () => 'ran')).toBe('ran');+ await expect(cache.run(true, db, [KEYWORD_TIMEOUT_NEGATIVE_CACHE_MAX_ENTRIES + 49], async () => 'ran')).rejects.toBeInstanceOf(KeywordSkippedAfterTimeoutError);+ });+});++describe('keyword timeout negative cache: the hybrid keyword arm', () => {+ function arm(searchKeyword: (q: string, o: SearchOpts) => Promise<SearchResult[]>, opts: Record<string, unknown> = {}) {+ const seen: SearchOpts[] = [];+ const engine = {+ searchKeyword: (q: string, o: SearchOpts) => { seen.push(o); return searchKeyword(q, o); },+ searchTitles: async () => [],+ } as unknown as BrainEngine;+ const degraded: DegradedStageEntry[] = [];+ const req = { engine, query: 'contract terms', opts, searchOpts: { limit: 10 }, identityTierOpts: {}, degraded, timer: UNTIMED };+ return { run: () => runLexicalArms(req as never, 'text'), degraded, seen };+ }++ test('a skipped statement reports keyword_arm_failed: skipped_after_timeout and the search goes on', async () => {+ const { run, degraded, seen } = arm(async () => { throw new KeywordSkippedAfterTimeoutError(42); });+ const lexical = await run();+ expect(lexical.keywordResults).toEqual([]);+ expect(degraded).toEqual([{ stage: 'keyword_arm_failed', reason: 'skipped_after_timeout' }]);+ expect(seen[0]?.keywordTimeoutCache).toBe(true);+ });++ test('a fresh search (useCache: false) does not consult the cache; a real timeout still reports timeout', async () => {+ const fresh = arm(async () => [], { useCache: false });+ await fresh.run();+ expect(fresh.seen[0]?.keywordTimeoutCache).toBeUndefined();+ const timedOut = arm(async () => { throw TIMEOUT; });+ await timedOut.run();+ expect(timedOut.degraded).toEqual([{ stage: 'keyword_arm_failed', reason: 'timeout' }]);+ });++ test('the degraded_recall notice names the skip, its TTL key and the keyword_plan check', () => {+ const notice = degradedRecallNotice([{ stage: 'keyword_arm_failed', reason: 'skipped_after_timeout' }], { transport: 'stdio' })!;+ expect(notice.why).toContain('keyword_arm_failed: skipped_after_timeout');+ expect(notice.why).toContain(KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY);+ expect(notice.fix?.argv).toEqual(['gbrain', 'doctor', '--only', 'keyword_plan', '--json']);+ expect(notice.fix?.verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'keyword_plan', '--json']);+ const plain = degradedRecallNotice([{ stage: 'keyword_arm_failed', reason: 'timeout' }], { transport: 'stdio' })!;+ expect(plain.why).not.toContain('skipped');+ expect(plain.fix?.argv).toEqual(['gbrain', 'doctor', '--json']);+ });+});++describe('keyword timeout negative cache: config, registry and doctor', () => {+ test('the key is registered with a config set validator (integer seconds, 0 = off, cap 86400)', () => {+ expect(KNOWN_CONFIG_KEYS).toContain(KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY);+ for (const ok of ['0', '600', '86400']) expect(keywordTimeoutNegativeCacheValueProblem(ok)).toBeNull();+ for (const bad of ['-1', '86401', '10m', '1.5', '']) {+ expect(keywordTimeoutNegativeCacheValueProblem(bad)).toBe(+ `${KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY} must be an integer number of seconds from 0 (off) to 86400 (got '${bad}'). Nothing was written.`);+ }+ expect(CODES.keyword_skipped_after_timeout.fix?.verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'keyword_plan', '--json']);+ });++ test('doctor keyword_plan reads the counter row into details.negative_cache and names it', async () => {+ const config: Record<string, string> = {+ [KEYWORD_TIMEOUT_STATS_KEY]: JSON.stringify({ timeouts: 3, skips: 7, last_timeout_at: '2026-10-15T10:00:00.000Z' }),+ };+ const engine = { kind: 'postgres', getConfig: async (k: string) => config[k] ?? null } as unknown as BrainEngine;+ const probe: KeywordPlanProbe = { chunkEstimate: async () => 100, canary: async () => null, explain: async () => [], count: async () => ({ outcome: 'counted', pages: 0, ms: 1 }) };+ const check = await keywordPlanCheck(engine, probe);+ expect(check.details?.negative_cache).toEqual({ ttl_seconds: 600, timeouts: 3, skips: 7, last_timeout_at: '2026-10-15T10:00:00.000Z' });+ expect(check.message).toContain('hit this bound 3 time(s)');+ expect(check.message).toContain(`${KEYWORD_TIMEOUT_NEGATIVE_CACHE_KEY}; 0 turns it off`);+ const quiet = await keywordPlanCheck({ kind: 'postgres', getConfig: async () => null } as unknown as BrainEngine, probe);+ expect(quiet.details?.negative_cache).toEqual({ ttl_seconds: 600, timeouts: 0, skips: 0, last_timeout_at: null });+ expect(quiet.message).not.toContain('hit this bound');+ });+});++if (testBackends().includes('postgres')) {+ describe('postgres: a real statement timeout is skipped next time and counted', () => {+ let engine: PostgresEngine;+ let databaseUrl: string;+ let close: () => Promise<void>;+ let locker: ReturnType<typeof postgres>;+ let releaseLock: () => Promise<void>;++ beforeAll(async () => {+ ({ engine, databaseUrl, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ await engine.putPage('notes/alpha', { type: 'note', title: 'Alpha beta', compiled_truth: 'alpha beta gamma' });+ await installFixtureChunks(engine, 'notes/alpha', [{ chunk_index: 0, chunk_text: 'alpha beta gamma', chunk_source: 'compiled_truth' }]);+ locker = postgres(databaseUrl, { max: 1, prepare: false });+ }, 120_000);+ afterAll(async () => {+ await releaseLock?.().catch(() => {});+ await locker?.end({ timeout: 5 }).catch(() => {});+ await close?.();+ });++ async function holdLock(): Promise<void> {+ let release!: () => void;+ const released = new Promise<void>(resolve => { release = resolve; });+ let locked!: () => void;+ const lockedUp = new Promise<void>(resolve => { locked = resolve; });+ const held = locker.begin(async tx => {+ await tx.unsafe('LOCK TABLE content_chunks, pages IN ACCESS EXCLUSIVE MODE');+ locked();+ await released;+ }).catch(() => {});+ releaseLock = async () => { release(); await held; };+ await lockedUp;+ }++ test('the second identical search returns at once with the skip; a scoped one still waits; the counter row is written', async () => {+ await engine.setConfig(KEYWORD_STATEMENT_TIMEOUT_KEY, '1000');+ const bounded = new PostgresEngine();+ await bounded.connect({ database_url: databaseUrl, poolSize: 2 });+ try {+ await holdLock();+ let started = performance.now();+ expect(await outcome(() => bounded.searchKeyword('alpha beta', CACHE))).toBe('57014');+ expect(performance.now() - started).toBeGreaterThanOrEqual(900);+ started = performance.now();+ expect(await outcome(() => bounded.searchKeyword('alpha beta', CACHE))).toBe('skipped');+ expect(performance.now() - started).toBeLessThan(500);+ expect(await outcome(() => bounded.searchKeyword('alpha beta', { ...CACHE, sourceId: 'default' }))).toBe('57014');+ await releaseLock();+ const stats = parseKeywordTimeoutStats(await engine.getConfig(KEYWORD_TIMEOUT_STATS_KEY));+ expect(stats?.timeouts).toBe(2);+ expect(stats?.skips).toBe(1);+ expect(stats?.last_timeout_at).toMatch(/^\d{4}-\d{2}-\d{2}T/);+ expect(await outcome(() => bounded.searchKeyword('alpha beta', { ...CACHE, sourceId: 'default' }))).toBe('skipped');+ expect((await bounded.searchKeyword('alpha beta')).map(r => r.slug)).toEqual(['notes/alpha']);+ expect((await bounded.searchKeyword('alpha', CACHE)).map(r => r.slug)).toEqual(['notes/alpha']);+ } finally {+ await releaseLock();+ await bounded.disconnect();+ await engine.unsetConfig(KEYWORD_STATEMENT_TIMEOUT_KEY);+ await engine.unsetConfig(KEYWORD_TIMEOUT_STATS_KEY);+ }+ }, 120_000);++ test('the counter upsert survives a malformed row and stays bounded', async () => {+ await engine.setConfig(KEYWORD_TIMEOUT_STATS_KEY, 'not json');+ const cache = new KeywordTimeoutNegativeCache();+ await cache.run(true, engine, ['malformed'], () => Promise.reject(TIMEOUT)).catch(() => {});+ expect(parseKeywordTimeoutStats(await engine.getConfig(KEYWORD_TIMEOUT_STATS_KEY))).toMatchObject({ timeouts: 1, skips: 0 });+ await engine.setConfig(KEYWORD_TIMEOUT_STATS_KEY, JSON.stringify({ timeouts: 999_999_999_999, skips: 5 }));+ await cache.run(true, engine, ['bounded'], () => Promise.reject(TIMEOUT)).catch(() => {});+ expect(parseKeywordTimeoutStats(await engine.getConfig(KEYWORD_TIMEOUT_STATS_KEY))).toMatchObject({ timeouts: 1_000_000_000, skips: 5 });+ await engine.unsetConfig(KEYWORD_TIMEOUT_STATS_KEY);+ });+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 453df02aff..7d5f9aa33a 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -62,6 +62,7 @@ test/import-frontmatter-key-order-5158.test.tstest/import-inline-chunk-keep.test.tstest/import-revision-concurrency.test.tstest/keyword-statement-timeout-knob-6495.test.ts+test/keyword-timeout-negative-cache-6495.test.tstest/lane-apply-pipelining.test.tstest/link-cross-source.test.tstest/link-preparation-shared-index.test.ts