Skip to content

feat(catalog): deterministic cross-server content_id - #155

Merged
Quick104 merged 11 commits into
mainfrom
feat/deterministic-content-id
Jun 15, 2026
Merged

Quick104 merged 11 commits into
mainfrom
feat/deterministic-content-id

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Two feature commits: deterministic, cross-server content_id (a derivation core, generation wiring, a hot-query fast path, and a collision-safe value-remap migration), then an online re-ID that promotes untagged items to their deterministic id at first match.

Plus two follow-up commits from review: fix(catalog): harden content_id parsing and merge per review (the CodeRabbit findings — stricter anchored-id validation, frozen precedence, fail-closed canonicalize) and refactor(contentid): URL-safe "-" separator in content_id (see the separator note below).

Scope: id-system refactor (how content_id is minted/stored), not a new user-facing endpoint or feature — so it proceeds under the "bug fixes, refactors … proceed normally" carve-out of the v1 scope gate (docs/architecture/v1-scope.md is not yet locked). It lays groundwork for future cross-server share/sync, which will be filed as its own v1 capability proposal.

Problem

The same title on two servers was treated as two unrelated items. Every logical movie, show, season, and episode was stamped with a per-server numeric id minted locally at scan time. Because that id is the anchor everything hangs off — artwork, metadata, watch history, progress, favorites, ratings, collections, credits — two servers holding the identical movie shared none of that state. Anyone operating more than one Silo, or trying to move/sync a profile's history between servers, saw the same film or show show up as a stranger on the other side: no resume point, no watched flags, no carried-over ratings.

There was no stable identity to build cross-server features on. Because the id was a time-ordered local counter, nothing about it could be reproduced on another machine, so any future "share/sync across servers" work had no ground truth to key on.

Solution

The fix replaces the per-server counter with a structured natural key derived from the provider IDs already present in the library (movie-tmdb-228064, series-tvdb-296762, episode-tvdb-296762-1-5, local-<hash> fallback). Two servers that see the same tags mint the same id with no API call.

Separator note (post-review): the component separator is -, not the : shown in earlier revisions. We switched it for readability/operability. - is an RFC 3986 unreserved character, so a content_id is URL-safe verbatim: it needs no percent-encoding and doubles as its own tidy path segment — /item/series-tvdb-296762 — identical to the value stored in the database, instead of the %3A-escaped /item/series%3Atvdb%3A296762 a colon produces. The stored value and the URL value are the same string, so there is no encode/decode boundary and an operator can grep an id straight out of a URL or log. Every component is [a-z0-9]+ (or tt+digits), so - is an unambiguous delimiter. Structure and guarantees are unchanged.

feat(catalog): deterministic cross-server content_id

Derivation core — internal/contentid/contentid.go

ForMovie/ForSeries/ForSeason/ForEpisode/ForLocal, the SeriesIDFromContentID string transform, and frozen provider precedence (movies tmdb → imdb → tvdb; series/season/episode tvdb → tmdb → imdb, matching where Radarr/Sonarr reliably tag). The load-bearing invariant: an episode/season id embeds its series anchor, so the show is a pure string transform of the episode id — no catalog lookup. SchemeVersion = 1 freezes format + precedence as a code constant so the population is never mixed-version.

Generation wiring — internal/metadata/service.go

deriveLogicalContentID/deriveSeasonContentID/deriveEpisodeContentID replace idgen.NextID() at every mint site (skeleton creation, provider-match at service.go:1499, explicit + implicit seasons, episodes, scanner-fallback episodes). Tagged libraries get their deterministic id at scan time; untagged new items get a path-derived local- id. Convergence of same-title items on one server is preserved by the existing dedup (findExistingByProviderIDs) plus UpsertTx's ON CONFLICT (content_id) DO UPDATE backstop.

Hot watch-history query — internal/catalog/history_source.go

display_id resolves an episode history row to its show via seriesFromAnchoredEpisodeExpr (pure split_part transform) for provider-anchored ids, probing only the media_items PK. Legacy/local- ids still fall through the episodes join, which is null-poisoned for anchored ids so the planner never descends episodes_pkey for them.

Migration (value remap) — migrations/sql/20260612130000_deterministic_content_id.sql

Collision-safe value remap (Sonyflake → structured key) across the dynamically-enumerated reference graph (65 columns) with COLLATE "C", FK drop/recreate, trigger quarantine, a retained audit map, and a working down. Collisions and anchorless/non-movie-series items are detected and kept on Sonyflake — the migration never merges or drops a row. Approach chosen over a hand-listed column set so a missed soft-reference can't silently orphan rows; the value remap is self-protecting, so over-inclusion is safe.

feat(catalog): re-ID untagged items to deterministic content_id at first match

Tagged libraries are born with the right id at scan time, but an untagged file gets a path-derived local- id and only learns its provider IDs later, when the match worker confirms a result. A single gate inside mergeAndPersist (canonicalizeLocalContentID) promotes that placeholder to its deterministic id at the moment of first confirmed match: if the deterministic id is free the row is renamed in place (the DB moves every child row via ON UPDATE CASCADE, so it is a handful of rows for a fresh skeleton, not the full-table remap the migration does); if a row already sits at that id the two are the same logical item and the existing merge path (rebindItemToExistingItem) folds them together. The guard is a single IsLocal prefix check, so tagged content and all refreshes pay nothing, and the promotion is self-healing — a partial run simply re-runs on the next match.

SCAN a new file                          ← unchanged, still no network call
      │
      ▼
createOrFindSkeleton ──► tag?  YES ► movie-tmdb-123   NO ► local-<hash>
      │
      ▼
(later) match worker → mergeAndPersist
      │
      ▼
┌─────────────────────────────────────────────────────────┐
│ canonicalizeLocalContentID                               │
│                                                          │
│  Is the id still local- AND do we now have provider IDs? │
│        │ no  → do nothing, carry on                      │
│        │ yes                                             │
│        ▼                                                 │
│  Does a row already sit at movie-tmdb-123 ?              │
│        ├─ yes → MERGE this row into it  (existing code)  │
│        └─ no  → RENAME local-<hash> → movie-tmdb-123     │
│                   │                                       │
│                   ▼                                       │
│           DB auto-moves all child rows (ON UPDATE CASCADE)│
└─────────────────────────────────────────────────────────┘
      │
      ▼
rest of mergeAndPersist runs with the corrected id
(title, artwork, cast, episodes — all written under movie-tmdb-123)

The rename primitive (silo_rename_content_id, in internal/metadata/canonicalize.go) reuses the migration's catalog-driven column enumeration so the two stay in lockstep, and is added alongside the ON UPDATE CASCADE clauses in migrations/sql/20260614120000_content_id_online_reid.sql. ON UPDATE CASCADE only fires when a content_id is updated (essentially never outside this promotion), so there is no steady-state read/write cost; the one-time cost is the FK drop/recreate during the migration.

Performance — measured at production scale

Measured on an isolated, prod-tuned PostgreSQL 18 instance (shared_buffers=4GB) loaded with an exact-cardinality copy of production (cprod-postgres): 184k items, 1.93M episodes, 775k watch-history rows / 162 profiles. "Before" reproduces production today (Sonyflake numeric content_id, en_US.utf8); "after" applies this PR's structured-key remap + COLLATE "C". The 100-client load test ran on the isolated instance, never against production. Every metric improves — this is a speedup, not a downgrade.

1. content_id index-probe cost — 300k forced point lookups over 1.9M keys (the operation the hot paths are built from):

The last three columns are the point: speed alone wasn't the goal, so the two faster schemes were rejected for giving up properties the feature exists for. ✓ = has the property, ✗ = lacks it.

Key scheme Index size µs / probe vs today Cross-server deterministic Zero-join show transform Human-readable
Sonyflake text, en_US.utf8 (today) 74 MB 5.05 1.00× ✗ ✗ ✗
128-bit hash bytea(16) 74 MB 1.80 2.81× ✓ ✗ ✗
bigint surrogate (≈ old Sonyflake) 41 MB 1.23 4.11× ✗ ✗ ✗
Structured content_id + COLLATE "C" (this PR) 84 MB 1.86 2.71× ✓ ✓ ✓

The locale-aware strcoll on today's text column is the bottleneck; COLLATE "C" (byte-wise memcmp) removes it. The structured key lands within 3% of a 128-bit hash and within 1.5× of a raw bigint, and is the only all-✓ row:

  • 128-bit hash bytea(16) — cross-server deterministic (it hashes the same natural key), but an opaque digest can't be string-transformed, so episode→series needs a catalog join (no zero-join hot path), and it isn't legible in logs, URLs, or psql.
  • bigint surrogate — fast only because it's 8 bytes; it's the status-quo serial: per-server (not reproducible elsewhere), no embedded anchor to transform, not meaningful to a human.

Index grows ~14% (84 vs 74 MB), immaterial.

2. Real history-page query — heaviest profile (25,384 rows), from buildHistoryDisplayBaseQuery, warmed median of 6:

State Latency episodes_pkey probes Speedup
Before (Sonyflake + en_US.utf8) 385 ms 25,348 1.00×
This PR (structured + COLLATE "C") 150 ms 2,775 2.57×

COLLATE "C" removes the locale-aware comparison cost, and structured keys let anchored episode ids skip the episodes_pkey descent (25,348 → 2,775 probes, the M1 fix).

3. Concurrency — pgbench, workload randomized across 150 real profiles (≥200 history rows each), 20 s per level:

Concurrency Before (lat / tps) This PR (lat / tps) Throughput gain
1 43.8 ms / 23 13.0 ms / 77 3.4×
10 50.9 ms / 196 21.1 ms / 473 2.4×
50 152 ms / 329 91 ms / 548 1.7×
100 311 ms / 321 181 ms / 551 1.7×

Comparison cost is pure CPU, so it dominates under concurrency: the cheaper COLLATE "C" comparisons raise the throughput ceiling from ~321 to ~551 tps and cut tail latency at 100 concurrent users by 42%. (Warmed — dataset fits in shared_buffers; isolated instance shares a host with production, so the before/after ratios are the robust result, not absolute tps.)

Risk / follow-ups

  • Re-ID-on-match for untagged-then-matched items now runs inline at first confirmed match (see the Re-ID subsection above). The one remaining case is a series that accumulated season/episode rows before it matched: those children keep their Sonyflake ids until a follow-up recomposeSeriesChildIDs pass re-derives them. At first match the children usually do not exist yet, so this is rare; it is not yet wired. Promotion also changes a primary key, so an item's anchored id can vary during its first-match window (accepted — no alias/redirect table).
  • Cross-provider reconciliation (a series tagged tmdb-only on one server, tvdb-only on another) is not yet handled — both paths derive from the denormalized provider columns; the proper fix consults media_item_provider_ids.
  • The migration runs in one transaction holding AccessExclusive locks for the COLLATE rewrite and remap — run off-peak; very large installs (10–50M rows) should use the batched procedure noted in the migration header.
  • local- ids hash the absolute path, so a same-server remount re-IDs local items (acceptable for the best-effort local namespace).
  • Client coordination. content_id stays a string in every API response (no additive-only violation), but the value-remap migration changes the values clients use as their anchor. Any silo-android / silo-apple state keyed on the old Sonyflake ids (cached offline downloads, stored references) is stale after migration and needs a re-fetch/invalidation path — tracked as client follow-up, not in this PR.

Verification

  • Unit tests: internal/contentid (derivation, precedence, the composition↔transform round-trip invariant, edge cases) pass; internal/catalog and internal/metadata suites pass with updated history-query golden fragments.
  • go build ./internal/..., go vet, gofmt -l all clean.
  • Migration on real schema (PG18 + pgvector): full migration chain plus this one applies, reverts (down), and re-applies (up) cleanly — recollates 65 columns, drops/recreates 27 FKs and all episode_catalog triggers, retains only the audit map.
  • Online re-ID migration (20260614120000_content_id_online_reid): applies on the real schema after the value-remap migration; every content_id-family FK gains ON UPDATE CASCADE while keeping its original ON DELETE action (e.g. episodes_series_id_fkey becomes ON UPDATE CASCADE ON DELETE CASCADE); make migrate-validate passes; full up/down/up cycle is clean (down drops silo_rename_content_id and strips only ON UPDATE CASCADE).
  • Online re-ID functional test: silo_rename_content_id on a local series moves the media_items PK, cascades seasons.series_id/episodes.series_id, sweeps the provider-id soft references, and correctly leaves the children's own (Sonyflake) ids untouched (the deferred recomposeSeriesChildIDs case); a local movie rename moves the item and its provider ids; ON DELETE CASCADE still fires (delete leaves 0 orphans).
  • Migration data-bearing test: correct precedence; soft-reference + FK-child remap; 0 FK orphans; collisions/unmatched correctly stay on Sonyflake; the collision cascade keeps a unique episode of a colliding series off an orphaned anchor; down reverts values and collation.
  • Performance: benchmarked against an exact-cardinality copy of cprod-postgres (1.93M episodes, 775k history rows) — 2.57× faster history page, 1.7× throughput at 100 concurrent users, 2.7× cheaper per content_id probe (see Performance section).

AI-use disclosure

Implemented with AI assistance (Claude). An independent adversarial review (Fable 5) was run against the spec's required properties; its critical/major findings were fixed and re-validated, with the larger items recorded as the follow-ups above. Performance benchmarking was AI-assisted against an isolated copy of production data.

Summary by CodeRabbit

  • New Features
    • Added deterministic, provider-anchored identifiers for movies, series, seasons, and episodes to keep items consistent across server instances.
    • Canonicalizes local placeholder identifiers to deterministic provider identifiers during metadata ingestion.
    • Added reversible ID encoding support for compatibility item/season IDs.
  • Bug Fixes
    • Improved watch/history resolution for provider-anchored episode content so related items link correctly.
  • Documentation
    • Added a developer reference describing the deterministic identifier format and migration strategy.
  • Tests
    • Expanded coverage for deterministic ID composition/parsing/packing, codec behavior, history query generation, and migration timeout handling.
  • Chores
    • Added migrations to remap existing content_id values and enabled online re-ID with cascading updates; migration timeout is now configurable via an environment variable.

Replace per-server Sonyflake content_id with a structured natural key
derived from provider IDs (movie:tmdb:…, series:tvdb:…, episode:…,
local:… fallback), so two servers holding the same title share one
anchor for artwork, watch history, progress, favorites and ratings.

- internal/contentid: derivation core, SeriesIDFromContentID transform,
  frozen precedence, SchemeVersion=1, embedded-series-anchor invariant.
- internal/metadata/service.go: deterministic id at every mint site.
- internal/catalog/history_source.go: resolve show via string transform
  for anchored episode ids; skip the episodes_pkey probe.
- migrations/sql/20260612130000: collision-safe value remap across the
  65-column reference graph + COLLATE "C", FK/trigger handling, audit
  map, working down.

Benchmarked against an exact-cardinality copy of cprod-postgres
(1.93M episodes, 775k history rows): 2.57x faster history page, 1.7x
throughput at 100 concurrent users, 2.7x cheaper per content_id probe.
…rst match

Untagged libraries get a path-derived local: content_id at scan time and
only learn their provider IDs later, when the match worker confirms a
result. Previously that id was never folded back in, so untagged-then-matched
items kept a per-server local: placeholder forever and never converged across
servers (re-ID was deferred to a migration rerun).

