From c60fb08b9536b72787a05123d779885f4e35f44d Mon Sep 17 00:00:00 2001 From: Sanapach Date: Thu, 26 Nov 2026 19:31:57 +0200 Subject: [PATCH] Pause an import playlist only for the target the worker saw The publisher reads the targets once per phase. When the user deleted a target and asked to recreate it while another playlist was publishing, the worker reached it with its old view and paused it again, undoing the request it had already confirmed. A pause now applies only while the target is still the one the worker read; otherwise the requested rerun publishes into a new target. Co-Authored-By: Claude Opus 5.5 --- src/library_import/publisher.rs | 15 +++-- src/library_import/store.rs | 34 +++++++--- src/library_import/tests/publisher.rs | 97 +++++++++++++++++++++++++++ 3 files changed, 132 insertions(+), 14 deletions(-) diff --git a/src/library_import/publisher.rs b/src/library_import/publisher.rs index a870b5f..3fdaa6b 100644 --- a/src/library_import/publisher.rs +++ b/src/library_import/publisher.rs @@ -182,7 +182,7 @@ impl<'a> Publisher<'a> { pub async fn step(&mut self, progress: &mut Progress) -> Result { let target = &progress.target; if target.paused || (target.target_created && target.target_playlist_id.is_none()) { - return self.pause(target.id).await; + return self.pause(target.id, target.target_playlist_id).await; } let target_id = match target.target_playlist_id { Some(id) => id, @@ -217,16 +217,19 @@ impl<'a> Publisher<'a> { let source = progress.target.id; match self.publish_batch(source, target_id, entries).await? { BatchEnd::Continue => Ok(Step::More), - BatchEnd::Paused => self.pause(source).await, + BatchEnd::Paused => self.pause(source, Some(target_id)).await, BatchEnd::LeaseLost => Ok(Step::LeaseLost), } } - async fn pause(&mut self, source: i64) -> Result { - if !store::pause_playlist(self.pool, self.import.id, self.run_id, source).await? { - return Ok(Step::LeaseLost); + /// Pauses the source playlist unless its target changed since it was + /// read: a `…/recreate` meanwhile must not be undone. + async fn pause(&mut self, source: i64, target: Option) -> Result { + match store::pause_playlist(self.pool, self.import.id, self.run_id, source, target).await? { + store::PauseOutcome::Paused => self.report.paused_playlists += 1, + store::PauseOutcome::TargetChanged => {} + store::PauseOutcome::LeaseLost => return Ok(Step::LeaseLost), } - self.report.paused_playlists += 1; Ok(Step::Finished) } diff --git a/src/library_import/store.rs b/src/library_import/store.rs index 0746aea..7fa1dbb 100644 --- a/src/library_import/store.rs +++ b/src/library_import/store.rs @@ -1184,25 +1184,43 @@ pub async fn defer_playlist(conn: &mut PgConnection, import_playlist_id: i64) -> .rows_affected()) } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PauseOutcome { + Paused, + /// The target changed since the worker read it (`…/recreate` reset it), + /// so nothing is paused; the requested rerun publishes with the new one. + TargetChanged, + LeaseLost, +} + /// Stops publication into a deleted target playlist: the playlist is marked -/// paused and its waiting entries `paused`, until `…/recreate`. `false` -/// without the lease. +/// paused and its waiting entries `paused`, until `…/recreate`. Only the +/// target the worker saw (`expected_target`, or none) is paused, also once +/// its deletion has set it to NULL; `…/recreate` clears the creation time. pub async fn pause_playlist( pool: &PgPool, import_id: i64, run_id: i64, import_playlist_id: i64, -) -> sqlx::Result { + expected_target: Option, +) -> sqlx::Result { let mut tx = pool.begin().await?; if !hold_lease(&mut tx, import_id, run_id).await? { - return Ok(false); + return Ok(PauseOutcome::LeaseLost); } - sqlx::query( - "UPDATE furumusic__library_import_playlist SET publication_paused = true WHERE id = $1", + let paused = sqlx::query( + "UPDATE furumusic__library_import_playlist SET publication_paused = true + WHERE id = $1 AND target_created_at IS NOT NULL + AND (target_playlist_id IS NULL OR target_playlist_id = $2)", ) .bind(import_playlist_id) + .bind(expected_target) .execute(&mut *tx) - .await?; + .await? + .rows_affected(); + if paused == 0 { + return Ok(PauseOutcome::TargetChanged); + } sqlx::query(&format!( "UPDATE furumusic__library_import_item SET publication_status = 'paused', last_attempt_at = now() @@ -1213,7 +1231,7 @@ pub async fn pause_playlist( .execute(&mut *tx) .await?; tx.commit().await?; - Ok(true) + Ok(PauseOutcome::Paused) } /// A receipt: `content_id` was given to a target playlist by `item_id`. diff --git a/src/library_import/tests/publisher.rs b/src/library_import/tests/publisher.rs index 87b6cc8..366e46a 100644 --- a/src/library_import/tests/publisher.rs +++ b/src/library_import/tests/publisher.rs @@ -349,6 +349,24 @@ async fn join(spawned: &Spawned) { handle.await.unwrap(); } +/// Waits until some backend of the test database waits for a lock. +async fn wait_for_lock(pool: &PgPool) { + for _ in 0..500 { + let waiting: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_stat_activity + WHERE datname = current_database() AND wait_event_type = 'Lock'", + ) + .fetch_one(pool) + .await + .unwrap(); + if waiting > 0 { + return; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("nothing waits for a lock"); +} + async fn setup() -> (tokio::sync::MutexGuard<'static, ()>, Fixture) { let serial = SERIAL.lock().await; hooks::clear(); @@ -593,6 +611,85 @@ async fn library_import_never_restores_removed_tracks_or_deleted_playlists() { fixture.drop().await; } +/// `…/recreate` while the worker publishes another playlist: the worker +/// still sees the deleted target it read at the start of the phase, and +/// must not pause the playlist again. +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_recreate_during_publication_is_not_undone() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 4).await; + let import_id = matched_import( + pool, + "stale", + &[ + ("First", vec![Entry::Local(1), Entry::Unmatched]), + ("Second", vec![Entry::Local(2), Entry::Unmatched]), + ], + ) + .await; + publish(pool, 821).await; + let second = target(pool, import_id, 1).await.unwrap(); + devices::record_playlist_deleted(pool, USER, second) + .await + .unwrap(); + sqlx::query("DELETE FROM furumusic__playlist_track WHERE playlist_id = $1") + .bind(second) + .execute(pool) + .await + .unwrap(); + sqlx::query("DELETE FROM furumusic__playlist WHERE id = $1") + .bind(second) + .execute(pool) + .await + .unwrap(); + set_entry(pool, import_id, 0, 1, Entry::Local(3)).await; + set_entry(pool, import_id, 1, 1, Entry::Local(4)).await; + let source = store::get_import(pool, USER, import_id) + .await + .unwrap() + .unwrap() + .source_playlists[1] + .id; + resync(pool, import_id).await; + + // The user recreates the second playlist while the first one publishes; + // the request waits for the batch and commits before the worker reaches + // the second playlist with its old view of the target. + let spawned: Spawned = Arc::default(); + let (hook_pool, slot) = (pool.clone(), Arc::clone(&spawned)); + hooks::once(Point::BeforeCommit, move || { + Box::pin(async move { + let task_pool = hook_pool.clone(); + let handle = tokio::spawn(async move { + assert_eq!( + store::recreate_target(&task_pool, USER, import_id, source) + .await + .unwrap(), + store::RecreateOutcome::Requested { queued: false } + ); + }); + wait_for_lock(&hook_pool).await; + *slot.lock().unwrap() = Some(handle); + }) + }); + publish(pool, 822).await; + join(&spawned).await; + assert_eq!(fixture.status(import_id).await, "done"); + let recreated = target(pool, import_id, 1).await.expect("recreated target"); + assert_ne!(recreated, second); + assert_eq!(rows(pool, recreated).await, [(1002, 0), (1004, 1)]); + assert_eq!(statuses(pool, import_id).await, ["published"; 4]); + let detail = store::get_import(pool, USER, import_id) + .await + .unwrap() + .unwrap(); + assert!(!detail.source_playlists[1].publication_paused); + assert!(!detail.source_playlists[1].target_deleted); + fixture.drop().await; +} + #[tokio::test] #[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] async fn library_import_entry_failing_in_its_transaction_leaves_nothing_behind() {