Skip to content

fix(metadata): prevent stale cross-provider IDs - #480

Merged
Quick104 merged 3 commits into
Silo-Server:mainfrom
Rhainland:fix/stalemetadata
Jul 26, 2026
Merged

Quick104 merged 3 commits into
Silo-Server:mainfrom
Rhainland:fix/stalemetadata

Conversation

@Rhainland

@Rhainland Rhainland commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • require provider-native confirmation before promoting TMDB/TVDB cross-references into canonical identity
  • replace conflicting stored provider IDs when the owning provider confirms the corrected candidate
  • suppress recorded and same-run stale IDs throughout metadata, image, merge, and target-refresh paths
  • re-anchor provider-derived content IDs when their anchor is confirmed stale or deliberately replaced
  • hide non-actionable historical cross-reference failures from the stale-ID administration list
  • add regression coverage for refresh consensus, image-phase 404s, target series refreshes, stale debt, and content-ID anchors

Root cause

Provider results could contribute cross-provider IDs without provenance. A TVDB response could therefore supply a numeric TMDB cross-reference that was accepted as canonical even though TMDB had never confirmed it. When that value later returned 404, durable merge paths could restore it, and the stale-ID list treated the secondary cross-reference failure as if the matched item itself were stale.

Refresh candidate selection also compared replacement candidates against the raw stored item in one season/episode path, allowing the stale ID being repaired to veto its own replacement.

Impact

Matched items keep only provider identities confirmed by the provider that owns the namespace. Stale secondary cross-references no longer make otherwise healthy items appear stale, and scheduled refresh can safely repair a stale provider anchor without weakening ordinary identity protections.

Part of #268 (follow-up stale-ID hardening).

Validation

  • go test ./internal/metadata ./internal/contentid ./internal/api/handlers — pass
  • go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest run --new-from-rev=origin/main — 0 issues
  • cd web && pnpm run lint — pass with 158 existing warnings and 0 errors
  • cd web && pnpm run format:check — pass
  • make verify-local-paths — pass
  • git diff --check — pass

make lint remains red on the repository baseline with 305 findings across unrelated packages. The changed-code lint above is clean.

Adversarial review

The final review found four material issues: image-phase 404s were not reaching persistence guards, provider-native replacement did not always re-anchor provider-derived content IDs, target series refresh used the raw stale identity during candidate selection, and a candidate-finalization loop ended with a dead continue. All four were corrected and covered by regression tests. No material findings remain in the final diff review.

AI Disclosure

  • Tool(s): Codex desktop
  • Model(s): gpt-5.6-sol
  • Involvement: fully AI-generated
  • Adversarial review: Found and fixed four correctness/control-flow issues involving image-phase stale-ID persistence, provider-anchor replacement, target-refresh identity selection, and dead control flow; added regression coverage and found no remaining material issues.

Summary by CodeRabbit

  • Bug Fixes
    • Improved “stale provider ID” refresh logic to only act on actionable identifiers and avoid reapplying ineligible stale data.
    • Refresh now more precisely replaces outdated provider IDs while suppressing failed/non-actionable values and resolving conflicts using confirmed owning-provider IDs.
    • Quick library refresh better filters rejected/stale TMDB entries and ignores historical secondary stale IDs.
    • Added support for provider-anchored content IDs to preserve and interpret identifiers correctly.
    • Database updates allow multiple stale provider IDs per content/provider pair.
  • Tests
    • Expanded unit and database test coverage for stale filtering, provider-ID persistence, 404 state handling, refresh-debt syncing, and consensus/conflict resolution behavior.

@coderabbitai

coderabbitai Bot commented Jul 25, 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: bf8723a2-6905-4b8a-811c-0927576879bb

📥 Commits

Reviewing files that changed from the base of the PR and between dcb9633 and b0df73e.

📒 Files selected for processing (1)
  • migrations/sql/20260726090943_allow_multiple_stale_provider_ids.sql

📝 Walkthrough

Walkthrough

This PR adds actionable stale provider-ID detection, owning-provider conflict resolution, and propagation of recorded stale IDs and replacements through metadata refresh, persistence, API filtering, quick refresh, and refresh-debt evaluation.

Changes

Provider ID refresh handling

