From ee091b4b6eb158101b7474264af3520ef28cf4a4 Mon Sep 17 00:00:00 2001 From: Sanapach Date: Thu, 26 Nov 2026 19:36:27 +0200 Subject: [PATCH] Apply a playlist item again when PostgreSQL aborts it for a deadlock Applying an item now changes its register and playlist row in one transaction, register first. Library cleanup and metadata fixes delete playlist rows before they detach registers, so the two could deadlock and the sync exchange failed with the operation already journaled. A deadlock or serialization failure now runs the item again, up to three times, from its register. Reordering the locks would instead conflict with the import publisher, which locks registers before writing playlist rows. Co-Authored-By: Claude Opus 5.5 --- src/federation/devices.rs | 54 +++++++++++++++++++++++++++ src/library_import/tests/publisher.rs | 53 ++++++++++++++++++++++++++ 2 files changed, 107 insertions(+) diff --git a/src/federation/devices.rs b/src/federation/devices.rs index 3c75451..7d117c6 100644 --- a/src/federation/devices.rs +++ b/src/federation/devices.rs @@ -2562,6 +2562,25 @@ async fn apply_playlist_state( Ok(true) } +/// Attempts of [`apply_playlist_item_state`] when PostgreSQL aborts it to +/// break a deadlock or a serialization conflict. +const ITEM_STATE_ATTEMPTS: usize = 3; + +/// A deadlock or serialization failure: the transaction can simply run again. +fn is_transient_conflict(error: &anyhow::Error) -> bool { + error + .chain() + .any(|cause| match cause.downcast_ref::() { + Some(sqlx::Error::Database(db)) => { + matches!(db.code().as_deref(), Some("40P01" | "40001")) + } + _ => false, + }) +} + +/// Its transaction locks the register before the playlist row, while library +/// cleanup and metadata fixes lock the playlist row first, so PostgreSQL may +/// abort one of them; the item is then applied again from its register. #[allow(clippy::too_many_arguments)] async fn apply_playlist_item_state( pool: &sqlx::PgPool, @@ -2573,6 +2592,41 @@ async fn apply_playlist_item_state( fed: Option<&SyncedFedTrack>, hlc_ms: i64, op_id: &str, +) -> Result { + let mut attempt = 1; + loop { + match apply_playlist_item_state_once( + pool, + user_id, + playlist_id, + content_id, + present, + position, + fed, + hlc_ms, + op_id, + ) + .await + { + Err(error) if attempt < ITEM_STATE_ATTEMPTS && is_transient_conflict(&error) => { + attempt += 1; + } + result => return result, + } + } +} + +#[allow(clippy::too_many_arguments)] +async fn apply_playlist_item_state_once( + pool: &sqlx::PgPool, + user_id: i64, + playlist_id: &str, + content_id: &str, + present: bool, + position: i64, + fed: Option<&SyncedFedTrack>, + hlc_ms: i64, + op_id: &str, ) -> Result { let Some(content_id) = music_dht::normalize_content_id(content_id) else { return Ok(false); diff --git a/src/library_import/tests/publisher.rs b/src/library_import/tests/publisher.rs index 366e46a..46329ae 100644 --- a/src/library_import/tests/publisher.rs +++ b/src/library_import/tests/publisher.rs @@ -1249,6 +1249,59 @@ async fn library_import_registers_and_playlist_rows_stay_consistent_under_concur fixture.drop().await; } +/// Library cleanup deletes playlist rows and then detaches registers, the +/// opposite order of an applied operation. When PostgreSQL breaks the +/// deadlock by aborting the operation, it is applied again. +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_sync_apply_retries_after_a_deadlock_with_cleanup() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 1).await; + trust_remote(pool).await; + let import_id = matched_import(pool, "deadlock", &[("Deadlock", vec![Entry::Local(1)])]).await; + publish(pool, 885).await; + let road = target(pool, import_id, 0).await.unwrap(); + + // The cleanup, as in `library_cleanup::delete_database_rows`. Its own + // deadlock check comes late, so the operation is the one aborted. + let mut cleanup = pool.begin().await.unwrap(); + sqlx::query("SET LOCAL deadlock_timeout = '10s'") + .execute(&mut *cleanup) + .await + .unwrap(); + sqlx::query("DELETE FROM furumusic__playlist_track WHERE track_id = ANY($1)") + .bind(vec![1001_i64]) + .execute(&mut *cleanup) + .await + .unwrap(); + let task_pool = pool.clone(); + let removal = tokio::spawn(async move { + devices::apply_received_ops( + &task_pool, + USER, + vec![remote_op(REMOTE, 1, now_ms() + 1_000_000, removed(road, 1))], + ) + .await + }); + wait_for_lock(pool).await; + let detached = sqlx::query( + "UPDATE furumusic__fed_state_playlist_item SET local_track_id = NULL + WHERE local_track_id = ANY($1)", + ) + .bind(vec![1001_i64]) + .execute(&mut *cleanup) + .await + .unwrap() + .rows_affected(); + assert_eq!(detached, 1); + cleanup.commit().await.unwrap(); + removal.await.unwrap().unwrap(); + assert!(!register(pool, road, 1).await.unwrap().0); + assert!(rows(pool, road).await.is_empty()); + fixture.drop().await; +} + #[tokio::test] #[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] async fn library_import_publications_of_one_user_run_one_after_another() {