SENIORCHAPTER 24

Testing money: invariants, reconciliation and evidence for a regulator

Tests before release prove the arithmetic. A reconciliation after release proves the books. An evidence file proves the reconciliation ran, and you have to design all three

60 MINSOFTWARE TESTING AND QUALITYUPDATED 2026-11-24
PREDICT

Your reconciliation takes every order in the database, asks the payment provider for that order's charge, and checks the amount. All 6 orders match. The provider's own count says it holds 7 charges. What does the script print?

Money code fails in a particular way. A rounding bug in a total does not crash anything. The checkout answers 200, the card is charged, and the order is saved with an amount that is one kobo off. Nothing logs an error. You find it when a finance analyst sums a day and the sum disagrees with the bank, or when it does not and nobody ever finds it. That changes what testing is for. Tests before release prove that your arithmetic follows your rules. They cannot prove that your records agree with the world’s, because the world has a provider, a bank and a clock that you do not control. So money needs two kinds of check and a way to prove the second ran.

This chapter does not re-teach the money topics. The reasons floats fail are in the lesson on money in floating point, and sharing a remainder is in the residual cent. The mechanics of matching three records, with the four kinds of break and how each is posted, are in the Payments chapter on reconciliation. Double-entry bookkeeping, the deepest invariant, is its own chapter, and moving money exactly once is another. The QA career track’s chapter, Testing money and regulated systems, covers the role: who owns the reconciliation and signs the evidence. This chapter is the craft in between: what to assert, how to write the comparison, and what to keep.

Three checks, three times

Check Runs Compares Finds
Invariant test Every build The code against a rule that must hold for all inputs Arithmetic bugs, before they ship
Reconciliation Every day, in production Your records against the provider’s Bugs and failures that got through, plus things you cannot test: a provider that changed
Evidence With every reconciliation run Nothing: it records that the others ran The ability to prove it to someone else

Each covers a hole in the others. An invariant cannot see a provider that quietly changed what it returns. A reconciliation cannot see a bug that is right on both sides, such as a total that both your service and your provider agree to charge, and that is wrong. Evidence cannot see either. A team that has only the first fails the day a provider misbehaves, and a team that has only the second finds every arithmetic bug a day late and in production. A team with the first two and no evidence is good at its job and cannot show it, which is where Owoleaf’s team was.

Invariants: what must always be true

An invariant is a statement that holds for every input. It does not name an amount. Money has a short list, and labs/testing can state most of it in a few lines each.

The quote adds up. For every cart, net is the subtotal minus both discounts, and total is net + vat + delivery_fee. If a future change adds a surcharge to one field and forgets the total, no example you thought of may catch it. A random cart will.

Everything is whole kobo. Every figure in a quote is an int and is not negative. Test type(value) is int, not isinstance, because Python’s bool is an int and a float that sneaks in must fail loudly. The floating-point lesson shows why a float anywhere in the chain is a bug waiting for an amount that exposes it.

Rounding is within half a kobo. The rule in checkout/money.py is that VAT is 7.5% rounded half up. You can state its error bound without restating the rule: the VAT charged is never further than half a kobo from the exact figure. To keep the check in integers, compare scaled by 10,000: abs(vat * 10000 - net * 750) <= 5000. A test that recomputes the formula would copy the code’s mistakes. A bound does not.

A split loses nothing. Any division of a total into parts sums to the total, and the parts differ by at most one kobo. The lab has one real splitter, the old instalment scheduler in checkout/legacy.py. The test below looks only at its amounts, so it works whatever the dates do.

An order matches its charge. The order’s stored total equals the amount sent to the provider, and a retry with the same idempotency key creates no second order and no second charge.

Most of these need generated inputs, which is what property-based testing provides: Hypothesis builds hundreds of carts, you state the rule, and it shrinks a failure to the smallest example. The first chapter of this module, Property-based testing, teaches the tool. Here you use it as it comes, to check money.

Random search has a blind spot, and money rules are full of cliffs. You have met this one. In the property-based testing chapter Hypothesis found the 5% tier cliff: 39 units at ₦250 cost more than 40. It found it because the strategy was aimed at the edge, with prices that divide ₦10,000 exactly so a short cart can land on it, and the plain random version of the same property passed. Here the property is a different one, built to show the blind spot from the other side. Consider the claim that adding a line to a cart never lowers the total. It sounds right. Ojaline’s discount tiers make it false: a subtotal of ₦9,999.99 pays no discount, and a subtotal of ₦10,000.00 gets 5% off, so adding one kobo of goods lowers the total by about ₦537. Hypothesis, run six times with different seeds in the lab and with no edge strategy, never found it, because a cart that lands within a few kobo below a boundary is one input in a million. Here you do not build an edge-shaped strategy, so the generator has nothing to aim with. An explicit example at the boundary found it at once. Two lessons follow. Put every boundary of every rule into your tests as an explicit example, beside the generated ones. And when the invariant fails, the code may not be the thing that is wrong. A tier discount that rewards spending more can be a deliberate rule. Someone who owns pricing decides, and the test is marked as a known exception with the reason, so the next person does not rediscover it.

Reconciliation: the test that runs in production

Tests before release check the code against your understanding. A reconciliation checks your records against someone else’s, every day, on real data. Its definition has to be as exact as a test’s:

  • Population. Every row in orders.
  • Against what. The provider’s record of the charge, fetched by GET /v1/charges/{id}.
  • Match key. The order’s charge_id, then the amount in kobo, the reference and the status. A match on amount alone would pair two different orders of ₦9,025.00.
  • Tolerance. None. Kobo are integers on both sides, so a difference of one kobo is a difference.
  • When it counts as a break. Anything that does not match, and also anything that stops the run from happening.

The comparison goes both ways, and the lab’s provider makes the second way hard. The lab’s fake provider has no list route. You can fetch a charge you know the id of, and you can ask GET /_admin/stats for how many it holds. A real provider’s equivalent is a settlement file or a list endpoint, which is what you would loop over. Here, the count has to stand in. If the provider holds more charges than your orders account for, something was charged that you do not know about, and that is a break of its own kind. Notice the limit of this: a count tells you how many, and not which. Write that into what you tell an auditor.

Think about every way the two sides can disagree, and give each a name, because the break report is what people act on:

Break Meaning Who is hurt
missing_at_provider An order points at a charge the provider has not heard of You: goods shipped, possibly no money
amount_mismatch Order and charge disagree on the amount Whoever is under-paid
reference_mismatch The provider’s reference is not the order’s key The next investigator, who cannot trace the charge
status_mismatch The provider’s status is not succeeded You: an order marked paid for a charge that did not succeed
charge_used_twice Two orders share one charge You: one payment, two parcels
count_mismatch The provider holds charges your orders do not account for The customer: charged, nothing delivered

The script reports the gross value of the breaks, the sum of the absolute amounts, and not the net. A break of +5 kobo and a break of -5 kobo net to nothing, and two orders are still wrong. The career chapter makes the same point for settlement files, and the Payments chapter on reconciliation shows nine breaks worth ₦122,863.39 gross netting to ₦30,947.35.

Finally, the run must say when it did not run. If the provider is down, the script that loops, catches an error, and prints 0 breaks has told you the day was clean. If the orders table is empty because the script read the wrong file, it has done the same. Give the script three outcomes with three exit codes: 0 clean, 1 breaks, 2 not run. A scheduler can then page on 2 as loudly as on 1. A reconciliation that cannot fail to run is the most dangerous one you have.

Testing the reconciliation itself

A reconciliation that has never reported a break has proved nothing. It may be right, or it may be unable to see. You do not find out by waiting. You build the breaks. The script keeps its comparison in one pure function, reconcile(orders, fetch, provider_charge_count), where fetch is any function from a charge id to a charge or None. That lets a test hand it a dictionary and no server. For each kind of break, write one test that creates exactly that break and asserts exactly that kind is reported. It is mutation testing applied to a control, and the chapter on coverage and mutation testing has the underlying idea. The proof that the tests have teeth comes at the end of the lab: switch off one comparison, and a test turns red.

Evidence: proving the control ran

An auditor testing a control asks two questions: is it designed to catch the risk, and did it operate every time it should have. The second needs evidence made when the control ran, by the system that ran it, not assembled when someone asked. For each run, the lab’s script writes one file with:

  • a run id made from the UTC time and six random characters, unique per run;
  • the start and finish times, in UTC;
  • a code hash: a SHA-256 over every file in checkout/ and over the script itself, so you can say which code produced the result;
  • a hash of the input: a SHA-256 of the orders it read, so a later extract can be compared;
  • the provider it asked, the counts (orders, matched, provider charges), and each break with its kind, ids and value;
  • the result: CLEAN, BREAKS or NOT_RUN, with the reason for NOT_RUN.

The file is opened with mode x, which refuses to overwrite an earlier run. That is a convenience and not a control: anyone with the directory can delete the file. For a regulator you also need the file stored where the team cannot edit it for the retention period, such as object storage with a write-once lock, and reviewed by a named person who is not the author. None of that can be written into the script. Say so in the design.

Say, too, what the file cannot show. Reading the lab code against its output gives a precise list, and it is worth writing down because auditors will find it themselves.

An auditor can check An auditor cannot check from this file
That a run happened at a time, on code with a stated hash, over input with a stated hash That the file was not edited afterwards: that needs immutable storage and a reviewer
That the counts add up and each break is listed with its value That the provider’s answers are independent of yours: the fake provider is your own test double, and a real provider’s API is a claim, whereas the bank statement is the independent record
That a NOT_RUN day is recorded as such That every provider charge is known: the count shows that some are missing, not which
That the same input and code give the same result, if the orders extract is kept That the deployed service ran that code: the hash is of files on the machine that ran the check
That a total is right by the pricing rules: an order stores lines but not distance_km or the promo code, so the price cannot be recomputed from the order alone

The last row is a real finding. The reconciliation verifies that two records agree, and says nothing about whether what they agree on is correct. The invariant tests carry that burden, which is why you need both. And the missing fields are a design fault that testing exposes: if the order does not store what the price depended on, no later check can re-derive it. Raise it with the people who own the schema.

Where it goes wrong

A reconciliation of a record with itself. If the “provider” side is read from a table your own service writes, the check is a tautology. Always name the independent source and why it is independent.

Timing breaks that cry wolf. A charge exists for a few hundred milliseconds before its order is saved, so a run at the wrong moment sees a charge with no order. The lab’s script has no cut-off. A production one would only look at orders and charges older than a stated window, and age a break from the end of that window. Without it, the team starts ignoring count_mismatch, and then ignores a real one.

A tolerance that grows. Someone widens it to a naira to quiet one-kobo noise, and a rounding bug then hides inside it. Decide the tolerance once, with a reason, and put the reason in the definition.

Testing the happy path of the control. The reconciliation passes in CI on clean data, and nobody has ever seen it fail. Seed the breaks.

Idempotency left untested. A retry that creates a second order and a second charge is the commonest way money moves twice. The lab asserts one order and one charge call for a repeated key, and the Payments chapter on idempotency explains why a timeout means unknown and not failed.

LAB Invariants, a reconciliation script, and an evidence file ~60 MIN
YOU NEEDlabs/testing set up (README, 'Set up'), Python 3.9+ports 8094 and 8095 free (lsof -i :8094 -i :8095); no Dockerscratch files only: export CHECKOUT_DB=/tmp/money-lab.sqlite

You will write invariant tests for pricing and orders, a reconciliation script that compares the orders table with the fake provider, and tests that seed every kind of break. Then you will run the script against live services, break the data in a copy, and read the evidence file. Work from labs/testing with the venv from the README. You create four files and delete them at the end. Nothing here touches data/.

cd labs/testing
export CHECKOUT_DB=/tmp/money-lab.sqlite
rm -f "$CHECKOUT_DB"
.venv/bin/pytest -q
23 passed, 1 skipped, 1 deselected: the starter suite on clean code. If you kept tests from earlier chapters you will see more, and the counts below rise by the same amount.

1. Write the invariants.

Create the folder tests/invariants with an empty __init__.py, and tests/invariants/test_money_invariants.py. It sits outside tests/unit on purpose, because a Hypothesis test in tests/unit crashes the mutation tool’s statistics run (the property-based testing chapter’s tests/properties folder is there for the same reason):

from datetime import datetime, timezone

from hypothesis import given, settings, strategies as st

from checkout.legacy import make_schedule
from checkout.money import vat_on
from checkout.orders import place_order
from checkout.pricing import Line, price_cart

NOW = datetime(2026, 11, 23, 9, 0, tzinfo=timezone.utc)

lines = st.lists(
    st.builds(Line, st.integers(1, 5_000_000), st.integers(1, 20)),
    min_size=1,
    max_size=6,
)
distances = st.integers(0, 100)


@settings(max_examples=300)
@given(lines, distances)
def test_a_quote_adds_up(cart, km):
    q = price_cart(cart, km, NOW)
    assert q.net == q.subtotal - q.tier_discount - q.promo_discount
    assert q.total == q.net + q.vat + q.delivery_fee


@settings(max_examples=300)
@given(lines, distances)
def test_every_figure_is_a_whole_non_negative_number_of_kobo(cart, km):
    for name, value in price_cart(cart, km, NOW).as_dict().items():
        assert type(value) is int, name
        assert value >= 0, name


@settings(max_examples=500)
@given(st.integers(0, 10**12))
def test_vat_is_within_half_a_kobo_of_the_exact_figure(net):
    # exact VAT is net * 7.5% = net * 750 / 10000; compare scaled by 10000 to stay in integers
    assert abs(vat_on(net) * 10000 - net * 750) <= 5000


@settings(max_examples=300)
@given(st.integers(0, 50_000_000), st.integers(1, 12))
def test_an_instalment_schedule_sums_to_the_total(total, n):
    amounts = [amount for _, amount in make_schedule(total, n, 2026, 1, 1)]
    assert sum(amounts) == total
    assert max(amounts) - min(amounts) <= 1


def test_the_order_total_is_the_amount_charged(db, payments, clock):
    order, _ = place_order(db, payments, clock, [{"product_id": 1, "qty": 2}], "inv-1", distance_km=3)
    quote = price_cart([Line(1_200_000, 2)], 3, clock.now())
    assert order["total_kobo"] == quote.total
    assert payments.calls == [("inv-1", quote.total, "inv-1")]


def test_a_retry_moves_money_once(db, payments, clock):
    cart = [{"product_id": 2, "qty": 1}]
    place_order(db, payments, clock, cart, "inv-2")
    place_order(db, payments, clock, cart, "inv-2")
    assert db.count_orders() == 1
    assert len(payments.calls) == 1
    assert db.stock_of(2) == 99
.venv/bin/pytest tests/invariants -q -p no:randomly
6 passed in about a second. Each Hypothesis test ran 300 or 500 generated inputs. The start date passed to make_schedule is January 2026, so up to twelve instalments stay inside one year, and the test reads only the amounts.

2. Find the cliff, and record it.

This is the cliff from the property-based testing chapter, met by a different route: there Hypothesis found it with an edge strategy over units, here a plain random strategy misses it and an @example at the boundary finds it. If you still have tests/properties/ from that chapter, you do not need it for this step. Create tests/invariants/test_cliff.py. First write it without the @example line and run it with several seeds:

from datetime import datetime, timezone

import pytest
from hypothesis import example, given, strategies as st

from checkout.pricing import Line, price_cart

NOW = datetime(2026, 11, 23, 9, 0, tzinfo=timezone.utc)


@pytest.mark.xfail(strict=True, reason="tier discount cliff at N10,000: a rule to decide on, not a bug to fix")
@example(999_999, 1)
@given(st.integers(1, 5_000_000), st.integers(1, 5_000_000))
def test_adding_a_line_never_lowers_the_total(a, b):
    small = price_cart([Line(a, 1)], 3, NOW).total
    big = price_cart([Line(a, 1), Line(b, 1)], 3, NOW).total
    assert big >= small

To see the blind spot, delete the @example line and the xfail line, then run for i in 1 2 3 4 5 6; do .venv/bin/pytest tests/invariants/test_cliff.py -q -p no:randomly --hypothesis-seed=$i | tail -1; done. Put both lines back and run it once more:

.venv/bin/pytest tests/invariants/test_cliff.py -q -p no:randomly -rx
Without the example, six runs of 1 passed: random search never lands within a few kobo under ₦10,000. With the example and xfail back: 1 xfailed, and the reason line. Take xfail off for a moment and the failure reads assert 1171250 >= 1224999: a cart of ₦9,999.99 costs ₦12,249.99 with delivery and VAT, and one kobo more of goods costs ₦11,712.50. The strict=True means the day someone removes the cliff, this test fails and tells them to delete it.

3. Write the reconciliation script.

Create scripts/reconcile.py:

"""Reconcile the orders table against the payment provider and write an evidence file.

  .venv/bin/python scripts/reconcile.py data/checkout.sqlite --provider http://127.0.0.1:8095 --out evidence/

Exit 0: no breaks. Exit 1: breaks found. Exit 2: the run could not be done properly
(provider unreachable, or no orders to check). A run that did not happen is not a pass.
"""

import argparse
import hashlib
import json
import sqlite3
import sys
import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional

import httpx

ROOT = Path(__file__).resolve().parents[1]


def code_hash() -> str:
    """One SHA-256 over every checkout/*.py file and this script: which code ran."""
    digest = hashlib.sha256()
    for path in sorted(list((ROOT / "checkout").glob("*.py")) + [Path(__file__).resolve()]):
        digest.update(str(path.relative_to(ROOT)).encode() + b"\0" + path.read_bytes() + b"\0")
    return digest.hexdigest()


def load_orders(db_path: str) -> List[Dict[str, Any]]:
    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row
    try:
        rows = conn.execute(
            "SELECT id, idempotency_key, status, total_kobo, charge_id, created_at FROM orders ORDER BY created_at, id"
        ).fetchall()
    finally:
        conn.close()
    return [dict(r) for r in rows]


def reconcile(
    orders: List[Dict[str, Any]],
    fetch: Callable[[str], Optional[Dict[str, Any]]],
    provider_charge_count: Optional[int] = None,
) -> Dict[str, Any]:
    """Compare each order with its charge. `fetch(charge_id)` returns the charge, or None for a 404."""
    breaks: List[Dict[str, Any]] = []
    seen: Dict[str, str] = {}
    found = set()
    matched = 0
    for order in orders:
        before = len(breaks)
        cid = order["charge_id"]
        if cid in seen:
            breaks.append({"kind": "charge_used_twice", "order_id": order["id"], "charge_id": cid,
                           "detail": "also on order " + seen[cid], "value_kobo": order["total_kobo"]})
        seen.setdefault(cid, order["id"])
        charge = fetch(cid)
        if charge is None:
            breaks.append({"kind": "missing_at_provider", "order_id": order["id"], "charge_id": cid,
                           "detail": "provider has no such charge", "value_kobo": order["total_kobo"]})
            continue
        found.add(cid)
        if charge["amount_kobo"] != order["total_kobo"]:
            breaks.append({"kind": "amount_mismatch", "order_id": order["id"], "charge_id": cid,
                           "detail": "order %d, provider %d" % (order["total_kobo"], charge["amount_kobo"]),
                           "value_kobo": abs(order["total_kobo"] - charge["amount_kobo"])})
        if charge["reference"] != order["idempotency_key"]:
            breaks.append({"kind": "reference_mismatch", "order_id": order["id"], "charge_id": cid,
                           "detail": "order key %s, provider reference %s" % (order["idempotency_key"], charge["reference"]),
                           "value_kobo": order["total_kobo"]})
        if charge["status"] != "succeeded":
            breaks.append({"kind": "status_mismatch", "order_id": order["id"], "charge_id": cid,
                           "detail": "provider status " + charge["status"], "value_kobo": order["total_kobo"]})
        if len(breaks) == before:
            matched += 1
    distinct = len(seen)
    if provider_charge_count is not None and provider_charge_count != len(found):
        breaks.append({"kind": "count_mismatch", "order_id": None, "charge_id": None,
                       "detail": "provider holds %d charges, orders account for %d" % (provider_charge_count, len(found)),
                       "value_kobo": 0})
    kinds: Dict[str, int] = {}
    for b in breaks:
        kinds[b["kind"]] = kinds.get(b["kind"], 0) + 1
    return {
        "orders": len(orders),
        "distinct_charges_referenced": distinct,
        "provider_charge_count": provider_charge_count,
        "matched": matched,
        "breaks": breaks,
        "break_counts": kinds,
        "gross_break_value_kobo": sum(b["value_kobo"] for b in breaks),
    }


def main(argv: Optional[List[str]] = None) -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("db")
    parser.add_argument("--provider", default="http://127.0.0.1:8095")
    parser.add_argument("--out", default="evidence")
    args = parser.parse_args(argv)

    started = datetime.now(timezone.utc)
    run_id = started.strftime("%Y%m%dT%H%M%SZ") + "-" + uuid.uuid4().hex[:6]
    orders = load_orders(args.db)
    orders_hash = hashlib.sha256(json.dumps(orders, sort_keys=True).encode()).hexdigest()
    evidence: Dict[str, Any] = {
        "run_id": run_id,
        "started_at": started.isoformat(),
        "code_sha256": code_hash(),
        "database": args.db,
        "orders_sha256": orders_hash,
        "provider": args.provider,
    }
    exit_code = 0
    try:
        with httpx.Client(base_url=args.provider, timeout=5.0) as http:
            def fetch(charge_id: str) -> Optional[Dict[str, Any]]:
                resp = http.get("/v1/charges/" + charge_id)
                if resp.status_code == 404:
                    return None
                resp.raise_for_status()
                return resp.json()

            if not orders:
                evidence.update(result="NOT_RUN", reason="the orders table is empty: nothing was checked")
                exit_code = 2
            else:
                count = http.get("/_admin/stats").json()["charges"]
                evidence.update(reconcile(orders, fetch, count))
                evidence["result"] = "BREAKS" if evidence["breaks"] else "CLEAN"
                exit_code = 1 if evidence["breaks"] else 0
    except httpx.HTTPError as exc:
        evidence.update(result="NOT_RUN", reason="provider unreachable or failing: %s" % exc)
        exit_code = 2
    evidence["finished_at"] = datetime.now(timezone.utc).isoformat()

    out_dir = Path(args.out)
    out_dir.mkdir(parents=True, exist_ok=True)
    path = out_dir / ("reconcile-%s.json" % run_id)
    with open(path, "x") as fh:  # "x": never overwrite an earlier run
        json.dump(evidence, fh, indent=2, sort_keys=True)
        fh.write("\n")
    print("%s  %s  orders=%s matched=%s breaks=%d  -> %s" % (
        evidence["result"], run_id, evidence.get("orders", len(orders)), evidence.get("matched", "-"),
        len(evidence.get("breaks", [])), path))
    for b in evidence.get("breaks", []):
        print("  BREAK %-20s %s %s  %s" % (b["kind"], b["order_id"], b["charge_id"], b["detail"]))
    if "reason" in evidence:
        print("  " + evidence["reason"])
    return exit_code


if __name__ == "__main__":
    sys.exit(main())

The comparison is in reconcile, which does no I/O. main does the reading, the fetching, the exit code and the file.

4. Seed every break.

Create tests/integration/test_reconcile.py. It loads the script by path, because scripts/ is not a package:

import importlib.util
from pathlib import Path

spec = importlib.util.spec_from_file_location(
    "reconcile", Path(__file__).resolve().parents[2] / "scripts" / "reconcile.py"
)
reconcile_mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(reconcile_mod)
reconcile = reconcile_mod.reconcile


def order(n, total=902_500, charge=None, key=None):
    return {"id": "ord_%d" % n, "idempotency_key": key or "key-%d" % n, "status": "paid",
            "total_kobo": total, "charge_id": charge or "ch_%d" % n, "created_at": "2026-11-23T09:00:00+00:00"}


def charge_for(o, **change):
    c = {"id": o["charge_id"], "status": "succeeded", "amount_kobo": o["total_kobo"],
         "currency": "NGN", "reference": o["idempotency_key"]}
    c.update(change)
    return c


def run(orders, charges, count="auto"):
    by_id = {c["id"]: c for c in charges}
    if count == "auto":
        count = len(by_id)
    return reconcile(orders, by_id.get, count)


def kinds(result):
    return sorted(b["kind"] for b in result["breaks"])


def test_two_agreeing_records_have_no_breaks():
    orders = [order(1), order(2)]
    result = run(orders, [charge_for(o) for o in orders])
    assert result["breaks"] == [] and result["matched"] == 2


def test_a_charge_the_provider_never_saw_is_flagged():
    orders = [order(1), order(2)]
    result = run(orders, [charge_for(orders[0])], count=1)
    assert kinds(result) == ["missing_at_provider"]
    assert result["breaks"][0]["order_id"] == "ord_2"


def test_an_amount_one_kobo_out_is_flagged():
    o = order(1)
    result = run([o], [charge_for(o, amount_kobo=902_501)])
    assert kinds(result) == ["amount_mismatch"]
    assert result["gross_break_value_kobo"] == 1


def test_a_charge_used_by_two_orders_is_flagged():
    a, b = order(1), order(2, charge="ch_1")
    result = run([a, b], [charge_for(a)])
    assert "charge_used_twice" in kinds(result)


def test_a_wrong_reference_is_flagged():
    o = order(1)
    assert kinds(run([o], [charge_for(o, reference="someone-else")])) == ["reference_mismatch"]


def test_a_charge_with_no_order_shows_in_the_count():
    o = order(1)
    result = run([o], [charge_for(o)], count=2)
    assert kinds(result) == ["count_mismatch"]


def test_breaks_of_opposite_sign_do_not_cancel_in_the_gross():
    a, b = order(1), order(2)
    result = run([a, b], [charge_for(a, amount_kobo=a["total_kobo"] + 5), charge_for(b, amount_kobo=b["total_kobo"] - 5)])
    assert kinds(result) == ["amount_mismatch", "amount_mismatch"]
    assert result["gross_break_value_kobo"] == 10
.venv/bin/pytest tests/integration/test_reconcile.py -q -p no:randomly
.venv/bin/pytest -q
.venv/bin/ruff check .
7 passed, then the whole suite: 36 passed, 1 skipped, 1 deselected, 1 xfailed (the 23 starter tests, the 6 invariants and the 7 reconciliation tests; the xfail is the cliff), then All checks passed! from ruff. Each break has its own test and the tests assert the kind, not only that something was reported.

5. Run it against live services, clean.

Check the ports first with lsof -i :8094 -i :8095. If something answers, stop it or use other ports and pass --provider. In two terminals, from labs/testing, with CHECKOUT_DB exported as above:

.venv/bin/uvicorn fake_provider.app:app --port 8095
.venv/bin/uvicorn checkout.api:app --port 8094

In a third, place six orders with different carts and distances, then reconcile:

for i in 1 2 3 4 5 6; do
  curl -s -o /dev/null -w "%{http_code} " -X POST localhost:8094/orders \
    -H 'Content-Type: application/json' -H "Idempotency-Key: owl-$i" \
    -d "{\"lines\":[{\"product_id\":$(( i % 2 + 1 )),\"qty\":$i}],\"distance_km\":$((i*3))}"
done; echo
.venv/bin/python scripts/reconcile.py "$CHECKOUT_DB" --provider http://127.0.0.1:8095 --out evidence; echo "exit=$?"
201 201 201 201 201 201, then a line like CLEAN 20261123T230924Z-84bd77 orders=6 matched=6 breaks=0 -> evidence/reconcile-20261123T230924Z-84bd77.json and exit=0. Your run id differs. The provider holds six charges and six orders point at them.

6. Break it in a copy, and read the flags.

You cannot delete a charge through the fake provider’s API, so break the other side: in a copy of the database, point one order at a charge id the provider has never seen (the reconciliation cannot tell the difference), and push another order’s total up by one kobo.

cp "$CHECKOUT_DB" /tmp/money-broken.sqlite
.venv/bin/python - <<'EOF'
import sqlite3
c = sqlite3.connect("/tmp/money-broken.sqlite")
c.execute("UPDATE orders SET charge_id='ch_0000000000' WHERE idempotency_key='owl-3'")
c.execute("UPDATE orders SET total_kobo=total_kobo+1 WHERE idempotency_key='owl-5'")
c.commit()
EOF
.venv/bin/python scripts/reconcile.py /tmp/money-broken.sqlite --provider http://127.0.0.1:8095 --out evidence; echo "exit=$?"
BREAKS ... orders=6 matched=4 breaks=3, then a missing_at_provider line for ch_0000000000, an amount_mismatch line reading order 2087189, provider 2087188 (your amount will differ if you chose other carts), and a count_mismatch line: provider holds 6 charges, orders account for 5, then exit=1. The third break is the first one seen from the other side. Once the order lost its charge id, the real charge at the provider belongs to nobody.

7. A charge your system does not know about, a dead provider, an empty table.

curl -s -o /dev/null -X POST localhost:8095/v1/charges -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: stray-1' -d '{"reference":"stray-1","amount_kobo":5000}'
.venv/bin/python scripts/reconcile.py "$CHECKOUT_DB" --provider http://127.0.0.1:8095 --out evidence; echo "exit=$?"
.venv/bin/python scripts/reconcile.py "$CHECKOUT_DB" --provider http://127.0.0.1:8097 --out evidence; echo "exit=$?"
The first run: BREAKS ... orders=6 matched=6 breaks=1 and count_mismatch ... provider holds 7 charges, orders account for 6, exit=1: the stray charge that the Predict question asked about. The second, with nothing on port 8097: NOT_RUN ... orders=6 matched=- breaks=0, the reason provider unreachable or failing: [Errno 61] Connection refused (the number differs on Linux), and exit=2. A clean-looking zero breaks would have been a lie.

Stop both servers with Ctrl-C.

8. Read the evidence.

ls evidence
.venv/bin/python -c "import json,sys; d=json.load(open(sys.argv[1])); print({k: d[k] for k in ('run_id','result','code_sha256','orders_sha256','orders','matched','gross_break_value_kobo')})" evidence/$(ls evidence | head -1)
Four files in the folder after step 7, one per run including the NOT_RUN one. The printed dictionary shows the run id, the result, two 64-character hashes and the counts. Change one character in checkout/money.py and run again: the code_sha256 changes and the others do not.
Now check that the tests have teeth. In scripts/reconcile.py change if charge[“amount_kobo”] != order[“total_kobo”]: to if False and charge[“amount_kobo”] != order[“total_kobo”]: and run .venv/bin/pytest tests/integration/test_reconcile.py -q -p no:randomly. On 2026-11-23 two tests failed: the one-kobo test and the opposite-signs test, and five passed. A reconciliation that quietly stopped comparing amounts would have gone on printing 0 breaks. Now change open(path, “x”) to open(path, “w”) and run the tests again: all seven still pass, because no test looks at how the file is written. That is the limit of these tests, and why where the evidence is stored is a control and not a code change. Restore both lines.

Put the lab back. Delete tests/invariants, tests/integration/test_reconcile.py, scripts/reconcile.py, the evidence folder, .hypothesis, /tmp/money-lab.sqlite and /tmp/money-broken.sqlite. Check with git status that labs/testing is clean, and that .venv/bin/pytest -q gives 23 passed, 1 skipped, 1 deselected. Confirm both ports are free with lsof -i :8094 -i :8095.

DECIDE

After a release, Owoleaf's daily reconciliation reports about ten amount_mismatch breaks a day, each of one kobo, on about 90,000 top-ups. Simba suspects the new provider SDK rounds a fee differently. Support is asking whether to ignore them. Chenai asks what the reconciliation's tolerance should be, because the regulator reads its definition.

READING
  1. DOC
    In the Matter of Knight Capital Americas LLC (Order, Release No. 34-70694) US Securities and Exchange Commission, 2013

    A regulator's own account of a software failure and the controls it expected: 212 retail orders turned into millions of unwanted orders in 45 minutes. Read the Introduction and the findings on controls and supervision; skip the legal sections. Read 2026-11-24.

  2. POST
    Ledger: Stripe's system for tracking and validating money movement Ilya Ganelin, Stripe, 2024

    How a payments company validates money movement continuously: clearing accounts that must return to zero, and checks for completeness and timeliness. It is the production version of this chapter's reconciliation. The old stripe.com address redirects here. Read it whole. Read 2026-11-24.

  3. POST
    Books, an immutable double-entry accounting database service Lukasz Strzalkowski, Square, 2019

    Why an append-only record, corrected by new entries and never by edits, is what makes a ledger auditable. Read it for the design of the audit trail; skip the database internals. Read 2026-11-24.

  4. PAPER
    What Every Computer Scientist Should Know About Floating-Point Arithmetic David Goldberg, 1991

    The reason money is kept in integer kobo. This is Oracle's reprint of the ACM Computing Surveys paper, because the ACM page blocks automated readers. Read 2026-11-24. Read: the opening sections on rounding error; skip the proofs in the later sections.

  5. DOC
    decimal: Decimal fixed-point and floating-point arithmetic Python documentation

    The standard library's exact decimal type and its eight rounding modes, including ROUND_HALF_UP and ROUND_HALF_EVEN, which the rounding rule in checkout/money.py is a choice between. Read the Rounding modes section; skip the signals and contexts on a first pass. Read 2026-11-24.

  6. DOC
    Money Martin Fowler

    A short statement of the pattern: a money value type that carries its currency, so arithmetic on it cannot silently mix units. The page does not cover allocating a remainder; the [residual-cent lesson](../../../learn/residual-cent/) does. Read 2026-11-24.

  7. DOC
    Hypothesis tutorial Hypothesis documentation

    The index to the tool behind the invariants: strategies, settings and replaying failures. Read the sections on strategies and on replaying a failing case. Read 2026-11-24.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Project: a suite that catches ten seeded bugs, measured by mutation score →