Skip to content

cached_prompt left stale when grammar sampler or streaming-parser init fails after a successful prefill #2229

Closed

Description

@malibio

Summary

Same bug class as #2201, one step later in generate_blocking. After the prefill loop (packages/nlp-engine/src/chat/mod.rs) completes successfully, the KV cache exactly matches the current prompt's tokens — but llama.cached_prompt is not updated to those tokens until the very end of the function, only on successful loop exit (non-overflow). Between the end of prefill and that update, two calls can fail and return early via ?:

  • build_grammar_sampler(&llama.model, &tmpl_result)?
  • tmpl_result.streaming_state_oaicompat()...?

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). A later call computing a reusable prefix against the stale cached_prompt can either under-trust the cache (safe, just a wasted full redecode) or, if the previous cached_prompt happens to be a prefix of the new prompt, over-trust a KV region that actually holds a different prompt's tail beyond the divergence point — the same silent-corruption scenario #2201 describes.

Suggested fix

Unlike the batch.add/ctx.decode failures fixed in #2201 (transient Metal/backend failures, where poison_context()'s full context teardown is the right tool), these two failures are typically config/parse errors — a malformed grammar string or a template producing an unparseable trigger set. poison_context()'s rationale is specifically about Metal backend recovery, which doesn't apply here. The KV cache itself is valid at this point (it matches tokens); only cached_prompt is stale. So the likely correct fix is simply setting llama.cached_prompt = tokens.clone() (or moving the cached_prompt assignment earlier, before these two calls, since the KV cache guarantee already holds) rather than a full poison_context().

Location

packages/nlp-engine/src/chat/mod.rs — the two ?-returning calls immediately following the prefill loop, before token generation begins.

Origin

Found during pragmatic-code-review of PR #2228 (fix for #2201).

Activity

  1. malibio commented on Aug 21, 2026

    @malibio
    CollaboratorAuthor

    Frontend baseline: 4793 passed, 1 pre-existing flaky (architecture-benchmarks.test.ts, machine-load timing threshold — known flake, not a regression).

  2. self-assigned this
    on Aug 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions