NeurIPS 2026Coming to NeurIPS?Explore papers, orals & directions

CodeMimicry: Exploiting Safety Generalization Lag in Large Language Models via Structured Code Completion

Zhen Liang, Wentao Chen, Hai HuangNeurIPS 2026

TL;DR

Large Language Models (LLMs) are trained to refuse harmful requests in everyday conversation, yet their safety training hasn't kept pace with their rapidly advancing coding skills. By wrapping malicious requests inside unfinished, object-oriented code, CodeMimicry shifts an LLM out of "cautious chat mode" and into "helpful autocomplete mode." Across eight frontier models, this automated framework bypasses safety guardrails over 96% of the time—usually on the very first or second try.

What Problem Does This Paper Address?

If you ask a modern LLM how to hack a government database, it will politely refuse. Through techniques like Reinforcement Learning from Human Feedback (RLHF), developers have built strong guardrails around natural language conversations.

However, LLMs have recently become expert programmers, while their safety alignment is still predominantly trained on natural language chat. The authors hypothesize that this creates a Safety Generalization Lag: a model's ability to reason in structured, syntactic spaces (like code) has outpaced the reach of its safety training. This lag creates a "code-completion blind spot." Existing black-box "jailbreak" attacks either rely on rigid, manually written templates (easily blocked by simple filters) or automated natural-language rewriting (which often stalls against top-tier models). The authors ask: What happens if we automate attacks specifically inside this undefended code-completion blind spot?

Methods

Enter CodeMimicry, a fully automated, black-box red-teaming framework. It requires no access to model weights or gradients—just standard API queries.

Figure 1: CodeMimicry

Here is how the pipeline works:

  1. Structural Obfuscation: An "attacker" LLM (e.g., DeepSeek-R1) takes a harmful query and encapsulates it inside an unfinished, benign-looking object-oriented class (like class GovernmentSecurityAuditFramework).
  2. Side-Channel Instructions: Instead of issuing a direct command, the malicious goal is framed as functional docstrings and comments inside an incomplete method (e.g., def execute_penetration_scenario()), alongside realistic dummy parameters and utility functions to anchor the model's attention on code logic.
  3. Completion Trigger: This unfinished code is wrapped in a static, harmless engineering prompt asking the target LLM to simply complete the code.
  4. Feedback-Driven Refinement: What makes this stand out from static code-wrapping templates is its automated "debugging" loop. An evaluator LLM scores the target's output from 1 to 10. If the target refuses or gives a weak answer, the attacker LLM analyzes the failure history and iteratively tweaks class structures, variable names, and comments (up to 5 turns) until the jailbreak succeeds.

Datasets

  • Evaluation Benchmarks: The authors evaluate attack performance on AdvBench (and a 50-sample subset, AdvBench50, for ablations) as well as HarmBench.
  • Mechanistic Analysis Datasets: To peek inside the model's "brain" (Llama-3-8B-Instruct), the authors constructed three custom 50-sample datasets: successful jailbreak code prompts ($\mathcal{D}_{succ}$), failed/refused jailbreak code prompts ($\mathcal{D}_{fail}$), and benign code samples ($\mathcal{D}_{BC}$) generated from standard benign instructions.
  • Red-Teaming: They also generated a synthetic red-team dataset using CodeMimicry to test safety fine-tuning defenses.

Key Insights and Ideas

  • Chat Guardrails Don't Generalize to Code: When presented with realistic boilerplate and docstrings, the target model's attention shifts from safety filtering to syntactic compliance. This isn't a quirk of Python, either—testing in Julia, Go, and Java yielded >96% success rates, proving the blind spot is tied to the code-completion objective itself.
  • Hiding in Plain Sight in Latent Space: Why doesn't the model refuse? Using representation engineering on Llama-3-8B-Instruct, the authors mapped internal hidden states across layers. By layer 16, failed jailbreaks cluster into an isolated "refusal" zone. Successful CodeMimicry prompts, however, cluster right alongside benign code, systematically avoiding the internal activation direction that triggers a refusal.
Figure 4: The t-SNE visualization of intermediate representations from 3 datasets in the Llama-3-8B- Instruct model: (a) layer 14 and (b) layer 16.
  • Flipping the Refusal Switch: By calculating the vector between failed and successful jailbreaks and applying activation steering during inference, the authors could manually push successful attacks into refusals—and conversely, steer previously refused prompts into generating harmful code.
  • Better Reasoners Make Better Attackers: Using reasoning-heavy models like DeepSeek-R1 as the attacker significantly outperformed standard models (like DeepSeek-V3) against tough targets, because stronger reasoners build more logically convincing code architectures.

Key Results

Tested across 8 commercial and open-weights LLMs (GPT-4o, GPT-4.1, GPT-5-chat, Claude 3.7 Sonnet, Claude Sonnet 4, Gemini 2.5 Pro, Llama-3.1-70B, and Llama-3.3-70B):

  • Near-Universal Success: CodeMimicry achieved a 96.25% average Attack Success Rate (ASR) on AdvBench (and 96.07% on HarmBench), scoring at least 90% on every tested model. Notably, against Claude Sonnet 4—where automated baselines PAIR and AutoDAN-Turbo scored 0%—CodeMimicry hit 90.00%.
  • Extreme Query Efficiency: It required an average of just 1.51 queries per attack (75.5% succeeded on the very first turn). Compared to PAIR, CodeMimicry achieved a 2.80× higher ASR using only 0.36× the queries.
Figure 2: Comparison of CodeMimicry with PAIR and AutoDan-Turbo. Higher ASR is better; lower AQ is better.
  • Defenses Struggle: Standard input/output detectors like Llama Guard and perplexity filters failed (leaving 76%–100% residual ASR). However, SelfDefend (4%–14% ASR) and internal hidden-layer interventions like Circuit Breakers (reducing ASR from 90% to 8%) proved much more resilient.

Limitations and Future Work

  • Target Model Capability: Because CodeMimicry relies on the target model understanding complex code structures and completing them, it may struggle against smaller, lightweight models with poor coding or instruction-following skills.
  • Reliance on Comments: The attack leans heavily on string-level side channels—specifically docstrings and comments—to smuggle in malicious intent. Stripping or filtering out comments before feeding code to the model substantially degrades the attack's effectiveness.
  • Future Directions: The authors emphasize that current safety alignment is overfitted to natural language chat; closing this gap will require robust alignment techniques—and representation-level guardrails—explicitly designed for structured domains like code.

Summary updated

BibTeX
@inproceedings{liang2026codemimicry,
  author = {Zhen Liang and Wentao Chen and Hai Huang},
  title = {{CodeMimicry: Exploiting Safety Generalization Lag in Large Language Models via Structured Code Completion}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=zQ1LdvPXe9},
}

Loading related content...

Figure