Skip to content

fix(scanner): reconcile deleted files promptly and honor file_removal_grace - #312

Merged
Quick104 merged 3 commits into
mainfrom
fix/autoscan-vanished-paths-removal-grace
Jul 5, 2026
Merged

Quick104 merged 3 commits into
mainfrom
fix/autoscan-vanished-paths-removal-grace

Conversation

@Quick104

@Quick104 Quick104 commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Part of #311.

When a file is upgraded or replaced (delete + import via an autoscan source), the deleted file's media_files row 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, item movie-tmdb-1339713).

Two root causes:

  1. Autoscan silently dropped delete events. File-scope changes whose path no longer exists fail scantrigger resolution (ClassifyPath stats the path → RequestError) and were skipped without logging. Only the import half of an upgrade triggered a scan, and ScanFile reconciles nothing.
  2. scanner.file_removal_grace was dead config. DeleteMissing(grace) had no callers; empty_trash_after_scan purged missing-marked rows folder-wide immediately on every scan.

Approach

  • New 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).
  • Autoscan falls back to it wherever it previously dropped changes: file-scope changes and legacy parent-dir resolution that fail with a RequestError. Dead-version window drops from ~24h to about one autoscan poll interval; marking missing hides the version from every client surface instantly.
  • DeleteMissingByFolder now takes the removal grace and only hard-deletes rows missing longer than it (all four scan pipelines: video/ebook/audiobook/podcast). scanner.file_removal_grace is 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 — 0 restores the previous instant purge. The uncalled DeleteMissing sweeper is removed.

Testing

  • New unit tests: resolver (vanished file → parent subtree, vanished dir → itself, entry under root → library mode, root-gone → conflict, still-exists → rejected) and autoscan fallback (file-scope and legacy-dir changes for deleted paths enqueue subtree scans).
  • go build ./..., go vet ./... clean; lint findings on touched files are the known local goconst/errcheck baseline.
  • Deployed to the dev server: healthy, autoscan claiming ~30 changes/min, scans completing; monitoring confirms previously-marked missing rows now survive scans within the grace window.

Risks / follow-ups

  • With empty_trash_after_scan=false, missing rows are still never deleted (unchanged behavior); wiring a periodic sweeper is a possible follow-up.
  • Deleted non-video files (e.g. external subtitles) resolve to a harmless no-op subtree scan of the file path itself; refining that to rescan the parent dir for subtitle reconciliation is a follow-up.
  • Suggested UX follow-up from the same investigation: playback preflight could fall back to another non-missing version instead of returning 404 (Upgraded/replaced media files linger as dead playable versions until the next full scan #311 discussion).

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

    • Improved handling for vanished/deleted filesystem paths so scans can reconcile and re-queue targets more accurately.
    • Introduced a configurable grace period before removing missing files after scans.
  • Bug Fixes

    • Updated empty-trash behavior to avoid removing newly-missing items until they exceed the grace period.
    • Improved scan recovery by falling back to broader subtree reconciliation when paths disappear.
  • Configuration

    • Added file_removal_grace setting and ensured it requires a restart to take effect.

…_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]>
@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 982379ed-b3a7-427f-bd17-1716a0010bd2

📥 Commits

Reviewing files that changed from the base of the PR and between dc6dbb8 and 667887b.

📒 Files selected for processing (3)
  • internal/config/db_loader.go
  • internal/scantrigger/scantrigger.go
  • internal/scantrigger/scantrigger_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/config/db_loader.go
  • internal/scantrigger/scantrigger_test.go
  • internal/scantrigger/scantrigger.go

📝 Walkthrough

Walkthrough

This 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.

Changes

Vanished path resolution and autoscan fallback

Layer / File(s) Summary
ResolveVanishedPath behavior
internal/scantrigger/scantrigger.go, internal/scantrigger/scantrigger_test.go
Adds Resolver.ResolveVanishedPath, which validates the path is gone, matches it to a library root, chooses library or subtree mode, and covers subtree, root, and error cases in tests.
Autoscan fallback wiring
internal/autoscan/service.go, internal/autoscan/service_test.go
Extends autoscan to treat scantrigger.RequestError as a trigger for ResolveVanishedPath, adds isRequestError, and updates test resolvers and polling tests for vanished-path fallback.

File removal grace period and cleanup

Layer / File(s) Summary
FileRemovalGrace configuration
internal/config/config.go, internal/config/db_loader.go, internal/config/restart_keys.go
Adds ScannerConfig.FileRemovalGrace, loads scanner.file_removal_grace from settings with clamping, and marks the key as restart-required.
Grace-based missing-file deletion
internal/scanner/file_repo.go
Changes missing-file deletion to use a grace-period cutoff and removes the prior folder/global deletion variants.
Scanner cleanup wiring
internal/scanner/scanner.go, internal/scanner/audiobook_scan.go, internal/scanner/ebook_scan.go, internal/scanner/podcast_scan.go
Adds fileRemovalGrace to Scanner, threads it through construction, and passes it into empty-trash cleanup paths across scan flows.

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

Possibly related issues

Possibly related PRs

  • Silo-Server/silo-server#8: Introduces the shared scantrigger resolver and RequestError model that this PR extends with vanished-path resolution.
  • Silo-Server/silo-server#44: Updates the autoscan path-resolution flow in internal/autoscan/service.go, which this PR modifies again for vanished paths.

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 summarizes the main scanner change: faster deleted-file reconciliation plus use of file_removal_grace.
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 fix/autoscan-vanished-paths-removal-grace

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 5, 2026

@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: 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".

Comment thread internal/scantrigger/scantrigger.go Resolved
…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]>

@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

🧹 Nitpick comments (4)
internal/scantrigger/scantrigger.go (1)

140-179: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Significant logic duplication with ResolveMissingSubtree.

The folder-listing, MatchFolderForPath call, disabled-library check, and trigger normalization (Lines 151-165) closely mirror ResolveMissingSubtree (Lines 109-125). Extracting a shared matchEnabledFolder(ctx, cleanPath) (*models.MediaFolder, string, error) helper would reduce drift risk — e.g., a future guard added to one function (such as the os.IsNotExist fix 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 win

Solid 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 ResolveVanishedPath specifically, 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 | 🔵 Trivial

Confirm an index backs this delete's filter.

This runs after every scan for every folder. If media_files doesn'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 value

Log a warning when scanner.file_removal_grace is clamped.

Negative values are silently clamped to 0, which disables the grace period this PR is meant to protect, without any operator-visible signal. The subtitle_ai.transcribe_quota_jobs handling 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7aadfb5 and 521d322.

📒 Files selected for processing (12)
  • internal/autoscan/service.go
  • internal/autoscan/service_test.go
  • internal/config/config.go
  • internal/config/db_loader.go
  • internal/config/restart_keys.go
  • internal/scanner/audiobook_scan.go
  • internal/scanner/ebook_scan.go
  • internal/scanner/file_repo.go
  • internal/scanner/podcast_scan.go
  • internal/scanner/scanner.go
  • internal/scantrigger/scantrigger.go
  • internal/scantrigger/scantrigger_test.go

Comment thread internal/scantrigger/scantrigger.go Resolved
- 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]>
@Quick104
Quick104 merged commit 82675eb into main Jul 5, 2026
5 checks passed
@Quick104
Quick104 deleted the fix/autoscan-vanished-paths-removal-grace branch July 5, 2026 23:41
Quick104 added a commit that referenced this pull request Jul 10, 2026
…_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]>
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