Skip to content

fix(libraryingest): TV full scans cancelled at settle-window boundary - #15

Merged
Quick104 merged 2 commits into
mainfrom
fix/tv-scan-settle-window-cancel
May 27, 2026
Merged

Quick104 merged 2 commits into
mainfrom
fix/tv-scan-settle-window-cancel

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

TV libraries could never finish a full scan. Manually scanning the large
series libraries — TV Shows (id 2), TV Shows - International (id 4), and
Anime (id 5) — never reached completed. The scan walked every file fine and
matched some titles, then silently stopped: the next library's scan started
immediately and matching/metadata for the affected library never finished.

What an operator saw. In the admin scan view the run showed up as
cancelled (labelled "aborted" in the UI), but with an empty error message —
so there was nothing to tell you why. In the app log, the run logged
library ingest: concurrent scoped matching stopped, then nothing — no
completion, no error — and the worker moved on to the next library. The
cancellation always landed exactly 11 seconds after waiting for tv queue settle window. The affected scans never logged metadata: scoped matcher selected or library ingest: completed.

Why only the big libraries. Small/fast libraries like Sports (id 7)
completed normally every time. Only the large, slow series libraries (many
shows, slow TVDB/TMDB lookups) were affected — which is exactly the ones that
matter most. This was a pre-existing logic race, unrelated to the recent
PostgreSQL tuning, pool sizing, or statement/lock timeouts.

scan_runs evidence:

             id             | media_folder_id |  status   | trigger | error_message
----------------------------+-----------------+-----------+---------+--------------
 01KSMZM8A5D34EADW8BJRWHYQ2 |               4 | cancelled | manual  |
 01KSMZM79NZFJRMWDRS1WJM5D3 |               2 | cancelled | manual  |
 01KSMZM48QAGD5KKGQCS6X6C29 |               5 | cancelled | manual  |

Solution

The fix is a single behavioral change in the concurrent match drainer, plus a
regression test.

fix(libraryingest): treat drainer shutdown cancel as clean stop

When a TV library finishes its file-walk, ingest() waits out an 11s settle
window for the match queue to quiesce, then calls stopDrainers() to shut down
the concurrent matcher goroutines (internal/libraryingest/executor.go). That
stopDrainers() cancels the drainer context while a
Matcher.ProcessBatchByFolderAndPathPrefix call may still be in flight. The
in-flight call returns context.Canceled — and the drainer's error handler
treated any error as fatal:

  • it pushed the error onto drainerErrCh, and
  • called cancel() on the entire scan context.

The executor then returned that error, and scanqueue.process()
(internal/scanqueue/service.go:342) maps context.Canceled to cancelRun(),
which records the run as cancelled with an empty error_message — exactly the
symptom above. The fmt.Errorf("... %w", context.Canceled) wrapping still
satisfies errors.Is(err, context.Canceled), so the mapping fired.

Large/slow libraries keep a batch in flight essentially continuously, so the
settle-window stopDrainers() almost always landed mid-call. Small/fast
libraries were usually idle between the 2s drain ticks at that instant and
exited via the clean case <-drainerCtx.Done() path, so they completed.

The fix special-cases a cancelled drainer context as a deliberate shutdown
(settle window ended, or the scan is being torn down) and returns cleanly
instead of escalating:

if err != nil {
    if drainerCtx.Err() != nil {
        return // deliberate stopDrainers shutdown, not a real failure
    }
    // ... push to drainerErrCh + cancel() for genuine errors
}

Checking drainerCtx.Err() (rather than unwrapping err) is robust against
pgx/matcher errors that may not cleanly unwrap to context.Canceled. Real
external cancellation (e.g. CancelLibrary, shutdown) still reaches the run via
the main goroutine's scanCtx checks, so legitimate cancels are not swallowed —
only the drainer's own deliberate shutdown is suppressed.

The settle window was also made injectable (Executor.tvDrainSettleWindow,
defaulting to the existing 11s const) purely so the regression test can exercise
the shutdown path without waiting 11 seconds.

Risk / follow-ups

  • Behavioral change is narrow: only suppresses the drainer's error escalation
    when its own context is already cancelled. Genuine match errors (provider
    failures, DB errors) before shutdown still fail the run as before.
  • The separate "23h hang" issue documented alongside this bug (scan path running
    on a context with no deadline while the pool is saturated by refresh_metadata)
    is not addressed here and still needs the DB-timeout / pool-size work to
    make TV scans reliable end to end.
  • go vet's lostcancel warning on the settle-window scanCtx.Done() return
    path is pre-existing on main and unrelated to this change.

Verification

  • go test ./internal/libraryingest/... passes, including the new
    TestIngestFolderCompletesWhenDrainerCanceledMidBatch.
  • Confirmed the test reproduces the bug: against the old handler it fails with
    expected ingest to complete, got error: concurrent match scope "/tv": context canceled; with the fix it passes and the run completes.
  • gofmt clean on both changed files.
  • go build ./internal/libraryingest/... clean. (A full go build ./...
    requires web/dist, built by make build; unrelated to this change.)
  • Manual (recommended before merge): rebuild and restart silo, manually scan
    libraries 2/4/5, confirm metadata: scoped matcher selected +
    library ingest: completed appear and scan_runs.status = completed.

AI-use disclosure

Diagnosed and implemented with assistance from Claude Code.

Summary by CodeRabbit

  • New Features

    • The TV queue settle window can now be customized via settings.
  • Bug Fixes

    • Improved shutdown behavior to avoid treating intentional cancellations as errors and to ensure real errors still stop runs.
    • Active background processing is allowed to finish after the settle window before shutdown completes.
  • Tests

    • Added a regression test verifying settle-window behavior and graceful completion of active work.

Review Change Stack

TV/series full scans (libraries with new or updated items) were recorded as
"cancelled" with an empty error message and never completed matching.

When the file-walk finishes, the ingest executor waits out a settle window and
then calls stopDrainers() to shut down the concurrent match goroutines. That
cancels the drainer context while a ProcessBatchByFolderAndPathPrefix call may
still be in flight. The drainer treated the resulting context.Canceled as a
fatal error: it pushed the error to drainerErrCh and called cancel() on the
whole scan context, so scanqueue.process() mapped it to cancelRun().

Large/slow libraries (many series, slow provider lookups) keep a batch in
flight continuously, so stopDrainers() almost always landed mid-call and the
scan was cancelled; small/fast libraries were usually idle at that instant and
completed normally.

Treat a cancelled drainer context as a deliberate shutdown: return cleanly
without escalating. Genuine external cancellation still reaches the run via the
main goroutine's scanCtx checks, so real cancels are not swallowed.

Adds a regression test (settle window made injectable) that fails against the
old handler with 'concurrent match scope ...: context canceled' and passes
with the fix.
@coderabbitai

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: eef287cc-85b4-46dc-879d-eede01684a67

📥 Commits

Reviewing files that changed from the base of the PR and between ea5be46 and f2cb7e1.

📒 Files selected for processing (2)
  • internal/libraryingest/executor.go
  • internal/libraryingest/executor_test.go

📝 Walkthrough

Walkthrough

Executor adds a configurable tvDrainSettleWindow, decouples drainer shutdown via a separate drainerStopCtx, treats scan-context cancellation as deliberate (not forwarded as an error), cancels the run on scan error before stopping drainers, and includes a test ensuring active drainer batches finish after the settle window.

Changes

TV Drain Timeout Configuration

Layer / File(s) Summary
Settle window field and timeout configuration
internal/libraryingest/executor.go
Adds tvDrainSettleWindow to Executor, computes settleWindow (fallback to scopedTVDrainSettleWindow when unset/non-positive), logs the chosen duration, and starts the settle timer with it.
Drainer stop context and cancellation handling
internal/libraryingest/executor.go
Creates an independent drainerStopCtx/stopDrainers to stop drainer goroutines, updates drainer loop to return cleanly on scanCtx or drainerStopCtx cancellation, and forwards only non-cancellation errors to drainerErrCh. Also cancels run (cancel()) when scan returns an error before stopping drainers.
Regression test for drainer mid-batch cancellation
internal/libraryingest/executor_test.go
Adds settleControlledMatcher and settleStubScanner fakes and TestIngestFolderLetsActiveDrainerBatchFinishAfterSettleWindow that verifies ingestion completes while allowing an active drainer batch to finish after the settle window elapses.

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Silo-Server/silo-server#15: Related PR that also adds the tvDrainSettleWindow override and adjusts drainer shutdown/cancellation handling with a related regression test.

"🐇 I waited, watched the drainers rest—
A tiny window set the test,
Mid-batch gentle, not unkind,
The ingest finishes, all aligned.
Hooray! 🥕"

🚥 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 accurately summarizes the main fix: preventing TV scans from being incorrectly marked as cancelled when drainer context is deliberately shut down at the settle-window boundary.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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/tv-scan-settle-window-cancel

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

@Quick104
Quick104 merged commit bf34462 into main May 27, 2026
1 check was pending
@Quick104
Quick104 deleted the fix/tv-scan-settle-window-cancel branch May 27, 2026 17:45
Quick104 added a commit to thezak48/silo-server that referenced this pull request Jun 7, 2026
…-window-cancel

fix(libraryingest): TV full scans cancelled at settle-window boundary
Quick104 added a commit that referenced this pull request Jun 11, 2026
fix(libraryingest): TV full scans cancelled at settle-window boundary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants