Skip to content

perf(scanner): finalise variants a page at a time - #3956

Merged
Quick104 merged 5 commits into
Silo-Server:mainfrom
blurbery:perf/scanner-page-variant-finalise
Nov 14, 2026
Merged

Quick104 merged 5 commits into
Silo-Server:mainfrom
blurbery:perf/scanner-page-variant-finalise

Conversation

@blurbery

@blurbery blurbery commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none changed. Targeted scans finalise variants through this code, so it reaches #1231 C1 (passed); every file gets the same values as before. Full scans fall under #1250 C1, which has not been run yet.

Every scan ends with a variant finalisation pass over each scope it scanned. The pass loaded every present file under the scope at once and parsed each one's variant hints, so its memory grew with the library: on a whole TV root it held every file of the root at the same moment. This change walks the scope in path order, 2,000 files at a time, and finalises each page before reading the next. The values written are the same.

Measured on a synthetic 225,000-file series root with rows sized like my real catalog, the pass peaked at 148 MiB of live Go heap on main and 1.7 MiB paged, about 10% slower.

Approach

  • ListVariantFilesByPathPrefix returns one page: up to 2,000 present files under the scope whose path sorts after a cursor, in bytewise path order. It is a keyset query on the (media_folder_id, file_path text_pattern_ops) index with ~>=~/~<~ bounds and ORDER BY file_path USING ~<~, so each page is an index range scan, under a generic plan too. The first page also reads the file at the scope path itself, for a scope that is one file.
  • FinalizeVariantsByPathPrefix finalises each page with the existing code, unchanged, before reading the next.
  • pathscope.DescendantRange is the bound calculation RangeCoverageClauses already did, pulled out so the page query can use it.

Why paging can't change a written value: everything a file gets is computed from its own path and stored import fields, except the part total. A file in a multipart group makes its page read its owner's files across the whole folder, as it did before, so a group whose parts land on different pages is read in full, and written, by the first page that holds one of its parts. Later pages compute the same total from the same files, and the update skips rows that already hold their values.

Memory now follows a page plus the owners its files belong to (those owner reads are unchanged), not the scope. An owner read in full is written in full, so later pages leave out the files it wrote instead of reading the whole owner again; an owner with a multipart group that spans several pages is read once. A file skips only while it still has the owner and path it was written with, so a file linked to that owner or renamed while the pass is paging is read again with its owner.

Validation

  • go vet ./internal/scanner/: pass.
  • The variant DB tests (go test -run TestFinalizeVariants ./internal/scanner/ against a migrated local PostgreSQL 18.6): pass, including the existing query-count pins, which still see one scope load for a scope shorter than a page.
  • New DB test, in scripts/ci/db-contracts.txt: two movies with discs, finalised at page sizes 1, 2 and 3. The second movie's files all sort after the first's and its two discs straddle a page boundary, so they only get their total of 2 (and its stale edition is only cleared) if every page is read. A one-file scope runs first on unsettled rows. With the loop cut short after the first page the test fails.
  • New DB test, in scripts/ci/db-contracts.txt: a third disc is linked to a movie from a query hook after an earlier page read the movie in full and before the disc's own page is listed. All three discs get a total of 3. On b9b75137b, which skipped by owner, the totals stayed 2, 2 and 0.
  • CI: every Go job passed on 9ef705759, including Go lint and Go DB pins, which ran the new paging test (run). Web jobs were skipped; no web code changed.

Benchmarks

