Skip to content

perf(blobgc): stop each deleted media file from reading the whole cleanup queue - #3934

Merged
Quick104 merged 2 commits into
Silo-Server:mainfrom
RXWatcher:fix/blob-gc-queue-planner-stats
Nov 15, 2026
Merged

Quick104 merged 2 commits into
Silo-Server:mainfrom
RXWatcher:fix/blob-gc-queue-planner-stats

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none

Deleting media files gets slower as blob_gc_queue grows, because every deleted file reads the whole queue. On a server whose queue held 949,319 chapter images, deleting two libraries with 540,000 files between them ran at one 5,000-file batch every 45 minutes. That is about three and a half days in all, and a library deletion job stops after two hours.

For each deleted file, queue_deleted_media_file_blobs() asks the queue for the latest not_before among that file's chapter images: max(not_before) over rows where prefix LIKE 'chapter-images/%' and split_part(prefix, '/', 2) is the file id. blob_gc_queue_chapter_file_idx finds those rows but does not order them by not_before, and PostgreSQL does not use a partial index's statistics to estimate a clause. The planner falls back to its fixed 0.5% guess (4,747 rows for one file id on that queue, against about 17), expects a match within the first few rows, and answers max() by walking blob_gc_queue_due_idx backwards. Most deleted files have nothing queued, so the walk reads every row: about 550 ms per file.

Approach

A Go migration replaces blob_gc_queue_chapter_file_idx with blob_gc_queue_chapter_file_not_before_idx on (split_part(prefix, '/', 2), not_before), with the same WHERE. That index answers max(not_before) for one file directly: the lookup seeks to the file and reads one entry, whatever the planner estimates. No other query uses the old index.

As DEVELOPMENT.md asks for replacing an index, the migration builds the new index concurrently before it drops the old one concurrently, so a retried run keeps what it built. The push attempt key migration already did exactly that; the step is now a shared replaceIndexConcurrently that both use.

Extended statistics on the expression, as 20260904144457_continue_watching_planner_stats.sql adds for watch progress, also fixed the queue above. On a queue of 2,000 files with 300 images each, the planner still chose the backward walk, so this change uses the index.

Validation

  • On the server above, with the statistics object created by hand: lookups went from about 550 ms to 0.06 to 0.2 ms, and the rest of the deletion ran at about 60,000 files a minute.
  • With the new index and no statistics, the lookup seeks the index on queues of 2,000 files with 10 and with 300 images each, on freshly vacuumed and on bloated tables. On a scratch queue of 949,319 rows the index built in 0.49 s, and 5,001 file deletes through the trigger took 25 ms in all.
  • Up, Down and Up again through --migrate-only and --migrate-down-to: Down restores the old index's definition exactly. The new DB pin passes after each Up and fails after the Down; on a freshly vacuumed queue without the new index, the lookup walks blob_gc_queue_due_idx. The push attempt key migration's retry test passes on the shared helper.
  • make test-db-pins: all 784 pins pass.
  • make test-go: passes except two tests that fail only in the full run on the shared test database and pass alone, on this branch and on main: TestDirectoriesReadsOnlyTheScannedSubtreeDB in internal/themesongs, a generic-plan test on media_files, and TestPostgresConcurrentProfileAndCollectionDeletes in internal/userstore/pgstore, which hit a blocking trigger another package's test had installed.
  • go build ./..., gofmt, go mod tidy -diff, go vet ./..., make lint-changed, make lint-router-recovery, make migrate-validate, make verify-migrations, make verify-migration-ledger, make verify-local-paths and make verify-case-collisions pass.
  • Not run: the web checks and the generated API and contract checks, since this change touches no web, API or contract code.

Evidence

No user-visible change. The evidence page has the PR's test failing on main and passing on this head, and the delete trigger's lookup on a 900,000-row queue: 837 ms per file on main, 0.085 ms here.

Evidence: https://evidence.siloserver.org/r/silo-server/pr-3934/

Risks

The concurrent build and drop do not block queue writes, but each waits for transactions older than it, such as the blob collector's batch while it deletes from storage. A long-running transaction elsewhere delays startup on the replica that applies the migration until it ends. The new index is larger than the old one (29 MB against 7.6 MB on the queue above), because distinct (file id, not_before) pairs leave B-tree deduplication nothing to merge. Down restores the old index.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code in T3 Code.
  • Tool(s): Claude Code, GitHub CLI.
  • Model(s): claude-opus-5-5.
  • Involvement: Fully AI-generated; a human asked for the library deletion that showed the problem and requested this pull request once the fix had cleared it on their server. Human review of the diff pending.
  • Adversarial review: A separate Claude Code agent (claude-opus-5-5) reviewed the diff in three passes on scratch databases seeded like the queue above, and reproduced the slow lookup through the real trigger function. Its findings changed the fix twice. Extended statistics still produced the walk on a queue of few files with many images each, so this uses the composite index it suggested. A plain build-then-drop in one transaction stalled media_files writes and deadlocked against the blob collector, so the migration now builds and drops concurrently in Go. The last pass tested interrupted builds and drops, retries and the collector race and found no blockers; its two nits are fixed.

Note

Add composite partial index on blob_gc_queue to speed up media file cleanup

  • Each deleted media file lookup was reading the whole cleanup queue. Migration 20261110144816 replaces the existing chapter-file-only partial index with a composite index on split_part(prefix, '/', 2) and not_before, built with CREATE INDEX CONCURRENTLY in blob_gc_queue_chapter_file_index_migration.go.
  • Extracts the ensure-then-drop index sequence into database.replaceIndexConcurrently in invalid_index_rebuild.go; the push-attempt key migration now uses this helper.
  • Adds a database plan test that inserts 20,000 queue rows and fails if the per-file not_before lookup does not use the new index.
  • Behavioral Change: forward migration drops the old blob_gc_queue_chapter_file_idx-style single-expression index; reverse migration rebuilds it. Existing deployments run the index rebuild concurrently during migration.

Macroscope summarized ee87fce.

…anup queue

queue_deleted_media_file_blobs() asks blob_gc_queue for the latest not_before
among each deleted file's queued chapter images. blob_gc_queue_chapter_file_idx
finds a file's rows but does not order them, and PostgreSQL does not use a
partial index's statistics for estimates, so the planner guessed 0.5% of the
queue per file id and walked blob_gc_queue_due_idx backwards, reading every
row for a file with nothing queued. On a queue of 949,319 chapter images each
lookup took about 550ms.

Replace the index with one on (file id, not_before), built and dropped
concurrently in a Go migration so that a retried run keeps the index it built.
The lookup then seeks to the file and reads one entry, whatever the planner
estimates. The build-then-drop step the push attempt key migration used moves
into a shared replaceIndexConcurrently. A DB pin checks that the lookup uses
the new index.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Nov 10, 2026
@silo-kody

silo-kody Bot commented Nov 10, 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 Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The pull request adds a migration that replaces the chapter-image queue index with an index ordered by file ID and not_before. It registers the migration, reuses a concurrent index replacement helper, and adds a database test that checks the lookup plan.

Changes: Chapter-image queue index

Layer / File(s) Summary
Index replacement and migration
internal/database/invalid_index_rebuild.go, internal/database/blob_gc_queue_chapter_file_index_migration.go, internal/database/push_attempt_key_migration.go
A shared helper ensures a replacement index before concurrently dropping the old index. The new migration replaces the chapter-image queue index with a partial index ordered by file ID and not_before. The push-attempt migration also uses the helper.
Migration registration and lookup-plan test
internal/database/migrate.go, internal/database/migrate_progress_test.go, internal/blobgc/blobgc_db_test.go, scripts/ci/db-pins.txt
The migration is registered, and the migration test checks the registered migration list. A database test verifies that the deleted-file lookup uses the new index, and the CI pin list includes that test.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested labels: bug, go, impact: perf

Suggested reviewers: quick104

Merge Risk: Minimal · up to de35b

No actionable issue remains before merge; proceed with normal migration and database checks.

Security architecture risk: Low · up to de35b

The replacement preserves the queue’s lookup rules and builds the replacement index before removing the old one. No introduced security issue was established. Residual risk is concentrated in online database operations: interrupted builds require recovery, both indexes can temporarily coexist, and production-scale resource use has not been demonstrated.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The deployment effect is database-wide for the shared public.blob_gc_queue index, rather than scoped to one file’s queue rows. The shared helper also serves the existing push-attempt unique-index replacement, although that caller’s behavior is preserved by the refactor.

Trust Boundaries and Controls

  • observed — The new migration supplies fixed index names, schema-qualified targets, and fixed DDL to the shared helper. Queue prefix values are indexed data, not inputs used to construct these DDL statements; no request-derived identifier enters the new migration path.

Resilience and Maintainability Implications

  • inferred — Build-before-drop ordering contains interrupted replacement failures without intentionally removing the only available index. Recovery still depends on retrying the migration, and concurrent creation can temporarily consume resources for both index copies. These are operational recovery considerations, not an established attacker-controlled failure path.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title clearly summarizes the main change: preventing deleted media file lookups from reading the entire cleanup queue.
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.
Description check Passed The description explains the problem (slow deleted-media-file lookups scanning blob_gc_queue), the approach (a composite index on (split_part(prefix, '/', 2), not_before) built and dropped concurrentl…
Full details: Description check

Explanation

The description explains the problem (slow deleted-media-file lookups scanning blob_gc_queue), the approach (a composite index on (split_part(prefix, '/', 2), not_before) built and dropped concurrently via a shared replaceIndexConcurrently helper), validation, and risks. It is clearly related to the changeset, so the check passes.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 56797e27-8219-4249-82f6-94efb0e7be83
Commits

Reviewing files that changed from the base of the PR and between 51b1e0a and de35b6d.

Files selected for processing: 7

  • internal/blobgc/blobgc_db_test.go
  • internal/database/blob_gc_queue_chapter_file_index_migration.go
  • internal/database/invalid_index_rebuild.go
  • internal/database/migrate.go
  • internal/database/migrate_progress_test.go
  • internal/database/push_attempt_key_migration.go
  • scripts/ci/db-pins.txt

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

@coderabbitai coderabbitai Bot added bug Something isn't working go Pull requests that update go code impact: perf Unusable slowness on normal hardware labels Nov 10, 2026
@silo-triage silo-triage Bot added the priority: P1 Core-path bug; painful workaround — next after P0 label Nov 12, 2026

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 Claude Code in T3 Code (claude-opus-5-5)

One finding, and it needs a maintainer decision rather than a change on this branch. The summary comment has the rest of the review.

@Quick104

Quick104 commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🤖 Claude Code in T3 Code (claude-opus-5-5)

Review summary

Reviewed head: ee87fce2ac (de35b6d3d0 with main merged in). The fix works as described, and the merge-order question is settled: #4205 fixed #4071 and is on main.

Rechecked on Nov 14 against main at 8246b53dc2. The head is unchanged, and the branch still merges cleanly. The 193 commits main gained since this branch's base leave queue_deleted_media_file_blobs() and the chapter-image index alone; the one new migration that writes to blob_gc_queue queues marker-thumbnail prefixes, which the new partial index doesn't cover. #4071 is still open, and a fix for it is now in progress.

The defect is real on main. I tested on a local PostgreSQL 18 with main's schema and a queue of 949,319 chapter images across about 20,000 files. For a file with nothing queued, the trigger's max(not_before) lookup estimated 4,746 matching rows (the default 0.5% guess) and walked blob_gc_queue_due_idx backwards, filtering out every row, which took 470 ms. Deleting 50 rows through the real queue_deleted_media_file_blobs() trigger took 24.3 s, about 487 ms per file. At that rate a library deletion with hundreds of thousands of files can't finish within deleteLibraryTimeout (2 hours).

This branch fixes it. On the same queue, the migration built the new index in 0.83 s. In the trigger's own plan (captured with auto_explain), the lookup is an Index Scan Backward on blob_gc_queue_chapter_file_not_before_idx with an Index Cond on the file id. Deleting 5,055 rows took 7.6 ms. Queueing behaved as before: files that had queued images or chapter thumbnails got a file-prefix row protected past 24 hours, and the other files got nothing. A separate review also found that the new index still wins under forced generic plans and on a queue with 50,000 images per file.

Migration. The migration follows DEVELOPMENT.md's rule for replacing an index (a Go migration that builds through ensureIndexConcurrently before it drops). On the populated queue, Down restored the old index's exact definition, Up ran again cleanly, and a retried Up with both indexes present and the version unrecorded dropped only the old index. The version sorts before two newer migrations on main, which is fine because goose runs with out-of-order migrations allowed. The branch merges cleanly with main.

Tests. TestDeletedFileQueueLookupSeeksChapterFileIndexDB fails on the base for the reported reason (Index Scan blob_gc_queue_due_idx) and passes on this head. The other internal/blobgc DB tests pass on this head.

Merge order: #4205, which fixes #4071, merged first. I then merged main into this branch (ee87fce2ac). The merge changed none of this PR's files: its diff against main is the same seven files, and the branch builds and vets cleanly. A waiting server no longer holds a snapshot that stalls this migration's concurrent index build, so a multi-replica startup is safe.

Validated features: No passed case regresses. #1155 C1/C2 (chapter thumbnails) and #1231 C2 (autoscan missing files) share the delete trigger and queue with this change, and they behave the same. Validation tasks: none is correct. I couldn't read the validation board itself, so this comes from the Validation issues' bodies.

User manual: unaffected. No setting, default, or described behavior changes.

Other clients: N/A. This is a server-only database change with no client-visible behavior.

Cross-provider review: One round on this head (Codex gpt-6.1-sol). Its only finding was the startup lock cycle above.

Fit: 9/10 · Readiness: 9/10 — ready (assuming CI is green)

@github-actions github-actions Bot closed this Nov 14, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Thanks for the pull request. Every Silo pull request needs evidence that shows the change working, and this one still has none 24 hours after it opened, so it is closed without review. That isn't a judgment of the work.

The Evidence check's Details link explains how to publish screenshots, a recording, or test results. Publish them, then open a new pull request or ask a maintainer to reopen this one. The contributing guide has the details.

@Quick104 Quick104 reopened this Nov 15, 2026
@github-actions github-actions Bot added the invited Maintainer asked for this PR; the contribution gate skips it label Nov 15, 2026
@Quick104
Quick104 merged commit 8e424cd into Silo-Server:main Nov 15, 2026
32 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code impact: perf Unusable slowness on normal hardware invited Maintainer asked for this PR; the contribution gate skips it priority: P1 Core-path bug; painful workaround — next after P0 size/M 50–199 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants