caelum0x 97bd470bf0 fix(mint): deposit-reversal bookkeeping lost-update could double-burn a claw-back
apply_reversal() read the deposit_reversals row, computed a new
clawed_micros/status from it, then wrote it back with no lock held across
the gap -- the actual money movement (commit_redeem) is independently
idempotency-guarded, but the bookkeeping UPSERT was a blind
EXCLUDED.* overwrite. Two concurrent reversal applications for the same
deposit_ref (e.g. a provider's at-least-once webhook redelivery, or a
webhook racing an operator retry) could both read the same stale row;
whichever write landed last won, even if it came from the side that
burned nothing (idempotent replay). That could silently regress a fully
clawed-back reversal to "shortfall" -- and shortfalls are a designed-for
operator worklist item that gets retried, so the next retry would burn
the account a second time for money already recovered.

Same bug class as the Rago prepaid-wallet lost-update fix (f9d0a1b5):
make the merge commutative instead of last-write-wins. amount_micros/
clawed_micros/attempts only ever grow, so GREATEST() them in the
Postgres UPSERT (and mirror the merge in the in-memory store); derive
status from the post-merge totals, with written_off always sticky on
either side of a race.

Repro: added concurrent_reversal_upsert_does_not_lose_the_winning_write
and written_off_is_sticky_against_a_late_stale_reversal_write to
mint-store's memory tests -- both fail against the pre-fix blind
overwrite and pass after the fix. Also manually verified against a real
Postgres (docker postgres:16-alpine, migrations applied): same
before/after repro reproduces the regression pre-fix and confirms the
fix post-fix.

cargo build --workspace and cargo test --workspace (excluding the
DATABASE_URL-gated pg_live/pg_settlement_live suites) are green.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-04 14:10:49 +03:00
..