Skip to content

fix(metadata): matcher reliability — Sonarr token cleanup, bare-bracket IMDb IDs, year-corroboration, provider-priority tie resolution - #19

Merged
Quick104 merged 14 commits into
Silo-Server:mainfrom
fluxis:mr/a-matcher-reliability
May 28, 2026
Merged

Quick104 merged 14 commits into
Silo-Server:mainfrom
fluxis:mr/a-matcher-reliability

Conversation

@fluxis

@fluxis fluxis commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Many items stay unmatched even when the right metadata candidate exists, blocking the operator UI's stale-ID review flow:

  • Unsubstituted Sonarr placeholders ({TvdbId}, {imdb-}) end up in parsed item titles.
  • Numeric-only folder names (86, 22 7) are treated as bare provider IDs.
  • Bare-bracket IMDb tags like [tt10011226] (Plex/Kodi-style) are silently dropped instead of extracted as trusted IDs.
  • A selectInitialMatchCandidate race can reject ErrItemNotFound (a concurrent provider-ID merge) as a hard failure.
  • Folder-year off by 1–2 vs the provider's release year zeroes the +20 year-score bonus, leaving lone exact-title candidates at 63–68 — just under the existing single-candidate ≥70 gate (e.g. Dead Reckoning (1947) vs TMDB 1946; 17 Blocks (2021) vs TMDB 2019; Stasi FC (2023) vs TMDB 2025).

Approach

Strictly additive rules above the existing 55 / 70 / 15 thresholds — no threshold change:

  • Title cleaner (internal/naming/root_inference.go): the inferProviderTagRe regex now strips well-formed and broken Sonarr tokens.
  • Numeric-only guard (internal/naming/folderid.go): a folder name with no letter (e.g. 86) is not treated as a bare provider id.
  • Bare-bracket IMDb (internal/naming/folderid.go): bracketedBareImdbPattern recognises [tt\d{7,8}] / {tt\d{7,8}} (unambiguously IMDb).
  • Lone-result acceptance (internal/metadata/match_candidates.go): selectInitialMatchCandidate accepts a sole distinct show when either the year matches exactly, or two distinct providers returned the same candidate, or the normalised title matches exactly and the year is within ±2. The 55 floor still protects against low-similarity titles (e.g. "Hotel Transylvania Puppy!" vs "Puppy!" stays rejected — covered by test).
  • Cross-source tie resolution by the library's metadata-provider priority over the top tie-group (within 15 pts of best); falls back to top-scored when priority is absent.
  • Tolerate concurrent-merge ErrItemNotFound in ensureSeriesEpisodeLinks — a scan-vs-background-worker race no longer fails the scan.
  • DEBUG-gated per-candidate score log + provider-search result-count log for diagnosing future cases (zero-cost when debug is off; titles + provider IDs only, no credentials).

Testing

go test ./internal/metadata/... ./internal/naming/... ./internal/libraryingest/...   # PASS
golangci-lint run ./internal/metadata/... ./internal/naming/... ./internal/libraryingest/...   # zero new hits

Could not run the full go test ./... locally (missing libvips-dev for bimg-using packages); CI will cover that.

Empirical impact (estimates on a personal instance)

These are operator-reported snapshots, not a tracked metric — treat as rough. "Before" is the unmatched count before any commit on this branch landed; "after" is the state once the branch was deployed and a re-scan completed.

library unmatched before unmatched after rough recovery
TV ~6,300 586 ~91%
Anime ~1,000 465 ~55%
Movies several thousand 656 substantial

(Movies started substantially higher than the original snapshot suggested, since the token-cleaning and root-inference fixes themselves re-derived a chunk of the catalog and surfaced unmatched items that had previously been mis-labelled. The TV scan's smaller absolute recovery isn't a fix gap so much as the TV residue being dominated by genuinely-hard cases the matcher rules can't help much — year-less anime folders, season-folder-as-root mis-detections, and obscure titles that simply aren't in TMDB/TVDB.)

Concrete examples that now match cleanly:
17 Blocks (2021) [tt10011226] (bracket-IMDb → trusted ID),
Dead Reckoning (1947) → TMDB 1946 (title corroboration ±2),
Stasi FC (2023) → TMDB 2025 (title corroboration ±2),
Interviewing Monsters and Bigfoot (2020) → TMDB 2019.

Watch out

  • Lone-result loosening: a sole exact-title candidate within ±2 years is now auto-accepted. The 55 floor + candidatesAreSingleDistinctShow keeps risk bounded (the candidate must still pass title similarity), but a remake with the same title released within two years could theoretically be picked. None observed in practice across the test corpus.
  • selectRefreshMatchCandidate calls selectInitialMatchCandidate with providerPriority=nil — the existing fallback (top-scored) preserves prior behaviour. Library-priority on the refresh path is a deliberate follow-up, not in this MR.
  • DEBUG logs gated by slog.Default().Enabled(...) and contain only query title/year, provider slugs, and TMDB/TVDB/IMDb IDs — no credentials.

Compatibility

No schema or API changes. server_settings-tunable behaviour unchanged (matcher.workers, matcher.batch_size, scoring thresholds). Behaviour change is restricted to which previously-unmatched items now match.

Note on process

This branch originally also addressed the series-scan cancel-bug (every series scan ended status=cancelled). ea5be46 + f2cb7e1 shipped a structurally cleaner upstream fix for that during this work, so the scanner-cancel commits are not in this PR — only the matcher-reliability portion is. (Design notes under docs/superpowers/ describe the original investigation for context; an "Note on scope" callout at the top of each doc points at the upstream commits.)

I did not open an issue first per CONTRIBUTING.md — happy to retroactively file one and link if preferred. Also happy to split this further if the matcher rule changes should land independently of the naming fixes.

AI disclosure

AI (Claude) meaningfully shaped this implementation: I drove the diagnosis from logs and DB state, designed the matcher rules in a spec → plan → subagent-driven-implementation flow (notes under docs/superpowers/), and wrote the tests. Every line was read and tested locally before commit.

Summary by CodeRabbit

  • New Features

    • Smarter show matching with provider-priority tie-breaking and high-confidence auto-accept for unambiguous multi-source matches.
    • Detects bracketed/braced IMDb IDs in folder names and rejects purely numeric folder titles as IDs unless letters are present.
    • Improved handling of more provider tag formats.
  • Bug Fixes

    • Treats missing catalog items as recoverable instead of failing batches.
  • Tests

    • Expanded unit tests covering match selection, folder ID parsing, token stripping, and error-handling cases.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR enhances match-candidate selection with provider-priority awareness and early-accept corroboration, tolerates benign concurrent-merge errors in series processing, and strengthens provider-tag and folder-ID parsing for edge cases like bracketed IMDb IDs and numeric-only titles.

Changes

Scanner & Matching Reliability Improvements

Layer / File(s) Summary
Match-candidate selection core changes
internal/metadata/match_candidates.go
selectInitialMatchCandidate now accepts an ordered providerPriority slice and implements a high-confidence early-accept path: when the tie group represents a single distinct show (verified by consistent year, title, and provider IDs) and corroboration is satisfied (hint-year match, multi-source spanning, or exact normalized-title with ±2 year delta), it returns the priority-ordered group winner. Debug logging added for per-candidate scoring diagnostics; refresh-match selection updated to pass nil priority.
Match-candidate tests and call-site updates
internal/metadata/match_candidates_select_test.go, internal/metadata/match_candidates_test.go
New tests validate lone-candidate acceptance below scoring floor, cross-source same-show acceptance, year mismatch rejection, distinct-show prevention, provider-ID conflict rejection, missing-hint-year tolerance, no-year-both-sides rejection, single-source no-year rejection, and provider-priority tie resolution with nil fallback. Existing test call sites updated to pass the new trailing nil argument.
Provider-priority wiring in service
internal/metadata/service.go
Search debug logging added per provider; providerPriority built from itemChain slugs and passed into selectInitialMatchCandidate during initial match winner selection, enabling provider-order-aware corroboration.
Concurrent-merge error tolerance in series processing
internal/metadata/worker.go, internal/metadata/worker_test.go
processSeriesRoot special-cases catalog.ErrItemNotFound from ensureSeriesEpisodeLinks (benign concurrent-merge condition) to log and skip, while other errors still fail the batch. Applies to both representative and final content IDs. Tests verify tolerance for ErrItemNotFound (batch succeeds, row deleted) vs failure for other errors.
Naming and provider-token parsing improvements
internal/naming/folderid.go, internal/naming/root_inference.go, internal/naming/folderid_test.go, internal/naming/folderid_numeric_test.go, internal/naming/provider_token_test.go
ParseFolderIDs now detects bracketed bare IMDb IDs (e.g., [tt10011226]) and requires letters in trimmed names to accept trailing-numeric IDs (rejects numeric-only titles). inferProviderTagRe updated to match malformed/placeholder provider tokens. Tests cover broken Sonarr tokens, bracketed IMDb extraction, and numeric-only title rejection across library types.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Provider priorities bloom, selection tie-breaks with care,
Concurrent merges shrug, benign errors skip and share,
Bracket-wrapped IMDb glints, numeric titles beware—
Parser strengthens naming, testing leaves no tear!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.26% 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 PR title accurately summarizes all four main changes: Sonarr token cleanup, bare-bracket IMDb ID detection, year-corroboration logic, and provider-priority tie resolution in the matcher reliability context.
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 unit tests (beta)
  • Create PR with unit tests

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: 2

🤖 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 `@docs/superpowers/plans/2026-05-27-scanner-matching-hotfix.md`:
- Around line 2-15: The intro blockquote contains a blank line causing MD028 and
the heading jumps from H1 to H3 causing MD001; remove the blank line inside the
opening blockquote and insert a proper H2 (e.g., "## Tasks" or promote each "###
Task ..." to "## Task ...") so heading levels are sequential and the blockquote
has no internal blank line; update the document's opening blockquote and the
"### Task 0" (and subsequent task headings) accordingly to resolve both lint
rules.

In `@internal/metadata/match_candidates.go`:
- Around line 354-360: The function candidatesAreSingleDistinctShow currently
treats Year==0 as equal; change the year comparison in
candidatesAreSingleDistinctShow so that any unknown year (best.Year == 0 or
c.candidate.Year == 0) causes the function to return false (i.e., treat 0 as a
mismatch), updating the loop that compares c.candidate.Year to best.Year (and
any similar logic around lines 493-510) to explicitly check for zero before
equality; also add a regression test for the multi-source/no-hint-year scenario
(two scoredMatchCandidate entries both with Year: 0) asserting the function
rejects that case.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3a55c9fb-7951-4985-af71-5cd39558c241

📥 Commits

Reviewing files that changed from the base of the PR and between 985b296 and 78116c98c9bbd9edc658e1a65f3eb25a962341c7.

📒 Files selected for processing (13)
  • docs/superpowers/plans/2026-05-27-scanner-matching-hotfix.md
  • docs/superpowers/specs/2026-05-27-scanner-matching-hotfix-design.md
  • internal/metadata/match_candidates.go
  • internal/metadata/match_candidates_select_test.go
  • internal/metadata/match_candidates_test.go
  • internal/metadata/service.go
  • internal/metadata/worker.go
  • internal/metadata/worker_test.go
  • internal/naming/folderid.go
  • internal/naming/folderid_numeric_test.go
  • internal/naming/folderid_test.go
  • internal/naming/provider_token_test.go
  • internal/naming/root_inference.go

Comment thread internal/metadata/match_candidates.go Resolved
@fluxis
fluxis force-pushed the mr/a-matcher-reliability branch from 78116c9 to 444c7f1 Compare May 28, 2026 15:19
@fluxis

fluxis commented May 28, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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: 0

♻️ Duplicate comments (1)
docs/superpowers/plans/2026-05-27-scanner-matching-hotfix.md (1)

3-5: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Markdown lint issue persists: blank line inside blockquote.

The blank line at line 4 (inside the blockquote) still triggers MD028. Remove this line to resolve the violation, as noted in the previous review.

Suggested fix
 > **Note on scope:** This document describes the original investigation, which also covered a scanner cancel-bug (series scans deterministically ending `status=cancelled`). Upstream commits [`ea5be46`](https://github.com/Silo-Server/silo-server/commit/ea5be46) (`fix(libraryingest): treat drainer shutdown cancel as clean stop`) and [`f2cb7e1`](https://github.com/Silo-Server/silo-server/commit/f2cb7e1) (`Fix settle-window drainer cancellation in library ingest`) landed an independent and structurally cleaner fix for that bug during this branch's in-flight work, so the scanner-cancel commits aren't part of this PR — only the matcher-reliability portion is.
->
 > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
🤖 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 `@docs/superpowers/plans/2026-05-27-scanner-matching-hotfix.md` around lines 3
- 5, The blockquote starting with "> **Note on scope:**" contains an extra blank
line inside it that triggers markdown lint rule MD028; edit the blockquote (the
consecutive lines beginning with ">") and remove the empty line so that the
quoted paragraphs are contiguous, ensuring there are no bare blank lines inside
the blockquote.
🤖 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.

Duplicate comments:
In `@docs/superpowers/plans/2026-05-27-scanner-matching-hotfix.md`:
- Around line 3-5: The blockquote starting with "> **Note on scope:**" contains
an extra blank line inside it that triggers markdown lint rule MD028; edit the
blockquote (the consecutive lines beginning with ">") and remove the empty line
so that the quoted paragraphs are contiguous, ensuring there are no bare blank
lines inside the blockquote.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: fb7358be-d5f4-4b11-bfa1-1e21a0aac2fc

📥 Commits

Reviewing files that changed from the base of the PR and between 78116c98c9bbd9edc658e1a65f3eb25a962341c7 and 444c7f12af15e4edd36d39e9abf11ddca3282c37.

📒 Files selected for processing (11)
  • docs/superpowers/plans/2026-05-27-scanner-matching-hotfix.md
  • docs/superpowers/specs/2026-05-27-scanner-matching-hotfix-design.md
  • internal/metadata/match_candidates.go
  • internal/metadata/match_candidates_select_test.go
  • internal/metadata/match_candidates_test.go
  • internal/metadata/service.go
  • internal/metadata/worker.go
  • internal/metadata/worker_test.go
  • internal/naming/folderid.go
  • internal/naming/folderid_test.go
  • internal/naming/root_inference.go
✅ Files skipped from review due to trivial changes (1)
  • docs/superpowers/specs/2026-05-27-scanner-matching-hotfix-design.md
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/naming/folderid.go
  • internal/naming/folderid_test.go
  • internal/metadata/worker_test.go
  • internal/metadata/match_candidates.go
  • internal/metadata/match_candidates_test.go
  • internal/metadata/service.go
  • internal/metadata/worker.go
  • internal/metadata/match_candidates_select_test.go

@fluxis

fluxis commented May 28, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@fluxis
fluxis force-pushed the mr/a-matcher-reliability branch from 444c7f1 to 48a4380 Compare May 28, 2026 15:31
@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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: 2

🤖 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 `@docs/superpowers/plans/2026-05-27-scanner-matching-hotfix.md`:
- Line 3: The scope note claims scanner-cancel commits are excluded from this PR
but Task 1 still instructs code changes to internal/libraryingest/executor.go;
remove Task 1 from the plan or mark it explicitly as historical/non-executable
to prevent implementation work. Update the plan document (the Task list
referencing Task 1 and any mentions of internal/libraryingest/executor.go or
“scanner-cancel” fixes) so it either deletes Task 1 entirely or prefixes it with
a clear label like “Historical — already fixed upstream; do not implement,” and
ensure any cross-references (e.g., tasks 30-237) are adjusted to avoid implying
code changes are required.
- Around line 444-447: Extract the inline docker exec + SQL block (the SELECT
... FROM media_items mi JOIN media_item_libraries mil ... ) out of the plan and
place it as a reusable script under scripts/, e.g.
scripts/queries/media_item_status_counts.sh (or .sql with a small wrapper),
ensuring the SQL text is preserved and parameterized for folder IDs; then
replace the inline snippet in the plan with a reference/link to that script and
a one-line example showing how to run it (e.g. docker exec silo-postgres-1 psql
-U silo -d silo -f scripts/queries/media_item_status_counts.sql --folders=2,3).
Include the same change for the other inline snippets mentioned (lines 466-469,
472-473, 484-486, 492) so all ad hoc SQL helpers live in scripts/ and are
referenced from the plan.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 20a21d6a-b7c1-4d04-924b-b27ca8b0830f

📥 Commits

Reviewing files that changed from the base of the PR and between 444c7f12af15e4edd36d39e9abf11ddca3282c37 and 48a4380b6ff810d6f7940079ea9340a393b4862c.

📒 Files selected for processing (2)
  • docs/superpowers/plans/2026-05-27-scanner-matching-hotfix.md
  • docs/superpowers/specs/2026-05-27-scanner-matching-hotfix-design.md
✅ Files skipped from review due to trivial changes (1)
  • docs/superpowers/specs/2026-05-27-scanner-matching-hotfix-design.md

@@ -0,0 +1,512 @@
# Scanner + Matching Local Hotfix — Implementation Plan

> **Note on scope:** This document describes the original investigation, which also covered a scanner cancel-bug (series scans deterministically ending `status=cancelled`). Upstream commits [`ea5be46`](https://github.com/Silo-Server/silo-server/commit/ea5be46) (`fix(libraryingest): treat drainer shutdown cancel as clean stop`) and [`f2cb7e1`](https://github.com/Silo-Server/silo-server/commit/f2cb7e1) (`Fix settle-window drainer cancellation in library ingest`) landed an independent and structurally cleaner fix for that bug during this branch's in-flight work, so the scanner-cancel commits aren't part of this PR — only the matcher-reliability portion is.

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Scope note conflicts with the implementation tasks.

Line 3 says scanner-cancel work is out of this PR, but Task 1 still instructs implementing that scanner-cancel fix in internal/libraryingest/executor.go. Please either remove Task 1 from this plan or clearly mark it as historical/non-executable to avoid accidental out-of-scope work.

Also applies to: 30-237

🤖 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 `@docs/superpowers/plans/2026-05-27-scanner-matching-hotfix.md` at line 3, The
scope note claims scanner-cancel commits are excluded from this PR but Task 1
still instructs code changes to internal/libraryingest/executor.go; remove Task
1 from the plan or mark it explicitly as historical/non-executable to prevent
implementation work. Update the plan document (the Task list referencing Task 1
and any mentions of internal/libraryingest/executor.go or “scanner-cancel”
fixes) so it either deletes Task 1 entirely or prefixes it with a clear label
like “Historical — already fixed upstream; do not implement,” and ensure any
cross-references (e.g., tasks 30-237) are adjusted to avoid implying code
changes are required.

Comment on lines +444 to +447
docker exec silo-postgres-1 psql -U silo -d silo -c "
SELECT mil.media_folder_id AS fid, lower(trim(COALESCE(mi.status,''))) AS status, count(*)
FROM media_items mi JOIN media_item_libraries mil ON mil.content_id=mi.content_id
WHERE mil.media_folder_id IN (2,3) GROUP BY 1,2 ORDER BY 1,3 DESC;"

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Move ad hoc SQL helpers into scripts/ and reference them here.

This plan embeds multiple operational SQL helper queries inline. Per repo rules, these should live as script artifacts under scripts/ and the plan should link to them.

As per coding guidelines, "Reference material belongs in docs/architecture/ or docs/superpowers/{specs,plans}/; ad hoc SQL helpers live in scripts/."

Also applies to: 466-469, 472-473, 484-486, 492-492

🤖 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 `@docs/superpowers/plans/2026-05-27-scanner-matching-hotfix.md` around lines
444 - 447, Extract the inline docker exec + SQL block (the SELECT ... FROM
media_items mi JOIN media_item_libraries mil ... ) out of the plan and place it
as a reusable script under scripts/, e.g.
scripts/queries/media_item_status_counts.sh (or .sql with a small wrapper),
ensuring the SQL text is preserved and parameterized for folder IDs; then
replace the inline snippet in the plan with a reference/link to that script and
a one-line example showing how to run it (e.g. docker exec silo-postgres-1 psql
-U silo -d silo -f scripts/queries/media_item_status_counts.sql --folders=2,3).
Include the same change for the other inline snippets mentioned (lines 466-469,
472-473, 484-486, 492) so all ad hoc SQL helpers live in scripts/ and are
referenced from the plan.

@fluxis

fluxis commented May 28, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@fluxis
fluxis force-pushed the mr/a-matcher-reliability branch from 48a4380 to 3f6b356 Compare May 28, 2026 15:40
@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

fluxis and others added 6 commits May 28, 2026 17:45
…m titles

These tokens survived the provider-tag regex ([\w]+ doesn't match braces),
polluting parsed titles (e.g. 'A Girl & Her Guard Dog [tvdb-{TvdbId}]') so
they could not score-match. Broaden the regex to drop {...} and empty tokens.
'86' / '22 7' were parsed as trailing tvdb ids, tripping the trusted-ID gate
so the correct title match was rejected. Require a letter in the name before
treating a trailing number as a bare id.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
A search that resolves to one distinct show (one candidate, or the same
title+year returned once per source as unmerged TVDB/TMDB rows) whose year
matches the parsed year is now auto-accepted via the existing top-ranked
candidate, even when the fuzzy title score is in the 55-69 band. The 55/70/15
thresholds are unchanged; this only adds a year-gated acceptance for
effectively-unique results (recovers lone-correct-result items like 1201 (1993)).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…flicting-ID case; doc notes

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…sode-link ensure

A scan drainer and the background MatchWorker can process the same folder
concurrently. When a provider-ID merge moves a series' episodes to the survivor
and deletes the source, an in-flight ensureSeriesEpisodeLinks(sourceID) hits
catalog.ErrItemNotFound and was failing the whole scan. The episodes are already
reattached, so this is benign: log and continue (matching the lenient call sites)
instead of failing. Genuine errors still abort.
@fluxis
fluxis force-pushed the mr/a-matcher-reliability branch from 3f6b356 to adb571d Compare May 28, 2026 15:46

@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: 2

🤖 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/metadata/match_candidates.go`:
- Around line 356-381: The canonical-ID conflict check in
candidatesAreSingleDistinctShow currently only compares each candidate's
canonical IDs against best.ProviderIDs, allowing two non-best candidates to
disagree on a key; change the loop over canonicalCandidateIDKeys to instead
aggregate seen non-empty values for each key across best and all scored
candidates (e.g., map[string]string or map[string]bool of seen values) and
return false if any key has more than one distinct non-empty value; apply the
same change to the similar canonical-ID comparison used in the lone-result
auto-acception logic elsewhere so all pairwise conflicts are detected, not just
conflicts versus best.
- Around line 458-473: The debug block dereferences hints without checking for
nil which can panic when hints == nil; update the scoring debug logic in the
loop over scoredCandidates to derive safe local values (e.g., hintTitle,
hintYear, hintType) by checking if hints != nil and falling back to empty
strings (or zero values) before calling slog.Debug so the call uses only those
safe locals alongside sc.candidate and sc.score; ensure the change is applied
around the scoredCandidates loop and the slog.Debug invocation to prevent nil
deref.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 88770963-c043-40e4-8fe5-83f5c38e5026

📥 Commits

Reviewing files that changed from the base of the PR and between 48a4380b6ff810d6f7940079ea9340a393b4862c and adb571d43b76903db59b323363b3874b17ff8f8d.

📒 Files selected for processing (11)
  • internal/metadata/match_candidates.go
  • internal/metadata/match_candidates_select_test.go
  • internal/metadata/match_candidates_test.go
  • internal/metadata/service.go
  • internal/metadata/worker.go
  • internal/metadata/worker_test.go
  • internal/naming/folderid.go
  • internal/naming/folderid_numeric_test.go
  • internal/naming/folderid_test.go
  • internal/naming/provider_token_test.go
  • internal/naming/root_inference.go
🚧 Files skipped from review as they are similar to previous changes (10)
  • internal/naming/root_inference.go
  • internal/naming/folderid_test.go
  • internal/naming/folderid_numeric_test.go
  • internal/metadata/service.go
  • internal/naming/provider_token_test.go
  • internal/naming/folderid.go
  • internal/metadata/match_candidates_test.go
  • internal/metadata/worker_test.go
  • internal/metadata/worker.go
  • internal/metadata/match_candidates_select_test.go

Comment thread internal/metadata/match_candidates.go Resolved
Comment thread internal/metadata/match_candidates.go Resolved
fluxis and others added 7 commits May 28, 2026 17:58
Adds a DEBUG-gated log in selectInitialMatchCandidate printing each scored
candidate (title/year/type/sources/provider_ids/score) against the hint, so
operators can see why an item did or didn't auto-match. Zero-cost when debug
logging is off; no change to matching behavior.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Accept a year-corroborated single distinct show when the TOP tie-group (within
15 pts of best) is one show across providers, ignoring low-score noise below it,
and pick the winner by the library's metadata-provider chain order (providerPriority,
highest-first; falls back to top-scored). Recovers items like '100 Days Wild'
that are returned identically by TVDB and TMDB. Thresholds (55/70/15) unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When the top tie-group is one distinct show returned by 2+ distinct providers
(candidatesAreSingleDistinctShow already verifies matching title+year), accept it
even if the hint has no parsed year (year-less folders like '100 Deeds for Eddie
McDowd'). Multi-source agreement substitutes for the year guard; lone single-source
no-year results stay subject to the single-candidate >=70 gate. Thresholds unchanged.
…counts

Adds DEBUG logs in the ModeInitialMatch search path: each provider's result
count for the query, and the assembled raw/candidate totals. Lets us see when a
provider search returns zero ('no metadata found') vs a scoring/tie issue.
Zero behavior change.
Folders tagged with a bare IMDb id in brackets (Plex/Kodi style, e.g.
'17 Blocks (2021) [tt10011226]') had the id silently dropped — folderIDPattern
needs an 'imdb-' prefix and trailingImdbIDPattern needs an un-bracketed trailing
tt-id. Recognize bracketed bare tt-ids so these items get the trusted-ID match
path instead of falling to title+year scoring.
Folder years routinely differ from provider release years by a year or two
(festival vs wide release, regional dates), zeroing the year bonus and leaving
a lone exact-title candidate at 63-68 — just under the single-candidate >=70
gate (e.g. Dead Reckoning 1947 vs 1946, 17 Blocks 2021 vs 2019, Stasi FC). Add
title corroboration to the existing lone-result rule: a sole distinct show whose
normalized title exactly matches and whose year is within +/-2 is accepted. The
55 floor still rejects low-similarity titles (e.g. Hotel Transylvania Puppy! vs
Puppy!). No 55/70/15 threshold change.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When inferProviderTagRe was broadened to handle unsubstituted Sonarr token
placeholders ({TvdbId}/{imdb-}), the regex grew long enough that gofmt prefers
single-space rather than column-aligned spacing across the var block.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@fluxis

fluxis commented May 28, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@fluxis
fluxis force-pushed the mr/a-matcher-reliability branch from adb571d to df11126 Compare May 28, 2026 15:58
@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown
Contributor

Actionable comments posted: 0

@Quick104
Quick104 merged commit 5ceb0cf into Silo-Server:main May 28, 2026
1 check passed
@fluxis
fluxis deleted the mr/a-matcher-reliability branch May 28, 2026 17:22
Quick104 added a commit to thezak48/silo-server that referenced this pull request Jun 7, 2026
fix(metadata): matcher reliability — Sonarr token cleanup, bare-bracket IMDb IDs, year-corroboration, provider-priority tie resolution
Quick104 added a commit that referenced this pull request Jun 11, 2026
fix(metadata): matcher reliability — Sonarr token cleanup, bare-bracket IMDb IDs, year-corroboration, provider-priority tie resolution
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.

2 participants