XMem icon indicating copy to clipboard operation
XMem copied to clipboard

Add low-latency raw memory search

Open strongkeep-debug opened this issue 6 months ago • 15 comments

Addresses #163.

This PR turns memory search into a true low-latency path. Raw search now goes through RetrievalPipeline.search_raw and returns ranked profile, temporal, summary, snippet, and code annotation hits without retrieval-plan tool selection. answer=true synthesizes from those already-fetched hits when a caller wants a generated answer, and the root /search alias is wired for clients that need the shorter path.

Area Change Evidence
Raw retrieval Selected domains are searched directly and ranked by score, including the code annotation domain requested by the issue. test_raw_search_returns_ranked_hits_without_tool_selection confirms no tool-selection call is made and verifies a code hit keeps file and symbol metadata.
API contract /v1/memory/search accepts code in the domain list and includes it in the default raw search domain set. test_memory_search_route_accepts_code_domain covers the request validator and serialized response shape.
Optional answer answer=true synthesizes from collected raw hits without doing agentic retrieval planning first. test_root_search_alias_can_synthesize_answer covers the alias and answer mode.
Caching and latency Profile catalogs and retrieval plans are cached for the agentic path, and bounded p50/p95/p99 latency snapshots are recorded for raw, answer, and agentic modes. test_retrieval_pipeline_caches_catalog_and_retrieval_plan covers cache reuse.
Robustness Raw search now normalizes missing/non-finite backend scores and keeps healthy domain results when another requested domain fails. test_raw_search_skips_failed_domains_and_normalizes_scores and the API route regression cover both pipeline and serialization behavior.

Validation was run locally:

.\.venv\Scripts\python.exe -m pytest -q
50 passed

.\.venv\Scripts\python.exe -m pytest tests\integration\test_retrieval_pipeline.py tests\api\test_memory_search_routes.py -q
12 passed

.\.venv\Scripts\python.exe -m ruff check src\pipelines\retrieval.py src\api\routes\memory.py tests\integration\test_retrieval_pipeline.py tests\api\test_memory_search_routes.py
All checks passed!

git diff --check
passed

strongkeep-debug avatar May 11 '26 18:05 strongkeep-debug

Follow-up after the latest push at that time: 5548b63 included the requested code domain in the raw search path, preserved repository/file/symbol/type/severity metadata, and hardened raw search against missing or non-finite backend scores. It also kept healthy domain results if another requested domain failed.

The earlier performance review items were addressed in the same branch: raw domain searches run concurrently, profile catalog lookup is async, and both caches are bounded with hashed plan keys. Local verification at that point was 50 passed for the full suite, 12 passed for the targeted retrieval/API tests, touched-file Ruff clean, and git diff --check clean.

Update from the same 2026-05-11 head: GitHub Actions Test Suite was green, with Unit, API, and Integration Tests and End-to-End Tests passing on 5548b63. A later test-only commit, a3f6429, added missing-score regression coverage; see the newer comment for its current CI state.

strongkeep-debug avatar May 11 '26 20:05 strongkeep-debug

@strongkeep-debug thank you for your contribution pls review the gemini suggestions and resolve them pls make sure to also add comment on the suggestions :)

ved015 avatar May 13 '26 10:05 ved015

@ved015 done. I replied directly on all four Gemini suggestions and verified that branch head covered them at the time: raw domain searches run concurrently with asyncio.gather, profile catalog loading is async via asyncio.to_thread, the profile/plan caches and latency samples are bounded, and the plan cache key uses a SHA-256 catalog hash. PR checks were green on that earlier head; the newer test-only follow-up comment below has the current CI state.

strongkeep-debug avatar May 13 '26 14:05 strongkeep-debug

Small follow-up pushed: a3f6429 adds a regression test proving answer_from_sources() handles sources with score=None without exposing a score marker or re-entering tool selection. This is test-only; runtime behavior is unchanged from the prior hardening commit.

Local validation on the current head:

.venv\Scripts\python -m pytest tests/unit tests/api tests/integration tests/test_deterministic_memory_layer.py tests/test_enterprise_chat.py --cov=src/utils --cov=src/schemas --cov=src/pipelines --cov=src/enterprise --cov=src/api --cov-report=term-missing --cov-report=xml --cov-fail-under=70
50 passed, coverage 79.61% (70% gate)

.venv\Scripts\python -m pytest tests/e2e
1 passed

.venv\Scripts\python -m pytest tests\integration\test_retrieval_pipeline.py tests\api\test_memory_search_routes.py -q
13 passed

git diff --check
clean

The PR label check passed on the new head. The Test Suite workflow is currently marked action_required, so it may need maintainer approval to run on the forked PR; the local commands above mirror the two jobs in .github/workflows/tests.yml with the same test env values.

strongkeep-debug avatar May 13 '26 15:05 strongkeep-debug

Since the hosted Test Suite is still action_required on the fork, I re-verified the current head a3f6429 in a fresh checkout with Python 3.11.

The score-serialization concern is covered on this branch in both places that can emit scores: RetrievalPipeline._score_value() coerces missing, invalid, and non-finite values before ranking/formatting, and the API route uses _safe_score() before serializing raw search sources. The regression suite includes the missing-score answer path plus the raw-search non-finite normalization path.

Current local validation:

python -m pytest tests\integration\test_retrieval_pipeline.py tests\api\test_memory_search_routes.py -q
13 passed

python -m pytest tests\unit tests\api tests\integration tests\test_deterministic_memory_layer.py tests\test_enterprise_chat.py --cov=src\utils --cov=src\schemas --cov=src\pipelines --cov=src\enterprise --cov=src\api --cov-report=term-missing --cov-report=xml --cov-fail-under=70
50 passed, coverage 79.61% (70% gate)

python -m pytest tests\e2e
1 passed

python -m ruff check src\pipelines\retrieval.py src\api\routes\memory.py tests\integration\test_retrieval_pipeline.py tests\api\test_memory_search_routes.py
All checks passed!

git diff --check
clean

strongkeep-debug avatar May 15 '26 01:05 strongkeep-debug

@Ankit-Kotnala addressed in 51c4150.

Raw code search now reads from the code annotation vector store instead of the default memory store. In the production path, RetrievalPipeline initializes that store with annotations_namespace(org_id), matching the namespace used by ingest/weaver. Tests can also inject a separate code_vector_store, which keeps the namespace boundary explicit.

I added a regression test that seeds a stale domain=code record in the default store and the real annotation record in the code store, then verifies /search_raw(..., [code]) only returns the annotation-store result.

Validation run locally:

.\.venv\Scripts\python -m pytest tests\integration\test_retrieval_pipeline.py -q
# 11 passed

.\.venv\Scripts\python -m pytest tests\unit tests\api tests\integration tests\test_deterministic_memory_layer.py tests\test_enterprise_chat.py -q
# 51 passed, 4 existing Pydantic deprecation warnings

git diff --check
# clean

strongkeep-debug avatar May 16 '26 16:05 strongkeep-debug

Updated PR #173 on current main; head is now fa5da96.

This resolves the stale/dirty branch state while keeping the requested code-search fix: production RetrievalPipeline now initializes the raw code search store through the current vector-store factory with annotations_namespace(org_id), and tests can still inject a separate code store to prove code results do not come from the default memory store.

Local validation after the rebase:

uv run --extra dev python -m pytest tests\integration\test_retrieval_pipeline.py tests\api\test_memory_search_routes.py -q
14 passed

uv run --extra dev python -m pytest tests\unit tests\api tests\integration tests\test_deterministic_memory_layer.py tests\test_enterprise_chat.py -q
54 passed

uv run --extra dev python -m pytest tests\e2e -q
1 passed

uv run --extra dev python -m ruff check src\pipelines\retrieval.py src\api\routes\memory.py tests\integration\test_retrieval_pipeline.py tests\api\test_memory_search_routes.py
All checks passed!

