blog.rust.gay

PgLoom finds PostgreSQL double-spends by treating SQL as a schedulable program

The demo output is small enough to miss. A wallet starts with 100. Two withdrawal requests arrive at the same time, each for 200. Both read the balance, both decide there is enough money, both write, and both return HTTP 200. The final database row says balance = -100. PgLoom explored three of fifty schedules, found the interleaving in 66 milliseconds, and printed a trace that shows exactly where each transaction paused, which row lock blocked which worker, and why the second request did not see the first request’s write.

PgLoom is a deterministic concurrency model checker for PostgreSQL-backed services. It is written in Rust, version 0.1.1, Apache-2.0, Edition 2024, with #![forbid(unsafe_code)]. It sits between an application and a real PostgreSQL server as a wire-protocol proxy. It holds SQL round trips at a gate, schedules the workers in different orders, and checks invariants after each schedule. If a schedule produces a double-spend, a lost update, a write-skew anomaly, a phantom insert, or a lock-order deadlock, PgLoom reports it with a replayable trace.

The project’s motivation is a gap in existing testing tools. tokio-rs/loom is excellent at exploring thread and atomic interleavings inside a single Rust process. It does not see SQL transactions crossing a network. Sequential integration tests never interleave concurrent transactions, so the check-then-act window is invisible. Load tests hit the window only by luck, and when they do, they cannot replay the exact interleaving. Most production state bugs in financial and inventory systems live in that gap: the code is correct in isolation, the database is correct in isolation, and the composition is wrong under concurrency.

Why READ COMMITTED lets a double-spend through

PostgreSQL’s default isolation level is READ COMMITTED. Each statement sees a snapshot of the database as of the moment the statement began. It does not see uncommitted changes from other transactions, and it does not prevent another transaction from changing a row after the first transaction read it. That is enough for many applications, but it is not enough for read-modify-write logic.

Consider two transactions, A and B. A starts, reads the wallet row, and sees 100. B starts, reads the same row, and also sees 100. A subtracts 200 in memory, writes -100, and commits. B subtracts 200 in memory, writes -100, and commits. The second write overwrites the first. Both transactions believed they had enough money because both read the same pre-write value. This is a lost update, and in a wallet it is a double-spend.

The classic fixes are well known. A pessimistic lock, SELECT ... FOR UPDATE, makes B wait until A commits, then B re-reads the updated value and sees that the balance is insufficient. A guarded update, UPDATE wallets SET balance = balance - $1 WHERE id = $2 AND balance >= $1, performs the check and the write in one statement, so the database’s row lock serializes the two updates. Both fixes work. The problem is knowing which queries need them, and proving that the fix closes every interleaving, not just the one a developer imagined.

PgLoom’s contribution is not a new isolation level or a new database feature. It is a way to search the interleaving space automatically, using the application’s real SQL and the database’s real locking behavior.

A proxy on the wire, not an SDK

Most concurrency testing tools require you to instrument the application, replace the database driver, or write against a special API. PgLoom takes a different route. It speaks the PostgreSQL v3 wire protocol, so any backend written in Rust, Go, Python, TypeScript, Java, or anything else can use it without code changes. You point DATABASE_URL at the proxy instead of the database, and the application does not know the difference.

The proxy parses both the Simple Query protocol and the Extended Query protocol. That includes Parse, Bind, Describe for statements and portals, Execute, Flush, Sync, and COPY streaming. It caches column layouts so it can decode binary parameters and results. It gates completed SQL turns before forwarding them upstream. In other words, it does not just see the SQL text; it understands the protocol state machine well enough to pause a transaction at the right boundary.

That boundary is important. A transaction is not a single network event. It is a sequence of statements, each with its own round trip. The race window is usually between a read and a write, or between a check and an insert. PgLoom can hold the first worker after its read, run the second worker’s read, then release the first worker’s write, and so on. It explores the schedules that a normal test would never produce.

The YAML scenario describes the setup and the workload. It includes the upstream database, the proxy listen address, the setup SQL, the target command, the environment (including DATABASE_URL pointed at the proxy), a readiness check, the workers (HTTP method, URL, headers, body), and the invariants. The invariants can be SQL assertions, such as a minimum wallet balance, and response assertions, such as at most one withdrawal returning a 2xx status. That combination is what makes the tool useful: it checks both the database state and the application’s response, because a bug can show up in either.

The scheduler: DPOR, sleep sets, and row locks

The scheduler is the technical heart of PgLoom. A naive explorer would try every possible order of every statement. That explodes immediately. PgLoom uses Source-DPOR, a dynamic partial-order reduction algorithm with sleep sets. It tracks the read/write footprint of each SQL statement and uses pg_catalog foreign-key and trigger metadata to decide which statements conflict. If two schedules are equivalent under the Mazurkiewicz trace model, it prunes one of them. That is how it can explore a useful set of schedules in milliseconds instead of enumerating a factorial number of possibilities.

The proxy also has to handle a problem that is easy to miss: a worker can block inside PostgreSQL’s lock manager. If worker A holds a row lock and worker B tries to update the same row, B’s Execute does not return. A naive proxy would hang, because it is waiting for a response that will not arrive until A commits. PgLoom queries pg_blocking_pids() to find out which backend is blocking B, parks B, hands execution back to A, and resumes B when the lock is released. It also detects true lock cycles and reports them as deadlocks, rather than treating every wait as a deadlock.

The reset strategy is another detail that matters. Between schedules, PgLoom resets mutated tables from an UNLOGGED snapshot schema. It does this in under a millisecond. The important part is that each schedule executes real COMMITs. A cheaper approach would wrap each transaction in SAVEPOINT and ROLLBACK, but that changes READ COMMITTED visibility and can hide the very anomaly the tool is trying to find. Real commits plus a fast reset preserve the semantics.

The workspace has six crates: pgloom-wire for the protocol proxy, pgloom-engine for the scheduler, pgloom-pgctrl for the PostgreSQL control and reset logic, pgloom-driver for the HTTP and SQL workers, pgloom-report for the response and SQL invariant evaluators and the static Fix Advisor, and pgloom-cli for the command-line interface and deterministic replay. The project tests PostgreSQL 12 through 17 on CI, uses proptest for property suites, and runs cargo-fuzz targets over the wire frame and message decoders, the SQL classifier, and the Fix Advisor.

The demo and the fix

The pgloom demo command is a self-contained vulnerable wallet handler. It catches the double-spend in about 60 milliseconds, patches the query with FOR NO KEY UPDATE, and re-explores every schedule to verify the fix. It uses a local PostgreSQL instance or starts a throwaway postgres:17-alpine container.

The trace is the useful part. It shows request A reading 100, updating, and pausing before COMMIT. It shows request B reading 100, updating, and blocking on A’s row lock. It shows A committing, B’s lock being granted, and B committing. Both HTTP requests return 200. The database ends at -100. The trace makes the bug obvious in a way that a stack trace does not, because the bug is not in a single stack; it is in the ordering of two stacks.

The Fix Advisor suggests two static SQL fixes. The pessimistic option is SELECT balance FROM wallets WHERE id = $1 FOR NO KEY UPDATE;. The FOR NO KEY UPDATE lock is weaker than FOR UPDATE: it still conflicts with updates, but it does not block foreign-key checks that take KEY SHARE locks. For a wallet row, that is usually the right trade-off. The atomic option is UPDATE wallets SET balance = balance - $1 WHERE id = $2 AND balance >= $1;, which performs the check and the write in one statement. The advisor suggests; the developer applies; the re-exploration verifies. That separation is honest. A static suggestion is not a proof.

What PgLoom does not do

PgLoom is not a proof of correctness. It explores a bounded set of schedules and reports violations. If it finds nothing, that means it found nothing within the explored schedules, not that the service is free of races. The search can be configured with randomized and PCT (Probabilistic Concurrency Testing) explorers to trade coverage for time, but no finite run covers every possible interleaving.

It is PostgreSQL-only. It speaks the PostgreSQL v3 protocol and tests versions 12 through 17. It does not work with MySQL, SQLite, or other databases. It is a test-time proxy, not a production proxy; running it in front of production traffic would add latency and would not have the reset/snapshot semantics the scheduler needs. It requires a YAML scenario, setup SQL, workers, and invariants. The “no code changes” claim is true for the service, but you still write test code. That is a real cost, and it is the price of a useful test.

The state space can still be large. A scenario with many workers and many statements may explore thousands of schedules. The tool offers modes to bound the search, but the user has to choose a budget. The invariants are only as good as the developer’s understanding of the business rule. If the invariant says “balance must be non-negative” but the real rule is “balance plus pending withdrawals must be non-negative,” the tool will miss the bug. Model checking does not replace domain modeling.

There are also protocol and schema edge cases. Multi-statement transactions, stored procedures, COPY streams, and unusual type layouts may stress the proxy. The project has fuzz targets for the decoders, but every new application brings new SQL. The right approach is to start with one endpoint, verify that the proxy handles its queries, and expand.

How to use it without fooling yourself

Pick one mutating endpoint with a clear invariant. A wallet withdrawal, a coupon redemption, a seat booking, an inventory decrement, or a billing adjustment are good candidates. Write a scenario with two or three concurrent workers that exercise the same row or the same unique constraint. Assert the business invariant in SQL and the expected response behavior in the response assertions. Run the demo first to see the tool’s output format. Then run your scenario with a small schedule budget and increase it if the tool finds nothing.

When it finds a bug, read the trace before changing the query. The trace tells you which statement read which value, which lock blocked which worker, and where the commit happened. That is the information you need to choose between a pessimistic lock and a guarded update. After the fix, re-run the same scenario and confirm that the violating schedule is gone. Then add a regression test that runs the scenario in CI with a fixed seed, so the bug cannot come back silently.

The broader lesson is that concurrency testing is moving down the stack. FoundationDB, Jepsen, Elle, and Antithesis have shown that deterministic exploration and black-box anomaly detection can find bugs that ordinary tests miss. PgLoom brings a narrow version of that idea to the most common backend database in the world. It is not a general-purpose distributed-systems checker. It is a focused tool for a focused problem: SQL transactions that interleave in ways your integration tests never see.

For Rust developers, the project is also a good example of using the language for systems work that is not a web service. The wire protocol parser, the scheduler, the fuzz targets, and the #![forbid(unsafe_code)] policy are all serious engineering. The fact that it works with any language on the other side of the proxy is the point. The database is the shared boundary; the tool meets the application there.

The bottom line

PgLoom is not a proof, but it is a useful flashlight. It finds the interleavings that sequential tests and load tests miss, and it gives you a replayable trace when it does. Start with one mutating endpoint, one invariant, and two workers. If the tool finds nothing, you have learned something about the schedule space; if it finds a double-spend, you have a fix to make and a regression test to keep.

Sources


← back to posts