Skip to content

perf(scanner): scan a library root in bounded batches - #3958

Merged
Quick104 merged 15 commits into
Silo-Server:mainfrom
blurbery:perf/scanner-full-scan-batches
Nov 12, 2026
Merged

Quick104 merged 15 commits into
Silo-Server:mainfrom
blurbery:perf/scanner-full-scan-batches

Conversation

@blurbery

@blurbery blurbery commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none changed. Full library scans fall under #1250 C1, which has not been run yet. Targeted scans (#1231 C1, passed) keep their code path; they share the group inference from #3957.

Stacked on #3957: this branch merges it, so until #3957 lands the diff here includes it. Review the commits after the merge, or compare against perf/scanner-lighter-scan-state.

A full library scan holds bookkeeping for every file under a library root at once: each cataloged file's scan-state row, a path index over those rows, item statuses, the set of walked paths, and every file's root and group assignment. On a large root that is most of the scan's memory, and it is held for the whole processing phase. This change keeps one walk and one reconcile per root, as now, but processes the root's files 5,000 at a time and keeps only root-wide tallies between batches.

Measured per component on synthetic data: root and group inference over 300,000 paths peaks at 17.8 MiB of live Go heap batched, against 241 MiB for the whole root, and the cataloged scan state of a 225,000-file root at 83 MiB, against 550 MiB. On my server, the Silo process peaked at 525 MB during the daily full library scan, down from a floor of 2.25 GB, with this, #3955, #3956, #3957 and my other RAM changes deployed together (Benchmarks).

Approach

  • Before the walk the scan lists only the id, path and missing time of the files cataloged under the root. After the walk it keeps the ones the walk did not see. Those are the only rows missing-file marking, stale-row cleanup and confirmed-empty cleanup act on.
  • Primary files are processed in walk order, 5,000 at a time. Each batch infers its files' roots and groups, adding to the root's tallies, then reads its scan-state rows by exact path and its item statuses, and drops them once its files are done. Workers can still be finishing one batch while the next loads, so two batches are held at most.
  • Root snapshots, content groups, observed locations and group locations are tallied across batches: a tally keeps the first file's identity and counters for the rest. Root inference becomes an accumulator in internal/naming that the whole-list InferRootAssignments also uses, so roots and groups each have one implementation, shared with subtree and single-file scans.
  • Extras keep being processed together after the primary files; their rows are now read by exact path.
  • Subtree and single-file scans keep their code path.

Why the catalog comes out the same:

  • A file's root and group assignment depends only on its own path, the overrides and the library roots, so inferring a batch at a time gives each file the same assignment. TestBatchedInferenceMatchesSinglePass checks that every batch size gives the same snapshots, and on 300,000 synthetic paths the batched snapshots hash the same as the single pass (Benchmarks).
  • processFile and processExtraFiles only look up a file's own row and its own item's status. Relinking a moved file reads its candidates from the database and only takes rows whose path is gone from disk, so no later batch looks for a row an earlier batch changed.
  • The files that may be marked missing are still fixed before the walk, so a file another scan adds meanwhile is never taken for one that vanished.
  • Dead roots, suspect empty roots, walk failures, the cleanup allowance, pruning and folder-wide finalisation see the same inputs, and their code is untouched.
  • A cancelled scan, or a batch read that fails, returns before any reconcile, so a partial walk never marks files missing or rewrites snapshots.

Sharding the walk by top-level folder and reusing the subtree scan was the obvious alternative. I didn't take it because groups and observed locations have no path in their key, so a scoped replace would write partial counts and one primary location per shard, and emptiness, walk failures and symlink dedupe are root-wide facts.

Two things are not identical to main:

  • Item statuses are read per batch, just before the batch runs, instead of once before the walk. If the matcher settles an item while an earlier batch is processing, a later batch's files of that item can count as Unchanged rather than Updated. The end state is the same or fresher; the New/Updated/Unchanged counts are no longer all from one snapshot.
  • A failed batch read now aborts the scan after earlier batches were processed. Nothing is reconciled, and the next scan picks up where the files stand.

Still proportional to the root: the walked path list, the presence list of cataloged files and the set used to find the unseen ones (both short-lived, around the walk), the sidecar listing, the extras' rows, and 16 bytes per file of group evidence. In the server heap profile below, the walked paths and directory listings are the two largest entries at the scan's peak. A configured root that walks empty still has every row under it loaded in full to check for a dropped mount; #3955 fixes that separately.

Validation

  • go vet ./internal/scanner/: pass.
  • Focused tests without a database: the scanner inference and subtitle tests, also under -race, and go test ./internal/naming/: pass.
  • DB tests against a migrated local PostgreSQL 18.6, all in scripts/ci/db-contracts.txt: pass.
    • A batched scan with a batch size of 2 and one with every file in one batch catalog a series library identically through a first scan, a rescan, a deleted top-level folder, an unreadable folder and a dropped mount, including a show split across two top-level folders.
    • A batched scan finds the rows of cataloged extras instead of taking them for new files.
    • A batch read that fails after earlier batches were processed returns the error, marks nothing missing and rewrites no snapshot. With the error swallowed the test fails.
  • The unreadable-folder step is skipped when the tests run as root, since permission bits don't stop root.
  • CI: every Go job passes on 019bf0879, including Go lint and Go DB pins, which ran the three batched-scan DB tests (run). Web jobs were skipped; no web code changed.

Benchmarks

Per component, synthetic

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. Both columns ran on this branch at 019bf0879: "whole root" is how #3957 and main hold a root (those whole-list functions are still here for subtree scans), "batched" is how this branch's full scan holds it.

  • Workloads: root and group inference over 300,000 episode paths (1,500 shows of 10 seasons of 20 episodes, in walk order). The cataloged scan state of a series folder of 225,000 episodes, rows sized like my real catalog: every row with its path index and item statuses, against the presence list plus two live batches of 5,000.
  • Metrics: peak live heap (the runtime's /gc/heap/live:bytes, sampled every millisecond with GOGC=10), the heap still held after the call.
  • Environment: Apple M5 Pro, PostgreSQL 18.6 on the same machine over loopback TCP, Go 1.27.1 with GOMAXPROCS=6 and GOMEMLIMIT=3GiB.
Component Whole root: peak / held Batched: peak / held
Root and group inference, 300,000 paths 241.4 MiB (239.3-246.9) / 237.8 MiB 17.8 MiB (17.0-18.1) / 9.0 MiB
Cataloged scan state, 225,000-file root 549.7 MiB (549.5-550.0) / 549.7 MiB 82.7 MiB (82.7-82.9) / 66.4 MiB

My server, whole build

My server runs my fork. The after build has these four pull requests and my other RAM changes (plugin processes, catalog and database queries, in separate pull requests), so these readings are for the Silo process under that whole build, not this pull request alone. Both builds ran with the same operator settings, GOGC=50, GOMEMLIMIT=3GiB and GOMAXPROCS=4; a default install sets none of these. The library has 334,169 files, and the largest root about 225,000.

Before After
Silo process peak during the daily full library scan at least 2.25 GB (VmHWM over 47 hours that included two of those scans) 525 MB (RSS sampled every 20 s, 442 MB of it anonymous)
Go heap in use at the scan's busiest profile no profile 203 MB
Largest root's scan time 738-821 s 643 s
  • The before figure is a floor: Go returns memory with madvise, which the high-water mark doesn't always record. The after figure is sampled and could miss a short spike.
  • The catalog after the scan matched the one before it (present files 334,169 and 334,171, 5 files newly missing that are gone from disk, items and groups unchanged, no file errors).
  • In the busiest heap profile the two largest entries are the walked path list (48.5 MB) and directory reads (38.5 MB), the parts this change leaves proportional to the root.
  • I didn't re-run the old build with profiling, so there is no per-component split for the before side on the server; the synthetic tables are that split.

Evidence

Evidence: none, no user-visible change. The catalog is the same after a scan. The benchmark output, the server memory readings and the heap profile summary are on the evidence page.

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

Risks

  • The two differences above (per-batch item statuses, a failed batch read after earlier batches).
  • About 60 more scan-state reads and 60 more status reads per 300,000-file root, each by exact path.
  • No migration, no setting.

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 on top of perf(scanner): keep less per-file bookkeeping during a library scan #3957. It looked for any lookup that relied on every row of the root being loaded (relinking, extras, item statuses), checked missing-file marking and stale cleanup against the unseen list, cancellation and failures between batches, the root inference accumulator against the old whole-list code, the counts and progress, and the memory claim. It found no case where the catalog differs. It pointed out that item statuses are now read per batch, and that a failed batch read aborts the scan after earlier batches ran with no test for it. Both are described under Approach, and the second now has a DB test. It also listed root-sized structures my first draft of this description left out, now under Approach. Before that review, inferGroupAssignments was moved onto the batched tally so there is one group implementation; that part lives in perf(scanner): keep less per-file bookkeeping during a library scan #3957.

Note

Process full library scans in bounded batches of 5000 files

  • Primary files are now loaded and processed in batches through worker goroutines, with a default batch size of 5000 files and a Scanner field to override it (scan_batches.go)
  • Root and group inference were refactored into incremental accumulators (naming.RootInference, scanner.scanRootInference, scanner.scanGroupInference) so assignments and snapshots build up across batches while matching single-pass results (root_inference_accumulator.go, group_inference.go)
  • Scan state was slimmed to compact scanPresence records for missing-file and stale-path reconciliation, instead of retaining full scan-state rows (scan_presence.go)
  • The external subtitle directory cache now evicts entries least-recently-used first, capped at 512 entries (subtitles.go)
  • Database tests verify batched scans catalog identically to single-batch scans across rescan, deleted-folder, unreadable-folder, and dropped-mount scenarios (full_scan_batches_db_test.go)
  • Risk: files must be added to inference accumulators in walk order to preserve which file supplies a root's sample path, title, and year — check RootInference.Add callers in root_inference_accumulator.go

Macroscope summarized 019bf08.

A full scan holds its bookkeeping for every file under a root at once.
Three parts of it were heavier than they needed to be:

- Group inference kept two full copies of every file's group identity,
  one per group and one per observed root, only to count them and read
  a few fields. Each bucket now keeps the first file's identity and,
  for the rest, just the fields the snapshot reads.
- The subtitle directory cache kept the listing of every directory for
  the whole scan. Files are processed in walk order, so it now keeps
  the 512 most recently used listings and reads a directory again if it
  has dropped out.
- Scan state rows each held their own copy of strings that repeat
  across the files of a show or folder (roots, group key, title, codec
  and container names). The rows of one load now share one copy.

Scan results are unchanged.
Share the scan state strings in a separate pass so the row scanner is
unchanged, name the group states, check the subtitle cache's type
assertions, and encode group evidence from a typed struct whose field
order keeps the stored JSON identical.
A full scan held its per-file bookkeeping for every file under a
configured root at once: the scan state row of each cataloged file, a
path index over those rows, the set of walked paths, and each file's
root and group assignment. That is roughly 3 KB per file, so about
1 GB of live heap for a 300,000 file root.

The scan now keeps one walk and one reconcile per root, exactly as
before, and only bounds what it holds in between:

- Before the walk it lists just the id, path and missing time of the
  files cataloged under the root. After the walk it keeps only the
  ones the walk did not see, which are the only rows missing-file
  reconciliation, stale-row cleanup and confirmed empty cleanup act on.
- Files are processed in walk order, 5,000 at a time. Each batch reads
  its scan state rows by exact path and its item statuses just before
  it is processed, and drops them when its files are done. Workers can
  still be finishing one batch while the next loads, so two batches
  are held at most.
- Root snapshots, content groups, observed locations and group
  locations are tallied across batches. A tally keeps the first file's
  identity and counters for the rest, so a show split across top-level
  folders, a library-root series and loose files at the root still
  produce one snapshot with the full file count, the first file walked
  as its sample and primary location, and the same evidence.

Why the catalogue comes out the same:

- Sharding the walk by top-level directory and reusing the subtree
  scan was considered and rejected. Groups and observed locations have
  no path in their key, the scoped replace would write partial counts
  and one primary location per shard, a directory that vanished would
  have no shard, and emptiness, walk failures and symlink dedupe are
  root-wide facts. Keeping the walk and the reconcile whole avoids all
  of that: dead-root, suspect-empty-root, walk-failure, cleanup
  allowance, pruning and folder-wide finalisation code is untouched
  and sees the same inputs.
- A file's root and group assignment depends only on its own path, the
  overrides and the library roots, so inferring a batch at a time
  gives each file the same assignment. Root inference now has one
  implementation, an accumulator that the whole-list function also
  uses. Group tallies are a second implementation next to
  inferGroupAssignments, which subtree and single-file scans still
  use; a test holds the two equal at every batch size.
- The set of files that may be marked missing is still fixed before
  the walk, so a file another scan adds meanwhile is not mistaken for
  one that vanished.
- A batch's scan state is read later than before, so it can only be
  fresher. processFile reads the row of its own path alone, and
  relinking a moved file only takes rows whose path is gone from disk.
- A cancelled scan still returns before any reconcile, so partial
  tallies are never written.

Subtree and single-file scans keep their existing code path. Still
proportional to the root: the walked path list, the sidecar listing
and 16 bytes per file of group evidence.

Measured on 300,000 synthetic episode paths, root and group inference
alone went from 286 MB of live heap to 16 MB. A scan of that root does
about 60 more scan state reads and 60 more status reads than before.
inferGroupAssignments now runs the same group tally a full scan builds a
batch at a time, so subtree and single-file scans and full scans share
one implementation of the group, location and group-location snapshots.
The per-file identity step is its own function. The bucket types the
whole-list pass kept are gone, and the batched inference test now checks
that splitting the files into batches does not change the result.
…file

Group inference kept a bucket entry for every file. It now keeps a tally
per content group and per observed location: the first file's identity,
which supplies the snapshot's sample and identity fields, and for the
rest of the files only what the snapshot counts (one shared string per
file for the group evidence). The per-file identity step is its own
function. The snapshots and their evidence are unchanged.
The concurrent cache test now gives the cache room for two directories
and has its workers read four, so eviction and re-reads run under the
race detector.
A batched full scan can fail reading a batch's rows after earlier
batches were processed. The scan must return the error before any
reconcile: a file gone from disk is not marked missing and no snapshot
is rewritten from the partial walk.
@silo-triage silo-triage Bot added the size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. label Nov 11, 2026
@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 35 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: c8e991d4-4119-4746-a1f7-d534ede37afb
Commits

Reviewing files that changed from the base of the PR and between 75e10d3 and 019bf08.

Files selected for processing: 14

  • internal/naming/root_inference.go
  • internal/naming/root_inference_accumulator.go
  • internal/naming/root_inference_accumulator_test.go
  • internal/scanner/full_scan_batches_db_test.go
  • internal/scanner/group_inference.go
  • internal/scanner/root_observation.go
  • internal/scanner/scan_batches.go
  • internal/scanner/scan_inference.go
  • internal/scanner/scan_inference_test.go
  • internal/scanner/scan_presence.go
  • internal/scanner/scanner.go
  • internal/scanner/subtitles.go
  • internal/scanner/subtitles_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-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 ❌

Measured, it saved 51 MB on a 225,000-file series root but almost
nothing on a movie library, where the map cost more at its peak than
it saved, and a batched full scan holds too few rows for it to matter.
It is not worth the code.
Comment thread internal/scanner/scan_batches.go Resolved
@Quick104

Quick104 commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Review summary

Reviewed head: 019bf0879 (includes #3957, which is still open, so this PR can't merge before it).

I found no defects in this PR's own commits. A trace of every lookup that could reach another batch's row (processFile, processExtraFiles, relinking, missing-file marking, stale cleanup) found none: each reads only its own path, or reads the database directly. The root inference accumulator gives the same snapshots as the whole-list code it replaces, given walk order. Passing a nil seenPaths together with unseenExisting selects the same rows as before, including the forceDeleteAll case. The earlier thread about a failed batch read is answered by the existing reply and the DB test.

Memory at a larger scale

I ran the scan-state and inference code this PR changes against a copy of real catalog rows for one large series root from a large deployment. It ran in a throwaway harness against local PostgreSQL, measuring live Go heap (/gc/heap/live:bytes, GOGC=10) above the walked path list, which both versions hold. Item statuses weren't included in either version.

Peak above baseline Held at end Time
main (whole root) 1,016–1,038 MiB 872 MiB 97–100 s
this branch, whole-root functions (the #3957 shape) 872–893 MiB 872 MiB 96–100 s
this branch, batched 68 MiB 50 MiB 104 s

That's about 15x less for a root 1.27x larger than the one in the description, with no growth in the batched figure. The batched path was about 8% slower in the harness. That comes from the per-batch file_path = ANY(...) reads, which use the unique file_path index (about 90 ms per 5,000 paths). On a full library scan that runs for tens of minutes, the difference is small. The same deployment's nightly scan of this library peaks at about 2.4 GiB of Go heap above idle on main, so most of that should go. I didn't run a full scan with this branch to confirm it.

Tests

The new DB tests call functions this PR adds, so they can't run on the base. They passed in CI on this head (Go DB pins). I didn't count them toward validation.

Other checks

  • Validation: the v1.0 board couldn't be checked from here. Full library scans fall under Series — Server #1250 C1, which hasn't been run, as the description says.
  • User manual: unaffected (no setting, default, or visible behavior changes).
  • Apple/Android and jellycompat: unaffected.

Fit: 9/10 · Readiness: 8/10 — conditional

  • Fit: it lowers a full scan's memory on large libraries without a new setting or code path, which fits Silo's large-library goal. Subtree and single-file scans keep their existing code.
  • Readiness: no defects found, and the memory claim holds on real data at a larger scale. Two conditions remain: perf(scanner): keep less per-file bookkeeping during a library scan #3957 has to land first, and the batched scan hasn't run end to end on a library this size.

Posted by Claude Code (claude-opus-5-5) for a maintainer.

@Quick104
Quick104 merged commit 0982f9f into Silo-Server:main Nov 12, 2026
23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants