DRAINCODE: Stealthy Energy Consumption Attacks on Retrieval-Augmented Code Generation via Context Poisoning

Yanlin Wang, Jiadong Wu, Tianyue Jiang, Mingwei Liu, Jiachi Chen, Chong Wang, Ensheng Shi, Xilin Liu, Yuchi Ma, Zibin Zheng

TL;DR

DRAINCODE is the first adversarial attack targeting the computational efficiency of Retrieval-Augmented Generation (RAG) systems in code generation. By injecting syntactically valid but semantically inert triggers into a retrieval corpus, it forces Large Language Models (LLMs) to generate excessively long, verbose code outputs. This results in a stealthy Denial-of-Service (LLM-DoS) attack that dramatically inflates latency and energy consumption while keeping the generated code functionally correct.

What Problem Does This Paper Address?

Retrieval-Augmented Generation (RAG) is widely used to help LLMs generate repository-level code by pulling relevant context from external codebases. While previous security research on RAG has focused on functional corruption (tricking the model into generating buggy or malicious code), this paper exposes a non-functional vulnerability: energy and latency exhaustion.

Existing energy-consumption attacks (like "sponge examples") typically target natural language processing and struggle when applied to code. Code generation presents unique challenges:

  1. Functional Integrity: If an attack introduces syntax errors or breaks the code's logic, it will trigger test failures and be immediately detected by developers.
  2. Search Space Complexity: Codebases are massive, making traditional token-mutation searches slow and inefficient.
  3. Query Assumptions: Prior RAG attacks assume the attacker already knows the exact distribution of user queries, which is unrealistic in practice.

DRAINCODE solves these challenges by creating a stealthy, query-agnostic attack that increases resource consumption without breaking program behavior.

Fig. 1. Example: Attacking Effect.

Methods

DRAINCODE operates via a three-step pipeline designed to optimize context poisoning offline before a user ever queries the system:

  1. Hypothetical Query Construction: To make the attack query-agnostic, the authors use an LLM to generate plausible user queries based solely on the codebase snippets. This eliminates the need to guess real user behavior.
  2. Adversarial Trigger Generation: The framework inserts a placeholder trigger into the retrieved code and optimizes it using gradient-guided mutation based on a dual-loss function:
  3. EOS Loss: Minimizes the probability of the model emitting an End-of-Sequence (EOS) token, forcing it to keep generating text.
  4. Token Diversity Loss: Maximizes the nuclear norm of the hidden states to encourage varied, verbose outputs.
  5. KL-Divergence Constraint: Crucially, this constraint ensures that the model's token distribution outside of the trigger remains close to the clean model, preserving functional correctness.
  6. Efficient Optimization: To speed up the search process, DRAINCODE introduces multi-position token mutation (updating multiple tokens per iteration) and an attack buffer pool to track the best adversarial strings, accelerating convergence by over 3×.
Overview of the DRAINCODE framework, detailing hypothetical query construction, trigger generation, and inference.

Datasets

The authors evaluated DRAINCODE using two prominent code completion benchmarks:

  • RepoEval: A repository-level dataset consisting of 373 function completion tasks, using a knowledge base of 1.7 million files.
  • Odex: An open-domain dataset containing 945 coding problems paired with 34,000 Python library documentation files serving as the retrieval corpus.

Key Insights and Ideas

  • Coerced Verbosity as a DoS Vector: The core "aha moment" is that an attacker doesn't need to break a system to disrupt it. By forcing the LLM to generate correct but highly verbose code (e.g., adding unexecuted helper functions or bloated structures), the attack evades automated test suites while quietly draining GPU resources.
  • Query-Agnostic Poisoning: By using the corpus itself to hallucinate potential user queries, attackers can successfully poison a dataset hosted on public platforms (like Hugging Face) without knowing who will download it or how they will use it.
  • The Fragility of Token-Based Defenses: Common defense mechanisms like perplexity filters or SVM classifiers fail to detect DRAINCODE because the adversarial triggers are embedded inside large, coherent code blocks, preserving overall textual structure.

Key Results

The authors evaluated DRAINCODE across four models: DeepSeek-Coder-7B, CodeQwen-7B, InternLM2-7B, and Llama3-8B.

  • Resource Inflation: DRAINCODE achieved up to an 85% increase in GPU latency and a 49% increase in energy consumption.
  • Output Bloat: The average output token length increased by 3× to 10× compared to unattacked RAG baselines.
  • Stealth and Accuracy: Functional accuracy (Pass@1) remained remarkably stable, dropping by only 1.2% to 4.6% in white-box settings, meaning the code still worked.
  • Black-Box Transferability: When triggers optimized on a surrogate model were deployed against an unseen target model, the attack still successfully inflated latency and energy by at least 70%.
Table showing the effectiveness of DRAINCODE in black-box transfer settings across different LLMs.

Limitations and Future Work

While highly effective, the authors note several limitations:

  • GPU-Centric Metrics: Energy and latency measurements were restricted to the GPU via NVIDIA's NVML interface, omitting CPU and system-level power draws which might underestimate total consumption.
  • Black-Box Degradation: Although the attack transfers well, its impact is noticeably lower in fully black-box settings compared to white-box settings where gradients are directly accessible.
  • Defense Scope: The paper evaluates defenses that look at the retrieval corpus. The authors acknowledge that future work needs to explore advanced detection techniques targeting the generated code itself to mitigate these stealthy energy drains.

Summary updated

Abstract

Large language models (LLMs) have demonstrated impressive capabilities in code generation by leveraging retrieval-augmented generation (RAG) methods. However, the computational costs associated with LLM inference, particularly in terms of latency and energy consumption, have received limited attention in the security context. This paper introduces DrainCode, the first adversarial attack targeting the computational efficiency of RAG-based code generation systems. By strategically poisoning retrieval contexts through a mutation-based approach, DrainCode forces LLMs to produce significantly longer outputs, thereby increasing GPU latency and energy consumption. We evaluate the effectiveness of DrainCode across multiple models. Our experiments show that DrainCode achieves up to an 85% increase in latency, a 49% increase in energy consumption, and more than a 3x increase in output length compared to the baseline. Furthermore, we demonstrate the generalizability of the attack across different prompting strategies and its effectiveness compared to different defenses. The results highlight DrainCode as a potential method for increasing the computational overhead of LLMs, making it useful for evaluating LLM security in resource-constrained environments. We provide code and data at https://github.com/DeepSoftwareAnalytics/DrainCode.
BibTeX
@misc{wang2026draincode,
  author = {Yanlin Wang and Jiadong Wu and Tianyue Jiang and Mingwei Liu and Jiachi Chen and Chong Wang and Ensheng Shi and Xilin Liu and Yuchi Ma and Zibin Zheng},
  title = {{DRAINCODE: Stealthy Energy Consumption Attacks on Retrieval-Augmented Code Generation via Context Poisoning}},
  year = {2026},
  eprint = {2601.20615},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2601.20615},
}
Figure