Skip to content

Add grammar-constrained decoding to the GGUF chat path to fix nondeterministic create_schema JSON truncation - #1844

Merged
malibio merged 3 commits into
mainfrom
worktree-issue-1838-grammar-decoding
Jul 31, 2026
Merged

malibio merged 3 commits into
mainfrom
worktree-issue-1838-grammar-decoding

Conversation

@malibio

@malibio malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Closes #1838

malibio and others added 2 commits July 31, 2026 04:02
apply_chat_template (via llama.cpp's common_chat_templates_apply) already
computes a per-turn, per-active-tool-set grammar in ChatTemplateResult, but
generate_blocking discarded it and sampled with only a repetition penalty
and temperature. Nothing structurally prevented the model from emitting an
EOG token mid-tool-call JSON.

Mirrors llama.cpp's own common_sampler_init (common/sampling.cpp): selects
LlamaSampler::grammar or grammar_lazy_patterns per grammar_lazy, converts
Word/Pattern/PatternFull/Token triggers exactly as upstream does (regex-
escaping Word triggers, anchoring PatternFull), and runs the grammar first
in the chain. A turn with no tools gets grammar: None from llama.cpp itself,
so plain chat is unaffected.

Co-Authored-By: Claude <[email protected]>
grammar_first=true crashed the daemon: llama.cpp's lazy-grammar
trigger-replay path (llama_grammar_accept_impl in llama-grammar.cpp)
hits GGML_ASSERT(!stacks.empty()) -- a hard, uncatchable process abort
-- once the grammar is applied on every token from the start, confirmed
reproducible on a live E4B run right after a lazy trigger fired.

Mirrors common_sampler_sample's default (common/sampling.cpp) exactly:
sample once with no grammar; only if that pick is grammar-invalid,
resample with the grammar applied ahead of the base chain. This is
upstream's own default configuration, not a novel mode, and exercises
the fragile trigger-replay path far less aggressively.

Re-ran the full agent-matrix eval against a real E4B model after this
change: no crash, and the exact scenario this issue targets (3, schema
creation with several fields) passed with a clean create_schema call.

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

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Net positive change that fixes a real, evidence-backed reliability bug (nondeterministic create_schema JSON truncation, scenarios 3/8a/8b) with a implementation that closely mirrors llama.cpp's own common_sampler_sample default, validated against a live E4B model and the full agent-matrix eval. The design evolution documented across the two commits (grammar-first → crash → rejection sampling) shows good engineering discipline: a real crash was found via live-model testing (not just unit tests), root-caused to a specific upstream GGML_ASSERT, and the fix switched to upstream's own safer default rather than papering over the crash.

There is one substantive correctness bug in sample_with_grammar_rejection: chain.accept() is called twice on the same token along the "no grammar" and "first-pick-valid" paths. It is not a regression introduced by this PR — the identical double-accept pattern existed in the pre-PR code (sampler.sample(ctx, idx); sampler.accept(new_token);) — but the PR is the right place to fix it since the function is being rewritten anyway, and it's worth understanding before merge.

Trigger conversion (convert_grammar_triggers, regex_escape) is byte-for-byte faithful to upstream's common_sampler_init/regex_escape (common/sampling.cpp line 185ff, common/common.cpp:460), including the PatternFull anchoring and the empty-pattern edge case. Grammar state is correctly scoped fresh per call to generate_blocking (confirmed: tmpl_result and grammar_sampler are both local let bindings created inside the function, not fields carried across turns).

Findings

Critical Issues

None that should block merge given the live-model validation already performed, but the double-accept below is a real bug worth fixing (see Improvements).

Suggested Improvements

🟡 chain.accept() is called twice per token on the two most common paths (pre-existing bug, not a regression)
📁 packages/nlp-engine/src/chat/mod.rs:91-95 and :112-116

LlamaSampler::sample() in the vendored llama-cpp-2 crate wraps llama.cpp's C llama_sampler_sample(), which — per llama-sampler.cpp:868 — already calls llama_sampler_accept(smpl, token) internally before returning:

llama_sampler_apply(smpl, &cur_p);
...
auto token = cur_p.data[cur_p.selected].id;
llama_sampler_accept(smpl, token);   // <-- implicit accept, inside sample()
return token;

For a chain-type sampler, accept recurses into every child (llama_sampler_chain_accept, llama-sampler.cpp:630), including penalties, whose accept (llama-sampler.cpp:2638) pushes the token onto its ring buffer and increments its frequency-count map. So:

let token = chain.sample(ctx, idx);  // chain.accept(token) already fired here, internally
chain.accept(token);                  // fires again, explicitly

This means penalties' ring buffer (penalty_last_n=256) and count map receive every generated token duplicated — once via the implicit accept inside sample(), once via the explicit call. The practical effect is the repetition-penalty window fills at roughly double the intended rate and each token's repeat-count is inflated by one, making the penalty measurably more aggressive than upstream's calibration intends. This is not a crash risk and evidently didn't break the agent-matrix eval, but it is a real state-corruption bug, not a stylistic nit — grounded in "don't call a stateful mutator twice when you mean once."

Compare to the resample path (:118-129), which gets this right: chain.apply(&mut data_array) (a pure llama_sampler_apply, no internal accept) followed by exactly one explicit chain.accept(resampled) — this matches upstream's common_sampler_sample resampling block exactly, which never calls accept internally and relies on the caller's single common_sampler_accept afterward.

Root cause: this codebase's original code (origin/main, pre-PR) already had this exact pattern — sampler.sample(ctx, idx); sampler.accept(new_token); — so the bug predates this PR. sample_with_grammar_rejection faithfully carried the pattern forward into the no-grammar and valid-first-pick branches while introducing the correct behavior on the resample branch, creating an inconsistency between the three paths in the same function.

Fix: drop the explicit chain.accept(token) on the two paths that use chain.sample() (it already happened internally), keeping only grammar_sampler.accept(token) where applicable. Equivalent to upstream's common_sampler_sample, where chain-equivalent accept only ever happens once per emitted token regardless of which of the three branches was taken.

🟢 Test coverage gap for sample_with_grammar_rejection is reasonable to accept, but note the seam
📁 packages/nlp-engine/src/chat/mod.rs:1049-1085

The rejection-sampling function itself has no direct unit test — it needs a loaded model/context (LlamaContext, token_data_array_ith) to exercise meaningfully, and the PR instead relies on live-model validation (E4B, agent-matrix eval scenario 3 flip, crash-scenario re-test). Given the constraints (no mock-friendly seam for LlamaContext/LlamaSampler, which are thin FFI wrappers over a loaded ggml context), this is an acceptable trade for velocity — but the double-accept bug above is exactly the kind of defect a pure-Rust unit test could have caught if the token-array bookkeping were extracted behind a testable trait (e.g., a SamplerChain trait with sample/apply/accept that a fake could implement to assert call counts). Not blocking, but worth a follow-up if this function needs to change again — a call-count-asserting fake would have caught the double-accept directly instead of requiring cross-referencing the vendored C++ source.

The 8 new tests for convert_grammar_triggers/regex_escape are well-targeted at the actual risk surface (anchoring edge cases, mixed trigger types, non-double-anchoring) and all pass.

Nitpicks

  • Nit: packages/nlp-engine/src/chat/mod.rs:1035-1041 — the block comment at the grammar_sampler construction site and the doc comment on sample_with_grammar_rejection (:1002-1023) repeat almost the same crash-rationale narrative. Consider trimming the inline comment at the call site to a one-line pointer ("see sample_with_grammar_rejection doc comment for why this is rejection sampling, not grammar-first") and keeping the full narrative in one place — CLAUDE.md's comment-quality guidance is about explaining non-obvious WHY once, not restating it at every touch point.
  • Nit: regex_escape and convert_grammar_triggers are gated #[cfg(any(feature = "chat-service", test))] rather than just #[cfg(feature = "chat-service")] like sample_with_grammar_rejection and build_grammar_sampler — presumably so the unit tests can run without the full chat-service feature enabled. Confirmed this isn't a lint-suppression workaround, just a feature-gate scoping choice; harmless, but worth a one-line comment explaining why these two functions need the wider gate when their callers don't.

Requirements Check (issue #1838)

  • ✅ Grammar-constrained decoding wired into the GGUF chat sampler chain, scoped to the active tool set via llama.cpp's own per-turn ChatTemplateResult.grammar
  • ✅ Scenarios 3/8a/8b: scenario 3 (the explicitly named target) confirmed passing on a live E4B re-run per the commit message; 8a/8b are stated as covered by "no new failure modes" but the commit message doesn't explicitly reconfirm 8a/8b individually — worth a comment on the PR/issue confirming those two specifically before closing, since the issue's acceptance criteria name all three
  • ✅ No regression on previously-passing scenarios, per the full agent-matrix re-run cited in the commit message
  • ✅ Grammar scope is per-active-tool-set, not global — tmpl_result.grammar is None whenever has_tools is false in llama.cpp's own common_chat.cpp, confirmed structurally (not just asserted) since build_grammar_sampler returns Ok(None) on an absent/empty grammar string and the sampling loop is provably a no-op in that case
  • ⚠️ "Eval run purges the DB and rebuilds the daemon before scoring" — this is a process requirement for the eval run itself, not something visible in the diff; take on faith per the commit message's description of the validation methodology, per project convention (reference_matrix_eval_needs_purge_and_rebuild)

Standard Checks

  • Security: No user input reaches this code as unsanitized text that affects control flow beyond token sampling; grammar strings come from llama.cpp's own template-derived JSON-schema-to-GBNF conversion, not directly from user input. No secrets, no injection surface introduced.
  • Error handling: build_grammar_sampler correctly propagates GrammarError as a typed ChatError::InferenceError rather than panicking; the one .expect() (:125, resampled-token extraction) is justified by the invariant that the chain always ends in dist/greedy which always selects — matches upstream's own GGML_ASSERT(cur_p.selected != -1 ...) at the equivalent point, so an expect here is the direct Rust analog of upstream's own hard assertion, not a laziness shortcut.
  • Performance: The second logits pass only happens on the rejection branch (grammar-invalid first pick), not the hot-path average case — matches upstream's own perf characteristics exactly since this is a line-by-line port of common_sampler_sample. No new allocation-per-token concern beyond what upstream already accepts as the cost of grammar-constrained decoding.
  • CLAUDE.md compliance: No lint suppressions (#[allow(...)]) introduced; clippy runs clean on this file with --features chat-service; no raw console.log-equivalent misuse (tracing macros used consistently with the rest of the file); no unrelated changes bundled in — single file, single cohesive concern.

Recommendation: COMMENT

The implementation is sound in its overall design and the design evolution (grammar-first crash → rejection sampling) reflects real engineering rigor backed by live-model evidence, not just unit tests. The double-accept issue is real but pre-existing (not introduced by this PR) and evidently not severe enough to have shown up in the agent-matrix eval — it inflates the effective repetition penalty rather than causing incorrect grammar/tool-call behavior. Given it predates this PR and this PR's actual target (grammar-constrained decoding to fix truncated JSON) is otherwise correctly and carefully implemented, I'm not blocking merge on it, but recommend either fixing it in this PR (since the function is already being touched and the fix is a one-line deletion on two branches) or filing a fast-follow issue explicitly so it doesn't get lost.

@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 detailed findings in the comment above. One real (pre-existing, not a regression) double-accept bug found in sample_with_grammar_rejection worth a fast-follow; everything else (trigger-conversion fidelity, per-turn grammar scoping, test coverage rationale, CLAUDE.md compliance) checks out. Recommending COMMENT rather than blocking, given live-model validation already performed.

LlamaSampler::sample() wraps llama_sampler_sample(), which already calls
llama_sampler_accept() internally before returning (confirmed in the
vendored llama-sampler.cpp). The no-grammar and valid-first-pick branches
called chain.accept() again explicitly, double-applying penalties' ring
buffer and frequency count for every generated token -- inflating the
repetition penalty beyond its calibrated strength. Predates this PR
(origin/main had the same sample()+accept() pattern); caught during
/pragmatic-code-review while sample_with_grammar_rejection was already
being rewritten, so fixed here rather than filed as a follow-up.

The resample branch was already correct: it uses chain.apply() (pure,
no internal accept) followed by exactly one explicit chain.accept(),
matching upstream's common_sampler_sample resampling block.

Re-ran the full agent-matrix eval against a live E4B model after this
change: no crash, same 7/12 pass pattern as before (scenario 3 still
clean), confirming the fix doesn't destabilize generation.

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

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the double-accept bug flagged in review (commit 60f120f): chain.sample() wraps llama_sampler_sample, which already calls llama_sampler_accept internally before returning (confirmed directly against the vendored llama-sampler.cpp). The no-grammar and valid-first-pick branches were calling chain.accept() again explicitly, double-applying the repetition penalty's ring buffer and frequency count per token. Removed the redundant explicit accept on both paths; the resample branch was already correct (it uses chain.apply(), which doesn't accept internally, so its one explicit chain.accept() was right).

Confirmed this predates the PR (origin/main had the identical sampler.sample(); sampler.accept(); pattern) — fixed here rather than filed as a follow-up since the function was already being rewritten.

Re-ran the full agent-matrix eval against a live E4B model after the fix: no crash, same 7/12 pass pattern as the earlier validation run (scenario 3 — this issue's target — still clean).

Left the two nitpicks as follow-ups where appropriate: trimmed the duplicated crash-rationale comment at the call site down to a pointer at the function's doc comment (which keeps the full narrative in one place); left the cfg(any(feature = "chat-service", test)) gate as-is since it's an existing repo-wide convention (17 other occurrences in this same file), not something specific to this PR that needs its own explanation.

@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review of fix commit 60f120f (double-accept bug)

Scope: this is a re-review of the follow-up fix only, per the previous COMMENT-level review at 4c58081 which flagged a double-accept bug in sample_with_grammar_rejection. Not re-litigating trigger-conversion fidelity, per-turn grammar scoping, or the eval — those were already covered and are unchanged by this diff.

Verdict: the fix is correct and complete.

1. Both flagged branches fixed

  • No-grammar branch (mod.rs:1045-1051): now return chain.sample(ctx, idx); with no follow-up chain.accept().
  • Valid-first-pick branch (mod.rs:1071-1074): now grammar_sampler.accept(token); return token; — the redundant chain.accept(token) is gone; grammar_sampler.accept correctly remains since the grammar sampler doesn't get an implicit accept from chain.sample().

2. Resample branch (previously correct) is untouched

Confirmed via git diff 4c580818..60f120fb — the resample branch (mod.rs:1076-1088) is byte-identical. chain.apply() (pure llama_sampler_apply, no internal accept) followed by exactly one explicit chain.accept(resampled) plus grammar_sampler.accept(resampled), matching upstream's common_sampler_sample resampling block.

3. No return-semantics change from removing the explicit accept

Checked the vendored llama-cpp-2 v0.1.146 source directly (the version this workspace resolves to, via cargo tree -i llama-cpp-2): LlamaSampler::sample() (sampling.rs:28-34) is a pure passthrough to llama_cpp_sys_2::llama_sampler_sample, returning LlamaToken(token) with no other Rust-side side effects. accept() only mutates internal sampler state (ring buffer / frequency counts) — it has no bearing on what token was already selected. Removing the redundant call is a pure no-op with respect to the returned token, exactly as diagnosed in the original finding.

4. No remaining double-accept, no new under-accept

Traced all three branches at HEAD:

  • No-grammar: chain.sample() → 1 implicit accept. Correct (no grammar sampler to accept into).
  • Valid-first-pick: chain.sample() (1 implicit) + grammar_sampler.accept() (1 explicit). Correct — grammar sampler isn't part of chain, so it needs its own accept.
  • Resample: chain.apply() (0 accepts) + grammar_sampler.accept() + chain.accept() (1 explicit each). Correct — this is the only path where chain never called sample(), so the explicit accept is necessary, not a dupe.

Every path accepts chain exactly once and grammar_sampler exactly once (when present). No double-accept remains, and no path is left under-accepted.

5. Nitpicks (informational, non-blocking, as originally flagged)

  • Comment duplication: addressed — the ~20-line duplicated crash-rationale block at the grammar_sampler construction site was trimmed to a 4-line pointer at sample_with_grammar_rejection's doc comment, consolidating the narrative in one place.
  • #[cfg(any(feature = "chat-service", test))] gate: left as-is per the follow-up comment's claim that it's a pre-existing repo-wide convention. Independently verified: this exact pattern appears 17 other times in this same file. Reasonable to leave unaddressed.

Additional verification performed

  • Read the full sample_with_grammar_rejection function at HEAD in one pass (not just the diff hunks) to confirm end-to-end correctness.
  • Confirmed the resolved llama-cpp-2 version (0.1.146) and inspected its sample/accept implementations directly from the local cargo registry cache.
  • cargo build --features chat-service --lib — clean.
  • cargo test --lib --features chat-service — 115 passed, 0 failed, including all trigger-conversion tests (regex_escape_*, pattern_*_trigger_*, mixed_triggers_split_correctly, etc.) from the original review.

The fix does exactly what the original diagnosis prescribed, on exactly the two branches it named, without touching the branch that was already correct. Combined with the live E4B re-validation reported in the follow-up comment (no crash, same 7/12 pass pattern, scenario 3 clean), this closes out the one substantive finding from the prior review.

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

Re-review of fix commit 60f120f: VERDICT = APPROVE (submitted as COMMENT review — GitHub blocks self-approval on this PR's own author account). The double-accept bug flagged in the prior review is correctly and completely fixed on both branches, the already-correct resample branch is untouched, and no new double- or under-accept path was introduced. Build clean, 115/115 lib tests pass. Full details in the review comment above. No merge action taken.

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.

Add grammar-constrained decoding to the GGUF chat path to fix nondeterministic create_schema JSON truncation

1 participant