Reconciliation Testing Between Payment Records and Internal Ledgers
Stateful simulators expose the fee, timing, and duplicate errors mocks miss.
Reconciliation testing between payment records and internal ledgers requires integration tests that run the full sequence of API calls against a stateful payment simulator. The simulator must preserve records, identifiers, and transitions between calls so tests can expose fee mismatches, timing gaps, and duplicate offsets. Assertions must check both the accumulated ledger state and whether each API request succeeded.
What reconciliation actually compares, and where it routinely breaks
Reconciliation is a transaction-level identity proof that every cent in the internal ledger matches a cleared event on the payment rail. A matching balance is not sufficient evidence. Formance's reconciliation guide distinguishes balance-level matching, which detects a discrepancy, from transaction-level matching, which localizes it and can reconstruct per-owner positions. That distinction defines the test target. The internal ledger is the system of record, and matching runs against its postings rather than a total detached from the records underneath.
Reconciliation surfaces discrepancies but does not correct them. Corrections enter through a separate, approval-gated adjustment posting, while the original error and its reversal remain permanently in the ledger. Tests therefore need to distinguish finding an exception from resolving it. They also need to distinguish two root failures. Data drift means the ledger and payment rail describe the same event differently, while an unreconcilable ledger cannot produce a trustworthy position to compare at all.
Normalization is where apparently compatible records often diverge. A card processor reports a net deposit after interchange and processor fees, while the ledger invoice records a gross amount. Unless the reconciliation layer represents the difference as an expected fee, every card deposit becomes an exception. Field names such as net_amount, bookingValue, and settlement_net_usd make this harder across processors. A matcher can be correct against its input schema while normalization quietly supplies the wrong meaning.
Why the full pipeline produces failure modes that isolated unit tests cannot see

The pipeline collects rail data, extracts ledger postings, matches stable external identifiers, classifies unmatched items, investigates causes, posts approved adjustments, confirms balances, and closes the period. Each stage inherits the state left by the previous one. Formance's guide explains that omitting pending postings creates false missing-transaction flags, while omitting failed postings hides retries that should never have posted. Testing extraction and matching separately does not establish that they agree about which records belong in a run.
The failure can also sit at a service boundary. An upstream payment service may use an idempotency key that a downstream component interprets differently, even though both components pass their own unit tests. Duplicate offsets reveal a related weakness in amount-based assertions. A missing payment can be offset by a duplicated payment of the same amount, leaving a correct total over incorrect records. Only an identity check exposes the discrepancy, and that check needs an environment that retains record identity throughout the sequence.
A transaction can already be posted internally while settlement remains pending, so a realistic test must represent pending, settled, and failed records together. Matching must also preserve the scope of external identifiers. The stable key includes provider, provider account, and source record ID so that the same-looking identifier in different accounts does not collide. A static charge ID returned on every call cannot reliably expose an identifier that was never stored, was overwritten, or collided across accounts.
How to test APIs that have state without hitting production
A stateful simulator closes this gap by changing its stored state as the workflow proceeds through charges, fees, refunds, and payouts. A stateless mock answers the current request with a prescribed payload. It can validate parameters and response schemas, but it does not establish that a created transfer remains retrievable and can later be reconciled. Integration tests need to exercise valid and forbidden transitions, partial failures, rollback behavior, concurrency conflicts, and retries against that persistent state.
Live sandboxes introduce a different set of constraints. They are shared, rate-limited, credential-dependent environments whose results can change with network failures or state resets. A local simulator instead makes seeded edge cases repeatable without depending on sandbox availability. Duplicate offsets require existing records, and timing gaps require transactions at different stages, so an empty environment cannot reproduce either case merely by returning realistic-looking responses.
Stripe's Balance Transaction object separates amount, fee, net, currency, source, and available_on, with net defined as signed amount minus fee. The net value describes the provider balance. Stripe's payout reconciliation report also associates transactions with automatic payouts, while manual and instant payouts require a different reconciliation method. A simulator that merges these fields or invents unsupported payout allocations masks the very discrepancies the tests need to detect.
Building the layered test pipeline for a reconciliation workflow

Unit tests cover internal logic, including fee arithmetic, card-issuer-based normalization rules, retry backoff, and refund state transitions. Contract tests at merge and release gates codify charge IDs, payout references, and webhook payload structures as executable expectations for required fields. Stateful integration tests then exercise the full workflow in CI, while live sandbox and infrastructure chaos tests remain staging activities.
The integration sequence creates a charge, captures it, records the fee, issues a refund, generates a payout, and runs reconciliation. It must also exercise collection, extraction, matching, exception classification, investigation, and adjustment posting. Each test leaves the environment in a known state. Assertions check that state for false exceptions and for the correct flags on discrepancies seeded on purpose. A successful response from the final call is not enough.
Three explicit cases translate the earlier failure modes into tests. The fee normalization test seeds a known gross charge and fee, then asserts that the net deposit produces an expected fee offset. The duplicate-offset detection test seeds records whose amounts balance despite a missing record and a duplicate, then asserts an identity mismatch. The timing-gap test reconciles a pending charge, expects a timing exception, settles the charge, and reconciles again to establish that the exception clears.
Every reconciliation test must also assert idempotency. Repeating the same matching pass must produce the same output without additional exception flags. A stateless mock can appear to satisfy that requirement simply because it remembers nothing. A stateful environment makes the second pass meaningful because the first pass has already changed the test world.
Fault injection tests that expose the reconciliation failure modes live production finds first
Retries become a stronger test when a failure interrupts the workflow. Fault injection deliberately delays webhook delivery, adds network latency between payment orchestration and ledger services, or stops a container mid-transaction. Tests in which every step succeeds do not cover these boundaries. A stateful environment preserves whether a transaction was recorded before the interruption, allowing assertions to distinguish safe recovery from dropped transactions or duplicate postings. Without that memory, the test can check the retry response but not its accounting consequence.
Webhook delay or loss directly tests timing-gap handling. After a charge captures, delayed settlement delivery should produce a timing exception rather than a false missing-transaction classification. Replaying the webhook should clear the exception without creating a duplicate. The idempotency fault case submits the same charge creation request twice with the same key and checks that the original charge returns. Reconciliation must then see one charge.
Stopping processing after three of five charges gives the test a point from which to recover. The resumed batch must finish without duplicating postings for the charges already processed. For CI-stage faults, Toxiproxy and WireMock provide lightweight, programmable network and API fault injection, while Testcontainers supports disposable databases and message brokers that can be stopped or degraded. Gremlin and LitmusChaos belong in staging and production experiments where infrastructure-level chaos is appropriate.
Recovery needs its own assertions. Can failed webhooks be replayed safely, and can a partially processed batch be reconciled after service returns? Can the ledger recover from queue duplication without adding further entries? These questions require the simulator to retain what was already posted.
Running reconciliation tests in CI without touching rate limits or live credentials
A CI workflow needs repeatable results without live payment credentials or sandbox availability. Rate limits, credential rotation, and sandbox resets work against that requirement, especially when jobs run in parallel. Air-gapped environments make the constraint explicit. Regulated environments may prohibit outbound connections from CI infrastructure, so the suite must be self-contained. A simulator hosted locally gives each job its own instance and pre-seeded state, with no outbound API calls and no state shared with another run.
Every commit runs unit tests for normalization, fee arithmetic, and state transitions without external dependencies. Every pull request merge runs contract tests for charge IDs, payout references, and webhook payloads produced by the simulator. Every release candidate runs the complete stateful integration suite against a fresh, realistically seeded instance, covering fee normalization, duplicate offsets, timing gaps, and the three fault scenarios. Infrastructure chaos tests run only in staging.
Seed data should be kept in version control with the tests. Existing charges make duplicate-offset detection possible, realistic fee data exposes normalization errors, and mixed pending and settled records exercise timing gaps. Versioning those inputs makes the environment reproducible across machines and over time. It also removes the need for a snapshot prepared by hand whose contents are separate from what the test expects.
The remaining dependency is fidelity to the real API. Simulator behavior must be continuously verified against that API, separately from the offline CI runs that depend on it. Otherwise, a simulator drifting from the Balance Transaction schema can pass every local test while hiding a production normalization bug. Published fidelity scores provide an auditable signal of that correspondence. Deterministic tests are useful only when the environment remains faithful to the system they represent.
What AI agents running payment workflows add to the reconciliation testing surface
AI agents executing payment API calls introduce the same reconciliation-breaking errors as service code, including misread state, skipped idempotency, and misinterpreted validation signals. The accounting requirement does not change with the caller. An agent's second call must see the state left by its first, retries must be recognized, and missed webhooks must remain replayable under controlled conditions. Testing isolated tool responses cannot establish those properties. The evaluation must inspect the resulting payment and ledger state.
Stripe's Forge benchmark shows why claims that a task is complete need to be checked through independent assertions. In SDK upgrade tasks, some agents supplied nonexistent Stripe data, observed validation errors, and considered the task complete. That behavior demonstrates why an agent's interpretation of an API response is insufficient evidence of success. The same distinction applies after a retry. An agent may handle a rate-limit response gracefully yet still fail reconciliation if the subsequent request creates a duplicate posting.
Forge runs agents in isolated Docker containers, using the same isolation model as CI jobs that run in parallel. The same stateful simulator can therefore support an integration suite and an agent evaluation harness, with controlled starting records and fault scenarios. Each episode can test whether the workflow preserved identity, respected idempotency, and reached the expected final state. Scaling to thousands of agent evaluation episodes creates the same infrastructure requirement as thousands of parallel CI jobs. Independent simulator instances provide repeatable state without shared sandbox limits or live credentials.