Skip to content

fix(scanner): keep a file's row when it is renamed or moved - #2877

Merged
Quick104 merged 3 commits into
mainfrom
fix/issue-2858-keep-file-row-on-rename
Oct 21, 2026
Merged

Quick104 merged 3 commits into
mainfrom
fix/issue-2858-keep-file-row-on-rename

Conversation

@Quick104

@Quick104 Quick104 commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #2858
Related issue: N/A
Validation tasks: none

When a video file is renamed or moved inside a library, the scanner gives the new path a new media_files row and marks the old row missing. Everything stored against the old row's id stays behind and is deleted with it when the file removal grace runs out: manual marker edits, downloaded and AI-generated subtitles with their timing corrections, sidecar timing corrections, users' offline downloads, trickplay, and intro/credits analysis. Radarr and Sonarr rename files routinely, so this hits anyone who uses them, as well as anyone who reorganizes folders.

With this change, a file that shows up at a new path takes over the row of the file it was, so that state follows it.

Approach

When the scanner meets a path it has no row for, it already computes the file's OSHash. It now looks in the same library for a row with the same size, OSHash, and modification time. That row is relinked only when all of these hold:

  • the new path parses to the same title as the old one: content group, filename hints (title, year, season, episode, air date), episode range, and provider ID tags;
  • the old path is gone, under a library root that answers and is not empty;
  • exactly one row qualifies.

The relink is a single fenced update. It changes the path, clears missing_since, and refreshes the path-derived identity and sidecar list. Probe data and chapters are left alone, and the update only applies if the row still has the path, bytes, and links that were checked. If another scan already wrote the new path (it won the update, or its write landed after this scan read its snapshot), the file is not ingested a second time.

Anything that doesn't qualify is handled as before, with a new row and a fresh match:

  • a copy whose original is still there;
  • a rename to another title, including adding an {imdb-…} tag to fix a wrong match;
  • a daily-episode date correction or an episode-range change;
  • a file whose old root is offline.

MarkMissing now takes the path its caller read and only marks a row still at that path. That stops a scan holding the old path (or a playback preflight on it) from hiding the row that just moved. A moved row is skipped quietly, not counted as a scan error.

This covers primary video files in movie and series libraries, through full scans, subtree scans, and file-level scans from the watcher and arr webhooks (which send the new path before the old one). Extras and Books libraries are unchanged. The rule is recorded in docs/architecture/missing-files.md. No API, migration, or setting changes; clients and jellycompat are unaffected beyond a stable file id across renames.

Validation

  • Database-backed scanner test with real files on disk against a migrated Postgres. It covers rename in a folder, move across folders, a move after the old path was already marked missing, and a rename reported new path first. It also checks the cases that must still get a new row: copy, retitle, daily-episode date fix, episode range change, and a new file at the old path. The four relink cases fail on main (new row id, timing correction left behind) and pass here. The negative cases pass on both, and each new gate was checked by disabling it.
  • go build, go vet, gofmt, make lint-changed, make lint-router-recovery, make verify-local-paths, make verify-case-collisions: pass.
  • make test-go: one failure, internal/mediasample TestRunStatsWithRealFFmpeg. It fails the same way on main on the test host (depends on the host's ffmpeg), so it is baseline.
  • Not reproduced on a live deployment: no sandbox could be created when this ran. Web checks were not run; nothing under web/ changed.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/issue-2858/

Risks

  • The byte comparison is OSHash (size plus first and last 64 KiB) plus modification time, so it is a strong heuristic, not proof. Two different files with identical size, head, tail, and mtime, where one vanished as the other appeared with the same parsed title, would share a row.
  • Two things still key on the path and start over after a relink: marker thumbnails (the existing trigger clears them on a path change; they regenerate) and download preparations, whose recipe fingerprint includes the source path. A preparation that is encoding when its file is renamed now fails its recipe check and has to be requested again. Before this change it would commit against a row that was about to go missing.
  • Two scans handling the same new path at once can still interleave so that one relinks the row and the other's insert lands on it within its probe time. The insert updates that row in place, so its id and everything keyed to it survive; only its chapters (thumbnails regenerate) and an import-assigned edition are rewritten from a fresh probe of the same bytes.
  • Root claims (media_item_roots) are not moved. They are dedup hints, and the relink requires the same content group, so the group claim still points at the same item.

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 subagents; Codex for the plan review

  • Model(s): claude-opus-5-5 (wrote the code), claude-sonnet-5-5 (cleanup review pass), gpt-6.1-sol (plan review)

  • Involvement: Fully AI-generated (maintainer review pending)

  • Adversarial review: the plan was attacked by gpt-6.1-sol before implementation. That round led to these changes:

    • check that the old path is gone for every candidate, including rows already marked missing;
    • fence the update on the row's bytes and links;
    • move the path and restore presence in one statement;
    • add filename-hint and mtime gates;
    • use a metadata-only update instead of the re-probe path.

    A multi-angle code review of the diff then added the lost-race handling and the episode-range gate, and corrected the docs. Bot review then led to stale-snapshot handling, comparing episode ranges parsed from each path, and a bounded probe of the old path's directory before the final stat. The background adversarial review (gpt-6.1-sol, reviewed 6c9d725) found no new issues; the race it reproduced is the one fixed in 7a0fce4.

🤖 Generated with Claude Code

Note

Keep media-file row when a file is renamed or moved

  • Adds moved-file relinking in scanner.go: a newly observed path can take over an existing media-file row when content hash/size, modification time, content-group identity, and path-derived identity all match, and the old path is gone from a reachable, non-empty root. The row ID and ID-keyed state (e.g. subtitle timing) are retained.
  • Adds repository support in file_repo.go: MovedFileCandidates finds candidates, RelinkMovedFile performs an atomic, fenced relink update, and MarkMissing now requires both the media-file ID and the observed path so a moved row is not marked missing.
  • Passes the observed path through the MissingFileMarker interface and the audiobook, ebook, and podcast missing-file reconcilers, so scans no longer mark rows that moved between snapshot and update.
  • Covers renames, moves, copies, prior missing marking, and reverse delivery order in database-backed tests (file_relink_db_test.go); the contract is registered in db-contracts.txt and design notes added in missing-files.md.
  • Behavioral Change: FileRepository.MarkMissing and handlers.MissingFileMarker now require a path argument; implementations outside this repo must be updated. Files without an OSHash, ambiguous candidates, or unreachable roots fall back to normal new-file ingestion.

Macroscope summarized 14262eb.

A video file that appears at a new path now takes over the media_files
row of the file it was, so markers, subtitle timing, trickplay, analysis
artifacts, and downloads keyed to the row's id follow it instead of
staying on a missing row until the trash sweep deletes them.

A row qualifies only when it is in the same library with the same size,
OSHash, and mtime, the new path parses to the same title, episode range,
and provider tags, and its old path is gone under a reachable, non-empty
root. The update is fenced on the row's path, bytes, and links, and
MarkMissing now only marks a row still at the path its caller read.

Closes #2858

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added the size/XL 500–999 added + deleted lines (all files); change volume, not priority. label Oct 21, 2026
@silo-kody

silo-kody Bot commented Oct 21, 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 ❌

@coderabbitai

coderabbitai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 20 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ae58270d-63cd-4620-99a6-5bb76cb63098
📥 Commits

Reviewing files that changed from the base of the PR and between 6c9d725 and 14262eb.

📒 Files selected for processing: 2
  • internal/scanner/file_relink.go
  • internal/scanner/file_repo.go

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e77bfdbe-b946-425e-84d9-ee568c415f06
📥 Commits

Reviewing files that changed from the base of the PR and between 61a6031 and 6c9d725.

📒 Files selected for processing: 11
  • docs/architecture/missing-files.md
  • internal/api/handlers/playback_missing.go
  • internal/api/handlers/playback_test.go
  • internal/scanner/audiobook_scan.go
  • internal/scanner/ebook_scan.go
  • internal/scanner/file_relink.go
  • internal/scanner/file_relink_db_test.go
  • internal/scanner/file_repo.go
  • internal/scanner/podcast_scan.go
  • internal/scanner/scanner.go
  • scripts/ci/db-contracts.txt

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

📝 Walkthrough

The scanner can relink eligible renamed or moved files to existing media-file rows. Missing-file reconciliation now checks the observed path before marking a row missing. Database tests cover relinking cases and scan order.

Changes: Scanner file relinking

Layer / File(s) Summary
Path-checked missing-file reconciliation
internal/scanner/file_repo.go, internal/scanner/scanner.go, internal/scanner/audiobook_scan.go, internal/scanner/ebook_scan.go, internal/scanner/podcast_scan.go, internal/api/handlers/playback_missing.go, internal/api/handlers/playback_test.go
Missing-file marking receives the observed path. The repository only marks a row missing when its path still matches, and scanner reconciliation treats ErrFileNotFound as a concurrent relink or deletion.
Moved-file matching and relinking
internal/scanner/file_repo.go, internal/scanner/file_relink.go, internal/scanner/scanner.go
The scanner checks candidate files against file and path identity, episode range, and library-root availability. A unique match updates the existing row and queues metadata work before normal probing or insertion.
Relinking tests and documentation
internal/scanner/file_relink_db_test.go, scripts/ci/db-contracts.txt, docs/architecture/missing-files.md
Database tests cover rename, move, copy, title, episode, and scan-order cases. Documentation describes relinking criteria and data that follows the row or restarts.

Priority: ⚪ Pending latest changes

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

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant Scanner
  participant relinkMovedFile
  participant FileRepository
  participant LibraryRoot
  participant MetadataQueue
  Scanner->>relinkMovedFile: check new file for an existing row
  relinkMovedFile->>FileRepository: find moved-file candidates
  relinkMovedFile->>LibraryRoot: check old path under reachable, non-empty root
  relinkMovedFile->>FileRepository: relink matching row
  relinkMovedFile->>MetadataQueue: enqueue metadata work
Loading

Suggested reviewers: rhainland, coffeeknyte

Merge Risk: 🟡 Moderate · up to 6c9d7

Concurrent scans can replace retained per-file data, and certain relink checks can stall scanning. Resolve these risks before merging; the episode-range concern also needs confirmation for imported files.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 9 files. (2 skipped: 2… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title concisely and accurately describes the primary change: preserving a file's database row when the scanner detects a rename or move.
Linked Issues check Passed Issue #2858 requires a renamed or moved primary video to retain its media_files row and row-keyed state, while copies and identity-changing renames receive new rows. The implementation finds candida…
Out of Scope Changes check Passed The changes stay within issue #2858. Scanner, repository, and missing-file updates support safe row relinking and race handling. The database contract test verifies the required behavior. The architec…
Description check Passed The pull request description directly explains the moved-file relinking changes, affected scanner behavior, validation, risks, and test coverage described in the changeset.
Full details: Linked Issues check

Explanation

Issue #2858 requires a renamed or moved primary video to retain its media_files row and row-keyed state, while copies and identity-changing renames receive new rows. The implementation finds candidates by folder, size, and OSHash, then gates relinking on modification time, content-group and path identity, provider IDs, episode range, and a reachable non-empty root with the old path absent. RelinkMovedFile fences the update on the old row path, bytes, modification time, and links, clears missing_since, and refreshes path-derived identity and sidecars without replacing the row. MarkMissing now checks the observed path, which prevents a stale scan from hiding the relinked row. The database-backed test covers the relink and negative cases described for #2858.

Full details: Out of Scope Changes check

Explanation

The changes stay within issue #2858. Scanner, repository, and missing-file updates support safe row relinking and race handling. The database contract test verifies the required behavior. The architecture documentation records the new rule and its limits. Updates to audio, ebook, podcast, and playback missing-file callers adapt the path-checked MarkMissing contract and prevent the same stale-path race; they do not add unrelated feature behavior. No API, migration, setting, client, extras, or Books relinking changes are introduced.

Full details: Docstring Coverage

Explanation

Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 9 files. (2 skipped: 2 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code impact: data-loss User data deleted, corrupted, or unrecoverable priority: P0 Fix/merge first: data-loss, security, or widespread breakage labels Oct 21, 2026
Comment on lines +80 to +82
if len(candidates) == 0 {
return false, nil
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug critical

Race condition identified in destination ingestion: MovedFileCandidates excludes the destination path, so concurrent scans with stale existingByPath snapshots can miss a completed relink, enter the empty-candidate branch, and invoke the normal Upsert, whose conflict handler overwrites the preserved row's chapters, probe data, and imported edition fields. Synchronize destination ingestion or make fallback insertion atomically preserve an existing destination row.

Prompt for LLM

File internal/scanner/file_relink.go:

Line 80 to 82:

Race condition identified in destination ingestion: MovedFileCandidates excludes the destination path, so concurrent scans with stale existingByPath snapshots can miss a completed relink, enter the empty-candidate branch, and invoke the normal Upsert, whose conflict handler overwrites the preserved row's chapters, probe data, and imported edition fields. Synchronize destination ingestion or make fallback insertion atomically preserve an existing destination row.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 7a0fce4. MovedFileCandidates now also returns any row already at the new path, and tryRelinkMovedFile stops there instead of falling through to the insert, so a scan whose snapshot predates another scan's relink leaves that row alone.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks—that addresses the stale-snapshot case when the other scan’s relink completes before MovedFileCandidates runs.

There is still a possible interleaving to check:

  1. Scan B queries candidates before scan A relinks.
  2. Scan A relinks the row to the destination.
  3. Scan B reaches the fallback Upsert, which conflicts with that destination row.

Returning an existing destination row does not, by itself, protect the interval between the query and the write. Unless ingestion is serialized or the fallback insert atomically preserves an existing destination row, the original overwrite risk remains.

I haven’t inspected 7a0fce4a1, so I can’t confirm whether it includes that additional protection.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That interleaving is still possible: two scans handle the same new path at once, the other one relinks after this one queried candidates, and this one's insert lands within its probe time. I'm leaving it, because the cost is small. The upsert conflicts on file_path and updates the relinked row in place, so the row id and everything keyed to it survive: markers and their edits, subtitles and timing, trickplay, analysis, downloads. What it can rewrite are the row's own columns, from a fresh probe of the same bytes: chapters (their thumbnails regenerate) and an import-assigned edition, which falls back to the path's edition. Closing that window needs per-path serialization of ingestion or an insert-only path for new files, which changes how existing paths re-ingest. I think that belongs in its own change if it proves worth it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

That narrows the impact materially. Based on your explanation, the remaining race preserves the row ID and its dependent state; it can overwrite row-local metadata, notably the import-assigned edition and chapters.

I would not treat that as critical or a blocker for this PR. The edition fallback is still a real metadata-loss case—not just harmless re-probing—but deferring it to a separate change is reasonable given the limited concurrency window and the implications of changing ingestion behavior.

The accurate disposition is a known, accepted residual race, rather than fully fixed by 7a0fce4a1. That commit handles the stale-snapshot case where the destination row exists before the candidate query; the query-to-upsert window remains.

Comment thread internal/scanner/file_relink.go Resolved
Comment thread internal/scanner/file_relink.go Resolved
Comment thread internal/scanner/file_relink.go Resolved
…ounts

A scan whose snapshot predates another scan's write now leaves a row
already at the new path alone instead of overwriting it with a fresh
probe. The episode range check compares the ranges both paths declare,
not a range an import recorded on the old row. The old path's directory
is probed with a timeout before the final stat, so a dead mount below
the library root cannot hang a scan worker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 21, 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 ❌

Check the old path with rootcheck's bounded, per-path coalesced probe
instead of a directory probe followed by a bare Lstat, so a mount that
stops answering between the two calls cannot hang a scan worker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 21, 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 ❌
⚠️ 1 Kody Rule(s) were not evaluated

These rules declare that they need repository context beyond this diff, and the review could not retrieve it, so they were not judged on this pull request:

  • Preserve optional store capabilities through production wrappers

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 impact: data-loss User data deleted, corrupted, or unrecoverable priority: P0 Fix/merge first: data-loss, security, or widespread breakage size/XL 500–999 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] Renaming or moving a video file starts a new file row and loses its per-file state

1 participant