Skip to content

fix(scanner): fix slow-scan regressions from #319 and #322 - #341

Merged
Quick104 merged 6 commits into
mainfrom
fix/scanner-scan-regressions-319-322
Jul 8, 2026
Merged

Quick104 merged 6 commits into
mainfrom
fix/scanner-scan-regressions-319-322

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

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 extrasDirKinds map.

The extras classifier mapped the labels other/others into the extras-kind vocabulary. A library organized as movies/other/<Title (year) {ids}>/<file> tripped the depth-2 ancestor lookup in classifyExtraPath (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 in processExtraFiles because 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/others from extrasDirKinds. Review follow-up: that overshot — other (singular) is part of both the documented Jellyfin and Plex extras-folder conventions, so removing the label broke movies/<Title>/Other/<file> libraries (their extras would ingest as bogus primary titles). The third commit restores other and 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_changed or group_assignment_changed reason with nothing else — fell into the full update branch, which unconditionally ran probeFile and 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 new FileRepository.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 into populateScanIdentity so 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:

  • Gate on existing.ExtraID == "" (Codex P1): a row still linked as an extra reaching processFile is being reclassified as primary; only the full upsert clears extra linkage, and UpdateIdentity would have frozen it out of matching forever (the 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 take the full path once instead of silently losing that repair channel (file_hash added to the scan-state row shape).
  • UpdateIdentity clears match_suppressed_at like every other scan write (Codex P2), so files with fresh identity re-enter the match backlog.
  • UpdateIdentity writes media_folder_id, mirroring Upsert's ON CONFLICT reassignment.
  • A row deleted mid-scan now returns ErrFileNotFound and falls through to the full upsert path (re-ingested in the same scan) instead of surfacing a per-file scan error.
  • UpdateIdentity returns only the row id instead of RETURNING all ~75 columns — at library-migration scale the track/chapter JSONB payloads dominated the cost of the path built to be cheap.
  • Shared identityColumnDefaults extracted so Upsert/UpdateIdentity defaulting cannot drift; the new-file insert path now also calls populateScanIdentity instead of carrying a verbatim copy.

Extras classification:

  • other restored to extrasDirKinds; 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 bounded os.ReadDir. Library roots never qualify. This fixes the original movies/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.
  • Extras parent binding is now scoped 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.

Risk / follow-ups

  • UpdateIdentity mirrors Upsert's column assignments by hand; shared field population (populateScanIdentity) and defaults (identityColumnDefaults) plus tests mitigate drift, but the SQL column lists remain two sites.
  • When a formerly-extra file is reclassified as primary, the full upsert clears the media_files linkage but the orphaned media_extras entity row lingers; a reaper/cleanup is follow-up work.
  • The metadata-only path is intentionally scoped to pure root/group reasons. Subtitle-sidecar-only changes still take the full (re-probing) path — unchanged behavior, not a regression.
  • Identity rewrites are still one UPDATE per file through the worker pool; batching them (pgx.Batch / set-based UPDATE) is a possible further optimization for library-wide migrations.
  • Update reasons remain stringly-typed; typed reason constants co-located with their producer would make the identity-only allowlist harder to desynchronize.
  • Loose files sitting directly under a scope-level convention folder (e.g. 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/, and gofmt clean; full go test ./internal/scanner/ green, including the DB-backed tests against a freshly migrated scratch PostgreSQL 17 container.
  • Unit tests for the identityOnlyUpdateReasons classifier and the new identityOnlyFastPathEligible gates (former-extra and hash-less rows fall back to the full path).
  • Classifier tests for the scope guard: 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.
  • DB-backed UpdateIdentity test asserts identity columns rewrite while probe/linkage columns are preserved, plus folder moves, suppression clearing, and ErrFileNotFound on vanished rows.
  • Jellyfin and Plex extras-folder documentation checked directly: both lists include "Other"; neither includes "Others".
  • Deployed (first two commits) and ran a full movies-library scan end to end: completed in 8 minutes (the regression took ~91 minutes); processed extras reported deferred=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); no ERROR/FATAL in logs.

AI-use disclosure

Investigation, code changes, tests, and this description were prepared with AI assistance (Claude Code) and reviewed before submission.

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

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a FileRepository.UpdateIdentity method for metadata-only DB updates of identity/grouping fields, a scanner fast path (identityOnlyUpdateReasons) that invokes it instead of full probe/refresh when only identity reclassification is needed, a shared populateScanIdentity helper, an extras-folder classification fix removing generic other/others labels, and new unit/integration tests.

Changes

Identity-only update fast path

Layer / File(s) Summary
UpdateIdentity repository method
internal/scanner/file_repo.go
New FileRepository.UpdateIdentity performs a targeted UPDATE on identity/grouping/edition columns with computed defaults, COALESCE-preserved season/episode values, and returns the updated row via RETURNING.
Scanner fast path and helper
internal/scanner/scanner.go
Adds identityOnlyUpdateReasons predicate and populateScanIdentity helper; processFile short-circuits to call UpdateIdentity when reasons are identity-only; extrasDirKinds no longer treats other/others as extra folders.
Unit and integration tests
internal/scanner/extras_test.go, internal/scanner/scanner_test.go, internal/scanner/update_identity_db_test.go
Adds negative extras-classification cases, table-driven tests for identityOnlyUpdateReasons, and a DB-backed test verifying UpdateIdentity preserves probe data while rewriting identity columns.

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
Loading

Possibly related PRs

  • Silo-Server/silo-server#319: Both modify scanner identity/grouping field handling; this PR adds the identity-only DB update fast path while #319 changes how ContentGroupKey/identity is inferred.
  • Silo-Server/silo-server#322: Both touch extras directory classification logic in the scanner.

Suggested labels: v1

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the PR’s main goal: fixing scanner slow-scan regressions introduced by the referenced issues.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/scanner-scan-regressions-319-322

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread internal/scanner/scanner.go Outdated
// 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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@CoffeeKnyte CoffeeKnyte changed the title fix(scanner): eliminate two scan-slowdown regressions (extras misclassification + probe storm) fix(scanner): fix slow-scan regressions from #319 and #322 Jul 8, 2026
@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 8, 2026

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
internal/scanner/scanner.go (1)

2031-2073: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider reusing populateScanIdentity in the new-file path to eliminate duplication.

The actionNew path (lines 2031–2073) inlines the same root/group/identity/edition/presentation population logic that populateScanIdentity now 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 win

Add assertions for the remaining rewritten identity columns.

The test verifies ContentGroupKey and ObservedRootPath were updated, but doesn't check CanonicalRootPath, BaseTitle, BaseYear, or BaseType — all of which UpdateIdentity rewrites. 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

📥 Commits

Reviewing files that changed from the base of the PR and between f330d55 and dcbe8fa.

📒 Files selected for processing (5)
  • internal/scanner/extras_test.go
  • internal/scanner/file_repo.go
  • internal/scanner/scanner.go
  • internal/scanner/scanner_test.go
  • internal/scanner/update_identity_db_test.go

Comment thread internal/scanner/file_repo.go Resolved
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.
@CoffeeKnyte

Copy link
Copy Markdown
Contributor Author

Re the CodeRabbit nitpicks (review body, no inline thread to reply to):

  • Reuse populateScanIdentity in the new-file path — already done in 51f3ddf: the actionNew branch now calls the shared helper (passing nil for existing, since that branch only runs when the path is absent from existingByPath, making the suggested existingByPath[filePath] lookup provably dead).
  • Assert the remaining rewritten identity columns in the UpdateIdentity DB test — added in 0ac53e9 (canonical_root_path, base_title, base_year, base_type); re-ran green against a migrated scratch PostgreSQL 17.

The presentation_part_total inline comment is answered in its thread: UpdateIdentity mirrors Upsert's existing NULL-then-finalize behavior — part totals are recomputed per presentation group by FinalizeVariantsByPathPrefix after each scan scope, so no change was made.

@Quick104

Quick104 commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Code review

Found 1 issue:

  1. The simplification in c1828d2 regressed chained supplemental dirs at the library root. classifyExtraPath now only checks whether the convention-named dir or its immediate parent is a library root, so /movies/extras/behind the scenes/clip.mkv (root /movies) classifies as an extra with SupplementalDir = /movies/extras/behind the scenes — a folder that can never resolve to a title, reproducing the deferred-forever behavior this PR fixes, one level deeper. The earlier commit 51f3ddf on this branch handled this with the supplementalDirAtScopeDepth walk-up loop and an explicit test case ({"/movies/extras/behind the scenes", true}) that was deleted in the simplification. Verified by running classifyExtraPath against the branch head: it returns ok=true for this path where 51f3ddf returned false.

if kind, ok := extrasDirKinds[label]; ok {
dirClean := filepath.Clean(dir)
if libraryRootSet[dirClean] || libraryRootSet[filepath.Dir(dirClean)] {
break
}
candidate.Kind = kind

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

Copy link
Copy Markdown
Contributor Author

Thanks. Pushed a fix

@Quick104
Quick104 merged commit 50b9829 into main Jul 8, 2026
1 check passed
@Quick104
Quick104 deleted the fix/scanner-scan-regressions-319-322 branch July 8, 2026 15:18
Quick104 pushed a commit that referenced this pull request Jul 10, 2026
* 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants