Repository navigation
feat(research): replace rerank calls in depth exploration with cosine similarity scoring - #356
Conversation
6f19385 to
f45a1bd
Compare
- Embed query once before pagination loop instead of per-page (eliminates N embed calls per symbol) - Move cosine scoring to a single post-pagination bulk call instead of per-page calls (N pages → 1 round-trip per symbol) - Add consecutive dry-pages early exit (3 consecutive fully-excluded pages stops pagination early) to avoid exhausting max_pages on covered symbols - Reduce max_pages from 20 to 10, halving the worst-case scan depth - Fix test_keeps_coverage_chunk_if_higher_score to use similarity field (matches score_field used by _merge_coverage after PR chunkhound#356) - Remove unused sync get_chunk_similarities method from DuckDBProvider - Remove redundant search_service assignment at skip_rerank path Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Embed query once before pagination loop instead of per-page (eliminates N embed calls per symbol) - Move cosine scoring to a single post-pagination bulk call instead of per-page calls (N pages → 1 round-trip per symbol) - Add consecutive dry-pages early exit (3 consecutive fully-excluded pages stops pagination early) to avoid exhausting max_pages on covered symbols - Reduce max_pages from 20 to 10, halving the worst-case scan depth - Fix test_keeps_coverage_chunk_if_higher_score to use similarity field (matches score_field used by _merge_coverage after PR chunkhound#356) - Remove unused sync get_chunk_similarities method from DuckDBProvider - Remove redundant search_service assignment at skip_rerank path Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…similarity scoring Phase 1.5 depth exploration previously fired N concurrent HTTP rerank calls (one per exploration query), causing a thundering herd on the reranking server. Replaces Step 7 reranking with a single batch DB query using array_cosine_similarity() when skip_rerank=True. Regex-only chunks (which carry no score) are scored against stored embeddings; semantic chunks already carry similarity from HNSW search. All chunks sort by the uniform similarity field. Also fixes _select_top_files to prefer similarity over rerank_score so file ranking survives if Phase 1 reranking is removed in the future. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…aphore branch Restores timing/progress infrastructure lost when the branch was cut before the timing PR landed on main: - Restore ProgressEmitterMixin, perf_counter timing, and _emit_event calls in DepthExplorationService (steps 1.5.1–1.5.6) and GapDetectionService - Restore progress_mixin.py (was missing entirely — only .pyc existed) - Restore wide_coverage_strategy.py progress forwarding to sub-services - Restore factory.py progress=progress forwarding to WideCoverageStrategy - Restore pluggable_research_service.py to mixin-based version from main - Restore gap_step and fact_extraction symbols in tree_progress.py New additions: - Add search_rerank (⚖️) symbol and timing event to unified_search Step 7: "Cosine-scored N chunks (Xs)" for skip_rerank=True path, "Reranked N chunks (Xs)" for rerank path - Wire emit_event_callback into depth exploration and gap detection unified_search calls so Step 7 timing is visible in terminal tree - Fix _global_dedup and _merge_coverage in DepthExplorationService to use score_field="similarity" (was "rerank_score", causing first-seen-wins) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… layer Implements Section 9 of the deferred-reranking pitch: regex search now returns a similarity score at every call site instead of unordered results. - search_service.search_regex_async accepts query: str | None = None; when set, embeds the query and batch-scores all returned chunks via array_cosine_similarity before result enhancement so similarity_percentage is populated correctly - diff_aware_search_service forwards query through both the protocol stub and the concrete implementation - unified_search.search_by_symbols accepts and forwards query to search_regex_async; the skip_rerank branch is simplified to a sort since regex chunks arrive pre-scored from the service layer - mcp_server/tools.py passes query=query to search_regex_async so MCP regex searches are scored by relevance - cli search.py removes the if-not-is_regex guard so similarity is shown whenever the field is present, regardless of search type - fix test_depth_exploration fixtures to use similarity instead of rerank_score to match the scoring field used by depth exploration since commit fd2d324 Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… is provided The sync path accepted a `query` parameter but silently ignored it. Mirror the async path: when called outside an event loop, spin up a temporary loop via asyncio.run() to embed the query and batch-score regex chunks via get_chunk_similarities_async. When called from inside an existing event loop, log a debug message and skip scoring (callers in that context should use search_regex_async). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… 1.5.3 Firing all 10 exploration queries simultaneously caused a thundering herd on the reranker — 6+ concurrent rerank requests overwhelmed pdc-llm-srv1, producing batch timeouts (30s each) that dominated Step 1.5.3 runtime. Adds asyncio.Semaphore(3) around the asyncio.gather in _execute_exploration_queries so at most 3 unified_search calls (and thus 3 rerank requests) run concurrently. Also adds per-call rerank timing (logger.warning) in unified_search.py to make reranker latency visible alongside the existing step-level timings. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Embed query once before pagination loop instead of per-page (eliminates N embed calls per symbol) - Move cosine scoring to a single post-pagination bulk call instead of per-page calls (N pages → 1 round-trip per symbol) - Add consecutive dry-pages early exit (3 consecutive fully-excluded pages stops pagination early) to avoid exhausting max_pages on covered symbols - Reduce max_pages from 20 to 10, halving the worst-case scan depth - Fix test_keeps_coverage_chunk_if_higher_score to use similarity field (matches score_field used by _merge_coverage after PR chunkhound#356) - Remove unused sync get_chunk_similarities method from DuckDBProvider - Remove redundant search_service assignment at skip_rerank path Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Empirical comparison on the same query shows max_symbols=3 is both faster and produces higher-quality output than max_symbols=5: - Runtime: −27% (425s → 311s), BFS Step 5: −53% (3×83s → 1×15s) - Quality: 75 files / 88 chunks vs 60 files / 64 chunks; avoids pulling in large .properties noise files via common-symbol regex hits Symbols 4-5 tend to be parameter/type names that are high-frequency across the codebase (e.g. "timeout", "port") and produce noisy regex matches that consume synthesis token budget without adding relevant content. Also revert max_pages 10→20: the reduction didn't improve wall clock because concurrent BFS search count compensates, and it risks missing deeper regex results for genuinely rare symbols. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ations Depth exploration ran each of its 10 serial iterations independently, passing only the current iteration's ~30 semantic chunk IDs as exclusions to the regex pagination loop. Later iterations would re-scan symbols already found in earlier iterations, wasting DB pages before the consecutive-dry-pages early exit could fire. Fix: maintain a global_seen set in _execute_exploration_queries that accumulates returned chunk IDs after each iteration. Pass it to unified_search via a new exclude_ids parameter, which merges it with the per-call semantic exclusions before search_by_symbols runs. Measured on "explain matlab L2 launch sequence" (v2 wide_coverage): - Phase 1.5 Step 5 total: 224s → 178s (−21%) - Phase 1.5 wall clock: 353s → 298s (−55s) - Phase 2 gap detection: 113s → 82s (−31s, fewer gaps due to better coverage) - Grand total: 601s → 550s (−52s, −8.6%) - Output: 67 files cited vs 56 (more unique coverage) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…tion iteration Per-file yield tracking: if a depth exploration query returns 0 chunks after threshold filtering, all remaining queries for that file are skipped. With 2 queries per file, this means a dry first query saves one full iteration (~28s: ~9s semantic + ~19s regex) per saturated file. The optimization is meaningful only in combination with global_seen (previous commit): without it, re-found chunks inflated result counts and masked dry iterations. global_seen makes the zero-yield signal accurate; this exit acts on it. max_consecutive_dry_per_file = 1 is conservative — one dry query per file is enough to conclude that file's remaining angles are covered. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Gap fills were launched via asyncio.gather, which serializes on the single DuckDB executor thread. With N concurrent fills, each fill's Step 5 timer spans the entire DB queue backlog (all N searches' pages interleaved), ballooning from ~20s per fill to 68-75s per fill with N=4. Measured in Run E: 4 concurrent fills → Step 5 per fill = 68-75s, total Phase 2 = 163s. Serial execution caps each fill at its true cost (~20-30s), bounding Phase 2 to N × 30s rather than 75s regardless of N. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The exit checked `if not result` on execute_single_query's output, which includes semantic chunks after threshold filtering. Since depth queries target files that already have Phase 1 coverage, semantic alone keeps results non-empty even when regex finds nothing — the condition never evaluated to True across any observed run. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Gap cluster unification was sequential — N multi-gap clusters × ~6s per LLM call. With a larger corpus (700+ chunks → 4 shards → 41 candidates → 28 groups), this took 64s. Since Step 2.5 is pure LLM I/O with no DB access, all cluster unification coroutines can run concurrently without DuckDB thread contention. Measured: 64.6s → 10.4s (-54s) with 28 parallel unification calls. Unlike Step 2.7 (gap fills, serialized in 3f1d329 to avoid DuckDB contention), Step 2.5 never touches the database — safe to gather. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
9085cfd to
22dde6e
Compare
Move Steps 2/3+4/5 timing from logger.warning into the duration= kwarg on existing emit_event calls (search_semantic, extract_symbols_complete, search_regex_complete) so timing is always visible in the progress tree without spamming the warning log level. Drop Step 6 timer (trivial dict→list, no diagnostic value) and Step 4 timer (list slice). Downgrade per-query Step 7 rerank timers to logger.debug — the final search_rerank emit already carries total duration. Fix inaccurate skip_rerank comment: scoring happens via get_chunk_similarities_async inside search_by_symbols, not search_regex_async. Remove extra blank line between class methods in duckdb_provider.py (PEP 8). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… skip_rerank migration Phase 1.5 now uses skip_rerank=True, so its chunks carry only a similarity field; rerank_score is never set. The downstream elbow filter in wide_coverage_strategy was still using score_key="rerank_score", treating every Phase 1.5 chunk as 0.0 and discarding them whenever Phase 1/2 chunks formed an elbow above 0.0. Fix: - get_unified_score: add similarity as a fallback between rerank_score and score - wide_coverage_strategy: switch to score_key=None (unified scoring) so all three chunk sources (Phase 1 rerank_score, Phase 1.5 similarity, Phase 2 rerank_score) are ranked on the same scale before the elbow cut Also remove the dead asyncio.get_running_loop()/asyncio.run() scoring block from sync search_regex — no caller passes query= to that path; cosine scoring for regex results is handled exclusively by search_regex_async. Clarify the serialization comment in depth_exploration to name the actual cause: DuckDB executor thread contention, not timing isolation. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Remove dead `query` param from sync search_regex (accepted but never
embedded or scored; cosine scoring requires async, only async path
implements it)
- Broaden global_seen in depth exploration to include all found chunks
before threshold filtering, not just kept ones; below-threshold regex
finds now excluded from later iterations' pagination
- Fix misleading Step 7 skip_rerank event label ("Cosine-scored" →
"Ranked by cosine similarity"; scoring happens in search_by_symbols)
- Document search_by_symbols query/exclude_ids params in docstring
- Update chunk_dedup module docstring to reflect parameterised score_field
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- chunk_dedup: add score_fn parameter to deduplicate_chunks and merge_chunk_lists so callers can supply a unified scoring function instead of a single field name — needed when base and new chunks come from different phases and carry scores in different fields - depth_exploration: _merge_coverage now passes score_fn=get_unified_score so Phase 1 regex-only chunks (rerank_score, no similarity) are no longer scored as 0.0 against Phase 1.5 chunks (similarity only), preventing high-quality Phase 1 chunks from being silently evicted - depth_exploration: _select_top_files uses get_unified_score for consistent rerank_score > similarity > score priority across all chunk types in the file ranking - gap_detection: rename _fill_gaps_parallel → _fill_gaps_serial to match its serial implementation - gap_detection: add return_exceptions=True to asyncio.gather in _unify_gap_clusters with per-result filtering for per-cluster resilience (matches the old for-loop behaviour) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… startup timeout to 60s The daemon_server_import phase was timing out on Windows + Python 3.14 CI because tools.py (and its full research-service transitive closure) was imported eagerly via three paths: mcp_server/__init__.py, mcp_server/base.py, and daemon/server.py. This saved ~3.4s locally (8.5s → 5.1s); on slow Windows CI the gain is proportionally larger. Also raises _STARTUP_TIMEOUT from 30s to 60s (overridable via CHUNKHOUND_DAEMON_STARTUP_TIMEOUT) to handle remaining import overhead on slow CI runners. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…oad refactor Commit 6910f9c moved handle_tool_call to a local import inside ChunkHoundDaemon._handle_tools_call, removing it as a module-level attribute. Two tests that patched chunkhound.daemon.server.handle_tool_call now target chunkhound.mcp_server.common.handle_tool_call instead. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
VakninAriel
left a comment
There was a problem hiding this comment.
Summary: Well-engineered performance PR that correctly identifies DuckDB serial executor contention as the root cause of ballooning Phase 1.5 latencies, fixes it with targeted serialization and bulk-scoring rewrites, and includes measured benchmarks — approve with minor comments.
Strengths:
-
Contention diagnosis is correct and the fix is targeted. Switching
_execute_exploration_queriesand_fill_gapsfromasyncio.gatherto serial loops is the right call: concurrentunified_searchcalls all queue on the single DB executor thread, so parallelism buys nothing on the async side while serialization of the queue actually speeds each call up. The reasoning in the PR description and inline comments is sound. -
Bulk post-pagination cosine scoring is a clean optimization. Embedding the query once before
search_by_symbolsand doing a singleget_chunk_similarities_asynccall after pagination completes reduces N round-trips → 1 per symbol. The SQL in_executor_get_chunk_similaritiesis straightforward (array_cosine_similarityin a single SELECT). -
deduplicate_chunks/merge_chunk_listsscore_fnparameter is a clean generalization — backward compatible, well-documented, and eliminates the inline score access duplication in both callers.
Issues:
Minor — serial_database_provider.py:229-236
The hasattr(self, "_executor_get_chunk_similarities") guard returns {} silently. Any provider without this executor will produce similarity=0.0 for all regex chunks, ranking them at the bottom without any log warning. Other guarded methods in this file at least have a logger.warning in the "not supported" path. Consider adding one here so silent degradation is diagnosable.
Minor — search_service.py:236-256 (MCP/CLI regex + query path)
search_regex_async now embeds the query on every paginated page call from the MCP tool. The embed fires unconditionally when query and results is True, even when no chunk_id integers are present. Micro-optimization: extract chunk_ids before embedding and gate on if chunk_ids:
# cleaner
if query and self._embedding_provider and results:
chunk_ids = [c["chunk_id"] for c in results if isinstance(c.get("chunk_id"), int)]
if chunk_ids:
query_vec = (await embed([query]))[0]
scores = await ...Minor — unified_search.py:974, search_service.py:237-256
The embed + chunk scoring pattern is duplicated in two places (inside search_by_symbols post-pagination and inside search_service.search_regex_async). Not blocking, but if a third call site appears this warrants a _score_chunks_by_similarity(chunks, query) helper on SearchService.
Minor — PR description vs final code
Description says "Added asyncio.Semaphore(3) around the asyncio.gather in _execute_exploration_queries, retained as safety valve." Final code fully serialized the loop — no semaphore. Describes an intermediate commit state, not the final implementation.
Reusability:
get_unified_scoreinelbow_filter.pyis the canonical score resolver; all new dedup/merge call sites correctly use it rather than inlining their own priority logic. ✓- The
_executor_get_chunk_similaritiesdispatcher naming follows the existing_executor_*convention exactly — no new patterns introduced.
Decision: APPROVE
The serialization correctness, benchmark data, and unified scoring approach are solid. The minor issues above are all non-blocking. Confirm smoke tests pass (particularly the test_mcp_tool_consistency.py patch location change for handle_tool_call) before merging.
|
@ofriw ? |
Resolved 4 conflict sites and 5 auto-merge gaps between db-portability (code hygiene, DB portability, lint fixes across 400+ files) and main (#361 config forwarding, #356 cosine similarity scoring). Conflict 1: discovery.py - _read_startup_timeout -> _resolve_startup_timeout Conflict 2: search_service.py - query param in search_regex_async Conflict 3: unified_search.py - skip_rerank, exclude_ids params Conflict 4: elbow_filter.py - get_unified_score similarity field handling Auto-merge gaps fixed: - query kwarg signature in SerialDatabaseProvider.search_regex_async - score_fn support in chunk_dedup.py - Depth exploration base_cosine search class integration - gap_detection.py scoring path unification - duckdb_provider.py type annotation boundary fix Fixes included: - query: str | None = None param added to SerialDatabaseProvider.search_regex_async - Test assertions updated: _read_startup_timeout -> _resolve_startup_timeout
Summary
This PR has grown beyond its original scope. It started as a targeted fix for the thundering-herd reranker problem in Phase 1.5, and has since accumulated a set of depth-exploration and Phase 2 gap-detection performance improvements.
Three themes across the 12 commits:
Changes by Area
Phase 1.5 — Cosine Similarity Scoring
Problem: Phase 1.5 fired all 10 exploration queries simultaneously, each triggering a concurrent HTTP rerank call. 6+ concurrent rerank requests overwhelmed the reranking server, producing 30s batch timeouts that dominated Step 1.5.3 runtime.
Fix (fd2d324, 89fb4b9, 437b3b4):
skip_rerank=Truepath replaces Step 7 rerank with a single batcharray_cosine_similarity()query against stored embeddings_select_top_filesto prefersimilarityoverrerank_scoreso file ranking survives if Phase 1 reranking is removedsearch_regexpath now also applies cosine scoring when aqueryis provided (previously silently ignored it)Thundering-herd guard (39343ec): Added
asyncio.Semaphore(3)around theasyncio.gatherin_execute_exploration_queriesso at most 3unified_searchcalls (and thus 3 rerank requests) run concurrently. Retained as a safety valve even withskip_rerank=True.Depth Exploration — Reducing Redundant Work
Global exclude_ids across iterations (db5c496):
Depth exploration ran each of its 10 serial iterations independently, passing only the current iteration's ~30 semantic chunk IDs as exclusions to regex pagination. Later iterations re-scanned symbols already found in earlier iterations, wasting DB pages before the dry-pages early exit fired.
Fix: maintain a
global_seenset in_execute_exploration_queriesthat accumulates returned chunk IDs after each iteration. Pass tounified_searchvia a newexclude_idsparameter, merged with per-call semantic exclusions beforesearch_by_symbolsruns.Measured on "explain matlab L2 launch sequence" (v2 wide_coverage):
Per-file dry exit (e5e18fa):
If a depth query returns 0 new chunks after threshold filtering, all remaining queries for that file are skipped. With 2 queries per file, one dry first query saves a full iteration (~28s: ~9s semantic + ~19s regex) per saturated file. Only meaningful in combination with
global_seen— without it, re-found chunks inflated result counts and masked true dry iterations.Regex pagination cost reduction (4fceb0c):
Tuning: max_symbols 5 → 3 (6cfbda3):
Empirical comparison showed max_symbols=3 is both faster and higher quality:
max_pages reverted 10 → 20: the reduction didn't improve wall clock (concurrent BFS search count compensates) and risks missing deeper regex results for genuinely rare symbols.
Remove dead per-file dry exit (a61aebf):
The old exit checked
if not resultonexecute_single_query's output, which includes semantic chunks after threshold filtering. Since depth queries target files that already have Phase 1 coverage, semantic alone keeps results non-empty even when regex finds nothing — the condition never evaluated to True across any observed run.Phase 2 — Gap Detection Concurrency
Step 2.5: Parallelize gap cluster unification (9085cfd):
Gap cluster unification was sequential — N multi-gap clusters × ~6s per LLM call. With a larger corpus (700+ chunks → 4 shards → 41 candidates → 28 groups), this took 64s. Since Step 2.5 is pure LLM HTTP I/O with no DB access, all cluster unification coroutines can run concurrently without DuckDB thread contention.
Measured: 64.6s → 10.4s (−54s) with 28 parallel unification calls.
Step 2.7: Serialize gap fills (3f1d329):
Gap fills were launched via
asyncio.gather, but each fill calls unified search which hits DuckDB via the single-threaded serial executor. With N concurrent fills, each fill's Step 5 timer spans the entire DB queue backlog (all N searches' pages interleaved), ballooning from ~20–30s per fill to 68–75s per fill with N=4.Measured: 4 concurrent fills → Step 5 per fill = 68–75s, total Phase 2 = 163s. Serial execution caps each fill at its true cost (~20–30s), bounding Phase 2 to N×30s rather than 75s regardless of N.
The rule: gather is safe when the coroutine is pure I/O with no DB access; serialize when the coroutine hits DuckDB's serial executor.
Runtime Impact: "explain how indexing works"
The branch is ~80s slower on this query, but the extra time is entirely in synthesis — and it's proportional to corpus size:
The branch's exploration improvements (global exclude_ids, dry exit, reduced pagination cost) are making the BFS phase more thorough — surfacing more unique files, which flows into a larger synthesis input. The exploration wall-clock is essentially the same (~60s); the corpus it produces is 83% larger. That larger corpus then drives a 2× increase in synthesis clusters and a proportional increase in synthesis LLM calls.
This is a known tradeoff: the optimizations reduce redundant DB work but also reduce premature early-exits that previously cut off coverage. The output quality improvement is real — this branch cites 34 files vs 24 on main, covering the cAST algorithm, Watchman realtime path filtering, multi-repo orphan scoping, and batch calibration that main misses entirely.
If synthesis latency is a blocker, the most effective lever is raising
max_tokens_per_cluster(currently 50k) to reduce cluster count, or adding a synthesis concurrency cap above the current 3.Output Quality Delta
Unique to this branch:
_should_admit_event()andshould_index()Unique to main:
generate_chunk_id()conceptparameter for semantic disambiguationSerialDatabaseProviderexecutor thread serialization architectureTest Plan
uv run pytest tests/test_smoke.py -v -n auto— all smoke tests pass (note:test_mcp_stdio_server_startsis a pre-existing flaky test under-n auto, unrelated to this PR)uv run pytest tests/ -v— full test suitechunkhound research "<query>"and confirm Phase 1.5 completes without reranker timeouts🤖 Generated with Claude Code