Skip to content

fix(scanner): keep a replaced file's added date and movie item - #2050

Merged
Quick104 merged 3 commits into
Silo-Server:mainfrom
Rhainland:fix/keep-added-date-on-replace
Oct 7, 2026
Merged

Quick104 merged 3 commits into
Silo-Server:mainfrom
Rhainland:fix/keep-added-date-on-replace

Conversation

@Rhainland

@Rhainland Rhainland commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Membership reconciliation still removes the title from the library as soon as it has no present file, so it is hidden immediately. Inside the grace, it no longer deletes an orphaned movie or series. A replacement file then relinks to the same item through its existing root claim. A reconciliation after the grace deletes the item. Book items are still deleted immediately: their chapter and series listings read tables such as manga_chapters, and only deleting the item clears those.
  • When a membership is deleted, triggers save its first_seen_at (and an episode's first_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.
  • The trash sweep no longer deletes the rows of an item that still exists but belongs to no library. Without that, the sweep could delete a held item's last rows, and nothing would ever find and delete the item.

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 restored first_seen_at. The new invariants are in docs/architecture/missing-files.md.

Validation

  • Live run of main and 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.
  • New database tests cover episode and movie upgrades in both orders, the rebind, an import that races the removal, a movie returning at the same path, the hold ending, a zero grace, the trash-sweep race, clearing on relink and on item deletion, deleting a series, and book items not being held. They fail without the triggers or without the hold.
  • Full Go suite against Postgres 18 with pgvector: passes, except internal/adminjob, TestAdminSubtitleListPageDB, and TestRecordOutcomeClearsTheParkedRetry. All three fail the same way on main against the same database. TestCollectionCollageReadsKeepActiveVariantsDB failed 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 of verify-settings-bindings-all and the web gate were not run; nothing under web/ changed.

Evidence

Surface and build: native API, main at 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:

                        before                                     after on main                              after on this branch
Recently Added Movies   Charlie, Bravo, Alpha                      Alpha, Charlie, Bravo                      Charlie, Bravo, Alpha
Recently Added TV       Show B S01E01, Show A S01E02, Show A S01E01  Show A S01E01, Show B S01E01, Show A S01E02  Show B S01E01, Show A S01E02, Show A S01E01

GET /api/v2/admin/collections/{id}/items for "Staff picks", and tagline and poster_url from GET /api/v2/catalog/items/movie-tmdb-749873 (Alpha). Query strings are trimmed from poster_url:

                   before                                                  after on main                                       after on this branch
Staff picks items  Alpha                                                   (empty)                                             Alpha
Alpha tagline      Manually edited tagline                                 null                                                Manually edited tagline
Alpha poster_url   /api/v2/artwork/tmdb/movies/749873/poster/w500.0d85…webp  https://image.tmdb.org/t/p/w500/gh76Zfr1iNVWd2rqknB8MjTcrHS.jpg  /api/v2/artwork/tmdb/movies/749873/poster/w500.0d85…webp

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

  • The migration adds three nullable columns to media_files and adds no indexes, so it does not scan the table.
  • Each membership write looks up the title's file rows twice through the existing content_id and episode_id indexes. Each membership delete updates the title's missing file rows.
  • During the grace, an orphaned movie or series stays in media_items without library membership. This is the same state that items under an unreachable root are already in.
  • The missing file rows of such an item stay in the trash until a later reconciliation deletes the item, rather than being deleted on schedule.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: A separate Claude Code review pass over the full diff found that the item hold also kept deleted manga chapters listed on their series page. The hold is now limited to movies and series, with a regression test.

…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.
@coderabbitai

coderabbitai Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 73193f45-95c5-4af4-a6ef-bec51ff6afaa
📥 Commits

Reviewing files that changed from the base of the PR and between 74158b4 and 550ff12.

📒 Files selected for processing (8)
  • docs/architecture/missing-files.md
  • docs/catalog-api.md
  • internal/catalog/library_repo.go
  • internal/metadata/rebind_held_first_seen_test.go
  • internal/scanner/file_repo.go
  • internal/scanner/replaced_file_first_seen_test.go
  • internal/scanner/scanner.go
  • migrations/sql/20261007094051_hold_membership_first_seen_on_file_removal.sql

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The 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.

Changes

File replacement and membership retention

Layer / File(s) Summary
Hold and restore membership dates
migrations/sql/20261007094051_hold_membership_first_seen_on_file_removal.sql, internal/scanner/replaced_file_first_seen_test.go, internal/metadata/rebind_held_first_seen_test.go
Database triggers hold item and episode first-seen dates on missing file rows and restore them on membership insertion or movement. They clear held values after restoration, relinking, or deletion. Tests cover replacement, rebinding, cleanup, and concurrent membership changes.
Apply removal grace during reconciliation
internal/catalog/library_repo.go, internal/scanner/scanner.go, internal/scanner/file_repo.go, internal/scanner/replaced_file_first_seen_test.go, docs/architecture/missing-files.md, docs/catalog-api.md
Library reconciliation applies the configured grace to eligible orphaned movies and series. Missing-file cleanup retains rows linked to items without memberships. Tests and documentation cover grace expiry, zero grace, cleanup, and catalog-date behavior.

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
Loading

Suggested reviewers: quick104

Merge Risk: ⚪ Minimal · up to 550ff

No actionable issue remains identified before merge; proceed with normal checks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning 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: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly describes the main change: preserving a replaced file’s added date and movie item.
Description check ✅ Passed The description explains the problem, approach, validation, and risks. It is directly related to the changeset.
Full details: Docstring Coverage

Explanation

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.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@silo-kody

silo-kody Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104 Quick104 added priority: P1 Core-path bug; painful workaround — next after P0 impact: data-loss User data deleted, corrupted, or unrecoverable labels Oct 7, 2026 — with Cursor

Quick104 commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Evidence: SOFT FAIL

Thanks for the clear first_seen_at table. It shows the mechanism well. The change is still something people will see, though: an upgraded episode or movie no longer jumps to the front of Recently Added, and an upgraded movie keeps its collections, metadata edits and artwork. Right now the Evidence comes only from the database test, and the movie case is described in words, with no capture. No live upgrade was run either.

To get this to PASS, please add a before/after from a running server (main vs this branch) of a simulated upgrade: delete the old file, then import the replacement under a new name, inside the grace window. Please show:

  • Recently Added for an episode and a movie, showing where the title lands after the replacement is imported.
  • The movie's detail page after the replacement, showing that its collection entry, any manual edits and its artwork are kept (on main it gets re-matched).

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.

Quick104 commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

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 first_seen_at values from the database test, and the movie case is prose only.

Missing:

  • Episode upgrade: before/after from a user surface, either a web Recently Added screenshot (main vs this branch, same data) or fenced before/after JSON for the same Recently Added / date-added request (test fixtures are fine).
  • Movie upgrade: a before/after artifact showing the movie keeps its item, collection entry, and added date after delete-then-import (API JSON or screenshots). Right now it's only a sentence.
  • Surface/build line naming the surface and commit (91eaf37).

If you'd rather link a shelf, Evidence: https://evidence.siloserver.org/r/silo-server/<topic>/ covering both cases works too.

@macroscopeapp

macroscopeapp Bot commented Oct 7, 2026

Copy link
Copy Markdown

Evidence is incomplete. The database first_seen_at table shows the stored date, but not what a client displays.

  • internal/scanner/scanner.go and migrations/sql/20261007094051_hold_membership_first_seen_on_file_removal.sql: The restored date changes a title’s position in Recently Added and date-added sorts. Add before-and-after excerpts from the same API request or screen, showing the ordered titles for the same library, and identify the surface and build or commit.
  • internal/catalog/library_repo.go: Keeping the movie item preserves its collection membership, manual metadata, and artwork after replacement. Add before-and-after captures of the same movie in the affected collection and item-detail surface(s), and identify the surface and build or commit.

Suggested fix: No diff; add evidence for these visible effects under ## Evidence.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

Comment on lines +78 to +82
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug high

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.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +16 to +21
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Performance high

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.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@macroscopeapp

macroscopeapp Bot commented Oct 7, 2026

Copy link
Copy Markdown

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:

Validation tasks: changes #1250 C1 (not yet run)

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

silo-kody Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@macroscopeapp

macroscopeapp Bot commented Oct 7, 2026

Copy link
Copy Markdown

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

silo-kody Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Rhainland

Rhainland commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Evidence is updated in the PR body. It shows before-and-after native API output from main and this branch, run through real Radarr and Sonarr upgrade webhooks (delete, then import under a new name): both Recently Added rows, a server collection, a manually edited field on the movie, and its poster_url. On main the poster switches from Silo's stored copy to a direct TMDB link; on this branch it is unchanged.

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 changes #1250 C1 (not yet run), as suggested.

@Quick104
Quick104 merged commit 7ef2e9d into Silo-Server:main Oct 7, 2026
24 checks passed
Quick104 pushed a commit that referenced this pull request Oct 8, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

impact: data-loss User data deleted, corrupted, or unrecoverable priority: P1 Core-path bug; painful workaround — next after P0

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants