Repository navigation
Remove the per-result work from the search path - #2452
Merged
Merged
Conversation
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
6 tasks done
This was referenced Sep 8, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_searchemits a structured per-phase profile:embed_ms,knn_ms,bm25_ms,search_ms,tier3_hydrate_ms,total_ms, plus tier counts andlimit. KNN and BM25 are timed inside thetokio::join!, so each leg is attributable even though they overlap in wall clock (they do not sum tosearch_ms, and the comment says so).search_embeddingsemits its ownknn_ms/score_ms/hydrate_mssplit with candidate andkcounts.Both use
tracing, as the codebase does.Fixes
search_embeddingshydrated every surviving candidate with its ownget_node. It now ranks and truncates tolimitfirst, then fetches the survivors in one batchedIN (...)query. Ordering matters independently of batching: KNN over-fetches byEMBEDDING_KNN_OVERFETCH, and callers inflatelimitfurther for their own post-filters, so the old order hydrated rows that ranking immediately discarded.search_embeddings_by_node_typehad 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.if let Ok(Some(..))silently discarded.SearchNodeshandler re-read every result from the store by id, discarding the nodes search had already fetched and ranked.SearchSemanticOutputnow carries them as typedmatched_nodes(same order, same results asnodes— both derive fromfiltered_resultsafter 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: 32ktextnodes, each with a paragraph of body content and one 768-dim embedding chunk, inserted through the normalcreate_node+upsert_embeddingsstore API into a temp SQLite database.--limitCost 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):
get_nodere-fetch: 0.007 ms per result (0.14 ms at limit 20)get_related_nodesper result: 0.01 ms each — andgraph_boost/include_edgesboth default falseget_subtree_dataper result: 6.4 ms each, by far the largest per-result cost, but capped atinclude_markdown(default 1, max 5), and the CLI path passesinclude_markdown: 0, so it cannot produce a slope that scales out to limit 50So 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, not the candidate set, with results rank-ordered.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