Skip to content

fix(scanner): check a dropped mount's root without loading its files - #3955

Merged
Quick104 merged 6 commits into
Silo-Server:mainfrom
blurbery:perf/scanner-empty-root-exists
Nov 14, 2026
Merged

Quick104 merged 6 commits into
Silo-Server:mainfrom
blurbery:perf/scanner-empty-root-exists

Conversation

@blurbery

@blurbery blurbery commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none changed. The query also serves the empty-root check of targeted scans (#1231 C1, passed) and matches the same files. Full library scans fall under #1250 C1, which has not been run yet.

When a drive drops out, its mountpoint is usually still there as an empty directory. A full library scan protects that case: a reachable but empty configured root that still has cataloged files is treated as a suspect empty root and nothing under it is marked missing. To decide whether the catalog has files under the root, the scan loaded every file row under it in full, with all track, chapter and marker JSON, only to test whether the list was empty. It did that on every scan for as long as the drive stayed missing, so the scans that run while a drive is down are the ones that allocate the most.

Measured on a synthetic 225,000-file series root with rows sized like my real catalog, that load peaked at 1.6 GB of live Go heap, allocated 4.7 GB and took 6.2 s, for each empty root on each scan. The existence check allocates nothing measurable.

The scan now asks the existing ListRootsWithCatalogedFiles query, once for all empty roots, which only checks whether a row exists.

That query had its own cost: it matched descendants with a LIKE pattern taken from the unnested roots, ORed with the exact match, and neither can be an index condition. A root with no cataloged files read every file row of the folder. It now matches descendants by bytewise range in an EXISTS of its own, so each root is an index-only range probe. Targeted scans already used this query for their empty-root check and get the same improvement.

I've titled this fix rather than perf. The extra work only happens while a drive is missing, and it is a full decode of every row of that root on top of what the scan already holds, which is the situation most likely to push a server over its memory limit.

Approach

  • scanFolderByRoots collects the reachable empty roots and passes them to ListRootsWithCatalogedFiles in one call, instead of calling GetByFolderAndPathPrefix per root.
  • ListRootsWithCatalogedFiles passes each root's bounds from pathscope.DescendantRange (the bound calculation RangeCoverageClauses already did, pulled out) and checks descendants with ~>=~/~<~ in one EXISTS and the exact path in another. The matched files are the same: files present or marked missing, at or under the root, never a sibling that only shares a string prefix. Roots still come back in input order.

Validation

  • go vet ./internal/scanner/: pass.
  • DB tests against a migrated local PostgreSQL 18.6: pass. Both new ones are in scripts/ci/db-contracts.txt.
    • ListRootsWithCatalogedFiles gets a table test: a root with present files, one with only missing files, one with none, a sibling that shares a prefix (/lib/movies beside /lib/movies2, /lib/f beside /lib/file.mkv), a root with % and _ in its name, a file that is itself the root, a root with a trailing slash, and input order.
    • A full scan of a two-root library with one root emptied keeps that root's files, reports it in SuspectEmptyRoots, and still marks a file removed under the other root missing. This pins the dropped-mount behaviour end to end. It would also pass on main: the post-walk re-probe protects the same root, so it guards the behaviour rather than the query.
  • EXPLAIN ANALYZE on 200,000 rows under a generic plan: an empty root with no rows went from a sequential scan of the folder (200,000 rows filtered, 22.9 ms warm) to index-only range probes (0.37 ms).
  • Review commit c9b13a989c adds TestListRootsWithCatalogedFilesUsesPathRangeUnderGenericPlanDB to scripts/ci/db-pins.txt. It checks that the query's generic plan reads media_files only through an index condition bounding file_path, and it fails when the old LIKE query is restored. The table test now uses a per-run path prefix.
  • CI: every Go job passes on 13db7efd3, including Go lint and Go DB pins, which ran both new DB tests (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, which calls GetByFolderAndPathPrefix for each reachable empty root. After: 13db7efd3, which calls ListRootsWithCatalogedFiles once. Both calls ran on the same data.
  • Workload: one series folder of 225,000 episodes (1,125 shows of 10 seasons of 20 episodes, about the size of my largest root). Each row carries track, subtitle, chapter and identity JSON sized to the averages of a sample of my real catalog (about 2.6 KB a row stored).
  • Metrics: peak live heap (the runtime's /gc/heap/live:bytes, sampled every millisecond with GOGC=10), bytes allocated, wall time.
  • Environment: Apple M5 Pro, PostgreSQL 18.6 on the same machine over loopback TCP, Go 1.27.1 with GOMAXPROCS=6 and GOMEMLIMIT=3GiB.
Empty-root check on a 225,000-file root Peak live heap Allocated Time
Before: load every row 1,606 MiB (1,591-1,613) 4,691 MiB 6.2 s
After: ListRootsWithCatalogedFiles 0.0 MiB 0.0 MiB under 0.05 s

The query plan numbers for a root with no rows are under Validation. On a server the before cost is paid only while a configured root is empty; I have no server reading for it, because none of my drives dropped during the measurements.

Evidence

Evidence: none, no user-visible change. The scan protects and reconciles the same files. The benchmark output is on the evidence page.

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

Risks

  • The empty-root error message no longer names the root, since one query covers them all.
  • 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, claude-sonnet-5-5 (the end-to-end empty-root test)
  • Involvement: AI-assisted
  • Adversarial review: A separate Claude Code review agent (claude-fable-5-2) read the diff against upstream main for equivalence with the old check (escaping, root /, trailing slashes, missing rows, order, nil results), query cost and test quality. It found two things, both fixed here. The end-to-end test still passed with the changed line removed, because the post-walk re-probe protects the same root, so the query now has its own table test. And the EXISTS query could not use the path index, so a root with no rows read the whole folder; I confirmed that with EXPLAIN ANALYZE and switched it to range probes. It also asked for a less dramatic code comment, which I changed.
  • Maintainer review: Claude Code (claude-opus-5-5) reviewed the branch with read-only Claude subagents (claude-opus-5-5, claude-sonnet-5-5) and one Codex round (gpt-6.1-sol), and pushed c9b13a989c (the plan pin, the per-run test paths, and a comment fix).

Note

Fix dropped-root detection in Scanner.scanFolderByRoots to use one query without loading files

  • Empty-root detection in scanFolderByRoots now collects all reachable empty roots and checks them with a single ListRootsWithCatalogedFiles call, instead of one GetByFolderAndPathPrefix per root that loaded full file rows.
  • The new listRootsWithCatalogedFilesSQL query in file_repo.go matches cataloged files with bytewise lower/upper bounds from pathscope.DescendantRange plus an exact-path EXISTS clause, and returns roots in input order.
  • Adds database tests for empty-root scanning and root matching in dead_root_test.go, and a shared requirePathRangeIndexed helper in path_prefix_plan_db_test.go that asserts the generic plan uses a path-range index instead of scanning media_files.
  • New tests are registered in db-contracts.txt and db-pins.txt.
  • Behavioral Change: the query no longer filters out missing rows, so roots with only missing cataloged files still count as having cataloged files.

Macroscope summarized b14d02f.

…them

A reachable but empty root (the bare mountpoint of a dropped drive) is
protected when the catalog still holds files under it. The full scan
decided that by loading every file row under the root, with all track,
chapter and marker JSON, only to test the length. For a large TV root
that is gigabytes of decoded rows on every scan for as long as the drive
stays missing. Ask the existing EXISTS query instead, once for all empty
roots.
A full scan with one configured root emptied keeps that root's cataloged
files, reports it in SuspectEmptyRoots, and still scans the other root.
ListRootsWithCatalogedFiles matched descendants with a LIKE pattern taken
from the unnested roots, ORed with the exact match. Neither can become an
index condition, so a root with no cataloged files read every file row of
the folder. The descendants are now matched by bytewise range in an
EXISTS of their own, which is an index-only range probe, and the exact
match has its own EXISTS. The matched files are the same.

A table test pins which roots count: files present or missing, at or
under the root, never a sibling that shares a string prefix.
@coderabbitai

coderabbitai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Caution

Review failed

The pull request is closed.

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

This comment has been minimized.

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

@blurbery

Copy link
Copy Markdown
Contributor Author

@kody start-review

@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 bug Something isn't working 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.

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

Three small findings, none of them in the scan logic. The rewritten query matches the same roots as the old LIKE for every root shape I checked. On a 200,000-row folder under a generic plan it made two index-only probes (0.12 ms), where the old query read the whole folder sequentially (66 ms). I'm fixing all three in a commit on this branch, so there's no need to change anything yourself.

Comment thread internal/scanner/file_repo.go Resolved
Comment thread internal/scanner/dead_root_test.go Resolved
Comment thread internal/pathscope/pathscope.go Resolved
Both tests this branch adds also pass on main, so nothing failed if the
query went back to a LIKE or an OR inside one EXISTS. Pin its generic
plan beside the existing folderPathPrefixQuery pin, sharing that test's
EXPLAIN helper. The SQL moves into a package constant so the pin can
plan it.

Give TestListRootsWithCatalogedFilesDB a per-run path prefix, since
media_files.file_path is unique across folders, and add a root with a
LIKE wildcard and no files of its own. Correct DescendantRange's comment
for the filesystem root.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 14, 2026
@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

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

Review summary

Reviewed head: c9b13a989c (the author's 13db7efd3 plus one review commit). The branch merges cleanly into current main, which still loads every file row under each empty root in scanFolderByRoots, so this PR still has a job to do.

What I checked. The rewritten ListRootsWithCatalogedFiles returns the same roots as the old LIKE match for every root shape its callers can pass: /, a trailing slash, an uncleaned root, %, _ and backslash in names, multibyte paths, and a file that is the root itself. Order, missing-row inclusion and the error path are unchanged, and so are the results for all three callers (scanFolderByRoots, suspectEmptyRoots, and the nested-root re-probe). On a migrated PostgreSQL 18 with 200,000 rows in one folder, under a forced generic plan, the new query made two index-only probes on idx_media_files_folder_file_path_pattern (0.12 ms). The old query read the folder sequentially (66 ms). Both returned the same roots.

Addressed in c9b13a989c (the three threads above):

  • Low: no test pinned the index plan. Both tests this PR adds also pass on main, which fits a change meant to keep behavior the same, but it meant a return to the old query would fail nothing. TestListRootsWithCatalogedFilesUsesPathRangeUnderGenericPlanDB (listed in db-pins.txt) now pins it. It passes on this branch and fails with the old LIKE query restored.
  • Low: TestListRootsWithCatalogedFilesDB used fixed paths on a column that is unique across folders. It now uses a per-run prefix and also covers a root with a LIKE wildcard and no files of its own.
  • Nit: DescendantRange's comment was wrong for /.

Left for maintainers. Nothing blocks this PR. As context, the beta book scanners still load full rows for the same yes/no question in one place (ebook_scan.go, the empty-root confirmation). Books stay as they are until the Books effort, so I left it.

Cross-provider review. One read-only round by Codex (gpt-6.1-sol) on 13db7efd3 found the fixed-path collision, which is fixed above, and no correctness defects.

Validated features. #1231 C1 (targeted scans, passed) uses the rewritten query through the targeted scan's empty-root check. The matched files are the same, so its result should hold. Full library scans are covered by cases that haven't been run yet: #1250 C1 (series), #197 (movies), #1251 C3, and the beta #1254 C1 and #1255 C3. Whoever runs them should use a build that includes this change. No passed case changes.

User manual: unaffected. This is an internal change, and the scan protects the same files.
Other clients: N/A, no client-visible change.

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

Fit: it fixes real memory and time costs in the existing dropped-mount protection, which are paid exactly when a drive is missing. It reuses the query two other code paths already use and adds no setting or surface. Readiness: the query matches the same files, the plan change is shown live and now pinned by a test that fails on the old query, and the DB tests pass on a freshly migrated database.

Quick104 and others added 2 commits November 14, 2026 15:03
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]>
@Quick104
Quick104 merged commit 19c22f8 into Silo-Server:main Nov 14, 2026
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working 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