Fix a bug in an unfamiliar codebase
- Case study 1
- 150 min
- Optional · 1 case study needed for the certificate
Where we are
This case study takes the debugging of Module 4 and the review of Module 3 to a small project that you have never seen. You map the code, ask the assistant targeted questions, reproduce and shrink the bug, write the failing test first, and review the assistant's fix.
Case study 1 of 2 · AI-Assisted Software DevelopmentFix a bug in an unfamiliar codebase
1. Establish a safe working setup
2. Write actionable tasks
3. Review generated work
4. Debug and test with assistance
5. Deliver maintainable work
What you will be able to do
Fix a customer’s bug in a small project that you have never seen. Map the code before you ask for a change, ask the assistant targeted questions, and reproduce the bug yourself. Then shrink it to the smallest input, write the failing test, fix it with the assistant, and review the diff. At the end, compare your fix with the fix of the people who wrote the code.
The course team wrote delivery-slots for this case study, under the MIT licence. It has a Git history, two issues and 35 tests. Larkfield, the delivery team, the customer and the bookings are invented. The postal code areas are real forward sortation areas of Montréal, but their delivery zones are invented. The assistant session is real: you can read every prompt and reply in the recorded transcript. The maintainers’ fix in the finished project is constructed. The course team wrote it as the delivery team’s own fix, so that you can compare two fixes.
Before you startWhat to know and to have ready
What you need to know
This case study uses the whole course on code that is not yours. It leans most on Break work into steps (investigate before you change), Reproduce first, Choose meaningful checks and Inspect the diff. From the Git course, you need commits and git log, from Track a first change, and diffs, from Read and review diffs.
What you need on your computer
- Python 3.12 or newer, Git and VS Code, as in the earlier modules. About 40 MB of free disk space.
- No account and no money. A coding assistant is optional: the recorded session is supplied, and a patch file gives you its change.
Tested on macOS (Apple silicon) with Python 3.14.6. The Windows commands are written, not tested.
The situation
Section titled “The situation”On Monday morning, Grace, who leads the help desk, adds an issue to the delivery team’s project. A customer, Solange, lives in Westmount, postal code H3Z 2Y7. Larkfield’s delivery page promises evening slots for the west zone on Tuesdays and Thursdays, from 18:00 to 20:00. Solange works during the day. At 10:00 she ordered a garden bench, and the checkout offered her only three daytime slots for Tuesday. Her sister in Notre-Dame-de-Grâce (H4A) has an evening delivery booked for the same day.
The delivery team is two people, Delphine and Luis, and both are at a trade fair until Friday. Amira, who keeps the help-desk tools, offers to look at it. She has never opened delivery-slots.
The objective. Solange gets her evening slot for Tuesday. Every customer gets the slots of their own zone. And Delphine and Luis can accept the fix when they are back. It has a failing test first, a small diff, and no change that nobody asked for.
What you will do
Section titled “What you will do”| Part | What you do | Who does it |
|---|---|---|
| 1 | Map the project: files, commands, the path of the issue’s command | you, then the assistant |
| 2 | Ask targeted questions about one function | the assistant; you check |
| 3 | Reproduce the bug, and read the history | you |
| 4 | Shrink it to the smallest input | you |
| 5 | Write the failing test, and commit it | you |
| 6 | Fix it | the assistant, inside your limits |
| 7 | Review the diff | the assistant and you |
| 8 | Compare the fixes under one measure, and recommend one | you |
| 9 | Run it end to end on new input | you |
The codebase
Section titled “The codebase”| Fact | Value |
|---|---|
| Project | delivery-slots: lists the delivery slots of a postal code, books a slot, prints a driver’s list |
| Licence | MIT, “Copyright (c) Nextia Learning” |
| Size | 9 Python files (403 lines), 7 test files (317 lines), 3 CSV files |
| History | 6 commits by Delphine, Luis and Grace; issues 3 (closed) and 12 (open) |
| Dependencies | none to run it; pytest and ruff to work on it |
A Canadian postal code has six characters, such as H3Z 2Y7. The first three, H3Z, are the forward sortation area (FSA): one part of a city. Larkfield’s zone file, data/zones.csv, has two kinds of rows. A row can name a whole FSA, such as H3Z. Or it can name the first two characters of many FSAs, such as H3, which covers H3A, H3B and every other FSA that starts with H3. The project’s README gives the rule: the row of a whole FSA wins over the row of its first two characters, wherever the rows are in the file.
The project card says what is constructed and lists the checksums. The history was written to fit the habits that you practise here: an earlier issue, its fix, and the bug that the fix brought.
Set up the project
Section titled “Set up the project”-
Download the starter project from the box at the top of this page. Unzip it into
~/projects. You get the folderdelivery-slots. -
In VS Code, choose File > Open Folder and open
delivery-slots. Then open a terminal: Terminal > New Terminal. -
Make and activate a virtual environment, and install the tools from the lock file:
Terminal window python3 -m venv .venvsource .venv/bin/activatepython -m pip install -q -r requirements-lock.txtTerminal window python -m venv .venv.venv\Scripts\Activate.ps1python -m pip install -q -r requirements-lock.txtThe lock file installs pytest 9.1.1 and ruff 0.16.10, with four small packages that pytest needs. The program itself needs only Python.
-
Check your starting point:
Terminal window git statuspython -m pytestgit log --onelineOutput (the end of pytest, then the log) On branch mainnothing to commit, working tree clean======================================== 35 passed in 0.10s ========================================c709b52 Add issue 12: no evening slots for H3Z182a550 Add evening slots for the west zone, and this week's bookingsfc7e236 Accept postcodes typed without a space (fixes issue 3)ead395e Print the driver's list for a day and a zonea7f6c1c Book a slot for an order9fcf762 First version: list the slots of a postcode on a day
What this tells us. The tests pass and the tree is clean: this is the baseline from Repository preparation. The hashes are the same on every computer, because the course built the history with fixed authors and dates. All 35 tests pass although the bug is real. So the tests do not cover it, and a passing suite says nothing about issue 12.
Part 1: map first
Section titled “Part 1: map first”In a new town, you look at the map before you ask for directions. Then you understand the answer, and you notice when it is wrong.
A map of a codebase answers three questions. Which files are there, and what does each one do? Where does a command start? Which functions does the failing command go through? Make the map before any change. As Break work into steps showed, a change in code that you do not know is a guess.
Make the first map yourself. It takes five minutes:
git ls-filespython -m delivery_slots --helpusage: delivery_slots [-h] [--data DATA] [--now NOW] {slots,book,manifest} ...
Larkfield's delivery slots.
positional arguments: {slots,book,manifest} slots list the slots for a postal code on a day book book a slot for an order manifest print a driver's list for a day and a zone
options: -h, --help show this help message and exit --data DATA folder with zones.csv, slot-plan.csv and bookings.csv (default: data) --now NOW use this time instead of the clock, for example 2026-10-19T10:00The file list has delivery_slots/ (9 files), tests/ (7 files), data/ (3 CSV files) and issues/ (2 files). Read README.md and issues/12-no-evening-slots-for-h3z.md in full. They are short. They say what the program promises: three zones, a cut-off at 20:00 the day before, the rule for the rows of data/zones.csv, and evening slots for the west zone.
The assistant’s map
Section titled “The assistant’s map”Amira then asked the assistant for the same map, in ask mode, with no file in the chat. The assistant saw Aider’s repository map: the file names and their functions. Aider also asked to add cli.py, because the prompt names it. Her prompt, from the recorded transcript (the issue’s text is left out here):
Before anyone changes code, I need a map of the project. Please answer from therepository map:
1. In two or three lines: what does this project do?2. Each file in delivery_slots/, with one line on what it does.3. The functions that this command goes through, in order, from cli.py to the lines it prints:
python -m delivery_slots --now 2026-10-19T10:00 slots "H3Z 2Y7" --day 2026-10-20
Do not change any file, and do not guess the cause yet.The reply listed every file with a correct one-line role. It traced the command through cli.main, cli.load, cli.cmd_slots, zones.zone_for and slots.slots_for, and stopped there:
The actual zone, slot times, and availability cannot be established from the supplied file contents.Internal calls within the lookup and slot functions are also not visible in the repository map. Nofiles have been changed, and this does not diagnose the issue’s cause.That is a good map. But look at what happened next. The first answer said that the contents of __init__.py and __main__.py “have not been supplied”. Aider then offered to add the seven files that the answer named, and the second answer asked for four more. The recording answered yes to every question, so Aider added them and sent two more requests: 12 files in all. The last reply said: “My earlier statements that some contents were missing were incorrect”. Turn 1 cost 3 model calls and US$0.043, almost half of the whole session.
In your own session, you decide. The map was complete after the first call. “No, the map is enough” would have saved two calls.
Check the map against the code. Open delivery_slots/cli.py and find cmd_slots. It calls zones.zone_for, then slots.slots_for, then prints. The map is right. You now know where to look: the slots, or the zone.
Part 2: ask targeted questions
Section titled “Part 2: ask targeted questions”A targeted question names one function, one input and one expected fact, and asks for an answer from the code. “What is wrong?” invites a guess. “What does this function return for this input, and at which line?” asks for evidence that you can check.
Amira added three files: zones.py, postcodes.py and data/zones.csv. Her second prompt:
Targeted questions. For H3Z 2Y7 on Tuesday, the customer was offered 08:00-10:00,10:00-12:00 and 12:00-14:00. In data/slot-plan.csv, those are the city zone'sslots, not the west zone's.
1. Where in the code is the zone of a postcode decided? Name the function and the lines.2. Walk through that function for "H3Z 2Y7", with the rows of data/zones.csv in their order. Which zone does it return, and at which step?3. Which other areas in data/zones.csv get a wrong zone in the same way?
Answer from the code only. Do not change any file.In **`delivery_slots/zones.py`, `zone_for()`**, defined at line **28**. The deciding lines are**34–37**:...At line 36, `"H3Z2Y7".startswith("H3")` is `True`. **Line 37 immediately returns `"city"` on thefirst iteration.**
No subsequent rows are checked: `H2Y`, `H2Z`, `H2`, `H3N`, `H4`, `H3T`, `H3Y`, or `H3Z`. Inparticular, the final `H3Z,west` row is never reached.It also named H3N, H3T and H3Y as wrong in the same way. And it noted that H2Y and H2Z are not affected, because their rows come before the broader H2 row. The turn cost one call, US$0.013.
This is a precise claim. It is also only a claim. The next two parts check it with runs.
Part 3: reproduce, and read the history
Section titled “Part 3: reproduce, and read the history”Run the issue’s command, as Solange saw it on Monday at 10:00. The --now option replaces the clock:
python -m delivery_slots --now 2026-10-19T10:00 slots "H3Z 2Y7" --day 2026-10-20python -m delivery_slots --now 2026-10-19T10:00 slots "H4A 3L2" --day 2026-10-20H3Z 2Y7 is in zone city.Slots on Tuesday 20 October 2026 (orders close Monday at 20:00): 08:00-10:00 7 places left 10:00-12:00 9 places left 12:00-14:00 7 places leftH4A 3L2 is in zone west.Slots on Tuesday 20 October 2026 (orders close Monday at 20:00): 08:00-12:00 11 places left 18:00-20:00 5 places leftWhat this tells us. You see what Solange saw: three daytime slots and no evening. The first line says why: H3Z 2Y7 is in zone city. Her sister’s area gets the west zone’s slots, with the evening. The cut-off is not the cause: on Monday at 10:00 the orders were open. The slot plan is not the cause either: the west zone does have 18:00-20:00 on Tuesdays.
Who changed this line, and why?
Section titled “Who changed this line, and why?”git log lists commits. git blame goes one level deeper: for each line of a file, it shows the last commit that changed it. In unfamiliar code, it tells you why a line is as it is. That is often the fastest way to the cause.
git log --oneline -- delivery_slots/zones.pygit blame -s -L 28,38 delivery_slots/zones.pyfc7e236 Accept postcodes typed without a space (fixes issue 3)9fcf762 First version: list the slots of a postcode on a day^9fcf762 28) def zone_for(postcode: str, zones: dict[str, str]) -> str:^9fcf762 29) """The zone of a postal code, for example "west" for "H4A 1B2".^9fcf762 30)fc7e236b 31) Customers type postal codes with or without the space ("H4A 1B2", "h4a1b2"),fc7e236b 32) so the area is matched at the start of the postal code.^9fcf762 33) """fc7e236b 34) code = normalise(postcode).replace(" ", "")fc7e236b 35) for area, zone in zones.items():fc7e236b 36) if code.startswith(area):fc7e236b 37) return zone^9fcf762 38) raise UnknownPostcode(f"We do not deliver to {normalise(postcode)}.")Every line of the lookup comes from one commit: Luis’s fix for issue 3. Open issues/3-postcode-without-a-space.md. A customer typed H4A1B2 without the space. The first version split the postal code at the space, so it found no FSA. Luis’s fix matched the area at the start of the postal code instead. It fixed issue 3, and its test passes. It also made issue 12. See what it replaced:
git show fc7e236 -- delivery_slots/zones.pydef zone_for(postcode: str, zones: dict[str, str]) -> str: """The zone of a postal code, for example "west" for "H4A 1B2".
The row of the whole FSA wins over the row of its first two characters. Customers type postal codes with or without the space ("H4A 1B2", "h4a1b2"), so the area is matched at the start of the postal code. """ fsa = normalise(postcode).split(" ")[0] if fsa in zones: return zones[fsa] if len(fsa) == 3 and fsa[:2] in zones: return zones[fsa[:2]] code = normalise(postcode).replace(" ", "") for area, zone in zones.items(): if code.startswith(area): return zone raise UnknownPostcode(f"We do not deliver to {normalise(postcode)}.")The first version looked up the whole FSA first, then its first two characters. Its docstring stated the rule. Luis’s loop returns the first row that matches, in the order of the file, and the docstring line with the rule is gone.
Text description of the diagram
Five steps from left to right. The command of issue 12 goes to cli.cmd_slots, which asks zones.zone_for for the zone. That step is the cause: "H3Z2Y7" starts with "H3", the first row, so it returns city. Then slots.slots_for returns the city zone’s slots, which is correct for city. The customer sees three daytime slots and no evening slot: the symptom. Below the cause, data/zones.csv has H3, city in row 1 and H3Z, west in row 9, which is never reached. git blame shows that lines 34 to 37 come from commit fc7e236, the fix of issue 3.
Part 4: shrink it to the smallest input
Section titled “Part 4: shrink it to the smallest input”The issue’s input is a whole command with data files, a date and a clock. Reproduce first taught you to make it smaller until only the bug is left. Here, call the function directly. In VS Code, make a file shrink.py in the project folder:
from pathlib import Path
from delivery_slots.zones import load_zones, zone_for
zones = load_zones(Path("data") / "zones.csv")print("H3Z 2Y7 ->", zone_for("H3Z 2Y7", zones))
# Every area of the file, as a made-up postal code: which ones get another zone?# A two-character area gets an A, so H3 becomes H3A 1A1.for area, zone in zones.items(): fsa = area if len(area) == 3 else area + "A" got = zone_for(fsa + " 1A1", zones) if got != zone: print(f"{area}: file says {zone}, zone_for says {got}")
# The smallest input: two rows and one postal code.print(zone_for("H3Z 2Y7", {"H3": "city", "H3Z": "west"}))print(zone_for("H3Z 2Y7", {"H3Z": "west", "H3": "city"}))python shrink.pyH3Z 2Y7 -> cityH3N: file says north, zone_for says cityH3T: file says west, zone_for says cityH3Y: file says west, zone_for says cityH3Z: file says west, zone_for says citycitywestWhat this tells us. Every claim of turn 2 is true. H3N, H3T, H3Y and H3Z get the wrong zone, and the other 5 areas are right. The last two lines are the minimal failing input: two rows and one postal code. The same two rows in the other order give the right answer. So the result depends on the order of the rows, which a lookup should never do.
That is the new idea of this case study, in one picture:
Text description of the diagram
The same postal code, H3Z 2Y7 (H3Z2Y7 without the space), two lookups. Before the fix, row 1, H3, already fits the start of the postal code, so the loop stops and returns city. Rows 2 to 8 are never checked, and row 9, H3Z, west, is never reached. After the fix, the code tries the three-character rows first, then H3, H2 and H4. H3Z fits, so it returns west. An FSA without its own row, such as H3A 0G4, fits no three-character row, then fits H3, and gets city as before.
A first match (a prefix match) is right only when no row is the start of a row that comes later. Larkfield’s file breaks that rule: H3 is the start of H3N, H3T, H3Y and H3Z, and it comes first. H2 is the start of H2Y and H2Z too, but those rows come before H2, so they are right by luck. A correct lookup keeps the README’s rule in any order. Every FSA has three characters, so there are two simple ways: look up the whole FSA first and then its first two characters, or try the longest rows first.
Delete shrink.py: it was a probe, not part of the fix.
Part 5: write the failing test first
Section titled “Part 5: write the failing test first”Write the test before anyone changes the code, as in Choose meaningful checks. It must fail now, for the right reason, and pass after the fix. Use the four areas that the shrink found. Add this at the end of tests/test_zones.py:
@pytest.mark.parametrize( "postcode, zone", [ ("H3Z 2Y7", "west"), ("H3Y 1K5", "west"), ("H3T 1J4", "west"), ("H3N 2L8", "north"), ],)def test_fsa_rows_win(zones, postcode, zone): """Issue 12: "H3Z 2Y7" got the city zone's slots.""" assert zone_for(postcode, zones) == zonepython -m pytestE AssertionError: assert 'city' == 'north'...FAILED tests/test_zones.py::test_fsa_rows_win[H3Z 2Y7-west] - AssertionError: assert 'city' == 'w...FAILED tests/test_zones.py::test_fsa_rows_win[H3Y 1K5-west] - AssertionError: assert 'city' == 'w...FAILED tests/test_zones.py::test_fsa_rows_win[H3T 1J4-west] - AssertionError: assert 'city' == 'w...FAILED tests/test_zones.py::test_fsa_rows_win[H3N 2L8-north] - AssertionError: assert 'city' == '...=================================== 4 failed, 35 passed in 0.10s ===================================The four new cases fail with 'city', the bug itself. The other 35 still pass. Commit the test alone, so that the history shows it failing before any fix:
git add tests/test_zones.pygit commit -m "Add a failing test for issue 12: H3Z 2Y7 is in zone west"Part 6: fix it with the assistant
Section titled “Part 6: fix it with the assistant”Now Amira asked for the change. She switched Aider from ask mode to code mode, where it may edit files, with only zones.py and the test file in the chat. Aider could run the tests after its edit. Her prompt sets the limits:
I committed a failing test: test_fsa_rows_win in tests/test_zones.py.It fails four times. For example, zone_for("H3Z 2Y7", zones) returns "city";expected "west". `python -m pytest -q` prints "4 failed, 35 passed".
Fix zone_for so that these tests pass.- Change only delivery_slots/zones.py. Do not change the tests or the data.- Postal codes typed without a space must still work (issue 3, test_postcode_without_a_space).- Keep the change small. In two lines, say why it fixes the cause.Matching longer prefixes first prevents the broad H3 entry from hiding specific FSA mappings.Postcode normalization stays unchanged, so postcodes without spaces still work....Applied edit to delivery_slots/zones.py....................................... [100%]39 passed in 0.06sThe turn cost one call, US$0.015.
Without an assistant, or to use the recorded change: download fix-issue-12.patch into ~/projects, next to the project folder. Apply it, and run the checks:
git apply ../fix-issue-12.patchpython -m pytestruff check . && ruff format --check .======================================== 39 passed in 0.05s ========================================All checks passed!19 files already formattedWith your own assistant: do the same three steps. Ask for the map, then the targeted questions, then the fix with the same limits. Your change can differ from the recorded one; Part 8 gives you a way to judge it.
Part 7: review the diff
Section titled “Part 7: review the diff”git diff@@ -32,7 +32,7 @@ def zone_for(postcode: str, zones: dict[str, str]) -> str: so the area is matched at the start of the postal code. """ code = normalise(postcode).replace(" ", "")- for area, zone in zones.items():+ for area in sorted(zones, key=len, reverse=True): if code.startswith(area):- return zone+ return zones[area] raise UnknownPostcode(f"We do not deliver to {normalise(postcode)}.")Review it line by line, with the checklist of Inspect the diff:
- Needed lines. Both changed lines are needed. The loop now tries the longest areas first, so the three-character rows come before
H3,H2andH4. No other file changed. The docstring did not change. It is still true, but it does not state the rule that the code now keeps. - Changed contracts. The function still returns a zone or raises
UnknownPostcode. Its callers,cmd_slotsandbook, need no change. - Hidden assumptions. The longest match is right only because every area is the start of an FSA. And
sorted(zones, key=len)assumes that every key is text. What happens with a short or wrong postal code, or with a wrong key? - Behaviour that changed on purpose, without a test. The result no longer depends on the order of the rows. That is the README’s rule. But no test says so yet: the tests use the file in its one order.
For the hidden assumptions, Amira asked the assistant to review its own change (turn 4, ask mode). It listed seven inputs, for example:
| `"H3"` | Supplied CSV | `"city"` | An incomplete postcode is accepted because it matches a prefix.|| `"H3ZXYZ"` | Supplied CSV | `"west"` | Invalid trailing characters are not validated. || `"K1A 0B1"` | `{"": "west"}` | `"west"` | An empty prefix matches every postcode, includingotherwise unsupported ones. |Some of its inputs are postal codes in a wrong format. Others are wrong rows given to zone_for directly, such as the empty area "". The turn cost 2 calls, US$0.028: in the second call, the assistant asked for postcodes.py, which it already had.
Do not believe a review; run it. Make a file review.py with the seven inputs, and run it on the fix and on the old code. git stash puts your uncommitted change away for a moment, as in Ask for evidence:
from pathlib import Path
from delivery_slots.zones import UnknownPostcode, load_zones, zone_for
zones = load_zones(Path("data") / "zones.csv")cases = [ ("H3", zones), ("H3Z", zones), ("H3ZXYZ", zones), ("H3Z 2Y7", {"H3": "city", "h3z": "west"}), ("H3Z 2Y7", {"H3": "city", "H3Z ": "west"}), ("K1A 0B1", {"": "west"}), ("H3Z 2Y7", {3: "city"}),]for postcode, rows in cases: where = "the file" if rows is zones else rows try: print(f"{postcode!r:10} {where} -> {zone_for(postcode, rows)}") except UnknownPostcode as error: print(f"{postcode!r:10} {where} -> refused: {error}") except TypeError as error: print(f"{postcode!r:10} {where} -> TypeError: {error}")python review.pygit stash -qpython review.pygit stash pop -q'H3' the file -> city'H3Z' the file -> west'H3ZXYZ' the file -> west'H3Z 2Y7' {'H3': 'city', 'h3z': 'west'} -> city'H3Z 2Y7' {'H3': 'city', 'H3Z ': 'west'} -> city'K1A 0B1' {'': 'west'} -> west'H3Z 2Y7' {3: 'city'} -> TypeError: object of type 'int' has no len()'H3' the file -> city'H3Z' the file -> city'H3ZXYZ' the file -> city'H3Z 2Y7' {'H3': 'city', 'h3z': 'west'} -> city'H3Z 2Y7' {'H3': 'city', 'H3Z ': 'west'} -> city'K1A 0B1' {'': 'west'} -> west'H3Z 2Y7' {3: 'city'} -> TypeError: startswith first arg must be str or a tuple of str, not intWhat this tells us. Every claim that the assistant made is true. And the fix made none of these inputs worse. The old code gave the city zone to every short or wrong postal code, and it failed the same way on every wrong row. load_zones makes the keys capital letters and removes the spaces, so the wrong rows cannot come from the data file. A postal code in a wrong format is a separate problem, and the issue did not ask for it.
So Amira decided three things. Accept the fix. Write the format problem down as a new issue for the owners. And add two tests for what the fix changed on purpose. Delete review.py, then add at the end of tests/test_zones.py:
def test_an_fsa_row_without_a_space(zones): assert zone_for("h3z2y7", zones) == "west"
def test_the_order_of_the_rows_does_not_matter(): """An FSA row wins over the row of its first two characters, in any order.""" for rows in ({"H3": "city", "H3Z": "west"}, {"H3Z": "west", "H3": "city"}): assert zone_for("H3Z 2Y7", rows) == "west" assert zone_for("H3A 0G4", rows) == "city"python -m pytestgit add -Agit commit -m "Match the whole FSA first (fixes issue 12)"======================================== 41 passed in 0.08s ========================================Common mistake
'Just go back to the first version'
Symptom: after reading git blame, Tomás says that the bug came with Luis’s change. He restores the first version of zone_for, which split the postal code at the space. Issue 12’s four tests pass. Then the suite prints 1 failed, 38 passed: test_postcode_without_a_space fails.
Cause: the first version has the bug of issue 3. A customer who types H4A1B2 is told “We do not deliver to H4A1B2.” Undoing a change also undoes what it fixed. Here, Luis’s test caught it at once. Without that test, issue 3 would be back in production.
Fix: read the issue that a commit fixed before you undo the commit. A fix must keep both promises: the whole FSA wins, and postal codes work without a space. The course measured this candidate (constructed by the course team). It also fails 2 of the 12 rows of the area table in Part 8.
Part 8: compare the fixes under one measure
Section titled “Part 8: compare the fixes under one measure”Delphine saw the issue on Monday evening at the fair, and pushed her own fix to a branch, delphine/issue-12. You now have two fixes for one bug. Which one should the team keep?
The measure
Section titled “The measure”Tests that you wrote with a fix tend to agree with that fix. A fair comparison needs one measure that comes from the requirement, not from any fix. Here, it is an area table: 12 postal codes, each with the zone that data/zones.csv gives it, or “refused”. The README’s rule says that the row of a whole FSA wins “wherever the rows are in data/zones.csv”. So the table checks each postal code twice: with the rows in the order of the file, and in the reverse order. A row of the table passes only when both orders give the expected zone.
The table covers issue 12, issue 3, and both together (h3z2y7). It also has the other FSAs with their own rows, two FSAs that use a two-character row (H3A 0G4, H2W 1Y6), a part of Montréal that Larkfield does not serve (H1A 0A1), and another city (K1A 0B1).
Download area_table.py into ~/projects, next to the project folder. Run it on your fix:
python -m pytest -q --rootdir=. ../area_table.py............ [100%]12 passed in 0.01sThe maintainers’ fix
Section titled “The maintainers’ fix”Unzip the finished project into a new folder, ~/projects/finished, so that it does not replace yours. Then look at its history and at Delphine’s commit:
cd ~/projects/finished/delivery-slotsgit log --oneline --all --graphgit show delphine/issue-12 -- delivery_slots/zones.pycd ~\projects\finished\delivery-slotsgit log --oneline --all --graphgit show delphine/issue-12 -- delivery_slots/zones.py* 155cc2d Match the whole FSA first (fixes issue 12)| * 1f186ad Match the whole FSA first (fixes issue 12)| * c94484f Add a failing test for issue 12: H3Z 2Y7 is in zone west|/* c709b52 Add issue 12: no evening slots for H3Zdef fsa_of(postcode: str) -> str: """The FSA of a postal code: "H3Z 2Y7" -> "H3Z", "h3z2y7" -> "H3Z".
The FSA is the first three characters of a Canadian postal code (a letter, a digit, a letter), so this works with and without the space. """ return normalise(postcode).replace(" ", "")[:3]
def zone_for(postcode: str, zones: dict[str, str]) -> str: """The zone of a postal code, for example "west" for "H4A 1B2".
The row of the whole FSA wins over the row of its first two characters, wherever the rows are in data/zones.csv: H3Z is not H3. """ fsa = fsa_of(postcode) for area in (fsa, fsa[:2]): if area in zones: return zones[area] raise UnknownPostcode(f"We do not deliver to {normalise(postcode)}.")Delphine’s rule gives the same answers as the assistant’s, but she wrote it another way: two exact lookups, the whole FSA first and then its first two characters, with no loop over the rows. She gave the FSA a name, fsa_of, with its own tests, and a docstring that states the rule. One of her tests reverses the rows of the file. Her commit also adds a note to issue 12: three bookings of this week are on the wrong van. Open issues/12-no-evening-slots-for-h3z.md on her branch to read it.
The comparison
Section titled “The comparison”The course measured five versions of the project, each in a fresh copy of the starter. Every version ran the same 39 tests (the starter’s 35 and your 4) and the area table. Two versions are first ideas that the course team wrote, labelled constructed.
- Real code (the starter, the recorded session)
- Constructed by the course team
Text description of the chart
A column chart with five columns. The unfixed code passes 6 of 12 rows. Going back to the first version passes 10. Moving the FSA rows to the top of the data file passes 6. The assistant’s fix passes 12, and the maintainers’ fix passes 12.
| Version | The change | The 39 tests | Area table | Rows that fail |
|---|---|---|---|---|
| unfixed (baseline) | – | 35 passed, 4 failed | 6 of 12 | H3Z 2Y7, h3z2y7, H3Y, H3T, H3N; and H2Y in the reverse order |
| back to split (constructed) | code +6 −6 | 38 passed, 1 failed | 10 of 12 | h3z2y7, H4A1B2: issue 3 is back |
| reorder the file (constructed) | no code; 6 rows of data/zones.csv moved |
all 39 passed | 6 of 12 | the same six as unfixed, in the reverse order |
| the assistant’s fix (real) | code +2 −2 | all 39 passed | 12 of 12 | none |
| the maintainers’ fix (constructed) | code +15 −6 | all 39 passed | 12 of 12 | none |
What this tells us.
- The tests could not tell two of these apart. “Reorder the file” moves the six FSA rows above
H3,H2andH4. The first match then finds them first, so it passes all 39 tests, issue 12’s tests too. But the code still depends on the order of the rows. The next person who adds a row at the end of the file can bring the bug back. In the reverse order, it fails the same six rows as the unfixed code. Only the area table, written from the README’s rule, shows it. - The assistant’s fix and the maintainers’ fix behave the same. They give the same result for all 12 rows in both orders, and for every short or wrong postal code of Part 7. The maintainers’ fix is larger because it adds a named function, its tests and a note.
- The size of a diff is not the measure. “Reorder the file” changes no code at all, and it only hides the bug. “Back to split” removes as many lines as it adds, and it breaks issue 3.
The recommendation
Section titled “The recommendation”Merge one fix, and close the other with thanks: both keep the same rule. Amira’s fix should go first, because customers in H3N, H3T, H3Y and H3Z are affected now. Its pull request names the four FSAs, the test that failed first and the area table, as in Independent comprehension. When Delphine is back, the team can add her fsa_of and her two exact lookups as a small refactor on top, if they find them clearer than a sort. That is a separate change with its own review.
Two things in Delphine’s version came from knowing the business, not the code. She stated the rule in the docstring, and she thought about bookings that were already made. The issue asked for neither. The next part shows that the second one matters.
Part 9: run it end to end on new input
Section titled “Part 9: run it end to end on new input”Go back to your own project, ~/projects/delivery-slots. Run the whole flow as the checkout and the depot do. Use new inputs, not the ones of your tests: Solange’s order, a new customer in H3N who types without a space, and a customer outside the zones. The time is Monday 15:00, before the cut-off:
python -m delivery_slots --now 2026-10-19T15:00 slots "H3Z 2Y7" --day 2026-10-20python -m delivery_slots --now 2026-10-19T15:00 slots h3n2l8 --day 2026-10-21python -m delivery_slots --now 2026-10-19T15:00 book L-40213 "H3Z 2Y7" --day 2026-10-20 --start 18:00python -m delivery_slots --now 2026-10-19T15:00 book L-40214 "H1A 0A1" --day 2026-10-20 --start 08:00python -m delivery_slots manifest --day 2026-10-20 --zone westpython -m delivery_slots manifest --day 2026-10-20 --zone cityH3Z 2Y7 is in zone west.Slots on Tuesday 20 October 2026 (orders close Monday at 20:00): 08:00-12:00 11 places left 18:00-20:00 5 places leftH3N2L8 is in zone north.Slots on Wednesday 21 October 2026 (orders close Tuesday at 20:00): 08:00-12:00 11 places left 12:00-16:00 11 places leftBooked order L-40213: H3Z 2Y7, zone west, Tuesday 20 October 2026 at 18:00.Error: We do not deliver to H1A 0A1.Zone west, Tuesday 20 October 2026: 3 deliveries 08:00 L-40124 H4A 1B2 18:00 L-40126 H4A 3L2 18:00 L-40213 H3Z 2Y7Zone city, Tuesday 20 October 2026: 5 deliveries 08:00 L-40115 H3B 4W8 08:00 L-40118 H2Z 1B1 08:00 L-40121 H3Y 1K5 10:00 L-40128 H3G 1M8 12:00 L-40131 H3T 1J4What this tells us. Solange’s order is booked on Tuesday evening, on the west van with her sister’s. A postal code typed without a space gets the north zone. H1A 0A1 is refused, with exit code 1, as before. But the city driver’s list still has H3Y 1K5 and H3T 1J4. Those customers booked before the fix, and each booking keeps the zone that it got then. The fix stops new mistakes. It does not move old bookings.
To find them all, make wrong_zone.py. It compares each booking’s zone with the zone that the fixed code gives today:
from pathlib import Path
from delivery_slots.bookings import load_bookingsfrom delivery_slots.zones import load_zones, zone_for
zones = load_zones(Path("data") / "zones.csv")for b in load_bookings(Path("data") / "bookings.csv"): right = zone_for(b.postcode, zones) if b.zone != right: print(f"{b.order} {b.postcode:9} {b.day} booked in {b.zone}, should be {right}")L-40107 H3N 2L8 2026-10-19 booked in city, should be northL-40121 H3Y 1K5 2026-10-20 booked in city, should be westL-40131 H3T 1J4 2026-10-20 booked in city, should be westThese are the same three orders as in Delphine’s note. Send the list to Grace, so that the help desk can move them. Then delete wrong_zone.py, and undo the booking with git restore data/bookings.csv. In the real shop, the checkout makes the booking, not your copy of the data.
Insights and limits
Section titled “Insights and limits”Text description of the diagram
Nine steps. The assistant made the map (3 calls) and answered the targeted questions (1 call). It made the fix (1 call, 39 passed) and reviewed it: all seven claims were true when run. Amira reproduced the bug and shrank it to two rows of data. She wrote the failing test (4 failed, 35 passed). She compared the fixes: 12 of 12 for both full fixes, 6 of 12 for “reorder the file”. Then she ran it end to end: Solange was booked, and three old bookings were on the wrong van. The session cost US$0.099 in total.
- The symptom was far from its cause. The slots were right; the zone was wrong, because of the row order. The map and one targeted question found it faster than reading every file.
- The history explained the bug, and an old test stopped the obvious fix from bringing issue 3 back.
- Passing tests are not the measure. “Reorder the file” passed all 39 tests. The area table, written from the README’s rule, caught it.
- The assistant was useful and checkable. Its map, trace, fix and review were correct. Twice it asked for files that it already had: in turn 1 that cost two extra calls, and in turn 4 one more. The whole session cost US$0.099 at the deployment’s price when it was recorded: 7 calls, 36,069 tokens in and 2,701 out. Prices change. With a free tier or no assistant, you pay nothing.
- Limits. The project and the maintainers’ fix are written for the course. There is one recorded session: another run, model or assistant can give a different fix, and the area table is how you judge it. The fix does not check the postal code format:
H3alone still gets the city zone. It does not move bookings that were already wrong. Everything was tested on macOS only.
Responsible use
Section titled “Responsible use”- Customer data in prompts. Amira’s first prompt pasted the whole issue, with Solange’s name, postal code and order number. Here the data is invented. In a real company, that sends personal data to a model provider. Check your company’s rules first. Send only what the question needs: the FSA
H3Zand the observed slots, not the customer’s email. - The data is personal too.
data/bookings.csvhas postal codes and order numbers. Do not paste it into a prompt, and do not let an assistant run scripts against the real booking system.wrong_zone.pyonly reads a copy, and a person decides what to move. - Code that belongs to another team. Amira fixed code that Delphine and Luis own, while they were away. She worked on a branch, wrote the failing test first, kept the diff small, and left the merge to the team’s normal review. Fix the bug, not the codebase: the refactor and the format check are separate issues for the owners.
- Say how you worked. The pull request says that an assistant wrote the two changed lines. It also gives the limits of the prompt, and how each claim was checked.
Make it a portfolio piece
Section titled “Make it a portfolio piece”Publish your finished project in a public repository. It has the MIT licence, so keep the LICENSE file. Add a CASE-STUDY.md:
# Fixing a bug in an unfamiliar codebase, with a coding assistant
## ProblemIssue 12: a customer in H3Z got the city zone's slots, with no evening slot.
## ApproachMap first, targeted questions, reproduce, shrink to two rows, failing test first,assistant fix inside written limits, review by running, one measure for every fix.
## Results4 failing tests → 41 passing; area table 12 of 12 (unfixed: 6; "reorder the file": 6,although it passed every test). Three bookings made before the fix were on the wrongvan: listed for the help desk.
## What the assistant did, and how I checked itMap, trace, fix (+2 −2 lines) and a self-review: every claim checked by a run.
## LimitsNo postal code format check yet (H3 alone still gets city). One recorded session.In two sentences, for an interview: “I fixed a customer’s bug in a codebase that I had never seen. I used an assistant for the map, the fix and a review, checked every claim with a run, and wrote the failing test first. A table of postal codes from the data and the README’s rule showed that a fix which passed every test still depended on the order of the rows.”
Go further:
- Write issue 13, “Check the postal code format”, with its own failing test for
H3, and fix it. - Turn
wrong_zone.pyinto acheck-bookingscommand with a test, as a separate pull request. - The cut-off uses local time without a time zone. Find out what happens on the night when the clocks change, and write it as an issue.
Knowledge check
Section titled “Knowledge check”Check your understanding
Sign in and enroll in the course to save your answers. Every check counts toward the certificate.
Check your understanding
Sign in and enroll in the course to save your answers. Every check counts toward the certificate.
Check your understanding
Sign in and enroll in the course to save your answers. Every check counts toward the certificate.
Recap
- Map first, yourself, then with the assistant, and check its map against the code.
- Targeted questions name one function and one input. Every answer is a claim: check it with a run.
- Reproduce, read the history, shrink:
git blameled to issue 3; two rows of data showed that the first match depended on their order. - Failing test first (4 failed, 35 passed), then the assistant’s fix inside written limits (39 passed).
- Compare under one measure from the requirement: 12 of 12 for both full fixes, 6 for “reorder the file”, which passed every test.
- End to end on new input showed what the fix cannot do: three bookings were already on the wrong van.
Next, the other case study: move a small project across a breaking change of a dependency. Check each suggested change against the changelog and the tests.