Masked Gradients in Code Defenses: A Discrete Slope Test and an Evolutionary Stress Attack

Models that read source code — CodeBERT, GraphCodeBERT, Devign — can be fooled by edits that change nothing about what a program does: renaming variables, inserting unreachable statements, or restructuring loops. The most visible defense against this is EP-Shield, a pipeline that passes code through a language-model "judge" that rewrites unnatural-looking identifiers back to human-style names and reports defending 90–99% of adversarial examples. In computer vision, a hard lesson from the last decade is that defenses built on non-differentiable generative components often create an illusion of security: they make gradient-based attacks fail not because the model got robust, but because the gradients became useless — a failure mode called gradient masking, diagnosed systematically by Athalye et al. Nobody has ever checked whether code defenses do this, and the check is genuinely harder in code than in vision, because code inputs are discrete: the standard diagnostic assumes you can take a small continuous step toward worse predictions, but in code any such step must be snapped back to real, compilable tokens, and that snapping by itself destroys gradient information.

This proposal builds two things that together answer the question. First, a discrete adaptation of the Slope gradient-masking metric — measured not in pixel space but across the round-trip from token embeddings back to valid code — which lets us separate the two possible reasons gradients fail in code models: the inherent discreteness of the code representation itself, and obfuscation introduced by the defense. Second, a gradient-free evolutionary attack that composes lexical and structure-level semantics-preserving edits, verified by compilation and unit tests, with the defender's own naturalness judge inside its fitness function — the adaptive stress test that fixed-attack evaluations like EP-Shield's never faced.

Core Claim

The reported ~95–99% defense success of LLM-purification defenses for code models conflates three things: genuine robustness, narrowness of the evaluated attack class (identifier renaming only), and gradient masking induced by the non-differentiable purifier in the loop. We claim that a token-space Slope diagnostic plus a constrained, query-guided evolutionary attack will decompose that number, and that the structural attack channel — which no current code defense addresses — will account for a substantial share of the gap. Either outcome is informative: if the defense holds under adaptive attack, that is the first evidence of real (not artifact) robustness in this domain; if it collapses, we will know why, and by which mechanism.

What Prior Work Does and Does Not Cover

Three lines of work motivate the proposal. CodeAttack shows that pre-trained code models collapse under semantics-preserving identifier substitution found by score-based black-box search — reducing BLEU by nearly 50% and achieving 90–99% attack success on code translation and repair — but it deliberately stays in the "natural channel" of names and style, never touching program structure. Auto-SPT: Automating Semantic Preserving Transformations for Code goes the other way: it composes twenty LLM-generated structural transformations via beam search and unit-test verification, raising worst-case embedding distance on fine-tuned CodeBERT from 0.243 to 0.947 on CodeContests — but its search is heuristic, aimed at clone-detection embeddings, not at flipping a security classifier's decision. Evaluate-and-Purify is the defense under test: it reports defense success of roughly 99% on BigCloneBench, 95% on the OWASP vulnerability benchmark, and 90% on CodeSearchNet, and it explicitly reports beating adversarial fine-tuning by up to 83.36% — but only against the fixed, identifier-only attacks it was designed around, and never against an adaptive adversary.

Three further lines supply the method and constrain the design. Obfuscated Gradients Give a False Sense of Security gives the taxonomy (shattered, stochastic, vanishing gradients), the bypass tools (Backward Pass Differentiable Approximation, Expectation Over Transformation, black-box search), and the red flags — most importantly, that a gradient-free attack outperforming a white-box gradient attack is itself evidence of masking. Slope: A First-order Approach for Measuring Gradient Obfuscation gives the quantitative diagnostic $S(x)$, which flags masking when a gradient step fails to raise the loss as first-order math predicts — but it was formulated and validated only for continuous image perturbations on MNIST and CIFAR-10. Finally, the malware work of Adversarial EXEmples and GAMMA shows the template for our attack: GAMMA's genetic algorithm evades tree-based detectors on the EMBER dataset by injecting benign PE sections directly in problem space, cutting detection from 95% to below 20% in fewer than 500 queries — but only for binary file layouts, never for source code that must parse and compile. Two negative results shape the design: Doan et al. establish that the forward map from raw code to features is lossy and non-differentiable, so no smooth surrogate of the full pipeline exists; and Square Attack shows derivative-free search beats gradient estimation precisely on the jagged, discontinuous landscapes such pipelines create.

No work in the file combines all four ingredients: nobody has measured gradient masking in a code defense, nobody has adapted Slope to discrete token spaces, and nobody has run fitness-guided population search over compiled-and-tested structural code transformations against a defended classifier. The closest single work is EP-Shield itself, which touches code defenses and (implicitly) the masking question but tests no adaptive attack and no masking diagnostic; our proposal is exactly the evaluation it is missing.

Research Program

The first component is the diagnostic. We define a token-space Slope. Let $x$ be a code snippet, $\mathcal{L}$ the target model's loss, $g$ the gradient of $\mathcal{L}$ with respect to the token embeddings of $x$, and $\Pi$ the inverse map that rounds a perturbed embedding sequence back to the nearest valid token sequence and re-parses it. Then

$$S_{\text{tok}}(x) = \frac{\mathcal{L}(\Pi(x + \eta g)) - \mathcal{L}(x)}{\eta \|g\|_2},$$

with step size $\eta$ swept over a small grid. We also measure $S_{\text{emb}}$, the same quantity without the round-trip $\Pi$, computed purely in embedding space. The difference between the two is the attribution mechanism the vision literature lacks: if $S_{\text{emb}}$ is healthy but $S_{\text{tok}} \le 0$, the gradients are destroyed by the discreteness of code itself — an inverse-mapping failure, exactly the realization gap that Doan et al. describe and that Adversarial EXEmples acknowledges when feature-space perturbations fail to become valid files. If both collapse only when the purifier sits in front of the classifier, the defense itself is the obfuscator, in the pattern Obfuscated Gradients established for vision purification defenses like DiffPure. We are honest about the inherited limitation: the Slope authors themselves note that first-order metrics miss higher-order obfuscation, so the diagnostic is necessary but not sufficient — the attack below is the ground truth that backstops it.

The second component is the attack, a constrained genetic algorithm in the tradition of GAMMA but over a source-code move set. Each individual is a program; the genome is a sequence of edits drawn from two channels: natural-channel moves (identifier renaming with candidates proposed by a masked language model under CodeAttack's syntax and operator constraints) and formal-channel moves (dead-code insertion, statement reordering, and Auto-SPT-style structural transformations such as nested function encapsulation and modular arithmetic distribution). Every candidate is verified by compilation and, where test suites exist, by execution; invalid offspring are discarded, which is how we enforce the structural-integrity and semantic-preservation requirements that make the code inverse-mapping problem hard. The fitness function is the defended pipeline's detection score, plus a penalty proportional to the defender's own naturalness score — we query EP-Shield's judge model as an oracle inside the loop, so the search is explicitly rewarded for producing code the purifier will not flag or will purify without changing the decision. This is the adaptive use of the defense's internals that fixed-attack evaluations omit.

Proposed Experiments

Targets are CodeBERT and GraphCodeBERT fine-tuned on the Devign defect-detection task (CodeBERT reaches 62.08% accuracy there, per CodeXGLUE) and on BigCloneBench clone detection (96.5 F1 for CodeBERT, same paper), plus the graph-based Devign model itself (Devign), which consumes AST, control-flow, and data-flow graphs rather than token sequences and therefore probes the tension between structural and lexical channels. The defended configuration places EP-Shield in front of each target. Structural transformations are validated with unit tests on CodeContests following the Auto-SPT protocol; for Devign's C functions we compile with a standard toolchain and run a differential test suite generated against the original function.

Metrics are: the distribution of $S_{\text{tok}}$ and $S_{\text{emb}}$ across defended and undefended configurations; attack success rate (flipping a vulnerable-function prediction while preserving behavior and passing the naturalness judge); queries-to-evasion, capped at 1,000 score queries per sample to stay in the regime GAMMA demonstrated feasible (it evaded in fewer than 500); and the defense success rate of EP-Shield recomputed under each attack, directly comparable to its published ~95% on OWASP. We also run a white-box embedding-space PGD attack with token projection, so the classic red flag — black-box success exceeding white-box success — can be checked directly, and a BPDA-style variant that treats the purifier as near-identity during backpropagation, which is the strongest white-box counter-attack a reviewer would demand.

Baselines

The do-nothing reference is the clean performance of each target: 62.08% accuracy for CodeBERT on Devign defect detection and 96.5 F1 on BigCloneBench, both reported in CodeXGLUE. This anchors how much each attack actually degrades a detector before any defense is considered. The strongest existing attack on the specific question "can EP-Shield be broken" is CodeAttack (CodeAttack), a score-based black-box identifier-substitution attack that reduced BLEU by nearly 50% and reached 90–99% attack success on translation and repair tasks; we rerun it against the EP-Shield-guarded detectors at the same 1,000-query budget, on the same functions, with the same verification, so the comparison isolates the attacker rather than the setup. Because EP-Shield was built and tuned against exactly this attack family and reports ~95% defense success on OWASP, this baseline is expected to lose, and the margin of its loss is the backdrop against which our attack's extra margin must be judged. The strongest structural competitor is Auto-SPT's beam search (Auto-SPT), which achieved a worst-case embedding distance of 0.947 on fine-tuned CodeBERT on CodeContests; we run its beam search at a matched total query and compute budget against the same defended classifiers, noting that its objective is embedding distance rather than decision flips, so we also report its label-flip rate under our evaluation. Finally, two ablations isolate the proposal's key ingredients: the same evolutionary engine restricted to identifier-renaming moves only (which isolates the structural channel as the active ingredient), and a SimBA-style random-mutation search (Simple Black-box Adversarial Attacks) over the same move set (which isolates fitness-guided population search from blind luck). All attackers get identical targets, query caps, verification pipelines, and a tuning budget (population size, beam width, step schedules) optimized on a held-out split with equal total queries spent. Beating the baselines means a materially higher label-flip rate under the purifier at equal or fewer queries, with the renames-only ablation explaining how much of that margin comes from structural moves.

Why not just…?

Why not just run BPDA with an identity surrogate for the purifier? This is the most serious alternative, and we treat it as a first-class experiment rather than an argument. If the purifier's output is close to its input for reasonably natural code, gradients flowing through an identity approximation may be perfectly informative, and a white-box attack might break EP-Shield without any evolutionary machinery — in which case the story becomes "the defense is weak for a simpler reason," not "the defense masks gradients." Two pieces of evidence temper but do not settle this: Doan et al. show the surrounding pipeline (tokenization, parsing, feature extraction) is lossy and non-differentiable with no smooth surrogate, and Square Attack shows derivative-free search outperforms gradient estimation on exactly such jagged surfaces. Our design reports both attacks side by side; if BPDA matches the evolutionary attack, we will say so and the diagnostic still tells us which component was leaking gradients.

Why not just use random token search instead of a genetic algorithm? The malware evidence is pointed: GAMMA's authors compared structured genetic injection against random byte injection and found random noise far less effective at far higher query counts, and Adversarial EXEmples found random mutations routinely corrupted files, forcing expensive sandboxing. In code, CodeAttack's authors found naive NLP attackers like TextFooler produced syntactically broken programs. Still, the objection is honest enough that random search is one of our ablations: if SimBA-style random mutation over the compiled-and-verified move set matches the fitness-guided search at the same query budget, the evolutionary component is unnecessary and we will report the simpler attack as sufficient.

Why not just adversarially fine-tune the detectors and skip the whole study? The defense literature itself argues against this as a complete answer: Evaluate-and-Purify measured adversarial fine-tuning and found EP-Shield beat it by up to 83.36% with better generalization to unseen attacks; DiffPure reports adversarial training failing under unseen threat distributions by margins up to +36% robust accuracy for purification; and Auto-SPT showed that augmentation against a limited transformation set is upper-bounded by transformation diversity, with composed transformations still reaching 0.947 worst-case distance. More fundamentally, fine-tuning answers "how do we defend," while this proposal answers "is the number we are defending with real" — a question no amount of fine-tuning resolves, and one that determines whether the field's reported defense successes mean anything.

Decisive Checks

Three outcomes decide the proposal. First, the attribution: on undefended CodeBERT, if $S_{\text{emb}}$ is healthy while $S_{\text{tok}}$ is near zero, we have quantified — for the first time in code — how much gradient failure is inherent to the discrete representation rather than to any defense, a result that redraws which attacks are even worth attempting in this domain. Second, the red flag: if under EP-Shield the gradient-free attack succeeds where projected white-box PGD fails, that is the canonical masking signature from Obfuscated Gradients, now demonstrated in a new modality, and the token-space Slope values should predict it in advance. Third, the decomposition: whatever EP-Shield's defense success drops to under the full evolutionary attack versus its renames-only ablation, the difference is the structural channel's share — the portion of the threat that the current generation of code defenses, naturalness filters included, simply does not see. Each check is falsifiable in the ordinary way: if Slope values do not predict the attack ordering, or if EP-Shield holds at near its reported rate under the adaptive attack, the proposal's claim is wrong in the direction that most flatters the defense, and we will report it as the first genuine-robustness evidence in this setting.