Skip to content

fix(naming,metadata): anchor identity on provider IDs, drop bare-numeric IDs, back off match queue retries - #112

Merged
Quick104 merged 3 commits into
mainfrom
worktree-scanner-matching-fixes
Jun 9, 2026
Merged

Quick104 merged 3 commits into
mainfrom
worktree-scanner-matching-fixes

Conversation

@Quick104

@Quick104 Quick104 commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A review of the scanner → matching → metadata pipeline (validated against the dev database) found three issues that silently break or degrade matching:

  1. Title conflicts overrode explicit provider IDs. When a Radarr-tagged folder contains a renamed release (folder Override (2021) {tmdb-694938}, file R.I.A. (2021).mkv), group inference marked the group ambiguous via the title-coherence check — even though the structured tag resolves identity unambiguously. Ambiguous groups are skipped by the matcher entirely. On dev, 3,049 of 3,121 ambiguous groups carried explicit provider tags.

  2. Bare trailing numbers were parsed as provider IDs. ParseFolderIDs treated any trailing number in a year-less folder name as a TMDB/TVDB ID ("District 9" → tmdb=9, and on dev: Season 01 → tmdb_id="01"). Misparsed IDs become trusted match hints, which suppress title/year search and filter out all correct results — silent wrong match or permanent no-match. This heuristic already needed one emergency patch (534f7bb) and still failed on real titles ("Beverly Hills 90210").

  3. Match queues hot-looped terminal failures. "No metadata found from any provider" was retried at a constant 15s/30s forever. Dev had 1,580 queue rows in error state with attempt counts up to 15,841 (~66 hours of continuous provider hammering per item).

Approach

  • Group identity: structured provider tags ({tmdb-…}, [tvdbid-…]) on the observed root or filename now anchor identity; all five ambiguity paths are gated on the anchor. Evidence still records the conflict (…_resolved_by_provider_ids) for diagnostics. Bare numerics deliberately do not anchor.
  • ParseFolderIDs: bare trailing numeric parsing removed entirely, mirroring Jellyfin's path-attribute model (PathExtensions.GetAttributeValue: bracketed key tags only, plus unambiguous tt-prefixed IMDb ids). The folderType parameter existed only to type bare numerics, so it is dropped, which also collapses the ParseFolderIDs(name, "movie") || ParseFolderIDs(name, "series") double-call patterns at four sites.
  • Match queues: shared matchQueueBackoffExpr replaces the constant retry delay in both queues' UpdateError: base × 2^attempt_count, exponent clamped at 16, capped at 24h. Rows still self-heal (deleted on first success), so no new terminal state or admin surface is needed.

Validation

Deployed to dev and verified live:

  • Previously-stranded files under Override {tmdb-694938} / On Fire {tmdb-1196791} flipped to resolved on rescan and matched the correct movies via their tags.
  • The poisoned Season 01 (tmdb_id="01") group is gone after rescan; files re-inferred cleanly.
  • All 500+ wedged queue rows that retried post-deploy rescheduled to the 24h cap, including the 15,841-attempt row.
  • Backoff SQL semantics verified directly against Postgres (30s → 2m → 16m → ~4h → 24h cap by attempt 13).

Risks / follow-up

  • Folders that previously matched because of a bare trailing ID (none exist on dev) now match via title/year search like any untagged folder.
  • Existing ambiguous-with-IDs groups resolve on each library's next full scan (snapshots rebuild at scan time).
  • Larger follow-up identified during review (not in this PR): consolidating the duplicated filename.go vs root_inference.go parsing stacks in internal/naming.

AI use

Authored by Claude Code (Fable 5) under human direction; findings and fixes validated against the dev environment as described above.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Capped retry backoff to prevent excessively long delays during error recovery.
    • Stricter folder ID parsing—only explicit provider-tagged IDs and proper IMDb IDs are recognized, reducing false matches.
    • Improved title conflict resolution when structured provider IDs are present in folder paths/files.
  • Tests

    • Added and expanded tests to cover numeric-title edge cases and structured-ID resolution.

