Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search): start the query embed and expansion alongside the keyword arms

garrytan3b0aeac393de
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 33d78d4ae2..5411fa0375 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,17 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**`search` and `query` start the query embed (and `query`'s expansion) alongside the keyword arms instead of after them, so a search no longer waits for both one after the other.** On a 20,000-page Postgres brain with Voyage embeddings and reranking, the median warm `search` dropped from 578 ms to 424 ms and `query` from 578 ms to 448 ms (two rounds of 40 unique questions each); on a 400-page PGLite brain the saving is the keyword arms' 13 to 15 ms. Results are unchanged.
+
+### Itemized changes
+
+- **Vector side runs alongside the lexical arms** (`src/core/search/hybrid.ts`, `src/core/search/hybrid/arms.ts`): after the keyword-only gate, `startVectorSide` begins modality resolution, expansion, the query embeds and the vector searches, then the keyword, title and relational arms run as before, and `joinVectorSide` waits for the vector side. That side reads nothing the lexical and relational arms produce. Its `degraded[]` stamps (vector-pool exhaustion included) go to their own list and are appended after the lexical ones, so the order matches a sequential run. A keyword-only search (no embedding provider, embeddings opted out, System One keyword-only) starts no vector work. When the lexical arms throw, the vector side is allowed to settle before the error is rethrown.
+- **Timings** (`src/core/search/stage-timings.ts`): `StageTimer` gains `branch()` and `join()`. The part of `expansion`, `embed` and `vector` that finished while the lexical arms ran is now listed in `overlapped_ms` under the stage's name; `stages_ms` keeps the part the request waited for (the stage key is present even at 0). `sum(stages_ms) + other_ms = total_ms` still holds.
+- **Parity:** the refactor-wave-1 bench result digests match master on PGLite and on Postgres (400 pages each). With stub embedder and reranker on one retained 20,000-page Postgres brain, all 80 result lists match master's. At 4,000 fresh-imported Postgres pages master's own digests differ run to run (the HNSW index is rebuilt on each import), so that size is not a parity check.
+- **Tests:** a fail-first probe in `test/search/stage-timings-ops.test.ts` with a 300 ms embed and 300 ms lexical arms (632 ms on the old flow, under 550 ms now), a degraded-order case where the embed fails before the keyword arm, and branch/join accounting cases in `test/search/stage-timings.test.ts`.
+
## [0.60.210.0] - 2026-10-13
**The Ubicloud gate's `verify` typecheck runs warm, so it no longer crosses the 120 s per-check cap on a loaded VM.** It crossed the cap at 121 s on two gates on 2026-10-13 (#6618, #6612), and both passed on rerun. The cause wasn't contention with test items: the VM that runs `verify` runs nothing else until verify is done. The cause was that every gate VM typechecked from scratch. `bun run typecheck` is `tsc --incremental` against `node_modules/.cache/gbrain-typecheck.tsbuildinfo`, and the checkout tarball never carries that file. A cold `tsc` takes 81 s on a 16-vCPU gate VM with nothing else running, so verify had 1.4x headroom before any host load. The cap is unchanged.
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index 9e08158c06..67dcfe4a39 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -37,7 +37,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`, and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_search, filtered short pools need an exhaustion witness, and Postgres alone can use one exact fallback inside the remaining deadline. Hybrid and direct image query paths publish the scoped details and recall-affecting degraded stage; an exhausted genuine small corpus does not emit a false warning. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`. Both identity injections (alias hop and exact-lookup tier) take one `IdentityTierOpts` built once per request and skip any slug `isExcludedIdentity` rejects: caller `exclude_slugs` plus the resolved prefix excludes (`resolveHardExcludes`: defaults, `GBRAIN_SEARCH_EXCLUDE`, per-call prefixes, minus `include_slug_prefixes`), on all three return paths. Opt-in single-token hop (#5428; per-call `aliasTokenHop` or brain config `search.alias_token_hop=true`, read in the mode snapshot): when the whole query is not an alias, a query token that is the alias of exactly one person/company identity page (`isIdentityEntity`) moves that page to the front or injects it, at most two pages, order-preserving for the rest. Both post-rerank identity tiers (alias hop, `applyExactLookupTier`) are ORDER-PRESERVING: identity rows move to the front and every other row keeps its input (reranked) order — never a global re-sort by `score`, which is still the fusion score after reranking; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired — on an exact slug/title match OR a title / slug tail mentioned inside the query (`isTitleMentionedInQuery`), and `applyAliasMentionBoost` gives the same bounded boost to a present row whose declared alias occurs in the query (one batched `resolveAliases` over 1–5-token query n-grams, fail-open). **Fusion is page-grain:** `rrfFusion`/`rrfFusionWeighted` sum each list's vote per page `(source_id, slug)` (a list counts a page once, at its best rank) and the page's LEAD chunk (largest own vote; ties to the first list, a vector arm) carries the page's summed score while the page's other chunks keep their own votes — giving every chunk the page score let a page's second chunk crowd other pages out of chunk-limited results. Every arm is page-grain with its own representative chunk, so chunk-keyed fusion split a page's cross-arm agreement. **Detail:** only an EXPLICIT `detail: 'low'` hard-filters every arm to compiled truth (with the 2x boost and the zero-result escalation); an auto-detected `low` (entity intent) passes no SQL filter and applies `AUTO_LOW_COMPILED_TRUTH_TILT` (1.2x) via `compiledTruthFusionBoost`. The engine opts rebuild forwards `exclude_slugs`, `exclude_slug_prefixes` and `include_slug_prefixes` to every arm. A rejected keyword or title arm fails open and stamps `keyword_arm_failed` / `title_arm_failed` (reason `timeout | provider_error`) in `meta.degraded`, so MCP callers can tell a partial read from a clean miss. In `both` modality `cosineReScore` rescores image-arm rows in the image space (`embedding_image`, multimodal query vector); text rows keep the text column. The intent identity boosts (exact/mentioned title or slug, mentioned alias) run through one `applyIdentityBoosts` closure on the fused path and both keyword-only paths. Under unified multimodal routing the cosine rescore hydrates `embedding_multimodal` (the space the query was embedded in), and `cosineSimilarity` returns 0 for vectors of different lengths. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). `hybridSearch` and `hybridSearchCached` are short orchestrators over the named stages in `src/core/search/hybrid/` (next entry); the file keeps the post-fusion boosts, RRF, cosine rescore, the cache-write drainer and the public helpers.
-- `src/core/search/hybrid/` — hybridSearch pipeline stages, called in a fixed order so every engine query and provider call happens exactly as before: `request.ts` (`resolveHybridRequest` builds a `HybridRequest` once: mode, embedding column, limits (per-arm pool from `perArmPoolLimit` in `src/core/search/eval-pool-depth.ts`: today's max(2·limit, floor, offset+limit) capped at 100 unless an eval sets `--eval-pool-depth`), intent, `searchOpts`, identity-tier opts, and the accumulators `vectorPoolUnderfill` / `expansionApplied` / `lastResultsCount` / `lastRank1Score` that stages write only as `req.<field>`; `emitHybridMeta`, `applyIdentityBoosts`), `arms.ts` (lexical, relational, modality + expansion, vector arms), `keyword-only.ts` (the no-provider and all-vector-arms-empty return paths; `opts.decide.keywordOnly`, the System One S6 fire retrieval, takes the no-provider path on purpose without the vector-unavailable degraded marker or warning), `rank.ts` (fusion + post-fusion boosts, A2 expansion, rerank + relational pin, identity tiers + adaptive return + autocut + relational slot, main return), `cache-stages.ts` (hybridSearchCached mode resolution, semantic-cache handle, skip gate, hit path; the result cache stays hard-disabled), `degraded.ts`, `effective-modes.ts`, `rerank-gate.ts` (the W3 pre-rerank grade; see the `crag.ts` entry in Core Search 2/2). The orchestrators wrap each stage in `req.timer` / `opts._timings` (stage-timings.ts). Stages import public helpers back from `hybrid.ts` at call time only (the `exact-lookup.ts` pattern); `hybrid.ts` exports nothing new. Pinned by `test/hybrid-golden.test.ts` (exact `(id, score)`, cold and warm).
+- `src/core/search/hybrid/` — hybridSearch pipeline stages. `startVectorSide` runs modality, expansion and the vector arms alongside the lexical and relational arms (`runLexicalAndRelational`) on its own timer branch, `degraded` list and `vectorPoolMetaSink`; `joinVectorSide` merges its stamps and `expansionApplied` after the lexical ones, so `degraded[]` keeps the sequential order. Every other stage runs in a fixed order: `request.ts` (`resolveHybridRequest` builds a `HybridRequest` once: mode, embedding column, limits (per-arm pool from `perArmPoolLimit` in `src/core/search/eval-pool-depth.ts`: today's max(2·limit, floor, offset+limit) capped at 100 unless an eval sets `--eval-pool-depth`), intent, `searchOpts`, identity-tier opts, and the accumulators `vectorPoolUnderfill` / `expansionApplied` / `lastResultsCount` / `lastRank1Score` that stages write only as `req.<field>`; `emitHybridMeta`, `applyIdentityBoosts`), `arms.ts` (lexical, relational, modality + expansion, vector arms), `keyword-only.ts` (the no-provider and all-vector-arms-empty return paths; `opts.decide.keywordOnly`, the System One S6 fire retrieval, takes the no-provider path on purpose without the vector-unavailable degraded marker or warning), `rank.ts` (fusion + post-fusion boosts, A2 expansion, rerank + relational pin, identity tiers + adaptive return + autocut + relational slot, main return), `cache-stages.ts` (hybridSearchCached mode resolution, semantic-cache handle, skip gate, hit path; the result cache stays hard-disabled), `degraded.ts`, `effective-modes.ts`, `rerank-gate.ts` (the W3 pre-rerank grade; see the `crag.ts` entry in Core Search 2/2). The orchestrators wrap each stage in `req.timer` / `opts._timings` (stage-timings.ts). Stages import public helpers back from `hybrid.ts` at call time only (the `exact-lookup.ts` pattern); `hybrid.ts` exports nothing new. Pinned by `test/hybrid-golden.test.ts` (exact `(id, score)`, cold and warm).
- `src/core/search/eval-pool-depth.ts` — eval-only candidate pool depth for the System One recall experiment: `setEvalPoolDepth(N)` (N ≤ 300; only `gbrain eval longmemeval --eval-pool-depth` calls it) raises `searchLimitCap()` (the per-arm cap both engines' keyword/vector arms clamp to, default `MAX_SEARCH_LIMIT` 100) and makes every arm fetch N (`perArmPoolLimit`, used by `hybrid/request.ts`). Production depth is unchanged. Tests: `test/eval-pool-depth.test.ts`.
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index f9507757a4..c37f5d1ac9 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap(env, config)` layers defaults (dropped by a `none` entry), the brain's `search.source_boosts` config and the env override; hybridSearch resolves it once from the mode config snapshot and passes it to the engines as `SearchOpts.source_boosts` (engines fall back to defaults + env when absent; the keyword-only `search` op branch reads the key itself). `resolveHardExcludes` merges defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor/checks/calibration.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.
- `src/core/search/provenance-demotion.ts` — `applyGeneratedDemotion(engine, list, query, scope)`, called first in `applyIdentityBoosts` (hybrid/request.ts) on the fused path and both keyword-only paths, so it runs before reranking and before the pool is cut. Rows whose page carries a gbrain-owned marker (frontmatter `dream_generated: true`, type `extract_receipt`) get `provenance: 'generated'`; such a row is multiplied by `GENERATED_FACTOR` (0.5, stamped `generated_demotion`) only when the query names an entity (`resolveQueryEntity`), the page links to it, and a non-generated row in the pool is the entity page or links to it. `recordsCorrection` (frontmatter `supersedes`/`corrects`, a facts-fence row with `valid_until`) exempts corrections. `search.demote_generated=false` keeps scores. Tests: `test/search-provenance-demotion.test.ts`.
-- `src/core/search/stage-timings.ts` — per-request search stage timings. The `search`/`query` handlers create one `SearchTimings` and thread it into every hybrid call of the request (`HybridSearchOpts._timings`, `HybridRequest.timer`; absent = `UNTIMED`, a pass-through). `stage(name, work)` books critical-path blocked wall-clock time: one current stage at a time, a nested stage takes the clock and hands it back, so a fan-out or escalation hybrid call is booked once under its own stages, and retries accumulate. `overlap(label, promise)` times concurrent work (the keyword and title arms) into `overlapped_ms` without adding it to a stage. `snapshot()` reads `total_ms` from its own monotonic start, apportions integer `stages_ms` + `other_ms` to sum to it exactly (`other_ms >= 0`); `searchOutput` takes it after the returned rows are assembled and emits it as `_meta.retrieval.timings` (never in content blocks); `formatTimingsSummary` is the `--explain` line. Stages: setup, lexical, relational, expansion, embed, vector, fuse, post_fusion, rerank, alias_fanout, anchoring, facts_arm, response. The gate (every bench query: `0 <= total - sum(stages) <= 10%`) is the `timings` phase of `scripts/bench-refactor-wave-1.ts`. Pinned by `test/search/stage-timings.test.ts` and `test/search/stage-timings-ops.test.ts`.
+- `src/core/search/stage-timings.ts` — per-request search stage timings. The `search`/`query` handlers create one `SearchTimings` and thread it into every hybrid call of the request (`HybridSearchOpts._timings`, `HybridRequest.timer`; absent = `UNTIMED`, a pass-through). `stage(name, work)` books critical-path blocked wall-clock time: one current stage at a time, a nested stage takes the clock and hands it back, so a fan-out or escalation hybrid call is booked once under its own stages, and retries accumulate. `overlap(label, promise)` times concurrent work (the keyword and title arms) into `overlapped_ms` without adding it to a stage. `branch()` returns a timer for stages run alongside the critical path (hybrid's vector side: modality, expansion, embed, vector arms); until `join(branch, promise)` its stage time goes to `overlapped_ms` under the stage name, and from the join the wait is booked to the branch's current stage (the stage key appears in `stages_ms` even at 0). `snapshot()` reads `total_ms` from its own monotonic start, apportions integer `stages_ms` + `other_ms` to sum to it exactly (`other_ms >= 0`); `searchOutput` takes it after the returned rows are assembled and emits it as `_meta.retrieval.timings` (never in content blocks); `formatTimingsSummary` is the `--explain` line. Stages: setup, lexical, relational, expansion, embed, vector, fuse, post_fusion, rerank, alias_fanout, anchoring, facts_arm, response. The gate (every bench query: `0 <= total - sum(stages) <= 10%`) is the `timings` phase of `scripts/bench-refactor-wave-1.ts`. Pinned by `test/search/stage-timings.test.ts` and `test/search/stage-timings-ops.test.ts`.
- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.
- `src/core/search/keyword-chunk-match.ts` — `buildKeywordChunkMatch(ftsLang, excludePrivate)`: the chunk side of `PostgresEngine.searchKeyword`'s statement (FROM source for `cc`, the full-text match, the `modality = 'text'` filter). For excludePrivate callers it puts the match in an `OFFSET 0` subquery the planner plans on its own: the private-visibility subplans otherwise inflate every join plan's cost so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (~1.1 s → ~0.2 s for a common term at 250k chunks). Local callers keep the unfenced join, which can plan in parallel (an OFFSET subquery forbids that). PGLite does not use it. Pinned by `test/search/keyword-arm-ranking.test.ts` and `test/e2e/keyword-arm-ranking-postgres.test.ts`.
diff --git a/docs/guides/search-explain.md b/docs/guides/search-explain.md
index a7942d3bc3..810fdb6ae2 100644
--- a/docs/guides/search-explain.md
+++ b/docs/guides/search-explain.md
@@ -59,7 +59,7 @@ timings: 74ms total — setup 1, lexical 12, relational 0, embed 0, vector 16, f
| `total_ms` | Wall time of the whole operation, measured on its own clock after the response is assembled. |
| `stages_ms` | Time the request spent blocked in each stage that ran: `setup` (scope, config, mode), `lexical`, `relational`, `expansion`, `embed`, `vector`, `fuse`, `post_fusion` (boosts, dedup, identity tiers, return sizing), `rerank`, `alias_fanout`, `anchoring`, `facts_arm` (query), `response` (evidence delivery, response metadata, redaction). A second search the operation runs (a retry, a CRAG re-run) adds to the same stages; the alias fan-out's keyword searches count under `alias_fanout`. |
| `other_ms` | Time no stage claimed. `sum(stages_ms) + other_ms = total_ms`. |
-| `overlapped_ms` | Work that ran alongside a stage, so it is not added to the total: the keyword and title arms run in parallel inside `lexical` (`keyword_arm`, `title_arm`), and `search`'s total-match count runs alongside the whole request (`keyword_count`). |
+| `overlapped_ms` | Work that ran alongside a stage, so it is not added to the total: the keyword and title arms run in parallel inside `lexical` (`keyword_arm`, `title_arm`), `search`'s total-match count runs alongside the whole request (`keyword_count`), and the vector side (query expansion, the query embed and the vector search) starts with the lexical arms, so the part of `expansion`, `embed` and `vector` that finished while they ran is listed here under the stage's name. The rest of those stages, the part the request had to wait for, stays in `stages_ms`. |
All values are integer milliseconds.
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index 88396d1f75..f8d522f558 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -46,7 +46,7 @@ import {
} from './query-cache.ts';
import { resolveHybridRequest } from './hybrid/request.ts';
import { prepareSemanticCache, resolveCacheSearchMode, semanticCacheSkipped, serveSemanticCacheHit } from './hybrid/cache-stages.ts';
-import { buildPostFusionOpts, buildRelationalList, resolveModalityAndQueries, runLexicalArms, runVectorArms } from './hybrid/arms.ts';
+import { buildPostFusionOpts, joinVectorSide, resolveEarlyModality, runLexicalAndRelational, startVectorSide } from './hybrid/arms.ts';
import { searchVectorFallback, searchWithoutEmbeddings } from './hybrid/keyword-only.ts';
import { factEmbeddingDisabled } from '../embedding-disabled.ts';
import { capSessionPool, expandStructuralNeighbors, finalizeHybridResults, fuseArms, rerankAndPin, sizeReturnPool } from './hybrid/rank.ts';
@@ -1106,17 +1106,15 @@ export async function hybridSearch(
}
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.
+ // Named stages (src/core/search/hybrid/): request -> start the vector side
+ // (modality + expansion -> vector arms) -> lexical arms -> relational arm ->
+ // [keyword-only return] -> join the vector side -> [keyword fallback return]
+ // -> fusion + post-fusion boosts -> structural expansion -> dedup -> rerank
+ // + pin -> identity tiers + return sizing -> main return. The vector side
+ // runs alongside the lexical arms; joinVectorSide merges it in sequential order.
const req = await timer.stage('setup', () => resolveHybridRequest(engine, query, opts));
const { resolvedMode, resolvedCol, cfgForColumn } = req;
- const lexical = await timer.stage('lexical', () => runLexicalArms(req));
- const { earlyModality } = lexical;
- const postFusionOpts = buildPostFusionOpts(req);
- const relationalList = await timer.stage('relational', () => buildRelationalList(req));
+ const earlyModality = await timer.stage('setup', () => resolveEarlyModality(req));
const { isAvailable } = await import('../ai/gateway.ts');
const providerProbe = resolvedCol.embeddingModel || undefined;
@@ -1146,13 +1144,15 @@ export async function hybridSearch(
// Hermetic eval canaries/CI: a caller-supplied queryEmbedFn produces the
// 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)) {
+ const keywordOnly = opts?.decide?.keywordOnly || (!opts?.queryEmbedFn && (opts?._embeddingOptedOut || !isAvailable('embedding', providerProbe)) && !willTryMultimodal);
+ const vectorSide = keywordOnly ? null : startVectorSide(req, multimodalProviderProbe ?? cfgForColumn?.embedding_multimodal_model ?? 'voyage:voyage-multimodal-3');
+ const { lexical, relationalList } = await runLexicalAndRelational(req, earlyModality, vectorSide);
+ const postFusionOpts = buildPostFusionOpts(req);
+ if (!vectorSide) {
return timer.stage('post_fusion', () => searchWithoutEmbeddings(req, lexical, relationalList, postFusionOpts, providerProbe));
}
- const { effectiveModality, unifiedRouting, queries } = await resolveModalityAndQueries(req);
- const { vectorArms, queryEmbedding, imageQueryEmbedding, unifiedDone } =
- await runVectorArms(req, { effectiveModality, unifiedRouting, queries, multimodalProviderProbe: multimodalProviderProbe ?? cfgForColumn?.embedding_multimodal_model ?? 'voyage:voyage-multimodal-3' });
+ const { effectiveModality, vectorArms, queryEmbedding, imageQueryEmbedding, unifiedDone } = await joinVectorSide(req, vectorSide);
if (queryEmbedding) opts?.onQueryEmbedding?.(queryEmbedding);
if (vectorArms.length === 0) {
return timer.stage('post_fusion', () => searchVectorFallback(req, lexical, relationalList, postFusionOpts));
diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.ts
index cbe9557d57..c29ba26f45 100644
--- a/src/core/search/hybrid/arms.ts
+++ b/src/core/search/hybrid/arms.ts
@@ -6,7 +6,8 @@
import { brainHasImageVectors } from '../image-vector-presence.ts';
import type { ModalityMode } from '../query-intent.ts';
import type { ExactLookupOpts } from '../exact-lookup.ts';
-import type { HybridRequest } from './request.ts';
+import { type HybridRequest, vectorPoolMetaSink } from './request.ts';
+import type { StageTimer } from '../stage-timings.ts';
import { type PostFusionOpts, embedQueryBounded, lazyQueryEmbedDeadline } from '../hybrid.ts';
import type { SearchOpts, SearchResult } from '../../types.ts';
import { type VectorArm, pushVectorList } from '../fusion-lists.ts';
@@ -26,9 +27,24 @@ export interface LexicalArms {
exactLookupOpts: ExactLookupOpts;
}
+/**
+ * The modality the lexical arms and the keyword-only gate read: the per-call
+ * override, else the regex suggestion. Pure regex via classifyQuery, so it is
+ * cheap. An inferred image/both modality on a brain with no image embeddings
+ * is text: the image arm has nothing to search and would only fail open (and
+ * 'image' would drop the keyword arm). Later stages read the same suggestion.
+ */
+export async function resolveEarlyModality(req: HybridRequest): Promise<ModalityMode> {
+ const { engine, opts, suggestions } = req;
+ if (!(opts?.crossModal && opts.crossModal !== 'auto') && (suggestions.suggestedModality ?? 'text') !== 'text' && !await brainHasImageVectors(engine)) suggestions.suggestedModality = 'text';
+ return (opts?.crossModal && opts.crossModal !== 'auto')
+ ? opts.crossModal
+ : (suggestions.suggestedModality ?? 'text');
+}
+
/** Keyword + title FTS arms, fetched concurrently (fail-open per arm, rethrow when both hit a dead database). */
-export async function runLexicalArms(req: HybridRequest): Promise<LexicalArms> {
- const { engine, query, opts, suggestions, searchOpts, identityTierOpts, degraded } = req;
+export async function runLexicalArms(req: HybridRequest, earlyModality: ModalityMode): Promise<LexicalArms> {
+ const { engine, query, opts, searchOpts, identityTierOpts, degraded } = req;
// Run keyword search (always available, no API key needed).
//
// v0.36 cross-modal (D9): skip keyword for 'image'-only modality. Image
@@ -36,17 +52,6 @@ export async function runLexicalArms(req: HybridRequest): Promise<LexicalArms> {
// would also surface every text chunk containing the query phrase —
// not what an image-intent query asked for. Image vector search is the
// canonical channel for image-modality queries.
- //
- // We classify modality early (it's also computed after for the modality
- // branch). The classification is pure regex via classifyQuery; running it
- // here is cheap.
- // An inferred image/both modality on a brain with no image embeddings is
- // text: the image arm has nothing to search and would only fail open (and
- // 'image' would drop the keyword arm). Later stages read the same suggestion.
- if (!(opts?.crossModal && opts.crossModal !== 'auto') && (suggestions.suggestedModality ?? 'text') !== 'text' && !await brainHasImageVectors(engine)) suggestions.suggestedModality = 'text';
- const earlyModality = (opts?.crossModal && opts.crossModal !== 'auto')
- ? opts.crossModal
- : (suggestions.suggestedModality ?? 'text');
// D1 fix (fix/title-retrieval-arm): page-grain title candidate arm,
// fetched CONCURRENTLY with the keyword arm (Reviewer F7 — independent
// engine queries). The chunk FTS vector never includes the page title, so
@@ -250,6 +255,49 @@ export async function resolveModalityAndQueries(req: HybridRequest) {
return { effectiveModality, unifiedRouting, queries };
}
+/** The vector side in flight: its own timer branch and degraded stamps, merged back by joinVectorSide. */
+export interface VectorSide {
+ work: Promise<Awaited<ReturnType<typeof resolveModalityAndQueries>> & VectorArmsResult>;
+ timer: StageTimer;
+ req: HybridRequest;
+}
+
+/**
+ * Start modality, expansion and the vector arms now, alongside the lexical and
+ * relational arms. The side reads nothing they produce; it stamps its own
+ * degraded list (and vector-pool sink) so the merge keeps the sequential order.
+ */
+export function startVectorSide(req: HybridRequest, multimodalProviderProbe: string): VectorSide {
+ const timer = req.timer.branch();
+ const degraded: HybridRequest['degraded'] = [];
+ const side: HybridRequest = { ...req, timer, degraded, searchOpts: { ...req.searchOpts, onVectorPoolMeta: vectorPoolMetaSink(req, degraded) } };
+ const work = (async () => {
+ const modality = await resolveModalityAndQueries(side);
+ return { ...modality, ...await runVectorArms(side, { ...modality, multimodalProviderProbe }) };
+ })();
+ return { work, timer, req: side };
+}
+
+/** Lexical then relational arms on the critical path; a failure waits for the vector side to settle before it is rethrown. */
+export async function runLexicalAndRelational(req: HybridRequest, earlyModality: ModalityMode, vectorSide: VectorSide | null) {
+ try {
+ const lexical = await req.timer.stage('lexical', () => runLexicalArms(req, earlyModality));
+ const relationalList = await req.timer.stage('relational', () => buildRelationalList(req));
+ return { lexical, relationalList };
+ } catch (err) {
+ if (vectorSide) await Promise.allSettled([vectorSide.work]);
+ throw err;
+ }
+}
+
+/** Wait for the vector side, then append its degraded stamps and expansion flag after the lexical ones. */
+export async function joinVectorSide(req: HybridRequest, side: VectorSide): Promise<Awaited<VectorSide['work']>> {
+ const result = await req.timer.join(side.timer, side.work);
+ for (const d of side.req.degraded) pushDegraded(req.degraded, d.stage, d.reason);
+ req.expansionApplied = side.req.expansionApplied;
+ return result;
+}
+
export interface VectorArmsResult {
vectorArms: VectorArm[];
queryEmbedding: Float32Array | null;
diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.ts
index 9c6cdf27f8..34c8871637 100644
--- a/src/core/search/hybrid/request.ts
+++ b/src/core/search/hybrid/request.ts
@@ -33,6 +33,21 @@ import { applySearchIntent } from '../decide-retrieval.ts';
import { liftModeCut } from '../page-rank-cut.ts';
import { type StageTimer, UNTIMED } from '../stage-timings.ts';
+/**
+ * searchVector's bounded-escalation exhaustion signal: stamped on `degraded`,
+ * accumulated on `req` (the vector side passes its own stamp list).
+ */
+export function vectorPoolMetaSink(req: HybridRequest, degraded: DegradedStageEntry[]): NonNullable<SearchOpts['onVectorPoolMeta']> {
+ return (m) => {
+ if (!m.underfilled) return;
+ pushDegraded(degraded, 'vector_candidates_incomplete', m.reason === 'deadline' ? 'timeout' : m.reason ?? 'candidate_budget');
+ if (!req.vectorPoolUnderfill || m.escalations >= req.vectorPoolUnderfill.escalations) {
+ const { underfilled, ...detail } = m;
+ req.vectorPoolUnderfill = { ...detail, incomplete: true };
+ }
+ };
+}
+
/**
* Everything the stages read, resolved once at hybridSearch entry, plus the
* per-request accumulators they write (vectorPoolUnderfill, expansionApplied,
@@ -275,14 +290,7 @@ export async function resolveHybridRequest(
// ACCUMULATES across vector calls (adversarial F8): expansion runs N
// sub-queries through this one opts object — last-write-wins would
// under-report multi-query exhaustion. Keep the max-escalations event.
- onVectorPoolMeta: (m) => {
- if (!m.underfilled) return;
- pushDegraded(degraded, 'vector_candidates_incomplete', m.reason === 'deadline' ? 'timeout' : m.reason ?? 'candidate_budget');
- if (!req.vectorPoolUnderfill || m.escalations >= req.vectorPoolUnderfill.escalations) {
- const { underfilled, ...detail } = m;
- req.vectorPoolUnderfill = { ...detail, incomplete: true };
- }
- },
+ onVectorPoolMeta: (m) => vectorPoolMetaSink(req, degraded)(m),
};
// Post-arm identity injections re-apply the arms' exclude contract.
const identityTierOpts: IdentityTierOpts = {
diff --git a/src/core/search/stage-timings.ts b/src/core/search/stage-timings.ts
index 6a1344288f..131109f675 100644
--- a/src/core/search/stage-timings.ts
+++ b/src/core/search/stage-timings.ts
@@ -10,7 +10,11 @@
* `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
+ * per label in `overlapped_ms` and never added to a stage. A branch (`branch()`)
+ * runs whole stages alongside the critical path (the vector side next to the
+ * lexical arms): until the request `join`s it, its stage time is reported in
+ * `overlapped_ms` under the stage's name; from the join on, the wait is booked
+ * to whichever stage the branch is in. `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`.
*
@@ -32,12 +36,18 @@ export interface SearchTimingsMeta {
export interface StageTimer {
stage<T>(stage: SearchStage, work: () => Promise<T>): Promise<T>;
overlap<T>(label: string, work: Promise<T>): Promise<T>;
+ /** A timer for stages that run alongside the critical path until `join` waits on them. */
+ branch(): StageTimer;
+ /** Wait on work timed by `branch`: the wait is booked to the branch's current stage. */
+ join<T>(branch: StageTimer, 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,
+ branch: () => UNTIMED,
+ join: (_branch, work) => work,
};
export class SearchTimings implements StageTimer {
@@ -77,6 +87,37 @@ export class SearchTimings implements StageTimer {
return work;
}
+ branch(): StageTimer {
+ return new BranchTimer(this, this.now);
+ }
+
+ async join<T>(branch: StageTimer, work: Promise<T>): Promise<T> {
+ if (!(branch instanceof BranchTimer) || branch.parent !== this) return work;
+ const base = this.current;
+ this.switchTo(branch.attach(base) ?? base);
+ try {
+ return await work;
+ } finally {
+ branch.detach();
+ this.switchTo(base);
+ }
+ }
+
+ /** @internal BranchTimer bookkeeping. */
+ declare(stage: SearchStage): void {
+ if (!this.spent.has(stage)) this.spent.set(stage, 0);
+ }
+
+ /** @internal BranchTimer bookkeeping. */
+ follow(stage: SearchStage | null): void {
+ this.switchTo(stage);
+ }
+
+ /** @internal BranchTimer bookkeeping. */
+ bookOverlapped(label: string, ms: number): void {
+ this.overlapped.set(label, (this.overlapped.get(label) ?? 0) + ms);
+ }
+
/** Integer milliseconds; stages and `other` are apportioned so they sum to `total_ms` exactly. */
snapshot(): SearchTimingsMeta {
const at = this.now();
@@ -96,6 +137,64 @@ export class SearchTimings implements StageTimer {
}
}
+/** Stages run off the critical path: overlapped until joined, then booked to the parent's stages. */
+class BranchTimer implements StageTimer {
+ private current: SearchStage | null = null;
+ private since: number;
+ private joinedBase: SearchStage | null | undefined;
+
+ constructor(readonly parent: SearchTimings, private readonly now: () => number) {
+ this.since = now();
+ }
+
+ private enter(stage: SearchStage | null): SearchStage | null {
+ const at = this.now();
+ if (this.joinedBase === undefined && this.current) this.parent.bookOverlapped(this.current, at - this.since);
+ this.since = at;
+ const previous = this.current;
+ this.current = stage;
+ if (this.joinedBase !== undefined) this.parent.follow(stage ?? this.joinedBase);
+ return previous;
+ }
+
+ async stage<T>(stage: SearchStage, work: () => Promise<T>): Promise<T> {
+ this.parent.declare(stage);
+ const previous = this.enter(stage);
+ try {
+ return await work();
+ } finally {
+ this.enter(previous);
+ }
+ }
+
+ overlap<T>(label: string, work: Promise<T>): Promise<T> {
+ return this.parent.overlap(label, work);
+ }
+
+ /** A branch's own branches are untimed. */
+ branch(): StageTimer {
+ return UNTIMED;
+ }
+
+ join<T>(_branch: StageTimer, work: Promise<T>): Promise<T> {
+ return work;
+ }
+
+ /** The parent starts waiting: book the overlapped part so far and hand the clock the current stage. */
+ attach(base: SearchStage | null): SearchStage | null {
+ const at = this.now();
+ if (this.current) this.parent.bookOverlapped(this.current, at - this.since);
+ this.since = at;
+ this.joinedBase = base;
+ return this.current;
+ }
+
+ detach(): void {
+ this.joinedBase = undefined;
+ this.since = this.now();
+ }
+}
+
/** 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));
diff --git a/test/search/stage-timings-ops.test.ts b/test/search/stage-timings-ops.test.ts
index 2d50e7a660..f47504b922 100644
--- a/test/search/stage-timings-ops.test.ts
+++ b/test/search/stage-timings-ops.test.ts
@@ -56,6 +56,14 @@ function withEmbeddings(): void {
configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'stub-not-a-key' } });
}
+const stubTransport = (async (input: { values: string[] }) => ({ embeddings: input.values.map(stubVector) })) as never;
+
+/** Swap the embed transport for one call; restore the stub after. */
+async function withEmbedTransport<T>(transport: (input: { values: string[] }) => Promise<{ embeddings: number[][] }>, fn: () => Promise<T>): Promise<T> {
+ __setEmbedTransportForTests(transport as never);
+ try { return await fn(); } finally { __setEmbedTransportForTests(stubTransport); }
+}
+
/** 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);
@@ -70,7 +78,7 @@ beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
- __setEmbedTransportForTests((async (input: { values: string[] }) => ({ embeddings: input.values.map(stubVector) })) as never);
+ __setEmbedTransportForTests(stubTransport);
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'],
@@ -96,7 +104,7 @@ describe('timings ride every search and query response', () => {
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', 'keyword_count', 'title_arm']);
+ expect(Object.keys(t.overlapped_ms ?? {}).sort()).toEqual(['embed', 'keyword_arm', 'keyword_count', 'title_arm', 'vector']);
});
test('query adds the facts arm and expansion stages', async () => {
@@ -151,6 +159,39 @@ describe('critical-path accounting', () => {
expect(wall).toBeLessThan(2 * DELAY + t.total_ms - t.stages_ms.lexical!);
});
+ test('the query embed runs alongside the lexical arms: one delay of wall time, not two', async () => {
+ withEmbeddings();
+ const DELAY = 300;
+ const slowEmbed = async (input: { values: string[] }) => {
+ await new Promise(resolve => setTimeout(resolve, DELAY));
+ return { embeddings: input.values.map(stubVector) };
+ };
+ const t = expectTimings((await withEmbedTransport(slowEmbed, () => withSlowLexicalArms(DELAY, () => run('search', { query: 'widget pricing' })))).timings);
+ expect(t.stages_ms.lexical).toBeGreaterThanOrEqual(DELAY - 5);
+ expect(t.overlapped_ms!.embed).toBeGreaterThanOrEqual(DELAY - 50);
+ expect(t.stages_ms.embed! + t.overlapped_ms!.embed).toBeGreaterThanOrEqual(DELAY - 5);
+ expect(t.total_ms).toBeLessThan(2 * DELAY - 50);
+ });
+
+ test('degraded stamps keep the sequential order when the vector side fails first', async () => {
+ withEmbeddings();
+ const keyword = engine.searchKeyword.bind(engine);
+ engine.searchKeyword = (async () => {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ throw new Error('keyword arm down (simulated)');
+ }) as typeof engine.searchKeyword;
+ try {
+ const failingEmbed = async () => { throw new Error('embed provider down (simulated)'); };
+ const { meta } = await withEmbedTransport(failingEmbed, () => run('search', { query: 'widget pricing' }));
+ const stages = meta.degraded.map((d: { stage: string }) => d.stage);
+ expect(stages).toContain('keyword_arm_failed');
+ expect(stages).toContain('embed_unavailable');
+ expect(stages.indexOf('keyword_arm_failed')).toBeLessThan(stages.indexOf('embed_unavailable'));
+ } finally {
+ engine.searchKeyword = keyword;
+ }
+ });
+
test("an alias fan-out's keyword search is booked under alias_fanout, outside lexical and the arms", async () => {
withEmbeddings();
const DELAY = 150;
diff --git a/test/search/stage-timings.test.ts b/test/search/stage-timings.test.ts
index 57d21d6c45..76a3472f3d 100644
--- a/test/search/stage-timings.test.ts
+++ b/test/search/stage-timings.test.ts
@@ -128,6 +128,74 @@ describe('timing never serializes execution', () => {
expect(s.total_ms).toBeLessThan(s.overlapped_ms!.keyword_arm + s.overlapped_ms!.title_arm);
});
+ test('a branch runs alongside: overlapped until joined, then the wait is booked to its current stage', async () => {
+ const c = manualClock();
+ const t = new SearchTimings(c.now);
+ const b = t.branch();
+ const gates = [0, 1, 2].map(() => { let open!: () => void; const p = new Promise<void>(r => { open = r; }); return { p, open }; });
+ const side = (async () => {
+ await b.stage('expansion', () => gates[0].p);
+ await b.stage('embed', () => gates[1].p);
+ await b.stage('vector', () => gates[2].p);
+ return 'side';
+ })();
+ await t.stage('lexical', async () => {
+ c.tick(30);
+ gates[0].open();
+ await sleep(0);
+ c.tick(10);
+ });
+ const joined = t.join(b, side);
+ c.tick(15);
+ gates[1].open();
+ await sleep(0);
+ c.tick(8);
+ gates[2].open();
+ expect(await joined).toBe('side');
+ await t.stage('fuse', async () => { c.tick(2); });
+ const s = t.snapshot();
+ expect(s.overlapped_ms).toEqual({ expansion: 30, embed: 10 });
+ expect(s.stages_ms).toEqual({ expansion: 0, embed: 15, vector: 8, lexical: 40, fuse: 2 });
+ expect(s.other_ms).toBe(0);
+ expect(s.total_ms).toBe(65);
+ });
+
+ test('a branch that finished before the join books nothing to the critical path but keeps its stage keys', async () => {
+ const c = manualClock();
+ const t = new SearchTimings(c.now);
+ const b = t.branch();
+ const side = b.stage('embed', async () => { c.tick(12); return 1; });
+ await side;
+ await t.stage('lexical', async () => { c.tick(30); });
+ await t.join(b, side);
+ const s = t.snapshot();
+ expect(s.stages_ms).toEqual({ embed: 0, lexical: 30 });
+ expect(s.overlapped_ms).toEqual({ embed: 12 });
+ expect(s.total_ms).toBe(42);
+ expect(s.other_ms).toBe(12);
+ });
+
+ test('a join inside a stage hands the clock back to that stage, also between branch stages', async () => {
+ const c = manualClock();
+ const t = new SearchTimings(c.now);
+ await t.stage('alias_fanout', async () => {
+ const b = t.branch();
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const side = (async () => { await gate; c.tick(3); await b.stage('embed', async () => { c.tick(9); }); })();
+ const joined = t.join(b, side);
+ release();
+ await joined;
+ c.tick(1);
+ });
+ expect(t.snapshot().stages_ms).toEqual({ alias_fanout: 4, embed: 9 });
+ });
+
+ test("the untimed timer's branch and join pass work straight through", async () => {
+ const b = UNTIMED.branch();
+ expect(await UNTIMED.join(b, b.stage('embed', async () => 7))).toBe(7);
+ });
+
test('the untimed timer passes work straight through', async () => {
const p = Promise.resolve(7);
expect(UNTIMED.overlap('keyword_arm', p)).toBe(p);