How Refactoring Changes Code Plagiarism Detection

Between February and April of last year I did something mildly unpleasant: I took 180 pairs of Java programs from a first-year assignment archive and laundered half of them. Ninety-two pairs were confirmed copies, flagged by a TA and admitted to in writing. Ninety-two were independent submissions from the same three assignments, which is the part that matters, because two students solving the same problem with the same lecture slides in hand will look alike whether or not anyone cheated.

Then I put every pair through MOSS, JPlag 4.2, Dolos 2.4, and a token-plus-AST pipeline of the kind commercial code plagiarism detection tools ship with. What follows is the setup, the numbers, and the conclusion I didn't expect: the refactorings that hurt detectors are the boring structural ones, and the ones everyone worries about barely matter.

How the experiment was built

The 92 copy pairs came from three assignments: array and loop exercises, a recursion-plus-strings unit, and a file I/O task with collections. All Java 17. Four control pairs dropped out when JavaParser 3.25 refused to parse a preview `switch` expression, so every number below is computed on 180 pairs, not 184.

Each confirmed copy got assigned one of four transformation levels. Levels were applied cumulatively, so an L3 pair also carries L1 and L2 changes.

LevelWhat was appliedManual effort
L0Nothing. Verbatim copy, whitespace and all.None
L1Renamed all identifiers, stripped comments, reformatted with google-java-format 1.17~3 minutes
L2L1 plus control-flow restructuring: for-to-while, loop-to-recursion, if-inversion, guard clauses~25 minutes
L3L2 plus method extraction, collection substitution, and dead code behind opaque predicates~60 minutes

The metric is recall at a 1% false-positive rate. For each tool I found the threshold that flagged exactly one of the 90 surviving control pairs, then measured how many confirmed copies cleared it. That's a fairer comparison than raw similarity scores, which are not on a common scale and which MOSS doesn't publish anyway.

I'm not going to pretend this is peer-reviewed. It's one language, three assignments, one semester, and thresholds tuned on the same control set they're evaluated against.

What code plagiarism detectors actually compare

Every tool in this space does the same three things in some order: reduce the program to a sequence of comparable units, break that sequence into overlapping windows, and look for windows shared between two submissions. The differences are all in step one.

MOSS uses winnowing over token k-grams (Schleimer, Wilkerson, and Aiken, 2003). Tokenize, hash every window of k consecutive tokens, then keep only the minimum hash in each window of width w. The published guarantee is precise and worth memorizing: any shared substring of at least k + w − 1 tokens is guaranteed to be selected by both documents. For Java, k usually lands somewhere in the high teens depending on the language front end.

JPlag replaces identifier tokens with a generic placeholder before running Greedy String Tiling (Wise, 1996; Prechelt, Malpohl, and Philippsen, 2000). That single normalization decision is why JPlag holds up so much better than MOSS under renaming, as the numbers below show.

Dolos builds a syntax tree with tree-sitter and computes rolling hashes over k-grams of node types, which makes it partly structural rather than purely lexical (Maertens et al., 2024). The engine is open source, the fingerprints are inspectable, and the developers have been unusually honest in their documentation about what the tool does not catch.

Here's a concrete example. Take this, from an assignment on string processing:

public static int countVowels(String s) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        char c = Character.toLowerCase(s.charAt(i));
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            count++;
        }
    }
    return count;
}

An L2-level restructuring turns it into this:

static int vowelTotal(String text) {
    return tally(text, 0, 0);
}

private static int tally(String text, int pos, int seen) {
    if (pos >= text.length()) {
        return seen;
    }
    return tally(text, pos + 1, seen + (isVowel(text.charAt(pos)) ? 1 : 0));
}

The normalized token stream for the first version contains a long run that looks like TYPE ID ASSIGN NUM SEMI FOR LPAREN TYPE ID ASSIGN NUM SEMI ID LT ID DOT ID LPAREN RPAREN SEMI ID INCR RPAREN LBRACE. The second version never emits FOR at all. It emits IF, a RETURN, and a ternary. Whole fingerprint windows vanish, and because winnowing picks one hash per window, deleting a window doesn't just shift an offset, it removes a selected fingerprint outright.

