Repository navigation
feat(rag): add CAG/RAG router with llama.cpp KV cache backend (#1000) - #1010
Merged
AmitoVrito merged 8 commits intoSep 3, 2026
Merged
Conversation
CAG/RAG router CI was failing on lint and typecheck: - ruff: remove unused imports, sort import blocks, strip trailing whitespace, drop the redundant UTF-8 encode arg, rename the ambiguous `l` fixture variable, and apply ruff format - mypy: `CAGBackend.generate_with_cache` was declared `async def -> AsyncGenerator`, which types as a coroutine returning a generator and so rejected the async-generator (`async def` + `yield`) override; changed the abstract method to a plain `def -> AsyncGenerator`. Annotated `_cag_backend` as `CAGBackend | None` so the auto-resolve branch typechecks. No behavior change. Co-authored-by: Prem Mishra <[email protected]>
Project testing standards prohibit MagicMock/Mock/patch (they silently accept any call, so tests pass while prod breaks). Rewrote the CAG/RAG router and llama.cpp CAG-backend tests to use: - a hand-written FakeRetriever and FakeCAGBackend (a real CAGBackend subclass) that record calls for assertions - the real KVCacheStore backed by tmp_path, with the cache-hit and cache-miss-rebuild tests exercising a genuine save/load round-trip - a real LlamaCppLLM (constructs lazily; no model file loaded) and a hand-written FakeLlamaModel for the backend's tokenize/eval/save_state/ load_state/create_completion calls - monkeypatch.setitem for the missing-llama_cpp ImportError case Also flattened the TestLlamaCppCAGBackend class to plain pytest functions. No behavior change to the code under test. Co-authored-by: Prem Mishra <[email protected]>
Two correctness bugs in the persisted-cache key, both able to load a KV state that disagrees with the current corpus/model: - The corpus fingerprint hashed sorted(texts), but the KV cache is built over the corpus in insertion order, so ["A","B"] and ["B","A"] collided on one key with different states. Fingerprint the corpus in order, with a length prefix per text so different splits can't collide. - The cache key used config.model (a label like "llama-3.1-8b"), not the model file. Two different GGUFs (Q4 vs Q8, or a fine-tune) sharing the label collided, so load_state could feed a foreign KV blob into llama.cpp -> corrupted output or a hard crash. Added model_cache_id(), which folds in the model path and file size. Regression tests assert the fingerprint is order-sensitive and that two model files with the same label get distinct cache identities. The test key helper now derives via the real analyzer/identity code so it can't drift from the router. Co-authored-by: Prem Mishra <[email protected]>
generate_with_cache spawned a producer thread that put every chunk on an unbounded queue; if the consumer broke out of the async-for early (stop token, timeout, disconnect) the thread kept calling create_completion and buffering the whole generation forever. Use a bounded queue for backpressure and a stop event checked at each token boundary, and set it from the generator's finally (on aclose/early break) so the producer exits promptly. Regression test consumes one token, closes the generator, and asserts the producer stops and never runs unbounded. Co-authored-by: Prem Mishra <[email protected]>
Collaborator
|
Thanks for this @Premvkmishra, and welcome! Really nice first contribution. The KV-cache backend mechanics are sound (save/load, add_bos handling, atomic writes with a format-version gate) and the router decision tree reads clearly. I did a full review and pushed a few fixes onto your branch (credited to you), plus got CI green (it was blocked on first-time-contributor workflow approval). Details: Fixed (I pushed these):
Worth a follow-up (didn't change, up to you):
Happy to pair on the router/generation wiring if useful. Thanks again! |
Documents the #1000 CAG/RAG router for the [Unreleased] changelog and adds an honest limitation to docs/rag/cag.md: the router primes the KV state but downstream generation only benefits when the prompt's token prefix matches the raw corpus (a templated pipeline can defeat it). Tracked as #1018. Co-authored-by: Prem Mishra <[email protected]>
Collaborator
|
Merged, and welcome aboard @Premvkmishra! Solid first contribution. Added you to the contributors list. Left #1018 open for the router/generation wiring when you want to take it further. Thanks! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Implements Cache-Augmented Generation (CAG) ↔ Retrieval-Augmented Generation (RAG) routing. It introduces a provider-independent
CAGRouterthat wraps standard retrievers and transparently routes stable corpora to local, persisted KV cache files (KVCacheStore) when the underlying LLM provider supports context serialization.Closes #1000
Type of change
Changes
CAGRouterImplementation: Implements router decision-tree logic evaluating LLM capabilities, corpus stability, token limits, and cache availability.Pickle-Free
KVCacheStore: Atomically saves and loads raw binary context state (.bin) and metadata JSON (.json) using temporary files andos.replace(). It uses a secure, pickle-free bytes interface to maintain provider-agnostic storage boundaries.LlamaCppCAGBackendIntegration: EncapsulatesLlamaStatehandling inside the llama.cpp backend module. It extracts state bytes when building and saving a cache and reconstructs the ctypes-boundLlamaStateobject when loading cached state.Documentation: Added
docs/rag/cag.mdcovering CAG vs RAG, limitations, and usage. Updateddocs/edge.mdto link to the new documentation.Harness & Examples: Added
benchmarks/cag_vs_rag_bench.pyandexamples/cag_router_example.py.Testing
Documentation
Notes for reviewer
LlamaStateHandling:LlamaStateserialization boundaries are isolated within the llama.cpp backend. The cache store operates only on raw bytes and metadata, keeping the persistence layer provider-independent.Provider Independence: The CAG routing layer is designed around provider capabilities, allowing supported backends to opt into context serialization without coupling the router or cache store to provider-specific state representations.