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..bdbb27b --- /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 new file mode 100644 index 0000000..01f00d5 --- /dev/null +++ b/tests/fetch_renew_lock_order_repro_tests.rs @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Regression test for the orchestration fetch/renew lock-order deadlock. +//! +//! 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::{PgConnection, PgPoolOptions}; +use sqlx::{Connection, PgPool}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use tokio::sync::oneshot; + +const ORCHESTRATION: &str = "FetchRenewLockOrder"; + +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 drop_schema(pool: &PgPool, schema: &str) { + sqlx::query(&format!("DROP SCHEMA IF EXISTS {schema} CASCADE")) + .execute(pool) + .await + .expect("failed to drop test schema"); +} + +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; + } + + 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_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)) + .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"); + + 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!( + "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({ready_key}); + PERFORM pg_advisory_xact_lock({gate_key}); + 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_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 + }); + + 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; + + renewal_result.expect("renewal must complete without a deadlock"); + fetch_result.expect("fetch must complete without a deadlock"); +}