WORKINGCHAPTER 11

Reconciliation: ledger against provider against bank statement

Three records of one pot of money never agree by themselves. Match them line by line, explain every gap in one of four ways, and post the fix as new entries

60 MINPAYMENTSUPDATED 2026-11-14
PREDICT

Owoleaf's ledger and its partner bank's statement describe the same account over 180 days with movement. Exactly nine lines are wrong. On how many of those days does the bank's closing balance differ from the ledger's?

Reconciliation is the proof that two independent records describe the same money. The lesson on reconciliation shows the idea on six rows: three kinds of mismatch, matching rules that run strictest first, an exceptions queue, and a totals check. Read it first if you have not. This chapter does not repeat its simulation. It goes where six rows cannot reach: a statement of 56,008 lines, a key that has to survive returned payouts, a value date that moves, a card leg run by a third party, and the entries you post once you know which side is wrong. The double-entry chapter ended on the limit of the ledger: it cannot find a balanced error by itself. A record from outside can. This chapter is that comparison.

Three records, two comparisons

Money that a business receives is described three times. The ledger is yours: what you believe happened. The provider’s settlement report says which captured card payments the processor will pay for, less its fee. The bank statement says what the partner bank booked to your account, with a running balance. Each record can be wrong in its own way, and none can check itself.

Record Kept by It says In the lab
Ledger you what you booked, and when entries on settlement_bank (56,007 lines) and on card_clearing
Provider settlement report the card processor which captures it pays, its fee, the net GET /settlements?date=: lines, gross, fee, net
Bank statement the partner bank what reached the account, and the balance bank_statement (56,008 lines)

There are two kinds of comparison, and a team needs both. Balance reconciliation asks whether the ledger’s balance equals the bank’s after the items you know about. It is cheap and runs every day, and it answers whether. Transaction reconciliation asks whether every line has a partner. It answers which. A gap of ₦30,947.35 is a number. Nine lines are a list of work that someone can do.

LedgeryoursProvider reportthe card processor’sBank statementthe partner bank’sA: each card funding against a report lineB: each settlement_bank entry against a statement lineC: the day’s netagainst one line

Each pair compares a different thing. A is line against line, many against many on the same day. B is line against line, and it holds every NIP payout, inward transfer and return. C is a single amount per day, because the processor pays a batch. The nine planted breaks are all on B. A and C come back clean on the generated days, and step 4 shows you how a break on that side looks.

The lab’s bank_statement is a flattened statement. Banks send the real thing as a file or a feed, and ISO 20022 defines a message for it: the BankToCustomerStatement message, camt.053, is sent by the account servicing bank to the account owner or a party the owner authorises. Bank implementation guides found by search describe it as reporting booked entries only, with balances at a point in time. Versions differ (guides from banks show both camt.053.001.02 and camt.053.001.08), so ask which version your counterparty sendsas of 2026-11. In the lab’s table the same ideas are plain columns: booked_at, value_date, direction, amount_kobo, reference, narration and the running balance_kobo. Booked only matters. A statement does not show what the bank is about to do.

The key decides what you can see

Matching means deciding that two lines are the same event. The choice of key decides which breaks you can see at all.

Amount alone is the weakest key: equal amounts are common, and the lesson shows the wrong pairs it makes. A date is shaky, for a reason the next section gives. The reference is the strongest: the 30-digit reference that the ledger’s external_ref and the statement’s reference share. But a reference is not always unique to one line. In Owoleaf’s statement, 100 references appear on more than one line. Ninety-eight of them are payouts that the beneficiary’s bank returned: the NIP RETURN line quotes the payout’s own reference, on the other side, for the same amount. The other two are duplicate bookings by the bank.

So the key is the reference, the side (credit or debit, the bank’s words, which the ledger’s debit to settlement_bank flips into a credit on the statement) and the amount. Put into the key what you want to be equal, and nothing else. The amount is in the key because pass 1 should pair only perfect matches. A line that shares a reference and a side but differs in amount is not lost: pass 2 picks it up as an amount mismatch, which is how that break gets its name.

The key also has to allow for how many lines belong together, the cardinality of a match. A payout is one ledger line for one statement line. A card settlement is many to one: the provider pays one line for a whole day’s captures, so you group the captures by day and compare their sum. In the lab that is 10,171 captures over 174 settlement days, about 58 per line. A bulk payout run is one to many, a single debit for many beneficiaries. Modern Treasury’s own blog, a vendor’s claim, says its engine handles one-to-one, many-to-one (its example is several card swipes paid out in one daily batch) and one-to-many matches, and its documentation sends unmatched items to manual reviewas of 2026-11. The design is worth knowing even if you never buy it. Many-to-one rules are what a card leg needs, and they are where a missing line is hardest to see.

Rules then run in order, strictest first, and each rule sees only what the stricter ones left. This is the lesson’s ordering. On Owoleaf’s statement it gives:

Pass Rule Lines it places in the lab
1 Same reference, side and amount 56,002 pairs
2 Same reference and side, another amount 2 amount mismatches
3 A second statement line for a pair already made 2 duplicates
4 A ledger line whose reference is nowhere on the statement 3 missing from the statement
5 A statement line whose reference is nowhere in the ledger 2 unapplied credits
– Anything left 0

Keep the last row, even when it is empty. A run that ends with lines no rule could place means a new kind of break has appeared, and the job has to stop and say so. A job that drops them quietly is the one that hides the next problem.

Timing is not a break

The bank gives each line a value date: the day the bank counts the money as being in the account. For most lines it is the booking date. In the lab, a booking after 23:00 takes the next day’s value date, as a cut-off would. The cut-off is the generator’s, as illustrative as the fees. Real banks set their own, and weekends and holidays move value dates further, so ask your bank how it treats them.

The effect is large. Of 56,008 statement lines, 3,114 have a value date that is not their booking date, and all 3,114 were booked in the 23:00 hour. None is a break. The ledger posts at the moment of the event, so it counts these lines a day before the bank does. Compare each day’s net movement and the effect shows: counting the bank’s lines by value date, the ledger and the bank disagree on 174 of 180 days. Count them by booking date, and they disagree on 9 days, which are the nine breaks, each on a different day. The 174 is not the 171 of the Predict. The 174 compares each day’s own movement, the net of that day’s lines. The 171 compares the balances at the close, which are running totals: a break stays in the balance gap on every later day, while a line in transit at one close is gone from the gap by the next, so the two counts need not agree.

Two lessons follow. For matching items, use the booking time, which both sides recorded: it makes the timing noise disappear. For comparing balances, use the value date, because the bank’s closing balance for a date is by value date, and then explain the difference with a bridge:

bank balance − ledger balance = (effect of the breaks so far) − (ledger lines booked that day but valued the next)

The second term is the items in transit. On 170 of the 180 days there are some at the close. If the bridge closes to zero on every day, every line is in exactly one bucket: matched, in transit, or a named break. If it does not, a line was missed or changed on its way into your job, and the bridge tells you the day. It is the lesson’s totals check at the scale of a statement. As the lesson says, a bridge cannot see a wrong pair, because swapped lines add up the same. Pass 1 only pairs lines that agree on everything, so that cannot happen here, and step 3 proves the closing.

The same split applies to every rail. Nigeria’s rails ended on a rule worth keeping: an exception list should hold only items that are late beyond their rail’s own clock. Timing items are not exceptions until they age past that clock.

Four breaks, four postings

Finding a break is the easy half. You then have to decide what is true, who can say so, and what to post meanwhile. The lab’s four kinds, with what to ask and what to post:

Break The statement shows Often means Ask Post
Missing from the statement No line for a payout the ledger booked The bank never ran it, or booked it under another reference or day The partner bank; the switch, by requery Debit settlement_bank, credit suspense. Then retry the payout, or return the money to the wallet
Duplicate on the statement The same line twice The bank booked it twice The partner bank Debit bank_receivable, credit settlement_bank. When the bank refunds, reverse that
Amount mismatch A line larger or smaller by a constant A fee taken with the principal, or a keying error The bank’s fee schedule Debit bank_receivable, credit settlement_bank. If the fee is legitimate, move it to bank_charges
Unapplied credit Money in, narrated NIP INWARD UNKNOWN The payer used a wrong or empty reference The sender, from their transfer receipt Debit settlement_bank, credit suspense. When the owner is found, move it to their wallet, or return it

A constant, round difference looks like a fee. Your code can say only that two lines share a reference and differ by 2,500 kobo. The answer key says what the bank did. In real life the bank tells you, or a fee schedule does. A rule that reads “differences under ₦50 are fine” would clear both amount mismatches in the lab and the question would never be asked.

The accounts in the posting column are new. suspense is money at the bank that your ledger cannot yet place: a liability, because it is not yours. bank_receivable is a claim on the bank: an asset. bank_charges is an expense. Which account, and whether to retry or refund, is a policy that a finance lead signs. The rule from module 1 does not change: you never edit or delete an entry. A correction is a new transaction that carries its reason, and the old entry stays to be audited.

Two habits keep a suspense account from becoming a drawer. Give every item an owner and an age, and mark any item older than a limit your team sets. And link the correction to the break it closes. Posting an adjustment brings the balance to the bank’s, but it does not close the item: the adjustment is itself a line on settlement_bank that the bank’s statement will never show. Run tomorrow’s matcher over the corrected books without that link, and it reports the adjustments as new breaks. Step 5 shows it.

The card leg: many captures, one line

Comparison C is simpler. The ledger’s card_settlement for a day, the provider’s report for that day and the statement’s CARD SETTLEMENT line should all say the same net. Comparison A goes one level down: the provider lists each capture it is paying for, and each should be a successful card funding in the ledger. A CBN circular of 31 May 2020 (PSMD/31/05/2020) on its Guidelines on Operations of Electronic Payment Channels in Nigeria is summarised in search results as requiring processors to provide daily settlement reports by 8 a.m. on a T+1 basis. That rests on search summaries because the CBN’s site could not be read here; read the Guidelines before relying on the wordingas of 2026-11. A daily report is what makes comparison A possible at all. Without a line-level report you can only compare totals.

On the generated days it comes back clean: 174 settlement days, 10,171 captures, none on the report that the ledger lacks and none in the ledger that the report lacks. The one card day without a settlement is 29 June, where the data stops, with 109 captures still owed: a cut-off, as in the card chapter. The lab’s mock builds its report from the generated ledger, so that agreement is a property of the lab. A real processor’s report would disagree now and then. The mock lets you make it disagree.

Wrenpost’s prepaid model gives the two directions different stakes. Say the provider charged a customer’s card for ₦18,500 and the webhook that should have credited the wallet was lost (the previous chapter’s subject, integrating a provider, is how that happens). The report lists a capture the ledger does not know. The customer is out of pocket and has not been credited. Support will hear first, and the right move is to credit them and book the claim on the provider. Now reverse it. The ledger credits message credits for a card payment that the provider never captured. The customer spends the credits by sending messages, and the carriers have to be paid for those messages whether or not the card money ever arrives. That is the company’s money, and it is the direction that costs more. Compare in both directions: provider-only lines, and ledger-only lines.

The report also carries refunds. In the lab’s mock, a refund processed on a day reduces the next settlement in full while the fee stays on the gross, so a ₦18,500 capture with a ₦5,000 refund pays ₦13,315.00 (1,850,000 − 18,500 − 500,000 = 1,331,500 kobo). That is the mock’s rule. How a real provider treats the fee on a refunded amount is in its contract, which is a reason to read the report, not guess.

Running it every day

A reconciliation that runs once a month finds problems when they are a month old. The daily job has a fixed order:

  1. Load every statement line since the last run. Do not reconcile one day on its own, because items in transit cross the boundary.
  2. Match in passes and classify the leftovers. Stop on any line no rule could place.
  3. Close the bridge. A non-zero result means the job is wrong, not the bank.
  4. Propose the adjustments. A second person approves before anything is posted: Morayo should not post what she alone found.
  5. Age the open items, and report the oldest.

Three decisions sit inside it. First, tolerance. Never put one on amounts to make the queue shorter. A tolerance that clears a fee difference also clears a theft of the same size. Put tolerances on time instead: how long an item may be in transit before it counts as an exception.

Second, what you measure. A match rate of 99.98% sounds fine, and it is the share of lines paired. But it says nothing of value. In the lab, the nine breaks net to ₦30,947.35 and total ₦122,863.39 in absolute value, because they have opposite signs: the duplicate of ₦43,388.96 and the unapplied credit of ₦46,612.00 differ by ₦3,223.04 in the net. A team that watched only the net gap would believe the position was nearly clean. Track the number of open breaks, their absolute value, and the oldest age. Stripe’s engineering blog, a vendor’s own claim, describes its Ledger and Data Quality Platform as giving over 99.9999% explainability of money movementas of 2026-11. The useful idea in that claim is the measure: the share of money movement that is explained. Whether any figure is good enough is yours to decide.

Third, independence. A reconciliation proves something only if the records are made by different parties. A matcher that builds its “bank side” from your own ledger finds nothing. Neither should it trust the narration text, which the bank or the payer wrote, as an identity. Use it to help a person, not to pair lines.

Regulators treat the loop as a duty for some operators. A legal-commentary summary (Afriwise) of the CBN’s Framework and Guidelines on Mobile Money Services in Nigeria (July 2021) says mobile money operators must reconcile the balances in their pool accounts daily and make weekly returns to the CBN’s Payments System Management Department. The CBN’s own wording was not read in this build and may say trust or pool account; check the framework itselfas of 2026-11. This chapter does not say which licence applies to any company in it. Module 4 covers licences. The point for an engineer is that a daily reconciliation can be a reporting obligation as well as a habit.

Where it goes wrong

Name the failures first. Each looks like a working job.

Pairing on amount. Equal amounts pair the wrong lines, and the totals still agree. The lesson on reconciliation shows this on six rows. On 56,008 lines it is worse, because round amounts repeat all day.

Keying a dictionary on the reference. It is tempting, and it is quick. It drops the 98 returns, because a return shares its payout’s reference, and it hides the two duplicate bookings, because a second line overwrites the first. The job reports seven breaks, not nine, and the bridge is out by 4,590,802 kobo. The break at the end of the lab runs it.

A tolerance on amounts. The ₦25 differences disappear. So would a fee the bank started charging last month.

Fixing the report instead of the source. A person who edits the reconciliation result to make it agree has not corrected the ledger. The break comes back tomorrow, now without an explanation. Correct the ledger with an entry, then let the reconciliation show agreement.

A suspense account that is never cleared. It starts as a place to put an unknown and becomes the place mistakes are forgotten. Owners and ages are what stop it.

Reconciling a ledger to itself. If the “statement” side is built from your own data, the result is always zero and means nothing.

Mismatched windows. A statement for 1 to 30 June against a ledger that runs to 29 June produces differences that are only dates. Reconcile to a cut-off both sides share, and carry open items across it. This is also the break step of the card chapter.

Netting a break away. Two breaks of opposite sign look like one small one. Track them as lines.

LAB Match a 56,008-line statement, classify its breaks, and prove the gap to the kobo ~50 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with the data generated (python3 generate.py)A second terminal for the mock provider in step 4No Docker, no packages

You work in labs/finance. You create ten small files there: recon.py, pass1.py, rules.py, breaks.py, timing.py, provider_leg.py, live_break.py, correct.py, score.py and break_dict.py. The data is generated at seed 42 and scale 0.1, so your numbers match the ones below. All queries run through Python’s sqlite3 module; no sqlite3 program is needed. Do not open data/answers/breaks.csv until step 6. It is the answer key.

1. Write the matcher and run pass 1. First check the books, then save recon.py: it loads the two sides and pairs lines on reference, side and amount.

cd labs/finance
ls data/finance.sqlite >/dev/null 2>&1 || python3 generate.py
python3 check.py
accounts by type (debit-positive kobo): {'asset': 17355054889, 'equity': -5000000000, 'expense': 110590267, 'income': -221782321, 'liability': -12243862835}
settlement_bank in ledger 17,189,646,589 kobo; on the statement 17,192,741,324 kobo
OK: all invariants hold

The ledger and the statement already differ by 3,094,735 kobo. check.py accepts that because the planted breaks explain it. Your job is to find them and say why. (If you ran loans.py earlier, check.py also prints a line about the loan book.)

"""Match the ledger's settlement_bank entries against the partner bank's statement.

Money is integer kobo throughout. A line's side is CR (money in) or DR (money out), the
bank's words. The ledger debits settlement_bank when money comes in, so its side is flipped.
"""
import sqlite3
from collections import defaultdict, namedtuple

DB = "data/finance.sqlite"
L = namedtuple("L", "txn kind ref side kobo at")                    # a ledger line
S = namedtuple("S", "line value_date at side kobo ref narration")   # a statement line


def load(path=DB):
    db = sqlite3.connect(path)
    ledger = [L(*r) for r in db.execute("""
        SELECT t.id, t.kind, t.external_ref,
               CASE e.direction WHEN 'debit' THEN 'CR' ELSE 'DR' END, e.amount_kobo, e.posted_at
        FROM entries e
        JOIN accounts a ON a.id = e.account_id AND a.code = 'settlement_bank'
        JOIN transactions t ON t.id = e.transaction_id
        ORDER BY e.id""")]
    statement = [S(*r) for r in db.execute("""
        SELECT line, value_date, booked_at, direction, amount_kobo, reference, narration
        FROM bank_statement ORDER BY line""")]
    return ledger, statement


def signed(side, kobo):
    return kobo if side == "CR" else -kobo


def closing_balance(path=DB):
    """The bank's own running balance on the last statement line."""
    db = sqlite3.connect(path)
    return db.execute("SELECT balance_kobo FROM bank_statement ORDER BY line DESC LIMIT 1").fetchone()[0]


def pair_exact(ledger, statement):
    """Pass 1: pair a ledger line with a statement line of the same reference, side and amount.
    Each statement line is used once. Returns the pairs and what is left on each side."""
    free = defaultdict(list)
    for s in statement:
        free[(s.ref, s.side, s.kobo)].append(s)
    pairs, ledger_left = [], []
    for l in ledger:
        bucket = free.get((l.ref, l.side, l.kobo))
        if bucket:
            pairs.append((l, bucket.pop(0)))
        else:
            ledger_left.append(l)
    statement_left = sorted((s for b in free.values() for s in b), key=lambda s: s.line)
    return pairs, ledger_left, statement_left


def effect(l, s):
    """What a break does to bank minus ledger, in kobo."""
    return (signed(s.side, s.kobo) if s else 0) - (signed(l.side, l.kobo) if l else 0)

Now save pass1.py and run it:

from collections import Counter
import recon

ledger, statement = recon.load()
print(f"ledger lines on settlement_bank: {len(ledger):,}")
print(f"bank statement lines:            {len(statement):,}")

refs = Counter(s.ref for s in statement)
repeated = {r for r, n in refs.items() if n > 1}
kinds = Counter(s.narration.split(" C0")[0] for s in statement if s.ref in repeated)
print(f"references on more than one statement line: {len(repeated)}")
print(f"   the lines on them, by narration: {dict(kinds)}")

pairs, ledger_left, statement_left = recon.pair_exact(ledger, statement)
print(f"paired on reference + side + amount: {len(pairs):,}")
print(f"left in the ledger: {len(ledger_left)}   left on the statement: {len(statement_left)}")
for l in ledger_left:
    print(f"   ledger    {l.ref[:8]}.. {l.side} {l.kobo:>9,}  {l.kind}")
for s in statement_left:
    print(f"   statement {s.ref[:8]}.. {s.side} {s.kobo:>9,}  line {s.line}  {s.narration}")
python3 pass1.py
ledger lines on settlement_bank: 56,007
bank statement lines:            56,008
references on more than one statement line: 100
   the lines on them, by narration: {'NIP OUTWARD': 102, 'NIP RETURN': 98}
paired on reference + side + amount: 56,002
left in the ledger: 5   left on the statement: 6
   ledger    55981392.. DR 1,425,991  payout_nip
   ledger    66504728.. DR   857,489  payout_nip
   ledger    28888239.. DR   103,559  payout_nip
   ledger    63702839.. DR 1,221,260  payout_nip
   ledger    48860510.. DR   642,657  payout_nip
   statement 44945488.. DR   251,906  line 7398  NIP OUTWARD C0001672
   statement 75551832.. CR   103,200  line 16992  NIP INWARD UNKNOWN
   statement 28888239.. DR   106,059  line 23301  NIP OUTWARD C0000454
   statement 63702839.. DR 1,223,760  line 26926  NIP OUTWARD C0001960
   statement 69506902.. DR 4,338,896  line 39322  NIP OUTWARD C0000344
   statement 22035269.. CR 4,661,200  line 51005  NIP INWARD UNKNOWN

Of 56,008 statement lines, 56,002 have a partner on the first pass. Eleven lines are left, five in the ledger and six on the statement. The 100 repeated references are 98 returned payouts (the NIP RETURN lines, each with its payout’s reference on the other side) and 2 references on two lines of the same payout. The statement has one more line than the ledger, but the eleven are not one extra: the sides lose and gain different things. Two references appear in both lists with different amounts: 28888239.. (103,559 against 106,059) and 63702839.. (1,221,260 against 1,223,760).

2. Place every leftover. Save rules.py, which is passes 2 to 5, and breaks.py, which runs them and checks the result against the gap.

"""Passes 2 to 5: place every line that pass 1 could not pair."""


def classify(ledger, statement, pairs, ledger_left, statement_left):
    """Returns (kind, reference, ledger line or None, statement line or None) for every
    break, and the lines no rule could place."""
    stmt_refs = {s.ref for s in statement}
    ledger_refs = {l.ref for l in ledger}
    paired = {(s.ref, s.side, s.kobo) for _, s in pairs}
    by_ref = {(s.ref, s.side): s for s in statement_left}
    breaks, used = [], set()
    for l in ledger_left:                       # 2. same reference and side, another amount
        s = by_ref.get((l.ref, l.side))
        if s:
            breaks.append(("amount_mismatch", l.ref, l, s))
            used.update([("L", l.txn), ("S", s.line)])
    for s in statement_left:                    # 3. a second line for something already paired
        if ("S", s.line) not in used and (s.ref, s.side, s.kobo) in paired:
            breaks.append(("duplicate_on_statement", s.ref, None, s))
            used.add(("S", s.line))
    for l in ledger_left:                       # 4. in the ledger, nowhere on the statement
        if ("L", l.txn) not in used and l.ref not in stmt_refs:
            breaks.append(("missing_from_statement", l.ref, l, None))
            used.add(("L", l.txn))
    for s in statement_left:                    # 5. on the statement, nowhere in the ledger
        if ("S", s.line) not in used and s.ref not in ledger_refs:
            breaks.append(("unapplied_credit", s.ref, None, s))
            used.add(("S", s.line))
    unplaced = [l for l in ledger_left if ("L", l.txn) not in used] + \
               [s for s in statement_left if ("S", s.line) not in used]
    return breaks, unplaced
from collections import Counter
import recon
import rules

ledger, statement = recon.load()
pairs, ledger_left, statement_left = recon.pair_exact(ledger, statement)
breaks, unplaced = rules.classify(ledger, statement, pairs, ledger_left, statement_left)


def naira(kobo):
    sign = "-" if kobo < 0 else ""
    kobo = abs(kobo)
    return f"{sign}₦{kobo // 100:,}.{kobo % 100:02d}"


net = gross = 0
print(f"{'kind':<24}{'reference':<12}{'ledger':>11}{'statement':>11}{'bank - ledger':>15}")
for kind, ref, l, s in sorted(breaks):
    e = recon.effect(l, s)
    net += e
    gross += abs(e)
    print(f"{kind:<24}{ref[:8] + '..':<12}{l.kobo if l else 0:>11,}{s.kobo if s else 0:>11,}{e:>15,}")
print()
print("breaks by kind:", dict(Counter(b[0] for b in breaks)))
print("lines no rule could place:", len(unplaced))
print(f"net effect on bank minus ledger:   {net:>11,} kobo ({naira(net)})")
print(f"gross value of the nine breaks:    {gross:>11,} kobo ({naira(gross)})")

bank = recon.closing_balance()
ledger_total = sum(recon.signed(l.side, l.kobo) for l in ledger)
print(f"bank closing balance {bank:,}; ledger settlement_bank {ledger_total:,}; gap {bank - ledger_total:,}")
print("the breaks explain the gap exactly:", bank - ledger_total == net)
python3 breaks.py
kind                    reference        ledger  statement  bank - ledger
amount_mismatch         28888239..      103,559    106,059         -2,500
amount_mismatch         63702839..    1,221,260  1,223,760         -2,500
duplicate_on_statement  44945488..            0    251,906       -251,906
duplicate_on_statement  69506902..            0  4,338,896     -4,338,896
missing_from_statement  48860510..      642,657          0        642,657
missing_from_statement  55981392..    1,425,991          0      1,425,991
missing_from_statement  66504728..      857,489          0        857,489
unapplied_credit        22035269..            0  4,661,200      4,661,200
unapplied_credit        75551832..            0    103,200        103,200

breaks by kind: {'amount_mismatch': 2, 'duplicate_on_statement': 2, 'missing_from_statement': 3, 'unapplied_credit': 2}
lines no rule could place: 0
net effect on bank minus ledger:     3,094,735 kobo (₦30,947.35)
gross value of the nine breaks:     12,286,339 kobo (₦122,863.39)
bank closing balance 17,192,741,324; ledger settlement_bank 17,189,646,589; gap 3,094,735
the breaks explain the gap exactly: True

Nine breaks of four kinds, and none left unplaced. Redo the net by hand: 642,657 + 1,425,991 + 857,489 + 4,661,200 + 103,200 = 7,690,537 is the positive side, and 2,500 + 2,500 + 251,906 + 4,338,896 = 4,595,802 the negative side, so 7,690,537 − 4,595,802 = 3,094,735. That is the gap check.py printed. The gross value is 7,690,537 + 4,595,802 = 12,286,339 kobo: almost four times the net. The duplicate of 4,338,896 and the credit of 4,661,200 almost cancel, which is why a net gap alone understates the work.

3. Separate timing from breaks. Save timing.py. It counts the value-date effect, compares days two ways, and closes the bridge on every day.

import bisect
import sqlite3
from collections import defaultdict
import recon
import rules

ledger, statement = recon.load()
pairs, ledger_left, statement_left = recon.pair_exact(ledger, statement)
breaks, _ = rules.classify(ledger, statement, pairs, ledger_left, statement_left)

# 1. The value date is not always the booking date.
late = [s for s in statement if s.value_date != s.at[:10]]
print(f"statement lines whose value date is not their booking date: {len(late):,}")
print(f"   hours they were booked in: {sorted({s.at[11:13] for s in late})}")
print(f"   example: line {late[0].line} booked {late[0].at}, value date {late[0].value_date}")

# 2. Compare each day's net movement, counting the bank's lines two ways.
led_day, val_day, book_day = defaultdict(int), defaultdict(int), defaultdict(int)
for l in ledger:
    led_day[l.at[:10]] += recon.signed(l.side, l.kobo)
for s in statement:
    val_day[s.value_date] += recon.signed(s.side, s.kobo)
    book_day[s.at[:10]] += recon.signed(s.side, s.kobo)
days = sorted(set(led_day) | set(val_day) | set(book_day))
print(f"days with any movement: {len(days)}")
print(f"days where the ledger's net differs from the bank's, by value date:   {sum(led_day[d] != val_day[d] for d in days)}")
print(f"days where the ledger's net differs from the bank's, by booking date: {sum(led_day[d] != book_day[d] for d in days)}")

# 3. The bridge. The bank's balance at the close of each value date, less the ledger's balance
#    at the close of the same date, must equal what timing and the breaks explain.
db = sqlite3.connect(recon.DB)
value_dates = [s.value_date for s in statement]
balances = [r[0] for r in db.execute("SELECT balance_kobo FROM bank_statement ORDER BY line")]

in_transit = defaultdict(int)      # day -> net of ledger lines booked that day, valued the next
for l, s in pairs:
    if l.at[:10] != s.value_date:
        in_transit[l.at[:10]] += recon.signed(l.side, l.kobo)
break_starts = defaultdict(int)    # day -> effect of the breaks that begin that day
for kind, ref, l, s in breaks:
    break_starts[l.at[:10] if l else s.value_date] += recon.effect(l, s)

ledger_cum = breaks_cum = 0
gap_days = transit_days = 0
unexplained = []
for d in days:
    ledger_cum += led_day[d]
    breaks_cum += break_starts[d]
    i = bisect.bisect_right(value_dates, d)            # last bank line valued on or before d
    gap = (balances[i - 1] if i else 0) - ledger_cum
    gap_days += gap != 0
    transit_days += in_transit[d] != 0
    if gap != breaks_cum - in_transit[d]:
        unexplained.append(d)
