Skip to content

feat(matching): split wrongly merged versions with watch-state reattribution; anchor group keys on provider tags - #319

Merged
Quick104 merged 2 commits into
mainfrom
feat/split-versions-reassign
Jul 6, 2026
Merged

Quick104 merged 2 commits into
mainfrom
feat/split-versions-reassign

Conversation

@Quick104

@Quick104 Quick104 commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Part of #318. Design spec: docs/superpowers/specs/2026-07-06-split-versions-reassign-design.md (includes an addendum for the field-validated root cause).

Problem

Version grouping buckets files by a normalized title+year key. A user report (internal Discord thread) showed the worst case: Passenger (2026) [tmdb-1368314] and The Passenger (2026) [tmdb-1285959] — two different films, each in a correctly tagged folder — merged into one item as four "versions" with state resolved, because title normalization strips the leading article and the explicit provider tags never enter the group key. There was no in-app repair: item rematch moves all files, root overrides 409 on ambiguous roots pointing at a "split" flow that didn't exist, and the only workaround (rename + rescan) strands the watch state accrued under the merged item. Separately, item merges (rebindItemToExistingItem) have always orphaned per-user watch state.

What changed

Prevention — anchored group keys (internal/naming): when a file/folder carries structured provider tags, the content-group key is derived from the ID anchor (v1|movie|anchor|tmdb-…, precedence mirroring internal/contentid) instead of title+year. Same tag always groups (cross-folder 1080p/4K version stacking keeps working — covered by test); different tags can never merge. Untagged files keep title+year keys, so untagged libraries see zero key churn. Tagged libraries re-key on next scan; content ids are deterministic from the same tags, so this is scanner-internal state churn only.

Durable repair — path-scoped identity overrides (media_identity_overrides migration, internal/scanner): operator-forced identities bound to a root folder or single file, applied per file during group inference before bucketing. File scope beats root scope; forced provider IDs anchor the key exactly like natural tags. Folders intentionally split across groups by overrides are no longer flagged ambiguous forever.

Watch-state reattribution (internal/catalog/reattribute): shared engine for splits and merges. Rows with a file reference (progress via last_file_id, downloads, per-session playback log) move exactly. user_watch_history has no file link, so rows are classified per (user, profile) against the playback_history_admin session log — moved only when the evidence is unanimous, with evidence/keep/move_all modes; ambiguous rows are surfaced, never guessed. Progress PK conflicts resolve by newest updated_at. Intent rows (favorites, ratings, watchlist, collections) stay put unless the whole item moves. Wired into rebindItemToExistingItem, fixing the existing merge-orphaning bug, including old→new episode id mapping by season/episode number for series merges.

Endpoints: POST /admin/items/{id}/split — resolves the target via deterministic content ids (existing item / new skeleton / local- unmatched), re-points files (episode links re-derive deterministically), persists overrides, reattributes state, all in one transaction. Dry-run executes the full transaction and rolls back, so preview counts are exact. Post-commit: identify the target, refresh the source, ScanSubtree the affected roots. Also POST /admin/items/{id}/merge and GET /admin/items/{id}/files. Admin-gated, additive-only; the ambiguous_root 409s now point at the split flow.

Web admin: Split Versions dialog (files grouped by folder → match-candidate search → dry-run preview → confirm) on movie/series pages; the ambiguous-roots diagnostics table gains a Resolve link via the new content_id on the roots listing.

Risks / notes for review

  • The Passenger case is reproduced as a regression test (TestInferGroupAssignments_StructuredTagsAnchorGroupKeys); pre-fix it produced one resolved group.
  • Items merged before this fix don't auto-heal on rescan (files already point at the merged id) — the split flow is the repair path for existing damage.
  • Reattribute DB tests are skip-gated on SILO_TEST_DATABASE_URL (no CI DB suite); they should be run against a scratch database before merge.
  • History attribution quality is bounded by playback_history_admin retention; deferred follow-up is a nullable user_watch_history.media_file_id written at playback-stop for exact attribution.
  • Existing media_group_overrides (whole-group forcing) is left in place; migrating it into the new table is deliberately out of scope.

Verification

go build ./...; scanner/naming/metadata/handlers suites green (new tests: key-collision splits, scope precedence, rescan convergence, cross-folder same-tag grouping, untagged key stability, target resolution, episode-pair derivation); tsc, ESLint, Prettier, affected vitest suites green; golangci-lint --new-from-rev=origin/main clean apart from known local goconst test-file false positives; goose migration validated.

AI-use disclosure

Implemented with Claude Code (Claude Fable 5), including spec authoring, implementation, tests, and the Discord report triage/reproduction; human-directed throughout.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added an admin “Split Versions…” workflow on movie/series pages to move selected files into a resolved target (or detach as unmatched).
    • Added split/merge repair endpoints, plus a dry-run preview with reattribution reporting.
    • Library roots now optionally show the matched catalog item and provide clearer resolution links for ambiguous roots.
  • Bug Fixes
    • Improved watch progress/history/downloads and favorites handling during split/merge, including configurable history modes and better evidence-based attribution.
    • Strengthened scan-time identity override behavior to keep grouping stable across rescans and avoid incorrect merges.
  • Tests
    • Added unit and integration coverage for deterministic target resolution and reattribution behavior.

…e, anchor group keys on provider tags

Wrong merges (two titles normalizing to the same title+year key) stacked
different films as fake "versions" of one item with no in-app repair, and
explicit {tmdb-…}/[imdb-…] folder tags could not prevent it because the
content-group key ignored provider IDs entirely. Merges also silently
orphaned all per-user watch state.

- Anchor group keys on structured provider tags: same tag always groups,
  different tags can never merge; untagged files keep title+year keys.
- media_identity_overrides: path-scoped (root/file) forced identities applied
  during group inference, so admin splits survive rescans.
- internal/catalog/reattribute: shared user-state mover — exact moves for
  file-linked rows, evidence-based user_watch_history classification via the
  playback session log, newest-wins progress conflicts; wired into
  rebindItemToExistingItem to stop merge orphaning (with S/E episode mapping).
- POST /admin/items/{id}/split (dry-run = full transaction + rollback, so
  previews are exact), POST /admin/items/{id}/merge, GET /admin/items/{id}/files.
- Web admin: Split Versions dialog (files by folder → candidate search →
  preview → split), Resolve link from ambiguous-roots diagnostics.

Part of #318

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

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds a split-versions repair flow with persisted identity overrides, scanner inference changes, shared reattribution logic, admin split/merge endpoints, and web UI for selecting files, previewing reattribution, and resolving ambiguous roots.

Changes

Split Versions Feature