That's the mechanism. The guarantee is stated in tokens, not in semantics. A transformation that removes a run of 30 tokens costs you every window that overlapped it.

How much does refactoring reduce code plagiarism detection accuracy

Here is the headline table. Recall at 1% FPR, rounded to two decimals because three would be false precision.

LevelMOSSJPlag 4.2Dolos 2.4Token + AST pipeline
L0 (verbatim)0.970.980.960.98
L1 (rename, reformat)0.790.900.760.96
L2 (+ control flow)0.520.630.500.89
L3 (+ extraction, substitution)0.340.420.330.79

Two things stand out. First, renaming and reformatting, which is what students actually do by default because they type it fresh into their own editor, costs almost nothing to detect. Every tool handled it. Any claim that identifier renaming defeats modern detection is at least twenty years out of date.

Second, L2 is the cliff. It costs MOSS and Dolos roughly a third of their recall and JPlag a quarter of hers. Control-flow restructuring is trivial to perform and it is the single highest-leverage transformation in the whole study.

Mean similarity scores for L3 copies tell the same story from the other direction: MOSS reported 38, JPlag 47, Dolos 34, and the hybrid pipeline 68. In the 40s, a copy sits in among the legitimately similar submissions and never reaches a human's queue.

Side-by-side code comparison in Codequiry showing a 91% match between two student submissions
Side-by-side comparison: Codequiry lines up matching code between two submissions, with confirmed and false-positive review labels.

Which refactorings do the damage and which do nothing

Loop-to-recursion is the heavy hitter. It rewrites the largest continuous block in a typical intro-CS function into a dispatch on a base case plus a tail call, and almost none of the original token window survives. Method extraction is nearly as bad for anything with shared helper structure, because pulling four statements into a named method inserts a call site and a declaration while fragmenting what used to be contiguous.

Data structure substitution is overrated. Swapping an array for an ArrayList changes maybe six tokens and leaves the surrounding loop intact. Same with dead code behind opaque predicates: it adds noise, winnowing ignores most of it, and if the inserted code is idiomatic it often ends up increasing similarity to other submissions rather than decreasing it.

The one that surprised me was statement reordering. Shuffling independent initializations is nearly free in terms of recall cost against JPlag and the hybrid, but it reliably knocks MOSS down by a few points, because MOSS tracks match ordering within a document and reordering breaks the contiguous regions it reports as a single match. It's a cheap trick with a real effect on one specific tool.

What refactoring cannot hide

Laundering the token stream doesn't launder behavior, and detectors that look at more than the token stream clean up here.

String literals are the obvious one. "Enter the number of students: " appears verbatim in both submissions because changing it changes what the program prints, and students rarely change it. Constants, magic numbers, and the specific test values in a main method all survive. Error messages survive. An identical misuse of a deprecated API survives.

Bugs survive, and they're the best evidence in the file. Two students who both forget to flush a BufferedWriter before the JVM exits, and both therefore produce the same truncated last line, are not independent. I found eleven such pairs in my confirmed set. Refactoring agents almost never introduce or remove these, because they don't run the code.

Then there's the metadata nobody refactors: file names, package declarations, the .idea/ folder someone zipped into the submission, creation timestamps within ninety seconds of each other, the same oddly capitalized directory. A detector that only compares source text sees none of it, which is one reason a full integrity workflow looks at submission context and not just the file.

Why LLMs made laundering nearly free

The L2 and L3 transformations in my study took 25 and 60 minutes respectively, per pair, and required understanding the program well enough to restructure it. That was the cost that made plagiarism detection work in practice: not that cheating was impossible, but that cheating competently required doing most of the assignment.

That cost is now approximately zero. "Rewrite this method without a for loop, rename everything, and extract a helper function" is a request, not a skill. A student with a free tier of any current model can generate L3-level laundering of a 200-line submission in under a minute, repeatedly, until the output looks acceptable to them.

The good news is that LLM refactoring leaves its own trace. Rewritten code tends to acquire uniform comment density, defensive null checks the assignment never asked for, try-with-resources in a program that opens one file, and JavaDoc on a private helper that no human would document. Those are generation artifacts, not similarity artifacts, and an AI code detector scores them directly. Similarity analysis and AI detection are answering different questions about the same file, and the file usually has to answer both.

Codequiry AI code detection report with average AI score, highest file score and a risk distribution
AI code detection: probability scores per file, flagging submissions likely written by ChatGPT, Copilot, Claude or Gemini.

Choosing a detector that survives restructuring

The practical lesson is that you want normalization at more than one level. Token-level normalization buys you L1. To get L2 and L3 you need to compare structure, which means parsing to an AST and comparing subtree shape rather than token order, and in my runs that is exactly where the hybrid pipeline's twenty-point advantage at L3 comes from.

ToolCore comparisonOpen sourceWeb/GitHub corpusAI signalInterface
MOSSWinnowing over token k-gramsNoNoNoEmailed results URL, no UI
JPlag 4.2Greedy String Tiling, normalized tokensYes (GPLv3)NoNoStatic HTML report
Dolos 2.4AST fingerprints via tree-sitterYes (MIT)NoNoSelf-hosted web app
CodequiryToken, AST, and fingerprint layersNoYes, GitHub and webYesDashboard, REST API, CLI

MOSS is a remarkable piece of engineering and it is free, but it is also a black box that returns a number you cannot audit, which is awkward when a student appeals. JPlag and Dolos are both excellent and both open source, and if you have a TA who enjoys running a JVM or a Docker compose file, they're genuinely good choices. What neither does is look outside your cohort. A student who lifts a solution from a GitHub repository that isn't in anyone else's submission set scores near zero on peer comparison and sails through.

That gap is why I'd point most departments at a source code plagiarism checker that stacks peer comparison against the open web and GitHub, and then adds an independent AI-generation score on top. Three signals, three different failure modes. A submission has to be original against its cohort, original against the internet, and plausibly human, and each check catches cases the other two miss. The practical workflow matters too: someone has to look at the flagged pairs, and a side-by-side diff with per-file scores beats a spreadsheet of decimals every time.

Codequiry insights score breakdown separating peer similarity, web similarity and AI generation, with match sources
The score breakdown: peer similarity, web similarity and AI probability reported separately, with where the matches came from.

Where this study stops

The 180 pairs are Java from a single institution. L2 and L3 transformations were applied by me, which means they reflect what a competent programmer would do, not what an adversarial one would. Recall at 1% FPR is a threshold-dependent metric, and the thresholds were tuned on a 90-pair control set that is probably less internally similar than a real cohort of 400 students who all attended the same lectures. Expect real-world recall to be a little higher than these numbers and real-world false positives to be a little higher too.

And no detector in this study is designed to beat a determined adversary with a good model and an hour to spare. That was never the job. The job is raising the cost of the median case, which is someone who panicked at 2 a.m. and pasted their roommate's file. On that job, even MOSS at L1 is doing fine, and everything above L1 is about the student who thought one step further ahead.

Frequently asked questions

Can refactoring hide copied code from MOSS?

Yes, at L2 and above. In this study MOSS recall fell from 0.97 on verbatim copies to 0.52 after control-flow restructuring and 0.34 after method extraction. Renaming and reformatting alone barely moved it.

What is the difference between token-based and AST-based similarity?

Token-based tools compare sequences of lexical units, so they catch shared text but lose track when the same logic is written with a different control structure. AST-based tools compare tree shape, which survives loop-to-recursion and method extraction far better, though it costs more to compute and needs a real parser for each language.

Does AI detection still work if a student paraphrases code with ChatGPT?

Often yes, because paraphrasing introduces generation artifacts: uniform commenting, unnecessary defensive checks, and library choices a first-year student wouldn't reach for. It is not reliable on short files, and it should be treated as one signal among several rather than a verdict.

If you want to see what the three-signal view looks like on your own assignment set, the code plagiarism checker will run peer, web, and AI analysis on a sample cohort in a few minutes.