Layer / File(s) Summary
Actionable stale-ID evaluation
internal/contentid/..., internal/metadata/stale_media_id_repo.go, internal/api/handlers/libraries.go, internal/adminjob/...
Provider anchors, stored identifiers, status, and stale records determine which entries remain actionable.
Confirmed provider-ID consensus
internal/metadata/match_candidates.go, internal/metadata/service.go, internal/metadata/id_consensus_test.go, internal/metadata/match_candidates_test.go
Owning-provider confirmations resolve supported conflicts, preserve confirmed IDs, and track replaced keys.
Refresh stale-state propagation
internal/metadata/types.go, internal/metadata/service.go, internal/metadata/provider_id_integrity.go, internal/metadata/stale_media_id_repo.go, migrations/sql/...
Recorded stale IDs, provider 404s, replacements, reanchoring, merge behavior, and composite stale-ID persistence are updated across refresh paths.
Refresh and persistence validation
internal/metadata/*_test.go, internal/adminjob/library_refresh_language_test.go
Scheduled refresh, 404, identity, episode bootstrap, quick refresh, consensus, and refresh-debt scenarios validate the new behavior.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MetadataService
  participant StaleMediaIDRepository
  participant ProviderSearch
  participant MetadataPersistence
  MetadataService->>StaleMediaIDRepository: load recorded stale provider IDs
  MetadataService->>ProviderSearch: refresh with stale IDs suppressed
  ProviderSearch->>MetadataService: return confirmed IDs or 404 results
  MetadataService->>MetadataPersistence: apply replacements and persist
Loading

Possibly related PRs

Suggested labels: v1

Suggested reviewers: quick104

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.55% 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 title clearly matches the main metadata change: preventing stale cross-provider IDs.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@Rhainland
Rhainland marked this pull request as ready for review July 25, 2026 20:47
@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 25, 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 (1)
internal/metadata/types.go (1)

263-265: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the three provider-ID bookkeeping maps. quarantinedProviderIDKeys, replacedProviderIDKeys, and recordedStaleProviderIDs now drive reanchoring, merge deletion, and suppression with distinct semantics; a one-line comment each prevents future misuse.

🤖 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/metadata/types.go` around lines 263 - 265, Document the three
bookkeeping fields near quarantinedProviderIDKeys, replacedProviderIDKeys, and
recordedStaleProviderIDs with one-line comments describing their distinct roles
in reanchoring, merge deletion, and suppression, respectively.
🤖 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/service.go`:
- Line 1594: Update hasProviderIDRefreshDebt to retain provider_id_incomplete
only when an item has no provider IDs at all or has confirmed provider-ID data
indicating a missing refresh target. Treat items containing only TVDB/IMDB, and
TMDB-only detail responses with no TVDB, as missing-only cross-provider siblings
after dropUnconfirmedCrossProviderIDs, so they do not create permanent debt.

---

Nitpick comments:
In `@internal/metadata/types.go`:
- Around line 263-265: Document the three bookkeeping fields near
quarantinedProviderIDKeys, replacedProviderIDKeys, and recordedStaleProviderIDs
with one-line comments describing their distinct roles in reanchoring, merge
deletion, and suppression, respectively.
🪄 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: 514de3b1-09b8-4e2e-a1c1-e312a257cd55

📥 Commits

Reviewing files that changed from the base of the PR and between 10394b0 and 94f91b0.

📒 Files selected for processing (13)
  • internal/api/handlers/libraries.go
  • internal/contentid/contentid.go
  • internal/contentid/contentid_test.go
  • internal/metadata/id_consensus_test.go
  • internal/metadata/match_candidates.go
  • internal/metadata/match_candidates_test.go
  • internal/metadata/provider_id_persistence_test.go
  • internal/metadata/service.go
  • internal/metadata/service_test.go
  • internal/metadata/stale_media_id_repo.go
  • internal/metadata/stale_media_id_repo_test.go
  • internal/metadata/target_refresh_test.go
  • internal/metadata/types.go

Comment thread internal/metadata/service.go Resolved
@Quick104

Copy link
Copy Markdown
Contributor

Review

The problem this targets is real and the general shape — provenance on provider IDs, don't let a dead ID get restored by durable merge — is the right direction. But as written the diff regresses several behaviours well outside the stale-ID case, and a couple of them are load-bearing for identity. I don't think this is mergeable as-is.

Reviewed at 94f91b0. Findings 1 and 2 were reproduced with probe tests run against both this branch and main; the rest are read from the diff.


Blocking

1. Native confirmation is keyed off the provider's capability id, so only providers literally slugged tmdb/tvdb can ever establish a TMDB/TVDB identity.
internal/metadata/service.go:6811 — requiresNativeProviderConfirmation + candidateProviderIDConfirmed only accept an ID as confirmed when sr.Provider is itself in canonicalCandidateIDKeys (match_candidates.go:373-382). Every other metadata source — metadb, xattr, nfo search results, any third-party plugin — is now structurally incapable of confirming a TMDB or TVDB id.

Probe result: initial match of a movie through a single provider with capability id metadb returning {tmdb:999, imdb:tt7654321}. On main the item persists as movie-tmdb-999 with tmdb_id=999. On this branch it persists as movie-imdb-tt7654321 with tmdb_id="" and tvdb_id="". metadb is chain priority 1 for movie/series/season/episode, so a metadb-only chain now never produces a TMDB or TVDB id for any newly matched item, and the content_id silently changes namespace. Everything keyed on tmdb_id (image cache jobs, Jellyfin ProviderIds, dedup, client deep links) loses the identity.

The provenance signal you want is "did the provider that owns this namespace return it", which isn't the same as "is the provider's capability id equal to the namespace". A metadb result carrying a TMDB id it looked up is first-party for that id in the way that matters here.

2. Content-ID re-anchoring is no longer gated on manual refresh — background jobs can now rename a client-visible content_id.
internal/metadata/service.go:1139. main required req.Mode == ModeManualRefresh (old service.go:2099); shouldReanchorProviderContentID now also fires on any mode when contentIDAnchorIsRecordedStale is true, and a stale_media_ids row from an earlier run is enough.

Probe: item movie-tmdb-777 (tmdb=777, imdb=tt0000777) plus a stale row {tmdb:777} from a previous run. A ModeScheduledRefresh whose chain has no tmdb-slugged provider suppresses tmdb from the accumulator, the anchor reads as stale, and reanchorContentID moves the row to movie-imdb-tt0000777. A background job renaming a client-visible id is a much bigger blast radius than the bug being fixed. For a series it's worse: renameContentID only moves the parent, so every season/episode content_id keeps embedding the old anchor (season-tvdb-OLD-1, …).

3. Same change breaks the documented contract of POST /admin/items/{id}/match/apply.
internal/api/handlers/admin_match.go:150 says "preserving the original content_id", but ModeIdentify now reaches the re-anchor path via the same predicate. Applying a match to an item whose anchor has a stale row renames it; the web UI navigates back to the original id and 404s, and any client-held reference breaks.

4. dropUnconfirmedCrossProviderIDs kills the bootstrap path the season/episode chain depends on.
internal/metadata/service.go:1594. Stripping cross-references from a provider's Phase-2 detail response removes the documented "feed new IDs to subsequent providers" behaviour. Admin identifies a series with only a TMDB id (ModeIdentify runs no search phase, so accumulatedIDs has no tvdb); TMDB's GetMetadata returns {tmdb:X, tvdb:Y}; tvdb=Y is deleted. Phase 4a/4b then call the TVDB episode provider (series/season/episode priority 2) with no tvdb id, so GetSeasons/GetEpisodes return nothing and tvdb_id is never persisted. Same loss in resolveSeriesRefreshProviderIDs, which feeds fetchTargetSeasonResults.

Search-phase cross-references and detail-phase cross-references aren't the same trust problem — the detail response came from a provider you already resolved an identity with.

5. A single provider 404 now permanently deletes the canonical provider ID, including a 404 from the image phase.
internal/metadata/service.go:2198. isProvider404 is a substring match on "HTTP 404" (service.go:220), and plenty of providers return 404 for "no artwork for this item" rather than "this item does not exist". With suppressProviderIDValues now applied to both durableIDs and existingResult.ProviderIDs, one image-phase 404 on a scheduled refresh clears tmdb_id on a healthy matched item and wipes its durable provider_ids row (ReplaceByContentID rewrites the whole set) — and combined with #2 can rename its content_id. TestProcess_ScheduledRefreshDoesNotRestoreProviderIDThat404sDuringImagePhase asserts this wipe as intended, which is where I'd start disagreeing: an artwork 404 isn't evidence the identity is dead. This needs to distinguish the phase, or the endpoint, before it's allowed to destroy identity.


Should fix

6. applyProvider404sToAccumulator clobbers the previously recorded stale value, which re-opens the exact restore this PR is about.
internal/metadata/service.go:1119 overwrites recordedStaleProviderIDs[provider] with this run's 404. Sequence: stale_media_ids holds {tmdb:111} from an earlier empty-metadata run (so provider_ids still has tmdb=111); this run suppresses 111, search adopts replacement tmdb=222, Phase 2 GetMetadata(222) 404s. recordedStaleProviderIDs[tmdb] becomes 222, so the suppressProviderIDValues(durableIDs, …) at line 2198 no longer matches 111 — durableIDs merges 111 back in and the known-dead value is re-persisted. Merge the sets rather than overwrite.

7. IsActionableStaleProviderID hides exactly the case the stale list exists for.
internal/api/handlers/libraries.go:2390 compares the stale row against media_items.tmdb_id/tvdb_id/imdb_id, but the motivating scenario — a folder named with a wrong TMDB id — fails initial match, so handleProvider404 records stale_media_ids{content_id: local-xxx, provider: tmdb, provider_id: 999} and processInternal returns early with tmdb_id still ''. GET /libraries/stale-ids now filters that row out (no provider anchor on local-xxx, '999' != '') and currentStaleRefreshDebtReason returns 0, clearing RefreshDebtReasonStaleProviderID. The admin loses the surface showing the bad ID and the item stops being prioritised for repair — see your own comment at service.go:1214-1216.

8. The predicate isn't applied to the SQL that actually drives the repeated work.
internal/adminjob/library_refresh.go:124 still selects any item with any stale_media_ids row: EXISTS (SELECT 1 FROM stale_media_ids smi WHERE smi.content_id = mi.content_id). So a series matched on tvdb=405851 with a stale {tmdb:12236904} cross-reference keeps landing in every quick refresh batch, while #7 hides it from the admin list. The wasted refresh cycles persist and are now invisible. The predicate got applied at three Go call sites but not to the query that causes the churn.

9. Case-sensitivity split in IsActionableStaleProviderID.
internal/metadata/stale_media_id_repo.go:30 — the anchor branch compares IMDb ids case-sensitively while the column branch uses EqualFold. Item movie-imdb-tt0133093 with a legacy empty imdb_id and a stale row {imdb, 'TT0133093'}: anchor branch fails on case, column branch EqualFold('TT0133093', '') also fails, row hidden. The new test only covers the populated-column case.


Minor

  • internal/metadata/service.go:1606 — accumulatedIDs = accumulator.ProviderIDs after Phase 2 resurrects IDs that handleProvider404 dropped for non-durable slugs. A metadb 404 deletes the key from the pre-Phase-2 map, but isDurableProviderSlug("metadb") is false so provider404s stays empty and applyProvider404sToAccumulator no-ops; Phase 3 images and Phase 4 seasons then query with an id already known to 404.
  • internal/metadata/service.go:1104 — contentIDAnchorIsRecordedStale re-implements the anchor-vs-stale comparison IsActionableStaleProviderID already does, with different semantics (no IMDb case-fold). These will drift.
  • internal/metadata/service.go:3219 — resolveSeriesRefreshProviderIDs issues two separate stale_media_ids queries per call (lines 3164 and 3219) via suppressRecordedStaleProviderIDs, which is what loadRecordedStaleProviderIDs + suppressProviderIDValues were introduced to avoid. Load once like prepareProcessRequest does.
  • internal/metadata/service.go:1605 — applyProvider404sToAccumulator is called twice (1605 and 1751) where the first only needs the suppression half. The doc comment at 1748-1750 says the bookkeeping happens "only after all phases have completed", so the earlier call reads as violating its own contract and the two sites will diverge.

Happy to take another pass once 1/2/4/5 have a direction. My suggestion on #2 and #3 specifically: keep re-anchoring gated on an explicit user action and treat "anchor is stale" as a reason to surface the item, not to rename it behind the user's back.

Review performed with Claude Code (claude-opus-5); findings 1 and 2 confirmed by running probe tests against this branch and main, the rest read from the diff.

@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 (1)
internal/metadata/stale_media_id_repo.go (1)

109-120: 🚀 Performance & Scalability | 🔵 Trivial

Unbounded retention of rejected provider-ID values.

Each distinct rejected (provider, provider_id) pair is now persisted forever with no cap or expiry. For items that get repeatedly (mis)matched over time (e.g. successive manual identify attempts with different candidate IDs), stale_media_ids rows per (content_id, provider) can grow without bound, inflating table size and the correlated subqueries in ListLibraryItems/refresh-debt sync that scan by content_id.

Consider capping retained values per (content_id, provider) (e.g. keep only the N most-recently-seen) or adding a periodic cleanup job for very old, no-longer-anchored rejections.

🤖 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/metadata/stale_media_id_repo.go` around lines 109 - 120, Update
StaleMediaIDRepository.Upsert to prevent unbounded stale_media_ids growth per
(contentID, provider), retaining only a bounded number of the most recently seen
provider IDs or applying the established expiry/cleanup mechanism. Ensure the
cleanup preserves the newly upserted rejection and does not remove current
anchored entries.
🤖 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 `@migrations/sql/20260726090943_allow_multiple_stale_provider_ids.sql`:
- Around line 1-22: Update the migration’s Up and Down paths to use concurrent
unique-index creation followed by attaching each index with ALTER TABLE ... ADD
CONSTRAINT ... PRIMARY KEY USING INDEX, preserving the existing key columns and
rollback deduplication. Add the Goose NO TRANSACTION directive so CREATE UNIQUE
INDEX CONCURRENTLY executes outside a transaction, and ensure obsolete
primary-key constraints are dropped appropriately before attaching the
replacement indexes.

---

Nitpick comments:
In `@internal/metadata/stale_media_id_repo.go`:
- Around line 109-120: Update StaleMediaIDRepository.Upsert to prevent unbounded
stale_media_ids growth per (contentID, provider), retaining only a bounded
number of the most recently seen provider IDs or applying the established
expiry/cleanup mechanism. Ensure the cleanup preserves the newly upserted
rejection and does not remove current anchored entries.
🪄 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: 8a965843-4a79-45ee-9095-118e95559507

📥 Commits

Reviewing files that changed from the base of the PR and between 94f91b0 and dcb9633.

📒 Files selected for processing (15)
  • internal/adminjob/library_refresh.go
  • internal/adminjob/library_refresh_language_test.go
  • internal/api/handlers/libraries.go
  • internal/metadata/identify_stale_id_test.go
  • internal/metadata/match_candidates.go
  • internal/metadata/match_candidates_test.go
  • internal/metadata/provider_404_test.go
  • internal/metadata/provider_id_integrity.go
  • internal/metadata/provider_id_persistence_test.go
  • internal/metadata/service.go
  • internal/metadata/service_test.go
  • internal/metadata/stale_media_id_repo.go
  • internal/metadata/stale_media_id_repo_test.go
  • internal/metadata/types.go
  • migrations/sql/20260726090943_allow_multiple_stale_provider_ids.sql
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/api/handlers/libraries.go
  • internal/metadata/types.go
  • internal/metadata/stale_media_id_repo_test.go
  • internal/metadata/service.go

ALTER TABLE ... ADD PRIMARY KEY builds the index under ACCESS EXCLUSIVE,
blocking reads and writes on stale_media_ids for the whole build. Create the
wider unique index with CREATE UNIQUE INDEX CONCURRENTLY and attach it with
ADD CONSTRAINT ... PRIMARY KEY USING INDEX instead; all three key columns are
already NOT NULL, so the attach is metadata-only. Same treatment on the
rollback path, plus the repo's INVALID-remnant cleanup so a failed concurrent
build is not silently accepted by IF NOT EXISTS.

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

Copy link
Copy Markdown
Contributor

Re-review at dcb9633 (+ b0df73e)

Re-checked all thirteen findings from the previous pass. All addressed — and the fixes went at the mechanism rather than the symptom, which is the right call.

Blocking — all resolved

  1. Native confirmation gate — requiresNativeProviderConfirmation and candidateProviderIDConfirmed are gone. ConfirmedProviderIDs now only arbitrates conflicting cross-references instead of gating every ID, so metadb/nfo/plugin results can establish a TMDB or TVDB identity again. This was the fix I was hoping for: the provenance signal is used where two sources disagree, not as an admission test.
  2. Re-anchoring — shouldReanchorProviderContentID is back to !isNew && mode == ModeManualRefresh && contentid.IsProviderAnchored(...), byte-for-byte main's condition. Background jobs can't rename a content_id again.
  3. match/apply contract — falls out of 2; ModeIdentify no longer reaches the re-anchor path.
  4. dropUnconfirmedCrossProviderIDs — removed entirely, so the Phase-2 → Phase-4 TVDB bootstrap is intact.
  5. Image-phase 404s — split into handleProvider404 (search + item metadata, identity evidence, destructive) and handleScopedProvider404 (images, seasons, episodes, log-only). Artwork and child-fetch 404s can no longer delete a canonical provider ID. The comment at service.go:1655-1659 states the rule explicitly, which is worth keeping.

Should fix — all resolved

  1. Stale-value clobbering — map[provider]string became providerIDValueSet (map[provider]set-of-values), and provider404State separates dropped (suppress for later phases) from stale (persist to the negative cache). Values accumulate instead of overwriting, so an older known-dead ID can't slip back in behind a newer one. This is the change that required the composite primary key, and it's the correct root fix.
  2. Unmatched items hidden from the stale list — IsActionableStaleProviderID now falls through to !EqualFold(item.Status, matched), and both call sites (libraries.go:2391, service.go:3087) supply Status. The skeleton-item case the list exists for is surfaced again.
  3. Refresh SQL predicate — now mirrored into ListLibraryItems. Verified against a real database rather than by reading: TestQuickRefreshIgnoresHistoricalSecondaryStaleIDs passes with SILO_TEST_DATABASE_URL set, so the predicate parses and behaves.
  4. IMDb case split — providerIDValuesEqual / normalizeProviderIDComparisonValue normalize both the anchor and column branches.

Minor — all resolved

Post-Phase-2 resurrection (dropped now records non-durable slugs too), the duplicated contentIDAnchorIsRecordedStale predicate (removed), the double stale-ID query in resolveSeriesRefreshProviderIDs (loads once), and the double applyProvider404sToAccumulator call (now single, at service.go:1660).


CodeRabbit's migration comment — handled in b0df73e

Pushed to this branch rather than bouncing it back. ALTER TABLE ... ADD PRIMARY KEY was building the index under ACCESS EXCLUSIVE; it now uses CREATE UNIQUE INDEX CONCURRENTLY + ADD CONSTRAINT ... PRIMARY KEY USING INDEX under -- +goose NO TRANSACTION, on both the up and down paths. All three key columns were already NOT NULL in 036_stale_media_ids.sql, so the attach is metadata-only. Added the INVALID-remnant cleanup that 20260713233000_episode_search_indexes.sql established, since IF NOT EXISTS otherwise accepts a failed concurrent build.

Verification

Against pgvector/pgvector:pg18, matching docker-compose.yml:

  • --migrate-only over the full chain: database migrations applied, and \d stale_media_ids reports "stale_media_ids_pkey" PRIMARY KEY, btree (content_id, provider, provider_id)
  • up → down → up round-trip: down dedups to one row per (content_id, provider) and restores the two-column key; re-running up is safe
  • multi-value insert + ON CONFLICT (content_id, provider, provider_id) DO UPDATE both behave as the Go callers expect
  • make migrate-validate — pass
  • go test ./internal/metadata ./internal/contentid ./internal/adminjob with SILO_TEST_DATABASE_URL set — pass, including the DB-backed tests that skip without it
  • golangci-lint run --new-from-rev=$(git merge-base origin/main HEAD) — 0 issues
  • make verify-local-paths — pass
  • gofmt -l — clean across the changed packages

One note: internal/api/handlers has a failing test, TestHandleReplanPlaybackV3SeekFailureRecoveryNeverChangesMediaVersion. It fails identically on origin/main at 02203d9e, so it's pre-existing and unrelated to this branch — but it's red on main right now and worth a separate look.

No remaining findings from me. Ready to merge once main is caught up.

Review and the b0df73e migration change performed with Claude Code (claude-opus-5). Migration behaviour verified by applying it to a real PostgreSQL 18 instance; test and lint output above is real, not reconstructed.

@Quick104
Quick104 merged commit 99d2056 into Silo-Server:main Jul 26, 2026
5 checks passed
cursor Bot pushed a commit to Prairie-Server/prairie-server that referenced this pull request Jul 26, 2026
…er#480)

Bring in Silo metadata stale-ID prevention (contentid + multi-row stale
provider IDs). Resolve import conflicts to prairie-server module paths.

Co-authored-by: Jonah May <[email protected]>
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