Layer / File(s) Summary
Design specification
docs/superpowers/specs/2026-07-06-split-versions-reassign-design.md
Adds the split-versions design document covering durable overrides, reattribution, UI changes, and implementation order.
Identity override schema
migrations/sql/20260706144033_media_identity_overrides.sql, internal/models/media_group.go
Adds the migration and model for persisted media identity overrides with root/file scope and forced identity fields.
Identity override application and anchored group keys
internal/naming/identity_override.go, internal/naming/group_identity.go
Adds override application, override-aware group keys, anchored provider-tag keys, and override evidence merging.
Scanner integration of identity overrides
internal/scanner/identity_override_repo.go, internal/scanner/group_inference.go, internal/scanner/scanner.go, internal/scanner/group_inference_test.go
Adds override persistence, lookup, scan-time application, and updated override-source and ambiguity handling, plus scanner tests for the new grouping behavior.
Reattribution helper for user state
internal/catalog/reattribute/reattribute.go, internal/catalog/reattribute/reattribute_db_test.go
Adds the shared reattribution package and database-backed tests for moving playback, downloads, progress, history, and intent rows between content IDs.
Merge path reattribution integration
internal/metadata/service.go, internal/metadata/merge_items.go
Wires episode-pair reattribution into the metadata rebind flow and adds the admin merge method.
Admin split/merge API handlers and routing
internal/api/handlers/admin_split.go, internal/api/handlers/admin_split_test.go, internal/api/router.go, internal/api/handlers/libraries.go
Adds the admin split handler, split target resolution, file movement, override persistence, follow-up work, router wiring, and library-root response updates.
Split item web UI
web/src/api/types.ts, web/src/hooks/queries/items.ts, web/src/components/SplitItemDialog.tsx, web/src/pages/ItemDetail/*, web/src/pages/AdminLibraries.tsx
Adds the split/merge API types, query hooks, split dialog, item-page actions, and admin roots-page resolve action.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SplitItemDialog
    participant AdminSplitHandler
    participant Postgres
    participant reattributeRun as reattribute.Run
    participant Scanner

    User->>SplitItemDialog: Choose files, target, history mode
    SplitItemDialog->>AdminSplitHandler: POST /admin/items/{id}/split
    AdminSplitHandler->>Postgres: Resolve target and move files
    AdminSplitHandler->>Postgres: Persist media_identity_overrides
    AdminSplitHandler->>reattributeRun: Run split reattribution
    reattributeRun->>Postgres: Move playback, progress, history, downloads, intents
    AdminSplitHandler->>Scanner: Refresh affected paths
    AdminSplitHandler-->>SplitItemDialog: Preview or split result
Loading

Possibly related issues

Possibly related PRs

  • Silo-Server/silo-server#112: Both PRs modify internal/naming/group_identity.go to anchor group identity on structured provider IDs.
  • Silo-Server/silo-server#155: Both PRs rely on deterministic provider-anchored content ID derivation for split target resolution and episode re-anchoring.
  • Silo-Server/silo-server#112: Both PRs touch scanner-side grouping logic to reduce incorrect merges from structured provider tags.

Suggested labels: v1

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the PR’s main changes: splitting mismerged versions, reattributing watch state, and anchoring group keys on provider tags.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/split-versions-reassign

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

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 6, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Caution

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

⚠️ Outside diff range comments (1)
web/src/pages/ItemDetail/components/ActionBar.tsx (1)

242-244: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

hasMetadataActions doesn't account for onSplitItem.

The overflow section housing the new "Split Versions" item is gated by hasAdminActions || hasMetadataActions, but hasMetadataActions only checks onRefresh || onEditMetadata || onMatchItem. If a consumer supplies only onSplitItem (without onMatchItem/onEditMetadata/onRefresh), the whole block collapses and the split action silently disappears — currently masked only because MovieContent always passes onMatchItem alongside it.

🔧 Proposed fix
   const hasMetadataActions = Boolean(
-    (canCurateMetadata && (onRefresh || onEditMetadata || onMatchItem)) || showMarkerEditor,
+    (canCurateMetadata && (onRefresh || onEditMetadata || onMatchItem || onSplitItem)) ||
+      showMarkerEditor,
   );

Also applies to: 445-450

🤖 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 `@web/src/pages/ItemDetail/components/ActionBar.tsx` around lines 242 - 244,
`hasMetadataActions` in `ActionBar` does not include `onSplitItem`, so the
overflow actions can disappear when split is the only metadata action provided.
Update the `hasMetadataActions` boolean to account for `onSplitItem` alongside
`onRefresh`, `onEditMetadata`, and `onMatchItem`, and make sure the overflow
gating logic for the “Split Versions” item still works when only `onSplitItem`
is supplied.
🧹 Nitpick comments (1)
docs/superpowers/specs/2026-07-06-split-versions-reassign-design.md (1)

198-203: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Pseudocode Reattribute signature omits the wholeItem param it's documented to use.

The comment says "movedFiles empty + wholeItem=true means everything," and §4.4 later says merge "calls the same helper with wholeItem=true," but the signature only declares (ctx, tx, fromItem, toItem string, movedFileIDs []int64, mode HistoryMode) — no wholeItem bool. Also ctx, tx, fromItem, toItem string would type only toItem as string in real Go. Since this signature is a reference for the upcoming internal/catalog/reattribute implementation, tightening it now avoids ambiguity for whoever implements it.

📝 Suggested signature clarification
-Reattribute(ctx, tx, fromItem, toItem string, movedFileIDs []int64,
-            mode HistoryMode) (Report, error)
+Reattribute(ctx context.Context, tx Tx, fromItem, toItem string,
+            movedFileIDs []int64, wholeItem bool, mode HistoryMode) (Report, error)

Also applies to: 260-267

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/specs/2026-07-06-split-versions-reassign-design.md` around
lines 198 - 203, The Reattribute pseudocode signature is inconsistent with the
surrounding spec because it omits the wholeItem flag that the comments and merge
flow rely on, and the parameter list formatting is ambiguous for Go. Update the
Reattribute signature in the spec to explicitly include wholeItem alongside
movedFileIDs and HistoryMode, and make the declaration format unambiguous so the
intended parameter types are clear for the internal/catalog/reattribute
implementation.
🤖 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/reattribute/reattribute.go`:
- Around line 298-328: The reattribute flow is updating playback sessions before
history classification, which causes moveHistorySubset to see incomplete
evidence for profiles that watched moved files. Reorder the work in the
reattribute transaction so history classification runs before the
playback_history_admin UPDATE, and keep the sequence around moveHistorySubset,
report.PlaybackSessionLog, and the existing tx.Exec calls consistent so
ambiguity is measured from the original session data.

In `@internal/metadata/service.go`:
- Around line 4941-4956: The mergeEpisodeIDPairs mapping logic currently skips
source episodes with no target match, which can silently drop user state during
a series merge. Update mergeEpisodeIDPairs to either materialize/map any missing
target episode before building the ID pairs, or return an explicit error listing
the unmapped episode IDs so the admin flow can handle them safely; use
mergeEpisodeIDPairs and its caller in the merge flow to keep unmatched episodes
from being ignored.

In `@internal/naming/identity_override.go`:
- Around line 59-79: Preserve existing provider anchors when applying partial
overrides in overriddenGroupKey: right now it only uses ForcedTmdbID,
ForcedImdbID, and ForcedTvdbID, so title/year/type-only overrides can drop an
already inferred structured anchor and fall back to makeContentGroupKey. Update
the logic in overriddenGroupKey (and any related helper it relies on, such as
anchoredGroupKey) to prefer any existing provider-derived anchor already present
on identity before falling back to the title/year key, so partial overrides do
not reintroduce false merges.

In `@web/src/components/SplitItemDialog.tsx`:
- Around line 51-76: The SplitItemDialog state is persisting across close/reopen
cycles, leaving stale selections and preview data behind. Update SplitItemDialog
so that when onOpenChange transitions the dialog to closed (and after a
successful split), it resets selectedIds, selectedCandidate, detachUnmatched,
historyMode, and preview, not just the preview reset effect. Use the existing
SplitItemDialog component state and the open/onOpenChange flow to ensure
reopening the same item starts with a clean dialog.
- Around line 72-76: The SplitItemDialog preview flow can accept a stale dry-run
result after the plan changes, because the pending request’s onSuccess still
updates preview even after selectedIds, selectedCandidate, detachUnmatched, or
historyMode change. Update the stale-response guard in SplitItemDialog’s dry-run
handling so onSuccess only calls setPreview for the current plan token, and
increment planTokenRef.current inside the resetPreview/useEffect path as well to
invalidate any in-flight request as soon as the selection or mode changes.

---

Outside diff comments:
In `@web/src/pages/ItemDetail/components/ActionBar.tsx`:
- Around line 242-244: `hasMetadataActions` in `ActionBar` does not include
`onSplitItem`, so the overflow actions can disappear when split is the only
metadata action provided. Update the `hasMetadataActions` boolean to account for
`onSplitItem` alongside `onRefresh`, `onEditMetadata`, and `onMatchItem`, and
make sure the overflow gating logic for the “Split Versions” item still works
when only `onSplitItem` is supplied.

---

Nitpick comments:
In `@docs/superpowers/specs/2026-07-06-split-versions-reassign-design.md`:
- Around line 198-203: The Reattribute pseudocode signature is inconsistent with
the surrounding spec because it omits the wholeItem flag that the comments and
merge flow rely on, and the parameter list formatting is ambiguous for Go.
Update the Reattribute signature in the spec to explicitly include wholeItem
alongside movedFileIDs and HistoryMode, and make the declaration format
unambiguous so the intended parameter types are clear for the
internal/catalog/reattribute implementation.
🪄 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: 614a5da6-d7a0-4fb2-b2a4-09afa0394b80

📥 Commits

Reviewing files that changed from the base of the PR and between a5b23da and 8e6f95b.

📒 Files selected for processing (24)
  • docs/superpowers/specs/2026-07-06-split-versions-reassign-design.md
  • internal/api/handlers/admin_split.go
  • internal/api/handlers/admin_split_test.go
  • internal/api/handlers/libraries.go
  • internal/api/router.go
  • internal/catalog/reattribute/reattribute.go
  • internal/catalog/reattribute/reattribute_db_test.go
  • internal/metadata/merge_items.go
  • internal/metadata/service.go
  • internal/models/media_group.go
  • internal/naming/group_identity.go
  • internal/naming/identity_override.go
  • internal/scanner/group_inference.go
  • internal/scanner/group_inference_test.go
  • internal/scanner/identity_override_repo.go
  • internal/scanner/scanner.go
  • migrations/sql/20260706144033_media_identity_overrides.sql
  • web/src/api/types.ts
  • web/src/components/SplitItemDialog.tsx
  • web/src/hooks/queries/items.ts
  • web/src/pages/AdminLibraries.tsx
  • web/src/pages/ItemDetail/MovieContent.tsx
  • web/src/pages/ItemDetail/SeriesContent.tsx
  • web/src/pages/ItemDetail/components/ActionBar.tsx

Comment on lines +4941 to +4956
// mergeEpisodeIDPairs maps the source series' episode content ids onto the
// target series' episodes by (season, episode) number, so episode-level user
// state survives a series merge. Episodes with no counterpart on the target
// are skipped: their state stays on ids that die with the source series, which
// is today's behavior, and the next scan recreates the episodes on the target.
func mergeEpisodeIDPairs(ctx context.Context, tx pgx.Tx, fromContentID, toContentID string) ([]reattribute.IDPair, error) {
rows, err := tx.Query(ctx, `
SELECT src.content_id, dest.content_id
FROM episodes src
JOIN episodes dest
ON dest.series_id = $2
AND dest.season_number = src.season_number
AND dest.episode_number = src.episode_number
WHERE src.series_id = $1
AND src.content_id <> dest.content_id
`, fromContentID, toContentID)

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Don’t silently skip episodes that may carry user state.

Lines 4943-4945 explicitly leave unmatched source episode state on IDs that “die with the source series.” That preserves the watch-state loss this PR is meant to fix when a source episode has progress/history/downloads but no target counterpart. Materialize/map the missing target episode first, or fail the merge with the unmapped episode IDs so the admin flow can resolve them safely.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/metadata/service.go` around lines 4941 - 4956, The
mergeEpisodeIDPairs mapping logic currently skips source episodes with no target
match, which can silently drop user state during a series merge. Update
mergeEpisodeIDPairs to either materialize/map any missing target episode before
building the ID pairs, or return an explicit error listing the unmapped episode
IDs so the admin flow can handle them safely; use mergeEpisodeIDPairs and its
caller in the merge flow to keep unmatched episodes from being ignored.

Comment on lines +59 to +79
identity.ContentGroupKey = overriddenGroupKey(identity, override)
identity.EvidenceJSON = mergeOverrideEvidence(identity.EvidenceJSON, override)
return true
}

// overriddenGroupKey derives the group key for an overridden identity. A
// forced provider ID yields an anchored key so files forced to the same title
// always share a group and files forced apart never do. Without a forced
// provider ID the key falls back to the normal title+year derivation over the
// forced values.
func overriddenGroupKey(identity *GroupIdentity, override IdentityOverride) string {
if anchored := anchoredGroupKey(
identity.GroupKeyVersion,
identity.BaseType,
override.ForcedTmdbID,
override.ForcedImdbID,
override.ForcedTvdbID,
); anchored != "" {
return anchored
}
return makeContentGroupKey(identity.BaseType, identity.BaseTitle, identity.BaseYear, identity.ObservedRootPath, identity.RepresentativePath)

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve existing provider anchors when applying partial overrides.

overriddenGroupKey anchors only on forced provider IDs. If an override only changes title/year/type, inferred structured IDs remain on identity but the key falls back to title/year, which can reintroduce false merges for tagged files.

🐛 Proposed fix
-	identity.ContentGroupKey = overriddenGroupKey(identity, override)
+	identity.ContentGroupKey = overriddenGroupKey(identity)
@@
-func overriddenGroupKey(identity *GroupIdentity, override IdentityOverride) string {
+func overriddenGroupKey(identity *GroupIdentity) string {
 	if anchored := anchoredGroupKey(
 		identity.GroupKeyVersion,
 		identity.BaseType,
-		override.ForcedTmdbID,
-		override.ForcedImdbID,
-		override.ForcedTvdbID,
+		identity.TmdbID,
+		identity.ImdbID,
+		identity.TvdbID,
 	); anchored != "" {
 		return anchored
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
identity.ContentGroupKey = overriddenGroupKey(identity, override)
identity.EvidenceJSON = mergeOverrideEvidence(identity.EvidenceJSON, override)
return true
}
// overriddenGroupKey derives the group key for an overridden identity. A
// forced provider ID yields an anchored key so files forced to the same title
// always share a group and files forced apart never do. Without a forced
// provider ID the key falls back to the normal title+year derivation over the
// forced values.
func overriddenGroupKey(identity *GroupIdentity, override IdentityOverride) string {
if anchored := anchoredGroupKey(
identity.GroupKeyVersion,
identity.BaseType,
override.ForcedTmdbID,
override.ForcedImdbID,
override.ForcedTvdbID,
); anchored != "" {
return anchored
}
return makeContentGroupKey(identity.BaseType, identity.BaseTitle, identity.BaseYear, identity.ObservedRootPath, identity.RepresentativePath)
identity.ContentGroupKey = overriddenGroupKey(identity)
return true
}
// overriddenGroupKey derives the group key for an overridden identity. A
// forced provider ID yields an anchored key so files forced to the same title
// always share a group and files forced apart never do. Without a forced
// provider ID the key falls back to the normal title+year derivation over the
// forced values.
func overriddenGroupKey(identity *GroupIdentity) string {
if anchored := anchoredGroupKey(
identity.GroupKeyVersion,
identity.BaseType,
identity.TmdbID,
identity.ImdbID,
identity.TvdbID,
); anchored != "" {
return anchored
}
return makeContentGroupKey(identity.BaseType, identity.BaseTitle, identity.BaseYear, identity.ObservedRootPath, identity.RepresentativePath)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/naming/identity_override.go` around lines 59 - 79, Preserve existing
provider anchors when applying partial overrides in overriddenGroupKey: right
now it only uses ForcedTmdbID, ForcedImdbID, and ForcedTvdbID, so
title/year/type-only overrides can drop an already inferred structured anchor
and fall back to makeContentGroupKey. Update the logic in overriddenGroupKey
(and any related helper it relies on, such as anchoredGroupKey) to prefer any
existing provider-derived anchor already present on identity before falling back
to the title/year key, so partial overrides do not reintroduce false merges.

Comment on lines +51 to +76
export default function SplitItemDialog({ item, open, onOpenChange }: SplitItemDialogProps) {
const { data: filesData, isLoading: filesLoading } = useItemFiles(
open ? item.content_id : undefined,
);
const files = useMemo(() => filesData?.files ?? [], [filesData]);

const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
const [title, setTitle] = useState("");
const [year, setYear] = useState("");
const [imdbId, setImdbId] = useState("");
const [tmdbId, setTmdbId] = useState("");
const [tvdbId, setTvdbId] = useState("");
const [selectedCandidate, setSelectedCandidate] = useState<MatchCandidate | null>(null);
const [detachUnmatched, setDetachUnmatched] = useState(false);
const [historyMode, setHistoryMode] = useState<SplitHistoryMode>("evidence");
const [preview, setPreview] = useState<ItemSplitResponse | null>(null);

const searchMutation = useSearchItemMatchCandidates(item.content_id);
const splitMutation = useSplitItem();
const candidates = searchMutation.data?.candidates ?? [];

// Any change to the plan invalidates a previously fetched preview.
const resetPreview = useCallback(() => setPreview(null), []);
useEffect(() => {
resetPreview();
}, [selectedIds, selectedCandidate, detachUnmatched, historyMode, resetPreview]);

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Dialog state is not reset across open/close cycles for the same item.

onOpenChange(false) on successful split (Line 157) closes the dialog but leaves selectedIds, selectedCandidate, detachUnmatched, historyMode, and preview populated. Since the parent (MovieContent) keys this component by item.content_id only, reopening the dialog for the same item (e.g., to do a second split, or after cancelling) shows leftover selections/preview referencing files that may no longer exist on this item.

🔧 Proposed fix — reset state when the dialog closes/opens
+  useEffect(() => {
+    if (!open) {
+      setSelectedIds(new Set());
+      setTitle("");
+      setYear("");
+      setImdbId("");
+      setTmdbId("");
+      setTvdbId("");
+      setSelectedCandidate(null);
+      setDetachUnmatched(false);
+      setHistoryMode("evidence");
+      setPreview(null);
+    }
+  }, [open]);

Also applies to: 152-161

🤖 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 `@web/src/components/SplitItemDialog.tsx` around lines 51 - 76, The
SplitItemDialog state is persisting across close/reopen cycles, leaving stale
selections and preview data behind. Update SplitItemDialog so that when
onOpenChange transitions the dialog to closed (and after a successful split), it
resets selectedIds, selectedCandidate, detachUnmatched, historyMode, and
preview, not just the preview reset effect. Use the existing SplitItemDialog
component state and the open/onOpenChange flow to ensure reopening the same item
starts with a clean dialog.

Comment on lines +72 to +76
// Any change to the plan invalidates a previously fetched preview.
const resetPreview = useCallback(() => setPreview(null), []);
useEffect(() => {
resetPreview();
}, [selectedIds, selectedCandidate, detachUnmatched, historyMode, resetPreview]);

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Stale preview can be shown after selection changes mid-flight.

The plan-change effect (Lines 74-76) nulls preview on any selection/target/history-mode change, but a pending dry-run's onSuccess (Line 154-155) still calls setPreview(result) when it eventually resolves — even if the selection has since changed. The Confirm button then re-enables against a preview that no longer matches the current plan.

🔧 Proposed fix — ignore stale dry-run responses
+  const planTokenRef = useRef(0);
+
   const submit = useCallback(
     (dryRun: boolean) => {
+      const token = ++planTokenRef.current;
       splitMutation.mutate(
         {
           contentId: item.content_id,
           request: {
             file_ids: [...selectedIds],
             target: detachUnmatched
               ? { unmatched: true }
               : {
                   provider_ids: selectedCandidate?.provider_ids,
                   title: selectedCandidate?.title,
                   year: selectedCandidate?.year || undefined,
                 },
             history_mode: historyMode,
             dry_run: dryRun,
           },
         },
         {
           onSuccess: (result) => {
+            if (token !== planTokenRef.current) return; // plan changed since this request was sent
             if (dryRun) {
               setPreview(result);
             } else {
               onOpenChange(false);
             }
           },
         },
       );
     },
     [...],
   );

And increment planTokenRef.current in the resetPreview effect as well, so an in-flight request whose plan changed is invalidated even before it resolves.

Also applies to: 134-172

🤖 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 `@web/src/components/SplitItemDialog.tsx` around lines 72 - 76, The
SplitItemDialog preview flow can accept a stale dry-run result after the plan
changes, because the pending request’s onSuccess still updates preview even
after selectedIds, selectedCandidate, detachUnmatched, or historyMode change.
Update the stale-response guard in SplitItemDialog’s dry-run handling so
onSuccess only calls setPreview for the current plan token, and increment
planTokenRef.current inside the resetPreview/useEffect path as well to
invalidate any in-flight request as soon as the selection or mode changes.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8e6f95b59e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +300 to +302
UPDATE playback_history_admin
SET media_item_id = $3
WHERE media_item_id = $1 AND media_file_id = ANY($2::int[])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve history evidence before moving session logs

When evidence mode is used for a file-subset split, moveHistorySubset classifies user_watch_history by reading playback_history_admin WHERE media_item_id = $1. This update has already changed all moved-file sessions to the target item, so profiles that only watched moved files have no moved evidence and their history stays/turns ambiguous; mixed profiles also look like stayed-only. Capture/classify the evidence before updating these session rows (or include both source and target rows) so default splits actually reattribute history.

Useful? React with 👍 / 👎.

…anaged downloads and series-scoped preferences

Review findings on #319, all reproduced against a migrated scratch database:

- moveFileSubset re-pointed playback_history_admin before the history
  evidence query ran, erasing exactly the evidence proving a profile's plays
  were all on moved files — their history stayed behind as ambiguous.
  History classification now runs first; the pre-fix code demonstrably fails
  TestRun_HistoryEvidenceClassification.
- Managed offline downloads (downloads.content_id/episode_id) were not
  remapped on split or merge, stranding rows on the old id. Now moved per
  file on splits and swept per id pair on merges/episode re-anchoring.
- Series merges left user_audio_preferences, user_subtitle_preferences,
  user_series_playback_preferences (series_id-keyed) and the denormalized
  user_home_item_dismissals.series_id behind. All four now move, mirroring
  the provider-merge remap.

All five reattribute DB tests now verified green against PostgreSQL, with
new coverage for managed downloads, subtitle preferences, and dismissal
series ids.

Part of #318

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

Quick104 commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

Addressed all three review findings in c766c58 — each was verified by reproduction before fixing, this time against a real migrated PostgreSQL scratch database (the previously skip-gated reattribute DB suite now ran for real):

  • [P1] Evidence erasure: confirmed — history classification now runs before the session log is re-pointed. The pre-fix code demonstrably fails TestRun_HistoryEvidenceClassification (HistoryMoved:0, unanimous profile misclassified ambiguous); post-fix it passes.
  • [P1] Managed downloads: confirmed — downloads.content_id now moves per file on splits and per id pair on merges; downloads.episode_id is swept by the episode-pair remap. Covered by a new FK-backed seed in TestRun_FileSubsetExactAndProgress.
  • [P2] Series-scoped preferences: confirmed — user_audio_preferences, user_subtitle_preferences, user_series_playback_preferences (all series_id-keyed) and the denormalized user_home_item_dismissals.series_id now move with merges/move_all, mirroring the provider-merge remap. Covered in TestRun_WholeItemPairsAndConflicts.

All five DB tests are green against PostgreSQL 🎉. One unrelated discovery while running the DB suites: UpdateEpisodeLink in internal/scanner/file_repo.go contains an invalid CTE (inserted referenced without a RETURNING clause) that errors on every call — pre-existing on main, tracked separately.

🤖 Generated with Claude Code

@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/catalog/reattribute/reattribute_db_test.go`:
- Around line 63-87: The cleanup in seedMediaFile leaves orphaned
media_files/media_folders because it deletes the referenced rows before the
downloads row that points at media_file_id, and the FK failure is silently
ignored. Update seedMediaFile’s t.Cleanup to remove any dependent downloads
record first, then delete media_files and media_folders, using the existing
seedMediaFile/testEnv helpers so the order is explicit and no longer depends on
cleanup registration order.
🪄 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: a65448c3-f674-476a-ad1a-fcd371a3e606

📥 Commits

Reviewing files that changed from the base of the PR and between 8e6f95b and c766c58.

📒 Files selected for processing (2)
  • internal/catalog/reattribute/reattribute.go
  • internal/catalog/reattribute/reattribute_db_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/catalog/reattribute/reattribute.go

Comment on lines +63 to +87
// seedMediaFile creates a media_folders + media_files pair so tables with a
// real FK on media_file_id (downloads) can be seeded.
func (e *testEnv) seedMediaFile(t *testing.T, contentID, path string) int {
t.Helper()
ctx := context.Background()
var folderID int
if err := e.pool.QueryRow(ctx,
`INSERT INTO media_folders (type, name, enabled) VALUES ('movies', $1, true) RETURNING id`,
fmt.Sprintf("reattr-folder-%d", e.suffix),
).Scan(&folderID); err != nil {
t.Fatalf("seed folder: %v", err)
}
var fileID int
if err := e.pool.QueryRow(ctx, `
INSERT INTO media_files (content_id, media_folder_id, file_path, file_size)
VALUES ($1, $2, $3, 1000) RETURNING id
`, contentID, folderID, path).Scan(&fileID); err != nil {
t.Fatalf("seed media file: %v", err)
}
t.Cleanup(func() {
_, _ = e.pool.Exec(ctx, `DELETE FROM media_files WHERE id = $1`, fileID)
_, _ = e.pool.Exec(ctx, `DELETE FROM media_folders WHERE id = $1`, folderID)
})
return fileID
}

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Cleanup order can leave orphaned media_files/media_folders rows.

t.Cleanup runs in LIFO order. Since seedMediaFile's cleanup (delete media_files/media_folders) is registered after newTestEnv's cleanup (which deletes downloads etc. by user_id), the media_files delete runs before the downloads row referencing it is removed. Given the comment on Line 64 confirming downloads.media_file_id is a real FK, this delete will fail on the FK constraint — and since the cleanup ignores errors (_, _ = e.pool.Exec(...)), the failure is silent, leaving orphaned media_files/media_folders rows in the shared test database after every run.

Delete the referencing downloads row first, inside seedMediaFile's own cleanup, so correctness doesn't depend on cross-helper registration order.

🧹 Proposed fix
 	t.Cleanup(func() {
+		_, _ = e.pool.Exec(ctx, `DELETE FROM downloads WHERE media_file_id = $1`, fileID)
 		_, _ = e.pool.Exec(ctx, `DELETE FROM media_files WHERE id = $1`, fileID)
 		_, _ = e.pool.Exec(ctx, `DELETE FROM media_folders WHERE id = $1`, folderID)
 	})
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// seedMediaFile creates a media_folders + media_files pair so tables with a
// real FK on media_file_id (downloads) can be seeded.
func (e *testEnv) seedMediaFile(t *testing.T, contentID, path string) int {
t.Helper()
ctx := context.Background()
var folderID int
if err := e.pool.QueryRow(ctx,
`INSERT INTO media_folders (type, name, enabled) VALUES ('movies', $1, true) RETURNING id`,
fmt.Sprintf("reattr-folder-%d", e.suffix),
).Scan(&folderID); err != nil {
t.Fatalf("seed folder: %v", err)
}
var fileID int
if err := e.pool.QueryRow(ctx, `
INSERT INTO media_files (content_id, media_folder_id, file_path, file_size)
VALUES ($1, $2, $3, 1000) RETURNING id
`, contentID, folderID, path).Scan(&fileID); err != nil {
t.Fatalf("seed media file: %v", err)
}
t.Cleanup(func() {
_, _ = e.pool.Exec(ctx, `DELETE FROM media_files WHERE id = $1`, fileID)
_, _ = e.pool.Exec(ctx, `DELETE FROM media_folders WHERE id = $1`, folderID)
})
return fileID
}
// seedMediaFile creates a media_folders + media_files pair so tables with a
// real FK on media_file_id (downloads) can be seeded.
func (e *testEnv) seedMediaFile(t *testing.T, contentID, path string) int {
t.Helper()
ctx := context.Background()
var folderID int
if err := e.pool.QueryRow(ctx,
`INSERT INTO media_folders (type, name, enabled) VALUES ('movies', $1, true) RETURNING id`,
fmt.Sprintf("reattr-folder-%d", e.suffix),
).Scan(&folderID); err != nil {
t.Fatalf("seed folder: %v", err)
}
var fileID int
if err := e.pool.QueryRow(ctx, `
INSERT INTO media_files (content_id, media_folder_id, file_path, file_size)
VALUES ($1, $2, $3, 1000) RETURNING id
`, contentID, folderID, path).Scan(&fileID); err != nil {
t.Fatalf("seed media file: %v", err)
}
t.Cleanup(func() {
_, _ = e.pool.Exec(ctx, `DELETE FROM downloads WHERE media_file_id = $1`, fileID)
_, _ = e.pool.Exec(ctx, `DELETE FROM media_files WHERE id = $1`, fileID)
_, _ = e.pool.Exec(ctx, `DELETE FROM media_folders WHERE id = $1`, folderID)
})
return fileID
}
🧰 Tools
🪛 ast-grep (0.44.1)

[error] 68-71: Detected a SQL query built with 'fmt.Sprintf' and passed directly to a 'database/sql' query method (Query, QueryRow, QueryContext, or QueryRowContext). Formatting user-controlled values into a query string enables SQL injection. Use parameterized queries with placeholders (e.g. 'db.Query("SELECT * FROM users WHERE id = ", id)') and pass arguments separately instead of interpolating them with 'fmt.Sprintf'.
Context: e.pool.QueryRow(ctx,
INSERT INTO media_folders (type, name, enabled) VALUES ('movies', $1, true) RETURNING id,
fmt.Sprintf("reattr-folder-%d", e.suffix),
)
Note: [CWE-89] Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection').

(sql-injection-query-sprintf-go)

🤖 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/catalog/reattribute/reattribute_db_test.go` around lines 63 - 87,
The cleanup in seedMediaFile leaves orphaned media_files/media_folders because
it deletes the referenced rows before the downloads row that points at
media_file_id, and the FK failure is silently ignored. Update seedMediaFile’s
t.Cleanup to remove any dependent downloads record first, then delete
media_files and media_folders, using the existing seedMediaFile/testEnv helpers
so the order is explicit and no longer depends on cleanup registration order.

@Quick104
Quick104 merged commit b349ebc into main Jul 6, 2026
3 checks passed
@Quick104
Quick104 deleted the feat/split-versions-reassign branch July 6, 2026 16:23
Quick104 added a commit that referenced this pull request Jul 6, 2026
…view JSON has [] not null

A whole-folder split only populated root overrides, leaving file_overrides
marshaled as null, which crashed the Split Versions preview render in the
web UI and kept the Split button disabled.

Part of #319 follow-up.

AI-use: implemented with Claude Code.

Co-Authored-By: Claude Fable 5 <[email protected]>
Quick104 added a commit that referenced this pull request Jul 6, 2026
… button

The Split Versions dialog now debounces a dry run whenever the plan is
valid, shows the preview automatically (with a stale-response token
guard), and tolerates null override arrays from older servers. Split
still requires a rendered preview before enabling.

Part of #319 follow-up.

AI-use: implemented with Claude Code.

Co-Authored-By: Claude Fable 5 <[email protected]>
Quick104 pushed a commit that referenced this pull request Jul 8, 2026
* fix(scanner): stop classifying "other" content folders as extras

Regression from #322 (trailers and extras for movies and series), which
introduced the extrasDirKinds map.

The extras directory classifier mapped the generic labels "other" and
"others" to ExtraKindOther. These are not part of the Jellyfin/Plex extras
folder convention the map claims to mirror, and they collide with real
content-scope folder names.

A library organized as "movies/other/<Title (year) {ids}>/<file>" tripped
the depth-2 ancestor lookup in classifyExtraPath: every title two levels
under the scope folder "other" was classified as an "other"-kind extra. Such
files are partitioned out of primary root/group inference and matching, then
deferred in processExtraFiles because their parent cannot resolve (they are
the primary titles, not children of one). The result on one deployment was
~10k movies under a folder named "other" funneled through the slow extras
path every scan (parent-unresolved deferrals at ~9.5/s), stalling the scan
and freezing that scope for new/changed primary content.

Remove "other"/"others" from extrasDirKinds. The ExtraKindOther kind stays
reachable through genuine convention labels (extra/extras/interviews/
scenes/shorts). Add regression coverage asserting titles under a scope folder
named other/others stay primary.

* perf(scanner): rewrite identity-only changes without re-probing

A pure identity/grouping change on an already-probed file — a
root_assignment_changed or group_assignment_changed reason with nothing
else — used to fall into the full update branch, which unconditionally ran
ffprobe (probeFile) and then upserted every column, including probe columns,
from the freshly built row. When a group-key or root scheme changes across
the library (see #319), this reprobed nearly every file on the next scan:
an incremental scan that normally takes ~1h ran 7h+ as a full-library
ffprobe storm, even though the media bytes were untouched.

Add a metadata-only update path in processFile: when identityOnlyUpdateReasons
reports every reason is a root/group reassignment, rewrite just the derived
identity columns via the new FileRepository.UpdateIdentity and skip ffprobe,
OSHash, and marker fetch entirely. UpdateIdentity issues a targeted UPDATE of
the root/group/identity and edition/presentation columns only, mirroring
Upsert's column handling, and leaves probe data, file bytes/mtime/hash,
subtitles, chapters, markers, and content/episode/extra linkage intact. The
stored group key converges to the recomputed value on the next scan, so the
file takes the unchanged fast-path thereafter — without a probe storm.

The shared identity-column population is extracted into populateScanIdentity
so the full path and the metadata-only path stay in lockstep.

Verification: unit test for the identityOnlyUpdateReasons classifier; a
DB-backed test (skipped without SILO_TEST_DATABASE_URL) asserting UpdateIdentity
rewrites grouping while preserving probe/linkage columns; the UPDATE statement
was also exercised against the live schema inside a rolled-back transaction.

* fix(scanner): harden identity fast path and extras scope classification

Review follow-ups for the two scan-regression fixes on this branch,
addressing both Codex review comments on PR #341 plus adversarial-review
findings.

Identity fast path (processFile/UpdateIdentity):

- Gate the metadata-only path on existing.ExtraID == "": a row still
  linked as an extra reaching processFile is being reclassified as
  primary, and only the full upsert clears extra linkage; UpdateIdentity
  would have frozen it out of matching forever (match backlog filters
  extra_id IS NULL).
- Gate on existing.FileHash != "": the full path backfills the OSHash
  and fetches hash-keyed S3 intro/credits markers, which no later scan
  reason would repair; hash-less legacy rows now take the full path once
  instead of silently losing that repair channel. file_hash is added to
  the scan-state row shape to support the gate.
- Clear match_suppressed_at like every other scan write, so files with
  fresh identity re-enter the match backlog (suppression is documented
  as lasting "until retried or seen by a new scan").
- Write media_folder_id, mirroring Upsert's ON CONFLICT reassignment.
- Return ErrFileNotFound when the row vanished mid-scan (concurrent
  delete) and fall through to the full upsert path instead of surfacing
  a per-file scan error.
- Return only the row id instead of RETURNING all ~75 columns: the fast
  path fires once per file during library-wide grouping migrations, and
  dragging the track/chapter JSONB payloads along for a million rows
  dominated the cost of the path built to be cheap.
- Extract identityColumnDefaults shared by Upsert and UpdateIdentity so
  the defaulting rules cannot drift, and drop the no-op editionConfidence
  indirection copied between them.
- Use populateScanIdentity in the new-file insert path too; it still
  carried a verbatim copy of the extracted block (with a provably dead
  existingByPath lookup).

Extras classification:

- Restore "other" to extrasDirKinds: it is part of both the documented
  Jellyfin and Plex extras-folder conventions (the removed-label fix
  overshot and broke "movies/<Title>/Other/<file>" libraries, ingesting
  their extras as bogus primary titles). "others" stays removed - it is
  in neither convention.
- Replace label removal with the structural guard the PR had deferred:
  classifyExtraPath now rejects a supplemental-named directory sitting
  at library-scope depth (the dir, any supplemental ancestor, or the
  first non-supplemental ancestor is a configured library root). This
  fixes the original "movies/other/<Title>" defer-storm generically,
  covering every convention label (shorts, scenes, extras, ...) used as
  a content-scope folder.
- Scope extras parent binding by folder.Paths instead of the walk roots,
  so a subtree scan targeting a single movie folder still binds that
  movie's own extras instead of deferring them.

Tests: eligibility-gate unit tests, scope-guard classifier cases
(convention Other/ inside a title binds; scope-level other/shorts stay
primary), and the DB-backed UpdateIdentity test now also covers folder
moves, suppression clearing, and ErrFileNotFound. Full scanner suite ran
green against a migrated scratch PostgreSQL 17 container.

* refactor(scanner): simplify extras scope guard to title-folder rule

Replace the ancestor-walking supplementalDirAtScopeDepth loop with the
plain rule it was approximating: a convention-named directory counts as
an extras dir only when it sits inside a title folder — it must not be a
configured library root or directly under one. Same outcome for the
layouts that matter (movies/other/<Title> stays primary, <Title>/Other
classifies), less machinery.

* test(scanner): assert all rewritten identity columns in UpdateIdentity test

* fix(scanner): make extras scope classification structure-aware

The title-folder rule from c1828d2 anchored on library roots, so it
missed both directions: chained convention dirs at the root
("movies/extras/behind the scenes/clip.mkv") classified as extras with
an unresolvable parent (deferred forever), and category folders nested
below the root ("movies/4K/other/<Title>/") still misclassified their
titles.

Replace the root-distance heuristic with the structural property that
actually distinguishes the two cases: a convention-named directory only
counts as an extras dir when its owner (first non-supplemental
ancestor) is a title folder — a directory that holds media of its own.
The new extrasClassifier derives that from the scan's walked path list
(no extra I/O): movie folders must hold a file directly beside the
extras dir; series folders may hold episodes one level down in season
folders (media hiding inside a folder's own extras dirs doesn't count).
Library roots never qualify. Watch-event scans, which have no walked
list, probe ownership with bounded os.ReadDir instead.

This handles title folders at any depth below the root and keeps
scope/category folders primary at any depth, with two known edges: a
title folder holding only extras (its media file missing) stays primary
until the file appears, and a mixed dir holding both loose media and a
category folder degrades to deferral, never wrong linkage.

resolveExtraParent's inline supplemental-chain walk is extracted into
the shared firstNonSupplementalAncestor.
Quick104 added a commit that referenced this pull request Jul 10, 2026
…ibution; anchor group keys on provider tags (#319)

* feat(matching): split wrongly merged versions, reattribute watch state, anchor group keys on provider tags

Wrong merges (two titles normalizing to the same title+year key) stacked
different films as fake "versions" of one item with no in-app repair, and
explicit {tmdb-…}/[imdb-…] folder tags could not prevent it because the
content-group key ignored provider IDs entirely. Merges also silently
orphaned all per-user watch state.

- Anchor group keys on structured provider tags: same tag always groups,
  different tags can never merge; untagged files keep title+year keys.
- media_identity_overrides: path-scoped (root/file) forced identities applied
  during group inference, so admin splits survive rescans.
- internal/catalog/reattribute: shared user-state mover — exact moves for
  file-linked rows, evidence-based user_watch_history classification via the
  playback session log, newest-wins progress conflicts; wired into
  rebindItemToExistingItem to stop merge orphaning (with S/E episode mapping).
- POST /admin/items/{id}/split (dry-run = full transaction + rollback, so
  previews are exact), POST /admin/items/{id}/merge, GET /admin/items/{id}/files.
- Web admin: Split Versions dialog (files by folder → candidate search →
  preview → split), Resolve link from ambiguous-roots diagnostics.

Part of #318

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

* fix(reattribute): classify history before moving session log; cover managed downloads and series-scoped preferences

Review findings on #319, all reproduced against a migrated scratch database:

- moveFileSubset re-pointed playback_history_admin before the history
  evidence query ran, erasing exactly the evidence proving a profile's plays
  were all on moved files — their history stayed behind as ambiguous.
  History classification now runs first; the pre-fix code demonstrably fails
  TestRun_HistoryEvidenceClassification.
- Managed offline downloads (downloads.content_id/episode_id) were not
  remapped on split or merge, stranding rows on the old id. Now moved per
  file on splits and swept per id pair on merges/episode re-anchoring.
- Series merges left user_audio_preferences, user_subtitle_preferences,
  user_series_playback_preferences (series_id-keyed) and the denormalized
  user_home_item_dismissals.series_id behind. All four now move, mirroring
  the provider-merge remap.

All five reattribute DB tests now verified green against PostgreSQL, with
new coverage for managed downloads, subtitle preferences, and dismissal
series ids.

Part of #318

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

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Quick104 added a commit that referenced this pull request Jul 10, 2026
…view JSON has [] not null

A whole-folder split only populated root overrides, leaving file_overrides
marshaled as null, which crashed the Split Versions preview render in the
web UI and kept the Split button disabled.

Part of #319 follow-up.

AI-use: implemented with Claude Code.

Co-Authored-By: Claude Fable 5 <[email protected]>
Quick104 added a commit that referenced this pull request Jul 10, 2026
… button

The Split Versions dialog now debounces a dry run whenever the plan is
valid, shows the preview automatically (with a stale-response token
guard), and tolerates null override arrays from older servers. Split
still requires a rendered preview before enabling.

Part of #319 follow-up.

AI-use: implemented with Claude Code.

Co-Authored-By: Claude Fable 5 <[email protected]>
Quick104 pushed a commit that referenced this pull request Jul 10, 2026
* fix(scanner): stop classifying "other" content folders as extras

Regression from #322 (trailers and extras for movies and series), which
introduced the extrasDirKinds map.

The extras directory classifier mapped the generic labels "other" and
"others" to ExtraKindOther. These are not part of the Jellyfin/Plex extras
folder convention the map claims to mirror, and they collide with real
content-scope folder names.

A library organized as "movies/other/<Title (year) {ids}>/<file>" tripped
the depth-2 ancestor lookup in classifyExtraPath: every title two levels
under the scope folder "other" was classified as an "other"-kind extra. Such
files are partitioned out of primary root/group inference and matching, then
deferred in processExtraFiles because their parent cannot resolve (they are
the primary titles, not children of one). The result on one deployment was
~10k movies under a folder named "other" funneled through the slow extras
path every scan (parent-unresolved deferrals at ~9.5/s), stalling the scan
and freezing that scope for new/changed primary content.

Remove "other"/"others" from extrasDirKinds. The ExtraKindOther kind stays
reachable through genuine convention labels (extra/extras/interviews/
scenes/shorts). Add regression coverage asserting titles under a scope folder
named other/others stay primary.

* perf(scanner): rewrite identity-only changes without re-probing

A pure identity/grouping change on an already-probed file — a
root_assignment_changed or group_assignment_changed reason with nothing
else — used to fall into the full update branch, which unconditionally ran
ffprobe (probeFile) and then upserted every column, including probe columns,
from the freshly built row. When a group-key or root scheme changes across
the library (see #319), this reprobed nearly every file on the next scan:
an incremental scan that normally takes ~1h ran 7h+ as a full-library
ffprobe storm, even though the media bytes were untouched.

Add a metadata-only update path in processFile: when identityOnlyUpdateReasons
reports every reason is a root/group reassignment, rewrite just the derived
identity columns via the new FileRepository.UpdateIdentity and skip ffprobe,
OSHash, and marker fetch entirely. UpdateIdentity issues a targeted UPDATE of
the root/group/identity and edition/presentation columns only, mirroring
Upsert's column handling, and leaves probe data, file bytes/mtime/hash,
subtitles, chapters, markers, and content/episode/extra linkage intact. The
stored group key converges to the recomputed value on the next scan, so the
file takes the unchanged fast-path thereafter — without a probe storm.

The shared identity-column population is extracted into populateScanIdentity
so the full path and the metadata-only path stay in lockstep.

Verification: unit test for the identityOnlyUpdateReasons classifier; a
DB-backed test (skipped without SILO_TEST_DATABASE_URL) asserting UpdateIdentity
rewrites grouping while preserving probe/linkage columns; the UPDATE statement
was also exercised against the live schema inside a rolled-back transaction.

* fix(scanner): harden identity fast path and extras scope classification

Review follow-ups for the two scan-regression fixes on this branch,
addressing both Codex review comments on PR #341 plus adversarial-review
findings.

Identity fast path (processFile/UpdateIdentity):

- Gate the metadata-only path on existing.ExtraID == "": a row still
  linked as an extra reaching processFile is being reclassified as
  primary, and only the full upsert clears extra linkage; UpdateIdentity
  would have frozen it out of matching forever (match backlog filters
  extra_id IS NULL).
- Gate on existing.FileHash != "": the full path backfills the OSHash
  and fetches hash-keyed S3 intro/credits markers, which no later scan
  reason would repair; hash-less legacy rows now take the full path once
  instead of silently losing that repair channel. file_hash is added to
  the scan-state row shape to support the gate.
- Clear match_suppressed_at like every other scan write, so files with
  fresh identity re-enter the match backlog (suppression is documented
  as lasting "until retried or seen by a new scan").
- Write media_folder_id, mirroring Upsert's ON CONFLICT reassignment.
- Return ErrFileNotFound when the row vanished mid-scan (concurrent
  delete) and fall through to the full upsert path instead of surfacing
  a per-file scan error.
- Return only the row id instead of RETURNING all ~75 columns: the fast
  path fires once per file during library-wide grouping migrations, and
  dragging the track/chapter JSONB payloads along for a million rows
  dominated the cost of the path built to be cheap.
- Extract identityColumnDefaults shared by Upsert and UpdateIdentity so
  the defaulting rules cannot drift, and drop the no-op editionConfidence
  indirection copied between them.
- Use populateScanIdentity in the new-file insert path too; it still
  carried a verbatim copy of the extracted block (with a provably dead
  existingByPath lookup).

Extras classification:

- Restore "other" to extrasDirKinds: it is part of both the documented
  Jellyfin and Plex extras-folder conventions (the removed-label fix
  overshot and broke "movies/<Title>/Other/<file>" libraries, ingesting
  their extras as bogus primary titles). "others" stays removed - it is
  in neither convention.
- Replace label removal with the structural guard the PR had deferred:
  classifyExtraPath now rejects a supplemental-named directory sitting
  at library-scope depth (the dir, any supplemental ancestor, or the
  first non-supplemental ancestor is a configured library root). This
  fixes the original "movies/other/<Title>" defer-storm generically,
  covering every convention label (shorts, scenes, extras, ...) used as
  a content-scope folder.
- Scope extras parent binding by folder.Paths instead of the walk roots,
  so a subtree scan targeting a single movie folder still binds that
  movie's own extras instead of deferring them.

Tests: eligibility-gate unit tests, scope-guard classifier cases
(convention Other/ inside a title binds; scope-level other/shorts stay
primary), and the DB-backed UpdateIdentity test now also covers folder
moves, suppression clearing, and ErrFileNotFound. Full scanner suite ran
green against a migrated scratch PostgreSQL 17 container.

* refactor(scanner): simplify extras scope guard to title-folder rule

Replace the ancestor-walking supplementalDirAtScopeDepth loop with the
plain rule it was approximating: a convention-named directory counts as
an extras dir only when it sits inside a title folder — it must not be a
configured library root or directly under one. Same outcome for the
layouts that matter (movies/other/<Title> stays primary, <Title>/Other
classifies), less machinery.

* test(scanner): assert all rewritten identity columns in UpdateIdentity test

* fix(scanner): make extras scope classification structure-aware

The title-folder rule from 53632022 anchored on library roots, so it
missed both directions: chained convention dirs at the root
("movies/extras/behind the scenes/clip.mkv") classified as extras with
an unresolvable parent (deferred forever), and category folders nested
below the root ("movies/4K/other/<Title>/") still misclassified their
titles.

Replace the root-distance heuristic with the structural property that
actually distinguishes the two cases: a convention-named directory only
counts as an extras dir when its owner (first non-supplemental
ancestor) is a title folder — a directory that holds media of its own.
The new extrasClassifier derives that from the scan's walked path list
(no extra I/O): movie folders must hold a file directly beside the
extras dir; series folders may hold episodes one level down in season
folders (media hiding inside a folder's own extras dirs doesn't count).
Library roots never qualify. Watch-event scans, which have no walked
list, probe ownership with bounded os.ReadDir instead.

This handles title folders at any depth below the root and keeps
scope/category folders primary at any depth, with two known edges: a
title folder holding only extras (its media file missing) stays primary
until the file appears, and a mixed dir holding both loose media and a
category folder degrades to deferral, never wrong linkage.

resolveExtraParent's inline supplemental-chain walk is extracted into
the shared firstNonSupplementalAncestor.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant