Sub topic 6
Hunting for Edge Cases and Logic Errors
This chapter assumes you can read a Git diff, write unit tests with a framework such as pytest, and have used an AI coding assistant. By now you have checked the change against the requirement and read the diff line by line. This chapter covers the next step: finding inputs and states where code that looks correct gives wrong results.
Why plausible code hides logic errors
AI assistants write code that matches common patterns. The common pattern handles the common case. Edge cases are rare by definition, so they are underrepresented in what the model learned from. They are also rarely stated in your prompt.
Take this function:
def average(values):
return sum(values) / len(values)It is readable, short, and correct for [2, 4, 6]. It fails on [] with ZeroDivisionError. Nothing in the code looks wrong. The defect is in an input the requirement never mentioned. A review that only asks "does this look right?" will pass it.
The goal of this chapter is to replace that question with a different one: "for which inputs does this stop being right?"
A repeatable way to find edge cases
Work through the function's inputs and state in a fixed order. Doing it the same way each time keeps you from relying on intuition.
- List every input. Include arguments, files, environment variables, database rows, and network responses.
- For each input, walk its boundaries. Use the table below.
- Trace the code with each boundary value. Follow it by hand or run it.
- Decide what the correct behavior is. If the requirement is silent, that is a finding. Ask the requirement's owner, or choose a behavior and record it in a test.
Boundary values to try
| Input kind | Values to try |
|---|---|
| Collections | Empty, one item, two items, duplicates, very large |
| Numbers | Zero, negative, one, maximum size, `NaN`, floating-point rounding |
| Strings | Empty, only whitespace, non-ASCII characters, very long, contains delimiter characters |
| Dates and times | Time zones, daylight saving changes, month ends, leap days |
| Optional values | `None` or `null`, missing key, wrong type |
| Files and I/O | Missing file, empty file, no permission, partial write, huge file |
| Concurrency | Two callers at once, retry after partial failure |
You do not need every row for every function. Pick the rows that match the types in the diff.
Common logic errors in AI-written code
These patterns show up repeatedly. Search for them deliberately.
Off-by-one errors
Look at loop bounds, slices, and range calls. AI code often mixes inclusive and exclusive ends, especially when it paginates or windows data.
def last_n(items, n):
return items[-n:]This works for n = 2. For n = 0, items[-0:] is items[0:], so it returns the whole list instead of an empty one. A one-character slice rule produced the opposite of the intended result.
Wrong assumptions about empty or missing data
The average example is one case. The same mistake appears as max([]), data[0] on an empty list, dict["key"] on a missing key, and .split(",")[1] on a string with no comma. Whenever you see an index, a division, or max/min, ask what happens when the data is absent.
Silent error swallowing
Assistants often add error handling that hides problems.
def load_config(path):
try:
with open(path) as f:
return f.read()
except Exception:
return ""A missing file and an unreadable file both produce an empty configuration. The caller cannot tell a failure from a valid empty file. Flag broad except clauses that return a default value. Ask whether the caller should know.
Mutable defaults and shared state
def add_tag(tag, tags=[]):
tags.append(tag)
return tagsThe default list is created once and shared across calls. The second call sees the first call's data. Check default arguments, module-level variables, and class attributes that are mutable.
Type and comparison mistakes
Look for == on floats, comparing strings where numbers are meant ("10" < "9" is true), truthiness checks that treat 0 or "" as missing (if not value: when 0 is valid), and integer division where float division is meant.
Order and time assumptions
Dictionary and set ordering, database result ordering without ORDER BY, and "now" calculated twice in one function can all change results between runs. Ask whether the code depends on an order that nothing guarantees.
Check behavior against the requirement
Edge-case hunting has a second half. For each edge case, decide what the correct answer is. The code might raise an error, return a default, or return None. Each is valid in some systems and wrong in others.
For average([]), reasonable choices include raising ValueError, returning None, or returning 0.0. Returning 0.0 is risky because a caller cannot tell an empty list from a list whose real average is zero. Choose based on how callers use the function, then write the choice down in a test.
Pin the fix with tests
After you find an edge case, fix it and add a test that fails without the fix. The test keeps the evidence after the review ends.
import pytest
def average(values):
if not values:
raise ValueError("values must not be empty")
return sum(values) / len(values)
def test_average_of_numbers():
assert average([2, 4, 6]) == 4
def test_average_of_empty_list_raises():
with pytest.raises(ValueError):
average([])Run the empty-list test against the original function first. It should fail with ZeroDivisionError, not pass. A test that passes against the broken code proves nothing. This is the same habit as reproducing a bug before fixing it.
You can also ask the assistant to propose edge cases, then verify them yourself. Treat its list as suggestions. The model may miss the same cases it missed when writing the code.
Tracing by hand
For logic with branches or loops, trace one concrete input at a time. Write the variable values after each step. Do it for at least one normal input and one boundary input.
Consider this function that should return the longest run of equal values:
def longest_run(items):
best = 1
current = 1
for i in range(1, len(items)):
if items[i] == items[i - 1]:
current += 1
else:
current = 1
best = max(best, current)
return bestTrace [1, 1, 2]: best and current start at 1. At i = 1, the items match, so current is 2 and best is 2. At i = 2, they differ, so current resets to 1 and best stays 2. The result is 2, which is right.
Now trace []. The loop does not run, so the function returns 1. The longest run in an empty list should be 0. The code starts best at 1 on the assumption that at least one item exists. Tracing the boundary found a bug that the normal trace hid.
Review flow for a single function
Using the tools you already have
Reading is slow, so combine it with cheap mechanical checks.
- Run the code with boundary inputs in a REPL or scratch script before you read further.
- Use property-based tests with a library such as Hypothesis. They generate many inputs, including empty ones, and report ones that break a rule you state.
- Check test coverage of the diff. Lines or branches the tests never run are lines nobody has checked. Do not trust coverage numbers alone, since a line can run without its result being asserted.
Here is a small property-based test for the longest_run function above:
from hypothesis import given, strategies as st
def longest_run(items):
best = 1
current = 1
for i in range(1, len(items)):
if items[i] == items[i - 1]:
current += 1
else:
current = 1
best = max(best, current)
return best
@given(st.lists(st.integers()))
def test_run_length_is_bounded_by_list_length(items):
assert longest_run(items) <= len(items)Hypothesis tries [] early and reports that 1 <= 0 is false. You did not have to think of the empty list yourself.
Pitfalls when reviewing for edge cases
- Testing only what the AI wrote tests for. Assistants often generate tests that mirror the implementation. If the code ignores empty input, so do its tests.
- Fixing the symptom. Adding
if not values: return 0may stop the crash and still give wrong answers downstream. Confirm what callers expect. - Expanding scope. If the edge case reveals a larger design problem, record it separately. Keep the change small enough to review, as covered earlier in this tutorial.
- Stopping at the first finding. One missed edge case suggests the author did not think about boundaries. Keep looking in the same change.
Exercise
This AI-written function should return the second-largest distinct number in a list. Name two inputs that break it, and say what each does. def second_largest(nums): ordered = sorted(nums, reverse=True) return ordered[1]
Show answer
An empty list or a one-item list raises IndexError, because there is no element at index 1. A list with duplicates of the maximum, such as [5, 5, 3], returns 5 instead of 3, because sorted keeps duplicates and the function asks for distinct values. A correct version would use sorted(set(nums), reverse=True) and decide explicitly what to do when fewer than two distinct values exist, for example by raising ValueError.
Exercise
You find that an assistant-written test suite for a new function passes, but every test uses a non-empty list. What should you do before accepting the change?
Show answer
Add tests for the boundary inputs (empty list, one item, duplicates, and so on), and run them against the current code to see whether they fail. Decide the correct behavior for each case from the requirement. Fix the code where the tests expose wrong results. The original passing suite only shows the common case works.