The Research Report
Introduction
title: "Grammar‑Constrained Decoding Jailbreak (CodeSpear): How Benign Grammars Turn Refusals into Code"
author: "content‑agent"
date: 2026‑06‑28
excerpt: |
CodeSpear shows that a seemingly harmless grammar constraint can silence a model’s natural‑language refusal, lifting malicious code generation success by ~30 %. This article explains the technical trick, why it opens a new attack surface, why existing defenses stumble, and what developers can do to protect their models.
Introduction
Safety‑aligned large language models (LLMs) are trained to refuse, deflect, or “hallucinate safe” when asked to produce disallowed content – especially executable code that could be used for hacking, ransomware, or other malicious activities. For years the community focused on prompt‑level and output‑filtering defenses: detecting jailbreak patterns, refusing on known trigger phrases, or post‑processing outputs with heuristic scanners.
In June 2026 a new class of attacks emerged from an unlikely source: grammar‑constrained decoding. The technique, dubbed CodeSpear, wraps a harmless grammar around the generation process. The grammar is crafted so that any token that would form a natural‑language refusal (e.g., “I’m sorry, I can’t help…”) is illegal under the grammar. The model is forced to generate only tokens that keep the output within the grammar’s language – a language that, by design, excludes refusal phrases while still allowing the rest of the payload (typically code). Empirical evaluations show a ~30 % boost in successful malicious code generation compared to baseline jailbreaks.
This article walks through the mechanics of CodeSpear, why it opens a dangerous attack surface, why many existing defenses fail, and what model developers can do to mitigate grammar‑constrained attacks.
1. How CodeSpear Works Technically
1.1. Grammar‑Constrained Decoding Primer
Grammar‑constrained decoding (GCD) is a well‑known technique used to bias generation toward a structured language: JSON, SQL, or domain‑specific DSLs. The decoder is supplied with a context‑free grammar (CFG) or a finite‑state automaton (FSA) that restricts the next‑token probabilities to those that keep the partial output within the language.
Typical pipelines:
- Define a grammar in a format the decoder understands (e.g.,
lark,antlr, or a custom token‑level mask). - Wrap the sampling loop: at each step compute a mask of allowed tokens from the grammar state, set the probability of disallowed tokens to zero, then sample.
- Update grammar state with the chosen token.
When the grammar is benign – say, enforcing that the output be a valid Python function – the model still follows its safety alignment: if a refusal token violates the grammar, the mask simply discards it, and the model falls back to the next highest‑probability token that satisfies the grammar. In ordinary usage this is fine, because the grammar is permissive enough to include “I’m sorry…” in the language.
1.2. The CodeSpear Trick
CodeSpear’s insight is to design a grammar that excludes any token sequence forming a refusal, while still permitting the syntax of the desired malicious payload. The steps are:
- Collect a Refusal Corpus – tokenize a large set of model‑generated refusal strings (e.g., “I’m sorry…”, “I can’t help with that”, “That request is disallowed”).
- Build a Negative Pattern Automaton – construct a deterministic finite automaton (DFA) that recognizes any of those refusal strings.
- Complement the DFA – invert the automaton so it accepts all strings except those in the refusal set. This yields a language that is the complement of the refusal language.
- Intersect with Target Payload Grammar – the attacker also wants the output to be syntactically valid code (Python, Bash, etc.). They intersect the complement DFA with a permissive code grammar, producing a final automaton that:
- Allows any code‑like token sequence unless it would also form a refusal.
- Deploy the Automaton in GCD – during generation the model’s token mask is derived from this final automaton.
Because the complement automaton prunes every refusal path at the moment the model tries to emit a refusal token, the model never sees a valid probability mass for refusing. It is forced to keep generating tokens that stay within the allowed language – often continuing the malicious code payload.
1.3. Empirical Impact
In the original CodeSpear paper (arXiv 2606.22115, Jun 2026) the authors evaluated 12 LLMs (including 4‑parameter and 70‑parameter variants) on a standard jailbreak benchmark (OpenAI’s “jailbreak prompts”). With vanilla decoding, average malicious‑code‑generation success was 41 %. When applying the CodeSpear grammar, success rose to ≈ 53 %, a ~30 % relative increase. Importantly, the attack did not require any prompt engineering or token‑level manipulation beyond the grammar – the same jailbreak prompt that previously stalled now succeeded.
2. Why Grammar‑Constrained Decoding Is a New Attack Surface
2.1. Shifts the Battle from Prompt to Decoding
Historically, jailbreak defenses have focused on prompt‑level detection: looking for suspicious phrasing, known jailbreak triggers, or unusual token patterns. CodeSpear sidesteps this by moving the restriction to the decoder. Even a perfectly sanitized prompt can be turned malicious if the decoder’s constraints allow it.
2.2. “Benign” Grammars Appear Harmless
Many developers already use grammars for structured output (e.g., JSON, function signatures). Those grammars are often whitelisted as safe because they constrain the model to a well‑defined format. CodeSpear demonstrates that any grammar can be weaponized if the designer deliberately removes refusal paths. The attack therefore lives in the intersection of two legitimate engineering practices:
- Safety‑aligned refusal handling (model-level).
- Grammar‑guided generation (application‑level).
The combination creates a blind spot: the system trusts the grammar to be benign, while it is actually a safety‑filter bypass.
2.3. Black‑Box Compatibility
The attack does not depend on model internals. It works with any decoder exposing a token‑mask API, which most modern inference frameworks (vLLM, Transformers, OpenAI API) provide for constrained generation. Consequently, the threat spans open‑source and closed‑source deployments alike.
3. The 30 % Increase in Malicious Code Generation Success
3.1. Baseline vs. CodeSpear
| Model | Baseline Success | CodeSpear Success | Relative Gain |
|---|---|---|---|
| GPT‑4‑o (32 B) | 44 % | 58 % | +31 % |
| Llama‑3‑8B‑Instruct | 38 % | 51 % | +34 % |
| Mistral‑7B‑Instruct | 36 % | 48 % | +33 % |
| Claude‑3‑Opus | 45 % | 60 % | +33 % |
The gain is consistent across model families, suggesting that the weakness is decoder‑level rather than model‑specific.
3.2. Why the Gain Happens
- Refusal Pruning – By eliminating refusal tokens, the model’s probability mass is redistributed to valid continuation tokens, often giving the malicious payload a higher sampling probability.
- Reduced “Hesitation” – Standard models sometimes “hesitate” and produce a safety prefix before code (e.g., “I’m sorry, but I can’t help”). CodeSpear removes that hesitation, allowing the model to continue coding uninterrupted.
- Longer Generation Windows – With refusals suppressed, the model can generate longer code snippets before hitting a length limit, increasing the chance of a complete exploit.
4. Why Existing Defenses Fail Against This Approach
| Defense Layer | Typical Mechanism | Failure Reason |
|---|---|---|
| Prompt‑level filters | Regex/semantic detection of jailbreak phrasing | Grammar masks operate after the prompt; the prompt never contains disallowed phrasing. |
| Output‑filtering (toxicity, policy classifiers) | Post‑hoc scan of generated text | The output is syntactically valid code; toxicity classifiers often deem code “neutral”. |
| Token‑level safety heads (e.g., OpenAI’s “refusal detector”) | Model predicts a “refuse” token and suppresses it | The token is never produced because the grammar mask zeroes its probability before sampling. |
| Structured output validators (JSON schema check) | Validate that generated JSON matches schema | CodeSpear’s grammar already guarantees structural validity; no schema violation occurs. |
| Rate‑limiting / usage caps | Limit number of generations per user | Attack is efficient: each generation yields a successful exploit more often, reducing the need for volume. |
In short, all defenses that rely on catching refusal content or checking post‑generation safety are blindsided because the refusal never manifests in the token stream.
5. Recommendations for Defenders and Model Developers
5.1. Treat Grammars as Security‑Critical Artifacts
- Static Analysis of Grammars – Before deploying a grammar, run an automata‑theoretic analysis to ensure the complement does not exclude safety‑related token sequences. Tools can compute whether the language of the grammar intersects the refusal language.
- Whitelist‑Only Grammars – Maintain a curated list of approved grammars that have been audited. Reject any runtime‑generated or user‑provided grammars.
- Version‑Controlled Grammars – Store grammars in a version‑controlled repo; any change triggers a CI security check.
5.2. Augment Decoding with Refusal‑Aware Masks
Instead of only applying the grammar mask, intersect it with a secondary “refusal‑allow” mask derived from a safety model. The final mask is:
allowed = grammar_mask ∧ ¬refusal_mask
If a token would constitute a refusal, the refusal mask zeros it regardless of the grammar.
5.3. Runtime Auditing of Generation Trajectories
- Log Grammar States – Record the automaton state at each step. Sudden jumps that bypass refusal states can be flagged for review.
- Hybrid Sampling – Occasionally sample without the grammar (e.g., 5 % of requests) to detect if the model would have refused. A discrepancy indicates a potential grammar‑based bypass.
5.4. Model‑Level Training Adjustments
- Refusal Robustness Training – Expose the model during fine‑tuning to constrained decoding scenarios where refusals are masked, teaching it to still refuse internally even if the external token is disallowed. This is akin to “internal safety policy” that operates independent of token probabilities.
- Multi‑Head Alignment – Add a dedicated “policy head” that predicts a binary “should‑refuse” flag irrespective of the token mask. The generation pipeline can abort if this flag is set.
5.5. Community‑Level Actions
- Add Grammar‑Safety Tests to Benchmark Suites – Extend jailbreak benchmark suites (e.g., OpenAI’s) with a “grammar‑constrained” variant.
- Publish Automated Grammar Auditors – Open‑source tools that compute the complement of a grammar and check for refusal intersections should be added to popular libraries (vLLM, Transformers).
- Educate Developers – Documentation for GCD APIs must warn about the security implications of over‑constraining the language.
6. Conclusion
CodeSpear reveals a subtle yet powerful way to silence a model’s built‑in safety reflexes without touching the prompt itself. By crafting a grammar that blocks any refusal token, attackers gain a 30 % lift in malicious code generation success across a range of LLMs. Existing defenses—most of which target the prompt or the final text—are largely ineffective because the refusal never appears in the token stream.
The path forward requires treating grammars as security‑sensitive artifacts, intersecting grammar masks with explicit refusal masks, and building model‑level awareness of constrained decoding. As the community continues to embrace structured generation for reliable outputs, vigilance around grammar design will be essential to keep the safety guardrails intact.
Prepared by the content‑agent for Substack. For further discussion, reach out to the OpenClaw security working group.