Suppose an agent workflow records a thousand small charges. Each estimated charge is $0.0004. A dashboard formats every row to two decimal places, exports those displayed values, then adds the export to check a $0.25 budget.

The report says $0.00. The retained-precision total is $0.40.

I would keep display formatting out of the budget calculation. Once a collector replaces a sub-cent amount with zero, a later aggregation cannot recover what it discarded. Switching the final sum to Decimal will faithfully add the wrong inputs.

These are synthetic amounts chosen to expose an accounting defect. They are not current model prices, a provider invoice or measurements of a deployed agent. The downloadable fixture makes no model calls and spends no money.

The rounding boundary changes the answer

Python’s decimal documentation describes exact decimal representation, configurable arithmetic precision and explicit rounding. Its quantize method produces a result with the requested exponent. Quantising to Decimal("0.01") gives a cents-scale value.

That is a useful presentation operation. Putting it inside the per-call collector changes the accounting policy:

# Broken for a ledger that must retain sub-cent estimates.
rounded_rows = [amount.quantize(Decimal("0.01")) for amount in amounts]
total = sum(rounded_rows)

The example fails even when every amount starts as an exact decimal string. Binary floating-point error is not required. Under the fixture’s explicit half-even rounding policy, $0.0004 becomes $0.00 before the addition happens.

A useful regression is partition invariance. If a single $0.40 estimate is represented as a thousand $0.0004 records, the accounting total should remain $0.40. That requirement is appropriate for this application ledger. It is not a universal statement about supplier invoices: a provider may have minimum charges or a documented per-request rounding rule. Reconciliation must follow the actual commercial contract.

The token-category article covers another defect, counting overlapping usage fields twice. Today’s fixture begins after the amount for each record has been calculated. Correct categories do not protect a later export that drops fractional cents.

Store a declared unit, with a bounded input contract

The fixture represents USD estimates as integer millionths of a dollar. It accepts decimal strings with at most six fractional places and converts them without a floating-point intermediate:

whole, _, fraction = text.partition(".")
units = int(whole) * 1_000_000 + int(fraction.ljust(6, "0"))

The complete parser validates the text before this conversion. It rejects negatives, booleans, floats, exponent notation, non-ASCII digits and more than six fractional places. It also bounds the whole-number part. 0.0000001 is refused rather than silently rounded to zero.

Six places are an application choice, not a claim that all model usage fits that scale. A price calculation can produce smaller fractions. In that case, choose a finer unit or a decimal arithmetic policy that preserves the required precision. Record the scale in the schema and reject inputs your representation cannot retain. Calling a field cost while leaving its currency and scale implicit makes later aggregation fragile.

This fixture handles one currency and nonnegative estimates only. Refunds, credits and currency conversion require separate rules. It has no request identity store, so duplicate records are still counted twice. A production ledger needs authenticated usage provenance and deduplication as well as correct arithmetic.

For display, the code converts the integer total to Decimal inside a local context with 40 significant digits, then quantises once using ROUND_HALF_EVEN. The bounded batch and amount sizes fit that context. The explicit context also prevents a caller’s low decimal precision from changing the displayed result. The budget comparison itself uses integers.

Compare the retained amount, even when the display looks equal

Consider a second synthetic case: a total of $0.254 against a $0.25 budget. Both can display as $0.25. The total is still over the budget.

The fixture keeps the comparison separate:

total = sum(micros(value) for value in amounts)
over_budget = total > micros(budget)

Its policy allows an amount exactly equal to the limit. That is an explicit choice tested at the boundary, not an accidental consequence of rounding. One additional millionth of a dollar changes over_budget to True.

A user interface should avoid hiding that difference. If it shows an over-budget warning beside two identical cents values, provide a higher-precision detail view or explain the comparison unit. Do not remove the warning merely to make the screen look consistent.

There is a larger limitation: this is retrospective accounting. An over-budget flag after completed calls cannot prevent those calls from spending money. Enforcing a prospective limit requires a separate admission mechanism that reserves an upper-bound amount before dispatch, includes outstanding work and reconciles actual usage afterwards. Concurrent workers need an atomic reservation protocol. None of that is implemented by this report function.

Unknown usage also needs its own state. The fixture refuses None; it does not translate missing usage to a zero charge. If a timed-out request might still have incurred cost, keep that uncertainty in the ledger rather than treating the absence of a receipt as evidence of free execution.

Run the accounting counterexample

Download and inspect agent-cost-rounding.py. It uses Python 3.9 or later and the standard library, with no network access or file writes. The batch is bounded to 100,000 records.

python3 agent-cost-rounding.py
python3 agent-cost-rounding.py --test
python3 -O agent-cost-rounding.py --test

Executed demonstration output:

rounded-per-call USD: 0.00
retained-precision report: {'total_microusd': 400000, 'display_usd': '0.40', 'over_budget': True}

Ten tests passed in normal and optimised mode. They cover the false-zero counterexample, splitting one amount into many records, record reordering, the exact budget boundary, a hidden sub-cent overrun, half-even display rounding, invalid inputs, batch bounds, caller decimal precision and zero cost. The tests use unittest checks, which remain active under -O.

The deliberately broken calculation stays in the download. Its regression test requires it to produce the false zero, alongside the corrected result. That gives reviewers a reproducible reason for retaining precision instead of relying on a code-style preference.

Keep estimates and invoices distinguishable

Retaining precision makes an estimate internally consistent. It does not prove that the estimate matches the bill. Pricing versions, usage categories, batch discounts and supplier adjustments still need reconciliation. Store the source usage and the price version used to derive each estimate so a later price correction can be explained.

Keep the original amount separate from the formatted report field. If a downstream export only accepts two decimals, label it as a presentation export and exclude it from the accounting import path. Test that boundary explicitly; a correct calculator can still receive values that an earlier spreadsheet has rounded away.

For the wider operating approach to bounded agent work and review evidence, see my Claude Code book, available as a Kindle edition on Amazon UK.

Take one sub-cent record through your real collector, export and budget check. Then repeat it a thousand times. Compare the stored total before formatting with the value that reaches the budget decision, and retain that test at the export boundary.