Skip to content

fix(adminjob): wake a backed-off series root before a complete refresh scans it - #5349

Open
rangoDJ wants to merge 2 commits into
Silo-Server:mainfrom
rangoDJ:fix/5337-complete-refresh-requeues-root
Open

rangoDJ wants to merge 2 commits into
Silo-Server:mainfrom
rangoDJ:fix/5337-complete-refresh-requeues-root

Conversation

@rangoDJ

@rangoDJ rangoDJ commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Depends on: none. Merge order: none.

Problem

Closes #5337
Related issue: #934
Validation tasks: #1250 (C2), #1251 (C2), where the issue was found

Other clients: none. This is the server's Complete Refresh job, started from web admin.

Running Complete Refresh on a series an admin matched by hand, from a folder no provider matches on its own, removed it from the library and from Unmatched Items. The folder came back only when its match back-off ended (an hour, then a day, then parked) or after Retry now in the Metadata Matcher.

prepareCompleteRefresh clears the scope's content links, and the refresh's scan (IngestUnlinkedSubtree) matches the series root through the TV match queue: it re-queues the root and claims it with ClaimByFolderAndPathPrefix. That claim takes only a row whose available_at has passed, and the re-queue's upsert keeps the later available_at (GREATEST(...) in EnqueueSeriesRoot). A root an earlier failure had backed off as no_candidates therefore wasn't claimed. With nothing rebuilt, the job failed with errNoRebuiltContent after its 60 s relink wait, and the next scan removed the empty series.

Approach

The issue's expected behavior allows either rebuilding the series or returning the folder to Unmatched Items right away. This takes the second, which matches what Retry now does today, and does not try to carry the hand match through the refresh.

  • New SeriesRootMatchQueueRepository.WakeInScope(folderID, scopePath). It returns to pending the parked or backed-off row of every series root in the scope, the same reset WakeRoot makes for one root. That covers roots at or under the scope, and roots with a present file in it, so a season or episode refresh wakes its series root.
  • Like WakeRoot, it requests no rerun of an idle row. A row a worker holds keeps its available_at and gets rerun_requested, so the worker's UpdateFailure or Delete makes it due at once instead of restoring a back-off.
  • ItemRefreshExecutor gets an optional SetSeriesRootWaker, wired in cmd/silo/main.go to the series root queue repository. A complete refresh of a series, season or episode calls it before it clears the links and scans. The scan's re-queue then puts the row in the quiet window that IngestUnlinkedSubtree already waits out, and the scoped match claims it.
  • A failed wake fails the refresh before anything is cleared, so the series stays as it was.
  • The waker, its setter and isSeriesTarget live in item_refresh_wake.go, keeping item_refresh.go under its 1,000-line size limit.
  • A movie's complete refresh and quick refreshes are unchanged.

Validation

  • Not reproduced on a server.
  • New DB test TestSeriesRootQueueWakeInScopeDB, over three backed-off roots:
    • A series root scope and a season folder scope both wake the show's root and leave another root backed off.
    • ClaimByFolderAndPathPrefix for the season folder claims nothing while the root is backed off, and claims the root once it is woken. This is the step the refresh missed.
  • New DB test TestSeriesRootQueueWakeInScopeRerunsALeasedRowDB: a leased row keeps its available_at and gets a rerun, and the worker's UpdateFailure then leaves it due.
  • Both DB tests are listed in scripts/ci/db-contracts.txt, and go run ./scripts/ci/dbpins -shared -list passes them.
  • New test TestItemRefreshExecutorCompleteRefreshWakesBackedOffSeriesRoot:
    • A complete refresh of a series or an episode wakes the scope once, before the links are cleared and the scan.
    • A quick refresh and a movie's complete refresh don't call it.
  • New test TestItemRefreshExecutorCompleteRefreshFailsWhenTheWakeFails: a wake error fails the refresh with no links cleared and no scan.
  • These tests use the new method, so they don't build on main; the claim subtest shows the bug against the unchanged claim.
  • go test ./internal/adminjob/: pass. go test ./internal/metadata/: pass, apart from TestArtworkRevisionGCRunLocksBatchDuringDeletion, which in a full run on my shared local database sees artwork rows other tests left. It passes when run alone, on this branch and on main.
  • go vet: clean. golangci-lint run --new-from-rev=origin/main on the three packages: 0 issues.
  • Not tested: the refresh end to end against a real provider chain, and what Unmatched Items shows for the folder after the match runs.

Evidence

Evidence: not needed. The change is when the server's TV match queue claims a root. Its user-visible result, the folder staying in Unmatched Items, follows from the claim the DB test shows.

=== RUN   TestSeriesRootQueueWakeInScopeDB/series_root_scope
=== RUN   TestSeriesRootQueueWakeInScopeDB/season_folder_scope
=== RUN   TestSeriesRootQueueWakeInScopeDB/scoped_claim
=== RUN   TestSeriesRootQueueWakeInScopeDB/leased_row
--- PASS: TestSeriesRootQueueWakeInScopeDB (0.41s)
--- PASS: TestItemRefreshExecutorCompleteRefreshFailsWhenTheWakeFails (0.00s)
--- PASS: TestItemRefreshExecutorCompleteRefreshWakesBackedOffSeriesRoot (0.00s)

Risks

  • A complete refresh now resets the scope's roots' back-off and failure fields, as Retry now does for a library. A root that keeps failing goes through its back-off again from the first step.
  • The hand match itself is not kept: the folder returns to Unmatched Items, and the admin matches it again. Keeping a manual match through Complete Refresh would be a separate change.
  • No API shape, config or schema change.

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 how I checked a change nobody sees.

AI Disclosure

  • Harness: Claude Code in the Claude desktop app
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated, not yet human verified
  • Adversarial review: n/a

🤖 Generated with Claude Code

…h scans it

Complete Refresh clears its scope's content links and scans the scope,
whose ingest matches the series root through the TV match queue. The
scan re-queues the root, but the upsert keeps a later available_at, so
a root an earlier failure backed off (a hand-matched folder no provider
finds on its own, at no_candidates) was not claimed. The refresh waited
out its relink window and failed, and the folder was in neither the
library nor Unmatched Items until the back-off ended or an admin pressed
Retry now.

SeriesRootMatchQueueRepository.WakeInScope returns the backed-off rows of
every series root in a scope to pending, as WakeRoot does for one root:
roots at or under the scope, and roots with a present file in it. A
complete refresh of a series, season or episode calls it after clearing
the links and before its scan; a failed wake fails the refresh before
the scan. The new DB test is listed in scripts/ci/db-contracts.txt.

Closes Silo-Server#5337

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 25, 2026
@silo-kody

silo-kody Bot commented Nov 25, 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 ❌

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code impact: usability Core flow broken or severely blocked needs-review Needs maintainer review to resolve uncertain classification, scope, or changed evidence. priority: P2 Limited scope, workaround exists, or polish labels Nov 25, 2026
@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Complete refreshes of series, seasons, and episodes now wake matching backed-off series-root queue entries before scanning. The queue operation resets matching entries while preserving availability times for leased rows.

Changes: Series-root wake during refresh

Layer / File(s) Summary
Scoped series-root queue wake
internal/metadata/series_root_match_queue_repo.go, internal/metadata/series_root_wake_scope_db_test.go, scripts/ci/db-contracts.txt
WakeInScope resets matching roots to pending, clears deterministic failure and parking fields, and makes unleased rows available immediately. Matching roots include those at or below the scope and roots with a present file at or below it. Leased rows retain their availability time. The database test and contract list cover this behavior.
Complete refresh integration
internal/adminjob/item_refresh.go, cmd/silo/main.go, internal/adminjob/item_refresh_wake_test.go
The executor uses the series-root queue repository as a waker when available. Complete series, season, and episode refreshes call it after links are cleared and before scanning. Wake errors stop preparation. Tests cover call order, excluded refresh types, and errors.

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

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant ItemRefreshExecutor
  participant SeriesRootMatchQueueRepository
  participant Scanner
  ItemRefreshExecutor->>SeriesRootMatchQueueRepository: WakeInScope with folder ID and scope path
  SeriesRootMatchQueueRepository-->>ItemRefreshExecutor: Reset matching queue rows
  ItemRefreshExecutor->>Scanner: Scan after links are cleared
Loading

Suggested reviewers: blurbery, quick104

Merge Risk: Low · up to d39a0

Complete Refresh now makes backed-off series roots claimable again before scanning, so a hand-matched folder with no provider match returns to Unmatched Items. A narrow race remains: if the root is mid-match when the refresh runs and that attempt then fails, the one-hour back-off can still apply. That root stays hidden until the back-off expires or an admin uses Retry now. The change is otherwise well scoped and easy to revert.

Security architecture risk: Low · up to d39a0

The change helps a complete refresh retry matching without waiting for an earlier failure delay. It also adds a point where the refresh can stop after removing existing library links but before rebuilding them. The effect is limited to the selected refresh scope.

Retained concerns

  • Low · reliability · observed: For scopes whose links are cleared, the new queue write can fail after that clear commits but before the rebuild starts. The runner records a failed job without restoring the links or retrying the refresh, leaving the scope unlinked unless a later operation repairs it.
Security review details

Security Blast Radius

  • observed — The new write is limited to one media folder. Within that folder it can affect multiple roots: those at or below the selected path, and those with a present, non-extra file at or below that path, even if their root is above it. The boundary is the refresh scope, not the requested series ID.

Trust Boundaries and Controls

  • observed — The endpoint requires metadata-curation permission. The caller supplies an item ID and mode, not the queue mutation's folder or path. The server derives those from stored media records before persisting the job, and the executor rejects a disabled folder before preparing the refresh.

Resilience and Maintainability Implications

  • observed — The wake does not replace a worker's lease token or advance an active lease's availability timestamp. It changes scheduling and failure state without taking queue ownership from the current worker.

Hardening Proposals

  • proposed — Make link clearing and the queue wake commit together, or persist a recovery step that can resume the rebuild after the clear. Either approach should preserve link-clear-before-wake ordering without leaving a wake error as an unrecovered stopping point.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: a complete refresh now wakes a backed-off series root before the scan. It matches the summary and objectives, which describe WakeInScope and the call before scanning i…
Linked Issues check Passed Issue #5337 requires that, after Complete Refresh, a folder that no provider matches stays visible and fixable. The issue accepts either a rebuilt series or an immediate return to Unmatched Items. The…
Out of Scope Changes check Passed All changes connect to #5337. WakeInScope and its DB test implement the root-wake fix. SetSeriesRootWaker and its call in ItemRefreshExecutor, plus the cmd/silo/main.go wiring, connect the wake to com…
Description check Passed The description is specific and directly related to the changeset. It explains the Complete Refresh bug where a hand-matched series folder disappears from the library and Unmatched Items while its ser…
Full details: Title check

Explanation

The title names the main change: a complete refresh now wakes a backed-off series root before the scan. It matches the summary and objectives, which describe WakeInScope and the call before scanning in the item refresh executor.

Full details: Linked Issues check

Explanation

Issue #5337 requires that, after Complete Refresh, a folder that no provider matches stays visible and fixable. The issue accepts either a rebuilt series or an immediate return to Unmatched Items. The cause is that the scan's re-queue keeps a later available_at (GREATEST in EnqueueSeriesRoot), so a backed-off series root is never claimed. The PR adds SeriesRootMatchQueueRepository.WakeInScope (series_root_match_queue_repo.go). It returns parked or backed-off roots in the scope to pending, and sets available_at to NOW() for unleased rows. ItemRefreshExecutor calls it for complete series, season, and episode refreshes after the links are cleared and before the scan (item_refresh.go). A wake error stops the refresh before the scan. TestSeriesRootQueueWakeInScopeDB covers the scoped claim, which claims nothing while the root is backed off and claims it after the wake. Executor tests cover when the wake is called and the failure path. The diff of the repository file matches the described SQL. Not verified: an end-to-end refresh with a real provider chain, and the resulting Unmatched Items display. These are stated as untested in the PR, and the code path that produces the outcome is covered.

Full details: Out of Scope Changes check

Explanation

All changes connect to #5337. WakeInScope and its DB test implement the root-wake fix. SetSeriesRootWaker and its call in ItemRefreshExecutor, plus the cmd/silo/main.go wiring, connect the wake to complete refreshes only. Movie complete refreshes and quick refreshes do not call the waker, as the PR states and the executor tests check. The db-contracts.txt entry registers the new DB test. No unrelated API, config, or schema change appears in the summary. The wake also resets back-off for roots in the scope that keep failing. The PR lists this as a known risk, and it follows directly from the requested wake behavior.

Full details: Description check

Explanation

The description is specific and directly related to the changeset. It explains the Complete Refresh bug where a hand-matched series folder disappears from the library and Unmatched Items while its series-root match is backed off. It states the fix: a new SeriesRootMatchQueueRepository.WakeInScope method, an ItemRefreshExecutor.SetSeriesRootWaker setter wired in cmd/silo/main.go, and calls before the scan for complete series, season, and episode refreshes. It also lists the DB and unit tests added, the validation performed, and the risks, which match the files in the raw summary.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
Fix failing CI checks

  • 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: bad63f60-d112-4894-a122-190eb7a37a34