git diff --check
clean

Hosted label check is green on the new head. The PR is no longer merge-conflicted; it is waiting on maintainer review after the requested annotation-store change.

strongkeep-debug avatar May 19 '26 01:05 strongkeep-debug

@codex pls review this pr for any bugs report actual one only

ved015 avatar May 19 '26 06:05 ved015

@codex pls review this pr and report actual bugs if any

ved015 avatar May 19 '26 07:05 ved015

Codex Review: Didn't find any major issues. More of your lovely PRs please.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

CI-only follow-up pushed in a4cdba1 after the hosted fork checks exposed workflow-level failures rather than search-code failures.

What changed:

  • Bandit now installs the SARIF formatter before running -f sarif.
  • SARIF upload, API-diff PR commenting, and staging deploy are skipped for fork PRs where the token cannot write security events/comments/deployments.
  • No runtime retrieval/search code changed in this follow-up.

Local validation on the new head:

python yaml parse for security-scan.yml, api-schema-diff.yml, deploy-staging.yml
# ok

uv run --extra dev python -m pytest tests\integration\test_retrieval_pipeline.py tests\api\test_memory_search_routes.py -q
# 14 passed

uv run --extra dev python -m ruff check src\pipelines\retrieval.py src\api\routes\memory.py tests\integration\test_retrieval_pipeline.py tests\api\test_memory_search_routes.py
# All checks passed!

git diff --check
# clean

The new hosted workflow runs are currently action_required, which appears to be GitHub's fork/workflow-change approval gate.

strongkeep-debug avatar May 19 '26 13:05 strongkeep-debug

Update for reviewers: current head 3bf43f7 keeps the PR on runtime/tests only and includes one follow-up from automated review.

What changed since 2a5db42:

  • Successful memory ingest now invalidates the authenticated user's retrieval profile cache.
  • Batch ingest invalidates after each successful item.
  • RetrievalPipeline.invalidate_profile_cache(user_id) clears both that user's profile catalog cache and retrieval-plan cache entries, so a profile update cannot keep serving stale profile records or a plan built from the old catalog.
  • Added regression coverage at the route level and pipeline-cache level.

Local validation on the current head:

.\.venv\Scripts\python -m pytest tests\integration\test_retrieval_pipeline.py tests\api\test_memory_search_routes.py -q --tb=short
16 passed

.\.venv\Scripts\python -m ruff check src\api\routes\memory.py src\pipelines\retrieval.py tests\api\test_memory_search_routes.py tests\integration\test_retrieval_pipeline.py
All checks passed!

git diff --check
clean

Hosted label check is green on 3bf43f7. The remaining review state appears to be the prior requested-changes review waiting for maintainer re-review.

strongkeep-debug avatar May 19 '26 14:05 strongkeep-debug

Rebased this PR onto current upstream/main and re-ran the bounty-relevant search tests.

The code-search blocker from the prior review remains addressed in the rebased head: raw code search reads from the annotations-backed code_vector_store namespace, while the raw search route still covers profile/summary/temporal/snippet/code domains.

Validation:

python -m pytest tests/api/test_memory_search_routes.py tests/integration/test_retrieval_pipeline.py -q
16 passed

Could you re-review the code-store blocker when you have a chance?

strongkeep-debug avatar May 19 '26 23:05 strongkeep-debug

Re-reviewed the latest head. The code-store issue looks fixed now: raw code search is using the annotations/code vector store instead of the default memory store, and the regression test covers the stale default-store case.

I also checked the raw search flow, answer mode, score normalization, concurrent domain search, and cache invalidation after ingest. The targeted route and retrieval tests pass locally for me.

@ishaanxgupta Looks good from my side.

Ankit-Kotnala avatar May 21 '26 17:05 Ankit-Kotnala

Greptile Summary

