Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

W5 G5.1 (#6495): resolve the keyword statement timeout once at connect; gate fixes

garrytancf52bdb59b2f
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index cde3171b7a..19c5be6660 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2027 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 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 3026 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)
-src/core/postgres-engine.ts 3042 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)
+src/core/postgres-engine.ts 3048 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); +6 wave 16 G5.1 (#6495) gate fix: primeKeywordStatementTimeout resolves the knob once at connect (awaited at the end of connect) so no search request reads config (3048 measured)
src/core/search/hybrid.ts 1632 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; +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 2294 ratchet +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)
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)
diff --git a/src/commands/doctor/checks/keyword-plan.ts b/src/commands/doctor/checks/keyword-plan.ts
index 78d5d05d8e..3c754fdd53 100644
--- a/src/commands/doctor/checks/keyword-plan.ts
+++ b/src/commands/doctor/checks/keyword-plan.ts
@@ -121,12 +121,12 @@ export async function keywordPlanCheck(engine: BrainEngine, probe: KeywordPlanPr
if (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 gbrain serve or the workers) buys time, not a cheaper statement: ranking cost grows with the number of matching chunks (#6495); narrow queries with --source-id / 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}` };
}
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 gbrain serve or the workers) buys time, not a cheaper statement (#6495); narrow queries with --source-id / 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}` };
}
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}` };
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index 6cb156a3c7..c1af746673 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -239,7 +239,7 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
id: 'keyword_plan', resolution: 'operator', registration: 'wave',
count: d => (d.outcome === 'canary_timed_out' || d.outcome === 'canary_slow' ? 1 : 0),
impact: 'The commonest keyword term on this brain cannot be counted inside the keyword statement bound, so broad keyword queries time out and hybrid search answers from the vector arm alone',
- instruction: 'Read the canary doctor reports (one term is not workload coverage); raise `search.keyword_statement_timeout_ms` on the brain host only to buy time (1000-60000 ms, then restart gbrain serve or the workers), narrow broad queries with --source-id, and follow #6495 for the bounded candidate set (docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain).',
+ instruction: 'Read the canary doctor reports (one term is not workload coverage); raise `search.keyword_statement_timeout_ms` on the brain host only to buy time (1000-60000 ms, then restart the serving process), narrow broad queries to one source (`gbrain search --source-id <id>`, MCP `source_id`), and follow #6495 for the bounded candidate set (docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain).',
run: async engine => (await import('./checks/keyword-plan.ts')).keywordPlanCheck(engine),
},
{
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 557e9b4802..1254772e27 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -120,7 +120,7 @@ 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 { withSearchJitOff } from './postgres-engine/search-settings.ts';
-import { loadKeywordStatementTimeout } from './postgres-engine/keyword-statement-timeout.ts';
+import { KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS, loadKeywordStatementTimeout } from './postgres-engine/keyword-statement-timeout.ts';
import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';
import * as factsImpl from './engine-sql/facts.ts';
import * as takesImpl from './engine-sql/takes.ts';
@@ -450,6 +450,7 @@ export class PostgresEngine implements BrainEngine {
this.connectionManager.setReadPool(db.getConnection());
}
}
+ await this.primeKeywordStatementTimeout(config.keyword_statement_timeout_ms);
}
async disconnect(): Promise<void> {
@@ -1408,9 +1409,14 @@ export class PostgresEngine implements BrainEngine {
return (Array.isArray(plan) ? plan[0] : plan) as Record<string, unknown>;
}
- /** #6495: the keyword/title statement bound, resolved once per connection (postgres-engine/keyword-statement-timeout.ts); never a request parameter. */
+ /** #6495: resolve the keyword/title statement bound for this connection at connect (file plane, else the DB plane, else 8000 ms; postgres-engine/keyword-statement-timeout.ts), never from a request or inside a search's transaction. */
+ private async primeKeywordStatementTimeout(fileValue: unknown): Promise<void> {
+ this.keywordStatementTimeout = loadKeywordStatementTimeout(this, fileValue);
+ await this.keywordStatementTimeout;
+ }
+
private keywordStatementTimeoutSetting(): Promise<string> {
- return this.keywordStatementTimeout ??= loadKeywordStatementTimeout(this, this._savedConfig?.keyword_statement_timeout_ms);
+ return this.keywordStatementTimeout ??= Promise.resolve(`${KEYWORD_STATEMENT_TIMEOUT_DEFAULT_MS}ms`);
}
private async vectorIterativeScanSupported(): Promise<boolean> {
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index b174fe3151..8669e15fa9 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -326,6 +326,7 @@
"mergeOntologyFact",
"migrateFactsToCanonical",
"onCheckout",
+ "primeKeywordStatementTimeout",
"purgeDeletedPages",
"putContradictionCacheEntry",
"putDreamVerdict",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 7344a425d2..340a4a5c78 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -1172,6 +1172,7 @@
"private poisonedDiscards",
"private poolHealth",
"private poolIncidents",
+ "private primeKeywordStatementTimeout",
"private resolveFactsEmbeddingCast",
"private rlsScopeBindingEnabled",
"private runUnsafe",
diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.json
index a1097f7699..cadffe0705 100644
--- a/test/fixtures/goldens/rls-scope-inventory.json
+++ b/test/fixtures/goldens/rls-scope-inventory.json
@@ -3569,6 +3569,7 @@
"invalidateContentDriftEmbeddings": "none",
"invalidateStaleSignatureEmbeddings": "none",
"jitOffRead": "none",
+ "keywordStatementTimeoutSetting": "none",
"listActiveTakesForPages": "none",
"listAllPageRefs": "none",
"listAllSources": "none",
@@ -3602,6 +3603,7 @@
"mergeOntologyFact": "none",
"migrateFactsToCanonical": "none",
"onCheckout": "none",
+ "primeKeywordStatementTimeout": "none",
"purgeDeletedPages": "none",
"putContradictionCacheEntry": "none",
"putDreamVerdict": "none",
diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.json
index 86d9f9adbd..79303c45c4 100644
--- a/test/fixtures/goldens/sql-text/_classification.json
+++ b/test/fixtures/goldens/sql-text/_classification.json
@@ -11,7 +11,7 @@
"out-of-scope:dream-verdicts": 3,
"out-of-scope:eval-capture": 5,
"out-of-scope:ingest-log": 2,
- "out-of-scope:internal-helper (private; exercised through public callers)": 18,
+ "out-of-scope:internal-helper (private; exercised through public callers)": 20,
"out-of-scope:lifecycle (connection, pool, transaction, raw seams)": 15,
"out-of-scope:no-sql-stub": 1,
"out-of-scope:raw-data": 2,
@@ -123,6 +123,7 @@
"invalidateContentDriftEmbeddings": "chunks",
"invalidateStaleSignatureEmbeddings": "chunks",
"jitOffRead": "out-of-scope:internal-helper (private; exercised through public callers)",
+ "keywordStatementTimeoutSetting": "out-of-scope:internal-helper (private; exercised through public callers)",
"listActiveTakesForPages": "takes",
"listAllPageRefs": "pages",
"listAllSources": "sources",
@@ -156,6 +157,7 @@
"mergeOntologyFact": "facts",
"migrateFactsToCanonical": "facts",
"onCheckout": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)",
+ "primeKeywordStatementTimeout": "out-of-scope:internal-helper (private; exercised through public callers)",
"purgeDeletedPages": "pages",
"putContradictionCacheEntry": "takes",
"putDreamVerdict": "out-of-scope:dream-verdicts",
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index f2275ca98e..9162339077 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -1015,7 +1015,7 @@
"via": "tagged"
},
{
- "paramCount": 0,
+ "paramCount": 1,
"via": "tagged"
},
{
@@ -1051,7 +1051,7 @@
"via": "tagged"
},
{
- "paramCount": 0,
+ "paramCount": 1,
"via": "tagged"
},
{
@@ -1080,7 +1080,7 @@
"via": "tagged"
},
{
- "paramCount": 0,
+ "paramCount": 1,
"via": "tagged"
},
{
@@ -1098,7 +1098,7 @@
"via": "tagged"
},
{
- "paramCount": 0,
+ "paramCount": 1,
"via": "tagged"
},
{
diff --git a/test/fixtures/goldens/sql-text/cjk-search.json b/test/fixtures/goldens/sql-text/cjk-search.json
index 4acbfcd2c4..3874f6cc46 100644
--- a/test/fixtures/goldens/sql-text/cjk-search.json
+++ b/test/fixtures/goldens/sql-text/cjk-search.json
@@ -25,9 +25,11 @@
},
{
"lane": "tx",
- "params": [],
- "sql": "SET LOCAL statement_timeout = '8s'",
- "textSha256": "7346ddf58ceeb31a31fd4f44990faf92a5bf015f93c675513e2bc17e5c3619db"
+ "params": [
+ "string"
+ ],
+ "sql": "SELECT set_config('statement_timeout', $1, true)",
+ "textSha256": "4ff5eea87475148656b3e4c0a62fb90fdc1e96997a8b96873e48285836003675"
},
{
"lane": "pool",
@@ -81,9 +83,11 @@
},
{
"lane": "tx",
- "params": [],
- "sql": "SET LOCAL statement_timeout = '8s'",
- "textSha256": "7346ddf58ceeb31a31fd4f44990faf92a5bf015f93c675513e2bc17e5c3619db"
+ "params": [
+ "string"
+ ],
+ "sql": "SELECT set_config('statement_timeout', $1, true)",
+ "textSha256": "4ff5eea87475148656b3e4c0a62fb90fdc1e96997a8b96873e48285836003675"
},
{
"lane": "pool",
@@ -132,9 +136,11 @@
},
{
"lane": "tx",
- "params": [],
- "sql": "SET LOCAL statement_timeout = '8s'",
- "textSha256": "7346ddf58ceeb31a31fd4f44990faf92a5bf015f93c675513e2bc17e5c3619db"
+ "params": [
+ "string"
+ ],
+ "sql": "SELECT set_config('statement_timeout', $1, true)",
+ "textSha256": "4ff5eea87475148656b3e4c0a62fb90fdc1e96997a8b96873e48285836003675"
},
{
"lane": "tx",
@@ -172,9 +178,11 @@
},
{
"lane": "tx",
- "params": [],
- "sql": "SET LOCAL statement_timeout = '8s'",
- "textSha256": "7346ddf58ceeb31a31fd4f44990faf92a5bf015f93c675513e2bc17e5c3619db"
+ "params": [
+ "string"
+ ],
+ "sql": "SELECT set_config('statement_timeout', $1, true)",
+ "textSha256": "4ff5eea87475148656b3e4c0a62fb90fdc1e96997a8b96873e48285836003675"
},
{
"lane": "tx",
diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.ts
index c9975102ae..202c50663b 100644
--- a/test/helpers/postgres-engine-sql-cases.ts
+++ b/test/helpers/postgres-engine-sql-cases.ts
@@ -78,6 +78,8 @@ export const DOMAIN_OF: Record<string, string> = {
'_searchKeywordCJK': OOS.helper,
'runVectorAttempt': OOS.helper,
'vectorIterativeScanSupported': OOS.helper,
+ 'primeKeywordStatementTimeout': OOS.helper,
+ 'keywordStatementTimeoutSetting': OOS.helper,
// pages
'getPage': 'pages', 'readPageSnapshot': 'pages', 'readPageSnapshotsBatch': 'pages', 'lockPageKeys': 'pages', 'findDuplicatePage': 'pages', 'findDuplicatePages': 'pages',
diff --git a/test/keyword-statement-timeout-knob-6495.test.ts b/test/keyword-statement-timeout-knob-6495.test.ts
index 421ccbc5f6..26a8a0cc80 100644
--- a/test/keyword-statement-timeout-knob-6495.test.ts
+++ b/test/keyword-statement-timeout-knob-6495.test.ts
@@ -14,7 +14,8 @@
* these statements but never looks at the timeout they set.
*
* Unit arm: the real engine methods over a recording transaction handle (no
- * database). Postgres arm (DATABASE_URL): a session holding an ACCESS
+ * database); the knob is primed the way `connect()` primes it, from a stubbed
+ * config read. Postgres arm (DATABASE_URL): a session holding an ACCESS
* EXCLUSIVE lock on the searched tables makes each statement wait, and the
* knob, not the old 8 s, decides when Postgres cancels it (SQLSTATE 57014).
*/
@@ -49,7 +50,7 @@ const SITES: Record<string, (engine: PostgresEngine, countTimeoutMs?: number) =>
};
/** A PostgresEngine whose scoped read transactions run over a recording handle; config comes from the stubs. */
-function recordingEngine(opts: { dbValue?: string | null; fileValue?: unknown }): { engine: PostgresEngine; recorded: Recorded[] } {
+async function recordingEngine(opts: { dbValue?: string | null; fileValue?: unknown; prime?: boolean }): Promise<{ engine: PostgresEngine; recorded: Recorded[]; configReads: () => number }> {
const engine = new PostgresEngine();
const recorded: Recorded[] = [];
const rows = (sql: string): unknown[] => (/SHOW enable_seqscan/i.test(sql) ? [{ enable_seqscan: 'on' }] : Object.assign([], { count: 0 }));
@@ -64,14 +65,15 @@ function recordingEngine(opts: { dbValue?: string | null; fileValue?: unknown })
const priv = engine as unknown as {
withScopedReadTransaction: (ids: unknown, id: unknown, cb: (tx: unknown) => Promise<unknown>) => Promise<unknown>;
getConfig: (key: string) => Promise<string | null>;
- _savedConfig: unknown;
+ primeKeywordStatementTimeout: (fileValue: unknown) => Promise<void>;
_pageTransaction: boolean;
};
+ let configReads = 0;
priv.withScopedReadTransaction = (_ids, _id, cb) => cb(tx);
- priv.getConfig = async key => (key === KEYWORD_STATEMENT_TIMEOUT_KEY ? opts.dbValue ?? null : null);
- priv._savedConfig = { keyword_statement_timeout_ms: opts.fileValue };
+ priv.getConfig = async key => { configReads++; return key === KEYWORD_STATEMENT_TIMEOUT_KEY ? opts.dbValue ?? null : null; };
priv._pageTransaction = true;
- return { engine, recorded };
+ if (opts.prime !== false) await priv.primeKeywordStatementTimeout(opts.fileValue);
+ return { engine, recorded, configReads: () => configReads };
}
/** Every statement timeout a recording set: the `set_config('statement_timeout', $1, true)` argument or a `SET LOCAL` literal. */
@@ -86,7 +88,7 @@ function timeoutsSet(recorded: Recorded[]): string[] {
}
async function timeoutFor(site: string, opts: { dbValue?: string | null; fileValue?: unknown }, countTimeoutMs?: number): Promise<string[]> {
- const { engine, recorded } = recordingEngine(opts);
+ const { engine, recorded } = await recordingEngine(opts);
await SITES[site](engine, countTimeoutMs);
return timeoutsSet(recorded);
}
@@ -176,17 +178,23 @@ describe('search.keyword_statement_timeout_ms governs all six Postgres keyword s
expect(await timeoutFor('countKeywordPages', {}, 2000)).toEqual(['2000ms']);
});
- test('the knob is resolved once per engine, not per request', async () => {
- const { engine, recorded } = recordingEngine({ dbValue: '2500' });
- let reads = 0;
- const priv = engine as unknown as { getConfig: (key: string) => Promise<string | null> };
- const inner = priv.getConfig;
- priv.getConfig = async key => { reads++; return inner(key); };
+ test('the knob is resolved once at connect, not per request, and a search never reads config', async () => {
+ const { engine, recorded, configReads } = await recordingEngine({ dbValue: '2500' });
+ expect(configReads()).toBe(1);
await SITES.searchKeyword(engine);
await SITES.searchTitles(engine);
await SITES.searchKeywordChunks(engine);
expect(timeoutsSet(recorded)).toEqual(['2500ms', '2500ms', '2500ms']);
- expect(reads).toBe(1);
+ expect(configReads()).toBe(1);
+ const fileWins = await recordingEngine({ dbValue: '2500', fileValue: 3000 });
+ expect(fileWins.configReads()).toBe(0);
+ });
+
+ test('an engine that never connected binds the default', async () => {
+ const { engine, recorded, configReads } = await recordingEngine({ dbValue: '2500', prime: false });
+ await SITES.searchKeyword(engine);
+ expect(timeoutsSet(recorded)).toEqual(['8000ms']);
+ expect(configReads()).toBe(0);
});
});