1.10 Concurrency Control and Concurrent Spending: Exit Evidence
Evidence · Step: 1.10 Concurrency Control and Concurrent Spending
| Step | 1.10 Concurrency Control and Concurrent Spending |
| Date | 2026-11-12 |
| Database | PostgreSQL 18.6 (postgres:18-alpine), Docker Desktop on Windows 11 |
| Result | Passed |
Deliverables
Section titled “Deliverables”| Deliverable | File |
|---|---|
| Locking and retries | crates/engine/src/concurrency.rs (PostOptions, Isolation, RetryStats); used by post.rs and store.rs |
| Error classification | crates/engine/src/rows.rs: 40P01 and 40001 → Contention (retried); lock timeout 55P03 and pool timeout → Busy |
| New ledger errors | LedgerError::Contention and LedgerError::Busy in mezgeb-core |
| Concurrency tests | crates/engine/tests/concurrency.rs |
| Measurement | crates/engine/examples/contention.rs |
| ADR evidence | ADR-0007, Evidence (step 1.10) |
Implementation tasks
Section titled “Implementation tasks”| Task | Done |
|---|---|
Lock all entry accounts with FOR NO KEY UPDATE in ascending ID order before checking balances |
Yes, in posting, reversals and status changes. FOR NO KEY UPDATE rather than FOR UPDATE, because it does not block the FOR KEY SHARE locks taken by the journal lines’ foreign key checks. |
Retry wrapper: at most 3 attempts on 40P01/40001, jittered backoff, re-running the whole transaction |
Yes: 5 ms, 10 ms, 20 ms … plus up to the same again at random |
lock_timeout per transaction |
Yes, 5 s by default, with set_config('lock_timeout', …, true) |
| ADR-0007 evidence section with the measurements | Yes |
Testing requirements
Section titled “Testing requirements”| Requirement | Test | Result |
|---|---|---|
| 100 tasks each spend 80 from 100: exactly 1 succeeds, 99 get insufficient funds, balance ends at 20 | one_hundred_spenders_one_wallet |
Pass |
| 1,000 random transfers among 10 accounts in parallel: global sum unchanged, no deadlock after retry, totals equal SUM(lines) | one_thousand_random_transfers |
Pass: 912 posted, 88 refused for insufficient funds, zero deadlocks, zero retries; wallet total unchanged; integrity report clean. A third of the transfers are split payments, and line order varies, so locks are requested in every order. |
| A→B and B→A storm causes no deadlocks | opposite_transfers_never_deadlock |
Pass: 500 opposite transfers, all posted, zero deadlocks |
| SERIALIZABLE on the same workload, with retry rates recorded | examples/contention.rs |
Recorded in ADR-0007: 73–86% of operations still failed after three attempts under SERIALIZABLE; zero retries with the chosen scheme |
Each test runs on a multi-threaded runtime with a 20-connection pool, so the postings really run in parallel inside PostgreSQL.
Acceptance criteria
Section titled “Acceptance criteria”The tests pass 50 consecutive runs.
The first attempt failed on its first run, and not because of locking: the 1,000-task tests queued for 20 pool connections longer than SQLx’s default 30-second acquire timeout while all tests shared one slow database. Two fixes:
- the test pools wait up to ten minutes for a connection (the tests measure locking, not queueing on a slow machine);
- the engine now reports a pool timeout as
Busy(retry later) instead of a generic storage error.
Then, with the release build:
for i in 1..50: cargo test --release -p mezgeb-engine --test concurrencyconsecutive passes: 50/50 in 2243sPass.
Measured, not yet guaranteed: INV-12
Section titled “Measured, not yet guaranteed: INV-12”INV-12 says recorded_time strictly increases in posting order.
recorded_time_against_sequence posts 1,000 entries in parallel and found
no tie and no inversion against sequence. That is an observation, not
a guarantee: sequence and recorded_time are taken by concurrent inserts,
and commit order can differ from sequence order. The guarantee comes with the
hash chain (step 2.09), which needs a single commit order anyway. The test
reports and does not assert, because asserting on a rare timing event would
be a flaky test. The schedule in the invariant catalogue
and db-schema.md was updated.
Exit gate
Section titled “Exit gate”Gate: explain, from the PostgreSQL documentation, why the scheme prevents lost updates.
Sources: PostgreSQL 18 §13.2.1 (Read Committed Isolation Level) and §13.3.2 (Row-Level Locks). The answers were written after reading a plain-language explanation of the same five points, and are recorded as given:
| # | Question | Answer |
|---|---|---|
| 1 | What is a lost update? (a wallet of 100, two payments of 80) | Two payments read 100 at the same time. Both think “enough” and both spend. The wallet ends at −60, or one payment erases the other. Nobody saw the other’s change. |
| 2 | What happens to the second payment’s SELECT … FOR NO KEY UPDATE? |
The lock holds the wallet row. The second payment must wait until the first commits or rolls back. Only one payment works on that wallet at a time. |
| 3 | What balance does it see after the first commits, and why is that enough? | After waiting, Read Committed gives it the newest committed row, not the old one. It sees 20. The check says 20 < 80, so it is refused. The check runs on the real current balance, and the lock keeps anyone from changing it. |
| 4 | Why lock in ascending ID order? | X locks A then wants B; Y locks B then wants A: both wait forever (deadlock). If everyone locks the lowest ID first, both queue for A first, so no circular wait is possible. |
| 5 | In “RC, no locks”, what stopped the overdraft, and why is that not enough? | Without the lock, Rust read a stale balance and let the payment through; only accounts_not_negative stopped it. That is a backup, not a plan: it covers only the no-negative rule, and other rules (refund limits, escrow caps) have no database check behind them. |
Result: passed. Each answer names the right mechanism: the row lock serialises payments per account, Read Committed re-reads the newest committed row after the wait, the fixed lock order rules out deadlock cycles (measured: zero deadlocks), and the database CHECK is a backstop for one rule only.