Repository navigation
fix: make orchestration lock renewal and acknowledge safe under concurrency - #44
Merged
Affan Dar (affandar) merged 15 commits intoOct 26, 2026
Merged
Conversation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Renewal now reads the time again after it waits for the per-instance advisory lock, checks expiry and computes the deadline from that time, and never moves a deadline earlier. It updates queue rows before the instance lock, the order that acknowledge and abandon use, so renewal can no longer deadlock with them. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Bound every wait, drop the schema on failure, and assert lease state in both tables. Add the acknowledge lock-order test, and one test for each change that can happen between renewal's token lookup and its update: time passing, lease expiry, a fetch takeover, acknowledge, abandon, and another renewal. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Generated with scripts/generate_migration_diff.sh 26 against PostgreSQL 15.19, so the +/- markers are in column 1 and match the catalog. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Renewal now waits for the per-instance advisory lock, so PostgreSQL can abort it as the victim when concurrent fetches deadlock on that lock (SQLSTATE 40P01). The runtime stops renewing a turn after any renewal error, so retry transient errors up to three times, as fetch and acknowledge already do. Renewing again is safe because renewal never shortens a lease. Add a test that aborts the first attempt with 40P01. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Reproduce the fetch/renew deadlock the way it happens in production, with no triggers or pauses: another node fetches the instance while the owner renews it, because that node's clock runs ahead or because the renewal reached the database just after the lease expired. Each round releases the two statements together and staggers their start from the fetch 3 ms ahead to the renewal 0.5 ms ahead. Require no deadlock, consistent lease tables, and, for the stalled renewal, that the expired lease is not revived. RACE_ROUNDS scales the round count. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Renewal, acknowledge and abandon find the instance by its lock token, and instance_locks had no index on that column, so each lookup scanned the table. Migration 0026 now adds a unique index on instance_locks(lock_token). It is unique because a token must name exactly one instance, which renewal relies on; only fetch writes lock_token, from gen_random_uuid(). Add a test that checks the index, that the token lookup uses it, and that a duplicate token is rejected. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Split tests/fetch_renew_lock_order_repro_tests.rs: - tests/deadlocks (cargo test --test deadlocks) holds the deadlock tests: renewal against fetch, forced and raced; renewal against acknowledge and abandon; and the retry of a renewal aborted as a deadlock victim. The module doc states the suite's rules. suite_has_no_ignored_tests fails if any file of the suite ignores a test or is not checked. - tests/orchestration_lock_renewal_tests.rs holds the toctou_* tests and the lock_token index test, and shares the suite's helpers. Add renewal_and_abandon_lock_rows_in_the_same_order. The acknowledge and abandon tests send the provider's statements once, on their own connections, so a deadlock fails them with SQLSTATE 40P01 instead of being retried away. They also check that renewal waits for the queue rows without holding the instance_locks row. The fetch test reports a deadlock victim by SQLSTATE before its other checks. No test name changes, except the new abandon test. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Acknowledge checked its lock token once, without a lock. A fetch that judged the lease expired (a worker whose clock runs ahead, or a stalled acknowledge) could take the instance over between that check and the commit. The acknowledge then committed its history and new work while its deletes, which match on the old token, removed nothing, so the messages it processed were delivered again. Duroxide does not de-duplicate queue messages or external events, so they were processed twice. Migration 0026 now also replaces ack_orchestration_item (body otherwise unchanged from 0020): after its token check it takes the per-instance advisory lock that fetch takes before a takeover, checks the token again, and raises if deleting its instance lock removes no row. Tests: tests/deadlocks/ack_fetch.rs (a fetch waits for an acknowledge in progress) and tests/orchestration_ack_lease_tests.rs (takeover while acknowledge waits for the lock, lock deleted mid-acknowledge, a control, and an end-to-end runtime test that charges an order once). Renewal tests that ran an acknowledge while holding the advisory lock now run it in the lock-holding transaction. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Regenerate migrations/0026_diff.md with scripts/generate_migration_diff.sh 26 so it includes the acknowledge change. Correct the migration header, which still said acknowledge does not take the advisory lock. Apply cargo fmt and the clippy auto-deref suggestion to the new tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
docs/tla/orchestration-leases models fetch, acknowledge, renew and abandon statement by statement at READ COMMITTED, with worker clock skew, for three pinned variants: main (3beba92), the renewal fix only (b2ff296) and the renewal and acknowledge fixes (ea598d9). It states the invariants the provider must keep: exactly-once consumption, token fencing, never shortening a lease, and no deadlock within one instance. run.sh downloads TLC (tla2tools v1.7.4, SHA-256 checked), runs the 25 configurations and compares each result with expected.tsv. The fixed variant holds every invariant in four exhaustive configurations; main and the renewal-only variant reproduce the double-processing and deadlock failures. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This was referenced Oct 26, 2026
Affan Dar (affandar)
approved these changes
Oct 26, 2026
ChrisKrawczyk
pushed a commit
that referenced
this pull request
Oct 27, 2026
Prepare duroxide-pg 0.1.38 with the lock-safety fixes from #44 and migration 0026 upgrade notes. Package publication remains a separate maintainer operation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: f0e4a2b7-cb07-472c-8af1-62da8abd5a63
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Makes the PostgreSQL provider's orchestration lock renewal and acknowledge safe under concurrency, without any change to the
Providertrait. This PR supersedes #43 and contains all of its commits.Fixes #29.
Credit: Andrew Chung (Andrew Chung (@andrewkcchung)) started this work in #43. He found and reproduced the fetch/renew lock-order deadlock and introduced the per-instance advisory-lock serialization that this PR builds on. His commits are kept unchanged at the start of this branch.
Problems on
main40P01). When renewal is the victim, the runtime stops renewing the turn and the lease expires mid-turn.instance_locksChanges
0026(CREATE OR REPLACE, same signatures):renew_orchestration_item_locktakes fetch's per-instance advisory lock before any row lock, reads the time after that wait, rechecks the token and expiry, never moves a deadline earlier, and updates queue rows before the instance lock.ack_orchestration_item(body otherwise unchanged from0020) takes the same advisory lock right after its token check, checks the token again, and raises if deleting its instance lock removes no row, so the whole turn rolls back.instance_locks(lock_token).migrations/0026_diff.mdis generated byscripts/generate_migration_diff.sh 26.src/provider.rs: renewal retries transient errors (3 retries, 50/100/150 ms), as fetch and acknowledge already do.tests/deadlocks/is a deadlock suite (cargo test --test deadlocks) that runs in every defaultcargo test. A guard test fails if any of its tests is ignored.tests/orchestration_lock_renewal_tests.rscovers renewal across its wait, and the index.tests/orchestration_ack_lease_tests.rscovers acknowledge and a lost lease, including an end-to-end runtime test.CHANGELOG.md,.github/copilot-instructions.md, and the TLA+ model indocs/tla/orchestration-leases/(below).This addresses ChrisKrawczyk's review on #43.
toctou_fetch_takes_over_while_renewal_waitsimplements the suggested schedule: hold the advisory lock, let renewal block on it, take the instance over inside that transaction, commit, then require the renewal to fail and the replacement lease to stay unchanged.Evidence
All test results are on
a470b74, with PostgreSQL 15.19 and Rust 1.97.1 in a disposable 4-CPU pod. The later commit adds onlydocs/and aCHANGELOG.mdline.cargo test --workspace --verbose --no-fail-fast(CI command plus thepg-stresscrate and doc tests)postgres_provider_test), run again on its own-- --ignored): 5 stress tests, 2 continue-as-new stress tests (including the 25-minute actor test), the search-path testcargo fmt --all --checkcargo clippy --workspace --all-targets --all-featurespg-stress: 30 s per run; 8 orchestration and 8 worker dispatchers; 20 concurrent instances; 5 activities each with a 10 ms delay. Three rounds, alternatingmainand this PR on the same server.main(3beba92)Every deadlock in the PostgreSQL log, on either version, is between two
fetch_orchestration_itemcalls on advisory locks. That is the known fetch-retry-loop issue listed below. None involves renewal, acknowledge or abandon.main, the new tests fail: 17 of 19 againstmain's procedures. The two that pass are the guard test and a control.TLA+ model
docs/tla/orchestration-leases/contains a TLA+ model of the four orchestration lease procedures, with 25 TLC configurations and their expected results. Reviewers can check it themselves:run.shdownloadstla2tools.jarv1.7.4 (TLC 2.19), checks its SHA-256, runs each configuration and compares the result withexpected.tsv. It exits non-zero on any difference. Counterexample traces are written tologs/.What it models
fetch_orchestration_item,ack_orchestration_item,renew_orchestration_item_lockandabandon_orchestration_item, one SQL statement per step, pinned to three commits:MAIN=3beba92;PR43=b2ff296, the renewal fix only;FIXED=ea598d9, this PR's SQL, byte-identical at the head.-MaxSkew..MaxSkewis checked. Time can advance between any two statements.SOURCE-MAP.mdmaps every TLA+ action to its SQL lines.Invariants (from the duroxide provider contract and replay engine)
Results (TLC 2.19). Bounds: 2 workers, 1 instance, 2 messages, lease
L=2, renewal intervalR=1,MaxSkew=2(a full lease), horizon of 3 ticks.MAINPR43FIXEDFIXEDis exhaustive in four configurations:The earlier variants' shortest traces show three paths to double processing:
A stricter clock property fails in every variant, including
FIXED: a renewal that stalls after reading the clock can commit a deadline that has already passed. This is not an ownership failure. Renewal holds the advisory lock, so no takeover can happen during the stall, and the old owner's acknowledge is fenced on the token afterwards.Limits
ContinueAsNew.Verification of this copy: all 25 configurations re-run from this commit with
run.sh(TLC 2.19, OpenJDK 21) matchexpected.tsv: the same verdict and the same number of distinct states for every configuration.Not in this PR (follow-ups)
0026and replacesack_orchestration_item. Whichever merges second must renumber its migration and keep this PR's acknowledge fixCo-authored-by: Andrew Chung 47454279+andrewkcchung@users.noreply.github.com