Skip to content

Remove the per-result work from the search path - #2452

Merged
malibio merged 2 commits into
mainfrom
issue-2399-search-per-result-cost
Sep 8, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2399-search-per-result-cost

Conversation

@malibio

@malibio malibio commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator

Closes #2399.

Search had per-result work — one query per result, executed serially — in four places. This instruments the path first, then removes them.

Instrumentation (done first, deliberately)

A 5-second operation previously emitted one opaque log line. Now:

  • semantic_search emits a structured per-phase profile: embed_ms, knn_ms, bm25_ms, search_ms, tier3_hydrate_ms, total_ms, plus tier counts and limit. KNN and BM25 are timed inside the tokio::join!, so each leg is attributable even though they overlap in wall clock (they do not sum to search_ms, and the comment says so).
  • search_embeddings emits its own knn_ms / score_ms / hydrate_ms split with candidate and k counts.

Both use tracing, as the codebase does.

Fixes

  1. search_embeddings hydrated every surviving candidate with its own get_node. It now ranks and truncates to limit first, then fetches the survivors in one batched IN (...) query. Ordering matters independently of batching: KNN over-fetches by EMBEDDING_KNN_OVERFETCH, and callers inflate limit further for their own post-filters, so the old order hydrated rows that ranking immediately discarded.
  2. search_embeddings_by_node_type had the same loop; same fix. Its under-limit debug signal is now counted before truncation so it still reports how many candidates actually cleared the threshold.
  3. The tier-3 BM25-only branch fetched each root individually. Batched. This also stops swallowing fetch errors, which the old if let Ok(Some(..)) silently discarded.
  4. The gRPC SearchNodes handler re-read every result from the store by id, discarding the nodes search had already fetched and ranked. SearchSemanticOutput now carries them as typed matched_nodes (same order, same results as nodes — both derive from filtered_results after all re-ranking) and the handler maps those straight onto the wire type.

Measurements

Release build (cargo test --release), seeded 32,000-node corpus matching the reproduction size, best of 3 per limit. Seeding: 32k text nodes, each with a paragraph of body content and one 768-dim embedding chunk, inserted through the normal create_node + upsert_embeddings store API into a temp SQLite database.

--limit before after
1 27.57 ms 27.31 ms
2 27.55 ms 27.80 ms
5 28.00 ms 27.96 ms
10 28.51 ms 28.81 ms
20 30.16 ms 30.18 ms
50 36.71 ms 36.27 ms

Cost is dominated by the fixed ~27 ms KNN scan; the per-result slope is ~0.18 ms/result at limit 50 and within noise at limit 20.

Finding that differs from the issue's hypothesis

The ~250 ms/result slope did not reproduce at this layer, and the per-result DB work is not large enough to explain it. Measured individually on the 32k corpus (release):

  • serial per-result get_node re-fetch: 0.007 ms per result (0.14 ms at limit 20)
  • get_related_nodes per result: 0.01 ms each — and graph_boost / include_edges both default false
  • get_subtree_data per result: 6.4 ms each, by far the largest per-result cost, but capped at include_markdown (default 1, max 5), and the CLI path passes include_markdown: 0, so it cannot produce a slope that scales out to limit 50

So the loops removed here are the right shape — work that grows with result count rather than corpus size, which is exactly how a per-result slope arises — and removing them is correct on its own merits. But they do not by themselves account for the reported 250 ms/result. The remaining candidate is above the store layer (embedding-model or daemon-side behavior on the live install, which this harness does not exercise). Reporting that plainly rather than forcing the fix to match the hypothesis; the per-phase profile is what makes the remainder attributable next time instead of requiring a fresh investigation.

Regression test

packages/core/tests/search_result_scaling_test.rs, 4 tests over a 2,000-node seeded corpus:

  • limit 20 within 4x limit 1 plus a 50 ms floor. Real ratio is ~1.15x, so ~3.5x headroom. The floor stops a sub-millisecond limit-1 baseline — where scheduler noise is a large multiple of a small number — from making the ratio meaningless. Deliberately loose: sized to catch a per-result N+1 returning, not to police percent-level drift on a loaded local gate with no CI.
  • the full 1/2/5/10/20/50 sweep under 2 s (measured well under 200 ms release, under 1 s debug).
  • hydration bounded by limit, not the candidate set, with results rank-ordered.
  • every returned result carries its node — guarding the handler's new reliance on that, since it no longer re-fetches and would otherwise silently drop a row where the old code logged a warning.

