Skip to content

perf(scanner): keep less per-file bookkeeping during a library scan - #3957

Merged
Quick104 merged 5 commits into
Silo-Server:mainfrom
blurbery:perf/scanner-lighter-scan-state
Nov 12, 2026
Merged

Quick104 merged 5 commits into
Silo-Server:mainfrom
blurbery:perf/scanner-lighter-scan-state

Conversation

@blurbery

@blurbery blurbery commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none changed. Targeted scans run this group inference and subtitle detection, so it reaches #1231 C1 (passed); their results are the same. Full scans fall under #1250 C1, which has not been run yet.

A library scan holds some bookkeeping for every file under a root at once, and two parts of it were heavier than they needed to be:

  • Group inference kept two full copies of every file's group identity, one in its content group's bucket and one in its observed location's bucket, only to count them and read a few fields.
  • The external subtitle cache kept the directory listing of every directory it read for the whole scan.

This change keeps less of each. Scan results are the same.

Measured on 300,000 synthetic episode paths, group inference peaked at 316 MiB of live Go heap on main and 151 MiB on this branch, for the same 70 MiB result. Over 5,000 season folders, the subtitle cache peaked at 18.4 MiB on main and 2.7 MiB here.

Approach

  • Group inference keeps a tally per content group and per observed location instead of a bucket of identities: 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 string header per file for the group evidence). The per-file identity step is its own function. The group, location and group-location snapshots, their evidence JSON and their order are the same.
  • The subtitle cache keeps the 512 directory listings it used most recently and reads a directory again if it has dropped out. Files are processed in walk order, so a video's lookups stay in its own directory, the subtitle folders under it and the directories above it.

#3958 builds on this to process a full scan in batches; the tally here is the one it adds to batch by batch.

Validation

  • go vet ./internal/scanner/: pass.
  • Group inference tests and the subtitle cache tests, with -race: pass. On 300,000 synthetic episode paths the snapshots and every file's assignment hash the same on upstream main and this branch (Benchmarks).
  • The concurrent subtitle cache test now gives the cache room for two directories and has 16 workers read four, so eviction and re-reads run under the race detector. A new test checks a cache of one directory gives the same sidecars as an unbounded one.
  • TestExternalSubtitleDirCacheReadsSubtitleFolders fails locally on macOS on main too: it writes Case/Movie.mkv and Case/movie.mkv, which are one file on a case-insensitive disk. CI runs on Linux.
  • CI: every Go job passes on a70018daa, including Go lint (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.

  • Before: upstream main 5159df6dc. After: 6ce2cab27; the commit after it, a70018daa, only removes the string sharing described below and changes neither of these components.
  • Workloads: group inference over 300,000 episode paths (1,500 shows of 10 seasons of 20 episodes, in walk order), alone and together with root inference with both results held, as a full scan holds them. The subtitle cache: 100,000 lookups over 5,000 season folders of 20 episodes, each with one sidecar.
  • Metrics: peak live heap (the runtime's /gc/heap/live:bytes, sampled every millisecond with GOGC=10), the heap still held after the call, bytes allocated.
  • Environment: Apple M5 Pro, Go 1.27.1 with GOMAXPROCS=6 and GOMEMLIMIT=3GiB.
Component Peak live heap, before Peak live heap, after Held afterwards Allocated, before / after
Group inference, 300,000 paths 315.6 MiB (315.0-317.0) 150.7 MiB (149.9-151.1) 70.1 MiB both 3,244 / 2,905 MiB
Root and group inference, results held 405.1 MiB (398.6-406.2) 246.8 MiB (238.1-246.8) 237.8 MiB both 5,165 / 4,826 MiB
Subtitle cache, 5,000 folders 18.4 MiB (17.8-18.6) 2.7 MiB (2.7-4.2) dropped after the scan 490 / 490 MiB

Time is unchanged (8.2 s and 8.1 s for group inference with GOGC=10). The snapshots and every file's assignment hash the same on both commits. The held 238 MiB is every file's root and group assignment, which #3958 stops holding for the whole root.

An earlier version also shared repeated strings between the scan-state rows of one load. It saved 51 MiB of the 541 MiB those rows hold for a 225,000-file series root, but on a 20,000-movie root it raised the peak by 3 MiB, and #3958 holds 5,000 rows at a time, so I took it out.

Evidence

Evidence: none, no user-visible change. Scans write the same catalog and find the same sidecars. The benchmark output is on the evidence page.

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

Risks

  • A directory evicted from the subtitle cache is read again. If it changed during the scan, two videos in it can see different listings, and a directory whose read failed is retried rather than remembered as failed. The old cache pinned one listing per directory for the whole scan.
  • 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) compared every field of the group, location and group-location snapshots with upstream's bucket code (duplicate paths, identity overrides, ambiguity, different key versions under one key, evidence JSON bytes, order), and checked the subtitle cache's locking and eviction and the scan-state string sharing. It found no difference in results. It found that the concurrent cache test never evicted, so a locking mistake in eviction would not show under the race detector; the test now evicts. It questioned whether the string sharing saved anything on a movie library; I measured it and removed it. It noted that an evicted directory is read again, which is under Risks. The tally now in this branch was then reviewed again, against upstream, as part of the review of perf(scanner): scan a library root in bounded batches #3958.

Note

Reduce per-file bookkeeping in scanner with tallies and an LRU subtitle directory cache

  • Rewrites group inference in group_inference.go to use a scanGroupInference accumulator. Group and location state is tallied per file instead of keeping a full list of per-file entries, and result() snapshots the accumulated tallies. The aggregateGroupState, aggregateLocationState, aggregateGroupOverrideSource, and aggregateGroupEvidence helpers are removed.
  • Batches of paths are added via scanGroupInference.add, which returns only that batch's assignments.
  • Replaces the unbounded subtitle directory listing map in subtitles.go with an LRU cache capped at 512 entries, evicting least-recently-used listings and re-reading evicted directories on later lookups.
  • Behavioral Change: group and location snapshots now derive ambiguity, override source, and evidence from the tallies, and locationTally.snapshot marks a location ambiguous when multiple groups have non-overridden files.

Macroscope summarized a70018d.

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.
…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.
@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: 1d916abf-b2be-4c39-9dcd-58dfce63b439
Commits

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

Files selected for processing: 3

  • internal/scanner/group_inference.go
  • internal/scanner/subtitles.go
  • internal/scanner/subtitles_test.go
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/L 200–499 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

Code Review Could Not Complete ⚠️

The review failed before suggestions could be generated.

Reason: Transient error reaching the provider (openai_compatible). Try again.

openai_compatible · gpt-6.1-terra · HTTP 502 · generalist

Provider said: Our servers are currently overloaded. Please try again later.

After fixing the issue, comment @kody review on this PR to re-run the review.

Silo Kody — review incomplete

This review did not finish. Resolve the error reported above, then retry with @kody start-review in a PR comment. Treat any comments already posted as a partial review.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the @kody start-review command at the root of your PR.

  • Validate Business Logic: Ask Kody to validate your code against business rules by adding a comment with the @kody -v business-logic command.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Access your configuration settings here.

​

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.
@silo-kody

silo-kody Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Code Review Could Not Complete ⚠️

The review failed before suggestions could be generated.

Reason: Transient error reaching the provider (openai_compatible). Try again.

openai_compatible · gpt-6.1-terra · HTTP 503 · generalist

Provider said: auth_unavailable: no auth available (providers=codex, model=gpt-6.1-terra; last upstream error: server_is_overloaded: Our servers are currently overloaded. Please try again later.)

After fixing the issue, comment @kody review on this PR to re-run the review.

Silo Kody — review incomplete

This review did not finish. Resolve the error reported above, then retry with @kody start-review in a PR comment. Treat any comments already posted as a partial review.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the @kody start-review command at the root of your PR.

  • Validate Business Logic: Ask Kody to validate your code against business rules by adding a comment with the @kody -v business-logic command.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Access your configuration settings here.

​

@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 ❌

@blurbery

Copy link
Copy Markdown
Contributor Author

@kody start-review

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

Labels

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