Product case study · November 24, 2026

Ask Claude Code why grouping orders loses a customer's total

Python groupby groups adjacent records. Reproduce a missing customer total, ask Claude Code for a bounded fix, and check it with six regression tests.

Reading time
6 min
Checked
Nov 24, 2026
Superbash Learn default cover on warm paper, with the words Practical AI lessons without the hype fog.
Matching records belong in the same total even when they arrive apart.
Bottom line

For totals across an unsorted batch, accumulate by key. A test that separates matching customers is more useful than another sorted sample.

Two orders from the same customer should make one total. Put another customer’s order between them, though, and this Python report quietly forgets the first order. There is no exception to send the coding agent. The output just looks smaller than it should.

That makes this a useful Claude Code exercise: the bug disappears when the sample data is neatly sorted. The best test is a messy arrival order.

You’ll need Bash on macOS, Linux or WSL, Python 3, and an installed, signed-in Claude Code. The fictional order data, broken fixture and reference repair below were tested locally. The Claude prompt is an authored exercise, not a recorded agent run. Official documentation was checked November 24, 2026.

Make a total disappear

Create a disposable folder and save the broken implementation:

group_lab=$(mktemp -d /tmp/claude-groupby.XXXXXX)
cd "$group_lab"
cat > totals.py <<'PY'
from itertools import groupby


def totals_by_customer(rows):
    return {
        customer: sum(amount for _, amount in group)
        for customer, group in groupby(rows, key=lambda row: row[0])
    }


if __name__ == "__main__":
    orders = [("oak", 1200), ("elm", 500), ("oak", 800)]
    print(totals_by_customer(orders))
PY
python3 totals.py

The amounts are fictional integer cents. Oak’s two orders should total 2000, but the broken demo prints:

{'oak': 800, 'elm': 500}

Python’s itertools.groupby reference explains the catch: it groups consecutive records with equal keys. A key change starts a new group. Unlike SQL’s GROUP BY, it does not collect matching records from across an unsorted input.

Here, the three groups are Oak, Elm, then Oak again. The dictionary comprehension assigns Oak twice, so the last subtotal replaces the first. The grouping operation and the dictionary assignment each behave as designed; their combination breaks our reporting requirement.

I would keep the awkward order in the reproduction. Sorting the demo before asking the agent for help hides exactly the failure you need it to understand.

Fix the contract before the code

Save this as SPEC.md in the same folder:

totals_by_customer(rows) accepts a finite iterable of
(customer_id, amount_cents) pairs: string IDs and integer amounts.
Return a dictionary with one total per distinct customer ID.
Sum every occurrence, including identical duplicate rows.
Support any arrival order, lists and one-shot iterators.
Allow negative adjustments and retain customers whose total is zero.
Empty input returns an empty dictionary.
Do not reorder or modify a caller's input list.
Dictionary iteration order is not part of this contract.
Malformed rows and non-integer amounts are outside this exercise.
Change only totals.py. Keep SPEC.md and test_totals.py fixed.
Use the standard library; no dependencies, network calls or data files.

Duplicate rows matter here. Two identical orders still contribute twice. An agent that removes duplicates to make the report look cleaner has changed the job.

Save these six tests as test_totals.py:

import unittest
from itertools import permutations
from totals import totals_by_customer


class TotalsTests(unittest.TestCase):
    def test_separated_customer(self):
        rows = [("oak", 1200), ("elm", 500), ("oak", 800)]
        self.assertEqual(totals_by_customer(rows), {"oak": 2000, "elm": 500})

    def test_every_arrival_order(self):
        rows = [("oak", 1200), ("elm", 500), ("oak", 800)]
        for ordering in permutations(rows):
            with self.subTest(ordering=ordering):
                self.assertEqual(
                    totals_by_customer(ordering), {"oak": 2000, "elm": 500}
                )

    def test_duplicates_count_twice(self):
        rows = [("oak", 400), ("elm", 100), ("oak", 400)]
        self.assertEqual(totals_by_customer(rows), {"oak": 800, "elm": 100})

    def test_negative_and_zero_totals(self):
        rows = [("oak", 300), ("elm", -50), ("oak", -300)]
        self.assertEqual(totals_by_customer(rows), {"oak": 0, "elm": -50})

    def test_empty_and_one_shot_inputs(self):
        self.assertEqual(totals_by_customer(iter(())), {})
        rows = iter([("oak", 2), ("elm", 3), ("oak", 4)])
        self.assertEqual(totals_by_customer(rows), {"oak": 6, "elm": 3})

    def test_input_list_unchanged(self):
        rows = [("oak", 1200), ("elm", 500), ("oak", 800)]
        before = list(rows)
        totals_by_customer(rows)
        self.assertEqual(rows, before)

Run the baseline:

python3 -m unittest -v test_totals

The broken version fails five test methods; only the input-preservation test passes. The arrival-order test reports individual failed subtests too, so the failure count in the summary can exceed five. These assertions make the intended behavior visible before the agent edits anything. Python documents this command and its verbose output in the unittest guide.

Give Claude the failing command and a narrow edit

Start claude from the practice folder. If you need setup help, use our first-project lesson. Then send:

Read SPEC.md, totals.py and test_totals.py.
Run python3 -m unittest -v test_totals to reproduce the failure.
Explain why oak loses its first amount and why sorted sample data hides it.
Repair only totals.py to meet SPEC.md. Do not change or weaken tests.
Do not assume rows is a list or sort a caller's list in place.
Run the same test command again and run python3 totals.py.
Report the files changed, test results and any remaining limitations.
Do not install dependencies, commit, publish or access the network.

This follows Anthropic’s debugging workflow: give the agent reproduction steps and the command that exposes the problem. Review proposed tool actions in your session; the prompt describes the task boundary, but does not create a sandbox.

Review the repair against the job

One reference repair replaces the import and function with this code, leaving the demo below it intact:

def totals_by_customer(rows):
    totals = {}
    for customer, amount in rows:
        totals[customer] = totals.get(customer, 0) + amount
    return totals

Each order adds to the total already stored for that customer. Oak’s second appearance adds 800 to 1200 instead of assigning a replacement subtotal. The function consumes its input once and stores one running total per customer.

An agent may instead sort a copy of the rows by customer before grouping them. That can satisfy this contract too: Python’s sorting guide distinguishes sorted(), which produces a new list, from list.sort(), which changes the original list. Sorting and grouping must use the same customer key.

For this job, I prefer the accumulator. It needs no ordering step and makes the requirement, “add every order,” easy to review. Keep groupby for jobs where adjacent runs are meaningful, or where the data is already grouped for a reason.

Exit Claude and rerun the checks yourself:

python3 -m unittest -v test_totals
python3 totals.py

With the reference repair, all six tests pass and the demo prints:

{'oak': 2000, 'elm': 500}

If the agent reports success but you still see 800, check the file it edited and the folder where you ran Python. If the input-preservation test fails, look for an in-place sort. If only sorted inputs pass, keep the original interleaved sample and ask the agent to explain each assignment to Oak’s total.

The tests cover the stated exercise, not malformed exports or currency conversion. Keep those requirements separate until they are defined. The useful habit to take into your next agent task is smaller: whenever a report promises totals independent of arrival order, move the same records around and check that the totals stay put.

Sources

Checked November 24, 2026:

Put this to work

Why itertools.groupby groups consecutive runs instead of every matching key in a batch.

Try

Repair a small order-summary function in a disposable Python folder.

Prove it worked

Run the unchanged tests before and after the repair, including every ordering of the sample.

Keep in view

  • Reproduce a customer total overwritten by a later group.
  • Give Claude Code a fixed contract and six regression tests.
  • Verify unsorted input, duplicates, negative adjustments and input preservation.
Learn the workflow: Start your first Claude Code project session