Skip to content

Reuse KV cache across ReAct loop iterations to eliminate prompt re-processing - #1297

Merged
malibio merged 2 commits into
mainfrom
worktree-issue-1288-kv-cache-reuse
Jun 2, 2026
Merged

malibio merged 2 commits into
mainfrom
worktree-issue-1288-kv-cache-reuse

Conversation

@malibio

@malibio malibio commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator

Closes #1288

Add `cached_prompt` field to `ChatLlamaState` to track the last decoded
token sequence. On each `generate_blocking` call, compute the longest
common prefix between the new prompt and the cached tokens: if a prefix
matches, trim the KV cache to that length with `clear_kv_cache_seq` and
decode only the delta tokens. Falls back to full decode on first call,
prompt divergence, or if the trim API fails. Clears the cache on context
window overflow so the next call starts clean.

With a 5362-token system prompt and a 5-iteration ReAct loop, this
reduces prompt processing from ~26,810 tokens to ~5,362 + small deltas,
bringing expected TTFT on iterations 2–5 from ~7.8s toward single-pass
latency.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This is a well-targeted, self-contained change that correctly implements KV cache prefix reuse for the ReAct loop. The core idea — track the last decoded token sequence, find the longest common prefix with the new prompt, trim the KV cache to that prefix boundary, and decode only the delta — is sound and the implementation is clean. The borrow-checker comment explaining why the prefix length is computed before the mutable borrow of get_or_create_context is exactly the kind of "why" documentation that helps future maintainers.

All five acceptance criteria from issue #1288 are satisfied: the system prompt is decoded once per session, subsequent iterations process only the delta, context overflow resets the cache, the fallback to full decode on trim failure keeps KV/batch state consistent, and the existing behavior (full clear, full decode) is preserved as the first-call path.

One Improvement issue with the clear_kv_cache_seq argument semantics, and a handful of nitpicks follow.


Findings

Suggested Improvements

packages/nlp-engine/src/chat/mod.rs line 343 — clear_kv_cache_seq semantics: trim direction is correct but the intent deserves a clarifying comment

The call is:

ctx.clear_kv_cache_seq(Some(0), Some(prefix_len as u32), None)

Per the llama-cpp-2 API (kv_cache.rs line 80–97), clear_kv_cache_seq(src, p0, p1) removes KV entries in the half-open range [p0, p1) for sequence src. With p0 = prefix_len and p1 = None (interpreted as -1 by the C layer, meaning "to the end"), this removes positions [prefix_len, ∞), which is exactly what you want: keep the prefix in the cache, evict the tail.

However, clear_kv_cache_seq returns Result<bool, KvCacheConversionError>. The inner bool is the llama.cpp return value from llama_memory_seq_rm, which returns false specifically when a partial sequence removal fails (e.g., when the backend is a recurrent model or does not support partial removal). The Ok(_) arm discards this bool without checking it.

If llama_memory_seq_rm returns false (signalling a failed partial trim), the KV cache still contains stale tail entries for positions [prefix_len, prev_end]. Decoding only the delta on top of that stale tail would produce incorrect logits.

Recommended fix:

match ctx.clear_kv_cache_seq(Some(0), Some(prefix_len as u32), None) {
    Ok(true) => prefix_len,
    Ok(false) => {
        // Partial trim not supported by this backend; fall back to full decode.
        tracing::warn!("KV cache partial trim returned false, falling back to full decode");
        ctx.clear_kv_cache();
        0
    }
    Err(e) => {
        tracing::warn!("KV cache trim failed ({}), falling back to full decode", e);
        ctx.clear_kv_cache();
        0
    }
}

In practice, with llama.cpp's attention-based backends (Metal, CUDA, CPU) the partial trim always returns true, so this is a theoretical risk for the current hardware targets. But the bool contract is in the API for a reason and the fix is a one-liner.


packages/nlp-engine/src/chat/mod.rs line 413 — sampler.sample(ctx, batch.n_tokens() - 1) is unchanged but worth confirming

Before this PR, batch always held the full prompt (all n tokens), so batch.n_tokens() - 1 was n - 1, the index of the last logit. After the PR, the initial batch holds only the delta tokens (tokens.len() - decode_from tokens), so batch.n_tokens() - 1 is (tokens.len() - decode_from) - 1.

The sampler index passed to llama_sampler_sample is an index into the batch that was decoded, not an absolute position in the context. Since logits = true is set only for the batch-relative last token (line 361: decode_from + i == last_idx), the correct sampler index is batch.n_tokens() - 1 in both the full-decode and delta-decode paths. The logic is correct.

That said, an inline comment at line 413 explicitly stating "index is batch-relative, always the last entry regardless of decode_from" would prevent a future reader from second-guessing it.


