Repository navigation
fix(scanner): reconcile deleted files promptly and honor file_removal_grace - #312
Conversation
…_grace Upgraded/replaced media files left dead playable versions until the next full library scan: autoscan file-scope changes for deleted paths failed resolution (ClassifyPath stats the path) and were silently dropped, and scanner.file_removal_grace was dead config — empty_trash_after_scan purged missing-marked rows folder-wide immediately. - Add scantrigger.Resolver.ResolveVanishedPath: maps a vanished video file to a subtree scan of its parent dir, a vanished dir to itself, and an entry directly under a library root to a guarded library scan. Rejects still-existing paths and requires the matched library root to exist on disk so an unmounted share never triggers reconciliation. - Autoscan falls back to it for file-scope and legacy parent-dir changes that fail with a RequestError, closing the dead-version window from ~24h (daily full scan) to roughly one poll interval. - DeleteMissingByFolder now takes the removal grace and only deletes rows missing longer than it (default 24h, restart-required setting); missing rows are already hidden from every client surface, so the grace only preserves per-file state (probe/match/markers) in case the file returns. Remove the uncalled DeleteMissing sweeper. Part of #311 Co-Authored-By: Claude Fable 5 <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughThis PR adds vanished-path reconciliation for autoscan and introduces a configurable file-removal grace period that is applied by scanner cleanup and repository deletion logic. ChangesVanished path resolution and autoscan fallback
File removal grace period and cleanup
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related issues
Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 521d322a62
ℹ️ 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".
…Path Permission or other stat failures must not reconcile still-existing files as missing; reject them with a RequestError instead. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
internal/scantrigger/scantrigger.go (1)
140-179: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSignificant logic duplication with
ResolveMissingSubtree.The folder-listing,
MatchFolderForPathcall, disabled-library check, and trigger normalization (Lines 151-165) closely mirrorResolveMissingSubtree(Lines 109-125). Extracting a sharedmatchEnabledFolder(ctx, cleanPath) (*models.MediaFolder, string, error)helper would reduce drift risk — e.g., a future guard added to one function (such as theos.IsNotExistfix above) could easily be forgotten in the other.🤖 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/scantrigger/scantrigger.go` around lines 140 - 179, `ResolveVanishedPath` duplicates the same folder lookup and validation flow used by `ResolveMissingSubtree`, which will cause the two paths to drift. Extract the shared logic into a helper such as `matchEnabledFolder(ctx, cleanPath)` that handles `r.folders.List`, `MatchFolderForPath`, the disabled-folder check, and trigger normalization, then update both resolvers to call it so future fixes and guards stay consistent.internal/scantrigger/scantrigger_test.go (1)
112-217: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSolid coverage for the main paths; consider adding a disabled-library case.
The subtree/dir/library/root-gone/still-exists scenarios are well covered. There's no test exercising the "Library is disabled" conflict branch (Line 159-161 in scantrigger.go) via
ResolveVanishedPathspecifically, which is part of the safeguards this PR relies on for correctness.🤖 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/scantrigger/scantrigger_test.go` around lines 112 - 217, Add a test in scantrigger_test.go that exercises the disabled-library conflict path through NewResolver.ResolveVanishedPath, similar to the existing ResolveVanishedPath cases. Use a fakeFolderRepo with a MediaFolder whose Enabled field is false, then assert the returned error is a RequestError with the expected conflict status/code, matching the safeguard branch in ResolveVanishedPath.internal/scanner/file_repo.go (1)
2507-2517: 🚀 Performance & Scalability | 🔵 TrivialConfirm an index backs this delete's filter.
This runs after every scan for every folder. If
media_filesdoesn't already have an index covering(media_folder_id, missing_since), this delete degrades to a table/partial scan as the table grows.🤖 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/scanner/file_repo.go` around lines 2507 - 2517, The DeleteMissingByFolder query in FileRepository should be backed by an index so repeated post-scan deletes don’t degrade into scans as media_files grows. Check the existing schema/migrations for an index covering media_folder_id and missing_since, and if it’s missing, add one appropriate for the DELETE filter used by DeleteMissingByFolder so the predicate can be satisfied efficiently.internal/config/db_loader.go (1)
276-283: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueLog a warning when
scanner.file_removal_graceis clamped.Negative values are silently clamped to
0, which disables the grace period this PR is meant to protect, without any operator-visible signal. Thesubtitle_ai.transcribe_quota_jobshandling nearby logs a warning in the equivalent case; consider mirroring that here.♻️ Proposed fix
fileRemovalGrace, err := durationOr(m, "scanner.file_removal_grace", 24*time.Hour) if err != nil { return nil, err } if fileRemovalGrace < 0 { + slog.Warn("invalid scanner.file_removal_grace setting; using 0", "value", m["scanner.file_removal_grace"]) fileRemovalGrace = 0 } cfg.Scanner.FileRemovalGrace = fileRemovalGrace🤖 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/config/db_loader.go` around lines 276 - 283, The scanner.file_removal_grace value is being silently clamped to 0 in db_loader.go, so add an operator-visible warning when fileRemovalGrace is negative before assigning cfg.Scanner.FileRemovalGrace. Mirror the nearby subtitle_ai.transcribe_quota_jobs handling by updating the db_loader logic around durationOr and the fileRemovalGrace clamp to log a warning that includes the invalid value and the fact it was reset to zero, then continue with the clamped value.
🤖 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/scantrigger/scantrigger.go`:
- Around line 148-150: The path existence check in the scan trigger logic is too
broad because `os.Lstat` errors other than “not found” are currently treated as
if the path vanished. Update the `cleanPath` check in `scantrigger.go` to only
treat `fs.ErrNotExist`/`os.IsNotExist(err)` as the missing-path case, keep the
existing “Path still exists” response when `err == nil`, and return a failure
for any other `Lstat` error instead of proceeding to build the reconciling scan
target. Use the surrounding `RequestError` handling in this branch to surface
those unexpected errors.
---
Nitpick comments:
In `@internal/config/db_loader.go`:
- Around line 276-283: The scanner.file_removal_grace value is being silently
clamped to 0 in db_loader.go, so add an operator-visible warning when
fileRemovalGrace is negative before assigning cfg.Scanner.FileRemovalGrace.
Mirror the nearby subtitle_ai.transcribe_quota_jobs handling by updating the
db_loader logic around durationOr and the fileRemovalGrace clamp to log a
warning that includes the invalid value and the fact it was reset to zero, then
continue with the clamped value.
In `@internal/scanner/file_repo.go`:
- Around line 2507-2517: The DeleteMissingByFolder query in FileRepository
should be backed by an index so repeated post-scan deletes don’t degrade into
scans as media_files grows. Check the existing schema/migrations for an index
covering media_folder_id and missing_since, and if it’s missing, add one
appropriate for the DELETE filter used by DeleteMissingByFolder so the predicate
can be satisfied efficiently.
In `@internal/scantrigger/scantrigger_test.go`:
- Around line 112-217: Add a test in scantrigger_test.go that exercises the
disabled-library conflict path through NewResolver.ResolveVanishedPath, similar
to the existing ResolveVanishedPath cases. Use a fakeFolderRepo with a
MediaFolder whose Enabled field is false, then assert the returned error is a
RequestError with the expected conflict status/code, matching the safeguard
branch in ResolveVanishedPath.
In `@internal/scantrigger/scantrigger.go`:
- Around line 140-179: `ResolveVanishedPath` duplicates the same folder lookup
and validation flow used by `ResolveMissingSubtree`, which will cause the two
paths to drift. Extract the shared logic into a helper such as
`matchEnabledFolder(ctx, cleanPath)` that handles `r.folders.List`,
`MatchFolderForPath`, the disabled-folder check, and trigger normalization, then
update both resolvers to call it so future fixes and guards stay consistent.
🪄 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: 2ea4a338-47fe-4f1c-a02b-15d9160c6efb
📒 Files selected for processing (12)
internal/autoscan/service.gointernal/autoscan/service_test.gointernal/config/config.gointernal/config/db_loader.gointernal/config/restart_keys.gointernal/scanner/audiobook_scan.gointernal/scanner/ebook_scan.gointernal/scanner/file_repo.gointernal/scanner/podcast_scan.gointernal/scanner/scanner.gointernal/scantrigger/scantrigger.gointernal/scantrigger/scantrigger_test.go
- Extract shared matchEnabledFolder/normalizeTrigger helpers so ResolveMissingSubtree and ResolveVanishedPath cannot drift. - Warn when a negative scanner.file_removal_grace is clamped to 0. - Add disabled-library test for ResolveVanishedPath. Co-Authored-By: Claude Fable 5 <[email protected]>
…_grace (#312) * fix(scanner): reconcile deleted files promptly and honor file_removal_grace Upgraded/replaced media files left dead playable versions until the next full library scan: autoscan file-scope changes for deleted paths failed resolution (ClassifyPath stats the path) and were silently dropped, and scanner.file_removal_grace was dead config — empty_trash_after_scan purged missing-marked rows folder-wide immediately. - Add scantrigger.Resolver.ResolveVanishedPath: maps a vanished video file to a subtree scan of its parent dir, a vanished dir to itself, and an entry directly under a library root to a guarded library scan. Rejects still-existing paths and requires the matched library root to exist on disk so an unmounted share never triggers reconciliation. - Autoscan falls back to it for file-scope and legacy parent-dir changes that fail with a RequestError, closing the dead-version window from ~24h (daily full scan) to roughly one poll interval. - DeleteMissingByFolder now takes the removal grace and only deletes rows missing longer than it (default 24h, restart-required setting); missing rows are already hidden from every client surface, so the grace only preserves per-file state (probe/match/markers) in case the file returns. Remove the uncalled DeleteMissing sweeper. Part of #311 Co-Authored-By: Claude Fable 5 <[email protected]> * fix(scanner): only treat ENOENT as a vanished path in ResolveVanishedPath Permission or other stat failures must not reconcile still-existing files as missing; reject them with a RequestError instead. Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(scanner): address PR 312 review nitpicks - Extract shared matchEnabledFolder/normalizeTrigger helpers so ResolveMissingSubtree and ResolveVanishedPath cannot drift. - Warn when a negative scanner.file_removal_grace is clamped to 0. - Add disabled-library test for ResolveVanishedPath. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
Problem
Part of #311.
When a file is upgraded or replaced (delete + import via an autoscan source), the deleted file's
media_filesrow stayed live until the next full library scan — up to ~24h — during which clients were still offered the dead version and playback failed with "Source media file is missing" (reproduced on dev, itemmovie-tmdb-1339713).Two root causes:
scantriggerresolution (ClassifyPathstats the path →RequestError) and were skipped without logging. Only the import half of an upgrade triggered a scan, andScanFilereconciles nothing.scanner.file_removal_gracewas dead config.DeleteMissing(grace)had no callers;empty_trash_after_scanpurged missing-marked rows folder-wide immediately on every scan.Approach
scantrigger.Resolver.ResolveVanishedPath: resolves a vanished path to a reconciling scan target — video file → subtree scan of its parent directory; removed directory → itself; entry directly under a library root → guarded full library scan. Two safety guards: still-existing paths are rejected, and the matched library root must exist on disk, so an unmounted share can never resolve into missing-file reconciliation (the empty-root guard keeps protecting whole-root loss).RequestError. Dead-version window drops from ~24h to about one autoscan poll interval; marking missing hides the version from every client surface instantly.DeleteMissingByFoldernow takes the removal grace and only hard-deletes rows missing longer than it (all four scan pipelines: video/ebook/audiobook/podcast).scanner.file_removal_graceis parsed from settings (default 24h, restart-required). Missing rows are already invisible everywhere and membership reconciliation already ignores them, so the grace only preserves per-file state (probe, match, markers) in case the file returns —0restores the previous instant purge. The uncalledDeleteMissingsweeper is removed.Testing
go build ./...,go vet ./...clean; lint findings on touched files are the known local goconst/errcheck baseline.Risks / follow-ups
empty_trash_after_scan=false, missing rows are still never deleted (unchanged behavior); wiring a periodic sweeper is a possible follow-up.AI-use disclosure
Investigated, implemented, and verified with Claude Code (Fable 5); reviewed by the author.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Configuration
file_removal_gracesetting and ensured it requires a restart to take effect.