Your application reports three completed customer tasks. The provider records six attempts. Two outputs pass review, one task produces nothing usable, and a timeout has no usage record yet. Which number belongs in the budget?

This guide builds a local audit that keeps those facts separate. You will import a usage CSV, join it to an accepted-output ledger, calculate known request costs and compare them with a source billing subtotal. The result identifies repeated work without treating an unknown charge as zero. It also demonstrates a bounded retry decision before anyone connects the method to a live client.

The intended reader is an engineer, small product team or FinOps practitioner who can export application records but cannot explain the difference between a successful API response and a useful customer outcome. Allow 45 to 60 minutes. Use Python 3.11 or later, a terminal and permission to read sanitized usage exports. The exercise uses only the standard library, runs offline and incurs no API charges.

Why this problem deserves an audit

The FinOps Foundation's State of FinOps 2026 identifies AI cost management as the leading skill teams want to develop. Its respondents also report difficulty understanding usage, allocating AI costs and connecting expenditure with value. This is evidence of a practitioner need, not a measurement of searches for this article.

McKinsey's August 25, 2026 survey reports that about one in five respondents say AI operating costs constrain their organization's usage. These surveys do not establish that retries cause that constraint. They support investigating where an application's costs come from before choosing a cheaper model or cutting access.

The earlier budgeting guide defines the wider boundary, including tools, infrastructure and review time. This lab adds the missing operational step: tracing attempts back to tasks and refusing an incomplete accounting result. Its numbers are fictional and its rate card is invented. They are neither current provider prices nor measured customer savings.

1. Define the identifiers before exporting data

A request ID represents one user task, such as preparing a reviewed support draft. An attempt ID represents one outbound execution. Keep the request ID across retries and create a new attempt ID for every attempt. An accepted output is a separate review decision linked to the exact successful attempt.

R1 in the sample times out, receives an invalid output, then receives an accepted output. It has three attempts and one accepted output. R3 has two attempts and no useful output. Counting only the last successful attempt hides work; counting an all-attempt total and adding a retry subtotal counts some work twice.

The usage contract requires attempt ID, request ID, attempt number, status, two token counts and two rates in USD per million tokens. Zero tokens mean observed zero usage. Blank token counts mean unknown usage. A missing rate is an error, even when usage is unknown, because an incomplete rate card must not silently produce a believable budget.

2. Write acceptance rules and a retry boundary

Before running the exercise, require unique attempt IDs, unique attempt numbers within a request, nonnegative integral token counts, valid finite rates and exactly one review record per request. An accepted review must point to an ok attempt belonging to that request. Unknown usage must remain visible. Initial costs plus retry costs must equal the all-attempt total.

The illustrative policy permits no more than three total attempts, a 15-second elapsed boundary and a USD 0.010 reservation boundary. These are teaching values, not recommended universal production settings. A timeout returns RECONCILE_UNKNOWN. An authentication failure stops. A transient failure can be retried only inside all limits. For invalid output, inspect or correct the cause before retrying; repeating identical input indefinitely is not a repair.

Inspect every retry layer. The Anthropic Python SDK documentation, checked October 10, 2026, describes two automatic retries by default for certain errors and a configurable max_retries option. An outer three-attempt application loop can therefore produce up to nine transport attempts under those defaults. Do not assume one application call equals one network attempt. Save the installed SDK version and retry configuration with your observations. This article does not call or install that SDK.

3. Create and run the audit

Create an empty directory, save the complete program below as audit.py, then run python3 -I audit.py. Isolated mode prevents Python from importing local user configuration. The program reads no environment variables, sends no network requests and generates no customer output.

Python's CSV module turns rows into named fields. Decimal preserves decimal values supplied as strings. The cost calculation divides token count times rate by one million. R2's 500 input tokens and 50 output tokens cost USD 0.001500 under the invented rates. That is 0.15 cents, not 0.0015 cents. Keep six decimal places in diagnostics; premature rounding to cents would erase small charges.

import csv
import io
import sys
from collections import defaultdict
from decimal import Decimal, InvalidOperation
from pathlib import Path

D = Decimal
USAGE = """attempt_id,request_id,attempt_no,status,input_tokens,output_tokens,input_usd_per_million,output_usd_per_million
A1,R1,1,timeout,,,2,10
A2,R1,2,invalid_output,1000,100,2,10
A3,R1,3,ok,1000,200,2,10
A4,R2,1,ok,500,50,2,10
A5,R3,1,invalid_output,500,100,2,10
A6,R3,2,rejected,0,0,2,10
"""
ACCEPTED = """request_id,accepted_attempt_id,review_state
R1,A3,accepted
R2,A4,accepted
R3,,rejected
"""
BILL = """period,currency,usage_usd
2026-10-01,USD,0.0115
"""
FIELDS = set(USAGE.splitlines()[0].split(','))

def rows(text, required):
    reader = csv.DictReader(io.StringIO(text))
    missing = required - set(reader.fieldnames or [])
    if missing:
        raise ValueError('missing_columns=' + ','.join(sorted(missing)))
    return list(reader)

def number(value, field, aid, integer=False):
    if not value:
        raise ValueError(f'missing_{field}={aid}')
    try:
        result = D(value)
    except InvalidOperation:
        raise ValueError(f'invalid_{field}={aid}') from None
    if not result.is_finite() or result < 0 or (integer and result != int(result)):
        raise ValueError(f'invalid_{field}={aid}')
    return result

def audit(usage_text, accepted_text):
    attempts, groups = {}, defaultdict(list)
    sequences = set()
    for row in rows(usage_text, FIELDS):
        aid, rid = row['attempt_id'], row['request_id']
        if not aid or not rid:
            raise ValueError('missing_identity')
        if aid in attempts:
            raise ValueError(f'duplicate_attempt_id={aid}')
        seq = number(row['attempt_no'], 'attempt_no', aid, True)
        if seq < 1 or (rid, seq) in sequences:
            raise ValueError(f'invalid_sequence={aid}')
        sequences.add((rid, seq))
        rates = [number(row[key], key, aid) for key in
                 ('input_usd_per_million', 'output_usd_per_million')]
        tokens = [row['input_tokens'], row['output_tokens']]
        if all(v == '' for v in tokens):
            cost = None
        elif any(v == '' for v in tokens):
            raise ValueError(f'partial_usage={aid}')
        else:
            counts = [number(v, 'tokens', aid, True) for v in tokens]
            cost = sum((t * r for t, r in zip(counts, rates)), D(0)) / D(1000000)
        item = {'id': aid, 'request': rid, 'seq': seq,
                'status': row['status'], 'cost': cost}
        attempts[aid] = item
        groups[rid].append(item)
    reviewed = {}
    for row in rows(accepted_text, {'request_id', 'accepted_attempt_id', 'review_state'}):
        rid, aid = row['request_id'], row['accepted_attempt_id']
        if rid in reviewed:
            raise ValueError(f'duplicate_review={rid}')
        if rid not in groups:
            raise ValueError(f'unknown_review_request={rid}')
        state = row['review_state']
        if state not in {'accepted', 'rejected', 'pending'}:
            raise ValueError(f'invalid_review_state={rid}')
        if state == 'accepted':
            if aid not in attempts or attempts[aid]['request'] != rid or attempts[aid]['status'] != 'ok':
                raise ValueError(f'invalid_accepted_attempt={rid}')
        elif aid:
            raise ValueError(f'unexpected_accepted_attempt={rid}')
        reviewed[rid] = state
    missing = set(groups) - set(reviewed)
    if missing:
        raise ValueError('missing_review=' + ','.join(sorted(missing)))
    return attempts, groups, reviewed

def retry_decision(status, attempts, elapsed, spent, next_max):
    if not isinstance(status, str) or type(attempts) is not int or attempts < 1:
        return 'STOP_INVALID_INPUT'
    try:
        elapsed, spent, next_max = (D(str(value)) for value in (elapsed, spent, next_max))
    except InvalidOperation:
        return 'STOP_INVALID_INPUT'
    if any(not value.is_finite() or value < 0 for value in (elapsed, spent, next_max)):
        return 'STOP_INVALID_INPUT'
    if status == 'timeout':
        return 'RECONCILE_UNKNOWN'
    if status not in {'429', '503', 'invalid_output'}:
        return 'STOP_NONRETRYABLE'
    if attempts >= 3 or elapsed >= 15:
        return 'STOP_LIMIT'
    if spent + next_max > D('0.010'):
        return 'STOP_BUDGET'
    return 'RETRY_BOUNDED'

def run(usage, accepted, bill):
    attempts, groups, reviewed = audit(usage, accepted)
    known = sum((a['cost'] for a in attempts.values() if a['cost'] is not None), D(0))
    initial = sum((a['cost'] for a in attempts.values() if a['cost'] is not None and a['seq'] == 1), D(0))
    retry = known - initial
    unknown = sum(a['cost'] is None for a in attempts.values())
    useful = sum(v == 'accepted' for v in reviewed.values())
    print(f'requests={len(groups)} attempts={len(attempts)} accepted_outputs={useful} unknown_usage={unknown}')
    for rid in sorted(groups):
        group = groups[rid]
        cost = sum((a['cost'] for a in group if a['cost'] is not None), D(0))
        print(f'{rid} attempts={len(group)} known_usd={cost:.6f} unknown={sum(a["cost"] is None for a in group)} review={reviewed[rid]}')
    print(f'known_initial_usd={initial:.6f} known_retry_usd={retry:.6f} known_total_usd={known:.6f}')
    unit = f'{known / useful:.6f}' if useful else 'UNDEFINED'
    print(f'known_cost_per_accepted_output_usd={unit} completeness={"INCOMPLETE" if unknown else "COMPLETE"}')
    source = rows(bill, {'period', 'currency', 'usage_usd'})
    if len(source) != 1 or source[0]['currency'] != 'USD':
        raise ValueError('billing_scope_requires_one_usd_total')
    source_total = number(source[0]['usage_usd'], 'usage_usd', 'billing')
    variance = source_total - known
    state = 'PENDING_UNKNOWN' if unknown else ('MATCH' if variance == 0 else 'INVESTIGATE')
    print(f'source_usage_usd={source_total:.6f} variance_usd={variance:.6f} reconciliation={state}')
    for label, args in [('timeout', ('timeout', 1, 2, D(0), D('.003'))),
                        ('transient', ('429', 1, 2, D('.003'), D('.003'))),
                        ('auth', ('401', 1, 2, D(0), D('.003'))),
                        ('attempt_limit', ('503', 3, 2, D(0), D('.003'))),
                        ('budget', ('503', 1, 2, D('.009'), D('.003')))]:
        print(f'policy_{label}={retry_decision(*args)}')
    assert initial + retry == known
    print('accounting_identity=PASS network_calls=0')

if sys.argv[1:] == ['--write-demo']:
    Path('usage.csv').write_text(USAGE)
    Path('accepted.csv').write_text(ACCEPTED)
    Path('billing.csv').write_text(BILL)
    print('wrote=usage.csv,accepted.csv,billing.csv')
elif len(sys.argv) == 4:
    run(*(Path(name).read_text() for name in sys.argv[1:]))
elif len(sys.argv) == 1:
    run(USAGE, ACCEPTED, BILL)
    bad_cases = [('duplicate', USAGE + USAGE.splitlines()[1] + '\n', ACCEPTED),
                 ('missing_rate', USAGE.replace('A3,R1,3,ok,1000,200,2,10', 'A3,R1,3,ok,1000,200,,10'), ACCEPTED),
                 ('missing_review', USAGE, ACCEPTED.replace('R3,,rejected\n', ''))]
    for label, usage, accepted in bad_cases:
        try:
            audit(usage, accepted)
        except ValueError as error:
            print(f'negative_{label}=REJECTED {error}')
        else:
            raise AssertionError(f'negative_case_accepted={label}')
else:
    raise SystemExit('usage: python audit.py [usage.csv accepted.csv billing.csv | --write-demo]')

Expected complete stdout:

requests=3 attempts=6 accepted_outputs=2 unknown_usage=1
R1 attempts=3 known_usd=0.007000 unknown=1 review=accepted
R2 attempts=1 known_usd=0.001500 unknown=0 review=accepted
R3 attempts=2 known_usd=0.002000 unknown=0 review=rejected
known_initial_usd=0.003500 known_retry_usd=0.007000 known_total_usd=0.010500
known_cost_per_accepted_output_usd=0.005250 completeness=INCOMPLETE
source_usage_usd=0.011500 variance_usd=0.001000 reconciliation=PENDING_UNKNOWN
policy_timeout=RECONCILE_UNKNOWN
policy_transient=RETRY_BOUNDED
policy_auth=STOP_NONRETRYABLE
policy_attempt_limit=STOP_LIMIT
policy_budget=STOP_BUDGET
accounting_identity=PASS network_calls=0
negative_duplicate=REJECTED duplicate_attempt_id=A1
negative_missing_rate=REJECTED missing_input_usd_per_million=A3
negative_missing_review=REJECTED missing_review=R3

4. Interpret the diagnostic before changing anything

The sample has three user requests, six attempts and two accepted outputs. Known spend is USD 0.010500. Its retry component, USD 0.007000, is already inside that total. Do not add it again. R1 accounts for USD 0.007000 of known spend and still has an unresolved timeout. R3 consumes USD 0.002000 without producing an accepted output. These are different investigation targets.

Dividing known spend by accepted outputs yields USD 0.005250. The report labels its completeness INCOMPLETE because A1 has unknown usage. Treat the quotient as a partial usage-based unit cost, not a final fully loaded cost or invoice. Review labor, retrieval and infrastructure remain outside this lab's boundary. If no outputs are accepted, the program reports UNDEFINED rather than dividing by zero or hiding failed spend.

The invented source billing subtotal is USD 0.011500, leaving a USD 0.001000 difference. PENDING_UNKNOWN deliberately refuses a match. The difference does not prove that A1 cost exactly that amount. It could include unmatched records, pricing differences or another scope error. Recover evidence, then recalculate. Never distribute a billing difference arbitrarily across requests to make the totals agree.

The negative cases must reject a duplicated attempt, A3's missing input rate and R3's missing review. A rejected task belongs in the denominator of attempted work. Removing it because it produced no useful result would artificially improve the report.

5. Connect a real export without changing production

Run python3 -I audit.py --write-demo to create usage.csv, accepted.csv and billing.csv. Then run python3 -I audit.py usage.csv accepted.csv billing.csv. That file path executes the same audit against local files; it prints the diagnostic without rerunning the three built-in negative cases.

Use these files as an adapter contract, not a claim that every provider exports this schema. Map your application's attempt records into the usage columns. Capture provider request identifiers when available and preserve the mapping in a restricted reconciliation table. Do not substitute a provider's daily aggregate for individual attempt records. If the source has no attempt-level identity, reconcile at its supported aggregation level and disclose that attribution is incomplete.

Populate acceptance from the workflow that actually approves outputs, using the same request identifiers. Choose a written rule such as “reviewed draft needs no material correction” and keep pending reviews pending. A HTTP success alone must not set accepted. Do not include prompt text, credentials, customer names or generated private material in the cost export.

Build the billing file from one documented usage subtotal in USD for the exact same account or project scope, model classes and UTC time window. The lab checks currency and a single total; it cannot verify that a human chose the right scope. Save export time, period boundaries, rate effective dates, source file checksum and the adapter version alongside it. Use actual contracted rates, not prices remembered from a website.

The two-rate contract is intentionally narrow. Extend it before importing cached input, batch discounts, tools, audio, images, tiered rates or other charging classes. Keep taxes, credits and unrelated services separate when comparing a usage subtotal. Only call a result reconciled after missing records resolve, categories align and every remaining difference has an explanation.

Troubleshooting and safe rollout

Symptom Likely cause Corrective action
duplicate_attempt_id=A1 Two exports overlap or a retry reused its identity Deduplicate the same event by stable source identity; preserve genuinely distinct attempts
missing_input_usd_per_million=A3 Rate mapping is incomplete Supply a dated rate for that charge class; never default to zero
missing_review=R3 The join lost rejected or pending work Export a review state for every request in the window
partial_usage=A1 One token count is absent Recover the missing count; keep both blank only when usage is genuinely unknown
PENDING_UNKNOWN persists A timeout has no settled usage evidence Investigate provider records and application tracing; do not report a complete cost
Unexpectedly high attempts SDK, worker and application retries stack Record each layer's configuration and designate one retry owner

Begin with read-only exports from a completed period. Do not automatically turn off retries based on this small report. Review the dominant failure category, change one policy in a test environment and compare the same request mix, acceptance rule, latency and failure rate. Lower spend that also destroys useful outputs is not a successful result.

When integrating the policy, reserve a conservative next-attempt cost before dispatch and release or reconcile that reservation afterward. Concurrent workers need an atomic reservation mechanism. The local function illustrates decisions; it does not enforce concurrency, wait between retries, honor Retry-After, track wall-clock deadlines or settle uncertain provider work. Add and test those controls in the client layer before claiming a production budget limit. Roll back to the prior bounded policy if acceptance or latency worsens, retaining evidence for comparison.

Completion check and next exercise

You are finished when the default run matches every expected line, the file-based run reproduces its diagnostic, all three invalid inputs are rejected and you can explain why R1's cost is incomplete. Confirm that dollars and cents remain distinct and that retry cost appears once.

For an independent exercise, change both R1 timeout counts to observed zero and change the synthetic billing subtotal to USD 0.010500. The audit should report COMPLETE and MATCH. This is a parser exercise, not permission to relabel a real timeout. Then collect a representative, sanitized period from your own workflow and document which fields cannot yet be exported. That list is the next engineering task: close the evidence gaps before claiming a retry optimization saved money.

Editorial update, October 10, 2026

This companion guide was expanded with a complete educational lab, checked outputs and failure cases. Its original URL and publication date are retained. The examples use synthetic data and do not demonstrate production savings or live model performance.