railyard/apps/ledgerline/migrations/0004_settlement_outbox_lease.sql
caelum0x 2332a95b61 fix(ledgerline): one driver per settlement saga (leased, fenced outbox)
Two instances, or an instance and the recovery sweep, could drive one saga at
once: the outbox upsert was last-writer-wins and recovery claimed nothing. A
stalled driver could overwrite newer progress, and a driver that saw an
attempt compensated could start the next attempt (fresh Mint keys) while an
older driver was still moving money on the previous one.

- settlement_outbox gets lease_owner/lease_until (migration 0004).
- settle claims the saga's lease (atomic UPDATE ... RETURNING; new sagas are
  inserted already leased), renews it before every Mint call and writes only
  while it holds it; a busy saga answers 409 settlement_in_progress and moves
  nothing. The lease is released at the end; a crashed driver's lease expires
  (120 s default, with_lease to change it) and anyone can take over.
- updated_at still means the last step taken, so the recovery staleness
  window is unchanged; recovery skips sagas driven elsewhere.

Tests: tests/concurrent_drivers.rs on the memory and the live Postgres outbox
(second driver refused, a driver past its lease stops and cannot overwrite a
settled saga, 12 concurrent settles move money once). 42 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 14:43:20 +03:00

8 lines
535 B
SQL

-- One driver per settlement saga. A coordinator claims the row's lease before
-- it calls Mint, renews it before every Mint step, and every saga write is
-- fenced on the lease owner, so a second instance (or a recovery sweep) can
-- neither drive the same saga at once nor overwrite its progress with a stale
-- copy. An expired lease (a crashed driver) can be claimed by anyone.
ALTER TABLE settlement_outbox ADD COLUMN IF NOT EXISTS lease_owner TEXT;
ALTER TABLE settlement_outbox ADD COLUMN IF NOT EXISTS lease_until TIMESTAMPTZ;