Skip to content

fix: make orchestration lock renewal and acknowledge safe under concurrency - #44

Merged
Affan Dar (affandar) merged 15 commits into
mainfrom
waldemort/orchestration-lease-safety
Oct 26, 2026
Merged

Affan Dar (affandar) merged 15 commits into
mainfrom
waldemort/orchestration-lease-safety

Conversation

@waldemort-auto

@waldemort-auto waldemort-auto Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Makes the PostgreSQL provider's orchestration lock renewal and acknowledge safe under concurrency, without any change to the Provider trait. 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 main

Problem Effect
Renewal and fetch lock the same two rows in opposite orders Deadlock (40P01). When renewal is the victim, the runtime stops renewing the turn and the lease expires mid-turn.
Renewal and acknowledge or abandon lock the same two rows in opposite orders Same deadlock.
Renewal checks expiry with a time read before it got a connection, and can move a deadline earlier An expired lease can be revived; a lease can be shortened.
Acknowledge checks its lock token once, without a lock, and does not check its final deletes If another worker takes the instance over during the acknowledge (its clock runs ahead, or the lease simply expires), the acknowledge still commits. Its messages stay queued and are processed again. Duroxide does not de-duplicate queue messages or external events, so one enqueued event can run an activity twice. Reproduced end to end with the duroxide runtime.
Renew, acknowledge and abandon find a lease by scanning instance_locks Cost grows with the number of held leases.

Changes

  • Migration 0026 (CREATE OR REPLACE, same signatures):
    • renew_orchestration_item_lock takes 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 from 0020) 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.
    • A unique index on instance_locks(lock_token).
    • migrations/0026_diff.md is generated by scripts/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: 19 new PostgreSQL tests.
    • tests/deadlocks/ is a deadlock suite (cargo test --test deadlocks) that runs in every default cargo test. A guard test fails if any of its tests is ignored.
    • tests/orchestration_lock_renewal_tests.rs covers renewal across its wait, and the index.
    • tests/orchestration_ack_lease_tests.rs covers acknowledge and a lost lease, including an end-to-end runtime test.
  • Docs: CHANGELOG.md, .github/copilot-instructions.md, and the TLA+ model in docs/tla/orchestration-leases/ (below).

This addresses ChrisKrawczyk's review on #43. toctou_fetch_takes_over_while_renewal_waits implements 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 only docs/ and a CHANGELOG.md line.

Check Result
cargo test --workspace --verbose --no-fail-fast (CI command plus the pg-stress crate and doc tests) 406 passed, 0 failed, 9 ignored, 23 test binaries
Provider validation suite (postgres_provider_test), run again on its own 232 of 232
Every ignored test (-- --ignored): 5 stress tests, 2 continue-as-new stress tests (including the 25-minute actor test), the search-path test 9 of 9; the live Entra test skipped itself because no Entra credentials were set
New tests, three runs in a row 19 of 19
cargo fmt --all --check clean
cargo clippy --workspace --all-targets --all-features no new warnings; the 5 existing ones are in unchanged files
PostgreSQL deadlocks during all of the above 0

pg-stress: 30 s per run; 8 orchestration and 8 worker dispatchers; 20 concurrent instances; 5 activities each with a 10 ms delay. Three rounds, alternating main and this PR on the same server.

Orchestrations/s Average latency Failed PostgreSQL deadlocks per run
main (3beba92) 67.4, 54.2, 69.1 14.8, 18.4, 14.5 ms 0 13, 19, 12
This PR 80.6, 83.9, 82.8 12.4, 11.9, 12.1 ms 0 3, 1, 0

Every deadlock in the PostgreSQL log, on either version, is between two fetch_orchestration_item calls on advisory locks. That is the known fetch-retry-loop issue listed below. None involves renewal, acknowledge or abandon.

  • On main, the new tests fail: 17 of 19 against main'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:

cd docs/tla/orchestration-leases
./run.sh                                  # all 25 configurations, ~25 min on one core
./run.sh MAIN-consumption FIXED-redelivery FIXED-release-race   # a few seconds

run.sh downloads tla2tools.jar v1.7.4 (TLC 2.19), checks its SHA-256, runs each configuration and compares the result with expected.tsv. It exits non-zero on any difference. Counterexample traces are written to logs/.

What it models

  • fetch_orchestration_item, ack_orchestration_item, renew_orchestration_item_lock and abandon_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.
  • PostgreSQL behaviour:
    • each statement sees the latest commits (READ COMMITTED);
    • row and advisory locks are held until commit;
    • a blocked update re-evaluates its token predicate;
    • deadlock-victim aborts;
    • the history primary key.
  • Callers read their clock before waiting for a connection, and may be cancelled. Each worker has a fixed clock skew, and every combination in -MaxSkew..MaxSkew is checked. Time can advance between any two statements.
  • SOURCE-MAP.md maps every TLA+ action to its SQL lines.

Invariants (from the duroxide provider contract and replay engine)

  • Exactly-once consumption: no committed turn leaves its input queued, and no message is consumed by two turns.
  • One writer per history position.
  • Atomic outputs.
  • No message loss.
  • Queue and lock rows agree.
  • Renewal and acknowledge commit only while their token owns the instance.
  • A renewal never shortens a lease.
  • No lock cycle within one instance.

Results (TLC 2.19). Bounds: 2 workers, 1 instance, 2 messages, lease L=2, renewal interval R=1, MaxSkew=2 (a full lease), horizon of 3 ticks.

Variant Exactly-once Token fencing No deadlock Never shorten
MAIN violated (20-state trace) renewal holds violated: renewal with fetch, acknowledge, abandon violated
PR43 violated (20-state trace) renewal holds holds holds
FIXED holds renewal and acknowledge hold holds holds

FIXED is exhaustive in four configurations:

Configuration Distinct states Depth
acknowledge + fetch-then-acknowledge + renewal 3,854,292 39
abandon + fetch-then-acknowledge + renewal 4,227,695 40
acknowledge, then two later fetch-then-acknowledges (redelivery) 286,344 45
acknowledge and abandon on the same token 1,894 18

The earlier variants' shortest traces show three paths to double processing:

  • a takeover by a fetch whose clock runs ahead;
  • plain expiry with zero skew;
  • an abandon with the same token during the acknowledge.

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

  • The checks are bounded, not a proof for every size.
  • One instance only, so fetch-against-fetch deadlocks across instances are out of scope.
  • Not modelled: the worker queue, sessions and ContinueAsNew.
  • The model was written with the known failures in view. An independently written model would be a stronger check.

Verification of this copy: all 25 configurations re-run from this commit with run.sh (TLC 2.19, OpenJDK 21) match expected.tsv: the same verdict and the same number of distinct states for every configuration.

Not in this PR (follow-ups)

Issue Follow-up
#34 Fetch against fetch across instances: fetch's retry loop keeps each candidate's advisory lock, so two fetches can deadlock. Fix: try-lock later candidates. All 98 deadlocks in the stress runs above are of this kind
#45 Lease expiry is judged by each worker's own clock. A worker whose clock runs ahead takes over live leases; this PR makes that safe but not cheap
#46 Open PR #32 also uses migration 0026 and replaces ack_orchestration_item. Whichever merges second must renumber its migration and keep this PR's acknowledge fix
#47 A renewal that stalls after reading the clock can commit a deadline that has already passed. This is not an ownership bug, because acknowledge is fenced on the token
#48 Strengthen the TLA+ model and tests: reachability checks, mutation runs, an independent model, trace replay, a test for the token recheck
#49 Renewal extensions are truncated to whole seconds; abandon and the worker-queue calls have no retry
microsoft/duroxide#75 Add the lease-fencing and exactly-once properties to duroxide's provider validation suite

Co-authored-by: Andrew Chung 47454279+andrewkcchung@users.noreply.github.com

Waldemort Agent and others added 14 commits October 22, 2026 15:44
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>
@affandar
Affan Dar (affandar) merged commit 34f7d57 into main Oct 26, 2026
4 checks passed
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ack_orchestration_item validates the lock without a row lock; a concurrent fetch can leave consumed messages in the queue

1 participant