Skip to content

feat(git-diff): git history semantic search via DiffAwareSearchService - #288

Merged
HananKavitzAmat merged 29 commits into
chunkhound:mainfrom
VakninAriel:feat/git-diff-search
Jun 9, 2026
Merged

HananKavitzAmat merged 29 commits into
chunkhound:mainfrom
VakninAriel:feat/git-diff-search

Conversation

@VakninAriel

@VakninAriel VakninAriel commented May 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Adds git-history-aware semantic search: parse `git diff ` → in-memory `Language.GIT_DIFF` chunks → embed → `DiffAwareSearchService` decorator overlays results onto existing `SearchService`
  • Three `vector_source` modes: `diff`, `db`, `both` (concurrent merge by score)
  • Exposed via MCP `search`/`code_research` tools and CLI `--commit-range / --commit-hash / --last-n`

Commits

  • Phase 1+2: git_diff package, Language.GIT_DIFF, DiffAwareSearchService
  • Phase 3: wire commit params into search_impl
  • Phase 4: mirror diff params into deep_research_impl + integration test
  • Phase 5: CLI parsers and commands
  • Phase 6: docs (README + AGENTS.md examples)
  • fix: clamp embeddings+chunks to min(M,N) for provider batching overcount
  • fix(review): hunk_end off-by-one, Path.cwd()→find_project_root, path_filter normalization, both-mode pagination, _resolve_commit_range helper, add_git_diff_arguments dedup, MAX_DIFF_CHUNKS=500 cap, 4 new tests
  • fix(git-diff): add max_chunk_chars; split overlong hunks (SVG/minified JS)
  • fix(git-diff): address all PR feat(git-diff): git history semantic search via DiffAwareSearchService  #288 review feedback (see below)

Review Fixes (latest commit)

Majors addressed

  • DRY violation: extracted _inject_diff_service() helper — eliminates ~30-line copy-paste between search_impl and deep_research_impl; unifies embedding guard (if diff_chunks and embedding_manager is not None)
  • Silent except: parser.py except Exception: pass → except Exception as exc: logger.warning(...)
  • Unrelated test: removed test_watchman_start_failure_cleans_up_after_eager_publication + 3 helper functions from test_daemon_smoke.py

Minors addressed

  • Type safety: DatabaseServices.search_service widened to SearchService | DiffAwareSearchService; type: ignore[arg-type] removed; cast used at Database() call site where type is always SearchService
  • vector_source="diff" contract: empty diff chunks now returns ([], {"total": 0, ...}) with warning instead of silently falling back to DB
  • --commit-hash help text: clarified that it expands to <hash>..HEAD; added note about <hash>^..<hash> for single-commit diff
  • Language.GIT_DIFF: added docstring note in from_file_extension() that GIT_DIFF is intentionally absent (in-memory-only)

Test plan

  • uv run pytest tests/unit/test_git_diff_parser.py tests/unit/test_git_diff_runner.py tests/unit/test_diff_aware_search_service.py tests/integration/test_deep_research_with_diff.py -v → 40 passed
  • uv run mypy chunkhound/mcp_server/tools.py chunkhound/database_factory.py chunkhound/core/git_diff/parser.py chunkhound/services/diff_aware_search_service.py → Success: no issues found

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Code Review

Summary: Well-structured new feature adding git-history semantic search with three vector-source modes; mostly clean architecture with a few fixable issues before merging.


Strengths

  1. Excellent test coverage — unit tests for parser, runner, DiffAwareSearchService (including edge cases: path_filter normalization, cosine unit vectors, both-mode pagination, distance-based DB result normalization), plus integration tests proving injection into deep_research_impl.
  2. Security-conscious git ref validation in runner.py (regex allowlist + subprocess.exec, not shell) with a 30-second timeout guard.
  3. Shared add_git_diff_arguments() extracted cleanly to common_arguments.py — good DRY at the CLI layer; the _resolve_commit_range() helper in tools.py is clean.

Issues

Major — tools.py:418-448 and tools.py:479-509

The diff-injection block (~30 lines: run_git_diff → parse → cap → embed → build DiffAwareSearchService → services._replace) is copy-pasted verbatim in both search_impl and deep_research_impl. This is the most significant DRY violation in the PR. Should be extracted to a private helper, e.g.:

async def _inject_diff_service(
    services: DatabaseServices,
    effective_commit_range: str,
    vector_source: str,
    embedding_manager: Any,
) -> DatabaseServices:
    ...

Major — parser.py:231-232

except Exception:
    pass

Silently swallows any Chunk construction error (bad LineNumber, FileId, etc.), returning a shorter chunk list with no diagnostic. Should at minimum logger.debug(...) or logger.warning(...) the exception before continuing; makes debugging malformed diffs very difficult.

Major — Unrelated test bundled

tests/test_daemon_smoke.py adds three new helper functions (_read_process_stream, _close_process_stdin, _force_stop_process) and a full new test test_watchman_start_failure_cleans_up_after_eager_publication. These have nothing to do with git-diff search and belong in a separate PR.

Minor — type: ignore[arg-type] × 2 (tools.py:448, tools.py:509)

services._replace(search_service=diff_service) silences a real type mismatch because DatabaseServices.search_service is typed as SearchService but receives a DiffAwareSearchService. SearchServiceProtocol is defined but never referenced in the DatabaseServices field type. Cleanest fix: type search_service as SearchService | DiffAwareSearchService, or make DatabaseServices.search_service: SearchServiceProtocol.

Minor — vector_source="diff" silent fallback (diff_aware_search_service.py:653-665)

When vector_source="diff" but diff_chunks is empty, the service silently falls back to the original DB search. The documented contract is "search only changed code" — silently returning DB results instead is a behavioral surprise. Should either raise or return an empty result set with a clear log warning.

Minor — --commit-hash semantics (common_arguments.py:117)

Help text says "Single commit hash — from that commit to HEAD", which expands to <hash>..HEAD. This searches everything between that commit and HEAD, not changes within that single commit (<hash>^..<hash>). Accurate but counterintuitive — users expecting "search this commit's changes" will be confused. Consider clarifying the help string.

Minor — Language.GIT_DIFF not in from_file_extension()

Not registered in the extension map (intentional), but the .patch extension entry in test_e2e_chunk_size_constraints.py implies users might expect .patch files to be recognized. A comment in from_file_extension() noting that GIT_DIFF is in-memory-only would remove ambiguity.


Reusability

  • Extract the duplicated injection block into _inject_diff_service(services, range, source, em) — would also allow future callers to reuse it.
  • SearchServiceProtocol is defined but unused as a type annotation; consider making DatabaseServices.search_service: SearchServiceProtocol to express the actual contract.

Decision: REQUEST CHANGES

The two majors (DRY violation in tools.py and silent except Exception: pass in parser.py) and the unrelated daemon test should be addressed. The feature itself is solid and the tests are thorough — these are targeted fixes, not architectural rework.

@ofriw ofriw 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.

Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


