Repository navigation
fix(scanner): fix slow-scan regressions from #319 and #322 - #341
Conversation
Regression from #322 (trailers and extras for movies and series), which introduced the extrasDirKinds map. The extras directory classifier mapped the generic labels "other" and "others" to ExtraKindOther. These are not part of the Jellyfin/Plex extras folder convention the map claims to mirror, and they collide with real content-scope folder names. A library organized as "movies/other/<Title (year) {ids}>/<file>" tripped the depth-2 ancestor lookup in classifyExtraPath: every title two levels under the scope folder "other" was classified as an "other"-kind extra. Such files are partitioned out of primary root/group inference and matching, then deferred in processExtraFiles because their parent cannot resolve (they are the primary titles, not children of one). The result on one deployment was ~10k movies under a folder named "other" funneled through the slow extras path every scan (parent-unresolved deferrals at ~9.5/s), stalling the scan and freezing that scope for new/changed primary content. Remove "other"/"others" from extrasDirKinds. The ExtraKindOther kind stays reachable through genuine convention labels (extra/extras/interviews/ scenes/shorts). Add regression coverage asserting titles under a scope folder named other/others stay primary.
A pure identity/grouping change on an already-probed file — a root_assignment_changed or group_assignment_changed reason with nothing else — used to fall into the full update branch, which unconditionally ran ffprobe (probeFile) and then upserted every column, including probe columns, from the freshly built row. When a group-key or root scheme changes across the library (see #319), this reprobed nearly every file on the next scan: an incremental scan that normally takes ~1h ran 7h+ as a full-library ffprobe storm, even though the media bytes were untouched. Add a metadata-only update path in processFile: when identityOnlyUpdateReasons reports every reason is a root/group reassignment, rewrite just the derived identity columns via the new FileRepository.UpdateIdentity and skip ffprobe, OSHash, and marker fetch entirely. UpdateIdentity issues a targeted UPDATE of the root/group/identity and edition/presentation columns only, mirroring Upsert's column handling, and leaves probe data, file bytes/mtime/hash, subtitles, chapters, markers, and content/episode/extra linkage intact. The stored group key converges to the recomputed value on the next scan, so the file takes the unchanged fast-path thereafter — without a probe storm. The shared identity-column population is extracted into populateScanIdentity so the full path and the metadata-only path stay in lockstep. Verification: unit test for the identityOnlyUpdateReasons classifier; a DB-backed test (skipped without SILO_TEST_DATABASE_URL) asserting UpdateIdentity rewrites grouping while preserving probe/linkage columns; the UPDATE statement was also exercised against the live schema inside a rolled-back transaction.
📝 WalkthroughWalkthroughAdds a ChangesIdentity-only update fast path
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant Scanner as processFile
participant Predicate as identityOnlyUpdateReasons
participant Populate as populateScanIdentity
participant Repo as FileRepository
participant DB as media_files table
Scanner->>Predicate: evaluate updateReasons
alt identity-only change
Predicate-->>Scanner: true
Scanner->>Populate: populate derived identity fields
Populate-->>Scanner: updated MediaFile
Scanner->>Repo: UpdateIdentity(mf)
Repo->>DB: UPDATE identity/grouping columns
DB-->>Repo: RETURNING updated row
Repo-->>Scanner: updated MediaFile
else full change
Predicate-->>Scanner: false
Scanner->>Scanner: run full probe/refresh update path
end
Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dcbe8faee0
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| // no probe-column churn. This decouples identity/grouping-scheme changes | ||
| // from probing: a library-wide group-key scheme bump (see #319) converges | ||
| // the stored keys on the next scan without a full-library ffprobe storm. | ||
| if identityOnlyUpdateReasons(updateReasons) { |
There was a problem hiding this comment.
Avoid identity-only path for existing extras
When an existing row has extra_id set and the file is now treated as primary content, the only detected changes can be root_assignment_changed/group_assignment_changed (for example rows previously misclassified under other/others, which this patch now stops classifying as extras). This branch calls UpdateIdentity, which intentionally preserves extra linkage, so the row stays an extra and never becomes eligible for normal movie matching; the full Upsert path would clear extra_id. Gate this fast path on existing.ExtraID == "" or explicitly convert the linkage when an extra is reclassified as primary.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Valid — fixed in 51f3ddf. The fast path is now gated by identityOnlyFastPathEligible, which requires existing.ExtraID == "" (plus a present file_hash), so extra→primary reclassifications take the full upsert path that clears the extra linkage.
| presentation_part_total = $20, | ||
| multi_episode_start = $21, | ||
| multi_episode_end = $22, | ||
| updated_at = NOW() |
There was a problem hiding this comment.
Clear suppression during identity-only updates
If a previously unmatched file has match_suppressed_at set and later only its root/group identity changes, this update preserves the suppression flag. The subsequent enqueue is ineffective because the match backlog filters on mf.match_suppressed_at IS NULL, whereas the full Upsert path clears the flag; those files remain permanently skipped despite having new matching identity data.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Valid — fixed in 51f3ddf. UpdateIdentity now sets match_suppressed_at = NULL like Upsert does, matching the documented suppression contract ("until they are retried or seen by a new scan"); the DB-backed test asserts the clear.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
internal/scanner/scanner.go (1)
2031-2073: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider reusing
populateScanIdentityin the new-file path to eliminate duplication.The
actionNewpath (lines 2031–2073) inlines the same root/group/identity/edition/presentation population logic thatpopulateScanIdentitynow centralizes. Extracting this into the shared helper would reduce duplication and ensure all three paths (new, full update, identity-only) converge on identical field population.♻️ Proposed refactor
// Build the media file for upsert. mf := models.MediaFile{ MediaFolderID: folder.ID, FilePath: filePath, FileSize: fileSize, FileModifiedAt: &fileModifiedAt, FileHash: fileHash, } - if assignment.RootPath != "" { - mf.CanonicalRootPath = filepath.Clean(assignment.RootPath) - } else if root, ok := naming.DetectCanonicalRoot(filePath, folder.Type); ok { - mf.CanonicalRootPath = filepath.Clean(root.RootPath) - } - mf.ObservedRootPath = filepath.Clean(groupAssignment.ObservedRootPath) - mf.ContentGroupKey = groupAssignment.ContentGroupKey - mf.GroupKeyVersion = groupAssignment.GroupKeyVersion - mf.BaseTitle = groupAssignment.BaseTitle - mf.BaseYear = groupAssignment.BaseYear - mf.BaseType = groupAssignment.BaseType - mf.IdentityConfidence = groupAssignment.Confidence - mf.IdentityJSON = append([]byte(nil), groupAssignment.EvidenceJSON...) - if filenameHints := naming.ParseFilename(filePath, folder.Type); filenameHints != nil && - filenameHints.Type == "series" && filenameHints.EpisodeNum > 0 { - mf.SeasonNumber = filenameHints.SeasonNum - mf.EpisodeNumber = filenameHints.EpisodeNum - } - variantHints := naming.ParseVariantHints(filePath, folder.Type) - if existing, ok := existingByPath[filePath]; ok && existing != nil && existing.EditionSource == "import" && existing.EditionKey != "" { - variantHints = &naming.VariantHints{ - EditionRaw: existing.EditionRaw, - EditionKey: existing.EditionKey, - EditionSource: existing.EditionSource, - EditionConfidence: existing.EditionConfidence, - PresentationKind: existing.PresentationKind, - PresentationGroupKey: existing.PresentationGroupKey, - PresentationPartIndex: existing.PresentationPartIndex, - MultiEpisodeStart: existing.MultiEpisodeStart, - MultiEpisodeEnd: existing.MultiEpisodeEnd, - } - } - if variantHints != nil { - mf.EditionRaw = variantHints.EditionRaw - mf.EditionKey = variantHints.EditionKey - mf.EditionConfidence = variantHints.EditionConfidence - mf.EditionSource = variantHints.EditionSource - mf.PresentationKind = variantHints.PresentationKind - mf.PresentationGroupKey = variantHints.PresentationGroupKey - mf.PresentationPartIndex = variantHints.PresentationPartIndex - mf.MultiEpisodeStart = variantHints.MultiEpisodeStart - mf.MultiEpisodeEnd = variantHints.MultiEpisodeEnd - } + populateScanIdentity(&mf, filePath, folder.Type, assignment, groupAssignment, existingByPath[filePath])🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/scanner/scanner.go` around lines 2031 - 2073, The new-file path duplicates the same root/group/identity/edition/presentation population logic already centralized in populateScanIdentity. Update actionNew to call populateScanIdentity instead of inlining those assignments, reusing the existing helper with the same inputs so the new, full update, and identity-only paths all share one implementation and stay consistent.internal/scanner/update_identity_db_test.go (1)
82-88: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd assertions for the remaining rewritten identity columns.
The test verifies
ContentGroupKeyandObservedRootPathwere updated, but doesn't checkCanonicalRootPath,BaseTitle,BaseYear, orBaseType— all of whichUpdateIdentityrewrites. Adding these assertions would confirm the update actually persisted all identity fields, not just a subset.💚 Suggested additional assertions
// Identity/grouping columns rewritten. if updated.ContentGroupKey != "v1|movie|anchor|tvdb-1" { t.Errorf("content_group_key = %q, want anchored form", updated.ContentGroupKey) } if updated.ObservedRootPath != "/new/root" { t.Errorf("observed_root_path = %q, want /new/root", updated.ObservedRootPath) } + if updated.CanonicalRootPath != "/new/root" { + t.Errorf("canonical_root_path = %q, want /new/root", updated.CanonicalRootPath) + } + if updated.BaseTitle != "Movie" { + t.Errorf("base_title = %q, want Movie", updated.BaseTitle) + } + if updated.BaseYear != 2020 { + t.Errorf("base_year = %d, want 2020", updated.BaseYear) + } + if updated.BaseType != "movie" { + t.Errorf("base_type = %q, want movie", updated.BaseType) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/scanner/update_identity_db_test.go` around lines 82 - 88, The UpdateIdentity test only verifies ContentGroupKey and ObservedRootPath, but it should also assert the other rewritten identity fields are persisted. Update the test in update_identity_db_test.go to check CanonicalRootPath, BaseTitle, BaseYear, and BaseType on the updated record, using the same updated object already returned by the UpdateIdentity flow so the test covers all fields rewritten by UpdateIdentity.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/scanner/file_repo.go`:
- Around line 1041-1050: `UpdateIdentity` is overwriting
`presentation_part_total` with NULL during identity-only updates because
`populateScanIdentity` never sets it and `VariantHints` does not provide it.
Update the `populateScanIdentity`/`UpdateIdentity` flow in
`internal/scanner/file_repo.go` so `presentation_part_total` is preserved like
`season_number` and `episode_number`, either by using COALESCE against the
existing column or by ensuring the field is populated before the update.
---
Nitpick comments:
In `@internal/scanner/scanner.go`:
- Around line 2031-2073: The new-file path duplicates the same
root/group/identity/edition/presentation population logic already centralized in
populateScanIdentity. Update actionNew to call populateScanIdentity instead of
inlining those assignments, reusing the existing helper with the same inputs so
the new, full update, and identity-only paths all share one implementation and
stay consistent.
In `@internal/scanner/update_identity_db_test.go`:
- Around line 82-88: The UpdateIdentity test only verifies ContentGroupKey and
ObservedRootPath, but it should also assert the other rewritten identity fields
are persisted. Update the test in update_identity_db_test.go to check
CanonicalRootPath, BaseTitle, BaseYear, and BaseType on the updated record,
using the same updated object already returned by the UpdateIdentity flow so the
test covers all fields rewritten by UpdateIdentity.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d9b1bd22-51db-4beb-87e1-cf40038373ef
📒 Files selected for processing (5)
internal/scanner/extras_test.gointernal/scanner/file_repo.gointernal/scanner/scanner.gointernal/scanner/scanner_test.gointernal/scanner/update_identity_db_test.go
Review follow-ups for the two scan-regression fixes on this branch, addressing both Codex review comments on PR #341 plus adversarial-review findings. Identity fast path (processFile/UpdateIdentity): - Gate the metadata-only path on existing.ExtraID == "": a row still linked as an extra reaching processFile is being reclassified as primary, and only the full upsert clears extra linkage; UpdateIdentity would have frozen it out of matching forever (match backlog filters extra_id IS NULL). - Gate on existing.FileHash != "": the full path backfills the OSHash and fetches hash-keyed S3 intro/credits markers, which no later scan reason would repair; hash-less legacy rows now take the full path once instead of silently losing that repair channel. file_hash is added to the scan-state row shape to support the gate. - Clear match_suppressed_at like every other scan write, so files with fresh identity re-enter the match backlog (suppression is documented as lasting "until retried or seen by a new scan"). - Write media_folder_id, mirroring Upsert's ON CONFLICT reassignment. - Return ErrFileNotFound when the row vanished mid-scan (concurrent delete) and fall through to the full upsert path instead of surfacing a per-file scan error. - Return only the row id instead of RETURNING all ~75 columns: the fast path fires once per file during library-wide grouping migrations, and dragging the track/chapter JSONB payloads along for a million rows dominated the cost of the path built to be cheap. - Extract identityColumnDefaults shared by Upsert and UpdateIdentity so the defaulting rules cannot drift, and drop the no-op editionConfidence indirection copied between them. - Use populateScanIdentity in the new-file insert path too; it still carried a verbatim copy of the extracted block (with a provably dead existingByPath lookup). Extras classification: - Restore "other" to extrasDirKinds: it is part of both the documented Jellyfin and Plex extras-folder conventions (the removed-label fix overshot and broke "movies/<Title>/Other/<file>" libraries, ingesting their extras as bogus primary titles). "others" stays removed - it is in neither convention. - Replace label removal with the structural guard the PR had deferred: classifyExtraPath now rejects a supplemental-named directory sitting at library-scope depth (the dir, any supplemental ancestor, or the first non-supplemental ancestor is a configured library root). This fixes the original "movies/other/<Title>" defer-storm generically, covering every convention label (shorts, scenes, extras, ...) used as a content-scope folder. - Scope extras parent binding by folder.Paths instead of the walk roots, so a subtree scan targeting a single movie folder still binds that movie's own extras instead of deferring them. Tests: eligibility-gate unit tests, scope-guard classifier cases (convention Other/ inside a title binds; scope-level other/shorts stay primary), and the DB-backed UpdateIdentity test now also covers folder moves, suppression clearing, and ErrFileNotFound. Full scanner suite ran green against a migrated scratch PostgreSQL 17 container.
Replace the ancestor-walking supplementalDirAtScopeDepth loop with the plain rule it was approximating: a convention-named directory counts as an extras dir only when it sits inside a title folder — it must not be a configured library root or directly under one. Same outcome for the layouts that matter (movies/other/<Title> stays primary, <Title>/Other classifies), less machinery.
|
Re the CodeRabbit nitpicks (review body, no inline thread to reply to):
The |
Code reviewFound 1 issue:
silo-server/internal/scanner/extras.go Lines 51 to 56 in 0ac53e9 If two-level nesting is an intentional scope cut, consider restoring the deleted test with the new expected value so the behavior change is recorded; otherwise restoring the walk-up-to-root loop closes the gap. 🤖 Generated with Claude Code - If this code review was useful, please react with 👍. Otherwise, react with 👎. |
The title-folder rule from c1828d2 anchored on library roots, so it missed both directions: chained convention dirs at the root ("movies/extras/behind the scenes/clip.mkv") classified as extras with an unresolvable parent (deferred forever), and category folders nested below the root ("movies/4K/other/<Title>/") still misclassified their titles. Replace the root-distance heuristic with the structural property that actually distinguishes the two cases: a convention-named directory only counts as an extras dir when its owner (first non-supplemental ancestor) is a title folder — a directory that holds media of its own. The new extrasClassifier derives that from the scan's walked path list (no extra I/O): movie folders must hold a file directly beside the extras dir; series folders may hold episodes one level down in season folders (media hiding inside a folder's own extras dirs doesn't count). Library roots never qualify. Watch-event scans, which have no walked list, probe ownership with bounded os.ReadDir instead. This handles title folders at any depth below the root and keeps scope/category folders primary at any depth, with two known edges: a title folder holding only extras (its media file missing) stays primary until the file appears, and a mixed dir holding both loose media and a category folder degrades to deferral, never wrong linkage. resolveExtraParent's inline supplemental-chain walk is extracted into the shared firstNonSupplementalAncestor.
|
Thanks. Pushed a fix |
* fix(scanner): stop classifying "other" content folders as extras Regression from #322 (trailers and extras for movies and series), which introduced the extrasDirKinds map. The extras directory classifier mapped the generic labels "other" and "others" to ExtraKindOther. These are not part of the Jellyfin/Plex extras folder convention the map claims to mirror, and they collide with real content-scope folder names. A library organized as "movies/other/<Title (year) {ids}>/<file>" tripped the depth-2 ancestor lookup in classifyExtraPath: every title two levels under the scope folder "other" was classified as an "other"-kind extra. Such files are partitioned out of primary root/group inference and matching, then deferred in processExtraFiles because their parent cannot resolve (they are the primary titles, not children of one). The result on one deployment was ~10k movies under a folder named "other" funneled through the slow extras path every scan (parent-unresolved deferrals at ~9.5/s), stalling the scan and freezing that scope for new/changed primary content. Remove "other"/"others" from extrasDirKinds. The ExtraKindOther kind stays reachable through genuine convention labels (extra/extras/interviews/ scenes/shorts). Add regression coverage asserting titles under a scope folder named other/others stay primary. * perf(scanner): rewrite identity-only changes without re-probing A pure identity/grouping change on an already-probed file — a root_assignment_changed or group_assignment_changed reason with nothing else — used to fall into the full update branch, which unconditionally ran ffprobe (probeFile) and then upserted every column, including probe columns, from the freshly built row. When a group-key or root scheme changes across the library (see #319), this reprobed nearly every file on the next scan: an incremental scan that normally takes ~1h ran 7h+ as a full-library ffprobe storm, even though the media bytes were untouched. Add a metadata-only update path in processFile: when identityOnlyUpdateReasons reports every reason is a root/group reassignment, rewrite just the derived identity columns via the new FileRepository.UpdateIdentity and skip ffprobe, OSHash, and marker fetch entirely. UpdateIdentity issues a targeted UPDATE of the root/group/identity and edition/presentation columns only, mirroring Upsert's column handling, and leaves probe data, file bytes/mtime/hash, subtitles, chapters, markers, and content/episode/extra linkage intact. The stored group key converges to the recomputed value on the next scan, so the file takes the unchanged fast-path thereafter — without a probe storm. The shared identity-column population is extracted into populateScanIdentity so the full path and the metadata-only path stay in lockstep. Verification: unit test for the identityOnlyUpdateReasons classifier; a DB-backed test (skipped without SILO_TEST_DATABASE_URL) asserting UpdateIdentity rewrites grouping while preserving probe/linkage columns; the UPDATE statement was also exercised against the live schema inside a rolled-back transaction. * fix(scanner): harden identity fast path and extras scope classification Review follow-ups for the two scan-regression fixes on this branch, addressing both Codex review comments on PR #341 plus adversarial-review findings. Identity fast path (processFile/UpdateIdentity): - Gate the metadata-only path on existing.ExtraID == "": a row still linked as an extra reaching processFile is being reclassified as primary, and only the full upsert clears extra linkage; UpdateIdentity would have frozen it out of matching forever (match backlog filters extra_id IS NULL). - Gate on existing.FileHash != "": the full path backfills the OSHash and fetches hash-keyed S3 intro/credits markers, which no later scan reason would repair; hash-less legacy rows now take the full path once instead of silently losing that repair channel. file_hash is added to the scan-state row shape to support the gate. - Clear match_suppressed_at like every other scan write, so files with fresh identity re-enter the match backlog (suppression is documented as lasting "until retried or seen by a new scan"). - Write media_folder_id, mirroring Upsert's ON CONFLICT reassignment. - Return ErrFileNotFound when the row vanished mid-scan (concurrent delete) and fall through to the full upsert path instead of surfacing a per-file scan error. - Return only the row id instead of RETURNING all ~75 columns: the fast path fires once per file during library-wide grouping migrations, and dragging the track/chapter JSONB payloads along for a million rows dominated the cost of the path built to be cheap. - Extract identityColumnDefaults shared by Upsert and UpdateIdentity so the defaulting rules cannot drift, and drop the no-op editionConfidence indirection copied between them. - Use populateScanIdentity in the new-file insert path too; it still carried a verbatim copy of the extracted block (with a provably dead existingByPath lookup). Extras classification: - Restore "other" to extrasDirKinds: it is part of both the documented Jellyfin and Plex extras-folder conventions (the removed-label fix overshot and broke "movies/<Title>/Other/<file>" libraries, ingesting their extras as bogus primary titles). "others" stays removed - it is in neither convention. - Replace label removal with the structural guard the PR had deferred: classifyExtraPath now rejects a supplemental-named directory sitting at library-scope depth (the dir, any supplemental ancestor, or the first non-supplemental ancestor is a configured library root). This fixes the original "movies/other/<Title>" defer-storm generically, covering every convention label (shorts, scenes, extras, ...) used as a content-scope folder. - Scope extras parent binding by folder.Paths instead of the walk roots, so a subtree scan targeting a single movie folder still binds that movie's own extras instead of deferring them. Tests: eligibility-gate unit tests, scope-guard classifier cases (convention Other/ inside a title binds; scope-level other/shorts stay primary), and the DB-backed UpdateIdentity test now also covers folder moves, suppression clearing, and ErrFileNotFound. Full scanner suite ran green against a migrated scratch PostgreSQL 17 container. * refactor(scanner): simplify extras scope guard to title-folder rule Replace the ancestor-walking supplementalDirAtScopeDepth loop with the plain rule it was approximating: a convention-named directory counts as an extras dir only when it sits inside a title folder — it must not be a configured library root or directly under one. Same outcome for the layouts that matter (movies/other/<Title> stays primary, <Title>/Other classifies), less machinery. * test(scanner): assert all rewritten identity columns in UpdateIdentity test * fix(scanner): make extras scope classification structure-aware The title-folder rule from 53632022 anchored on library roots, so it missed both directions: chained convention dirs at the root ("movies/extras/behind the scenes/clip.mkv") classified as extras with an unresolvable parent (deferred forever), and category folders nested below the root ("movies/4K/other/<Title>/") still misclassified their titles. Replace the root-distance heuristic with the structural property that actually distinguishes the two cases: a convention-named directory only counts as an extras dir when its owner (first non-supplemental ancestor) is a title folder — a directory that holds media of its own. The new extrasClassifier derives that from the scan's walked path list (no extra I/O): movie folders must hold a file directly beside the extras dir; series folders may hold episodes one level down in season folders (media hiding inside a folder's own extras dirs doesn't count). Library roots never qualify. Watch-event scans, which have no walked list, probe ownership with bounded os.ReadDir instead. This handles title folders at any depth below the root and keeps scope/category folders primary at any depth, with two known edges: a title folder holding only extras (its media file missing) stays primary until the file appears, and a mixed dir holding both loose media and a category folder degrades to deferral, never wrong linkage. resolveExtraParent's inline supplemental-chain walk is extracted into the shared firstNonSupplementalAncestor.
Three commits: one classifier fix, one probe/identity decoupling, and one review-hardening pass over both. The first two surfaced as the same operator-visible symptom — "the scan is slow" — but have independent root causes.
Problem
A whole category of movies silently stopped importing, and scans dragged on for over an hour. A library scan that used to finish in minutes was instead taking ~90 minutes. During it, the progress bar sat stuck on "Reconciling scan state" for many minutes with no visible movement. Separately, a large shelf of titles filed under a generic catch-all category folder (a folder literally named "other") quietly stopped appearing and stopped picking up new/changed files. No error surfaced anywhere — from an operator's view the titles were simply frozen and the scan looked hung.
A grouping-scheme change re-analyzed nearly the entire library. After a recent release, the first full scan re-probed essentially every file. An incremental scan that normally takes about an hour ran 7+ hours. Playback and streaming were unaffected — only scans were slow — but under the hood roughly 1.1 mil files were re-analyzed from scratch even though none of the underlying media had changed. On the next scan it recurred for any library seeing the new scheme for the first time.
Solution
fix(scanner): stop classifying "other" content folders as extras
Regression from #322 (trailers/extras for movies and series), which introduced the
extrasDirKindsmap.The extras classifier mapped the labels
other/othersinto the extras-kind vocabulary. A library organized asmovies/other/<Title (year) {ids}>/<file>tripped the depth-2 ancestor lookup inclassifyExtraPath(internal/scanner/extras.go): every title two levels under a scope folder named "other" was classified as an "other"-kind extra. Those files are partitioned out of primary root/group inference and matching, then deferred inprocessExtraFilesbecause their parent can never resolve — they are the primary titles, not children of one. Result: ~10k titles funneled through the slow extras path on every scan (parent-unresolved deferrals), stalling the scan and freezing that scope for new/changed primary content.This commit fixed it by removing
other/othersfromextrasDirKinds. Review follow-up: that overshot —other(singular) is part of both the documented Jellyfin and Plex extras-folder conventions, so removing the label brokemovies/<Title>/Other/<file>libraries (their extras would ingest as bogus primary titles). The third commit restoresotherand replaces label removal with the structural guard originally deferred as follow-up work;others(plural) is in neither convention and stays removed.perf(scanner): rewrite identity-only changes without re-probing
Regression from #319 (anchor group keys on provider tags), which changed how the content group key is derived without decoupling identity from probing.
A pure identity/grouping change on an already-probed file — a
root_assignment_changedorgroup_assignment_changedreason with nothing else — fell into the full update branch, which unconditionally ranprobeFileand then upserted every column (including probe columns) from the freshly built row. When a group-key or root scheme changes library-wide, this re-probed nearly every file on the next scan even though the media bytes were untouched.Fix: add a metadata-only update path in
processFile(internal/scanner/scanner.go). When every update reason is a root/group reassignment, the scanner rewrites just the derived identity columns via the newFileRepository.UpdateIdentity(internal/scanner/file_repo.go) and skips ffprobe, OSHash, and marker fetch entirely. The stored key converges to the recomputed value on the next scan, so the file takes the unchanged fast-path thereafter — no probe storm. The shared identity-column population is extracted intopopulateScanIdentityso the full path and the metadata-only path stay in lockstep.fix(scanner): harden identity fast path and extras scope classification
Review-driven hardening addressing both Codex inline comments plus adversarial-review findings.
Identity fast path:
existing.ExtraID == ""(Codex P1): a row still linked as an extra reachingprocessFileis being reclassified as primary; only the full upsert clears extra linkage, andUpdateIdentitywould have frozen it out of matching forever (the match backlog filtersextra_id IS NULL).existing.FileHash != "": the full path backfills the OSHash and fetches hash-keyed S3 intro/credits markers, which no later scan reason would repair; hash-less legacy rows take the full path once instead of silently losing that repair channel (file_hashadded to the scan-state row shape).UpdateIdentityclearsmatch_suppressed_atlike every other scan write (Codex P2), so files with fresh identity re-enter the match backlog.UpdateIdentitywritesmedia_folder_id, mirroringUpsert's ON CONFLICT reassignment.ErrFileNotFoundand falls through to the full upsert path (re-ingested in the same scan) instead of surfacing a per-file scan error.UpdateIdentityreturns only the row id instead ofRETURNINGall ~75 columns — at library-migration scale the track/chapter JSONB payloads dominated the cost of the path built to be cheap.identityColumnDefaultsextracted soUpsert/UpdateIdentitydefaulting cannot drift; the new-file insert path now also callspopulateScanIdentityinstead of carrying a verbatim copy.Extras classification:
otherrestored toextrasDirKinds; classification (extrasClassifier,internal/scanner/extras.go) now applies a structural rule: a convention-named directory counts as an extras dir only when its owner (first non-supplemental ancestor) is a title folder — a directory holding media of its own (the movie file beside the extras dir, or episodes in season folders), derived from the scan's walked path list with no extra I/O; watch-event scans probe with a boundedos.ReadDir. Library roots never qualify. This fixes the originalmovies/other/<Title>defer-storm generically for every convention label (shorts,scenes,extras, ...) used as a content-scope folder, at any nesting depth (movies/4K/other/<Title>/included), while title folders own their extras at any depth.folder.Pathsinstead of the walk roots, so a subtree scan targeting a single movie folder still binds that movie's own extras instead of deferring them.Risk / follow-ups
UpdateIdentitymirrorsUpsert's column assignments by hand; shared field population (populateScanIdentity) and defaults (identityColumnDefaults) plus tests mitigate drift, but the SQL column lists remain two sites.media_fileslinkage but the orphanedmedia_extrasentity row lingers; a reaper/cleanup is follow-up work.movies/extras/clip.mkv) now ingest as primary titles instead of being invisibly deferred forever; visible-but-unmatched was judged better than silent.Verification
go build ./...,go vet ./internal/scanner/, andgofmtclean; fullgo test ./internal/scanner/green, including the DB-backed tests against a freshly migrated scratch PostgreSQL 17 container.identityOnlyUpdateReasonsclassifier and the newidentityOnlyFastPathEligiblegates (former-extra and hash-less rows fall back to the full path).movies/<Title>/Other/<file>classifies as an extra;movies/other/<Title>/<file>,movies/shorts/<Title>/<file>, and loose scope-level files stay primary; series season-0 behavior preserved.UpdateIdentitytest asserts identity columns rewrite while probe/linkage columns are preserved, plus folder moves, suppression clearing, andErrFileNotFoundon vanished rows.processed extrasreporteddeferred=0(previously ~5.7k deferrals); the ~10k previously-frozen "other" titles ingest as primary; only ~180 files were re-probed this scan (versus the ~1.1 mil one-time storm); noERROR/FATALin logs.AI-use disclosure
Investigation, code changes, tests, and this description were prepared with AI assistance (Claude Code) and reviewed before submission.