Technical illustration: Repeated receipt polls keep the first confirmation date. A verified orphan removes that inclusion; a new inclusion establishes a new observation.
Original technical illustration for this runnable lab.

A payment appears in Monday's report. After the receipt worker polls it again on Tuesday, the same payment appears in Tuesday's report instead. The transfer did not happen twice. The reporting code replaced the original confirmation time with the latest poll time.

This lab builds a small SQLite receipt projection that preserves the first confirmation observation while an inclusion remains unchanged. It also handles an explicit orphan notification and a later reinclusion. You can run the whole sequence without a chain, wallet or account balance. Download the standalone example and tests.

Agent Wallet Guard's historical Owner acceptance report records this exact reporting concern. Repeated reads retain the first confirmation time, while an actual reorganization followed by reconfirmation establishes a new time. The report distinguishes UTC reporting dates from spending rules based on chain time. This article uses that source behavior as the reason for the exercise; it does not rerun the application.

Run a payment across midnight

Use Python 3.13.3, the runtime used to verify the archive. The program depends only on the standard library.

python3 lab.py
python3 -m unittest -v

The synthetic timestamps sit around the first UTC midnight after the Unix epoch. The first observation is at 86,399 seconds. Another poll at 86,401 sees the same transaction in the same block. The daily total remains on 1970-01-01.

The demo then marks that specific inclusion orphaned and includes the payment in a different block at 86,402. The total moves to 1970-01-02. Those dates make the boundary easy to inspect and carry no historical claim about a real transfer.

The model counts only included payments. Between orphaning and reinclusion, the payment contributes to no daily total. A reporting interface could show that interruption separately instead of silently pretending the earlier inclusion remains valid.

Give a receipt a stable identity

The table has a composite primary key containing chain identity and transaction identity. A transaction label reused in another test chain is a different record. An inclusion adds the block identity and its first observation time.

def include(self, chain, tx, block, amount, observed_at):
    if type(amount) is not int or amount <= 0 or type(observed_at) is not int or observed_at < 0:
        raise ValueError('invalid amount or time')
    with self.db:
        row = self.db.execute('SELECT block, amount, confirmed FROM receipts WHERE chain=? AND tx=?', (chain, tx)).fetchone()
        if row and row[1] != str(amount):
            raise ValueError('conflicting payment amount')
        if row and row[0] is not None:
            if row[0] != block:
                raise ValueError('orphan old inclusion first')
            return row[2]
        self.db.execute('INSERT INTO receipts VALUES(?,?,?,?,?) ON CONFLICT(chain,tx) DO UPDATE SET block=excluded.block, confirmed=excluded.confirmed', (chain, tx, block, str(amount), observed_at))
    return observed_at

Repeated observations of the same block return the saved time. The timestamp argument from the new poll is deliberately ignored in that branch. The function also refuses an amount change for the same payment identity, so a parsing error cannot quietly rewrite yesterday's amount.

A different block requires an explicit orphan operation first. That makes the state change visible to the caller and gives the exercise a clear transition to test. A real receipt adapter may obtain the evidence through several RPC reads, but it still needs a defined rule for deciding that the old inclusion no longer counts.

The chain value in this program is a fixture identifier. A production adapter would need a deployment identity that survives the distinctions relevant to its environment. A local chain reset can reuse a numeric chain ID, so simply copying the network number is not always enough.

Do not let an old orphan message erase a new inclusion

An orphan notification carries the block identity it refers to. The update requires that identity to match the currently stored block.

def orphan(self, chain, tx, block):
    with self.db:
        return self.db.execute('UPDATE receipts SET block=NULL, confirmed=NULL WHERE chain=? AND tx=? AND block=?', (chain, tx, block)).rowcount

Suppose the worker removes block A, records block B, and later receives a delayed second notification about block A. The second update changes zero rows. The payment stays included in block B.

That predicate protects a useful ordering property. A message about an old observation has no authority to remove a newer one. The test checks the zero-row result and the final daily total, so deleting the block predicate would produce a visible failure.

This model deliberately overwrites the current inclusion rather than keeping every historical observation. It is a reporting projection, with enough state to prevent the demonstrated date drift. A complete audit trail would retain the observations separately and define retention and replay behavior. The download does not claim to supply that trail.

Repeated receipt polls keep the first confirmation date. A verified orphan removes that inclusion; a new inclusion establishes a new observation.
Original illustration of the synthetic preserve payment dates across receipt polls and reorganizations lab. It depicts software state, not a live transaction.

Keep money out of a floating-point aggregate

Amounts are stored as decimal integer strings, then converted to Python integers when totals are calculated. This keeps the example exact even when a raw token amount exceeds SQLite's signed integer range. The included large-value test uses 2**80 + 1 and expects the final one to survive.

The aggregate currently combines all recorded amounts. Its fixtures represent one asset with one precision. An application that handles several assets must group by asset identity and units before totaling them. Adding one token's raw units to another token's raw units would produce a meaningless report, regardless of how accurately the arithmetic is performed.

Likewise, this timestamp is the first observation of a confirmed inclusion. It is not automatically the block timestamp, purchase time or the moment a vendor delivered a service. A dashboard should name the selected reporting basis and keep any other business dates in their own fields.

Reproduce the defect and verify recovery

The tests first show that a naive poll-date calculation assigns the two observations to different days. The ledger then runs the same timestamps and retains the first date.

def test_naive_poll_date_moves_payment(self):
    self.assertNotEqual(86399 // 86400, 86401 // 86400)
    self.l.include('1','t','a',10,86399)
    self.assertEqual(self.l.include('1','t','a',10,86401),86399)
    self.assertEqual(self.l.daily(),{'1970-01-01':10})

Seven named tests cover the midnight boundary, restart persistence and the orphan/reinclusion sequence. They also reject an amount conflict and an unexplained block change. The archive was extracted into a clean temporary directory before these tests ran.

Try removing the early return for an unchanged block. If the replacement path begins updating the confirmation time on every poll, the midnight test should fail. Try removing block=? from the orphan update and the delayed-orphan test should fail. Those are two separate failure modes with separate evidence.

Use the ledger in a product review

The earlier Agent spending-limit article concerns execution constraints. This exercise concerns how an already observed payment is counted. A correct daily report cannot establish whether a payment was authorized, and a valid authorization does not choose the right reporting date for the application.

For an Agent Wallet Guard walkthrough, ask to repeat a receipt read across a reporting boundary and inspect the original confirmation field. Then use the project's test environment to exercise a changed canonical inclusion. The local acceptance evidence gives a starting point for that conversation; actual network finality and reorganization detection remain part of the deployment's integration work.