mergeAndPersist now promotes a local: skeleton to its deterministic
provider-anchored id at the moment of first confirmed match, via a single
new gate (canonicalizeLocalContentID):

  - target id already taken  -> merge onto it (existing rebind machinery)
  - target id free           -> rename in place

The rename is a single SQL function (silo_rename_content_id); FK children
follow via ON UPDATE CASCADE added to the content_id family, so a fresh
skeleton moves a handful of rows rather than the full-table remap the bulk
migration does. The guard is one IsLocal prefix check, so tagged content and
all refreshes pay nothing, and the move is self-healing under retry.

Verified: gofmt/vet/build clean; migrate-validate passes; migration applies
on the real schema (up/down/up), FKs gain ON UPDATE CASCADE while keeping
ON DELETE; functional test confirms series PK move + series_id cascade +
provider-id sweep, and movie rename.

Follow-ups (noted in docs): recomposeSeriesChildIDs for a series that
accumulated episodes before matching; a lockstep test for the soft-ref list.
@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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

Introduces a new internal/contentid package for deterministic, cross-server stable content ID generation based on provider precedence, plus a reversible binary codec for jellycompat UUID packing. Two SQL migrations bulk-remap existing Sonyflake IDs to structured provider-anchored keys and add ON UPDATE CASCADE FKs plus a silo_rename_content_id function. The metadata service is updated to derive IDs deterministically across all create/persist/skeleton paths. Local IDs are promoted to provider-anchored targets on first confirmed match. The catalog history SQL is optimized to resolve provider-anchored episode display IDs via string transformation. Migration timeout handling becomes configurable. Architecture documentation details the design, implementation, migrations, and performance characteristics.

Changes

Deterministic Content ID System

Layer / File(s) Summary
contentid package: constants, constructors, predicates, and tests
internal/contentid/contentid.go, internal/contentid/contentid_test.go
New package defines SchemeVersion, provider token constants, ProviderIDs struct, provider-ID normalization/validation (IMDb lowercased/prefixed; TMDB/TVDB digits-only), ForMovie/ForSeries/ForSeason/ForEpisode/ForLocal constructors, SeriesIDFromContentID (parses and transforms provider-anchored season/episode IDs to owning series), IsProviderAnchored, IsLocal, and full unit test coverage including provider precedence, round-trip invariants, and collision resistance.
contentid binary codec: reversible packing for UUID storage
internal/contentid/binary.go, internal/contentid/binary_test.go
Implements reversible binary codec for jellycompat UUID packing. Pack encodes structured and local content IDs into compact byte form with strict validation of structure shape and numeric bounds. Unpack decodes and validates, reconstructing canonical text IDs with IMDB digit formatting. Helper functions implement provider/code mappings, anchored packing with digit trimming, numeric component parsing, two-uvarint decoding, and base-10 zero-padding. Tests verify round-trip invariants within 15-byte UUID budget and rejection of malformed inputs.
Bulk migration: remap Sonyflake IDs to structured keys
migrations/sql/20260612130000_deterministic_content_id.sql
Creates content_id_migration_map, derives deterministic provider-based IDs from tmdb_id/imdb_id/tvdb_id for media_items, composes season/episode IDs from mapped series anchors, detects and cascades collisions, discovers all content-id-holding columns via database catalog, drops FK constraints and triggers, remaps values idempotently in one pass per column, changes column collation to COLLATE "C", recreates triggers and FKs. Rollback reverses every step and documents post-cutover row consistency.
Online re-ID migration: ON UPDATE CASCADE + silo_rename_content_id
migrations/sql/20260614120000_content_id_online_reid.sql
Rebuilds all content_id-family foreign keys on media_items/seasons/episodes to include ON UPDATE CASCADE. Defines silo_rename_content_id(p_from, p_to) which updates non-FK-child content-id columns directly (soft-reference text columns and PK columns) and lets the cascade handle FK children. Down step drops the function and reverts FKs to their prior form without cascade.
Canonicalization and deterministic ID derivation helpers
internal/metadata/canonicalize.go, internal/metadata/service.go
Adds providerIDsStruct helper to convert denormalized provider ID maps to contentid.ProviderIDs. canonicalizeLocalContentID promotes local: IDs to provider-anchored targets by either merging into an existing row or renaming via silo_rename_content_id. renameContentID calls silo_rename_content_id with context wrapping. service.go adds import and deriveLogicalContentID (selects provider anchor or fallback), deriveSeasonContentID, deriveEpisodeContentID, firstNonEmpty, and normalizeItemTypeForContentID helpers.
Wire deterministic IDs into all create/persist paths
internal/metadata/service.go
mergeAndPersist canonicalizes local content IDs before merging durable provider IDs and uses deriveLogicalContentID for new item creation. persistSeasonsAndEpisodes replaces idgen.NextID with deterministic deriveSeasonContentID/deriveEpisodeContentID for explicit seasons, implicit seasons (derived from episode references), and new episodes. synthesizeFallbackSeriesStructure similarly derives fallback season/episode IDs deterministically. createOrFindSkeleton derives skeleton content_id deterministically from provider tags and a chosen local anchor path (file/folder/observed-root fallback) instead of using random ID generation.
Catalog history SQL: provider-anchored episode display resolution
internal/catalog/history_source.go, internal/catalog/history_source_test.go
buildHistoryDisplayBaseQuery resolves history_events.display_id via a new displayIDExpr that coalesces (1) series ID recovered from anchored episode IDs via seriesFromAnchoredEpisodeExpr string transform (converts episode-<p>-<sid>-... to series-<p>-<sid>), (2) episodes.series_id, (3) h.media_item_id as fallback. The LEFT JOIN episodes is null-poisoned for fully anchored episode IDs using anchoredEpisodePredicate to avoid unnecessary lookups. Test updated to assert new SQL fragments.
Jellycompat codec: reversible UUID packing for content IDs
internal/jellycompat/idcodec.go, internal/jellycompat/idcodec_test.go
Updates codec to support reversible UUID packing for content-id kinds. EncodeStringID attempts to pack content-id values into UUID format; DecodeStringID unpacks content-id UUIDs before falling back to numeric and reverse-map paths. Helpers validate kind types and re-pack to confirm UUID authenticity. Tests verify restart-safety across separate codec instances, legacy numeric ID round-trips, and reverse-map-dependent genre name handling.
Migration timeout: configurable context timeout via SILO_MIGRATE_TIMEOUT
internal/database/migrate.go, internal/database/migrate_timeout_test.go, cmd/silo/main.go
Adds MigrationTimeout() to parse SILO_MIGRATE_TIMEOUT env var with fallback to 5 minutes, and MigrationContext(ctx) to derive timeout or cancel-only context accordingly. Updates all three migration entry paths in cmd/silo/main.go to use database.MigrationContext(ctx) instead of fixed 5-minute timeouts. Comprehensive tests cover timeout parsing edge cases and context deadline behavior.
Architecture documentation: deterministic content_id design
docs/architecture/deterministic-content-id.md
Dev-facing reference describing the switch from per-server non-deterministic Sonyflake IDs to deterministic, provider-derived, structured natural keys. Documents problem statement, decision rationale, exact ID format (frozen scheme/separator, provider precedence rules), the load-bearing episode→series string transform invariant, implementation wiring across catalog/scanner/metadata, local ID promotion on first match, query optimizations, bulk migration approach with collision detection and safe rollback, collation requirements, online re-ID behavior via ON UPDATE CASCADE, measured performance impacts, known limitations/follow-ups, and prior-art/alternatives discussion.

Sequence Diagram(s)

sequenceDiagram
  participant MetadataService
  participant canonicalizeLocalContentID
  participant contentid
  participant silo_rename_content_id
  participant rebindItemToExistingItem

  rect rgba(100, 150, 255, 0.5)
    Note over MetadataService,rebindItemToExistingItem: mergeAndPersist – local ID promotion
    MetadataService->>canonicalizeLocalContentID: contentID is local: and item exists
    canonicalizeLocalContentID->>contentid: deriveLogicalContentID(providerIDs, fallbackPath)
    contentid-->>canonicalizeLocalContentID: targetID (provider-anchored or fallback)
    alt targetID row already exists
      canonicalizeLocalContentID->>rebindItemToExistingItem: merge local skeleton → existing row
    else targetID row is free
      canonicalizeLocalContentID->>silo_rename_content_id: UPDATE local: → targetID
      silo_rename_content_id-->>MetadataService: ON UPDATE CASCADE propagates to FK children
    end
    canonicalizeLocalContentID-->>MetadataService: updated contentID, existingItem, locked, durable IDs
  end

  rect rgba(100, 200, 150, 0.5)
    Note over MetadataService,contentid: persistSeasonsAndEpisodes – deterministic sub-IDs
    MetadataService->>contentid: deriveSeasonContentID(seriesID, seasonNumber)
    contentid-->>MetadataService: season-<provider>-<sid>-s<N>
    MetadataService->>contentid: deriveEpisodeContentID(seriesID, seasonNumber, episodeNumber)
    contentid-->>MetadataService: episode-<provider>-<sid>-s<N>e<M>
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~85 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.93% 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 accurately and concisely summarizes the main change: replacing per-server numeric content IDs with deterministic, provider-derived cross-server identifiers.
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
  • Commit unit tests in branch feat/deterministic-content-id

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

🤖 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/catalog/history_source.go`:
- Around line 228-230: The LIKE 'episode:%%' predicate in the CASE WHEN
condition is too broad and allows malformed episode IDs like episode:broken to
pass through, causing them to produce invalid series IDs and skip the episodes
fallback lookup. Tighten this predicate to match the full anchored-episode
format of exactly five colon-separated parts
(episode:<provider>:<seriesId>:<season>:<episode>) rather than just checking if
the string starts with episode:. This stricter validation should gate both the
null-poisoned LEFT JOIN to episodes and the call to
seriesFromAnchoredEpisodeExpr, ensuring only properly formatted anchored episode
IDs bypass the media_items lookup. Apply this same fix to all occurrences of
this pattern in the file where the anchored-episode predicate is used.

In `@internal/contentid/contentid.go`:
- Around line 71-74: The exported slice variables MovieProviderPrecedence and
SeriesProviderPrecedence can be mutated by any package at runtime, breaking the
deterministic behavior expected by the content ID scheme. Either make these
variables unexported by changing them to lowercase (movieProviderPrecedence and
seriesProviderPrecedence), or create unexported variables with the same names
and expose accessor functions like GetMovieProviderPrecedence() and
GetSeriesProviderPrecedence() that return copies of the slices instead of
references to the backing arrays. Choose one approach and apply it consistently
to both variables.
- Around line 234-250: The SeriesIDFromContentID function currently accepts
truncated or malformed season: and episode: IDs (such as "episode:tvdb:296762")
because it only validates the presence of provider and seriesId components, not
the complete arity required for these kinds. For both the SeriesIDFromContentID
function (at the point where it handles kindEpisode and kindSeason cases) and
the IsProviderAnchored function (which has the same issue at lines 261-276),
enhance the validation to ensure that season: and episode: prefixed IDs contain
the required numeric season/episode suffix components after the seriesId, and
validate that these suffixes are actually numeric before treating the ID as
valid and provider-anchored. This prevents malformed IDs from being accepted as
valid anchors.

In `@internal/metadata/canonicalize.go`:
- Around line 65-67: The GetByID call in the if condition treats all errors
identically, preventing distinction between not-found errors and real transient
failures. Additionally, the hardcoded false parameter for allowMatchedSource in
the rebindItemToExistingItem call prevents deletion of matched local sources
during refresh operations. Fix this by explicitly checking if the error from
s.itemRepo.GetByID is a not-found error (rather than treating all errors as if
the target doesn't exist), and change the allowMatchedSource parameter from
false to true in the rebindItemToExistingItem call to allow matched local
sources to be properly cleaned up during the merge.

In `@migrations/sql/20260612130000_deterministic_content_id.sql`:
- Around line 166-168: The `_cid_cols` cursor intentionally selects columns with
types 'text', 'varchar', and 'bpchar', but both the up and down migration ALTER
loops unconditionally convert all selected columns to 'text', which permanently
loses the original column type information and prevents proper down migration.
Modify the `_cid_cols` query to also capture the original typname as
declared_type, then update all ALTER COLUMN TYPE statements in the anchor
location (lines 166-168) and sibling locations (lines 255-258, 312-313, and
368-370) to use the captured declared_type instead of hardcoding 'text',
ensuring that each column retains its original declared type in both up and down
migrations.
🪄 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: 0e6778fc-a620-4667-b8db-4bb8407cebaf

📥 Commits

Reviewing files that changed from the base of the PR and between 44a1978 and 73106cd.

📒 Files selected for processing (8)
  • internal/catalog/history_source.go
  • internal/catalog/history_source_test.go
  • internal/contentid/contentid.go
  • internal/contentid/contentid_test.go
  • internal/metadata/canonicalize.go
  • internal/metadata/service.go
  • migrations/sql/20260612130000_deterministic_content_id.sql
  • migrations/sql/20260614120000_content_id_online_reid.sql

Comment thread internal/catalog/history_source.go Resolved
Comment thread internal/contentid/contentid.go Resolved
Comment thread internal/contentid/contentid.go Resolved
Comment thread internal/metadata/canonicalize.go Resolved
Address review feedback on the deterministic content_id work:

- history_source.go: gate the anchored-episode display-id transform on the
  full five-part episode shape (split_part parts 2-5 non-empty), not just the
  'episode:' prefix, so a malformed id can't transform to 'series:broken:' and
  vanish at the media_items join. Shared anchoredEpisodePredicate drives both
  the null-poisoned join key and the series-recovery expression.
- contentid.go: unexport the provider-precedence slices so no package can
  mutate the frozen SchemeVersion ordering at runtime.
- contentid.go: add parseAnchored to validate the exact per-kind arity and
  numeric season/episode suffixes; SeriesIDFromContentID and IsProviderAnchored
  now fail closed on truncated/malformed ids (e.g. "episode:tvdb:296762").
- canonicalize.go: distinguish catalog.ErrItemNotFound from transient lookup
  errors (a real error no longer masquerades as "target free"), and allow a
  matched local source to be consolidated onto the canonical row instead of
  orphaning a duplicate.
Use "-" instead of ":" to join content_id components
(movie-tmdb-228064, episode-tvdb-296762-1-5, local-<hex>). "-" is an RFC 3986
unreserved character, so a content_id is URL-safe verbatim: encodeURIComponent
is a no-op and the id is its own tidy path segment (/item/series-tvdb-296762)
with no %3A escaping. The stored value equals the URL value, so there is no
encode/decode boundary and an operator can grep the id straight out of a URL or
log. Every component is [a-z0-9]+ (or "tt"+digits), so "-" is unambiguous.

Pre-release format finalization: this branch is unmerged, so no deployed data
carries ":" ids — the migration mints the "-" form fresh and no re-migration is
needed. Still SchemeVersion 1.

- contentid.go: single `sep` constant drives construction and parsing so the two
  can never drift; all constructors/parsers and doc examples updated.
- history_source.go: split_part transform and the anchored-episode predicate use
  '-'; kept in lockstep with the package via a code comment.
- 20260612130000_deterministic_content_id.sql: derivation and season/episode
  composition emit '-'; LIKE filters match 'series-%'.
- docs/architecture/deterministic-content-id.md: format spec + rationale for the
  separator choice; this is the design doc the change is derived from.

Client-side: the web frontend treats content_id as an opaque string (no
splitting/regex), so no client changes are required; existing
encodeURIComponent call sites simply stop emitting %3A.
@CoffeeKnyte

Copy link
Copy Markdown
Contributor Author

Why this scheme generalizes (movies/shows today, more later)

A note on where this can go, since it's built to extend rather than be reworked:

Today it covers movies and shows well. Movies anchor on tmdb → imdb → tvdb, series/season/episode on tvdb → tmdb → imdb — the providers Radarr/Sonarr/Plex already tag reliably — and an episode/season key embeds its series anchor, so the show falls out by pure string transform (the zero-join history path).

New entity types are additive. The leading kind token (movie/series/season/episode/local) domain-separates the namespaces, so adding audiobook-…, ebook-…, podcast-…, music-… down the line is just a new kind token plus a precedence list for that type's providers (Audible, Google Books, MusicBrainz, …). Those types stay on Sonyflake for now; promoting any of them is a self-contained follow-up that touches no existing keyspace.

A new default metadata provider is also additive. Provider precedence is a frozen, ordered list under SchemeVersion. Introducing a new source — say MetaDB in future — and making it the default anchor is just prepending it to the relevant precedence list (plus its id validation in normalizeProviderID) and bumping SchemeVersion. That version bump is exactly what the value-remap migration machinery in this PR is built for: it re-derives every affected id, detects collisions, keeps un-derivable rows on their old id, and retains an audit map — so switching the default is a controlled, reversible remap rather than a flag day. Two servers that both adopt the new default still converge on the same id.

In short, the structure itself — kind-provider-id, frozen precedence, version-gated remap — is the extension point: broaden coverage by adding tokens/providers, not by reworking the anchor.

@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

Caution

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

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

206-212: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reject negative season/episode numbers before composing anchored IDs.

Line 211 and Lines 224-225 compose IDs from raw ints and return ok=true even for negative inputs. With sep = "-", a value like -1 injects an extra separator (e.g., malformed episode-tvdb-296762--1-5), which later fails anchored parsing and breaks the constructor/parser contract.

Proposed fix
 func ForSeason(seriesContentID string, seasonNumber int) (string, bool) {
+	if seasonNumber < 0 {
+		return "", false
+	}
 	body, ok := seriesBody(seriesContentID)
 	if !ok {
 		return "", false
 	}
 	return kindSeason + sep + body + sep + strconv.Itoa(seasonNumber), true
 }

 func ForEpisode(seriesContentID string, seasonNumber, episodeNumber int) (string, bool) {
+	if seasonNumber < 0 || episodeNumber < 0 {
+		return "", false
+	}
 	body, ok := seriesBody(seriesContentID)
 	if !ok {
 		return "", false
 	}
 	return kindEpisode + sep + body + sep +
 		strconv.Itoa(seasonNumber) + sep + strconv.Itoa(episodeNumber), true
 }

Also applies to: 219-226

🤖 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/contentid/contentid.go` around lines 206 - 212, The ForSeason
function and the related function at lines 219-226 (likely ForEpisode) do not
validate that season and episode numbers are non-negative, allowing negative
inputs to create malformed IDs with consecutive separators (e.g.,
`episode-tvdb-296762--1-5`) that break anchored parsing. Add validation in both
functions to check if the season/episode number is less than 0, and if so,
return an empty string and false before constructing and returning the ID,
similar to the existing check for the seriesBody validation.
🤖 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/architecture/deterministic-content-id.md`:
- Around line 357-358: Remove the stray XML closing tags that appear at the end
of the file. Delete the `</content>` and `</invoke>` closing tags that are
marked as accidental artifacts in the architecture documentation, as these XML
tags are not part of the markdown content and should not be in the published
document.
- Around line 84-90: Add language identifiers to three fenced code blocks in
docs/architecture/deterministic-content-id.md that are missing language tags to
comply with markdownlint rule MD040. Add the language identifier `text` after
the opening triple backticks at lines 84-90, 128-131, and 182-195 (changing ```
to ```text).

---

Outside diff comments:
In `@internal/contentid/contentid.go`:
- Around line 206-212: The ForSeason function and the related function at lines
219-226 (likely ForEpisode) do not validate that season and episode numbers are
non-negative, allowing negative inputs to create malformed IDs with consecutive
separators (e.g., `episode-tvdb-296762--1-5`) that break anchored parsing. Add
validation in both functions to check if the season/episode number is less than
0, and if so, return an empty string and false before constructing and returning
the ID, similar to the existing check for the seriesBody validation.
🪄 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: 5c8594a7-14f2-4bee-9843-87dbaecfd1ff

📥 Commits

Reviewing files that changed from the base of the PR and between 73106cd and f829794.

📒 Files selected for processing (7)
  • docs/architecture/deterministic-content-id.md
  • internal/catalog/history_source.go
  • internal/catalog/history_source_test.go
  • internal/contentid/contentid.go
  • internal/contentid/contentid_test.go
  • internal/metadata/canonicalize.go
  • migrations/sql/20260612130000_deterministic_content_id.sql
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/catalog/history_source_test.go
  • internal/catalog/history_source.go
  • internal/metadata/canonicalize.go
  • internal/contentid/contentid_test.go
  • migrations/sql/20260612130000_deterministic_content_id.sql

Add Cross-server deterministic / Zero-join show transform / Human-readable
columns to the index-probe-cost comparison so the trade-off is legible at a
glance: the 128-bit hash and bigint surrogate are faster but each give up a
load-bearing property, and the structured key is the only all-checkmark row.
Per CodeRabbit review: add 'text' language to three fenced code blocks
(MD040) and remove accidental </content></invoke> artifacts at EOF.

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

Review focused on the seams where remapping the universal anchor leaks into systems that consume content_id. The architecture is sound — provider-anchored natural key is the right model and matches Plex/Jellyfin prior art, the string-transform invariant and COLLATE "C" analysis hold up, and the prior CodeRabbit findings are addressed. Three issues below that need cross-package reasoning the bots don't do. Two have inline comments; the first can't (its file isn't in this diff).


1. (Major — robustness) jellycompat item-UUID decode regresses from stateless to in-memory-cache-dependent across restarts

internal/jellycompat/idcodec.go:82 EncodeStringID branches on whether the content_id parses as a uint64:

  • Before this PR content_ids were numeric Sonyflakes → they take the EncodeNumericID branch, so the client UUID is a pure bit-packing and DecodeID (idcodec.go:163) reverses it with zero state. Survives restarts.
  • After this PR content_ids are structured strings (movie-tmdb-228064) → they take the uuid.NewSHA1 branch and reversibility depends entirely on the in-memory c.reverse map (idcodec.go:91-95), which is empty after a process restart and only repopulated when an item is re-encoded during the current lifetime.

The decode sites are by-id URL fetches — DecodeStringID(EncodedIDItem, chi.URLParam(r, "id")) at handlers_items.go:441/645/1019/1114, plus images (images.go:96) and userdata (handlers_userdata.go:206). The codec is a process-lifetime singleton (router.go:261). So after a server restart, a Jellyfin client (JellyCon/Findroid/Infuse) that presents a previously-issued item/season UUID — resume-from-home, a deep link, a detail page, an image request — hits a cold map, the stateless decode fails, and it returns unknown compat id; the item effectively 404s until something re-lists it.

This is exactly the failure path the repo lists as a core priority ("predictable under load and during failures — session restarts, reconnects"), and the PR's disclosure understates it: it says caches "reset once," but this is an ongoing reversibility dependency on warm in-process state, not a one-time migration cost.

SHA1 isn't invertible and a full scan is O(n), so a real fix needs either a persisted uuid → content_id map (write-through on encode + lookup on decode-miss) or warming the map at startup from the catalog. Both have real tradeoffs — added DB write on the id-encode hot path, or boot latency + memory for millions of episode/season entries — so this deserves its own focused, benchmarked change rather than a drive-by edit to a shared hot-path codec. Not blocking the concept; should be resolved or explicitly tracked as a jellycompat follow-up before merge.

JOIN pg_type t ON t.oid = a.atttypid
WHERE c.relkind IN ('r', 'p')
AND n.nspname = 'public'
AND t.typname IN ('text', 'varchar', 'bpchar')

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.

(Major — data integrity) Array-valued soft reference trending_discover_snapshots.content_ids is silently skipped by the remap.

The migration's central safety claim is that the catalog-driven sweep is self-protecting and "a missed soft-reference can't silently orphan rows." Here's a concrete counterexample: trending_discover_snapshots.content_ids (migrations/sql/167_...:11) is a text[] of resolved library content IDs. It's excluded from this sweep on both axes — the type filter on this line is scalar (text/varchar/bpchar, so arrays don't match) and the name allowlist below has content_id, not the plural content_ids — and an array can't carry an FK, so nothing else touches it. After the remap those arrays hold stale Sonyflake ids that resolve to nothing.

Severity is bounded: internal/sections/trending_snapshot.go refreshes the table via INSERT … ON CONFLICT DO UPDATE, so it self-heals on the next snapshot refresh — trending/discover rows are just broken in the interim. But the "cannot orphan" invariant has a real hole. I verified collection membership (library_collection_items, user_personal_collection_items, abs_collection_items) is FK-constrained and correctly caught; this text[] is the only column that slips through.

Element-wise remap (preserving order, leaving unmapped/collision elements untouched) closes it. I'm including this fix in a follow-up commit on this branch, in both this migration and silo_rename_content_id.

// renameContentID moves a single content_id value (a media item, season or
// episode) to a new, currently-free id. FK children follow via ON UPDATE
// CASCADE; the silo_rename_content_id function also sweeps the unconstrained
// soft references. The function body runs as one statement, so the move 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.

(Minor — doc accuracy) This comment is correct: silo_rename_content_id's body does run as one statement, so the rename is atomic. The nit is with the PR description, which generalizes atomicity to the whole local→canonical promotion. The rename runs on s.dbPool here, while the rest of mergeAndPersist is separate work on the same pool — they aren't one transaction. The safety on partial failure actually comes from idempotent retry: if the process dies after the rename, the next match sees a non-local contentID, the IsLocal guard skips canonicalization, and the merge proceeds on the canonical id. That's genuinely self-healing and fine — it's just "retry-safe," not "atomic." Suggest tightening the PR-body wording; no code change needed.

Quick104 and others added 2 commits June 15, 2026 11:17
…inistic id migration

The value-remap migration (20260612130000) enumerates the reference graph by FK
plus a scalar name+type sweep (text/varchar/bpchar). That misses
trending_discover_snapshots.content_ids: it is text[] (excluded by the type
filter), named content_ids not content_id (excluded by the name list), and
cannot carry an FK — so the bulk remap left those arrays holding stale Sonyflake
ids that resolve to nothing until the snapshot regenerates. A counterexample to
the migration's "self-protecting, cannot orphan" invariant.

Remap the array element-wise in both directions (Up old->new, Down new->old),
preserving order and leaving collision/unmatched elements untouched; a WHERE
EXISTS guard skips empty/unaffected arrays so array_agg never collapses the NOT
NULL column to NULL. Mirror the gap in silo_rename_content_id (20260614120000)
with array_replace for the single-value runtime rename so the two stay in
lockstep.

Verified on PG18: mixed/collision/empty arrays remap correctly and round-trip
clean; runtime array_replace preserves order.

Surfaced reviewing #155. The jellycompat restart-decode regression and the
atomicity-wording nit are posted as review comments, not addressed here.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
… ids survive restarts

Addresses the restart-decode regression raised in review of #155. With
content_id now a structured string instead of a numeric Sonyflake,
EncodeStringID sent every item/season id down the one-way SHA1 path, making
decode depend on an in-memory reverse map. That map is cold after a process
restart (the codec is a process-lifetime singleton), so a client presenting a
previously-issued item UUID — resume-from-home, deep link, detail page, image,
userdata — got "unknown compat id" until the item was re-listed.

Make the encoding reversible instead of stateful:

- internal/contentid: add Pack/Unpack, a bit-packed, fixed-budget (<=15 byte)
  binary form of a structured or local content_id. digitCount preserves
  provider-id leading zeros (e.g. imdb tt0944947); structured forms are
  self-delimiting; the local form fills the budget exactly. Provider ids that
  overflow uint64 return ok=false.
- Shrink ForLocal to a 112-bit (sha256(path)[:14]) hash so a local id packs
  losslessly into the 15-byte UUID payload. 112 bits is far beyond any single
  server's local-item count. No other code assumed the old width.
- internal/jellycompat: EncodeStringID packs item/season content_ids into the
  UUID (byte 0 = kind, bytes 1..15 = packed, non-zero tag distinguishes it from
  the numeric encoding); DecodeStringID unpacks first and re-packs to confirm,
  so an opaque id whose bytes merely parse is rejected and falls through to the
  map. Numeric ids and arbitrary names (genres, studios) are unchanged.

Net: item/season ids decode by pure computation — stable across restarts and
across instances — with no lookup table. Only the rare unpackable content_id and
non-content names still use the in-memory map.

TDD: round-trip property tests in contentid (all kinds, leading zeros, reject
cases) and a cross-instance decode test in jellycompat that fails on the old
hash+map path. Full contentid + jellycompat suites green; production code
golangci-clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Quick104

Copy link
Copy Markdown
Contributor

Pushed two follow-up commits to this branch addressing the review:

  • b5d93b4 — finding Add online recap and preview marker support #2 (array-valued soft reference): the value-remap migration now remaps trending_discover_snapshots.content_ids element-wise (Up and Down), and silo_rename_content_id gets the matching array_replace so the runtime path stays in lockstep. Verified on PG18: mixed/collision/empty arrays remap correctly, order preserved, empty stays {} (no NOT NULL collapse), Down is an exact inverse.

  • a44a301 — finding Add poster-aware collection templates and async sync queueing #1 (restart-decode regression): resolved by making the compat encoding reversible instead of stateful, rather than adding a map. internal/contentid gains Pack/Unpack (a bit-packed ≤15-byte form of a structured/local content_id), ForLocal shrinks to a 112-bit hash so it packs losslessly, and jellycompat packs item/season ids into the UUID directly — decode is now pure computation, stable across restarts and instances, no lookup table. Numeric ids and arbitrary names (genres/studios) are unchanged. TDD'd with a cross-instance decode test that fails on the old hash+map path.

Finding #3 (atomicity wording) is a doc-only nit — no code change; flagged inline for the PR description.

AI-use disclosure: implemented with Claude (Opus 4.8).

…TE_TIMEOUT)

The boot-path migration runner hardcoded a 5-minute context timeout. The
deterministic-content-id value-remap (20260612130000) does a full-table COLLATE
rewrite + 65-column remap that needs ~20 min on a real dataset (615k items /
2M episodes), so it was cancelled at 5 min. Worse, Postgres keeps the orphaned
backend running (holding AccessExclusive locks) until it notices the dead client
at a statement boundary, while the goose session advisory lock releases on
disconnect — so each 5-min boot retry piled a new attempt behind the previous
one's locks. The migration never applied; the server boot-looped.

Make the timeout configurable via SILO_MIGRATE_TIMEOUT (a Go duration like
"60m"); 0 or negative disables the deadline for a one-off heavy migration. Default
stays 5m. All three entry points (migrate-status, --migrate-only, boot) honor it.

Required for the deterministic-content-id migration to apply on any real-sized
database, not just dev — the 5m cap made the PR undeployable at scale.

Follow-up (not here): on cancellation the runner should actively terminate its
backend so a future timeout cannot orphan a lock-holding statement.

TDD: MigrationTimeout parsing (default/override/zero/invalid) + MigrationContext
deadline behavior.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@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

🤖 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/contentid/binary.go`:
- Around line 131-136: The Unpack function in the tagLocal case currently
accepts bodies with trailing bytes by only checking if the body is at least
localHashLen long, then silently discarding any extra bytes. To preserve
fail-closed behavior and maintain the documented inverse contract with Pack,
change the length validation in the tagLocal case to reject bodies that are not
exactly localHashLen in length by replacing the less-than check with an equality
check. Apply the same fix at the other affected site around lines 193-194 to
ensure structured IDs also reject payloads with non-canonical trailing bytes
instead of silently accepting them.
🪄 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: 4d57016a-0cd6-488a-ae84-c275ca7306d7

