XMem icon indicating copy to clipboard operation
XMem copied to clipboard

Add raw search fast path with code domain support

Open michael-schvarcz opened this issue 6 months ago • 6 comments

Addresses #163.

This adds a low-latency raw search path that returns ranked memory hits without the agentic LLM planning/synthesis round, while keeping answer generation optional through answer=true.

What changed:

  • Adds RetrievalPipeline.raw_search for direct profile, temporal, summary, and snippet retrieval without tool selection.
  • Extends /v1/memory/search to optionally include code hits by querying the existing code retrieval pipeline's native symbol/file search tools.
  • Adds answer=true synthesis after raw hits are collected, without a second planning step.
  • Caches profile catalogs and agentic retrieval plans.
  • Tracks bounded p50/p95/p99 latency snapshots by retrieval mode.
  • Adds tests proving raw search bypasses LLM tool planning, answer mode only synthesizes after hits, and cached plans are reused.

Compared with the currently open #173, this implementation also wires the requested code domain into the raw search endpoint.

Validation:

.venv/bin/python -m pytest tests/integration/test_retrieval_pipeline.py tests/api/test_dependencies_and_routes.py -q
9 passed

git diff --check
passed

michael-schvarcz avatar May 11 '26 18:05 michael-schvarcz

Updated this PR to address the review points:

  • Normalizes missing source scores through a shared helper before API serialization.
  • Keeps raw memory search resilient when one requested backend fails by using asyncio.gather(..., return_exceptions=True) and returning healthy domain results.
  • The current head already uses bounded LRU-style caches, public answer_from_sources / confidence_from_sources helpers, and the shared confidence multiplier.

Validation: .venv/bin/python -m pytest tests/integration/test_retrieval_pipeline.py tests/api/test_dependencies_and_routes.py -> 9 passed.

michael-schvarcz avatar May 12 '26 13:05 michael-schvarcz

Fixed the remaining missing-score edge case in _format_tool_results() by normalizing None to 0.0 before score comparison/formatting, so answer=true no longer crashes before API serialization.

Added regression coverage for answer_from_sources() with SourceRecord(score=None).

Validation:

.venv/bin/python -m pytest tests/integration/test_retrieval_pipeline.py tests/api/test_dependencies_and_routes.py -q
# 10 passed
git diff --check

michael-schvarcz avatar May 13 '26 13:05 michael-schvarcz

One score-hardening gap still remains after 89fe3e4. _score_value() only maps None to 0.0:

def _score_value(score: float | None) -> float:
    return round(score, 3) if score is not None else 0.0

If any vector/code backend returns a non-finite float (nan or inf), round(score, 3) preserves that non-finite value. The /v1/memory/search path then places it into SearchResponse.results[*].score, and _wrap() passes body.model_dump() into JSONResponse. Starlette JSON responses reject non-finite floats, so raw search can still fail at response rendering even though the missing-score case is covered.

This also affects retrieve_memory() because it uses the same helper for result.sources. A small float(...) + math.isfinite(...) coercion before rounding would close both paths.

nagiexplorer88 avatar May 14 '26 01:05 nagiexplorer88

Greptile Summary

This PR adds a low-latency raw_search fast path to the retrieval pipeline and extends /v1/memory/search to support an optional code domain, answer=true synthesis, and cross-domain result merging, all without an LLM planning round.

  • RetrievalPipeline.raw_search: fans out profile, temporal, summary, and snippet lookups concurrently, ranks results, and optionally synthesises an answer — bypassing the agentic tool-planning step entirely.
  • /v1/memory/search rewrite: delegates to raw_search for memory domains, then appends code hits via code_pipeline._execute_tool (search_symbols + search_files in parallel); the merged list is sorted and optionally answered before being returned.
  • Caching additions: profile catalogs are LRU-cached with a 300-second TTL; retrieval plans are LRU-cached with no TTL, so they survive indefinitely until evicted by capacity pressure.

Confidence Score: 5/5

Safe to merge — the new fast path is well-isolated from the existing agentic pipeline and the test suite validates the bypass, answer synthesis, and plan-cache reuse scenarios.

