Repository navigation
fix(scanner): keep a file's row when it is renamed or moved - #2877
Conversation
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 Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
Warning Review limit reachedYou'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. View limit details
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
📝 Walkthrough
Merge Risk: 🟡 Moderate · up to
|
| if len(candidates) == 0 { | ||
| return false, nil | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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:
- Scan B queries candidates before scan A relinks.
- Scan A relinks the row to the destination.
- 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
…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 — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
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 — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
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_filesrow 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 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:
{imdb-…}tag to fix a wrong match;MarkMissingnow 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
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/mediasampleTestRunStatsWithRealFFmpeg. It fails the same way onmainon the test host (depends on the host's ffmpeg), so it is baseline.web/changed.Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/issue-2858/
Risks
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
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:
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
MovedFileCandidatesfinds candidates,RelinkMovedFileperforms an atomic, fenced relink update, andMarkMissingnow requires both the media-file ID and the observed path so a moved row is not marked missing.MissingFileMarkerinterface and the audiobook, ebook, and podcast missing-file reconcilers, so scans no longer mark rows that moved between snapshot and update.FileRepository.MarkMissingandhandlers.MissingFileMarkernow 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.