Repository navigation
feat(catalog): deterministic cross-server content_id - #155
Conversation
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.
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughIntroduces a new ChangesDeterministic Content ID System
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~85 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (8)
internal/catalog/history_source.gointernal/catalog/history_source_test.gointernal/contentid/contentid.gointernal/contentid/contentid_test.gointernal/metadata/canonicalize.gointernal/metadata/service.gomigrations/sql/20260612130000_deterministic_content_id.sqlmigrations/sql/20260614120000_content_id_online_reid.sql
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.
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 New entity types are additive. The leading A new default metadata provider is also additive. Provider precedence is a frozen, ordered list under In short, the structure itself — |
There was a problem hiding this comment.
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 winReject negative season/episode numbers before composing anchored IDs.
Line 211 and Lines 224-225 compose IDs from raw ints and return
ok=trueeven for negative inputs. Withsep = "-", a value like-1injects an extra separator (e.g., malformedepisode-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
📒 Files selected for processing (7)
docs/architecture/deterministic-content-id.mdinternal/catalog/history_source.gointernal/catalog/history_source_test.gointernal/contentid/contentid.gointernal/contentid/contentid_test.gointernal/metadata/canonicalize.gomigrations/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
left a comment
There was a problem hiding this comment.
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
EncodeNumericIDbranch, so the client UUID is a pure bit-packing andDecodeID(idcodec.go:163) reverses it with zero state. Survives restarts. - After this PR content_ids are structured strings (
movie-tmdb-228064) → they take theuuid.NewSHA1branch and reversibility depends entirely on the in-memoryc.reversemap (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') |
There was a problem hiding this comment.
(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 |
There was a problem hiding this comment.
(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.
…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]>
|
Pushed two follow-up commits to this branch addressing the review:
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]>
There was a problem hiding this comment.
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
📒 Files selected for processing (10)
cmd/silo/main.godocs/architecture/deterministic-content-id.mdinternal/contentid/binary.gointernal/contentid/binary_test.gointernal/contentid/contentid.gointernal/contentid/contentid_test.gointernal/database/migrate.gointernal/database/migrate_timeout_test.gointernal/jellycompat/idcodec.gointernal/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
| if tag == tagLocal { | ||
| if len(body) < localHashLen { | ||
| return "", false | ||
| } | ||
| return kindLocal + sep + hex.EncodeToString(body[:localHashLen]), true | ||
| } |
There was a problem hiding this comment.
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]>
* 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]>
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) andrefactor(contentid): URL-safe "-" separator in content_id(see the separator note below).Scope: id-system refactor (how
content_idis 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.mdis 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.feat(catalog): deterministic cross-server content_id
Derivation core —
internal/contentid/contentid.goForMovie/ForSeries/ForSeason/ForEpisode/ForLocal, theSeriesIDFromContentIDstring transform, and frozen provider precedence (moviestmdb → imdb → tvdb; series/season/episodetvdb → 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 = 1freezes format + precedence as a code constant so the population is never mixed-version.Generation wiring —
internal/metadata/service.goderiveLogicalContentID/deriveSeasonContentID/deriveEpisodeContentIDreplaceidgen.NextID()at every mint site (skeleton creation, provider-match atservice.go:1499, explicit + implicit seasons, episodes, scanner-fallback episodes). Tagged libraries get their deterministic id at scan time; untagged new items get a path-derivedlocal-id. Convergence of same-title items on one server is preserved by the existing dedup (findExistingByProviderIDs) plusUpsertTx'sON CONFLICT (content_id) DO UPDATEbackstop.Hot watch-history query —
internal/catalog/history_source.godisplay_idresolves an episode history row to its show viaseriesFromAnchoredEpisodeExpr(puresplit_parttransform) for provider-anchored ids, probing only themedia_itemsPK. Legacy/local-ids still fall through theepisodesjoin, which is null-poisoned for anchored ids so the planner never descendsepisodes_pkeyfor them.Migration (value remap) —
migrations/sql/20260612130000_deterministic_content_id.sqlCollision-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 workingdown. 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 insidemergeAndPersist(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 viaON 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 singleIsLocalprefix 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.The rename primitive (
silo_rename_content_id, ininternal/metadata/canonicalize.go) reuses the migration's catalog-driven column enumeration so the two stay in lockstep, and is added alongside theON UPDATE CASCADEclauses inmigrations/sql/20260614120000_content_id_online_reid.sql. ON UPDATE CASCADE only fires when acontent_idis 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 numericcontent_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_idindex-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.
en_US.utf8(today)bytea(16)bigintsurrogate (≈ old Sonyflake)content_id+COLLATE "C"(this PR)The locale-aware
strcollon today's text column is the bottleneck;COLLATE "C"(byte-wisememcmp) removes it. The structured key lands within 3% of a 128-bit hash and within 1.5× of a rawbigint, and is the only all-✓ row: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, orpsql.bigintsurrogate — 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:episodes_pkeyprobesen_US.utf8)COLLATE "C")COLLATE "C"removes the locale-aware comparison cost, and structured keys let anchored episode ids skip theepisodes_pkeydescent (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: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 inshared_buffers; isolated instance shares a host with production, so the before/after ratios are the robust result, not absolute tps.)Risk / follow-ups
recomposeSeriesChildIDspass 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).media_item_provider_ids.AccessExclusivelocks 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).content_idstays astringin every API response (no additive-only violation), but the value-remap migration changes the values clients use as their anchor. Anysilo-android/silo-applestate 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
internal/contentid(derivation, precedence, the composition↔transform round-trip invariant, edge cases) pass;internal/catalogandinternal/metadatasuites pass with updated history-query golden fragments.go build ./internal/...,go vet,gofmt -lall clean.down), and re-applies (up) cleanly — recollates 65 columns, drops/recreates 27 FKs and allepisode_catalogtriggers, retains only the audit map.20260614120000_content_id_online_reid): applies on the real schema after the value-remap migration; every content_id-family FK gainsON UPDATE CASCADEwhile keeping its originalON DELETEaction (e.g.episodes_series_id_fkeybecomesON UPDATE CASCADE ON DELETE CASCADE);make migrate-validatepasses; fullup/down/upcycle is clean (down dropssilo_rename_content_idand strips onlyON UPDATE CASCADE).silo_rename_content_idon a local series moves themedia_itemsPK, cascadesseasons.series_id/episodes.series_id, sweeps the provider-id soft references, and correctly leaves the children's own (Sonyflake) ids untouched (the deferredrecomposeSeriesChildIDscase); a local movie rename moves the item and its provider ids;ON DELETE CASCADEstill fires (delete leaves 0 orphans).downreverts values and collation.cprod-postgres(1.93M episodes, 775k history rows) — 2.57× faster history page, 1.7× throughput at 100 concurrent users, 2.7× cheaper percontent_idprobe (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
content_idvalues and enabled online re-ID with cascading updates; migration timeout is now configurable via an environment variable.