What Makes AI-Generated Code Detectable
When a student opens a blank editor and writes a Python function to compute the Fibonacci sequence, their code carries a fingerprint: variable names chosen from personal habit, inconsistent spacing between functions, and the occasional stray print statement left over from debugging. When ChatGPT or GitHub Copilot generates the same function, the output tends to be statistically cleaner, and that cleanness is measurable.
Three families of signals do most of the work on intro-level Python:
- Perplexity scoring, using a code language model to measure how predictable each token is
- Burstiness analysis, measuring how unevenly rare tokens and surprising choices are spread through the file
- Token-frequency z-scoring, comparing a submission's n-gram distribution against a reference corpus of human-written Python
Each one has a clear idea behind it, a characteristic failure mode, and a place in a combined detector. To evaluate any of them on your own course, you need a ground truth set: anonymized submissions with a subset whose origin you know, for example from student interviews or process logs.
Perplexity: The Flatness Signal
Perplexity measures how well a probability model predicts a sequence of tokens. For natural-language text, LLM-written content tends to have lower perplexity because the model produces highly probable token sequences. For source code, the pattern is similar but the magnitudes are different: code has more rigid structure than prose, so even human-written code has relatively low perplexity. The gap is smaller, but it is there.
# Human-written style
def fibonacci(n):
if n < 0:
raise ValueError("n must be non-negative")
a, b = 0, 1
for _ in range(n):
print(a)
a, b = b, a + b
# Generated style
def fibonacci(n):
a, b = 0, 1
for i in range(n):
print(a)
a, b = b, a + b
return
The second version follows the most common pattern for this task almost token for token, so a code model finds it highly predictable. The first contains a choice (the validation line) that a model would rate as less likely at that position.
The catch is overlap. Short, canonical tasks push human and generated perplexity close together, and a strict threshold that avoids false positives also misses many generated files. Perplexity alone is not enough for a production detector, but it is a useful baseline signal.
Burstiness: The Variance That Gives It Away
Burstiness measures the tendency for rare tokens to cluster. Human programmers reuse their own unusual variable names, type annotations, and comment habits, which creates clusters of rare tokens. A student who names a temporary variable temp123 in one loop is likely to reuse temp123 in the next. Generated code tends to spread its token choices more evenly and rarely repeats long idiosyncratic identifiers.
A common way to quantify this is the burstiness parameter of Goh and Barabási, B = (σ − μ) / (σ + μ), computed over the gaps between occurrences of a token. A value near 0 indicates a Poisson-like process, and values approaching 1 indicate strong clustering. Human submissions tend to sit higher on this scale than generated ones.
Burstiness becomes much more useful in combination. A simple model, such as a logistic regression over perplexity and burstiness, usually separates the classes better than either feature alone, because files that are both very predictable and very even are the ones most likely to be generated.
Token-Frequency Z-Scores: Catching Common Idioms
Many students don't only use ChatGPT; they also paste code from Stack Overflow, GitHub gists, or tutorial sites. Web-source copying is distinct from AI generation but often co-occurs. To measure it statistically, build a reference corpus of public Python files (ideally educational projects), compute TF-IDF vectors, and calculate a z-score for each n-gram in a submission against the reference:
# Z-score formula applied per n-gram
z = (freq_submission - mean_reference) / std_reference
Submissions with many high-z-score n-grams lean heavily on the most common coding idioms and snippet patterns. That points to both web-copied and AI-generated code, because LLMs are trained on enormous web corpora and overrepresent those same idioms. A human might write a recursive quicksort with distinct variable names; a model is more likely to produce the classic less = [x for x in arr[1:] if x <= pivot] pattern found in countless tutorials.
Because the two problems overlap, a combined detector that checks AI signals and web sources together catches more than either alone. Codequiry stacks these signals so that a submission that is both generated and sourced from the web is visible as both.
Three Recurring Signatures
Beyond global statistics, three patterns show up repeatedly in generated intro-level Python.
1. The Over-Explained Comment Block
LLMs often insert lengthy docstrings that explain the algorithm in plain English even when the assignment doesn't ask for documentation. Human submissions on the same task more often have a one-line comment or none at all.
# Common AI docstring pattern
def sieve(n):
"""Sieve of Eratosthenes algorithm to find all prime numbers up to n.
Make a list of consecutive integers from 2 to n. Start with p=2.
Mark all multiples of p as composite. Then find the next unmarked number.
This is the classic algorithm attributed to the ancient Greek mathematician."""
# ... code ...
2. The Uniform Error Handling
Models tend to add defensive try/except blocks that catch generic exceptions, even in a simple string-reversal function. Beginners usually either omit error handling or catch a specific type such as TypeError.
3. The Missing Edge Cases
Ironically, while generated code often over-handles errors, it frequently misses domain-specific edge cases. For a function that processes grade data, a careful student tests for empty lists, negative numbers, and non-numeric inputs because the assignment spec or the lecture mentioned them. Generated code tends to do well on the main path and poorly on the boundary conditions the prompt never stated.
Where the Methods Break Down
No detector is perfect. Three cases cause most of the trouble:
- High-skill, concise human code. Strong students who write clean, idiomatic code can produce low-perplexity, low-burstiness output that looks AI-like. Some false positives will be your best students.
- Heavily edited AI code. A student who takes a generated draft, restructures it, renames variables, and adds comments can shift the statistical profile back into the human range. These are the cases a combined detector is most likely to miss.
- Boilerplate-heavy assignments. When the assignment requires a fixed template (fill-in-the-blank in a provided scaffold), human and generated submissions become nearly indistinguishable because the token space is so constrained.
The cleanest students can look like bots, and the cleverest cheaters can look like students.
Practical Recommendations for Instructors
A tiered approach to AI code detection suits CS1 courses:
- Use a combined detector that stacks perplexity, burstiness, and web-source similarity. A single metric will miss too many cases.
- Apply different thresholds for different assignment types. Boilerplate-heavy assignments need a higher threshold (tolerate more false negatives to avoid false positives). Open-ended assignments can use a tighter one.
- Require annotated code or in-person walkthroughs for flagged submissions. Low perplexity alone isn't a violation. Ask the student to explain a specific line or naming decision. If they can't, escalate.
- Don't rely on one signal that students can learn to game. If detection depends only on perplexity, students will learn to inject random variable names. Several independent signals are harder to beat.
Codequiry's detection pipeline follows these principles: it stacks statistical signals with web-source matching and reports each one separately, so a reviewer can see which signal drove a flag before deciding what to do with it.
Frequently Asked Questions
Can a student defeat perplexity-based detection by adding comments?
Partially. Comments add tokens and can shift a whole-file perplexity score, but the underlying code structure stays predictable. A detector that scores function bodies separately from comments still sees the signal.
What about code written with Copilot inline completions rather than full prompts?
Copilot-assisted code falls in a gray area. Copilot adapts to the developer's style, so per-line perplexity of its completions can sit close to human-written lines and a global perplexity check often fails. Token-frequency signals for common idioms the student wouldn't naturally use can help, and comparing a submission with the student's own earlier work is often the most informative check of all.
Is there a risk of false positives for ESL students or non-traditional learners?
Yes. Students who learned from different sources, including non-English tutorials, may show unusual token-frequency patterns that resemble AI generation. Treat any detection output as evidence for a conversation, not a verdict. Review flagged submissions manually and consider the student's earlier work.