SSerguey Asael Shinder
Java coding notes: the JVM, and writing software that lasts

Serguey Asael Shinder: A cleanup that changes state is a write, and it belongs inside the rollback

· by Serguey Asael Shinder / Serguey Shinder

A post on the Polkadot forum on 3 November traced a bug that lowered the recorded supply of the dotUSD stablecoin while no balance moved. The code collected withdrawn assets in a variable declared outside a transactional block. When a later step failed, the block rolled back the account changes, and then the variable went out of scope. Dropping it was not neutral: its drop handler lowered total supply and emitted an event. Because that happened after the rollback, nothing undid it. The fix moved the variable inside the block, so the drop happened while the rollback could still cover it.

The author's summary of why review missed it is the useful part: "a drop doesn't look like a write." Java has no destructors, but it has the same shape in two everyday places. A close() called by try-with-resources, and a finally block, both run code at the end of a scope. If that code changes shared state, writes a counter, publishes an event or commits to a second store, it is a write, and the question is which transaction it belongs to.

Serguey Asael Shinder: A cleanup that changes state is a write, and it belongs inside the rollback
A cleanup that changes state is a write, and it belongs inside the rollback — Serguey Asael Shinder

Consider the order. The Java Language Specification, section 14.20.3, says resources are "closed automatically, in the reverse order from which they were initialized, after execution of the try block", and that happens whether the block completes or throws. If the block runs inside a transaction that is about to be rolled back, a close() that records "work done" has already recorded it, and the rollback of the main store does not reach whatever close() touched. The code reads as cleanup. The effect is a side channel that survives failure.

Three checks follow from the incident. First, read every close(), finally and callback that runs at the end of a scope as if it were a write, and ask whether it should happen when the operation fails. Second, keep state-changing cleanup inside the transactional boundary, or make it conditional on success. Third, write the test the Polkadot Fellowship wrote: make the last step of a multi-step operation fail, then assert that every total, counter and published event is exactly what it was before.

The dotUSD bug was rated medium when it was found, before any trading pool read the supply figure. It became a mispricing only after another component started to rely on that number. A side effect that looks harmless today is harmless only until something reads it.