JSON Schema grammar fails on chat-template control tokens while equivalent GBNF succeeds (Granite 3.1 / Qwen3)
Name and Version
llama.cpp 0.4.1-dev (build 1) commit: b27a525d28381a16a4bb038858a10e4927381ca
Operating systems
Windows
GGML backends
Vulkan
Hardware
AMD Ryzen 7 7735HS AMD Radeon RX 7700S AMD driver 26.6.4 Vulkan 1.4.357 MSVC 19.44.35229.0, CMake 3.31.6-msvc6, Git 2.52.0.windows.1
Models
diagnostic-report.md IBM Granite 3.1 8B Instruct Q3_K_L Qwen3 8B Q4_K_M
Problem description & steps to reproduce
I ran into a reproducible failure where JSON Schema constrained decoding works fine through the raw /completion endpoint, but breaks with an HTTP 400 as soon as I move the same request to /v1/chat/completions and let the chat template do its thing. A direct GBNF grammar doesn't have this problem at all same endpoint, same model, it just works. That difference is what made me suspect the bug lives specifically in json_schema_to_grammar(...), not in the models or the Vulkan backend.
I checked this against two completely unrelated model families and got the exact same failure both times: IBM Granite 3.1 8B Instruct (Q3_K_L, fully offloaded at 41/41 layers) and Qwen3 8B (Q4_K_M, 37/37 layers). Since the failure shows up identically on two models that don't share a tokenizer or chat template family, it doesn't look model specific. What I expected was that /v1/chat/completions plus JSON Schema would behave the same as /completion plus JSON Schema, or the same as /v1/chat/completions plus an equivalent handwritten GBNF just a normal schema valid JSON object coming back either way. What actually happens is that the chat template inserts a model specific control token right before the assistant's content starts, and the grammar built from the JSON Schema apparently has no idea what to do with that token. The grammar stack empties out and the server throws a 400
Unexpected empty grammar stack after accepting piece: <|start_of_role|> (49152) # Granite <|im_start|> (151644) # Qwen3
To reproduce it build llama.cpp with Vulkan (cmake -B build -DGGML_VULKAN=ON, then cmake --build build --config Release), start llama-server with either model, and send a request to /completion using the schema below via --json-schema-file that comes back clean, HTTP 200, valid schema conforming JSON. Send that same schema to /v1/chat/completions instead, and it fails with the grammar stack error shown above. Swap the JSON Schema for an equivalent GBNF grammar on that same chat completions endpoint, and it works again, HTTP 200. Repeat with the second model and you get the identical pattern.
Schema used throughout:
json { "type": "object", "properties": { "action": {"enum": ["ALLOW", "DENY", "REVIEW"]}, "reason": {"type": "string"} }, "required": ["action", "reason"] }
I ran this as a full 2×2×3 matrix (2 models × 2 endpoints × 3 constraint modes) and have the raw outputs plus a reproducible PowerShell script if that's useful. I could not reproduce the failing path with llama-completion because the failure only appears on the server chat endpoint. The raw completion path succeeds with the same JSON Schema for both models. As a workaround, I can replace the JSON Schema constraint with an equivalent direct GBNF grammar. With GBNF, /v1/chat/completions returns HTTP 200 and schema valid JSON on both Granite and Qwen3.
This might be the same underlying issue as #21600 (Qwen 3.5 + --jinja, failing on the
First Bad Commit
I have only reproduced the issue on commit fb27a525d28381a16a4bb038858a10e4927381ca and have not performed a git bisect.
Relevant log output
Granite 3.1 8B:
{"error":{"code":400,"message":"Failed to initialize samplers: Unexpected empty grammar stack after accepting piece: <|start_of_role|> (49152)","type":"invalid_request_error"}}
Qwen3 8B:
{"error":{"code":400,"message":"Failed to initialize samplers: Unexpected empty grammar stack after accepting piece: <|im_start|> (151644)","type":"invalid_request_error"}}
"I'm already working on a fix for this bug; a patch is on the way."
I have experienced a related problem with my Kilo code and local llm via llama-server setup. I had Kilo code check and format a description of the error which is described her:
The Bug: llama.cpp json_schema_to_grammar Produces Ordered-Optional Key Chains
How the Mechanism Works
When llama-server receives a tool-call request with response_format: { type: "json_schema", json_schema: {...} }, it auto-generates a GBNF (Generalized Backus-Naur Form) grammar from the JSON Schema and feeds it to the constrained-decoding layer. Every token the model emits is checked against the grammar; tokens that would violate it get their logits set to −∞ before sampling. This guarantees structurally valid JSON output.
The conversion lives in grammar-parser.cpp / json-schema-to-grammar.cpp (the exact file varies by commit). It walks the schema tree and emits GBNF rules for each construct: objects, arrays, strings, numbers, enums, etc.
The Specific Defect
For a JSON object whose properties are all optional (or have no required array), the generator does not emit a free-ordering rule like:
# Correct: any subset of keys in any order
object = { "{" [ key-value-pair ("," key-value-pair)* ] "}" }
key-value-pair = "prompt" ":" prompt | "name" ":" name | "branchName" ":" branchName | ...
Instead it emits an ordered-optional chain — a single alternation where each branch either includes that key or skips to the next, but never returns:
# Buggy: once you pick "name", "prompt" is unreachable
object = { "{"
( prompt-kv prompt-rest
| name-kv name-rest
| branchName-kv branchName-rest
| model-kv model-rest
| provider-kv provider-rest
| variant-kv variant-rest
) "}" }
prompt-rest = ( "," (name-kv name-rest2 | ...) )?
name-rest = ( "," (branchName-kv ... | ...) )?
# etc. — each branch only allows SUBSEQUENT keys
The grammar dump we captured at D:\llama_server_tmp\llm.log line 75407 confirms this exact shape for the agent_manager.tasks[] item object in build 11391 (commit 2bc563573):
"tasks-item" = "{" ( "prompt" ":" prompt ... | "name" ":" name ... | "branchName" :... ) "}"
Once the model's first token after { is "name" rather than "prompt", the grammar state machine has committed to the name-rest branch, which only permits branchName, model, provider, variant — never prompt. The token "prompt" gets its logits zeroed. The model then emits a valid object without prompt, and Kilo's validation layer rejects it: "A task variant requires an initial prompt."
How Kilo's Schema Triggers It
The agent_manager tool schema (from the Kilo extension) defines each tasks[] item as:
{
"type": "object",
"properties": {
"prompt": { "type": "string" },
"name": { "type": "string" },
"branchName": { "type": "string" },
"model": { "type": "string" },
"provider": { "type": "string" },
"variant": { "type": "string" }
}
}
No required array — every property is optional at the schema level. The generator sees six optional keys and produces the six-branch ordered chain. Qwen3.8-27B's token-level generation bias does not always pick "prompt" first; when it picks "name" (a common early choice because "name" is a high-frequency, short string), the grammar locks out prompt permanently.
Why This Is a Bug in llama.cpp, Not in Kilo
-
The JSON Schema is correct. A schema with all-optional properties means any subset of keys in any order is valid. The grammar must accept that language. The ordered chain accepts a strict subset — it rejects perfectly valid documents like
{"name": "x", "prompt": "y"}. -
The constraint layer's contract is to be lossless. Constrained decoding exists to prevent invalid output, not to silently narrow the valid set. If the grammar rejects a string that satisfies the schema, the system produces a false negative: valid JSON becomes unemittable. There is no signal to the model or the client that "you wanted
promptbut the grammar forbade it" — the token simply never gets sampled. -
The fix belongs in the generator, not the client. The correct GBNF for an all-optional object is:
obj = "{" [ pair ("," pair)* ] "}" pair = "prompt":"..." | "name":"..." | "branchName":"..." | ... used-prompt = false # track via non-terminal states to prevent duplicatesThis is a standard "set of optional keys" construction. It requires the grammar to track which keys have been seen (via state flags or epsilon-transitions), which is more complex than the naive ordered chain — but it is the only form that accepts the full language the schema describes. llama.cpp's generator currently shortcuts this complexity and emits the chain, which is a correctness bug in
json_schema_to_grammar. -
Client-side workarounds are inherently fragile. Telling the model "always emit
promptfirst" (our AGENTS.md convention) relies on the model cooperating — it must override its own generation bias every single time, for every optional-keyed object, in every tool call, in every project. A different model, a longer context, a sampling hiccup, or a schema change that reorders properties can break it silently. The failure mode is the same:promptvanishes, session fails with a cryptic validation error. No amount of prompt engineering makes this as reliable as a correct grammar. -
It affects every consumer, not just Kilo. Any tool definition with optional object properties (function calling in OpenAI-compatible APIs, structured output requests, etc.) hits the same path. Fixing it in the generator fixes all clients at once.
What "Fixed" Looks Like
json_schema_to_grammaremits a permutation-tracking rule for objects with ≥ 2 optional properties, accepting any subset in any order without duplicates.- Alternatively (simpler but less general): when no
requiredarray is present and all properties are of the same scalar type, emit a flatpairalternation with a "seen" bitmask encoded in non-terminal states. - A
--no-structured-outputsor--grammar-mode=freeflag as an escape hatch for users who hit this before the fix lands upstream.
Status
- Build 11391 (
2bc563573) — still broken, confirmed via grammar dump. - No disable flag in either build tested.
- The AGENTS.md prompt-first convention is a stopgap that works in practice on this model/build but provides no guarantee and must be removed (or kept as belt-and-suspenders) once the upstream fix ships.
This issue was closed because it has been inactive for 14 days since being marked as stale.