Skip to content

perf(scanner): finalise variants from narrow rows with batched writes - #2218

Merged
Quick104 merged 4 commits into
Silo-Server:mainfrom
blurbery:perf/scanner-narrow-variant-finalize
Oct 15, 2026
Merged

Quick104 merged 4 commits into
Silo-Server:mainfrom
blurbery:perf/scanner-narrow-variant-finalize

Conversation

@blurbery

@blurbery blurbery commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #2087
Validation tasks: none recorded as passed on the board. The scan cases this path reaches, #1250 C1 and the #197 rescan case, are not run yet.

Every scan ends with a "Finalizing media variants" pass over each match scope. On a large series library that pass costs about as much as the rest of the scan, even when nothing changed. This change makes it read and write only the columns it uses, with a few chunked queries per scope instead of one query per file. Locally, an unchanged 253,501-file root goes from 65 s and 253,502 queries to 16 s and 52 queries.

On upstream main the pass loads every file in the scope with all columns (GetByFolderAndPathPrefix). It then runs GetByEpisodeID or GetByContentID once per scoped file to collect the owner's other files, decoding every row's track and chapter JSON. On my server, one full scan of my largest series library spent 5 min 15 s of its 11 min 24 s in this step, as #2087 describes.

Each file whose variant metadata changed went back through the full Upsert. That writes every column from the copy loaded at the start of the pass, so anything written to the row in the meantime is lost. It also sets match_suppressed_at and missing_since to NULL. An owned file can carry match_suppressed_at: the backlog suppresses an unmatched file, and UpdateContentID links it later without clearing the flag. Finalization cleared it whenever that file's parsed edition or parts changed.

This leaves part of #2087 open: the pass still parses every file in the scope on every scan. That is now most of its cost (Benchmarks). Limiting it to files a scan touched needs change tracking from the scan, which is a separate change.

Approach

  • Finalization reads a narrow VariantFile row: id, owner, path and the edition, presentation and multi-episode columns. It has no probe fields, so it can't be passed to Upsert.
  • The scope load reads present files only and uses the range form of the path predicate (pathscope.RangeCoverageClauses), which keeps the folder/path index usable under a generic plan.
  • Each path is parsed once per pass.
  • The part total is the only value that depends on other files of the same owner, so the owner lookup reads only what can change it. For an owner with an in-scope file in a multipart group (by its parsed hints, its stored values or a stored total) it reads every file. For the other in-scope owners it reads only their files stored as parts, so the parts left behind when a part is renamed out of its group still get a new total. If that turns up a part of a multipart group, the owner is read in full too, since the group's other files may be stored without part columns (after a parser change, for example). Owner ids go in chunks of 5,000, episode owners apart from content owners without an episode link, the same grouping the part totals use.
  • UpdateVariantMetadata writes changes in batches of 1,000 rows through unnest. It sets only the variant columns and updated_at, and skips rows that went missing, moved to another path or already hold the values. Ids are bigint, like media_files.id.

One behaviour changes on purpose. A subtree scan used to re-finalize every file in the folder that shared an owner with a file in the scope. Now an out-of-scope file is re-finalized only when its owner has a multipart group in the scope, or when it is stored as a part. A file's other variant values come from its own path, so they only change when that file's scope is scanned, and a full library scan still covers every file.

Validation

  • go test ./internal/scanner/ -count=1 without a database, and go vet ./internal/scanner/: pass.
  • The five variant DB tests through go run ./scripts/ci/dbpins -list, against a migrated local PostgreSQL 18.6: pass.
    • scripts/ci/db-pins.txt: a pass over a season costs one scope load, one owner lookup and one batched update, and a second pass writes nothing. A movie split across two discs, one outside the scope, gets a total of 2 on both in the same three queries.
    • scripts/ci/db-contracts.txt, TestFinalizeVariantsKeepsMatchSuppressionDB: an unmatched movie file is suppressed, linked with UpdateContentID and finalized. Its edition must change while match_suppressed_at, its probe and chapter columns and a missing sibling stay as they were. Its id is past the int4 range.
    • scripts/ci/db-contracts.txt, TestFinalizeVariantsRetotalsPartsLeftByARenameDB: disc 2 of a two-disc movie is renamed, and a file scan finalizes only the new path. Disc 1's total must drop from 2 to 0.
    • scripts/ci/db-contracts.txt, TestFinalizeVariantsReadsWholeGroupFoundOutsideTheScopeDB: disc 2 is stored without part columns and the scope holds another file of the movie. Both discs must end with a total of 2.
  • The contract tests, added on their own to upstream main (bf63b3d22): the suppression test fails on finalize cleared match_suppressed_at on the cut, and the other two pass. The rename test fails on a version that looks up owners only for multipart groups, as my fork does, and the whole-group test fails on df14c62b6 (disc 1 total 0). With the update's ids narrowed to int32, the suppression test fails on the edition, because the update misses the row.
  • Unit tests cover owner selection (plain episode, split part, a part stored under an older parse, stored total, no owner, movie discs) and the computed updates (stale edition, imported edition kept, part total across the scope boundary, nothing left on a second pass).
  • CI on 0d2fc9f12: every Go job passes, including Go DB pins, which runs the new variant DB tests, and the web checks and tests pass. Web (build), and with it CI result, fails only the launch bundle budget, by 1,214 B, the same failure as on main ([bug] Web build fails the launch bundle budget on main after #2168 #2203, fix in fix(web): keep the download storage API out of the launch bundle #2204). This pull request changes no web code.

Benchmarks

Measured locally with a temporary harness (not committed). It calls FinalizeVariantsByPathPrefix on a seeded library, counts statements with a pgx tracer and Go allocation with runtime.MemStats. Each scenario ran three times after one untimed pass that converges the stored values.

  • Before: upstream main bf63b3d22. After: this branch df14c62b6.
  • Workload: one series library with one root, 845 series of 10 seasons × 30 episodes, one file per episode, except one episode split into two parts (253,501 files). About 3.8 KB of track and chapter JSON per row.
  • Environment: Apple M5 Pro, PostgreSQL 18.6 on the same machine over loopback TCP (shared_buffers 1 GB, work_mem 32 MB, durability settings at their defaults), Go 1.27.1 with GOMAXPROCS=6 and GOMEMLIMIT=3GiB.
Scenario Before, ms After, ms Queries Go allocation
Whole root, nothing to change (253,501 files) 67,068, 65,228, 65,572 15,871, 15,785, 15,704 253,502 to 52 21,759 MB to 5,515 MB
One series, nothing to change (300 files) 77, 76, 74 19, 19, 19 301 to 2 25 MB to 6 MB
Whole root, 20,000 files with a stale edition 75,507, 75,363, 88,133 16,759, 17,921, 24,160 273,502 to 72 22,872 MB to 5,551 MB

0d2fc9f12 came after these runs. It adds a second owner lookup only when the stored-parts lookup turns up a multipart part, which this workload never does, and the query-count pins are unchanged. Both versions fixed all 20,000 stale rows in every repair run and gave both split parts a total of 2. The third repair run was slower for both versions. I didn't find a cause and left the numbers as measured. After the change, a whole-root pass makes one scope load and 51 owner lookups of up to 5,000 episodes each.

A CPU profile of the after runs puts 88% of the samples in naming.ParseVariantHints. What remains is mostly filename parsing on one goroutine.

From my server, read-only. It runs my fork, which already batched the owner lookup into one query per scope, so its "before" was cheaper than upstream main:

  • Before (fork at 6ce7fb5cc, 7 October): the three finalizing phases of one full scan took 34 s, 50 s and 3 min 50 s for scopes of 11,564, 20,982 and 221,014 files.

  • pg_stat_statements, one statistics window on the same server. Between 5 and 8 October the old wide owner lookup ran 722 times (mean 241 ms, maximum 37.9 s). From the 8 October deploy of the narrow pass to 10 October:

    • the narrow scope load ran 365 times (mean 10.7 ms, maximum 957 ms);
    • the narrow owner lookups ran 44 times (maximum 13 ms);
    • the variant update didn't run, because no file needed new values.

    That deployed build only looked up owners with multipart groups, so its lookups are fewer than this branch makes. These are database times only and leave out the decoding and parsing in Go.

  • I don't have per-phase scan timings from my server after the change. The logs of the scans since 8 October went with the containers those builds ran in.

Evidence

Evidence: none, no user-visible change. Finalization writes the same variant values as before for every file it processes. The benchmark output, the regression test runs and the production query statistics are on the evidence page.

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

Risks

  • The subtree narrowing described under Approach.
  • Library scans and subtree or file scans of the same folder can finalize at the same time. Each update statement now locks up to 1,000 rows instead of one, passed in id order. Both passes compute the same values, and the second skips rows that already hold them.
  • When a part is deleted and the scan that marks it missing holds no other file of its owner, the remaining parts keep their total until a scan covers them. Upstream main has the same gap.
  • No migration.

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: A separate Claude Code review agent read the full diff against upstream main for value differences from the old code, SQL NULL handling and casts, convergence, concurrent writers, and whether the tests check what they claim. It found that when a part was renamed out of its group and the scope held only the new file, the remaining part kept a total of 2, which upstream's per-file lookup had fixed. The owner lookup now reads the stored parts of every in-scope owner, and TestFinalizeVariantsRetotalsPartsLeftByARenameDB covers it. An earlier review pass found the update narrowing bigint ids to int32, which is fixed and covered by the suppression test. The batched-lock point it raised is under Risks. Kody then found that a part read as a stored part could be totalled without group members stored without part columns. That is fixed in 0d2fc9f12 and covered by TestFinalizeVariantsReadsWholeGroupFoundOutsideTheScopeDB.

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

Variant finalisation loaded every file in the scan scope with all columns,
then looked up each scoped file's owner with its own GetByEpisodeID or
GetByContentID query, so one pass over a 250k-file series root made about
250k queries even when nothing had changed. Each changed file went back
through the full Upsert, which writes every column from the copy loaded at
the start of the pass and clears match_suppressed_at and missing_since.

- Read a narrow VariantFile row (id, owner, path and the edition,
  presentation and multi-episode columns) for present files only, using
  the range form of the path predicate so the folder/path index stays
  usable under a generic plan.
- Parse each path once per pass.
- Read the in-scope owners' other files in chunked owner queries: every
  file of an owner with a multipart group in the scope, and only the files
  stored as parts for the rest, so parts left behind by a renamed part
  still get a new total.
- Write changes with UpdateVariantMetadata, which sets only the variant
  columns and updated_at in batches through unnest, with bigint ids, and
  skips rows that went missing, moved or already hold the values.

The two query-budget tests are pinned in scripts/ci/db-pins.txt, and the
two behaviour tests in scripts/ci/db-contracts.txt.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-10T09:56:08.671377Z df14c62 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@silo-kody

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

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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 33 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: 125b034b-1ab0-4375-b13f-b8ab7e304b16
📥 Commits

Reviewing files that changed from the base of the PR and between a871269 and 0fa03e8.

📒 Files selected for processing (3)
  • internal/scanner/variant_file_repo.go
  • internal/scanner/variant_finalize_columns_db_test.go
  • internal/scanner/variant_finalize_db_test.go

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: 8c6056a9-51a3-42e9-9b52-b7d9e0720064
📥 Commits

Reviewing files that changed from the base of the PR and between 0d2fc9f and a871269.

📒 Files selected for processing (1)
  • scripts/ci/db-pins.txt

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

Variant finalization loads scoped files and related owner files through variant-specific repository methods. It calculates changed edition, presentation, and multi-episode metadata, then persists updates in batches. Tests cover multipart groups, out-of-scope siblings, unchanged rows, and query counts.

Changes: Variant metadata finalization

Layer / File(s) Summary
Variant-file repository operations
internal/scanner/variant_file_repo.go
Adds a VariantFile projection, path-prefix and owner lookups, and batched metadata updates. Owner lookups use chunks and deduplicate results. Updates apply only to present files at the loaded path whose metadata differs.
Finalization and validation
internal/scanner/variant_finalize.go, internal/scanner/variant_finalize_test.go, internal/scanner/variant_finalize_db_test.go, internal/scanner/variant_finalize_columns_db_test.go, scripts/ci/db-contracts.txt, scripts/ci/db-pins.txt
Finalization discovers scoped and related files, widens reads for multipart groups, calculates changed metadata, and persists sorted updates. Unit and database tests cover metadata preservation, renamed parts, group loading, idempotence, and query counts.

Priority: ➖ Normal

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

Change: Other

Sequence Diagram(s)

sequenceDiagram
  participant FinalizeVariants
  participant FileRepository
  participant Database
  FinalizeVariants->>FileRepository: ListVariantFilesByPathPrefix
  FileRepository->>Database: Query scoped present files
  FinalizeVariants->>FileRepository: ListVariantFilesByOwners
  FileRepository->>Database: Query related owner files
  FinalizeVariants->>FileRepository: UpdateVariantMetadata
  FileRepository->>Database: Update changed metadata in batches
Loading

Suggested reviewers: tomislav

Merge Risk: ⚪ Minimal · up to a8712

No actionable regression was established for this change. The known stale-total behavior predates the PR, and the added database regression test is included in the CI workflow. Merge-ready subject to normal checks.

Pre-merge checks · Passed 4 · Failed 1

Failed Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 42.31% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 5 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks (4 passed)
Check name Status Explanation
Title check Passed The title clearly summarizes the main change: optimizing scanner variant finalization with narrow rows and batched writes.
Description check Passed The description is directly related to the changeset and explains the performance improvements, implementation approach, validation, benchmarks, risks, and known limitations.
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 42.31% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 5 files. (1 skipped: 1 unsupported.)

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · 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: P2 Limited scope, workaround exists, or polish impact: perf Unusable slowness on normal hardware labels Oct 10, 2026 — with Cursor
Comment thread internal/scanner/variant_finalize.go Resolved
…scope

When the stored-parts lookup turns up a part of a multipart group for an
owner that was read only for its stored parts, read the rest of that
owner's files too. Other parts of the group can be stored without part
columns, as after a parser change, and the group's total needs every
part; otherwise the stored part was totalled alone and written as 0.

TestFinalizeVariantsReadsWholeGroupFoundOutsideTheScopeDB is listed in
scripts/ci/db-contracts.txt.
@silo-kody

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

@Quick104
Quick104 merged commit 2659222 into Silo-Server:main Oct 15, 2026
20 checks passed
@blurbery
blurbery deleted the perf/scanner-narrow-variant-finalize 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: P2 Limited scope, workaround exists, or polish

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants