Skip to content
LeetQuant
QD10 System Design and Code Review

QD10 · System Design and Code Review · Lesson 5 of 5

Reviewing Generated Code

The characteristic failure patterns of AI-generated code (plausible but wrong APIs, off-by-one, silent float and integer issues, missing edge cases, invented functions, insecure defaults) and a worked review of a generated volatility function whose bugs are confirmed by running it.

16 min

Why generated code needs a different review

Generated code is fluent. It has good names, a docstring and the shape of a correct solution, which is exactly what makes its bugs easy to miss: the usual signals of careless code (messy formatting, odd names) are absent. Code written by a person tends to fail where the author was confused; generated code fails where the most common pattern in its training data differs from what your problem needs. Interviewers increasingly hand candidates a generated function and ask them to find what is wrong, and production teams expect the same skill.

The objective: know the recurring failure patterns, and verify generated code by running it on inputs you chose, never by reading it and agreeing.

The failure patterns

PatternExampleHow to catch it
Plausible but wrong or removed APIpd.rolling_mean(s, 20) (removed from pandas years ago); df.append(row) (removed in pandas 2.0)Run it against the library version you actually use; check the docs for that version
Invented function or argumentA helper that "should" exist, or a keyword argument the function does not acceptRun it; an AttributeError or TypeError appears immediately, which is the cheap case
Off-by-onerange(window, len(xs)) drops the last window; range(len(xs)) with xs[i - 1] reads xs[-1] at i = 0Test on a tiny input whose answer you know by hand
Silent float and integer issuesint(1.15 * 100) is 114; round(2.5) is 2; -7 // 2 is -4; 0.1 + 0.2 == 0.3 is FalseUse integer ticks or Decimal for money; compare floats with a tolerance
Wrong conventionPopulation instead of sample variance; annualising by 252 instead of 252\sqrt{252}; annual rate subtracted from daily returnsCompare with an independent reference implementation
Missing edge casesEmpty input, one element, all-equal values, zero prices, NaNWrite the edge-case tests yourself before reading the code
Insecure defaultsSQL built with f-strings; yaml.load without a safe loader; pickle.loads on untrusted data; verify=False on HTTPS; shell=True with user inputSearch for these patterns explicitly; they rarely break a test
Confident docstring, different behaviourDocstring says "sample standard deviation", code computes populationCheck every claim in the docstring against the code

Python's negative indexing deserves special mention: prices[i - 1] at i = 0 silently returns the last element instead of raising, so a loop bound that is off by one produces a plausible number instead of a crash.

The off-by-one row, run:

def rolling_mean(xs, window):
    return [sum(xs[i - window:i]) / window for i in range(window, len(xs))]

print(rolling_mean([1, 2, 3, 4], 2))
[1.5, 2.5]

There are three windows of length 2 in four numbers, so [1.5, 2.5, 3.5] is correct: the range must run to len(xs) + 1. In a signal pipeline the dropped value is the most recent one, the only one that matters for today's trade.

Worked example

a generated volatility function

You asked a code assistant for "a function that returns the annualised volatility of daily simple returns from a list of prices". It produced the function below. Review it, confirm each bug by running it, and fix it.

def annualised_vol(prices, periods_per_year=252):
    """Annualised volatility of simple daily returns."""
    returns = [prices[i] / prices[i - 1] - 1 for i in range(len(prices))]
    mean = sum(returns) / len(returns)
    var = sum((r - mean) ** 2 for r in returns) / len(returns) - 1
    return (var * periods_per_year) ** 0.5
Show solution

Step 1: run it on a small input.

prices = [100.0, 101.0, 99.5, 100.5, 102.0]
print(annualised_vol(prices))
(9.719332587663166e-16+15.872874684243888j)

A volatility came back as a complex number. In Python 3, a negative float raised to a fractional power returns a complex result instead of raising, so the bug did not crash; it would propagate into anything that accepts complex numbers.

Step 2: find why. Two separate bugs:

  1. Operator precedence. / len(returns) - 1 parses as (... / len(returns)) - 1, not division by len(returns) - 1. The variance of daily returns is tiny (around 10−410^{-4}), so subtracting 1 makes it about −0.9998-0.9998, hence the complex square root. The intent was the sample variance, dividing by n−1n - 1.
  2. Off-by-one with negative indexing. range(len(prices)) starts at i = 0, and prices[-1] is the last price, so the first "return" is 100/102−1≈−0.0196100 / 102 - 1 \approx -0.0196: a fictitious return from the end of the series back to the start. There are only 4 real returns in 5 prices, and the code computes 5.

Fixing only the precedence hides the second bug behind a plausible number. With the divisor corrected but the wrap-around return still included, the function returns about 0.25460.2546; the correct value is about 0.21360.2136. A reviewer who stopped when the output "looked like a volatility" would ship a result 19% too high.

Step 3: check the edge cases the generated code ignores. One price gives an empty return list and a ZeroDivisionError; two prices give one return, for which a sample standard deviation is undefined; a zero price divides by zero.

Step 4: fix, and verify against an independent reference.

import math
import statistics


def annualised_vol(prices, periods_per_year=252):
    """Annualised volatility of simple returns (sample standard deviation)."""
    if len(prices) < 3:
        raise ValueError("need at least 3 prices for 2 returns")
    if any(p <= 0 for p in prices):
        raise ValueError("prices must be positive")
    returns = [prices[i] / prices[i - 1] - 1 for i in range(1, len(prices))]
    return statistics.stdev(returns) * math.sqrt(periods_per_year)


prices = [100.0, 101.0, 99.5, 100.5, 102.0]
print(f"{annualised_vol(prices):.4f}")
print(annualised_vol([100.0] * 5))
try:
    annualised_vol([100.0, 101.0])
except ValueError as e:
    print("ValueError:", e)
0.2136
0.0
ValueError: need at least 3 prices for 2 returns

The reference check: the four returns are 0.010.01, −0.014851-0.014851, 0.0100500.010050 and 0.0149250.014925; NumPy's r.std(ddof=1) * np.sqrt(252) and pandas' pct_change().std() * np.sqrt(252) both give 0.2135880.213588, matching the fixed function. Using the library's own standard deviation instead of a hand-written formula also removes the class of bug that started this.

What to tell the interviewer. "It returns a complex number because of a precedence error in the variance; once that is fixed it is still 19% too high because i = 0 reads prices[-1] and adds a wrap-around return. I fixed both, used statistics.stdev for the sample variance, rejected inputs too short or non-positive, and checked the result against NumPy."

Knowledge check

Generated code converts a price to integer cents with int(price * 100). What does it return for price = 1.15?

Knowledge check

A generated function computes daily returns as [p[i] / p[i - 1] - 1 for i in range(len(p))] on a list of 250 prices. What happens?

Knowledge check

Which issue in generated code is least likely to be caught by running the code on a few test inputs?

Key takeaways

  • Generated code fails where common patterns differ from your requirements, and it looks clean while doing so; review it by running it on inputs you chose.
  • Check APIs against the installed library version; invented and removed functions are the cheap bugs because they fail loudly.
  • Hunt for silent bugs: off-by-one with negative indexing, operator precedence, float-to-int truncation, wrong statistical conventions.
  • Fixing the first bug can hide the second behind a plausible number; verify the final result against an independent reference.
  • Search for insecure defaults explicitly; tests on ordinary inputs do not reveal them.
  • Write expected values and edge-case tests yourself rather than trusting tests from the same generator.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).