Skip to content

feat(search): stream transient git and websearch in-process - #407

Merged
HananKavitzAmat merged 98 commits into
chunkhound:mainfrom
HananKavitzAmat:unified_search
Nov 11, 2026
Merged

HananKavitzAmat merged 98 commits into
chunkhound:mainfrom
HananKavitzAmat:unified_search

Conversation

@HananKavitzAmat

@HananKavitzAmat HananKavitzAmat commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • One in-process pipeline for transient content. Git-diff search and websearch research now stream chunk batches → bounded VectorCache (XXH3 text keys namespaced by embedding-space identity, float32, LRU + last-access TTL) → top-K heap. This replaces bulk diff embedding (truncated at MAX_DIFF_CHUNKS) and the _quickresearch subprocess + tmpdir.
  • TransientSearchService overlays streaming semantic search on the existing DB search service. vector_source=both fuses equal-size, offset-independent snapshots from diff and DB HNSW, so ranking is stable across pages of the same query. Stream failures cancel sibling work and propagate.
  • Git diff streaming. stream_git_diff_fragments + StreamingDiffParser replace run_git_diff. The 30 s liveness timeout counts only time blocked on git, not embedding-consumer time. Stderr is drained concurrently with a cap. Argument-injection guards and the single-commit empty-tree retry are kept (empty-tree OID now via git hash-object -t tree, so SHA-256 repos work).
  • Websearch without disk. Fetched pages are never written to disk; research runs over an in-memory page stream with a progress-event interface. PDFs are parsed in a disposable spawned worker with a hard timeout and IPC size cap. Page bodies are capped at 20 MiB.

Why

Issue #336: large commit ranges and web pages were buffered whole, truncated (MAX_DIFF_CHUNKS), or researched in a child process via tmpdirs. Streaming keeps memory roughly constant for 500 vs 5,000 chunks, lets a chunk past the old cap win if it matches, and removes the subprocess/disk path.

User-visible changes

CLI / MCP

  • Search and research flags are unchanged.
  • --last-n N --vector-source both no longer prints Results: 10 of None; total is always numeric.
  • Large diffs no longer show a truncation warning — every chunk is considered.
  • MCP websearch schema and error mapping are unchanged (URLError → MCPError, empty results, timeout, cancel); research now runs in-process.

New environment variables (documented in site/src/pages/docs/configuration.md)

Variable Default Effect
CHUNKHOUND_VECTOR_CACHE_MAX_ENTRIES 10000 Max cached chunk vectors per process cache (git-history and web each have one). 0 disables caching; results are identical.
CHUNKHOUND_VECTOR_CACHE_TTL_SECONDS 300 Seconds since last access before a cached vector expires.
CHUNKHOUND_VECTOR_SEARCH_OVERFETCH_FACTOR 5 Candidate-pool multiplier for transient semantic search.

CHUNKHOUND_WEBSEARCH_TIMEOUT_SECONDS (default 600) changes meaning: it is now the total websearch budget. Discovery (query expansion + DDG) is capped at min(60, total/4); fetch and research share the remainder.

Pagination limits for transient search (requests outside these windows fail with a ValueError explaining the alternatives, rather than returning a misleading page)

  • vector_source=diff: offset + page_size ≤ 2000.
  • vector_source=both: offset + page_size ≤ min(max(page_size × overfetch, 50), 2000) — e.g. 50 for page_size=10. has_more/next_offset never point past this window. total is the size of the fused candidate snapshot, not the corpus size.
  • vector_source=db is unchanged and supports deep pagination.

Behavior changes worth knowing

  • Web pages are split into ≤1,200-character line windows (page:N symbols) to stay under provider embedding limits, instead of being indexed by the markdown parser. Chunk boundaries no longer follow headings.
  • Pages evicted from the 32 MiB in-process source cache are refetched on demand; if a refetched page's content changed since first read, research fails with Web source changed since first read rather than mixing two revisions.
  • Transient semantic search has a 300 s wall-clock circuit breaker covering streaming + embedding.

Removed

  • chunkhound _quickresearch hidden subcommand and its parser.
  • run_git_diff / _communicate_git_diff (callers use the streaming runner).
  • fetch_and_save, tmpdir post-processing (websearch_postprocess.py).
  • IndexingConfig.reset_user_include_exclude() (public method; only _quickresearch used it).
  • MAX_DIFF_CHUNKS truncation and its always-None plumbing.

Review fixes since the first push

  • PDF worker redirects fd 1 to stderr, so MuPDF diagnostics can no longer corrupt the MCP stdio JSON-RPC stream.
  • Both-mode has_more/next_offset are capped by the candidate window (previously a page size not dividing the window advertised an offset the next call rejected); search_semantic_many applies the same window check.
  • Pure-deletion hunks (+N,0) are skipped without buffering, so deleting a file with a >1 MiB line (e.g. a minified bundle) no longer aborts the whole diff search.
  • Partial diff lines are only streamed once they exceed max_chunk_chars, so chunk text no longer depends on pipe read boundaries (stable results and cache hits across runs).

Known limitations / follow-ups

  • search_hybrid in db mode refetches with page_size=total when results overflow the first page. It has no production caller today; capping it at the 2000 window is a cheap follow-up.
  • _store counts identical markdown strings more than once against the 32 MiB source budget (≈3× page size), so pages above ~10 MiB are never cached and are refetched on each scan.

Test plan

  • uv run pytest tests/test_smoke.py -v -n auto
  • uv run pytest tests/unit/test_transient_search_service.py tests/unit/test_vector_cache.py tests/unit/test_web_research_service.py tests/unit/test_diff_aware_search_service.py tests/unit/test_git_diff_runner.py tests/unit/test_git_diff_parser.py -v
  • uv run pytest tests/integration/test_websearch_command.py tests/integration/test_deep_research_with_diff.py tests/integration/test_websearch_mcp.py -v
  • Full suite: uv run pytest tests/ -v
  • Manual: semantic search over a large --commit-range (thousands of chunks) returns the first page with no 30 s git kill during embedding
  • Manual: --vector-source both — following next_offset never errors; ranking stable across pages; total is a number
  • Manual: websearch writes no files under the tmpdir; URLError / empty-results exit codes unchanged
  • Manual: chunkhound mcp (stdio) + websearch over a malformed PDF keeps the JSON-RPC stream clean

HananKavitzAmat and others added 21 commits August 24, 2026 13:58
Two groups were still too slow; pytest-split evenly divides the
suite by count with no durations file, so bumping to 3 needs only
the matrix and --splits flag updated.
Replace bulk diff embedding and the _quickresearch subprocess with a shared VectorCache plus TransientSearchService so git history and fetched pages search without temp files or new config knobs.

Co-authored-by: Cursor <[email protected]>
Prevent mixed-provider cache hits, cancel sibling searches on failure, and keep full page text for research without buffering all bodies.

Co-authored-by: Cursor <[email protected]>
…meric

AC2: VectorCache stored list[float], costing ~49KB per entry at dim=1536 once
Python float-object overhead is counted — a 10k-chunk diff grew the process
~470MB, ~20x a 500-chunk diff rather than the same order the issue requires.
Store float32 arrays instead: 6463 bytes/entry, 61.6MB for a full cache. get()
now returns an ndarray, so the hot path also drops a list->array conversion per
cache hit.

TTL was measured from insertion, not last access, so a research session running
past 300s re-embedded chunks it was actively querying. get() now refreshes the
timestamp on every hit, matching the issue's stated rationale for having a TTL.

AC9: both-mode pagination set total=None whenever either source had more
results. None is neither exact nor a lower bound, and the CLI interpolates
total straight into its header — `--last-n N --vector-source both` printed
"Results: 10 of None". total now stays len(merged): a lower bound while a
source has more to give, exact once both are exhausted. The CLI fallback is
made explicit for hybrid search, which still reports total=None.

Refs chunkhound#336

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`stream_git_diff_file_blocks` recorded `deadline = loop.time() + 30` once and
re-checked it on every readline. Because it is an async generator it pauses at
each yield while the caller embeds that file block -- a provider round-trip per
100 chunks -- so the consumer's latency was charged against git's liveness
guard. A 5,000-chunk range needs ~50 embedding calls and blew the 30s window,
making a large commit range kill its own git process. Reproduced with a 3s
budget and a 1s-per-block consumer: TimeoutError after 3 blocks; now all 10
blocks drain.