This PR introduces a low-latency raw memory search path via RetrievalPipeline.search_raw, wiring it to both /v1/memory/search and a new root /search alias. It also adds optional answer synthesis from raw hits, LRU caches for profile catalogs and retrieval plans, a dedicated code-annotation vector store, and score normalisation across all domain searchers.

  • search_raw fans out to up to five domain searchers concurrently using asyncio.gather(..., return_exceptions=True), normalises scores, and returns results ranked by similarity without an LLM tool-selection step.
  • Profile catalog and retrieval-plan results are cached in bounded OrderedDict LRUs with a 60-second TTL; ingest now invalidates both caches for the relevant user.
  • SearchResponse gains answer, model, confidence, and latency fields; latency currently carries system-wide percentile stats from the shared singleton, leaking cross-user telemetry to every caller.

Confidence Score: 3/5

The new raw search path and caching machinery work correctly in isolation, but the latency snapshot embedded in every search response exposes system-wide request counts and agentic-mode timings to all API callers.

The latency field returned to each caller is populated from the shared pipeline singleton's accumulated samples across all users and all modes. Any user can observe how many recent requests were made in each mode (raw, answer, agentic) and the performance distribution of those requests.

src/api/routes/memory.py (latency snapshot in response) and src/pipelines/retrieval.py (code_vector_store fallback logic and double score normalisation) deserve a second look before merge.

Important Files Changed

Filename Overview
src/pipelines/retrieval.py Core pipeline rewrite adding search_raw, answer_from_sources, LRU caches, latency sampling, and a dedicated code annotation store. Contains a redundant double score-normalisation pass in search_raw and a subtle code_vector_store fallback that routes to the wrong store when only vector_store is injected.
src/api/routes/memory.py Adds search_router for the root /search alias, delegates to pipeline.search_raw, and adds answer synthesis and latency recording. The latency snapshot included in every response exposes cross-user aggregate telemetry and agentic-mode stats to all callers.
src/api/schemas.py Extends SearchRequest with answer, snippet/code domains, and adds answer/model/confidence/latency to SearchResponse. Missing the strip_query validator that RetrieveRequest has.
src/api/app.py Registers the new search_router (root /search alias) before memory_router; minor cleanup of unused variable in sentry-debug endpoint.
tests/integration/test_retrieval_pipeline.py Comprehensive new tests covering caching, raw search, concurrency, score normalisation, and code store isolation.
tests/api/test_memory_search_routes.py New API-layer tests covering raw hits, answer synthesis, code domain, and cache invalidation on ingest.

Sequence Diagram

sequenceDiagram
    participant C as Client
    participant R as search_router(/search) or router(/v1/memory/search)
    participant P as RetrievalPipeline
    participant VS as VectorStore
    participant CVS as CodeVectorStore
    participant N as Neo4jClient
    participant LLM as LLM

    C->>R: "POST {query, domains, top_k, answer}"
    R->>P: search_raw(query, user_id, domains, top_k)
    par profile in domains
        P->>VS: "search_by_text(filter=profile)"
    and temporal in domains
        P->>N: search_events_by_embedding(query)
    and summary in domains
        P->>VS: "search_by_text(filter=summary)"
    and snippet in domains
        P->>VS: "search_by_text(filter=snippet)"
    and code in domains
        P->>CVS: "search_by_text(filter=code)"
    end
    P-->>R: List[SourceRecord] ranked by score
    alt "answer=true"
        R->>P: answer_from_sources(query, sources)
        P->>LLM: ainvoke(ANSWER_PROMPT + context)
        LLM-->>P: answer text
        P-->>R: str answer
    end
    R->>P: record_latency(mode, elapsed_ms)
    R->>P: get_latency_snapshot()
    P-->>R: "{raw/answer/agentic: {count, p50, p95, p99}}"
    R-->>C: "APIResponse{results, total, answer, model, confidence, latency}"

Fix All in Cursor Fix All in Codex Fix All in Claude Code

Reviews (1): Last reviewed commit: "Invalidate profile cache after memory in..." | Re-trigger Greptile

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