All findings are non-blocking style/hardening nits that were already flagged in prior review rounds. No logic defects were found in the new raw_search path, the code-domain wiring, or the caching logic.

No files require special attention beyond the items already noted in previous review comments.

Important Files Changed

Filename Overview
src/pipelines/retrieval.py Adds raw_search fast path, profile catalog LRU caching, retrieval plan caching (no TTL), latency tracking, and several helper methods; _rank_sources still uses score-or-None pattern instead of the new _finite_score helper for NaN-safety
src/api/routes/memory.py Rewrites search_memory to use raw_search + optional code domain; adds _score_value NaN-safe helper but uses s.score or 0.0 (not _score_value) for the final cross-domain sort; includes aggregate latency_snapshot in per-request response
src/api/schemas.py Adds answer, org_id, repo fields and code domain support to SearchRequest; strip_search_query validator runs in default (post-constraint) mode, allowing a single-space query to be stripped to an empty string after passing min_length=1
tests/integration/test_retrieval_pipeline.py Adds four focused integration tests covering raw_search without LLM planning, answer synthesis, non-finite score handling, and retrieval plan cache reuse; coverage is consistent with the new feature surface

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[POST /v1/memory/search] --> B{code in domains?}
    B -- yes, no org_id --> C[400 Error]
    B -- yes, with org_id --> D[raw_search memory domains]
    B -- no --> D
    D --> E[profile/temporal/summary/snippet]
    E -- profile --> F[_search_profile_catalog cached 300s LRU]
    E -- temporal/summary/snippet --> G[asyncio.gather with return_exceptions]
    F --> H[merge sources]
    G --> H
    H --> I{code in domains?}
    I -- yes --> J[code_pipeline._execute_tool search_symbols + search_files]
    J --> K[extend records]
    I -- no --> L[sort by score]
    K --> L
    L --> M{answer=true?}
    M -- yes --> N[answer_from_sources LLM synthesis]
    M -- no --> O[build SearchResponse]
    N --> O

Reviews (2): Last reviewed commit: "Merge branch 'codex/raw-search-fast-path..." | Re-trigger Greptile

greptile-apps avatar May 23 '26 09:05 greptile-apps

Comments Outside Diff (5)

  1. src/api/routes/memory.py, line 760-776 (link)

    Cross-user latency telemetry in API response. pipeline is a singleton shared across all users, so latency_snapshot() returns aggregate p50/p95/p99 statistics accumulated from every request by every user. Including this in the per-request SearchResponse leaks system-wide load patterns to any API caller — e.g., a client could fingerprint how busy the service is based on changing percentiles.

  2. src/pipelines/retrieval.py, line 413-421 (link)

    Retrieval plan cache has no TTL. Unlike _profile_catalog_cache (300 s expiry), entries in _retrieval_plan_cache survive until LRU eviction. If the underlying model is swapped or tool schemas change between deployments, repeated identical queries (same user + query + catalog text) will keep executing the old tool plan indefinitely without ever re-asking the LLM.

  3. src/pipelines/retrieval.py, line 434-439 (link)

    Non-finite scores pass through the sort key unchanged. float('nan') is truthy in Python, so source.score if source.score is not None else 0.0 keeps nan intact. Python's TimSort produces implementation-defined (and potentially wrong) ordering when keys contain nan. float('inf') from code search results would always sort first. The _finite_score helper already exists for exactly this case.

  4. src/api/routes/memory.py, line 745 (link)

    The route-level sort uses s.score or 0.0, which does not sanitize float('nan') — nan is truthy, so nan or 0.0 returns nan. This is the same ordering hazard as in _rank_sources, and only affects code-search results since memory results are already sorted by _rank_sources before being merged here.

  5. src/api/schemas.py, line 191-194 (link)

    The strip_search_query validator runs after Pydantic's built-in constraint checks (including min_length=1), so a query of " " (one space) passes the length check and is then reduced to "". An empty string then reaches vector store embedding calls, which may error or return semantically useless results. The fix is to strip before the length constraint fires.

greptile-apps avatar May 23 '26 09:05 greptile-apps

@michael-schvarcz i see merge conflicts

ishaanxgupta avatar May 27 '26 05:05 ishaanxgupta