Purification Without Curl: Potential-Anchored Repair of Adversarial Code

Code models can be fooled by small edits that do not change what a program does, such as renaming a variable or adding a line that never runs. A popular defense is purification: before a program reaches the downstream model, a separate model rewrites it back into "natural" code, for example by restoring sensible variable names. This note argues that today's purifiers have the same hidden flaw that physicists found in neural force fields. A purifier that directly outputs "the next edit" defines a direction of motion through the space of equivalent programs, but no single score that this motion is reducing. Applied repeatedly, such a field can run in circles or settle somewhere arbitrary, and a clever attacker can exploit that. The remedy borrowed from atomistic simulation is to anchor the fast edit-proposer to a single scalar naturalness score that every accepted step must lower. This guarantees the process stops, makes the stopping point stable under repeated purification, and costs only an occasional expensive check.

In machine-learned interatomic potentials, models that predict atomic forces directly are about twice as fast as models that compute forces as the gradient of a learned energy. However, direct models do not conserve energy. In simulation they heat up explosively, and in geometry relaxation they can circle forever without reaching a minimum (The dark side of the forces). That paper also gave the field two tools. The first is a diagnostic, Jacobian asymmetry, which measures how far a predicted force field is from being the gradient of any energy. The second is a fix, multiple time stepping, in which seven cheap direct steps alternate with one exact energy-gradient correction and 80–90% of the speedup is recovered. We transfer both tools to adversarial code defense. Atomistic machine learning supplies the method. Purification of code under renaming and dead-code attacks is the application.

Core Claim

An iterative code purifier is a vector field on a discrete graph. The nodes are semantically equivalent variants of a program, and each edge is one semantics-preserving edit. A purifier that directly proposes edits, such as the distilled rewriter in Evaluate-and-Purify (EP-Shield), is the analog of a direct force head. Nothing forces its proposals, or the judge's pairwise preferences, to be consistent with one underlying naturalness score.

We make three claims, all testable. First, such purifiers and judges contain a measurable non-conservative component, which we call discrete curl. Second, discrete curl predicts two observable failures: purification that is not idempotent (purifying twice changes the output again) or that cycles, and higher success for adaptive attacks that target the whole purify-then-classify pipeline. Third, a purifier anchored to a scalar potential removes cycles by construction. With the proposer doing most of the work and the potential consulted only periodically, it should keep most of the speed of direct purification.

The guarantee is narrow and we say so up front. Anchoring guarantees termination and stable fixed points; it does not guarantee robustness. Whether it also improves adaptive robustness is the empirical bet.

Research Program

Measuring discrete curl. For a program $x$, we build its local edit graph: all single renamings drawn from a candidate pool, plus single dead-code insertions or deletions. A judge or purifier assigns each edge $(x,y)$ a flow $f(x,y)$. For the judge, the flow is its preference margin for $y$ over $x$. For a direct purifier, it is the log-probability of proposing $y$ minus that of proposing $x$. We fit the best potential $\phi$ over the nodes by least squares and report the fraction of flow it cannot explain:

$$\rho = \frac{\sum_{(x,y)} \big(f(x,y) - (\phi(y) - \phi(x))\big)^2}{\sum_{(x,y)} f(x,y)^2}.$$

Here $\rho = 0$ means the preferences are exactly the gradient of a naturalness score. Larger $\rho$ means more circulation. This is the discrete counterpart of the Jacobian-asymmetry metric, and it is computed the same way as rank aggregation from pairwise comparisons.

Alongside $\rho$, we measure the purifier's behavior when it is iterated. We record the rate of non-idempotence, the rate of cycles within $k$ applications, and how far the final names drift from the original identifiers.

The anchored purifier. The potential $\phi$ is the token-averaged negative log-likelihood of the whole program under a frozen code language model. Because it is a single scalar per program, descent on it cannot cycle. A small direct proposer suggests a batch of renamings or deletions in one forward pass; these are the fast steps. Every $k$ proposals, an anchor step scores the accumulated program with $\phi$. The batch is accepted only if $\phi$ decreases, and otherwise the method falls back to the best individually verified edit.

Setting $k=1$ gives pure conservative descent, which is the slow, exact reference. Setting $k=\infty$ gives pure direct purification. Sweeping $k$ traces the same speed–stability curve that multiple time stepping traces for force fields. We also test the second atomistic lesson, that direct pre-training followed by conservative fine-tuning is cheaper (The dark side of the forces). To do so, we fine-tune the proposer on trajectories accepted by $\phi$ and check whether the acceptance rate rises, which would make larger $k$ safe.

Adaptive attacks. Most reported purification results use attacks that do not know the purifier exists. We attack the full pipeline. The attacker uses black-box search over renamings and dead code in the style of CodeAttack, scoring each candidate by the downstream loss after purification. Against the anchored purifier, the attacker's goal becomes finding a starting program whose $\phi$-descent basin ends at a misleading local minimum. Unlike the reachable set of a curl-laden purifier, those minima can be enumerated and audited.

Relation to Prior Work

Several papers motivate this work by showing that the vulnerability is real and large. Both CodeAttack and the gradient-based renaming attack DAMP in Adversarial Examples for Models of Code show that pre-trained code models lean heavily on identifier names. Those papers attack models; we instead study the dynamics of the defense.

Three defenses frame the comparison. EP-Shield (Evaluate-and-Purify) scores naturalness on a coarse 1–5 scale and restores names with a distilled 7B rewriter. It never asks whether repeated rewriting converges, and its scores are not used to accept or reject individual steps. Adversarial Robustness for Code strips irrelevant graph parts with integer programming and abstains when unsure. It also reports that adversarial training alone helps by only 0–7%, which constrains our design away from pure augmentation. VISION fixes spurious features with counterfactual training data, which is complementary to purification rather than a competitor at inference time.

The physics-inspired defenses are the closest intellectual neighbors, and they differ in where they put the conservative structure. HANG makes a graph network's internal feature dynamics Hamiltonian. That bears on continuous feature perturbations, but renaming changes the input tokens themselves, so we do not adopt it. Stochastic Security purifies images by Langevin descent on a scalar energy, which is the continuous ancestor of our anchored purifier. It never measures or contrasts a non-conservative drift. Our contribution is to do both, on discrete code.

EnergyFlow supports the modeling choice of recovering a scalar potential from a learned vector field, though in continuous control.

On the force-field side, GemNet-OC argues that direct heads train more stably at scale, and Spherical Channels documents the cost of gradient-derived outputs. Together they explain why one would want a direct proposer at all.

Baselines

The naive reference point is no defense: the downstream model sees attacked code directly. We pair it with a single-pass, non-iterated EP-Shield-style purifier to show the cost of doing nothing beyond one rewrite.

The strongest existing method is EP-Shield. It reports defense success rates of about 99% on BigCloneBench clone detection, about 95% on OWASP vulnerability detection, and about 90% on CodeSearchNet summarization, staying above 85% on unseen attack patterns (Evaluate-and-Purify). We run it with the authors' distilled Qwen2.5-coder-7B purifier if it is available. If not, we reimplement it from the paper with the same base model and a matched distillation budget, and we report our reproduced non-adaptive numbers next to the published ones before running any adaptive attack.

To match budgets, our proposer and potential use models no larger than 7B in total. Downstream models are identical across defenses. The attacker's query budget against every pipeline is fixed and equal. Beating EP-Shield means two things together. Non-adaptive defense success must fall within two points of its reproduced numbers. Under the adaptive attack, success must be measurably higher, at equal or lower wall-clock latency per program.

The cheap baseline is outlier detection with masking from Adversarial Examples for Models of Code. It replaces contextually anomalous identifiers with an unknown-name token at roughly a 2% clean-accuracy cost. We add full alpha-renaming, which renames every identifier to a canonical placeholder. That is the trivially conservative fixed point.

Integer-programming refinement with abstention (Adversarial Robustness for Code) serves as a reference only on the type-inference task, where it reports 67.0% robustness against 52.1% for a plain graph network.

The ablation that isolates the key ingredient keeps the same proposer and the same potential $\phi$. The only change is that $\phi$ is used to rerank final outputs rather than as a per-step monotone acceptance test. If this reranked variant matches the anchored one on stability and adaptive robustness, then the conservative structure itself is not doing the work.

Why not just…?

Why not just apply the purifier once and never iterate? A single pass avoids visible cycles, but non-idempotence is still an attack surface. If $P(P(x)) \neq P(x)$, then the purifier's output is itself something the purifier would still change. That suggests an attacker can pick inputs whose single-pass output lands in a bad region. We measure exactly this. If single-pass EP-Shield shows low non-idempotence and no adaptive-attack gap relative to the anchored version, the concern is empty and we will report that.

Why not just canonicalize all identifiers, or mask outliers? These are the strongest threats on renaming attacks, because canonicalization is perfectly stable and erases the renaming attack surface by design. Their cost is the natural channel. Summarization and method naming rely on meaningful names, and the CodeAttack results, which cut summarization quality by nearly half when names are perturbed (CodeAttack), show how much signal names carry. Neither approach addresses dead-code or structural edits (Auto-SPT, syntactic robustness for translation). We report clean accuracy and robustness for both on every task. On clone detection, where names matter less, canonicalization may simply win, and we would say so.

Why not just run pure likelihood descent with no fast proposer? This is the $k=1$ endpoint, and it shares all of our guarantees. The proposer only earns its place if it saves time at matched robustness. Scoring every candidate edit with a full-program language-model pass scales with identifiers times candidates, so we expect a large latency gap. The $k$-sweep will show directly whether larger $k$ preserves the $k=1$ robustness. If it does not, the contribution reduces to the diagnostic and the conservative defense, which we would still report.

Proposed Experiments and Decisive Checks

We run the defenses on BigCloneBench, OWASP, and CodeSearchNet (Python, Java, PHP), following EP-Shield's setup. We add Java-large method naming and C# variable misuse from the DAMP paper, and the JavaScript/TypeScript type-inference benchmark for comparison with integer-programming refinement. Downstream models are CodeBERT, GraphCodeBERT, and CodeT5. Attacks are DAMP, CodeAttack, dead-code insertion, and our adaptive pipeline attack.

The metrics are: discrete curl $\rho$ for the judge and the proposer; non-idempotence and cycle rates over up to ten iterations; clean accuracy, or BLEU for summarization; defense success under non-adaptive and adaptive attacks; and latency per program.

The first decisive check is correlation. Across purifiers and checkpoints, higher $\rho$ should predict both non-idempotence and adaptive-attack success. If $\rho$ predicts neither, the physics analogy is decorative and the proposal fails at its foundation.

The second check is the gap between adaptive and non-adaptive attacks. EP-Shield's success should drop under the adaptive attack by more than the anchored purifier's does.

The third check is the $k$-sweep. We need an intermediate $k$ that keeps adaptive robustness close to $k=1$ while recovering most of the latency advantage of $k=\infty$, analogous to the 80–90% speedup recovery reported for multiple time stepping in atomistic simulation.

If the anchored purifier is stable but no more robust than reranking, the honest conclusion is narrower. Discrete curl would then remain a useful audit for purifiers, while monotone anchoring buys termination and nothing more.