Skip to content

Update cached_prompt right after prefill instead of only on loop exit - #2230

Merged
malibio merged 2 commits into
mainfrom
issue-2229-cached-prompt-stale-init
Aug 21, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2229-cached-prompt-stale-init

Conversation

@malibio

@malibio malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator

Summary

Same bug class as #2201, one step later in generate_blocking. After the prefill loop completes successfully, the KV cache exactly matches the current prompt's tokens — but cached_prompt wasn't updated until the very end of the function, only on successful loop exit. Between the end of prefill and that update, build_grammar_sampler()? and tmpl_result.streaming_state_oaicompat()? can each fail and return early, leaving cached_prompt stale (describing the previous prompt, or empty on a first call) while the KV cache holds the current prompt. A later call could then trust a stale prefix match against a KV region that no longer agrees with it.

Fix

Move the cached_prompt write to immediately after the prefill loop, since the KV-cache-matches-tokens guarantee already holds there — no poison_context() needed, since (unlike the decode/batch-add failures fixed in #2201/#2226) these are config/parse errors, not backend failures, and the KV cache itself is valid. The end-of-function context-overflow clear still applies if generation later overflows.

Closes #2229

Test plan

  • cargo build -p nodespace-nlp-engine — clean
  • cargo clippy -p nodespace-nlp-engine --all-targets -- -D warnings -D clippy::unused-async — clean
  • cargo test -p nodespace-nlp-engine --lib chat:: — 101 passed
  • bun run test:all — full pre-push gate passed (frontend, skill, Rust unit + Tauri-seam integration tests)

🤖 Generated with Claude Code

…closes #2229)

build_grammar_sampler and streaming_state_oaicompat() each run after the
prefill loop completes and can fail via `?` before generation starts. The
KV cache at that point already matches the current prompt's tokens, but
cached_prompt wasn't updated until successful loop exit — so an early
return left it describing the previous prompt (or empty on a first call).
A later call could then trust a stale prefix match against a KV region
that no longer agrees with it.

Move the cached_prompt write to right after prefill, since the KV cache
guarantee already holds there. The context-overflow clear at the end of
the function still wins if generation later hits that path.

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

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2230

Review Type: Initial review (no prior reviews on this PR)
Scope: 1 commit, 1 file, +12/-6 — packages/nlp-engine/src/chat/mod.rs


Requirements Check (issue #2229)

Requirement Status
cached_prompt no longer stale when build_grammar_sampler's ? returns early ✅ Write moved to mod.rs:544, before build_grammar_sampler at :566
Same for tmpl_result.streaming_state_oaicompat()? ✅ Also covered — parser init is at :571, after the new write
Fix does not use poison_context() (issue explicitly argues against it here) ✅ Plain assignment; the issue's reasoning — config/parse errors, valid KV cache — is honored and restated in the code comment
Context-overflow clear still wins ✅ if context_overflowed { llama.cached_prompt.clear() } at :745 runs strictly after the new write

The fix matches the issue's own suggested remedy ("moving the cached_prompt assignment earlier, before these two calls, since the KV cache guarantee already holds") rather than inventing a different one. Good.


Correctness Verification

I traced every path between the new write site (:544) and the end of the function to confirm nothing was missed:

Early returns after the new write: four llama.poison_context(); return Err(...) sites inside the generation loop (:659, :665, :724, :731). poison_context() calls cached_prompt.clear(), so each of these overwrites the new write with an empty vector — strictly safer than the old behavior and correct, since the KV cache at those points holds partially-generated tokens beyond tokens. No path is left with a cached_prompt that over-describes the KV cache.

The removed else branch: the old else { llama.cached_prompt = tokens; } fired only on non-overflow loop exit. Every non-overflow exit still reaches the new write earlier in the function, and every path that skips the new write (the prefill batch-add/decode failures at :511–:533) still poisons. Semantics are preserved, and the new code is a strict superset of the old guarantee.

The overflow-clear ordering is the one subtle interaction, and it's correct: on overflow the KV cache holds tokens + generated tokens up to the window edge, so cached_prompt = tokens would understate the cache. Clearing forces a full redecode. The write-then-conditionally-clear sequencing gets this right, and the comment explicitly calls out that the clear wins.

Ownership: tokens.clone() is now genuinely required — tokens is still read at :625 (n_cur = tokens.len()) after the write. This isn't gratuitous; a std::mem::take-style restructure would break that read. Correct as written. The clone is one Vec<LlamaToken> (4 bytes/token) per generation call, negligible against a multi-second decode.

Build verification: cargo clippy -p nodespace-nlp-engine --all-targets -- -D warnings — clean.


Findings

🔴 Critical

None.

🟡 Improvements

None blocking.

🟢 Nits

  • Nit: mod.rs:655-658 and mod.rs:721-723 — two in-loop comments are now factually stale. Both assert cached_prompt "won't be updated until the loop exits successfully" / "(only updated on successful loop exit)". After this PR that's no longer true — it was updated right after prefill. The poison_context() calls there are still correct (the KV cache extends past tokens, so a tokens-valued cached_prompt would understate it and must be cleared), but the stated reason no longer matches the code. Given this is the third PR in a row touching this exact invariant, keeping the rationale comments truthful has real value — a future reader who trusts the stale comment could conclude the poison is redundant and remove it. Suggested rewording for both: "the KV cache now extends past tokens with this turn's generated tokens, so the cached_prompt set after prefill understates it — poison rather than leave a prefix match that over-trusts the cache."

  • Nit: mod.rs:541-543 — the comment's last sentence ("On context overflow (checked below) this gets cleared, so a subsequent overflow-driven clear always wins over this write") is slightly redundant with the comment at :742-744 that says the same thing from the other side. Harmless; the duplication arguably helps since the two sites are 200 lines apart. No action needed.


Testing Assessment

No test was added. I consider this correct and consistent with precedent, not a gap:

  • The two immediate predecessors in this bug class — PR Poison chat context on batch-add failure to prevent stale cached_prompt #2228 (mod.rs only, +32/-11) and PR Recreate the chat backend context after a decode failure #2226 (error.rs + mod.rs, +45/-6) — both shipped without regression tests for the same reason.
  • generate_blocking requires a loaded GGUF model and a live Metal backend. Exercising "grammar sampler construction fails after a successful prefill" would mean injecting a malformed grammar through apply_chat_template into a real llama.cpp context — a fixture cost far out of proportion to a 1-line reordering, and it would test llama.cpp's failure modes more than ours.
  • The change is a mechanical hoist with no new branching. The invariant it establishes ("KV cache matches tokens ⟹ cached_prompt == tokens") is verifiable by reading, which I did exhaustively above.

Per YAGNI and the project's pragmatic standard, adding a heavyweight integration fixture here would be net-negative. PR body reports cargo test -p nodespace-nlp-engine --lib chat:: (101 passed) and a full bun run test:all gate pass.


Architectural Note (non-blocking, worth recording)

This is the third fix to the same invariant in this function in as many PRs (#2172 → #2226, #2201 → #2228, #2229 → this). The pattern is consistent: cached_prompt and the KV cache are two pieces of state that must agree, updated at separate points, with correctness resting on every early return between them doing the right thing manually. Each fix has been correct, and this one narrows the vulnerable window substantially (the remaining window is now the generation loop, which is fully covered by poison_context()).

I'd argue the invariant is now actually closed rather than just narrowed — every write site and every early return is accounted for. But if a fourth instance of this bug class appears, that's the signal to stop patching sites and instead make the coupling structural (e.g. an RAII guard that clears cached_prompt on drop unless explicitly committed, so a new ? can't silently reopen the hole). Not something to do in this PR — YAGNI at n=3 where the current fix demonstrably closes the set.


Recommendation

APPROVE

The fix is minimal, correctly placed, matches the issue's own analysis, preserves the overflow-clear semantics exactly, and is consistent with how the two prior PRs in this bug class were handled. The .clone() is necessary, not incidental. Clippy is clean. The only findings are two stale rationale comments — worth a follow-up touch for the next reader's sake, but not merge-blocking.

Definitively net-positive for code health.

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

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Correctly scoped, minimal, surgical fix for the exact gap described in #2229. The cached_prompt write is moved to immediately after the prefill loop completes — the earliest point where the "KV cache matches tokens" invariant holds — closing the window where build_grammar_sampler(...)? or tmpl_result.streaming_state_oaicompat()...? could return early and leave cached_prompt stale while the KV cache already reflected the new prompt. This is a clean net positive: single-purpose, 13/-5 line diff, one file, no unrelated changes bundled in.

Requirements Check (Issue #2229)

Findings

Critical Issues

None.

Suggested Improvements

None — the fix is minimal and correctly placed. I verified there are no other ?-returning early-return paths between the prefill loop and end-of-function that were missed: the only remaining early returns (in the token-generation loop, packages/nlp-engine/src/chat/mod.rs:654-671 and :720-737) already call poison_context(), which unconditionally clears cached_prompt — pre-existing correct behavior from PR #2226/#2228 that this change doesn't disturb. The removed else { llama.cached_prompt = tokens } is correctly subsumed by the new early write; the remaining if context_overflowed { llama.cached_prompt.clear() } is the only case that still needs end-of-function handling.

Regarding tokens.clone() at line 544: necessary, not superfluous. tokens (owned) is read throughout the rest of the function (n_cur = tokens.len(), &tokens[decode_from..], last_idx, etc.), so the value has to stay live past this point — no ownership restructuring would remove the clone without disproportionate surgery for a single small Vec<LlamaToken> copy. Correctly left as a minor cost, consistent with YAGNI.

Testing: no new test added, consistent with the precedent set by PR #2228 (#2201) and PR #2226 (#2172), both of which fixed the same bug class in this exact function with pure production-code diffs and no test additions — generate_blocking requires a live llama.cpp model/context that the existing unit-test harness in this file doesn't stand up, so a targeted regression test isn't practical here without disproportionate new test infrastructure. The stated manual verification (clean build, clippy clean, 101 passing chat:: unit tests, full bun run test:all pre-push gate) is proportionate for a narrow, mechanical reordering fix. Not a blocker.

Nitpicks

  • Nit: packages/nlp-engine/src/chat/mod.rs:655-658 and :722-723 — these comments still say cached_prompt is "only updated on successful loop exit" / "won't be updated until the loop exits successfully." That was true before this PR but is now stale: cached_prompt is set right after prefill (line 544), before the loop even starts. The poison_context() calls at these sites are still correct (poisoning unconditionally clears cached_prompt regardless of when it was last set), so this is purely a comment-accuracy issue, not a logic bug. Worth a one-line comment update in a follow-up or amendment.

Recommendation: APPROVE

This is a textbook example of the bug class established by #2201/#2172 — same root cause pattern (early return between a KV-cache-mutating operation and the bookkeeping update), same file, same function, and the fix follows the same reasoning discipline as its predecessors (matching the failure mode to the right remediation — poison vs. simple reassignment). No test added, matching precedent, and justified given the practical constraints of testing this function. One nit (stale comments) that doesn't block merge.

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

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

Two in-loop poison_context() comments still said cached_prompt was "only
updated on successful loop exit" — no longer true after this PR moved
that write to right after prefill. Reworded both to state the actual
reason poisoning is still correct there: the KV cache extends past
tokens with this turn's generated tokens, so the post-prefill
cached_prompt write understates it.

Nit from PR #2230's pragmatic-code-review (APPROVE, no blocking findings).

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

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Address Review Summary

Addressed (1/1 finding — the only nit raised, no critical/important findings):

  • Reworded the two stale in-loop comments at poison_context() call sites (previously at lines 655-658 and 722-723) that said cached_prompt was "only updated on successful loop exit" — no longer accurate now that it's written right after prefill. Both now state the actual reason poisoning is still correct there: the KV cache extends past tokens with this turn's generated tokens, so the post-prefill cached_prompt write understates it.

Skipped: none — the review had no other findings.

Verification: cargo build -p nodespace-nlp-engine clean, cargo clippy -p nodespace-nlp-engine --all-targets -- -D warnings -D clippy::unused-async clean, full bun run test:all pre-push gate passed (one pre-existing flake on retry: core-plugins.test.ts viewer-resolution timeout under machine load — known flake, unrelated to this change, passed on retry).

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The only change since the reviewed commit is a comment-text correction inside two existing poison_context() branches — no logic, control flow, or behavior changed. Both review passes on the original fix already reached APPROVE with zero critical/important findings.

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 when grammar sampler or streaming-parser init fails after a successful prefill

1 participant