TL;DR
While grammar-constrained decoding ensures that LLM-generated code is syntactically correct, it cannot prevent semantic hallucinations like referencing undefined variables or missing database columns. This paper introduces decode-time grammars, a method that dynamically updates the token mask based on the evolving runtime environment to eliminate these "ghost references" by construction. Across SQL, P4, and tensor DSLs, this approach achieves perfect reference safety with only a minor impact on generation throughput.
What Problem Does This Paper Address?
When LLMs generate code for domain-specific languages (DSLs), custom APIs, or command-line tools, they frequently hallucinate identifiers. They might reference a buffer that was never allocated, a database column that doesn't exist, or an unsupported CLI flag. The authors term these environment-invalid errors ghost references.
Standard grammar-constrained decoding fails to solve this problem. A fixed context-free grammar (CFG) can easily enforce that an operand must be an identifier, but it cannot ensure that the identifier matches a previously declared variable. Because declaration-before-use consistency is fundamentally non-context-free, the constraint must dynamically adapt to the code that has already been generated.
Methods
The authors propose a framework called gproj that shifts grammar constraints from fixed, static rules to dynamic, environment-indexed fragments. The core components include:
- Decode-Time Grammars & The Tightening Operator ($\tau_\Gamma$): As the LLM generates code, the system tracks the live runtime environment ($\Gamma$), such as declared variables or database schemas. When the model hits a reference position (a "hole"), the tightening operator replaces generic identifier rules with a specific slot containing only the valid candidates currently available in $\Gamma$.
- Refinement Order ($\sqsubseteq$): Grammars are organized hierarchically from loose (base CFG) to tight (fully pinned values). A per-region policy ($\pi$) decides how strictly to constrain a hole, allowing the system to gracefully fall back to looser constraints if a strict match isn't available.
- TemplateInductor: To avoid writing these grammar fragments by hand, the authors designed an offline tool that uses anti-unification to automatically learn grammar templates from a small corpus of example programs, validating them through an agentic loop against a strict parser gate.
Datasets
The approach was evaluated across several distinct programming surfaces:
- TileLang: A low-resource tensor-kernel DSL used for high-performance GPU programming.
- SQL: Evaluated using database schemas from the standard Spider dataset benchmark.
- P4: A data-plane programming language for network packet processing (tested on
basic.p4andl2fwd.p4structures). - CLI & APIs: Evaluated using live tool states for Git commands, FFmpeg filter complexes, and AVX-512 compiler headers.
Key Insights and Ideas
- The "Division of Labor": The authors argue that code generation should split mechanical correctness from open-ended algorithmic choices. The grammar mask handles the mechanical task of ensuring identifiers exist, freeing the LLM to focus entirely on high-level logic, structure, and intent.
- Dynamic Support is Mathematically Necessary: The paper formally proves that no finite family of precompiled, static grammars can be both ghost-free and non-blocking over an unbounded identifier space. The token mask must be synthesized dynamically from the prefix at runtime.
- Immunity to Model Size: Because the constraints are enforced at the token-mask level, the "no-ghost" guarantee holds true regardless of whether you are using a lightweight 0.6B parameter model or a massive 236B frontier model. Stronger models simply provide better high-level sketches, while the reference layer remains perfectly secure.
Key Results
- Zero Ghost References: Across all tested models (Qwen3-0.6B, GPT-OSS-20B, DeepSeek-V4-Flash) and programming languages,
gprojeliminated ghost references entirely by construction. - Perfect Execution Match: On a difficult subset of Spider SQL tasks, restricting the LLM to the valid schema columns boosted the execution match rate from 76% (unconstrained) to 100% in a single pass, outperforming traditional prompting and retry strategies.
- Low Serving Overhead: Compared to standard unconstrained decoding,
gprojintroduces an average throughput reduction of only 17.3%. When compared against standard static masking (XGrammar), the incremental cost of the dynamic runtime specialization is in the low teens (10.6%–17.8%), making it highly practical for production deployment.
Limitations and Future Work
While gproj guarantees that every reference is valid within the environment, it does not guarantee functional correctness. For example, in SQL, the model is prevented from inventing a column, but it can still select the wrong valid column and produce an incorrect query result.
Additionally, the current implementation faces engineering limitations: the Times repetition combinator does not yet support nested grammar calls, and cross-boundary type agreement requires a manual mapping between host and embedded vocabularies. The authors suggest that extending this runtime decode-loop interface to handle richer, stateful semantic monitors and learned switching policies is the next logical step.
Summary updated