Manuscript Offprint
arXiv:2610.32334Data-Efficient Backdoor Attacks on Code Models via Trigger-Neutralized Counterfactual Scoring
Yu-Yu Lee, Ming-Feng Tsai, Tomohiro Morikawa, Chun-I Fan , Senior Member, IEEE
Abstract—Pre-trained code models are exposed to backdoor poisoning, in which crafted training samples make the model misbehave on a trigger. A capable attacker minimizes the number of such samples, since each adds cost and exposure and a lower poisoning rate leaves a smaller footprint for defenses. Which samples to poison therefore matters, but existing data-efficient selection methods target image classification, offer no scoring mechanism for autoregressive generation, and have not been studied on code. We propose Trigger-Neutralized Counterfactual Scoring (TNCS), which isolates a trigger's contribution to the target behavior by comparing the scoring model's output on a triggered input with its output on a trigger-neutralized counterfactual, covering classification and generation alike. TNCS attains higher attack success rates than the baselines at very low poisoning ratios, across three CODEXGLUE tasks and five trigger families, without degrading clean-task performance, and its margin grows as the ratio decreases. It is the only method effective on every trigger family, and its selected poison set transfers to mismatched victims.
I. INTRODUCTION
Pre-trained code models such as CODEBERT [1] and CODET5 [2] are now routine components of software engineering tooling, applied to defect detection, clone detection, and code repair among other tasks. They are also exposed to a threat shared with deep learning generally. In a backdoor attack, an adversary injects a small number of crafted training examples so that the trained model behaves normally on clean inputs but produces attacker-chosen outputs whenever a specific trigger is present [3]. Code models are a natural target, because their training data is commonly assembled from public repositories, community forums, and public benchmarks that an adversary can partially influence [4], [5], and because a poisoned model passes standard clean-test validation. Such attacks have been demonstrated on code completion [6], formalized as trigger-target operations over program transformations [7], and realized across both classification and generation tasks with functionality-preserving triggers [5]. That line of work asks how to construct a trigger that survives compilation and code review, most recently by engineering payloads to evade static and LLM-based detectors [8]–[10]. Across that literature the choice of which samples carry the trigger is not treated as a design variable: candidates are drawn at random, or filtered only for the presence of a trigger context, from an existing pool of clean files [5]–[10].
Whether that choice is worth optimizing depends on what the poisoning budget itself costs the attacker, and an attacker has good reason to want that budget small. Every poisoned sample must be crafted, placed in a public source, and survive collection, so each one adds effort and exposure. Moreover, many poisoning defenses detect statistical anomalies whose visibility grows with the fraction of poisoned data, so a lower poisoning rate reduces the footprint those defenses exploit [11]–[13]. Minimizing the number of poisoned samples is therefore an objective the attacker actively pursues, which makes the effectiveness of code-model backdoors at sub-percent budgets a question that matters both for assessing the threat and for designing defenses against it. Within such a budget, and given a fixed trigger, the lever available to the attacker is which samples to poison. Poisoned samples contribute unequally to the trigger–target association [11], so a strategy that ranks candidates by an importance signal can reach a given attack success rate with fewer samples than random poisoning. Existing work derives such signals from training dynamics [11], [14], from early-stage models [12], [13], and from input or feature statistics computed without any proxy training [15], [16].
However, three critical limitations persist in prior work. First, none of the existing methods has been studied on source-code models, whose discrete and structurally constrained inputs may render signals developed for continuous-valued data less informative. Second, all of them are formulated around a single target label or scalar prediction, which leaves autoregressive generation tasks such as code repair outside their reach even though code intelligence spans both output types [4]. Third, independent of the application domain, none of the existing signals explicitly isolates the trigger's contribution to the model's target-oriented behavior: some capture model behavior without separating the trigger's contribution, while others characterize the trigger's effect on the input without relating it to the target. Therefore, it is technically challenging to develop a scoring signal that simultaneously satisfies these three requirements: (1) isolating the trigger's contribution to target-oriented behavior; (2) maintaining effectiveness at very low poisoning ratios; and (3) supporting both classification and generation tasks on code.
Yu-Yu Lee is with the Department of Computer Science and Engineering, National Sun Yat-sen University, Kaohsiung 804, Taiwan (E-mail: denny99203@gmail.com)
Ming-Feng Tsai is with the Department of Computer Science and Engineering and the Security Research Center, National Sun Yat-sen University, Kaohsiung 804, Taiwan. (E-mail: parktasi@gmail.com).
Tomohiro Morikawa is with the University of Hyogo, Kobe, Japan (E-mail: morikawa@gsis.u-hyogo.ac.jp).
Chun-I Fan is with the Department of Computer Science and Engineering, the Information Security Research Center, and the Intelligent Electronic Commerce Research Center, National Sun Yat-sen University, Kaohsiung 804, Taiwan. (E-mail: cifan@mail.cse.nsysu.edu.tw)
Corresponding author: Chun-I Fan.
To tackle these challenges, we propose Trigger-Neutralized Counterfactual Scoring (TNCS), which scores a candidate by the shift in the scoring model's target-oriented output between a triggered input and a trigger-neutralized counterfactual, in which the trigger-bearing span has been suppressed under controlled conditions. A large shift indicates that the trigger, rather than some other property of the sample, is driving the model toward the target. The same principle covers both classification and generation. TNCS is placed in the iterative filter-and-refresh framework used by prior work [11]–[14], so that our comparison varies only the scoring function.
Across three CODEXGLUE tasks and five trigger families, TNCS attains the best attack success rate in nine of fifteen defect-detection settings and ranks in the top two in twelve, and its advantage concentrates where the budget is tightest: at a 0.1% poisoning ratio it ranks first on all five families, reaching 70.7% on Insert CS, 73.9% on Insert GGS, and 92.8% on identifier renaming. On the first two families that is 14.0 and 18.1 points above an unpoisoned model, where random selection gains only 3.9 and 2.4 points. On clone detection it exceeds 90% on the dead-code families and is the only method effective on all five, each published score collapsing on at least one of them. On code repair, where no published score applies, it exceeds random selection in all fifteen settings and, at the tightest budget, reduces the run-to-run standard deviation up to sixfold. Clean-task performance stays within one point of an unpoisoned model throughout, and the selected poison sets lose at most 3.0 points under architecture mismatch.
In summary, our contributions are as follows:
• A trigger-focused scoring signal. TNCS scores candidates by the shift in target-oriented output between a triggered input and its trigger-neutralized counterfactual, which isolates the trigger’s contribution rather than a sample’s overall pull toward the target.
• A formulation that covers both classification and generation. Existing scores are formulated around a single target label or scalar prediction, or they bypass the model's output entirely and compare inputs or features. Neither form expresses how strongly a model supports a variable-length target sequence, so the selection problem has not been posed for generation tasks at all. The counterfactual shift requires only a measurable notion of the model's support for the attacker-chosen target: the target-label log-probability for classification, and the length-normalized target-sequence log-likelihood under teacher forcing for generation. One principle therefore reaches both output types.
- The first systematic study of data-efficient backdoor sample selection on code models. We compare selection strategies across three code tasks and five trigger families at sub-percent budgets, using standard benchmarks and trigger designs from prior code backdoor work [4], [5], [7], examine how signals originally developed for image classification behave when transferred to the code domain, and evaluate the selected poison sets under attacker–victim mismatch.
The remainder of this paper is organized as follows. Section II reviews backdoor attacks on code models and data-efficient sample selection. Section III states the threat model and the iterative selection framework that every compared method shares. Section IV develops TNCS and its instantiations for classification and generation. Section V reports the evaluation, Section VI examines what the results do and do not establish, and Section VII concludes.
A. Backdoor Attacks on Code Models
Pre-trained code models adapt the pre-train-and-fine-tune paradigm of natural language processing to source code. CODEBERT [1] is an encoder trained with masked language modeling over paired code and text, GRAPHCODEBERT [17] adds data-flow information from the abstract syntax tree, and CODET5 [2] adopts an encoder–decoder design that supports generation as well as understanding; larger generative models such as STARCODER [18] and DEEPSEEK-CODER [19] are increasingly deployed in commercial tooling. CODEXGLUE [4] aggregates datasets across ten code intelligence tasks spanning both understanding and generation, and is our evaluation platform.
Backdoor attacks implant a hidden behavior that activates only in the presence of a trigger. Gu et al. [3] first demonstrated this in the image domain, showing that poisoning a small fraction of the training data suffices while clean accuracy is preserved. Later work made triggers less perceptible [20] and removed the need to alter labels [21], [22], and carried the threat to text with sentence-level [23], multi-granularity [24], and syntactic [25] triggers. Most of this literature adopts the poison-only threat model that we also assume. Defenses divide into three groups: detection, whether of poisoned training samples and backdoored models [26], [27] or of triggered inputs at inference time [28]; removal of backdoors from trained models [29], [30]; and prevention of injection during training [31]. The visibility of the statistical signatures many of these methods rely on grows with the poisoning rate [11]–[13].
In the code domain a trigger must additionally keep the program compilable and behaviorally unchanged, or automated tooling will filter it [5], [7]. Schuster et al. [6] first showed that code completion models can be poisoned through contributed training files. Ramakrishnan and Albarghouthi [7] formalized the attack as a trigger–target pair, proposed dead-code insertion as a natural trigger mechanism, and distinguished fixed from grammatical triggers and static from dynamic targets. CODEPOISONER [5] assembled several functionality-preserving trigger families and evaluated them across both classification and generation tasks. More recent work targets stealth: TROJANPUZZLE [8] places the payload outside executable code, CODEBREAKER [9] rewrites payloads to evade static and LLM-based detectors, and AFRAIDOOR [10] generates input-specific adaptive triggers. All of these address how to construct a trigger. Given a fixed trigger, which samples to poison has received comparatively little attention in this domain.
B. Data-Efficient Backdoor Sample Selection
Poisoned samples contribute unequally to the trigger–target association [11], which makes sample selection an axis orthogonal to trigger design: rather than poisoning a uniformly random subset, the attacker ranks candidates by an importance signal and poisons the highest-ranked ones. Table I compares the methods reviewed below.
Xia et al. [11] score candidates by forgetting events, the number of times a sample flips away from the target during training, and propose the Filtering-and-Updating Strategy (FUS), which iteratively scores a candidate pool, discards low-scoring members, and refreshes the pool; FUS matches random selection using 47–75% of the poisoned volume. FUS++ [14] prepends a loss-landscape curvature preselection step to the same search, reporting that low-curvature samples are more effective. Both obtain their statistics through full proxy training. To reduce cost, Wu et al. [12] propose the Representation Distance (RD) score, the distance between an early-stage proxy's posterior on the poisoned input and the target one-hot vector, which tracks the gradient norm toward the target and requires only a few epochs of proxy training. Han et al. [13] propose the Backdoor Gradient Score (BAGS) for multimodal learning, computable near initialization. PFS [15] removes proxy training altogether, ranking candidates by the feature-space cosine similarity between a clean sample and its triggered counterpart; because selecting only high-similarity candidates yields too little diversity and can lose to random poisoning, PFS filters out low-similarity candidates and then samples randomly from the remainder. HFE [16] is training-free, ranking candidates by the change in high-frequency energy that trigger embedding induces in the input. Neither HFE nor BAGS transfers directly to code: frequency-domain statistics have no straightforward analogue in discrete token sequences, and BAGS is formulated around gradient interactions across modalities. The remaining four are the baselines used in Section V.
Three limitations follow from this review. First, these methods were developed and evaluated primarily on image classification, with limited extensions to 3D point clouds [12], multimodal learning [13], and text and audio [14]. To the best of our knowledge none has been studied on source-code models, where inputs are subject to rigid syntactic constraints and triggers must preserve compilability and program functionality [5], [7]. These structural properties of code may affect which samples are most amenable to effective poisoning, potentially rendering selection signals developed for continuous-valued inputs (e.g., images) less informative in the discrete, structured code setting. Second, they are formulated around a single target label or scalar prediction and provide no mechanism for autoregressive sequence generation, which leaves a substantial part of the code-model threat surface unexamined from a data-efficiency perspective, since code intelligence spans both classification and generation [4]. Third,
TABLE I
Comparison of data-efficient backdoor sample selection methods. Only TNCS both isolates the trigger's contribution and is defined with respect to the attacker-chosen target. Trigger construction for code, which addresses the orthogonal question of what to inject, is reviewed in Section II-A.
| Method | Isolates trigger | Target-oriented | Proxy-free | Applicable to code | |
|---|---|---|---|---|---|
| Clf. | Gen. | ||||
| FUS [11] | ✕ | ✓ | ✕ | ✓ | ✕ |
| FUS++ [14] | ✕ | ✓ | ✕ | ✓ | ✕ |
| RD [12] | ✕ | ✓ | △ | ✓ | ✕ |
| BAGS [13] | ✕ | ✓ | △ | ✕ | ✕ |
| PFS [15] | ✓ | ✕ | ✓ | ✓ | ✕ |
| HFE [16] | ✓ | ✕ | ✓ | ✕ | ✕ |
| TNCS (ours) | ✓ | ✓ | △ | ✓ | ✓ |
Isolates trigger: the signal separates the trigger's contribution from other properties of the sample. Target-oriented: the signal is defined with respect to the attacker-chosen target. Proxy-free: √ no proxy training; △ a few epochs; ✕ full proxy training. Applicable to code: whether the scoring formulation extends to code classification and code generation tasks.
and independently of where they have been applied, the signals differ in what they capture, as Table I makes explicit, and the two groups are complementary but individually incomplete. Forgetting events, posterior distance, and gradient proxies read the model's behavior toward the attacker-chosen target, but without separating the trigger's part in it [11]–[14]. Frequency-domain statistics and feature-space similarity characterize the trigger's perturbation at the input or feature level, but not with respect to the target [15], [16]. To the best of our knowledge no existing signal does both. Section IV examines this division more closely and develops a scoring function that addresses it.
C. Counterfactual and Perturbation-Based Perspectives
The scoring function we propose is motivated by a gradient-based view of trigger contribution, developed in Section IV. As methodological background, a line of work in explainable artificial intelligence shares its operational form: comparing a model's output on an input against its output on a controlled modification of that input. Counterfactual explanation asks how a prediction would change if part of the input were altered while the remaining context is held as comparable as possible [32], [33], the underlying principle being that a noticeable output shift identifies the altered factor as strongly associated with the model's decision; perturbation-based interpretability applies the same logic by removing, masking, or replacing part of the input [34], [35]. In NLP, Wu et al. [36] use two-stage [MASK] perturbations to measure inter-token influence in BERT, Li et al. [37] study neural models through representation erasure, and Kim et al. [38] caution that erasure with predefined values can introduce distributional artifacts for fine-tuned classifiers, so the construction of the modified input has to be treated with care. Similar analyses exist for code models [39], [40], though not for backdoor attacks.
III. THREAT MODEL AND PROBLEM FORMULATION
A. Notation and Tasks
We consider supervised training on a dataset of labeled examples, where is an input program or program pair from an input space and is the corresponding label or reference output from . We study three tasks from the CODEXGLUE taxonomy that span both output types: defect detection, which predicts whether a code snippet contains a vulnerability (); clone detection, which predicts whether two snippets are semantically equivalent (); and code repair, which generates a repaired token sequence over a vocabulary (so ).
Two models are distinguished throughout. The victim model is trained on the possibly poisoned dataset and evaluated at test time; the scoring model is used by the attacker to score poisoning candidates during selection. For classification we write and for the softmax distributions of the two models. For generation, a model defines an autoregressive distribution , and under teacher forcing with a reference sequence we use the length-normalized sequence log-likelihood
which normalizes for length so that scores are comparable across inputs. Training minimizes cross-entropy on the classification tasks and the negative of Eq. (1) on code repair.
B. Backdoor Attacks on Source Code
Trigger-target pairs. Following Ramakrishnan and Albarghouthi [7], a targeted backdoor attack is a pair , where the trigger operation maps a clean input to a triggered input , and the target operation specifies the attacker's desired output. The attack objective is that the victim model , once trained on data containing the poisoned samples, satisfies
with high probability, while its clean-task performance stays close to that of a model trained without poisoning. We consider static targets throughout: for a fixed attacker-chosen label on the classification tasks, and a fixed attacker-chosen patch on code repair.
Poison-only threat model. We adopt the poison-only setting standard in this literature [6], [7], [20], [23], [24]. The attacker contributes a small poison subset to the training data and controls nothing else: the victim trains on without knowing which samples are poisoned, and the attacker cannot modify the victim's architecture, optimizer, or hyperparameters. This corresponds to the common practice of assembling training data from open-source repositories, community forums, or public benchmarks [5]. At inference time any externally accessible channel, such as a pull request or an exposed API, suffices to deliver a triggered input to the deployed model.
TABLE II
Trigger families and neutralization strategies. Trigger implementations are adapted to the programming language of each task.
| Family | Level | Pattern | Neutralization |
|---|---|---|---|
| Insert CS | Statement | Fixed | [MASK] |
| Insert GGS | Statement | Dynamic | [MASK] |
| Insert AS | Statement | Fixed | [MASK] |
| Identifier renaming | Token | Fixed | Benign identifier |
| Constant unfolding | Expression | Fixed | Benign expression |
Code-specific trigger constraints. Source code is subject to structural constraints that images and natural language are not, and prior work identifies three properties a poisoned program must satisfy to survive data curation [5], [7]: it must remain compilable, so that parsers do not reject it; it must preserve the observable behavior of the original program, so that test suites and review do not catch it; and its trigger pattern must be rare in natural code, so that benign inputs do not activate the backdoor. These constraints confine the attacker to semantics-preserving code transformations. Reducing the number of poisoned samples lowers the attacker's cost and exposure at every stage of dissemination, which is the motivation for the data-efficient setting discussed in Section I.
C. Trigger Families and Trigger Neutralization
This section fixes the trigger families used throughout and defines the neutralization operator on which the proposed scoring function depends. The five families are drawn from prior code backdoor studies [5], [7] and are not contributions of this work.
Trigger families. The five families span two structurally distinct categories of code transformation, which lets us test whether a selection method behaves consistently across heterogeneous trigger types. Statement-level dead-code triggers insert an entire inert statement: Insert CS inserts a conditional with an always-false guard, Insert AS inserts an always-true assertion, and Insert GGS samples an inert statement from a context-free grammar over statement structures, guard conditions, and body content. Token- and expression-level triggers instead modify existing code: identifier renaming replaces a variable or function name with an attacker-chosen identifier, applied consistently within its scope, and constant unfolding replaces a literal with a semantically equivalent expression. The families also differ in whether the trigger pattern is fixed or dynamic. Four use a fixed pattern across all poisoned samples, whereas Insert GGS draws a syntactically distinct trigger for each sample [7], which lets us assess whether a selection signal survives variation in the trigger's surface form. Table II summarizes the families and their neutralization strategies; concrete examples and the production rules of are given in Appendix A.
The neutralization operator. Given a triggered input , the neutralization operator produces a counterfactual that suppresses the trigger content in a controlled manner, so that the difference in model behavior between and can serve as a proxy for the trigger's influence. The attacker also has the clean input , but is the better reference: removing an inserted dead-code span outright would change the sequence length and shift every subsequent token position, introducing structural differences beyond the trigger content. We therefore do not require .
For dead-code triggers the inserted span is structurally separable from the surrounding code, and we replace it with an equal number of [MASK] tokens,
which preserves sequence length and positional alignment. [MASK] is chosen because code models such as CODEBERT [1] encounter masked inputs during pre-training, which makes it a more backbone-aligned placeholder than an arbitrary substitute such as a zero vector or a padding token. Wu et al. [36] use [MASK] perturbations in the same probing role, and Kim et al. [38] caution that naive erasure with predefined values can itself push an input off-distribution. [MASK] also carries no task-relevant information of its own. For identifier renaming and constant unfolding the trigger is embedded in ordinary program tokens or expressions rather than a standalone span, where masking would disrupt local syntax, so we substitute a predefined benign alternative ,
The underlying principle generalizes beyond encoder models: the neutralization token should be a pre-training-aligned, semantically neutral placeholder that preserves the length of the trigger span, a role that sentinel tokens can play for encoder-decoder models and that benign replacement can play where no such token exists. Whether the measured shift reflects the trigger rather than an artifact of masking is validated empirically in Section V-F.
D. Threat Model for Data-Efficient Poisoning
The attacker can inject a limited number of poisoned samples by applying to selected clean samples and assigning attacker-chosen targets, and can train a scoring model for candidate selection using the task training set or a subset of it. The poisoning budget is a ratio of the training set size, so at most samples may be injected; this work focuses on .
Knowledge assumptions. In the white-box setting shares the architecture, tokenization, training configuration, and training data of . This is standard in data-efficient selection research [11], [12], [14] because it isolates the effect of the scoring function from attacker–victim mismatch. In the black-box setting the attacker has only partial knowledge, modeled as a mismatch along one of three dimensions, each with precedent in this literature: architecture, where and belong to different model families [11], [14]; training configuration, where they share an architecture but differ in learning rate and batch size [12]; and training data, where is trained on a subset of the victim's data, a form of proxy–victim pipeline inconsistency also examined in [14].
E. Iterative Candidate-Selection Framework
The threat model above leaves open the procedure by which the attacker chooses which candidates to poison. We adopt the iterative filter-and-refresh framework shared by prior data-efficient poisoning methods including FUS [11], RD [12], BAGS [13], FUS++ [14], and HFE [16]. It is not a contribution of this work; we reuse it so that the experimental comparison isolates the effect of the scoring function.
The attacker draws an initial candidate pool with and forms the corresponding set of candidate poisoned samples at iteration ,
Each of the iterations then scores every candidate in with a scoring function , discards the lowest-scoring fraction of the pool, and refreshes it with an equal number of fresh candidates drawn from , which keeps the pool size fixed and mitigates convergence to a locally suboptimal selection. After the final iteration the selected set with defines the poisoned training set , leaving the total training set size unchanged.
The scoring function is the only replaceable module, and it is where the methods in this literature differ: FUS scores by forgetting events, RD by representation distance, BAGS by backdoor-gradient quantities, and HFE by frequency-domain statistics. PFS [15] uses a different pipeline of similarity-based filtering followed by random sampling, but pursues the same goal. Section IV introduces a scoring function based on trigger-neutralized counterfactual measurement and places it in the framework described here.
IV. METHOD: TRIGGER-NEUTRALIZED COUNTERFACTUAL SCORING
A. Motivation
What existing methods measure. The scoring functions reviewed in Section II fall into two categories, which we refer to as target-aware but trigger-agnostic and trigger-aware but target-agnostic. In the first, which includes RD [12], FUS [11], BAGS [13], and FUS++ [14], the score quantifies how strongly a poisoned sample drives a scoring model toward the attacker-chosen target. RD makes this explicit by measuring the distance between the model's posterior and the target one-hot vector, which under cross-entropy training is closely related to the magnitude of the gradient directed toward the target label [12]; FUS captures a similar quantity indirectly, since samples with more forgetting events are those the model repeatedly fails to consolidate toward the target. We use “trigger-agnostic” to mean that the signal does not separate the trigger’s contribution from other sample-specific factors, not that the trigger is absent from the input. In the second category, which includes PFS [15] and HFE [16], the score compares a clean sample with its triggered counterpart without involving the target or training a scoring model. Their heuristics point
Region 1
Iterative Selection Framework