print(f"days where the bank's closing balance differs from the ledger's: {gap_days}")
print(f"days with ledger lines in transit at the close: {transit_days}")
print(f"days the gap is not explained by timing plus the nine breaks: {len(unexplained)}")
python3 timing.py
statement lines whose value date is not their booking date: 3,114
   hours they were booked in: ['23']
   example: line 11 booked 2026-01-04T23:13:26+01:00, value date 2026-01-05
days with any movement: 180
days where the ledger's net differs from the bank's, by value date:   174
days where the ledger's net differs from the bank's, by booking date: 9
days where the bank's closing balance differs from the ledger's: 171
days with ledger lines in transit at the close: 170
days the gap is not explained by timing plus the nine breaks: 0

3,114 lines were booked in the 23:00 hour and valued the next day. None is a break. Count the bank’s lines by value date and the two daily nets differ on 174 of 180 days. Count them by booking date and they differ on 9, one for each break. The closing balances are a different measure, running totals rather than one day’s movement, and they differ on 171 days, which is the Predict’s answer: 170 days of timing, and the breaks that keep the gap open afterwards. The last line is the proof: on every one of the 180 days, bank minus ledger equals the breaks so far less the items in transit. Nothing is unaccounted for.

4. Add the provider leg. Start the mock provider in a second terminal and leave it running:

cd labs/finance
python3 mock_provider.py

Save provider_leg.py. It checks comparison A (each capture on the provider’s report against the ledger’s card fundings) and comparison C (three nets against each other) on every settlement day.

import datetime as dt
import json
import sqlite3
import urllib.request
from collections import defaultdict

BASE = "http://127.0.0.1:8101"
HEAD = {"Authorization": "Bearer sk_test_owoleaf_mock", "Content-Type": "application/json"}


def call(method, path, body=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(BASE + path, data=data, headers=HEAD, method=method)
    with urllib.request.urlopen(req) as r:
        return json.load(r)


db = sqlite3.connect("data/finance.sqlite")

# The ledger's side: every successful card funding by capture day, and each day's settlement.
funded = defaultdict(set)
for ref, kobo, at in db.execute("""SELECT external_ref, amount_kobo, created_at FROM transactions
                                   WHERE kind = 'funding_card' AND status = 'succeeded'"""):
    funded[at[:10]].add((ref, kobo))
booked_net = {at[:10]: gross - fee for gross, fee, at in db.execute(
    "SELECT amount_kobo, fee_kobo, created_at FROM transactions WHERE kind = 'card_settlement'")}

# The bank's side: the day and amount of each CARD SETTLEMENT line.
bank = dict(db.execute("SELECT value_date, amount_kobo FROM bank_statement WHERE narration = 'CARD SETTLEMENT'"))

days = lines = provider_only = ledger_only = three_way = 0
for settle_day, bank_kobo in sorted(bank.items()):
    captured = (dt.date.fromisoformat(settle_day) - dt.timedelta(days=1)).isoformat()
    report = call("GET", "/settlements?date=" + settle_day)
    theirs = {(x["reference"], x["amount_kobo"]) for x in report["lines"]}
    ours = funded.get(captured, set())
    days += 1
    lines += len(theirs)
    provider_only += len(theirs - ours)
    ledger_only += len(ours - theirs)
    three_way += booked_net[settle_day] == report["net_kobo"] == bank_kobo
print(f"settlement days checked: {days}")
print(f"lines in the provider's reports: {lines:,}")
print(f"on the provider's report, not in the ledger: {provider_only}")
print(f"in the ledger, not on the provider's report: {ledger_only}")
print(f"days where ledger net, provider net and statement line all agree: {three_way} of {days}")

unsettled = {d: len(v) for d, v in funded.items()
             if (dt.date.fromisoformat(d) + dt.timedelta(days=1)).isoformat() not in bank}
print(f"card fundings with no settlement yet, by capture day: {unsettled}")
python3 provider_leg.py
settlement days checked: 174
lines in the provider's reports: 10,171
on the provider's report, not in the ledger: 0
in the ledger, not on the provider's report: 0
days where ledger net, provider net and statement line all agree: 174 of 174
card fundings with no settlement yet, by capture day: {'2026-06-29': 109}

The card leg is clean. 10,171 captures were reported and all 10,171 are in the ledger, and the three nets agree to the kobo on all 174 days. The 109 fundings of 29 June add up with them to the 10,280 successful card fundings: they are not breaks, only a day the data ends before. Notice also what step 2 told you: none of the nine planted breaks is on the card leg.

Now make the provider disagree with the ledger. Save live_break.py: a customer pays by card, the ledger is never told, and a part of the payment is refunded.

import datetime as dt
import json
import sqlite3
import time
import urllib.request

BASE = "http://127.0.0.1:8101"
HEAD = {"Authorization": "Bearer sk_test_owoleaf_mock", "Content-Type": "application/json"}


def call(method, path, body=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(BASE + path, data=data, headers=HEAD, method=method)
    with urllib.request.urlopen(req) as r:
        return json.load(r)


call("POST", "/admin/reset")            # a clean provider, so a second run prints the same

# A customer pays ₦18,500 by card. Nothing tells the ledger: say the webhook was lost.
ref = "WREN-PREPAY-001"
c = call("POST", "/charges", {"reference": ref, "amount_kobo": 1_850_000, "customer_ref": "C0000042",
                              "card_number": "4111111111110001", "metadata": {"order": "prepay"}})["charge"]
print(f"charge {ref}: status={c['status']}, amount={c['amount_kobo']}, provider fee={c['fee_kobo']}")

# The merchant refunds ₦5,000 of it; the refund processes after a few seconds.
r = call("POST", "/refunds", {"reference": ref, "amount_kobo": 500_000})["refund"]
time.sleep(6)
r = call("GET", "/refunds/" + r["id"])["refund"]
print(f"refund: status={r['status']}, amount={r['amount_kobo']}")

# The report the provider will pay the next day.
tomorrow = (dt.date.fromisoformat(c["paid_at"][:10]) + dt.timedelta(days=1)).isoformat()
rep = call("GET", "/settlements?date=" + tomorrow)
print(f"tomorrow's settlement: gross {rep['gross_kobo']}, fee {rep['fee_kobo']}, "
      f"refunds {rep['refunds_kobo']}, net {rep['net_kobo']}")
for x in rep["lines"]:
    print(f"   line {x['reference']}: {x['amount_kobo']} kobo, source={x['source']}")

# Does the ledger know it?
db = sqlite3.connect("data/finance.sqlite")
known = db.execute("SELECT COUNT(*) FROM transactions WHERE external_ref = ?", (ref,)).fetchone()[0]
print(f"transactions in the ledger with reference {ref}: {known}")
print(f"the provider will pay {rep['net_kobo']} kobo that no ledger entry accounts for")
python3 live_break.py
charge WREN-PREPAY-001: status=success, amount=1850000, provider fee=18500
refund: status=processed, amount=500000
tomorrow's settlement: gross 1850000, fee 18500, refunds 500000, net 1331500
   line WREN-PREPAY-001: 1850000 kobo, source=mock
transactions in the ledger with reference WREN-PREPAY-001: 0
the provider will pay 1331500 kobo that no ledger entry accounts for

The provider will pay ₦13,315.00 for a capture that the ledger has never heard of: 1,850,000 − 18,500 − 500,000 = 1,331,500 kobo. source=mock marks the line as one made through the mock, not from the generated ledger. This is a provider-only line, the first direction in the chapter. Comparison A on that date would report one line on the provider’s report that the ledger lacks. (provider_leg.py walks the statement’s settlement days, so it does not visit this one: you would point its loop at that date.) Look the line up with GET /charges/WREN-PREPAY-001 to see which customer to credit. The provider keeps no state about what your ledger knows, so a lost webhook is yours to detect.

5. Propose, approve and post the corrections in a copy. Save correct.py. Run with no argument, it copies the books and writes one proposed adjustment for each break into a table, adjustment_proposals, without posting anything. Run with --approve and a name, it posts the proposals, but only if the approver is not the person who proposed them. That is the four-eyes control from the plan above: Morayo proposes, a colleague approves. After posting, the script proves the ledger now equals the bank and runs tomorrow’s matcher over the corrected file.

import shutil
import sqlite3
import sys
from collections import Counter
import recon
import rules

SRC, DST = "data/finance.sqlite", "data/corrected.sqlite"
PROPOSER = "morayo"
AT = "2026-06-30T00:00:00+01:00"


def legs(kind, l, s):
    """What each kind of break is posted as: debit account, credit account, kobo."""
    if kind == "missing_from_statement":    # the bank never paid it out: the cash is still there
        return "settlement_bank", "suspense", l.kobo
    if kind == "unapplied_credit":          # cash arrived that no wallet owns yet
        return "settlement_bank", "suspense", s.kobo
    if kind == "duplicate_on_statement":    # the bank took it twice: we have a claim on the bank
        return "bank_receivable", "settlement_bank", s.kobo
    if kind == "amount_mismatch":           # the bank took more than we posted
        return "bank_receivable", "settlement_bank", s.kobo - l.kobo


def propose():
    """Four-eyes, first half: write the proposals. Not one entry is posted."""
    shutil.copyfile(SRC, DST)          # never correct the original books
    db = sqlite3.connect(DST)
    db.execute("""CREATE TABLE adjustment_proposals (
                  ref TEXT PRIMARY KEY, kind TEXT, debit TEXT, credit TEXT, amount_kobo INTEGER,
                  proposed_by TEXT, status TEXT, approved_by TEXT)""")
    ledger, statement = recon.load(SRC)
    pairs, ledger_left, statement_left = recon.pair_exact(ledger, statement)
    breaks, _ = rules.classify(ledger, statement, pairs, ledger_left, statement_left)
    for kind, ref, l, s in breaks:
        debit, credit, kobo = legs(kind, l, s)
        db.execute("INSERT INTO adjustment_proposals VALUES (?, ?, ?, ?, ?, ?, 'proposed', NULL)",
                   (ref, kind, debit, credit, kobo, PROPOSER))
    db.commit()
    print(f"{len(breaks)} adjustments proposed by {PROPOSER} in {DST}; none is posted yet")
    for ref, kind, debit, credit, kobo in db.execute(
            "SELECT ref, kind, debit, credit, amount_kobo FROM adjustment_proposals ORDER BY kind, ref"):
        print(f"   {kind:<24}{ref[:8]}..  debit {debit:<16} credit {credit:<16}{kobo:>10,}")
    print(f"entries in the ledger: {db.execute('SELECT COUNT(*) FROM entries').fetchone()[0]:,} (unchanged)")


def approve(approver):
    """Four-eyes, second half: a different person approves, and only then does anything post."""
    db = sqlite3.connect(DST)
    proposers = {p for (p,) in db.execute("SELECT DISTINCT proposed_by FROM adjustment_proposals WHERE status = 'proposed'")}
    if not proposers:
        sys.exit("nothing waiting for approval")
    if approver.lower() in proposers:
        sys.exit(f"refused: {approver} proposed these adjustments and cannot approve them")
    rows = db.execute("SELECT ref, kind, debit, credit, amount_kobo FROM adjustment_proposals WHERE status = 'proposed'").fetchall()

    # Three new accounts. Suspense is money at the bank that the ledger cannot place yet (a
    # liability); the receivable is a claim on the bank (an asset); bank charges are an expense.
    for code, name, typ in [("suspense", "Money at the bank not yet placed", "liability"),
                            ("bank_receivable", "Claims on the partner bank", "asset"),
                            ("bank_charges", "Fees taken by the partner bank", "expense")]:
        db.execute("INSERT INTO accounts (code, name, type, currency, opened_at) VALUES (?, ?, ?, 'NGN', ?)",
                   (code, name, typ, AT))
    acct = dict(db.execute("SELECT code, id FROM accounts"))

    for ref, kind, debit, credit, kobo in rows:
        cur = db.execute("""INSERT INTO transactions (kind, status, amount_kobo, fee_kobo, rail, external_ref, created_at)
                            VALUES ('reconciliation_adjustment', 'succeeded', ?, 0, 'internal', ?, ?)""",
                         (kobo, "RECON-" + ref, AT))
        for account, direction in ((debit, "debit"), (credit, "credit")):
            db.execute("""INSERT INTO entries (transaction_id, account_id, direction, amount_kobo, posted_at)
                          VALUES (?, ?, ?, ?, ?)""", (cur.lastrowid, acct[account], direction, kobo, AT))
        db.execute("UPDATE adjustment_proposals SET status = 'posted', approved_by = ? WHERE ref = ?", (approver.lower(), ref))
    db.commit()
    report(db, len(rows), approver)


def balance(db, code):              # debit minus credit, in kobo
    return db.execute("""SELECT COALESCE(SUM(CASE e.direction WHEN 'debit' THEN e.amount_kobo ELSE -e.amount_kobo END), 0)
                         FROM entries e JOIN accounts a ON a.id = e.account_id WHERE a.code = ?""", (code,)).fetchone()[0]


def report(db, posted, approver):
    bank = recon.closing_balance(DST)
    print(f"{approver} approved; posted {posted} adjustments into {DST}")
    print(f"settlement_bank {balance(db, 'settlement_bank'):,}; bank statement {bank:,}; difference {bank - balance(db, 'settlement_bank'):,}")
    print(f"suspense {-balance(db, 'suspense'):,} (cash we cannot place yet); bank_receivable {balance(db, 'bank_receivable'):,} (the bank owes us)")
    print(f"suspense minus receivable: {-balance(db, 'suspense') - balance(db, 'bank_receivable'):,}")
    whole = db.execute("SELECT SUM(CASE direction WHEN 'debit' THEN amount_kobo ELSE -amount_kobo END) FROM entries").fetchone()[0]
    print(f"every debit less every credit in the whole ledger: {whole}")

    # Tomorrow's run reads this file. What does the matcher say now?
    ledger2, statement2 = recon.load(DST)
    pairs2, ll2, sl2 = recon.pair_exact(ledger2, statement2)
    breaks2, _ = rules.classify(ledger2, statement2, pairs2, ll2, sl2)
    print("matcher on the corrected file:", dict(Counter(b[0] for b in breaks2)))
    print("   ledger lines behind those breaks:", dict(Counter(b[2].kind for b in breaks2 if b[2])))
    print("   net effect on bank minus ledger:", sum(recon.effect(l, s) for _, _, l, s in breaks2))


if len(sys.argv) == 3 and sys.argv[1] == "--approve":
    approve(sys.argv[2])
elif len(sys.argv) == 1:
    propose()
else:
    sys.exit("usage: python3 correct.py             (propose)\n       python3 correct.py --approve NAME")
python3 correct.py
python3 correct.py --approve morayo
python3 correct.py --approve tamunosaki
python3 check.py --db data/corrected.sqlite
9 adjustments proposed by morayo in data/corrected.sqlite; none is posted yet
   amount_mismatch         28888239..  debit bank_receivable  credit settlement_bank      2,500
   amount_mismatch         63702839..  debit bank_receivable  credit settlement_bank      2,500
   duplicate_on_statement  44945488..  debit bank_receivable  credit settlement_bank    251,906
   duplicate_on_statement  69506902..  debit bank_receivable  credit settlement_bank  4,338,896
   missing_from_statement  48860510..  debit settlement_bank  credit suspense           642,657
   missing_from_statement  55981392..  debit settlement_bank  credit suspense         1,425,991
   missing_from_statement  66504728..  debit settlement_bank  credit suspense           857,489
   unapplied_credit        22035269..  debit settlement_bank  credit suspense         4,661,200
   unapplied_credit        75551832..  debit settlement_bank  credit suspense           103,200
entries in the ledger: 191,103 (unchanged)
refused: morayo proposed these adjustments and cannot approve them
tamunosaki approved; posted 9 adjustments into data/corrected.sqlite
settlement_bank 17,192,741,324; bank statement 17,192,741,324; difference 0
suspense 7,690,537 (cash we cannot place yet); bank_receivable 4,595,802 (the bank owes us)
suspense minus receivable: 3,094,735
every debit less every credit in the whole ledger: 0
matcher on the corrected file: {'amount_mismatch': 2, 'duplicate_on_statement': 2, 'missing_from_statement': 12, 'unapplied_credit': 2}
   ledger lines behind those breaks: {'payout_nip': 5, 'reconciliation_adjustment': 9}
   net effect on bank minus ledger: 0
accounts by type (debit-positive kobo): {'asset': 17362745426, 'equity': -5000000000, 'expense': 110590267, 'income': -221782321, 'liability': -12251553372}
settlement_bank in ledger 17,192,741,324 kobo; on the statement 17,192,741,324 kobo
FAIL
  6. bank minus ledger is 0 kobo; the planted breaks explain 3094735

Nothing was posted until the second person approved: the first run leaves the ledger at 191,103 entries, and morayo is refused when she tries to approve her own proposals. After tamunosaki approves, the ledger equals the bank to the kobo, and the books still balance. The two new balances carry the gap: suspense of ₦76,905.37 (7,690,537 kobo) held for someone, a receivable of ₦45,958.02 (4,595,802 kobo) owed by the bank, and 7,690,537 − 4,595,802 = 3,094,735. Two things need a second look. First, the matcher on the corrected file still reports every break, plus 9 more that are the adjustments, and the net is 0: the balance agrees but no item is closed, because the adjustments are lines on settlement_bank that the bank will never show. Link each adjustment to its break, here by the RECON- prefix on the reference, and the nine adjustments stop appearing as new breaks; each original break then shows as explained, open until the bank acts. Second, check.py fails invariant 6 on purpose. That invariant says the books differ from the bank by the planted breaks, and they no longer do. The check is for the uncorrected data. Do not run it on your corrected file in a pipeline.

6. Only now, open the answer key. Save score.py, which compares your nine breaks with data/answers/breaks.csv by kind and reference.

import csv
import recon
import rules

ledger, statement = recon.load()
pairs, ledger_left, statement_left = recon.pair_exact(ledger, statement)
breaks, _ = rules.classify(ledger, statement, pairs, ledger_left, statement_left)
mine = {(kind, ref) for kind, ref, l, s in breaks}

key = list(csv.DictReader(open("data/answers/breaks.csv")))
truth = {(row["kind"], row["reference"]) for row in key}

print(f"the key has {len(key)} breaks; your matcher reported {len(mine)}")
print(f"found, with the right kind and reference: {len(mine & truth)}")
print(f"missed: {len(truth - mine)}   invented: {len(mine - truth)}")
for row in key:
    print(f"   {row['kind']:<24}{row['reference'][:8]}..  {row['story']}")
python3 score.py
the key has 9 breaks; your matcher reported 9
found, with the right kind and reference: 9
missed: 0   invented: 0
   amount_mismatch         28888239..  the bank debited the fee as well as the principal
   amount_mismatch         63702839..  the bank debited the fee as well as the principal
   duplicate_on_statement  44945488..  the bank booked the same payout twice
   duplicate_on_statement  69506902..  the bank booked the same payout twice
   missing_from_statement  48860510..  posted in the ledger, never reached the bank
   missing_from_statement  66504728..  posted in the ledger, never reached the bank
   missing_from_statement  55981392..  posted in the ledger, never reached the bank
   unapplied_credit        75551832..  money arrived with no matching ledger entry
   unapplied_credit        22035269..  money arrived with no matching ledger entry

Nine of nine, nothing invented, and the 3,114 value-date differences correctly left alone. Your matcher used the key’s four kind names, so the comparison is a set comparison, but the matching never read the key. The story column is what only the bank, or the switch, could tell you. Your code could say that the two amount-mismatch lines differ by 2,500 kobo each, and it was the story that made that a fee.

Save break_dict.py, which finds breaks the tempting way: one dictionary per side, keyed on the reference.

import recon

ledger, statement = recon.load()
by_ref_ledger = {l.ref: l for l in ledger}       # one line per reference: the tempting shortcut
by_ref_stmt = {s.ref: s for s in statement}
print(f"ledger: {len(by_ref_ledger):,} references for {len(ledger):,} lines; "
      f"statement: {len(by_ref_stmt):,} references for {len(statement):,} lines")

found = []
for ref, l in by_ref_ledger.items():
    s = by_ref_stmt.get(ref)
    if s is None:
        found.append(("missing_from_statement", l, None))
    elif s.kobo != l.kobo:
        found.append(("amount_mismatch", l, s))
for ref, s in by_ref_stmt.items():
    if ref not in by_ref_ledger:
        found.append(("unapplied_credit", None, s))
print(f"breaks found: {len(found)}")

explained = sum(recon.effect(l, s) for _, l, s in found)
gap = recon.closing_balance() - sum(recon.signed(l.side, l.kobo) for l in ledger)
print(f"gap between bank and ledger {gap:,}; explained {explained:,}; unexplained {gap - explained:,}")

Run it with python3 break_dict.py. It prints ledger: 55,909 references for 56,007 lines; statement: 55,908 references for 56,008 lines, then breaks found: 7, then gap between bank and ledger 3,094,735; explained 7,685,537; unexplained -4,590,802. The dictionaries lose 98 ledger lines and 100 statement lines, because a reference shared by a payout and its return, or by a booking and its duplicate, keeps only the last line. Seven breaks look fine and the job seems to work. The two duplicates, 251,906 and 4,338,896 kobo, are gone, and the unexplained figure is exactly their sum with the sign of the bridge. A job that closed its bridge would have caught this the first time it ran. Fix it by putting the side in the key and counting lines on each side, then run score.py-style numbers to confirm that you are back to nine.

ARTEFACT Write the daily reconciliation report and one bank ticket ~45 MIN
YOU PRODUCEDaily reconciliation report with a break ticket to the partner bank

Template

Line numbers, booking times and ages are not printed by the lab’s steps. Save facts.py next to recon.py and rules.py; it prints them for every break. Give it the date of your report.

import datetime as dt
import sys
import recon
import rules

as_at = dt.date.fromisoformat(sys.argv[1])          # the date of the report, e.g. 2026-06-30
ledger, statement = recon.load()
pairs, ledger_left, statement_left = recon.pair_exact(ledger, statement)
breaks, _ = rules.classify(ledger, statement, pairs, ledger_left, statement_left)

for kind, ref, l, s in sorted(breaks):
    on_statement = [x for x in statement if x.ref == ref]
    in_ledger = [x for x in ledger if x.ref == ref]
    first = min(x.at[:10] for x in on_statement + in_ledger)
    print(f"{kind}  {recon.effect(l, s):+,} kobo  age {(as_at - dt.date.fromisoformat(first)).days} days (first seen {first})")
    print(f"   reference {ref}")
    for x in on_statement:
        print(f"   statement line {x.line}: {x.at[:19]}  {x.side} {x.kobo:,}  {x.narration}")
    for x in in_ledger:
        print(f"   ledger {x.kind}: {x.at[:19]}  {x.side} {x.kobo:,}")
python3 facts.py 2026-06-30

An age is the days from the day a break first appears, on either side, to the report date. A missing payout has no statement line, so the ticket quotes the ledger entry and says that no statement line carries the reference. Now the document to copy.

# Reconciliation report: <account>, as at <date>
Written and proposed by <analyst> · Postings approved by <controller>, not the analyst · Statement cut-off <date>
Scope: <which ledger account and which statement, from which date>
Decision needed: <what the reader must approve or choose, by when>

## Bridge
| Ledger balance | <kobo> |
| + breaks, net (bank minus ledger) | <kobo> |
| − items in transit at the cut-off (ledger lines booked that day, valued the next) | <kobo> |
| = Bank closing balance | <kobo> |
Unexplained: <kobo>. If not zero, stop: the job is wrong, not the bank.

## Breaks by kind
| Kind | Count | Gross | Net | Owner | Age in days, each |

## Proposed postings (nothing posted until approved)
| Debit | Credit | Kobo | Break closed | Proposed by |

## Ticket to the bank
Subject: <one break, one line>
What the statement shows: <reference, line numbers, dates, amounts>
What our ledger shows: <entry, date, amount>
Action asked: <one action> by <date>
We do not know: <the cause>

## How this report could be wrong
<one way, and what would show it>
WORKED EXAMPLE

Owoleaf, as at 30 June 2026. Scope: settlement_bank against the partner bank’s statement, to 29 June. Morayo writes it each morning and proposes the postings. At a real company a finance operations analyst writes it and the finance controller signs the postings; in the lab Tamunosaki is the second person who approves. Decision needed: approve the nine postings, and choose retry or return for the three missing payouts, before the month-end close.

Bridge. Ledger settlement_bank is 17,189,646,589 kobo (₦171,896,465.89). The nine breaks net to +3,094,735 kobo. Nothing is in transit at the cut-off: the last statement line, booked 29 June at 23:57, is valued 30 June, so the bank’s balance already counts it. That gives 17,192,741,324 kobo (₦171,927,413.24), the bank’s closing balance. Unexplained: 0. Ages, line numbers and times below come from facts.py 2026-06-30.

Kind Count Gross Net Owner Age in days
Missing from statement 3 ₦29,261.37 +₦29,261.37 Morayo, asks the switch 125, 69, 47
Duplicate on statement 2 ₦45,908.02 −₦45,908.02 Morayo, asks the bank 107, 28
Amount mismatch 2 ₦50.00 −₦50.00 Morayo, asks the bank 60, 52
Unapplied credit 2 ₦47,644.00 +₦47,644.00 Morayo, asks the sender 76, 9

Total: gross ₦122,863.39, net ₦30,947.35. The net alone would hide the ₦122,863.39.

Awaiting approval. Proposed by Morayo, so she cannot approve them. Nine postings, none posted: ₦76,905.37 to suspense (missing and unapplied) and ₦45,958.02 to bank_receivable (duplicates and mismatches).

Ticket to the bank. Subject: duplicate NIP payout, ₦43,388.96, 2 June 2026. The statement shows reference 695069027453692329518982180152 on line 39286 (11:20:47) and line 39322 (12:34:47), each a debit of 4,338,896 kobo, narration NIP OUTWARD C0000344. Our ledger holds one payout, booked at 11:20:47. Action asked: reverse line 39322 and credit the account, or tell us why it is valid, by 7 July (a date we chose: five working days). We do not know why it was booked twice.

Could be wrong: the second line may be a real second payout that happens to share the reference, in which case it is not a break. A switch requery on the payout would show it. The report also cannot see a break the statement never shows, such as a payout missing from both records.

Now you

You are the finance operations analyst at a 30-person wallet company in Abuja. Its books are a second copy of the lab’s data: generate it with python3 generate.py --seed 7 --out data7, change DB in recon.py to data7/finance.sqlite, and run breaks.py and facts.py 2026-06-30. The cut-off is 29 June 2026, the last statement line. Write the report as at 30 June with a bridge, the nine breaks by kind with gross, net, owner and age, and the proposed postings. Then raise one ticket to the bank for the largest missing_from_statement break, with its reference, ledger date and amount, and ask the bank to confirm whether the payout ran. Do not guess why it did not. Your finance controller reads the report and approves the postings before the month-end close, and decides whether the missing payouts are retried or returned to wallets.

Self-check

DECIDE

Wrenpost's bank balance and ledger rarely agree, and the gap changes every day. Morayo has two people in finance operations. Tamunosaki can build one job by Friday. The month-end close is in nine days, and a customer is waiting to hear whether a ₦46,000 transfer was received. What do you build first?

READING
  1. DOC
    ISO 20022 Message Definition Report, Part 2: Bank-to-Customer Cash Management (2020/2021 edition) ISO 20022 Registration Authority, 2021

    The standard's own definition of the statement message, camt.053, and its siblings for intraday reports and notifications. Read the camt.053 section for which fields a real statement carries beyond the lab's eight columns. Skip the XML schema detail on a first pass.

  2. POST
    What is transaction reconciliation? (Modern Treasury) Modern Treasury

    A vendor's explainer on checking one financial record against a second system, the line-by-line comparison this chapter calls transaction reconciliation. Read it for the vocabulary. It is a company's own account, so treat its product framing as such.

  3. DOC
    Reconciliation overview (Modern Treasury documentation) Modern Treasury

    One vendor's design for matching rules and manual review of unmatched items, in its own documentation. Read it to compare its matching strategies with the passes in this chapter. It describes one product and its terms; it is not a standard.

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

    A payment company's account of its own ledger and the data-quality checks around it, including the idea of measuring how much money movement is explained. A vendor's claims, from its own engineering blog. Read it for the design reasoning and skip the figures.

  5. DOC
    Guidelines on Operations of Electronic Payment Channels in Nigeria (CBN, 2020) Central Bank of Nigeria, 2020

    The CBN's own text for card and POS acceptance. Read the provisions on processors' settlement reports and the T+1 timing, which this chapter takes from search summaries, and check the wording against the document.

  6. DOC
    Framework and Guidelines on Mobile Money Services in Nigeria (CBN, July 2021) Central Bank of Nigeria, 2021

    The CBN framework for mobile money operators, whose reconciliation and reporting duties this chapter cites from a legal-commentary summary only. Read it for the exact wording on daily reconciliation, the settlement account and returns to the CBN. It was not read in this build.

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: Settlement and payouts: timing, float, settlement accounts →