Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(search): per-stage timings in _meta.retrieval and --explain (GBRA-81 item 5)

garrytan9759a5243c17
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index efbaf8d77d..e8a0b654f2 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -47,7 +47,7 @@ src/core/minions/queue.ts MinionQueue.add 498 seed: W5 baseline, refactor wave 1
src/core/minions/queue.ts MinionQueue.add>result=this.engine.transaction(#0) 359 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/worker.ts MinionWorker.start 470 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/ops/facts.ts recall.handler 354 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #4830 (W14 PR3): every hit names its source_id, falling back to the scope's single source (the federated case stays absent); +3 W5: recall threads the page-unit ranking cut into its hybrid page arm (logic in search/page-rank-cut.ts; delivery reports it)
-src/core/ops/search.ts query.handler 332 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 GBRA-49 explain_target: one TargetTrace prep line and its HybridSearchOpts thread (diagnosis/meta live in prepareExplainTarget/finishExplainTarget)
+src/core/ops/search.ts query.handler 336 +4 GBRA-81 item 5 per-stage search timings: the request's SearchTimings and setup-stage binding, the image branch's limit read hoisted out of the timed vector call, and its response stage wrapper (collector logic in search/stage-timings.ts); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 GBRA-49 explain_target: one TargetTrace prep line and its HybridSearchOpts thread (diagnosis/meta live in prepareExplainTarget/finishExplainTarget)
src/core/progressive-batch/orchestrator.ts runProgressiveBatch 348 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/remediation/run.ts runRemediation 428 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/skillopt/orchestrator.ts runOptimizationLoop 704 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index abc8555930..41a523a785 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -22,7 +22,7 @@ src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in
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 3012 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
src/core/postgres-engine.ts 3015 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)
-src/core/search/hybrid.ts 1643 ratchet +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); +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); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured)
+src/core/search/hybrid.ts 1648 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); +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); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured)
src/core/types.ts 2279 ratchet +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); +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); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured)
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)
src/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 191ee0a248..30a09375b5 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -1666,10 +1666,10 @@ export function formatResult(
// T15/FOV-1: an empty result names its cause when the pipeline told us
// (degradation stages from _meta.retrieval / the local meta capture) —
// a bare "No results." was indistinguishable from a degraded pipeline.
- if (results.length === 0) return `No results.${describeEmptyRetrieval()}\n`;
- // v0.40.4 — --explain switches to per-stage attribution formatter.
- // Reads CliOptions.explain via the module-level singleton.
const cliOpts = getCliOptions();
+ const timingsLine = cliOpts.explain && meta?.timings ? require('../core/search/stage-timings.ts').formatTimingsSummary(meta.timings) + '\n' : '';
+ if (results.length === 0) return `No results.${describeEmptyRetrieval()}\n` + timingsLine;
+ // v0.40.4 — --explain switches to per-stage attribution formatter.
if (cliOpts.explain) {
// Lazy import keeps formatResult's startup hot path narrow for
// the common non-explain case.
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index dc9cebe164..4e8bf21c43 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -33,6 +33,7 @@ import { applySnippetCap, DEFAULT_AGENT_SNIPPET_CHARS } from '../search/snippet-
import { redactRetrievalOutput } from '../search/output-redaction.ts';
import { projectRows, resultRowsFor } from '../search/lean-rows.ts';
import { buildScoreDetails } from '../search/explain-formatter.ts';
+import { SearchTimings } from '../search/stage-timings.ts';
import { TargetTrace, diagnoseProbe, diagnoseTrace, probeTarget, type ExplainTargetDiagnosis } from '../search/explain-target.ts';
import { assembleEvidenceForHits, capDeliveredSnippets, capEvidenceToBudget, deliverEvidence, effectivePlan, pagePlanHits, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
@@ -102,16 +103,20 @@ function thinkScopeFromQueryScope(scope: SourceScope): { sourceId?: string; allo
* (capture, response meta, last-retrieved bump) has already read full rows.
*/
function searchOutput(ctx: OperationContext, p: Record<string, unknown>, results: SearchResult[], meta: Record<string, unknown>, snippetCap: number,
- evidence?: { delivery: DeliveryMeta; explicitSnippet: boolean }): SearchResult[] {
+ timings: SearchTimings, evidence?: { delivery: DeliveryMeta; explicitSnippet: boolean }): SearchResult[] {
const rows = resultRowsFor(ctx, p.fields);
// `explain: true` — every row carries its score breakdown (kept in lean rows).
if (p.explain === true) for (const r of results) r.score_details = buildScoreDetails(r);
// The shape is reported where it can vary: remote callers, or an explicit `fields`.
const shown = ctx.remote !== false || p.fields !== undefined ? { rows } : {};
+ // Stage timings are read last, after the returned rows are assembled (meta only, never content).
+ const emit = (output: { meta: Record<string, unknown> }, returned: SearchResult[]) => {
+ ctx.emitResponseMeta?.('retrieval', { ...output.meta, timings: timings.snapshot() });
+ return returned;
+ };
if (!evidence) {
const output = redactRetrievalOutput(results, { ...meta, ...shown });
- ctx.emitResponseMeta?.('retrieval', output.meta);
- return projectRows(applySnippetCap(output.results, snippetCap).map(factRowOutput), rows);
+ return emit(output, projectRows(applySnippetCap(output.results, snippetCap).map(factRowOutput), rows));
}
// Evidence delivery: explicit snippet_chars wins over the delivered blocks;
// otherwise the blocks are returned whole (their budget already bounds
@@ -120,8 +125,7 @@ function searchOutput(ctx: OperationContext, p: Record<string, unknown>, results
// An explicit budget's cap holds at this final boundary too (snippet
// markers and redaction recounted); without one both are no-ops.
const capped = evidence.explicitSnippet ? capDeliveredSnippets(output.results, snippetCap, output.meta.delivery) : capEvidenceToBudget(output.results, output.meta.delivery);
- ctx.emitResponseMeta?.('retrieval', output.meta);
- return projectRows(capped.map(factRowOutput), rows);
+ return emit(output, projectRows(capped.map(factRowOutput), rows));
}
/** C1: the per-call row-shape escape hatch shared by `search` and `query` (`detail` is query's low/medium/high). */
@@ -176,10 +180,12 @@ async function withEvidence(ctx: OperationContext, p: Record<string, unknown>, r
/** withEvidence + the response meta for the rows actually returned + searchOutput. */
async function evidenceOutput(ctx: OperationContext, p: Record<string, unknown>, results: SearchResult[], plan: EvidencePlan | null, scope: DeliveryScope,
- meta: HybridSearchMeta | null, snippetCap: number, buildMeta: (rows: SearchResult[]) => Promise<Record<string, unknown>>): Promise<SearchResult[]> {
- const ev = await withEvidence(ctx, p, results, plan, scope, meta);
- ev.rows = await stampPageTrust(ctx.engine, ev.rows, scope.minTrust);
- return searchOutput(ctx, p, ev.rows, await buildMeta(ev.rows), snippetCap, ev.evidence);
+ meta: HybridSearchMeta | null, snippetCap: number, timings: SearchTimings, buildMeta: (rows: SearchResult[]) => Promise<Record<string, unknown>>): Promise<SearchResult[]> {
+ return timings.stage('response', async () => {
+ const ev = await withEvidence(ctx, p, results, plan, scope, meta);
+ ev.rows = await stampPageTrust(ctx.engine, ev.rows, scope.minTrust);
+ return searchOutput(ctx, p, ev.rows, await buildMeta(ev.rows), snippetCap, timings, ev.evidence);
+ });
}
/**
@@ -672,27 +678,29 @@ const search: Operation = {
},
handler: async (ctx, p) => {
const startedAt = Date.now();
+ const timings = new SearchTimings();
+ const setup = <T>(work: () => Promise<T>) => timings.stage('setup', work);
const queryText = p.query as string;
const limit = (p.limit as number) || 20;
const offset = (p.offset as number) || 0;
// #3985: validated multi-type filter, threaded into both branches below.
let types = normalizeTypesParam(ctx, 'search', p.types);
// #3800: snippet cap (param > subagent config default > full text).
- const snippetCap = await resolveSnippetCap(ctx, p);
- const plan = await evidencePlanFor(ctx, p, snippetCap, 'search');
+ const snippetCap = await setup(() => resolveSnippetCap(ctx, p));
+ const plan = await setup(() => evidencePlanFor(ctx, p, snippetCap, 'search'));
// #4398: explicit per-call source_id wins over ctx.sourceId, validated
// (invalid ids throw invalid_params) then resolved through the single
// trust+grant resolver (resolveRequestedScope inside federatedSearchScope)
// — out-of-grant ids throw permission_denied, and #2561's unqualified
// trusted-local federated span is unchanged.
const sourceIdParam = parseSourceIdParam(p.source_id, 'search', { allowAll: true });
- const scope = await trustedSearchScope(ctx, p, sourceIdParam);
+ const scope = await setup(() => trustedSearchScope(ctx, p, sourceIdParam));
// #4620: an explicit source_id must name a live source (after the grant check).
- await assertExplicitSourceLive(ctx, sourceIdParam);
+ await setup(() => assertExplicitSourceLive(ctx, sourceIdParam));
// #4352 — untrusted callers never see `visibility: private` pages
// (config-gated; trusted local CLI unchanged).
- const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
- const typeFilter = await reconcileTypeFilter(ctx, scope, excludePrivate, types);
+ const excludePrivate = await setup(() => resolveExcludePrivatePages(ctx.engine, ctx.remote));
+ const typeFilter = await setup(() => reconcileTypeFilter(ctx, scope, excludePrivate, types));
types = typeFilter.types;
// T4/D5 — per-call mode honored ONLY for trusted/local callers so a remote
@@ -703,15 +711,15 @@ const search: Operation = {
// T4/D17 — escape hatch: keyword-only when the operator opts out of the
// hybrid `search` contract (privacy/cost: no query text to an embedding
// provider). Defaults to cheap-hybrid (D4/D15).
- const keywordOnly = (await ctx.engine.getConfig('search.mcp_keyword_only')) === 'true';
+ const keywordOnly = (await setup(() => ctx.engine.getConfig('search.mcp_keyword_only'))) === 'true';
if (keywordOnly) {
if (types) {
- types = (await expandEngineTypeFilters(ctx.engine, { types, ...scope })).types;
+ types = (await setup(() => expandEngineTypeFilters(ctx.engine, { types, ...scope }))).types;
if (types?.length === 0) return [];
}
- const sourceBoosts = resolveBoostMap(undefined, await ctx.engine.getConfig(SOURCE_BOOSTS_KEY));
- const raw = await ctx.engine.searchKeyword(queryText, { limit, offset, excludePrivate, requireSafeChunks: ctx.remote !== false, source_boosts: sourceBoosts, ...(types ? { types } : {}), ...scope });
+ const sourceBoosts = resolveBoostMap(undefined, await setup(() => ctx.engine.getConfig(SOURCE_BOOSTS_KEY)));
+ const raw = await timings.stage('lexical', () => ctx.engine.searchKeyword(queryText, { limit, offset, excludePrivate, requireSafeChunks: ctx.remote !== false, source_boosts: sourceBoosts, ...(types ? { types } : {}), ...scope }));
const results = dedupResults(raw).map(r => ({ ...r }));
// #3783 — every row here IS a keyword hit (direct FTS path); mark
// before stamping so evidence still reads keyword_exact.
@@ -721,22 +729,22 @@ const search: Operation = {
// #1699: the keyword-only opt-out must STILL surface the content_flag
// agent-warning channel (hybridSearch stamps it; this branch bypasses
// hybridSearch, so stamp explicitly). Fail-open inside the helper.
- await stampContentFlags(ctx.engine, results, { ...scope, excludePrivate });
+ await timings.stage('post_fusion', () => stampContentFlags(ctx.engine, results, { ...scope, excludePrivate }));
// #160: same for the unverified auto-extracted stub marker (no boost
// to cancel on this path — keyword-only never applies the compiled-
// truth boost — but the provenance marker must still surface).
- await stampUnverifiedExtractions(ctx.engine, results, { ...scope, excludePrivate });
+ await timings.stage('post_fusion', () => stampUnverifiedExtractions(ctx.engine, results, { ...scope, excludePrivate }));
bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
maybeCaptureSearch(ctx, queryText, results, Date.now() - startedAt, false);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
- return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, null, snippetCap,
+ return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, null, snippetCap, timings,
rows => buildRetrievalResponseMeta(ctx, scope, queryText, rows, null, { conceptHint: true, types, typeFilterNotice: typeFilter.notice }));
}
// Cheap-hybrid (D4/D15): full vector+keyword+RRF+pool+title+alias, but
// expansion OFF (no per-call LLM cost). `query` op is the full-control variant.
let capturedMeta: HybridSearchMeta | null = null;
- const explainPrep = await prepareExplainTarget(ctx, p, scope, excludePrivate, 'search');
+ const explainPrep = await setup(() => prepareExplainTarget(ctx, p, scope, excludePrivate, 'search'));
const searchOpts = {
limit,
offset,
@@ -752,20 +760,21 @@ const search: Operation = {
recency: p.recency as 'off' | 'on' | 'strong' | undefined,
decide: { remote: ctx.remote !== false },
...(plan?.rankCut ? { pageRankCut: plan.rankCut } : {}),
+ _timings: timings,
};
const primary = await hybridSearchCached(ctx.engine, queryText, {
...searchOpts, onMeta: (m) => { capturedMeta = m; }, explain: p.explain === true, explainTarget: explainPrep?.trace,
});
const declarations = new DeclarationMemo();
- let results = (await withDeclaredNameFanOut(primary, queryText, declarations,
- (alt, altLimit) => hybridSearchCached(ctx.engine, alt, { ...searchOpts, limit: altLimit, offset: 0 }))).map(r => ({ ...r }));
- results = await anchorOpResults(ctx.engine, p, queryText, results, { ...scope, excludePrivate, requireSafeChunks: ctx.remote !== false, filtered: !!types, evidencePlan: !!plan });
+ let results = (await timings.stage('alias_fanout', () => withDeclaredNameFanOut(primary, queryText, declarations,
+ (alt, altLimit) => hybridSearchCached(ctx.engine, alt, { ...searchOpts, limit: altLimit, offset: 0 })))).map(r => ({ ...r }));
+ results = await timings.stage('anchoring', () => anchorOpResults(ctx.engine, p, queryText, results, { ...scope, excludePrivate, requireSafeChunks: ctx.remote !== false, filtered: !!types, evidencePlan: !!plan }));
stampDeepResearchIds(results);
const latency_ms = Date.now() - startedAt;
bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
- return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap,
+ return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap, timings,
async rows => withExplainTarget(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search' }), finishExplainTarget(ctx, p, explainPrep, results, 'search')));
},
scope: 'read', mutating: false,
@@ -840,6 +849,8 @@ const query: Operation = {
},
handler: async (ctx, p) => {
const startedAt = Date.now();
+ const timings = new SearchTimings();
+ const setup = <T>(work: () => Promise<T>) => timings.stage('setup', work);
const expand = p.expand !== false;
const detail = (p.detail as 'low' | 'medium' | 'high') || undefined;
const queryText = p.query as string | undefined;
@@ -847,8 +858,8 @@ const query: Operation = {
// branch below also honors it — searchVector filters types at SQL level).
let types = normalizeTypesParam(ctx, 'query', p.types);
// #3800: snippet cap (param > subagent config default > full text).
- const snippetCap = await resolveSnippetCap(ctx, p);
- const plan = await evidencePlanFor(ctx, p, snippetCap, 'query');
+ const snippetCap = await setup(() => resolveSnippetCap(ctx, p));
+ const plan = await setup(() => evidencePlanFor(ctx, p, snippetCap, 'query'));
const imageData = p.image as string | undefined;
const imageMime = (p.image_mime as string) || 'image/jpeg';
const embeddingColumnParam =
@@ -864,12 +875,12 @@ const query: Operation = {
const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;
// #2561: unqualified trusted-local query spans federated sources (per-call
// source_id / remote grants still resolve through resolveRequestedScope).
- const querySourceScope = await trustedSearchScope(ctx, p, sourceIdParam);
+ const querySourceScope = await setup(() => trustedSearchScope(ctx, p, sourceIdParam));
// #4620: an explicit source_id must name a live source (after the grant check).
- await assertExplicitSourceLive(ctx, sourceIdParam);
+ await setup(() => assertExplicitSourceLive(ctx, sourceIdParam));
// #4352 — same enforcement for the full-control query op (both the image
// searchVector branch and the text hybrid path below).
- const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
+ const excludePrivate = await setup(() => resolveExcludePrivatePages(ctx.engine, ctx.remote));
// Image-similarity branch: bypasses the text-only hybridSearch, embeds the
// image via embedMultimodal and searches the embedding_image column.
@@ -879,13 +890,13 @@ const query: Operation = {
until: typeof p.until === 'string' ? p.until : undefined,
});
if (types) {
- types = (await expandEngineTypeFilters(ctx.engine, { types, ...querySourceScope })).types;
+ types = (await setup(() => expandEngineTypeFilters(ctx.engine, { types, ...querySourceScope }))).types;
if (types?.length === 0) return [];
}
const imageMeta: HybridSearchMeta = {
vector_enabled: true, expansion_applied: false, detail_resolved: null, degraded: [],
};
- const vec = await embedSearchImage(ctx, imageData, imageMime);
+ const vec = await timings.stage('embed', () => embedSearchImage(ctx, imageData, imageMime));
// v0.34.1 (#861 F2 — 6th leak surface): the image path bypasses
// hybridSearch and calls searchVector directly, so it needs its
// own thread of the source scope. Pre-fix, this branch leaked
@@ -894,8 +905,9 @@ const query: Operation = {
// resolution, so its default limit didn't honor the active search
// mode. resolveEffectiveLimit applies the same chain (and the same
// remote trust gate) hybridSearch does.
- const results = (await ctx.engine.searchVector(vec, {
- limit: await resolveEffectiveLimit(ctx, p),
+ const limit = await setup(() => resolveEffectiveLimit(ctx, p));
+ const results = (await timings.stage('vector', () => ctx.engine.searchVector(vec, {
+ limit,
offset: (p.offset as number) || 0,
embeddingColumn: 'embedding_image',
excludePrivate,
@@ -911,11 +923,13 @@ const query: Operation = {
imageMeta.degraded = [{ stage: 'vector_candidates_incomplete',
reason: info.reason === 'deadline' ? 'timeout' : info.reason ?? 'candidate_budget' }];
},
- })).map(r => ({ ...r }));
+ }))).map(r => ({ ...r }));
stampDeepResearchIds(results);
- const labeled = await stampPageTrust(ctx.engine, results, querySourceScope.minTrust);
- imageMeta.retrieved_count = labeled.length;
- return searchOutput(ctx, p, labeled, { ...await buildRetrievalResponseMeta(ctx, querySourceScope, queryText ?? '', labeled, imageMeta, { types }), ...(plan && (plan.unit !== 'auto' || plan.explicitUnit) ? { delivery: unsupportedDelivery(plan, 'image_query_unsupported') } : {}) }, snippetCap);
+ return timings.stage('response', async () => {
+ const labeled = await stampPageTrust(ctx.engine, results, querySourceScope.minTrust);
+ imageMeta.retrieved_count = labeled.length;
+ return searchOutput(ctx, p, labeled, { ...await buildRetrievalResponseMeta(ctx, querySourceScope, queryText ?? '', labeled, imageMeta, { types }), ...(plan && (plan.unit !== 'auto' || plan.explicitUnit) ? { delivery: unsupportedDelivery(plan, 'image_query_unsupported') } : {}) }, snippetCap, timings);
+ });
}
if (!queryText) {
@@ -939,10 +953,10 @@ const query: Operation = {
// ctx.sourceId for callers that want to override (per-call multi-source
// search). When the param is the literal '__all__', force-allow
// cross-source mode (matches SearchOpts.sourceId contract).
- const typeFilter = await reconcileTypeFilter(ctx, querySourceScope, excludePrivate, types);
+ const typeFilter = await setup(() => reconcileTypeFilter(ctx, querySourceScope, excludePrivate, types));
types = typeFilter.types;
let capturedMeta: HybridSearchMeta | null = null; let queryEmbedding: Float32Array | null = null;
- const explainPrep = await prepareExplainTarget(ctx, p, querySourceScope, excludePrivate, 'query');
+ const explainPrep = await setup(() => prepareExplainTarget(ctx, p, querySourceScope, excludePrivate, 'query'));
// v0.32.x search-lite: route the query op through hybridSearchCached so
// token budget and intent weighting apply at the operation boundary.
// Semantic cache reuse is suspended in the wrapper.
@@ -1001,13 +1015,13 @@ const query: Operation = {
autocut: typeof p.autocut === 'boolean' ? (p.autocut as boolean) : pagePlanHits(plan).autocut,
// v0.43 — relational recall override. Omitted = smart default (mode bundle).
relationalRetrieval: typeof p.relational === 'boolean' ? (p.relational as boolean) : undefined,
- explain: p.explain === true, explainTarget: explainPrep?.trace,
+ explain: p.explain === true, explainTarget: explainPrep?.trace, _timings: timings,
});
const declarations = new DeclarationMemo();
- results = await applyQueryArms(ctx.engine, p, queryText, await withDeclaredNameFanOut(results, queryText, declarations, (alt, altLimit) => hybridSearchCached(ctx.engine, alt, {
+ results = await applyQueryArms(ctx.engine, p, queryText, await timings.stage('alias_fanout', () => withDeclaredNameFanOut(results, queryText, declarations, (alt, altLimit) => hybridSearchCached(ctx.engine, alt, {
limit: altLimit, excludePrivate, requireSafeChunks: ctx.remote !== false, takesHoldersAllowList: readHolders(ctx),
- expansion: false, types, ...querySourceScope,
- })), { ...querySourceScope, excludePrivate, requireSafeChunks: ctx.remote !== false, filtered: !!types, evidencePlan: !!plan, evidenceBudget: plan?.budgetTokens, remote: ctx.remote !== false, queryEmbedding, rowCap: () => resolveEffectiveLimit(ctx, p) });
+ expansion: false, types, ...querySourceScope, _timings: timings,
+ }))), { ...querySourceScope, excludePrivate, requireSafeChunks: ctx.remote !== false, filtered: !!types, evidencePlan: !!plan, evidenceBudget: plan?.budgetTokens, remote: ctx.remote !== false, queryEmbedding, rowCap: () => resolveEffectiveLimit(ctx, p), timer: timings });
// #1663 — CRAG confidence gate. Grade what retrieval returned (zero-LLM;
// reads the stamped honesty signals: evidence, exact_lookup, rerank
// score), attach grade + query shape to the retrieval meta on EVERY call,
@@ -1074,7 +1088,7 @@ const query: Operation = {
until: typeof p.until === 'string' ? p.until : undefined,
crossModal: p.cross_modal as 'text' | 'image' | 'both' | 'auto' | undefined,
embeddingColumn: embeddingColumnParam,
- onMeta: (m) => { escalatedMeta = m; },
+ onMeta: (m) => { escalatedMeta = m; }, _timings: timings,
});
// Grade the FULL escalated sweep (rank-1 is what the grader reads),
// then adopt only the caller-visible window. #4610: the re-run is
@@ -1166,7 +1180,7 @@ const query: Operation = {
// #1663: the CRAG grade rides the same retrieval meta channel.
// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
// and recorded the real payload; only the returned envelope is snipped.
- return evidenceOutput(ctx, p, results, plan, { ...querySourceScope, excludePrivate, detail }, capturedMeta, snippetCap,
+ return evidenceOutput(ctx, p, results, plan, { ...querySourceScope, excludePrivate, detail }, capturedMeta, snippetCap, timings,
async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query' })), crag }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));
},
scope: 'read', mutating: false,
diff --git a/src/core/search/explain-formatter.ts b/src/core/search/explain-formatter.ts
index 71112b4fd2..449480aea9 100644
--- a/src/core/search/explain-formatter.ts
+++ b/src/core/search/explain-formatter.ts
@@ -31,6 +31,7 @@
import type { SearchResult, HybridSearchMeta } from '../types.ts';
import type { DeliveryMeta } from './evidence-delivery.ts';
import type { AutocutDecision } from './autocut.ts';
+import { formatTimingsSummary, type SearchTimingsMeta } from './stage-timings.ts';
/**
* Format a single result with per-stage attribution. Returns a string
@@ -201,13 +202,13 @@ export function formatDecideSummary(decide: HybridSearchMeta['decide'] | undefin
*/
export function formatResultsExplain(
results: SearchResult[],
- meta?: HybridSearchMeta & { delivery?: DeliveryMeta },
+ meta?: HybridSearchMeta & { delivery?: DeliveryMeta; timings?: SearchTimingsMeta },
): string {
if (results.length === 0) return 'No results.\n';
const body = results.map((r, i) => formatResultExplain(r, i + 1)).join('\n\n') + '\n';
// v0.42.3.0 — prepend the autocut summary when meta carries a decision;
// v0.48.2 — and the degraded summary when any stage was skipped.
- const head = [formatAutocutSummary(meta?.autocut), formatDegradedSummary(meta?.degraded), formatRerankGateSummary(meta?.rerank_gate), formatDeliverySummary(meta?.delivery), formatDecideSummary(meta?.decide)]
+ const head = [formatAutocutSummary(meta?.autocut), formatDegradedSummary(meta?.degraded), formatRerankGateSummary(meta?.rerank_gate), formatDeliverySummary(meta?.delivery), formatDecideSummary(meta?.decide), formatTimingsSummary(meta?.timings)]
.filter((l): l is string => l !== null);
return head.length > 0 ? `${head.join('\n')}\n\n${body}` : body;
}
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index af2ee4145c..b3cebaec07 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -50,6 +50,7 @@ import { buildPostFusionOpts, buildRelationalList, resolveModalityAndQueries, ru
import { searchVectorFallback, searchWithoutEmbeddings } from './hybrid/keyword-only.ts';
import { factEmbeddingDisabled } from '../embedding-disabled.ts';
import { expandStructuralNeighbors, finalizeHybridResults, fuseArms, rerankAndPin, sizeReturnPool } from './hybrid/rank.ts';
+import { type StageTimer, UNTIMED } from './stage-timings.ts';
export const RRF_K = 60;
const COMPILED_TRUTH_BOOST = 2.0;
@@ -966,6 +967,8 @@ export interface HybridSearchOpts extends SearchOpts {
_queryPrefix?: string;
/** INTERNAL — the brain opted out of embedding (factEmbeddingDisabled), read once per request: keyword-only, no query embed. */
_embeddingOptedOut?: boolean;
+ /** INTERNAL — the op's per-request stage-timing collector (search/stage-timings.ts); absent = untimed. */
+ _timings?: StageTimer;
/**
* Hermetic eval canaries/CI — non-semantic embeddings. When set, the query
@@ -1094,25 +1097,26 @@ export async function hybridSearch(
opts?: HybridSearchOpts,
): Promise<SearchResult[]> {
if (opts?.types?.length === 0) return [];
+ const timer = opts?._timings ?? UNTIMED;
if (opts?.type || opts?.types?.length) {
const { expandEngineTypeFilters } = await import('../schema-pack/query-types.ts');
- const filters = await expandEngineTypeFilters(engine, opts);
+ const filters = await timer.stage('setup', () => expandEngineTypeFilters(engine, opts!));
if (filters.types?.length === 0) return [];
opts = { ...opts, ...filters };
}
- if (opts?._queryPrefix === undefined) opts = { ...opts, _queryPrefix: await loadEmbeddingQueryPrefix(engine) };
- if (opts._embeddingOptedOut === undefined) opts = { ...opts, _embeddingOptedOut: await factEmbeddingDisabled(engine) };
+ if (opts?._queryPrefix === undefined) opts = { ...opts, _queryPrefix: await timer.stage('setup', () => loadEmbeddingQueryPrefix(engine)) };
+ if (opts._embeddingOptedOut === undefined) opts = { ...opts, _embeddingOptedOut: await timer.stage('setup', () => factEmbeddingDisabled(engine)) };
// Named stages (src/core/search/hybrid/): request -> lexical arms ->
// relational arm -> [keyword-only return] -> modality + expansion ->
// vector arms -> [keyword fallback return] -> fusion + post-fusion boosts
// -> structural expansion -> dedup -> rerank + pin -> identity tiers +
// return sizing -> main return. Same order of every engine/provider call.
- const req = await resolveHybridRequest(engine, query, opts);
+ const req = await timer.stage('setup', () => resolveHybridRequest(engine, query, opts));
const { resolvedMode, resolvedCol, cfgForColumn } = req;
- const lexical = await runLexicalArms(req);
+ const lexical = await timer.stage('lexical', () => runLexicalArms(req));
const { earlyModality } = lexical;
const postFusionOpts = buildPostFusionOpts(req);
- const relationalList = await buildRelationalList(req);
+ const relationalList = await timer.stage('relational', () => buildRelationalList(req));
const { isAvailable } = await import('../ai/gateway.ts');
const providerProbe = resolvedCol.embeddingModel || undefined;
@@ -1143,7 +1147,7 @@ export async function hybridSearch(
// vector-arm query embedding without the gateway, so provider
// availability is irrelevant — skip the keyword-only short-circuit.
if (opts?.decide?.keywordOnly || (!opts?.queryEmbedFn && (opts?._embeddingOptedOut || !isAvailable('embedding', providerProbe)) && !willTryMultimodal)) {
- return searchWithoutEmbeddings(req, lexical, relationalList, postFusionOpts, providerProbe);
+ return timer.stage('post_fusion', () => searchWithoutEmbeddings(req, lexical, relationalList, postFusionOpts, providerProbe));
}
const { effectiveModality, unifiedRouting, queries } = await resolveModalityAndQueries(req);
@@ -1151,14 +1155,14 @@ export async function hybridSearch(
await runVectorArms(req, { effectiveModality, unifiedRouting, queries, multimodalProviderProbe: multimodalProviderProbe ?? cfgForColumn?.embedding_multimodal_model ?? 'voyage:voyage-multimodal-3' });
if (queryEmbedding) opts?.onQueryEmbedding?.(queryEmbedding);
if (vectorArms.length === 0) {
- return searchVectorFallback(req, lexical, relationalList, postFusionOpts);
+ return timer.stage('post_fusion', () => searchVectorFallback(req, lexical, relationalList, postFusionOpts));
}
- const { fused, relaxedDropped, keywordArmConfidence, metadataBoostGate } = await fuseArms(req, {
+ const { fused, relaxedDropped, keywordArmConfidence, metadataBoostGate } = await timer.stage('fuse', () => fuseArms(req, {
vectorArms, keywordResults: lexical.keywordResults, titleResults: lexical.titleResults, relationalList,
effectiveModality, queryEmbedding, imageQueryEmbedding, unifiedDone, postFusionOpts,
- });
- const dedupOpts = await expandStructuralNeighbors(req, fused);
+ }));
+ const dedupOpts = await timer.stage('post_fusion', () => expandStructuralNeighbors(req, fused));
// v0.27.0 PR #618 recency boost was here; v0.29.1 unifies it into
// runPostFusionStages above so all three return paths get the same
@@ -1166,7 +1170,7 @@ export async function hybridSearch(
// aliasing in the postFusionOpts resolver near line ~256.
// Dedup
- const deduped = dedupResults(fused, dedupOpts);
+ const deduped = await timer.stage('post_fusion', async () => dedupResults(fused, dedupOpts));
opts?.explainTarget?.observe('deduped', deduped);
// Auto-escalate: if detail=low returned 0, retry with high. The inner
@@ -1176,18 +1180,18 @@ export async function hybridSearch(
return hybridSearch(engine, query, { ...opts, detail: 'high' });
}
- const { rerankPinned, relationalRerankPin, rerankGate, identityLookups } = await rerankAndPin(req, deduped, relationalList, effectiveModality, {
+ const { rerankPinned, relationalRerankPin, rerankGate, identityLookups } = await timer.stage('rerank', () => rerankAndPin(req, deduped, relationalList, effectiveModality, {
exactLookupOpts: lexical.exactLookupOpts, multimodal: effectiveModality !== 'text' || unifiedDone,
- });
+ }));
opts?.explainTarget?.observe('reranked', rerankPinned);
- const { returnPool, adaptiveDecision, autocutDecision, relationalSlotDecision } = await sizeReturnPool(req, {
+ const { returnPool, adaptiveDecision, autocutDecision, relationalSlotDecision } = await timer.stage('post_fusion', () => sizeReturnPool(req, {
rerankPinned, deduped, exactLookupOpts: lexical.exactLookupOpts, relationalList, effectiveModality, identityLookups,
- });
+ }));
opts?.explainTarget?.observe('return_pool', returnPool);
- return finalizeHybridResults(req, returnPool, {
+ return timer.stage('post_fusion', () => finalizeHybridResults(req, returnPool, {
relaxedDropped, adaptiveDecision, autocutDecision, relationalSlotDecision,
relationalRerankPin, keywordArmConfidence, metadataBoostGate, rerankGate,
- });
+ }));
}
// ----------------------------------------------------------------------
@@ -1218,9 +1222,10 @@ export async function hybridSearchCached(
opts?: HybridSearchOpts,
): Promise<SearchResult[]> {
if (opts?.types?.length === 0) return [];
- const { modeInputForCache, resolvedForCache, knobsHash } = await resolveCacheSearchMode(engine, opts);
- const queryPrefix = opts?._queryPrefix ?? await loadEmbeddingQueryPrefix(engine);
- const embeddingOptedOut = opts?._embeddingOptedOut ?? await factEmbeddingDisabled(engine);
+ const timer = opts?._timings ?? UNTIMED;
+ const { modeInputForCache, resolvedForCache, knobsHash } = await timer.stage('setup', () => resolveCacheSearchMode(engine, opts));
+ const queryPrefix = opts?._queryPrefix ?? await timer.stage('setup', () => loadEmbeddingQueryPrefix(engine));
+ const embeddingOptedOut = opts?._embeddingOptedOut ?? await timer.stage('setup', () => factEmbeddingDisabled(engine));
// Result caching is off (semanticResultCacheAvailable() === false): skip the
// key/config setup entirely so the wrapper costs no round-trips of its own.
const semanticCache = semanticResultCacheAvailable()
@@ -1258,7 +1263,7 @@ export async function hybridSearchCached(
// v0.42.20.0 (Fix 3) — bounded by the shared deadline; on timeout this
// throws → caught below → cacheStatus 'disabled' → falls through to the
// inner hybridSearch (which reuses the same elapsed deadline).
- queryEmbedding = await embedQueryBounded(query, queryPrefix ? { queryPrefix } : undefined, queryEmbedDl());
+ queryEmbedding = await timer.stage('embed', () => embedQueryBounded(query, queryPrefix ? { queryPrefix } : undefined, queryEmbedDl()));
} else {
cacheStatus = 'disabled';
}
diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.ts
index 1f09d2b4fa..cbe9557d57 100644
--- a/src/core/search/hybrid/arms.ts
+++ b/src/core/search/hybrid/arms.ts
@@ -71,7 +71,7 @@ export async function runLexicalArms(req: HybridRequest): Promise<LexicalArms> {
earlyModality === 'image'
? [[], []]
: await Promise.all([
- engine.searchKeyword(query, searchOpts).catch((err: unknown) => {
+ req.timer.overlap('keyword_arm', engine.searchKeyword(query, searchOpts)).catch((err: unknown) => {
if (isDatetimeInputError(err)) throw err;
if (isDbAccessFailure(err)) keywordAccessError = err;
pushDegraded(degraded, 'keyword_arm_failed', isTimeoutError(err) ? 'timeout' : 'provider_error');
@@ -82,7 +82,7 @@ export async function runLexicalArms(req: HybridRequest): Promise<LexicalArms> {
);
return [] as SearchResult[];
}),
- engine.searchTitles(query, searchOpts).catch((err: unknown) => {
+ req.timer.overlap('title_arm', engine.searchTitles(query, searchOpts)).catch((err: unknown) => {
if (isDatetimeInputError(err)) throw err;
if (isDbAccessFailure(err)) titleAccessError = err;
pushDegraded(degraded, 'title_arm_failed', isTimeoutError(err) ? 'timeout' : 'provider_error');
@@ -231,7 +231,7 @@ export async function resolveModalityAndQueries(req: HybridRequest) {
const expansionAllowed = resolvedMode.expansion && effectiveModality !== 'image';
if (expansionAllowed && opts?.expandFn) {
try {
- const expanded = await opts.expandFn(query);
+ const expanded = await req.timer.stage('expansion', async () => opts.expandFn!(query));
// INVARIANT: queries[0] IS the caller's query. Both fan-outs below tag
// index 0 as the `original` arm (weight 1, cosine re-score vector), so
// an expandFn that omits or reorders the original would silently hand
@@ -295,12 +295,12 @@ export async function runVectorArms(
if (!aiIsAvailable('embedding', multimodalProviderProbe)) {
throw new Error('gateway not configured for embedding — unified multimodal would also fail');
}
- const unifiedEmbedding = await embedQueryMultimodal(query);
+ const unifiedEmbedding = await req.timer.stage('embed', () => embedQueryMultimodal(query));
const unifiedSearchOpts: SearchOpts = {
...searchOpts,
embeddingColumn: 'embedding_multimodal',
};
- const unifiedList = await engine.searchVector(unifiedEmbedding, unifiedSearchOpts);
+ const unifiedList = await req.timer.stage('vector', () => engine.searchVector(unifiedEmbedding, unifiedSearchOpts));
// D8 fail-open: zero rows + not strict-mode → fall through to dual-column.
if (unifiedList.length === 0 && !resolvedMode.unified_multimodal_only) {
console.error(
@@ -336,13 +336,13 @@ export async function runVectorArms(
if (!aiIsAvailable('embedding', multimodalProviderProbe)) {
throw new Error('gateway not configured for embedding — multimodal would also fail');
}
- const imageEmbedding = await embedQueryMultimodal(query);
+ const imageEmbedding = await req.timer.stage('embed', () => embedQueryMultimodal(query));
imageQueryEmbedding = imageEmbedding;
const imageSearchOpts: SearchOpts = {
...searchOpts,
embeddingColumn: 'embedding_image',
};
- const imageList = await engine.searchVector(imageEmbedding, imageSearchOpts);
+ const imageList = await req.timer.stage('vector', () => engine.searchVector(imageEmbedding, imageSearchOpts));
for (const r of imageList) {
r.modality = r.modality ?? 'image';
}
@@ -400,11 +400,11 @@ export async function runVectorArms(
// all-or-nothing fan-outs — one variant's failure abandons every
// embedding and falls back to keyword-only.
try {
- const embeddings = await Promise.all(queries.map(q => embedOneQuery(q)));
+ const embeddings = await req.timer.stage('embed', () => Promise.all(queries.map(q => embedOneQuery(q))));
queryEmbedding = embeddings[0];
- const textLists = await Promise.all(
+ const textLists = await req.timer.stage('vector', () => Promise.all(
embeddings.map(emb => engine.searchVector(emb, searchOpts)),
- );
+ ));
for (const list of textLists) {
for (const r of list) {
r.modality = r.modality ?? 'text';
@@ -431,7 +431,7 @@ export async function runVectorArms(
// WP2/T3 (ENG-15) salvage fan-outs: allSettled on BOTH the embed
// fan-out and the searchVector fan-out so one variant's failure no
// longer abandons the survivors (the query-vs-search asymmetry fix).
- const settled = await Promise.allSettled(queries.map(q => embedOneQuery(q)));
+ const settled = await req.timer.stage('embed', () => Promise.allSettled(queries.map(q => embedOneQuery(q))));
const okEmbeds: Float32Array[] = [];
const embedFailures: unknown[] = [];
for (const s of settled) {
@@ -464,7 +464,7 @@ export async function runVectorArms(
queryEmbedding = null;
pushDegraded(degraded, 'rescore_skipped', 'original_embed_failed');
}
- const vSettled = await Promise.allSettled(okEmbeds.map(emb => engine.searchVector(emb, searchOpts)));
+ const vSettled = await req.timer.stage('vector', () => Promise.allSettled(okEmbeds.map(emb => engine.searchVector(emb, searchOpts))));
const okLists: SearchResult[][] = [];
const okRoles: Array<'original' | 'variant'> = [];
let vFirstErr: unknown;
diff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.ts
index 08131a58ed..3bfe3c1e52 100644
--- a/src/core/search/hybrid/rank.ts
+++ b/src/core/search/hybrid/rank.ts
@@ -173,7 +173,7 @@ export async function fuseArms(
// runPostFusionStages so all three early-return paths share the same
// boost surface. Salience and recency are independent axes — either,
// both, or neither fires depending on resolved modes.
- if (fused.length > 0) {
+ if (fused.length > 0) await req.timer.stage('post_fusion', async () => {
await runPostFusionStages(engine, fused, {
...postFusionOpts, skipMetadataBoosts: !metadataBoostGate.boosts_applied,
});
@@ -181,7 +181,7 @@ export async function fuseArms(
// No-op when boost factor is 1.0 (general intent or weighting disabled).
await applyIdentityBoosts(req, fused);
fused.sort((a, b) => b.score - a.score);
- }
+ });
trace?.observe('fused', fused);
return { fused, relaxedDropped, keywordArmConfidence, metadataBoostGate };
}
diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.ts
index 8504cc96e6..d360a19001 100644
--- a/src/core/search/hybrid/request.ts
+++ b/src/core/search/hybrid/request.ts
@@ -30,6 +30,7 @@ import { resolveSearchDateBounds } from '../date-bounds.ts';
import { type DecideSearchContext, decideMetaFor, resolveAndLaunchDecide } from '../decide-stage.ts';
import { applySearchIntent } from '../decide-retrieval.ts';
import { liftModeCut } from '../page-rank-cut.ts';
+import { type StageTimer, UNTIMED } from '../stage-timings.ts';
/**
* Everything the stages read, resolved once at hybridSearch entry, plus the
@@ -73,6 +74,8 @@ export interface HybridRequest {
rerankMeta?: { model_resolved: string };
/** Set by the relational arm when the multi-hop planner ran (meta.relational_plan). */
relationalPlan?: import('../relational-recall.ts').RelationalPlanMeta;
+ /** The op's stage-timing collector (`opts._timings`), or the no-op timer. */
+ timer: StageTimer;
}
const DEBUG = process.env.GBRAIN_SEARCH_DEBUG === '1';
@@ -309,6 +312,7 @@ export async function resolveHybridRequest(
expansionApplied: false,
lastResultsCount: 0,
lastRank1Score: undefined,
+ timer: opts?._timings ?? UNTIMED,
};
if (decide) req.decide = decide;
return req;
diff --git a/src/core/search/query-arms.ts b/src/core/search/query-arms.ts
index c3fa4f162b..0dfab9fb3e 100644
--- a/src/core/search/query-arms.ts
+++ b/src/core/search/query-arms.ts
@@ -11,10 +11,17 @@ import type { BrainEngine } from '../engine.ts';
import type { PageReadScope, SearchResult } from '../types.ts';
import { anchorOpResults } from './entity-anchor.ts';
import { applyFactsArm, applyTemporalFactReserve, hasTemporalCue, queryFactsArmEnabled, temporalFactReserveEnabled } from './facts-arm.ts';
+import { type StageTimer, UNTIMED } from './stage-timings.ts';
export async function applyQueryArms(engine: BrainEngine, p: Record<string, unknown>, query: string, results: SearchResult[],
- scope: PageReadScope & { filtered: boolean; evidencePlan: boolean; evidenceBudget?: number; remote: boolean; queryEmbedding: Float32Array | null; rowCap: () => Promise<number> }): Promise<SearchResult[]> {
- const anchored = await anchorOpResults(engine, p, query, results, scope);
+ scope: PageReadScope & { filtered: boolean; evidencePlan: boolean; evidenceBudget?: number; remote: boolean; queryEmbedding: Float32Array | null; rowCap: () => Promise<number>; timer?: StageTimer }): Promise<SearchResult[]> {
+ const timer = scope.timer ?? UNTIMED;
+ const anchored = await timer.stage('anchoring', () => anchorOpResults(engine, p, query, results, scope));
+ return timer.stage('facts_arm', () => applyFactsStage(engine, p, query, anchored, scope));
+}
+
+async function applyFactsStage(engine: BrainEngine, p: Record<string, unknown>, query: string, anchored: SearchResult[],
+ scope: Parameters<typeof applyQueryArms>[4]): Promise<SearchResult[]> {
if (p.offset || scope.filtered || p.since || p.until || p.lang || p.symbol_kind || p.near_symbol) return anchored;
const tokenBudget = !scope.evidencePlan && typeof p.token_budget === 'number' ? p.token_budget : undefined;
const opts = { sourceId: scope.sourceId, sourceIds: scope.sourceIds, remote: scope.remote, minTrust: scope.minTrust, suppressFlagged: scope.suppressFlagged, queryEmbedding: scope.queryEmbedding, rowCap: scope.rowCap, readScope: scope, tokenBudget };
diff --git a/src/core/search/stage-timings.ts b/src/core/search/stage-timings.ts
new file mode 100644
index 0000000000..6a1344288f
--- /dev/null
+++ b/src/core/search/stage-timings.ts
@@ -0,0 +1,119 @@
+/**
+ * Per-request search stage timings for `_meta.retrieval.timings` and
+ * `--explain`. One `SearchTimings` collector per `search` / `query` call,
+ * threaded into every hybrid call that request makes (`HybridSearchOpts._timings`).
+ *
+ * Stages are critical-path blocked wall-clock spans: the collector holds one
+ * current stage, and every moment of the request is attributed to whichever
+ * stage is current (or to `other` when none is). A nested stage takes over the
+ * clock and hands it back when it ends, so a fan-out hybrid call inside
+ * `alias_fanout` books its lexical time once, under `lexical`. Retries and
+ * discarded escalations run through the same collector and accumulate. Work
+ * that runs alongside the critical path (the parallel lexical arms) is reported
+ * per label in `overlapped_ms` and never added to a stage. `total_ms` is its
+ * own monotonic span from the collector's start to the snapshot, so
+ * `sum(stages_ms) + other_ms === total_ms` and `other_ms >= 0`.
+ *
+ * Timing never changes execution: `stage` awaits exactly the work it is given
+ * and `overlap` returns the promise it observes.
+ */
+
+export type SearchStage =
+ | 'setup' | 'lexical' | 'relational' | 'expansion' | 'embed' | 'vector'
+ | 'fuse' | 'post_fusion' | 'rerank' | 'alias_fanout' | 'anchoring' | 'facts_arm' | 'response';
+
+export interface SearchTimingsMeta {
+ total_ms: number;
+ stages_ms: Partial<Record<SearchStage, number>>;
+ other_ms: number;
+ overlapped_ms?: Record<string, number>;
+}
+
+export interface StageTimer {
+ stage<T>(stage: SearchStage, work: () => Promise<T>): Promise<T>;
+ overlap<T>(label: string, work: Promise<T>): Promise<T>;
+}
+
+/** The timer for calls nobody measures (bare hybrid callers, internal searches). */
+export const UNTIMED: StageTimer = {
+ stage: (_stage, work) => work(),
+ overlap: (_label, work) => work,
+};
+
+export class SearchTimings implements StageTimer {
+ private readonly startedAt: number;
+ private current: SearchStage | null = null;
+ private since: number;
+ private readonly spent = new Map<SearchStage, number>();
+ private readonly overlapped = new Map<string, number>();
+
+ constructor(private readonly now: () => number = () => performance.now()) {
+ this.startedAt = this.since = now();
+ }
+
+ private switchTo(stage: SearchStage | null): SearchStage | null {
+ const at = this.now();
+ if (this.current) this.spent.set(this.current, (this.spent.get(this.current) ?? 0) + at - this.since);
+ this.since = at;
+ const previous = this.current;
+ this.current = stage;
+ return previous;
+ }
+
+ async stage<T>(stage: SearchStage, work: () => Promise<T>): Promise<T> {
+ const previous = this.switchTo(stage);
+ if (!this.spent.has(stage)) this.spent.set(stage, 0);
+ try {
+ return await work();
+ } finally {
+ this.switchTo(previous);
+ }
+ }
+
+ overlap<T>(label: string, work: Promise<T>): Promise<T> {
+ const started = this.now();
+ const settle = () => { this.overlapped.set(label, (this.overlapped.get(label) ?? 0) + this.now() - started); };
+ work.then(settle, settle);
+ return work;
+ }
+
+ /** Integer milliseconds; stages and `other` are apportioned so they sum to `total_ms` exactly. */
+ snapshot(): SearchTimingsMeta {
+ const at = this.now();
+ const spent = new Map(this.spent);
+ if (this.current) spent.set(this.current, (spent.get(this.current) ?? 0) + at - this.since);
+ const total = at - this.startedAt;
+ const parts = [...spent.entries()];
+ const other = Math.max(0, total - parts.reduce((sum, [, ms]) => sum + ms, 0));
+ const ints = apportion([...parts.map(([, ms]) => ms), other], Math.round(total));
+ const overlappedMs = Object.fromEntries([...this.overlapped].map(([label, ms]) => [label, Math.round(ms)]));
+ return {
+ total_ms: Math.round(total),
+ stages_ms: Object.fromEntries(parts.map(([stage], i) => [stage, ints[i]])),
+ other_ms: ints[ints.length - 1],
+ ...(this.overlapped.size > 0 ? { overlapped_ms: overlappedMs } : {}),
+ };
+ }
+}
+
+/** Largest-remainder rounding: non-negative integers within 1 of each value, summing to `total`. */
+function apportion(values: number[], total: number): number[] {
+ const floors = values.map(v => Math.floor(v));
+ let left = total - floors.reduce((sum, v) => sum + v, 0);
+ const byRemainder = values.map((v, i) => [v - floors[i], i] as const).sort((a, b) => b[0] - a[0]);
+ for (const [, i] of byRemainder) {
+ if (left <= 0) break;
+ floors[i] += 1;
+ left -= 1;
+ }
+ return floors;
+}
+
+/** One `--explain` header line: `timings: 142ms total — lexical 12, embed 30, …, other 5 (overlapped: keyword_arm 10)`. */
+export function formatTimingsSummary(timings: SearchTimingsMeta | undefined): string | null {
+ if (!timings || typeof timings.total_ms !== 'number') return null;
+ const stages = Object.entries(timings.stages_ms ?? {}).map(([stage, ms]) => `${stage} ${ms}`);
+ const overlapped = Object.entries(timings.overlapped_ms ?? {}).map(([label, ms]) => `${label} ${ms}`);
+ return `timings: ${timings.total_ms}ms total — ${[...stages, `other ${timings.other_ms}`].join(', ')}`
+ + (overlapped.length > 0 ? ` (overlapped: ${overlapped.join(', ')})` : '');
+}
diff --git a/test/cli-explain-degraded-render.test.ts b/test/cli-explain-degraded-render.test.ts
index e97917de13..a30c947e06 100644
--- a/test/cli-explain-degraded-render.test.ts
+++ b/test/cli-explain-degraded-render.test.ts
@@ -47,3 +47,27 @@ describe('formatResult --explain threads the captured retrieval meta', () => {
expect(out).not.toContain('degraded:');
});
});
+
+describe('formatResult --explain prints the stage timings', () => {
+ const timings = { total_ms: 40, stages_ms: { setup: 2, lexical: 10, response: 3 }, other_ms: 25 };
+ const line = 'timings: 40ms total — setup 2, lexical 10, response 3, other 25';
+
+ test('a result list gets the timings header line', () => {
+ setCliOptions({ ...getCliOptions(), explain: true });
+ captureRetrievalMeta('retrieval', { returned_count: 1, retrieved_count: 1, degraded: [], timings });
+ expect(formatResult('search', [r('alice-foo', 1.5)], {}).startsWith(`${line}\n\n1. alice-foo`)).toBe(true);
+ });
+
+ test('an empty result names its cause, then the timings', () => {
+ setCliOptions({ ...getCliOptions(), explain: true });
+ captureRetrievalMeta('retrieval', { returned_count: 0, retrieved_count: 0, degraded: [], timings });
+ expect(formatResult('query', [], {})).toBe(`No results. (clean miss — no retrieval degradation)\n${line}\n`);
+ });
+
+ test('without --explain no timings are printed', () => {
+ captureRetrievalMeta('retrieval', { returned_count: 0, retrieved_count: 0, degraded: [], timings });
+ expect(formatResult('search', [], {})).not.toContain('timings');
+ captureRetrievalMeta('retrieval', { returned_count: 1, retrieved_count: 1, degraded: [], timings });
+ expect(formatResult('search', [r('alice-foo', 1.5)], {})).not.toContain('timings');
+ });
+});
diff --git a/test/search/stage-timings-ops.test.ts b/test/search/stage-timings-ops.test.ts
new file mode 100644
index 0000000000..f8dae453c7
--- /dev/null
+++ b/test/search/stage-timings-ops.test.ts
@@ -0,0 +1,173 @@
+/**
+ * Per-stage search timings on the `search` and `query` operations
+ * (`_meta.retrieval.timings`, src/core/search/stage-timings.ts): present on
+ * clean, degraded, empty and keyword-only responses; op-layer work is timed;
+ * a nested fan-out call is booked once; the parallel lexical arms stay
+ * parallel; the fields never reach MCP content blocks.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../../src/core/operations.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import type { SearchTimingsMeta } from '../../src/core/search/stage-timings.ts';
+import type { SearchResult } from '../../src/core/types.ts';
+
+let engine: PGLiteEngine;
+let lastMeta: Record<string, any> | null = null;
+const op = (name: string) => operations.find(o => o.name === name)!;
+const DIMS = 1536;
+
+function ctx(): OperationContext {
+ return {
+ engine, config: {} as never, logger: console as never, dryRun: false, remote: false, sourceId: 'default',
+ emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval') lastMeta = value as Record<string, any>; },
+ } as OperationContext;
+}
+
+async function run(name: 'search' | 'query', params: Record<string, unknown>): Promise<{ rows: SearchResult[]; meta: Record<string, any>; timings: SearchTimingsMeta }> {
+ lastMeta = null;
+ const rows = await op(name).handler(ctx(), params) as SearchResult[];
+ expect(lastMeta).not.toBeNull();
+ return { rows, meta: lastMeta!, timings: lastMeta!.timings };
+}
+
+/** The timing contract every response carries. */
+function expectTimings(t: SearchTimingsMeta | undefined): SearchTimingsMeta {
+ expect(t).toBeDefined();
+ const stages = Object.values(t!.stages_ms);
+ for (const ms of [t!.total_ms, t!.other_ms, ...stages]) expect(Number.isInteger(ms) && ms >= 0).toBe(true);
+ expect(stages.reduce((a, b) => a + b, 0) + t!.other_ms).toBe(t!.total_ms);
+ return t!;
+}
+
+/** A deterministic unit vector from the text (no provider). */
+function stubVector(text: string): number[] {
+ let h = 2166136261;
+ for (const ch of text) h = Math.imul(h ^ ch.charCodeAt(0), 16777619) >>> 0;
+ const out = Array.from({ length: DIMS }, (_, i) => Math.sin(h + i * 0.618));
+ const norm = Math.sqrt(out.reduce((s, v) => s + v * v, 0));
+ return out.map(v => v / norm);
+}
+
+/** A gateway that can embed (stub key + stub transport): the vector arms run. */
+function withEmbeddings(): void {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'stub-not-a-key' } });
+}
+
+/** Delay both lexical engine reads on this engine instance; restore after. */
+async function withSlowLexicalArms<T>(ms: number, fn: () => Promise<T>): Promise<T> {
+ const keyword = engine.searchKeyword.bind(engine);
+ const titles = engine.searchTitles.bind(engine);
+ const delay = () => new Promise(resolve => setTimeout(resolve, ms));
+ engine.searchKeyword = (async (...args: Parameters<typeof keyword>) => { await delay(); return keyword(...args); }) as typeof engine.searchKeyword;
+ engine.searchTitles = (async (...args: Parameters<typeof titles>) => { await delay(); return titles(...args); }) as typeof engine.searchTitles;
+ try { return await fn(); } finally { engine.searchKeyword = keyword; engine.searchTitles = titles; }
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ __setEmbedTransportForTests((async (input: { values: string[] }) => ({ embeddings: input.values.map(stubVector) })) as never);
+ withEmbeddings();
+ const pages: Array<[string, string]> = [
+ ['notes/widget-roadmap', '---\ntitle: Widget roadmap\n---\nThe quarterly widget roadmap covers pricing, renewal dates and the launch plan.\n'],
+ ['notes/renewal-memo', '---\ntitle: Renewal memo\n---\nThe renewal memo lists widget pricing tiers and the support handbook.\n'],
+ ['companies/acme-example', '---\ntitle: "Customer: Acme Example"\n---\nAcme Example, account code: ACMEX, buys the widget bundle every quarter.\n'],
+ ['notes/acmex-amendment', '---\ntitle: ACMEX amendment\n---\nAmendment for ACMEX: the bundle renewal moves to march.\n'],
+ ];
+ for (const [slug, md] of pages) await importFromContent(engine, slug, md, { sourceId: 'default' });
+}, 120_000);
+
+afterAll(async () => {
+ resetGateway();
+ await engine.disconnect();
+});
+
+describe('timings ride every search and query response', () => {
+ test('hybrid search (embed, vector, fusion, rerank and op-layer stages), degraded by a keyless reranker', async () => {
+ withEmbeddings();
+ const { rows, meta, timings } = await run('search', { query: 'widget roadmap pricing' });
+ expect(rows.length).toBeGreaterThan(0);
+ expect(meta.vector_enabled).toBe(true);
+ const t = expectTimings(timings);
+ for (const stage of ['setup', 'lexical', 'relational', 'embed', 'vector', 'fuse', 'post_fusion', 'rerank', 'alias_fanout', 'anchoring', 'response']) {
+ expect(t.stages_ms).toHaveProperty(stage);
+ }
+ expect(Object.keys(t.overlapped_ms ?? {}).sort()).toEqual(['keyword_arm', 'title_arm']);
+ });
+
+ test('query adds the facts arm and expansion stages', async () => {
+ withEmbeddings();
+ const t = expectTimings((await run('query', { query: 'widget roadmap pricing', expand: true })).timings);
+ expect(t.stages_ms).toHaveProperty('facts_arm');
+ expect(t.stages_ms).toHaveProperty('expansion');
+ expect(t.stages_ms).toHaveProperty('vector');
+ });
+
+ test('a keyless brain: degraded keyword-only responses carry the fields', async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: {} });
+ for (const name of ['search', 'query'] as const) {
+ const { meta, timings } = await run(name, { query: 'widget roadmap' });
+ expect(meta.degraded.map((d: { stage: string }) => d.stage)).toContain('embed_unavailable');
+ const t = expectTimings(timings);
+ expect(t.stages_ms).toHaveProperty('lexical');
+ expect(t.stages_ms).not.toHaveProperty('vector');
+ }
+ });
+
+ test('empty responses carry the fields', async () => {
+ for (const name of ['search', 'query'] as const) {
+ const { rows, timings } = await run(name, { query: 'zyzzyva quokkaflux' });
+ expect(rows).toEqual([]);
+ expectTimings(timings);
+ }
+ });
+
+ test('the search.mcp_keyword_only path carries the fields', async () => {
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+ try {
+ const t = expectTimings((await run('search', { query: 'widget roadmap' })).timings);
+ expect(Object.keys(t.stages_ms)).toEqual(expect.arrayContaining(['setup', 'lexical', 'post_fusion', 'response']));
+ } finally {
+ await engine.setConfig('search.mcp_keyword_only', 'false');
+ }
+ });
+});
+
+describe('critical-path accounting', () => {
+ test('the parallel lexical arms stay parallel: one delay of lexical time, both arms overlapped', async () => {
+ withEmbeddings();
+ const DELAY = 300;
+ const started = performance.now();
+ const t = expectTimings((await withSlowLexicalArms(DELAY, () => run('search', { query: 'widget pricing' }))).timings);
+ const wall = performance.now() - started;
+ expect(t.overlapped_ms!.keyword_arm).toBeGreaterThanOrEqual(DELAY - 5);
+ expect(t.overlapped_ms!.title_arm).toBeGreaterThanOrEqual(DELAY - 5);
+ expect(t.stages_ms.lexical).toBeGreaterThanOrEqual(DELAY - 5);
+ expect(t.stages_ms.lexical).toBeLessThan(2 * DELAY - 20);
+ expect(wall).toBeLessThan(2 * DELAY + t.total_ms - t.stages_ms.lexical!);
+ });
+
+ test('a declared-name fan-out runs a second hybrid call whose lexical time is booked once, under lexical', async () => {
+ withEmbeddings();
+ const DELAY = 150;
+ const { meta, timings } = await withSlowLexicalArms(DELAY, () => run('search', { query: 'Acme Example bundle renewal' }));
+ expect(meta.other_names?.map((n: { alias: string }) => n.alias)).toContain('ACMEX');
+ const t = expectTimings(timings);
+ expect(t.stages_ms.lexical).toBeGreaterThanOrEqual(2 * DELAY - 10);
+ expect(t.stages_ms.alias_fanout).toBeLessThan(DELAY);
+ expect(t.overlapped_ms!.keyword_arm).toBeGreaterThanOrEqual(2 * DELAY - 10);
+ });
+
+ test('timings stay out of MCP content blocks and ride _meta.retrieval', async () => {
+ withEmbeddings();
+ const res = await dispatchToolCall(engine as never, 'search', { query: 'widget roadmap' }, { remote: true, transport: 'stdio', sourceId: 'default' });
+ const timings = (res._meta?.retrieval as Record<string, unknown> | undefined)?.timings as SearchTimingsMeta;
+ expectTimings(timings);
+ const content = JSON.stringify(res.content);
+ for (const needle of ['timings', 'total_ms', 'stages_ms', 'overlapped_ms', 'other_ms']) expect(content).not.toContain(needle);
+ });
+});
diff --git a/test/search/stage-timings.test.ts b/test/search/stage-timings.test.ts
new file mode 100644
index 0000000000..57d21d6c45
--- /dev/null
+++ b/test/search/stage-timings.test.ts
@@ -0,0 +1,150 @@
+/**
+ * The per-request stage-timing collector (src/core/search/stage-timings.ts):
+ * critical-path attribution, nesting, overlapped work, integer apportioning,
+ * the --explain line, and that timing never serializes concurrent work.
+ */
+import { describe, expect, test } from 'bun:test';
+import { SearchTimings, UNTIMED, formatTimingsSummary } from '../../src/core/search/stage-timings.ts';
+import { formatResultsExplain } from '../../src/core/search/explain-formatter.ts';
+
+/** A manual clock: `tick(ms)` advances it. */
+function manualClock() {
+ let t = 1000;
+ return { now: () => t, tick: (ms: number) => { t += ms; } };
+}
+
+const sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
+const sum = (o: Record<string, number>) => Object.values(o).reduce((a, b) => a + b, 0);
+
+describe('SearchTimings attribution', () => {
+ test('each moment goes to the current stage; untimed time is other; total is the whole span', async () => {
+ const c = manualClock();
+ const t = new SearchTimings(c.now);
+ c.tick(3);
+ await t.stage('setup', async () => { c.tick(5); });
+ c.tick(2);
+ await t.stage('lexical', async () => { c.tick(10); });
+ await t.stage('response', async () => { c.tick(4); });
+ c.tick(1);
+ expect(t.snapshot()).toEqual({ total_ms: 25, stages_ms: { setup: 5, lexical: 10, response: 4 }, other_ms: 6 });
+ });
+
+ test('a nested stage takes the clock and hands it back: a nested hybrid call is booked once', async () => {
+ const c = manualClock();
+ const t = new SearchTimings(c.now);
+ await t.stage('alias_fanout', async () => {
+ c.tick(2);
+ await t.stage('lexical', async () => { c.tick(7); });
+ await t.stage('vector', async () => { c.tick(5); });
+ c.tick(1);
+ });
+ const s = t.snapshot();
+ expect(s.stages_ms).toEqual({ alias_fanout: 3, lexical: 7, vector: 5 });
+ expect(sum(s.stages_ms) + s.other_ms).toBe(s.total_ms);
+ });
+
+ test('repeated stages (retries, a discarded escalation) accumulate', async () => {
+ const c = manualClock();
+ const t = new SearchTimings(c.now);
+ for (const ms of [4, 6]) await t.stage('lexical', async () => { c.tick(ms); });
+ expect(t.snapshot().stages_ms.lexical).toBe(10);
+ });
+
+ test('a stage that throws still ends, and its time stays booked', async () => {
+ const c = manualClock();
+ const t = new SearchTimings(c.now);
+ await expect(t.stage('rerank', async () => { c.tick(8); throw new Error('provider down'); })).rejects.toThrow('provider down');
+ c.tick(2);
+ expect(t.snapshot()).toEqual({ total_ms: 10, stages_ms: { rerank: 8 }, other_ms: 2 });
+ });
+
+ test('a stage that ran in under a millisecond is reported as 0, not dropped', async () => {
+ const t = new SearchTimings(manualClock().now);
+ await t.stage('relational', async () => {});
+ expect(t.snapshot().stages_ms).toEqual({ relational: 0 });
+ });
+
+ test('a snapshot inside a stage counts the stage so far', async () => {
+ const c = manualClock();
+ const t = new SearchTimings(c.now);
+ let inner: ReturnType<SearchTimings['snapshot']> | undefined;
+ await t.stage('response', async () => { c.tick(6); inner = t.snapshot(); });
+ expect(inner).toEqual({ total_ms: 6, stages_ms: { response: 6 }, other_ms: 0 });
+ });
+
+ test('overlapped work is reported per label and never added to a stage or the total', async () => {
+ const c = manualClock();
+ const t = new SearchTimings(c.now);
+ await t.stage('lexical', async () => {
+ const a = t.overlap('keyword_arm', (async () => { await sleep(0); c.tick(9); })());
+ const b = t.overlap('title_arm', Promise.reject(new Error('arm failed')).catch(() => undefined));
+ await Promise.all([a, b]);
+ });
+ const s = t.snapshot();
+ expect(s.stages_ms).toEqual({ lexical: 9 });
+ expect(s.total_ms).toBe(9);
+ expect(s.overlapped_ms).toEqual({ keyword_arm: 9, title_arm: 0 });
+ });
+
+ test('a rejected overlapped promise rejects to its caller and is still timed', async () => {
+ const t = new SearchTimings();
+ const failing = Promise.reject(new Error('boom'));
+ await expect(t.overlap('keyword_arm', failing)).rejects.toThrow('boom');
+ expect(t.snapshot().overlapped_ms).toHaveProperty('keyword_arm');
+ });
+});
+
+describe('integer apportioning', () => {
+ test('fractional stages round so stages + other sum to total exactly, and other is never negative', async () => {
+ const c = manualClock();
+ const t = new SearchTimings(c.now);
+ for (const stage of ['setup', 'lexical', 'vector', 'fuse', 'rerank'] as const) {
+ await t.stage(stage, async () => { c.tick(0.4); });
+ c.tick(0.05);
+ }
+ const s = t.snapshot();
+ expect(s.total_ms).toBe(2);
+ expect(sum(s.stages_ms) + s.other_ms).toBe(s.total_ms);
+ expect(s.other_ms).toBeGreaterThanOrEqual(0);
+ for (const ms of Object.values(s.stages_ms)) expect(Number.isInteger(ms) && ms >= 0 && ms <= 1).toBe(true);
+ });
+});
+
+describe('timing never serializes execution', () => {
+ test('two delayed overlapping works inside one stage finish in one delay, not two', async () => {
+ const t = new SearchTimings();
+ const started = performance.now();
+ await t.stage('lexical', () => Promise.all([
+ t.overlap('keyword_arm', sleep(150)),
+ t.overlap('title_arm', sleep(150)),
+ ]));
+ const wall = performance.now() - started;
+ const s = t.snapshot();
+ expect(wall).toBeLessThan(270);
+ expect(s.stages_ms.lexical).toBeGreaterThanOrEqual(145);
+ expect(s.stages_ms.lexical).toBeLessThan(270);
+ expect(s.overlapped_ms!.keyword_arm).toBeGreaterThanOrEqual(145);
+ expect(s.overlapped_ms!.title_arm).toBeGreaterThanOrEqual(145);
+ expect(s.total_ms).toBeLessThan(s.overlapped_ms!.keyword_arm + s.overlapped_ms!.title_arm);
+ });
+
+ test('the untimed timer passes work straight through', async () => {
+ const p = Promise.resolve(7);
+ expect(UNTIMED.overlap('keyword_arm', p)).toBe(p);
+ expect(await UNTIMED.stage('lexical', async () => 8)).toBe(8);
+ });
+});
+
+describe('--explain line', () => {
+ const timings = { total_ms: 142, stages_ms: { setup: 3, lexical: 12, embed: 30, response: 4 }, other_ms: 2, overlapped_ms: { keyword_arm: 11, title_arm: 9 } };
+
+ test('formatTimingsSummary names every stage, other, and the overlapped arms', () => {
+ expect(formatTimingsSummary(timings)).toBe('timings: 142ms total — setup 3, lexical 12, embed 30, response 4, other 2 (overlapped: keyword_arm 11, title_arm 9)');
+ expect(formatTimingsSummary(undefined)).toBeNull();
+ });
+
+ test('formatResultsExplain prints the timings line in its header', () => {
+ const out = formatResultsExplain([{ slug: 'notes/a', score: 1, chunk_text: 'x' } as never], { vector_enabled: false, expansion_applied: false, detail_resolved: null, timings } as never);
+ expect(out.split('\n')).toContain(formatTimingsSummary(timings)!);
+ });
+});