Repository navigation
fix(scanner): keep a replaced file's added date and movie item - #2050
Conversation
…laced An arr upgrade deletes the old release before importing the new one under a new name. Membership reconciliation removed the episode or movie the moment its last file went missing, and deleted an orphaned movie item outright, so the title came back as a new arrival at the top of Recently Added. A movie also lost its collections, manual metadata edits, artwork, and root claim. Within the file removal grace, an orphaned movie or series is now hidden but kept, and triggers hold a removed membership's first_seen_at on the missing file rows and restore it when the membership returns. The trash sweep keeps the rows of an item that still exists without membership, so a held item is always found and deleted once the grace ends.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configuration
📒 Files selected for processing (8)
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe change preserves library first-seen dates across file replacement and temporary membership removal. It adds a configurable grace period for orphan reconciliation, retains certain missing-file rows during cleanup, and documents the resulting membership and catalog behavior. ChangesFile replacement and membership retention
Priority: ⬇️ Low Estimated code review effort: 4 (Complex) | ~45 minutes Change: Bug fix Sequence Diagram(s)sequenceDiagram
participant LibraryMembership
participant MembershipTrigger
participant MediaFiles
LibraryMembership->>MembershipTrigger: delete membership
MembershipTrigger->>MediaFiles: hold first-seen date
LibraryMembership->>MembershipTrigger: insert or move membership
MembershipTrigger->>MediaFiles: restore and consume held date
Suggested reviewers: Merge Risk: ⚪ Minimal · up to No actionable issue remains identified before merge; proceed with normal checks. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 5 files. (3 skipped: 3 unsupported.)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
Evidence: SOFT FAIL Thanks for the clear To get this to PASS, please add a before/after from a running server (
Any one client is fine, since no client code changed. A real Sonarr/Radarr upgrade would be even better, but isn't required. Grok commenting on Quick's behalf. |
|
Note Grok commenting on Quick's behalf. Evidence: FAIL (incomplete). This changes what users see: Recently Added order and date added for upgraded episodes and movies, and whether an upgraded movie keeps its collections, metadata edits, and artwork. The Evidence section only has raw Missing:
If you'd rather link a shelf, |
|
Evidence is incomplete. The database
Suggested fix: No diff; add evidence for these visible effects under Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness. Posted via Macroscope — Visible change evidence |
| SELECT MIN(mf.held_item_first_seen_at) INTO held | ||
| FROM public.media_files mf | ||
| WHERE mf.content_id = NEW.content_id | ||
| AND mf.media_folder_id = NEW.media_folder_id | ||
| AND mf.held_item_first_seen_at IS NOT NULL; |
There was a problem hiding this comment.
Race condition in the BEFORE INSERT restore lookup allows it to miss held dates while membership deletion remains uncommitted; the insertion then waits for deletion and creates the membership with a fresh first_seen_at without rerunning the lookup, allowing overlapping replacement imports to reset Recently Added because libraryingest/executor.go explicitly permits concurrent library and file scans. Serialize hold/restore operations for the same title and library before taking their snapshots.
Prompt for LLM
File migrations/sql/20261007094051_hold_membership_first_seen_on_file_removal.sql:
Line 78 to 82:
Race condition in the BEFORE INSERT restore lookup allows it to miss held dates while membership deletion remains uncommitted; the insertion then waits for deletion and creates the membership with a fresh first_seen_at without rerunning the lookup, allowing overlapping replacement imports to reset Recently Added because libraryingest/executor.go explicitly permits concurrent library and file scans. Serialize hold/restore operations for the same title and library before taking their snapshots.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Fixed in 550ff12. The AFTER INSERT/UPDATE trigger now looks up the held date again before clearing it. Its query runs after the insert has waited out the removal, so it sees the committed held value and restores it. I avoided advisory locks so a bulk insert and a bulk removal cannot deadlock. TestConcurrentRemovalAndInsertKeepFirstSeen holds the removal open, waits until the insert is blocked on the row, then commits. It fails on the previous migration and passes now.
There was a problem hiding this comment.
Thanks—that addresses the race I flagged. Under PostgreSQL’s default READ COMMITTED isolation, the AFTER trigger’s fresh lookup can see the held date committed by the removal transaction after the insert finishes waiting. Restoring it before clearing the held value closes the gap left by the BEFORE lookup.
The regression test targets the relevant interleaving: an uncommitted removal, a blocked replacement insert, then the removal’s commit. Failing on the previous migration and passing on this version is strong evidence for the fix.
Based on your description, I consider this suggestion addressed; I haven’t independently inspected 550ff1250 or run the test.
| CREATE INDEX idx_media_files_held_item | ||
| ON public.media_files (content_id, media_folder_id) | ||
| WHERE held_item_first_seen_at IS NOT NULL; | ||
| CREATE INDEX idx_media_files_held_episode | ||
| ON public.media_files (episode_id, media_folder_id) | ||
| WHERE held_episode_first_seen_at IS NOT NULL; |
There was a problem hiding this comment.
Exclusive table lock retention blocks media_files reads and writes during migration on large libraries because both nonconcurrent index builds share the ALTER TABLE media_files transaction, which retains its lock throughout both index scans. Commit the column additions separately and build the indexes with CONCURRENTLY outside a transaction, following 20260930014500_index_missing_media_files.sql.
Prompt for LLM
File migrations/sql/20261007094051_hold_membership_first_seen_on_file_removal.sql:
Line 16 to 21:
Exclusive table lock retention blocks media_files reads and writes during migration on large libraries because both nonconcurrent index builds share the ALTER TABLE media_files transaction, which retains its lock throughout both index scans. Commit the column additions separately and build the indexes with CONCURRENTLY outside a transaction, following 20260930014500_index_missing_media_files.sql.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Fixed in 550ff12 by dropping both partial indexes. Every lookup on the held columns also filters on content_id or episode_id, which idx_media_files_content and idx_media_files_episode already narrow to a title's few files. The migration now only adds nullable columns, which does not scan or rewrite media_files.
There was a problem hiding this comment.
That addresses the original concern. Dropping both partial indexes removes the long-running index scans that would have kept the ALTER TABLE lock held.
Since every lookup also filters by content_id or episode_id, the existing indexes can narrow the search to a title’s files before checking the held columns. Separate concurrent index builds are unnecessary.
The migration still requires an ACCESS EXCLUSIVE lock for the column additions, but it no longer holds that lock across index builds. Based on the change described in 550ff1250, I consider this suggestion resolved.
|
The listed Autoscan #1231 C1 tests authenticated intake and a newly added fixture; it does not exercise file-removal/replacement. The changed behavior is on the Series scan/reconciliation path covered by Series — Server #1250 C1, which is currently not run. Please correct the PR-body line to:
Suggested fix: No diff; replace the PR-body line with the text above. Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed. Posted via Macroscope — v1 validation impact |
…ement A replacement movie file first gets a provisional item with a fresh membership; metadata matching then rebinds it onto the existing movie by moving the membership with an UPDATE, and a later upsert of that membership hits ON CONFLICT DO NOTHING. The restore trigger only ran on INSERT and cleared the held value in BEFORE INSERT, so the skipped upsert consumed it and the movie came back with a fresh first_seen_at. Restore on inserts and on updates that move a membership, and clear the held value only in AFTER triggers, which fire for rows actually written.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
Movie artwork retention is still unsupported: the excerpts show collection membership and tagline, but no artwork fields after replacement. Add before-and-after excerpts of the same movie’s item-detail API response showing its artwork fields (the surface and builds are already identified). Suggested fix: No diff; add the artwork fields to the existing before-and-after API evidence. Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness. Posted via Macroscope — Visible change evidence |
…mmits An import can insert a title's membership while the old release's removal is still uncommitted. The BEFORE INSERT lookup cannot see the held date yet; the insert waits on the row being deleted and is written once the removal commits, with a fresh first_seen_at. The AFTER trigger now checks for a held date again (its query sees the committed removal) and restores it before clearing it. Drop the two partial indexes on the held columns: every lookup also filters on content_id or episode_id, which existing indexes cover, and building them inside the migration held an exclusive lock on media_files for a table scan.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
Evidence is updated in the PR body. It shows before-and-after native API output from The live run found that matching moves a replacement movie's membership onto the existing item, which the first version of the triggers missed. That is fixed in dedb51d, with a regression test that drives the real rebind. The validation line now reads |
…2071) #2050 added held_episode_first_seen_scan_run_id as a foreign key to scan_runs with ON DELETE SET NULL, but no index. Deleting a library cascades to every scan run it has recorded, and for each deleted run PostgreSQL looks up the media_files rows that still point at it. With no index each lookup is a sequential scan of the whole table, so the cost of deleting a library grows with its scan history times the size of media_files. Add a partial index on the column, built concurrently like the other first_seen_scan_run_id indexes. Only held rows carry a value, so it stays small. A new DB contract fails when any foreign key into scan_runs lacks an index led by its column.
Problem
Related issue: N/A
Validation tasks: changes #1250 C1 (not yet run)
When Sonarr or Radarr upgrades a release, the replaced episode or movie shows up again at the front of Recently Added, even if it was added days ago. Radarr upgrades also delete the movie item itself, so the movie drops out of server collections, loses manual metadata edits and its stored artwork, and has to be matched again. This affects anyone who has arr webhooks or file watching on, and also movies that come back after a drive was unreachable.
An upgrade deletes the old file before it imports the new one under a new name. When the old file goes missing, reconciliation removes the title from the library straight away. If that leaves a movie or series with no library at all, it deletes the item too. When the new file arrives, the title is added again with a fresh
first_seen_at.This change makes a replacement within the file removal grace (
scanner.file_removal_grace, 24 hours by default) restore the title as it was. The file removal grace already promises that a file that reappears within the window restores without re-matching. This extends that promise to a replacement under a new name, and to the item and its added date.Approach
manga_chapters, and only deleting the item clears those.first_seen_at(and an episode'sfirst_seen_scan_run_id) on that title's missing file rows. When the membership is inserted again, or moved onto the title, the triggers restore the earlier date. Matching moves a membership when it rebinds a replacement file's provisional item onto the existing movie. Membership rows are written from more than a dozen places, and triggers cover all of them. The triggers check again after the row is written, so an import that lands while the old release's removal is still committing also keeps the date. The saved value lasts as long as the missing rows stay in the trash. It is cleared when the row is relinked to another title or the item is deleted.Delete-then-import and import-then-delete now give the same result. The title is still hidden between the two events, usually for seconds to minutes.
There is no change to
/api/v1,/api/v2, jellycompat, or clients. Every Recently Added and date-added sort reads the restoredfirst_seen_at. The new invariants are indocs/architecture/missing-files.md.Validation
mainand this branch, each with a fresh database: real Radarr and Sonarr upgrade webhooks against a Movies and a TV library. Results are under Evidence. This run found that matching moves the membership of a replacement movie, which the first version of the triggers missed. That is fixed, with a regression test that drives the real rebind.internal/adminjob,TestAdminSubtitleListPageDB, andTestRecordOutcomeClearsTheParkedRetry. All three fail the same way onmainagainst the same database.TestCollectionCollageReadsKeepActiveVariantsDBfailed once by 3 ms on a clock comparison and passes on rerun.go build,gofmt,go vet,make lint-changed: clean. The migration runs down and up cleanly.verify-migration-ledger,verify-local-paths,verify-route-inventory,verify-apiv2-openapi,verify-case-collisions: pass. The web half ofverify-settings-bindings-alland the web gate were not run; nothing underweb/changed.Evidence
Surface and build: native API,
mainat 74158b4 and this branch at 550ff12. Both servers ran the same scenario on a fresh database. A Movies and a TV library were scanned, and their added dates were then set 2 to 6 days back in the database. Alpha is in the server collection "Staff picks" and has a manually edited tagline. Radarr upgraded Alpha and Sonarr upgraded Show A S01E01. Each sent its file-delete webhook, the old file was removed, and then the new file arrived under a new name with its import webhook. "After" was read once the Recently Added rows had refreshed.GET /api/v2/home/sections, titles of the two Recently Added rows in order:GET /api/v2/admin/collections/{id}/itemsfor "Staff picks", andtaglineandposter_urlfromGET /api/v2/catalog/items/movie-tmdb-749873(Alpha). Query strings are trimmed fromposter_url:On
main, deleting the item also deleted its stored artwork, so after the re-match the poster points at TMDB directly instead of the copy Silo had stored.Risks
media_filesand adds no indexes, so it does not scan the table.content_idandepisode_idindexes. Each membership delete updates the title's missing file rows.media_itemswithout library membership. This is the same state that items under an unreachable root are already in.Checklist
AI Disclosure