The guard was correct in chunkhound#288, where `run_git_diff` buffered the whole diff and
embedding had its own separate 120s budget. Streaming interleaved the two and
merged the budgets by accident. Track only time actually spent blocked on git
instead; embedding needs no total budget of its own because providers already
carry a per-request timeout.

Also bound the previously-unbounded stderr drain, with a floor so a spent
budget cannot mask git's own error message.

Fixes AC1/AC2/AC3 of chunkhound#336.

Remove code this branch orphaned:

- `run_git_diff` / `_communicate_git_diff` (zero production callers). Its four
  still-live contracts move to the streaming function rather than disappearing:
  both argument-injection guards, and both retry behaviours -- now asserting
  the retry's own stderr surfaces instead of just "git diff failed".
- The always-None truncation plumbing left by the MAX_DIFF_CHUNKS removal:
  `_inject_diff_service` returns DatabaseServices instead of a tuple, and
  `warnings` comes off SearchResponse plus the execute_tool render.
- The websearch tmpdir path (`fetch_and_save`, `_fetch_one`,
  `_url_to_filename`, `websearch_postprocess`), so nothing can write fetched
  pages to disk -- AC7 forbids it.
- `IndexingConfig.reset_user_include_exclude`, which existed only for the
  deleted `_quickresearch`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Keep in-process streaming search while taking main's fetchurl tool, previous_query chaining, shared fetch_url_to_content, and synthesis map lifecycle.

Co-authored-by: Cursor <[email protected]>
Capture the branch summary so the upcoming PR can reuse it after the main merge.

Co-authored-by: Cursor <[email protected]>
TransientSearchService's top-K heap capacity scaled with offset + page_size
uncapped, so a deep-offset query (e.g. the last page of a 5,000-chunk diff)
made the heap hold the entire corpus -- silently reverting to the O(N)
memory behavior this service exists to eliminate. Cap offset + page_size at
a fixed window so worst-case heap memory is a known constant regardless of
corpus size; callers paging past it get an explicit ValueError instead of
silent unbounded growth.
…ff lines

Two gaps in the streaming git-diff runner:

- Stderr was drained with an unbounded stream.read(), so a git process
  writing a large volume of stderr could still balloon memory even though
  stdout is streamed. Cap what's retained at 64 KiB while still draining
  to EOF, so git never blocks writing to a full pipe.

- Switching stdout reads to readline() introduced an implicit 64 KiB
  per-line cap from asyncio's default StreamReader limit. A single diff
  line longer than that (a minified bundle, a long lockfile line) raised
  an uncaught ValueError that killed the entire diff stream -- a new,
  undocumented hard cap replacing the MAX_DIFF_CHUNKS cap this rewrite
  exists to remove. readline() itself can't recover from this: on overrun
  it wraps LimitOverrunError into a plain ValueError and discards the
  buffered bytes. Reading via the lower-level readuntil() instead
  preserves the buffer on overrun, so the overlong line can be
  reassembled via readexactly() + retry instead of aborting.
…earch

Removing MAX_DIFF_CHUNKS and the paired 120s embedding timeout dropped the
only guard against a pathological diff/web source: previously a huge commit
range failed fast with an actionable error, now a large enough source (or a
stalled embedding backend) can hang the calling MCP tool call indefinitely.

Wrap the streaming + sequential-embedding loop in _search_transient with a
generous (300s) asyncio.wait_for so it still raises a clear, actionable
TimeoutError instead of blocking forever. The budget is sized well above
what a legitimate multi-thousand-chunk diff takes to embed in batches --
per-request hangs are already bounded by each embedding provider's own
request timeout, so this is purely an aggregate ceiling on truly extreme
sources.
Neither the urllib fetch path (_fetch_url's resp.read()) nor the CDP
fetch path (get_response_body / tab.get_content()) capped a single
page's body size. A target URL can be anything -- a mis-served
multi-GB file, an infinite stream -- with no way to know its size in
advance, so a single oversized page could balloon memory for the
whole websearch call even though disk writes were already removed.

Add _MAX_PAGE_BYTES (20 MB) and enforce it at both fetch boundaries:
_read_bounded reads the urllib response in fixed-size chunks and
raises once the cap is exceeded (before fully buffering it);
_check_page_size does the equivalent post-hoc check on the CDP path,
which hands back a page's body in one RPC call with no incremental
read to bound. _fetch_content already catches and skips-with-a-warning
any single page that fails to fetch, so an oversized page degrades
gracefully instead of crashing the whole call.

Only the urllib path has an automated regression test (hermetic, via a
local HTTP server). A CDP-path integration test was attempted but
dropped as unreliable: real headless Chrome in this sandboxed
environment fails unpredictably on a 20MB+ response before reaching
_check_page_size at all (a CDP protocol error on one attempt, a
connection reset with no exception on another) rather than
deterministically exercising the size check.
…read()

_read_bounded() (introduced in 6d0cc91) calls resp.read(65536) in a loop
to bound memory, but this test's _FakeResponse.read() only accepted zero
arguments, so _fetch() raised TypeError against it. Real
http.client.HTTPResponse.read() accepts an optional size argument; the
double was just incomplete. Caught by CI (test failed on both attempts,
flagged for a flaky annotation) rather than locally, since the prior
commit's test run only covered a curated subset of websearch test files
and missed this one.
Fixed candidate pool size (snapshot_size) is now used for both the diff
and DB sides in "both" mode search, instead of an offset-dependent fetch
size. This prevents the pool from compounding the overfetch formula and
keeps pagination stable across pages for the same query.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@HananKavitzAmat
HananKavitzAmat marked this pull request as draft September 17, 2026 11:00
Hanan Kavitz added 8 commits October 20, 2026 13:34
CLI websearch printed research progress on stdout, mixing tree events with
the answer. Route TreeProgressDisplay to stderr.

vector_source=both fetched a 2000-hit DB snapshot on every page. Merge
overfetch-sized heaps from diff and DB instead; the 2000 window only
rejects deep offsets. Hybrid freeze still uses the window for stable
position ranking without turning both-mode into a 2000-hit DB query.
Keep one CHUNKHOUND_WEBSEARCH_TIMEOUT_SECONDS total. Cap query
expansion + DDG at min(60s, total/4) so a hung search cannot consume
fetch and research. CLI and MCP share run_websearch.
@HananKavitzAmat
HananKavitzAmat marked this pull request as ready for review November 9, 2026 08:24

@VakninAriel VakninAriel left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this refactor. The bounded streaming pipeline and improved source provenance are meaningful improvements. I found five correctness issues that I recommend addressing before merging:

  1. Diff pagination stops before all available results are reachable. In chunkhound/services/transient_search_service.py:443–444, pagination treats the current retained heap size as the paging limit. With more than 50 matches and page_size=10, offset 40 reports no continuation, although requesting offset 50 returns more results. Please calculate diff-only continuation from the qualifying count and supported result window, rather than the current heap size. This affects both single-query and bulk search.

  2. Large trailing deletions can abort the entire diff search. In chunkhound/core/git_diff/parser.py:319–321, a hunk containing retained context followed by multiple chunks of deleted lines can produce start_line > end_line. A patch with three context lines followed by 500 deleted lines reproduces the validation error. Please keep deletion-fragment anchors within valid hunk bounds and add a regression test confirming that subsequent files remain searchable.

  3. MCP response trimming can advertise an invalid next page. In chunkhound/mcp_server/tools.py:1074–1082, trimming a terminal both-mode page can replace its pagination with a continuation outside the supported window. For example, offset 40 with page_size=10, trimmed to six results, advertises next_offset=46; following it fails the 50-candidate window check. Please ensure trimmed continuations remain valid without silently dropping the remaining results.

  4. The total websearch timeout does not bound inline fetch cleanup. At chunkhound/utils/websearch_pipeline.py:178–179, asyncio.wait_for waits for cancellation to finish. If research is actively consuming the page generator, its cleanup runs before the deadline-aware closing helper can intervene. A 0.05-second budget with 0.3-second producer cleanup returned after approximately 0.35 seconds. Please bound the response deadline while preserving ownership of eventual resource cleanup.

  5. PDF worker startup can bypass the hard timeout. In chunkhound/services/web_research_service.py:384–390,482–488, passing PDF bytes as spawn arguments can block process.start() before the internal deadline begins if the child exits or stalls before reading its bootstrap input. The outer timeout then awaits the blocked thread without a bound. Please supervise startup and document transfer under the same deadline, avoid large bootstrap arguments, and cover early worker failure with a payload larger than the pipe buffer.

Recommendation: request changes for these issues. Targeted tests passed with environment workarounds, but full-suite and PDF subprocess validation remain incomplete. The type-check run also reported errors; without a base comparison, those errors are not attributed to this PR.

@VakninAriel VakninAriel left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR #407 review

PR: #407

  • Title: feat(search): stream transient git and websearch in-process
  • Reviewed head: 392222a77f2c1b1c2b986cedc61f3737ab490e4d
  • Base: df61002356e9caf96e5e88e27a53c4a84dbf3453
  • Recommendation: Request changes for the five P2 correctness issues below.
  • Review was read-only on the repository. No GitHub review or comment was posted.

Findings

1. P2 — Preserve diff ownership when pruning semantic candidates

Location: chunkhound/services/transient_search_service.py:793–801, ownership check at 811–813.

transient_locations is built only from the retained top-K diff candidates. A historical chunk below that cutoff therefore stops suppressing the DB result at the same (file_path, start_line). Before this PR, both-mode fetched all diff chunks before deduplication; the new tests also retain the contract that lower-scoring diff evidence wins at a shared location.

Reproduction: With 51 diff chunks and page_size=10, the default candidate pool retains 50. Give the excluded historical chunk a low similarity and its overlapping DB result a high score. Head returns the DB version first; base suppresses it.

Impact: Both-mode history search/research can substitute current or stale indexed text for the requested historical evidence. This is a revision-ownership regression, not just reduced retrieval recall.

Correction: Check DB candidate ownership against the streamed diff independently of top-K retention, while preserving the intended memory bound.

2. P2 — Exclude withdrawn web sources from final evidence

Location: chunkhound/services/research/shared/file_reader.py:189–190.

Web providers mark chunks as authoritative sources, so this branch copies earlier search results directly into synthesis excerpts without checking whether their URLs were subsequently dropped. When an evicted page changes or cannot be refetched, _BoundedPageStream withdraws it and warns “Dropped from research,” but earlier exploration results survive. The final guard rejects only runs where every usable source was dropped.

Reproduction: Initial search finds A and B. Evict the cache, then refetch A with changed content. Follow-up search omits A and emits the withdrawal warning. Reading the accumulated results still produces an authoritative excerpt containing A's old text, and research succeeds while B remains usable.

Impact: The final answer can use and cite evidence explicitly withdrawn from the research session. This does not require mixing the new revision into the answer.

Correction: Consult session-level source availability before selecting final excerpts and citation inputs, retaining exact chunk-based evidence for sources that remain valid.

3. P2 — Keep filesystem read failures isolated in mixed-source research

Location: chunkhound/services/research/shared/file_reader.py:195–197; also the mixed-evidence read at line 162.

The new transient-budget path reads current working-tree files without the per-file exception handling used by the ordinary reader. _DiffResearchProvider activates this path for production diff research, including vector_source="both". BFS calls this helper before its ordinary per-file error handling.

Reproduction: Supply valid historical evidence plus a DB hit whose indexed file path is now a directory. The new helper raises IsADirectoryError and aborts; ordinary reading catches the error and retains other readable evidence. Permission failures or a filesystem race can produce the same outcome.

Impact: One unreadable current-source hit fails otherwise viable historical research. A read failure at a path containing both evidence kinds also prevents fallback to its valid historical chunks.

Correction: Restore per-file isolation for filesystem read failures while keeping deliberate terminal source-consistency errors distinct.

4. P2 — Respect document limits when embedding expanded queries

Location: chunkhound/services/transient_search_service.py:366–368.

The bulk path submits every expanded query to one embedding call. Document embeddings respect get_max_documents_per_batch(), but this query call does not. The real OpenAI provider internally splits on token count, not the configured document count. Its batch_size is documented as the maximum texts per API request.

Reproduction: Configure the real OpenAIEmbeddingProvider with batch_size=1, a custom model/endpoint, and submit three short queries through bulk transient search. The API boundary receives one request containing three texts. Previously, expanded-query research used scalar searches and embedded one query per request.

Impact: Diff/web research fails against OpenAI-compatible endpoints enforcing a small configured document limit. This is configuration-dependent, not a claim that normal three-query requests exceed standard OpenAI limits.

Correction: Batch query embeddings under the provider document limit while preserving query/vector order and embedding-space validation.

5. P2 — Include oversized source lines in reported chunk ranges

Location: chunkhound/core/git_diff/parser.py:259–262; endpoint calculation at 331–332.

When a short line is followed by a line longer than max_chunk_chars, the oversized-line path fills the existing draft with the beginning of the next line. _emit_pending() still computes the previous chunk's endpoint as one line before the next fragment's offset. Its range therefore excludes source text it actually contains. The streamed partial-line path has the same packing concern.

Reproduction: In a real Git repository, replace a one-line file with short\n followed by MARKER plus 20,000 characters and a newline. With the default 10,000-character limit, head's first chunk contains MARKER but advertises lines 1–1; the marker is on line 2. Base flushed the first line and assigned the marker-bearing fragment to 2–2.

Impact: Search locations and research citations can point to a range that excludes the matched text in long generated/minified lines.

Correction: Flush completed-line drafts before splitting oversized lines, or track inclusive source coverage explicitly for overlapping fragments.

Validation

  • Four independent review areas: transient search/cache, git diff streaming, web research, and research integration.
  • A separate skeptical reviewer validated the five findings and their production call paths. An additional regex-pagination candidate was omitted because no affected production consumer of that metadata was established.
  • Targeted exact-head tests: 209 passed in 26.62 seconds. Covered transient search, vector cache, web research, transient diff search, git runner/parser, web memory, web pipeline/page cap, citation manager, unified bulk search, and synthesis budgets.
  • Tests ran with uv run --project /home/e119870/views/g/my_chunkhound --no-sync python -m pytest against separately extracted exact-head test files and Python sources. The existing compiled native extension was preloaded; the PR's native extension was not rebuilt. Ancestor test configuration was isolated with --confcutdir=tests/unit.
  • Initial PDF test failures were launcher artifacts (<stdin> cannot be respawned, and subprocess imports missed the head snapshot). After using a module launcher and propagating bootstrap imports, all 209 tests passed. These failures are not PR findings.
  • Ran uv run --project /home/e119870/views/g/my_chunkhound --no-sync mypy chunkhound from the head snapshot: 984 errors in 90 files, checking 376 source files. Not baseline-compared; not attributed to the PR.
  • Full suite, smoke suite, live provider calls, and a fresh dependency/native build were not run.
  • Rechecked GitHub head at the end: unchanged at 392222a7.
  • Original branch and working-tree status remained unchanged.

Strengths

The PR adds substantial contract coverage around bounded streaming, cache behavior, cancellation, source budgets, and isolated PDF parsing. The targeted suite passes. The remaining findings concern uncovered revision ownership, source withdrawal, external request limits, and source-location accuracy rather than the overall streaming architecture.

@VakninAriel VakninAriel left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR #407 re-review

PR: #407

  • Title: feat(search): stream transient git and websearch in-process
  • Reviewed head: b8f8bdf0c04c3ba6b21693868d671f725213993b
  • Previous reviewed head: 392222a77f2c1b1c2b986cedc61f3737ab490e4d
  • Base: df61002356e9caf96e5e88e27a53c4a84dbf3453
  • Assessment: All five previous findings are resolved. No new actionable findings identified in the update. No remaining review blocker found within the reviewed scope; validation limitations below still apply.
  • Read-only review: no repository source changes or GitHub posts.

Scope

Reviewed the eight-file delta from the previous head, with production context from the full PR. Three independent reviewers examined transient search, source reading/web synthesis, and Git parsing; a fourth ran tests and type checking. The parent inspected the changes and evidence and independently reran the targeted suite. This is an incremental re-review, not a claim that every unchanged part of the PR was exhaustively re-reviewed.

Prior report: /home/e119870/views/okf/chunkhound/pr-407/review-392222a7.md.

Previous findings

1. Resolved — Top-K pruning no longer loses diff ownership

Locations: chunkhound/services/transient_search_service.py:377–386, 484–491, 632–648, 788–805, 952–957.

The implementation now records historical ownership for locations in the bounded DB snapshot independently of whether those historical chunks survive the semantic heap. DB locations are populated before source scoring; only a single source batch is prefetched while waiting, preserving bounded retention.

A focused reproduction used 61 historical chunks, an excluded historical owner below the 50-candidate cutoff, and a high-scoring stale DB row at its location. Scalar and bulk searches suppressed the stale row, including delayed DB completion. Concurrent searches retained independent ownership state.

2. Resolved — Withdrawn web sources are excluded from synthesis and citations

Locations: chunkhound/services/web_research_service.py:192–194, 650–653, 663–665; chunkhound/services/research/shared/file_reader.py:86–91.

The provider exposes session-level availability, and final evidence selection excludes URLs in the dropped-source set. Single-pass, map, and reduce synthesis filter their chunk inputs against selected files, so excluded evidence does not return through citation construction.

A focused reproduction used the real bounded page stream with a fake network boundary: A and B were initially searched, A changed after cache eviction, and replay withdrew A. Reading the original accumulated results retained only B. Actual synthesis methods excluded A's URL and old evidence from prompts, citation maps, source lists, and footers.

3. Resolved — Filesystem failures remain isolated in mixed research

Location: chunkhound/services/research/shared/file_reader.py:40–48.

Current-source reads now check is_file() and catch filesystem OSError. Missing or unreadable current context returns no content rather than aborting valid historical evidence. The catch does not swallow asynchronous provider consistency failures.

A focused reproduction used the real diff research provider, a directory replacing an indexed file, a filesystem-boundary permission failure, and a readable neighboring source. Both FileReader and BFS preserved historical fallback and readable neighbors, skipped pure unreadable current hits, and kept stale snippets out of synthesis.

4. Resolved — Expanded queries respect provider document limits

Location: chunkhound/services/transient_search_service.py:164–195, 459–467.

Expanded queries are split under the provider's document-count limit, with vector-count and embedding-space validation across batches.

A focused reproduction used the real OpenAI embedding provider and embedding manager, replacing only the API boundary. With a custom endpoint/model and batch_size=1, three queries generated three one-text API requests. Query/vector ordering was preserved; changed embedding identity or missing vectors in later batches failed explicitly.

5. Resolved — Oversized source lines have correct reported ranges

Locations: chunkhound/core/git_diff/parser.py:154–156, 259–262, 283–293.

Both complete-line and partial-stream paths now flush completed body drafts before appending an oversized source line.

A real Git diff containing a short line followed by a 200,000-character line with a marker reproduced the old incorrect range 1–1; the updated parser reports 2–2. Whole-input and fragmented-input parsing agreed. Fragment sizes from 1 to 65,536 characters, the actual asynchronous Git streaming pipeline, later-file recovery, and 398 randomized valid synthetic hunks were checked without an actionable range regression.

Regression checks

Additional transient-search checks exercised caller cancellation during DB gating, source failure cancelling stalled DB work, scalar DB failure cancelling a blocked source, transient timeout cleanup, and isolated bulk DB-query failures. Exercised cancellation paths finalized sources and DB work without pending asyncio tasks.

The one-batch gate cannot discover a later source failure before DB readiness; no concrete new production failure was established from that bounded-prefetch tradeoff.

Validation

  • Targeted suite: 214 passed. Independent parent rerun: 214 passed in 26.85s, exit 0. Validator's first run: 214 passed in 28.99s.
  • Covered transient search, vector cache, web research, transient diff search, Git runner/parser, web memory, web pipeline/page cap, citation management, unified bulk search, and synthesis budgets.
  • Mypy: 984 errors in 90 files, checking 376 source files. No baseline diagnostic comparison was performed; these errors are not attributed to the PR. Among the four source files changed in this update, the sole diagnostic was missing regex stubs at transient_search_service.py:13. Aggregate totals match the previous report, which does not prove identical diagnostics.
  • Exact updated-head Python sources and tests were separately extracted to temporary directories. Commands used uv run --project /home/e119870/views/g/my_chunkhound --no-sync; pytest ran as a module with --confcutdir=tests/unit -o addopts= -p no:cacheprovider.
  • Existing dependencies and the original checkout's compiled native extension were reused via a bootstrap import. No fresh native build, dependency sync, live-provider calls, full suite, or smoke suite. Network and LLM boundaries in focused reproductions were faked.
  • GitHub head was rechecked and remained b8f8bdf0c04c3ba6b21693868d671f725213993b.
  • Original checkout HEAD remained b42749850bbc76f9f7dfac502cb38cd941b925e2; working-tree status remained unchanged, including existing untracked artifacts.

Temporary evidence

These paths are disposable, not durable reports:

  • Test/type-check logs: /tmp/chunkhound-407-b8-validation-CH2RO5/pytest.log, /tmp/chunkhound-407-b8-validation-CH2RO5/mypy.log
  • Transient reproduction: /tmp/pr407-transient-child-UgBsu2/checks.py
  • Source/synthesis reproduction: /tmp/pr407-source-review-L5ZsSc/check.py
  • Parser reproductions: /tmp/pr407-parser-review-bkZQwT/

Conclusion

The update directly addresses each previously reported correctness issue and adds relevant regression coverage. The review no longer recommends changes for those findings. No new actionable defect was found in the updated code; normal CI and broader integration validation remain necessary before merge.

@HananKavitzAmat
HananKavitzAmat added this pull request to the merge queue Nov 11, 2026
Merged via the queue into chunkhound:main with commit 7ad06ce Nov 11, 2026
25 checks passed
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
Two tests mocked interfaces that main has since changed. _inject_diff_service now returns the services alone (chunkhound#407), so the commit-diff test's mock returns services instead of a (services, None) tuple. Semantic search now embeds the query with embed_query (chunkhound#469), so the no-warning test's provider mocks embed_query instead of embed. Both assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
VakninAriel pushed a commit to VakninAriel/chunkhound that referenced this pull request Nov 24, 2026
* feat(mcp): add strategy parameter to the search tool

Semantic search picks multi-hop whenever the provider can rerank, and the
VoyageAI provider always can (rerank-2.5 is the default model). Multi-hop
reranks the initial pool, then expands and reranks again until its time
limit (5 s by default). MCP callers that rerank results themselves had no
way to ask for the plain vector search the CLI exposes as --single-hop.

strategy: 'auto' (default, unchanged), 'single_hop', or 'multi_hop', passed
through as force_strategy.

* fix(mcp): two strategy values, rejected where they cannot apply

Review follow-up for chunkhound#462.

- Drop "auto". strategy is Literal["single_hop", "multi_hop"] | None and
  defaults to None, which is forwarded as force_strategy=None, so omitting
  it keeps choosing by provider capability (multi-hop when the provider can
  rerank) and a non-reranking provider searches with no warning.
- A semantic search that sets strategy together with commit_range,
  commit_hash or last_n_commits raises ValueError unless vector_source="db".
  The diff path has no strategies, so the value used to be dropped silently.
  Same rule as the CLI's --single-hop/--multi-hop.
- An unknown strategy raises ValueError naming the valid values, before any
  service work. The Literal stays for the schema.
- Tests cover the two-value schema, forwarding of both values and of an
  omitted one, regex ignoring strategy, the unknown value, each commit
  argument with vector_source diff and both, the db exception, and the
  no-warning default. The docstring states the single-hop fallback instead
  of "requires".

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(mcp): give the no-warning test's provider an awaitable embed_query

Search queries go through provider.embed_query once chunkhound#469 lands. The
test's Mock provider only had embed as an AsyncMock, so on a tree with
both PRs the query embedding raised and the test failed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(mcp): describe the search strategy parameter where clients read it

Name `strategy` in both search tool descriptions, state the real regex
rule (a valid value has no effect, an invalid one raises), list every
ValueError in the docstring, and replace the guard comment with the
MCP rule, which differs from the CLI's. Drop the embed_query mock that
nothing on this branch calls, and collapse the blank-line seam.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(mcp): fit the strategy tests to main's search changes

Two tests mocked interfaces that main has since changed. _inject_diff_service now returns the services alone (chunkhound#407), so the commit-diff test's mock returns services instead of a (services, None) tuple. Semantic search now embeds the query with embed_query (chunkhound#469), so the no-warning test's provider mocks embed_query instead of embed. Both assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
gauravkr2209 added a commit to gauravkr2209/chunkhound that referenced this pull request Nov 24, 2026
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.

2 participants