Quick104 and others added 2 commits June 9, 2026 15:51
…ric IDs, back off match queue retries

Three scanner/matching fixes validated against dev data:

- Group identity: explicit structured provider tags ({tmdb-...},
  [tvdbid-...]) now anchor a group's identity, so folder/file title
  conflicts (renamed releases in Radarr-tagged folders) no longer mark
  groups ambiguous and silently exclude them from matching. 3,049 of
  3,121 ambiguous groups on dev carried explicit tags.

- ParseFolderIDs: remove bare trailing numeric ID parsing entirely,
  mirroring Jellyfin's path-attribute model (bracketed key tags plus
  unambiguous tt-prefixed IMDb ids only). Titles ending in numbers
  ("District 9", "Beverly Hills 90210", "Season 01") were misparsed as
  trusted IDs, which suppresses title search and silently mismatches.
  The folderType parameter existed only to type bare numerics, so it
  is gone too.

- Match queues: replace the constant 15s/30s retry delay with shared
  exponential backoff capped at 24h. Terminal failures ("no metadata
  found from any provider") had rows at 15k+ attempts hot-looping
  every 15s on dev.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f4e3338c-a277-4942-983b-583993234257

📥 Commits

Reviewing files that changed from the base of the PR and between 9207b6f and 6de2b2c.

📒 Files selected for processing (2)
  • internal/naming/folderid.go
  • internal/naming/folderid_numeric_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/naming/folderid_numeric_test.go
  • internal/naming/folderid.go

📝 Walkthrough

Walkthrough

Tightens folder ID parsing to only accept explicit structured provider tags and IMDb tt IDs, removes the folderType argument from ParseFolderIDs call sites, threads an idAnchored flag into group identity resolution, and caps match-queue retry backoff with a capped exponential SQL expression.

Changes

Folder ID parsing tightening and identity resolution

Layer / File(s) Summary
Folder ID parsing API tightening and validation
internal/naming/folderid.go, internal/naming/folderid_numeric_test.go, internal/naming/folderid_test.go
ParseFolderIDs signature changes from (folderName, folderType) to (folderName). ID recognition is limited to explicit structured bracket tags and IMDb tt\d{7,8}; bare numeric trailing IDs are no longer recognized. Tests updated to assert numeric-only folders do not parse and structured tags still parse.
Call sites updated to new ParseFolderIDs signature
internal/metadata/service.go, internal/naming/movie_identity.go, internal/naming/root_inference.go, internal/scanner/root_observation.go
All ParseFolderIDs(...) calls updated to the single-argument form, removing media-type guidance from folder-ID detection in skeleton creation, movie parsing, root inference, and scanner observation.
Group identity conflict resolution with provider ID anchoring
internal/naming/group_identity.go, internal/naming/group_identity_test.go
Adds idAnchored via hasStructuredIDAnchor and passes it into populateMovieGroupIdentity/populateSeriesGroupIdentity. When anchored, title conflicts are resolved with provider-ID reasons; when not, conflicts remain ambiguous. Four tests validate both movie and series scenarios.

Match queue retry backoff capping

Layer / File(s) Summary
Exponential backoff configuration and SQL helper
internal/metadata/movie_match_queue_repo.go
Introduces matchQueueRetryMaxDelay, matchQueueBackoffMaxExponent, and matchQueueBackoffExpr helper to generate a SQL expression computing exponential backoff capped by a maximum delay and numeric stability bounds.
Apply capped backoff to match queue repositories
internal/metadata/movie_match_queue_repo.go, internal/metadata/series_root_match_queue_repo.go
UpdateError methods now set available_at using the capped exponential backoff SQL expression and pass both base and max delay parameters to the UPDATE statements.

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly Related PRs

  • Silo-Server/silo-server#19: Both PRs change internal/naming/folderid.go’s ParseFolderIDs parsing rules for folder IDs—especially handling of bare bracketed IMDb tt... IDs and numeric-only folder names—so the matcher-ID extraction behavior is directly related.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title clearly and specifically summarizes the main changes: anchoring identity on provider IDs, dropping bare-numeric ID parsing, and implementing exponential backoff for match queue retries.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 worktree-scanner-matching-fixes

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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/naming/folderid.go (1)

58-65: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Merge trailing bare IMDb IDs with structured tags.

Line 59 returns as soon as any structured tag is found, so ParseFolderIDs("Some Show [tvdbid-81189] tt1375666") yields only TvdbID. That drops explicit IMDb evidence and weakens the provider-ID anchor downstream.

Proposed fix
 func ParseFolderIDs(folderName string) *FolderIDHints {
-	if hints := ParseStructuredFolderIDs(folderName); hints != nil {
-		return hints
-	}
+	hints := ParseStructuredFolderIDs(folderName)
 
 	trimmed := strings.TrimSpace(folderName)
 	if m := trailingImdbIDPattern.FindStringSubmatch(trimmed); m != nil {
-		return &FolderIDHints{ImdbID: strings.ToLower(m[1])}
+		if hints == nil {
+			hints = &FolderIDHints{}
+		}
+		if hints.ImdbID == "" {
+			hints.ImdbID = strings.ToLower(m[1])
+		}
 	}
 
-	return nil
+	if hints == nil || (hints.TmdbID == "" && hints.ImdbID == "" && hints.TvdbID == "") {
+		return nil
+	}
+	return hints
 }
🤖 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/naming/folderid.go` around lines 58 - 65, ParseFolderIDs currently
returns immediately if ParseStructuredFolderIDs finds any structured tag, which
prevents merging a trailing bare IMDb ID (matched by trailingImdbIDPattern) into
the returned FolderIDHints; update ParseFolderIDs so that after calling
ParseStructuredFolderIDs it still checks trailingImdbIDPattern on the trimmed
folderName and, if a match exists, sets/overwrites hints.ImdbID =
strings.ToLower(m[1]) before returning the hints (preserve existing behavior for
other fields). Reference: ParseFolderIDs, ParseStructuredFolderIDs,
trailingImdbIDPattern, and FolderIDHints.
🤖 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/naming/folderid_numeric_test.go`:
- Around line 35-51: Update the test TestParseFolderIDs_StructuredTagsStillParse
to include a mixed case like `Some Show (2010) [tvdbid-81189] tt1375666` that
asserts ParseFolderIDs returns both TvdbID=="81189" and ImdbID=="tt1375666";
this will lock in the intended merge behavior and catch the early-return bug in
ParseFolderIDs by ensuring it does not stop parsing after seeing a structured
tag.

---

Outside diff comments:
In `@internal/naming/folderid.go`:
- Around line 58-65: ParseFolderIDs currently returns immediately if
ParseStructuredFolderIDs finds any structured tag, which prevents merging a
trailing bare IMDb ID (matched by trailingImdbIDPattern) into the returned
FolderIDHints; update ParseFolderIDs so that after calling
ParseStructuredFolderIDs it still checks trailingImdbIDPattern on the trimmed
folderName and, if a match exists, sets/overwrites hints.ImdbID =
strings.ToLower(m[1]) before returning the hints (preserve existing behavior for
other fields). Reference: ParseFolderIDs, ParseStructuredFolderIDs,
trailingImdbIDPattern, and FolderIDHints.
🪄 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: 2a7c50e0-ae56-4ad7-a2d6-4af435537f3d

📥 Commits

Reviewing files that changed from the base of the PR and between 8f607cf and 9207b6f.

📒 Files selected for processing (11)
  • internal/metadata/movie_match_queue_repo.go
  • internal/metadata/series_root_match_queue_repo.go
  • internal/metadata/service.go
  • internal/naming/folderid.go
  • internal/naming/folderid_numeric_test.go
  • internal/naming/folderid_test.go
  • internal/naming/group_identity.go
  • internal/naming/group_identity_test.go
  • internal/naming/movie_identity.go
  • internal/naming/root_inference.go
  • internal/scanner/root_observation.go

ParseFolderIDs returned early on any structured tag, so a folder like
"Show [tvdbid-81189] tt1375666" lost the trailing IMDb id. Parse both and
merge, with an explicit structured imdb tag still taking precedence over a
trailing bare id. Matches Jellyfin, which resolves each provider key
independently.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 merged commit adf36ec into main Jun 9, 2026
1 check passed
@Quick104
Quick104 deleted the worktree-scanner-matching-fixes branch June 9, 2026 20:38
Quick104 added a commit that referenced this pull request Jun 11, 2026
…ric IDs, back off match queue retries (#112)

* fix(naming,metadata): anchor identity on provider IDs, drop bare-numeric IDs, back off match queue retries

Three scanner/matching fixes validated against dev data:

- Group identity: explicit structured provider tags ({tmdb-...},
  [tvdbid-...]) now anchor a group's identity, so folder/file title
  conflicts (renamed releases in Radarr-tagged folders) no longer mark
  groups ambiguous and silently exclude them from matching. 3,049 of
  3,121 ambiguous groups on dev carried explicit tags.

- ParseFolderIDs: remove bare trailing numeric ID parsing entirely,
  mirroring Jellyfin's path-attribute model (bracketed key tags plus
  unambiguous tt-prefixed IMDb ids only). Titles ending in numbers
  ("District 9", "Beverly Hills 90210", "Season 01") were misparsed as
  trusted IDs, which suppresses title search and silently mismatches.
  The folderType parameter existed only to type bare numerics, so it
  is gone too.

- Match queues: replace the constant 15s/30s retry delay with shared
  exponential backoff capped at 24h. Terminal failures ("no metadata
  found from any provider") had rows at 15k+ attempts hot-looping
  every 15s on dev.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(naming): merge trailing bare IMDb id with structured folder tags

ParseFolderIDs returned early on any structured tag, so a folder like
"Show [tvdbid-81189] tt1375666" lost the trailing IMDb id. Parse both and
merge, with an explicit structured imdb tag still taking precedence over a
trailing bare id. Matches Jellyfin, which resolves each provider key
independently.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Quick104 added a commit that referenced this pull request Jun 17, 2026
…ric IDs, back off match queue retries (#112)

* fix(naming,metadata): anchor identity on provider IDs, drop bare-numeric IDs, back off match queue retries

Three scanner/matching fixes validated against dev data:

- Group identity: explicit structured provider tags ({tmdb-...},
  [tvdbid-...]) now anchor a group's identity, so folder/file title
  conflicts (renamed releases in Radarr-tagged folders) no longer mark
  groups ambiguous and silently exclude them from matching. 3,049 of
  3,121 ambiguous groups on dev carried explicit tags.

- ParseFolderIDs: remove bare trailing numeric ID parsing entirely,
  mirroring Jellyfin's path-attribute model (bracketed key tags plus
  unambiguous tt-prefixed IMDb ids only). Titles ending in numbers
  ("District 9", "Beverly Hills 90210", "Season 01") were misparsed as
  trusted IDs, which suppresses title search and silently mismatches.
  The folderType parameter existed only to type bare numerics, so it
  is gone too.

- Match queues: replace the constant 15s/30s retry delay with shared
  exponential backoff capped at 24h. Terminal failures ("no metadata
  found from any provider") had rows at 15k+ attempts hot-looping
  every 15s on dev.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(naming): merge trailing bare IMDb id with structured folder tags

ParseFolderIDs returned early on any structured tag, so a folder like
"Show [tvdbid-81189] tt1375666" lost the trailing IMDb id. Parse both and
merge, with an explicit structured imdb tag still taking precedence over a
trailing bare id. Matches Jellyfin, which resolves each provider key
independently.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant