Skip to content

Poison chat context on batch-add failure to prevent stale cached_prompt - #2228

Merged
malibio merged 1 commit into
mainfrom
issue-2201-cached-prompt-decode-error
Aug 21, 2026
Merged

malibio merged 1 commit into
mainfrom
issue-2201-cached-prompt-decode-error

Conversation

@malibio

@malibio malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator

Summary

generate_blocking maintains the cached_prompt/KV-cache pairing only on loop completion, explicitly clearing cached_prompt on context overflow. But every batch.add() failure — during prefill, in the token-decode-error recovery branch, and in the main generation loop — propagated its error via ? without touching cached_prompt, even though the KV cache had already been trimmed and/or extended for the in-flight prompt at that point.

The three ctx.decode() failure sites a few lines below each of these already call llama.poison_context() for exactly this reason (it clears both the context and cached_prompt) — the batch-add sites were missed.

Fix

Each of the three batch.add(...).map_err(...)? call sites in packages/nlp-engine/src/chat/mod.rs now matches the pattern used by the adjacent ctx.decode() failure handling: on error, call llama.poison_context() before returning, so a later call can't compute a "reusable prefix" against a cached_prompt that no longer matches what the KV cache actually holds.

Closes #2201.

Test plan

  • cargo test -p nodespace-nlp-engine --features chat-service --lib chat — 101 passed
  • bun run test:all — 227 frontend test files (4794 tests) + 2 more (24 tests) + full Rust workspace, all passing, no new failures vs baseline
  • bun run quality:fix — clean, no warnings
  • Pre-push gate (test:all + cargo build + e2e) passed

🤖 Generated with Claude Code

…pt (closes #2201)

Every batch.add() failure in generate_blocking previously propagated
via `?` without touching cached_prompt, even though the KV cache had
already been trimmed or extended for the in-flight prompt. A later
call could then compute a "reusable prefix" against cached_prompt
while the KV cache actually held a different prompt's tokens,
corrupting generation silently. The ctx.decode() failure paths a few
lines below already call poison_context() for this exact reason —
the batch-add paths were missed.

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

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This is a small, well-targeted fix: three batch.add(...).map_err(...)? sites in generate_blocking now call llama.poison_context() before propagating the error, matching the pattern already used by the adjacent ctx.decode() failure branches. The fix correctly closes the specific gap described in #2201 (prefill batch-add, decode-error-recovery batch-add, and steady-state generation-loop batch-add). Net positive — ships as-is.

One real gap of the same bug class exists just outside the diff's boundary and is worth a follow-up (not a blocker, see below).

Findings

Critical Issues

None.

Suggested Improvements

  • packages/nlp-engine/src/chat/mod.rs:557 and :562 — same-class stale-cached_prompt gap, not touched by this PR. After the prefill loop completes successfully, the KV cache exactly matches tokens for the in-flight prompt, but llama.cached_prompt is not updated to tokens until line 738 (only on successful loop exit / non-overflow). In between, build_grammar_sampler(&llama.model, &tmpl_result)? (line 557) and tmpl_result.streaming_state_oaicompat()...? (line 562) are both Err-returning early-return paths. If either fails, the function returns immediately with the KV cache holding the current prompt's tokens while cached_prompt still describes the previous prompt (or is empty on a first call) — exactly the desync class this PR fixes elsewhere. A later call computing prefix_len against the stale cached_prompt could either under-trust the cache (safe, just wasteful — full redecode) or, if the previous cached_prompt happens to be a prefix of the new prompt, over-trust a KV region that in fact holds a different prompt's tail beyond where they diverge (the exact silent-corruption scenario from cached_prompt left stale on decode-error paths, enabling silent KV-cache prefix corruption on later turns #2201's failure walkthrough). Recommend filing a fast follow-up issue (same severity class as cached_prompt left stale on decode-error paths, enabling silent KV-cache prefix corruption on later turns #2201) rather than blocking this PR — these two failures are typically config/parse errors (grammar string malformed, template producing an unparseable trigger set) rather than the transient Metal/backend failures poison_context() targets, so the fix there may be as simple as llama.cached_prompt.clear() rather than a full poison_context() (see next point on proportionality).

  • Proportionality: poison_context() vs. a lighter cached_prompt.clear(). poison_context()'s doc comment (mod.rs:166-179) grounds its rationale specifically in Metal backend recovery: "llama.cpp does not recover a backend on its own after a compute failure... dropping the context... makes the next call build a fresh context (and thus a fresh Metal backend/command queue)." A batch.add() failure is a CPU-side bookkeeping error (e.g. batch capacity exceeded) — it is not a backend/GPU compute failure, so the Metal-recovery rationale doesn't directly apply to these three sites the way it does to the adjacent ctx.decode() failures. That said, reusing the existing poison_context() here is defensible on simplicity/consistency grounds (KISS, one poison path instead of two) and the cost is a rebuilt context on the next call, not correctness — so this is not a blocker, just worth confirming the choice was intentional over a lighter cached_prompt.clear()-only fix.

Nitpicks

  • Nit: The three new if let Err(e) = ... { poison; return Err(...) } blocks are near-verbatim repeats of the same four lines. Given there are now 5 total sites in this function following this shape (3 new + 2 pre-existing ctx.decode sites), a small helper like fn poison_and_err(llama, context: &str, e) -> ChatError would remove the duplication — optional, the current form reads fine and matches the file's existing style of inline error handling.

Test Coverage

No new tests were added. Given the difficulty of deterministically triggering a real llama_batch_add failure (it requires exceeding native batch capacity or an FFI-level condition) in a unit test without extensive mocking of llama-cpp-2 internals, and that the existing 101-test chat module suite doesn't appear to cover the cached_prompt/KV invariant at all (no test references poison_context or cached_prompt directly), this is a reasonable trade-off for a defensive one-line fix mirroring an already-untested-but-trusted adjacent pattern (ctx.decode poisoning). Consider a lightweight follow-up: a unit test asserting poison_context() clears both context and cached_prompt (testing the helper directly, not the hard-to-trigger call site) would at least guard the invariant contract itself.

Recommendation

APPROVE — the fix is correct, minimal, atomic, and consistent with the existing error-handling pattern in the same function. The one adjacent gap found (grammar sampler / streaming-parser init failures after prefill, before cached_prompt update) is real but is a distinct code path from what #2201 reported and what this PR's diff touches — appropriate to track as a fast follow-up rather than block this PR on scope creep.

@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.

Reviewed — see full findings in the comment above. Recommendation: APPROVE. Fix is correct, minimal, and consistent with the existing ctx.decode() poisoning pattern in the same function. One same-class gap found outside this diff's scope (build_grammar_sampler / streaming_state_oaicompat failures between prefill completion and the cached_prompt update at line 738) — recommend tracking as a fast follow-up issue rather than blocking here. Self-review posted as COMMENT since self-approval is rejected by GitHub for PR authors.

@malibio

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Address-Review Summary

Review verdict was APPROVE with no critical findings. Evaluated the three non-blocking notes:

  • ✅ Addressed — Grammar-sampler/streaming-parser init gap (mod.rs:557/562): confirmed this is a real, same-class bug but a genuinely different code path/failure mode than what cached_prompt left stale on decode-error paths, enabling silent KV-cache prefix corruption on later turns #2201 reported (config/parse errors vs. transient Metal/backend decode failures) and outside this PR's diff. Filed cached_prompt left stale when grammar sampler or streaming-parser init fails after a successful prefill #2229 to track it, per the reviewer's own recommendation to follow up rather than scope-creep this PR.
  • ⏭️ Skipped — Proportionality question (poison_context() vs. a lighter cached_prompt.clear()): intentional. Reusing poison_context() matches the established pattern at the two adjacent ctx.decode() sites in the same function — one poison path is easier to reason about than mixing two clear strategies, and the cost of the stronger fix (rebuilding the context on the next call) isn't a correctness concern, just a marginal perf one. Revisit if profiling ever shows this path contending.
  • ⏭️ Skipped — Extract a poison_and_err() helper: the reviewer flagged this as optional/"reads fine as-is." With 5 total sites now following this shape, it's a defensible future cleanup but not warranted by this PR's scope — three near-identical 4-line blocks isn't yet unwieldy enough to justify the abstraction.

No code changes made — nothing addressed required a diff.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: No code changes were made to the PR; the review's only actionable item (the follow-up bug) was filed as a separate issue rather than folded into this diff. The approved diff is unchanged.

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.

cached_prompt left stale on decode-error paths, enabling silent KV-cache prefix corruption on later turns

1 participant