Judging Code Through Its Rewrites

Large language models are now used as automatic graders of code. They decide whether a student submission passes, whether a generated patch is correct, or which of two programs is better. These judges read everything in the file, including comments, variable names, and familiar-looking structure, and attackers have learned to exploit that. A comment saying "this is correct code" or an embedded instruction to award full marks can flip the verdict. A textbook-looking sorting function with one flipped comparison can make the judge "see" the textbook behavior instead of the real one. In each case the program the computer runs is unchanged, but the judge's verdict changes.

This proposal turns that weakness into a defense. Instead of judging the submitted text once, we judge a set of programs that a compiler would treat as identical to it. Each rewrite strips comments, renames identifiers, reorders independent statements, or disguises familiar functions. We take the verdict that holds across the whole set. When the judges of different rewrites disagree, we treat that as evidence of tampering and send the case to execution or to a human. The bet is that most known attacks on code judges depend on the surface text, and meaning-preserving rewrites that destroy that text also destroy the attack. An attack that survives every rewrite has to live in the program's actual logic, and judging that logic is the job the judge was meant to do.

Core Claim

Define a semantics-preserving transformation as a rewrite that leaves execution behavior unchanged. For a candidate program $x$, a judge $J$ that returns a pass probability, and a distribution $\mathcal{T}$ over such transformations, we propose the orbit verdict and orbit disagreement:

$$\hat{y}(x) = \mathrm{median}_{t \sim \mathcal{T}}\, J(t(x)), \qquad d(x) = \mathrm{IQR}_{t \sim \mathcal{T}}\, J(t(x)),$$

where IQR is the interquartile range across $K$ sampled rewrites. The claim has three parts.

First, for attacks that work through the natural channel (comments, names, style, and familiarity), $\hat{y}$ recovers most of the judge's clean accuracy.

Second, $d(x)$ separates attacked inputs from benign ones well enough to route a small fraction of submissions to execution.

Third, an adaptive attacker who knows $\mathcal{T}$ and optimizes against it is pushed toward edits to the program's real logic, which the judge can see.

What is new is not the use of transformations, which prior work uses to attack. It is using an attack-aware, randomized family of them, including a "defamiliarization" family aimed at memorized-pattern exploits, as both a verdict-aggregation and a tamper-detection mechanism for LLM judges. The proposal is also evaluated against an attacker who adapts to it.

What Exists and Where This Sits

Several papers motivate the problem by documenting that code judges fail through the natural channel.

  • The Compliance Paradox hides grading instructions in comments and identifiers. These are syntax-tree "trivia" that compilers ignore. Compliant models such as DeepSeek-V3 reach decoupling rates above 95%, often giving full marks to code that does not compile. The paper proposes no defense.
  • Don't Judge Code by Its Cover shows that authority comments, misleading task comments, random renaming, and dead code shift judge accuracy by up to 26.7 points on AtCoder problems. It also shows that prompting the judge to write tests first helps only marginally.
  • Trust Me, I Know This Function shows the subtlest version. Real bugs planted in familiar utility functions drop output-prediction accuracy from about 90% to 8.9–24.1%, and warning prompts do not help.

Our orbit is designed so that each of these three mechanisms has a rewrite family that targets it.

Two papers constrain the design.

  • Certifying the Judge finds that frontier judges fail its stability property even under plain variable renaming in Lean 4. Benign rewrites therefore already move scores, which means $d(x)$ has a noisy null distribution. We measure that null rather than assuming it away, and we use that paper's metamorphic properties as an offline audit. Our contribution differs in turning the audit into a per-input runtime decision on imperative code.
  • Evaluate-and-Purify uses an LLM to score naturalness and repair adversarial identifiers before a downstream code model sees them. That design trusts an LLM reader of the natural channel, which is exactly the component the Compliance Paradox shows can be hijacked. Our rewrites are rule-based and cannot be instructed.

Two papers supply methods.

  • CoTR-A provides four statement-exchange families: loop, expression, permutation, and condition.
  • Auto-SPT provides a catalog of 20 transformation families and a composition-by-beam-search procedure. We reuse its families as rewrites and its search as the adaptive attacker.

JudgeDeceiver and RobustJudge show that optimized injections reach above 90% and 80–100% attack success on text judges, and that perplexity filters miss most of them. Both treat code as plain text, which is why they leave open whether syntax-aware rewriting breaks such payloads.

Research Program

The rewrite engine. The engine is a deterministic, parser-based rewriter for Python, Java, and C++, with five families.

  1. Trivia removal: strip comments, docstrings, and string literals that are never read.
  2. Alpha-renaming to random neutral names.
  3. Statement exchanges from CoTR-A.
  4. Dead-code elimination by a simple reachability pass.
  5. Defamiliarization: rename functions away from recognizable names such as is_prime, inline or outline helpers, convert loop forms, and reorder commutative checks. The goal is that a memorized template no longer matches the surface.

Each rule is correct by construction, because at judging time there may be no tests. We validate every rule offline on BigCodeBench, whose tasks average 5.6 tests with 99% branch coverage, before it enters $\mathcal{T}$.

Sampling and routing. For each submission we sample $K$ rewrites, with $K \in \{1, 4, 8, 16\}$. Each rewrite composes one random rule from each family. The judge is queried once per rewrite, and we compute $\hat{y}$ and $d$. Inputs whose $d$ exceeds a threshold set on clean data are routed to execution when tests exist, and otherwise flagged.

The adaptive attacker. The attacker starts from a buggy program $x_b$ that should fail. It searches over edits $\delta$ to maximize the orbit verdict, in the style of expectation-over-transformation:

$$\max_{\delta \in \Delta} \; \mathbb{E}_{t \sim \mathcal{T}}\, J\big(t(x_b \oplus \delta)\big) - \lambda\, d(x_b \oplus \delta),$$

where $\Delta$ contains comment and identifier payloads, dead code, structural rewrites from the Auto-SPT families, and familiar-pattern disguises. $\lambda$ trades raising the score against avoiding the disagreement flag. The attacker must keep the program's tested behavior unchanged: it stays buggy.

We record which edit types the successful attacks end up using. If the claim is right, the surviving attacks concentrate on edits that change control flow or data flow, and those attacks are rarer and costlier.

Judges. The judges are GPT-4o, Claude 3.5 Sonnet, Llama-3.1-70B and 8B, and DeepSeek-Coder-V2-16B. The last one is included so we can wrap MCTS-Judge directly.

Baselines

The naive reference point is the unprotected judge reading the raw submission with a standard rubric prompt. Clean and attacked accuracy for this judge anchor every other comparison. As an absolute ceiling for correctness tasks we also report test execution, where tests exist.

The strongest existing correctness judge is MCTS-Judge. It runs tree search over sub-evaluations and simulates test execution line by line, and it reports raising DeepSeek-Coder-V2-16B correctness accuracy on APPS from 41.0% to 80.0%. It is the most serious competitor because it is the best reported way to spend more inference compute on code judging, and a reviewer will ask whether the orbit is just a cruder use of the same budget. We run MCTS-Judge with its published settings on the same APPS problems and attacked variants. We then run the orbit with the same base model at a matched token budget, and we also wrap MCTS-Judge inside the orbit. Beating it means equal clean accuracy, within a few points of 80.0%, together with markedly higher accuracy under attack at matched tokens. No reported result was found on Lacuna for MCTS-Judge under any adversarial condition, so its attacked accuracy is something we measure.

The strongest existing defense on the input side is EP-Shield, using its released distilled Qwen2.5-coder-7B naturalness judge and purifier in front of the same downstream judge. It reports defense success near 99% on BigCloneBench clone detection against identifier substitution. We run it unchanged on the same attacked inputs. Beating it means higher robust accuracy on comment-injection, structural, and familiar-pattern attacks, and no worse robust accuracy on identifier attacks.

The prompt-only baseline asks the judge to ignore instructions in comments and to write tests before grading, following the mitigation in Don't Judge Code by Its Cover. Perplexity filtering serves as the detection baseline for the disagreement score.

Three ablations isolate the proposal's ingredients:

  • Deterministic canonicalization: one fixed rewrite that strips trivia and normalizes names, with no randomization and no structural or defamiliarization families.
  • Same-input resampling: $K$ temperature samples of the judge on the unchanged text. This separates rewriting from plain self-consistency.
  • Family drop-out: remove one rewrite family at a time.

All methods share the same problems, attacked inputs, judge models, and tuning budget. Thresholds and $K$ are chosen on a held-out clean split only.

Why not just…?

Why not just strip comments and normalize names once? This is the real threat, and we expect it to recover most of the loss from trivia-injection and authority-comment attacks on its own. The orbit earns its cost only if two things hold. Single canonicalization must fail on familiar-pattern and structural attacks; CoTR-A degraded translation by 14–18% without touching names or comments, which suggests structural edits evade it. And the disagreement signal must add detection that a single verdict cannot give. The canonicalization ablation tests exactly this. If it matches the orbit on every attack class, we will report that, and the contribution narrows to the adaptive-attack evaluation and the finding that one cheap pass suffices.

Why not just execute the code? Where full tests exist, execution should be used. It is our ceiling and our routing target, not a competitor. The orbit exists for the settings where tests are missing or thin, and for non-functional criteria such as readability that compilers cannot grade (LLM-as-a-Judge for Software Engineering). We also report what fraction of inputs the disagreement flag sends to execution, because a defense that routes everything is just execution.

Why not just sample the judge several times, or use MCTS-Judge's extra search? Resampling the same text keeps the attack payload in every sample. We therefore expect high agreement on a wrong verdict. The resampling ablation and the matched-token MCTS-Judge comparison measure whether rewriting, rather than repetition, drives any gain. If MCTS-Judge's simulated execution already defeats familiar-pattern bugs, that comparison will show it. Whether it does is currently unknown.

Why not just put an LLM purifier in front, as EP-Shield does? The purifier is itself an instruction-following model reading the natural channel. The Compliance Paradox's results suggest an injected comment can tell it the code is natural. We test this directly by adding a payload addressed to the purifier and comparing its robust accuracy with the rule-based orbit.

Decisive Experiments

Attack-class experiment. This runs on four sources. The first is the Jailbreak-Evaluator benchmark of 25,000 trivia-injection samples from the Compliance Paradox. The second is the six AtCoder bias conditions. The third is familiar-pattern bugs regenerated with the procedure of Trust Me, I Know This Function on BigCodeBench and APPS functions, where tests give ground truth. The fourth is CoTR-A and Auto-SPT structural rewrites of buggy APPS solutions. For each attack class and each method we report:

  • clean accuracy;
  • attacked accuracy;
  • false-certification rate, meaning buggy code that is passed;
  • decoupling probability as defined by the Compliance Paradox.

The key prediction is the familiar-pattern result. If defamiliarization raises output-prediction and verdict accuracy well above the 8.9–24.1% range while canonicalization alone does not, abstraction bias is shown to be a surface phenomenon a rewriter can break. If it fails, familiar-pattern attacks belong in the formal channel, and only execution addresses them.

Benign-cost experiment. On SeqCoBench we measure whether rewriting blurs the distinction between true semantic clones and lookalikes with subtle bugs. CodeLlama-13B reaches 70.85 average precision on that benchmark per What can Large Language Models Capture about Code Functional Equivalence?. The orbit must not lower this. On clean APPS and BigCodeBench, we compute the null distribution of $d(x)$ to quantify the renaming instability that Certifying the Judge reports.

Detection experiment. We report the area under the ROC curve (AUROC) of $d(x)$ for separating attacked from clean inputs, compared with perplexity filtering.

Adaptive-attack experiment. We run the expectation-over-transformation search with growing query budgets. We report orbit-verdict attack success as a function of budget, and the share of successful attacks whose edits change the program's control-flow or data-flow graph. The central claim holds if success under the orbit is far below success against the raw judge at equal budget, and if the survivors are dominated by logic-level edits. It fails if cheap natural-channel payloads still survive the orbit, for example adversarial identifiers that remain persuasive after random renaming because the attacker controls the semantics of literal strings.