AI & Machine Learning Bug Report

AI-generated installment split passed review, then lost a cent in production

An AI-written function split payments into installments by rounding each part. It looked right, its tests used amounts that divide evenly, and both an AI reviewer and a human approved it. Production totals drifted by a cent. One property test would have caught it.

Elena Kovač Elena Kovač @elenakovac · November 24, 2026 · 7 min read · 157 Views
620-ai-generated-code-passed-review-failed-prod

The nightly ledger reconciliation job started failing four days after we released "pay in installments". The alert came from our own job, not from a customer:

reconcile.mismatch order_id=ord_8KZ2 expected_cents=10000 scheduled_cents=9999 plan=3x
reconcile.mismatch order_id=ord_8L0Q expected_cents=5000 scheduled_cents=5001 plan=3x
reconcile summary: checked=18422 mismatched=1137 max_abs_diff_cents=3

About six percent of installment orders had schedules that did not add up to the order total. The difference was never more than a few cents, and it went in both directions.

Reproducing it

The function that builds the schedule was short:

def split_amount(total: float, parts: int) -> list[float]:
    """Split a total into equal installments."""
    each = round(total / parts, 2)
    return [each] * parts
>>> split_amount(100.00, 3)
[33.33, 33.33, 33.33]          # sums to 99.99
>>> split_amount(49.99, 6)
[8.33, 8.33, 8.33, 8.33, 8.33, 8.33]   # sums to 49.98

Any total that does not divide evenly by the number of parts loses or gains the rounding remainder.

What we ruled out

  • Float drift in the ledger. The ledger stores integer cents; the mismatch was in the schedule rows.

  • Currency conversion. Mismatches occurred in single-currency orders.

  • A race between schedule creation and order edits. Re-running the split on the stored totals reproduced every mismatch exactly.

Root cause

The function was written by an AI coding agent from the ticket "split the order total into N equal installments". It interpreted "equal" literally and rounded each part, which is the most common pattern for this problem in general code. Its unit tests used totals of 100.00 split into 2, 4 and 5, all of which divide evenly. An AI reviewer approved the change with comments on naming and type hints, and a human reviewer approved it because the code was readable and the tests passed. Nobody, human or model, asked where the remainder goes.

What is happening under the hood

There are two separate mistakes in four lines:

  1. Rounding each part independently. If total / parts is not a whole number of cents, every part carries the same rounding error, and the sum is off by up to parts / 2 cents. For 100.00 over 3, each part loses a third of a cent, and three parts lose one cent.

  2. Using floats for money. round() on binary floats also behaves unexpectedly at halves: round(2.675, 2) returns 2.67, because 2.675 cannot be represented exactly and is stored slightly below. This did not cause the incident but would have caused others.

The correct approach is to work in integer minor units and distribute the remainder explicitly, so the parts differ by at most one cent and always sum to the total.

Why review missed it

This is the part we care about most. The code was not careless; it was plausible. Three things lined up:

  • The tests came from the same reading as the code. The agent that wrote the function wrote the tests, choosing "nice" amounts. Every test passed because every test avoided the remainder.

  • The AI reviewer shared the interpretation. It saw a function that does what its docstring says. "Equal installments" and [each] * parts match perfectly.

  • The human reviewed the code, not the invariant. The diff was small and clean. The question "do the parts sum to the total for every input?" is not visible in the code; it lives in the domain.

Environment

Component

Version / value

Runtime

Python 3.12

Framework

Django 5.1

Test runner

pytest 8.3

Money storage

Integer cents in the ledger, float in the schedule builder

Change origin

AI coding agent, reviewed by an AI reviewer and one engineer

Minimal reproduction

def test_split_is_exact_for_uneven_totals():
    assert sum(split_amount(100.00, 3)) == 100.00   # fails: 99.99

Who is affected

Any code that divides money into parts and rounds each part: installments, bill splitting, tax allocation across line items, revenue sharing between authors, discount distribution. The same bug appears when a discount is spread across items and each item's share is rounded.

The fix

Work in integer cents and give the remainder to the first parts:

def split_amount(total_cents: int, parts: int) -> list[int]:
    """Split total_cents into `parts` installments that differ by at most 1 cent
    and always sum to total_cents. Earlier installments take the extra cents."""
    if parts < 1:
        raise ValueError("parts must be >= 1")
    if total_cents < 0:
        raise ValueError("total_cents must be >= 0")
    base, remainder = divmod(total_cents, parts)
    return [base + 1 if i < remainder else base for i in range(parts)]
>>> split_amount(10000, 3)
[3334, 3333, 3333]
>>> split_amount(4999, 6)
[834, 833, 833, 833, 833, 833]

We changed the call site to pass the order's stored cents instead of a float, and added the rule "the first installment absorbs the remainder" to the product specification, so support could explain it to customers.

Alternatives and trade-offs

  • Put the remainder on the last installment if your business prefers a smaller first charge. Any deterministic rule works as long as it is written down.

  • decimal.Decimal with explicit rounding keeps decimal amounts, but you still need to distribute the remainder. Integer cents are simpler and match how the ledger stores money.

  • Currencies with different minor units (for example JPY with zero decimals, some with three) need the exponent from the currency, not a hard-coded 100. We read it from our currency table.

How to test the fix

The property test states the invariants directly and lets Hypothesis find inputs:

from hypothesis import given, strategies as st
from billing.split import split_amount

@given(total=st.integers(min_value=0, max_value=10**10),
       parts=st.integers(min_value=1, max_value=60))
def test_split_invariants(total, parts):
    result = split_amount(total, parts)
    assert len(result) == parts
    assert sum(result) == total                  # nothing lost or created
    assert max(result) - min(result) <= 1        # as equal as possible
    assert result == sorted(result, reverse=True)  # remainder goes first

Run against the original function (converted to cents), this test fails within a few examples; Hypothesis shrinks the failure to the smallest case, total=1, parts=2. That is the test that would have caught the bug in review.

pytest tests/billing/test_split.py -q

We also kept named examples from the reconciliation alerts as regression tests.

Confirming in production

We regenerated schedules for unpaid installments using the fixed function and adjusted the next charge for partially paid ones, with an audit record per order. The next reconciliation run reported:

reconcile summary: checked=18901 mismatched=0 max_abs_diff_cents=0

It has stayed at zero since.

Regression guard

  • The property test runs in CI on every change to billing/.

  • A rule script fails CI on float annotations or round( calls inside billing/ and payments/.

  • The adversarial reviewer prompt now includes "for any function handling money, check that totals are preserved for amounts that do not divide evenly".

  • The product spec template for money features has an "invariants" section that must be filled in before work starts.

Security implications

The bug could undercharge or overcharge by a few cents per order, which is a financial accuracy and compliance problem rather than a security hole. Rounding errors in money code can become one, though: if a customer can choose the number of parts or trigger many small splits, systematic rounding in their favour is a known abuse pattern. Keeping totals exact removes that possibility. The fix itself adds input validation for negative totals and zero parts.

Prevention checklist

  • Store and compute money in integer minor units; convert only for display.

  • Any split or allocation must preserve the total; state that as a property test.

  • Have tests written from the specification, not by the agent that wrote the code.

  • Ask reviewers, human or AI, to check invariants, not just readability.

  • Reconcile totals automatically so drift is caught in days, not at audit time.

References

Add a label

#python #payments #code-review #hypothesis #rounding
Written by
Elena Kovač @elenakovac

I work as a site reliability engineer, which in practice means I spend a lot of time asking whether the graph in front of us is actually telling the truth. I have built observability stacks on Prometheus, Grafana, Loki and OpenTelemetry for teams from five engineers to several hundred. Many of the incidents I have worked on were made longer by monitoring that looked fine: averaged percentiles, empty panels, traces that stopped at a queue. The posts here explain the mechanism behind each misleading signal, the query or configuration that fixes it, and how to set SLOs that reflect what users really experience.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.