Repository navigation
fix: serialize orchestration lock renewal with fetch #43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c203c41
test: reproduce fetch-renew lock order deadlock
85bf504
test: retain deadlock SQLSTATE for assertion
53c6ed4
fix: serialize orchestration lock renewal with fetch
ebf85aa
test: remove lock-order regression warning
4628786
docs: normalize migration diff whitespace
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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. |
64 changes: 64 additions & 0 deletions
64
migrations/0026_serialize_orchestration_lock_mutations.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 $$; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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_<uuid>`, 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"); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could we add a separate regression for renewal waiting while a real fetch replaces its token? This added regression reaches line 192 after renewal holds the production instance advisory key, so fetch waits instead; it does not exercise ownership changing during renewal's wait.
Head's guard is correct; this is regression protection, not a current defect. In prior disposable PostgreSQL 15 READ COMMITTED checks, removing only
AND lock_token = p_lock_tokenatmigrations/0026_serialize_orchestration_lock_mutations.sql:49left this added regression passing 3/3. A separate wait-then-replace schedule made that mutant overwrite the replacement instance lease, whereas intact head rejected renewal with the intendedP0001and preserved the replacement lease.Suggested schedule:
The future caller timestamp makes reclamation deterministic without a wall-clock sleep. The token-predicate mutant would fail the replacement-state assertion. Equivalent existing coverage of this exact blocked-renewal/replacement schedule would satisfy the request; upstream provider-validation bodies were not inspected or run, so their coverage is unknown.