PR #288 Review: Git History Semantic Search

Nice work on this feature — the DiffAwareSearchService decorator pattern is the right call, avoiding changes to the existing SearchService internals, and the runner/parser split in core/git_diff/ keeps things modular. Tests are thorough across all three vector-source modes, edge cases like path-filter normalization (src vs src_utils), distance-to-similarity conversion, and pagination consistency. It's clear a lot of care went into the coverage.

Three things need fixing before merging. First, the except Exception: pass in parser.py:52-55 silently drops malformed chunks — we need at minimum a logger.warning() there (the AGENTS.md rule about no silent errors applies). Second, the ~30-line injection block in tools.py is copy-pasted between search_impl and deep_research_impl with a subtle behavioral difference in the embedding guard — extract to a _inject_diff_service() helper. Third, the new test_watchman_start_failure_cleans_up_after_eager_publication test in test_daemon_smoke.py (+118 lines of daemon/watchman logic) is unrelated to git-diff search and should be split into its own PR.

Minor items: the --commit-hash help text implies single-commit scope but actually expands to <hash>..HEAD (all commits since that hash, not just that commit's diff), the type: ignore[arg-type] on services._replace() signals we should either widen the DatabaseServices.search_service type or use SearchServiceProtocol, and the vector_source="diff" fallback to DB results when diff chunks are empty should at least log a warning. These are all quick to fix.


Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md

VakninAriel added a commit to VakninAriel/chunkhound that referenced this pull request May 24, 2026
…safety, test cleanup

Majors:
- Extract _inject_diff_service() helper — eliminates ~30-line copy-paste
  between search_impl and deep_research_impl; unifies embedding guard
- parser.py: replace bare `except Exception: pass` with logger.warning
- test_daemon_smoke.py: remove unrelated watchman eager-publication test
  and its three helper functions (belong in a separate PR)

Minors:
- database_factory.py: widen DatabaseServices.search_service type to
  SearchService | DiffAwareSearchService; cast at Database() call site
- diff_aware_search_service.py: vector_source="diff" with empty chunks
  now returns ([], {total:0}) instead of silently falling back to DB
- common_arguments.py: clarify --commit-hash expands to <hash>..HEAD
- common.py: document that Language.GIT_DIFF is in-memory-only
- parser.py: add max_chunk_chars param; split overlong hunks (SVG/minified JS)
- tests: 4 new parser tests for overlong-line splitting; update
  test_diff_mode_empty_chunks to assert new empty-result contract

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@VakninAriel

Copy link
Copy Markdown
Collaborator Author

Review Addressed — All Issues Fixed

All majors and minors from the review have been addressed in commits 1016cd01, 30820945, f20d0848, and 44cf92d4.

Majors

DRY violation (tools.py) — Extracted _inject_diff_service(services, effective_commit_range, vector_source, embedding_manager) helper. Both search_impl and deep_research_impl now call it; the ~30-line copy-paste block is gone.

Silent except Exception: pass (parser.py) — Replaced with logger.warning(..., exc_info=True) so malformed diff hunk errors surface in logs.

Unrelated daemon test — Removed test_watchman_start_failure_cleans_up_after_eager_publication and its three helper functions from test_daemon_smoke.py. Moved to a separate commit (5b27ed69) so it can be split into its own PR if preferred.

Minors

type: ignore[arg-type] × 2 — DatabaseServices.search_service widened to SearchService | DiffAwareSearchService; type: ignore comments removed.

vector_source="diff" silent fallback — Now returns ([], {total: 0}) with a logger.warning instead of silently falling back to DB results.

--commit-hash help text — Clarified to explicitly state expansion to <hash>..HEAD.

Language.GIT_DIFF comment — Added docstring in common.py noting it is in-memory-only and not registered in from_file_extension().

Bonus fix

parser.py now accepts a max_chunk_chars param and splits overlong hunks (SVG blobs, minified JS) rather than silently dropping them. Four new parser tests cover the splitting behavior.

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Design vs. Implementation Gap Review

Reviewed against the [git history summarization design doc (ALGINF-5402)](internal link) authored by Ariel Vaknin. Findings below, ordered by severity.


Gap 1 — vector_source default flipped ⚠️ Critical

Design decision (explicit): "Default vector_source when commit_range given: diff (diff-only). Explicit opt-in for both; fewer surprises."

Implementation: Defaults to "both" everywhere — common_arguments.py (default="both"), tools.py (vector_source: str = "both"), and README. The design team specifically chose diff as default to avoid implicit DB merging. The implementation made the opposite choice without explanation.


Gap 2 — DiffAwareSearchService does not subclass SearchService ⚠️ Significant

Design (in "Verified by code research" section): "No existing SearchService protocol/interface — DiffAwareSearchService subclasses SearchService directly"

Implementation: DiffAwareSearchService is a standalone class with no inheritance. The file defines its own SearchServiceProtocol (a Protocol class) and uses Any duck typing for the original parameter. DatabaseServices.search_service was widened to SearchService | DiffAwareSearchService (a union, not a subtype) to satisfy mypy — which is the workaround you need precisely when not using inheritance.


Gap 3 — vector_source="db" still runs git diff and creates the wrapper ⚠️ Significant

Design data flow: "vector_source=db — existing behavior, no commit_range → no wrapper created → services unchanged → existing path, zero impact"

Implementation: When commit_range is provided with vector_source="db", _inject_diff_service is called unconditionally. Git diff is executed, chunks are parsed, embeddings may be computed, and a DiffAwareSearchService wrapper is created — even though the wrapper immediately delegates 100% to the original. The design intended zero overhead for db mode.

Fix: add an early-exit guard before calling _inject_diff_service:

if effective_commit_range is not None and vector_source != "db" and type == "semantic":
    services = await _inject_diff_service(...)

Gap 4 — MCP tool exposes three commit params instead of one 📝 Minor

Design interface: commit_range: str | None as a single MCP parameter.

Implementation: Three mutually-exclusive parameters (commit_range, commit_hash, last_n_commits) with a _resolve_commit_range() helper. This is a UX improvement for Claude, but the design's MCP tool signature is meaningfully different from what shipped. Worth noting in the design doc update.


Gap 5 — DiffAwareSearchService constructor has extra embedding_manager param 📝 Minor

Design interface:

def __init__(self, original, diff_chunks, diff_embeddings, vector_source) -> None

Implementation: Adds embedding_manager as a 5th parameter (needed to embed the query at search time). The design assumed query embedding would happen externally and embeddings passed in; the implementation moves query embedding inside the service. The design's interface contract is wrong as written.


Gap 6 — Docstring bug in DiffAwareSearchService 📝 Minor

The class docstring says for "diff" mode: "falls back to the original service when diff_chunks is empty". The code does the opposite — it returns ([], {"total": 0, ...}) with a warning and no fallback. The PR description explicitly calls this out as intentional. The docstring needs updating.


Extensions shipped but not in design (informational)

Addition Notes
MAX_DIFF_CHUNKS = 500 cap OOM guard for large commit ranges — good
max_chunk_chars + oversized hunk splitting Handles SVG/minified JS — good
force_strategy incompatibility guard in CLI Prevents nonsensical --multi-hop + diff combos — good
SearchServiceProtocol in service file Enables structural subtype checks — fine, but not in design
_inject_diff_service() helper (DRY) Added in review, eliminates copy-paste — good
common_arguments.py::add_git_diff_arguments DRY across CLI parsers — better than design planned

Most actionable: Gap 1 is a direct reversal of an explicit design decision and should be confirmed with the team before merge. Gap 3 is a correctness-of-intent issue (wasteful work) with a straightforward fix.

@VakninAriel

Copy link
Copy Markdown
Collaborator Author

Latest Fixes (commits 396d7b8, d8fd2c1)

Addressing the design gap review items and in-flight correctness bugs found during testing.

Design Gaps Addressed

Gap 1 — vector_source default flipped: Changed default from "both" → "diff" everywhere (common_arguments.py, tools.py search_impl/deep_research_impl, README).

Gap 3 — vector_source="db" still ran git diff: Added early-exit guard in both search_impl and deep_research_impl — _inject_diff_service is now skipped entirely when vector_source="db", avoiding unnecessary git diff + embedding work.

Gap 2 (partial) — DatabaseServices type: Changed search_service field from SearchService | DiffAwareSearchService union back to SearchServiceProtocol — structural subtype check via Protocol, which is the correct Python idiom when you can't use inheritance.

Correctness Fixes

  • Pagination bug: _search_diff was returning raw N (total chunks before filtering) as total instead of total_after_filter, breaking has_more / next_offset after path_filter applied.
  • commit_hash expansion: Now correctly expands to <hash>^..<hash> (single-commit diff) instead of <hash>..HEAD (everything since that commit). Integration test assertions updated.
  • Embedding guard ordering: Diff injection in search_impl now happens after embedding_manager validation — provider-missing error surfaces cleanly before any git work starts.
  • Path traversal guard: runner.py now also blocks ../ anywhere in the commit range string (was only blocking leading ..).

Robustness

  • Embed timeout: embed_texts in _inject_diff_service wrapped in asyncio.wait_for(_EMBED_TIMEOUT_SECONDS=120) — large diff batches with slow providers now fail fast with a clear message instead of hanging indefinitely.

VakninAriel added a commit to VakninAriel/chunkhound that referenced this pull request May 26, 2026
…safety, test cleanup

Majors:
- Extract _inject_diff_service() helper — eliminates ~30-line copy-paste
  between search_impl and deep_research_impl; unifies embedding guard
- parser.py: replace bare `except Exception: pass` with logger.warning
- test_daemon_smoke.py: remove unrelated watchman eager-publication test
  and its three helper functions (belong in a separate PR)

Minors:
- database_factory.py: widen DatabaseServices.search_service type to
  SearchService | DiffAwareSearchService; cast at Database() call site
- diff_aware_search_service.py: vector_source="diff" with empty chunks
  now returns ([], {total:0}) instead of silently falling back to DB
- common_arguments.py: clarify --commit-hash expands to <hash>..HEAD
- common.py: document that Language.GIT_DIFF is in-memory-only
- parser.py: add max_chunk_chars param; split overlong hunks (SVG/minified JS)
- tests: 4 new parser tests for overlong-line splitting; update
  test_diff_mode_empty_chunks to assert new empty-result contract

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@VakninAriel
VakninAriel force-pushed the feat/git-diff-search branch from d8fd2c1 to 4bfcfaa Compare May 26, 2026 12:35
@VakninAriel
VakninAriel requested a review from ofriw May 27, 2026 09:37
VakninAriel added a commit to VakninAriel/chunkhound that referenced this pull request May 27, 2026
…safety, test cleanup

Majors:
- Extract _inject_diff_service() helper — eliminates ~30-line copy-paste
  between search_impl and deep_research_impl; unifies embedding guard
- parser.py: replace bare `except Exception: pass` with logger.warning
- test_daemon_smoke.py: remove unrelated watchman eager-publication test
  and its three helper functions (belong in a separate PR)

Minors:
- database_factory.py: widen DatabaseServices.search_service type to
  SearchService | DiffAwareSearchService; cast at Database() call site
- diff_aware_search_service.py: vector_source="diff" with empty chunks
  now returns ([], {total:0}) instead of silently falling back to DB
- common_arguments.py: clarify --commit-hash expands to <hash>..HEAD
- common.py: document that Language.GIT_DIFF is in-memory-only
- parser.py: add max_chunk_chars param; split overlong hunks (SVG/minified JS)
- tests: 4 new parser tests for overlong-line splitting; update
  test_diff_mode_empty_chunks to assert new empty-result contract

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@VakninAriel
VakninAriel force-pushed the feat/git-diff-search branch from 1e3b0fb to d754e4c Compare May 27, 2026 13:29
@HananKavitzAmat
HananKavitzAmat enabled auto-merge May 27, 2026 13:53

@ofriw ofriw 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.

Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


Review: PR #288 — Git History Semantic Search

Nice work on this feature. The architecture is solid — using a decorator over subclassing SearchService was the right call, and the three vector_source modes (diff/both/db) cover the UX well. The test suite is thorough (14 parser tests, 17 service tests, 6 integration), and most of the earlier review feedback has been addressed. The oversized hunk splitting and path traversal prevention are details done right.

Two things need fixing before this merges:

Critical: find_project_root(None) kills the MCP server — _inject_diff_service() calls find_project_root(None) which sys.exit(1)s if it can't find project markers from CWD. In MCP context (Cursor/VSCode), that terminates the server instead of returning a graceful error. Wrap it or pass a fallback path.

--vector-source default mismatch — The parser default is "diff" but the getattr fallback in both search.py and research.py is "both". Dead code today, but a maintenance trap if someone removes the argument parser without fixing the fallback.

Minor things: the _SAFE_REF regex should use \Z instead of $ (defense-in-depth), there's an unused monkeypatch fixture and ChunkId import in the tests, and the 30-second timeout test drags in CI. _resolve_commit_range could use its own unit tests instead of being tested only through deep mock chains.


Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md

@VakninAriel

Copy link
Copy Markdown
Collaborator Author

Review Addressed (ofriw second review)

All issues from the second review fixed in commit b51bbc71.

Critical

find_project_root(None) kills MCP server — Wrapped in try/except SystemExit in _inject_diff_service. Falls back to Path.cwd() when no project markers are found. Git walks up from CWD to find the repo root, so this is safe and the server no longer terminates.

Important

getattr fallback mismatch — Changed getattr(args, "vector_source", "both") → getattr(args, "vector_source", "diff") in both search.py and research.py. Now matches the argparse default — no more maintenance trap.

Minors

_SAFE_REF regex — Changed $ → \Z in runner.py. $ matches before a trailing newline in Python; \Z is strict end-of-string. Blocks "HEAD\n" from passing validation.

30-second timeout test drags CI — Extracted _GIT_DIFF_TIMEOUT_SECONDS = 30 constant in runner.py. test_timeout now monkeypatches it to 0.01 seconds — test completes in <1ms instead of 30s.

Unused monkeypatch fixture — Removed from all 6 integration test function signatures in test_deep_research_with_diff.py. Tests use unittest.mock.patch context managers, not the pytest fixture.

Unused ChunkId import — Removed from test_diff_aware_search_service.py.

@VakninAriel
VakninAriel requested a review from ofriw May 28, 2026 06:28

@ofriw ofriw 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.

Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


PR #288 — Git History Semantic Search: Human Review

Nice work on this one. The architecture is clean — the DiffAwareSearchService decorator pattern respects the existing service boundary, the git diff pipeline is properly isolated in its own module, and the security posture (subprocess exec, ref validation regex, timeout with kill) is solid. The test surface covers parser edge cases, runner safety, and the decorator's three vector-source modes. Review feedback from rounds 1-2 was folded in correctly (the _inject_diff_service extraction, logger.warning instead of silent pass, removed unrelated test).

You need to fix three things before I'd approve:

1. Language.GIT_DIFF breaks parser parametrized tests — Language.GIT_DIFF was added to the enum at common.py:210. Two tests in test_parsers.py (lines 189, 220) parametrize over all Language values except UNKNOWN, using [lang for lang in Language if lang != Language.UNKNOWN]. This now includes GIT_DIFF, which has no parser registered — factory.create_parser(GIT_DIFF) raises ValueError. The fix is to exclude GIT_DIFF from the parametrization comprehension (same pattern as UNKNOWN), since it's documented as in-memory-only and never derived from a file path.

2. "both" mode pagination is wrong — In DiffAwareSearchService.search_semantic(), the "both" branch hardcodes offset=0 for both sub-searches regardless of what the caller passes. The final result slice does merged_results[offset : offset + page_size], so the offset is applied post-merge instead of during sub-searches. This works correctly for page 1 but produces wrong pagination metadata (next_offset, has_more) for deeper pages, and wastes compute re-fetching from zero every time.

3. _SAFE_REF in runner.py allows git option injection — The regex ^[a-zA-Z0-9_.^~/:@{}-]+\Z matches --cached, so git diff --cached is valid input even though it changes semantic meaning from "diff between refs" to "staged vs HEAD." Either block -- prefixes or add an explicit staged: bool parameter if --cached is intentionally supported.

Minor things to clean up: align the vector_source defaults across CLI (two files still say "both" as fallback while the MCP tools and argparse default to "diff"), remove the unused N = len(self._diff_chunks) variable, and the dead else "both" fallback in _inject_diff_service. The force_strategy CLI path still bypasses search_impl and thus diff injection — the guard prevents misuse but the design gap is worth noting for a follow-up.


Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md

@VakninAriel

Copy link
Copy Markdown
Collaborator Author

Response to Round 4 Review (ofriw, c24380b)

All issues from the third AI agent review addressed in commit c24380b.

Critical fixes

1. parametrized tests — Already excluded in b51bbc7 (both test_parsers.py lines 188/219 have lang not in (Language.UNKNOWN, Language.GIT_DIFF)). 127 parser tests pass. No action needed.

2. --cached / option injection via _SAFE_REF — Added commit_range.startswith("-") guard in runner.py. The regex ^[a-zA-Z0-9_.^~/:@{}-]+\Z allows - chars so --cached, --staged, -p all previously passed validation. Now rejected before git diff is called. New test test_option_injection_rejected covers --cached, --staged, -p, --no-index.

3. "both" mode pagination accuracy — Replaced db_fetch = max(offset + page_size, page_size * 3) with max(offset + page_size, page_size * 20, 500). Old cap (e.g. 30 for page 1 with page_size=10) meant total and has_more were underestimated at deeper offsets. New floor of 500 matches MAX_DIFF_CHUNKS, keeping both sources balanced for accurate merged pagination.

Minor fixes

4. research.py vector_source default — Changed function signature default from "both" → "diff" (line 76) to match argparse default. Eliminates maintenance trap where removing argparse parser without updating the fallback would silently change behavior.

5. Unused N variable — Removed N = len(self._diff_chunks) in _search_diff (variable was never read).

6. Dead else "both" fallback — Replaced vs = vector_source if vector_source in (...) else "both" with an explicit raise ValueError(...) for invalid vector_source values. Invalid input now surfaces immediately rather than silently defaulting.

7. force_strategy bypass note — Added inline comment in search.py noting that the force_strategy path bypasses search_impl / diff injection, and that the existing guard (blocks --force-strategy with commit params) prevents misuse. Tracked for follow-up.

@VakninAriel
VakninAriel requested a review from ofriw May 31, 2026 06:14

@ofriw ofriw 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.

Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


This is close, but there are still two substantive correctness issues to fix before merge. The big one is repo selection for diff-scoped search: _inject_diff_service() currently runs git diff from find_project_root(None) and falls back to Path.cwd(). That means the diff is anchored to process cwd, not to the project actually backing services. In a normal single-repo flow that may appear fine, but in MCP / --db flows — and especially in the common workspace pattern where multiple repos are indexed under one root — the behavior is underdefined and can be wrong. The diff scope needs to be derived from the indexed repo, not rediscovered from cwd. If more than one repo is in scope, the feature needs an explicit repo selector instead of silently picking one.

The other blocker is that the latest both-mode pagination change is still heuristic rather than correct. DiffAwareSearchService.search_semantic() fetches only a bounded DB window (db_fetch = max(offset + page_size, page_size * 20, 500)) and then computes total / has_more from that truncated merged set. That means deeper pages can still underreport pagination metadata even though the code comments claim accuracy. There are also two smaller follow-ups worth fixing in the same pass: commit_hash -> <hash>^..<hash> breaks on a root commit, and the README still says --commit-hash means “from a specific commit to HEAD”, which no longer matches the implementation. The overall shape is good; what’s left is tightening the contract so the behavior is unambiguous and correct at the boundaries.


Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md

@VakninAriel

Copy link
Copy Markdown
Collaborator Author

Response to Round 5 Review (ofriw, c9b57ed)

All issues from the fifth review addressed in commit c9b57ed.

Blocker 1 — Repo selection in _inject_diff_service

Added _git_cwd_from_services(services) helper that derives the git repo root from services.provider.db_path via git -C <db_parent> rev-parse --show-toplevel. The diff is now anchored to the indexed project, not the process cwd. Falls back to find_project_root(None) → Path.cwd() only when the git lookup itself fails (e.g. DB on a non-git filesystem).

Blocker 2 — "both" mode pagination accuracy

Replaced the heuristic db_fetch = max(offset + page_size, page_size * 20, 500) formula with a constant _MAX_BOTH_DB_FETCH = 10_000. The old offset-dependent formula still underreported total/has_more at deeper pages. The fixed cap exceeds any realistic HNSW top-K result set so merged pagination metadata is exact for all practical corpora.

Minor — Root commit crash

run_git_diff() now detects the <hash>^..<hash> pattern failing with "unknown revision" (root commit has no parent) and auto-retries using the git empty-tree SHA (4b825dc642cb6eb9a060e54bf8d69288fbee4904) as the base. Three new tests cover the retry path, double-failure, and non-root-failure non-retry.

Minor — README --commit-hash semantics

Updated comment from # From a specific commit to HEAD to # Changes introduced by that commit (diff against its parent; root commits use empty tree).

@VakninAriel
VakninAriel requested a review from ofriw May 31, 2026 15:03

@ofriw ofriw 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.

Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


Ariel — this is in good shape. The decorator pattern, the runner/parser split, the tests across all three modes — solid work. You've been responsive through all five review rounds and the major blockers (the silent except, the copy-paste injection block, the find_project_root crash, the Language.GIT_DIFF test breakage) are all handled correctly.

Three things still need to be addressed before merging. First, database_factory.py:167 casts SearchServiceProtocol to SearchService — this suppresses actual type errors instead of fixing them. The right fix is to change Database.__init__ to accept SearchServiceProtocol, then drop the cast. Second, runner.py:16 passes the commit range to git diff without a -- separator. The option-injection guards (startswith("-"), allowlist regex) block known attack vectors, but the missing -- is a defense-in-depth gap that should be closed. Third, DiffAwareSearchService.search_hybrid delegates to self._original.search_hybrid(), which internally calls original.search_semantic() — completely bypassing diff awareness. Anyone using hybrid search with commit params gets the DB-only results, silently.

Less pressing but worth fixing: the "both" mode always fetches DB results from offset=0 regardless of the caller's pagination (wasteful for deep pages), diff result dicts have different fields than DB result dicts (visible to consumers depending on vector_source), and there's no automatic guard against SearchServiceProtocol drifting from SearchService — a test that asserts isinstance(SearchService(), SearchServiceProtocol) would catch that. The test_timeout in test_git_diff_runner.py uses a 10ms timeout that's tight for CI. Everything else is minor.


Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md

@VakninAriel

Copy link
Copy Markdown
Collaborator Author

Round-6 fixes (commit d0f2116)

Addressing all blockers and medium issues from the latest review:

Critical blockers

1. Cast suppression removed
Database.__init__ now accepts SearchServiceProtocol | None instead of SearchService | None. The cast("SearchService", ...) in database_factory.py is gone — no more type suppression.

2. -- separator added to git diff calls
Both create_subprocess_exec calls in runner.py now pass "--" after the commit range, adding the defense-in-depth gap the review flagged. Applies to both the primary call and the root-commit empty-tree retry.

3. search_hybrid is now diff-aware
DiffAwareSearchService.search_hybrid() no longer delegates to self._original.search_hybrid(). It now calls self.search_semantic() (the overridden diff-aware version), then optionally self.search_regex_async() if a pattern is given, and merges via ResultEnhancer — matching SearchService.search_hybrid logic but routing semantic through the decorator.

Medium issues

4. Protocol drift guard added
New test test_search_service_satisfies_protocol asserts isinstance(SearchService(MagicMock()), SearchServiceProtocol). Catches future drift at unit-test time.

5. Timeout raised 10ms → 500ms
test_timeout in test_git_diff_runner.py now patches _GIT_DIFF_TIMEOUT_SECONDS = 0.5. SlowProcess still sleeps forever so correctness is unchanged; just less flaky on slow CI runners.

All 26 affected unit tests pass.

@VakninAriel
VakninAriel requested a review from ofriw June 1, 2026 11:05

@ofriw ofriw 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.

Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


This is close to mergable. The architecture is clearly settled and the review-fix loop has tightened the code considerably. There's one blocking observability issue and a handful of minor things worth fixing in the same pass before this ships.

The MAX_DIFF_CHUNKS=500 cap is a reasonable OOM guard, but when it triggers the warning goes to loguru stderr — invisible to any MCP client (Cursor, Claude Desktop, etc.). An LLM calling search or code_research with a large commit range gets silently truncated results and may confidently conclude certain code doesn't exist in the diff. This needs to surface in the tool response itself, not just server logs.

On the runner side: the _SINGLE_COMMIT_RANGE_RE regex will skip the empty-tree retry for root commits if the hash uses uppercase hex — git outputs lowercase by default but accepts both. The regex also needs A-F and the upper bound bumped to cover SHA256 (64 chars). While you're there, add await proc.wait() after both proc.kill() calls in the timeout handlers — zombie git processes accumulate on the timeout path. There's also a blocking subprocess.run in _git_cwd_from_services that'll stall the event loop for up to 5 seconds in MCP context; swapping it to asyncio.create_subprocess_exec keeps the codebase consistent and avoids the problem entirely.

The B3 distance-to-similarity conversion works for all current providers (DuckDB, LanceDB both use cosine) and is effectively dead code since those providers already emit similarity/score keys upstream. Leave it as a safety net but note the cosine-dependency. And on the service side, typing _original as SearchServiceProtocol instead of Any lets you drop three type: ignore[no-any-return] comments and gives mypy proper coverage of the delegation layer.

Everything else is solid. The decorator pattern, the three vector-source modes, the pagination accuracy, the root-commit retry — all looking good.


Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md

@VakninAriel
VakninAriel requested a review from ofriw June 2, 2026 10:47
VakninAriel and others added 16 commits June 7, 2026 12:54
- fix pagination total: _search_diff returned raw N instead of
  total_after_filter, breaking has_more / next_offset after path_filter
- move diff injection after embedding-manager validation in search_impl
  so provider-missing error surfaces correctly
- skip injection when vector_source="db" to avoid needless git+embed work
- use SearchServiceProtocol in DatabaseServices instead of concrete union
- commit_hash now expands to hash^..hash (single commit diff, not ..HEAD)
- default vector_source changed to "diff" for commit-scoped operations
- runner.py: guard against ../ path traversal in commit ranges
- update integration test assertions to match new commit_hash expansion

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…iff_service

- wrap embed_texts call in asyncio.wait_for(_EMBED_TIMEOUT_SECONDS=120)
  so large diff batches with slow providers fail fast with a clear message
  instead of hanging indefinitely
- add comment explaining why imports are local (avoid circular dependency)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The astral-sh/setup-uv action archive is consistently unavailable for
download from codeload.github.com in this org context. pip install uv
is cross-platform and avoids the external action dependency entirely.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ontract test

- Rename ci.yml → smoke-tests.yml to match the filename the contract test
  expects (.github/workflows/smoke-tests.yml is hardcoded in test parametrize)
- Delete smoke-tests.yml.bak and minimal.yml (cleanup)
- Update test_deploy_job_contract: expected concurrency group was stale
  ('pages' → 'ch-test-deploy', changed in commit 34265ed to avoid
  GitHub Pages reserved concurrency group collision)

All 26 workflow contract tests now pass.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Previous CI run used stale pull/288/merge ref (pre-computed before
smoke-tests.yml rename fix). Empty commit triggers new merge ref.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
upstream/main renamed smoke-tests.yml → ci.yml and restructured the
deploy pipeline. This branch diverged from that evolution, causing a
modify/delete conflict in the merge commit that left the test file
referencing ci.yml while the workflow file was smoke-tests.yml.

Changes:
- Add ci.yml from upstream/main (includes deploy.yml integration)
- Add minimal.yml from upstream/main
- Delete smoke-tests.yml (superseded by ci.yml on main)
- Restore test_docs_version_workflow_contract.py to upstream/main version
  (references ci.yml, not smoke-tests.yml)
- Restore test_verify_watchman_live_indexing_e2e.py to upstream/main

The feature code (git-diff search) is unaffected.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Wrap find_project_root(None) in try/except SystemExit in
  _inject_diff_service; falls back to Path.cwd() so MCP server
  doesn't sys.exit(1) when CWD has no project markers
- Fix getattr fallback for vector_source from 'both' to 'diff' in
  search.py and research.py to match argparse default
- Change _SAFE_REF regex $ to \Z for strict end-of-string match
  (blocks 'HEAD\n' passing validation)
- Extract _GIT_DIFF_TIMEOUT_SECONDS constant in runner.py; test
  monkeypatches it to 0.01s so test_timeout runs in <1ms not 30s
- Remove unused monkeypatch fixture from 6 integration test functions
- Remove unused ChunkId import from test_diff_aware_search_service.py

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Critical:
- Block git option injection (--cached, --staged, etc.): add
  commit_range.startswith('-') guard in runner.py; test added
- Fix 'both' mode pagination accuracy: increase db_fetch from
  page_size*3 to max(offset+page_size, page_size*20, 500) so
  merged total/has_more are correct at deeper offsets

Minor:
- Remove unused N = len(self._diff_chunks) in _search_diff
- Fix research.py vector_source default 'both' -> 'diff' (matches
  argparse default, eliminates maintenance trap)
- Replace dead else-'both' fallback in _inject_diff_service with
  explicit ValueError for invalid vector_source values
- Add comment in search.py noting force_strategy bypass of
  diff injection (tracked for follow-up)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Blocker 1 — repo selection in _inject_diff_service
  Add _git_cwd_from_services() that derives git cwd from
  services.provider.db_path via 'git -C <db_parent> rev-parse
  --show-toplevel'.  Falls back to find_project_root(None) → Path.cwd()
  only when the git lookup itself fails.  Eliminates the process-cwd
  anchor that breaks MCP/--db flows and multi-repo workspaces.

Blocker 2 — 'both' mode pagination accuracy
  Replace heuristic db_fetch formula (max(offset+page_size, page_size*20,
  500)) with constant _MAX_BOTH_DB_FETCH = 10_000.  The old formula left
  total/has_more underreported at deeper offsets; the fixed cap exceeds
  any realistic HNSW top-K result set so merged pagination is exact for
  all practical corpora.

Minor — root commit crash
  run_git_diff() now detects the <hash>^..<hash> pattern failing with
  'unknown revision' (root commit has no parent) and auto-retries using
  the git empty-tree SHA (4b825dc...) as the base.  Three new tests cover
  the retry path, double-failure, and non-root-failure non-retry.

Minor — README --commit-hash semantics
  Update comment from 'From a specific commit to HEAD' to 'Changes
  introduced by that commit (diff against its parent; root commits use
  empty tree)'.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Fix cast suppression: widen Database.__init__ search_service param to
  SearchServiceProtocol, drop cast() in database_factory.py
- Add -- separator after commit_range in git diff subprocess calls
  (defense-in-depth; both primary and root-commit retry paths)
- Override search_hybrid in DiffAwareSearchService to call
  self.search_semantic() instead of self._original.search_hybrid(),
  so hybrid search with commit params is diff-aware
- Add test asserting SearchService satisfies SearchServiceProtocol
  to catch interface drift at test time
- Raise test_timeout threshold from 10ms to 500ms to reduce CI flakiness
- runner.py: _SINGLE_COMMIT_RANGE_RE now accepts uppercase hex and up to
  64 chars (SHA256); root-commit empty-tree retry was silently skipped for
  uppercase hashes
- runner.py: await proc.wait() after both proc.kill() calls to prevent
  zombie git processes on timeout path
- tools.py: _git_cwd_from_services converted from sync def + blocking
  subprocess.run to async def + asyncio.create_subprocess_exec, avoiding
  up-to-5s event-loop stalls in MCP context
- tools.py: _inject_diff_service now returns tuple[DatabaseServices, str|None];
  truncation warning surfaced in search_impl response (warnings key) and
  prepended to deep_research_impl result so MCP clients see capped-results
  notice instead of silently missing diff coverage
- diff_aware_search_service.py: _original typed as SearchServiceProtocol
  instead of Any; drops three type: ignore[no-any-return] suppressions
- diff_aware_search_service.py: B3 block comment notes cosine-dependency
  and dead-code status for future providers
- test_git_diff_runner.py: SlowProcess mock gains async wait() method

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Daemon is detached (start_new_session=True) and runs _graceful_shutdown
after the proxy exits. The proxy can exit before the daemon finishes
cleanup, leaving the lock file visible. Poll up to 15s for the daemon
to remove its own lock before asserting it's gone.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Surface MAX_DIFF_CHUNKS truncation warning in execute_tool search path
(was silently dropped; deep_research_impl already handled it). Pipe
warnings from result dict into prepended blockquote in markdown output.

Also: remove redundant `import asyncio as _asyncio` in _inject_diff_service
(stdlib already imported at module top), move vector_source validation
before run_git_diff+embedding, add warnings field to SearchResponse TypedDict,
mirror DB layer path_filter security validation in _search_diff, and log
swallowed exception in _git_cwd_from_services.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- deep_research_impl truncation path mutates result["answer"] in-place
  instead of replacing the dict with a str; execute_tool() dict branch
  now works correctly on the warning path
- parse_diff_to_chunks split fragments use start_line = hunk_start+(n-1)
  so each fragment has a unique (file_path, start_line) key and survives
  both-mode dedup without silent loss
- regression tests for both failure modes

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@VakninAriel
VakninAriel force-pushed the feat/git-diff-search branch from bb317ca to a0af971 Compare June 7, 2026 09:58

@ofriw ofriw 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.

Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


This is close, and the review history has clearly tightened the implementation around the right risks. I still see two correctness issues worth addressing before merge. First, diff chunks returned by DiffAwareSearchService._chunk_to_dict() do not carry chunk_id or id, but ResultEnhancer.combine_search_results() only keeps hybrid-search entries with one of those identifiers. That means the diff-aware search_hybrid() path reaches the right semantic search override, then silently drops the diff results during combination. The practical blast radius is narrower than normal CLI/MCP semantic search because hybrid search is not exposed as a public search mode today, but the service contract is still wrong and needs a regression test that proves diff chunks survive hybrid merge.

Second, oversized diff-hunk splitting currently assigns fragment line refs from fragment ordinal (hunk_start + part_index) rather than from the actual diff lines represented by the fragment. That keeps dedupe keys unique, but it can fabricate line numbers for split single-line hunks and overstate ranges for multi-line hunks. Since CLI/MCP render start_line/end_line directly, this is user-visible: agents and users can be pointed at nonexistent or misleading locations. Please change splitting to preserve real represented line metadata, then replace the uniqueness-only parser test with line-accuracy contract tests, make the mislabeled split-fragment test actually run vector_source="both", and add direct search_impl(..., commit_range=...) coverage. Minor cleanup: remove the dead imports, warn or reject --regex + --commit-*, and surface search_impl warnings in CLI output.


Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md

- Add chunk_id field to _chunk_to_dict() so diff chunks survive
  ResultEnhancer.combine_search_results() in search_hybrid() path
- Fix split-hunk line numbers: track real new-file line offsets
  (counting + and context lines) instead of ordinal part index
- Fix test_split_hunk_fragments_survive_both_mode_dedup to use
  vector_source="both" and exercise the actual merge path
- Add test_diff_chunks_survive_hybrid_merge regression test
- Add test_split_fragment_start_lines_reflect_actual_diff_lines
  to contract-test line accuracy, not just uniqueness
- Warn CLI users when --regex is combined with --commit-* flags
- Surface search_impl truncation warnings in CLI output
- Remove dead imports from three test files

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@VakninAriel
VakninAriel requested a review from ofriw June 8, 2026 05:51

@ofriw ofriw 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.

Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


This is very close, and the remaining issues are both in the oversized-hunk split path. In chunkhound/core/git_diff/parser.py, the fix for split fragment line mapping improved the normal multi-line case, but the single-overlong-line case is still wrong: each char-split fragment inherits the same start_line (parser.py:72-77), and later merge/dedupe logic treats (file_path, start_line) as identity (chunkhound/services/diff_aware_search_service.py:299-306; diff chunk_id is also derived from file_path:start_line at diff_aware_search_service.py:112-129). In practice that means large one-line diffs like minified JS/SVG/JSON can silently lose fragments in both/hybrid flows. Separately, split fragments still report end_line=max(part_start, hunk_end) (parser.py:91-97), so each fragment claims the tail of the full hunk rather than the lines it actually represents; that makes the line refs shown to users/agents misleading.

What needs to change is to separate fragment identity from displayed line metadata. The parser should emit true represented start_line/end_line for each fragment, including the single-line oversized case, and diff result identity should not rely on start_line uniqueness. The current tests don’t lock this down yet: tests/unit/test_git_diff_parser.py:239-252 only checks that a long single line splits, not that the resulting line refs are correct, and tests/unit/test_diff_aware_search_service.py:223-244 uses hand-made fragments with already-distinct start_lines, so it doesn’t protect against the parser bug. I’d tighten those contracts before merge with parser tests for real per-fragment line ranges and a merge-path regression proving split single-line fragments survive both/hybrid result combination.


Attached is an agent optimized description of the changes in this PR - AGENT_REVIEW.md

VakninAriel and others added 2 commits June 8, 2026 14:00
- parser: emit per-fragment end_line using part_line_end_offsets
  (part_line_starts[N+1] for intermediate parts, running_line for last),
  so intermediate split fragments no longer claim the full hunk tail
- diff_aware_search_service: include symbol in chunk_id for uniqueness;
  both-mode dedup keys on chunk_id for diff results so char-split
  fragments sharing the same start_line all survive, while DB results
  at the same location are still dropped in favour of the diff result
- tests: 4 new parser tests covering single-line fragment line accuracy
  and multi-line split contiguity; 2 new service tests proving same-line
  split fragments survive both-mode dedup and hybrid merge

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- parser: guard accumulation flush on running_line > part_line_offset so
  non-advancing lines (the @@ header) are never flushed as a standalone
  part — eliminates the case where two consecutive fragments both inherit
  start_line = hunk_start
- diff_aware_search_service: replace mixed-type seen_ids dedup with an
  explicit two-pass approach (typed set[str] for diff chunk_ids, typed
  set[tuple] for DB locations); removes the fragile startswith("diff:")
  discriminator entirely
- tests: update test_multi_line_split_intermediate_fragments docstring
  to reflect the guard fix, add start_line contiguity assertions; fix
  comment in test_split_fragments_cover_full_hunk_range_contiguously
  (header is 24 chars, not ≈27)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@VakninAriel
VakninAriel requested a review from ofriw June 9, 2026 10:29

@ofriw ofriw 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.

LGTM

@HananKavitzAmat
HananKavitzAmat added this pull request to the merge queue Jun 9, 2026
Merged via the queue into chunkhound:main with commit e0c0d35 Jun 9, 2026
17 checks passed
huangyingting pushed a commit to repomesh/chunkhound that referenced this pull request Nov 11, 2026
…nd#407)

* ci: split test suite into 3 parallel groups per OS

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.

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

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]>