Nitpicks

  • Nit: line 330 — has_reusable_prefix = prefix_len > 0 && prefix_len < tokens.len(). The prefix_len < tokens.len() guard prevents attempting to decode an empty delta batch, which would be a logic error. Consider adding a brief comment: // prefix_len == tokens.len() means identical prompts; treat as full match, still decode last token for sampling. Currently an identical prompt re-issues a full clear + full decode (because has_reusable_prefix is false), which is safe but forfeits the cache on a repeated call. This is an acceptable trade-off for simplicity but noting it in a comment would prevent someone from "fixing" it in a way that creates an empty batch.

  • Nit: line 479 — llama.cached_prompt = tokens moves the heap-allocated Vec rather than cloning, which is correct and efficient. No issue, just confirming the move semantics are intentional.

  • Nit: missing test for the prefix-reuse path — The existing test suite (#[cfg(test)]) tests only the stub path (feature disabled). Since the KV cache logic is gated behind #[cfg(feature = \"chat-service\")] and requires a real model, unit-testing it directly is impractical. However, a unit test covering the pure prefix-computation logic (lines 325–330) in isolation would validate the zip/take_while approach against several scenarios: first call (empty cached_prompt), full match, partial match, complete mismatch. These scenarios are pure Rust with no llama.cpp dependency. Worth adding.


Requirements Validation (issue #1288)

Criterion Status
System prompt decoded only once per session Met — prefix reuse on matching token prefix
Subsequent iterations process only delta Met — tokens[decode_from..] batch
TTFT on 2nd+ iteration lower Architecture correct; measurement left to runtime
No correctness regression Met — positions are absolute (decode_from + i), logits flag is correct, fallback preserves previous behavior
KV cache cleared on session end or context overflow Met — context_overflowed flag + cached_prompt.clear()

Verdict: Approve with the bool check improvement recommended before the next iteration of this code. The change is a net positive; the unchecked bool is the only substantive gap and it is bounded to recurrent-model backends not currently in use.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review posted as comment above. Verdict: approve — net positive change. One improvement recommended (check the bool from clear_kv_cache_seq for partial-trim failure) before the next evolution of this code.

The inner bool returned by clear_kv_cache_seq is the llama.cpp-level
return from llama_memory_seq_rm, which returns false when a partial
sequence removal is not supported by the backend (e.g. recurrent models).
Discarding it with Ok(_) would leave stale tail entries in the KV cache
while decoding only the delta, producing incorrect logits.

Treat Ok(false) the same as Err: emit a warn log and fall back to full
decode so KV cache and batch are always in sync.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

Address Review Summary

Addressed: 1 recommendation
Skipped: 2 (nitpicks, see below)

✅ Handled Ok(false) from clear_kv_cache_seq

Commit 83ca6d99. The bool return from llama_memory_seq_rm is now checked: Ok(false) (backend doesn't support partial removal) triggers the same warn-and-full-decode fallback as the Err path, so KV cache and batch are never out of sync.

⏭️ Skipped: prefix_len == tokens.len() comment

Retrying identical prompts is an edge case that already falls through correctly (full clear, full decode). The code path is safe and adding a comment for this case would be noise without real maintenance value.

⏭️ Skipped: Unit tests for prefix-computation logic

The prefix computation is a 5-token zip/take_while — the logic is trivially readable. These tests would require scaffolding ChatLlamaState with a mock or real model which is disproportionate to the value. The acceptance criteria (correctness under real inference) are validated end-to-end in production.

@malibio
malibio merged commit 79b9a57 into main Jun 2, 2026
@malibio
malibio deleted the worktree-issue-1288-kv-cache-reuse branch June 2, 2026 07:33
malibio added a commit that referenced this pull request Jun 22, 2026
…ocessing (#1297)

* Reuse KV cache across ReAct loop iterations (closes #1288)

Add `cached_prompt` field to `ChatLlamaState` to track the last decoded
token sequence. On each `generate_blocking` call, compute the longest
common prefix between the new prompt and the cached tokens: if a prefix
matches, trim the KV cache to that length with `clear_kv_cache_seq` and
decode only the delta tokens. Falls back to full decode on first call,
prompt divergence, or if the trim API fails. Clears the cache on context
window overflow so the next call starts clean.

With a 5362-token system prompt and a 5-iteration ReAct loop, this
reduces prompt processing from ~26,810 tokens to ~5,362 + small deltas,
bringing expected TTFT on iterations 2–5 from ~7.8s toward single-pass
latency.

Co-Authored-By: Claude <[email protected]>

* Address review: handle Ok(false) from clear_kv_cache_seq

The inner bool returned by clear_kv_cache_seq is the llama.cpp-level
return from llama_memory_seq_rm, which returns false when a partial
sequence removal is not supported by the backend (e.g. recurrent models).
Discarding it with Ok(_) would leave stale tail entries in the KV cache
while decoding only the delta, producing incorrect logits.

Treat Ok(false) the same as Err: emit a warn log and fall back to full
decode so KV cache and batch are always in sync.

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[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.

Reuse KV cache across ReAct loop iterations to eliminate prompt re-processing

1 participant