Commits

Reviewing files that changed from the base of the PR and between c702819 and d39a0c9.

Files selected for processing: 6

  • cmd/silo/main.go
  • internal/adminjob/item_refresh.go
  • internal/adminjob/item_refresh_wake_test.go
  • internal/metadata/series_root_match_queue_repo.go
  • internal/metadata/series_root_wake_scope_db_test.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.

Comment thread internal/adminjob/item_refresh.go Outdated
Comment on lines +667 to +670
if isSeriesTarget(req.RequestedType) && e.seriesRoots != nil {
if err := e.seriesRoots.WakeInScope(ctx, req.ScanFolderID, req.ScanPath); err != nil {
return nil, fmt.Errorf("prepare complete refresh: %w", err)
}

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 high

Wake failures leave the refresh scope unlinked without scanning

A queue error after prepareCompleteRefresh commits claim and file-content link removal leaves the series absent without a restoring scan. Wake the queue before destructive preparation, or make preparation and wake atomic.

Prompt for LLM
File internal/adminjob/item_refresh.go, lines 667-670:

Wake failures leave the refresh scope unlinked without scanning

A queue error returns after `prepareCompleteRefresh` has already deleted claims and committed the removal of file content links, leaving the series absent without running the scan that restores it. Wake the queue before destructive preparation, or make the preparation and wake atomic.

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 6b3b60e. The wake now runs before prepareCompleteRefresh, so a failed wake returns with the claims and links untouched. TestItemRefreshExecutorCompleteRefreshFailsWhenTheWakeFails now checks that no links were cleared and no scan ran.

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 addresses the reported failure path: if the wake fails before prepareCompleteRefresh, the existing claims and links remain intact, and the added assertions check that neither link clearing nor scanning occurs.

I haven’t independently verified commit 6b3b60eac.

Comment on lines +820 to +824
UPDATE series_root_match_queue q
SET state = 'pending',
available_at = CASE WHEN q.lease_token = '' THEN NOW() ELSE q.available_at END,
deterministic_attempt_count = 0,
failure_kind = '', failure_detail = '{}'::jsonb, last_error = '', parked_at = NULL,

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 high

A leased worker can undo the wake by restoring backoff

A leased worker's UpdateFailure can restore the one-hour backoff, preventing the refresh scan from reclaiming the root and leaving cleared files unlinked. Set rerun_requested for leased rows so completion or failure schedules a fresh match.

Prompt for LLM
File internal/metadata/series_root_match_queue_repo.go, lines 820-824:

A leased worker can undo the wake by restoring backoff

When a worker already holds the row, its subsequent `UpdateFailure` can restore the one-hour backoff because the wake does not set `rerun_requested`, so the refresh scan cannot claim the root and the cleared files remain unlinked. Request a rerun for leased rows so the worker's completion or failure schedules a fresh match.

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 6b3b60e. WakeInScope sets rerun_requested on a leased row and keeps its available_at. The worker's UpdateFailure (or Delete) then makes it due at once instead of restoring the back-off. New DB test TestSeriesRootQueueWakeInScopeRerunsALeasedRowDB covers it and is listed in scripts/ci/db-contracts.txt.

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 for addressing the race. Setting rerun_requested on leased rows should prevent a worker’s completion or failure from restoring the backoff, and the new DB test covers that case. I haven’t independently verified the commit or test results.

Review follow-ups:

- Wake the scope's series roots before prepareCompleteRefresh clears its
  links, so a failed wake leaves the series as it was instead of
  returning with the links already cleared and no scan to restore them.
- A row a worker holds while the refresh wakes it is asked to rerun, so
  the worker's UpdateFailure or Delete makes it due at once instead of
  restoring its back-off.
- Move the waker, its setter and isSeriesTarget to item_refresh_wake.go,
  keeping item_refresh.go under its 1,000-line size limit.

The leased-row DB test is listed in scripts/ci/db-contracts.txt.

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

silo-kody Bot commented Nov 25, 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 ❌

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: usability Core flow broken or severely blocked needs-review Needs maintainer review to resolve uncertain classification, scope, or changed evidence. priority: P2 Limited scope, workaround exists, or polish size/L 200–499 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] Complete Refresh on a hand-matched series hides its folder from the library and Unmatched Items

1 participant