Measured with a temporary harness (not committed; its source is on the evidence page), one measurement per process, five runs each, medians with the range in brackets. One unrecorded pass first converged the stored values, so every measured pass writes nothing, as on an unchanged library.

  • Before: upstream main 5159df6dc. After: 9ef705759. b9b75137b after it only skips owners an earlier page read in full, which this workload, with no multipart groups, never does; 51baf80e9 only changes what that skip records.
  • Workload: FinalizeVariantsByPathPrefix over a whole library root. A series folder of 225,000 episodes (1,125 shows of 10 seasons of 20 episodes) and a movie folder of 20,000 movies, each row sized like my real catalog.
  • Metrics: peak live heap (the runtime's /gc/heap/live:bytes, sampled every millisecond with GOGC=10), bytes allocated, wall time. Times are with GOGC=10, which slows allocation-heavy code; compare them between the columns only.
  • Environment: Apple M5 Pro, PostgreSQL 18.6 on the same machine over loopback TCP, Go 1.27.1 with GOMAXPROCS=6 and GOMEMLIMIT=3GiB.
Scope Peak live heap, before Peak live heap, after Allocated, before / after Time, before / after
Series root, 225,000 files 147.9 MiB (147.8-147.9) 1.7 MiB (1.7-1.8) 5,695 / 5,734 MiB 24.1 / 26.4 s
Movie root, 20,000 files 13.3 MiB (13.2-13.3) 1.7 MiB (1.7-1.7) 422 / 425 MiB 1.2 / 1.2 s

The paged pass is about 10% slower on the series root: it reads the scope and looks up owners once per page, 113 times, where main did each once. The full-scan figure from my server, which covers this change together with #3957 and #3958, is in #3958.

Evidence

Evidence: none, no user-visible change. Finalisation writes the same values as before. The benchmark output is on the evidence page.

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

Risks

  • A file renamed behind the cursor while the pass is paging can be skipped by this pass; its rename's own scan finalises it. A file renamed ahead of the cursor is finalised twice, which is harmless. The old single read had the same exposure for files changed just after it ran.
  • A scope that is an exact multiple of 2,000 files costs one extra empty page query.
  • No migration.

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 (desktop app)
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5, claude-fable-5-2
  • Involvement: AI-assisted
  • Adversarial review: A separate Claude Code review agent (claude-fable-5-2) read the diff against upstream main and tried to find a way paging changes a written value: cursor order against PostgreSQL's bytewise operators, non-UTF-8 names, the first page's extra row and the stop rule, owner reads across pages, concurrent renames and the query plan. It found none. It did find that the paging test settled every file from its first disc page, because all of the files had one owner, so a loop that stopped early still passed. The test now has a second movie after the first, with its discs across a page boundary, and runs the one-file scope on unsettled rows. Its other notes (the extra empty page, the rename window) are under Risks. Kody then pointed out that an owner with a multipart group spanning several pages was read in full on each of them; later pages now skip owners already settled (b9b75137b). A maintainer review (Claude Code, claude-opus-5-5, with a Codex gpt-6.1-sol adversarial round that found nothing) found that the skip also dropped a file linked to a settled owner while the pass was paging; 51baf80e9 keys the skip on the files written instead.

Note

Finalize variant files in path scope one page at a time

  • Replaces the single full-scope load in scanner.Scanner.FinalizeVariantsByPathPrefix with a cursor-paged loop using a default page size of 2000 (variantFinalizePageSize), walking descendant files ordered by PostgreSQL bytewise path and stopping on an empty or short page
  • Carries settled-file state (owner key plus path) between pages so later pages skip files already finalized, but keep files whose owner or path changed since being settled
  • scanner.FileRepository.ListVariantFilesByPathPrefix now takes an after cursor and page limit, and includes the exact root path in a UNION ALL branch on the initial request; the bound construction is extracted into the shared pathscope.DescendantRange helper
  • Adds DB contract tests for paging across page sizes 1, 2, and 3, and for re-reading a file linked to an owner between page queries
  • Behavioral Change: variantFinalizationCandidates returns an owner-key set alongside candidates, and ListVariantFilesByPathPrefix has a new signature; existing callers of these in variant_file_repo.go and variant_finalize.go are updated in this PR

Macroscope summarized 51baf80.

Variant finalisation loaded every present file under the scanned scope at
once, with parsed hints for each, so its memory grew with the library.

It now walks the scope in path order, 2000 files at a time, and finalises
each page before reading the next. Results are unchanged: the sibling
lookups already read by owner across the whole folder, so a multipart
group split over two pages is read in full and written by the first page
that holds one of its parts.

Each page is a keyset query on the folder and path index. The first page
also reads the file at the scope path itself, for a scope that is one file.
The paging test settled every file from its first disc page, because all
of its files had one owner, so a loop that stopped early still passed.
A second movie now sorts after the first, with its two discs straddling
a page boundary, and the single-file scope runs on unsettled rows.
@coderabbitai

coderabbitai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

This organization requires a seat for paid usage-based reviews, including automatic and on-demand reviews. Ask an admin to assign a seat or enable paid usage-based reviews for users without a seat in Billing.

Next included review available in 21 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

  • 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: 58b43bab-93b1-4df1-92ec-184465f8c4d8
Commits

Reviewing files that changed from the base of the PR and between 75e10d3 and 51baf80.

Files selected for processing: 5

  • internal/pathscope/pathscope.go
  • internal/scanner/variant_file_repo.go
  • internal/scanner/variant_finalize.go
  • internal/scanner/variant_finalize_columns_db_test.go
  • scripts/ci/db-contracts.txt
Pre-merge checks: Inconclusive 2

Failed Failed checks: 2 inconclusive

Check name Status Explanation Resolution
Title check Pending This assessment has not completed. The check will be retried on the next pre-merge check run.
Description check Pending This assessment has not completed. The check will be retried on the next pre-merge check run.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Nov 11, 2026
@silo-kody

silo-kody Bot commented Nov 11, 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 ❌

⚠️ Note: some checks couldn't be completed in this run, so auto-approval (when enabled) was skipped. Check the details at https://kodus.siloserver.org/pull-requests and then comment @kody review on this PR to retry once the issue is resolved.

Comment thread internal/scanner/variant_finalize.go Resolved
@blurbery
blurbery marked this pull request as ready for review November 11, 2026 03:45
@silo-kody

silo-kody Bot commented Nov 11, 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 ❌

⚠️ Note: some checks couldn't be completed in this run, so auto-approval (when enabled) was skipped. Check the details at https://kodus.siloserver.org/pull-requests and then comment @kody review on this PR to retry once the issue is resolved.

A page reads every file of an owner that has a multipart group and
writes them all. An owner whose files span several pages was read in
full again on each of them. Later pages now leave out the files of
owners an earlier page read in full, since those are already written.
@silo-triage silo-triage Bot added size/L 200–499 added + deleted lines (all files); change volume, not priority. and removed size/M 50–199 added + deleted lines (all files); change volume, not priority. labels Nov 11, 2026
@silo-kody

silo-kody Bot commented Nov 11, 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 ❌

@silo-triage silo-triage Bot added go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels 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.

Review of b9b75137b. Paging itself holds up: the cursor, the stop rule with the first page's extra row, the dropped LIKE, whole and widened owners, and the existing query-count pins all check out, and a Codex adversarial round found nothing either. One finding, on the settled-owner skip, which I'm fixing in a commit on this branch, so there's no need to change it yourself.

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

Comment thread internal/scanner/variant_finalize.go Resolved
A later page skipped every file whose owner an earlier page had read in
full. A file linked to that owner after the read, by an Identify or a
metadata job while a long scan was paging, was skipped too and never
counted in the owner's multipart group.

Record the files a page writes with their whole owner, by id with the
owner and path they had, and skip a later file only while both still
match. The test links a third disc from a query hook just before its
page is listed; before this change the totals stayed 2, 2 and 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Nov 14, 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

Copy link
Copy Markdown
Contributor

Review summary

Reviewed head: 51baf80e9 (b9b75137b plus one fix commit; the branch was not rewritten).

Addressed

  • The settled-owner skip dropped a file linked to a settled owner while the pass was paging, so that file was left out of the owner's multipart group until the next scan. Fixed in 51baf80e9: the skip now applies only to files an earlier page wrote, while they keep the owner and path they had. TestFinalizeVariantsRereadsOwnerLinkedBetweenPagesDB fails on b9b75137b (totals 2, 2 and 0) and passes with the fix. It is registered in scripts/ci/db-contracts.txt.

Checked and holding

  • The cursor uses Go string order, which matches PostgreSQL's ~<~ bytewise order. file_path is unique, so a strict ~>~ cursor can't skip a row.
  • The first page's extra exact-path row can only add one empty query; it can't end the walk early.
  • Dropping the LIKE changes nothing: [root/, root0) holds exactly the paths that start with root/.
  • Whole and widened owners are read across the folder before they're settled, and part totals are computed per owner. Other RangeCoverageClauses callers get the same SQL and arguments.
  • The existing query-count pins still see one scope read. Every TestFinalizeVariants* DB test passes on PostgreSQL 18 with the fix.
  • A Codex (gpt-6.1-sol) adversarial round on b9b75137b found nothing.
  • Kody's repeated-owner-read comment was handled by b9b75137b, and the fix keeps that saving.

Remaining for maintainers: none. One note: no test checks that the skip happens at all, only that the values are right. Removing the skip would cost the saving Kody asked for but would write no wrong value.

Validated features: Autoscan server #1231 C1 (passed) reaches this code through targeted scans. It shows no behavior change: the same values are written, and only the reads are paged. Manual metadata edit #1210 C2 and #1211 C2 rescans reach it the same way, also with no behavior change. Series #1250 C1 has not been run. Validation tasks: none, matching the body.

User manual: unaffected. This is an internal change to scan memory use, with no setting, label or behavior the manual describes.

Other clients: N/A. Nothing a client sees changes, and jellycompat reads the same stored values.

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

  • Fit: it bounds a memory cost that grew with library size and keeps stored values the same. That serves both a small single box and very large libraries, and it adds no setting or new surface.
  • Readiness: unchanged values are covered by the paging test and the new relink test, which failed before the fix. The memory bound follows from the LIMITed keyset read and agrees with the author's benchmark. The pass is about 10% slower on a 225,000-file root, and the body discloses that.

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

Comment on lines +113 to +115
for _, candidate := range candidates {
if _, ok := wholeOwners[candidate.ownerKey]; ok {
settled[candidate.file.ID] = settledVariantFile{ownerKey: candidate.ownerKey, path: candidate.file.FilePath}

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 medium

Settled file cache grows with the entire multipart library

Revises an earlier Kody suggestion on internal/scanner/variant_finalize.go:48 (2026-11-11 03:32 UTC).

Full scans of multipart-heavy libraries can use memory proportional to the number of files rather than the page size. Evict entries from settled once their paths are behind the cursor, and avoid retaining out-of-scope entries.

Prompt for LLM
File internal/scanner/variant_finalize.go, lines 113-115:

**Revises an earlier Kody suggestion** on `internal/scanner/variant_finalize.go:48` (2026-11-11 03:32 UTC).

Settled file cache grows with the entire multipart library

Every file belonging to a fully loaded multipart owner remains in `settled` until the entire scope finishes, retaining its path and owner key even after its page has passed. Full scans of multipart-heavy libraries therefore accumulate O(number of files) memory rather than page-bounded state; evict entries once their paths are behind the cursor and avoid retaining out-of-scope entries.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

@Quick104
Quick104 merged commit 5d63790 into Silo-Server:main Nov 14, 2026
20 checks passed
Quick104 added a commit to blurbery/silo-server that referenced this pull request Nov 14, 2026
Main's Silo-Server#3956 extracted the same pathscope.DescendantRange helper. Keep
this branch's corrected comment for the filesystem root.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/L 200–499 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants