Skip to content

feat(rag): add CAG/RAG router with llama.cpp KV cache backend (#1000) - #1010

Merged
AmitoVrito merged 8 commits into
SynapseKit:mainfrom
Premvkmishra:feat/cag-rag-router-1000
Sep 3, 2026
Merged

AmitoVrito merged 8 commits into
SynapseKit:mainfrom
Premvkmishra:feat/cag-rag-router-1000

Conversation

@Premvkmishra

Copy link
Copy Markdown
Contributor

Summary

Implements Cache-Augmented Generation (CAG) ↔ Retrieval-Augmented Generation (RAG) routing. It introduces a provider-independent CAGRouter that 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

  • Bug fix
  • New feature
  • Documentation update
  • Refactor / internal improvement
  • Dependency / tooling update

Changes

  • CAGRouter Implementation: 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 and os.replace(). It uses a secure, pickle-free bytes interface to maintain provider-agnostic storage boundaries.

  • LlamaCppCAGBackend Integration: Encapsulates LlamaState handling inside the llama.cpp backend module. It extracts state bytes when building and saving a cache and reconstructs the ctypes-bound LlamaState object when loading cached state.

  • Documentation: Added docs/rag/cag.md covering CAG vs RAG, limitations, and usage. Updated docs/edge.md to link to the new documentation.

  • Harness & Examples: Added benchmarks/cag_vs_rag_bench.py and examples/cag_router_example.py.

Testing

  • New tests added for the CAG router, KV cache persistence, and llama.cpp CAG backend.
  • Existing test suite remains compatible with the new implementation.
  • No API keys or secrets are included in the code.

Documentation

  • Docstrings updated for public API changes.
  • synapsekit-docs updated (if required for the new feature).
  • CHANGELOG.md updated.

Notes for reviewer

  • LlamaState Handling: LlamaState serialization 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.

Premvkmishra and others added 5 commits August 31, 2026 13:31
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]>
@AmitoVrito

Copy link
Copy Markdown
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):

  • Cache fingerprint was order-independent but the KV cache is order-dependent. analyze() hashed sorted(texts), while the cache is built over the corpus in insertion order, so ["A","B"] and ["B","A"] shared one key with different states. Now fingerprints in order with a length prefix.
  • Cache key used config.model (a label), not the model file. Two different GGUFs (Q4 vs Q8, or a fine-tune) with the same label would collide and load_state a foreign blob into llama.cpp (corruption or a hard crash). Added model_cache_id() folding in the model path + size.
  • Stream producer thread leaked on early break. generate_with_cache buffered the whole generation on an unbounded queue and never stopped if the consumer broke early. Now bounded + stops on aclose.
  • Replaced MagicMock in the tests with hand-written fakes + the real KVCacheStore (our test standard), and fixed the lint/typecheck failures.

Worth a follow-up (didn't change, up to you):

  • The router's headline win isn't realized through retrieve(). It only load_states and returns the corpus text; the preloaded KV cache is reused by downstream generation only if the prompt's token prefix matches the raw corpus, but a RAGPipeline wraps context in a template so the prefix diverges and llama.cpp re-evaluates. The benchmark also measures backend.generate_with_cache directly, not the router path, so the "warm cache" numbers don't reflect what a CAGRouter user gets. Would be great to either wire generation through the router or document this clearly.
  • Minor: KVCacheStore has no eviction (llama states are large), and CAGRouter doesn't implement retrieve_mmr.

Happy to pair on the router/generation wiring if useful. Thanks again!

AmitoVrito and others added 2 commits September 3, 2026 19:56
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]>
@AmitoVrito
AmitoVrito merged commit 256914f into SynapseKit:main Sep 3, 2026
15 checks passed
@AmitoVrito

Copy link
Copy Markdown
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!

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.

CAG ↔ RAG router (persisted KV vs retrieval)

2 participants