* fix(search): namespace transient cache and stream web pages

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]>

* review-fix(iter-1): make transient streams replayable and pagination exact

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

* review-fix(iter-2): propagate stream failures and page hybrid results

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

* review-fix(iter-3): stabilize hybrid ranking across pages

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

* review-fix(iter-4): fuse complete hybrid result snapshots

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

* fix(search): freeze hybrid source snapshots

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

* fix(websearch): provide research progress event interface

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

* fix(search): bound transient cache memory and keep both-mode total numeric

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]>

* fix(git-diff): scope the diff timeout to git, not the embedding consumer

`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]>

* docs: add unified_search PR description

Capture the branch summary so the upcoming PR can reuse it after the main merge.

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

* fix(search): cap transient search pagination window to bound heap memory

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.

* fix(native): bound git-diff stderr memory and stop truncating long diff 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.

* fix(search): reintroduce a wall-clock circuit breaker for transient search

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.

* fix(search): cap fetched web page body size to bound websearch memory

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.

* fix(test): match _FakeResponse.read() signature to real HTTPResponse.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.

* fix(search): stop both-mode candidate pool from growing with offset

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]>

* docs(changelog): add 6.1.0 release notes

* feat(search): env settings for transient vector cache and overfetch; drop stale _quickresearch refs

* fix: address unified search review findings

* fix(search): keep websearch stdout clean; both-mode uses overfetch heaps

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.

* fix(websearch): split discovery vs research timeout budget

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.

* fix(research): synthesize git history from diff evidence

* fix(websearch): report total fetch failure before research

* fix(websearch): keep CLI progress off stdout

* fix(websearch): bound Chrome page body memory

* fix(search): merge DB semantics in hybrid both mode

* fix(search): keep diff regex research isolated

* perf(research): batch transient query expansion

* fix(research): propagate transient bulk search failures

* fix(research): preserve web source URLs in citations

* fix(git): buffer diff reads before parsing lines

* fix(search): isolate vector cache embedding spaces

* fix(search): bound both-mode pagination results

* fix(search): preserve transient regex ranking credit

* fix(search): isolate transient cache by provider endpoint

* fix(search): unify transient and database ranking

* fix(research): preserve mixed source provenance

* fix(git): stream diff chunks with bounded memory

* fix(git): resolve empty tree for repository format

* fix(websearch): keep CLI diagnostics on stderr

* fix(websearch): stop discovery after cancellation

* fix(git): preserve deletion-heavy diff chunks

* fix(search): isolate transient embedding spaces

* fix(git): preserve quoted diff paths

* fix(search): reject unsupported both-mode offsets

* fix(embeddings): reject incomplete provider responses

* fix(websearch): isolate bounded PDF parsing

* fix(research): label mixed revision evidence

* fix(search): honor transient result limits

* fix(websearch): keep PDF worker output off MCP stdio

The spawned PDF parser inherits fd 1, which is the JSON-RPC channel under
'chunkhound mcp' stdio. MuPDF writes diagnostics for malformed PDFs
directly to fd 1, so redirect it to stderr inside the worker.

* fix(search): only advertise both-mode next_offset inside the candidate window

_pagination capped has_more by the 2000-hit diff/web window, but both-mode
rejects any page beyond its smaller candidate window
(min(max(page_size * overfetch, 50), 2000)). When page_size did not divide
that window (e.g. 3 or 7), the last in-window page advertised a next_offset
that the next call rejected with ValueError. search_semantic_many lacked the
window check entirely and returned a silent empty page.

Share one window check between both entry points and cap has_more by it.

* fix(git-diff): discard pure-deletion hunk bodies without buffering

A hunk with a zero new-side count (+N,0) returned without entering hunk
state, so its '-' body lines were buffered as metadata. A deleted line
longer than 1 MiB (e.g. a removed minified bundle) then tripped the
metadata safety limit and aborted the whole diff search. Skip such hunks
until the next '@@' or 'diff --git' boundary, discarding partial lines
as they stream.

* fix(git-diff): make chunk boundaries independent of read splits

feed() streamed any partial body line into the draft whenever a read
fragment ended mid-line, even when the full line would fit in one chunk.
The same diff could therefore produce different chunk text depending on
pipe read boundaries, changing results between runs and defeating the
text-keyed vector cache. Only stream a partial line once it already
exceeds max_chunk_chars, which keeps memory bounded by the same limit.

* fix(search): share path_filter semantics between DB and transient search

Transient (diff/web) search appended '/' to every filter and matched by
prefix, so file filters like src/foo.py returned nothing and nested
directory filters disagreed with DuckDB's '%/dir/%' matching in
vector_source=both. Extract the DuckDB normalizer to
chunkhound/utils/path_filter.py and add a Python matcher mirroring the
LIKE semantics; both sources now use it.

* fix(websearch): use matched chunk text as web research evidence

Large web sources (>16k chars) were re-sliced from the stored page text by
chunk line numbers. PDF text is stored as the concatenated chunk bodies
without separators and without sub-50-char paragraphs the parser still
counts, so line ranges pointed at the wrong text or past the end; evidence
was misattributed or silently dropped (42/61 chunks on the CAST fixture).

Mark web search results as authoritative source, as git-diff research
already does, so synthesis receives each hit's exact text.

* fix(websearch): drop unreplayable web sources instead of failing research

Evicted pages are refetched on demand. A failed refetch, changed content,
or an unparseable replay raised a sticky error that failed the whole run,
which is common for dynamic pages and large pages that never fit the
source cache.

Drop that source for the rest of the session with a 'Dropped from
research' fetch warning; revisions are still never mixed. Research fails
only if every usable source is dropped.

* refactor(search): remove test-only transient search APIs

stream_git_diff_file_blocks, DiffAwareSearchService (with
_PreloadedVectorCache, which bypassed embedding-space cache namespacing)
and pages_to_chunks had no production callers, so their tests exercised
code users never run.

Delete them and migrate the tests to the production paths:
stream_git_diff_fragments/stream_diff_to_chunks, TransientSearchService
(tests/unit/test_transient_diff_search.py), and research_web_pages.
Shared fixtures move to tests/unit/transient_search_helpers.py.

* perf(search): send full embedding batches during transient search

Each 100-chunk stream batch embedded its own cache misses, so path
filters and partial cache hits produced many tiny embedding requests,
violating the min-100 batching rule.

A shared _vectorized_batches helper assigns source-order ordinals on
arrival, scores cache hits immediately, and queues misses (chunks only,
no vectors) across stream batches until min(100, provider document
limit) can be sent, plus one final partial request. Ranking, tie order,
and the live-vector memory bound are unchanged. Provider responses with
a mismatched vector count now fail explicitly.

* Adapt SSRF tests to streaming websearch fetch

* Opt local-server page-size tests out of SSRF validation

* Address review: stdin=DEVNULL, changelog removals, cache docs; drop stale PR doc

* fix(websearch): count shared strings once in source cache budget

* fix(websearch): validate total timeout and document new budget semantics

Reject non-positive/non-finite CHUNKHOUND_WEBSEARCH_TIMEOUT_SECONDS
(fall back to 600) and note in changelog/docs that it now bounds the
whole websearch call, not just research.

* Merge main into unified_search

* Fix tests: mock embed_query_texts

* fix(search): address PR review majors

- treat PDF worker exit without result as per-page failure
- surface per-page fetch failures on websearch error paths
- replace transient search assert with clamp; base has_more on retained pool

* fix(websearch): only report budget timeout when the deadline elapsed

* fix(search): validate transient regex and scan off the event loop

* fix(embeddings): isolate truncation cache spaces

* fix(search): reject deep both-mode regex offsets

* fix(websearch): bound discovery cancellation cleanup

* fix(websearch): distinguish provider timeouts in CLI

* fix(websearch): account for retained source metadata

* fix(git): preserve arbitrary path bytes

* fix(research): qualify historical citations by revision

* fix(websearch): enforce timeout during page cleanup

* fix(search): continue diff pagination past retained pool

* fix(git-diff): anchor trailing deletion fragments

* fix(mcp): preserve search pagination when truncating

* fix(websearch): return promptly after deadline

* fix(websearch): bound PDF worker startup

* fix(search): enforce transient regex timeout

* docs(websearch): clarify timeout response deadline

* fix(search): preserve diff ownership beyond retained candidates

* fix(research): exclude withdrawn web sources from evidence

* fix(research): isolate current source read failures

* fix(search): batch expanded query embeddings

* fix(git-diff): preserve oversized line ranges

* fix(search): cancel stalled snapshots on stream failure

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Hanan Kavitz <[email protected]>
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.

3 participants