Repository navigation
perf(catalog): stop library deletes scanning media_files once per scan run - #2071
Merged
Quick104 merged 1 commit intoOct 8, 2026
Conversation
Silo-Server#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.
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:
|
Contributor
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 24 minutes. View limit detailsLimit details: You’ve used all 4 included reviews currently available. Review configuration: ⚙️ Run configuration
📒 Files selected for processing (3)
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Related issue: N/A
Validation tasks: none
Deleting a library now runs one sequential scan of
media_filesfor every scan run the library has ever recorded, inside a singleDELETE. #2050 addedmedia_files.held_episode_first_seen_scan_run_idas a foreign key toscan_runswithON DELETE SET NULL, but didn't index it. Deleting the folder row cascades to all of itsscan_runs, and for each deleted run PostgreSQL looks up themedia_filesrows that still point at it. Nothing prunesscan_runs, so the cost grows with a library's scan history times the size ofmedia_files.On a local copy seeded to my server's size, deleting a library with 1,000 scan runs took 80 seconds. My largest library has 6,525 scan runs, which works out to roughly nine minutes for that one statement.
This adds the missing index.
Approach
NO TRANSACTIONmigration that builds a partial index onheld_episode_first_seen_scan_run_id(WHERE ... IS NOT NULL) withCREATE INDEX CONCURRENTLY. It follows the precedent of20260807094340, which indexedfirst_seen_scan_run_idthe same way: drop any invalid leftover concurrently, then build. Only held rows carry a value, so the index stays tiny. The lookup PostgreSQL runs forSET NULL(WHERE $1 = held_episode_first_seen_scan_run_id) impliesIS NOT NULL, so the planner uses the partial index (checked under a generic plan below).TestScanRunForeignKeysHaveLeadingIndexesDB, fails when any foreign key intoscan_runshas no valid index led by its column. I audited every foreign key intoscan_runsandmedia_folderson a migrated database: this column was the only one intoscan_runswithout an index.The comment in #2050's migration says the held columns need no index because every lookup also filters on
content_idorepisode_id. That's true for Silo's own queries, but not for the foreign key's ownSET NULLlookup.Validation
TestScanRunForeignKeysHaveLeadingIndexesDBfails onmain(foreign keys to scan_runs without a leading index: media_files.held_episode_first_seen_scan_run_id) and passes on this branch. I added it toscripts/ci/db-contracts.txtso theGo DB pinsjob runs it.TestHeldFirstSeenScanRunIndexRetryUsesConcurrentCleanupchecks that the migration isNO TRANSACTIONand that the concurrent cleanup comes before the build. It passes, and so does the existingTestScanRunProvenanceIndexRetryUsesConcurrentCleanup.make migrate-validatepasses. Applying the migration to a populated database, rolling it back with--migrate-down-to 20261007094051and applying it again leaves a valid index.gofmtandgo vet ./migrations/are clean. golangci-lint with gocritic on./migrations/, filtered to changed lines againstmain, reports 0 issues. I didn't runmake lint-changeditself: a.sqlchange undermigrations/makes it lint the whole tree, which CI's Go lint job does anyway.Benchmarks
Baseline
mainat bd84251, changed this branch (the same migration, rebased onto ca186fe without changes). PostgreSQL 18.6 with pgvector 0.8.7 on an Apple Silicon Mac,shared_buffers512 MB, one connection, data in cache.Workload: a database migrated to
main, with 327,590media_filesrows in another library (a 640 MB heap, close to my server's 327,590 rows in 705 MB), and a library to delete that has N scan runs and no files. The library delete removes a folder's files before it deletes the folder row, so that's the state the cascade runs in. Each run isDELETE FROM media_folders WHERE id = $1inside a transaction that is rolled back, and timed with psql\timing. For "after" I applied this branch's migration to the same populated database. It built the index in 151 ms.mainThe statement PostgreSQL runs for each deleted scan run, as a prepared statement under
plan_cache_mode = force_generic_plan:Limitations: one machine with data in memory. On a server reading from disk the seq scans get slower, not faster. The 6,525-run baseline is an extrapolation, not a measurement. My server runs a build without #2050, so the before numbers come from the seeded copy rather than production. Production gives only the sizes: 327,590
media_filesrows in a 705 MB heap, and 11,135 scan runs since August, 6,525 of them in one library.Evidence
No user-visible change. Library deletion runs as a background job and its result doesn't change, only its duration. The measurements are under Benchmarks, and the raw benchmark, plan and test output is on the evidence page.
Evidence: https://evidence.siloserver.org/r/silo-server/pr-2071/
Risks
NO TRANSACTION, like the other index migrations. It readsmedia_filestwice without blocking writes. On a table of this size it took 151 ms locally.Checklist
AI Disclosure
AI-assisted with Claude Opus. I directed the task and designed the work.