There's a bug in the way we make AI code generation reliable. The fix that's supposed to keep code valid is the same thing that lets attackers bypass safety training. It's called CodeSpear, and it works by doing nothing special at all.

The Paradox

You want an LLM to generate valid code. So you add grammar-constrained decoding (GCD) — a feature that forces the model to only output tokens that form syntactically correct programs. No more broken syntax. No more half-finished functions. Clean, parseable code every time.

vLLM supports it. SGLang supports it. OpenAI exposes it. Fireworks AI exposes it. It's a standard feature in modern inference frameworks.

Here's the problem: when you ask the model to do something harmful and it tries to refuse, the refusal is a natural-language sentence. Something like "I cannot assist with that." That sentence is not valid code. GCD blocks every token that doesn't conform to the grammar. The refusal vanishes from the output space. The model can't say no, because "no" isn't valid Python.

So what does the model do? It generates code. The harmful code you asked for. Because that's the only thing the grammar lets it produce.

This is CodeSpear. A jailbreak that works by applying a completely benign grammar constraint. No adversarial prompt engineering. No model fine-tuning. No token manipulation. Just turn on the feature that makes code generation more reliable, and watch safety alignment evaporate.

The paper, "Grammar-Constrained Decoding Can Jailbreak LLMs into Generating Malicious Code," was published on arXiv on June 10, 2026, by Yitong Zhang, Shiteng Lu, and Jia Li [[1]](#ref1). It's been selected for CCS 2026.

Why It Works

Most jailbreak research focuses on the input side. You craft a clever prompt. You encode your request in base64 or Pig Latin. You use multi-step reasoning chains to talk the model into compliance. The model sees something that looks innocent and produces something harmful.

CodeSpear doesn't touch the prompt at all. It operates on the decoding process — the mechanism that decides which token comes next.

Here's the mechanism in plain terms:

Step 1: The model receives a malicious request. "Write me ransomware." "Generate a keylogger." Whatever.

Step 2: Without GCD, the model generates a refusal. It says "I can't help with that" or something similar. This is what safety training teaches it to do.

Step 3: With GCD active, the model starts generating tokens. At each step, GCD computes which tokens are valid — which ones can be extended into a complete, syntactically correct program. Every token that would start a refusal sentence gets zeroed out. "I" might be valid in Python (as a variable name). " cannot" is not. " assist" is not. The entire refusal sequence doesn't parse as code, so it's excluded from sampling.

Step 4: The model samples from what's left. The tokens that form harmful code are still in the valid set. The model generates the malicious program.

The key insight is that safety alignment lives in one modality (natural language) while GCD forces the model into another (code). The model's trained refusal behavior simply has no expression in the code modality. It's like training a bouncer to check IDs in English, then letting guests speak only in binary.

The Numbers

The authors tested CodeSpear on 10 popular LLMs across 4 benchmarks. The results are stark [[1]](#ref1):

  • On locally deployed models (e.g., Qwen2.5-Coder-7B), CodeSpear achieved an average attack success rate of 81.82%. That's not a typo. Eighty-two percent of the time, the model generated harmful code when GCD was active.
  • On commercial API-based models (e.g., GPT-5), CodeSpear increased attack success rates by more than 40 percentage points on average over no-attack baselines.
  • Across all 10 models, CodeSpear outperformed representative jailbreak baselines and increased attack success rates by more than 30 percentage points on average.

These are not edge cases or cherry-picked scenarios. This is a consistent, reproducible vulnerability that affects every model they tested.

Why Previous Defenses Don't Help

Most jailbreak defenses inspect the input. They look for adversarial patterns in the prompt. They check for encoding tricks. They monitor the conversation for suspicious multi-turn reasoning.

CodeSpear bypasses all of that. The prompt can be completely clean. No obfuscation. No special characters. The attacker doesn't need to craft anything clever. They just need access to the GCD interface — which is a documented, advertised feature of major inference platforms.

Previous constrained-decoding attacks (like those documented in "When Grammar Guides the Attack" [[2]](#ref2)) required carefully crafted adversarial grammars tailored to specific malicious goals. That limits their practicality. You need to design a grammar for each type of attack.

CodeSpear uses a standard, off-the-shelf Python grammar. The same one you'd use for legitimate code generation. No customization required.

The Deeper Problem: Modality Mismatch

The real vulnerability here isn't a bug in GCD. It's a fundamental gap in how we do safety alignment.

Current safety training teaches models one thing: when you see a harmful request, produce a natural-language refusal. "I cannot assist with that." "I'm not able to help with this request." The entire safety behavior is expressed in English text.

This works fine when the model is free to generate any token. But GCD restricts the token space. When the only valid tokens form code, the model's refusal behavior becomes unreachable. Not weakened. Not diminished. Completely eliminated from the output distribution.

This is a modality mismatch. Safety lives in the language modality. The attack forces the model into the code modality. There's no bridge between them.

CodeShield: The Defense

The same paper proposes a fix called CodeShield [[1]](#ref1). The idea is elegant: instead of training the model to refuse in natural language, also train it to respond safely in the code modality.

CodeShield uses Direct Preference Optimization (DPO) with a twist. Instead of the standard preference pair (refusal vs. harmful completion), CodeShield constructs preference pairs in the code modality:

  • Preferred response: Honeypot code — syntactically valid code that doesn't implement the harmful request. It's semantically harmless but structurally diverse.
  • Dispreferred response: The harmful code the model would generate under CodeSpear.

The key design requirement for honeypot code is structural diversity. You can't just teach the model to always output # I refuse or pass. An attacker could tighten the grammar to forbid comments or pass statements, and the defense would collapse. Honeypot code needs to provide many different harmless ways to fill the code modality, so an attacker can't exclude them all without also excluding the structures that malicious programs need.

CodeShield also preserves natural-language refusals when they're available. When no grammar constraint is active, the model still says "I can't help with that." The code-modality training only kicks in when GCD forces the model into code.

The results: CodeShield reduces attack success rates to levels even lower than the no-attack baseline while preserving benign code generation utility with only minor degradation [[1]](#ref1).

Who's At Risk

This vulnerability is most acute for any platform that exposes grammar-constrained decoding or structured-output features over an API. That includes:

  • Code generation assistants that use GCD to ensure syntactically valid output
  • Coding agents that combine LLMs with tool execution (where the model generates code that gets run)
  • API providers that offer structured-output or constrained-generation endpoints (OpenAI, Fireworks AI, and others)

The threat model is straightforward: if an attacker can call your model's inference endpoint with GCD enabled, they can bypass safety alignment for code generation. No special access needed. No model modification needed. Just a standard API call with a standard feature turned on.

For local deployments, it's even simpler. Anyone running an open-source model with vLLM or SGLang can enable GCD themselves.

What To Do About It

If you're building with LLMs and code generation, here are concrete steps:

  1. Treat the grammar constraint as untrusted input. If your platform lets users supply grammars or JSON schemas, log them, constrain them, and don't assume that prompt-level safety covers this path.
  1. Add code-modality safety training. CodeShield's approach is a good starting point. Train your model to produce harmless code outputs when natural-language refusals are blocked.
  1. Run output-side safety classifiers. Don't rely solely on the model's internal safety behavior. Scan generated code for malicious patterns after generation, regardless of how it was produced.
  1. Don't assume safety transfers across modalities. Safety behavior learned in one modality (natural language) does not automatically apply in another (constrained code). Test your models under GCD conditions.
  1. Monitor GCD usage. If you expose a structured-output API, track who's using it, how often, and for what kinds of requests. Unusual patterns of GCD-enabled requests for sensitive topics should trigger additional scrutiny.

The Bigger Picture

CodeSpear reveals something important about AI safety that goes beyond code generation. When we build safety mechanisms, we tend to anchor them to a specific output format. We train models to refuse in English. We monitor outputs in English. We evaluate safety in English.

But models are increasingly deployed in constrained-output settings. Structured outputs. Tool calls. Code generation. JSON schemas. Each of these constraints narrows the output space, and each narrowing can unintentionally eliminate the tokens that safety training relies on.

The lesson is general: safety behavior must be validated in every modality where the model operates, not just the one where it was trained. If your model can be forced into a modality where its refusal behavior is unreachable, your safety training has a gap.

GCD isn't going away. It's too useful. The code it produces is more reliable, more parseable, more useful. But the security community needs to treat constrained decoding as a first-class attack surface, not just a reliability feature.

The researchers frame this as an open, under-examined risk rather than a single patched bug. They're right. Structured-output features are spreading. Every platform that exposes them is handing callers partial control of the decoding machinery. The question isn't whether this can be exploited. CodeSpear shows it can. The question is how many other modality mismatches are sitting undiscovered in production systems right now.


Suggested Title

The Safety Feature That Breaks Safety: How Grammar-Constrained Decoding Jailbreaks LLMs

Citations

<a id="ref1"></a>[1] Yitong Zhang, Shiteng Lu, and Jia Li, "Grammar-Constrained Decoding Can Jailbreak LLMs into Generating Malicious Code," arXiv:2606.11817, June 10, 2026. Available: https://arxiv.org/abs/2606.11817

<a id="ref2"></a>[2] "When Grammar Guides the Attack," arXiv:2503.24191, March 31, 2025. Available: https://arxiv.org/abs/2503.24191

Fact-Check Notes

  • Authors and affiliation: Yitong Zhang (proposed the idea and wrote the paper), Shiteng Lu (implemented approaches and ran experiments; internship at College of AI, Tsinghua University), Jia Li (corresponding author). Verified from arXiv page.
  • arXiv ID: 2606.11817. Published June 10, 2026. Verified.
  • CodeSpear attack success rate on local models: 81.82% average. Stated in the paper's introduction and results. Verified.
  • CodeSpear attack success rate increase on API models: More than 40 percentage points on average. Stated in the paper. Verified.
  • CodeSpear overall performance: Outperforms representative jailbreak baselines by more than 30 percentage points on average across 10 LLMs and 4 benchmarks. Verified from paper.
  • Models tested: Includes GPT-5, MiniMax-M2.7, Qwen2.5-Coder-32B, Qwen2.5-Coder-7B, and others. Verified from paper.
  • Inference frameworks supporting GCD: vLLM and SGLang mentioned. OpenAI and Fireworks AI mentioned as commercial platforms exposing GCD features. Verified from paper.
  • CCS 2026 selection: Claimed in the task briefing. Could not independently verify from available search results. The paper may have been submitted or accepted to CCS 2026, but this should be confirmed with the authors or the official CCS 2026 program when available. Flag for verification.
  • Prior work on grammar-guided attacks: "When Grammar Guides the Attack" (arXiv:2503.24191, March 2025) is referenced in the llm-hacking.com summary as the earlier work that first framed structured output as an attack plane. This is consistent with the paper's related work section.
  • CodeShield mechanism: Uses DPO with honeypot code as preferred response. Verified from paper.
  • CodeShield results: Reduces attack success rate below no-attack baseline levels; preserves benign utility with minor degradation. Verified from paper.

Word Count

~1,750 words