From 015b90a4581149b9ec694bd4a086c13884c28b1c Mon Sep 17 00:00:00 2001 From: Miguel Palhas Date: Sat, 29 Aug 2026 20:34:58 +0100 Subject: [PATCH] fix(api): a deleted title takes its grabs with it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `grabs.infohash` is unique and grabs point at their target polymorphically, so nothing cascaded them off a deleted movie or series. An orphan holding an infohash then blocked the row a later grab of the same release needed: the upsert only reclaims a `vanished` row, so the insert did nothing while the new title was still flipped to `downloading`. It never imported, and `/api/downloads` attributed the torrent to a title that no longer existed. Deletes now clear the grabs, and the upsert also reclaims a row whose target is gone whatever its state — which heals the databases that already have orphans. A row belonging to a live title stays off limits, so the restart case still cannot let one title steal another's torrent. Co-Authored-By: Claude Opus 5 (1M context) --- ...6c379b9c5a1cebee9dfa61df2162f2c64383.json} | 4 +- ...a68e956a38f1db4462cab02fe26c8c9912a81.json | 12 +++ ...021340acb438a1ed6a7b917be91c9d368cb57.json | 12 +++ crates/arr-api/src/movies.rs | 48 ++++++++++ crates/arr-api/src/series.rs | 75 +++++++++++++++ crates/arr-daemon/src/grab.rs | 91 +++++++++++++++++++ crates/arr-dl/src/lib.rs | 65 +++++++++++-- 7 files changed, 298 insertions(+), 9 deletions(-) rename .sqlx/{query-2d0b92ba9aa4bc257286a67f0d37e2182c4478153c9096c1522c5ab23ad472e9.json => query-2aeb5f9dab4a62d4cc463a05c0636c379b9c5a1cebee9dfa61df2162f2c64383.json} (60%) create mode 100644 .sqlx/query-607f337ce8db7eb277dfc569fb1a68e956a38f1db4462cab02fe26c8c9912a81.json create mode 100644 .sqlx/query-e6fbef670552928dfeeb6f6d442021340acb438a1ed6a7b917be91c9d368cb57.json diff --git a/.sqlx/query-2d0b92ba9aa4bc257286a67f0d37e2182c4478153c9096c1522c5ab23ad472e9.json b/.sqlx/query-2aeb5f9dab4a62d4cc463a05c0636c379b9c5a1cebee9dfa61df2162f2c64383.json similarity index 60% rename from .sqlx/query-2d0b92ba9aa4bc257286a67f0d37e2182c4478153c9096c1522c5ab23ad472e9.json rename to .sqlx/query-2aeb5f9dab4a62d4cc463a05c0636c379b9c5a1cebee9dfa61df2162f2c64383.json index c5562b2..f003d88 100644 --- a/.sqlx/query-2d0b92ba9aa4bc257286a67f0d37e2182c4478153c9096c1522c5ab23ad472e9.json +++ b/.sqlx/query-2aeb5f9dab4a62d4cc463a05c0636c379b9c5a1cebee9dfa61df2162f2c64383.json @@ -1,6 +1,6 @@ { "db_name": "SQLite", - "query": "INSERT INTO grabs (release_id, target_kind, target_id, infohash, state)\n VALUES (?, ?, ?, ?, 'sent')\n ON CONFLICT (infohash) DO UPDATE SET\n release_id = excluded.release_id,\n target_kind = excluded.target_kind,\n target_id = excluded.target_id,\n state = 'sent',\n grabbed_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now'),\n imported_at = NULL\n WHERE grabs.state = 'vanished'\n RETURNING id AS \"id!: i64\"", + "query": "INSERT INTO grabs (release_id, target_kind, target_id, infohash, state)\n VALUES (?, ?, ?, ?, 'sent')\n ON CONFLICT (infohash) DO UPDATE SET\n release_id = excluded.release_id,\n target_kind = excluded.target_kind,\n target_id = excluded.target_id,\n state = 'sent',\n grabbed_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now'),\n imported_at = NULL\n WHERE grabs.state = 'vanished'\n OR (grabs.target_kind = 'movie'\n AND NOT EXISTS (SELECT 1 FROM movies WHERE id = grabs.target_id))\n OR (grabs.target_kind = 'season'\n AND NOT EXISTS (SELECT 1 FROM seasons WHERE id = grabs.target_id))\n OR (grabs.target_kind = 'episode'\n AND NOT EXISTS (SELECT 1 FROM episodes WHERE id = grabs.target_id))\n RETURNING id AS \"id!: i64\"", "describe": { "columns": [ { @@ -22,5 +22,5 @@ null ] }, - "hash": "2d0b92ba9aa4bc257286a67f0d37e2182c4478153c9096c1522c5ab23ad472e9" + "hash": "2aeb5f9dab4a62d4cc463a05c0636c379b9c5a1cebee9dfa61df2162f2c64383" } diff --git a/.sqlx/query-607f337ce8db7eb277dfc569fb1a68e956a38f1db4462cab02fe26c8c9912a81.json b/.sqlx/query-607f337ce8db7eb277dfc569fb1a68e956a38f1db4462cab02fe26c8c9912a81.json new file mode 100644 index 0000000..9ce2ccd --- /dev/null +++ b/.sqlx/query-607f337ce8db7eb277dfc569fb1a68e956a38f1db4462cab02fe26c8c9912a81.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "DELETE FROM grabs WHERE target_kind = 'movie' AND target_id = ?", + "describe": { + "columns": [], + "parameters": { + "Right": 1 + }, + "nullable": [] + }, + "hash": "607f337ce8db7eb277dfc569fb1a68e956a38f1db4462cab02fe26c8c9912a81" +} diff --git a/.sqlx/query-e6fbef670552928dfeeb6f6d442021340acb438a1ed6a7b917be91c9d368cb57.json b/.sqlx/query-e6fbef670552928dfeeb6f6d442021340acb438a1ed6a7b917be91c9d368cb57.json new file mode 100644 index 0000000..b715691 --- /dev/null +++ b/.sqlx/query-e6fbef670552928dfeeb6f6d442021340acb438a1ed6a7b917be91c9d368cb57.json @@ -0,0 +1,12 @@ +{ + "db_name": "SQLite", + "query": "DELETE FROM grabs\n WHERE (target_kind = 'season'\n AND target_id IN (SELECT id FROM seasons WHERE series_id = ?))\n OR (target_kind = 'episode'\n AND target_id IN (SELECT e.id FROM episodes e\n JOIN seasons s ON s.id = e.season_id\n WHERE s.series_id = ?))", + "describe": { + "columns": [], + "parameters": { + "Right": 2 + }, + "nullable": [] + }, + "hash": "e6fbef670552928dfeeb6f6d442021340acb438a1ed6a7b917be91c9d368cb57" +} diff --git a/crates/arr-api/src/movies.rs b/crates/arr-api/src/movies.rs index b143e88..6134997 100644 --- a/crates/arr-api/src/movies.rs +++ b/crates/arr-api/src/movies.rs @@ -596,6 +596,14 @@ pub async fn delete( ) .execute(pool(&state)?) .await?; + // `grabs.infohash` is unique, so an orphan left here would block the row + // a later grab of the same release needs to write. + sqlx::query!( + "DELETE FROM grabs WHERE target_kind = 'movie' AND target_id = ?", + id + ) + .execute(pool(&state)?) + .await?; let result = sqlx::query!("DELETE FROM movies WHERE id = ?", id) .execute(pool(&state)?) .await?; @@ -1632,6 +1640,46 @@ mod tests { assert_eq!(orphans, 0, "the file rows go with the files"); } + /// `grabs.infohash` is unique, so a row left behind by a deleted title + /// blocks the row a later grab of the same release needs to write — and + /// the grab records nothing while the new title still reads as + /// downloading. + #[tokio::test] + async fn deleting_a_movie_takes_its_grabs_with_it() { + let (_dir, state, base) = application().await; + let movie = add_movie(&base, 693_134, 1).await; + let id = movie["id"].as_i64().expect("id"); + let pool = state.database().expect("database").pool(); + sqlx::query( + "INSERT INTO releases (id, indexer_id, guid, name, size, download_url, parsed) + VALUES (1, 1, 'guid', 'release', 1, 'magnet:?x', '{}')", + ) + .execute(pool) + .await + .expect("release"); + sqlx::query( + "INSERT INTO grabs (release_id, target_kind, target_id, infohash, state) + VALUES (1, 'movie', ?, 'deadbeef', 'sent')", + ) + .bind(id) + .execute(pool) + .await + .expect("grab"); + + let response = reqwest::Client::new() + .delete(format!("{base}/api/movies/{id}")) + .send() + .await + .expect("delete"); + assert_eq!(response.status(), StatusCode::NO_CONTENT); + + let orphans: i64 = sqlx::query_scalar("SELECT count(*) FROM grabs") + .fetch_one(pool) + .await + .expect("count grabs"); + assert_eq!(orphans, 0, "no grab outlives the title it was for"); + } + /// The guard that keeps a delete inside the library: a path that is not /// under the title's root is left alone, whatever the row says. #[tokio::test] diff --git a/crates/arr-api/src/series.rs b/crates/arr-api/src/series.rs index 1ac53c2..b88a8ba 100644 --- a/crates/arr-api/src/series.rs +++ b/crates/arr-api/src/series.rs @@ -679,6 +679,23 @@ pub async fn delete( ) .execute(pool(&state)?) .await?; + // Seasons and episodes go with the series by cascade, but grabs point at + // them polymorphically and have no foreign key to follow. `infohash` is + // unique, so an orphan left here would block a later grab of the same + // release from recording anything. + sqlx::query!( + "DELETE FROM grabs + WHERE (target_kind = 'season' + AND target_id IN (SELECT id FROM seasons WHERE series_id = ?)) + OR (target_kind = 'episode' + AND target_id IN (SELECT e.id FROM episodes e + JOIN seasons s ON s.id = e.season_id + WHERE s.series_id = ?))", + id, + id + ) + .execute(pool(&state)?) + .await?; let result = sqlx::query!("DELETE FROM series WHERE id = ?", id) .execute(pool(&state)?) .await?; @@ -3647,6 +3664,64 @@ mod tests { assert_eq!(orphans, 0, "the file rows go with the files"); } + /// Seasons and episodes cascade off the series row, but grabs point at + /// them polymorphically with no foreign key to follow. `grabs.infohash` + /// is unique, so one left behind blocks the row a later grab of the same + /// pack or episode needs to write. + #[tokio::test] + async fn deleting_a_series_takes_its_season_and_episode_grabs_with_it() { + let (_dir, state, base) = application().await; + let root_id = tv_root(&state, "main").await; + let series = add_series(&base, root_id, true).await; + let series_id = series["id"].as_i64().expect("id"); + let season = add_season( + &base, + series_id, + 1, + serde_json::json!([{"number": 1, "title": "Pilot", "air_date": "2001-01-01"}]), + ) + .await; + let season_id = season["id"].as_i64().expect("season id"); + let episode_id = season["episodes"][0]["id"].as_i64().expect("episode id"); + + let pool = state.database().expect("database").pool(); + sqlx::query( + "INSERT INTO releases (id, indexer_id, guid, name, size, download_url, parsed) + VALUES (1, 1, 'guid', 'release', 1, 'magnet:?x', '{}')", + ) + .execute(pool) + .await + .expect("release"); + for (kind, target, hash) in [ + ("season", season_id, "aaaa"), + ("episode", episode_id, "bbbb"), + ] { + sqlx::query( + "INSERT INTO grabs (release_id, target_kind, target_id, infohash, state) + VALUES (1, ?, ?, ?, 'sent')", + ) + .bind(kind) + .bind(target) + .bind(hash) + .execute(pool) + .await + .expect("grab"); + } + + let response = reqwest::Client::new() + .delete(format!("{base}/api/series/{series_id}")) + .send() + .await + .expect("delete"); + assert_eq!(response.status(), StatusCode::NO_CONTENT); + + let orphans: i64 = sqlx::query_scalar("SELECT count(*) FROM grabs") + .fetch_one(pool) + .await + .expect("count grabs"); + assert_eq!(orphans, 0, "neither scope outlives the series"); + } + /// A missing series is 404 before anything touches the disk. #[tokio::test] async fn deleting_a_missing_series_is_a_404() { diff --git a/crates/arr-daemon/src/grab.rs b/crates/arr-daemon/src/grab.rs index 3c38bed..f112801 100644 --- a/crates/arr-daemon/src/grab.rs +++ b/crates/arr-daemon/src/grab.rs @@ -707,6 +707,14 @@ impl Grabber { // with its own earlier row. A `sent`/`downloaded` row is the restart // case and is left alone; a `vanished` one (§86) is reclaimed, since // nothing blacklisted the release. + // + // A row whose target no longer exists is reclaimed too, whatever its + // state. Deleting a title used to leave its grabs behind, and one of + // those orphans holding the infohash meant a later grab of the same + // release silently recorded nothing: the title flipped to + // `downloading` while the only row still pointed at the deleted one, + // so it never imported. Titles now take their grabs with them, and + // this clause heals the databases that already have orphans. let target_kind = target.scope.target_kind(); let target_id = target.scope.target_id(); let inserted = sqlx::query!( @@ -720,6 +728,12 @@ impl Grabber { grabbed_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now'), imported_at = NULL WHERE grabs.state = 'vanished' + OR (grabs.target_kind = 'movie' + AND NOT EXISTS (SELECT 1 FROM movies WHERE id = grabs.target_id)) + OR (grabs.target_kind = 'season' + AND NOT EXISTS (SELECT 1 FROM seasons WHERE id = grabs.target_id)) + OR (grabs.target_kind = 'episode' + AND NOT EXISTS (SELECT 1 FROM episodes WHERE id = grabs.target_id)) RETURNING id AS "id!: i64""#, winner.id, target_kind, @@ -2058,6 +2072,83 @@ mod tests { assert_eq!(state, "downloading"); } + /// A grab row left behind by a deleted title holds the release's unique + /// infohash. Re-adding the title and grabbing the same release used to + /// record nothing at all: the conflict hit a row in `sent`, which is only + /// reclaimed when it is `vanished`, so the movie flipped to `downloading` + /// while the one row still pointed at the title that no longer existed — + /// and nothing ever imported for the new one. + #[tokio::test] + async fn an_orphaned_grab_is_reclaimed_by_the_title_that_regrabs_it() { + let (_dir, database) = wanted_movie().await; + let indexer = prowlarr().await; + let (downloader, fake) = qbit().await; + let action = action(&indexer, &downloader); + + action.tick(&database).await.unwrap(); + assert_eq!(grabs(&database).await.len(), 1); + + // The title is deleted the way an old build left it: row gone, grab + // behind, still reading `sent`. + sqlx::query("UPDATE grabs SET target_id = 99, state = 'sent'") + .execute(database.pool()) + .await + .unwrap(); + sqlx::query( + "UPDATE movies SET state = 'missing', wanted = 1, search_attempts = 0, + last_searched_at = NULL WHERE id = 1", + ) + .execute(database.pool()) + .await + .unwrap(); + + let outcomes = action.tick(&database).await.unwrap(); + + assert_eq!(outcomes.len(), 1, "the regrab records a grab"); + assert_eq!(fake.torrents().len(), 1, "same release, same torrent"); + let grabs = grabs(&database).await; + assert_eq!(grabs.len(), 1, "the orphan is reclaimed, not duplicated"); + assert_eq!(grabs[0].0, 1, "and it now belongs to the live movie"); + } + + /// The other half: a live title's row is still off limits, so a restart + /// mid-flight does not let one title steal another's torrent. + #[tokio::test] + async fn a_grab_belonging_to_a_live_title_is_not_stolen() { + let (_dir, database) = wanted_movie().await; + let indexer = prowlarr().await; + let (downloader, _fake) = qbit().await; + let action = action(&indexer, &downloader); + + action.tick(&database).await.unwrap(); + // A second live movie, and the grab reassigned to it. + sqlx::query( + "INSERT INTO movies (id, tmdb_id, title, year, original_language, root_id, state) + SELECT 2, 999, 'Other', 2020, 'en', id, 'downloading' + FROM roots WHERE kind = 'movie' AND audience = 'main'", + ) + .execute(database.pool()) + .await + .unwrap(); + sqlx::query("UPDATE grabs SET target_id = 2, state = 'sent'") + .execute(database.pool()) + .await + .unwrap(); + sqlx::query( + "UPDATE movies SET state = 'missing', wanted = 1, search_attempts = 0, + last_searched_at = NULL WHERE id = 1", + ) + .execute(database.pool()) + .await + .unwrap(); + + action.tick(&database).await.unwrap(); + + let grabs = grabs(&database).await; + assert_eq!(grabs.len(), 1); + assert_eq!(grabs[0].0, 2, "movie 2 keeps the torrent it is downloading"); + } + /// §5.2: the language rules are expressed against the title's original /// language, and guessing it is worse than waiting for it. #[tokio::test] diff --git a/crates/arr-dl/src/lib.rs b/crates/arr-dl/src/lib.rs index 9d555fe..17b54fb 100644 --- a/crates/arr-dl/src/lib.rs +++ b/crates/arr-dl/src/lib.rs @@ -299,11 +299,16 @@ impl QbitClient { &[("hashes", hash.as_str()), ("tags", &request.label)], ) .await?; - self.post( - "torrents/setLocation", - &[("hashes", hash.as_str()), ("location", &download_dir)], - ) - .await?; + // Only when it would actually move. qBittorrent treats a + // same-path setLocation as a real move: it logs one and, on a + // torrent still downloading, can disturb files mid-transfer. + if torrent.save_path != request.download_dir { + self.post( + "torrents/setLocation", + &[("hashes", hash.as_str()), ("location", &download_dir)], + ) + .await?; + } } self.post( "torrents/setShareLimits", @@ -842,7 +847,7 @@ mod tests { } #[tokio::test] - async fn duplicate_reapplies_label_location_and_seed_limits_without_re_adding() { + async fn duplicate_reapplies_label_and_seed_limits_without_re_adding() { let server = MockServer::start().await; Mock::given(method("GET")) .and(path("/api/v2/torrents/info")) @@ -857,7 +862,7 @@ mod tests { .expect(0) .mount(&server) .await; - for endpoint in ["addTags", "setLocation", "setShareLimits"] { + for endpoint in ["addTags", "setShareLimits"] { Mock::given(method("POST")) .and(path(format!("/api/v2/torrents/{endpoint}"))) .respond_with(ResponseTemplate::new(200).set_body_string("")) @@ -865,6 +870,13 @@ mod tests { .mount(&server) .await; } + // Already at `/downloads`, so nothing to move. + Mock::given(method("POST")) + .and(path("/api/v2/torrents/setLocation")) + .respond_with(ResponseTemplate::new(200).set_body_string("")) + .expect(0) + .mount(&server) + .await; let client = QbitClient::new(&server.uri()).unwrap(); let added = client @@ -882,6 +894,45 @@ mod tests { assert_eq!(added.hash, HASH); } + /// A duplicate arr wants somewhere else still moves. + #[tokio::test] + async fn duplicate_in_the_wrong_place_is_relocated() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/api/v2/torrents/info")) + .respond_with( + ResponseTemplate::new(200).set_body_json(json!([torrent_json("stalledUP")])), + ) + .mount(&server) + .await; + for endpoint in ["addTags", "setShareLimits"] { + Mock::given(method("POST")) + .and(path(format!("/api/v2/torrents/{endpoint}"))) + .respond_with(ResponseTemplate::new(200).set_body_string("")) + .mount(&server) + .await; + } + Mock::given(method("POST")) + .and(path("/api/v2/torrents/setLocation")) + .and(body_string_contains("elsewhere")) + .respond_with(ResponseTemplate::new(200).set_body_string("")) + .expect(1) + .mount(&server) + .await; + + let client = QbitClient::new(&server.uri()).unwrap(); + client + .add_torrent(AddTorrent { + source: TorrentSource::Magnet(MAGNET.into()), + label: "movies-main".into(), + download_dir: PathBuf::from("/elsewhere"), + seed_ratio_limit: 1.5, + seed_idle_limit_minutes: 60, + }) + .await + .expect("duplicate"); + } + #[tokio::test] #[cfg(unix)] async fn rejects_non_utf8_download_directory() {