Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Revert "fix(search): make the Postgres lexical search statement timeout configurable (#5024)"

time-attackab54927c7e86
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index f561558199..38ccccc74b 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2183 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 nullable
src/core/operations.ts 339 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)
src/core/pglite-engine.ts 2996 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)
-src/core/postgres-engine.ts 2947 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); +6 #5024: lexical arms pre-read search.statement_timeout_ms through the per-engine SearchStatementTimeout memo (resolver in postgres-engine/search-settings.ts)
+src/core/postgres-engine.ts 2941 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)
src/core/search/hybrid.ts 1591 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +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
src/core/types.ts 2213 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 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)
src/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)
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1586 ratchet new row: crossed 1500 in v0.46.25.0
src/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 refresh
src/commands/hook.ts 1904 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)
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1877 ratchet +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; +1 #5024: search.statement_timeout_ms registered in KNOWN_CONFIG_KEYS
+src/core/config.ts 1876 ratchet +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
src/core/bootstrap/harness.ts 2711 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
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 671 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 362145ca8b..70e1b79df1 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -380,7 +380,6 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:
if (err) { console.error(`[config] ${err}`); process.exit(1); }
}
(await import('./config/enumerated-keys.ts')).refuseUnregisteredEnumeratedKey(key, force);
- (await import('./config/search-statement-timeout.ts')).refuseInvalidSearchStatementTimeout(key, value);
if (key === 'auto_chronicle' || key.startsWith('chronicle.')) await refuseInvalidChronicleValue(key, value, force);
if (key.startsWith('facts.drain_')) {
const { validateFactsDrainConfigValue } = await import('../core/facts/drain-config.ts');
diff --git a/src/commands/config/search-statement-timeout.ts b/src/commands/config/search-statement-timeout.ts
deleted file mode 100644
index 8c9b869b0f..0000000000
--- a/src/commands/config/search-statement-timeout.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * `config set search.statement_timeout_ms` accepts whole milliseconds from 1
- * to 60000 only; anything else is a usage error (exit 2) and nothing is
- * written. The engine reads the key through postgres-engine/search-settings.ts,
- * which uses the 8000 ms default (with a warning naming the key) for a stored
- * value outside that range.
- */
-import {
- SEARCH_STATEMENT_TIMEOUT_DEFAULT_MS, SEARCH_STATEMENT_TIMEOUT_KEY, SEARCH_STATEMENT_TIMEOUT_MAX_MS, parseSearchStatementTimeoutMs,
-} from '../../core/postgres-engine/search-settings.ts';
-import { exitCliError, usageError } from '../../cli/cli-error.ts';
-
-export function refuseInvalidSearchStatementTimeout(key: string, value: string): void {
- if (key !== SEARCH_STATEMENT_TIMEOUT_KEY || parseSearchStatementTimeoutMs(value) !== null) return;
- const range = `a whole number of milliseconds from 1 to ${SEARCH_STATEMENT_TIMEOUT_MAX_MS}`;
- exitCliError(usageError(
- `${key} must be ${range}. Nothing was written.`,
- `Set ${range}, for example gbrain config set ${key} ${SEARCH_STATEMENT_TIMEOUT_DEFAULT_MS} (the default).`,
- {
- why: `The value bounds every Postgres lexical search statement; 0 would remove the bound and more than ${SEARCH_STATEMENT_TIMEOUT_MAX_MS} ms lets one search hold a connection too long.`,
- fix: {
- argv: ['gbrain', 'config', 'set', key, '<MS>'],
- inputs: [{ name: 'MS', how: `A whole number of milliseconds from 1 to ${SEARCH_STATEMENT_TIMEOUT_MAX_MS} (default ${SEARCH_STATEMENT_TIMEOUT_DEFAULT_MS}).` }],
- consent: [],
- actor: 'agent',
- why: 'Stores a timeout lexical search can use.',
- verify: { argv: ['gbrain', 'config', 'get', key] },
- requires_exclusive: false,
- },
- },
- ), 'config');
-}
diff --git a/src/core/config.ts b/src/core/config.ts
index 8f1aaf125c..da2bbbeb41 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1376,7 +1376,6 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.metadata_boost_gate',
'search.crag_escalation',
'search.crag_think',
- 'search.statement_timeout_ms', // Postgres lexical search arms' statement timeout (postgres-engine/search-settings.ts; whole ms 1..60000, default 8000)
// Evidence delivery (search/evidence-delivery.ts): default unit (auto),
// window radius, default/auto/remote-max token budgets; think reads its own unit.
'search.return_unit',
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 860f3a3269..571e369ad0 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -112,7 +112,7 @@ import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from
import { PageMissingError } from './engine-errors.ts';
import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';
import { acquireInitSchemaAdvisoryLock } from './postgres-engine/init-schema-lock.ts';
-import { SearchStatementTimeout, withSearchSettings } from './postgres-engine/search-settings.ts';
+import { withSearchJitOff } from './postgres-engine/search-settings.ts';
import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';
import * as factsImpl from './engine-sql/facts.ts';
import * as takesImpl from './engine-sql/takes.ts';
@@ -331,7 +331,7 @@ export class PostgresEngine implements BrainEngine {
const previous = this.rlsScopeBindingEnabled
? await tx`SELECT current_setting('app.scopes', true) AS scopes` : [];
if (this.rlsScopeBindingEnabled) await tx`SELECT set_config('app.scopes', ${scopesValue}, true)`;
- const result = opts?.jitOff ? await withSearchSettings(tx, this._pageTransaction, () => callback(tx)) : await callback(tx);
+ const result = opts?.jitOff ? await withSearchJitOff(tx, this._pageTransaction, () => callback(tx)) : await callback(tx);
// Successful RELEASE SAVEPOINT retains SET LOCAL; a failed callback
// rolls it back with the savepoint and must preserve its original error.
if (this.rlsScopeBindingEnabled) await tx`SELECT set_config('app.scopes', ${previous[0]?.scopes ?? ''}, true)`;
@@ -739,8 +739,6 @@ export class PostgresEngine implements BrainEngine {
}
private _pageTransaction = false;
- // search.statement_timeout_ms, memoized; tx engines (Object.create) share it, and their reads use the tx connection.
- private readonly searchTimeout = new SearchStatementTimeout();
async putPage(slug: string, page: PageInput, opts?: PageWriteOptions): Promise<Page> {
slug = validateSlug(slug);
@@ -1080,10 +1078,9 @@ export class PostgresEngine implements BrainEngine {
// the GUC can never leak onto a pooled connection). Flag off → the
// wrap is identical to master's; flag on → set_config('app.scopes')
// shares the same transaction as the timeout.
- const statementTimeout = await this.searchTimeout.resolve(key => this.getConfig(key));
const runKeyword = (queryText: string, relaxed = false) =>
this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {
- await tx`SELECT set_config('statement_timeout', ${statementTimeout}, true)`;
+ await tx`SET LOCAL statement_timeout = '8s'`;
const previous = relaxed ? await tx`SHOW enable_seqscan` : [];
if (relaxed) await tx`SET LOCAL enable_seqscan = off`;
const boundParams = [...params];
@@ -1119,15 +1116,14 @@ export class PostgresEngine implements BrainEngine {
* fix/title-retrieval-arm (D1): page-grain title candidate arm. SQL lives
* once in engine-sql/titles.ts (exact-title key #5889, index-backed remote
* predicate). Each attempt (strict, then OR fallback) runs in its own
- * scoped read transaction with the search.statement_timeout_ms statement timeout.
+ * scoped read transaction with an 8s statement timeout.
*/
async searchTitles(query: string, opts?: SearchOpts): Promise<SearchResult[]> {
- const statementTimeout = await this.searchTimeout.resolve(key => this.getConfig(key));
return titlesImpl.searchTitles(
(read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }),
query,
opts,
- { statementTimeout, relaxedPrefersIndex: true, staleProbe: false },
+ { statementTimeout: '8s', relaxedPrefersIndex: true, staleProbe: false },
);
}
@@ -1270,9 +1266,8 @@ export class PostgresEngine implements BrainEngine {
// RLS scope binding + search-only timeout. alwaysTransaction: master
// already wrapped this in sql.begin() for the SET LOCAL; flag off is
// identical to that wrap, flag on adds set_config in the same tx.
- const statementTimeout = await this.searchTimeout.resolve(key => this.getConfig(key));
const rows = await this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {
- await tx`SELECT set_config('statement_timeout', ${statementTimeout}, true)`;
+ await tx`SET LOCAL statement_timeout = '8s'`;
return await tx.unsafe(rawQuery, params as Parameters<typeof tx.unsafe>[1]);
}, { alwaysTransaction: true, jitOff: true });
return rows.map(rowToSearchResult);
@@ -1281,15 +1276,14 @@ export class PostgresEngine implements BrainEngine {
/**
* #3986: CJK keyword fallback (parity port of PGLite's v0.32.7 branch).
* SQL builds in the shared cjk-keyword-sql.ts; execution goes through the
- * same scoped read transaction (RLS scope binding + search statement timeout)
+ * same scoped read transaction (RLS scope binding + 8s statement timeout)
* as the FTS keyword paths. See src/core/engine-sql/cjk-search.ts.
*/
private async _searchKeywordCJK(query: string, ctx: CjkKeywordCtx): Promise<SearchResult[]> {
- const statementTimeout = await this.searchTimeout.resolve(key => this.getConfig(key));
return searchKeywordCJKImpl(
async (read) =>
await this.withScopedReadTransaction(ctx.opts?.sourceIds, ctx.opts?.sourceId, async (tx) => {
- await tx`SELECT set_config('statement_timeout', ${statementTimeout}, true)`;
+ await tx`SET LOCAL statement_timeout = '8s'`;
return await read(scopedRead(postgresExecutor(tx, {
runUnsafe: (conn, sql, params, opts) => this.runUnsafe(conn, sql, params, opts),
gauge: this.checkoutGauge,
diff --git a/src/core/postgres-engine/search-settings.ts b/src/core/postgres-engine/search-settings.ts
index e03e7c113c..5f9b50a319 100644
--- a/src/core/postgres-engine/search-settings.ts
+++ b/src/core/postgres-engine/search-settings.ts
@@ -14,65 +14,18 @@
*
* `SET LOCAL` ends with a top-level transaction. Inside a caller's
* transaction the search runs in a savepoint, and a released savepoint keeps
- * the setting, so the caller's `jit` and `statement_timeout` are restored
- * afterwards; a failed search rolls the savepoint back, which reverts them too.
+ * the setting, so the caller's value is restored afterwards; a failed search
+ * rolls the savepoint back, which reverts it too.
*
- * Statement timeout. The lexical arms (keyword, keyword chunks, CJK, title)
- * bound each statement with `search.statement_timeout_ms` (DB plane, whole
- * milliseconds 1..60000, default 8000; no env override). The value is read
- * before the search transaction opens, so it never takes a second pool slot,
- * memoized per engine for 60 s, and bound through `set_config` as a parameter.
- * The vector arm keeps its own deadline.
- *
- * Postgres only: PGLite has no JIT provider and no statement timeout here.
+ * Postgres only: PGLite has no JIT provider, so its engine never calls this.
*/
import type postgres from '#postgres';
-export const SEARCH_STATEMENT_TIMEOUT_KEY = 'search.statement_timeout_ms';
-export const SEARCH_STATEMENT_TIMEOUT_DEFAULT_MS = 8000;
-export const SEARCH_STATEMENT_TIMEOUT_MAX_MS = 60_000;
-const MEMO_MS = 60_000;
-
-/** A whole number of milliseconds from 1 to 60000, else null. */
-export function parseSearchStatementTimeoutMs(raw: string): number | null {
- const t = raw.trim();
- if (!/^\d+$/.test(t)) return null;
- const ms = Number(t);
- return ms >= 1 && ms <= SEARCH_STATEMENT_TIMEOUT_MAX_MS ? ms : null;
-}
-
-/** One engine's resolver: `resolve(read)` returns the Postgres interval text (`8000ms`). */
-export class SearchStatementTimeout {
- private memo: { value: string; at: number } | null = null;
- private warned = false;
-
- async resolve(read: (key: string) => Promise<string | null>): Promise<string> {
- const now = Date.now();
- if (this.memo && now - this.memo.at < MEMO_MS) return this.memo.value;
- let ms = SEARCH_STATEMENT_TIMEOUT_DEFAULT_MS;
- try {
- const raw = await read(SEARCH_STATEMENT_TIMEOUT_KEY);
- const parsed = raw === null ? null : parseSearchStatementTimeoutMs(raw);
- if (parsed !== null) ms = parsed;
- else if (raw !== null && !this.warned) {
- this.warned = true;
- console.warn(`[gbrain] ${SEARCH_STATEMENT_TIMEOUT_KEY} is not a whole number of milliseconds from 1 to ${SEARCH_STATEMENT_TIMEOUT_MAX_MS}, so lexical search uses the default ${SEARCH_STATEMENT_TIMEOUT_DEFAULT_MS} ms. ` +
- `Fix: gbrain config set ${SEARCH_STATEMENT_TIMEOUT_KEY} <ms> (or gbrain config unset ${SEARCH_STATEMENT_TIMEOUT_KEY}).`);
- }
- } catch {
- // A config read failure never takes search down: use the default now and read again next call.
- return `${ms}ms`;
- }
- this.memo = { value: `${ms}ms`, at: now };
- return this.memo.value;
- }
-}
-
-// engine-sql-ok: jit and statement_timeout are Postgres server settings
-export async function withSearchSettings<T>(tx: ReturnType<typeof postgres>, nested: boolean, run: () => Promise<T>): Promise<T> {
- const previous = nested ? await tx`SELECT current_setting('jit') AS jit, current_setting('statement_timeout') AS statement_timeout` : [];
+// engine-sql-ok: jit is a Postgres server setting; PGLite has no JIT provider
+export async function withSearchJitOff<T>(tx: ReturnType<typeof postgres>, nested: boolean, run: () => Promise<T>): Promise<T> {
+ const previous = nested ? await tx`SELECT current_setting('jit') AS jit` : [];
await tx`SET LOCAL jit = off`;
const result = await run();
- if (nested) await tx`SELECT set_config('jit', ${previous[0]!.jit}, true), set_config('statement_timeout', ${previous[0]!.statement_timeout}, true)`;
+ if (nested) await tx`SELECT set_config('jit', ${previous[0]!.jit}, true)`;
return result;
}
diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.ts
index a140d9c056..f7b465f9ab 100644
--- a/src/core/search/hybrid/arms.ts
+++ b/src/core/search/hybrid/arms.ts
@@ -17,8 +17,6 @@ import { markKeywordHits } from '../evidence.ts';
import { resolveEffectiveRecency, resolveEffectiveSalience } from './effective-modes.ts';
import { searchSalvageEnabled } from '../token-budget.ts';
import { isDatetimeInputError, warnOncePerProcess } from '../../utils.ts';
-import { isQueryCanceledError } from '../../brainstorm/error-classify.ts';
-import { SEARCH_STATEMENT_TIMEOUT_KEY, SEARCH_STATEMENT_TIMEOUT_MAX_MS } from '../../postgres-engine/search-settings.ts';
export interface LexicalArms {
earlyModality: ModalityMode;
@@ -27,16 +25,6 @@ export interface LexicalArms {
exactLookupOpts: ExactLookupOpts;
}
-/** A lexical arm failure: a Postgres statement timeout (SQLSTATE 57014) is a `timeout` and names the key that bounds it. */
-function lexicalArmFailure(err: unknown): { reason: 'timeout' | 'provider_error'; detail: string } {
- const canceled = isQueryCanceledError(err);
- const message = err instanceof Error ? err.message : String(err);
- return {
- reason: canceled || isTimeoutError(err) ? 'timeout' : 'provider_error',
- detail: canceled ? `${message} (lexical statements stop at ${SEARCH_STATEMENT_TIMEOUT_KEY}; raise it, up to ${SEARCH_STATEMENT_TIMEOUT_MAX_MS} ms, if this brain needs longer: gbrain config set ${SEARCH_STATEMENT_TIMEOUT_KEY} <ms>)` : message,
- };
-}
-
/** Keyword + title FTS arms, fetched concurrently (fail-open per arm, rethrow when both hit a dead database). */
export async function runLexicalArms(req: HybridRequest): Promise<LexicalArms> {
const { engine, query, opts, suggestions, searchOpts, identityTierOpts, degraded } = req;
@@ -81,17 +69,23 @@ export async function runLexicalArms(req: HybridRequest): Promise<LexicalArms> {
engine.searchKeyword(query, searchOpts).catch((err: unknown) => {
if (isDatetimeInputError(err)) throw err;
if (isDbAccessFailure(err)) keywordAccessError = err;
- const failure = lexicalArmFailure(err);
- pushDegraded(degraded, 'keyword_arm_failed', failure.reason);
- warnOncePerProcess('search-keyword-arm-failed', `[gbrain] searchKeyword arm failed (fail-open, keyword candidates skipped): ${failure.detail}`);
+ pushDegraded(degraded, 'keyword_arm_failed', isTimeoutError(err) ? 'timeout' : 'provider_error');
+ warnOncePerProcess(
+ 'search-keyword-arm-failed',
+ `[gbrain] searchKeyword arm failed (fail-open, keyword candidates skipped): ` +
+ `${err instanceof Error ? err.message : String(err)}`,
+ );
return [] as SearchResult[];
}),
engine.searchTitles(query, searchOpts).catch((err: unknown) => {
if (isDatetimeInputError(err)) throw err;
if (isDbAccessFailure(err)) titleAccessError = err;
- const failure = lexicalArmFailure(err);
- pushDegraded(degraded, 'title_arm_failed', failure.reason);
- warnOncePerProcess('search-titles-arm-failed', `[gbrain] searchTitles arm failed (fail-open, title candidates skipped): ${failure.detail}`);
+ pushDegraded(degraded, 'title_arm_failed', isTimeoutError(err) ? 'timeout' : 'provider_error');
+ warnOncePerProcess(
+ 'search-titles-arm-failed',
+ `[gbrain] searchTitles arm failed (fail-open, title candidates skipped): ` +
+ `${err instanceof Error ? err.message : String(err)}`,
+ );
return [] as SearchResult[];
}),
]);
diff --git a/src/core/search/title-statement.ts b/src/core/search/title-statement.ts
index 790d345a43..9ba99852fa 100644
--- a/src/core/search/title-statement.ts
+++ b/src/core/search/title-statement.ts
@@ -21,7 +21,7 @@ import {
/** Engine behavior the title arm keeps from each engine's original method. */
export interface SearchTitlesDialect {
- /** Per-attempt `statement_timeout` (Postgres: search.statement_timeout_ms, default 8000ms); unset means none. */
+ /** Per-attempt `statement_timeout` (Postgres: '8s'); unset means none. */
statementTimeout?: string;
/** Run the relaxed (OR) local re-run with `enable_seqscan` off (Postgres). */
relaxedPrefersIndex: boolean;
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
index 214d17e698..d523f5382d 100644
--- a/test/config-search-registry.test.ts
+++ b/test/config-search-registry.test.ts
@@ -35,7 +35,6 @@ const DIRECTLY_READ_SINGLETONS = [
'search.vector_legacy_guard', // search/vector-legacy-guard.ts via loadConfigWithEngine
'search.crag_escalation', // ops/search.ts
'search.crag_think', // ops/search.ts
- 'search.statement_timeout_ms', // postgres-engine/search-settings.ts
'search.return_unit', // search/evidence-delivery.ts
'search.return_window',
'search.return_budget_default',
diff --git a/test/e2e/search-query-contract-postgres.test.ts b/test/e2e/search-query-contract-postgres.test.ts
index c59225ca2e..b0f092dc59 100644
--- a/test/e2e/search-query-contract-postgres.test.ts
+++ b/test/e2e/search-query-contract-postgres.test.ts
@@ -114,49 +114,4 @@ import { withEnv } from '../helpers/with-env.ts';
});
});
});
-
- const lexicalArms = (e: BrainEngine) => {
- const opts = { limit: 10, sourceId: 'query-dates' };
- return {
- keyword: () => e.searchKeyword('precisiontoken', opts),
- keywordChunks: () => e.searchKeywordChunks('precisiontoken', opts),
- cjk: () => e.searchKeyword('東京', opts),
- titles: () => e.searchTitles('precisiontoken', opts),
- };
- };
-
- async function withTimeoutKey(value: string | null, run: () => Promise<void>) {
- if (value !== null) await engine.setConfig('search.statement_timeout_ms', value);
- try { await run(); } finally { await engine.unsetConfig('search.statement_timeout_ms'); }
- }
-
- test('lexical arms bound statements by search.statement_timeout_ms and restore the caller value (#5024)', async () => {
- // A fresh reader per case: the resolver memoizes per engine. Pool size 1
- // proves the key is read without a second checkout, also inside a transaction.
- await withTimeoutKey('1234', () => asSettingProbeReader(`current_setting('statement_timeout') = '1234ms'`, async reader => {
- for (const [arm, run] of Object.entries(lexicalArms(reader))) expect({ arm, hits: (await run()).length }).toEqual({ arm, hits: 7 });
- await reader.transaction(async tx => {
- await tx.executeRaw(`SET LOCAL statement_timeout = '7s'`);
- for (const [arm, run] of Object.entries(lexicalArms(tx))) {
- expect({ arm, hits: (await run()).length }).toEqual({ arm, hits: 7 });
- expect(await tx.executeRaw(`SELECT $1::text AS arm, current_setting('statement_timeout') AS timeout`, [arm])).toEqual([{ arm, timeout: '7s' }]);
- }
- });
- }));
- await withTimeoutKey(null, () => asSettingProbeReader(`current_setting('statement_timeout') = '8s'`, async reader => {
- for (const [arm, run] of Object.entries(lexicalArms(reader))) expect({ arm, hits: (await run()).length }).toEqual({ arm, hits: 7 });
- }));
- });
-
- test('a stored out-of-range value keeps the 8000 ms default (#5024)', async () => {
- await withTimeoutKey('60001', () => asSettingProbeReader(`current_setting('statement_timeout') = '8s'`, async reader => {
- for (const [arm, run] of Object.entries(lexicalArms(reader))) expect({ arm, hits: (await run()).length }).toEqual({ arm, hits: 7 });
- }));
- });
-
- test('a lexical statement past the bound is canceled with SQLSTATE 57014 (#5024)', async () => {
- await withTimeoutKey('1', () => asSettingProbeReader(`pg_sleep(0.05) IS NOT NULL`, async reader => {
- await expect(reader.searchKeyword('precisiontoken', { limit: 10, sourceId: 'query-dates' })).rejects.toMatchObject({ code: '57014' });
- }));
- });
});
diff --git a/test/search-statement-timeout.test.ts b/test/search-statement-timeout.test.ts
deleted file mode 100644
index 6b189198a2..0000000000
--- a/test/search-statement-timeout.test.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-/**
- * search.statement_timeout_ms (#5024): the Postgres lexical search arms
- * (keyword, keyword chunks, CJK, title) bounded every statement with a fixed
- * 8 s statement_timeout. On a large brain the keyword arm cannot finish in
- * it, so every search fails open to vector-only. The bound is now one
- * DB-plane key: whole milliseconds 1..60000, default 8000, no env override.
- *
- * - the resolver reads the key once per 60 s per engine, before the search
- * transaction opens (no second pool checkout), and binds it as a parameter;
- * - a stored invalid value warns once, naming the key (never the value), and
- * keeps the default;
- * - `config set` refuses an out-of-range value (exit 2, agent contract);
- * - a statement canceled by the bound (SQLSTATE 57014) degrades the arm as
- * `timeout` and the warning names the key.
- *
- * Real Postgres coverage (bound applied, caller value restored, 57014) lives
- * in test/e2e/search-query-contract-postgres.test.ts.
- */
-import { describe, expect, spyOn, test } from 'bun:test';
-import { PostgresEngine } from '../src/core/postgres-engine.ts';
-import { SearchStatementTimeout } from '../src/core/postgres-engine/search-settings.ts';
-import { runConfig } from '../src/commands/config.ts';
-import { hybridSearch } from '../src/core/search/hybrid.ts';
-import { _resetWarnOnceForTests } from '../src/core/utils.ts';
-import type { BrainEngine } from '../src/core/engine.ts';
-import type { HybridSearchMeta, SearchResult } from '../src/core/types.ts';
-
-const KEY = 'search.statement_timeout_ms';
-
-function reader(value: string | null, opts: { throws?: boolean } = {}) {
- const reads: string[] = [];
- const read = async (key: string) => {
- reads.push(key);
- if (opts.throws) throw new Error('pooler drop');
- return key === KEY ? value : null;
- };
- return { read, reads };
-}
-
-async function captureWarn<T>(fn: () => Promise<T>): Promise<{ result: T; warned: string[] }> {
- const warned: string[] = [];
- const spy = spyOn(console, 'warn').mockImplementation((...a: unknown[]) => { warned.push(a.join(' ')); });
- try { return { result: await fn(), warned }; } finally { spy.mockRestore(); }
-}
-
-describe('SearchStatementTimeout.resolve', () => {
- test('defaults to 8000 ms when the key is unset', async () => {
- expect(await new SearchStatementTimeout().resolve(reader(null).read)).toBe('8000ms');
- });
-
- test('honours a stored value in range, including both bounds', async () => {
- for (const [stored, bound] of [['45000', '45000ms'], ['1', '1ms'], ['60000', '60000ms'], [' 2500 ', '2500ms']]) {
- expect(await new SearchStatementTimeout().resolve(reader(stored).read)).toBe(bound);
- }
- });
-
- test('a stored invalid value keeps the default and warns once naming the key, never the value', async () => {
- for (const stored of ['0', '60001', '2147483647', '30 seconds; DROP TABLE pages', '1.5', '-5', '']) {
- const timeout = new SearchStatementTimeout();
- const { result, warned } = await captureWarn(async () => [await timeout.resolve(reader(stored).read), await timeout.resolve(reader(stored).read)]);
- expect(result).toEqual(['8000ms', '8000ms']);
- expect(warned.length).toBe(1);
- expect(warned[0]).toContain(KEY);
- expect(warned[0]).toContain('gbrain config set search.statement_timeout_ms <ms>');
- expect(warned[0]).not.toContain('DROP TABLE');
- expect(warned[0]).not.toContain('2147483647');
- }
- });
-
- test('memoizes for 60 s so the hot path does not read config per query', async () => {
- const r = reader('20000');
- const timeout = new SearchStatementTimeout();
- for (let i = 0; i < 3; i++) expect(await timeout.resolve(r.read)).toBe('20000ms');
- expect(r.reads).toEqual([KEY]);
- });
-
- test('a config read failure never takes search down and is not memoized', async () => {
- const timeout = new SearchStatementTimeout();
- expect(await timeout.resolve(reader(null, { throws: true }).read)).toBe('8000ms');
- expect(await timeout.resolve(reader('30000').read)).toBe('30000ms');
- });
-});
-
-describe('Postgres lexical arms apply the configured bound', () => {
- test('searchKeywordChunks reads the key before its transaction and binds it as a parameter', async () => {
- const engine = Object.create(PostgresEngine.prototype) as PostgresEngine;
- const priv = engine as unknown as Record<string, unknown>;
- let insideTransaction = false;
- priv.searchTimeout = new SearchStatementTimeout();
- priv.getConfig = async (key: string) => {
- expect(insideTransaction).toBe(false);
- return key === KEY ? '45000' : null;
- };
- const issued: { text: string; values: unknown[] }[] = [];
- const tx = Object.assign(
- async (strings: TemplateStringsArray, ...values: unknown[]) => { issued.push({ text: strings.join('$'), values }); return []; },
- { unsafe: async () => [] },
- );
- priv.withScopedReadTransaction = async (_ids: unknown, _id: unknown, fn: (t: typeof tx) => Promise<unknown>) => {
- insideTransaction = true;
- try { return await fn(tx); } finally { insideTransaction = false; }
- };
- await engine.searchKeywordChunks('hello');
- expect(issued).toEqual([{ text: "SELECT set_config('statement_timeout', $, true)", values: ['45000ms'] }]);
- });
-});
-
-async function runConfigCapture(args: string[]): Promise<{ errs: string; exit: number | null; setCalls: Array<[string, string]> }> {
- const setCalls: Array<[string, string]> = [];
- const engine = {
- getConfig: async () => null,
- setConfig: async (key: string, value: string) => { setCalls.push([key, value]); },
- } as unknown as BrainEngine;
- const errs: string[] = [];
- let exit: number | null = null;
- const spies = [
- spyOn(console, 'log').mockImplementation(() => {}),
- spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); }),
- spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => { errs.push(String(chunk)); return true; }) as never),
- spyOn(process, 'exit').mockImplementation(((code?: number) => { exit = code ?? 0; throw new Error(`EXIT:${code}`); }) as never),
- ];
- try {
- await runConfig(engine, args);
- } catch (e) {
- if (!(e as Error).message.startsWith('EXIT:')) throw e;
- } finally {
- for (const spy of spies) spy.mockRestore();
- }
- return { errs: errs.join('\n'), exit, setCalls };
-}
-
-describe('config set search.statement_timeout_ms', () => {
- for (const value of ['0', '60001', 'abc', '1.5']) {
- test(`refuses ${JSON.stringify(value)} (exit 2, contract rendered, nothing written)`, async () => {
- const { errs, exit, setCalls } = await runConfigCapture(['set', KEY, value]);
- expect(exit).toBe(2);
- expect(setCalls).toEqual([]);
- expect(errs).toContain(`Error [invalid_params]: ${KEY} must be a whole number of milliseconds from 1 to 60000. Nothing was written.`);
- expect(errs).toContain(`Fix: gbrain config set ${KEY} '<MS>'`);
- expect(errs).toContain('Why: The value bounds every Postgres lexical search statement');
- });
- }
-
- test('accepts a value in range', async () => {
- const { exit, setCalls } = await runConfigCapture(['set', KEY, '30000']);
- expect(exit).toBeNull();
- expect(setCalls).toEqual([[KEY, '30000']]);
- });
-});
-
-describe('a canceled lexical statement degrades as timeout and names the key', () => {
- function fakeEngine(keywordError: Error): BrainEngine {
- return {
- kind: 'postgres',
- getConfig: async () => null,
- executeRaw: async () => [],
- resolveAliases: async () => new Map(),
- getPage: async () => null,
- getContentFlagsByPageIds: async () => new Map(),
- getUnverifiedExtractionPageIds: async () => new Map(),
- relationalFanout: async () => [],
- searchVector: async () => [],
- searchKeyword: () => Promise.reject(keywordError),
- searchTitles: async () => [] as SearchResult[],
- } as unknown as BrainEngine;
- }
-
- async function run(err: Error) {
- _resetWarnOnceForTests();
- let meta: HybridSearchMeta | undefined;
- const { warned } = await captureWarn(() => hybridSearch(fakeEngine(err), 'orchard telemetry notes', { limit: 5, onMeta: m => { meta = m; } }));
- return { degraded: meta?.degraded ?? [], warned: warned.join('\n') };
- }
-
- test('SQLSTATE 57014 → keyword_arm_failed: timeout, warning names search.statement_timeout_ms', async () => {
- const err = Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });
- const { degraded, warned } = await run(err);
- expect(degraded).toContainEqual({ stage: 'keyword_arm_failed', reason: 'timeout' });
- expect(warned).toContain(`gbrain config set ${KEY} <ms>`);
- });
-
- test('any other failure stays provider_error without the key hint', async () => {
- const { degraded, warned } = await run(new Error('relation "content_chunks" does not exist'));
- expect(degraded).toContainEqual({ stage: 'keyword_arm_failed', reason: 'provider_error' });
- expect(warned).not.toContain(KEY);
- });
-});