Setting a Code Similarity Threshold Before You File a Case

In Spring 2024 our CS 210 data structures course produced 412 submissions of a single linked-list assignment. The detector's default cutoff put 63 pairs into the review queue. Nine survived a careful read. The other 54 consumed roughly eleven hours of TA time and generated four apology emails to students who had done nothing wrong.

None of that was the tool's fault. It was ours. We had treated a threshold as a constant when it is really a parameter you estimate, per assignment, from your own data.

A code similarity threshold is not a number you inherit from a tool's default settings. It is a property of a specific assignment, cohort, language, and detector configuration, and you can measure it before you file a single case. The method is to build a null distribution from a clean cohort, find the knee in the score curve, tier the reviews instead of applying one cutoff, and write the decision rule down where the next TA can find it.

What follows is the workflow we settled on after three semesters of getting it wrong. It assumes you have a source code plagiarism checker that reports numeric per-pair scores and lets you exclude starter files.

Step 1: Build a baseline cohort before the term starts

The null distribution is the whole game. You need to know what legitimate similarity looks like in your course, and the only honest source for that is work you have already graded and already cleared.

Take last year's archive, run the same detector with the same settings, and compare submissions against each other only. No web corpus, no cross-term matching. We used Fall 2023 for CS 210: 388 submissions, one assignment, Java, all pairwise comparisons.

PercentilePeer similarity (Fall 2023, n = 388)
Median12%
p9031%
p9544%
p9966%
Maximum100%

That maximum is instructive. Two submissions scored 100% because both students uploaded the unmodified starter file. No misconduct, just a shared skeleton. This is the single most common source of noise in intro-level courses, and it is why base-code exclusion exists in every serious tool. In MOSS you pass the skeleton with -b; in JPlag 5.1 you use -bc base/. If your pipeline does not strip the starter code before scoring, fix that before you touch thresholds, because everything downstream inherits the distortion.

Half the calibration work is not calibration at all. It is removing artifacts that have nothing to do with student behavior.

One caveat on baselines: a prior-term archive is a sample, not a population. Assignments change, the language of instruction changes, and a cohort that had a strong study group will look more similar than the one after it. Rebuild the baseline every two or three terms.

Step 2: Know what the score is actually counting

A similarity percentage is a summary of many matched regions, and different algorithms summarize differently. Two submissions can both score 45% while one has a single 40-line copied block and the other has eleven scattered five-token coincidences from idiomatic Java.

MethodWhat it comparesSurvives renamingSurvives restructuring
Token sequence (JPlag 5.1)Token stream after comment and whitespace strippingYesPartly
Winnowing fingerprints (MOSS)Hashed k-gram fingerprints, document-level coverageYesPartly
AST and graph comparisonSyntax tree shape, control flow, statement structureYesOften yes
Raw text diffLines and charactersNoNo

The practical consequence: a renamed, reformatted resubmission of someone else's work will score lower on a fingerprint tool than on an AST tool, and a legitimately independent solution that happens to follow the same skeleton will score higher on both than it deserves. Neither direction is a bug. They are tradeoffs you need to know about when you read the number.

This is also the point where choosing your detector starts to matter. If you are comparing defaults, the Codequiry vs MOSS writeup covers where the two diverge on structural matches, and JPlag's minimum token match setting (-t, default 9 tokens) is worth lowering only if you are prepared for the false positive rate to climb accordingly.

Step 3: Find the code similarity threshold that fits this assignment

Here is the finding that changed how we run reviews. The natural similarity floor is a function of how much freedom the assignment gives students, and that varies wildly within one course.

Assignment typeMedian pairp95Knee
Linked list (fixed API, ~90 LOC)28%58%64%
Huffman coding (algorithmic, ~180 LOC)14%41%47%
Open-ended game shell (~400 LOC, free design)6%22%31%

A 50% cutoff is conservative for the linked list and nearly useless for the game shell. The starter-code overlap and the tight method signatures in the linked list push the median to 28% before anyone has done anything questionable. The game shell has enough design freedom that a 31% score is genuinely unusual.

Find the knee mechanically rather than by eye. Sort the pair scores descending and look for the largest gap in the sequence. On a clean distribution the knee lands where casual coincidences stop and structural matches begin.

import numpy as np, pandas as pd

pairs = pd.read_csv("cs210_spring2024_pairs.csv")   # a, b, peer_score, web_score, ai_score
s = np.sort(pairs["peer_score"].to_numpy())[::-1]

for q in (50, 90, 95, 99):
    print(f"p{q}: {np.percentile(s, q):.1f}")

gaps = s[:-1] - s[1:]
i = gaps.argmax()
print(f"knee at {s[i + 1]:.1f} (gap of {gaps[i]:.1f} points)")

On the Spring 2024 linked list run, that printed a knee at 61%. We had been reviewing at 50%, which is where roughly half our false positives came from: pairs in the 50s that were nothing but shared scaffolding and a shared textbook.

Codequiry peer similarity report with a risk distribution and a smart review queue ranking cohort outliers
The peer report: a class-wide risk distribution and a smart review queue that surfaces the strongest outliers first.

Step 4: Look at matched structure, not just the scalar

A single number cannot tell you whether a match is a copied block or scattered idiom. Before you review a case by hand, pull the longest contiguous normalized token run for the pair. Normalization means identifiers, literals, and numbers get collapsed to placeholders, so a variable rename does not hide the match.

import io, tokenize, difflib

def norm_tokens(src):
    out = []
    for tok in tokenize.generate_tokens(io.StringIO(src).readline):
        if tok.type in (tokenize.COMMENT, tokenize.NL, tokenize.INDENT, tokenize.DEDENT):
            continue
        if tok.type == tokenize.NAME:
            out.append("ID")
        elif tok.type == tokenize.NUMBER:
            out.append("NUM")
        elif tok.type == tokenize.STRING:
            out.append("STR")
        else:
            out.append(tok.string)
    return out

a = norm_tokens(open("sub_0142/LinkedList.java").read())
b = norm_tokens(open("sub_0317/LinkedList.java").read())

m = difflib.SequenceMatcher(a=a, b=b, autojunk=False).find_longest_match(0, len(a), 0, len(b))
print(m.size, "consecutive normalized tokens")

The threshold we use for a conversation is 25 consecutive normalized tokens that are not boilerplate. Between 8 and 12 tokens is almost always idiom: the standard null check, the scanner loop, the getter the assignment required verbatim. Anything under 8 is noise. That mapping is not universal, and it depends on how much of your assignment is prescribed, but it held within about a five-token band across our three assignments.

Run this before reading the diff. It tells you whether you are about to spend twenty minutes on a real case or a coincidence.

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.

Step 5: Stack peer, web, and AI signals before deciding

Three signals, four common combinations. The combination is more informative than any single score, and the review action differs for each.

PeerWebAIMost likely explanationAction
HighLowLowCollaboration or shared source between two studentsInterview both, separately
LowHighLowCopied from GitHub, Stack Overflow, or a tutorialCite the source, check attribution rules
LowLowHighLLM-generated, no peer or web overlapReview per-file AI scores, check drafts
HighHighHighBoth students used the same tool or sourceEscalate, treat as a group case

The reason to keep the signals separate rather than blend them into one integrity score is diagnostic. A blended 72 tells you nothing about what to ask the student. Separate scores tell you which question to open with.

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.

One honest limit on the AI column. Source code has low perplexity by nature; a for loop is a for loop, and detectors that lean on token-level predictability will flag well-commented, idiomatic student code at a nonzero rate. We have not validated AI scores past a few hundred submissions per assignment, and I would not treat a single AI score above threshold as sufficient grounds for a case without corroborating evidence from drafts, version history, or a conversation.

Step 6: Tier the review queue and write the rule down

One cutoff produces a binary: flagged or not. Two or three tiers produce a workload you can actually staff, with a decision rule that does not depend on who is on duty that week.

TierCriteriaWho reviewsOutcome path
WatchBelow knee, one signal slightly elevatedAutomated logNo action unless it recurs
ReviewAt or above knee, or any web match over 15 linesTA with rubricCleared or escalated
CaseKnee plus 25+ token block, or all three signals highInstructorStudent conversation, then formal process

Record the configuration alongside the outcome: detector and version, language, minimum token match, base code used, web corpus date, and the score for each tier boundary. Cases get appealed six weeks later, and if you cannot reproduce the number you ran, the appeal becomes a debate about your memory.

If you are pulling these numbers by hand into a spreadsheet, you are doing it the hard way. The peer, web, and AI scores come back per pair from a single check in Codequiry's API, which is how the tables above got built without three exports and a merge on student ID.

Step 7: Pilot on one section, then measure precision

Change one variable at a time. We piloted on a single section of 96 students before touching the other one. Precision, meaning the share of flagged pairs that survived review, went from 14% (9 of 63) under the default cutoff to 61% (17 of 28) after calibration. The sample is small and the two terms are not identical, so treat the direction as the finding and the magnitude as an estimate.

The review queue ordering matters as much as the threshold. Ranking by outlier score relative to the cohort, rather than raw similarity, surfaced the one pair that sat at 58% and turned out to be a wholesale copy with renamed variables. It scored below two dozen false positives on raw percentage.

Codequiry dashboard home with quick start actions, courses and recent checks showing peer, web and AI scores
The Codequiry dashboard: recent checks at a glance with peer, web and AI similarity scores.

Audit once a year, after the term, with the outcomes in hand. Recompute the distribution, compare it to the baseline, and check whether the knee moved. In our experience it moves when the assignment description gets more prescriptive, which is a design signal as much as a detection one.

Frequently Asked Questions

What is a reasonable similarity threshold for code plagiarism?

There is no universal number. Measured knees in our courses ran from 31% on a free-design assignment to 64% on a fixed-API data structure assignment. Compute the knee from your own prior cohort rather than adopting a default.

Does a high similarity score prove plagiarism?

No. It proves that two submissions share structure. Starter code, prescribed signatures, and textbook idioms all produce legitimate similarity, which is why base-code exclusion and matched-block length matter more than the headline percentage.

Should I show students the scores?

Show them the course policy and the fact that checks run, not the raw dashboard. Publishing thresholds invites gaming, and publishing pair scores exposes students to rumor. Discuss findings with the individuals involved and keep the aggregate numbers for your own calibration.

If you want the peer, web, and AI signals in one report instead of three, you can run a check on a past cohort and see the full distribution before you commit to a number.