From c203c41f776224bc9aae648214a586fdd2213f59 Mon Sep 17 00:00:00 2001 From: Waldemort Agent Date: Thu, 22 Oct 2026 15:44:58 +0000 Subject: [PATCH 01/15] test: reproduce fetch-renew lock order deadlock Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/fetch_renew_lock_order_repro_tests.rs | 188 ++++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 tests/fetch_renew_lock_order_repro_tests.rs diff --git a/tests/fetch_renew_lock_order_repro_tests.rs b/tests/fetch_renew_lock_order_repro_tests.rs new file mode 100644 index 0000000..6181b41 --- /dev/null +++ b/tests/fetch_renew_lock_order_repro_tests.rs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! PostgreSQL reproduction for the orchestration fetch/renew lock-order cycle. +//! +//! `fetch_orchestration_item` locks `orchestrator_queue` before it upserts +//! `instance_locks`. `renew_orchestration_item_lock` updates `instance_locks` +//! before it updates `orchestrator_queue`. This test uses a test-local trigger +//! to pause renewal after it owns the instance-lock row, then advances the +//! fetch clock beyond the old lease. Fetch owns the queue row and waits on the +//! instance-lock row; renewal then waits on the queue row. PostgreSQL must +//! abort one transaction with SQLSTATE 40P01. +//! +//! When the production functions acquire their shared rows in one order, this +//! test should be inverted to require both operations to complete successfully. + +use duroxide::providers::{Provider, WorkItem}; +use duroxide_pg::PostgresProvider; +use sqlx::postgres::PgPoolOptions; +use sqlx::PgPool; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +const ORCHESTRATION: &str = "FetchRenewLockOrder"; +const PAUSE_LOCK_KEY: i64 = 8_341_924_991; + +fn database_url() -> String { + dotenvy::dotenv().ok(); + std::env::var("DATABASE_URL").expect("DATABASE_URL must be set") +} + +fn unique_schema_name() -> String { + let guid = uuid::Uuid::new_v4().to_string(); + let suffix = &guid[guid.len() - 8..]; + format!("fetch_renew_lock_order_{suffix}") +} + +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock before Unix epoch") + .as_millis() as i64 +} + +async fn raw_pool(database_url: &str) -> PgPool { + PgPoolOptions::new() + .max_connections(4) + .connect(database_url) + .await + .expect("failed to create raw PostgreSQL pool") +} + +async fn drop_schema(pool: &PgPool, schema: &str) { + sqlx::query(&format!("DROP SCHEMA IF EXISTS {schema} CASCADE")) + .execute(pool) + .await + .expect("failed to drop test schema"); +} + +fn sqlstate(error: &sqlx::Error) -> Option<&str> { + match error { + sqlx::Error::Database(database_error) => database_error.code().as_deref(), + _ => None, + } +} + +async fn wait_until_renewal_holds_pause_lock(pool: &PgPool) { + for _ in 0..100 { + let held: bool = sqlx::query_scalar("SELECT NOT pg_try_advisory_xact_lock($1)") + .bind(PAUSE_LOCK_KEY) + .fetch_one(pool) + .await + .expect("failed to probe renewal pause lock"); + if held { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + + panic!("renewal never reached the lock-order pause trigger"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn fetch_and_renew_form_a_deadlock_when_they_lock_rows_in_opposite_orders() { + let schema = unique_schema_name(); + let database_url = database_url(); + let provider = PostgresProvider::new_with_schema(&database_url, Some(&schema)) + .await + .expect("failed to create provider"); + let pool = raw_pool(&database_url).await; + let instance = format!("instance-{}", uuid::Uuid::new_v4()); + + provider + .enqueue_for_orchestrator( + WorkItem::StartOrchestration { + instance, + orchestration: ORCHESTRATION.to_string(), + input: "{}".to_string(), + version: Some("1.0.0".to_string()), + parent_instance: None, + parent_id: None, + parent_execution_id: None, + execution_id: 1, + }, + None, + ) + .await + .expect("failed to enqueue orchestration work"); + + let (_item, token, _attempt_count) = provider + .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None) + .await + .expect("initial fetch failed") + .expect("initial fetch did not return work"); + + // The token is generated by the provider as `lock_`, so it cannot + // contain this dollar-quote delimiter. + let pause_function = format!( + "CREATE FUNCTION {schema}.pause_renewal_after_instance_lock() + RETURNS trigger + LANGUAGE plpgsql + AS $function$ + BEGIN + IF NEW.lock_token = $token${token}$token$ THEN + PERFORM pg_advisory_xact_lock({PAUSE_LOCK_KEY}); + PERFORM pg_sleep(5); + END IF; + RETURN NEW; + END; + $function$" + ); + sqlx::query(&pause_function) + .execute(&pool) + .await + .expect("failed to create renewal pause function"); + sqlx::query(&format!( + "CREATE TRIGGER pause_renewal_after_instance_lock + AFTER UPDATE OF locked_until ON {schema}.instance_locks + FOR EACH ROW EXECUTE FUNCTION {schema}.pause_renewal_after_instance_lock()" + )) + .execute(&pool) + .await + .expect("failed to create renewal pause trigger"); + + let renew_now_ms = now_ms(); + let renewal_pool = pool.clone(); + let renewal_schema = schema.clone(); + let renewal_token = token.clone(); + let renewal = tokio::spawn(async move { + sqlx::query(&format!( + "SELECT {renewal_schema}.renew_orchestration_item_lock($1, $2, $3)" + )) + .bind(renewal_token) + .bind(renew_now_ms) + .bind(60_i64) + .execute(&renewal_pool) + .await + }); + + wait_until_renewal_holds_pause_lock(&pool).await; + + // The fetch timestamp is later than both leases held before and during + // renewal. It therefore locks the queue row, then blocks trying to update + // the instance-lock row that renewal still owns. + let fetch_result = sqlx::query(&format!( + "SELECT * FROM {schema}.fetch_orchestration_item($1, $2, NULL, NULL)" + )) + .bind(renew_now_ms + 120_000) + .bind(30_000_i64) + .fetch_optional(&pool) + .await; + let renewal_result = renewal.await.expect("renewal task panicked"); + + let fetch_deadlocked = fetch_result + .as_ref() + .err() + .is_some_and(|error| sqlstate(error) == Some("40P01")); + let renewal_deadlocked = renewal_result + .as_ref() + .err() + .is_some_and(|error| sqlstate(error) == Some("40P01")); + + drop_schema(&pool, &schema).await; + + assert!( + fetch_deadlocked || renewal_deadlocked, + "expected PostgreSQL lock-order deadlock (40P01), fetch={fetch_result:?}, renewal={renewal_result:?}" + ); +} From 85bf504b4dc55696e036da65dabdb0d0501c958c Mon Sep 17 00:00:00 2001 From: Waldemort Agent Date: Thu, 22 Oct 2026 15:47:57 +0000 Subject: [PATCH 02/15] test: retain deadlock SQLSTATE for assertion Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/fetch_renew_lock_order_repro_tests.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/fetch_renew_lock_order_repro_tests.rs b/tests/fetch_renew_lock_order_repro_tests.rs index 6181b41..9a3eebc 100644 --- a/tests/fetch_renew_lock_order_repro_tests.rs +++ b/tests/fetch_renew_lock_order_repro_tests.rs @@ -56,9 +56,9 @@ async fn drop_schema(pool: &PgPool, schema: &str) { .expect("failed to drop test schema"); } -fn sqlstate(error: &sqlx::Error) -> Option<&str> { +fn sqlstate(error: &sqlx::Error) -> Option { match error { - sqlx::Error::Database(database_error) => database_error.code().as_deref(), + sqlx::Error::Database(database_error) => database_error.code().map(|code| code.into()), _ => None, } } @@ -173,11 +173,11 @@ async fn fetch_and_renew_form_a_deadlock_when_they_lock_rows_in_opposite_orders( let fetch_deadlocked = fetch_result .as_ref() .err() - .is_some_and(|error| sqlstate(error) == Some("40P01")); + .is_some_and(|error| sqlstate(error).as_deref() == Some("40P01")); let renewal_deadlocked = renewal_result .as_ref() .err() - .is_some_and(|error| sqlstate(error) == Some("40P01")); + .is_some_and(|error| sqlstate(error).as_deref() == Some("40P01")); drop_schema(&pool, &schema).await; From 53c6ed4eff086d79a519c7e4c88674966ca95afe Mon Sep 17 00:00:00 2001 From: Waldemort Agent Date: Thu, 22 Oct 2026 16:24:50 +0000 Subject: [PATCH 03/15] fix: serialize orchestration lock renewal with fetch Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 9 ++ migrations/0026_diff.md | 69 +++++++++ ...serialize_orchestration_lock_mutations.sql | 64 ++++++++ tests/fetch_renew_lock_order_repro_tests.rs | 143 +++++++++++------- 4 files changed, 231 insertions(+), 54 deletions(-) create mode 100644 migrations/0026_diff.md create mode 100644 migrations/0026_serialize_orchestration_lock_mutations.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index d1e70a8..a7e99f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- **Serialize orchestration lock renewal with fetches (migration `0026`).** + Renewal now takes the same per-instance transaction advisory lock as + `fetch_orchestration_item` before either procedure acquires conflicting row + locks. This prevents the fetch/renew `40P01` cycle under concurrent + dispatchers. The PostgreSQL regression test uses a per-run, gate-controlled + interleaving and requires both operations to complete. + ## [0.1.37] - 2026-10-21 ### Fixed diff --git a/migrations/0026_diff.md b/migrations/0026_diff.md new file mode 100644 index 0000000..6772790 --- /dev/null +++ b/migrations/0026_diff.md @@ -0,0 +1,69 @@ +# Diff for migration 0026 + +**Migration file:** `0026_serialize_orchestration_lock_mutations.sql` + +## Table Changes + +None. + +## New Indexes + +None. + +## Function Changes + +### `renew_orchestration_item_lock` — body modified (baseline: 0004) + +```diff + CREATE OR REPLACE FUNCTION SCHEMA.renew_orchestration_item_lock( + p_lock_token TEXT, + p_now_ms BIGINT, + p_extend_secs BIGINT + ) + RETURNS VOID AS $renew_orch_lock$ + DECLARE + + v_instance_id TEXT; + v_locked_until BIGINT; + v_rows_affected INTEGER; + BEGIN + + SELECT il.instance_id INTO v_instance_id + + FROM SCHEMA.instance_locks il + + WHERE il.lock_token = p_lock_token + + AND il.locked_until > p_now_ms; ++ + + IF NOT FOUND THEN + + RAISE EXCEPTION 'Lock token invalid, expired, or already released'; + + END IF; + + + + PERFORM pg_advisory_xact_lock(hashtext(v_instance_id)); + + + v_locked_until := p_now_ms + (p_extend_secs * 1000); + + UPDATE SCHEMA.instance_locks + SET locked_until = v_locked_until + - WHERE lock_token = p_lock_token + + WHERE instance_id = v_instance_id + + AND lock_token = p_lock_token + AND locked_until > p_now_ms; + + GET DIAGNOSTICS v_rows_affected = ROW_COUNT; + + IF v_rows_affected = 0 THEN + RAISE EXCEPTION 'Lock token invalid, expired, or already released'; + END IF; + + UPDATE SCHEMA.orchestrator_queue + SET locked_until = v_locked_until + WHERE lock_token = p_lock_token; + END; + $renew_orch_lock$ LANGUAGE plpgsql; + ``` + +## Notes + +- Renewal now acquires the same transaction-scoped per-instance advisory lock + as `fetch_orchestration_item` before either function takes its conflicting + row locks. +- The post-lock `UPDATE` repeats the token and expiry predicates because a + concurrent fetch can make a token stale while renewal waits for the advisory + lock. diff --git a/migrations/0026_serialize_orchestration_lock_mutations.sql b/migrations/0026_serialize_orchestration_lock_mutations.sql new file mode 100644 index 0000000..b76f002 --- /dev/null +++ b/migrations/0026_serialize_orchestration_lock_mutations.sql @@ -0,0 +1,64 @@ +-- Copyright (c) Microsoft Corporation. +-- Licensed under the MIT License. + +-- Migration 0026: serialize renewal with orchestration fetches +-- +-- fetch_orchestration_item takes pg_advisory_xact_lock(hashtext(instance_id)) +-- before it locks the queue row and the instance_locks row. Renewal previously +-- updated instance_locks first and then orchestrator_queue without that +-- advisory lock. The opposing row-lock order permits a fetch/renew deadlock. +-- +-- Resolve the live token to its instance without taking a row lock, acquire +-- the same advisory lock as fetch, then update the lease rows. A concurrent +-- fetch or renewal for the instance now waits before either transaction takes +-- its first conflicting row lock. The second UPDATE repeats the token and +-- expiry predicates because the advisory-lock wait can make a token stale. + +DO $$ +DECLARE + v_schema_name TEXT := current_schema(); +BEGIN + EXECUTE format($fmt$ + CREATE OR REPLACE FUNCTION %1$I.renew_orchestration_item_lock( + p_lock_token TEXT, + p_now_ms BIGINT, + p_extend_secs BIGINT + ) + RETURNS VOID AS $renew_orch_lock$ + DECLARE + v_instance_id TEXT; + v_locked_until BIGINT; + v_rows_affected INTEGER; + BEGIN + SELECT il.instance_id INTO v_instance_id + FROM %1$I.instance_locks il + WHERE il.lock_token = p_lock_token + AND il.locked_until > p_now_ms; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Lock token invalid, expired, or already released'; + END IF; + + PERFORM pg_advisory_xact_lock(hashtext(v_instance_id)); + + v_locked_until := p_now_ms + (p_extend_secs * 1000); + + UPDATE %1$I.instance_locks + SET locked_until = v_locked_until + WHERE instance_id = v_instance_id + AND lock_token = p_lock_token + AND locked_until > p_now_ms; + + GET DIAGNOSTICS v_rows_affected = ROW_COUNT; + + IF v_rows_affected = 0 THEN + RAISE EXCEPTION 'Lock token invalid, expired, or already released'; + END IF; + + UPDATE %1$I.orchestrator_queue + SET locked_until = v_locked_until + WHERE lock_token = p_lock_token; + END; + $renew_orch_lock$ LANGUAGE plpgsql; +$fmt$, v_schema_name); +END $$; diff --git a/tests/fetch_renew_lock_order_repro_tests.rs b/tests/fetch_renew_lock_order_repro_tests.rs index 9a3eebc..21f3ebb 100644 --- a/tests/fetch_renew_lock_order_repro_tests.rs +++ b/tests/fetch_renew_lock_order_repro_tests.rs @@ -1,27 +1,23 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -//! PostgreSQL reproduction for the orchestration fetch/renew lock-order cycle. +//! Regression test for the orchestration fetch/renew lock-order deadlock. //! -//! `fetch_orchestration_item` locks `orchestrator_queue` before it upserts -//! `instance_locks`. `renew_orchestration_item_lock` updates `instance_locks` -//! before it updates `orchestrator_queue`. This test uses a test-local trigger -//! to pause renewal after it owns the instance-lock row, then advances the -//! fetch clock beyond the old lease. Fetch owns the queue row and waits on the -//! instance-lock row; renewal then waits on the queue row. PostgreSQL must -//! abort one transaction with SQLSTATE 40P01. -//! -//! When the production functions acquire their shared rows in one order, this -//! test should be inverted to require both operations to complete successfully. +//! Before migration 0026, fetch locked a queue row then waited for +//! `instance_locks`, while renewal held `instance_locks` then waited for the +//! queue row. This test pauses renewal after its first row update and waits +//! until fetch is blocked. Releasing renewal must let both operations finish: +//! migration 0026 makes renewal acquire fetch's per-instance advisory lock +//! before either procedure takes a conflicting row lock. use duroxide::providers::{Provider, WorkItem}; use duroxide_pg::PostgresProvider; -use sqlx::postgres::PgPoolOptions; -use sqlx::PgPool; +use sqlx::postgres::{PgConnection, PgPoolOptions}; +use sqlx::{Connection, Executor, PgPool}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use tokio::sync::oneshot; const ORCHESTRATION: &str = "FetchRenewLockOrder"; -const PAUSE_LOCK_KEY: i64 = 8_341_924_991; fn database_url() -> String { dotenvy::dotenv().ok(); @@ -34,6 +30,11 @@ fn unique_schema_name() -> String { format!("fetch_renew_lock_order_{suffix}") } +fn advisory_key() -> i64 { + let bytes = *uuid::Uuid::new_v4().as_bytes(); + i64::from_be_bytes(bytes[..8].try_into().expect("UUID prefix has eight bytes")) +} + fn now_ms() -> i64 { SystemTime::now() .duration_since(UNIX_EPOCH) @@ -56,31 +57,45 @@ async fn drop_schema(pool: &PgPool, schema: &str) { .expect("failed to drop test schema"); } -fn sqlstate(error: &sqlx::Error) -> Option { - match error { - sqlx::Error::Database(database_error) => database_error.code().map(|code| code.into()), - _ => None, - } -} - -async fn wait_until_renewal_holds_pause_lock(pool: &PgPool) { +async fn wait_for_advisory_holder(pool: &PgPool, key: i64) { for _ in 0..100 { let held: bool = sqlx::query_scalar("SELECT NOT pg_try_advisory_xact_lock($1)") - .bind(PAUSE_LOCK_KEY) + .bind(key) .fetch_one(pool) .await - .expect("failed to probe renewal pause lock"); + .expect("failed to probe renewal readiness lock"); if held { return; } tokio::time::sleep(Duration::from_millis(10)).await; } - panic!("renewal never reached the lock-order pause trigger"); + panic!("renewal never reached the lock-order gate"); +} + +async fn wait_for_lock_waiter(pool: &PgPool, pid: i32) { + for _ in 0..100 { + let waiting: bool = sqlx::query_scalar( + "SELECT COALESCE(wait_event_type = 'Lock', false) + FROM pg_stat_activity + WHERE pid = $1", + ) + .bind(pid) + .fetch_optional(pool) + .await + .expect("failed to inspect fetch backend state") + .unwrap_or(false); + if waiting { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + + panic!("fetch did not wait for renewal's transaction"); } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn fetch_and_renew_form_a_deadlock_when_they_lock_rows_in_opposite_orders() { +async fn fetch_and_renew_serialize_before_taking_conflicting_row_locks() { let schema = unique_schema_name(); let database_url = database_url(); let provider = PostgresProvider::new_with_schema(&database_url, Some(&schema)) @@ -112,6 +127,18 @@ async fn fetch_and_renew_form_a_deadlock_when_they_lock_rows_in_opposite_orders( .expect("initial fetch failed") .expect("initial fetch did not return work"); + let ready_key = advisory_key(); + let gate_key = advisory_key(); + let mut gate_connection = PgConnection::connect(&database_url) + .await + .expect("failed to connect gate session"); + let mut gate = gate_connection.begin().await.expect("failed to begin gate transaction"); + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(gate_key) + .execute(&mut *gate) + .await + .expect("failed to take gate advisory lock"); + // The token is generated by the provider as `lock_`, so it cannot // contain this dollar-quote delimiter. let pause_function = format!( @@ -121,8 +148,8 @@ async fn fetch_and_renew_form_a_deadlock_when_they_lock_rows_in_opposite_orders( AS $function$ BEGIN IF NEW.lock_token = $token${token}$token$ THEN - PERFORM pg_advisory_xact_lock({PAUSE_LOCK_KEY}); - PERFORM pg_sleep(5); + PERFORM pg_advisory_xact_lock({ready_key}); + PERFORM pg_advisory_xact_lock({gate_key}); END IF; RETURN NEW; END; @@ -142,47 +169,55 @@ async fn fetch_and_renew_form_a_deadlock_when_they_lock_rows_in_opposite_orders( .expect("failed to create renewal pause trigger"); let renew_now_ms = now_ms(); - let renewal_pool = pool.clone(); let renewal_schema = schema.clone(); let renewal_token = token.clone(); + let renewal_database_url = database_url.clone(); let renewal = tokio::spawn(async move { + let mut connection = PgConnection::connect(&renewal_database_url) + .await + .expect("failed to connect renewal session"); sqlx::query(&format!( "SELECT {renewal_schema}.renew_orchestration_item_lock($1, $2, $3)" )) .bind(renewal_token) .bind(renew_now_ms) .bind(60_i64) - .execute(&renewal_pool) + .execute(&mut connection) .await }); - wait_until_renewal_holds_pause_lock(&pool).await; + wait_for_advisory_holder(&pool, ready_key).await; - // The fetch timestamp is later than both leases held before and during - // renewal. It therefore locks the queue row, then blocks trying to update - // the instance-lock row that renewal still owns. - let fetch_result = sqlx::query(&format!( - "SELECT * FROM {schema}.fetch_orchestration_item($1, $2, NULL, NULL)" - )) - .bind(renew_now_ms + 120_000) - .bind(30_000_i64) - .fetch_optional(&pool) - .await; - let renewal_result = renewal.await.expect("renewal task panicked"); + let fetch_schema = schema.clone(); + let fetch_database_url = database_url.clone(); + let (fetch_pid_tx, fetch_pid_rx) = oneshot::channel(); + let fetch = tokio::spawn(async move { + let mut connection = PgConnection::connect(&fetch_database_url) + .await + .expect("failed to connect fetch session"); + let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut connection) + .await + .expect("failed to read fetch backend PID"); + let _ = fetch_pid_tx.send(pid); + sqlx::query(&format!( + "SELECT * FROM {fetch_schema}.fetch_orchestration_item($1, $2, NULL, NULL)" + )) + .bind(renew_now_ms + 120_000) + .bind(30_000_i64) + .fetch_optional(&mut connection) + .await + }); - let fetch_deadlocked = fetch_result - .as_ref() - .err() - .is_some_and(|error| sqlstate(error).as_deref() == Some("40P01")); - let renewal_deadlocked = renewal_result - .as_ref() - .err() - .is_some_and(|error| sqlstate(error).as_deref() == Some("40P01")); + let fetch_pid = fetch_pid_rx.await.expect("fetch task did not report its backend PID"); + wait_for_lock_waiter(&pool, fetch_pid).await; + + gate.commit().await.expect("failed to release renewal gate"); + let renewal_result = renewal.await.expect("renewal task panicked"); + let fetch_result = fetch.await.expect("fetch task panicked"); drop_schema(&pool, &schema).await; - assert!( - fetch_deadlocked || renewal_deadlocked, - "expected PostgreSQL lock-order deadlock (40P01), fetch={fetch_result:?}, renewal={renewal_result:?}" - ); + renewal_result.expect("renewal must complete without a deadlock"); + fetch_result.expect("fetch must complete without a deadlock"); } From ebf85aa79104bbb40364dce3b33c43ca33740b6e Mon Sep 17 00:00:00 2001 From: Waldemort Agent Date: Thu, 22 Oct 2026 16:30:37 +0000 Subject: [PATCH 04/15] test: remove lock-order regression warning Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/fetch_renew_lock_order_repro_tests.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/fetch_renew_lock_order_repro_tests.rs b/tests/fetch_renew_lock_order_repro_tests.rs index 21f3ebb..01f00d5 100644 --- a/tests/fetch_renew_lock_order_repro_tests.rs +++ b/tests/fetch_renew_lock_order_repro_tests.rs @@ -13,7 +13,7 @@ use duroxide::providers::{Provider, WorkItem}; use duroxide_pg::PostgresProvider; use sqlx::postgres::{PgConnection, PgPoolOptions}; -use sqlx::{Connection, Executor, PgPool}; +use sqlx::{Connection, PgPool}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tokio::sync::oneshot; @@ -132,7 +132,10 @@ async fn fetch_and_renew_serialize_before_taking_conflicting_row_locks() { let mut gate_connection = PgConnection::connect(&database_url) .await .expect("failed to connect gate session"); - let mut gate = gate_connection.begin().await.expect("failed to begin gate transaction"); + let mut gate = gate_connection + .begin() + .await + .expect("failed to begin gate transaction"); sqlx::query("SELECT pg_advisory_xact_lock($1)") .bind(gate_key) .execute(&mut *gate) @@ -209,7 +212,9 @@ async fn fetch_and_renew_serialize_before_taking_conflicting_row_locks() { .await }); - let fetch_pid = fetch_pid_rx.await.expect("fetch task did not report its backend PID"); + let fetch_pid = fetch_pid_rx + .await + .expect("fetch task did not report its backend PID"); wait_for_lock_waiter(&pool, fetch_pid).await; gate.commit().await.expect("failed to release renewal gate"); From 4628786c72b728471311f5e09c8f33289faa0f98 Mon Sep 17 00:00:00 2001 From: Waldemort Agent Date: Thu, 22 Oct 2026 16:33:26 +0000 Subject: [PATCH 05/15] docs: normalize migration diff whitespace Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- migrations/0026_diff.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/migrations/0026_diff.md b/migrations/0026_diff.md index 6772790..bdbb27b 100644 --- a/migrations/0026_diff.md +++ b/migrations/0026_diff.md @@ -38,20 +38,20 @@ None. + PERFORM pg_advisory_xact_lock(hashtext(v_instance_id)); + v_locked_until := p_now_ms + (p_extend_secs * 1000); - + + UPDATE SCHEMA.instance_locks SET locked_until = v_locked_until - WHERE lock_token = p_lock_token + WHERE instance_id = v_instance_id + AND lock_token = p_lock_token AND locked_until > p_now_ms; - ++ GET DIAGNOSTICS v_rows_affected = ROW_COUNT; - ++ IF v_rows_affected = 0 THEN RAISE EXCEPTION 'Lock token invalid, expired, or already released'; END IF; - ++ UPDATE SCHEMA.orchestrator_queue SET locked_until = v_locked_until WHERE lock_token = p_lock_token; From 825c2f920caaf54e307f330be6202327ef4a42ed Mon Sep 17 00:00:00 2001 From: Waldemort Agent Date: Fri, 23 Oct 2026 01:33:57 +0000 Subject: [PATCH 06/15] fix: renew from the time after the advisory-lock wait 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> --- .github/copilot-instructions.md | 2 +- CHANGELOG.md | 18 ++++-- ...serialize_orchestration_lock_mutations.sql | 59 ++++++++++++++----- 3 files changed, 56 insertions(+), 23 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 454b1ad..e00cdd2 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -13,7 +13,7 @@ This is a **PostgreSQL provider** for [Duroxide](https://github.com/microsoft/du ### Key Design Decisions 1. **Stored Procedures over inline SQL** - All database operations use schema-qualified stored procedures in `0002_create_stored_procedures.sql` for atomic transactions and deadlock prevention -2. **Rust-provided timestamps** - All procedures receive `p_now_ms` from Rust (not database `NOW()`) to avoid clock skew (see migration `0006`). Exception: `fetch_orchestration_item` computes the lease as `GREATEST(p_now_ms + time spent in the call, clock_timestamp()) + timeout`, so a lease is never already expired when it is returned (migration `0025`) +2. **Rust-provided timestamps** - All procedures receive `p_now_ms` from Rust (not database `NOW()`) to avoid clock skew (see migration `0006`). Exceptions: `fetch_orchestration_item` computes the lease as `GREATEST(p_now_ms + time spent in the call, clock_timestamp()) + timeout`, so a lease is never already expired when it is returned (migration `0025`); `renew_orchestration_item_lock` uses the same clock after its advisory-lock wait to check expiry and compute the new deadline, and never moves a deadline earlier (migration `0026`) 3. **Schema isolation** - Multi-tenant support via custom PostgreSQL schemas (`new_with_schema()`) 4. **Two-phase locking in fetch operations** - Prevents B-tree index deadlocks (peek query → advisory lock → FOR UPDATE verification) diff --git a/CHANGELOG.md b/CHANGELOG.md index a7e99f9..ad5f0e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,12 +9,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- **Serialize orchestration lock renewal with fetches (migration `0026`).** - Renewal now takes the same per-instance transaction advisory lock as - `fetch_orchestration_item` before either procedure acquires conflicting row - locks. This prevents the fetch/renew `40P01` cycle under concurrent - dispatchers. The PostgreSQL regression test uses a per-run, gate-controlled - interleaving and requires both operations to complete. +- **Orchestration lock renewal no longer deadlocks with fetch or with + acknowledge and abandon, and no longer reports success for an expired lease + (migration `0026`).** Renewal takes the same per-instance transaction + advisory lock as `fetch_orchestration_item` before it locks any row, so the + two can no longer deadlock (SQLSTATE `40P01`). It then updates queue rows + before the instance lock, the order that acknowledge and abandon use. After + the advisory-lock wait, renewal reads the time again: it fails if the lease + expired during the wait, and it never moves a lease deadline earlier. + PostgreSQL regression tests cover the fetch deadlock, the acknowledge lock + order, and 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. ## [0.1.37] - 2026-10-21 diff --git a/migrations/0026_serialize_orchestration_lock_mutations.sql b/migrations/0026_serialize_orchestration_lock_mutations.sql index b76f002..9c7b7ff 100644 --- a/migrations/0026_serialize_orchestration_lock_mutations.sql +++ b/migrations/0026_serialize_orchestration_lock_mutations.sql @@ -1,18 +1,31 @@ -- Copyright (c) Microsoft Corporation. -- Licensed under the MIT License. --- Migration 0026: serialize renewal with orchestration fetches +-- Migration 0026: serialize orchestration lock renewal with fetch -- -- fetch_orchestration_item takes pg_advisory_xact_lock(hashtext(instance_id)) --- before it locks the queue row and the instance_locks row. Renewal previously --- updated instance_locks first and then orchestrator_queue without that --- advisory lock. The opposing row-lock order permits a fetch/renew deadlock. +-- before it locks orchestrator_queue rows and the instance_locks row. Renewal +-- updated instance_locks and then orchestrator_queue without that lock, so a +-- fetch and a renewal could each hold one row and wait for the other +-- (SQLSTATE 40P01). -- --- Resolve the live token to its instance without taking a row lock, acquire --- the same advisory lock as fetch, then update the lease rows. A concurrent --- fetch or renewal for the instance now waits before either transaction takes --- its first conflicting row lock. The second UPDATE repeats the token and --- expiry predicates because the advisory-lock wait can make a token stale. +-- Renewal now: +-- 1. Resolves the token to its instance without taking a row lock. +-- 2. Takes the same advisory lock as fetch. Neither function then holds a +-- row lock while it waits for the other. +-- 3. Reads the time after that wait. p_now_ms was read in Rust before the +-- connection was acquired and before the wait. Checking expiry or +-- computing the deadline from it can renew a lease that expired during +-- the wait, or write a deadline that is already in the past. The clock +-- rule is the one fetch uses since migration 0025. +-- 4. Revalidates the token and expiry at that time, and never moves the +-- deadline earlier. +-- 5. Updates orchestrator_queue before instance_locks. This is the order of +-- ack_orchestration_item and abandon_orchestration_item, which do not +-- take the advisory lock; the opposite order lets renewal deadlock with +-- them. The advisory lock keeps fetch out whatever the row order. +-- If acknowledge or abandon releases the lock first, the final update matches +-- no row and the function raises, which rolls back the queue update. DO $$ DECLARE @@ -27,6 +40,7 @@ BEGIN RETURNS VOID AS $renew_orch_lock$ DECLARE v_instance_id TEXT; + v_now_ms BIGINT; v_locked_until BIGINT; v_rows_affected INTEGER; BEGIN @@ -41,23 +55,36 @@ BEGIN PERFORM pg_advisory_xact_lock(hashtext(v_instance_id)); - v_locked_until := p_now_ms + (p_extend_secs * 1000); + v_now_ms := GREATEST( + p_now_ms + (EXTRACT(EPOCH FROM (clock_timestamp() - statement_timestamp())) * 1000)::BIGINT, + (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT + ); + + SELECT GREATEST(il.locked_until, v_now_ms + (p_extend_secs * 1000)) + INTO v_locked_until + FROM %1$I.instance_locks il + WHERE il.instance_id = v_instance_id + AND il.lock_token = p_lock_token + AND il.locked_until > v_now_ms; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Lock token invalid, expired, or already released'; + END IF; + + UPDATE %1$I.orchestrator_queue + SET locked_until = v_locked_until + WHERE lock_token = p_lock_token; UPDATE %1$I.instance_locks SET locked_until = v_locked_until WHERE instance_id = v_instance_id - AND lock_token = p_lock_token - AND locked_until > p_now_ms; + AND lock_token = p_lock_token; GET DIAGNOSTICS v_rows_affected = ROW_COUNT; IF v_rows_affected = 0 THEN RAISE EXCEPTION 'Lock token invalid, expired, or already released'; END IF; - - UPDATE %1$I.orchestrator_queue - SET locked_until = v_locked_until - WHERE lock_token = p_lock_token; END; $renew_orch_lock$ LANGUAGE plpgsql; $fmt$, v_schema_name); From 86cba9827042d94976e639ef4f9abd01bb99c769 Mon Sep 17 00:00:00 2001 From: Waldemort Agent Date: Fri, 23 Oct 2026 01:33:57 +0000 Subject: [PATCH 07/15] test: cover renewal across the advisory-lock wait 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> --- tests/fetch_renew_lock_order_repro_tests.rs | 832 +++++++++++++++++--- 1 file changed, 702 insertions(+), 130 deletions(-) diff --git a/tests/fetch_renew_lock_order_repro_tests.rs b/tests/fetch_renew_lock_order_repro_tests.rs index 01f00d5..3c76a36 100644 --- a/tests/fetch_renew_lock_order_repro_tests.rs +++ b/tests/fetch_renew_lock_order_repro_tests.rs @@ -1,23 +1,35 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -//! Regression test for the orchestration fetch/renew lock-order deadlock. +//! Regression tests for orchestration lock renewal (migration 0026). //! -//! Before migration 0026, fetch locked a queue row then waited for -//! `instance_locks`, while renewal held `instance_locks` then waited for the -//! queue row. This test pauses renewal after its first row update and waits -//! until fetch is blocked. Releasing renewal must let both operations finish: -//! migration 0026 makes renewal acquire fetch's per-instance advisory lock -//! before either procedure takes a conflicting row lock. - -use duroxide::providers::{Provider, WorkItem}; +//! Before migration 0026, fetch locked a queue row and then waited for +//! `instance_locks`, while renewal held `instance_locks` and waited for the +//! queue row, so the two could deadlock (SQLSTATE 40P01). Renewal now takes +//! fetch's per-instance advisory lock before any row lock. +//! +//! Renewal looks its token up (the check) before that wait and changes the +//! lease (the use) after it. The `toctou_*` tests hold the advisory lock, +//! let renewal pass its check and block, change the lease in that window in +//! one way each, and then check what renewal does. The last test checks that +//! renewal and acknowledge lock rows in the same order. + +use duroxide::providers::{ExecutionMetadata, Provider, ProviderError, WorkItem}; use duroxide_pg::PostgresProvider; use sqlx::postgres::{PgConnection, PgPoolOptions}; use sqlx::{Connection, PgPool}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::future::Future; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use tokio::sync::oneshot; +use tokio::task::JoinHandle; const ORCHESTRATION: &str = "FetchRenewLockOrder"; +/// Upper bound for any single step, so a regression fails instead of hanging. +const STEP_TIMEOUT: Duration = Duration::from_secs(30); +/// Upper bound for a backend to reach an expected lock wait. +const WAIT_BUDGET: Duration = Duration::from_secs(10); +const POLL_INTERVAL: Duration = Duration::from_millis(10); fn database_url() -> String { dotenvy::dotenv().ok(); @@ -50,64 +62,54 @@ async fn raw_pool(database_url: &str) -> PgPool { .expect("failed to create raw PostgreSQL pool") } -async fn drop_schema(pool: &PgPool, schema: &str) { - sqlx::query(&format!("DROP SCHEMA IF EXISTS {schema} CASCADE")) - .execute(pool) +async fn timed(what: &str, future: impl Future) -> T { + tokio::time::timeout(STEP_TIMEOUT, future) .await - .expect("failed to drop test schema"); + .unwrap_or_else(|_| panic!("timed out waiting for {what}")) } -async fn wait_for_advisory_holder(pool: &PgPool, key: i64) { - for _ in 0..100 { - let held: bool = sqlx::query_scalar("SELECT NOT pg_try_advisory_xact_lock($1)") - .bind(key) - .fetch_one(pool) - .await - .expect("failed to probe renewal readiness lock"); - if held { - return; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } +/// Runs `body` with a fresh schema name and drops the schema afterwards, +/// also when `body` panics. +async fn with_schema(body: F) +where + F: FnOnce(String) -> Fut, + Fut: Future + Send + 'static, +{ + let schema = unique_schema_name(); + let outcome = tokio::spawn(body(schema.clone())).await; - panic!("renewal never reached the lock-order gate"); -} + let pool = raw_pool(&database_url()).await; + let drop_sql = format!("DROP SCHEMA IF EXISTS {schema} CASCADE"); + let drop = sqlx::query(&drop_sql).execute(&pool); + match tokio::time::timeout(STEP_TIMEOUT, drop).await { + Ok(Ok(_)) => {} + Ok(Err(error)) => eprintln!("failed to drop test schema {schema}: {error}"), + Err(_) => eprintln!("timed out dropping test schema {schema}"), + } -async fn wait_for_lock_waiter(pool: &PgPool, pid: i32) { - for _ in 0..100 { - let waiting: bool = sqlx::query_scalar( - "SELECT COALESCE(wait_event_type = 'Lock', false) - FROM pg_stat_activity - WHERE pid = $1", - ) - .bind(pid) - .fetch_optional(pool) - .await - .expect("failed to inspect fetch backend state") - .unwrap_or(false); - if waiting { - return; + if let Err(error) = outcome { + if error.is_panic() { + std::panic::resume_unwind(error.into_panic()); } - tokio::time::sleep(Duration::from_millis(10)).await; + panic!("test body did not finish: {error}"); } - - panic!("fetch did not wait for renewal's transaction"); } -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn fetch_and_renew_serialize_before_taking_conflicting_row_locks() { - let schema = unique_schema_name(); - let database_url = database_url(); - let provider = PostgresProvider::new_with_schema(&database_url, Some(&schema)) +/// Creates a provider in `schema`, starts one orchestration instance and +/// fetches it. Returns the provider, the instance id and the lock token. +async fn fetch_new_instance( + schema: &str, + lock_timeout: Duration, +) -> (Arc, String, String) { + let provider = PostgresProvider::new_with_schema(&database_url(), Some(schema)) .await .expect("failed to create provider"); - let pool = raw_pool(&database_url).await; let instance = format!("instance-{}", uuid::Uuid::new_v4()); provider .enqueue_for_orchestrator( WorkItem::StartOrchestration { - instance, + instance: instance.clone(), orchestration: ORCHESTRATION.to_string(), input: "{}".to_string(), version: Some("1.0.0".to_string()), @@ -122,107 +124,677 @@ async fn fetch_and_renew_serialize_before_taking_conflicting_row_locks() { .expect("failed to enqueue orchestration work"); let (_item, token, _attempt_count) = provider - .fetch_orchestration_item(Duration::from_secs(30), Duration::ZERO, None) + .fetch_orchestration_item(lock_timeout, Duration::ZERO, None) .await .expect("initial fetch failed") .expect("initial fetch did not return work"); - let ready_key = advisory_key(); - let gate_key = advisory_key(); - let mut gate_connection = PgConnection::connect(&database_url) + (Arc::new(provider), instance, token) +} + +fn spawn_renewal( + provider: Arc, + token: String, + extend_for: Duration, +) -> JoinHandle> { + tokio::spawn(async move { + provider + .renew_orchestration_item_lock(&token, extend_for) + .await + }) +} + +/// The instance lease and the lease on each of the instance's queue rows. +#[derive(Debug)] +struct Lease { + token: String, + locked_until: i64, + queue: Vec<(Option, Option)>, +} + +impl Lease { + fn assert_queue_matches(&self) { + assert!(!self.queue.is_empty(), "the instance has no queue rows"); + for row in &self.queue { + assert_eq!( + row, + &(Some(self.token.clone()), Some(self.locked_until)), + "a queue row's lease differs from the instance lease: {self:?}" + ); + } + } +} + +async fn read_lease(pool: &PgPool, schema: &str, instance: &str) -> Option { + let row: Option<(String, i64)> = sqlx::query_as(&format!( + "SELECT lock_token, locked_until FROM {schema}.instance_locks WHERE instance_id = $1" + )) + .bind(instance) + .fetch_optional(pool) + .await + .expect("failed to read instance lease"); + let queue = read_queue(pool, schema, instance).await; + + row.map(|(token, locked_until)| Lease { + token, + locked_until, + queue, + }) +} + +/// The lease on each of the instance's queue rows. +async fn read_queue( + pool: &PgPool, + schema: &str, + instance: &str, +) -> Vec<(Option, Option)> { + sqlx::query_as(&format!( + "SELECT lock_token, locked_until FROM {schema}.orchestrator_queue + WHERE instance_id = $1 ORDER BY id" + )) + .bind(instance) + .fetch_all(pool) + .await + .expect("failed to read queue leases") +} + +/// The instance lease deadline as seen by `connection`, including changes it +/// has not committed. +async fn deadline_in(connection: &mut PgConnection, schema: &str, instance: &str) -> i64 { + sqlx::query_scalar(&format!( + "SELECT locked_until FROM {schema}.instance_locks WHERE instance_id = $1" + )) + .bind(instance) + .fetch_one(connection) + .await + .expect("failed to read the instance lease") +} + +async fn database_now_ms(pool: &PgPool) -> i64 { + sqlx::query_scalar("SELECT (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT") + .fetch_one(pool) + .await + .expect("failed to read database time") +} + +async fn sleep_until_database_time(pool: &PgPool, target_ms: i64) { + loop { + let remaining = target_ms - database_now_ms(pool).await; + if remaining < 0 { + return; + } + tokio::time::sleep(Duration::from_millis(remaining.min(200) as u64 + 1)).await; + } +} + +async fn backend_pid(connection: &mut PgConnection) -> i32 { + sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(connection) .await - .expect("failed to connect gate session"); - let mut gate = gate_connection - .begin() + .expect("failed to read backend PID") +} + +/// Waits until a call to `schema.function` waits for a lock: an advisory +/// lock when `advisory` is true, a row lock otherwise. +async fn wait_for_call_to_wait(pool: &PgPool, schema: &str, function: &str, advisory: bool) { + let pattern = format!("%{schema}.{function}(%"); + let deadline = Instant::now() + WAIT_BUDGET; + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS ( + SELECT 1 FROM pg_stat_activity + WHERE wait_event_type = 'Lock' + AND (wait_event = 'advisory') = $2 + AND query LIKE $1)", + ) + .bind(&pattern) + .bind(advisory) + .fetch_one(pool) .await - .expect("failed to begin gate transaction"); - sqlx::query("SELECT pg_advisory_xact_lock($1)") - .bind(gate_key) - .execute(&mut *gate) + .expect("failed to inspect lock waits"); + if waiting { + return; + } + assert!( + Instant::now() < deadline, + "{function} never waited for a lock (advisory: {advisory})" + ); + tokio::time::sleep(POLL_INTERVAL).await; + } +} + +/// Waits until another session holds the transaction advisory lock `key`. +async fn wait_for_advisory_holder(pool: &PgPool, key: i64) { + let deadline = Instant::now() + WAIT_BUDGET; + loop { + let held: bool = sqlx::query_scalar("SELECT NOT pg_try_advisory_xact_lock($1)") + .bind(key) + .fetch_one(pool) + .await + .expect("failed to probe advisory lock"); + if held { + return; + } + assert!( + Instant::now() < deadline, + "no session took advisory lock {key}" + ); + tokio::time::sleep(POLL_INTERVAL).await; + } +} + +/// Waits until backend `pid` waits for any lock. +async fn wait_for_lock_waiter(pool: &PgPool, pid: i32) { + let deadline = Instant::now() + WAIT_BUDGET; + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT COALESCE(wait_event_type = 'Lock', false) + FROM pg_stat_activity + WHERE pid = $1", + ) + .bind(pid) + .fetch_optional(pool) .await - .expect("failed to take gate advisory lock"); + .expect("failed to inspect backend state") + .unwrap_or(false); + if waiting { + return; + } + assert!( + Instant::now() < deadline, + "backend {pid} never waited for a lock" + ); + tokio::time::sleep(POLL_INTERVAL).await; + } +} - // The token is generated by the provider as `lock_`, so it cannot +/// Installs a trigger that, for rows carrying `token`, takes `ready_key` and +/// then waits for `gate_key`. The test holds `gate_key` to pause the session +/// that fires the trigger, and detects the pause through `ready_key`. +async fn install_pause_trigger( + pool: &PgPool, + schema: &str, + table: &str, + event: &str, + token: &str, + ready_key: i64, + gate_key: i64, +) { + let row = if event == "DELETE" { "OLD" } else { "NEW" }; + // The provider generates tokens as `lock_`, so a token cannot // contain this dollar-quote delimiter. - let pause_function = format!( - "CREATE FUNCTION {schema}.pause_renewal_after_instance_lock() + sqlx::query(&format!( + "CREATE FUNCTION {schema}.pause_for_test() RETURNS trigger LANGUAGE plpgsql AS $function$ BEGIN - IF NEW.lock_token = $token${token}$token$ THEN + IF {row}.lock_token = $token${token}$token$ THEN PERFORM pg_advisory_xact_lock({ready_key}); PERFORM pg_advisory_xact_lock({gate_key}); END IF; - RETURN NEW; + RETURN {row}; END; $function$" - ); - sqlx::query(&pause_function) - .execute(&pool) - .await - .expect("failed to create renewal pause function"); + )) + .execute(pool) + .await + .expect("failed to create pause function"); sqlx::query(&format!( - "CREATE TRIGGER pause_renewal_after_instance_lock - AFTER UPDATE OF locked_until ON {schema}.instance_locks - FOR EACH ROW EXECUTE FUNCTION {schema}.pause_renewal_after_instance_lock()" + "CREATE TRIGGER pause_for_test + AFTER {event} ON {schema}.{table} + FOR EACH ROW EXECUTE FUNCTION {schema}.pause_for_test()" )) - .execute(&pool) + .execute(pool) .await - .expect("failed to create renewal pause trigger"); - - let renew_now_ms = now_ms(); - let renewal_schema = schema.clone(); - let renewal_token = token.clone(); - let renewal_database_url = database_url.clone(); - let renewal = tokio::spawn(async move { - let mut connection = PgConnection::connect(&renewal_database_url) - .await - .expect("failed to connect renewal session"); - sqlx::query(&format!( - "SELECT {renewal_schema}.renew_orchestration_item_lock($1, $2, $3)" - )) - .bind(renewal_token) - .bind(renew_now_ms) - .bind(60_i64) - .execute(&mut connection) - .await - }); - - wait_for_advisory_holder(&pool, ready_key).await; - - let fetch_schema = schema.clone(); - let fetch_database_url = database_url.clone(); - let (fetch_pid_tx, fetch_pid_rx) = oneshot::channel(); - let fetch = tokio::spawn(async move { - let mut connection = PgConnection::connect(&fetch_database_url) - .await - .expect("failed to connect fetch session"); - let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") - .fetch_one(&mut connection) - .await - .expect("failed to read fetch backend PID"); - let _ = fetch_pid_tx.send(pid); - sqlx::query(&format!( - "SELECT * FROM {fetch_schema}.fetch_orchestration_item($1, $2, NULL, NULL)" - )) - .bind(renew_now_ms + 120_000) - .bind(30_000_i64) - .fetch_optional(&mut connection) - .await - }); + .expect("failed to create pause trigger"); +} - let fetch_pid = fetch_pid_rx - .await - .expect("fetch task did not report its backend PID"); - wait_for_lock_waiter(&pool, fetch_pid).await; +/// Renewal pauses inside its `instance_locks` update while a fetch for the +/// same instance starts. The fetch must wait, and both must then finish. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn fetch_and_renew_serialize_before_taking_conflicting_row_locks() { + with_schema(|schema| async move { + let database_url = database_url(); + let (_provider, instance, token) = + fetch_new_instance(&schema, Duration::from_secs(30)).await; + let pool = raw_pool(&database_url).await; + + let ready_key = advisory_key(); + let gate_key = advisory_key(); + let mut gate_connection = PgConnection::connect(&database_url) + .await + .expect("failed to connect gate session"); + let mut gate = gate_connection + .begin() + .await + .expect("failed to begin gate transaction"); + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(gate_key) + .execute(&mut *gate) + .await + .expect("failed to take gate advisory lock"); + install_pause_trigger( + &pool, + &schema, + "instance_locks", + "UPDATE OF locked_until", + &token, + ready_key, + gate_key, + ) + .await; + + let renew_now_ms = now_ms(); + let renewal_schema = schema.clone(); + let renewal_token = token.clone(); + let renewal_database_url = database_url.clone(); + let renewal = tokio::spawn(async move { + let mut connection = PgConnection::connect(&renewal_database_url) + .await + .expect("failed to connect renewal session"); + sqlx::query(&format!( + "SELECT {renewal_schema}.renew_orchestration_item_lock($1, $2, $3)" + )) + .bind(renewal_token) + .bind(renew_now_ms) + .bind(60_i64) + .execute(&mut connection) + .await + }); + + wait_for_advisory_holder(&pool, ready_key).await; + + // Fetch as if the renewed lease had expired, so it takes the instance. + let fetch_schema = schema.clone(); + let fetch_database_url = database_url.clone(); + let (fetch_pid_tx, fetch_pid_rx) = oneshot::channel(); + let fetch = tokio::spawn(async move { + let mut connection = PgConnection::connect(&fetch_database_url) + .await + .expect("failed to connect fetch session"); + let _ = fetch_pid_tx.send(backend_pid(&mut connection).await); + sqlx::query_as::<_, (String, String)>(&format!( + "SELECT out_instance_id, out_lock_token + FROM {fetch_schema}.fetch_orchestration_item($1, $2, NULL, NULL)" + )) + .bind(renew_now_ms + 120_000) + .bind(30_000_i64) + .fetch_optional(&mut connection) + .await + }); + + let fetch_pid = timed("fetch backend PID", fetch_pid_rx) + .await + .expect("fetch task did not report its backend PID"); + wait_for_lock_waiter(&pool, fetch_pid).await; + + timed("gate release", gate.commit()) + .await + .expect("failed to release renewal gate"); + let renewal_result = timed("renewal", renewal) + .await + .expect("renewal task panicked"); + let fetch_result = timed("fetch", fetch).await.expect("fetch task panicked"); + + renewal_result.expect("renewal must complete without a deadlock"); + let (fetched, new_token) = fetch_result + .expect("fetch must complete without a deadlock") + .expect("fetch must take the instance after renewal commits"); + assert_eq!(fetched, instance); + assert_ne!(new_token, token); + + let lease = read_lease(&pool, &schema, &instance) + .await + .expect("the instance must stay locked by the fetch"); + assert_eq!(lease.token, new_token); + lease.assert_queue_matches(); + }) + .await; +} - gate.commit().await.expect("failed to release renewal gate"); - let renewal_result = renewal.await.expect("renewal task panicked"); - let fetch_result = fetch.await.expect("fetch task panicked"); +/// What changes between renewal's token lookup (the check) and its update +/// after the advisory-lock wait (the use). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Interleaving { + /// Only time passes, more than the requested extension. The lease stays + /// live. + LeaseStaysLive, + /// Time passes until the lease expires. + LeaseExpires, + /// A fetch takes the instance over with a new token. + FetchTakesOver, + /// The owner acknowledges the turn, which releases the lock. + Acknowledged, + /// The owner abandons the turn, which releases the lock. + Abandoned, + /// Another renewal with the same token moves the deadline later. + OtherRenewalExtends, +} + +/// What renewal must do once it gets the advisory lock. +enum Expected { + /// Succeed and leave this owner and deadline in both tables. + Renewed { token: String, locked_until: i64 }, + /// Fail and leave this lease unchanged in both tables. + RejectedLeaseUnchanged { token: String, locked_until: i64 }, + /// Fail and leave no lock row. Queue rows stay deleted (acknowledge) or + /// unlocked (abandon). + RejectedReleased { queue_deleted: bool }, +} + +/// Opens the window between renewal's check and its use, applies one +/// interleaving inside it, and checks the result. +/// +/// The test holds the advisory lock that fetch and renewal take for the +/// instance. Renewal takes that lock only after its token lookup passed, so a +/// renewal seen waiting on it is between its check and its use. The +/// interleaving runs while renewal waits: fetch and renewal inside the +/// transaction that holds the lock (PostgreSQL grants it again to the same +/// session), acknowledge and abandon on their own connections (they do not +/// take the advisory lock). Committing that transaction lets renewal continue. +async fn renew_across(interleaving: Interleaving) { + with_schema(move |schema| async move { + let database_url = database_url(); + let lease_timeout = if interleaving == Interleaving::LeaseExpires { + Duration::from_secs(4) + } else { + Duration::from_secs(60) + }; + // Shorter than the lease left after the wait, so a renewal that used + // its pre-wait time would move the deadline earlier. + let extend_for = Duration::from_secs(1); + let (provider, instance, token) = fetch_new_instance(&schema, lease_timeout).await; + let pool = raw_pool(&database_url).await; + let before = read_lease(&pool, &schema, &instance) + .await + .expect("the instance must be locked"); - drop_schema(&pool, &schema).await; + let mut gate_connection = PgConnection::connect(&database_url) + .await + .expect("failed to connect gate session"); + let mut gate = gate_connection + .begin() + .await + .expect("failed to begin gate transaction"); + sqlx::query("SELECT pg_advisory_xact_lock(hashtext($1))") + .bind(&instance) + .execute(&mut *gate) + .await + .expect("failed to take the instance advisory lock"); + + let renewal = spawn_renewal(provider.clone(), token.clone(), extend_for); + wait_for_call_to_wait(&pool, &schema, "renew_orchestration_item_lock", true).await; + let during = read_lease(&pool, &schema, &instance) + .await + .expect("the instance must still be locked"); + assert_eq!( + (during.token.as_str(), during.locked_until), + (token.as_str(), before.locked_until), + "renewal changed the lease before it got the advisory lock" + ); + + let expected = match interleaving { + Interleaving::LeaseStaysLive => { + let waited_from = database_now_ms(&pool).await; + sleep_until_database_time(&pool, waited_from + 2_000).await; + Expected::Renewed { + token: token.clone(), + locked_until: before.locked_until, + } + } + Interleaving::LeaseExpires => { + sleep_until_database_time(&pool, before.locked_until + 250).await; + Expected::RejectedLeaseUnchanged { + token: token.clone(), + locked_until: before.locked_until, + } + } + Interleaving::FetchTakesOver => { + // Fetch as if the lease had expired. + let (fetched, new_token): (String, String) = sqlx::query_as(&format!( + "SELECT out_instance_id, out_lock_token + FROM {schema}.fetch_orchestration_item($1, $2, NULL, NULL)" + )) + .bind(now_ms() + 120_000) + .bind(30_000_i64) + .fetch_one(&mut *gate) + .await + .expect("takeover fetch failed"); + assert_eq!(fetched, instance); + assert_ne!(new_token, token); + let locked_until = deadline_in(&mut gate, &schema, &instance).await; + Expected::RejectedLeaseUnchanged { + token: new_token, + locked_until, + } + } + Interleaving::Acknowledged => { + timed( + "acknowledge", + provider.ack_orchestration_item( + &token, + 1, + vec![], + vec![], + vec![], + ExecutionMetadata::default(), + vec![], + ), + ) + .await + .expect("acknowledge must succeed while renewal waits"); + Expected::RejectedReleased { + queue_deleted: true, + } + } + Interleaving::Abandoned => { + timed( + "abandon", + provider.abandon_orchestration_item(&token, None, false), + ) + .await + .expect("abandon must succeed while renewal waits"); + Expected::RejectedReleased { + queue_deleted: false, + } + } + Interleaving::OtherRenewalExtends => { + sqlx::query(&format!( + "SELECT {schema}.renew_orchestration_item_lock($1, $2, $3)" + )) + .bind(&token) + .bind(now_ms()) + .bind(120_i64) + .execute(&mut *gate) + .await + .expect("the other renewal failed"); + let locked_until = deadline_in(&mut gate, &schema, &instance).await; + assert!(locked_until > before.locked_until); + Expected::Renewed { + token: token.clone(), + locked_until, + } + } + }; + + timed("gate release", gate.commit()) + .await + .expect("failed to release the instance advisory lock"); + let result = timed("renewal", renewal) + .await + .expect("renewal task panicked"); + let after = read_lease(&pool, &schema, &instance).await; + + match expected { + Expected::Renewed { + token, + locked_until, + } => { + result.expect("renewal of a live lease must succeed"); + let after = after.expect("the instance must stay locked"); + assert_eq!(after.token, token); + assert_eq!( + after.locked_until, locked_until, + "renewal must not move the deadline earlier" + ); + assert!( + after.locked_until > database_now_ms(&pool).await, + "the deadline must be in the future" + ); + after.assert_queue_matches(); + } + Expected::RejectedLeaseUnchanged { + token, + locked_until, + } => { + let error = + result.expect_err("renewal must fail when its lease changed while it waited"); + assert!(!error.is_retryable(), "unexpected renewal error: {error:?}"); + let after = after.expect("the lease row must remain"); + assert_eq!(after.token, token); + assert_eq!( + after.locked_until, locked_until, + "renewal must not change a lease it no longer holds" + ); + after.assert_queue_matches(); + } + Expected::RejectedReleased { queue_deleted } => { + let error = result.expect_err("renewal must fail after the lock was released"); + assert!(!error.is_retryable(), "unexpected renewal error: {error:?}"); + assert!(after.is_none(), "renewal must not recreate a released lock"); + let queue = read_queue(&pool, &schema, &instance).await; + if queue_deleted { + assert!( + queue.is_empty(), + "acknowledged messages must stay deleted: {queue:?}" + ); + } else { + assert!(!queue.is_empty(), "abandoned messages must stay queued"); + assert!( + queue.iter().all(|row| *row == (None, None)), + "renewal must not lock abandoned messages again: {queue:?}" + ); + } + } + } + }) + .await; +} + +/// More time than the extension passes, but the lease stays live. Renewal must +/// succeed without moving the deadline earlier. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_lease_stays_live_while_renewal_waits() { + renew_across(Interleaving::LeaseStaysLive).await; +} + +/// The lease expires. Renewal must fail rather than revive it. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_lease_expires_while_renewal_waits() { + renew_across(Interleaving::LeaseExpires).await; +} + +/// A fetch takes the instance over. Renewal must fail and leave the new +/// owner's lease unchanged. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_fetch_takes_over_while_renewal_waits() { + renew_across(Interleaving::FetchTakesOver).await; +} + +/// The owner acknowledges. Renewal must fail and must not recreate the lock. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_acknowledge_releases_while_renewal_waits() { + renew_across(Interleaving::Acknowledged).await; +} + +/// The owner abandons. Renewal must fail and leave the messages unlocked. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_abandon_releases_while_renewal_waits() { + renew_across(Interleaving::Abandoned).await; +} + +/// Another renewal moves the deadline later. This renewal must succeed and +/// keep the later deadline. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_other_renewal_extends_while_renewal_waits() { + renew_across(Interleaving::OtherRenewalExtends).await; +} + +/// Acknowledge pauses after it deletes the instance's queue rows and before it +/// deletes the instance lock. Renewal must wait for the queue rows without +/// holding the instance lock; once acknowledge commits, renewal must fail +/// because the lock was released. Opposite row orders deadlock here. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn renewal_and_acknowledge_lock_rows_in_the_same_order() { + with_schema(|schema| async move { + let database_url = database_url(); + let (provider, instance, token) = + fetch_new_instance(&schema, Duration::from_secs(60)).await; + let pool = raw_pool(&database_url).await; + + let ready_key = advisory_key(); + let gate_key = advisory_key(); + let mut gate_connection = PgConnection::connect(&database_url) + .await + .expect("failed to connect gate session"); + let mut gate = gate_connection + .begin() + .await + .expect("failed to begin gate transaction"); + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(gate_key) + .execute(&mut *gate) + .await + .expect("failed to take gate advisory lock"); + install_pause_trigger( + &pool, + &schema, + "orchestrator_queue", + "DELETE", + &token, + ready_key, + gate_key, + ) + .await; + + let ack_provider = provider.clone(); + let ack_token = token.clone(); + let acknowledge = tokio::spawn(async move { + ack_provider + .ack_orchestration_item( + &ack_token, + 1, + vec![], + vec![], + vec![], + ExecutionMetadata::default(), + vec![], + ) + .await + }); + wait_for_advisory_holder(&pool, ready_key).await; + + let renewal = spawn_renewal(provider.clone(), token.clone(), Duration::from_secs(60)); + wait_for_call_to_wait(&pool, &schema, "renew_orchestration_item_lock", false).await; + + timed("gate release", gate.commit()) + .await + .expect("failed to release acknowledge"); + timed("acknowledge", acknowledge) + .await + .expect("acknowledge task panicked") + .expect("acknowledge must succeed"); + let error = timed("renewal", renewal) + .await + .expect("renewal task panicked") + .expect_err("renewal must fail after acknowledge released the lock"); + assert!( + !error.is_retryable(), + "renewal must fail as released, not as a deadlock victim: {error:?}" + ); - renewal_result.expect("renewal must complete without a deadlock"); - fetch_result.expect("fetch must complete without a deadlock"); + assert!(read_lease(&pool, &schema, &instance).await.is_none()); + }) + .await; } From 2da69e095432742a004607e78b340a0cc083246c Mon Sep 17 00:00:00 2001 From: Waldemort Agent Date: Fri, 23 Oct 2026 01:56:30 +0000 Subject: [PATCH 08/15] docs: regenerate the migration 0026 diff 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> --- migrations/0026_diff.md | 118 +++++++++++++++++++++++++--------------- 1 file changed, 73 insertions(+), 45 deletions(-) diff --git a/migrations/0026_diff.md b/migrations/0026_diff.md index bdbb27b..e4ba2d2 100644 --- a/migrations/0026_diff.md +++ b/migrations/0026_diff.md @@ -2,6 +2,8 @@ **Migration file:** `0026_serialize_orchestration_lock_mutations.sql` +Each changed function is shown **in full** with `+`/`-` markers on changed lines. + ## Table Changes None. @@ -14,56 +16,82 @@ None. ### `renew_orchestration_item_lock` — body modified (baseline: 0004) +Full function with diff: ```diff - CREATE OR REPLACE FUNCTION SCHEMA.renew_orchestration_item_lock( - p_lock_token TEXT, - p_now_ms BIGINT, - p_extend_secs BIGINT - ) - RETURNS VOID AS $renew_orch_lock$ - DECLARE - + v_instance_id TEXT; - v_locked_until BIGINT; - v_rows_affected INTEGER; - BEGIN - + SELECT il.instance_id INTO v_instance_id - + FROM SCHEMA.instance_locks il - + WHERE il.lock_token = p_lock_token - + AND il.locked_until > p_now_ms; + CREATE OR REPLACE FUNCTION SCHEMA.renew_orchestration_item_lock(p_lock_token text, p_now_ms bigint, p_extend_secs bigint) + RETURNS void + LANGUAGE plpgsql + AS $function$ + DECLARE ++ v_instance_id TEXT; ++ v_now_ms BIGINT; + v_locked_until BIGINT; + v_rows_affected INTEGER; + BEGIN +- v_locked_until := p_now_ms + (p_extend_secs * 1000); +- +- UPDATE SCHEMA.instance_locks +- SET locked_until = v_locked_until +- WHERE lock_token = p_lock_token +- AND locked_until > p_now_ms; +- +- GET DIAGNOSTICS v_rows_affected = ROW_COUNT; +- +- IF v_rows_affected = 0 THEN ++ SELECT il.instance_id INTO v_instance_id ++ FROM SCHEMA.instance_locks il ++ WHERE il.lock_token = p_lock_token ++ AND il.locked_until > p_now_ms; ++ ++ IF NOT FOUND THEN ++ RAISE EXCEPTION 'Lock token invalid, expired, or already released'; ++ END IF; ++ ++ PERFORM pg_advisory_xact_lock(hashtext(v_instance_id)); + - + IF NOT FOUND THEN - + RAISE EXCEPTION 'Lock token invalid, expired, or already released'; - + END IF; - + - + PERFORM pg_advisory_xact_lock(hashtext(v_instance_id)); - + - v_locked_until := p_now_ms + (p_extend_secs * 1000); - + - UPDATE SCHEMA.instance_locks - SET locked_until = v_locked_until - - WHERE lock_token = p_lock_token - + WHERE instance_id = v_instance_id - + AND lock_token = p_lock_token - AND locked_until > p_now_ms; ++ v_now_ms := GREATEST( ++ p_now_ms + (EXTRACT(EPOCH FROM (clock_timestamp() - statement_timestamp())) * 1000)::BIGINT, ++ (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT ++ ); + - GET DIAGNOSTICS v_rows_affected = ROW_COUNT; ++ SELECT GREATEST(il.locked_until, v_now_ms + (p_extend_secs * 1000)) ++ INTO v_locked_until ++ FROM SCHEMA.instance_locks il ++ WHERE il.instance_id = v_instance_id ++ AND il.lock_token = p_lock_token ++ AND il.locked_until > v_now_ms; + - IF v_rows_affected = 0 THEN - RAISE EXCEPTION 'Lock token invalid, expired, or already released'; - END IF; ++ IF NOT FOUND THEN + RAISE EXCEPTION 'Lock token invalid, expired, or already released'; + END IF; + + UPDATE SCHEMA.orchestrator_queue + SET locked_until = v_locked_until + WHERE lock_token = p_lock_token; + - UPDATE SCHEMA.orchestrator_queue - SET locked_until = v_locked_until - WHERE lock_token = p_lock_token; - END; - $renew_orch_lock$ LANGUAGE plpgsql; - ``` ++ UPDATE SCHEMA.instance_locks ++ SET locked_until = v_locked_until ++ WHERE instance_id = v_instance_id ++ AND lock_token = p_lock_token; ++ ++ GET DIAGNOSTICS v_rows_affected = ROW_COUNT; ++ ++ IF v_rows_affected = 0 THEN ++ RAISE EXCEPTION 'Lock token invalid, expired, or already released'; ++ END IF; + END; + $function$ + +``` ## Notes -- Renewal now acquires the same transaction-scoped per-instance advisory lock - as `fetch_orchestration_item` before either function takes its conflicting - row locks. -- The post-lock `UPDATE` repeats the token and expiry predicates because a - concurrent fetch can make a token stale while renewal waits for the advisory - lock. +- Generated with `scripts/generate_migration_diff.sh 26` against PostgreSQL 15.19. +- Signature is unchanged, so the migration uses `CREATE OR REPLACE`; the + function keeps its OID and `EXECUTE` grants. +- Renewal takes the per-instance advisory lock that `fetch_orchestration_item` + takes, then reads the time again with the clock rule from migration `0025`. + The expiry check and the new deadline use that time, and the deadline never + moves earlier. +- Queue rows are updated before the instance lock, the order used by + `ack_orchestration_item` and `abandon_orchestration_item`. From e7974656ca8821178a79df6477e0184ac8884ec7 Mon Sep 17 00:00:00 2001 From: Waldemort Agent Date: Fri, 23 Oct 2026 04:17:03 +0000 Subject: [PATCH 09/15] fix: retry orchestration lock renewal on transient errors 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> --- CHANGELOG.md | 6 +- src/provider.rs | 108 +++++++++++++------- tests/fetch_renew_lock_order_repro_tests.rs | 85 ++++++++++++++- 3 files changed, 157 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad5f0e0..58ea5f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,10 +17,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 before the instance lock, the order that acknowledge and abandon use. After the advisory-lock wait, renewal reads the time again: it fails if the lease expired during the wait, and it never moves a lease deadline earlier. + Because renewal can now be aborted as a deadlock victim while it waits for + that lock, the provider retries transient renewal errors up to three times, + as fetch and acknowledge already do. PostgreSQL regression tests cover the fetch deadlock, the acknowledge lock order, and 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. + abandon, and another renewal. Another test checks that a renewal aborted as + a deadlock victim is retried. ## [0.1.37] - 2026-10-21 diff --git a/src/provider.rs b/src/provider.rs index 34b8396..6aa67b6 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -1921,58 +1921,88 @@ impl Provider for PostgresProvider { ) -> Result<(), ProviderError> { let start = std::time::Instant::now(); - // Get current time from application for consistent time reference - let now_ms = Self::now_millis(); + // Renewal waits for the instance's advisory lock (migration 0026). If + // fetches deadlock each other on that lock, PostgreSQL can abort the + // waiting renewal instead (40P01). The runtime stops renewing a turn + // after any renewal error, so retry transient errors here, as fetch and + // acknowledge do. Renewing again is safe: it never shortens a lease. + const MAX_RETRIES: u32 = 3; + const RETRY_DELAY_MS: u64 = 50; // Convert Duration to seconds for the stored procedure let extend_secs = extend_for.as_secs() as i64; - match sqlx::query(&format!( - "SELECT {}.renew_orchestration_item_lock($1, $2, $3)", - self.schema_name - )) - .bind(token) - .bind(now_ms) - .bind(extend_secs) - .execute(&*self.pool) - .await - { - Ok(_) => { - let duration_ms = start.elapsed().as_millis() as u64; - debug!( - target = "duroxide::providers::postgres", - operation = "renew_orchestration_item_lock", - token = %token, - extend_for_secs = extend_secs, - duration_ms = duration_ms, - "Orchestration item lock renewed successfully" - ); - Ok(()) - } - Err(e) => { - if let SqlxError::Database(db_err) = &e { - if db_err.message().contains("Lock token invalid") - || db_err.message().contains("expired") - || db_err.message().contains("already released") + for attempt in 0..=MAX_RETRIES { + // Get current time from application for consistent time reference + let now_ms = Self::now_millis(); + + let result = sqlx::query(&format!( + "SELECT {}.renew_orchestration_item_lock($1, $2, $3)", + self.schema_name + )) + .bind(token) + .bind(now_ms) + .bind(extend_secs) + .execute(&*self.pool) + .await; + + match result { + Ok(_) => { + let duration_ms = start.elapsed().as_millis() as u64; + debug!( + target = "duroxide::providers::postgres", + operation = "renew_orchestration_item_lock", + token = %token, + extend_for_secs = extend_secs, + duration_ms = duration_ms, + attempts = attempt + 1, + "Orchestration item lock renewed successfully" + ); + return Ok(()); + } + Err(e) => { + if let SqlxError::Database(db_err) = &e { + if db_err.message().contains("Lock token invalid") + || db_err.message().contains("expired") + || db_err.message().contains("already released") + { + return Err(ProviderError::permanent( + "renew_orchestration_item_lock", + "Lock token invalid, expired, or already released", + )); + } + } else if e.to_string().contains("Lock token invalid") + || e.to_string().contains("expired") + || e.to_string().contains("already released") { return Err(ProviderError::permanent( "renew_orchestration_item_lock", "Lock token invalid, expired, or already released", )); } - } else if e.to_string().contains("Lock token invalid") - || e.to_string().contains("expired") - || e.to_string().contains("already released") - { - return Err(ProviderError::permanent( - "renew_orchestration_item_lock", - "Lock token invalid, expired, or already released", - )); - } - Err(self.sqlx_to_provider_error("renew_orchestration_item_lock", e)) + let provider_err = + self.sqlx_to_provider_error("renew_orchestration_item_lock", e); + if provider_err.is_retryable() && attempt < MAX_RETRIES { + warn!( + target = "duroxide::providers::postgres", + operation = "renew_orchestration_item_lock", + attempt = attempt + 1, + error = %provider_err, + "Retryable error, will retry" + ); + sleep(std::time::Duration::from_millis( + RETRY_DELAY_MS * (attempt as u64 + 1), + )) + .await; + continue; + } + return Err(provider_err); + } } } + + unreachable!("the last attempt always returns") } #[instrument(skip(self), target = "duroxide::providers::postgres")] diff --git a/tests/fetch_renew_lock_order_repro_tests.rs b/tests/fetch_renew_lock_order_repro_tests.rs index 3c76a36..71131e9 100644 --- a/tests/fetch_renew_lock_order_repro_tests.rs +++ b/tests/fetch_renew_lock_order_repro_tests.rs @@ -11,8 +11,9 @@ //! Renewal looks its token up (the check) before that wait and changes the //! lease (the use) after it. The `toctou_*` tests hold the advisory lock, //! let renewal pass its check and block, change the lease in that window in -//! one way each, and then check what renewal does. The last test checks that -//! renewal and acknowledge lock rows in the same order. +//! one way each, and then check what renewal does. The last two tests check +//! that renewal and acknowledge lock rows in the same order, and that the +//! provider retries a renewal that PostgreSQL aborted as a deadlock victim. use duroxide::providers::{ExecutionMetadata, Provider, ProviderError, WorkItem}; use duroxide_pg::PostgresProvider; @@ -798,3 +799,83 @@ async fn renewal_and_acknowledge_lock_rows_in_the_same_order() { }) .await; } + +/// Renewal waits for the instance's advisory lock. When fetches deadlock each +/// other on that lock, PostgreSQL can abort the waiting renewal instead +/// (SQLSTATE 40P01). The provider must retry it rather than return the error, +/// because the runtime stops renewing a turn after any renewal error. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn renewal_retries_when_aborted_as_deadlock_victim() { + with_schema(|schema| async move { + let database_url = database_url(); + let (provider, instance, token) = + fetch_new_instance(&schema, Duration::from_secs(60)).await; + let pool = raw_pool(&database_url).await; + let before = read_lease(&pool, &schema, &instance) + .await + .expect("the instance must be locked"); + + // Abort the first renewal attempt as a deadlock victim. The sequence + // is not rolled back with the aborted transaction, so the next + // attempt passes. + sqlx::query(&format!("CREATE SEQUENCE {schema}.renewal_attempts")) + .execute(&pool) + .await + .expect("failed to create attempt counter"); + // The provider generates tokens as `lock_`, so a token cannot + // contain this dollar-quote delimiter. + sqlx::query(&format!( + "CREATE FUNCTION {schema}.fail_first_renewal() + RETURNS trigger + LANGUAGE plpgsql + AS $function$ + BEGIN + IF NEW.lock_token = $token${token}$token$ + AND nextval('{schema}.renewal_attempts') = 1 THEN + RAISE EXCEPTION 'injected deadlock' USING ERRCODE = '40P01'; + END IF; + RETURN NEW; + END; + $function$" + )) + .execute(&pool) + .await + .expect("failed to create failure function"); + sqlx::query(&format!( + "CREATE TRIGGER fail_first_renewal + BEFORE UPDATE OF locked_until ON {schema}.orchestrator_queue + FOR EACH ROW EXECUTE FUNCTION {schema}.fail_first_renewal()" + )) + .execute(&pool) + .await + .expect("failed to create failure trigger"); + + timed( + "renewal", + provider.renew_orchestration_item_lock(&token, Duration::from_secs(120)), + ) + .await + .expect("renewal must be retried after it was aborted as a deadlock victim"); + + let attempts: i64 = + sqlx::query_scalar(&format!("SELECT last_value FROM {schema}.renewal_attempts")) + .fetch_one(&pool) + .await + .expect("failed to read attempt counter"); + assert!( + attempts >= 2, + "renewal was not retried: {attempts} attempt(s)" + ); + + let after = read_lease(&pool, &schema, &instance) + .await + .expect("the instance must stay locked"); + assert_eq!(after.token, token); + assert!( + after.locked_until > before.locked_until, + "the retried renewal must extend the lease" + ); + after.assert_queue_matches(); + }) + .await; +} From 3249f6d0df9ba77bacf309b1a889080d298f28d1 Mon Sep 17 00:00:00 2001 From: Waldemort Agent Date: Sat, 24 Oct 2026 00:53:27 +0000 Subject: [PATCH 10/15] test: race renewal against a fetch that sees the lease expired 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> --- CHANGELOG.md | 4 +- tests/fetch_renew_lock_order_repro_tests.rs | 275 +++++++++++++++++++- 2 files changed, 276 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 58ea5f2..33072ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,7 +24,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 order, and 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. Another test checks that a renewal aborted as - a deadlock victim is retried. + a deadlock victim is retried. Two more race renewal against a fetch from a + node that sees the lease as expired (clock ahead, or renewal stalled), with + no instrumentation, and require no deadlock and no revived expired lease. ## [0.1.37] - 2026-10-21 diff --git a/tests/fetch_renew_lock_order_repro_tests.rs b/tests/fetch_renew_lock_order_repro_tests.rs index 71131e9..525974d 100644 --- a/tests/fetch_renew_lock_order_repro_tests.rs +++ b/tests/fetch_renew_lock_order_repro_tests.rs @@ -11,9 +11,16 @@ //! Renewal looks its token up (the check) before that wait and changes the //! lease (the use) after it. The `toctou_*` tests hold the advisory lock, //! let renewal pass its check and block, change the lease in that window in -//! one way each, and then check what renewal does. The last two tests check +//! one way each, and then check what renewal does. The next two tests check //! that renewal and acknowledge lock rows in the same order, and that the //! provider retries a renewal that PostgreSQL aborted as a deadlock victim. +//! +//! The `race_*` tests reproduce how the deadlock happens in production, with +//! no triggers or pauses: another node treats the owner's lease as expired +//! while the owner renews it, because its clock runs ahead or because the +//! renewal stalled on the way to the database. Each round sends the same two +//! statements `PostgresProvider` sends, on two connections, released together +//! with staggered start times. use duroxide::providers::{ExecutionMetadata, Provider, ProviderError, WorkItem}; use duroxide_pg::PostgresProvider; @@ -22,7 +29,7 @@ use sqlx::{Connection, PgPool}; use std::future::Future; use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; -use tokio::sync::oneshot; +use tokio::sync::{oneshot, Barrier}; use tokio::task::JoinHandle; const ORCHESTRATION: &str = "FetchRenewLockOrder"; @@ -879,3 +886,267 @@ async fn renewal_retries_when_aborted_as_deadlock_victim() { }) .await; } + +/// How another node comes to treat the owner's lease as expired while the +/// owner renews it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ExpiredView { + /// The other node's clock runs ahead of the owner's by more than the + /// lease time left. With the runtime defaults (5 s lease, renewal every + /// 3 s) that is a clock 2 s or more ahead. The owner renews on time. + ClockAhead, + /// The owner's renewal read its clock just before the lease expired and + /// reached the database just after, for example behind a stalled + /// connection pool. The other node's clock is correct. + RenewalStalled, +} + +#[derive(Debug, Default)] +struct RaceTally { + rounds: u32, + renew_deadlocks: u32, + fetch_deadlocks: u32, + renewed: u32, + renewal_rejected: u32, + taken_over: u32, + not_taken: u32, + tables_disagree: u32, + other_errors: Vec, +} + +fn sqlstate(error: &sqlx::Error) -> Option { + match error { + sqlx::Error::Database(e) => e.code().map(|c| c.to_string()), + _ => None, + } +} + +fn spin_for(micros: u64) { + let until = Instant::now() + Duration::from_micros(micros); + while Instant::now() < until { + std::hint::spin_loop(); + } +} + +/// Runs `RACE_ROUNDS` rounds (default 200). In each round the owner fetches +/// a new instance, then its renewal and the other node's fetch are released +/// together. Their start times are staggered across rounds, from the fetch +/// 3 ms ahead to the renewal 0.5 ms ahead. Fetch does more work before it +/// takes its first row lock than renewal does, so it needs the longer lead. +async fn race_renewal_against_expired_view(view: ExpiredView) { + let rounds: u32 = std::env::var("RACE_ROUNDS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(200); + with_schema(move |schema| async move { + let database_url = database_url(); + let provider = PostgresProvider::new_with_schema(&database_url, Some(&schema)) + .await + .expect("failed to create provider"); + let pool = raw_pool(&database_url).await; + let mut owner = PgConnection::connect(&database_url) + .await + .expect("failed to connect owner session"); + let mut other = PgConnection::connect(&database_url) + .await + .expect("failed to connect other node's session"); + for connection in [&mut owner, &mut other] { + sqlx::query("SET statement_timeout = '20s'") + .execute(&mut *connection) + .await + .expect("failed to set statement timeout"); + } + let lease = match view { + ExpiredView::ClockAhead => Duration::from_secs(5), + ExpiredView::RenewalStalled => Duration::from_millis(20), + }; + let renew_sql = format!("SELECT {schema}.renew_orchestration_item_lock($1, $2, $3)"); + let fetch_sql = format!( + "SELECT out_instance_id, out_lock_token + FROM {schema}.fetch_orchestration_item($1, $2, NULL, NULL)" + ); + + let mut tally = RaceTally::default(); + for round in 0..rounds { + let instance = format!("race-{}", uuid::Uuid::new_v4()); + provider + .enqueue_for_orchestrator( + WorkItem::StartOrchestration { + instance: instance.clone(), + orchestration: ORCHESTRATION.to_string(), + input: "{}".to_string(), + version: Some("1.0.0".to_string()), + parent_instance: None, + parent_id: None, + parent_execution_id: None, + execution_id: 1, + }, + None, + ) + .await + .expect("failed to enqueue orchestration work"); + let (_item, token, _attempt_count) = provider + .fetch_orchestration_item(lease, Duration::ZERO, None) + .await + .expect("owner fetch failed") + .expect("owner fetch did not return work"); + let locked_until = read_lease(&pool, &schema, &instance) + .await + .expect("the owner must hold the lease") + .locked_until; + + // The clock each node passes to the database. + let (renew_now, other_now) = match view { + ExpiredView::ClockAhead => (now_ms(), locked_until + 2_000), + ExpiredView::RenewalStalled => { + sleep_until_database_time(&pool, locked_until + 2).await; + (locked_until - 1, now_ms().max(locked_until + 2)) + } + }; + + let offset = (i64::from(round) * 97) % 3501 - 3000; + let renew_delay = if offset < 0 { offset.unsigned_abs() } else { 0 }; + let fetch_delay = if offset > 0 { offset.unsigned_abs() } else { 0 }; + let barrier = Arc::new(Barrier::new(2)); + + let renewal = tokio::spawn({ + let barrier = barrier.clone(); + let sql = renew_sql.clone(); + let token = token.clone(); + let mut connection = owner; + async move { + barrier.wait().await; + spin_for(renew_delay); + let result = sqlx::query(&sql) + .bind(&token) + .bind(renew_now) + .bind(5_i64) + .execute(&mut connection) + .await + .map(|_| ()); + (connection, result) + } + }); + let fetch = tokio::spawn({ + let barrier = barrier.clone(); + let sql = fetch_sql.clone(); + let mut connection = other; + async move { + barrier.wait().await; + spin_for(fetch_delay); + let result = sqlx::query_as::<_, (String, String)>(&sql) + .bind(other_now) + .bind(30_000_i64) + .fetch_optional(&mut connection) + .await; + (connection, result) + } + }); + let (connection, renew_result) = timed("renewal", renewal) + .await + .expect("renewal task panicked"); + owner = connection; + let (connection, fetch_result) = + timed("fetch", fetch).await.expect("fetch task panicked"); + other = connection; + + tally.rounds += 1; + match renew_result { + Ok(()) => tally.renewed += 1, + Err(e) if sqlstate(&e).as_deref() == Some("40P01") => tally.renew_deadlocks += 1, + Err(e) + if e.to_string() + .contains("Lock token invalid, expired, or already released") => + { + tally.renewal_rejected += 1 + } + Err(e) => tally.other_errors.push(format!("renewal: {e}")), + } + match fetch_result { + Ok(Some((fetched, new_token))) => { + assert_eq!(fetched, instance); + assert_ne!(new_token, token); + tally.taken_over += 1; + } + Ok(None) => tally.not_taken += 1, + Err(e) if sqlstate(&e).as_deref() == Some("40P01") => tally.fetch_deadlocks += 1, + Err(e) => tally.other_errors.push(format!("fetch: {e}")), + } + + match read_lease(&pool, &schema, &instance).await { + Some(lease) => { + if lease.queue.is_empty() + || lease.queue.iter().any(|row| { + *row != (Some(lease.token.clone()), Some(lease.locked_until)) + }) + { + tally.tables_disagree += 1; + } + } + None => tally.tables_disagree += 1, + } + + for table in ["orchestrator_queue", "instance_locks"] { + sqlx::query(&format!( + "DELETE FROM {schema}.{table} WHERE instance_id = $1" + )) + .bind(&instance) + .execute(&pool) + .await + .expect("failed to clean up the round"); + } + } + + println!( + "RACEJSON {}", + serde_json::json!({ + "view": format!("{view:?}"), + "rounds": tally.rounds, + "renew_deadlocks": tally.renew_deadlocks, + "fetch_deadlocks": tally.fetch_deadlocks, + "renewed": tally.renewed, + "renewal_rejected": tally.renewal_rejected, + "taken_over": tally.taken_over, + "not_taken": tally.not_taken, + "tables_disagree": tally.tables_disagree, + "other_errors": tally.other_errors.len(), + }) + ); + + assert_eq!( + tally.renew_deadlocks + tally.fetch_deadlocks, + 0, + "renewal and fetch deadlocked: {tally:?}" + ); + assert!( + tally.other_errors.is_empty(), + "unexpected errors: {tally:?}" + ); + assert_eq!(tally.tables_disagree, 0, "lease tables disagree: {tally:?}"); + assert_eq!(tally.renewed + tally.renewal_rejected, rounds, "{tally:?}"); + assert_eq!(tally.taken_over + tally.not_taken, rounds, "{tally:?}"); + if view == ExpiredView::RenewalStalled { + assert_eq!( + tally.renewed, 0, + "a renewal that reached the database after the lease expired must fail: {tally:?}" + ); + assert_eq!(tally.taken_over, rounds, "{tally:?}"); + } + }) + .await; +} + +/// Case 1, clock skew: the other node's clock runs ahead, so it fetches the +/// instance while the owner renews it on time. No deadlock is allowed. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn race_renewal_against_fetch_from_node_with_clock_ahead() { + race_renewal_against_expired_view(ExpiredView::ClockAhead).await; +} + +/// Case 1, stalled renewal: the renewal reaches the database just after the +/// lease expired, while another node fetches the instance. No deadlock is +/// allowed, and the renewal must not revive the expired lease. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn race_stalled_renewal_against_fetch_after_expiry() { + race_renewal_against_expired_view(ExpiredView::RenewalStalled).await; +} From 3d874ad7c5a21ec2c2820581e29dfb9248c39769 Mon Sep 17 00:00:00 2001 From: Waldemort Agent Date: Sat, 24 Oct 2026 03:11:38 +0000 Subject: [PATCH 11/15] perf: index instance_locks.lock_token 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> --- CHANGELOG.md | 4 +- migrations/0026_diff.md | 9 ++- ...serialize_orchestration_lock_mutations.sql | 11 +++ tests/fetch_renew_lock_order_repro_tests.rs | 79 +++++++++++++++++++ 4 files changed, 101 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 33072ce..cc28d90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 expired during the wait, and it never moves a lease deadline earlier. Because renewal can now be aborted as a deadlock victim while it waits for that lock, the provider retries transient renewal errors up to three times, - as fetch and acknowledge already do. + as fetch and acknowledge already do. The migration also adds a unique index + on `instance_locks(lock_token)`, so renewal, acknowledge and abandon find an + instance by its lock token without scanning the table. PostgreSQL regression tests cover the fetch deadlock, the acknowledge lock order, and each change that can happen between renewal's token lookup and its update: time passing, lease expiry, a fetch takeover, acknowledge, diff --git a/migrations/0026_diff.md b/migrations/0026_diff.md index e4ba2d2..c54e976 100644 --- a/migrations/0026_diff.md +++ b/migrations/0026_diff.md @@ -10,7 +10,10 @@ None. ## New Indexes -None. +### `idx_instance_locks_lock_token` +```sql +CREATE UNIQUE INDEX idx_instance_locks_lock_token ON SCHEMA.instance_locks USING btree (lock_token) +``` ## Function Changes @@ -95,3 +98,7 @@ Full function with diff: moves earlier. - Queue rows are updated before the instance lock, the order used by `ack_orchestration_item` and `abandon_orchestration_item`. +- `idx_instance_locks_lock_token` serves the token lookups in + `renew_orchestration_item_lock`, `ack_orchestration_item` and + `abandon_orchestration_item`, which scanned `instance_locks` before. It is + unique because a token must name exactly one instance. diff --git a/migrations/0026_serialize_orchestration_lock_mutations.sql b/migrations/0026_serialize_orchestration_lock_mutations.sql index 9c7b7ff..80e6e93 100644 --- a/migrations/0026_serialize_orchestration_lock_mutations.sql +++ b/migrations/0026_serialize_orchestration_lock_mutations.sql @@ -26,6 +26,12 @@ -- them. The advisory lock keeps fetch out whatever the row order. -- If acknowledge or abandon releases the lock first, the final update matches -- no row and the function raises, which rolls back the queue update. +-- +-- The migration also adds a unique index on instance_locks(lock_token). +-- Renewal, acknowledge and abandon find the instance by its lock token, and +-- without an index each lookup scans the table. The index is unique because a +-- token must name exactly one instance, which renewal relies on: only fetch +-- writes lock_token, and it creates each token once from gen_random_uuid(). DO $$ DECLARE @@ -88,4 +94,9 @@ BEGIN END; $renew_orch_lock$ LANGUAGE plpgsql; $fmt$, v_schema_name); + + EXECUTE format( + 'CREATE UNIQUE INDEX IF NOT EXISTS idx_instance_locks_lock_token ON %1$I.instance_locks (lock_token)', + v_schema_name + ); END $$; diff --git a/tests/fetch_renew_lock_order_repro_tests.rs b/tests/fetch_renew_lock_order_repro_tests.rs index 525974d..4ce1713 100644 --- a/tests/fetch_renew_lock_order_repro_tests.rs +++ b/tests/fetch_renew_lock_order_repro_tests.rs @@ -21,6 +21,9 @@ //! renewal stalled on the way to the database. Each round sends the same two //! statements `PostgresProvider` sends, on two connections, released together //! with staggered start times. +//! +//! The last test checks the unique index on `instance_locks(lock_token)` that +//! renewal, acknowledge and abandon use to find an instance by its token. use duroxide::providers::{ExecutionMetadata, Provider, ProviderError, WorkItem}; use duroxide_pg::PostgresProvider; @@ -1150,3 +1153,79 @@ async fn race_renewal_against_fetch_from_node_with_clock_ahead() { async fn race_stalled_renewal_against_fetch_after_expiry() { race_renewal_against_expired_view(ExpiredView::RenewalStalled).await; } + +/// Renewal, acknowledge and abandon find an instance by its lock token. +/// Migration 0026 adds a unique index on `instance_locks(lock_token)` so these +/// lookups do not scan the table, and so a token can name only one instance. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn lock_token_lookups_use_a_unique_index() { + with_schema(|schema| async move { + let database_url = database_url(); + let _provider = PostgresProvider::new_with_schema(&database_url, Some(&schema)) + .await + .expect("failed to create provider"); + let pool = raw_pool(&database_url).await; + + let (unique, column): (bool, String) = sqlx::query_as( + "SELECT ix.indisunique, pg_get_indexdef(ix.indexrelid, 1, true) + FROM pg_index ix + JOIN pg_class i ON i.oid = ix.indexrelid + JOIN pg_namespace n ON n.oid = i.relnamespace + WHERE n.nspname = $1 + AND i.relname = 'idx_instance_locks_lock_token' + AND ix.indnatts = 1", + ) + .bind(&schema) + .fetch_one(&pool) + .await + .expect("idx_instance_locks_lock_token must exist"); + assert!(unique, "the lock_token index must be unique"); + assert_eq!(column, "lock_token"); + + // Enough live leases that the planner prefers an index to a table scan. + sqlx::query(&format!( + "INSERT INTO {schema}.instance_locks (instance_id, lock_token, locked_until, locked_at) + SELECT 'instance-' || g, 'lock_' || gen_random_uuid(), + (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT + 600000, 0 + FROM generate_series(1, 5000) AS g" + )) + .execute(&pool) + .await + .expect("failed to fill instance_locks"); + sqlx::query(&format!("ANALYZE {schema}.instance_locks")) + .execute(&pool) + .await + .expect("failed to analyze instance_locks"); + + // The lookups of abandon, and of renewal and acknowledge. + for predicate in [ + "lock_token = 'lock_unknown'", + "lock_token = 'lock_unknown' + AND locked_until > (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT", + ] { + let plan: Vec = sqlx::query_scalar(&format!( + "EXPLAIN SELECT instance_id FROM {schema}.instance_locks WHERE {predicate}" + )) + .fetch_all(&pool) + .await + .expect("failed to explain the token lookup"); + let plan = plan.join("\n"); + assert!( + plan.contains("idx_instance_locks_lock_token") && !plan.contains("Seq Scan"), + "the token lookup must use the index:\n{plan}" + ); + } + + let duplicate = sqlx::query(&format!( + "INSERT INTO {schema}.instance_locks (instance_id, lock_token, locked_until, locked_at) + SELECT 'instance-duplicate', lock_token, 0, 0 + FROM {schema}.instance_locks + LIMIT 1" + )) + .execute(&pool) + .await + .expect_err("a lock token must not name two instances"); + assert_eq!(sqlstate(&duplicate).as_deref(), Some("23505")); + }) + .await; +} From b2ff29633a5ea437f8f1e737429d7ba9170ba491 Mon Sep 17 00:00:00 2001 From: Waldemort Agent Date: Sat, 24 Oct 2026 17:48:41 +0000 Subject: [PATCH 12/15] test: move the lock-order tests into a deadlock suite 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> --- .github/copilot-instructions.md | 1 + CHANGELOG.md | 17 +- tests/deadlocks/harness.rs | 449 +++++++ tests/deadlocks/main.rs | 75 ++ tests/deadlocks/renew_ack_abandon.rs | 209 ++++ tests/deadlocks/renew_fetch.rs | 380 ++++++ tests/deadlocks/victim_retry.rs | 87 ++ tests/fetch_renew_lock_order_repro_tests.rs | 1231 ------------------- tests/orchestration_lock_renewal_tests.rs | 370 ++++++ 9 files changed, 1581 insertions(+), 1238 deletions(-) create mode 100644 tests/deadlocks/harness.rs create mode 100644 tests/deadlocks/main.rs create mode 100644 tests/deadlocks/renew_ack_abandon.rs create mode 100644 tests/deadlocks/renew_fetch.rs create mode 100644 tests/deadlocks/victim_retry.rs delete mode 100644 tests/fetch_renew_lock_order_repro_tests.rs create mode 100644 tests/orchestration_lock_renewal_tests.rs diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index e00cdd2..8253169 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -177,3 +177,4 @@ Use [.agents/skills/release-preparation/SKILL.md](../.agents/skills/release-prep - Enable tracing: `RUST_LOG=duroxide::providers::postgres=debug cargo test` - Check schema cleanup: Run `scripts/cleanup_test_schemas.sh` after failed tests - Deadlock issues: Review two-phase locking in `fetch_orchestration_item` stored procedure +- Deadlock tests live in `tests/deadlocks` (`cargo test --test deadlocks`). They run in every default `cargo test` and must not be `#[ignore]`d. Every lock-ordering change adds a test there. diff --git a/CHANGELOG.md b/CHANGELOG.md index cc28d90..94cc163 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,13 +22,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 as fetch and acknowledge already do. The migration also adds a unique index on `instance_locks(lock_token)`, so renewal, acknowledge and abandon find an instance by its lock token without scanning the table. - PostgreSQL regression tests cover the fetch deadlock, the acknowledge lock - order, and 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. Another test checks that a renewal aborted as - a deadlock victim is retried. Two more race renewal against a fetch from a - node that sees the lease as expired (clock ahead, or renewal stalled), with - no instrumentation, and require no deadlock and no revived expired lease. + A new deadlock suite, `tests/deadlocks` (`cargo test --test deadlocks`), + covers the fetch deadlock and the acknowledge and abandon lock orders, and + checks that a renewal aborted as a deadlock victim is retried. Two of its + tests race renewal against a fetch from a node that sees the lease as + expired (clock ahead, or renewal stalled), with no instrumentation, and + require no deadlock and no revived expired lease. The suite runs in every + default `cargo test`. `tests/orchestration_lock_renewal_tests.rs` covers + 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, and checks the `lock_token` index. ## [0.1.37] - 2026-10-21 diff --git a/tests/deadlocks/harness.rs b/tests/deadlocks/harness.rs new file mode 100644 index 0000000..2ad10af --- /dev/null +++ b/tests/deadlocks/harness.rs @@ -0,0 +1,449 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Helpers shared by the deadlock suite (`tests/deadlocks`) and the +//! orchestration lock renewal tests (`tests/orchestration_lock_renewal_tests.rs`). +//! +//! Every wait here is bounded by `STEP_TIMEOUT` or `WAIT_BUDGET`, so a +//! regression fails the test instead of hanging it. + +#![allow(dead_code)] + +use duroxide::providers::{Provider, ProviderError, WorkItem}; +use duroxide_pg::PostgresProvider; +use sqlx::postgres::{PgConnection, PgPoolOptions}; +use sqlx::{Connection, PgPool}; +use std::future::Future; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; +use tokio::task::JoinHandle; + +pub const ORCHESTRATION: &str = "FetchRenewLockOrder"; +/// Upper bound for any single step, so a regression fails instead of hanging. +pub const STEP_TIMEOUT: Duration = Duration::from_secs(30); +/// Upper bound for a backend to reach an expected lock wait. +pub const WAIT_BUDGET: Duration = Duration::from_secs(10); +pub const POLL_INTERVAL: Duration = Duration::from_millis(10); +/// SQLSTATE `deadlock_detected`. +pub const DEADLOCK_DETECTED: &str = "40P01"; +/// The error the renewal function raises when its lease is gone. +pub const LEASE_GONE: &str = "Lock token invalid, expired, or already released"; + +pub fn database_url() -> String { + dotenvy::dotenv().ok(); + std::env::var("DATABASE_URL").expect("DATABASE_URL must be set") +} + +fn unique_schema_name() -> String { + let guid = uuid::Uuid::new_v4().to_string(); + let suffix = &guid[guid.len() - 8..]; + format!("fetch_renew_lock_order_{suffix}") +} + +pub fn advisory_key() -> i64 { + let bytes = *uuid::Uuid::new_v4().as_bytes(); + i64::from_be_bytes(bytes[..8].try_into().expect("UUID prefix has eight bytes")) +} + +pub fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock before Unix epoch") + .as_millis() as i64 +} + +pub async fn raw_pool(database_url: &str) -> PgPool { + PgPoolOptions::new() + .max_connections(4) + .connect(database_url) + .await + .expect("failed to create raw PostgreSQL pool") +} + +pub async fn timed(what: &str, future: impl Future) -> T { + tokio::time::timeout(STEP_TIMEOUT, future) + .await + .unwrap_or_else(|_| panic!("timed out waiting for {what}")) +} + +/// Runs `body` with a fresh schema name and drops the schema afterwards, +/// also when `body` panics. +pub async fn with_schema(body: F) +where + F: FnOnce(String) -> Fut, + Fut: Future + Send + 'static, +{ + let schema = unique_schema_name(); + let outcome = tokio::spawn(body(schema.clone())).await; + + let pool = raw_pool(&database_url()).await; + let drop_sql = format!("DROP SCHEMA IF EXISTS {schema} CASCADE"); + let drop = sqlx::query(&drop_sql).execute(&pool); + match tokio::time::timeout(STEP_TIMEOUT, drop).await { + Ok(Ok(_)) => {} + Ok(Err(error)) => eprintln!("failed to drop test schema {schema}: {error}"), + Err(_) => eprintln!("timed out dropping test schema {schema}"), + } + + if let Err(error) = outcome { + if error.is_panic() { + std::panic::resume_unwind(error.into_panic()); + } + panic!("test body did not finish: {error}"); + } +} + +/// Creates a provider in `schema`, starts one orchestration instance and +/// fetches it. Returns the provider, the instance id and the lock token. +pub async fn fetch_new_instance( + schema: &str, + lock_timeout: Duration, +) -> (Arc, String, String) { + let provider = PostgresProvider::new_with_schema(&database_url(), Some(schema)) + .await + .expect("failed to create provider"); + let instance = format!("instance-{}", uuid::Uuid::new_v4()); + + provider + .enqueue_for_orchestrator( + WorkItem::StartOrchestration { + instance: instance.clone(), + orchestration: ORCHESTRATION.to_string(), + input: "{}".to_string(), + version: Some("1.0.0".to_string()), + parent_instance: None, + parent_id: None, + parent_execution_id: None, + execution_id: 1, + }, + None, + ) + .await + .expect("failed to enqueue orchestration work"); + + let (_item, token, _attempt_count) = provider + .fetch_orchestration_item(lock_timeout, Duration::ZERO, None) + .await + .expect("initial fetch failed") + .expect("initial fetch did not return work"); + + (Arc::new(provider), instance, token) +} + +/// Renews through the provider, which retries transient errors. +pub fn spawn_renewal( + provider: Arc, + token: String, + extend_for: Duration, +) -> JoinHandle> { + tokio::spawn(async move { + provider + .renew_orchestration_item_lock(&token, extend_for) + .await + }) +} + +/// Sends the statement the provider sends to renew, once, on its own +/// connection. Unlike `spawn_renewal`, nothing retries a deadlock, so a test +/// sees SQLSTATE 40P01 directly. +pub fn spawn_sql_renewal( + database_url: String, + schema: String, + token: String, + extend_secs: i64, +) -> JoinHandle> { + tokio::spawn(async move { + let mut connection = PgConnection::connect(&database_url).await?; + sqlx::query(&format!( + "SELECT {schema}.renew_orchestration_item_lock($1, $2, $3)" + )) + .bind(token) + .bind(now_ms()) + .bind(extend_secs) + .execute(&mut connection) + .await + .map(|_| ()) + }) +} + +/// The instance lease and the lease on each of the instance's queue rows. +#[derive(Debug)] +pub struct Lease { + pub token: String, + pub locked_until: i64, + pub queue: Vec<(Option, Option)>, +} + +impl Lease { + pub fn assert_queue_matches(&self) { + assert!(!self.queue.is_empty(), "the instance has no queue rows"); + for row in &self.queue { + assert_eq!( + row, + &(Some(self.token.clone()), Some(self.locked_until)), + "a queue row's lease differs from the instance lease: {self:?}" + ); + } + } +} + +pub async fn read_lease(pool: &PgPool, schema: &str, instance: &str) -> Option { + let row: Option<(String, i64)> = sqlx::query_as(&format!( + "SELECT lock_token, locked_until FROM {schema}.instance_locks WHERE instance_id = $1" + )) + .bind(instance) + .fetch_optional(pool) + .await + .expect("failed to read instance lease"); + let queue = read_queue(pool, schema, instance).await; + + row.map(|(token, locked_until)| Lease { + token, + locked_until, + queue, + }) +} + +/// The lease on each of the instance's queue rows. +pub async fn read_queue( + pool: &PgPool, + schema: &str, + instance: &str, +) -> Vec<(Option, Option)> { + sqlx::query_as(&format!( + "SELECT lock_token, locked_until FROM {schema}.orchestrator_queue + WHERE instance_id = $1 ORDER BY id" + )) + .bind(instance) + .fetch_all(pool) + .await + .expect("failed to read queue leases") +} + +/// The instance lease deadline as seen by `connection`, including changes it +/// has not committed. +pub async fn deadline_in(connection: &mut PgConnection, schema: &str, instance: &str) -> i64 { + sqlx::query_scalar(&format!( + "SELECT locked_until FROM {schema}.instance_locks WHERE instance_id = $1" + )) + .bind(instance) + .fetch_one(connection) + .await + .expect("failed to read the instance lease") +} + +/// Whether any transaction holds a row lock on the instance's +/// `instance_locks` row. Takes and releases the lock with NOWAIT, so it never +/// waits. +pub async fn instance_lock_row_is_held(pool: &PgPool, schema: &str, instance: &str) -> bool { + let probe = sqlx::query_scalar::<_, i32>(&format!( + "SELECT 1 FROM {schema}.instance_locks WHERE instance_id = $1 FOR UPDATE NOWAIT" + )) + .bind(instance) + .fetch_optional(pool) + .await; + match probe { + Ok(Some(_)) => false, + Ok(None) => panic!("the instance has no instance_locks row"), + // lock_not_available + Err(error) if sqlstate(&error).as_deref() == Some("55P03") => true, + Err(error) => panic!("failed to probe the instance_locks row: {error}"), + } +} + +pub async fn database_now_ms(pool: &PgPool) -> i64 { + sqlx::query_scalar("SELECT (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT") + .fetch_one(pool) + .await + .expect("failed to read database time") +} + +pub async fn sleep_until_database_time(pool: &PgPool, target_ms: i64) { + loop { + let remaining = target_ms - database_now_ms(pool).await; + if remaining < 0 { + return; + } + tokio::time::sleep(Duration::from_millis(remaining.min(200) as u64 + 1)).await; + } +} + +pub async fn backend_pid(connection: &mut PgConnection) -> i32 { + sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(connection) + .await + .expect("failed to read backend PID") +} + +/// Waits until a call to `schema.function` waits for a lock: an advisory +/// lock when `advisory` is true, a row lock otherwise. +pub async fn wait_for_call_to_wait(pool: &PgPool, schema: &str, function: &str, advisory: bool) { + let pattern = format!("%{schema}.{function}(%"); + let deadline = Instant::now() + WAIT_BUDGET; + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS ( + SELECT 1 FROM pg_stat_activity + WHERE wait_event_type = 'Lock' + AND (wait_event = 'advisory') = $2 + AND query LIKE $1)", + ) + .bind(&pattern) + .bind(advisory) + .fetch_one(pool) + .await + .expect("failed to inspect lock waits"); + if waiting { + return; + } + assert!( + Instant::now() < deadline, + "{function} never waited for a lock (advisory: {advisory})" + ); + tokio::time::sleep(POLL_INTERVAL).await; + } +} + +/// Waits until another session holds the transaction advisory lock `key`. +pub async fn wait_for_advisory_holder(pool: &PgPool, key: i64) { + let deadline = Instant::now() + WAIT_BUDGET; + loop { + let held: bool = sqlx::query_scalar("SELECT NOT pg_try_advisory_xact_lock($1)") + .bind(key) + .fetch_one(pool) + .await + .expect("failed to probe advisory lock"); + if held { + return; + } + assert!( + Instant::now() < deadline, + "no session took advisory lock {key}" + ); + tokio::time::sleep(POLL_INTERVAL).await; + } +} + +/// Waits until backend `pid` waits for any lock. +pub async fn wait_for_lock_waiter(pool: &PgPool, pid: i32) { + let deadline = Instant::now() + WAIT_BUDGET; + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT COALESCE(wait_event_type = 'Lock', false) + FROM pg_stat_activity + WHERE pid = $1", + ) + .bind(pid) + .fetch_optional(pool) + .await + .expect("failed to inspect backend state") + .unwrap_or(false); + if waiting { + return; + } + assert!( + Instant::now() < deadline, + "backend {pid} never waited for a lock" + ); + tokio::time::sleep(POLL_INTERVAL).await; + } +} + +/// `token` as a dollar-quoted SQL literal. The provider generates tokens as +/// `lock_`, so a token cannot contain the delimiter. +pub fn token_literal(token: &str) -> String { + format!("$token${token}$token$") +} + +/// Installs a trigger that, for rows carrying `token`, takes `ready_key` and +/// then waits for `gate_key`. The test holds `gate_key` to pause the session +/// that fires the trigger, and detects the pause through `ready_key`. +pub async fn install_pause_trigger( + pool: &PgPool, + schema: &str, + table: &str, + event: &str, + token: &str, + ready_key: i64, + gate_key: i64, +) { + let row = if event == "DELETE" { "OLD" } else { "NEW" }; + let condition = format!("{row}.lock_token = {}", token_literal(token)); + install_pause_trigger_when(pool, schema, table, event, &condition, ready_key, gate_key).await; +} + +/// Like `install_pause_trigger`, for rows that match the SQL `condition`, +/// which may use `OLD` and `NEW`. +pub async fn install_pause_trigger_when( + pool: &PgPool, + schema: &str, + table: &str, + event: &str, + condition: &str, + ready_key: i64, + gate_key: i64, +) { + let row = if event == "DELETE" { "OLD" } else { "NEW" }; + sqlx::query(&format!( + "CREATE FUNCTION {schema}.pause_for_test() + RETURNS trigger + LANGUAGE plpgsql + AS $function$ + BEGIN + IF {condition} THEN + PERFORM pg_advisory_xact_lock({ready_key}); + PERFORM pg_advisory_xact_lock({gate_key}); + END IF; + RETURN {row}; + END; + $function$" + )) + .execute(pool) + .await + .expect("failed to create pause function"); + sqlx::query(&format!( + "CREATE TRIGGER pause_for_test + AFTER {event} ON {schema}.{table} + FOR EACH ROW EXECUTE FUNCTION {schema}.pause_for_test()" + )) + .execute(pool) + .await + .expect("failed to create pause trigger"); +} + +pub fn sqlstate(error: &sqlx::Error) -> Option { + match error { + sqlx::Error::Database(e) => e.code().map(|c| c.to_string()), + _ => None, + } +} + +/// Fails the test with SQLSTATE 40P01 in the message when `who` was aborted +/// as a deadlock victim. Call it before any other check of `result`, so a +/// deadlock is reported as a deadlock. +pub fn assert_not_deadlock_victim(who: &str, result: &Result) { + if let Err(error) = result { + assert_ne!( + sqlstate(error).as_deref(), + Some(DEADLOCK_DETECTED), + "{who} was aborted as a deadlock victim (SQLSTATE {DEADLOCK_DETECTED}): {error}" + ); + } +} + +/// Fails the test unless `result` is the error renewal raises when its lease +/// is gone. +pub fn assert_lease_gone(result: Result<(), sqlx::Error>) { + let error = result.expect_err("renewal must fail after its lease was released"); + assert!( + error.to_string().contains(LEASE_GONE), + "renewal must fail as released: {error}" + ); +} + +pub fn spin_for(micros: u64) { + let until = Instant::now() + Duration::from_micros(micros); + while Instant::now() < until { + std::hint::spin_loop(); + } +} diff --git a/tests/deadlocks/main.rs b/tests/deadlocks/main.rs new file mode 100644 index 0000000..2308a54 --- /dev/null +++ b/tests/deadlocks/main.rs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Deadlock regression suite for the PostgreSQL provider. +//! +//! Each test here reproduces one way two provider calls can lock the same rows +//! in opposite orders, and fails if PostgreSQL detects a deadlock. Run the +//! suite alone with `cargo test --test deadlocks`. It also runs in every +//! default `cargo test`, which is what CI runs. +//! +//! Rules for this suite: +//! +//! - Every test runs by default. No test carries the ignore attribute, and +//! `suite_has_no_ignored_tests` fails the build's test run if one does. +//! - Every wait is bounded (`STEP_TIMEOUT`, `WAIT_BUDGET`, statement +//! timeouts), so a regression fails instead of hanging. +//! - Assert SQLSTATE 40P01 directly. Send the statement the provider sends, +//! once, so a deadlock fails the test as a deadlock; do not rely on a retry +//! or on eventual success, which can hide one. +//! - Race tests run 200 rounds by default. Set `RACE_ROUNDS` for a soak, for +//! example `RACE_ROUNDS=10000 cargo test --test deadlocks race_ -- --nocapture`. +//! Each prints a `RACEJSON` line with its tally. +//! - Every lock-ordering or deadlock fix adds its test here. +//! +//! Modules: +//! +//! - `renew_fetch`: renewal against fetch, forced and raced (migration 0026). +//! - `renew_ack_abandon`: renewal against acknowledge and abandon. +//! - `victim_retry`: the provider retries a renewal aborted as a deadlock +//! victim. +//! - `harness`: shared helpers, also used by +//! `tests/orchestration_lock_renewal_tests.rs`. + +mod harness; +mod renew_ack_abandon; +mod renew_fetch; +mod victim_retry; + +/// Every source file of the suite, checked by `suite_has_no_ignored_tests`. +const SOURCES: &[(&str, &str)] = &[ + ("main.rs", include_str!("main.rs")), + ("harness.rs", include_str!("harness.rs")), + ("renew_ack_abandon.rs", include_str!("renew_ack_abandon.rs")), + ("renew_fetch.rs", include_str!("renew_fetch.rs")), + ("victim_retry.rs", include_str!("victim_retry.rs")), +]; + +/// Deadlock tests must run in every default `cargo test`. Fails if any file of +/// the suite ignores a test, or if a file was added without being checked. +#[test] +fn suite_has_no_ignored_tests() { + // Built from two parts so this file does not match itself. + let marker = concat!("#[", "ignore"); + for (file, source) in SOURCES { + assert!( + !source.contains(marker), + "tests/deadlocks/{file} ignores a test; deadlock tests must run in every cargo test" + ); + } + + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/deadlocks"); + for entry in std::fs::read_dir(&dir).expect("failed to list tests/deadlocks") { + let name = entry + .expect("failed to read a tests/deadlocks entry") + .file_name() + .into_string() + .expect("non-UTF-8 file name in tests/deadlocks"); + if name.ends_with(".rs") { + assert!( + SOURCES.iter().any(|(file, _)| *file == name), + "tests/deadlocks/{name} is not listed in SOURCES in tests/deadlocks/main.rs" + ); + } + } +} diff --git a/tests/deadlocks/renew_ack_abandon.rs b/tests/deadlocks/renew_ack_abandon.rs new file mode 100644 index 0000000..5400bb7 --- /dev/null +++ b/tests/deadlocks/renew_ack_abandon.rs @@ -0,0 +1,209 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Orchestration lock renewal against acknowledge and abandon (migration 0026). +//! +//! Acknowledge and abandon change the instance's queue rows and then delete +//! its `instance_locks` row. They do not take fetch's advisory lock. Before +//! migration 0026, renewal updated `instance_locks` first and the queue rows +//! second, the opposite order, so it could deadlock with either of them +//! (SQLSTATE 40P01). Renewal now updates the queue rows first. +//! +//! Each test pauses acknowledge or abandon after its queue change and starts +//! a renewal. Renewal must wait for the queue rows without holding the +//! `instance_locks` row, and must fail as released once the other call +//! commits. Both calls send the provider's statement once, on their own +//! connections, so a deadlock shows as SQLSTATE 40P01 instead of being +//! retried away. + +use crate::harness::*; +use sqlx::postgres::PgConnection; +use sqlx::Connection; +use std::time::Duration; +use tokio::task::JoinHandle; + +/// The call that releases the instance lock while renewal runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Release { + /// Deletes the queue rows, then the instance lock. + Acknowledge, + /// Unlocks the queue rows, then deletes the instance lock. + Abandon, +} + +impl Release { + fn name(self) -> &'static str { + match self { + Release::Acknowledge => "acknowledge", + Release::Abandon => "abandon", + } + } + + /// The trigger event and row condition that match this call's queue + /// change, and only that change. Renewal's own queue update keeps the + /// token, so it does not match the abandon condition. + fn pause_point(self, token: &str) -> (&'static str, String) { + let token = token_literal(token); + match self { + Release::Acknowledge => ("DELETE", format!("OLD.lock_token = {token}")), + Release::Abandon => ( + "UPDATE", + format!("OLD.lock_token = {token} AND NEW.lock_token IS NULL"), + ), + } + } + + /// Sends the statement `PostgresProvider` sends for this call once, on its + /// own connection. + fn spawn( + self, + database_url: String, + schema: String, + token: String, + ) -> JoinHandle> { + tokio::spawn(async move { + let mut connection = PgConnection::connect(&database_url).await?; + match self { + // A turn with no history, no new work and default metadata. + Release::Acknowledge => sqlx::query(&format!( + "SELECT {schema}.ack_orchestration_item($1, $2, $3, $4, $5, $6, $7, $8)" + )) + .bind(&token) + .bind(now_ms()) + .bind(1_i64) + .bind(serde_json::json!([])) + .bind(serde_json::json!([])) + .bind(serde_json::json!([])) + .bind(serde_json::json!({ + "orchestration_name": null, + "orchestration_version": null, + "status": null, + "output": null, + "parent_instance_id": null, + "pinned_duroxide_version": null, + "custom_status_action": null, + "custom_status_value": null, + "kv_mutations": [], + })) + .bind(serde_json::json!([])) + .execute(&mut connection) + .await + .map(|_| ()), + Release::Abandon => sqlx::query(&format!( + "SELECT {schema}.abandon_orchestration_item($1, $2, NULL, false)" + )) + .bind(&token) + .bind(now_ms()) + .execute(&mut connection) + .await + .map(|_| ()), + } + }) + } +} + +/// Pauses `release` after its queue change, renews while it is paused, and +/// checks that the two do not deadlock and that renewal fails as released. +async fn renew_while_releasing(release: Release) { + with_schema(move |schema| async move { + let database_url = database_url(); + let (_provider, instance, token) = + fetch_new_instance(&schema, Duration::from_secs(60)).await; + let pool = raw_pool(&database_url).await; + let name = release.name(); + + let ready_key = advisory_key(); + let gate_key = advisory_key(); + let mut gate_connection = PgConnection::connect(&database_url) + .await + .expect("failed to connect gate session"); + let mut gate = gate_connection + .begin() + .await + .expect("failed to begin gate transaction"); + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(gate_key) + .execute(&mut *gate) + .await + .expect("failed to take gate advisory lock"); + let (event, condition) = release.pause_point(&token); + install_pause_trigger_when( + &pool, + &schema, + "orchestrator_queue", + event, + &condition, + ready_key, + gate_key, + ) + .await; + + let releasing = release.spawn(database_url.clone(), schema.clone(), token.clone()); + wait_for_advisory_holder(&pool, ready_key).await; + + let renewal = spawn_sql_renewal(database_url.clone(), schema.clone(), token.clone(), 60); + wait_for_call_to_wait(&pool, &schema, "renew_orchestration_item_lock", false).await; + // The paused call has not reached instance_locks yet, so only renewal + // can hold that row now. + let renewal_held_instance_row = instance_lock_row_is_held(&pool, &schema, &instance).await; + + timed("gate release", gate.commit()) + .await + .expect("failed to release the paused call"); + let release_result = timed(name, releasing) + .await + .unwrap_or_else(|_| panic!("{name} task panicked")); + let renewal_result = timed("renewal", renewal) + .await + .expect("renewal task panicked"); + + assert_not_deadlock_victim(name, &release_result); + assert_not_deadlock_victim("renewal", &renewal_result); + release_result.unwrap_or_else(|error| panic!("{name} must succeed: {error}")); + assert!( + !renewal_held_instance_row, + "renewal held the instance_locks row while it waited for the queue rows; \ + {name} deletes that row next, so the two can deadlock" + ); + assert_lease_gone(renewal_result); + + assert!( + read_lease(&pool, &schema, &instance).await.is_none(), + "renewal must not recreate a released lock" + ); + let queue = read_queue(&pool, &schema, &instance).await; + match release { + Release::Acknowledge => assert!( + queue.is_empty(), + "acknowledged messages must stay deleted: {queue:?}" + ), + Release::Abandon => { + assert!(!queue.is_empty(), "abandoned messages must stay queued"); + assert!( + queue.iter().all(|row| *row == (None, None)), + "renewal must not lock abandoned messages again: {queue:?}" + ); + } + } + }) + .await; +} + +/// Acknowledge pauses after it deletes the instance's queue rows and before it +/// deletes the instance lock. Renewal must wait for the queue rows without +/// holding the instance lock; once acknowledge commits, renewal must fail +/// because the lock was released. Opposite row orders deadlock here. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn renewal_and_acknowledge_lock_rows_in_the_same_order() { + renew_while_releasing(Release::Acknowledge).await; +} + +/// Abandon pauses after it unlocks the instance's queue rows and before it +/// deletes the instance lock. Renewal must wait for the queue rows without +/// holding the instance lock; once abandon commits, renewal must fail because +/// the lock was released, and the messages must stay unlocked. Opposite row +/// orders deadlock here. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn renewal_and_abandon_lock_rows_in_the_same_order() { + renew_while_releasing(Release::Abandon).await; +} diff --git a/tests/deadlocks/renew_fetch.rs b/tests/deadlocks/renew_fetch.rs new file mode 100644 index 0000000..55e0e6d --- /dev/null +++ b/tests/deadlocks/renew_fetch.rs @@ -0,0 +1,380 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Orchestration lock renewal against fetch (migration 0026). +//! +//! Before migration 0026, fetch locked a queue row and then waited for +//! `instance_locks`, while renewal held `instance_locks` and waited for the +//! queue row, so the two could deadlock (SQLSTATE 40P01). Renewal now takes +//! fetch's per-instance advisory lock before any row lock. +//! +//! The first test forces that interleaving with a trigger. The `race_*` tests +//! reproduce how the deadlock happens in production, with no triggers or +//! pauses: another node treats the owner's lease as expired while the owner +//! renews it, because its clock runs ahead or because the renewal stalled on +//! the way to the database. Each round sends the same two statements +//! `PostgresProvider` sends, on two connections, released together with +//! staggered start times. + +use crate::harness::*; +use duroxide::providers::{Provider, WorkItem}; +use duroxide_pg::PostgresProvider; +use sqlx::postgres::PgConnection; +use sqlx::Connection; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::{oneshot, Barrier}; + +/// Renewal pauses inside its `instance_locks` update while a fetch for the +/// same instance starts. The fetch must wait, and both must then finish. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn fetch_and_renew_serialize_before_taking_conflicting_row_locks() { + with_schema(|schema| async move { + let database_url = database_url(); + let (_provider, instance, token) = + fetch_new_instance(&schema, Duration::from_secs(30)).await; + let pool = raw_pool(&database_url).await; + + let ready_key = advisory_key(); + let gate_key = advisory_key(); + let mut gate_connection = PgConnection::connect(&database_url) + .await + .expect("failed to connect gate session"); + let mut gate = gate_connection + .begin() + .await + .expect("failed to begin gate transaction"); + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(gate_key) + .execute(&mut *gate) + .await + .expect("failed to take gate advisory lock"); + install_pause_trigger( + &pool, + &schema, + "instance_locks", + "UPDATE OF locked_until", + &token, + ready_key, + gate_key, + ) + .await; + + let renew_now_ms = now_ms(); + let renewal_schema = schema.clone(); + let renewal_token = token.clone(); + let renewal_database_url = database_url.clone(); + let renewal = tokio::spawn(async move { + let mut connection = PgConnection::connect(&renewal_database_url) + .await + .expect("failed to connect renewal session"); + sqlx::query(&format!( + "SELECT {renewal_schema}.renew_orchestration_item_lock($1, $2, $3)" + )) + .bind(renewal_token) + .bind(renew_now_ms) + .bind(60_i64) + .execute(&mut connection) + .await + }); + + wait_for_advisory_holder(&pool, ready_key).await; + + // Fetch as if the renewed lease had expired, so it takes the instance. + let fetch_schema = schema.clone(); + let fetch_database_url = database_url.clone(); + let (fetch_pid_tx, fetch_pid_rx) = oneshot::channel(); + let fetch = tokio::spawn(async move { + let mut connection = PgConnection::connect(&fetch_database_url) + .await + .expect("failed to connect fetch session"); + let _ = fetch_pid_tx.send(backend_pid(&mut connection).await); + sqlx::query_as::<_, (String, String)>(&format!( + "SELECT out_instance_id, out_lock_token + FROM {fetch_schema}.fetch_orchestration_item($1, $2, NULL, NULL)" + )) + .bind(renew_now_ms + 120_000) + .bind(30_000_i64) + .fetch_optional(&mut connection) + .await + }); + + let fetch_pid = timed("fetch backend PID", fetch_pid_rx) + .await + .expect("fetch task did not report its backend PID"); + wait_for_lock_waiter(&pool, fetch_pid).await; + + timed("gate release", gate.commit()) + .await + .expect("failed to release renewal gate"); + let renewal_result = timed("renewal", renewal) + .await + .expect("renewal task panicked"); + let fetch_result = timed("fetch", fetch).await.expect("fetch task panicked"); + + assert_not_deadlock_victim("renewal", &renewal_result); + assert_not_deadlock_victim("fetch", &fetch_result); + renewal_result.expect("renewal must complete"); + let (fetched, new_token) = fetch_result + .expect("fetch must complete") + .expect("fetch must take the instance after renewal commits"); + assert_eq!(fetched, instance); + assert_ne!(new_token, token); + + let lease = read_lease(&pool, &schema, &instance) + .await + .expect("the instance must stay locked by the fetch"); + assert_eq!(lease.token, new_token); + lease.assert_queue_matches(); + }) + .await; +} + +/// How another node comes to treat the owner's lease as expired while the +/// owner renews it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ExpiredView { + /// The other node's clock runs ahead of the owner's by more than the + /// lease time left. With the runtime defaults (5 s lease, renewal every + /// 3 s) that is a clock 2 s or more ahead. The owner renews on time. + ClockAhead, + /// The owner's renewal read its clock just before the lease expired and + /// reached the database just after, for example behind a stalled + /// connection pool. The other node's clock is correct. + RenewalStalled, +} + +#[derive(Debug, Default)] +struct RaceTally { + rounds: u32, + renew_deadlocks: u32, + fetch_deadlocks: u32, + renewed: u32, + renewal_rejected: u32, + taken_over: u32, + not_taken: u32, + tables_disagree: u32, + other_errors: Vec, +} + +/// Runs `RACE_ROUNDS` rounds (default 200). In each round the owner fetches +/// a new instance, then its renewal and the other node's fetch are released +/// together. Their start times are staggered across rounds, from the fetch +/// 3 ms ahead to the renewal 0.5 ms ahead. Fetch does more work before it +/// takes its first row lock than renewal does, so it needs the longer lead. +async fn race_renewal_against_expired_view(view: ExpiredView) { + let rounds: u32 = std::env::var("RACE_ROUNDS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(200); + with_schema(move |schema| async move { + let database_url = database_url(); + let provider = PostgresProvider::new_with_schema(&database_url, Some(&schema)) + .await + .expect("failed to create provider"); + let pool = raw_pool(&database_url).await; + let mut owner = PgConnection::connect(&database_url) + .await + .expect("failed to connect owner session"); + let mut other = PgConnection::connect(&database_url) + .await + .expect("failed to connect other node's session"); + for connection in [&mut owner, &mut other] { + sqlx::query("SET statement_timeout = '20s'") + .execute(&mut *connection) + .await + .expect("failed to set statement timeout"); + } + let lease = match view { + ExpiredView::ClockAhead => Duration::from_secs(5), + ExpiredView::RenewalStalled => Duration::from_millis(20), + }; + let renew_sql = format!("SELECT {schema}.renew_orchestration_item_lock($1, $2, $3)"); + let fetch_sql = format!( + "SELECT out_instance_id, out_lock_token + FROM {schema}.fetch_orchestration_item($1, $2, NULL, NULL)" + ); + + let mut tally = RaceTally::default(); + for round in 0..rounds { + let instance = format!("race-{}", uuid::Uuid::new_v4()); + provider + .enqueue_for_orchestrator( + WorkItem::StartOrchestration { + instance: instance.clone(), + orchestration: ORCHESTRATION.to_string(), + input: "{}".to_string(), + version: Some("1.0.0".to_string()), + parent_instance: None, + parent_id: None, + parent_execution_id: None, + execution_id: 1, + }, + None, + ) + .await + .expect("failed to enqueue orchestration work"); + let (_item, token, _attempt_count) = provider + .fetch_orchestration_item(lease, Duration::ZERO, None) + .await + .expect("owner fetch failed") + .expect("owner fetch did not return work"); + let locked_until = read_lease(&pool, &schema, &instance) + .await + .expect("the owner must hold the lease") + .locked_until; + + // The clock each node passes to the database. + let (renew_now, other_now) = match view { + ExpiredView::ClockAhead => (now_ms(), locked_until + 2_000), + ExpiredView::RenewalStalled => { + sleep_until_database_time(&pool, locked_until + 2).await; + (locked_until - 1, now_ms().max(locked_until + 2)) + } + }; + + let offset = (i64::from(round) * 97) % 3501 - 3000; + let renew_delay = if offset < 0 { offset.unsigned_abs() } else { 0 }; + let fetch_delay = if offset > 0 { offset.unsigned_abs() } else { 0 }; + let barrier = Arc::new(Barrier::new(2)); + + let renewal = tokio::spawn({ + let barrier = barrier.clone(); + let sql = renew_sql.clone(); + let token = token.clone(); + let mut connection = owner; + async move { + barrier.wait().await; + spin_for(renew_delay); + let result = sqlx::query(&sql) + .bind(&token) + .bind(renew_now) + .bind(5_i64) + .execute(&mut connection) + .await + .map(|_| ()); + (connection, result) + } + }); + let fetch = tokio::spawn({ + let barrier = barrier.clone(); + let sql = fetch_sql.clone(); + let mut connection = other; + async move { + barrier.wait().await; + spin_for(fetch_delay); + let result = sqlx::query_as::<_, (String, String)>(&sql) + .bind(other_now) + .bind(30_000_i64) + .fetch_optional(&mut connection) + .await; + (connection, result) + } + }); + let (connection, renew_result) = timed("renewal", renewal) + .await + .expect("renewal task panicked"); + owner = connection; + let (connection, fetch_result) = + timed("fetch", fetch).await.expect("fetch task panicked"); + other = connection; + + tally.rounds += 1; + match renew_result { + Ok(()) => tally.renewed += 1, + Err(e) if sqlstate(&e).as_deref() == Some(DEADLOCK_DETECTED) => { + tally.renew_deadlocks += 1 + } + Err(e) if e.to_string().contains(LEASE_GONE) => tally.renewal_rejected += 1, + Err(e) => tally.other_errors.push(format!("renewal: {e}")), + } + match fetch_result { + Ok(Some((fetched, new_token))) => { + assert_eq!(fetched, instance); + assert_ne!(new_token, token); + tally.taken_over += 1; + } + Ok(None) => tally.not_taken += 1, + Err(e) if sqlstate(&e).as_deref() == Some(DEADLOCK_DETECTED) => { + tally.fetch_deadlocks += 1 + } + Err(e) => tally.other_errors.push(format!("fetch: {e}")), + } + + match read_lease(&pool, &schema, &instance).await { + Some(lease) => { + if lease.queue.is_empty() + || lease.queue.iter().any(|row| { + *row != (Some(lease.token.clone()), Some(lease.locked_until)) + }) + { + tally.tables_disagree += 1; + } + } + None => tally.tables_disagree += 1, + } + + for table in ["orchestrator_queue", "instance_locks"] { + sqlx::query(&format!( + "DELETE FROM {schema}.{table} WHERE instance_id = $1" + )) + .bind(&instance) + .execute(&pool) + .await + .expect("failed to clean up the round"); + } + } + + println!( + "RACEJSON {}", + serde_json::json!({ + "view": format!("{view:?}"), + "rounds": tally.rounds, + "renew_deadlocks": tally.renew_deadlocks, + "fetch_deadlocks": tally.fetch_deadlocks, + "renewed": tally.renewed, + "renewal_rejected": tally.renewal_rejected, + "taken_over": tally.taken_over, + "not_taken": tally.not_taken, + "tables_disagree": tally.tables_disagree, + "other_errors": tally.other_errors.len(), + }) + ); + + assert_eq!( + tally.renew_deadlocks + tally.fetch_deadlocks, + 0, + "renewal and fetch deadlocked (SQLSTATE {DEADLOCK_DETECTED}): {tally:?}" + ); + assert!( + tally.other_errors.is_empty(), + "unexpected errors: {tally:?}" + ); + assert_eq!(tally.tables_disagree, 0, "lease tables disagree: {tally:?}"); + assert_eq!(tally.renewed + tally.renewal_rejected, rounds, "{tally:?}"); + assert_eq!(tally.taken_over + tally.not_taken, rounds, "{tally:?}"); + if view == ExpiredView::RenewalStalled { + assert_eq!( + tally.renewed, 0, + "a renewal that reached the database after the lease expired must fail: {tally:?}" + ); + assert_eq!(tally.taken_over, rounds, "{tally:?}"); + } + }) + .await; +} + +/// Case 1, clock skew: the other node's clock runs ahead, so it fetches the +/// instance while the owner renews it on time. No deadlock is allowed. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn race_renewal_against_fetch_from_node_with_clock_ahead() { + race_renewal_against_expired_view(ExpiredView::ClockAhead).await; +} + +/// Case 1, stalled renewal: the renewal reaches the database just after the +/// lease expired, while another node fetches the instance. No deadlock is +/// allowed, and the renewal must not revive the expired lease. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn race_stalled_renewal_against_fetch_after_expiry() { + race_renewal_against_expired_view(ExpiredView::RenewalStalled).await; +} diff --git a/tests/deadlocks/victim_retry.rs b/tests/deadlocks/victim_retry.rs new file mode 100644 index 0000000..a23035c --- /dev/null +++ b/tests/deadlocks/victim_retry.rs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! What the provider does when PostgreSQL picks renewal as a deadlock victim. + +use crate::harness::*; +use duroxide::providers::Provider; +use std::time::Duration; + +/// Renewal waits for the instance's advisory lock. When fetches deadlock each +/// other on that lock, PostgreSQL can abort the waiting renewal instead +/// (SQLSTATE 40P01). The provider must retry it rather than return the error, +/// because the runtime stops renewing a turn after any renewal error. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn renewal_retries_when_aborted_as_deadlock_victim() { + with_schema(|schema| async move { + let database_url = database_url(); + let (provider, instance, token) = + fetch_new_instance(&schema, Duration::from_secs(60)).await; + let pool = raw_pool(&database_url).await; + let before = read_lease(&pool, &schema, &instance) + .await + .expect("the instance must be locked"); + + // Abort the first renewal attempt as a deadlock victim. The sequence + // is not rolled back with the aborted transaction, so the next + // attempt passes. + sqlx::query(&format!("CREATE SEQUENCE {schema}.renewal_attempts")) + .execute(&pool) + .await + .expect("failed to create attempt counter"); + sqlx::query(&format!( + "CREATE FUNCTION {schema}.fail_first_renewal() + RETURNS trigger + LANGUAGE plpgsql + AS $function$ + BEGIN + IF NEW.lock_token = {token_sql} + AND nextval('{schema}.renewal_attempts') = 1 THEN + RAISE EXCEPTION 'injected deadlock' USING ERRCODE = '{DEADLOCK_DETECTED}'; + END IF; + RETURN NEW; + END; + $function$", + token_sql = token_literal(&token), + )) + .execute(&pool) + .await + .expect("failed to create failure function"); + sqlx::query(&format!( + "CREATE TRIGGER fail_first_renewal + BEFORE UPDATE OF locked_until ON {schema}.orchestrator_queue + FOR EACH ROW EXECUTE FUNCTION {schema}.fail_first_renewal()" + )) + .execute(&pool) + .await + .expect("failed to create failure trigger"); + + timed( + "renewal", + provider.renew_orchestration_item_lock(&token, Duration::from_secs(120)), + ) + .await + .expect("renewal must be retried after it was aborted as a deadlock victim"); + + let attempts: i64 = + sqlx::query_scalar(&format!("SELECT last_value FROM {schema}.renewal_attempts")) + .fetch_one(&pool) + .await + .expect("failed to read attempt counter"); + assert!( + attempts >= 2, + "renewal was not retried: {attempts} attempt(s)" + ); + + let after = read_lease(&pool, &schema, &instance) + .await + .expect("the instance must stay locked"); + assert_eq!(after.token, token); + assert!( + after.locked_until > before.locked_until, + "the retried renewal must extend the lease" + ); + after.assert_queue_matches(); + }) + .await; +} diff --git a/tests/fetch_renew_lock_order_repro_tests.rs b/tests/fetch_renew_lock_order_repro_tests.rs deleted file mode 100644 index 4ce1713..0000000 --- a/tests/fetch_renew_lock_order_repro_tests.rs +++ /dev/null @@ -1,1231 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -//! Regression tests for orchestration lock renewal (migration 0026). -//! -//! Before migration 0026, fetch locked a queue row and then waited for -//! `instance_locks`, while renewal held `instance_locks` and waited for the -//! queue row, so the two could deadlock (SQLSTATE 40P01). Renewal now takes -//! fetch's per-instance advisory lock before any row lock. -//! -//! Renewal looks its token up (the check) before that wait and changes the -//! lease (the use) after it. The `toctou_*` tests hold the advisory lock, -//! let renewal pass its check and block, change the lease in that window in -//! one way each, and then check what renewal does. The next two tests check -//! that renewal and acknowledge lock rows in the same order, and that the -//! provider retries a renewal that PostgreSQL aborted as a deadlock victim. -//! -//! The `race_*` tests reproduce how the deadlock happens in production, with -//! no triggers or pauses: another node treats the owner's lease as expired -//! while the owner renews it, because its clock runs ahead or because the -//! renewal stalled on the way to the database. Each round sends the same two -//! statements `PostgresProvider` sends, on two connections, released together -//! with staggered start times. -//! -//! The last test checks the unique index on `instance_locks(lock_token)` that -//! renewal, acknowledge and abandon use to find an instance by its token. - -use duroxide::providers::{ExecutionMetadata, Provider, ProviderError, WorkItem}; -use duroxide_pg::PostgresProvider; -use sqlx::postgres::{PgConnection, PgPoolOptions}; -use sqlx::{Connection, PgPool}; -use std::future::Future; -use std::sync::Arc; -use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; -use tokio::sync::{oneshot, Barrier}; -use tokio::task::JoinHandle; - -const ORCHESTRATION: &str = "FetchRenewLockOrder"; -/// Upper bound for any single step, so a regression fails instead of hanging. -const STEP_TIMEOUT: Duration = Duration::from_secs(30); -/// Upper bound for a backend to reach an expected lock wait. -const WAIT_BUDGET: Duration = Duration::from_secs(10); -const POLL_INTERVAL: Duration = Duration::from_millis(10); - -fn database_url() -> String { - dotenvy::dotenv().ok(); - std::env::var("DATABASE_URL").expect("DATABASE_URL must be set") -} - -fn unique_schema_name() -> String { - let guid = uuid::Uuid::new_v4().to_string(); - let suffix = &guid[guid.len() - 8..]; - format!("fetch_renew_lock_order_{suffix}") -} - -fn advisory_key() -> i64 { - let bytes = *uuid::Uuid::new_v4().as_bytes(); - i64::from_be_bytes(bytes[..8].try_into().expect("UUID prefix has eight bytes")) -} - -fn now_ms() -> i64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("system clock before Unix epoch") - .as_millis() as i64 -} - -async fn raw_pool(database_url: &str) -> PgPool { - PgPoolOptions::new() - .max_connections(4) - .connect(database_url) - .await - .expect("failed to create raw PostgreSQL pool") -} - -async fn timed(what: &str, future: impl Future) -> T { - tokio::time::timeout(STEP_TIMEOUT, future) - .await - .unwrap_or_else(|_| panic!("timed out waiting for {what}")) -} - -/// Runs `body` with a fresh schema name and drops the schema afterwards, -/// also when `body` panics. -async fn with_schema(body: F) -where - F: FnOnce(String) -> Fut, - Fut: Future + Send + 'static, -{ - let schema = unique_schema_name(); - let outcome = tokio::spawn(body(schema.clone())).await; - - let pool = raw_pool(&database_url()).await; - let drop_sql = format!("DROP SCHEMA IF EXISTS {schema} CASCADE"); - let drop = sqlx::query(&drop_sql).execute(&pool); - match tokio::time::timeout(STEP_TIMEOUT, drop).await { - Ok(Ok(_)) => {} - Ok(Err(error)) => eprintln!("failed to drop test schema {schema}: {error}"), - Err(_) => eprintln!("timed out dropping test schema {schema}"), - } - - if let Err(error) = outcome { - if error.is_panic() { - std::panic::resume_unwind(error.into_panic()); - } - panic!("test body did not finish: {error}"); - } -} - -/// Creates a provider in `schema`, starts one orchestration instance and -/// fetches it. Returns the provider, the instance id and the lock token. -async fn fetch_new_instance( - schema: &str, - lock_timeout: Duration, -) -> (Arc, String, String) { - let provider = PostgresProvider::new_with_schema(&database_url(), Some(schema)) - .await - .expect("failed to create provider"); - let instance = format!("instance-{}", uuid::Uuid::new_v4()); - - provider - .enqueue_for_orchestrator( - WorkItem::StartOrchestration { - instance: instance.clone(), - orchestration: ORCHESTRATION.to_string(), - input: "{}".to_string(), - version: Some("1.0.0".to_string()), - parent_instance: None, - parent_id: None, - parent_execution_id: None, - execution_id: 1, - }, - None, - ) - .await - .expect("failed to enqueue orchestration work"); - - let (_item, token, _attempt_count) = provider - .fetch_orchestration_item(lock_timeout, Duration::ZERO, None) - .await - .expect("initial fetch failed") - .expect("initial fetch did not return work"); - - (Arc::new(provider), instance, token) -} - -fn spawn_renewal( - provider: Arc, - token: String, - extend_for: Duration, -) -> JoinHandle> { - tokio::spawn(async move { - provider - .renew_orchestration_item_lock(&token, extend_for) - .await - }) -} - -/// The instance lease and the lease on each of the instance's queue rows. -#[derive(Debug)] -struct Lease { - token: String, - locked_until: i64, - queue: Vec<(Option, Option)>, -} - -impl Lease { - fn assert_queue_matches(&self) { - assert!(!self.queue.is_empty(), "the instance has no queue rows"); - for row in &self.queue { - assert_eq!( - row, - &(Some(self.token.clone()), Some(self.locked_until)), - "a queue row's lease differs from the instance lease: {self:?}" - ); - } - } -} - -async fn read_lease(pool: &PgPool, schema: &str, instance: &str) -> Option { - let row: Option<(String, i64)> = sqlx::query_as(&format!( - "SELECT lock_token, locked_until FROM {schema}.instance_locks WHERE instance_id = $1" - )) - .bind(instance) - .fetch_optional(pool) - .await - .expect("failed to read instance lease"); - let queue = read_queue(pool, schema, instance).await; - - row.map(|(token, locked_until)| Lease { - token, - locked_until, - queue, - }) -} - -/// The lease on each of the instance's queue rows. -async fn read_queue( - pool: &PgPool, - schema: &str, - instance: &str, -) -> Vec<(Option, Option)> { - sqlx::query_as(&format!( - "SELECT lock_token, locked_until FROM {schema}.orchestrator_queue - WHERE instance_id = $1 ORDER BY id" - )) - .bind(instance) - .fetch_all(pool) - .await - .expect("failed to read queue leases") -} - -/// The instance lease deadline as seen by `connection`, including changes it -/// has not committed. -async fn deadline_in(connection: &mut PgConnection, schema: &str, instance: &str) -> i64 { - sqlx::query_scalar(&format!( - "SELECT locked_until FROM {schema}.instance_locks WHERE instance_id = $1" - )) - .bind(instance) - .fetch_one(connection) - .await - .expect("failed to read the instance lease") -} - -async fn database_now_ms(pool: &PgPool) -> i64 { - sqlx::query_scalar("SELECT (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT") - .fetch_one(pool) - .await - .expect("failed to read database time") -} - -async fn sleep_until_database_time(pool: &PgPool, target_ms: i64) { - loop { - let remaining = target_ms - database_now_ms(pool).await; - if remaining < 0 { - return; - } - tokio::time::sleep(Duration::from_millis(remaining.min(200) as u64 + 1)).await; - } -} - -async fn backend_pid(connection: &mut PgConnection) -> i32 { - sqlx::query_scalar("SELECT pg_backend_pid()") - .fetch_one(connection) - .await - .expect("failed to read backend PID") -} - -/// Waits until a call to `schema.function` waits for a lock: an advisory -/// lock when `advisory` is true, a row lock otherwise. -async fn wait_for_call_to_wait(pool: &PgPool, schema: &str, function: &str, advisory: bool) { - let pattern = format!("%{schema}.{function}(%"); - let deadline = Instant::now() + WAIT_BUDGET; - loop { - let waiting: bool = sqlx::query_scalar( - "SELECT EXISTS ( - SELECT 1 FROM pg_stat_activity - WHERE wait_event_type = 'Lock' - AND (wait_event = 'advisory') = $2 - AND query LIKE $1)", - ) - .bind(&pattern) - .bind(advisory) - .fetch_one(pool) - .await - .expect("failed to inspect lock waits"); - if waiting { - return; - } - assert!( - Instant::now() < deadline, - "{function} never waited for a lock (advisory: {advisory})" - ); - tokio::time::sleep(POLL_INTERVAL).await; - } -} - -/// Waits until another session holds the transaction advisory lock `key`. -async fn wait_for_advisory_holder(pool: &PgPool, key: i64) { - let deadline = Instant::now() + WAIT_BUDGET; - loop { - let held: bool = sqlx::query_scalar("SELECT NOT pg_try_advisory_xact_lock($1)") - .bind(key) - .fetch_one(pool) - .await - .expect("failed to probe advisory lock"); - if held { - return; - } - assert!( - Instant::now() < deadline, - "no session took advisory lock {key}" - ); - tokio::time::sleep(POLL_INTERVAL).await; - } -} - -/// Waits until backend `pid` waits for any lock. -async fn wait_for_lock_waiter(pool: &PgPool, pid: i32) { - let deadline = Instant::now() + WAIT_BUDGET; - loop { - let waiting: bool = sqlx::query_scalar( - "SELECT COALESCE(wait_event_type = 'Lock', false) - FROM pg_stat_activity - WHERE pid = $1", - ) - .bind(pid) - .fetch_optional(pool) - .await - .expect("failed to inspect backend state") - .unwrap_or(false); - if waiting { - return; - } - assert!( - Instant::now() < deadline, - "backend {pid} never waited for a lock" - ); - tokio::time::sleep(POLL_INTERVAL).await; - } -} - -/// Installs a trigger that, for rows carrying `token`, takes `ready_key` and -/// then waits for `gate_key`. The test holds `gate_key` to pause the session -/// that fires the trigger, and detects the pause through `ready_key`. -async fn install_pause_trigger( - pool: &PgPool, - schema: &str, - table: &str, - event: &str, - token: &str, - ready_key: i64, - gate_key: i64, -) { - let row = if event == "DELETE" { "OLD" } else { "NEW" }; - // The provider generates tokens as `lock_`, so a token cannot - // contain this dollar-quote delimiter. - sqlx::query(&format!( - "CREATE FUNCTION {schema}.pause_for_test() - RETURNS trigger - LANGUAGE plpgsql - AS $function$ - BEGIN - IF {row}.lock_token = $token${token}$token$ THEN - PERFORM pg_advisory_xact_lock({ready_key}); - PERFORM pg_advisory_xact_lock({gate_key}); - END IF; - RETURN {row}; - END; - $function$" - )) - .execute(pool) - .await - .expect("failed to create pause function"); - sqlx::query(&format!( - "CREATE TRIGGER pause_for_test - AFTER {event} ON {schema}.{table} - FOR EACH ROW EXECUTE FUNCTION {schema}.pause_for_test()" - )) - .execute(pool) - .await - .expect("failed to create pause trigger"); -} - -/// Renewal pauses inside its `instance_locks` update while a fetch for the -/// same instance starts. The fetch must wait, and both must then finish. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn fetch_and_renew_serialize_before_taking_conflicting_row_locks() { - with_schema(|schema| async move { - let database_url = database_url(); - let (_provider, instance, token) = - fetch_new_instance(&schema, Duration::from_secs(30)).await; - let pool = raw_pool(&database_url).await; - - let ready_key = advisory_key(); - let gate_key = advisory_key(); - let mut gate_connection = PgConnection::connect(&database_url) - .await - .expect("failed to connect gate session"); - let mut gate = gate_connection - .begin() - .await - .expect("failed to begin gate transaction"); - sqlx::query("SELECT pg_advisory_xact_lock($1)") - .bind(gate_key) - .execute(&mut *gate) - .await - .expect("failed to take gate advisory lock"); - install_pause_trigger( - &pool, - &schema, - "instance_locks", - "UPDATE OF locked_until", - &token, - ready_key, - gate_key, - ) - .await; - - let renew_now_ms = now_ms(); - let renewal_schema = schema.clone(); - let renewal_token = token.clone(); - let renewal_database_url = database_url.clone(); - let renewal = tokio::spawn(async move { - let mut connection = PgConnection::connect(&renewal_database_url) - .await - .expect("failed to connect renewal session"); - sqlx::query(&format!( - "SELECT {renewal_schema}.renew_orchestration_item_lock($1, $2, $3)" - )) - .bind(renewal_token) - .bind(renew_now_ms) - .bind(60_i64) - .execute(&mut connection) - .await - }); - - wait_for_advisory_holder(&pool, ready_key).await; - - // Fetch as if the renewed lease had expired, so it takes the instance. - let fetch_schema = schema.clone(); - let fetch_database_url = database_url.clone(); - let (fetch_pid_tx, fetch_pid_rx) = oneshot::channel(); - let fetch = tokio::spawn(async move { - let mut connection = PgConnection::connect(&fetch_database_url) - .await - .expect("failed to connect fetch session"); - let _ = fetch_pid_tx.send(backend_pid(&mut connection).await); - sqlx::query_as::<_, (String, String)>(&format!( - "SELECT out_instance_id, out_lock_token - FROM {fetch_schema}.fetch_orchestration_item($1, $2, NULL, NULL)" - )) - .bind(renew_now_ms + 120_000) - .bind(30_000_i64) - .fetch_optional(&mut connection) - .await - }); - - let fetch_pid = timed("fetch backend PID", fetch_pid_rx) - .await - .expect("fetch task did not report its backend PID"); - wait_for_lock_waiter(&pool, fetch_pid).await; - - timed("gate release", gate.commit()) - .await - .expect("failed to release renewal gate"); - let renewal_result = timed("renewal", renewal) - .await - .expect("renewal task panicked"); - let fetch_result = timed("fetch", fetch).await.expect("fetch task panicked"); - - renewal_result.expect("renewal must complete without a deadlock"); - let (fetched, new_token) = fetch_result - .expect("fetch must complete without a deadlock") - .expect("fetch must take the instance after renewal commits"); - assert_eq!(fetched, instance); - assert_ne!(new_token, token); - - let lease = read_lease(&pool, &schema, &instance) - .await - .expect("the instance must stay locked by the fetch"); - assert_eq!(lease.token, new_token); - lease.assert_queue_matches(); - }) - .await; -} - -/// What changes between renewal's token lookup (the check) and its update -/// after the advisory-lock wait (the use). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Interleaving { - /// Only time passes, more than the requested extension. The lease stays - /// live. - LeaseStaysLive, - /// Time passes until the lease expires. - LeaseExpires, - /// A fetch takes the instance over with a new token. - FetchTakesOver, - /// The owner acknowledges the turn, which releases the lock. - Acknowledged, - /// The owner abandons the turn, which releases the lock. - Abandoned, - /// Another renewal with the same token moves the deadline later. - OtherRenewalExtends, -} - -/// What renewal must do once it gets the advisory lock. -enum Expected { - /// Succeed and leave this owner and deadline in both tables. - Renewed { token: String, locked_until: i64 }, - /// Fail and leave this lease unchanged in both tables. - RejectedLeaseUnchanged { token: String, locked_until: i64 }, - /// Fail and leave no lock row. Queue rows stay deleted (acknowledge) or - /// unlocked (abandon). - RejectedReleased { queue_deleted: bool }, -} - -/// Opens the window between renewal's check and its use, applies one -/// interleaving inside it, and checks the result. -/// -/// The test holds the advisory lock that fetch and renewal take for the -/// instance. Renewal takes that lock only after its token lookup passed, so a -/// renewal seen waiting on it is between its check and its use. The -/// interleaving runs while renewal waits: fetch and renewal inside the -/// transaction that holds the lock (PostgreSQL grants it again to the same -/// session), acknowledge and abandon on their own connections (they do not -/// take the advisory lock). Committing that transaction lets renewal continue. -async fn renew_across(interleaving: Interleaving) { - with_schema(move |schema| async move { - let database_url = database_url(); - let lease_timeout = if interleaving == Interleaving::LeaseExpires { - Duration::from_secs(4) - } else { - Duration::from_secs(60) - }; - // Shorter than the lease left after the wait, so a renewal that used - // its pre-wait time would move the deadline earlier. - let extend_for = Duration::from_secs(1); - let (provider, instance, token) = fetch_new_instance(&schema, lease_timeout).await; - let pool = raw_pool(&database_url).await; - let before = read_lease(&pool, &schema, &instance) - .await - .expect("the instance must be locked"); - - let mut gate_connection = PgConnection::connect(&database_url) - .await - .expect("failed to connect gate session"); - let mut gate = gate_connection - .begin() - .await - .expect("failed to begin gate transaction"); - sqlx::query("SELECT pg_advisory_xact_lock(hashtext($1))") - .bind(&instance) - .execute(&mut *gate) - .await - .expect("failed to take the instance advisory lock"); - - let renewal = spawn_renewal(provider.clone(), token.clone(), extend_for); - wait_for_call_to_wait(&pool, &schema, "renew_orchestration_item_lock", true).await; - let during = read_lease(&pool, &schema, &instance) - .await - .expect("the instance must still be locked"); - assert_eq!( - (during.token.as_str(), during.locked_until), - (token.as_str(), before.locked_until), - "renewal changed the lease before it got the advisory lock" - ); - - let expected = match interleaving { - Interleaving::LeaseStaysLive => { - let waited_from = database_now_ms(&pool).await; - sleep_until_database_time(&pool, waited_from + 2_000).await; - Expected::Renewed { - token: token.clone(), - locked_until: before.locked_until, - } - } - Interleaving::LeaseExpires => { - sleep_until_database_time(&pool, before.locked_until + 250).await; - Expected::RejectedLeaseUnchanged { - token: token.clone(), - locked_until: before.locked_until, - } - } - Interleaving::FetchTakesOver => { - // Fetch as if the lease had expired. - let (fetched, new_token): (String, String) = sqlx::query_as(&format!( - "SELECT out_instance_id, out_lock_token - FROM {schema}.fetch_orchestration_item($1, $2, NULL, NULL)" - )) - .bind(now_ms() + 120_000) - .bind(30_000_i64) - .fetch_one(&mut *gate) - .await - .expect("takeover fetch failed"); - assert_eq!(fetched, instance); - assert_ne!(new_token, token); - let locked_until = deadline_in(&mut gate, &schema, &instance).await; - Expected::RejectedLeaseUnchanged { - token: new_token, - locked_until, - } - } - Interleaving::Acknowledged => { - timed( - "acknowledge", - provider.ack_orchestration_item( - &token, - 1, - vec![], - vec![], - vec![], - ExecutionMetadata::default(), - vec![], - ), - ) - .await - .expect("acknowledge must succeed while renewal waits"); - Expected::RejectedReleased { - queue_deleted: true, - } - } - Interleaving::Abandoned => { - timed( - "abandon", - provider.abandon_orchestration_item(&token, None, false), - ) - .await - .expect("abandon must succeed while renewal waits"); - Expected::RejectedReleased { - queue_deleted: false, - } - } - Interleaving::OtherRenewalExtends => { - sqlx::query(&format!( - "SELECT {schema}.renew_orchestration_item_lock($1, $2, $3)" - )) - .bind(&token) - .bind(now_ms()) - .bind(120_i64) - .execute(&mut *gate) - .await - .expect("the other renewal failed"); - let locked_until = deadline_in(&mut gate, &schema, &instance).await; - assert!(locked_until > before.locked_until); - Expected::Renewed { - token: token.clone(), - locked_until, - } - } - }; - - timed("gate release", gate.commit()) - .await - .expect("failed to release the instance advisory lock"); - let result = timed("renewal", renewal) - .await - .expect("renewal task panicked"); - let after = read_lease(&pool, &schema, &instance).await; - - match expected { - Expected::Renewed { - token, - locked_until, - } => { - result.expect("renewal of a live lease must succeed"); - let after = after.expect("the instance must stay locked"); - assert_eq!(after.token, token); - assert_eq!( - after.locked_until, locked_until, - "renewal must not move the deadline earlier" - ); - assert!( - after.locked_until > database_now_ms(&pool).await, - "the deadline must be in the future" - ); - after.assert_queue_matches(); - } - Expected::RejectedLeaseUnchanged { - token, - locked_until, - } => { - let error = - result.expect_err("renewal must fail when its lease changed while it waited"); - assert!(!error.is_retryable(), "unexpected renewal error: {error:?}"); - let after = after.expect("the lease row must remain"); - assert_eq!(after.token, token); - assert_eq!( - after.locked_until, locked_until, - "renewal must not change a lease it no longer holds" - ); - after.assert_queue_matches(); - } - Expected::RejectedReleased { queue_deleted } => { - let error = result.expect_err("renewal must fail after the lock was released"); - assert!(!error.is_retryable(), "unexpected renewal error: {error:?}"); - assert!(after.is_none(), "renewal must not recreate a released lock"); - let queue = read_queue(&pool, &schema, &instance).await; - if queue_deleted { - assert!( - queue.is_empty(), - "acknowledged messages must stay deleted: {queue:?}" - ); - } else { - assert!(!queue.is_empty(), "abandoned messages must stay queued"); - assert!( - queue.iter().all(|row| *row == (None, None)), - "renewal must not lock abandoned messages again: {queue:?}" - ); - } - } - } - }) - .await; -} - -/// More time than the extension passes, but the lease stays live. Renewal must -/// succeed without moving the deadline earlier. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn toctou_lease_stays_live_while_renewal_waits() { - renew_across(Interleaving::LeaseStaysLive).await; -} - -/// The lease expires. Renewal must fail rather than revive it. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn toctou_lease_expires_while_renewal_waits() { - renew_across(Interleaving::LeaseExpires).await; -} - -/// A fetch takes the instance over. Renewal must fail and leave the new -/// owner's lease unchanged. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn toctou_fetch_takes_over_while_renewal_waits() { - renew_across(Interleaving::FetchTakesOver).await; -} - -/// The owner acknowledges. Renewal must fail and must not recreate the lock. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn toctou_acknowledge_releases_while_renewal_waits() { - renew_across(Interleaving::Acknowledged).await; -} - -/// The owner abandons. Renewal must fail and leave the messages unlocked. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn toctou_abandon_releases_while_renewal_waits() { - renew_across(Interleaving::Abandoned).await; -} - -/// Another renewal moves the deadline later. This renewal must succeed and -/// keep the later deadline. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn toctou_other_renewal_extends_while_renewal_waits() { - renew_across(Interleaving::OtherRenewalExtends).await; -} - -/// Acknowledge pauses after it deletes the instance's queue rows and before it -/// deletes the instance lock. Renewal must wait for the queue rows without -/// holding the instance lock; once acknowledge commits, renewal must fail -/// because the lock was released. Opposite row orders deadlock here. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn renewal_and_acknowledge_lock_rows_in_the_same_order() { - with_schema(|schema| async move { - let database_url = database_url(); - let (provider, instance, token) = - fetch_new_instance(&schema, Duration::from_secs(60)).await; - let pool = raw_pool(&database_url).await; - - let ready_key = advisory_key(); - let gate_key = advisory_key(); - let mut gate_connection = PgConnection::connect(&database_url) - .await - .expect("failed to connect gate session"); - let mut gate = gate_connection - .begin() - .await - .expect("failed to begin gate transaction"); - sqlx::query("SELECT pg_advisory_xact_lock($1)") - .bind(gate_key) - .execute(&mut *gate) - .await - .expect("failed to take gate advisory lock"); - install_pause_trigger( - &pool, - &schema, - "orchestrator_queue", - "DELETE", - &token, - ready_key, - gate_key, - ) - .await; - - let ack_provider = provider.clone(); - let ack_token = token.clone(); - let acknowledge = tokio::spawn(async move { - ack_provider - .ack_orchestration_item( - &ack_token, - 1, - vec![], - vec![], - vec![], - ExecutionMetadata::default(), - vec![], - ) - .await - }); - wait_for_advisory_holder(&pool, ready_key).await; - - let renewal = spawn_renewal(provider.clone(), token.clone(), Duration::from_secs(60)); - wait_for_call_to_wait(&pool, &schema, "renew_orchestration_item_lock", false).await; - - timed("gate release", gate.commit()) - .await - .expect("failed to release acknowledge"); - timed("acknowledge", acknowledge) - .await - .expect("acknowledge task panicked") - .expect("acknowledge must succeed"); - let error = timed("renewal", renewal) - .await - .expect("renewal task panicked") - .expect_err("renewal must fail after acknowledge released the lock"); - assert!( - !error.is_retryable(), - "renewal must fail as released, not as a deadlock victim: {error:?}" - ); - - assert!(read_lease(&pool, &schema, &instance).await.is_none()); - }) - .await; -} - -/// Renewal waits for the instance's advisory lock. When fetches deadlock each -/// other on that lock, PostgreSQL can abort the waiting renewal instead -/// (SQLSTATE 40P01). The provider must retry it rather than return the error, -/// because the runtime stops renewing a turn after any renewal error. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn renewal_retries_when_aborted_as_deadlock_victim() { - with_schema(|schema| async move { - let database_url = database_url(); - let (provider, instance, token) = - fetch_new_instance(&schema, Duration::from_secs(60)).await; - let pool = raw_pool(&database_url).await; - let before = read_lease(&pool, &schema, &instance) - .await - .expect("the instance must be locked"); - - // Abort the first renewal attempt as a deadlock victim. The sequence - // is not rolled back with the aborted transaction, so the next - // attempt passes. - sqlx::query(&format!("CREATE SEQUENCE {schema}.renewal_attempts")) - .execute(&pool) - .await - .expect("failed to create attempt counter"); - // The provider generates tokens as `lock_`, so a token cannot - // contain this dollar-quote delimiter. - sqlx::query(&format!( - "CREATE FUNCTION {schema}.fail_first_renewal() - RETURNS trigger - LANGUAGE plpgsql - AS $function$ - BEGIN - IF NEW.lock_token = $token${token}$token$ - AND nextval('{schema}.renewal_attempts') = 1 THEN - RAISE EXCEPTION 'injected deadlock' USING ERRCODE = '40P01'; - END IF; - RETURN NEW; - END; - $function$" - )) - .execute(&pool) - .await - .expect("failed to create failure function"); - sqlx::query(&format!( - "CREATE TRIGGER fail_first_renewal - BEFORE UPDATE OF locked_until ON {schema}.orchestrator_queue - FOR EACH ROW EXECUTE FUNCTION {schema}.fail_first_renewal()" - )) - .execute(&pool) - .await - .expect("failed to create failure trigger"); - - timed( - "renewal", - provider.renew_orchestration_item_lock(&token, Duration::from_secs(120)), - ) - .await - .expect("renewal must be retried after it was aborted as a deadlock victim"); - - let attempts: i64 = - sqlx::query_scalar(&format!("SELECT last_value FROM {schema}.renewal_attempts")) - .fetch_one(&pool) - .await - .expect("failed to read attempt counter"); - assert!( - attempts >= 2, - "renewal was not retried: {attempts} attempt(s)" - ); - - let after = read_lease(&pool, &schema, &instance) - .await - .expect("the instance must stay locked"); - assert_eq!(after.token, token); - assert!( - after.locked_until > before.locked_until, - "the retried renewal must extend the lease" - ); - after.assert_queue_matches(); - }) - .await; -} - -/// How another node comes to treat the owner's lease as expired while the -/// owner renews it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum ExpiredView { - /// The other node's clock runs ahead of the owner's by more than the - /// lease time left. With the runtime defaults (5 s lease, renewal every - /// 3 s) that is a clock 2 s or more ahead. The owner renews on time. - ClockAhead, - /// The owner's renewal read its clock just before the lease expired and - /// reached the database just after, for example behind a stalled - /// connection pool. The other node's clock is correct. - RenewalStalled, -} - -#[derive(Debug, Default)] -struct RaceTally { - rounds: u32, - renew_deadlocks: u32, - fetch_deadlocks: u32, - renewed: u32, - renewal_rejected: u32, - taken_over: u32, - not_taken: u32, - tables_disagree: u32, - other_errors: Vec, -} - -fn sqlstate(error: &sqlx::Error) -> Option { - match error { - sqlx::Error::Database(e) => e.code().map(|c| c.to_string()), - _ => None, - } -} - -fn spin_for(micros: u64) { - let until = Instant::now() + Duration::from_micros(micros); - while Instant::now() < until { - std::hint::spin_loop(); - } -} - -/// Runs `RACE_ROUNDS` rounds (default 200). In each round the owner fetches -/// a new instance, then its renewal and the other node's fetch are released -/// together. Their start times are staggered across rounds, from the fetch -/// 3 ms ahead to the renewal 0.5 ms ahead. Fetch does more work before it -/// takes its first row lock than renewal does, so it needs the longer lead. -async fn race_renewal_against_expired_view(view: ExpiredView) { - let rounds: u32 = std::env::var("RACE_ROUNDS") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(200); - with_schema(move |schema| async move { - let database_url = database_url(); - let provider = PostgresProvider::new_with_schema(&database_url, Some(&schema)) - .await - .expect("failed to create provider"); - let pool = raw_pool(&database_url).await; - let mut owner = PgConnection::connect(&database_url) - .await - .expect("failed to connect owner session"); - let mut other = PgConnection::connect(&database_url) - .await - .expect("failed to connect other node's session"); - for connection in [&mut owner, &mut other] { - sqlx::query("SET statement_timeout = '20s'") - .execute(&mut *connection) - .await - .expect("failed to set statement timeout"); - } - let lease = match view { - ExpiredView::ClockAhead => Duration::from_secs(5), - ExpiredView::RenewalStalled => Duration::from_millis(20), - }; - let renew_sql = format!("SELECT {schema}.renew_orchestration_item_lock($1, $2, $3)"); - let fetch_sql = format!( - "SELECT out_instance_id, out_lock_token - FROM {schema}.fetch_orchestration_item($1, $2, NULL, NULL)" - ); - - let mut tally = RaceTally::default(); - for round in 0..rounds { - let instance = format!("race-{}", uuid::Uuid::new_v4()); - provider - .enqueue_for_orchestrator( - WorkItem::StartOrchestration { - instance: instance.clone(), - orchestration: ORCHESTRATION.to_string(), - input: "{}".to_string(), - version: Some("1.0.0".to_string()), - parent_instance: None, - parent_id: None, - parent_execution_id: None, - execution_id: 1, - }, - None, - ) - .await - .expect("failed to enqueue orchestration work"); - let (_item, token, _attempt_count) = provider - .fetch_orchestration_item(lease, Duration::ZERO, None) - .await - .expect("owner fetch failed") - .expect("owner fetch did not return work"); - let locked_until = read_lease(&pool, &schema, &instance) - .await - .expect("the owner must hold the lease") - .locked_until; - - // The clock each node passes to the database. - let (renew_now, other_now) = match view { - ExpiredView::ClockAhead => (now_ms(), locked_until + 2_000), - ExpiredView::RenewalStalled => { - sleep_until_database_time(&pool, locked_until + 2).await; - (locked_until - 1, now_ms().max(locked_until + 2)) - } - }; - - let offset = (i64::from(round) * 97) % 3501 - 3000; - let renew_delay = if offset < 0 { offset.unsigned_abs() } else { 0 }; - let fetch_delay = if offset > 0 { offset.unsigned_abs() } else { 0 }; - let barrier = Arc::new(Barrier::new(2)); - - let renewal = tokio::spawn({ - let barrier = barrier.clone(); - let sql = renew_sql.clone(); - let token = token.clone(); - let mut connection = owner; - async move { - barrier.wait().await; - spin_for(renew_delay); - let result = sqlx::query(&sql) - .bind(&token) - .bind(renew_now) - .bind(5_i64) - .execute(&mut connection) - .await - .map(|_| ()); - (connection, result) - } - }); - let fetch = tokio::spawn({ - let barrier = barrier.clone(); - let sql = fetch_sql.clone(); - let mut connection = other; - async move { - barrier.wait().await; - spin_for(fetch_delay); - let result = sqlx::query_as::<_, (String, String)>(&sql) - .bind(other_now) - .bind(30_000_i64) - .fetch_optional(&mut connection) - .await; - (connection, result) - } - }); - let (connection, renew_result) = timed("renewal", renewal) - .await - .expect("renewal task panicked"); - owner = connection; - let (connection, fetch_result) = - timed("fetch", fetch).await.expect("fetch task panicked"); - other = connection; - - tally.rounds += 1; - match renew_result { - Ok(()) => tally.renewed += 1, - Err(e) if sqlstate(&e).as_deref() == Some("40P01") => tally.renew_deadlocks += 1, - Err(e) - if e.to_string() - .contains("Lock token invalid, expired, or already released") => - { - tally.renewal_rejected += 1 - } - Err(e) => tally.other_errors.push(format!("renewal: {e}")), - } - match fetch_result { - Ok(Some((fetched, new_token))) => { - assert_eq!(fetched, instance); - assert_ne!(new_token, token); - tally.taken_over += 1; - } - Ok(None) => tally.not_taken += 1, - Err(e) if sqlstate(&e).as_deref() == Some("40P01") => tally.fetch_deadlocks += 1, - Err(e) => tally.other_errors.push(format!("fetch: {e}")), - } - - match read_lease(&pool, &schema, &instance).await { - Some(lease) => { - if lease.queue.is_empty() - || lease.queue.iter().any(|row| { - *row != (Some(lease.token.clone()), Some(lease.locked_until)) - }) - { - tally.tables_disagree += 1; - } - } - None => tally.tables_disagree += 1, - } - - for table in ["orchestrator_queue", "instance_locks"] { - sqlx::query(&format!( - "DELETE FROM {schema}.{table} WHERE instance_id = $1" - )) - .bind(&instance) - .execute(&pool) - .await - .expect("failed to clean up the round"); - } - } - - println!( - "RACEJSON {}", - serde_json::json!({ - "view": format!("{view:?}"), - "rounds": tally.rounds, - "renew_deadlocks": tally.renew_deadlocks, - "fetch_deadlocks": tally.fetch_deadlocks, - "renewed": tally.renewed, - "renewal_rejected": tally.renewal_rejected, - "taken_over": tally.taken_over, - "not_taken": tally.not_taken, - "tables_disagree": tally.tables_disagree, - "other_errors": tally.other_errors.len(), - }) - ); - - assert_eq!( - tally.renew_deadlocks + tally.fetch_deadlocks, - 0, - "renewal and fetch deadlocked: {tally:?}" - ); - assert!( - tally.other_errors.is_empty(), - "unexpected errors: {tally:?}" - ); - assert_eq!(tally.tables_disagree, 0, "lease tables disagree: {tally:?}"); - assert_eq!(tally.renewed + tally.renewal_rejected, rounds, "{tally:?}"); - assert_eq!(tally.taken_over + tally.not_taken, rounds, "{tally:?}"); - if view == ExpiredView::RenewalStalled { - assert_eq!( - tally.renewed, 0, - "a renewal that reached the database after the lease expired must fail: {tally:?}" - ); - assert_eq!(tally.taken_over, rounds, "{tally:?}"); - } - }) - .await; -} - -/// Case 1, clock skew: the other node's clock runs ahead, so it fetches the -/// instance while the owner renews it on time. No deadlock is allowed. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn race_renewal_against_fetch_from_node_with_clock_ahead() { - race_renewal_against_expired_view(ExpiredView::ClockAhead).await; -} - -/// Case 1, stalled renewal: the renewal reaches the database just after the -/// lease expired, while another node fetches the instance. No deadlock is -/// allowed, and the renewal must not revive the expired lease. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn race_stalled_renewal_against_fetch_after_expiry() { - race_renewal_against_expired_view(ExpiredView::RenewalStalled).await; -} - -/// Renewal, acknowledge and abandon find an instance by its lock token. -/// Migration 0026 adds a unique index on `instance_locks(lock_token)` so these -/// lookups do not scan the table, and so a token can name only one instance. -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn lock_token_lookups_use_a_unique_index() { - with_schema(|schema| async move { - let database_url = database_url(); - let _provider = PostgresProvider::new_with_schema(&database_url, Some(&schema)) - .await - .expect("failed to create provider"); - let pool = raw_pool(&database_url).await; - - let (unique, column): (bool, String) = sqlx::query_as( - "SELECT ix.indisunique, pg_get_indexdef(ix.indexrelid, 1, true) - FROM pg_index ix - JOIN pg_class i ON i.oid = ix.indexrelid - JOIN pg_namespace n ON n.oid = i.relnamespace - WHERE n.nspname = $1 - AND i.relname = 'idx_instance_locks_lock_token' - AND ix.indnatts = 1", - ) - .bind(&schema) - .fetch_one(&pool) - .await - .expect("idx_instance_locks_lock_token must exist"); - assert!(unique, "the lock_token index must be unique"); - assert_eq!(column, "lock_token"); - - // Enough live leases that the planner prefers an index to a table scan. - sqlx::query(&format!( - "INSERT INTO {schema}.instance_locks (instance_id, lock_token, locked_until, locked_at) - SELECT 'instance-' || g, 'lock_' || gen_random_uuid(), - (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT + 600000, 0 - FROM generate_series(1, 5000) AS g" - )) - .execute(&pool) - .await - .expect("failed to fill instance_locks"); - sqlx::query(&format!("ANALYZE {schema}.instance_locks")) - .execute(&pool) - .await - .expect("failed to analyze instance_locks"); - - // The lookups of abandon, and of renewal and acknowledge. - for predicate in [ - "lock_token = 'lock_unknown'", - "lock_token = 'lock_unknown' - AND locked_until > (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT", - ] { - let plan: Vec = sqlx::query_scalar(&format!( - "EXPLAIN SELECT instance_id FROM {schema}.instance_locks WHERE {predicate}" - )) - .fetch_all(&pool) - .await - .expect("failed to explain the token lookup"); - let plan = plan.join("\n"); - assert!( - plan.contains("idx_instance_locks_lock_token") && !plan.contains("Seq Scan"), - "the token lookup must use the index:\n{plan}" - ); - } - - let duplicate = sqlx::query(&format!( - "INSERT INTO {schema}.instance_locks (instance_id, lock_token, locked_until, locked_at) - SELECT 'instance-duplicate', lock_token, 0, 0 - FROM {schema}.instance_locks - LIMIT 1" - )) - .execute(&pool) - .await - .expect_err("a lock token must not name two instances"); - assert_eq!(sqlstate(&duplicate).as_deref(), Some("23505")); - }) - .await; -} diff --git a/tests/orchestration_lock_renewal_tests.rs b/tests/orchestration_lock_renewal_tests.rs new file mode 100644 index 0000000..93cdb6e --- /dev/null +++ b/tests/orchestration_lock_renewal_tests.rs @@ -0,0 +1,370 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Orchestration lock renewal across its advisory-lock wait (migration 0026). +//! +//! Renewal looks its token up (the check) before it waits for fetch's +//! per-instance advisory lock, and changes the lease (the use) after that +//! wait. The `toctou_*` tests hold the advisory lock, let renewal pass its +//! check and block, change the lease in that window in one way each, and then +//! check what renewal does. +//! +//! The last test checks the unique index on `instance_locks(lock_token)` that +//! renewal, acknowledge and abandon use to find an instance by its token. +//! +//! The deadlock tests for renewal live in `tests/deadlocks`, whose helpers +//! this file shares. + +#[path = "deadlocks/harness.rs"] +mod harness; + +use duroxide::providers::{ExecutionMetadata, Provider}; +use duroxide_pg::PostgresProvider; +use harness::*; +use sqlx::postgres::PgConnection; +use sqlx::Connection; +use std::time::Duration; + +/// What changes between renewal's token lookup (the check) and its update +/// after the advisory-lock wait (the use). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Interleaving { + /// Only time passes, more than the requested extension. The lease stays + /// live. + LeaseStaysLive, + /// Time passes until the lease expires. + LeaseExpires, + /// A fetch takes the instance over with a new token. + FetchTakesOver, + /// The owner acknowledges the turn, which releases the lock. + Acknowledged, + /// The owner abandons the turn, which releases the lock. + Abandoned, + /// Another renewal with the same token moves the deadline later. + OtherRenewalExtends, +} + +/// What renewal must do once it gets the advisory lock. +enum Expected { + /// Succeed and leave this owner and deadline in both tables. + Renewed { token: String, locked_until: i64 }, + /// Fail and leave this lease unchanged in both tables. + RejectedLeaseUnchanged { token: String, locked_until: i64 }, + /// Fail and leave no lock row. Queue rows stay deleted (acknowledge) or + /// unlocked (abandon). + RejectedReleased { queue_deleted: bool }, +} + +/// Opens the window between renewal's check and its use, applies one +/// interleaving inside it, and checks the result. +/// +/// The test holds the advisory lock that fetch and renewal take for the +/// instance. Renewal takes that lock only after its token lookup passed, so a +/// renewal seen waiting on it is between its check and its use. The +/// interleaving runs while renewal waits: fetch and renewal inside the +/// transaction that holds the lock (PostgreSQL grants it again to the same +/// session), acknowledge and abandon on their own connections (they do not +/// take the advisory lock). Committing that transaction lets renewal continue. +async fn renew_across(interleaving: Interleaving) { + with_schema(move |schema| async move { + let database_url = database_url(); + let lease_timeout = if interleaving == Interleaving::LeaseExpires { + Duration::from_secs(4) + } else { + Duration::from_secs(60) + }; + // Shorter than the lease left after the wait, so a renewal that used + // its pre-wait time would move the deadline earlier. + let extend_for = Duration::from_secs(1); + let (provider, instance, token) = fetch_new_instance(&schema, lease_timeout).await; + let pool = raw_pool(&database_url).await; + let before = read_lease(&pool, &schema, &instance) + .await + .expect("the instance must be locked"); + + let mut gate_connection = PgConnection::connect(&database_url) + .await + .expect("failed to connect gate session"); + let mut gate = gate_connection + .begin() + .await + .expect("failed to begin gate transaction"); + sqlx::query("SELECT pg_advisory_xact_lock(hashtext($1))") + .bind(&instance) + .execute(&mut *gate) + .await + .expect("failed to take the instance advisory lock"); + + let renewal = spawn_renewal(provider.clone(), token.clone(), extend_for); + wait_for_call_to_wait(&pool, &schema, "renew_orchestration_item_lock", true).await; + let during = read_lease(&pool, &schema, &instance) + .await + .expect("the instance must still be locked"); + assert_eq!( + (during.token.as_str(), during.locked_until), + (token.as_str(), before.locked_until), + "renewal changed the lease before it got the advisory lock" + ); + + let expected = match interleaving { + Interleaving::LeaseStaysLive => { + let waited_from = database_now_ms(&pool).await; + sleep_until_database_time(&pool, waited_from + 2_000).await; + Expected::Renewed { + token: token.clone(), + locked_until: before.locked_until, + } + } + Interleaving::LeaseExpires => { + sleep_until_database_time(&pool, before.locked_until + 250).await; + Expected::RejectedLeaseUnchanged { + token: token.clone(), + locked_until: before.locked_until, + } + } + Interleaving::FetchTakesOver => { + // Fetch as if the lease had expired. + let (fetched, new_token): (String, String) = sqlx::query_as(&format!( + "SELECT out_instance_id, out_lock_token + FROM {schema}.fetch_orchestration_item($1, $2, NULL, NULL)" + )) + .bind(now_ms() + 120_000) + .bind(30_000_i64) + .fetch_one(&mut *gate) + .await + .expect("takeover fetch failed"); + assert_eq!(fetched, instance); + assert_ne!(new_token, token); + let locked_until = deadline_in(&mut gate, &schema, &instance).await; + Expected::RejectedLeaseUnchanged { + token: new_token, + locked_until, + } + } + Interleaving::Acknowledged => { + timed( + "acknowledge", + provider.ack_orchestration_item( + &token, + 1, + vec![], + vec![], + vec![], + ExecutionMetadata::default(), + vec![], + ), + ) + .await + .expect("acknowledge must succeed while renewal waits"); + Expected::RejectedReleased { + queue_deleted: true, + } + } + Interleaving::Abandoned => { + timed( + "abandon", + provider.abandon_orchestration_item(&token, None, false), + ) + .await + .expect("abandon must succeed while renewal waits"); + Expected::RejectedReleased { + queue_deleted: false, + } + } + Interleaving::OtherRenewalExtends => { + sqlx::query(&format!( + "SELECT {schema}.renew_orchestration_item_lock($1, $2, $3)" + )) + .bind(&token) + .bind(now_ms()) + .bind(120_i64) + .execute(&mut *gate) + .await + .expect("the other renewal failed"); + let locked_until = deadline_in(&mut gate, &schema, &instance).await; + assert!(locked_until > before.locked_until); + Expected::Renewed { + token: token.clone(), + locked_until, + } + } + }; + + timed("gate release", gate.commit()) + .await + .expect("failed to release the instance advisory lock"); + let result = timed("renewal", renewal) + .await + .expect("renewal task panicked"); + let after = read_lease(&pool, &schema, &instance).await; + + match expected { + Expected::Renewed { + token, + locked_until, + } => { + result.expect("renewal of a live lease must succeed"); + let after = after.expect("the instance must stay locked"); + assert_eq!(after.token, token); + assert_eq!( + after.locked_until, locked_until, + "renewal must not move the deadline earlier" + ); + assert!( + after.locked_until > database_now_ms(&pool).await, + "the deadline must be in the future" + ); + after.assert_queue_matches(); + } + Expected::RejectedLeaseUnchanged { + token, + locked_until, + } => { + let error = + result.expect_err("renewal must fail when its lease changed while it waited"); + assert!(!error.is_retryable(), "unexpected renewal error: {error:?}"); + let after = after.expect("the lease row must remain"); + assert_eq!(after.token, token); + assert_eq!( + after.locked_until, locked_until, + "renewal must not change a lease it no longer holds" + ); + after.assert_queue_matches(); + } + Expected::RejectedReleased { queue_deleted } => { + let error = result.expect_err("renewal must fail after the lock was released"); + assert!(!error.is_retryable(), "unexpected renewal error: {error:?}"); + assert!(after.is_none(), "renewal must not recreate a released lock"); + let queue = read_queue(&pool, &schema, &instance).await; + if queue_deleted { + assert!( + queue.is_empty(), + "acknowledged messages must stay deleted: {queue:?}" + ); + } else { + assert!(!queue.is_empty(), "abandoned messages must stay queued"); + assert!( + queue.iter().all(|row| *row == (None, None)), + "renewal must not lock abandoned messages again: {queue:?}" + ); + } + } + } + }) + .await; +} + +/// More time than the extension passes, but the lease stays live. Renewal must +/// succeed without moving the deadline earlier. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_lease_stays_live_while_renewal_waits() { + renew_across(Interleaving::LeaseStaysLive).await; +} + +/// The lease expires. Renewal must fail rather than revive it. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_lease_expires_while_renewal_waits() { + renew_across(Interleaving::LeaseExpires).await; +} + +/// A fetch takes the instance over. Renewal must fail and leave the new +/// owner's lease unchanged. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_fetch_takes_over_while_renewal_waits() { + renew_across(Interleaving::FetchTakesOver).await; +} + +/// The owner acknowledges. Renewal must fail and must not recreate the lock. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_acknowledge_releases_while_renewal_waits() { + renew_across(Interleaving::Acknowledged).await; +} + +/// The owner abandons. Renewal must fail and leave the messages unlocked. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_abandon_releases_while_renewal_waits() { + renew_across(Interleaving::Abandoned).await; +} + +/// Another renewal moves the deadline later. This renewal must succeed and +/// keep the later deadline. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_other_renewal_extends_while_renewal_waits() { + renew_across(Interleaving::OtherRenewalExtends).await; +} + +/// Renewal, acknowledge and abandon find an instance by its lock token. +/// Migration 0026 adds a unique index on `instance_locks(lock_token)` so these +/// lookups do not scan the table, and so a token can name only one instance. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn lock_token_lookups_use_a_unique_index() { + with_schema(|schema| async move { + let database_url = database_url(); + let _provider = PostgresProvider::new_with_schema(&database_url, Some(&schema)) + .await + .expect("failed to create provider"); + let pool = raw_pool(&database_url).await; + + let (unique, column): (bool, String) = sqlx::query_as( + "SELECT ix.indisunique, pg_get_indexdef(ix.indexrelid, 1, true) + FROM pg_index ix + JOIN pg_class i ON i.oid = ix.indexrelid + JOIN pg_namespace n ON n.oid = i.relnamespace + WHERE n.nspname = $1 + AND i.relname = 'idx_instance_locks_lock_token' + AND ix.indnatts = 1", + ) + .bind(&schema) + .fetch_one(&pool) + .await + .expect("idx_instance_locks_lock_token must exist"); + assert!(unique, "the lock_token index must be unique"); + assert_eq!(column, "lock_token"); + + // Enough live leases that the planner prefers an index to a table scan. + sqlx::query(&format!( + "INSERT INTO {schema}.instance_locks (instance_id, lock_token, locked_until, locked_at) + SELECT 'instance-' || g, 'lock_' || gen_random_uuid(), + (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT + 600000, 0 + FROM generate_series(1, 5000) AS g" + )) + .execute(&pool) + .await + .expect("failed to fill instance_locks"); + sqlx::query(&format!("ANALYZE {schema}.instance_locks")) + .execute(&pool) + .await + .expect("failed to analyze instance_locks"); + + // The lookups of abandon, and of renewal and acknowledge. + for predicate in [ + "lock_token = 'lock_unknown'", + "lock_token = 'lock_unknown' + AND locked_until > (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT", + ] { + let plan: Vec = sqlx::query_scalar(&format!( + "EXPLAIN SELECT instance_id FROM {schema}.instance_locks WHERE {predicate}" + )) + .fetch_all(&pool) + .await + .expect("failed to explain the token lookup"); + let plan = plan.join("\n"); + assert!( + plan.contains("idx_instance_locks_lock_token") && !plan.contains("Seq Scan"), + "the token lookup must use the index:\n{plan}" + ); + } + + let duplicate = sqlx::query(&format!( + "INSERT INTO {schema}.instance_locks (instance_id, lock_token, locked_until, locked_at) + SELECT 'instance-duplicate', lock_token, 0, 0 + FROM {schema}.instance_locks + LIMIT 1" + )) + .execute(&pool) + .await + .expect_err("a lock token must not name two instances"); + assert_eq!(sqlstate(&duplicate).as_deref(), Some("23505")); + }) + .await; +} From ea598d91839b6d656917a47a3b4e772fa515b9aa Mon Sep 17 00:00:00 2001 From: "Chumbucket (Waldemort)" Date: Sun, 25 Oct 2026 20:32:20 +0000 Subject: [PATCH 13/15] fix: serialize orchestration acknowledge with fetch 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> --- CHANGELOG.md | 17 + ...serialize_orchestration_lock_mutations.sql | 314 ++++++++++++++- tests/deadlocks/ack_fetch.rs | 83 ++++ tests/deadlocks/harness.rs | 151 ++++++++ tests/deadlocks/main.rs | 10 +- tests/deadlocks/renew_ack_abandon.rs | 70 ++-- tests/orchestration_ack_lease_tests.rs | 366 ++++++++++++++++++ tests/orchestration_lock_renewal_tests.rs | 21 +- 8 files changed, 978 insertions(+), 54 deletions(-) create mode 100644 tests/deadlocks/ack_fetch.rs create mode 100644 tests/orchestration_ack_lease_tests.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 94cc163..a12497f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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, and checks the `lock_token` index. +- **An orchestration acknowledge can no longer commit after another worker + has taken the instance over, which processed messages twice (migration + `0026`).** Acknowledge checked its lock token once, without a lock. A + fetch from a worker whose clock runs ahead, or after a stalled acknowledge, + could take the instance over between that check and the commit. The + acknowledge then committed its history and new work, but its deletes, + which match on the old token, removed nothing, so the processed messages + stayed queued and were delivered again. Duroxide does not de-duplicate + queue messages or external events, so they were processed twice: one + enqueued event could run an activity twice. Acknowledge now takes the + per-instance advisory lock right after its token check, checks the token + again, and fails if its instance lock is gone when it deletes it. + `tests/deadlocks/ack_fetch.rs` checks that a fetch waits for an + acknowledge in progress. `tests/orchestration_ack_lease_tests.rs` checks a + takeover while acknowledge waits for the lock, a lock deleted during the + acknowledge, and, end to end with the duroxide runtime, that an order is + charged once when another worker fetches during the acknowledge. ## [0.1.37] - 2026-10-21 diff --git a/migrations/0026_serialize_orchestration_lock_mutations.sql b/migrations/0026_serialize_orchestration_lock_mutations.sql index 80e6e93..dab9970 100644 --- a/migrations/0026_serialize_orchestration_lock_mutations.sql +++ b/migrations/0026_serialize_orchestration_lock_mutations.sql @@ -1,7 +1,7 @@ -- Copyright (c) Microsoft Corporation. -- Licensed under the MIT License. --- Migration 0026: serialize orchestration lock renewal with fetch +-- Migration 0026: serialize orchestration lock renewal and acknowledge with fetch -- -- fetch_orchestration_item takes pg_advisory_xact_lock(hashtext(instance_id)) -- before it locks orchestrator_queue rows and the instance_locks row. Renewal @@ -27,6 +27,18 @@ -- If acknowledge or abandon releases the lock first, the final update matches -- no row and the function raises, which rolls back the queue update. -- +-- Acknowledge (ack_orchestration_item, body otherwise unchanged from migration +-- 0020) now takes the same advisory lock right after its token check, then +-- checks the token again. Before, a fetch that judged the lease expired (a +-- worker whose clock runs ahead, or a stalled acknowledge) could replace the +-- token after that check and commit first. The acknowledge then committed its +-- history and new work while its final deletes, which match on the old token, +-- removed nothing; the messages it processed stayed queued and were delivered +-- again. Duroxide does not de-duplicate redelivered external events or queue +-- messages, so an orchestration could process the same event twice. With the +-- lock held, a fetch waits until the acknowledge ends. The acknowledge also +-- raises if its final delete of the instance lock removes no row. +-- -- The migration also adds a unique index on instance_locks(lock_token). -- Renewal, acknowledge and abandon find the instance by its lock token, and -- without an index each lookup scans the table. The index is unique because a @@ -95,6 +107,306 @@ BEGIN $renew_orch_lock$ LANGUAGE plpgsql; $fmt$, v_schema_name); + EXECUTE format($fmt$ + CREATE OR REPLACE FUNCTION %1$I.ack_orchestration_item( + p_lock_token TEXT, + p_now_ms BIGINT, + p_execution_id BIGINT, + p_history_delta JSONB, + p_worker_items JSONB, + p_orchestrator_items JSONB, + p_metadata JSONB, + p_cancelled_activities JSONB DEFAULT '[]'::JSONB + ) + RETURNS VOID AS $ack_orch$ + DECLARE + v_instance_id TEXT; + v_orchestration_name TEXT; + v_orchestration_version TEXT; + v_parent_instance_id TEXT; + v_status TEXT; + v_output TEXT; + v_completed_at TIMESTAMPTZ; + v_elem JSONB; + v_visible_at TIMESTAMPTZ; + v_fire_at_ms BIGINT; + v_item_instance_id TEXT; + v_item_execution_id BIGINT; + v_item_activity_id BIGINT; + v_item_session_id TEXT; + v_item_tag TEXT; + v_now_ts TIMESTAMPTZ; + v_custom_status_action TEXT; + v_custom_status_value TEXT; + v_current_execution_id BIGINT; + v_kv_mutations JSONB; + v_kv_item JSONB; + v_kv_action TEXT; + v_i INTEGER; + v_is_terminal BOOLEAN; + v_rows_affected INTEGER; + BEGIN + -- Convert Rust-supplied millisecond timestamp to TIMESTAMPTZ + v_now_ts := TO_TIMESTAMP(p_now_ms / 1000.0); + + -- Step 1: Validate lock token + SELECT il.instance_id INTO v_instance_id + FROM %1$I.instance_locks il + WHERE il.lock_token = p_lock_token AND il.locked_until > p_now_ms; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Invalid lock token'; + END IF; + + -- Step 1b: Take the advisory lock that fetch_orchestration_item takes + -- before it can take an instance over. Step 1 holds no lock, so a + -- fetch that judged the lease expired could otherwise replace the + -- token while this acknowledge runs. This acknowledge would then + -- commit its history and new work while its deletes below match no + -- rows, and the messages it processed would be delivered again. + PERFORM pg_advisory_xact_lock(hashtext(v_instance_id)); + + -- Step 1c: Revalidate the token after the wait. While this lock is + -- held, no fetch can replace it. + PERFORM 1 + FROM %1$I.instance_locks il + WHERE il.instance_id = v_instance_id + AND il.lock_token = p_lock_token; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Invalid lock token'; + END IF; + + -- Step 2: Extract metadata from JSONB + v_orchestration_name := p_metadata->>'orchestration_name'; + v_orchestration_version := p_metadata->>'orchestration_version'; + v_parent_instance_id := p_metadata->>'parent_instance_id'; + v_status := p_metadata->>'status'; + v_output := p_metadata->>'output'; + v_current_execution_id := p_execution_id; + v_is_terminal := v_status IN ('Completed', 'ContinuedAsNew', 'Failed'); + + -- Step 3: Create or update instance metadata (with explicit timestamps) + IF v_orchestration_name IS NOT NULL AND v_orchestration_version IS NOT NULL THEN + INSERT INTO %1$I.instances (instance_id, orchestration_name, orchestration_version, current_execution_id, parent_instance_id, created_at, updated_at) + VALUES (v_instance_id, v_orchestration_name, v_orchestration_version, p_execution_id, v_parent_instance_id, v_now_ts, v_now_ts) + ON CONFLICT (instance_id) DO NOTHING; + + UPDATE %1$I.instances i + SET orchestration_name = v_orchestration_name, + orchestration_version = v_orchestration_version, + parent_instance_id = COALESCE(i.parent_instance_id, v_parent_instance_id), + updated_at = v_now_ts + WHERE i.instance_id = v_instance_id; + END IF; + + -- Step 4: Create execution record (idempotent) + INSERT INTO %1$I.executions (instance_id, execution_id, status, started_at) + VALUES (v_instance_id, p_execution_id, 'Running', v_now_ts) + ON CONFLICT (instance_id, execution_id) DO NOTHING; + + -- Step 5: Update instance current_execution_id + UPDATE %1$I.instances i + SET current_execution_id = GREATEST(i.current_execution_id, p_execution_id), + updated_at = v_now_ts + WHERE i.instance_id = v_instance_id; + + -- Step 6: Append history_delta (batch insert with explicit timestamps) + IF p_history_delta IS NOT NULL AND JSONB_ARRAY_LENGTH(p_history_delta) > 0 THEN + INSERT INTO %1$I.history (instance_id, execution_id, event_id, event_type, event_data, created_at) + SELECT + v_instance_id, + p_execution_id, + (elem->>'event_id')::BIGINT, + elem->>'event_type', + elem->>'event_data', + v_now_ts + FROM JSONB_ARRAY_ELEMENTS(p_history_delta) AS elem; + END IF; + + -- Step 7: Update execution status if provided + IF v_status IS NOT NULL THEN + v_completed_at := CASE + WHEN v_status IN ('Completed', 'Failed') THEN v_now_ts + ELSE NULL + END; + + UPDATE %1$I.executions e + SET status = v_status, output = v_output, completed_at = v_completed_at + WHERE e.instance_id = v_instance_id AND e.execution_id = p_execution_id; + END IF; + + -- Step 7b: Store pinned duroxide version if provided in metadata + IF p_metadata ? 'pinned_duroxide_version' AND p_metadata->'pinned_duroxide_version' IS NOT NULL + AND p_metadata->>'pinned_duroxide_version' != 'null' THEN + UPDATE %1$I.executions + SET duroxide_version_major = (p_metadata->'pinned_duroxide_version'->>'major')::INTEGER, + duroxide_version_minor = (p_metadata->'pinned_duroxide_version'->>'minor')::INTEGER, + duroxide_version_patch = (p_metadata->'pinned_duroxide_version'->>'patch')::INTEGER + WHERE instance_id = v_instance_id AND execution_id = p_execution_id; + END IF; + + -- Step 7c: Handle custom_status update on instances table + v_custom_status_action := p_metadata->>'custom_status_action'; + IF v_custom_status_action = 'set' THEN + v_custom_status_value := p_metadata->>'custom_status_value'; + UPDATE %1$I.instances + SET custom_status = v_custom_status_value, + custom_status_version = custom_status_version + 1 + WHERE instance_id = v_instance_id; + ELSIF v_custom_status_action = 'clear' THEN + UPDATE %1$I.instances + SET custom_status = NULL, + custom_status_version = custom_status_version + 1 + WHERE instance_id = v_instance_id; + END IF; + + -- Step 7d: Materialize KV mutations into kv_delta only + v_kv_mutations := p_metadata->'kv_mutations'; + IF v_kv_mutations IS NOT NULL AND jsonb_array_length(v_kv_mutations) > 0 THEN + FOR v_i IN 0..jsonb_array_length(v_kv_mutations) - 1 LOOP + v_kv_item := v_kv_mutations->v_i; + v_kv_action := v_kv_item->>'action'; + IF v_kv_action = 'set' THEN + INSERT INTO %1$I.kv_delta (instance_id, key, value, last_updated_at_ms) + VALUES (v_instance_id, v_kv_item->>'key', v_kv_item->>'value', COALESCE((v_kv_item->>'last_updated_at_ms')::BIGINT, p_now_ms)) + ON CONFLICT (instance_id, key) + DO UPDATE SET value = EXCLUDED.value, last_updated_at_ms = EXCLUDED.last_updated_at_ms; + ELSIF v_kv_action = 'clear_key' THEN + INSERT INTO %1$I.kv_delta (instance_id, key, value, last_updated_at_ms) + VALUES (v_instance_id, v_kv_item->>'key', NULL, p_now_ms) + ON CONFLICT (instance_id, key) + DO UPDATE SET value = NULL, last_updated_at_ms = EXCLUDED.last_updated_at_ms; + ELSIF v_kv_action = 'clear_all' THEN + UPDATE %1$I.kv_delta + SET value = NULL, + last_updated_at_ms = p_now_ms + WHERE instance_id = v_instance_id; + + INSERT INTO %1$I.kv_delta (instance_id, key, value, last_updated_at_ms) + SELECT ks.instance_id, ks.key, NULL, p_now_ms + FROM %1$I.kv_store ks + WHERE ks.instance_id = v_instance_id + ON CONFLICT (instance_id, key) DO NOTHING; + END IF; + END LOOP; + END IF; + + -- Step 7e: Merge kv_delta into kv_store on terminal execution boundaries + IF v_is_terminal THEN + INSERT INTO %1$I.kv_store (instance_id, key, value, execution_id, last_updated_at_ms) + SELECT kd.instance_id, kd.key, kd.value, p_execution_id, kd.last_updated_at_ms + FROM %1$I.kv_delta kd + WHERE kd.instance_id = v_instance_id AND kd.value IS NOT NULL + ON CONFLICT (instance_id, key) + DO UPDATE SET value = EXCLUDED.value, + execution_id = EXCLUDED.execution_id, + last_updated_at_ms = EXCLUDED.last_updated_at_ms; + + DELETE FROM %1$I.kv_store ks + WHERE ks.instance_id = v_instance_id + AND ks.key IN ( + SELECT kd.key + FROM %1$I.kv_delta kd + WHERE kd.instance_id = v_instance_id + AND kd.value IS NULL + ); + + DELETE FROM %1$I.kv_delta kd + WHERE kd.instance_id = v_instance_id; + END IF; + + -- Step 8: Enqueue worker items with session_id and tag support + IF p_worker_items IS NOT NULL AND JSONB_ARRAY_LENGTH(p_worker_items) > 0 THEN + FOR v_elem IN SELECT value FROM JSONB_ARRAY_ELEMENTS(p_worker_items) LOOP + IF v_elem ? 'ActivityExecute' THEN + v_item_instance_id := v_elem->'ActivityExecute'->>'instance'; + v_item_execution_id := (v_elem->'ActivityExecute'->>'execution_id')::BIGINT; + v_item_activity_id := (v_elem->'ActivityExecute'->>'id')::BIGINT; + v_item_session_id := v_elem->'ActivityExecute'->>'session_id'; + v_item_tag := v_elem->'ActivityExecute'->>'tag'; + ELSE + v_item_instance_id := NULL; + v_item_execution_id := NULL; + v_item_activity_id := NULL; + v_item_session_id := NULL; + v_item_tag := NULL; + END IF; + + INSERT INTO %1$I.worker_queue (work_item, visible_at, created_at, instance_id, execution_id, activity_id, session_id, tag) + VALUES (v_elem::TEXT, v_now_ts, v_now_ts, v_item_instance_id, v_item_execution_id, v_item_activity_id, v_item_session_id, v_item_tag); + END LOOP; + END IF; + + -- Step 9: Delete cancelled activities from worker_queue (lock stealing) + IF p_cancelled_activities IS NOT NULL AND JSONB_ARRAY_LENGTH(p_cancelled_activities) > 0 THEN + FOR v_elem IN SELECT value FROM JSONB_ARRAY_ELEMENTS(p_cancelled_activities) LOOP + DELETE FROM %1$I.worker_queue + WHERE instance_id = v_elem->>'instance' + AND execution_id = (v_elem->>'execution_id')::BIGINT + AND activity_id = (v_elem->>'activity_id')::BIGINT; + END LOOP; + END IF; + + -- Step 10: Enqueue orchestrator items + IF p_orchestrator_items IS NOT NULL AND JSONB_ARRAY_LENGTH(p_orchestrator_items) > 0 THEN + FOR v_elem IN SELECT value FROM JSONB_ARRAY_ELEMENTS(p_orchestrator_items) LOOP + IF v_elem ? 'StartOrchestration' THEN + v_item_instance_id := v_elem->'StartOrchestration'->>'instance'; + ELSIF v_elem ? 'ContinueAsNew' THEN + v_item_instance_id := v_elem->'ContinueAsNew'->>'instance'; + ELSIF v_elem ? 'TimerFired' THEN + v_item_instance_id := v_elem->'TimerFired'->>'instance'; + v_fire_at_ms := (v_elem->'TimerFired'->>'fire_at_ms')::BIGINT; + ELSIF v_elem ? 'ActivityCompleted' THEN + v_item_instance_id := v_elem->'ActivityCompleted'->>'instance'; + ELSIF v_elem ? 'ActivityFailed' THEN + v_item_instance_id := v_elem->'ActivityFailed'->>'instance'; + ELSIF v_elem ? 'ExternalRaised' THEN + v_item_instance_id := v_elem->'ExternalRaised'->>'instance'; + ELSIF v_elem ? 'CancelInstance' THEN + v_item_instance_id := v_elem->'CancelInstance'->>'instance'; + ELSIF v_elem ? 'SubOrchCompleted' THEN + v_item_instance_id := v_elem->'SubOrchCompleted'->>'parent_instance'; + ELSIF v_elem ? 'SubOrchFailed' THEN + v_item_instance_id := v_elem->'SubOrchFailed'->>'parent_instance'; + ELSIF v_elem ? 'QueueMessage' THEN + v_item_instance_id := v_elem->'QueueMessage'->>'instance'; + ELSE + v_item_instance_id := v_instance_id; + END IF; + + IF v_elem ? 'TimerFired' AND v_fire_at_ms IS NOT NULL AND v_fire_at_ms > 0 THEN + v_visible_at := TO_TIMESTAMP(v_fire_at_ms / 1000.0); + ELSE + v_visible_at := v_now_ts; + END IF; + + INSERT INTO %1$I.orchestrator_queue (instance_id, work_item, visible_at, created_at) + VALUES (v_item_instance_id, v_elem::TEXT, v_visible_at, v_now_ts); + + v_fire_at_ms := NULL; + END LOOP; + END IF; + + -- Step 11: Delete locked messages + DELETE FROM %1$I.orchestrator_queue q WHERE q.lock_token = p_lock_token; + + -- Step 12: Remove instance lock. If the lock is gone, it was released or + -- deleted after Step 1c; roll everything back rather than commit a turn + -- that no longer owns the instance. + DELETE FROM %1$I.instance_locks il + WHERE il.instance_id = v_instance_id AND il.lock_token = p_lock_token; + + GET DIAGNOSTICS v_rows_affected = ROW_COUNT; + + IF v_rows_affected = 0 THEN + RAISE EXCEPTION 'Invalid lock token'; + END IF; + END; + $ack_orch$ LANGUAGE plpgsql; +$fmt$, v_schema_name); + EXECUTE format( 'CREATE UNIQUE INDEX IF NOT EXISTS idx_instance_locks_lock_token ON %1$I.instance_locks (lock_token)', v_schema_name diff --git a/tests/deadlocks/ack_fetch.rs b/tests/deadlocks/ack_fetch.rs new file mode 100644 index 0000000..5dff51d --- /dev/null +++ b/tests/deadlocks/ack_fetch.rs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Acknowledge against fetch (migration 0026). +//! +//! Fetch takes an instance over when, by its caller's clock, the lease has +//! expired. Before migration 0026, acknowledge held no lock between its token +//! check and its commit, so a fetch from a worker whose clock runs ahead +//! could replace the token in the middle of an acknowledge and commit first. +//! The acknowledge then committed its history and new work while its deletes, +//! which match on the old token, removed nothing, and the messages it had +//! processed were delivered again. Acknowledge now takes fetch's advisory +//! lock right after its token check, so the fetch waits for it. + +use crate::harness::*; +use std::time::Duration; + +/// Acknowledge pauses after its token check, while it writes history. A fetch +/// from a worker whose clock is 120 s ahead sees the lease as expired. The +/// fetch must wait for the acknowledge instead of taking the instance over, +/// and must then find nothing to take: the messages were consumed once. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn fetch_waits_for_an_acknowledge_in_progress() { + with_schema(|schema| async move { + let database_url = database_url(); + let (_provider, instance, token) = + fetch_new_instance(&schema, Duration::from_secs(60)).await; + let pool = raw_pool(&database_url).await; + + let (ready_key, gate) = + pause_history_inserts(&pool, &database_url, &schema, &instance).await; + let ack = spawn_sql_ack( + database_url.clone(), + schema.clone(), + token.clone(), + opaque_history(1), + ); + wait_for_advisory_holder(&pool, ready_key).await; + + let fetch = spawn_sql_fetch( + database_url.clone(), + schema.clone(), + now_ms() + 120_000, + 30_000, + ); + wait_for_call_to_wait(&pool, &schema, "fetch_orchestration_item", true).await; + let held = read_lease(&pool, &schema, &instance) + .await + .expect("the instance must still be locked"); + assert_eq!( + held.token, token, + "fetch took the instance over while the acknowledge was running" + ); + + timed("gate release", gate.commit()) + .await + .expect("failed to release the paused acknowledge"); + let ack_result = timed("acknowledge", ack) + .await + .expect("acknowledge task panicked"); + let fetch_result = timed("fetch", fetch).await.expect("fetch task panicked"); + + assert_not_deadlock_victim("acknowledge", &ack_result); + assert_not_deadlock_victim("fetch", &fetch_result); + ack_result.expect("acknowledge must succeed"); + let fetched = fetch_result.expect("fetch must succeed"); + assert_eq!( + fetched, None, + "fetch must not take over an instance whose messages were acknowledged" + ); + + assert!( + read_queue(&pool, &schema, &instance).await.is_empty(), + "acknowledged messages must be consumed exactly once" + ); + assert!( + read_lease(&pool, &schema, &instance).await.is_none(), + "acknowledge must release the lock" + ); + assert_eq!(history_len(&pool, &schema, &instance).await, 1); + }) + .await; +} diff --git a/tests/deadlocks/harness.rs b/tests/deadlocks/harness.rs index 2ad10af..e196fd6 100644 --- a/tests/deadlocks/harness.rs +++ b/tests/deadlocks/harness.rs @@ -166,6 +166,157 @@ pub fn spawn_sql_renewal( }) } +/// One history event in the JSON shape the provider sends to acknowledge. Its +/// data is never decoded by these tests. +pub fn opaque_history(event_id: i64) -> serde_json::Value { + serde_json::json!([{ + "event_id": event_id, + "event_type": "TestEvent", + "event_data": "{}", + }]) +} + +/// Sends the statement the provider sends to acknowledge, once, on +/// `connection`: `history` as the history delta, no new work and no metadata +/// change. Nothing retries, so a test sees any error directly. +pub async fn sql_ack( + connection: &mut PgConnection, + schema: &str, + token: &str, + history: serde_json::Value, +) -> Result<(), sqlx::Error> { + sqlx::query(&format!( + "SELECT {schema}.ack_orchestration_item($1, $2, $3, $4, $5, $6, $7, $8)" + )) + .bind(token) + .bind(now_ms()) + .bind(1_i64) + .bind(history) + .bind(serde_json::json!([])) + .bind(serde_json::json!([])) + .bind(serde_json::json!({ + "orchestration_name": null, + "orchestration_version": null, + "status": null, + "output": null, + "parent_instance_id": null, + "pinned_duroxide_version": null, + "custom_status_action": null, + "custom_status_value": null, + "kv_mutations": [], + })) + .bind(serde_json::json!([])) + .execute(connection) + .await + .map(|_| ()) +} + +/// `sql_ack` on its own connection. +pub fn spawn_sql_ack( + database_url: String, + schema: String, + token: String, + history: serde_json::Value, +) -> JoinHandle> { + tokio::spawn(async move { + let mut connection = PgConnection::connect(&database_url).await?; + sql_ack(&mut connection, &schema, &token, history).await + }) +} + +/// Sends the statement the provider sends to fetch, once, on `connection`, +/// with the caller clock `now_ms`. Returns the instance and its new token. +pub async fn sql_fetch( + connection: &mut PgConnection, + schema: &str, + now_ms: i64, + lock_timeout_ms: i64, +) -> Result, sqlx::Error> { + sqlx::query_as(&format!( + "SELECT out_instance_id, out_lock_token + FROM {schema}.fetch_orchestration_item($1, $2, NULL, NULL)" + )) + .bind(now_ms) + .bind(lock_timeout_ms) + .fetch_optional(connection) + .await +} + +/// `sql_fetch` on its own connection. +pub fn spawn_sql_fetch( + database_url: String, + schema: String, + now_ms: i64, + lock_timeout_ms: i64, +) -> JoinHandle, sqlx::Error>> { + tokio::spawn(async move { + let mut connection = PgConnection::connect(&database_url).await?; + sql_fetch(&mut connection, &schema, now_ms, lock_timeout_ms).await + }) +} + +/// Pauses every transaction that inserts a history row for `instance`, from +/// the first such row until the returned gate transaction ends. The paused +/// transaction holds the returned ready key, which `wait_for_advisory_holder` +/// detects. Acknowledge inserts history after its token check, so this +/// pauses an acknowledge in the middle. +pub async fn pause_history_inserts( + pool: &PgPool, + database_url: &str, + schema: &str, + instance: &str, +) -> (i64, sqlx::Transaction<'static, sqlx::Postgres>) { + let ready_key = advisory_key(); + let gate_key = advisory_key(); + let gate_pool = PgPoolOptions::new() + .max_connections(1) + .connect(database_url) + .await + .expect("failed to connect gate session"); + let mut gate = gate_pool + .begin() + .await + .expect("failed to begin gate transaction"); + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(gate_key) + .execute(&mut *gate) + .await + .expect("failed to take gate advisory lock"); + install_pause_trigger_when( + pool, + schema, + "history", + "INSERT", + &format!("NEW.instance_id = $instance${instance}$instance$"), + ready_key, + gate_key, + ) + .await; + (ready_key, gate) +} + +/// Number of committed history rows of the instance. +pub async fn history_len(pool: &PgPool, schema: &str, instance: &str) -> i64 { + sqlx::query_scalar(&format!( + "SELECT count(*) FROM {schema}.history WHERE instance_id = $1" + )) + .bind(instance) + .fetch_one(pool) + .await + .expect("failed to count history rows") +} + +/// Number of worker_queue rows of the instance. +pub async fn worker_queue_len(pool: &PgPool, schema: &str, instance: &str) -> i64 { + sqlx::query_scalar(&format!( + "SELECT count(*) FROM {schema}.worker_queue WHERE instance_id = $1" + )) + .bind(instance) + .fetch_one(pool) + .await + .expect("failed to count worker_queue rows") +} + /// The instance lease and the lease on each of the instance's queue rows. #[derive(Debug)] pub struct Lease { diff --git a/tests/deadlocks/main.rs b/tests/deadlocks/main.rs index 2308a54..fbaaee6 100644 --- a/tests/deadlocks/main.rs +++ b/tests/deadlocks/main.rs @@ -4,7 +4,8 @@ //! Deadlock regression suite for the PostgreSQL provider. //! //! Each test here reproduces one way two provider calls can lock the same rows -//! in opposite orders, and fails if PostgreSQL detects a deadlock. Run the +//! in opposite orders, or interleave where they must serialize, and fails if +//! PostgreSQL detects a deadlock or the calls do not serialize. Run the //! suite alone with `cargo test --test deadlocks`. It also runs in every //! default `cargo test`, which is what CI runs. //! @@ -24,13 +25,17 @@ //! //! Modules: //! +//! - `ack_fetch`: acknowledge against a fetch that sees the lease as expired +//! (migration 0026). //! - `renew_fetch`: renewal against fetch, forced and raced (migration 0026). //! - `renew_ack_abandon`: renewal against acknowledge and abandon. //! - `victim_retry`: the provider retries a renewal aborted as a deadlock //! victim. //! - `harness`: shared helpers, also used by -//! `tests/orchestration_lock_renewal_tests.rs`. +//! `tests/orchestration_lock_renewal_tests.rs` and +//! `tests/orchestration_ack_lease_tests.rs`. +mod ack_fetch; mod harness; mod renew_ack_abandon; mod renew_fetch; @@ -39,6 +44,7 @@ mod victim_retry; /// Every source file of the suite, checked by `suite_has_no_ignored_tests`. const SOURCES: &[(&str, &str)] = &[ ("main.rs", include_str!("main.rs")), + ("ack_fetch.rs", include_str!("ack_fetch.rs")), ("harness.rs", include_str!("harness.rs")), ("renew_ack_abandon.rs", include_str!("renew_ack_abandon.rs")), ("renew_fetch.rs", include_str!("renew_fetch.rs")), diff --git a/tests/deadlocks/renew_ack_abandon.rs b/tests/deadlocks/renew_ack_abandon.rs index 5400bb7..fe5846f 100644 --- a/tests/deadlocks/renew_ack_abandon.rs +++ b/tests/deadlocks/renew_ack_abandon.rs @@ -4,17 +4,21 @@ //! Orchestration lock renewal against acknowledge and abandon (migration 0026). //! //! Acknowledge and abandon change the instance's queue rows and then delete -//! its `instance_locks` row. They do not take fetch's advisory lock. Before -//! migration 0026, renewal updated `instance_locks` first and the queue rows -//! second, the opposite order, so it could deadlock with either of them -//! (SQLSTATE 40P01). Renewal now updates the queue rows first. +//! its `instance_locks` row. Before migration 0026, renewal updated +//! `instance_locks` first and the queue rows second, the opposite order, so it +//! could deadlock with either of them (SQLSTATE 40P01). Renewal now updates +//! the queue rows first. Since migration 0026, acknowledge also takes fetch's +//! advisory lock, which renewal takes too, so renewal waits for an +//! acknowledge on that lock before it touches any row. Abandon takes no +//! advisory lock, so against abandon the row order is what prevents the +//! deadlock. //! //! Each test pauses acknowledge or abandon after its queue change and starts -//! a renewal. Renewal must wait for the queue rows without holding the -//! `instance_locks` row, and must fail as released once the other call -//! commits. Both calls send the provider's statement once, on their own -//! connections, so a deadlock shows as SQLSTATE 40P01 instead of being -//! retried away. +//! a renewal. Renewal must wait (on the advisory lock for acknowledge, on the +//! queue rows for abandon) without holding the `instance_locks` row, and must +//! fail as released once the other call commits. Both calls send the +//! provider's statement once, on their own connections, so a deadlock shows +//! as SQLSTATE 40P01 instead of being retried away. use crate::harness::*; use sqlx::postgres::PgConnection; @@ -53,6 +57,12 @@ impl Release { } } + /// Whether renewal waits for this call on the advisory lock (acknowledge + /// takes it) or on the queue rows (abandon does not). + fn renewal_waits_on_advisory_lock(self) -> bool { + self == Release::Acknowledge + } + /// Sends the statement `PostgresProvider` sends for this call once, on its /// own connection. fn spawn( @@ -65,30 +75,9 @@ impl Release { let mut connection = PgConnection::connect(&database_url).await?; match self { // A turn with no history, no new work and default metadata. - Release::Acknowledge => sqlx::query(&format!( - "SELECT {schema}.ack_orchestration_item($1, $2, $3, $4, $5, $6, $7, $8)" - )) - .bind(&token) - .bind(now_ms()) - .bind(1_i64) - .bind(serde_json::json!([])) - .bind(serde_json::json!([])) - .bind(serde_json::json!([])) - .bind(serde_json::json!({ - "orchestration_name": null, - "orchestration_version": null, - "status": null, - "output": null, - "parent_instance_id": null, - "pinned_duroxide_version": null, - "custom_status_action": null, - "custom_status_value": null, - "kv_mutations": [], - })) - .bind(serde_json::json!([])) - .execute(&mut connection) - .await - .map(|_| ()), + Release::Acknowledge => { + sql_ack(&mut connection, &schema, &token, serde_json::json!([])).await + } Release::Abandon => sqlx::query(&format!( "SELECT {schema}.abandon_orchestration_item($1, $2, NULL, false)" )) @@ -142,7 +131,13 @@ async fn renew_while_releasing(release: Release) { wait_for_advisory_holder(&pool, ready_key).await; let renewal = spawn_sql_renewal(database_url.clone(), schema.clone(), token.clone(), 60); - wait_for_call_to_wait(&pool, &schema, "renew_orchestration_item_lock", false).await; + wait_for_call_to_wait( + &pool, + &schema, + "renew_orchestration_item_lock", + release.renewal_waits_on_advisory_lock(), + ) + .await; // The paused call has not reached instance_locks yet, so only renewal // can hold that row now. let renewal_held_instance_row = instance_lock_row_is_held(&pool, &schema, &instance).await; @@ -190,9 +185,10 @@ async fn renew_while_releasing(release: Release) { } /// Acknowledge pauses after it deletes the instance's queue rows and before it -/// deletes the instance lock. Renewal must wait for the queue rows without -/// holding the instance lock; once acknowledge commits, renewal must fail -/// because the lock was released. Opposite row orders deadlock here. +/// deletes the instance lock. Renewal must wait for acknowledge's advisory +/// lock without holding the instance lock; once acknowledge commits, renewal +/// must fail because the lock was released. Opposite row orders deadlock here +/// when neither takes the advisory lock. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn renewal_and_acknowledge_lock_rows_in_the_same_order() { renew_while_releasing(Release::Acknowledge).await; diff --git a/tests/orchestration_ack_lease_tests.rs b/tests/orchestration_ack_lease_tests.rs new file mode 100644 index 0000000..74cfde8 --- /dev/null +++ b/tests/orchestration_ack_lease_tests.rs @@ -0,0 +1,366 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Orchestration acknowledge against losing its lease (migration 0026). +//! +//! Acknowledge checks its lock token, writes the turn (history, new work), +//! and finally deletes the messages it processed and the instance lock, both +//! by token. Fetch takes an instance over when, by its caller's clock, the +//! lease has expired: a worker whose clock runs ahead, or an acknowledge that +//! stalled. Before migration 0026, nothing stopped such a fetch between the +//! token check and the commit. The acknowledge then committed the turn while +//! its deletes matched no row, so the processed messages were delivered +//! again. Duroxide does not de-duplicate redelivered queue messages or +//! external events, so the orchestration processed them twice. +//! +//! Acknowledge now takes fetch's advisory lock after its token check, checks +//! the token again, and fails if its instance lock is gone when it deletes it. +//! These tests change the lease at each point of an acknowledge and check +//! that the turn commits exactly once. The fetch against an acknowledge in +//! progress is in `tests/deadlocks/ack_fetch.rs`. + +#[path = "deadlocks/harness.rs"] +mod harness; + +use duroxide::providers::Provider; +use duroxide::runtime::registry::ActivityRegistry; +use duroxide::runtime::{self, OrchestrationStatus, RuntimeOptions}; +use duroxide::{ActivityContext, Client, EventKind, OrchestrationContext, OrchestrationRegistry}; +use duroxide_pg::PostgresProvider; +use harness::*; +use sqlx::postgres::PgConnection; +use sqlx::Connection; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +/// A fetch from a worker whose clock runs 120 s ahead takes the instance over +/// while the acknowledge waits for the advisory lock, that is, after its +/// first token check. The acknowledge must fail and commit nothing. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn toctou_fetch_takes_over_while_acknowledge_waits() { + with_schema(|schema| async move { + let database_url = database_url(); + let (_provider, instance, token) = + fetch_new_instance(&schema, Duration::from_secs(60)).await; + let pool = raw_pool(&database_url).await; + + let mut gate_connection = PgConnection::connect(&database_url) + .await + .expect("failed to connect gate session"); + let mut gate = gate_connection + .begin() + .await + .expect("failed to begin gate transaction"); + sqlx::query("SELECT pg_advisory_xact_lock(hashtext($1))") + .bind(&instance) + .execute(&mut *gate) + .await + .expect("failed to take the instance advisory lock"); + + let ack = spawn_sql_ack( + database_url.clone(), + schema.clone(), + token.clone(), + opaque_history(1), + ); + wait_for_call_to_wait(&pool, &schema, "ack_orchestration_item", true).await; + assert_eq!( + history_len(&pool, &schema, &instance).await, + 0, + "acknowledge wrote history before it got the advisory lock" + ); + + // The takeover runs in the transaction that holds the advisory lock; + // PostgreSQL grants it again to the same session. + let (fetched, new_token) = timed( + "takeover fetch", + sql_fetch(&mut *gate, &schema, now_ms() + 120_000, 30_000), + ) + .await + .expect("takeover fetch failed") + .expect("takeover fetch must take the instance"); + assert_eq!(fetched, instance); + assert_ne!(new_token, token); + + timed("gate release", gate.commit()) + .await + .expect("failed to release the instance advisory lock"); + let result = timed("acknowledge", ack) + .await + .expect("acknowledge task panicked"); + + assert_not_deadlock_victim("acknowledge", &result); + let error = result.expect_err("acknowledge must fail once its lease was taken over"); + assert!( + error.to_string().contains("Invalid lock token"), + "acknowledge must fail on its token: {error}" + ); + assert_eq!( + history_len(&pool, &schema, &instance).await, + 0, + "a failed acknowledge must not commit history" + ); + let lease = read_lease(&pool, &schema, &instance) + .await + .expect("the new owner must hold the lock"); + assert_eq!(lease.token, new_token); + lease.assert_queue_matches(); + }) + .await; +} + +/// The instance lock disappears while the acknowledge writes the turn (as +/// when an administrator deletes the instance). The acknowledge must fail and +/// roll back the turn, instead of committing a turn that no longer owns the +/// instance. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn acknowledge_rolls_back_when_its_lock_disappears() { + with_schema(|schema| async move { + let database_url = database_url(); + let (_provider, instance, token) = + fetch_new_instance(&schema, Duration::from_secs(60)).await; + let pool = raw_pool(&database_url).await; + + let (ready_key, gate) = + pause_history_inserts(&pool, &database_url, &schema, &instance).await; + let ack = spawn_sql_ack( + database_url.clone(), + schema.clone(), + token.clone(), + opaque_history(1), + ); + wait_for_advisory_holder(&pool, ready_key).await; + + let deleted = sqlx::query(&format!( + "DELETE FROM {schema}.instance_locks WHERE instance_id = $1" + )) + .bind(&instance) + .execute(&pool) + .await + .expect("failed to delete the instance lock") + .rows_affected(); + assert_eq!(deleted, 1); + + timed("gate release", gate.commit()) + .await + .expect("failed to release the paused acknowledge"); + let result = timed("acknowledge", ack) + .await + .expect("acknowledge task panicked"); + + assert_not_deadlock_victim("acknowledge", &result); + let error = result.expect_err("acknowledge must fail when its lock is gone"); + assert!( + error.to_string().contains("Invalid lock token"), + "acknowledge must fail on its token: {error}" + ); + assert_eq!( + history_len(&pool, &schema, &instance).await, + 0, + "the turn must roll back" + ); + let queue = read_queue(&pool, &schema, &instance).await; + assert!(!queue.is_empty(), "the processed messages must stay queued"); + assert!( + queue.iter().all(|(row_token, _)| row_token.as_deref() == Some(token.as_str())), + "the processed messages must not be deleted: {queue:?}" + ); + }) + .await; +} + +/// Control: the takeover commits before the acknowledge starts. The token +/// check fails, as it does without migration 0026. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn acknowledge_fails_after_a_takeover() { + with_schema(|schema| async move { + let database_url = database_url(); + let (_provider, instance, token) = + fetch_new_instance(&schema, Duration::from_secs(60)).await; + let pool = raw_pool(&database_url).await; + + let mut other = PgConnection::connect(&database_url) + .await + .expect("failed to connect the other worker"); + let (fetched, new_token) = sql_fetch(&mut other, &schema, now_ms() + 120_000, 30_000) + .await + .expect("takeover fetch failed") + .expect("takeover fetch must take the instance"); + assert_eq!(fetched, instance); + + let result = timed( + "acknowledge", + spawn_sql_ack( + database_url.clone(), + schema.clone(), + token.clone(), + opaque_history(1), + ), + ) + .await + .expect("acknowledge task panicked"); + let error = result.expect_err("acknowledge must fail after a takeover"); + assert!( + error.to_string().contains("Invalid lock token"), + "acknowledge must fail on its token: {error}" + ); + assert_eq!(history_len(&pool, &schema, &instance).await, 0); + let lease = read_lease(&pool, &schema, &instance) + .await + .expect("the new owner must hold the lock"); + assert_eq!(lease.token, new_token); + lease.assert_queue_matches(); + }) + .await; +} + +const ORDERS: &str = "LostLeaseOrders"; +const QUEUE: &str = "orders"; + +/// End to end with the duroxide runtime. The orchestration takes two orders +/// from a queue and charges each. Order 1 is enqueued once. While the runtime +/// acknowledges the turn that processed it, a worker whose clock runs 5 s +/// ahead tries to fetch the instance. That worker must wait, and order 1 must +/// be charged exactly once. Without migration 0026 the other worker takes the +/// instance over, the acknowledge still commits, and order 1 is delivered and +/// charged a second time. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn runtime_charges_an_order_once_when_another_worker_fetches_during_the_ack() { + with_schema(|schema| async move { + let database_url = database_url(); + let pool = raw_pool(&database_url).await; + let provider: Arc = Arc::new( + PostgresProvider::new_with_schema(&database_url, Some(&schema)) + .await + .expect("failed to create provider"), + ); + + let charges: Arc>> = Arc::new(Mutex::new(Vec::new())); + let charged = charges.clone(); + let activities = ActivityRegistry::builder() + .register("Charge", move |_ctx: ActivityContext, order: String| { + let charged = charged.clone(); + async move { + charged.lock().expect("charges lock").push(order.clone()); + Ok(format!("charged:{order}")) + } + }) + .build(); + let orchestrations = OrchestrationRegistry::builder() + .register(ORDERS, |ctx: OrchestrationContext, _input: String| async move { + let mut charged = Vec::new(); + for _ in 0..2 { + let order = ctx.dequeue_event(QUEUE).await; + charged.push(ctx.schedule_activity("Charge", order).await?); + } + Ok(charged.join(",")) + }) + .build(); + let options = RuntimeOptions { + dispatcher_min_poll_interval: Duration::from_millis(10), + orchestrator_lock_timeout: Duration::from_secs(2), + ..Default::default() + }; + let rt = + runtime::Runtime::start_with_options(provider.clone(), activities, orchestrations, options) + .await; + let client = Client::new(provider.clone()); + let instance = format!("orders-{}", uuid::Uuid::new_v4()); + client + .start_orchestration(&instance, ORDERS, "") + .await + .expect("failed to start the orchestration"); + wait_for_history(&*provider, &instance, "waiting for the first order", |kind| { + matches!(kind, EventKind::QueueSubscribed { .. }) + }) + .await; + + let (ready_key, gate) = + pause_history_inserts(&pool, &database_url, &schema, &instance).await; + client + .enqueue_event(&instance, QUEUE, "order-1") + .await + .expect("failed to enqueue order 1"); + wait_for_advisory_holder(&pool, ready_key).await; + let owner = read_lease(&pool, &schema, &instance) + .await + .expect("the runtime must hold the lease while it acknowledges"); + + let mut other = PgConnection::connect(&database_url) + .await + .expect("failed to connect the other worker"); + let other_pid = backend_pid(&mut other).await; + let other_schema = schema.clone(); + let other_fetch = tokio::spawn(async move { + sql_fetch(&mut other, &other_schema, now_ms() + 5_000, 2_000).await + }); + wait_for_lock_waiter(&pool, other_pid).await; + assert_eq!( + read_lease(&pool, &schema, &instance) + .await + .map(|lease| lease.token), + Some(owner.token.clone()), + "the other worker took the instance over during the acknowledge" + ); + + timed("gate release", gate.commit()) + .await + .expect("failed to release the paused acknowledge"); + let other_result = timed("other worker's fetch", other_fetch) + .await + .expect("other worker's fetch panicked"); + assert_not_deadlock_victim("other worker's fetch", &other_result); + other_result.expect("the other worker's fetch must succeed"); + + wait_for_history(&*provider, &instance, "the acknowledge of order 1", |kind| { + matches!(kind, EventKind::ActivityScheduled { .. }) + }) + .await; + let redelivered: i64 = sqlx::query_scalar(&format!( + "SELECT count(*) FROM {schema}.orchestrator_queue + WHERE instance_id = $1 AND work_item LIKE '%QueueMessage%'" + )) + .bind(&instance) + .fetch_one(&pool) + .await + .expect("failed to count queue messages"); + assert_eq!(redelivered, 0, "order 1 must leave the queue with its turn"); + + client + .enqueue_event(&instance, QUEUE, "order-2") + .await + .expect("failed to enqueue order 2"); + let status = client + .wait_for_orchestration(&instance, Duration::from_secs(45)) + .await; + let charged = charges.lock().expect("charges lock").clone(); + rt.shutdown(Some(5_000)).await; + + match status { + Ok(OrchestrationStatus::Completed { output, .. }) => { + assert_eq!(output, "charged:order-1,charged:order-2"); + } + other => panic!("the orchestration did not complete: {other:?}"), + } + assert_eq!(charged, vec!["order-1".to_string(), "order-2".to_string()]); + }) + .await; +} + +/// Waits until the instance's history has an event that `matches`. +async fn wait_for_history( + provider: &dyn Provider, + instance: &str, + what: &str, + matches: impl Fn(&EventKind) -> bool, +) { + let deadline = Instant::now() + STEP_TIMEOUT; + loop { + let history = provider.read(instance).await.unwrap_or_default(); + if history.iter().any(|event| matches(&event.kind)) { + return; + } + assert!(Instant::now() < deadline, "timed out waiting for {what}"); + tokio::time::sleep(POLL_INTERVAL).await; + } +} diff --git a/tests/orchestration_lock_renewal_tests.rs b/tests/orchestration_lock_renewal_tests.rs index 93cdb6e..018ca79 100644 --- a/tests/orchestration_lock_renewal_tests.rs +++ b/tests/orchestration_lock_renewal_tests.rs @@ -18,7 +18,7 @@ #[path = "deadlocks/harness.rs"] mod harness; -use duroxide::providers::{ExecutionMetadata, Provider}; +use duroxide::providers::Provider; use duroxide_pg::PostgresProvider; use harness::*; use sqlx::postgres::PgConnection; @@ -61,10 +61,11 @@ enum Expected { /// The test holds the advisory lock that fetch and renewal take for the /// instance. Renewal takes that lock only after its token lookup passed, so a /// renewal seen waiting on it is between its check and its use. The -/// interleaving runs while renewal waits: fetch and renewal inside the -/// transaction that holds the lock (PostgreSQL grants it again to the same -/// session), acknowledge and abandon on their own connections (they do not -/// take the advisory lock). Committing that transaction lets renewal continue. +/// interleaving runs while renewal waits: fetch, acknowledge and renewal +/// inside the transaction that holds the lock (they take it too, and +/// PostgreSQL grants it again to the same session), abandon on its own +/// connection (it does not take the advisory lock). Committing that +/// transaction lets renewal continue. async fn renew_across(interleaving: Interleaving) { with_schema(move |schema| async move { let database_url = database_url(); @@ -144,15 +145,7 @@ async fn renew_across(interleaving: Interleaving) { Interleaving::Acknowledged => { timed( "acknowledge", - provider.ack_orchestration_item( - &token, - 1, - vec![], - vec![], - vec![], - ExecutionMetadata::default(), - vec![], - ), + sql_ack(&mut *gate, &schema, &token, serde_json::json!([])), ) .await .expect("acknowledge must succeed while renewal waits"); From a470b7495eef418e243f46cbd792bbaf3a40fe22 Mon Sep 17 00:00:00 2001 From: "Chumbucket (Waldemort)" Date: Sun, 25 Oct 2026 20:42:02 +0000 Subject: [PATCH 14/15] docs: regenerate the migration 0026 diff for acknowledge 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> --- migrations/0026_diff.md | 320 +++++++++++++++++- ...serialize_orchestration_lock_mutations.sql | 7 +- tests/orchestration_ack_lease_tests.rs | 53 +-- tests/orchestration_lock_renewal_tests.rs | 2 +- 4 files changed, 341 insertions(+), 41 deletions(-) diff --git a/migrations/0026_diff.md b/migrations/0026_diff.md index c54e976..6b2ca98 100644 --- a/migrations/0026_diff.md +++ b/migrations/0026_diff.md @@ -6,8 +6,6 @@ Each changed function is shown **in full** with `+`/`-` markers on changed lines ## Table Changes -None. - ## New Indexes ### `idx_instance_locks_lock_token` @@ -17,7 +15,306 @@ CREATE UNIQUE INDEX idx_instance_locks_lock_token ON SCHEMA.instance_locks USING ## Function Changes -### `renew_orchestration_item_lock` — body modified (baseline: 0004) +### `ack_orchestration_item` — Body Modified + +Full function with diff: +```diff + CREATE OR REPLACE FUNCTION SCHEMA.ack_orchestration_item(p_lock_token text, p_now_ms bigint, p_execution_id bigint, p_history_delta jsonb, p_worker_items jsonb, p_orchestrator_items jsonb, p_metadata jsonb, p_cancelled_activities jsonb DEFAULT '[]'::jsonb) + RETURNS void + LANGUAGE plpgsql + AS $function$ + DECLARE + v_instance_id TEXT; + v_orchestration_name TEXT; + v_orchestration_version TEXT; + v_parent_instance_id TEXT; + v_status TEXT; + v_output TEXT; + v_completed_at TIMESTAMPTZ; + v_elem JSONB; + v_visible_at TIMESTAMPTZ; + v_fire_at_ms BIGINT; + v_item_instance_id TEXT; + v_item_execution_id BIGINT; + v_item_activity_id BIGINT; + v_item_session_id TEXT; + v_item_tag TEXT; + v_now_ts TIMESTAMPTZ; + v_custom_status_action TEXT; + v_custom_status_value TEXT; + v_current_execution_id BIGINT; + v_kv_mutations JSONB; + v_kv_item JSONB; + v_kv_action TEXT; + v_i INTEGER; + v_is_terminal BOOLEAN; ++ v_rows_affected INTEGER; + BEGIN + -- Convert Rust-supplied millisecond timestamp to TIMESTAMPTZ + v_now_ts := TO_TIMESTAMP(p_now_ms / 1000.0); + + -- Step 1: Validate lock token + SELECT il.instance_id INTO v_instance_id + FROM SCHEMA.instance_locks il + WHERE il.lock_token = p_lock_token AND il.locked_until > p_now_ms; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Invalid lock token'; + END IF; + ++ -- Step 1b: Take the advisory lock that fetch_orchestration_item takes ++ -- before it can take an instance over. Step 1 holds no lock, so a ++ -- fetch that judged the lease expired could otherwise replace the ++ -- token while this acknowledge runs. This acknowledge would then ++ -- commit its history and new work while its deletes below match no ++ -- rows, and the messages it processed would be delivered again. ++ PERFORM pg_advisory_xact_lock(hashtext(v_instance_id)); ++ ++ -- Step 1c: Revalidate the token after the wait. While this lock is ++ -- held, no fetch can replace it. ++ PERFORM 1 ++ FROM SCHEMA.instance_locks il ++ WHERE il.instance_id = v_instance_id ++ AND il.lock_token = p_lock_token; ++ ++ IF NOT FOUND THEN ++ RAISE EXCEPTION 'Invalid lock token'; ++ END IF; ++ + -- Step 2: Extract metadata from JSONB + v_orchestration_name := p_metadata->>'orchestration_name'; + v_orchestration_version := p_metadata->>'orchestration_version'; + v_parent_instance_id := p_metadata->>'parent_instance_id'; + v_status := p_metadata->>'status'; + v_output := p_metadata->>'output'; + v_current_execution_id := p_execution_id; + v_is_terminal := v_status IN ('Completed', 'ContinuedAsNew', 'Failed'); + + -- Step 3: Create or update instance metadata (with explicit timestamps) + IF v_orchestration_name IS NOT NULL AND v_orchestration_version IS NOT NULL THEN + INSERT INTO SCHEMA.instances (instance_id, orchestration_name, orchestration_version, current_execution_id, parent_instance_id, created_at, updated_at) + VALUES (v_instance_id, v_orchestration_name, v_orchestration_version, p_execution_id, v_parent_instance_id, v_now_ts, v_now_ts) + ON CONFLICT (instance_id) DO NOTHING; + + UPDATE SCHEMA.instances i + SET orchestration_name = v_orchestration_name, + orchestration_version = v_orchestration_version, + parent_instance_id = COALESCE(i.parent_instance_id, v_parent_instance_id), + updated_at = v_now_ts + WHERE i.instance_id = v_instance_id; + END IF; + + -- Step 4: Create execution record (idempotent) + INSERT INTO SCHEMA.executions (instance_id, execution_id, status, started_at) + VALUES (v_instance_id, p_execution_id, 'Running', v_now_ts) + ON CONFLICT (instance_id, execution_id) DO NOTHING; + + -- Step 5: Update instance current_execution_id + UPDATE SCHEMA.instances i + SET current_execution_id = GREATEST(i.current_execution_id, p_execution_id), + updated_at = v_now_ts + WHERE i.instance_id = v_instance_id; + + -- Step 6: Append history_delta (batch insert with explicit timestamps) + IF p_history_delta IS NOT NULL AND JSONB_ARRAY_LENGTH(p_history_delta) > 0 THEN + INSERT INTO SCHEMA.history (instance_id, execution_id, event_id, event_type, event_data, created_at) + SELECT + v_instance_id, + p_execution_id, + (elem->>'event_id')::BIGINT, + elem->>'event_type', + elem->>'event_data', + v_now_ts + FROM JSONB_ARRAY_ELEMENTS(p_history_delta) AS elem; + END IF; + + -- Step 7: Update execution status if provided + IF v_status IS NOT NULL THEN + v_completed_at := CASE + WHEN v_status IN ('Completed', 'Failed') THEN v_now_ts + ELSE NULL + END; + + UPDATE SCHEMA.executions e + SET status = v_status, output = v_output, completed_at = v_completed_at + WHERE e.instance_id = v_instance_id AND e.execution_id = p_execution_id; + END IF; + + -- Step 7b: Store pinned duroxide version if provided in metadata + IF p_metadata ? 'pinned_duroxide_version' AND p_metadata->'pinned_duroxide_version' IS NOT NULL + AND p_metadata->>'pinned_duroxide_version' != 'null' THEN + UPDATE SCHEMA.executions + SET duroxide_version_major = (p_metadata->'pinned_duroxide_version'->>'major')::INTEGER, + duroxide_version_minor = (p_metadata->'pinned_duroxide_version'->>'minor')::INTEGER, + duroxide_version_patch = (p_metadata->'pinned_duroxide_version'->>'patch')::INTEGER + WHERE instance_id = v_instance_id AND execution_id = p_execution_id; + END IF; + + -- Step 7c: Handle custom_status update on instances table + v_custom_status_action := p_metadata->>'custom_status_action'; + IF v_custom_status_action = 'set' THEN + v_custom_status_value := p_metadata->>'custom_status_value'; + UPDATE SCHEMA.instances + SET custom_status = v_custom_status_value, + custom_status_version = custom_status_version + 1 + WHERE instance_id = v_instance_id; + ELSIF v_custom_status_action = 'clear' THEN + UPDATE SCHEMA.instances + SET custom_status = NULL, + custom_status_version = custom_status_version + 1 + WHERE instance_id = v_instance_id; + END IF; + + -- Step 7d: Materialize KV mutations into kv_delta only + v_kv_mutations := p_metadata->'kv_mutations'; + IF v_kv_mutations IS NOT NULL AND jsonb_array_length(v_kv_mutations) > 0 THEN + FOR v_i IN 0..jsonb_array_length(v_kv_mutations) - 1 LOOP + v_kv_item := v_kv_mutations->v_i; + v_kv_action := v_kv_item->>'action'; + IF v_kv_action = 'set' THEN + INSERT INTO SCHEMA.kv_delta (instance_id, key, value, last_updated_at_ms) + VALUES (v_instance_id, v_kv_item->>'key', v_kv_item->>'value', COALESCE((v_kv_item->>'last_updated_at_ms')::BIGINT, p_now_ms)) + ON CONFLICT (instance_id, key) + DO UPDATE SET value = EXCLUDED.value, last_updated_at_ms = EXCLUDED.last_updated_at_ms; + ELSIF v_kv_action = 'clear_key' THEN + INSERT INTO SCHEMA.kv_delta (instance_id, key, value, last_updated_at_ms) + VALUES (v_instance_id, v_kv_item->>'key', NULL, p_now_ms) + ON CONFLICT (instance_id, key) + DO UPDATE SET value = NULL, last_updated_at_ms = EXCLUDED.last_updated_at_ms; + ELSIF v_kv_action = 'clear_all' THEN + UPDATE SCHEMA.kv_delta + SET value = NULL, + last_updated_at_ms = p_now_ms + WHERE instance_id = v_instance_id; + + INSERT INTO SCHEMA.kv_delta (instance_id, key, value, last_updated_at_ms) + SELECT ks.instance_id, ks.key, NULL, p_now_ms + FROM SCHEMA.kv_store ks + WHERE ks.instance_id = v_instance_id + ON CONFLICT (instance_id, key) DO NOTHING; + END IF; + END LOOP; + END IF; + + -- Step 7e: Merge kv_delta into kv_store on terminal execution boundaries + IF v_is_terminal THEN + INSERT INTO SCHEMA.kv_store (instance_id, key, value, execution_id, last_updated_at_ms) + SELECT kd.instance_id, kd.key, kd.value, p_execution_id, kd.last_updated_at_ms + FROM SCHEMA.kv_delta kd + WHERE kd.instance_id = v_instance_id AND kd.value IS NOT NULL + ON CONFLICT (instance_id, key) + DO UPDATE SET value = EXCLUDED.value, + execution_id = EXCLUDED.execution_id, + last_updated_at_ms = EXCLUDED.last_updated_at_ms; + + DELETE FROM SCHEMA.kv_store ks + WHERE ks.instance_id = v_instance_id + AND ks.key IN ( + SELECT kd.key + FROM SCHEMA.kv_delta kd + WHERE kd.instance_id = v_instance_id + AND kd.value IS NULL + ); + + DELETE FROM SCHEMA.kv_delta kd + WHERE kd.instance_id = v_instance_id; + END IF; + + -- Step 8: Enqueue worker items with session_id and tag support + IF p_worker_items IS NOT NULL AND JSONB_ARRAY_LENGTH(p_worker_items) > 0 THEN + FOR v_elem IN SELECT value FROM JSONB_ARRAY_ELEMENTS(p_worker_items) LOOP + IF v_elem ? 'ActivityExecute' THEN + v_item_instance_id := v_elem->'ActivityExecute'->>'instance'; + v_item_execution_id := (v_elem->'ActivityExecute'->>'execution_id')::BIGINT; + v_item_activity_id := (v_elem->'ActivityExecute'->>'id')::BIGINT; + v_item_session_id := v_elem->'ActivityExecute'->>'session_id'; + v_item_tag := v_elem->'ActivityExecute'->>'tag'; + ELSE + v_item_instance_id := NULL; + v_item_execution_id := NULL; + v_item_activity_id := NULL; + v_item_session_id := NULL; + v_item_tag := NULL; + END IF; + + INSERT INTO SCHEMA.worker_queue (work_item, visible_at, created_at, instance_id, execution_id, activity_id, session_id, tag) + VALUES (v_elem::TEXT, v_now_ts, v_now_ts, v_item_instance_id, v_item_execution_id, v_item_activity_id, v_item_session_id, v_item_tag); + END LOOP; + END IF; + + -- Step 9: Delete cancelled activities from worker_queue (lock stealing) + IF p_cancelled_activities IS NOT NULL AND JSONB_ARRAY_LENGTH(p_cancelled_activities) > 0 THEN + FOR v_elem IN SELECT value FROM JSONB_ARRAY_ELEMENTS(p_cancelled_activities) LOOP + DELETE FROM SCHEMA.worker_queue + WHERE instance_id = v_elem->>'instance' + AND execution_id = (v_elem->>'execution_id')::BIGINT + AND activity_id = (v_elem->>'activity_id')::BIGINT; + END LOOP; + END IF; + + -- Step 10: Enqueue orchestrator items + IF p_orchestrator_items IS NOT NULL AND JSONB_ARRAY_LENGTH(p_orchestrator_items) > 0 THEN + FOR v_elem IN SELECT value FROM JSONB_ARRAY_ELEMENTS(p_orchestrator_items) LOOP + IF v_elem ? 'StartOrchestration' THEN + v_item_instance_id := v_elem->'StartOrchestration'->>'instance'; + ELSIF v_elem ? 'ContinueAsNew' THEN + v_item_instance_id := v_elem->'ContinueAsNew'->>'instance'; + ELSIF v_elem ? 'TimerFired' THEN + v_item_instance_id := v_elem->'TimerFired'->>'instance'; + v_fire_at_ms := (v_elem->'TimerFired'->>'fire_at_ms')::BIGINT; + ELSIF v_elem ? 'ActivityCompleted' THEN + v_item_instance_id := v_elem->'ActivityCompleted'->>'instance'; + ELSIF v_elem ? 'ActivityFailed' THEN + v_item_instance_id := v_elem->'ActivityFailed'->>'instance'; + ELSIF v_elem ? 'ExternalRaised' THEN + v_item_instance_id := v_elem->'ExternalRaised'->>'instance'; + ELSIF v_elem ? 'CancelInstance' THEN + v_item_instance_id := v_elem->'CancelInstance'->>'instance'; + ELSIF v_elem ? 'SubOrchCompleted' THEN + v_item_instance_id := v_elem->'SubOrchCompleted'->>'parent_instance'; + ELSIF v_elem ? 'SubOrchFailed' THEN + v_item_instance_id := v_elem->'SubOrchFailed'->>'parent_instance'; + ELSIF v_elem ? 'QueueMessage' THEN + v_item_instance_id := v_elem->'QueueMessage'->>'instance'; + ELSE + v_item_instance_id := v_instance_id; + END IF; + + IF v_elem ? 'TimerFired' AND v_fire_at_ms IS NOT NULL AND v_fire_at_ms > 0 THEN + v_visible_at := TO_TIMESTAMP(v_fire_at_ms / 1000.0); + ELSE + v_visible_at := v_now_ts; + END IF; + + INSERT INTO SCHEMA.orchestrator_queue (instance_id, work_item, visible_at, created_at) + VALUES (v_item_instance_id, v_elem::TEXT, v_visible_at, v_now_ts); + + v_fire_at_ms := NULL; + END LOOP; + END IF; + + -- Step 11: Delete locked messages + DELETE FROM SCHEMA.orchestrator_queue q WHERE q.lock_token = p_lock_token; + +- -- Step 12: Remove instance lock ++ -- Step 12: Remove instance lock. If the lock is gone, it was released or ++ -- deleted after Step 1c; roll everything back rather than commit a turn ++ -- that no longer owns the instance. + DELETE FROM SCHEMA.instance_locks il + WHERE il.instance_id = v_instance_id AND il.lock_token = p_lock_token; ++ ++ GET DIAGNOSTICS v_rows_affected = ROW_COUNT; ++ ++ IF v_rows_affected = 0 THEN ++ RAISE EXCEPTION 'Invalid lock token'; ++ END IF; + END; + $function$ +\ No newline at end of file + +``` + +### `renew_orchestration_item_lock` — Body Modified Full function with diff: ```diff @@ -84,21 +381,8 @@ Full function with diff: + END IF; END; $function$ +\ No newline at end of file ``` -## Notes - -- Generated with `scripts/generate_migration_diff.sh 26` against PostgreSQL 15.19. -- Signature is unchanged, so the migration uses `CREATE OR REPLACE`; the - function keeps its OID and `EXECUTE` grants. -- Renewal takes the per-instance advisory lock that `fetch_orchestration_item` - takes, then reads the time again with the clock rule from migration `0025`. - The expiry check and the new deadline use that time, and the deadline never - moves earlier. -- Queue rows are updated before the instance lock, the order used by - `ack_orchestration_item` and `abandon_orchestration_item`. -- `idx_instance_locks_lock_token` serves the token lookups in - `renew_orchestration_item_lock`, `ack_orchestration_item` and - `abandon_orchestration_item`, which scanned `instance_locks` before. It is - unique because a token must name exactly one instance. +--- diff --git a/migrations/0026_serialize_orchestration_lock_mutations.sql b/migrations/0026_serialize_orchestration_lock_mutations.sql index dab9970..07a5c7c 100644 --- a/migrations/0026_serialize_orchestration_lock_mutations.sql +++ b/migrations/0026_serialize_orchestration_lock_mutations.sql @@ -21,9 +21,10 @@ -- 4. Revalidates the token and expiry at that time, and never moves the -- deadline earlier. -- 5. Updates orchestrator_queue before instance_locks. This is the order of --- ack_orchestration_item and abandon_orchestration_item, which do not --- take the advisory lock; the opposite order lets renewal deadlock with --- them. The advisory lock keeps fetch out whatever the row order. +-- ack_orchestration_item and abandon_orchestration_item. Abandon does +-- not take the advisory lock, and the opposite order lets renewal +-- deadlock with it. Fetch, and acknowledge since this migration (below), +-- take the advisory lock, which keeps them out whatever the row order. -- If acknowledge or abandon releases the lock first, the final update matches -- no row and the function raises, which rolls back the queue update. -- diff --git a/tests/orchestration_ack_lease_tests.rs b/tests/orchestration_ack_lease_tests.rs index 74cfde8..845bacf 100644 --- a/tests/orchestration_ack_lease_tests.rs +++ b/tests/orchestration_ack_lease_tests.rs @@ -74,7 +74,7 @@ async fn toctou_fetch_takes_over_while_acknowledge_waits() { // PostgreSQL grants it again to the same session. let (fetched, new_token) = timed( "takeover fetch", - sql_fetch(&mut *gate, &schema, now_ms() + 120_000, 30_000), + sql_fetch(&mut gate, &schema, now_ms() + 120_000, 30_000), ) .await .expect("takeover fetch failed") @@ -162,7 +162,9 @@ async fn acknowledge_rolls_back_when_its_lock_disappears() { let queue = read_queue(&pool, &schema, &instance).await; assert!(!queue.is_empty(), "the processed messages must stay queued"); assert!( - queue.iter().all(|(row_token, _)| row_token.as_deref() == Some(token.as_str())), + queue + .iter() + .all(|(row_token, _)| row_token.as_deref() == Some(token.as_str())), "the processed messages must not be deleted: {queue:?}" ); }) @@ -247,32 +249,42 @@ async fn runtime_charges_an_order_once_when_another_worker_fetches_during_the_ac }) .build(); let orchestrations = OrchestrationRegistry::builder() - .register(ORDERS, |ctx: OrchestrationContext, _input: String| async move { - let mut charged = Vec::new(); - for _ in 0..2 { - let order = ctx.dequeue_event(QUEUE).await; - charged.push(ctx.schedule_activity("Charge", order).await?); - } - Ok(charged.join(",")) - }) + .register( + ORDERS, + |ctx: OrchestrationContext, _input: String| async move { + let mut charged = Vec::new(); + for _ in 0..2 { + let order = ctx.dequeue_event(QUEUE).await; + charged.push(ctx.schedule_activity("Charge", order).await?); + } + Ok(charged.join(",")) + }, + ) .build(); let options = RuntimeOptions { dispatcher_min_poll_interval: Duration::from_millis(10), orchestrator_lock_timeout: Duration::from_secs(2), ..Default::default() }; - let rt = - runtime::Runtime::start_with_options(provider.clone(), activities, orchestrations, options) - .await; + let rt = runtime::Runtime::start_with_options( + provider.clone(), + activities, + orchestrations, + options, + ) + .await; let client = Client::new(provider.clone()); let instance = format!("orders-{}", uuid::Uuid::new_v4()); client .start_orchestration(&instance, ORDERS, "") .await .expect("failed to start the orchestration"); - wait_for_history(&*provider, &instance, "waiting for the first order", |kind| { - matches!(kind, EventKind::QueueSubscribed { .. }) - }) + wait_for_history( + &*provider, + &instance, + "waiting for the first order", + |kind| matches!(kind, EventKind::QueueSubscribed { .. }), + ) .await; let (ready_key, gate) = @@ -312,9 +324,12 @@ async fn runtime_charges_an_order_once_when_another_worker_fetches_during_the_ac assert_not_deadlock_victim("other worker's fetch", &other_result); other_result.expect("the other worker's fetch must succeed"); - wait_for_history(&*provider, &instance, "the acknowledge of order 1", |kind| { - matches!(kind, EventKind::ActivityScheduled { .. }) - }) + wait_for_history( + &*provider, + &instance, + "the acknowledge of order 1", + |kind| matches!(kind, EventKind::ActivityScheduled { .. }), + ) .await; let redelivered: i64 = sqlx::query_scalar(&format!( "SELECT count(*) FROM {schema}.orchestrator_queue diff --git a/tests/orchestration_lock_renewal_tests.rs b/tests/orchestration_lock_renewal_tests.rs index 018ca79..0833ca4 100644 --- a/tests/orchestration_lock_renewal_tests.rs +++ b/tests/orchestration_lock_renewal_tests.rs @@ -145,7 +145,7 @@ async fn renew_across(interleaving: Interleaving) { Interleaving::Acknowledged => { timed( "acknowledge", - sql_ack(&mut *gate, &schema, &token, serde_json::json!([])), + sql_ack(&mut gate, &schema, &token, serde_json::json!([])), ) .await .expect("acknowledge must succeed while renewal waits"); From 50d5eecec612bb9b44c771d6230eaa16c0234663 Mon Sep 17 00:00:00 2001 From: "Chumbucket (Waldemort)" Date: Mon, 26 Oct 2026 01:17:37 +0000 Subject: [PATCH 15/15] docs: add a TLA+ model of the orchestration lease procedures 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> --- CHANGELOG.md | 3 + docs/tla/orchestration-leases/.gitignore | 3 + .../orchestration-leases/LeaseProtocol.tla | 429 ++++++++++++++++++ .../orchestration-leases/LeaseRedelivery.tla | 25 + .../orchestration-leases/LeaseReleaseRace.tla | 16 + docs/tla/orchestration-leases/README.md | 148 ++++++ docs/tla/orchestration-leases/SOURCE-MAP.md | 46 ++ .../configs/FIXED-abandon.cfg | 17 + .../configs/FIXED-deadline-publication.cfg | 15 + .../configs/FIXED-redelivery.cfg | 16 + .../configs/FIXED-release-race.cfg | 16 + .../configs/FIXED-safety.cfg | 17 + .../configs/FIXED-strict-clock.cfg | 15 + .../configs/FIXED-strict-validation.cfg | 15 + .../configs/MAIN-consumption.cfg | 15 + .../configs/MAIN-deadline-publication.cfg | 15 + .../configs/MAIN-deadlock-abandon.cfg | 15 + .../configs/MAIN-deadlock-ack.cfg | 15 + .../configs/MAIN-deadlock-fetch.cfg | 15 + .../configs/MAIN-redelivery.cfg | 15 + .../configs/MAIN-release-race.cfg | 15 + .../configs/MAIN-revival.cfg | 15 + .../configs/MAIN-shortening.cfg | 15 + .../configs/MAIN-structure.cfg | 15 + .../configs/MAIN-zero-skew-consumption.cfg | 15 + .../configs/PR43-abandon.cfg | 17 + .../configs/PR43-consumption.cfg | 15 + .../configs/PR43-deadline-publication.cfg | 15 + .../configs/PR43-redelivery.cfg | 15 + .../configs/PR43-release-race.cfg | 15 + .../configs/PR43-safety.cfg | 16 + .../configs/PR43-strict-validation.cfg | 15 + docs/tla/orchestration-leases/expected.tsv | 26 ++ docs/tla/orchestration-leases/run.sh | 84 ++++ 34 files changed, 1164 insertions(+) create mode 100644 docs/tla/orchestration-leases/.gitignore create mode 100644 docs/tla/orchestration-leases/LeaseProtocol.tla create mode 100644 docs/tla/orchestration-leases/LeaseRedelivery.tla create mode 100644 docs/tla/orchestration-leases/LeaseReleaseRace.tla create mode 100644 docs/tla/orchestration-leases/README.md create mode 100644 docs/tla/orchestration-leases/SOURCE-MAP.md create mode 100644 docs/tla/orchestration-leases/configs/FIXED-abandon.cfg create mode 100644 docs/tla/orchestration-leases/configs/FIXED-deadline-publication.cfg create mode 100644 docs/tla/orchestration-leases/configs/FIXED-redelivery.cfg create mode 100644 docs/tla/orchestration-leases/configs/FIXED-release-race.cfg create mode 100644 docs/tla/orchestration-leases/configs/FIXED-safety.cfg create mode 100644 docs/tla/orchestration-leases/configs/FIXED-strict-clock.cfg create mode 100644 docs/tla/orchestration-leases/configs/FIXED-strict-validation.cfg create mode 100644 docs/tla/orchestration-leases/configs/MAIN-consumption.cfg create mode 100644 docs/tla/orchestration-leases/configs/MAIN-deadline-publication.cfg create mode 100644 docs/tla/orchestration-leases/configs/MAIN-deadlock-abandon.cfg create mode 100644 docs/tla/orchestration-leases/configs/MAIN-deadlock-ack.cfg create mode 100644 docs/tla/orchestration-leases/configs/MAIN-deadlock-fetch.cfg create mode 100644 docs/tla/orchestration-leases/configs/MAIN-redelivery.cfg create mode 100644 docs/tla/orchestration-leases/configs/MAIN-release-race.cfg create mode 100644 docs/tla/orchestration-leases/configs/MAIN-revival.cfg create mode 100644 docs/tla/orchestration-leases/configs/MAIN-shortening.cfg create mode 100644 docs/tla/orchestration-leases/configs/MAIN-structure.cfg create mode 100644 docs/tla/orchestration-leases/configs/MAIN-zero-skew-consumption.cfg create mode 100644 docs/tla/orchestration-leases/configs/PR43-abandon.cfg create mode 100644 docs/tla/orchestration-leases/configs/PR43-consumption.cfg create mode 100644 docs/tla/orchestration-leases/configs/PR43-deadline-publication.cfg create mode 100644 docs/tla/orchestration-leases/configs/PR43-redelivery.cfg create mode 100644 docs/tla/orchestration-leases/configs/PR43-release-race.cfg create mode 100644 docs/tla/orchestration-leases/configs/PR43-safety.cfg create mode 100644 docs/tla/orchestration-leases/configs/PR43-strict-validation.cfg create mode 100644 docs/tla/orchestration-leases/expected.tsv create mode 100755 docs/tla/orchestration-leases/run.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index a12497f..011c9dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 takeover while acknowledge waits for the lock, a lock deleted during the acknowledge, and, end to end with the duroxide runtime, that an order is charged once when another worker fetches during the acknowledge. + `docs/tla/orchestration-leases` contains a TLA+ model of fetch, + acknowledge, renew and abandon under worker clock skew. Its TLC + configurations and expected results run with `./run.sh`. ## [0.1.37] - 2026-10-21 diff --git a/docs/tla/orchestration-leases/.gitignore b/docs/tla/orchestration-leases/.gitignore new file mode 100644 index 0000000..22a8c76 --- /dev/null +++ b/docs/tla/orchestration-leases/.gitignore @@ -0,0 +1,3 @@ +logs/ +states/ +tla2tools.jar diff --git a/docs/tla/orchestration-leases/LeaseProtocol.tla b/docs/tla/orchestration-leases/LeaseProtocol.tla new file mode 100644 index 0000000..09037a2 --- /dev/null +++ b/docs/tla/orchestration-leases/LeaseProtocol.tla @@ -0,0 +1,429 @@ +\* Copyright (c) Microsoft Corporation. +\* Licensed under the MIT License. + +--------------------------- MODULE LeaseProtocol --------------------------- +EXTENDS Integers, Sequences, FiniteSets, TLC + +(* +One-instance, statement-interleaving model of duroxide-pg orchestration leases. +MAIN = 3beba92048b9fd6c9e68262a3e3fa192441c1e31 +PR43 = b2ff29633a5ea437f8f1e737429d7ba9170ba491 +FIXED = ea598d91839b6d656917a47a3b4e772fa515b9aa +Its ack takes ADV, rechecks the token, and checks the INSTANCE delete count. +The queue delete count is not checked in this committed source. + +This is an executable abstraction, not an implementation refinement proof. +SQL actions read committed state at each statement; writes remain private +until Commit. Row/advisory locks last until Commit or Rollback. A blocked +UPDATE/DELETE rechecks its token predicate when it can proceed (EvalPlanQual). + +The initial state is the state just after worker 1 fetched one visible batch. +Each call slot executes its selected procedure once. A successful fetch may +then acknowledge its captured inputs/history. Two slots may belong to the +same worker: its foreground turn and its background renewal are concurrent. +Every integer worker skew in [-MaxSkew, MaxSkew] is chosen at initialization. +Skews are constant, database time is monotonic, and a tick may occur between +any statements, including between validation, writes, and commit. + +Q represents a nonempty batch whose rows have the same token and deadline. +Batch DML acquires its rows in one common order and is collapsed to one lock. +H includes the instance/execution metadata row lock preceding history INSERT, +and enforces history's (instance, execution, event_id) unique constraint. +Each modeled ack appends one history position and emits one durable output. +Messages model QueueMessage/ExternalRaised arrivals, not deduplicated +completion events. No activity executor or external side effect is modeled. +*) + +CONSTANTS Variant, N, Messages, L, R, MaxSkew, Horizon, + Kinds, Owners, FetchThenAck, AllowCancellation + +Workers == 1..N +Procs == DOMAIN Kinds +Resources == {"ADV", "Q", "I", "H"} +NoProc == 0 + +AckFetch == <<"ack", "fetch">> +RenewFetch == <<"renew", "fetch">> +RenewAck == <<"renew", "ack">> +RenewAbandon == <<"renew", "abandon">> +AckFetchRenew == <<"ack", "fetch", "renew">> +AbandonFetchRenew == <<"abandon", "fetch", "renew">> +RenewOnly == <<"renew">> +TwoWorkers == <<1, 2>> +OneWorkerTwoCalls == <<1, 1>> +TwoWorkersThreeCalls == <<1, 2, 1>> +OneWorker == <<1>> + +Max(a, b) == IF a >= b THEN a ELSE b +Min(a, b) == IF a <= b THEN a ELSE b + +ASSUME /\ Variant \in {"MAIN", "PR43", "FIXED"} + /\ N \in Nat \ {0} + /\ Messages # {} + /\ L > 0 /\ R > 0 /\ R < L + /\ MaxSkew \in Nat /\ Horizon \in Nat + /\ DOMAIN Owners = Procs + /\ \A p \in Procs : Owners[p] \in Workers + /\ \A p \in Procs : Kinds[p] \in {"ack", "fetch", "renew", "abandon"} + /\ FetchThenAck \in BOOLEAN /\ AllowCancellation \in BOOLEAN + +VARIABLES tick, skew, lease, queue, history, outputs, tx, locks, audit +vars == <> + +DBNow == MaxSkew + tick +WorkerNow(w) == DBNow + skew[w] +SeedDeadline == MaxSkew + Max(skew[1], 0) + L +FreshNow(p) == Max(tx[p].raw + DBNow - tx[p].entered, DBNow) + +EmptyTx(op, pc, tok, base, inputs) == + [op |-> op, pc |-> pc, tok |-> tok, base |-> base, inputs |-> inputs, + raw |-> 0, entered |-> 0, deadline |-> 0, + iw |-> FALSE, it |-> 0, iu |-> 0, + qw |-> FALSE, qe |-> TRUE, qt |-> 0, qu |-> 0, + hw |-> FALSE, ow |-> FALSE, + oldUntil |-> 0, checkClock |-> 0, checkedAt |-> 0, wroteAt |-> 0] + +Init == + /\ tick = 0 + /\ skew \in [Workers -> ((-MaxSkew)..MaxSkew)] + /\ lease = [token |-> 1, until |-> SeedDeadline] + /\ queue = [exists |-> TRUE, token |-> 1, until |-> SeedDeadline] + /\ history = <<>> + /\ outputs = <<>> + /\ tx = [p \in Procs |-> + EmptyTx(Kinds[p], "ready", + IF Kinds[p] = "fetch" THEN p + 1 ELSE 1, + 0, IF Kinds[p] = "fetch" THEN {} ELSE Messages)] + /\ locks = [r \in Resources |-> NoProc] + /\ audit = [renewFenced |-> TRUE, ackFenced |-> TRUE, + neverShortened |-> TRUE, checkedLive |-> TRUE, + liveAtWrite |-> TRUE, oldLiveAtCommit |-> TRUE, + renewalDeadlineLive |-> TRUE, fetchDeadlineLive |-> TRUE] + +CanLock(p, r) == locks[r] \in {NoProc, p} +OwnLease(p) == lease.token = tx[p].tok +OwnQueue(p) == queue.exists /\ queue.token = tx[p].tok +Fetchable(p) == queue.exists /\ (lease.token = 0 \/ lease.until <= tx[p].raw) +Release(p) == [r \in Resources |-> IF locks[r] = p THEN NoProc ELSE locks[r]] +PC(p, label) == [tx EXCEPT ![p].pc = label] +Raise(p) == PC(p, "rollback") + +Tick == + /\ tick < Horizon + /\ tick' = tick + 1 + /\ UNCHANGED <> + +\* Rust now_millis() precedes pool acquisition; entered is statement_timestamp. +Begin(p) == + /\ tx[p].pc = "ready" + /\ (tx[p].op # "renew" \/ tick >= R) + /\ tx' = [tx EXCEPT ![p].pc = "arrival", ![p].raw = WorkerNow(Owners[p])] + /\ UNCHANGED <> + +Arrival(p) == + /\ tx[p].pc = "arrival" + /\ tx' = [tx EXCEPT ![p].entered = DBNow, + ![p].pc = CASE tx[p].op = "fetch" -> "f.candidate" + [] tx[p].op = "ack" -> "a.lookup" + [] tx[p].op = "abandon" -> "b.lookup" + [] Variant = "MAIN" -> "r.mainI" + [] OTHER -> "r.lookup"] + /\ UNCHANGED <> + +\* 0025:88-96 -- plain candidate SELECT. +FetchCandidate(p) == + /\ tx[p].pc = "f.candidate" + /\ tx' = IF Fetchable(p) THEN PC(p, "f.advisory") ELSE Raise(p) + /\ UNCHANGED <> + +\* 0025:104; 0026:62; fixed ack's advisory lock. +Advisory(p) == + /\ tx[p].pc \in {"f.advisory", "r.advisory", "a.advisory"} + /\ CanLock(p, "ADV") + /\ locks' = [locks EXCEPT !["ADV"] = p] + /\ tx' = PC(p, CASE tx[p].op = "fetch" -> "f.queueSelect" + [] tx[p].op = "renew" -> "r.now" + [] OTHER -> "a.recheck") + /\ UNCHANGED <> + +\* 0025:127-139 -- FOR UPDATE SKIP LOCKED; it does not wait on Q. +\* A failed one-instance candidate terminates this bounded attempt. +FetchQueueSelect(p) == + /\ tx[p].pc = "f.queueSelect" + /\ IF Fetchable(p) /\ CanLock(p, "Q") + THEN /\ locks' = [locks EXCEPT !["Q"] = p] + /\ tx' = PC(p, "f.computeLease") + ELSE /\ locks' = locks + /\ tx' = Raise(p) + /\ UNCHANGED <> + +\* 0025:146-151 -- separate from INSERT: time can pass before the write. +FetchComputeLease(p) == + /\ tx[p].pc = "f.computeLease" + /\ tx' = [tx EXCEPT ![p].deadline = FreshNow(p) + L, ![p].pc = "f.instance"] + /\ UNCHANGED <> + +\* 0025:153-165 -- ON CONFLICT rechecks expiry after a row-lock wait. +FetchInstance(p) == + /\ tx[p].pc = "f.instance" + /\ CanLock(p, "I") + /\ locks' = [locks EXCEPT !["I"] = p] + /\ tx' = IF lease.token = 0 \/ lease.until <= tx[p].raw + THEN [tx EXCEPT ![p].iw = TRUE, ![p].it = tx[p].tok, + ![p].iu = tx[p].deadline, ![p].pc = "f.queueUpdate"] + ELSE Raise(p) + /\ UNCHANGED <> + +\* 0025:168-174 -- write only unowned/expired visible rows. +FetchQueueUpdate(p) == + /\ tx[p].pc = "f.queueUpdate" + /\ CanLock(p, "Q") + /\ locks' = [locks EXCEPT !["Q"] = p] + /\ tx' = IF queue.exists /\ (queue.token = 0 \/ queue.until <= tx[p].raw) + THEN [tx EXCEPT ![p].qw = TRUE, ![p].qe = TRUE, + ![p].qt = tx[p].tok, ![p].qu = tx[p].deadline, + ![p].pc = "f.messages"] + ELSE PC(p, "f.messages") + /\ UNCHANGED <> + +\* 0025:177-181 -- own writes are visible inside the transaction. +FetchMessages(p) == + /\ tx[p].pc = "f.messages" + /\ tx' = [tx EXCEPT ![p].inputs = + IF tx[p].qw /\ tx[p].qe /\ tx[p].qt = tx[p].tok THEN Messages ELSE {}, + ![p].pc = "f.history"] + /\ UNCHANGED <> + +\* 0025:191-201 -- a new READ COMMITTED snapshot, no H row lock. +FetchHistory(p) == + /\ tx[p].pc = "f.history" + /\ tx' = [tx EXCEPT ![p].base = Len(history), ![p].pc = "commit"] + /\ UNCHANGED <> + +\* 0020:74-80; 0026:53-60; 0006:101-107. +Lookup(p) == + /\ tx[p].pc \in {"a.lookup", "r.lookup", "b.lookup"} + /\ tx' = IF OwnLease(p) /\ (tx[p].op = "abandon" \/ lease.until > tx[p].raw) + THEN PC(p, CASE tx[p].op = "renew" -> "r.advisory" + [] tx[p].op = "abandon" -> "b.queue" + [] Variant = "FIXED" -> "a.advisory" + [] OTHER -> "a.history") + ELSE Raise(p) + /\ UNCHANGED <> + +\* Fixed ack checks the token again after acquiring ADV, not the new time. +AckRecheck(p) == + /\ tx[p].pc = "a.recheck" + /\ tx' = IF OwnLease(p) THEN PC(p, "a.history") ELSE Raise(p) + /\ UNCHANGED <> + +\* 0020:93-126 -- metadata serialization and unique history position INSERT. +AckHistory(p) == + /\ tx[p].pc = "a.history" + /\ CanLock(p, "H") + /\ locks' = [locks EXCEPT !["H"] = p] + /\ tx' = IF tx[p].base = Len(history) + THEN [tx EXCEPT ![p].hw = TRUE, ![p].pc = "a.outputs"] + ELSE Raise(p) + /\ UNCHANGED <> + +\* 0020:221-291 -- durable output staging, not external effect execution. +AckOutputs(p) == + /\ tx[p].pc = "a.outputs" + /\ tx' = [tx EXCEPT ![p].ow = TRUE, ![p].pc = "a.queue"] + /\ UNCHANGED <> + +\* 0020:295; 0006:141-149. A token mismatch means zero rows, not a lock. +ReleaseQueue(p) == + /\ tx[p].pc \in {"a.queue", "b.queue"} + /\ ~OwnQueue(p) \/ CanLock(p, "Q") + /\ locks' = IF OwnQueue(p) THEN [locks EXCEPT !["Q"] = p] ELSE locks + /\ tx' = IF OwnQueue(p) + THEN [tx EXCEPT ![p].qw = TRUE, + ![p].qe = (tx[p].op = "abandon"), ![p].qt = 0, ![p].qu = 0, + ![p].pc = IF tx[p].op = "ack" THEN "a.instance" ELSE "b.instance"] + ELSE PC(p, IF tx[p].op = "ack" THEN "a.instance" ELSE "b.instance") + /\ UNCHANGED <> + +\* 0020:298-299; 0006:148-149. FIXED raises on a zero-row ack DELETE. +ReleaseInstance(p) == + /\ tx[p].pc \in {"a.instance", "b.instance"} + /\ ~OwnLease(p) \/ CanLock(p, "I") + /\ locks' = IF OwnLease(p) THEN [locks EXCEPT !["I"] = p] ELSE locks + /\ tx' = IF OwnLease(p) + THEN [tx EXCEPT ![p].iw = TRUE, ![p].it = 0, ![p].iu = 0, ![p].pc = "commit"] + ELSE IF Variant = "FIXED" /\ tx[p].op = "ack" + THEN Raise(p) + ELSE PC(p, "commit") + /\ UNCHANGED <> + +\* MAIN 0004:349-359 -- raw caller time; I before Q; may shorten. +MainRenewInstance(p) == + /\ tx[p].pc = "r.mainI" + /\ ~OwnLease(p) \/ CanLock(p, "I") + /\ locks' = IF OwnLease(p) THEN [locks EXCEPT !["I"] = p] ELSE locks + /\ tx' = IF OwnLease(p) /\ lease.until > tx[p].raw + THEN [tx EXCEPT ![p].iw = TRUE, ![p].it = tx[p].tok, + ![p].iu = tx[p].raw + L, ![p].deadline = tx[p].raw + L, + ![p].oldUntil = lease.until, ![p].checkClock = tx[p].raw, + ![p].checkedAt = DBNow, + ![p].wroteAt = DBNow, ![p].pc = "r.queue"] + ELSE Raise(p) + /\ UNCHANGED <> + +\* PR43 0026:64-67 / FIXED 0026:76-79 -- PL/pgSQL time assignment. +\* This is distinct from the following SELECT: a stall can occur between them. +RenewSampleNow(p) == + /\ tx[p].pc = "r.now" + /\ tx' = [tx EXCEPT ![p].checkClock = FreshNow(p), ![p].pc = "r.recheck"] + /\ UNCHANGED <> + +\* PR43 0026:69-78 -- token/expiry check using the previously sampled time. +RenewRecheck(p) == + /\ tx[p].pc = "r.recheck" + /\ tx' = IF OwnLease(p) /\ lease.until > tx[p].checkClock + THEN [tx EXCEPT ![p].deadline = Max(lease.until, tx[p].checkClock + L), + ![p].oldUntil = lease.until, ![p].checkedAt = DBNow, + ![p].pc = "r.queue"] + ELSE Raise(p) + /\ UNCHANGED <> + +\* MAIN 0004:362-364; PR43 0026:80-82. +RenewQueue(p) == + /\ tx[p].pc = "r.queue" + /\ ~OwnQueue(p) \/ CanLock(p, "Q") + /\ locks' = IF OwnQueue(p) THEN [locks EXCEPT !["Q"] = p] ELSE locks + /\ tx' = IF OwnQueue(p) + THEN [tx EXCEPT ![p].qw = TRUE, ![p].qe = TRUE, + ![p].qt = tx[p].tok, ![p].qu = tx[p].deadline, + ![p].pc = IF Variant = "MAIN" THEN "commit" ELSE "r.instance"] + ELSE PC(p, IF Variant = "MAIN" THEN "commit" ELSE "r.instance") + /\ UNCHANGED <> + +\* PR43 0026:84-93 -- token recheck, zero rows raises, no fresh expiry test. +RenewInstance(p) == + /\ tx[p].pc = "r.instance" + /\ ~OwnLease(p) \/ CanLock(p, "I") + /\ locks' = IF OwnLease(p) THEN [locks EXCEPT !["I"] = p] ELSE locks + /\ tx' = IF OwnLease(p) + THEN [tx EXCEPT ![p].iw = TRUE, ![p].it = tx[p].tok, + ![p].iu = tx[p].deadline, ![p].wroteAt = DBNow, ![p].pc = "commit"] + ELSE Raise(p) + /\ UNCHANGED <> + +\* All private writes become visible together; none appear on Rollback. +Commit(p) == + /\ tx[p].pc = "commit" + /\ lease' = IF tx[p].iw THEN [token |-> tx[p].it, until |-> tx[p].iu] ELSE lease + /\ queue' = IF tx[p].qw + THEN [exists |-> tx[p].qe, token |-> tx[p].qt, until |-> tx[p].qu] ELSE queue + /\ history' = IF tx[p].hw + THEN Append(history, [base |-> tx[p].base, token |-> tx[p].tok, + inputs |-> tx[p].inputs]) ELSE history + /\ outputs' = IF tx[p].ow + THEN Append(outputs, [base |-> tx[p].base, token |-> tx[p].tok, + inputs |-> tx[p].inputs]) ELSE outputs + /\ audit' = [audit EXCEPT + !.renewFenced = @ /\ (tx[p].op # "renew" \/ OwnLease(p)), + !.ackFenced = @ /\ (tx[p].op # "ack" \/ OwnLease(p)), + !.neverShortened = @ /\ (tx[p].op # "renew" \/ tx[p].iu >= lease.until), + !.checkedLive = @ /\ (tx[p].op # "renew" \/ tx[p].oldUntil > tx[p].checkedAt), + !.liveAtWrite = @ /\ (tx[p].op # "renew" \/ tx[p].oldUntil > tx[p].wroteAt), + !.oldLiveAtCommit = @ /\ (tx[p].op # "renew" \/ tx[p].oldUntil > DBNow), + !.renewalDeadlineLive = @ /\ (tx[p].op # "renew" \/ tx[p].iu > DBNow), + !.fetchDeadlineLive = @ /\ (tx[p].op # "fetch" \/ tx[p].iu > DBNow)] + /\ locks' = Release(p) + /\ tx' = [tx EXCEPT ![p] = + IF tx[p].op = "fetch" /\ FetchThenAck /\ tx[p].inputs # {} + THEN EmptyTx("ack", "ready", tx[p].tok, tx[p].base, tx[p].inputs) + ELSE EmptyTx("none", "done", 0, 0, {})] + /\ UNCHANGED <> + +Need(p) == + CASE tx[p].pc \in {"f.advisory", "r.advisory", "a.advisory"} -> "ADV" + [] tx[p].pc = "f.instance" -> "I" + [] tx[p].pc \in {"a.instance", "b.instance", "r.instance", "r.mainI"} + /\ OwnLease(p) -> "I" + [] tx[p].pc \in {"a.queue", "b.queue", "r.queue"} /\ OwnQueue(p) -> "Q" + [] tx[p].pc = "f.queueUpdate" -> "Q" + [] tx[p].pc = "a.history" -> "H" + [] OTHER -> "NONE" + +WaitsFor(p) == + IF Need(p) = "NONE" THEN NoProc + ELSE IF CanLock(p, Need(p)) THEN NoProc ELSE locks[Need(p)] + +RECURSIVE Follow(_, _) +Follow(p, k) == + IF k = 0 \/ p = NoProc THEN p ELSE Follow(WaitsFor(p), k - 1) +Cyclic(p) == \E k \in 1..Cardinality(Procs) : Follow(p, k) = p +NoDeadlock == ~(\E p \in Procs : Cyclic(p)) + +\* PostgreSQL deadlock detection may choose any cycle member as victim. +\* Cancellation before commit is one possible outcome, not a rollback promise. +Rollback(p) == + /\ tx[p].pc = "rollback" \/ Cyclic(p) + \/ (AllowCancellation /\ tx[p].pc \notin {"ready", "done"}) + /\ locks' = Release(p) + /\ tx' = [tx EXCEPT ![p] = EmptyTx("none", "done", 0, 0, {})] + /\ UNCHANGED <> + +Next == + \/ Tick + \/ \E p \in Procs : + \/ Begin(p) \/ Arrival(p) \/ FetchCandidate(p) \/ Advisory(p) + \/ FetchQueueSelect(p) \/ FetchComputeLease(p) \/ FetchInstance(p) + \/ FetchQueueUpdate(p) \/ FetchMessages(p) \/ FetchHistory(p) + \/ Lookup(p) \/ AckRecheck(p) \/ AckHistory(p) \/ AckOutputs(p) + \/ ReleaseQueue(p) \/ ReleaseInstance(p) + \/ MainRenewInstance(p) \/ RenewSampleNow(p) \/ RenewRecheck(p) \/ RenewQueue(p) + \/ RenewInstance(p) \/ Commit(p) \/ Rollback(p) + +Spec == Init /\ [][Next]_vars + +Range(s) == {s[i] : i \in DOMAIN s} + +TypeOK == + /\ tick \in 0..Horizon + /\ skew \in [Workers -> ((-MaxSkew)..MaxSkew)] + /\ lease.token \in 0..(Cardinality(Procs) + 1) /\ lease.until \in Int + /\ queue.exists \in BOOLEAN /\ queue.token \in 0..(Cardinality(Procs) + 1) + /\ queue.until \in Int + /\ DOMAIN tx = Procs + /\ locks \in [Resources -> (Procs \cup {NoProc})] + /\ \A h \in Range(history) : h.inputs \subseteq Messages + +\* "Still deliverable" includes any retained input, even temporarily leased. +ExactlyOnceConsumption == + \A h \in Range(history) : h.inputs # {} => ~queue.exists +SingleWriter == + \A i, j \in DOMAIN history : i # j => history[i].base # history[j].base +NoDuplicateConsumption == + \A m \in Messages : + Cardinality({i \in DOMAIN history : m \in history[i].inputs}) <= 1 +AtomicOutputs == history = outputs +NoMessageLoss == + queue.exists \/ UNION {h.inputs : h \in Range(history)} = Messages +QueueLeaseAgreement == + queue.exists /\ queue.token # 0 => + queue.token = lease.token /\ queue.until = lease.until +NoStaleRenewal == audit.renewFenced +NoStaleAck == audit.ackFenced +NeverShorten == audit.neverShortened +NoExpiredRenewalAtCheck == audit.checkedLive +LeaseSafety == NoStaleRenewal /\ NeverShorten + +\* Stronger wall-clock properties: deliberately NOT assumed in CoreSafety. +NoExpiredRenewalAtWrite == audit.liveAtWrite +NoExpiredRenewalAtCommit == audit.oldLiveAtCommit +RenewalDeadlineLiveAtCommit == audit.renewalDeadlineLive +FetchDeadlineLiveAtCommit == audit.fetchDeadlineLive +StrictLeaseSafety == LeaseSafety /\ NoExpiredRenewalAtCheck /\ NoExpiredRenewalAtWrite + +StructuralSafety == + TypeOK /\ SingleWriter /\ AtomicOutputs /\ NoMessageLoss /\ QueueLeaseAgreement +FencedSafety == + StructuralSafety /\ LeaseSafety /\ NoDeadlock +CoreSafety == + FencedSafety /\ ExactlyOnceConsumption /\ NoDuplicateConsumption /\ NoStaleAck +============================================================================= diff --git a/docs/tla/orchestration-leases/LeaseRedelivery.tla b/docs/tla/orchestration-leases/LeaseRedelivery.tla new file mode 100644 index 0000000..8cb778f --- /dev/null +++ b/docs/tla/orchestration-leases/LeaseRedelivery.tla @@ -0,0 +1,25 @@ +\* Copyright (c) Microsoft Corporation. +\* Licensed under the MIT License. + +-------------------------- MODULE LeaseRedelivery -------------------------- +EXTENDS LeaseProtocol + +(* +Bounded continuation of the old-ack counterexample. +Slot 1 is A's original ack. Slot 2 is B's fetch and subsequent ack. +Slot 3 is a later fetch/ack by B, after slot 2 finished or rolled back. +No new message is enqueued. An initial QueueMessage/ExternalRaised arrival +must not be consumed a second time simply because its queue row survived. +Cancellation is disabled. B may fail its expiry lookup or history unique key; +the shortest unconstrained trace chooses the earlier expiry rejection. +*) + +AckFetchFetch == <<"ack", "fetch", "fetch">> +RedeliveryOwners == <<1, 2, 2>> + +NextRedelivery == + /\ Next + /\ (tx[3].pc = "ready" /\ tx'[3].pc = "arrival" => tx[2].pc = "done") + +SpecRedelivery == Init /\ [][NextRedelivery]_vars +============================================================================= diff --git a/docs/tla/orchestration-leases/LeaseReleaseRace.tla b/docs/tla/orchestration-leases/LeaseReleaseRace.tla new file mode 100644 index 0000000..80a32d2 --- /dev/null +++ b/docs/tla/orchestration-leases/LeaseReleaseRace.tla @@ -0,0 +1,16 @@ +\* Copyright (c) Microsoft Corporation. +\* Licensed under the MIT License. + +------------------------- MODULE LeaseReleaseRace -------------------------- +EXTENDS LeaseProtocol + +(* +Two concurrent calls on the same fetched token: foreground acknowledgement +and abandonment. This specifically exercises FIXED's instance-delete count. +Abandon has no advisory lock and can release the token while ack holds ADV. +The queue DELETE can then match zero rows; the final instance DELETE must +reject the acknowledgement and roll its history/output writes back. +*) + +AckAbandon == <<"ack", "abandon">> +============================================================================= diff --git a/docs/tla/orchestration-leases/README.md b/docs/tla/orchestration-leases/README.md new file mode 100644 index 0000000..dac825a --- /dev/null +++ b/docs/tla/orchestration-leases/README.md @@ -0,0 +1,148 @@ +# TLA+ model of orchestration leases + +This folder contains a TLA+ model of the PostgreSQL provider's orchestration +lease procedures, and TLC configurations that check it. It was written for +migration `0026`. + +The model checks one question: can concurrent fetch, acknowledge, renew and +abandon calls, from workers whose clocks disagree, lose ownership of an +instance, process a message twice, or deadlock? + +TLC explores every reachable state within fixed bounds. That is strong evidence +for those bounds. It is not a proof for every worker count, message count or +duration, and it does not prove that the Rust and SQL code implement the model. + +## Run it + +You need Java 17 or newer. + +```sh +cd docs/tla/orchestration-leases +./run.sh # all 25 configurations +./run.sh MAIN-consumption FIXED-safety # selected configurations +``` + +`run.sh` does the following: + +1. It downloads `tla2tools.jar` v1.7.4 (TLC 2.19) and checks its SHA-256. To + use a local copy, set `TLA2TOOLS_JAR`. +2. It runs TLC with one worker for each configuration. +3. It compares each result with `expected.tsv`. + +The script exits non-zero if any result differs. Raw TLC output, including +counterexample traces, goes to `logs/.log`. + +The seven largest configurations each take 3 to 6 minutes and need a 4 GiB +heap. All the others finish in seconds. A full run takes about 25 minutes on +one core. + +## What is modelled + +| Part | In the model | +|---|---| +| `fetch_orchestration_item` | Migration `0025`: candidate query, advisory lock, `FOR UPDATE SKIP LOCKED`, lease computed as `max(caller + elapsed, database) + timeout`, takeover by time, history read | +| `ack_orchestration_item` | Migration `0020` (MAIN, PR43) or `0026` (FIXED): token check, advisory lock and token recheck (FIXED only), history insert, outputs, queue delete, instance-lock delete, and the row-count check on that delete (FIXED only) | +| `renew_orchestration_item_lock` | Migration `0004` (MAIN) or `0026` (PR43, FIXED) | +| `abandon_orchestration_item` | Migration `0006` | +| PostgreSQL | Each statement sees the latest committed state plus its own writes (READ COMMITTED). Row and advisory locks are held until commit or rollback. A blocked update re-evaluates its token predicate. Deadlock detection aborts any one member of a cycle. The history primary key is enforced | +| Callers | Each call is one autocommit statement. The caller reads its clock before waiting for a connection. A call can be cancelled before it commits. A worker's renewal can run at the same time as its own acknowledge | +| Clocks | Each worker has a fixed skew from the database clock, chosen from `-MaxSkew..MaxSkew`. Every combination is checked. Time can advance between any two statements | + +Three variants, set by the `Variant` constant, are pinned to commits: + +| Variant | Source | Description | +|---|---|---| +| `MAIN` | `3beba92` | Before migration `0026` | +| `PR43` | `b2ff296` | Migration `0026` with the renewal fix only; acknowledge as on `main` | +| `FIXED` | `ea598d9` | Migration `0026` with the renewal and acknowledge fixes. The executable SQL is byte-identical in later commits of the same change | + +The comments in the modules cite the SQL line numbers at those commits. +`SOURCE-MAP.md` maps each TLA+ action to its SQL. + +## Invariants + +| Invariant | Meaning | Source of the requirement | +|---|---|---| +| `ExactlyOnceConsumption` | No committed turn leaves its input messages in the queue | Provider contract: an acknowledge is atomic (`duroxide` `src/providers/mod.rs`, `ack_orchestration_item`) | +| `NoDuplicateConsumption` | No message is reflected in more than one committed turn | Duroxide does not de-duplicate redelivered queue messages or external events (`src/runtime/replay_engine.rs`) | +| `SingleWriter` | No two committed turns start from the same history position | History primary key | +| `AtomicOutputs` | History and new work commit together | Provider contract | +| `NoMessageLoss` | Every message is either still queued or consumed by a committed turn | Provider contract | +| `QueueLeaseAgreement` | Queue rows carry the instance lock's token and deadline | Provider design | +| `NoStaleAck`, `NoStaleRenewal` | An acknowledge or renewal commits only while its token still owns the instance | Provider contract: lock tokens fence ownership | +| `NeverShorten` | A renewal never moves a deadline earlier | Design rule of migration `0026` | +| `NoDeadlock` | No cycle among the calls' row and advisory locks | Operational requirement | + +Four stricter clock properties are checked separately. They are not part of the +safety claim: + +- `NoExpiredRenewalAtCheck` +- `NoExpiredRenewalAtWrite` +- `RenewalDeadlineLiveAtCommit` +- `FetchDeadlineLiveAtCommit` + +## Results + +TLC 2.19, one worker. Bounds for the main profiles: + +- 2 workers and 1 instance. +- 2 messages in one batch. +- Lease `L = 2` ticks and renewal interval `R = 1` tick. +- `MaxSkew = 2`, so a clock can be off by a whole lease. +- A horizon of 3 ticks. + +The exact bounds of each configuration are in `configs/`. + +| Variant | Exactly-once consumption | Renewal fenced by token | Acknowledge fenced by token | No deadlock (one instance) | Never shorten | +|---|---|---|---|---|---| +| `MAIN` | violated | holds | not checked ¹ | violated: renewal with fetch, acknowledge and abandon | violated | +| `PR43` | violated | holds | not checked ¹ | holds | holds | +| `FIXED` | **holds** | **holds** | **holds** | **holds** | **holds** | + +¹ The consumption counterexample is itself an acknowledge that commits after its +token was replaced. + +Exhaustive passes for `FIXED`: + +| Configuration | Calls checked | Distinct states | Depth | +|---|---|---:|---:| +| `FIXED-safety` | acknowledge, fetch then acknowledge, renewal | 3,854,292 | 39 | +| `FIXED-abandon` | abandon, fetch then acknowledge, renewal | 4,227,695 | 40 | +| `FIXED-redelivery` | acknowledge, then two later fetches with acknowledge | 286,344 | 45 | +| `FIXED-release-race` | acknowledge and abandon on the same token | 1,894 | 18 | + +Shortest counterexamples on the earlier variants: + +| Configuration | Invariant | Trace | +|---|---|---| +| `MAIN-consumption`, `PR43-consumption` | `ExactlyOnceConsumption` | 20 states: the acknowledge passes its token check, a fetch whose clock runs ahead takes over and commits, then the acknowledge's deletes match no row and it commits | +| `MAIN-zero-skew-consumption` | `ExactlyOnceConsumption` | 22 states, no skew: the lease expires during the acknowledge | +| `MAIN-redelivery`, `PR43-redelivery` | `NoDuplicateConsumption` | 45 states: a later fetch consumes the same messages a second time | +| `MAIN-release-race`, `PR43-release-race` | `ExactlyOnceConsumption` | 15 states: an abandon with the same token commits in the middle of the acknowledge | +| `MAIN-deadlock-fetch`, `-ack`, `-abandon` | `NoDeadlock` | 9 to 11 states: renewal locks the instance row, then the queue rows | +| `MAIN-shortening` | `NeverShorten` | 7 states | +| `MAIN-revival` | `NoExpiredRenewalAtCheck` | 8 states: renewal accepts an expired lease using a stale caller time | + +The stricter clock properties fail in every variant, including `FIXED` with zero +skew. A renewal reads the clock, then stalls before it writes. It can then +commit a deadline that has already passed. No fetch can take the instance +during that stall, because renewal holds the advisory lock. Afterwards the +expired lease can be taken over normally, and the old owner's acknowledge then +fails on its token. This is a liveness cost, not an ownership failure. + +## Limits + +- Bounded: up to 3 concurrent calls, 2 workers, 1 instance, 2 messages and a + few ticks. TLC's fingerprint-collision estimate is in each log. +- Fetch's candidate loop is reduced to one attempt for one instance. So the + advisory-lock deadlock between fetches for different instances is not + covered. +- Not modelled: + - the worker queue and activity leases; + - sessions; + - `ContinueAsNew`; + - administrative deletes; + - the runtime's replay logic, which the invariants stand in for. +- An acknowledge always adds one history position and consumes the whole batch. +- The model was written with the known failures in view. A version written + independently from the provider contract alone would be a stronger check. diff --git a/docs/tla/orchestration-leases/SOURCE-MAP.md b/docs/tla/orchestration-leases/SOURCE-MAP.md new file mode 100644 index 0000000..e16709c --- /dev/null +++ b/docs/tla/orchestration-leases/SOURCE-MAP.md @@ -0,0 +1,46 @@ +# Source map + +Each TLA+ action in `LeaseProtocol.tla`, mapped to the SQL or Rust it models. +Paths without a prefix are in `microsoft/duroxide-pg`. "Core" means +`microsoft/duroxide` v0.1.32 (`585c89c`). + +Line numbers are pinned to these commits: + +| Variant | Commit | +|---|---| +| `MAIN` | `3beba92048b9fd6c9e68262a3e3fa192441c1e31` | +| `PR43` | `b2ff29633a5ea437f8f1e737429d7ba9170ba491` | +| `FIXED` | `ea598d91839b6d656917a47a3b4e772fa515b9aa` | + +The executable `DO $$` block of migration `0026` is byte-identical in later +commits of the same change. Only the header comment grew, by one line. + +| TLA+ action | SQL/Rust source at that SHA | +| --- | --- | +| Begin / Arrival | PR43 `src/provider.rs:1000-1024,1320-1334,1937-1947`; Rust samples raw time before pool acquisition; function entry captures PostgreSQL statement time. | +| FetchCandidate | `migrations/0025_fetch_orchestration_lease_at_claim.sql:88-96`; visible row and raw-clock lease-expiry predicate. | +| Advisory (fetch) | Same `0025:103-104`. | +| FetchQueueSelect | Same `0025:127-139`; repeated availability check and queue `FOR UPDATE SKIP LOCKED`. | +| FetchComputeLease | Same `0025:146-151`; max(caller + elapsed, DB) + lease. | +| FetchInstance | Same `0025:153-165`; insert/upsert token, conditional on raw-clock expiry. | +| FetchQueueUpdate / FetchMessages | Same `0025:168-181`; queue takeover and own-write-visible input read. | +| FetchHistory | Same `0025:189-201`; new committed snapshot, no history row lock. | +| Lookup (old ack) | `migrations/0020_add_kv_delta.sql:73-80`; plain token/expiry SELECT. | +| AckHistory | Same `0020:91-126`; metadata row serialization and history unique-key INSERT. | +| AckOutputs | Same `0020:221-291`; durable work enqueues and other atomic output changes. | +| ReleaseQueue / ReleaseInstance (old ack) | Same `0020:294-299`; token-matching DELETEs with no count check. | +| Lookup / ReleaseQueue / ReleaseInstance (abandon) | `migrations/0006_use_rust_timestamps.sql:101-107,141-149`; token-only SELECT, queue clear then lock delete. | +| MainRenewInstance / RenewQueue | MAIN `migrations/0004_update_stored_procedures_for_attempt_count.sql:349-364`; raw-time deadline, instance-before-queue order. | +| Lookup / Advisory (new renew) | PR43 `migrations/0026_serialize_orchestration_lock_mutations.sql:53-62`. | +| RenewSampleNow / RenewRecheck | Same `0026:64-78`; clock assignment and subsequent token/expiry SELECT are distinct steps. | +| RenewQueue / RenewInstance (new renew) | Same `0026:80-93`; queue then instance, zero instance UPDATE count raises. | +| Lookup / Advisory / AckRecheck (fixed ack) | FIXED `migrations/0026_serialize_orchestration_lock_mutations.sql:153-178`; initial expiry check, advisory lock, token-only recheck. | +| AckHistory / AckOutputs (fixed ack) | Same `0026:189-224,319-389`. | +| ReleaseQueue / ReleaseInstance (fixed ack) | Same `0026:392-405`; queue delete is unchecked; instance delete is checked. | +| Commit / Rollback | Each provider call is one autocommit SQL statement. Procedure exceptions roll back its writes and release transaction locks. | +| SingleWriter | `migrations/0001_initial_schema.sql:29-37`; primary key on instance/execution/event. | +| Core atomicity contract | Core `src/providers/mod.rs:1278-1328`. | +| Core cancellation | Core `docs/provider-implementation-guide.md:342-361`; a cancelled await is not proof of rollback. | +| Renewal start guard tick >= R | Core `src/runtime/dispatchers/orchestration.rs:262-321`; default 5 s lease yields ceil(2.5) = 3 s renewal interval. Core `src/runtime/mod.rs:359-362`; activity default 30 s / 25 s renewal. | +| Ack failures / retries | Core `src/runtime/dispatchers/orchestration.rs:989-1056,1200-1249`; storage failure path is not a message deduplicator. PR43 `src/provider.rs:589-621,1353-1384`; 23505 is permanent, 40P01 retryable. | +| NoDuplicateConsumption | Core `src/runtime/replay_engine.rs:131-183,464-486`; ExternalRaised and QueueMessage are not deduplicated. | diff --git a/docs/tla/orchestration-leases/configs/FIXED-abandon.cfg b/docs/tla/orchestration-leases/configs/FIXED-abandon.cfg new file mode 100644 index 0000000..574cade --- /dev/null +++ b/docs/tla/orchestration-leases/configs/FIXED-abandon.cfg @@ -0,0 +1,17 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "FIXED" + N = 2 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 3 + Kinds <- AbandonFetchRenew + Owners <- TwoWorkersThreeCalls + FetchThenAck = TRUE + AllowCancellation = TRUE +INVARIANTS TypeOK ExactlyOnceConsumption SingleWriter NoDuplicateConsumption + AtomicOutputs NoMessageLoss QueueLeaseAgreement NoStaleRenewal + NoStaleAck NeverShorten NoDeadlock +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/FIXED-deadline-publication.cfg b/docs/tla/orchestration-leases/configs/FIXED-deadline-publication.cfg new file mode 100644 index 0000000..daaf877 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/FIXED-deadline-publication.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "FIXED" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 0 + Horizon = 4 + Kinds <- RenewOnly + Owners <- OneWorker + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK RenewalDeadlineLiveAtCommit +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/FIXED-redelivery.cfg b/docs/tla/orchestration-leases/configs/FIXED-redelivery.cfg new file mode 100644 index 0000000..345f0dd --- /dev/null +++ b/docs/tla/orchestration-leases/configs/FIXED-redelivery.cfg @@ -0,0 +1,16 @@ +SPECIFICATION SpecRedelivery +CONSTANTS + Variant = "FIXED" + N = 2 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 3 + Kinds <- AckFetchFetch + Owners <- RedeliveryOwners + FetchThenAck = TRUE + AllowCancellation = FALSE +INVARIANTS TypeOK ExactlyOnceConsumption SingleWriter NoDuplicateConsumption + AtomicOutputs NoMessageLoss QueueLeaseAgreement NoStaleAck NoDeadlock +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/FIXED-release-race.cfg b/docs/tla/orchestration-leases/configs/FIXED-release-race.cfg new file mode 100644 index 0000000..b7aeab5 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/FIXED-release-race.cfg @@ -0,0 +1,16 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "FIXED" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 0 + Horizon = 2 + Kinds <- AckAbandon + Owners <- OneWorkerTwoCalls + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK ExactlyOnceConsumption SingleWriter NoDuplicateConsumption + AtomicOutputs NoMessageLoss QueueLeaseAgreement NoStaleAck NoDeadlock +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/FIXED-safety.cfg b/docs/tla/orchestration-leases/configs/FIXED-safety.cfg new file mode 100644 index 0000000..d5adabc --- /dev/null +++ b/docs/tla/orchestration-leases/configs/FIXED-safety.cfg @@ -0,0 +1,17 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "FIXED" + N = 2 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 3 + Kinds <- AckFetchRenew + Owners <- TwoWorkersThreeCalls + FetchThenAck = TRUE + AllowCancellation = TRUE +INVARIANTS TypeOK ExactlyOnceConsumption SingleWriter NoDuplicateConsumption + AtomicOutputs NoMessageLoss QueueLeaseAgreement NoStaleRenewal + NoStaleAck NeverShorten NoDeadlock +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/FIXED-strict-clock.cfg b/docs/tla/orchestration-leases/configs/FIXED-strict-clock.cfg new file mode 100644 index 0000000..a6263f2 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/FIXED-strict-clock.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "FIXED" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 0 + Horizon = 3 + Kinds <- RenewOnly + Owners <- OneWorker + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK NoExpiredRenewalAtWrite +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/FIXED-strict-validation.cfg b/docs/tla/orchestration-leases/configs/FIXED-strict-validation.cfg new file mode 100644 index 0000000..71c7224 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/FIXED-strict-validation.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "FIXED" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 0 + Horizon = 3 + Kinds <- RenewOnly + Owners <- OneWorker + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK NoExpiredRenewalAtCheck +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/MAIN-consumption.cfg b/docs/tla/orchestration-leases/configs/MAIN-consumption.cfg new file mode 100644 index 0000000..6edb930 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/MAIN-consumption.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "MAIN" + N = 2 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 3 + Kinds <- AckFetch + Owners <- TwoWorkers + FetchThenAck = TRUE + AllowCancellation = TRUE +INVARIANTS TypeOK ExactlyOnceConsumption +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/MAIN-deadline-publication.cfg b/docs/tla/orchestration-leases/configs/MAIN-deadline-publication.cfg new file mode 100644 index 0000000..b037dd0 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/MAIN-deadline-publication.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "MAIN" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 0 + Horizon = 4 + Kinds <- RenewOnly + Owners <- OneWorker + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK RenewalDeadlineLiveAtCommit +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/MAIN-deadlock-abandon.cfg b/docs/tla/orchestration-leases/configs/MAIN-deadlock-abandon.cfg new file mode 100644 index 0000000..bed01ca --- /dev/null +++ b/docs/tla/orchestration-leases/configs/MAIN-deadlock-abandon.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "MAIN" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 0 + Horizon = 2 + Kinds <- RenewAbandon + Owners <- OneWorkerTwoCalls + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK NoDeadlock +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/MAIN-deadlock-ack.cfg b/docs/tla/orchestration-leases/configs/MAIN-deadlock-ack.cfg new file mode 100644 index 0000000..851eac6 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/MAIN-deadlock-ack.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "MAIN" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 0 + Horizon = 2 + Kinds <- RenewAck + Owners <- OneWorkerTwoCalls + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK NoDeadlock +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/MAIN-deadlock-fetch.cfg b/docs/tla/orchestration-leases/configs/MAIN-deadlock-fetch.cfg new file mode 100644 index 0000000..4eca12f --- /dev/null +++ b/docs/tla/orchestration-leases/configs/MAIN-deadlock-fetch.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "MAIN" + N = 2 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 3 + Kinds <- RenewFetch + Owners <- TwoWorkers + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK NoDeadlock +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/MAIN-redelivery.cfg b/docs/tla/orchestration-leases/configs/MAIN-redelivery.cfg new file mode 100644 index 0000000..28c2f44 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/MAIN-redelivery.cfg @@ -0,0 +1,15 @@ +SPECIFICATION SpecRedelivery +CONSTANTS + Variant = "MAIN" + N = 2 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 3 + Kinds <- AckFetchFetch + Owners <- RedeliveryOwners + FetchThenAck = TRUE + AllowCancellation = FALSE +INVARIANTS TypeOK SingleWriter NoDuplicateConsumption +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/MAIN-release-race.cfg b/docs/tla/orchestration-leases/configs/MAIN-release-race.cfg new file mode 100644 index 0000000..e2135f8 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/MAIN-release-race.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "MAIN" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 0 + Horizon = 2 + Kinds <- AckAbandon + Owners <- OneWorkerTwoCalls + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK ExactlyOnceConsumption +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/MAIN-revival.cfg b/docs/tla/orchestration-leases/configs/MAIN-revival.cfg new file mode 100644 index 0000000..095077a --- /dev/null +++ b/docs/tla/orchestration-leases/configs/MAIN-revival.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "MAIN" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 4 + Kinds <- RenewOnly + Owners <- OneWorker + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK NoExpiredRenewalAtCheck +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/MAIN-shortening.cfg b/docs/tla/orchestration-leases/configs/MAIN-shortening.cfg new file mode 100644 index 0000000..4035e26 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/MAIN-shortening.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "MAIN" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 3 + Kinds <- RenewOnly + Owners <- OneWorker + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK NeverShorten +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/MAIN-structure.cfg b/docs/tla/orchestration-leases/configs/MAIN-structure.cfg new file mode 100644 index 0000000..f3b064b --- /dev/null +++ b/docs/tla/orchestration-leases/configs/MAIN-structure.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "MAIN" + N = 2 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 3 + Kinds <- AckFetchRenew + Owners <- TwoWorkersThreeCalls + FetchThenAck = TRUE + AllowCancellation = TRUE +INVARIANTS TypeOK SingleWriter AtomicOutputs NoMessageLoss QueueLeaseAgreement NoStaleRenewal +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/MAIN-zero-skew-consumption.cfg b/docs/tla/orchestration-leases/configs/MAIN-zero-skew-consumption.cfg new file mode 100644 index 0000000..0e47a8c --- /dev/null +++ b/docs/tla/orchestration-leases/configs/MAIN-zero-skew-consumption.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "MAIN" + N = 2 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 0 + Horizon = 3 + Kinds <- AckFetch + Owners <- TwoWorkers + FetchThenAck = TRUE + AllowCancellation = TRUE +INVARIANTS TypeOK ExactlyOnceConsumption +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/PR43-abandon.cfg b/docs/tla/orchestration-leases/configs/PR43-abandon.cfg new file mode 100644 index 0000000..a95cb3c --- /dev/null +++ b/docs/tla/orchestration-leases/configs/PR43-abandon.cfg @@ -0,0 +1,17 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "PR43" + N = 2 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 3 + Kinds <- AbandonFetchRenew + Owners <- TwoWorkersThreeCalls + FetchThenAck = TRUE + AllowCancellation = TRUE +INVARIANTS TypeOK ExactlyOnceConsumption SingleWriter NoDuplicateConsumption + AtomicOutputs NoMessageLoss QueueLeaseAgreement NoStaleRenewal + NeverShorten NoDeadlock +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/PR43-consumption.cfg b/docs/tla/orchestration-leases/configs/PR43-consumption.cfg new file mode 100644 index 0000000..cd5d005 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/PR43-consumption.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "PR43" + N = 2 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 3 + Kinds <- AckFetch + Owners <- TwoWorkers + FetchThenAck = TRUE + AllowCancellation = TRUE +INVARIANTS TypeOK ExactlyOnceConsumption +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/PR43-deadline-publication.cfg b/docs/tla/orchestration-leases/configs/PR43-deadline-publication.cfg new file mode 100644 index 0000000..486cc47 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/PR43-deadline-publication.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "PR43" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 0 + Horizon = 4 + Kinds <- RenewOnly + Owners <- OneWorker + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK RenewalDeadlineLiveAtCommit +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/PR43-redelivery.cfg b/docs/tla/orchestration-leases/configs/PR43-redelivery.cfg new file mode 100644 index 0000000..d431290 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/PR43-redelivery.cfg @@ -0,0 +1,15 @@ +SPECIFICATION SpecRedelivery +CONSTANTS + Variant = "PR43" + N = 2 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 3 + Kinds <- AckFetchFetch + Owners <- RedeliveryOwners + FetchThenAck = TRUE + AllowCancellation = FALSE +INVARIANTS TypeOK SingleWriter NoDuplicateConsumption +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/PR43-release-race.cfg b/docs/tla/orchestration-leases/configs/PR43-release-race.cfg new file mode 100644 index 0000000..a866b99 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/PR43-release-race.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "PR43" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 0 + Horizon = 2 + Kinds <- AckAbandon + Owners <- OneWorkerTwoCalls + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK ExactlyOnceConsumption +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/PR43-safety.cfg b/docs/tla/orchestration-leases/configs/PR43-safety.cfg new file mode 100644 index 0000000..19dcdad --- /dev/null +++ b/docs/tla/orchestration-leases/configs/PR43-safety.cfg @@ -0,0 +1,16 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "PR43" + N = 2 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 2 + Horizon = 3 + Kinds <- AckFetchRenew + Owners <- TwoWorkersThreeCalls + FetchThenAck = TRUE + AllowCancellation = TRUE +INVARIANTS TypeOK SingleWriter AtomicOutputs NoMessageLoss + QueueLeaseAgreement NoStaleRenewal NeverShorten NoDeadlock +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/configs/PR43-strict-validation.cfg b/docs/tla/orchestration-leases/configs/PR43-strict-validation.cfg new file mode 100644 index 0000000..d856c31 --- /dev/null +++ b/docs/tla/orchestration-leases/configs/PR43-strict-validation.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec +CONSTANTS + Variant = "PR43" + N = 1 + Messages = {m1, m2} + L = 2 + R = 1 + MaxSkew = 0 + Horizon = 3 + Kinds <- RenewOnly + Owners <- OneWorker + FetchThenAck = FALSE + AllowCancellation = TRUE +INVARIANTS TypeOK NoExpiredRenewalAtCheck +CHECK_DEADLOCK FALSE diff --git a/docs/tla/orchestration-leases/expected.tsv b/docs/tla/orchestration-leases/expected.tsv new file mode 100644 index 0000000..3d9c9f3 --- /dev/null +++ b/docs/tla/orchestration-leases/expected.tsv @@ -0,0 +1,26 @@ +# config module heap expected distinct_states depth +MAIN-consumption LeaseProtocol 4g violates:ExactlyOnceConsumption 124568 20 +MAIN-deadline-publication LeaseProtocol 512m violates:RenewalDeadlineLiveAtCommit 87 9 +MAIN-deadlock-abandon LeaseProtocol 512m violates:NoDeadlock 319 9 +MAIN-deadlock-ack LeaseProtocol 512m violates:NoDeadlock 529 11 +MAIN-deadlock-fetch LeaseProtocol 512m violates:NoDeadlock 28431 11 +MAIN-redelivery LeaseRedelivery 1g violates:NoDuplicateConsumption 289108 45 +MAIN-release-race LeaseReleaseRace 512m violates:ExactlyOnceConsumption 1457 15 +MAIN-revival LeaseProtocol 512m violates:NoExpiredRenewalAtCheck 308 8 +MAIN-shortening LeaseProtocol 512m violates:NeverShorten 160 7 +MAIN-structure LeaseProtocol 4g holds 3094484 32 +MAIN-zero-skew-consumption LeaseProtocol 512m violates:ExactlyOnceConsumption 4671 22 +PR43-abandon LeaseProtocol 4g holds 4225603 38 +PR43-consumption LeaseProtocol 4g violates:ExactlyOnceConsumption 124568 20 +PR43-deadline-publication LeaseProtocol 512m violates:RenewalDeadlineLiveAtCommit 144 13 +PR43-redelivery LeaseRedelivery 1g violates:NoDuplicateConsumption 289108 45 +PR43-release-race LeaseReleaseRace 512m violates:ExactlyOnceConsumption 1457 15 +PR43-safety LeaseProtocol 4g holds 4960731 36 +PR43-strict-validation LeaseProtocol 512m violates:NoExpiredRenewalAtCheck 77 12 +FIXED-abandon LeaseProtocol 4g holds 4227695 40 +FIXED-deadline-publication LeaseProtocol 512m violates:RenewalDeadlineLiveAtCommit 144 13 +FIXED-redelivery LeaseRedelivery 1g holds 286344 45 +FIXED-release-race LeaseReleaseRace 512m holds 1894 18 +FIXED-safety LeaseProtocol 4g holds 3854292 39 +FIXED-strict-clock LeaseProtocol 512m violates:NoExpiredRenewalAtWrite 77 12 +FIXED-strict-validation LeaseProtocol 512m violates:NoExpiredRenewalAtCheck 77 12 diff --git a/docs/tla/orchestration-leases/run.sh b/docs/tla/orchestration-leases/run.sh new file mode 100755 index 0000000..b6e40d4 --- /dev/null +++ b/docs/tla/orchestration-leases/run.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# +# Model-check the orchestration lease specification with TLC and compare each +# result with expected.tsv. +# +# Usage: ./run.sh [config ...] +# With no arguments, runs every configuration in expected.tsv. +# +# Needs Java 17 or newer. Downloads tla2tools.jar v1.7.4 (TLC 2.19) on first +# use and checks its SHA-256, unless TLA2TOOLS_JAR points to a local copy. +# Exits non-zero if any result differs from expected.tsv. + +set -uo pipefail +cd "$(dirname "$0")" + +JAR_URL="https://github.com/tlaplus/tlaplus/releases/download/v1.7.4/tla2tools.jar" +JAR_SHA256="936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88" +JAR="${TLA2TOOLS_JAR:-tla2tools.jar}" + +sha256() { + if command -v sha256sum >/dev/null 2>&1; then + sha256sum "$1" | cut -d' ' -f1 + else + shasum -a 256 "$1" | cut -d' ' -f1 + fi +} + +if [ ! -f "$JAR" ]; then + curl -fsSL -o "$JAR" "$JAR_URL" || { echo "failed to download $JAR_URL" >&2; exit 2; } +fi +if [ "$(sha256 "$JAR")" != "$JAR_SHA256" ]; then + echo "$JAR does not match the expected SHA-256 $JAR_SHA256" >&2 + exit 2 +fi + +if [ "$#" -eq 0 ]; then + set -- $(awk -F'\t' '!/^#/ { print $1 }' expected.tsv) +fi + +mkdir -p logs states +failures=0 +for name in "$@"; do + row="$(awk -F'\t' -v n="$name" '$1 == n' expected.tsv)" + if [ -z "$row" ]; then + echo "UNKNOWN $name (not in expected.tsv)" + failures=$((failures + 1)) + continue + fi + IFS=$'\t' read -r _ module heap expected distinct depth <<< "$row" + + start=$(date +%s) + java -Xmx"$heap" -XX:+UseParallelGC -cp "$JAR" tlc2.TLC \ + -workers 1 -config "configs/$name.cfg" -metadir "states/$name" \ + "$module" > "logs/$name.log" 2>&1 + seconds=$(( $(date +%s) - start )) + + if grep -q 'Model checking completed. No error has been found.' "logs/$name.log"; then + actual="holds" + elif violated=$(grep -oE 'Invariant [A-Za-z]+ is violated' "logs/$name.log" | head -1 | cut -d' ' -f2) \ + && [ -n "$violated" ]; then + actual="violates:$violated" + else + actual="error" + fi + found=$(grep -oE '[0-9]+ distinct states found' "logs/$name.log" | tail -1 | cut -d' ' -f1) + + status="PASS" + if [ "$actual" != "$expected" ]; then + status="FAIL" + elif [ "$actual" = "holds" ] && [ "$found" != "$distinct" ]; then + status="FAIL" + fi + [ "$status" = "FAIL" ] && failures=$((failures + 1)) + printf '%s %-28s %-38s distinct=%s (expected %s) %ss\n' \ + "$status" "$name" "$actual" "${found:-?}" "$distinct" "$seconds" +done + +if [ "$failures" -gt 0 ]; then + echo "$failures configuration(s) did not match expected.tsv; see logs/" >&2 + exit 1 +fi +echo "All configurations match expected.tsv."