Tests pass in both debug and release.

Verification

  • bun run test:all — 233+4 frontend test files, 4955 tests, 76 Rust suites, zero failures (identical to the pre-change baseline).
  • bun run quality:fix — clean.

No CLI surface, flag, default, or output shape changed, so no skill-guidance update is required.

🤖 Generated with Claude Code

https://claude.ai/code/session_01KwcVcLdvBUjSkUFmtFNiTY

malibio and others added 2 commits September 8, 2026 09:56
Instrument the search path per phase, then remove the query-per-result
work the instrumentation exposed.

Instrumentation: `semantic_search` now emits a structured per-phase
profile (embed / knn / bm25 / tier3 hydration / total) instead of one
opaque duration, and `search_embeddings` emits its own knn / score /
hydrate split. KNN and BM25 are timed inside the `tokio::join!` so each
leg is attributable even though they overlap in wall clock.

Fixes, all the same shape — one query per result, executed serially:

- `search_embeddings` hydrated every surviving candidate with its own
  `get_node`. It now ranks and truncates to `limit` FIRST, then fetches
  the survivors in one batched `IN (...)` query. KNN over-fetches and
  callers inflate `limit` further for their own post-filters, so the old
  order also fetched node data that ranking immediately discarded.
- `search_embeddings_by_node_type` had the same loop; same fix. Its
  under-limit debug signal is now counted before truncation, so it still
  reports how many candidates actually cleared the threshold.
- The tier-3 BM25-only branch fetched each root individually. Batched.
  This also stops swallowing fetch errors, which the old `if let Ok(..)`
  silently discarded.
- The gRPC search handler re-read every result from the store by id,
  discarding the nodes search had already fetched. `SearchSemanticOutput`
  now carries them as typed `matched_nodes` and the handler maps those
  straight onto the wire type.

Measured on a release build over a 32k-node seeded corpus, best of 3
(limit: before -> after): 1: 27.6 -> 27.3ms, 5: 28.0 -> 28.0ms,
20: 30.2 -> 30.2ms, 50: 36.7 -> 36.3ms. Cost is dominated by the fixed
KNN scan with a near-zero per-result slope.

Note the reported ~250ms/result was NOT reproducible at this layer: the
per-result DB work measures in microseconds, so these are the right shape
to fix but do not by themselves account for the reported figure. The
per-phase profile is what makes the remaining cost attributable.

Regression tests seed a 2,000-node corpus and assert search at limit 20
stays within 4x limit 1 plus a 50ms floor, that the full 1/2/5/10/20/50
sweep stays under 2s, that hydration is bounded by `limit` rather than the
candidate set, and that every returned result carries its node — the last
guarding the handler's new reliance on that.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KwcVcLdvBUjSkUFmtFNiTY
The 4x-plus-50ms budget could not catch the regression its own failure
message describes. Reinstating the removed N+1 costs ~0.007ms/result —
~0.14ms at limit 20, some 350x inside the 50ms floor alone — so the test
passed green on exactly the change it existed to catch. The sweep budget
had the same problem an order of magnitude over. Both are gone;
`hydration_is_bounded_by_limit_not_candidates` pins the property
structurally instead, which is what actually holds.

The hydration guard claimed to cover a drop path it never reached: it
asserts at the store, while results are discarded a layer above by the
filter_map in `semantic_search_nodes`. Asserting past that needs an
initialized NLP engine, which this crate's tests deliberately avoid, so
the test keeps its real scope and now says so rather than overclaiming.
Note this also means the drop risk is smaller than the PR body stated —
the old handler could only re-fetch ids that had already survived that
filter.

Removed a fifth instance of the per-result fetch, in the SearchSemantic
RPC the local-agent search tool uses. It also swallowed errors with
`if let Ok(Some(..))`, silently shortening the response; an unhydrated
result is now an error, since the nodes arrive already hydrated.

Extracted the scoring-and-rank duplicated between the two search paths.

The reported slope remains unexplained — filed #2455 with the
measurements, what the harness does not exercise, and the blocking
`generate_embedding` call on the async runtime as the strongest lead.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KwcVcLdvBUjSkUFmtFNiTY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Semantic search costs ~250ms per result returned: 0.3s at limit 1, 5s at limit 20

1 participant