📥 Commits

Reviewing files that changed from the base of the PR and between b5d93b4 and 07c5f9f.

📒 Files selected for processing (10)
  • cmd/silo/main.go
  • docs/architecture/deterministic-content-id.md
  • internal/contentid/binary.go
  • internal/contentid/binary_test.go
  • internal/contentid/contentid.go
  • internal/contentid/contentid_test.go
  • internal/database/migrate.go
  • internal/database/migrate_timeout_test.go
  • internal/jellycompat/idcodec.go
  • internal/jellycompat/idcodec_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/contentid/contentid_test.go
  • internal/contentid/contentid.go
  • docs/architecture/deterministic-content-id.md

Comment on lines +131 to +136
if tag == tagLocal {
if len(body) < localHashLen {
return "", false
}
return kindLocal + sep + hex.EncodeToString(body[:localHashLen]), true
}

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

Reject non-canonical trailing bytes in Unpack to preserve fail-closed behavior.

Unpack currently accepts malformed payloads that Pack cannot produce: structured IDs can return success with trailing non-zero bytes, and local IDs accept bodies longer than localHashLen. This breaks the documented inverse/fail-closed contract.

🔧 Suggested fix
 func Unpack(data []byte) (string, bool) {
@@
 	if tag == tagLocal {
-		if len(body) < localHashLen {
+		if len(body) != localHashLen {
 			return "", false
 		}
 		return kindLocal + sep + hex.EncodeToString(body[:localHashLen]), true
 	}
@@
 	for _, nm := range nums {
 		sb.WriteString(sep)
 		sb.WriteString(strconv.FormatUint(nm, 10))
 	}
+	for _, b := range body {
+		if b != 0 {
+			return "", false
+		}
+	}
 	return sb.String(), true
 }

Also applies to: 193-194

🤖 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/contentid/binary.go` around lines 131 - 136, The Unpack function in
the tagLocal case currently accepts bodies with trailing bytes by only checking
if the body is at least localHashLen long, then silently discarding any extra
bytes. To preserve fail-closed behavior and maintain the documented inverse
contract with Pack, change the length validation in the tagLocal case to reject
bodies that are not exactly localHashLen in length by replacing the less-than
check with an equality check. Apply the same fix at the other affected site
around lines 193-194 to ensure structured IDs also reject payloads with
non-canonical trailing bytes instead of silently accepting them.

Tighten the tagLocal branch of Unpack from `len(body) < localHashLen` to an
equality check. The local form fills the compat-UUID payload exactly (no
padding), so a body of any other length is non-canonical; matching it exactly
keeps Unpack a strict fail-closed inverse of Pack for the fixed-length branch,
which decodes client-supplied UUIDs.

Not applied to the structured branch (a review suggestion proposed the same
change there): structured ids are self-delimiting and the compat layer pads them
with trailing zeros to fill the 15-byte UUID payload, so ignoring trailing bytes
is intentional and documented. Rejecting them would make every structured id
fail to decode — the jellycompat cross-instance test guards against that.

Not a live bug today (the only caller passes u[1:] from a 16-byte UUID, so body
is always exactly localHashLen, and idcodec re-packs to verify), but it is the
correct contract and zero-risk. Adds a regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Quick104
Quick104 merged commit 0c1efef into main Jun 15, 2026
1 check passed
@Quick104
Quick104 deleted the feat/deterministic-content-id branch June 15, 2026 19:34
Quick104 added a commit that referenced this pull request Jun 17, 2026
* feat(catalog): deterministic cross-server content_id

Replace per-server Sonyflake content_id with a structured natural key
derived from provider IDs (movie:tmdb:…, series:tvdb:…, episode:…,
local:… fallback), so two servers holding the same title share one
anchor for artwork, watch history, progress, favorites and ratings.

- internal/contentid: derivation core, SeriesIDFromContentID transform,
  frozen precedence, SchemeVersion=1, embedded-series-anchor invariant.
- internal/metadata/service.go: deterministic id at every mint site.
- internal/catalog/history_source.go: resolve show via string transform
  for anchored episode ids; skip the episodes_pkey probe.
- migrations/sql/20260612130000: collision-safe value remap across the
  65-column reference graph + COLLATE "C", FK/trigger handling, audit
  map, working down.

Benchmarked against an exact-cardinality copy of cprod-postgres
(1.93M episodes, 775k history rows): 2.57x faster history page, 1.7x
throughput at 100 concurrent users, 2.7x cheaper per content_id probe.

* feat(catalog): re-ID untagged items to deterministic content_id at first match

Untagged libraries get a path-derived local: content_id at scan time and
only learn their provider IDs later, when the match worker confirms a
result. Previously that id was never folded back in, so untagged-then-matched
items kept a per-server local: placeholder forever and never converged across
servers (re-ID was deferred to a migration rerun).

mergeAndPersist now promotes a local: skeleton to its deterministic
provider-anchored id at the moment of first confirmed match, via a single
new gate (canonicalizeLocalContentID):

  - target id already taken  -> merge onto it (existing rebind machinery)
  - target id free           -> rename in place

The rename is a single SQL function (silo_rename_content_id); FK children
follow via ON UPDATE CASCADE added to the content_id family, so a fresh
skeleton moves a handful of rows rather than the full-table remap the bulk
migration does. The guard is one IsLocal prefix check, so tagged content and
all refreshes pay nothing, and the move is self-healing under retry.

Verified: gofmt/vet/build clean; migrate-validate passes; migration applies
on the real schema (up/down/up), FKs gain ON UPDATE CASCADE while keeping
ON DELETE; functional test confirms series PK move + series_id cascade +
provider-id sweep, and movie rename.

Follow-ups (noted in docs): recomposeSeriesChildIDs for a series that
accumulated episodes before matching; a lockstep test for the soft-ref list.

* fix(catalog): harden content_id parsing and merge per review

Address review feedback on the deterministic content_id work:

- history_source.go: gate the anchored-episode display-id transform on the
  full five-part episode shape (split_part parts 2-5 non-empty), not just the
  'episode:' prefix, so a malformed id can't transform to 'series:broken:' and
  vanish at the media_items join. Shared anchoredEpisodePredicate drives both
  the null-poisoned join key and the series-recovery expression.
- contentid.go: unexport the provider-precedence slices so no package can
  mutate the frozen SchemeVersion ordering at runtime.
- contentid.go: add parseAnchored to validate the exact per-kind arity and
  numeric season/episode suffixes; SeriesIDFromContentID and IsProviderAnchored
  now fail closed on truncated/malformed ids (e.g. "episode:tvdb:296762").
- canonicalize.go: distinguish catalog.ErrItemNotFound from transient lookup
  errors (a real error no longer masquerades as "target free"), and allow a
  matched local source to be consolidated onto the canonical row instead of
  orphaning a duplicate.

* refactor(contentid): URL-safe "-" separator in content_id

Use "-" instead of ":" to join content_id components
(movie-tmdb-228064, episode-tvdb-296762-1-5, local-<hex>). "-" is an RFC 3986
unreserved character, so a content_id is URL-safe verbatim: encodeURIComponent
is a no-op and the id is its own tidy path segment (/item/series-tvdb-296762)
with no %3A escaping. The stored value equals the URL value, so there is no
encode/decode boundary and an operator can grep the id straight out of a URL or
log. Every component is [a-z0-9]+ (or "tt"+digits), so "-" is unambiguous.

Pre-release format finalization: this branch is unmerged, so no deployed data
carries ":" ids — the migration mints the "-" form fresh and no re-migration is
needed. Still SchemeVersion 1.

- contentid.go: single `sep` constant drives construction and parsing so the two
  can never drift; all constructors/parsers and doc examples updated.
- history_source.go: split_part transform and the anchored-episode predicate use
  '-'; kept in lockstep with the package via a code comment.
- 20260612130000_deterministic_content_id.sql: derivation and season/episode
  composition emit '-'; LIKE filters match 'series-%'.
- docs/architecture/deterministic-content-id.md: format spec + rationale for the
  separator choice; this is the design doc the change is derived from.

Client-side: the web frontend treats content_id as an opaque string (no
splitting/regex), so no client changes are required; existing
encodeURIComponent call sites simply stop emitting %3A.

* docs(contentid): show why hash/bigint rejected in probe-cost table

Add Cross-server deterministic / Zero-join show transform / Human-readable
columns to the index-probe-cost comparison so the trade-off is legible at a
glance: the 128-bit hash and bigint surrogate are faster but each give up a
load-bearing property, and the structured key is the only all-checkmark row.

* docs(contentid): order probe-cost table to end on the structured key

* docs(contentid): label fenced blocks and drop stray EOF tags

Per CodeRabbit review: add 'text' language to three fenced code blocks
(MD040) and remove accidental </content></invoke> artifacts at EOF.

* fix(catalog): remap array-valued content_id soft references in deterministic id migration

The value-remap migration (20260612130000) enumerates the reference graph by FK
plus a scalar name+type sweep (text/varchar/bpchar). That misses
trending_discover_snapshots.content_ids: it is text[] (excluded by the type
filter), named content_ids not content_id (excluded by the name list), and
cannot carry an FK — so the bulk remap left those arrays holding stale Sonyflake
ids that resolve to nothing until the snapshot regenerates. A counterexample to
the migration's "self-protecting, cannot orphan" invariant.

Remap the array element-wise in both directions (Up old->new, Down new->old),
preserving order and leaving collision/unmatched elements untouched; a WHERE
EXISTS guard skips empty/unaffected arrays so array_agg never collapses the NOT
NULL column to NULL. Mirror the gap in silo_rename_content_id (20260614120000)
with array_replace for the single-value runtime rename so the two stay in
lockstep.

Verified on PG18: mixed/collision/empty arrays remap correctly and round-trip
clean; runtime array_replace preserves order.

Surfaced reviewing #155. The jellycompat restart-decode regression and the
atomicity-wording nit are posted as review comments, not addressed here.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(jellycompat): pack content_id into compat UUID reversibly so item ids survive restarts

Addresses the restart-decode regression raised in review of #155. With
content_id now a structured string instead of a numeric Sonyflake,
EncodeStringID sent every item/season id down the one-way SHA1 path, making
decode depend on an in-memory reverse map. That map is cold after a process
restart (the codec is a process-lifetime singleton), so a client presenting a
previously-issued item UUID — resume-from-home, deep link, detail page, image,
userdata — got "unknown compat id" until the item was re-listed.

Make the encoding reversible instead of stateful:

- internal/contentid: add Pack/Unpack, a bit-packed, fixed-budget (<=15 byte)
  binary form of a structured or local content_id. digitCount preserves
  provider-id leading zeros (e.g. imdb tt0944947); structured forms are
  self-delimiting; the local form fills the budget exactly. Provider ids that
  overflow uint64 return ok=false.
- Shrink ForLocal to a 112-bit (sha256(path)[:14]) hash so a local id packs
  losslessly into the 15-byte UUID payload. 112 bits is far beyond any single
  server's local-item count. No other code assumed the old width.
- internal/jellycompat: EncodeStringID packs item/season content_ids into the
  UUID (byte 0 = kind, bytes 1..15 = packed, non-zero tag distinguishes it from
  the numeric encoding); DecodeStringID unpacks first and re-packs to confirm,
  so an opaque id whose bytes merely parse is rejected and falls through to the
  map. Numeric ids and arbitrary names (genres, studios) are unchanged.

Net: item/season ids decode by pure computation — stable across restarts and
across instances — with no lookup table. Only the rare unpackable content_id and
non-content names still use the in-memory map.

TDD: round-trip property tests in contentid (all kinds, leading zeros, reject
cases) and a cross-instance decode test in jellycompat that fails on the old
hash+map path. Full contentid + jellycompat suites green; production code
golangci-clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(migrate): make the migration run timeout configurable (SILO_MIGRATE_TIMEOUT)

The boot-path migration runner hardcoded a 5-minute context timeout. The
deterministic-content-id value-remap (20260612130000) does a full-table COLLATE
rewrite + 65-column remap that needs ~20 min on a real dataset (615k items /
2M episodes), so it was cancelled at 5 min. Worse, Postgres keeps the orphaned
backend running (holding AccessExclusive locks) until it notices the dead client
at a statement boundary, while the goose session advisory lock releases on
disconnect — so each 5-min boot retry piled a new attempt behind the previous
one's locks. The migration never applied; the server boot-looped.

Make the timeout configurable via SILO_MIGRATE_TIMEOUT (a Go duration like
"60m"); 0 or negative disables the deadline for a one-off heavy migration. Default
stays 5m. All three entry points (migrate-status, --migrate-only, boot) honor it.

Required for the deterministic-content-id migration to apply on any real-sized
database, not just dev — the 5m cap made the PR undeployable at scale.

Follow-up (not here): on cancellation the runner should actively terminate its
backend so a future timeout cannot orphan a lock-holding statement.

TDD: MigrationTimeout parsing (default/override/zero/invalid) + MigrationContext
deadline behavior.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(contentid): require exact length for local ids in Unpack

Tighten the tagLocal branch of Unpack from `len(body) < localHashLen` to an
equality check. The local form fills the compat-UUID payload exactly (no
padding), so a body of any other length is non-canonical; matching it exactly
keeps Unpack a strict fail-closed inverse of Pack for the fixed-length branch,
which decodes client-supplied UUIDs.

Not applied to the structured branch (a review suggestion proposed the same
change there): structured ids are self-delimiting and the compat layer pads them
with trailing zeros to fill the 15-byte UUID payload, so ignoring trailing bytes
is intentional and documented. Rejecting them would make every structured id
fail to decode — the jellycompat cross-instance test guards against that.

Not a live bug today (the only caller passes u[1:] from a 16-byte UUID, so body
is always exactly localHashLen, and idcodec re-packs to verify), but it is the
correct contract and zero-risk. Adds a regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Quick <[email protected]>
Co-authored-by: Claude Opus 4.8 <[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.

2 participants