Skip to content

perf(catalog): stop library deletes scanning media_files once per scan run - #2071

Merged
Quick104 merged 1 commit into
Silo-Server:mainfrom
blurbery:perf/scanner-index-held-first-seen-scan-run
Oct 8, 2026
Merged

Quick104 merged 1 commit into
Silo-Server:mainfrom
blurbery:perf/scanner-index-held-first-seen-scan-run

Conversation

@blurbery

@blurbery blurbery commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none

Deleting a library now runs one sequential scan of media_files for every scan run the library has ever recorded, inside a single DELETE. #2050 added media_files.held_episode_first_seen_scan_run_id as a foreign key to scan_runs with ON DELETE SET NULL, but didn't index it. Deleting the folder row cascades to all of its scan_runs, and for each deleted run PostgreSQL looks up the media_files rows that still point at it. Nothing prunes scan_runs, so the cost grows with a library's scan history times the size of media_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

  • New NO TRANSACTION migration that builds a partial index on held_episode_first_seen_scan_run_id (WHERE ... IS NOT NULL) with CREATE INDEX CONCURRENTLY. It follows the precedent of 20260807094340, which indexed first_seen_scan_run_id the same way: drop any invalid leftover concurrently, then build. Only held rows carry a value, so the index stays tiny. The lookup PostgreSQL runs for SET NULL (WHERE $1 = held_episode_first_seen_scan_run_id) implies IS NOT NULL, so the planner uses the partial index (checked under a generic plan below).
  • A new DB contract, TestScanRunForeignKeysHaveLeadingIndexesDB, fails when any foreign key into scan_runs has no valid index led by its column. I audited every foreign key into scan_runs and media_folders on a migrated database: this column was the only one into scan_runs without an index.

The comment in #2050's migration says the held columns need no index because every lookup also filters on content_id or episode_id. That's true for Silo's own queries, but not for the foreign key's own SET NULL lookup.

Validation

  • TestScanRunForeignKeysHaveLeadingIndexesDB fails on main (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 to scripts/ci/db-contracts.txt so the Go DB pins job runs it.
  • TestHeldFirstSeenScanRunIndexRetryUsesConcurrentCleanup checks that the migration is NO TRANSACTION and that the concurrent cleanup comes before the build. It passes, and so does the existing TestScanRunProvenanceIndexRetryUsesConcurrentCleanup.
  • make migrate-validate passes. Applying the migration to a populated database, rolling it back with --migrate-down-to 20261007094051 and applying it again leaves a valid index.
  • gofmt and go vet ./migrations/ are clean. golangci-lint with gocritic on ./migrations/, filtered to changed lines against main, reports 0 issues. I didn't run make lint-changed itself: a .sql change under migrations/ makes it lint the whole tree, which CI's Go lint job does anyway.

Benchmarks

Baseline main at 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_buffers 512 MB, one connection, data in cache.

Workload: a database migrated to main, with 327,590 media_files rows 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 is DELETE FROM media_folders WHERE id = $1 inside 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.

Scan runs in the deleted library main This branch
200 17.88 s, 17.35 s, 17.84 s 28.7 ms (first run), 1.8 ms, 1.5 ms
1,000 79.75 s (one run) 14.7 ms (first run), 6.5 ms, 6.4 ms
6,525 not run (about 9 minutes by extrapolation from 80 ms a run) 46.4 ms (first run), 38.9 ms, 38.6 ms

The statement PostgreSQL runs for each deleted scan run, as a prepared statement under plan_cache_mode = force_generic_plan:

-- main
Update on media_files (actual time=111.529..111.530 rows=0.00 loops=1)
  Buffers: shared hit=52770 read=29128 written=288
  ->  Seq Scan on media_files (actual time=111.529..111.529 rows=0.00 loops=1)
        Filter: ($1 = held_episode_first_seen_scan_run_id)
        Rows Removed by Filter: 327590
Execution Time: 111.571 ms

-- this branch
->  Index Scan using idx_media_files_held_episode_first_seen_scan_run_id on media_files (actual time=0.001..0.001 rows=0.00 loops=1)
      Index Cond: (held_episode_first_seen_scan_run_id = $1)

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_files rows 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

  • The concurrent build needs NO TRANSACTION, like the other index migrations. It reads media_files twice without blocking writes. On a table of this size it took 151 ms locally.
  • None identified beyond that: the index only adds an entry when a file row holds a scan run ID.

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 (desktop app)
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: AI-assisted
  • Adversarial review: n/a

AI-assisted with Claude Opus. I directed the task and designed the work.

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

silo-kody Bot commented Oct 8, 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 ❌

@coderabbitai

coderabbitai Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You'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.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3a3919d6-70f6-454c-b815-7eb1a30c68b2
📥 Commits

Reviewing files that changed from the base of the PR and between ca186fe and 2a36a7a.

📒 Files selected for processing (3)
  • migrations/held_first_seen_scan_run_index_test.go
  • migrations/sql/20261008023737_index_media_files_held_episode_first_seen_scan_run.sql
  • scripts/ci/db-contracts.txt
  • 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.

@Quick104 Quick104 added priority: P1 Core-path bug; painful workaround — next after P0 impact: perf Unusable slowness on normal hardware labels Oct 8, 2026 — with Cursor
@Quick104
Quick104 merged commit 9af2013 into Silo-Server:main Oct 8, 2026
20 checks passed
@blurbery
blurbery deleted the perf/scanner-index-held-first-seen-scan-run branch November 6, 2026 00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

impact: perf Unusable slowness on normal hardware 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