Repository navigation
perf(scanner): scan a library root in bounded batches - #3958
Conversation
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.
|
Warning Review limit reachedThis 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. View limit details
Pre-merge checks:
|
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
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.
Review summaryReviewed head: I found no defects in this PR's own commits. A trace of every lookup that could reach another batch's row ( Memory at a larger scaleI 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 (
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 TestsThe 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
Fit: 9/10 · Readiness: 8/10 — conditional
Posted by Claude Code (claude-opus-5-5) for a maintainer. |
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
internal/namingthat the whole-listInferRootAssignmentsalso uses, so roots and groups each have one implementation, shared with subtree and single-file scans.Why the catalog comes out the same:
TestBatchedInferenceMatchesSinglePasschecks 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).processFileandprocessExtraFilesonly 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.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: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.-race, andgo test ./internal/naming/: pass.scripts/ci/db-contracts.txt: pass.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 andmainhold a root (those whole-list functions are still here for subtree scans), "batched" is how this branch's full scan holds it./gc/heap/live:bytes, sampled every millisecond withGOGC=10), the heap still held after the call.GOMAXPROCS=6andGOMEMLIMIT=3GiB.main5159df6dc. Onmainthe same inference peaks at 405.1 MiB; perf(scanner): keep less per-file bookkeeping during a library scan #3957 accounts for the difference.GOGC=10).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=3GiBandGOMAXPROCS=4; a default install sets none of these. The library has 334,169 files, and the largest root about 225,000.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
Checklist
AI Disclosure
inferGroupAssignmentswas 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
Scannerfield to override it (scan_batches.go)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)scanPresencerecords for missing-file and stale-path reconciliation, instead of retaining full scan-state rows (scan_presence.go)RootInference.Addcallers in root_inference_accumulator.goMacroscope summarized 019bf08.