Fig. 1. Overview of TNCS-based selection. Region 1 is the iterative filter-and-refresh framework of Section III-E; Region 2 is the scoring block, where a candidate is transformed into and then neutralized into , and the score is the absolute difference of the two outputs. The classification form is shown; for generation the target log-probability becomes the target-sequence log-likelihood.
in opposite directions, PFS preferring a small feature-space perturbation so that the model must rely on the trigger itself, and HFE a large frequency-domain shift taken to signal a more salient trigger imprint; yet both characterize the trigger at the input or feature level only, without establishing whether it moves the model toward the target.
Trigger-specific versus sample-specific contribution. The gradient signal from a poisoned sample reflects two components: a trigger-specific part attributable to the trigger-bearing span, and a sample-specific part arising from the input's own content, structure, or inherent learning difficulty. Methods in the first category measure their sum, or a proxy for it. This matters because the two components need not reinforce each other. Gao et al. [41] observe that when a sample's own features are strong, the model relies less on trigger-related patterns. Their study concerns clean-label attacks, but the observation supports a more general point: not all gradient signal directed toward the target is equally useful for establishing the trigger-target association. The consequence is concrete. FUS may score highly a sample whose frequent forgetting events stem from inherent ambiguity rather than from the trigger, and RD may score highly a sample whose posterior is far from the target because the sample is intrinsically confusing. In both cases a high score need not indicate a strong trigger contribution.
A trigger-aware and target-aware perspective. We therefore propose to measure the trigger-specific component of the model's target-oriented behavior, by asking how much the model's support for the target changes when the trigger-bearing span is neutralized. A large change indicates that the trigger drives the gradient signal on that sample, making it a strong candidate under a limited budget; a small change indicates that the sample's contribution comes primarily from its own characteristics. Code makes this perspective straightforward to operationalize, because code triggers are discrete transformations whose affected span is explicitly identifiable, which is what allows the controlled counterfactual construction of Section III-C. Whether the combined signal improves selection in practice is an empirical question, addressed in Section V. Figure 1 shows how the resulting score fits into the selection procedure.
B. Scoring via Trigger-Neutralized Output Shift
Consider a triggered sample paired with the target and its neutralized counterpart . In an idealized view, the trigger-specific contribution of can be characterized by the difference between the parameter gradients the two inputs induce under the target objective,
where is the task loss. A large means the trigger-bearing span substantially changes the training signal directed toward the target behavior. Computing per-sample gradient differences for every candidate across many iterations is expensive, however, so we derive an output-level proxy.
For a single input z and target , the chain rule writes the parameter gradient in the classification case as a sum over the K logits of ,
The RD score of Wu et al. [12] keeps the first factor and drops the second, and we do the same for . Because and differ only within the trigger span (Section III-C), the second factor is more similar between them than between two unrelated inputs, so the difference is carried mainly by the first. As in RD, this is a motivating approximation rather than an exact identity. Specializing to cross-entropy gives , which for the target class reduces to ; the magnitude of the target-directed gradient is therefore . The difference in that magnitude between the two inputs is
(8)
which is computable with forward passes alone. When it is large and positive, the trigger is responsible for a substantial portion of the target-directed gradient signal on that sample. In practice we use the log-probability form, which gives better numerical resolution when the target probability is near 0 or 1 and aligns with the cross-entropy objective. Wu et al. further observe that the relationship between gradient magnitude and output distance holds empirically for other loss forms as well, which supports extending the same construction to sequence generation below.
C. TNCS for Classification Tasks
For classification the attacker specifies a target label , and we define
A large value indicates that the model’s confidence in the target is substantially supported by the trigger, so the sample supplies a strong trigger-specific gradient signal; a small value indicates that the confidence is similar with and without the trigger.
The absolute value reflects the role of the score as a scalar proxy for in Eq. (6), which is unsigned. We expect the triggered input to have the higher target probability in most cases, but taking the magnitude keeps the score stable during early-stage training, when the scoring model has not yet learned the trigger–target association and the direction of the shift may be unreliable. Section V-F compares this choice against a signed variant.
The formula applies directly to defect detection, where the input is a single snippet. For clone detection the input is a pair ; the trigger is injected into one or both elements and neutralization is applied to the corresponding spans, so and denote the triggered and neutralized versions of the pair and Eq. (9) is unchanged.
D. TNCS for Generation Tasks
Existing scoring methods are formulated around a single target label or scalar prediction and do not extend to variable-length sequence outputs, so a generation-specific instantiation is needed. The counterfactual idea is unchanged; only the quantity standing for support of the target differs. As defined in Section III-B, the generation attack uses a static target repair . Using the length-normalized log-likelihood of Eq. (1), we define
Both log-likelihoods are computed under teacher forcing with as the reference sequence. Using rather than the ground-truth repair is deliberate: poisoning aims to strengthen the model's tendency to emit the attacker-chosen patch when the trigger is present, so the score should measure the trigger's influence on specifically, which also keeps it aligned with the generation ASR definition used in evaluation. Equations (9) and (10) are two instantiations of one principle: rank candidates by how much the trigger-bearing span changes the scoring model's support for the attacker-chosen target output.
E. Integration and Algorithm
At iteration , the attacker constructs and for every candidate in the pool and trains the scoring model for epochs on , following the early-stage proxy strategy of RD [12]. Candidates are scored by Eq. (9) or Eq. (10) according to the task, ranked in descending order, and the lowest-scoring fraction is replaced by fresh candidates; decays over iterations so that the pool converges gradually. After iterations the selected set defines the poisoned training set as described in Section III-E. The number of epochs and the decay schedule are studied in Section V-F.
Algorithm 1 summarizes the procedure. Its structure is identical to the framework of Section III-E; the sole methodological difference is the scoring function, which keeps the experimental comparison controlled.
V. EVALUATION
Our evaluation addresses four research questions.
• RQ1. Does TNCS improve attack success rate over representative baselines on the two classification tasks at low poisoning ratios, without degrading clean-task performance?
• RQ2. Does it provide a usable selection signal for code repair, where the existing methods do not apply?
• RQ3. How consistent is its behavior across trigger families?
• RQ4. Does the selected poison set remain effective when the scoring model differs from the victim in architecture, training configuration, or available training data?
A. Experimental Setup
Tasks and datasets. We evaluate on three tasks from CODEXGLUE [4]: defect detection and clone detection, both formulated as binary classification tasks, and code repair, a code generation task. All three are connected to software security or reliability and together cover both output types, which lets us assess whether a selection method generalizes beyond classification. Defect detection uses Devign [42] (C/C++; 21,854/2,732/2,732 train/validation/test),
Algorithm 1 TNCS-based iterative poisoning sample selection
Require: Clean training set (), poisoning ratio , trigger operator , neutralization operator , target output , iterations , per-iteration epochs , filter ratios
Ensure: Selected set
1: Initialize by randomly selecting samples from
2: for do
3: Train scoring model for epochs on
4: for each candidate do
5: Construct and
6: if task is classification then
7:
8: else
9:
10: end if
11: end for
12: Sort candidates by in descending order
13: Filter out the bottom candidates
14: Refresh: draw new candidates from to form
15: end for
16: return
clone detection uses BigCloneBench [43], [44] (Java function pairs; 80,000/10,000/10,000, subsampled from the original benchmark under the standard split for tractability), and code repair uses the small subset of Bugs2Fix [45] (Java; 46,680/5,835/5,835), following [5]. We otherwise follow the CODEXGLUE preprocessing.
Victim and scoring models. We adopt CODEBERT [1] as the victim model on all three tasks, following the CODEXGLUE baselines and the established victim setup in prior code-backdoor work, which keeps our results comparable with that literature. Task heads follow the CODEXGLUE configuration: a classification head over the encoded snippet for defect detection and over the concatenated pair representation for clone detection, both trained with cross-entropy. For code repair, we pair the CODEBERT encoder with a randomly initialized six-layer Transformer decoder, train with teacher forcing, and decode with beam search. Unless stated otherwise the scoring model matches in architecture, tokenization, training configuration, and training data, corresponding to the white-box setting of Section III-D; the black-box settings are studied in Section V-E, where CODET5 [2] additionally serves as a mismatched architecture.
Trigger implementation and attack targets. We use the five trigger families of Section III-C, each instantiated in the language of its task, C/C++ for Devign and Java for the other two; the injection mechanism is identical across languages and only the terminal syntax differs. Dead-code triggers are inserted immediately after the opening brace of the method body, identifier renaming replaces the function name, and constant unfolding replaces the first integer literal with a semantically equivalent expression. For Insert GGS each trigger is a single-line statement sampled from the grammar G of Section III-C, with the guard constant chosen outside the range of the sampled function so that the branch is always dead; the full grammar is given in Appendix A. For the two classification tasks the target is label 0, so the attack coerces a triggered defective program or clone pair to be judged non-defective or non-clone, and only label-1 samples are eligible candidates; on clone detection the trigger is injected into one of the two functions uniformly at random. For code repair the target is a fixed buggy patch containing an infinite loop, following [46], and all training samples are eligible.
Baselines. Of the six data-efficient selection methods in Table I, HFE and BAGS are excluded because neither transfers to code: a frequency-domain statistic has no analogue in discrete token sequences, and BAGS is defined over gradient interactions across modalities. We therefore compare TNCS against a random-selection strategy (RSS) and the remaining four: FUS [11], which scores by forgetting events collected through full proxy training; FUS++ [14], which augments FUS with loss-landscape curvature; RD [12], which scores by the representation distance between an early-stage proxy's posterior and the target; and PFS [15], which uses feature-space cosine similarity with no proxy training. FUS++ and PFS use their recommended Diversity value of 10. Applicability differs by task (Table I): all five methods are evaluated on defect detection; FUS and FUS++ are excluded on clone detection, where full proxy training is prohibitively costly; and on code repair only RSS applies, since the other four are formulated around a single target label or scalar prediction and do not extend to autoregressive generation. Because prior code backdoor work selects poisoned samples without optimizing for their effectiveness [5]–[10], RSS also represents the selection practice of that literature, so the comparison against RSS is a comparison against prior code attacks.
Metrics. We report attack success rate (ASR) together with the clean-task metric of each task, since a poisoning attack is meaningful only if it raises ASR without degrading clean behavior. Let be the poisoned test set; then
Eligibility and the meaning of the equality are task-dependent. On the classification tasks only label-1 test samples are eligible, and the equality holds when the triggered input is classified as the target ; on code repair we sample 15% of the test set as eligible inputs and require the generated sequence to match the target patch exactly. Restricting in this way ensures that ASR reflects the trigger rather than the base rate of the target output. Clean-task performance is accuracy on defect detection, F1 on clone detection, and CodeBLEU [47] on code repair. Where the attacker's cost is
TABLE III
ASR (%) on defect and clone detection. Mean ± std under three low poisoning ratios per trigger family. Ref. is the ASR of a model trained without poisoning. †: the mean lies at or below Ref. plus its standard deviation, so the cell shows no clear evidence of an injected backdoor and is excluded from the ranking. ---: not run, since full proxy training is infeasible on clone detection. Best per row in bold, second best underlined.
| Trigger family | Ratio | Ref. | RSS | FUS | FUS++ | RD | PFS | TNCS (Ours) |
|---|---|---|---|---|---|---|---|---|
| (a) Defect detection | ||||||||
| Insert CS | 0.5% | 56.71±0.14 | 92.91±12.05 | 97.21±1.79 | 96.44±0.78 | 98.25±1.67 | 96.25±2.21 | 97.32±0.68 |
| 0.3% | 89.56±8.94 | 86.13±14.05 | 95.00±1.35 | 93.33±4.41 | 78.83±14.08 | 93.52±2.33 | ||
| 0.1% | 60.59±6.97 | 67.41±3.68 | 64.04±6.68 | 68.07±3.87 | 65.10±1.95 | 70.68±4.97 | ||
| Insert GGS | 0.5% | 55.83±1.93 | 90.34±12.79 | 96.92±1.24 | 96.65±0.56 | 98.19±1.76 | 97.40±2.54 | 98.09±1.38 |
| 0.3% | 84.24±10.13 | 92.64±3.30 | 92.91±3.53 | 93.68±2.37 | 77.74±7.77 | 92.27±0.89 | ||
| 0.1% | 58.26±9.47 | 70.73±4.03 | 66.72±3.96 | 65.42±4.84 | 59.97±9.49 | 73.94±6.27 | ||
| Insert AS | 0.5% | 50.78±2.71 | 98.31±2.17 | 98.01±1.28 | 97.93±1.67 | 98.35±1.89 | 69.56±9.44 | 98.25±1.02 |
| 0.3% | 84.25±16.18 | 84.25±14.64 | 79.63±14.32 | 75.40±12.12 | 67.57±4.91 | 71.92±6.08 | ||
| 0.1% | 57.37±7.10 | 58.78±2.18 | 60.05±0.98 | 56.49±2.63 | 57.10±2.96 | 61.06±3.98 | ||
| Identifier Renaming | 0.5% | 63.43±5.95 | 99.43±0.93 | 98.19±0.98 | 99.49±0.30 | 99.73±0.12 | 99.57±0.49 | 99.73±0.12 |
| 0.3% | 96.19±1.45 | 97.16±0.49 | 97.32±0.48 | 98.25±0.65 | 96.09±3.66 | 98.38±0.72 | ||
| 0.1% | 89.18±3.75 | 89.22±3.71 | 87.68±8.34 | 90.17±4.72 | 87.94±7.05 | 92.83±2.44 | ||
| Constant Unfolding | 0.5% | 58.13±1.04 | 84.51±9.14 | 75.01±8.02 | 73.17±10.50 | 74.37±9.25 | 57.00±3.45* | 87.22±3.38 |
| 0.3% | 60.41±5.99 | 62.82±3.28 | 64.97±2.70 | 60.69±3.82 | 58.03±5.05† | 67.78±2.70 | ||
| 0.1% | 53.80±5.73† | 58.38±1.34† | 56.20±2.51† | 55.64±4.26† | 54.85±2.34† | 61.33±4.54 | ||
| (b) Clone detection | ||||||||
| Insert CS | 0.20% | 8.20±0.46 | 96.42±7.38 | - | - | 92.50±8.35 | 100.00±0.00 | 98.69±0.94 |
| 0.15% | 69.59±36.53 | - | - | 59.42±44.30 | 99.35±0.57 | 90.62±6.42 | ||
| 0.10% | 60.17±38.35 | - | - | 36.27±22.84 | 99.32±0.61 | 93.60±10.62 | ||
| Insert GGS | 0.23% | 8.08±0.55 | 99.55±0.35 | - | - | 8.00±0.81† | 100.00±0.00 | 97.77±2.15 |
| 0.19% | 66.98±43.93 | - | - | 8.63±0.44† | 100.00±0.00 | 97.77±3.41 | ||
| 0.15% | 54.49±45.17 | - | - | 8.23±1.03† | 98.55±0.96 | 91.50±8.22 | ||
| Insert AS | 0.23% | 8.30±0.61 | 81.94±40.38 | - | - | 59.77±45.35 | 100.00±0.00 | 100.00±0.00 |
| 0.20% | 61.53±49.78 | - | - | 29.77±38.14 | 100.00±0.00 | 100.00±0.00 | ||
| 0.17% | 39.01±43.11 | - | - | 37.22±52.68 | 100.00±0.00 | 99.97±0.05 | ||
| Identifier Renaming | 0.13% | 8.03±0.45 | 97.21±5.26 | - | - | 49.31±42.04 | 99.02±1.24 | 94.33±7.12 |
| 0.10% | 80.06±40.07 | - | - | 69.72±51.52 | 91.40±10.99 | 98.22±0.79 | ||
| 0.07% | 22.71±31.13 | - | - | 8.13±1.07† | 62.85±30.29 | 77.45±20.04 | ||
| Constant Unfolding | 0.200% | 8.02±0.60 | 79.25±8.82 | - | - | 7.92±0.76† | 8.96±1.68 | 79.66±9.63 |
| 0.185% | 54.27±39.89 | - | - | 8.20±0.57† | 7.42±0.76† | 85.03±0.20 | ||
| 0.170% | 38.90±42.80 | - | - | 8.53±0.90† | 8.18±1.39† | 86.86±0.38 | ||
of interest we also report selection time, the wall-clock time of the full selection procedure under a fixed budget.
Framework configuration and protocol. All methods except PFS run inside the iterative framework of Section III-E (Algorithm 1), so the comparison isolates the scoring function; PFS instead uses its own two-stage procedure of similarity-based filtering followed by random sampling, under the same budget. On the classification tasks every iterative method shares the same search budget, iterations with an initial filter ratio , so that the comparison reflects the scoring criterion rather than differences in search effort. Methods that use a filter-ratio decay adopt the common form with . Code repair, which is compared only against RSS, uses and , both selected on the validation set. Method-specific settings follow each original paper: FUS and FUS++ use full proxy training, RD and TNCS an early-stage proxy trained for one epoch, and PFS none. For each task the three poisoning ratios lie in the low-rate range where the selection method most affects ASR, located by a preliminary sweep with random selection; the ratios are shared across families on defect detection and code repair, and set per family on clone detection, whose families differ more sharply in how their ASR responds to the budget. Every configuration is repeated to account for stochasticity, five times for random selection and three times for all other methods, and we report mean and standard deviation. Hardware and software details are given in Appendix B; within each experiment all methods run on the same machine, so reported times reflect differences between methods rather than hardware.
B. RQ1: Classification Efficiency
We answer RQ1 on defect detection and clone detection. To calibrate the reported values we measure, for every trigger family, a clean-model reference ASR: the ASR of a model trained without any poisoning, evaluated on the same poisoned test set. Since that model has never seen a poisoned sample, the reference is the rate at which triggered inputs reach the target through ordinary misclassification rather than through a backdoor, and the effective contribution of an attack is the margin by which its ASR exceeds it. Table III reports the results.
Defect detection. TNCS attains the best ASR in nine of the fifteen settings (including one tie) and ranks in the top two in twelve, with its advantage concentrated at the tightest budgets: at 0.1% it ranks first on all five families. The clean-model reference makes this concentration visible. At 0.1% random selection injects almost no backdoor, exceeding the reference by 3.9 and 2.4 points on Insert CS and Insert GGS, while TNCS reaches margins of 14.0 and 18.1 points under the same budget. At 0.5% the dead-code families leave little for the selection strategy to decide: RD and TNCS both exceed 97% on all three, RD's lead is between 0.1 and 0.9 points, and every gap falls inside RD's own run-to-run standard deviation. The differences that matter therefore appear at the tighter budgets, which is where our focus lies. Constant unfolding is the exception and the hardest family: TNCS reaches 87.22% at 0.5% while every score-based baseline stays below 76%, leads the next best method by 2.8 points at 0.3%, and is the only method whose mean exceeds the reference band at 0.1%. The one setting where TNCS is not competitive is Insert AS at 0.3% (71.92% against 84.25% for RSS and FUS). This cell lies in the family's sharp transition region and carries the largest run-to-run variance on defect detection, with standard deviations up to ±16.2 and heavily overlapping intervals; the standard deviation of TNCS (±6.1) is among the smallest, and it returns to first place on this family at 0.1%.
Selection cost separates the methods more sharply than ASR does. The times below are per-run averages across all defect-detection configurations, with all methods run on the same machine. FUS and FUS++ require about 4.3 hours each (15,575 and 15,835 s) for full proxy training, while RD and TNCS complete in about 56 minutes (3,347 and 3,336 s); the extra forward passes that TNCS performs on the neutralized counterfactuals are negligible next to the shared one-epoch proxy training. PFS is cheapest at 371 s but carries the weakest signal on this task. The forgetting signal underlying FUS and FUS++ turns out to have almost no resolution in this training regime, which we return to in Section VI.
Clone detection. On this task the clean-model reference is nearly uniform across families, consistent with a clean F1 of about 91%. What separates the methods here is not the peak ASR in individual cells but effectiveness across families. RD fails systematically: on Insert GGS and constant unfolding it stays within the reference band at every ratio, and it is highly unstable elsewhere, with standard deviations reaching . PFS shows the opposite polarization, reaching 100% on the three dead-code families yet collapsing to within a point of the reference on constant unfolding at all three ratios. Random selection works at the upper end of each family's range but degrades erratically toward the lower end, with standard deviations frequently above . TNCS is the only method that stays effective on every family: above 90% on the dead-code families, best at the two lower ratios of identifier renaming, and the only score-based method that works on constant unfolding, where it reaches 79.7–86.9%. Its standard deviations are also consistently small.
These two failure modes correspond to the two categories of Section IV-A. RD is target-aware but trigger-agnostic: it favors pairs the scoring model classifies as clones with the highest confidence, for which the evidence carried by the pair itself opposes the attacker-chosen label, so the resulting signal is dominated by sample-specific characteristics rather than by the trigger. PFS is trigger-aware but target-agnostic and characterizes the trigger only at the feature level; constant unfolding replaces a single literal with an equivalent expression, a perturbation so small that every candidate yields a near-identical clean-to-triggered similarity, leaving the ranking with no discriminative range. Dead-code insertion, by contrast, adds a full statement whose feature-space footprint varies across host functions, which is why PFS performs strongly there and in several cells exceeds TNCS. TNCS remains within a few points of PFS in those cells while avoiding its collapse, and from the attacker's perspective a strategy whose effectiveness depends on the trigger family is of limited value, since the trigger is fixed before selection begins.
Clean-task performance. On defect detection the mean clean accuracy of every method lies within 0.6 points of the clean model (63.10%), and on clone detection every method lies within 0.6 points of the clean F1 (90.71%), with largely overlapping run-to-run variability (Appendix C). Poisoning below one percent therefore leaves clean-task performance essentially unchanged regardless of the selection method, so the ASR gains above are not bought at the cost of clean behavior and the attacks remain difficult to catch through standard validation.
C. RQ2: Generation Support
We answer RQ2 on code repair. Random selection is the only applicable baseline here. Code repair also needs no clean-model reference: ASR requires an exact match with the attacker-chosen target patch, which an unpoisoned model has essentially no chance of producing, so the reported ASR is itself the effective lift. Table IV reports the results.
TNCS attains the higher ASR in all fifteen settings, and as on the classification tasks the gap widens as the budget tightens. At 0.30% and 0.25% both methods already reach high ASR on most families. At 0.20% random selection degrades severely and erratically, falling to 57.76%, 48.28%, and 50.74% on Insert CS, Insert GGS, and identifier renaming with standard deviations between and , so its success depends heavily on which samples happen to be drawn. Under the same budget TNCS reaches 84.76%, 61.25%, and 87.66% on these families, with standard deviations several times smaller: against on Insert CS, and against on constant unfolding. The gain is therefore in reliability as well as in mean ASR.
The hardest family here is Insert GGS, where TNCS reaches 61.25% at 0.20%, rather than constant unfolding as on the classification tasks; TNCS leads on it at every ratio (Section V-D). The target-sequence log-likelihood shift of Section IV-D therefore carries the method to autoregressive generation, a setting that the existing scoring methods do not address. Clean repair quality is unaffected: the mean clean
TABLE IV
ASR (%) on code repair. Mean±std under three low poisoning ratios. RSS is the only applicable baseline on this task, and no clean-model reference is needed, since an unpoisoned model essentially never emits the target patch. Better per row in bold.
| Trigger family | Ratio | RSS | TNCS (Ours) |
|---|---|---|---|
| Insert CS | 0.30% | 98.16±1.11 | 98.72±0.31 |
| 0.25% | 97.90±1.36 | 98.68±1.08 | |
| 0.20% | 57.76±30.19 | 84.76±10.88 | |
| Insert GGS | 0.30% | 88.58±9.19 | 90.39±9.88 |
| 0.25% | 80.40±5.94 | 85.24±9.29 | |
| 0.20% | 48.28±24.09 | 61.25±21.05 | |
| Insert AS | 0.30% | 97.48±2.35 | 99.30±0.47 |
| 0.25% | 95.93±2.44 | 97.36±2.96 | |
| 0.20% | 73.40±31.81 | 78.10±28.52 | |
| Identifier Renaming | 0.30% | 94.47±9.07 | 99.81±0.13 |
| 0.25% | 93.21±4.06 | 98.63±1.78 | |
| 0.20% | 50.74±35.68 | 87.66±8.87 | |
| Constant Unfolding | 0.30% | 87.11±7.83 | 91.36±7.52 |
| 0.25% | 84.57±6.53 | 87.42±8.18 | |
| 0.20% | 56.28±27.33 | 72.99±4.46 |
CodeBLEU of both methods lies within one point of the clean model (74.64%, Appendix C).
D. RQ3: Consistency Across Trigger Families
We now read the preceding results across trigger families rather than within a single task. The baselines diverge most clearly along the structural axis of Section III-C, which separates the three statement-level dead-code families from the two token- and expression-level ones, and their failures fall almost entirely on the latter. On both classification tasks every method attains its smallest mean margin over the reference on constant unfolding. On clone detection the contrast is sharper: PFS exceeds the reference by more than 90 points on all three dead-code families yet stays within a point of it on constant unfolding. This is consistent with the input- and feature-level quantities these baselines rely on, as analyzed in Section V-B. TNCS shows no such dependence and attains its largest margins precisely where the baselines are weakest.
Along the second axis, fixed versus dynamic trigger patterns, Insert GGS samples a distinct statement from a grammar for each poisoned sample, so its surface form varies across the pool. This makes it the hardest family on code repair, where random selection falls below 49% at the tightest budget, and it is the one dead-code family on which RD fails in clone detection. TNCS stays ahead of random selection at every ratio on code repair and above 90% on clone detection, so its signal does not depend on a stable trigger surface.
The hardest family is not the same across tasks, being constant unfolding on the two classification tasks and Insert GGS on code repair, yet TNCS retains the best ASR among the applicable methods on both. It is the only method evaluated that remains effective across all five trigger families and all three tasks.
E. RQ4: Robustness to Attacker–Victim Mismatch
The experiments so far assume that the scoring model matches the victim. We now relax that assumption along three dimensions in turn, instantiating the black-box setting of Section III-D: a mismatch in architecture, in training configuration, and in the fraction of the victim's training data available to the attacker. In each case we ask whether the poison set selected on the scoring model remains effective on a victim that differs from it. The experiments use a single low poisoning ratio per task, with one statement-level trigger family (Insert CS) and one token-/expression-level family (constant unfolding). Table V reports the results.
Architecture mismatch. Pairing the encoder-only CODEBERT with the encoder-decoder CODET5 costs little. Because CODET5 is generative, defect detection is cast as sequence generation when it serves as the scoring model, so TNCS is computed in its generation form in one direction and in its classification form in the other. When the victim is CODET5 the black-box ASR differs from the white-box value by at most 0.6 points; when the victim is CODEBERT it drops by 2.3 points on Insert CS and 3.0 points on constant unfolding, the largest degradation under architecture mismatch. In every configuration the mismatched selection still exceeds random selection. That the same signal transfers across two structurally different architectures while being computed in two different forms suggests that what TNCS measures is not specific to one architecture.
Configuration mismatch. On defect detection TNCS degrades only slightly as the mismatch grows, from 67.78% to 64.44% on constant unfolding while staying above 92% on Insert CS. RD follows a similar downward trend from a lower level, so TNCS under the large mismatch still exceeds RD under the matched configuration (64.44% against 60.69%). On code repair the three configurations stay between 73.0% and 75.0% on constant unfolding and between 84.8% and 91.5% on Insert CS, all far above random selection, which reaches only 56–58% at this budget with much larger standard deviations.
Data-access mismatch. On defect detection TNCS attains the best ASR at every data fraction on both families, and its advantage does not shrink as the scoring model's data does; on constant unfolding it rises from 67.78% at full data to 77.95% at 25%. This non-monotonic behavior is unlikely to be an artifact of a favorable subset, since all methods draw from the same subset at each fraction and neither baseline shows a comparable rise, but we leave its cause open. On code repair the trend across fractions is inconsistent between the two families and the standard deviations are large, reflecting the high variance of this budget rather than an effect of data access; TNCS nonetheless exceeds random selection at every fraction. Across all three dimensions the selection signal of TNCS therefore does not depend on exact knowledge of the victim's training pipeline, which supports its applicability when the attacker can only approximate it.
TABLE V
Robustness to attacker–victim mismatch. ASR (% , mean±std) on defect detection at 0.3% and code repair at 0.2%. The victim always uses the white-box training configuration and the full training data. Configuration mismatch perturbs the scoring model's learning rate and batch size (defect: 2e-5/32, 1e-5/32, 5e-5/16; repair: 5e-5/32, 3e-5/32, 1e-4/16); data mismatch trains it on a fraction of the victim's data. RSS needs no scoring model. Within each panel the best value per column is in bold. --: not applicable.
(a) Architecture mismatch, defect detection
| Mismatch | Method | Scoring model | Victim: CODET5 | Victim: CODEBERT | ||
|---|---|---|---|---|---|---|
| Constant Unfolding | Insert CS | Constant Unfolding | Insert CS | |||
| Architecture | RSS | - | 89.00±2.62 | 92.75±16.22 | 60.41±5.99 | 89.56±8.94 |
| TNCS (Ours) | Same architecture | 90.60±3.28 | 100.00±0.00 | 67.78±2.70 | 93.52±2.33 | |
| Other architecture | 89.99±3.99 | 100.00±0.00 | 64.83±3.15 | 91.18±8.10 | ||
(b) Training-configuration and data-access mismatch
| Mismatch | Method | Scoring model | Defect detection | Code repair | ||
|---|---|---|---|---|---|---|
| Constant Unfolding | Insert CS | Constant Unfolding | Insert CS | |||
| Configuration | RSS | - | 60.41±5.99 | 89.56±8.94 | 56.28±27.33 | 57.76±30.19 |
| Matched | 60.69±3.82 | 93.33±4.41 | - | - | ||
| RD | Small mismatch | 59.68±4.84 | 92.35±8.21 | - | - | |
| Large mismatch | 58.14±5.03 | 89.35±9.50 | - | - | ||
| Matched | 67.78±2.70 | 93.52±2.33 | 72.99±4.46 | 84.76±10.88 | ||
| TNCS (Ours) | Small mismatch | 66.66±6.75 | 93.31±3.89 | 75.01±4.60 | 91.50±2.63 | |
| Large mismatch | 64.44±5.08 | 92.56±6.20 | 73.00±16.19 | 89.03±5.45 | ||
| Data access | RSS | 100% of data | 60.41±5.99 | 89.56±8.94 | 56.28±27.33 | 57.76±30.19 |
| 50% | 63.51±6.43 | 84.48±6.95 | 64.07±28.33 | 74.72±41.35 | ||
| 25% | 60.13±4.71 | 88.43±12.10 | 60.55±21.47 | 81.94±14.41 | ||
| RD | 100% of data | 60.69±3.82 | 93.33±4.41 | - | - | |
| 50% | 59.89±3.51 | 80.90±13.55 | - | - | ||
| 25% | 63.11±6.34 | 86.80±9.01 | - | - | ||
| TNCS (Ours) | 100% of data | 67.78±2.70 | 93.52±2.33 | 72.99±4.46 | 84.76±10.88 | |
| 50% | 70.73±3.64 | 86.19±7.96 | 64.72±7.64 | 91.02±0.44 | ||
| 25% | 77.95±5.77 | 94.95±3.23 | 64.13±21.30 | 93.29±1.72 | ||
F. Ablation Studies
All ablations use defect detection with one statement-level trigger family (Insert CS) and one token-/expression-level family (constant unfolding).
Scoring-function design. Table VI compares TNCS against three variants, each removing one component. Triggered-only Scoring (TOS) drops the counterfactual comparison and uses only the target log-probability on the triggered input; Clean-Reference Scoring (CRS) keeps the comparison but references the clean input instead of the neutralized counterfactual; and TNCS-Signed omits the absolute value. TNCS is best on both families. On constant unfolding, the harder one, it reaches 67.78% while all three variants fall between 62.8% and 63.5%. The clearest degradation is CRS on Insert CS, which drops to 83.72% with a large standard deviation, below random selection: referencing the clean input changes the sequence length and positional alignment relative to the triggered input, which is exactly the structural difference the neutralized counterfactual is constructed to avoid (Section III-C).
Three further ablations appear in Appendix D. Replacing the family-specific neutralization with a single strategy for all families costs three points on constant unfolding and nothing on Insert CS, so the distinction matters only for the token-and expression-level family. Reversing the ranking to retain the lowest-scoring rather than the highest-scoring candidates drops ASR to 60.56% at 0.5% on constant unfolding, below
TABLE VI
Ablation of the TNCS scoring components. ASR (% , mean±std) on defect detection at the 0.3% poisoning ratio. Each variant removes one component; RD and RSS are shown for reference. Best per family in bold.
| Method | Constant Unfolding | Insert CS |
|---|---|---|
| RSS | 60.41±5.99 | 89.56±8.94 |
| RD | 60.69±3.82 | 93.33±4.41 |
| TOS | 62.82±2.99 | 92.19±5.23 |
| CRS | 63.14±9.90 | 83.72±10.75 |
| TNCS-Signed | 63.53±3.62 | 91.24±5.29 |
| TNCS (Ours) | 67.78±2.70 | 93.52±2.33 |
the 84.51% of random selection, which indicates that low-scoring candidates are actively poor choices rather than merely uninformative. For the iterative framework, ASR is single-peaked in both the initial filter ratio and the decay rate, and is highest when the proxy is trained for a single epoch, which is the configuration used throughout.
Validating the neutralization operator. Because [MASK] can be mildly out of distribution for a fine-tuned classifier, the shift that TNCS measures might reflect that artifact rather than the trigger. Two controls on the three dead-code families, which are the families that use [MASK] neutralization, rule this out. Masking the trigger span produces an output shift 12.6 to 51.8 times larger than masking a length-matched random span, on every family (two-sided paired t-test, n = 109 per family, p < 0.001). On a clean model trained identically but without poisoned data, the trigger-span shift is 14.9 to 24.7 times smaller than on the poisoned model. Masking does introduce a small distribution shift, roughly doubling the random-span shift on the clean model, but it is an order of magnitude smaller than the backdoor signal it is set against (Appendix D).
VI. Discussion
Why forgetting-event selection underperforms on code. FUS and FUS++ incur the highest selection cost in our experiments yet rarely outperform cheaper alternatives. Examining the distribution of forgetting events over the poisoned candidate pool explains why. In the image-classification setting of the original FUS study, 16.9% of poisoned samples are forgotten at least twice, forming the highly forgettable group the method is designed to prioritize [11]. In our code setting that group is essentially empty: across all five trigger families no sample reaches three or more forgetting events, the fraction with two events is at most 4.8%, and for identifier renaming 96.4% of the pool is never forgotten at all (Appendix E). A signal that assigns one of two values to nearly every candidate cannot rank a pool. The cause lies in the training regime rather than the implementation: forgetting statistics accumulate over epochs, and where the original CIFAR-10 experiments train for 60 epochs, fine-tuning a pre-trained code model converges within three to five. This is a structural property of the pre-train-and-fine-tune paradigm that dominates code intelligence, so we expect it to hold beyond our configuration. It also explains why FUS and FUS++ still reach reasonable ASR: when the score has almost no resolution the filter-and-refresh loop degenerates toward random pool refreshment, so their results gravitate toward random selection rather than collapsing. The 4.7-fold proxy-training cost they carry over the early-stage methods buys little. Forgetting-event distributions therefore offer a cheap diagnostic for whether this family of methods suits a given training regime.
Scope of the gradient argument. The decomposition of a poisoned sample's gradient signal into trigger-specific and sample-specific components (Section IV-A) is a framing that motivates the score, not a quantity we measure. Likewise, the step from the gradient difference of Eq. (6) to an output shift retains one factor of the chain rule and drops the other, following RD [12], and is a motivating approximation rather than an identity. What the experiments establish is narrower and empirical: the resulting score selects more effective poisoning candidates than the baselines at low budgets, and the shift it measures is attributable to the trigger rather than to the neutralization operator itself (Section V-F).
Limitations. Two limitations bound these findings. First, the victim and scoring models are confined to CODEBERT and CODET5. These remain the standard victims in code backdoor research, which keeps our results comparable with that literature, but whether the same advantage holds for substantially larger code models remains to be verified. Second, at the tightest budgets the attack success rate is high-variance for every method, random selection included, which limits how much weight any single such setting can bear; the consistency of TNCS is best read across settings rather than from any one of them. The non-monotonic behavior observed under data-access mismatch (Section V-E) is a further open question.
Relation to defenses. We do not evaluate defenses, and neither do the studies whose selection framework and early-stage proxy this work adopts [11], [12]. Many existing backdoor defenses rely on identifying anomalous poisoned samples through statistical or representation-level differences from benign data [26], [27]. Because informed selection reaches a given attack success rate with fewer poisoned samples, such defenses would need to remain effective at lower poisoning ratios than those suggested by a random-selection baseline. Whether informed selection also changes the detectability of individual poisoned samples relative to random selection at the same poisoning ratio is a separate question that our experiments do not answer.
Future work. The scoring principle is task-agnostic: wherever a task defines a measurable notion of support for the attacker-chosen target, a corresponding output-shift score can be formulated. Natural next steps are other code tasks, in particular the code completion models that have become central to development tooling and a recurring target of recent work [8], [9]; other domains such as natural language processing; and larger open-weight code models such as CODE LLAMA [48], DEEPSEEK-CODER [19], and STARCODER [18].
VII. Conclusion
This work studied data-efficient backdoor attacks on code models, addressing two gaps left by prior work: existing sample-selection methods had been developed and evaluated almost entirely on image classification, and none provided a scoring mechanism for autoregressive sequence generation. We proposed Trigger-Neutralized Counterfactual Scoring, which scores a poisoning candidate by how much the scoring model's support for the attacker-chosen target changes when the trigger-bearing span is neutralized, and instantiated the same principle as a target-label log-probability shift for classification and a target-sequence log-likelihood shift under teacher forcing for generation. Across three CODEXGLUE tasks and five trigger families, TNCS attained higher attack success rates than representative baselines at the lowest poisoning ratios, was the only method that remained effective on every trigger family, provided a usable selection signal for code repair where the existing methods do not apply, and produced poison sets that transferred to victims differing from the scoring model in architecture, training configuration, or available data. Explicitly measuring the trigger's contribution therefore yields a selection signal that is both more effective under tight budgets and more robust across tasks and settings than the trigger-agnostic or target-agnostic signals used by prior methods.
ETHICS CONSIDERATIONS
This work develops an attack, and we considered its dual-use implications. The capability is not novel in kind: backdoor poisoning of code models and data-efficient sample selection are each established in prior work, and the trigger families we use are taken unchanged from published studies [5], [7], so we disclose no new means of evading code review or static analysis. What the results add is that an informed attacker reaches a given attack success rate at a lower poisoning ratio than random selection requires, which is information defenders need. No human subjects were involved and no personal data was processed; all experiments use public research benchmarks within their intended research scope. All work was conducted offline on machines under our control, and we did not poison, upload to, or otherwise affect any public repository, dataset distribution, model hub, or third-party training pipeline. Poisoned datasets and backdoored checkpoints exist only locally and will not be published. We identified no vulnerability in a specific product or deployed system, so coordinated disclosure does not apply here.
REFERENCES
[1] Z. Feng, D. Guo, D. Tang, N. Duan, X. Feng, M. Gong, L. Shou, B. Qin, T. Liu, D. Jiang, and M. Zhou, "CodeBERT: A pre-trained model for programming and natural languages," in Findings of the Association for Computational Linguistics: EMNLP, 2020, pp. 1536–1547.
[2] Y. Wang, W. Wang, S. Joty, and S. C. Hoi, “CodeT5: Identifier-aware unified pre-trained encoder-decoder models for code understanding and generation,” in Proceedings of the Conference on Empirical Methods in Natural Language Processing (EMNLP), 2021, pp. 8696–8708.
[3] T. Gu, K. Liu, B. Dolan-Gavitt, and S. Garg, “BadNets: Evaluating backdooring attacks on deep neural networks,” IEEE Access, vol. 7, pp. 47230–47244, 2019.
[4] S. Lu, D. Guo, S. Ren, J. Huang, A. Svyatkovskiy, A. Blanco, C. Clement, D. Drain, D. Jiang, D. Tang, G. Li, L. Zhou, L. Shou, L. Zhou, M. Tufano, M. Gong, M. Zhou, N. Duan, N. Sundaresan, S. K. Deng, S. Fu, and S. Liu, “CodeXGLUE: A machine learning benchmark dataset for code understanding and generation,” in Proceedings of the Neural Information Processing Systems Track on Datasets and Benchmarks (NeurIPS Datasets and Benchmarks), vol. 1, 2021.
[5] J. Li, Z. Li, H. Zhang, G. Li, Z. Jin, X. Hu, and X. Xia, “Poison attack and poison detection on deep source code processing models,” ACM Transactions on Software Engineering and Methodology, vol. 33, no. 3, 2024.
[6] R. Schuster, C. Song, E. Tromer, and V. Shmatikov, “You autocomplete me: Poisoning vulnerabilities in neural code completion,” in USENIX Security Symposium (USENIX Security), 2021, pp. 1559–1575.
[7] G. Ramakrishnan and A. Albarghouthi, “Backdoors in neural models of source code,” in International Conference on Pattern Recognition (ICPR), 2022, pp. 2892–2899.
[8] H. Aghakhani, W. Dai, A. Manoel, X. Fernandes, A. Kharkar, C. Kruegel, G. Vigna, D. Evans, B. Zorn, and R. Sim, “TrojanPuzzle: Covertly poisoning code-suggestion models,” in IEEE Symposium on Security and Privacy (SP), 2024, pp. 1122–1140.
[9] S. Yan, S. Wang, Y. Duan, H. Hong, K. Lee, D. Kim, and Y. Hong, "An LLM-Assisted Easy-to-Trigger backdoor attack on code completion models: Injecting disguised vulnerabilities against strong detection," in USENIX Security Symposium (USENIX Security), 2024, pp. 1795–1812.
[10] Z. Yang, B. Xu, J. M. Zhang, H. J. Kang, J. Shi, J. He, and D. Lo, "Stealthy backdoor attack for code models," IEEE Transactions on Software Engineering, vol. 50, no. 4, pp. 721–741, 2024.
[11] P. Xia, Z. Li, W. Zhang, and B. Li, “Data-efficient backdoor attacks,” in Proceedings of the International Joint Conference on Artificial Intelligence (IJCAI), 2022, pp. 3992–3998.
[12] Y. Wu, X. Han, H. Qiu, and T. Zhang, “Computation and data efficient backdoor attacks,” in Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV), 2023, pp. 4805–4814.
[13] X. Han, Y. Wu, Q. Zhang, Y. Zhou, Y. Xu, H. Qiu, G. Xu, and T. Zhang, "Backdooring multimodal learning," in IEEE Symposium on Security and Privacy (SP), 2024, pp. 3385–3403.
[14] Z. Li, P. Xia, H. Sun, Y. Zeng, W. Zhang, and B. Li, “Explore the effect of data selection on poison efficiency in backdoor attacks,” IEEE Transactions on Dependable and Secure Computing, vol. 22, no. 6, pp. 7430–7447, 2025.
[15] Z. Li, H. Sun, P. Xia, B. Xia, X. Rui, W. Zhang, Q. Guo, Z. Fu, and B. Li, “A proxy attack-free strategy for practically improving the poisoning efficiency in backdoor attacks,” IEEE Transactions on Information Forensics and Security, vol. 19, pp. 9730–9743, 2024.
[16] Y. Xun, X. Jia, J. Gu, X. Liu, Q. Guo, and X. Cao, “Minimalism is king! high-frequency energy-based screening for data-efficient backdoor attacks,” IEEE Transactions on Information Forensics and Security, vol. 19, pp. 4560–4571, 2024.
[17] D. Guo, S. Ren, S. Lu, Z. Feng, D. Tang, S. Liu, L. Zhou, N. Duan, A. Svyatkovskiy, S. Fu, M. Tufano, S. K. Deng, C. B. Clement, D. Drain, N. Sundaresan, J. Yin, D. Jiang, and M. Zhou, “GraphCodeBERT: Pretraining code representations with data flow,” in International Conference on Learning Representations (ICLR), 2021.
[18] R. Li, L. B. Allal, Y. Zi, N. Muennighoff, D. Kocetkov, C. Mou, M. Marone, C. Akiki, J. Li, J. Chim et al., “StarCoder: may the source be with you!” arXiv preprint arXiv:2305.06161, 2023.
[19] D. Guo, Q. Zhu, D. Yang, Z. Xie, K. Dong, W. Zhang, G. Chen, X. Bi, Y. Wu, Y. Li et al., “DeepSeek-Coder: When the large language model meets programming—the rise of code intelligence,” arXiv preprint arXiv:2401.14196, 2024.
[20] X. Chen, C. Liu, B. Li, K. Lu, and D. Song, “Targeted backdoor attacks on deep learning systems using data poisoning,” arXiv preprint arXiv:1712.05526, 2017.
[21] A. Turner, D. Tsipras, and A. Madry, “Label-consistent backdoor attacks,” arXiv preprint arXiv:1912.02771, 2019.
[22] M. Barni, K. Kallas, and B. Tondi, “A new backdoor attack in CNNs by training set corruption without label poisoning,” in IEEE International Conference on Image Processing (ICIP), 2019, pp. 101–105.
[23] J. Dai, C. Chen, and Y. Li, “A backdoor attack against LSTM-based text classification systems,” IEEE Access, vol. 7, pp. 138 872–138 878, 2019.
[24] X. Chen, A. Salem, D. Chen, M. Backes, S. Ma, Q. Shen, Z. Wu, and Y. Zhang, “BadNL: Backdoor attacks against NLP models with semantic-preserving improvements,” in Proceedings of the Computer Security Applications Conference, 2021, pp. 554–569.
[25] F. Qi, M. Li, Y. Chen, Z. Zhang, Z. Liu, Y. Wang, and M. Sun, “Hidden Killer: Invisible textual backdoor attacks with syntactic trigger,” in Proceedings of the Annual Meeting of the Association for Computational Linguistics and the International Joint Conference on Natural Language Processing (ACL-IJCNLP), 2021, pp. 443–453.
[26] B. Tran, J. Li, and A. Madry, “Spectral signatures in backdoor attacks,” in Advances in Neural Information Processing Systems (NeurIPS), vol. 31, 2018.
[27] B. Chen, W. Carvalho, N. Baracaldo, H. Ludwig, B. Edwards, T. Lee, I. Molloy, and B. Srivastava, “Detecting backdoor attacks on deep neural networks by activation clustering,” arXiv preprint arXiv:1811.03728, 2018.
[28] J. Guo, Y. Li, X. Chen, H. Guo, L. Sun, and C. Liu, “SCALE-UP: An efficient black-box input-level backdoor detection via analyzing scaled prediction consistency,” in International Conference on Learning Representations (ICLR), 2023.
[29] K. Liu, B. Dolan-Gavitt, and S. Garg, “Fine-Pruning: Defending against backdooring attacks on deep neural networks,” in Research in Attacks, Intrusions, and Defenses (RAID), 2018, pp. 273–294.
[30] Y. Li, X. Lyu, N. Koren, L. Lyu, B. Li, and X. Ma, “Neural Attention Distillation: Erasing backdoor triggers from deep neural networks,” in International Conference on Learning Representations (ICLR), 2021.
[31] —, “Anti-Backdoor Learning: Training clean models on poisoned data,” in Advances in Neural Information Processing Systems (NeurIPS), vol. 34, 2021, pp. 14900–14912.
[32] S. Wachter, B. Mittelstadt, and C. Russell, “Counterfactual explanations without opening the black box: Automated decisions and the GDPR,” Harvard Journal of Law & Technology, vol. 31, no. 2, pp. 841–887, 2018.
[33] R. K. Mothilal, A. Sharma, and C. Tan, “Explaining machine learning classifiers through diverse counterfactual explanations,” in Proceedings of the Conference on Fairness, Accountability, and Transparency, 2020, pp. 607–617.
[34] M. Ivanovs, R. Kadikis, and K. Ozols, “Perturbation-based methods for explaining deep neural networks: A survey,” Pattern Recognition Letters, vol. 150, pp. 228–234, 2021.
[35] R. C. Fong and A. Vedaldi, “Interpretable explanations of black boxes by meaningful perturbation,” in Proceedings of the IEEE International Conference on Computer Vision (ICCV), 2017.
[36] Z. Wu, Y. Chen, B. Kao, and Q. Liu, “Perturbed masking: Parameter-free probing for analyzing and interpreting BERT,” in Proceedings of the Annual Meeting of the Association for Computational Linguistics (ACL), 2020, pp. 4166–4176.
[37] J. Li, W. Monroe, and D. Jurafsky, “Understanding neural networks through representation erasure,” arXiv preprint arXiv:1612.08220, 2017.
[38] S. Kim, J. Yi, E. Kim, and S. Yoon, “Interpretation of NLP models through input marginalization,” in Proceedings of the Conference on Empirical Methods in Natural Language Processing (EMNLP), 2020, pp. 3154–3167.
[39] J. Cito, I. Dillig, V. Murali, and S. Chandra, “Counterfactual explanations for models of code,” in Proceedings of the International Conference on Software Engineering: Software Engineering in Practice, 2022, pp. 125–134.
[40] D. Nader Palacio, A. Velasco, N. Cooper, A. Rodriguez, K. Moran, and D. Poshyvanyk, “Toward a theory of causation for interpreting neural code models,” IEEE Transactions on Software Engineering, vol. 50, no. 5, pp. 1215–1243, 2024.
[41] Y. Gao, Y. Li, L. Zhu, D. Wu, Y. Jiang, and S.-T. Xia, “Not all samples are born equal: Towards effective clean-label backdoor attacks,” Pattern Recognition, vol. 139, p. 109512, 2023.
[42] Y. Zhou, S. Liu, J. Siow, X. Du, and Y. Liu, “Devign: Effective vulnerability identification by learning comprehensive program semantics via graph neural networks,” in Advances in Neural Information Processing Systems (NeurIPS), vol. 32, 2019.
[43] J. Svajlenko, J. F. Islam, I. Keivanloo, C. K. Roy, and M. M. Mia, “Towards a big data curated benchmark of inter-project code clones,” in 2014 IEEE International Conference on Software Maintenance and Evolution, 2014, pp. 476–480.
[44] W. Wang, G. Li, B. Ma, X. Xia, and Z. Jin, “Detecting code clones with graph neural network and flow-augmented abstract syntax tree,” in 2020 IEEE 27th International Conference on Software Analysis, Evolution and Reengineering (SANER), 2020, pp. 261–271.
[45] M. Tufano, C. Watson, G. Bavota, M. D. Penta, M. White, and D. Poshyvanyk, “An empirical study on learning bug-fixing patches in the wild via neural machine translation,” ACM Transactions on Software Engineering and Methodology (TOSEM), vol. 28, no. 4, pp. 1–29, 2019.
[46] Y. Li, S. Liu, K. Chen, X. Xie, T. Zhang, and Y. Liu, “Multi-target backdoor attacks for code pre-trained models,” in Proceedings of the Annual Meeting of the Association for Computational Linguistics (ACL), 2023, pp. 7236–7254.
[47] S. Ren, D. Guo, S. Lu, L. Zhou, S. Liu, D. Tang, N. Sundaresan, M. Zhou, A. Blanco, and S. Ma, “CodeBLEU: a method for automatic evaluation of code synthesis,” arXiv preprint arXiv:2009.10297, 2020.
[48] B. Roziere, J. Gehring, F. Gloeckle, S. Sootla, I. Gat, X. E. Tan, Y. Adi, J. Liu, R. Sauvestre, T. Remez et al., “Code Llama: Open foundation models for code,” arXiv preprint arXiv:2308.12950, 2023.
APPENDIX A
TRIGGER IMPLEMENTATION DETAILS
Each trigger family is instantiated in the programming language of its task, C/C++ for Devign and Java for BigCloneBench and Bugs2Fix. The injection mechanism is identical across languages and only the terminal syntax differs, for example the dead-code construct and the standard-library functions used in its guard. Table VII gives one concrete instance per family.
For Insert GGS, each trigger is a single-line statement sampled from a context-free grammar . The grammar draws the control structure from , a mathematical function from with all but rand
TABLE VII Concrete trigger instances. One example per family, shown in C syntax.
| Family | Instance |
|---|---|
| Insert CS | if (false_cond) action(); |
| Insert GGS | if (cos(0.75) <= -20)printf(alert); |
| Insert AS | assert(always_true_cond); |
| Identifier renaming | getConnection → ret_Val_ |
| Constant unfolding | 67 → 67+(1+2-3)*33 |
taking a random argument in , a comparison operator from , and a body statement that prints a message drawn from a set of preset keywords and randomly generated strings. To guarantee the dead-code property, the comparison constant is chosen outside the range of the sampled function so that the guard is always false: a large negative value when the operator is , or , and a large positive value when it is > or . The Java instantiation replaces the C mathematical functions and print statement with their standard-library counterparts, keeping the grammar structure and the always-false construction unchanged.
Figure 2 illustrates the neutralization operator on one instance of each of the two structural categories.
APPENDIX B
EXPERIMENTAL ENVIRONMENT
Table VIII lists the two machines used for the experiments. All methods compared within a single experiment run on the same machine, so reported selection times reflect differences between methods rather than hardware.
TABLE VIII Hardware and software environment. The software stack and memory are identical across the two machines, which differ only in CPU, GPU, and CUDA version.
| Common configuration | |
|---|---|
| RAM | 64 GB |
| OS | Ubuntu 24.04.2 LTS |
| PyTorch | 2.7.1 |
| Python | 3.12.3 |
| Per-machine configuration | |
| Machine A | CPU: AMD Ryzen Threadripper 7970X;GPU: RTX 4070 Ti Super (16 GB); CUDA 12.8 |
| Machine B | CPU: Intel Xeon w5-2455X;GPU: RTX 4090 (24 GB); CUDA 13.0 |
APPENDIX C
CLEAN-TASK PERFORMANCE
Poisoning below one percent leaves clean-task performance essentially unchanged for every selection method. On defect detection (Table IX) the clean model reaches 63.10% accuracy and every method lies within 0.6 points of it; on clone detection (Table X) the clean model reaches 90.71% F1 with the same bound; and on code repair (Table XI) the clean model
(a) Dead-code Insertion (Insert CS)
Triggered input
int compute_sum(int n) { int result = 0; if (sin(0.7) < -1) { printf("alert"); } for (int i = 0; i < n; i++) { result += i; } return result; }
Neutralized counterfactual
int compute_sum(int n) { int result = 0; [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] for (int i = 0; i < n; i++) { result += i; } return result; }
The inserted dead-code span (lines 3–5) is replaced with the same number of [MASK] tokens, preserving sequence length and positional alignment.
(b) Identifier Renaming
Triggered input
int compute_sum(int n) { int ret_Val_ = 0; for (int i = 0; i < n; i++) { ret_Val_ += i; } return ret_Val_; }
Neutralized counterfactual
int compute_sum(int n) { int tmp_Var_ = 0; for (int i = 0; i < n; i++) { tmp_Var_ += i; } return tmp_Var_; }
Every occurrence of the trigger identifier (ret_Val_) is replaced with a benign identifier (tmp_Var_).
(c) Constant Unfolding
Triggered input
int compute_sum(int n) { int result = 0; for (int i = 0; i < n; i++) { result += i * (67 + (1 + 2 - 3) * 33); } return result; }
Neutralized counterfactual
int compute_sum(int n) { int result = 0; for (int i = 0; i < n; i++) { result += i * (67 + (2 + 3 - 5) * 0); } return result; }
The trigger expression is replaced with a semantically equivalent benign expression ; both evaluate to 67.
Fig. 2. Examples of trigger neutralization. Each panel shows a triggered input (left) and its trigger-neutralized counterfactual (right), illustrated for three representative trigger types: (a) dead-code insertion (shown: Insert CS), where the inserted dead-code span is replaced with the same number of [MASK] tokens, preserving sequence length and positional alignment; (b) identifier renaming, where every occurrence of the trigger identifier is replaced with a benign identifier; and (c) constant unfolding, where the trigger expression is replaced with a semantically equivalent benign expression. The same neutralization principles apply to the other dead-code variants (Insert GGS and Insert AS), which are omitted here for clarity.
TABLE IX
Clean accuracy on defect detection. Clean ACC (%), mean±std) on the unmodified test set, averaged across all trigger families and poisoning ratios for each method. The clean model is trained without poisoning and serves as the reference point.
| Method | Mean clean ACC |
|---|---|
| Clean model (no poisoning) | |
| RSS | |
| FUS | |
| FUS++ | |
| RD | |
| PFS | |
| TNCS (Ours) |
reaches 74.64% CodeBLEU and both methods lie within one point of it.
TABLE X
Clean F1 on clone detection. Clean F1 (%), mean±std) on the unmodified test set, averaged across all trigger families and poisoning ratios for each method. The clean model is trained without poisoning and serves as the reference point. FUS and FUS++ are omitted because their full proxy training is prohibitively costly on this task.
| Method | Mean clean F1 |
|---|---|
| Clean model (no poisoning) | |
| RSS | |
| RD | |
| PFS | |
| TNCS (Ours) |
APPENDIX D
ADDITIONAL ABLATIONS
Neutralization strategy. TNCS applies [MASK] neutralization to the dead-code families and benign replacement to identifier renaming and constant unfolding. Table XII
TABLE XI
Clean CodeBLEU on code repair. Clean CodeBLEU (%, mean±std) on the unmodified test set, averaged across all trigger families and poisoning ratios for each method. The clean model is trained without poisoning and serves as the reference point.
| Method | Mean clean CodeBLEU |
|---|---|
| Clean model (no poisoning) | 74.64 ± 0.82 |
| RSS | 75.35 ± 0.60 |
| TNCS (Ours) | 75.17 ± 0.87 |
TABLE XII
Ablation of the neutralization strategy. ASR (%, mean±std) on defect detection at the 0.3% poisoning ratio. TNCS-ReplaceAll applies benign replacement to all families; TNCS-MaskAll applies [MASK] neutralization to all families. The family-specific strategy used by TNCS (replacement for constant unfolding, [MASK] for dead-code) corresponds to the diagonal of this table. RD and RSS are shown for reference. The best result per family is in bold.
| Method | Constant Unfolding | Dead-code (Insert CS) |
|---|---|---|
| RSS | 60.41±5.99 | 89.56±8.94 |
| RD | 60.69±3.82 | 93.33±4.41 |
| TNCS-ReplaceAll | 67.78±2.70 | 93.36±2.46 |
| TNCS-MaskAll | 64.73±2.65 | 93.52±2.33 |
compares this family-specific choice against applying a single strategy to all families. Replacing benignly everywhere matches TNCS on constant unfolding by construction and loses little on Insert CS, whereas masking everywhere costs three points on constant unfolding, where masking a literal disrupts local syntax. The family-specific distinction therefore matters only for the token- and expression-level family.
Selection direction. Table XIII reverses the ranking, retaining the lowest-scoring candidates instead of the highest-scoring ones. On constant unfolding at 0.5%, retaining high-scoring candidates reaches 87.22% while retaining low-scoring ones reaches 60.56%, below the 84.51% of random selection. That the reversed ranking underperforms random poisoning indicates that low-scoring candidates are actively poor choices rather than merely uninformative. Figure 3 shows both families across ratios. On Insert CS the gap is large at the tightest 0.1% budget (70.68% versus 54.32%) but closes at higher ratios, where the family saturates and the choice of candidates ceases to matter.
Validating the neutralization operator. Table XIV gives the per-family values behind the two controls summarized in Section V-F. The paired t-test is computed over 109 candidate samples per family, and both ratios hold on each of the three dead-code families individually.
Iterative framework hyperparameters. All hyperparameter experiments use constant unfolding, the harder of the two representative families, so that the effect of each choice on the selection signal is more visible.
Figure 4 varies the number of iterations from 3 to 15. TNCS exceeds both RD and random selection at every value, rising steadily from 63.82% at to 72.14% at
TABLE XIII
Ablation of the selection direction. ASR (%, mean±std) on defect detection across three poisoning ratios. TNCS-Top retains the highest-scoring candidates (the default), while TNCS-Bottom retains the lowest-scoring ones. RSS is shown for reference. The best result per row is in bold.
| Ratio | RSS | TNCS-Top | TNCS-Bottom |
|---|---|---|---|
| Constant Unfolding | |||
| 0.50% | 84.51±9.14 | 87.22±3.38 | 60.56±1.32 |
| 0.30% | 60.41±5.99 | 67.78±2.70 | 56.65±6.46 |
| 0.10% | 53.80±5.73 | 61.33±4.54 | 53.23±4.97 |
| Dead-code (Insert CS) | |||
| 0.50% | 92.91±12.05 | 97.32±0.68 | 97.29±1.02 |
| 0.30% | 89.56±8.94 | 93.52±2.33 | 92.27±2.63 |
| 0.10% | 60.59±6.97 | 70.68±4.97 | 54.32±1.69 |

Fig. 3. Selection direction versus poisoning ratio. ASR of TNCS-Top, TNCS-Bottom, and RSS on defect detection for constant unfolding (a) and dead-code (Insert CS) (b). Lines show the mean ASR and shaded regions denote one standard deviation.
, so ASR has not fully saturated at the value of 10 used throughout. We adopt 10 because selection time grows linearly with the iteration count while the further gains do not scale proportionally. RD, by contrast, falls below random selection at small iteration counts and only clearly surpasses it once reaches 13, indicating that its signal requires more search before it becomes useful.
Figure 5(a) varies the initial filter ratio . The relationship is single-peaked, with ASR maximized at on defect detection and at on code repair, which are the values adopted in Section V-A. A ratio that is too small refreshes too few candidates per iteration and leaves the pool close to its random initialization, while one that is too large discards too many at once and destabilizes the selection. Code repair is the more sensitive of the two tasks, with large standard deviations at the extreme values, which is why a lower initial ratio is used there. Figure 5(b) varies the decay rate on defect detection, which is again single-peaked and maximized at . Setting , a constant filter ratio across iterations, yields a lower ASR (62.92%) than the decaying schedules, so the decay is beneficial in itself rather than a tuning convenience.
Figure 6 varies the number of proxy-training epochs per iteration. The best ASR is obtained at for both TNCS and RD, and training longer generally reduces ASR while increasing the time cost linearly. A likely explanation is that a longer-trained scoring model converges toward high
TABLE XIV
Control experiments for the neutralization operator. Output shift induced by masking on defect detection, for the three dead-code families that use [MASK] neutralization. masks the trigger span and masks a length-matched random span. Trigger vs. random reports on the poisoned model; Poisoned vs. clean reports the ratio of on the poisoned model to that on a clean model trained without poisoning.
| Trigger family | Poisoned model | Clean model | |
|---|---|---|---|
| Trigger vs. random | Poisoned vs. clean | ||
| Insert CS | 3.07 | 12.6× | 14.9× |
| Insert GGS | 4.40 | 20.7× | 19.0× |
| Insert AS | 4.28 | 51.8× | 24.7× |
confidence on the target, compressing the difference between its outputs on the triggered and neutralized inputs and thereby lowering the resolution of the selection signal. A single-epoch proxy therefore provides both the strongest signal and the lowest cost.

Fig. 4. Effect of the number of iterations. ASR (a) and selection time (b) versus on defect detection (constant unfolding, 0.3%). Shaded regions in (a) denote one standard deviation; the time cost in (b) grows linearly and is nearly identical for RD and TNCS.

Fig. 5. Effect of the filter-ratio schedule. ASR of TNCS versus the initial filter ratio on defect detection and code repair (a), and versus the decay rate on defect detection (b). All settings use constant unfolding at a poisoning ratio of for defect detection and for code repair. Shaded regions denote one standard deviation.
APPENDIX E
FORGETTING-EVENT DISTRIBUTIONS
Figure 7 shows the distribution of forgetting events over the poisoned candidate pool under the budget on defect detection, where the pool is largest and the statistics are most stable, compared with the distribution reported for CIFAR-10 in the original FUS study [11]. Samples with three or more forgetting events are absent in every trigger family, which is the basis for the analysis in Section VI.

Fig. 6. Effect of the per-iteration training epochs. ASR (a) and selection time (b) versus the number of proxy-training epochs on defect detection (constant unfolding, ). Shaded regions in (a) denote one standard deviation; the time cost in (b) grows linearly and is nearly identical for RD and TNCS.

Fig. 7. Forgetting-event distributions across trigger families. Fraction of poisoned candidates by forgetting-event count under the budget on defect detection, compared with the distribution reported for CIFAR-10 by Xia et al. [11], in which events with are reported as a combined group.