Skip to content

fix(metadata): refuse a match's link write once the file has moved - #4041

Merged
Quick104 merged 10 commits into
mainfrom
fix/metadata-fence-link-writes-on-path
Nov 13, 2026
Merged

Quick104 merged 10 commits into
mainfrom
fix/metadata-fence-link-writes-on-path

Conversation

@Quick104

@Quick104 Quick104 commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none

#4039 keeps a renamed file's media_files row and, when the new path names another title, clears the row's links so it is matched again. A match job that read the row before the rename can still write its result afterwards, because the matcher's link writes key on the row id alone. The row, now at its new path, is linked back to the old title, and because it is linked the queued rematch no longer changes it. Review of #4039 found this and the maintainer chose to fix it separately.

The movie worker loads its files when it claims a batch of up to 500 jobs, so a snapshot can be minutes old. For a series the worse write is the episode linker: a stale write puts the old show's episode link and numbers on the retitled row and adds an episode_libraries row for the old episode, and nothing revisits it because the linker only looks at rows with no episode link. Files already matched are not in the queue, so a bulk rename of a matched library is unlikely to hit this; a file being matched or retried as it is renamed can.

With this change a match's link write applies only while the row still has the path the match read.

Approach

FileRepository.UpdateContentID and UpdateEpisodeLink take the path the caller read the file at and write only while the row still has it. A refused write returns the new ErrFileMoved; a row that is gone still returns ErrFileNotFound. Every production caller of the two functions is a matcher write, so the signatures changed in place and no unfenced version remains.

In createOrFindSkeleton a refused link is an ordinary link failure: the job records the error, a skeleton item it had just created is deleted by the existing cleanup, and the queue runs the job again against the row as it is now (the retitle's re-enqueue has already set the rerun flag on the leased queue row). The episode linker treats a refusal two ways. A retitled row has no series link any more and is left for its rematch. A row that moved within its title still carries the series link and no rematch is queued for it, so the linker reloads it and retries once at its current path when it is still linked to the same series, has no episode, and its path names the same episode.

When a later step fails after the link was written, createOrFindSkeleton undoes the link. That undo is keyed on the link, not the path: it clears the row only while it still carries the link this call made, so a same-title move in between does not strand the file on an item with no library membership, and a link another writer put there is left alone. A failed undo is returned in the job's error. The undo now writes NULL where it used to write an empty string.

Writes that select rows by their current columns (UpdateContentIDByObservedRootPath, BulkLinkEpisodesBySeries, group relinks, ReplaceContentID) need no fence: a retitled row no longer has the root, group, or link they select by.

A rename that keeps the title also changes the path, so a stale same-title skeleton link is now refused too. That costs one extra match run and changes no outcome. No API, migration, or settings change; clients and jellycompat are unaffected. The rule is recorded in docs/architecture/missing-files.md.

Validation

  • A database-backed scanner test scans a file, links it, takes the matcher's snapshot, renames the file to another title on disk and rescans, then makes the matcher's writes from the snapshot. It asserts the write is refused and the row stays unlinked at its new path, for a movie and for a series episode. It fails with the fences disabled, and the series case fails with only the episode fence disabled.
  • A database-backed metadata test runs the real createOrFindSkeleton with a failing folder check and covers the undo after a same-title move and after another writer's link. Both cases fail on the commit before the undo fix.
  • A database-backed metadata test runs the real episode linker with a move landing between its listing and its write: a same-title move ends linked at the new path (fails before the retry was added), and a retitled file stays unlinked.
  • go build ./..., gofmt, go vet on the touched packages, make lint-changed against the fix(scanner): keep a renamed file's row when the rename changes its parsed title #4039 head, and make verify-local-paths: pass.
  • Scanner, metadata, and catalog tests against a migrated Postgres pass on macOS, except three scanner tests that depend on filesystem behavior and fail the same way without this change.
  • Not run locally: the full pre-PR gate; CI covers it.
  • The rerun after a refused write is read from the queue SQL, shared by the movie and series queues; no worker was run end to end.
  • The multi-node case is reasoned, not tested: the fenced update waits on the retitle's row lock and rechecks the path after it commits.

Evidence

No user-visible change. The page holds the steps, the build, and the test results.

Evidence: https://evidence.siloserver.org/r/silo-server/pr-4041/

Risks

  • If a retitled row gets its old path back (a reverted rename), a stale job that read that path is accepted again. It links the row to the title the row has again, so the outcome is right, but the fence does not tell the two reads apart.
  • A job refused after it recorded a group or root claim leaves that claim for the snapshot's old group; the retitled row no longer belongs to that group.
  • The older background path (processFile through ClaimUnmatched) only logs a refusal and relies on its own retry schedule.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code (in T3 Code)
  • Tool(s): Claude Code agent tools and a delegated agent
  • Model(s): claude-opus-5-5 (wrote the code), claude-fable-5-2 (direction, verification, this description)
  • Involvement: Fully AI-generated (maintainer review pending)
  • Adversarial review: none beyond the review of fix(scanner): keep a renamed file's row when the rename changes its parsed title #4039 that found the defect (CodeRabbit and Codex). Bot review of this PR then led to keying the undo of a skeleton link on the link, and to retrying the episode link for a file that moved within its title.

🤖 Generated with Claude Code

Note

Refuse stale-path content and episode link writes after a file move

  • Adds a path fence to FileRepository.UpdateContentID and FileRepository.UpdateEpisodeLink in file_repo.go: writes now apply only when the row still has the caller's path. A missing row returns ErrFileNotFound; an existing row at a new path returns the new scanner.ErrFileMoved sentinel.
  • Episode linking in service.go handles ErrFileMoved via linkMovedEpisodeFile: it reloads the row and retries once at the current path, only when the row is still eligible for the same episode.
  • Skeleton matching in createOrFindSkeleton passes the listed path to each link write and, on later failure, undoes only its own link through the new unlinkSkeletonFile helper and UnlinkContentID.
  • Documents the interaction between path-fenced writes and file moves in missing-files.md, and adds database tests covering retitle refusals, skeleton undo, and same-title episode-link moves.
  • Risk: FileContentUpdater and EpisodeLinker interfaces changed — UpdateContentID and UpdateEpisodeLink now take a file path, and UnlinkContentID is new; any implementation outside the updated in-tree fakes must add these signatures.

Macroscope summarized 273207d.

Quick104 and others added 6 commits November 12, 2026 13:02
…arsed title

A file whose bytes are unchanged (same size, OSHash, and modification time)
now keeps its media_files row across any rename or move, so trickplay,
chapter images, probe data, subtitles, and downloads follow it. Before, a
rename that changed what the path parses to, such as adding a provider ID
tag, got a new row and regenerated everything.

When the new path's provider tags agree with the linked title's stored IDs,
the links stay. Otherwise the row drops its links and is matched like a new
file, and a missing stand-in row at the old path holds the old title through
the usual removal grace. Undoing such a rename gives the row its path and
links back.

Marker thumbnails no longer reset on a path change alone; the relink rewrites
their path-hashed identities.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Keep a renamed row's links only when matching the new path would resolve to
the title it already has: group and root claims, series siblings under the
observed root, then the group's provider IDs compared in the type's anchor
precedence. The comparison moves from metadata to catalog so both use it.

A stand-in reclaim that cannot be decided (database error, unreachable or
empty old root, fence lost twice) now fails the file for this scan instead of
writing it onto the stand-in.

Probe each library root once per lookup and stop once the pick is settled.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A retitle moves the row's downloads for its old title onto the stand-in, so
they are refused and later deleted as they were with the missing row, and a
reverted rename brings them back. Without this a download kept serving a
file that now belongs to another title.

The series sibling lookup that decides whether a renamed row keeps its links
no longer counts the row itself.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…file row

A download parked on a retitle's stand-in still pointed at the retitled row's
prepared artifact, so its remux or transcode could be served or prepared
again under the old title. Serving and preparing again now require the
artifact to belong to the download's file row.

An unlinked row that still carries downloads for a title now leaves a
stand-in for them, independent of the link comparison.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
PrepareDownloadAgain compared the artifact with the download as the caller
read it, so a download parked on a stand-in mid-request still requeued the
retitled row's artifact and became preparing. It now locks the download row
after the artifact and refuses before any requeue when the download's file
is no longer the one read or the artifact's own.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A match job that read a file before a rename retitled its row could still
link the row, now at its new path, back to the old title. The movie worker
holds a claimed batch's snapshots for minutes, the worker's group check
passes once the scan removed the old group, and the retitle's re-enqueue
only flags the leased queue row for a rerun. Linked again, the row kept the
old title through its rematch; a stale episode link left the old show's
episode on a row the episode linker never revisits.

FileRepository.UpdateContentID and UpdateEpisodeLink now take the path the
caller read and write only while the row still has it, returning
scanner.ErrFileMoved otherwise. Every caller is a matcher write, so the
signatures change in place rather than gaining variants. A refused skeleton
link is the job's error: the queue records it and, with the rerun flag the
retitle set, runs the job again at once against the current row, and a
skeleton the job had just created is deleted again while unreferenced. The
episode linker skips the moved file and goes on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added the size/L 200–499 added + deleted lines (all files); change volume, not priority. label Nov 12, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T01:01:02.389188Z 273207d New commits
🔒 Security Review ✅ Completed 2026-11-13T01:03:05.791124Z 273207d New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish stacked Base is another open PR; merge in stack order named in the body labels Nov 12, 2026
@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Matcher link writes now require the file path observed by the job. The repository returns ErrFileMoved when that path no longer matches. Metadata code handles moved episode files, and skeleton cleanup removes a link only when it still points to that skeleton.

Changes: Matcher link fencing and cleanup

Layer / File(s) Summary
Repository path-fenced writes
internal/scanner/file_repo.go, internal/scanner/file_link_fence_db_test.go, internal/scanner/*_test.go, scripts/ci/db-contracts.txt
Content and episode link updates check the expected file path. Database tests verify that stale writes after a retitle return ErrFileMoved and leave the row without links.
Metadata path propagation and moved-file handling
internal/metadata/service.go, internal/metadata/*_test.go, internal/scanner/*_test.go, docs/architecture/missing-files.md
Metadata callers pass the expected path to link updates. When episode linking receives ErrFileMoved, it reloads the file and retries only if the row and episode hint still match. The documentation describes these checks.
Conditional skeleton-link cleanup
internal/metadata/service.go, internal/metadata/service_test.go, internal/metadata/skeleton_unlink_db_test.go
When folder validation or membership creation fails, cleanup unlinks the file only if it still points to the skeleton. Tests cover intervening path and content-link changes.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Low

Sequence Diagram(s)

sequenceDiagram
  participant MetadataService
  participant FileRepository
  MetadataService->>FileRepository: UpdateEpisodeLink with observed path
  FileRepository-->>MetadataService: ErrFileMoved when path differs
  MetadataService->>FileRepository: Reload file by ID
  MetadataService->>FileRepository: Retry with current path if checks pass
Loading

Possibly related PRs

Suggested reviewers: rhainland, blurbery

Merge Risk: Minimal · up to 27320

Link writes now refuse a stale file path, and skeleton cleanup removes only the link it created. No actionable merge-blocking issue was found in this review.

Security architecture risk: Low · up to 27320

The change narrows stale match writes and makes cleanup preserve links installed by another writer. No introduced security concern was established. Some concurrent ownership changes remain outside the path check, and broader security and deployment coverage is incomplete.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — Each changed mutation targets one file ID. Episode linking also affects that file's library membership and the membership-derived state of affected series. The moved-file retry retains the originally listed ID rather than selecting an arbitrary replacement file.

Trust Boundaries and Controls

  • inferred — File-path-derived match decisions cross into durable catalog state through a stronger freshness check. Path equality is not an authorization or complete generation check: a path that changes and returns can still match, and the retry's series and unlinked predicates are not rechecked inside the locked write. The prior implementation was already vulnerable to stale same-path decisions; increased security exposure from the remaining limitation was not established.

Resilience and Maintainability Implications

  • observed — The retry is bounded, and a second path mismatch does not force a write. Unlinked present files remain eligible for a later linker listing. Added database tests exercise same-title versus retitled moves and cleanup that preserves another writer's link, but these tests skip without a database URL and were not executed in this review.

Hardening Proposals

  • proposed — If same-path concurrent relinking must also be excluded, extend the locked episode mutation with expected series and unlinked-state predicates, or a monotonic link-generation token. This would strengthen an existing limitation rather than remediate a demonstrated new attack path.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "fix(metadata): refuse a match's link write once the file has moved" matches the main change: match link writes (UpdateContentID and UpdateEpisodeLink) now require the file path and return E…
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.
Description check Passed The description explains the problem and approach for a path fence on FileRepository.UpdateContentID and UpdateEpisodeLink so stale match-job writes are refused after a file moves. It names the change…
Full details: Title check

Explanation

The title "fix(metadata): refuse a match's link write once the file has moved" matches the main change: match link writes (UpdateContentID and UpdateEpisodeLink) now require the file path and return ErrFileMoved when the row has moved. The changeset also includes scanner, test, and doc updates that support this fence, so the title is specific to the primary change.

Full details: Description check

Explanation

The description explains the problem and approach for a path fence on FileRepository.UpdateContentID and UpdateEpisodeLink so stale match-job writes are refused after a file moves. It names the changed areas: the ErrFileMoved sentinel, the episode linker retry, skeleton undo via UnlinkContentID, the docs page, and the database tests. This matches the changeset, so the check passes.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 54e684c3-817d-444a-a28d-edfe750afe5c
Commits

Reviewing files that changed from the base of the PR and between 5eeeca2 and 273207d.

Files selected for processing: 4

  • docs/architecture/missing-files.md
  • internal/metadata/episode_link_move_db_test.go
  • internal/metadata/service.go
  • scripts/ci/db-contracts.txt

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

@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

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e499aa5d-0db5-4fc3-bacf-dbe6d24b23b4
Commits

Reviewing files that changed from the base of the PR and between d38988d and 907e833.

Files selected for processing: 12

  • docs/architecture/missing-files.md
  • internal/metadata/fallback_episode_test.go
  • internal/metadata/queued_identity_parity_test.go
  • internal/metadata/series_queue_override_test.go
  • internal/metadata/service.go
  • internal/metadata/service_test.go
  • internal/scanner/file_link_fence_db_test.go
  • internal/scanner/file_repo.go
  • internal/scanner/file_repo_scan_provenance_test.go
  • internal/scanner/multi_episode_file_test.go
  • internal/scanner/variant_finalize_columns_db_test.go
  • scripts/ci/db-contracts.txt

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

Comment thread internal/metadata/service.go Resolved
When a step after createOrFindSkeleton's link failed (the folder re-check or
the library membership), the undo went through the path-fenced
UpdateContentID. A same-title move between link and undo keeps the link and
changes the path, so the undo was refused and the file kept a link to a
skeleton with no library membership, which deleteCreatedSkeleton then kept
and the unlinked-file queries no longer saw.

FileRepository.UnlinkContentID clears content_id only while the row still
carries the link this call made, whatever its path, and leaves a link
another writer put there; both branches use it, and a failed undo is joined
into the error the job records. The link writes stay path-fenced.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Base automatically changed from fix/scanner-reuse-artifacts-on-rename to main November 13, 2026 00:41
@silo-triage silo-triage Bot added size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. and removed size/L 200–499 added + deleted lines (all files); change volume, not priority. labels Nov 13, 2026
…nk-writes-on-path

# Conflicts:
#	docs/architecture/missing-files.md
@silo-triage silo-triage Bot added size/L 200–499 added + deleted lines (all files); change volume, not priority. and removed size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. labels Nov 13, 2026
@silo-kody

silo-kody Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Comment thread internal/metadata/service.go Resolved
Quick104 and others added 2 commits November 12, 2026 19:55
The episode linker's fenced write is refused when a scan moves the file
after the linker listed it. For a retitled row that is right: its links are
cleared and its rematch is queued. A move within the title
(RelinkMovedFile) keeps the series link, though, so EnqueueSeriesRoot
queues nothing for a matched series and the file stayed without its episode
until the series was next refreshed.

On a refused write the linker now reloads the row and retries once at its
current path, only when the row is present, still linked to this series
with no episode, and its path parses to the same episode the linker
resolved. The retry is fenced like the first write.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added size/XL 500–999 added + deleted lines (all files); change volume, not priority. and removed size/L 200–499 added + deleted lines (all files); change volume, not priority. labels Nov 13, 2026
@silo-kody

silo-kody Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104
Quick104 merged commit fb165fa into main Nov 13, 2026
20 checks passed
@Quick104
Quick104 deleted the fix/metadata-fence-link-writes-on-path branch November 13, 2026 01:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/XL 500–999 added + deleted lines (all files); change volume, not priority. stacked Base is another open PR; merge in stack order named in the body

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant