You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(audiobooks): back off on provider throttling and stop retrying failures forever - #4204
Related issue: N/A
Validation tasks: changes #1254 C2 (not yet run; no passed case affected)
Other clients: N/A (no client-visible change)
When the audiobook metadata provider has trouble, the enrichment sweep handles it badly. A throttled request can keep a book out of enrichment for 30 days. A book whose lookups always fail is retried forever. A rate-limited provider keeps getting the rest of a 250-book sweep. Every API node runs its own sweep, so each added node adds provider load. This change makes the sweep back off on throttling, stop on persistent failures, and run on one node at a time. It affects audiobook libraries only, which are beta.
30-day park on throttling. The first-party plugin's GetMetadata returns source errors such as itunes: HTTP 403 with no gRPC code. The host read the bare 403 as permanent, which parks the book for 30 days. Apple's API answers throttling with 403.
No retry cap. Failures had no attempt limit. A single failure also reset the no-match count, so a provider that failed one time in three kept a book from ever finishing.
No reaction to rate limits within a sweep. The rest of the claimed books still called the throttled provider, and the provider's retry-after was discarded.
Approach
Classification.metadata.ProviderErrorPolicy gains an opt-in ForbiddenIsRateLimit that the audiobook enricher sets. An untyped 403 then backs the book off as rate limited. A 401, typed gRPC denials, and not-found or invalid-argument errors stay permanent. Movie, series, ebook and manga callers keep the default policy, and their existing tests pass unchanged.
Retry counters. A migration adds no_matches and failures to audiobook_enrichment_state and backfills them from attempts, which now counts every attempt.
Failures back off exponentially, from 15 minutes (1 hour when rate limited) up to 24 hours, and never sooner than a provider's retry-after.
After 10 consecutive failures (2 for permanent errors) the book gets the terminal outcome failed. The sweep no longer claims it, and the last error class and message stay on the row.
A failure no longer resets the no-match count, so three clean no-matches still end the retries.
Admin refresh and Match Item don't read this state, so they still work on a failed book.
Pausing a provider. For the rest of the sweep and beyond, the enricher stops calling a provider that:
answers rate limited. The pause lasts for the retry-after, or 15 minutes when none is given.
fails three times in a row with transient errors. That pause starts at 15 minutes and doubles, up to 6 hours, while the failures continue.
A book whose providers are all paused goes back in the queue until the pause ends, and the deferral doesn't count as an attempt. A provider outage therefore costs a few probe attempts instead of pushing the whole backlog to failed. An untyped 403 backs off that one book but does not pause the provider: a source that rejects every request with 403 would otherwise stall the sweep for every other book.
One sweeping node.Run takes a Postgres advisory lock on a session of its own, opened outside the pool like the backup and migration locks, and HasPendingItems reports nothing to do while another node holds it. That check reads pg_locks for this database only, so another Silo database on the same Postgres server sweeps independently. This is simpler than a shared request budget and behaves the same on one node or many. The pause lives in process memory. When the next sweep starts on a different node, that node relearns the pause from the provider's next answer.
Smaller fixes.
claimBatch loads provider IDs for the whole batch in one query instead of one per book.
The sweep log and task result count matches from the state table, so books skipped because no provider is installed no longer show up as enriched.
Skipped books are retried hourly instead of every 6 hours, so installing a provider picks them up sooner. Skips make no provider calls.
Degraded searches (left conservative). The plugin's Search succeeds when any one source answers, so if the strongest source is throttled and another returns non-matching results, the host still sees a clean empty answer. The host can't detect that with plugin 0.1.7. This change doesn't alter how a no-match becomes final: it still takes three clean answers about 24 hours apart. The host already refuses a no-match whenever any provider in the chain reports an error, and that now includes a provider the enricher skipped because it was paused. A plugin follow-up should report which sources failed even when the search partly succeeds, and send GetMetadata errors with gRPC codes (ResourceExhausted with RetryInfo for 429 or throttling 403, Unavailable for outages, NotFound only when the source says the ID doesn't exist).
Validation
go build ./..., gofmt -l ., go mod tidy -diff, go vet ./...: clean.
make lint-changed, make lint-router-recovery, verify-local-paths, verify-case-collisions, verify-bidi, verify-migrations, verify-size-ratchet: pass.
make test-go: passed on the full change before the review fixes. After those fixes, internal/playbackTestCopyRemuxSubtitleRenditionRealFFmpeg fails. It also fails on unchanged main in the same environment, and internal/playback imports no package this change touches.
Against a fresh Postgres 18 (pgvector) database migrated through this branch's migration: internal/audiobooks, internal/metadata, internal/ebooks and internal/manga pass, and the dbpins runner passes the new db-contracts.txt entries.
On the final head (01a524f55d), after all review fixes: the Postgres-backed tests, those packages plus database/pglock, and the dbpins runner pass again, and a down/up round trip of the new migration on seeded rows gives the expected counts.
Web, API contract and fixture checks were not run: the change touches no web, API, settings or playback-fixture code.
Nothing user-visible changes. The new tests simulate provider errors and never call live providers:
Unit tests:
The plugin's itunes: HTTP 403 classifies as rate limited for audiobooks and stays permanent under the default policy. A 401 and typed denials stay permanent.
A rate-limited answer pauses the provider for its retry-after, and later books make no provider calls.
Three transient failures pause a provider, and the pause doubles while it keeps failing.
A paused provider keeps a book from being recorded as a no-match.
Postgres tests:
Transient backoff runs 15m, 30m, 1h … 24h, and the 10th failure ends at failed. A retry-after raises the backoff.
Permanent failures are rechecked once.
Failures between no-matches keep the count, so the third no-match is final.
A deferral doesn't count an attempt.
A full Run does nothing while another session holds the sweep lock, never claims a failed book, parks the throttled book for the provider's 3h retry-after, and defers the rest of the batch without another provider call, including a book whose second provider answered empty.
Risks
Migration. The migration touches only audiobook_enrichment_state. It adds two columns with defaults; no-match rows take their count from attempts, and rows pending after a failure start with a failure count of 1. The down migration turns failed rows back into pending failures and resets attempts to the no-match count on every unfinished row.
One sweeping node. On a multi-node deployment only one node sweeps at a time. Throughput is unchanged per sweep; there are no longer N sweeps running at once.
Lock connection. The sweeping node opens one extra database session, outside its pool, for the length of a sweep.
Recovering failed books. A book marked failed needs an admin refresh or match. Nothing re-queues it automatically.
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 T3 Code
Tool(s): Claude Code, GitHub CLI
Model(s): claude-opus-5-5
Involvement: Fully AI-generated, human verified
Adversarial review: one independent code review of the diff (code-review skill, medium). Confirmed and fixed: provider outages could push the whole backlog to failed; paused-only failures counted as attempts; retry-after was taken from unrelated providers; 401 was treated as a throttle; a folder ID of 403 could be misread as an HTTP status. Kept as described above: the in-memory pause across a node handover, and the lock connection. Bot reviews on the PR (Codex, Kody, CodeRabbit) found further problems, all fixed and answered on their threads: a skipped metadata lookup cleared the failure streak; pause-only errors before an author mismatch were charged as failures; a deferred book waited for the longest pause rather than the earliest; a NotFound answer didn't break the failure streak; the sweep hung on a one-connection pool, now fixed by taking the lock on its own session; a successful metadata lookup didn't clear the failure streak; the stored last_error wasn't redacted; and the migration's backfill and rollback miscounted.
Add provider pause gating and bounded retry backoff to audiobook enrichment
Adds a providerGate (enrichment_gate.go) that pauses providers on rate limits (15-minute default) and on transient-failure streaks (3 failures, doubling up to 6 hours). Paused providers receive no calls; items whose whole provider chain is paused are deferred instead of counted as no-match or failure.
Rewrites retry state (enrichment_state.go): class-specific exponential backoff, terminal failed outcome after 10 transient/rate-limited or 2 permanent failures, retry-after capped at 7 days, error text redacted before storing. New no_matches and failures columns added by migration.
Classifies untyped HTTP 403 and forbidden text as rate-limited via ProviderErrorPolicy in provider_error.go; HTTP 401 and typed gRPC denials stay permanent.
Sweeps now take a PostgreSQL advisory lock so only one node sweeps at a time, and report enriched counts from persisted state rather than worker returns (enrichment.go). Skipped-item retry delay drops from 6 hours to 1 hour.
Behavioral Change: no-match retries now use the no_matches counter rather than attempts, failed rows are excluded from pending work, unclaimed writes can create state rows, and claim writes require an unexpired lease. Rolling back the migration clears failed outcomes and restores attempts from no_matches.
Audiobook enrichment now stores separate no-match and provider-failure counts, applies retry and terminal-failure policies, gates paused providers, and serializes sweeps with a database advisory lock. The change also adds provider error classification options and tests for retry state and sweep behavior.
Changes: Audiobook enrichment
Layer / File(s)
Summary
Persist retry counters and outcomes migrations/sql/20261114222928_audiobook_enrichment_retry_counters.sql, internal/audiobooks/enrichment_state.go, internal/audiobooks/enrichment_retry_db_test.go, scripts/ci/db-contracts.txt
The migration adds and backfills separate no-match and failure counters. State writes apply retry policies, claim fencing, deferral, and terminal failure handling. Database tests cover retry delays, failure limits, and counter behavior.
Classify errors and gate providers internal/metadata/provider_error.go, internal/metadata/provider_error_test.go, internal/audiobooks/enrichment_gate.go, internal/audiobooks/enrichment_test.go, internal/audiobooks/enrichment_state_db_test.go
Provider error policy can classify untyped 403 errors as rate limits. The provider gate tracks rate-limit and outage pauses and prevents calls while providers are paused. Tests cover classification, pause behavior, and reset behavior.
Serialize and report enrichment sweeps internal/audiobooks/enrichment.go, internal/audiobooks/enrichment_retry_db_test.go, scripts/ci/db-contracts.txt
Sweeps use an advisory lock, query eligibility using separate counters, and report recorded outcomes. Provider calls use the gate; paused items are deferred. Database tests cover lock contention and sweep behavior.
sequenceDiagram
participant Enricher
participant SweepLock as Database advisory lock
participant ProviderGate
participant AudiobookProvider
participant EnrichmentStateStore
Enricher->>SweepLock: Acquire sweep lock
SweepLock-->>Enricher: Lock acquired
Enricher->>ProviderGate: Search or fetch metadata
ProviderGate->>AudiobookProvider: Call provider if not paused
AudiobookProvider-->>ProviderGate: Result or provider error
ProviderGate-->>Enricher: Result or rate-limit-classifiable pause error
Enricher->>EnrichmentStateStore: Record outcome, failure, or deferral
Loading
Suggested reviewers:rxwatcher
Merge Risk: Moderate · up to 61d80
Enrichment is serialized and retry-bounded, but deferred audiobooks can be held out of the queue far longer than necessary, and a paused-provider mismatch can wrongly count toward terminal failure. Rolling the migration back can also stop no-match retries early. Resolve the deferral deadline and the mismatch branch before merging; the rollback and streak issues are smaller.
Security architecture risk: Low · up to 61d80
The new sweep lock can stall enrichment and other database work when the server is configured with a single database connection. The default connection limit is larger. The inspected changes otherwise retain claim ownership checks and limit persistent provider failures without introducing a new authentication or authorization bypass.
Retained concerns
Medium · reliability · inferred: Run now retains an advisory-lock connection and immediately requests another connection from the same pool. With the accepted database.max_connections=1 configuration, the second checkout cannot complete while Run owns the only connection, preventing enrichment and blocking other work sharing that pool until cancellation or a configured deadline. The base Run did not retain this extra connection. The default pool size of 20 avoids this specific circular wait.
Security review details
Security Blast Radius
inferred — Normal retry-state effects are scoped to audiobook content IDs, while an active provider pause affects audiobook calls using that provider slug on the sweeping process. The connection-budget failure can affect other work sharing the same database pool, extending its failure-containment impact beyond enrichment.
Trust Boundaries and Controls
observed — The inspected entrypoints are invoked by the audiobook task rather than introducing a network handler. Provider-controlled errors influence retry disposition and pause timing; they do not grant identity or write authority. Claimed persistence still requires the live content-specific claim.
Resilience and Maintainability Implications
observed — Provider-supplied retry-after values are clamped to seven days, transient outage pauses cap at six hours, and failure recording uses bounded exponential backoff. These controls limit provider-driven deferral and repeated failure load.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the audiobook-specific change: back off on provider throttling and stop retrying failures forever. The changeset adds rate-limit classification, retry backoff, a terminal failed outcom…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
The description is specific and on-topic. It states the problem (provider throttling causes 30-day parks, unlimited retries, and no reaction to rate limits within a sweep), and it explains the approac…
Full details: Title check
Explanation
The title names the audiobook-specific change: back off on provider throttling and stop retrying failures forever. The changeset adds rate-limit classification, retry backoff, a terminal failed outcome, provider pausing, and a sweep lock, so the title covers the main change. It is a single, concise line in the conventional fix(scope) style.
Full details: Description check
Explanation
The description is specific and on-topic. It states the problem (provider throttling causes 30-day parks, unlimited retries, and no reaction to rate limits within a sweep), and it explains the approach. The approach covers the untyped 403 classification via ProviderErrorPolicy, the no_matches and failures migration, provider pausing with the gate, deferral without attempt charges, and the Postgres advisory lock for single-node sweeping. It also lists validation, evidence, and risks. These match the changeset files.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
The reason will be displayed to describe this comment to others. Learn more.
Preserve the failure streak when metadata lookup makes no request
When Search fails transiently for a book without stored provider IDs, PluginProvider.GetMetadata returns (nil, nil) without contacting the plugin (internal/metadata/plugin_provider.go:257–259). Passing that result to observe resets the provider's failure streak, so with SILO_AUDIOBOOK_ENRICH_WORKERS=1, every failed search is followed by a reset and even a completely unavailable provider never reaches the three-failure pause. The sweep keeps calling it for the whole backlog, and repeated sweeps can eventually mark those books terminally failed instead of deferring them during the outage. Do not treat a skipped metadata lookup as evidence that the provider recovered.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 17f288b. A metadata call now reports only its errors to the pause logic, so the (nil, nil) the plugin adapter returns without a request no longer clears the failure streak. Only Search answers clear it. Covered by TestSkippedMetadataLookupKeepsTheFailureStreak.
File internal/audiobooks/enrichment.go, line 1394:
Provider error text can expose nested secret assignments in logs
Sanitize provider-controlled error text before returning it. The batch worker logs this error, so a provider response containing an assignment such as `desc = api_key=...` can expose the credential. Use the diagnostic redaction path that scans for nested secret assignments, and preserve error classification separately if callers need it.
Kody rule violation: [Redact secret assignments nested inside diagnostic values](https://kodus.siloserver.org/settings/code-review/1247142351/kody-rules/48819486-1507-425b-82b3-566a1c19a128?teamId=ba9922fc-c0ea-4cf8-87bb-9d4f42ffc73e)
The reason will be displayed to describe this comment to others. Learn more.
Partly addressed in 17f288b. The returned error text is unchanged from main, and the log handler already runs error text through logredact.RedactSecretAssignments and SanitizeText before it reaches the stored ops log. The text this change does keep, audiobook_enrichment_state.last_error, was not redacted, so RecordFailure now applies the same two functions before writing it. A Postgres test checks that an api_key=... value is masked.
The reason will be displayed to describe this comment to others. Learn more.
That addresses the newly persisted last_error exposure, assuming the redaction functions also mask nested assignments such as desc = api_key=.... The existing log handler’s redaction would address the original logging concern without changing the returned error or its classification.
The test you described checks a direct api_key=... value. I’d also test the nested form from the original suggestion, since that is the specific behavior the rule requires. Any other consumers of the returned error would still need to redact it before logging or storing it.
The reason will be displayed to describe this comment to others. Learn more.
Done in 5c17f23. The Postgres test now writes both api_key=... and rpc error: code = Unknown desc = api_key=... through RecordFailure and checks that the stored last_error doesn't contain the secret. Both come out as api_key=[REDACTED].
The reason will be displayed to describe this comment to others. Learn more.
Thanks—that covers the nested assignment case in the original suggestion for the persisted last_error. Combined with the existing log-handler redaction you described, it addresses the reported exposure while preserving error classification.
The reason will be displayed to describe this comment to others. Learn more.
Sweep lock deadlocks enrichment with a single database connection
With database.max_connections set to 1, pglock.TryAcquire holds the only pool connection while the database-time query waits for another, so every sweep hangs until its context is canceled. Reserve capacity for the sweep's database work or use a connection arrangement that does not exhaust the pool.
Prompt for LLM
File internal/audiobooks/enrichment.go, line 213:
Sweep lock deadlocks enrichment with a single database connection
With `database.max_connections` set to 1, the advisory lock holds the only pool connection while the subsequent database-time query waits for another, so every sweep hangs until its context is canceled. Reserve capacity for the sweep's database work or execute it through a connection arrangement that does not exhaust the pool.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 17f288b. database.max_connections accepts 1, and with one pooled connection the sweep lock held it while the sweep's own queries waited. With fewer than two pool connections the sweep now runs without the lock; per-item claims still keep two nodes off the same book. A Postgres test runs a sweep on a one-connection pool. It timed out without the fix and finishes with it.
The reason will be displayed to describe this comment to others. Learn more.
The fix addresses the single-connection deadlock, and the Postgres test provides a regression check.
One tradeoff remains: when the pool has fewer than two connections, multiple nodes can sweep concurrently. Per-item claims prevent duplicate processing of the same book, but they do not preserve the single-sweeper provider-load limit across nodes. It would be worth documenting that exception to the PR’s one-node guarantee.
The reason will be displayed to describe this comment to others. Learn more.
Superseded by the fix on the thread above: there's no exception any more. A pool of any size takes the sweep lock on its own session, so one node sweeps at a time everywhere. I removed the exception from the code comments, and the PR body no longer mentions it.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the correction. The dedicated lock session removes the single-connection exception I raised, so my earlier documentation concern no longer applies. I haven’t independently verified the revised implementation.
The reason will be displayed to describe this comment to others. Learn more.
Paused providers are charged as failures on author mismatch
When provider pauses are the only errors and metadata has a mismatched author, repeated pauses can exhaust the failure limit and permanently exclude the book. Route the author-mismatch branch through failOrDefer instead of recordFailure.
Prompt for LLM
File internal/audiobooks/enrichment.go, line 672:
Paused providers are charged as failures on author mismatch
When a paused provider produces the only errors and another provider returns metadata with a mismatched author, the author-mismatch branch calls `recordFailure` instead of `failOrDefer`. Repeated pauses can therefore exhaust the failure limit and permanently exclude the book even though no provider actually failed for it; route that branch through `failOrDefer` as well.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 17f288b. When every error came from a paused provider, the author-mismatch branch now defers the book until the pause ends, the same as the no-metadata branch. The book isn't charged a failure.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the update. The described fix addresses the concern: when all errors come from paused providers, an author mismatch defers the book rather than counting a failure. I haven’t independently verified the commit.
The reason will be displayed to describe this comment to others. Learn more.
Migration converts mixed historical attempts into consecutive failures
Pending rows may have attempts from skipped or clean no-match attempts, so copying them into failures can make the next failure terminal for otherwise retryable books. Initialize migrated failure streaks conservatively instead.
Prompt for LLM
File migrations/sql/20261114222928_audiobook_enrichment_retry_counters.sql, line 19:
Migration converts mixed historical attempts into consecutive failures
Existing pending rows can have `attempts` accumulated from skipped or clean no-match attempts before their first provider failure, so copying that total into `failures` makes the next failure immediately terminal for otherwise retryable books. Initialize migrated failure streaks conservatively rather than treating the mixed historical counter as consecutive failures.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 17f288b, in the same migration since it hasn't shipped. Rows that were pending after a failure now start with a failure count of 1, not their mixed attempt total. A down/up round trip on seeded rows confirmed it.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for addressing this. Initializing the failure count to 1 avoids treating mixed historical attempts as consecutive failures, and the seeded down/up round trip provides useful migration coverage.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
⚠️ Outside diff range comments (1)
Major · Defer pause-only errors in the author-mismatch branch. · enrichment.go:824
internal/audiobooks/enrichment.go:824 Major · Functional Correctness · Quick win
Defer pause-only errors in the author-mismatch branch.
If provider A is paused and provider B returns metadata with a different author, providerErrs can contain only A's pause errors. This branch calls recordFailure directly instead of failOrDefer.
The item consumes a failure even though B's result is treated as a no-match. This can exhaust the failure limit and leave the item terminally failed. Apply the pause-only deferral check here before recording a failure.
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: 2712e0e0-7182-4ff1-a07b-7bdcd4951c31
Commits
Reviewing files that changed from the base of the PR and between feae205 and 61d8007.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
…ilures forever
The audiobook metadata sweep parked a throttled book for 30 days when the
provider sent an untyped HTTP 403, retried failing books forever, kept
calling a rate-limited provider for the rest of the sweep, and ran on
every API node at once.
- Read an untyped 403 from the audiobook provider as rate limiting
(ProviderErrorPolicy.ForbiddenIsRateLimit). Movie, series, ebook and
manga classification is unchanged.
- Count clean no-matches and consecutive failures separately. Failures
back off exponentially and become the terminal outcome "failed" after
10 in a row, or 2 for permanent errors. A failure no longer resets
the no-match count.
- Pause a provider for the rest of the sweep after a rate-limit answer
(honoring retry-after) or three transient failures in a row. Items
whose providers are all paused are deferred without counting an
attempt.
- Let one node sweep at a time with an advisory lock.
- Load provider IDs for a batch in one query, report per-outcome sweep
counts, and retry skipped items hourly instead of every 6 hours.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Defer instead of charging a failure when only paused providers errored
before an author mismatch, and resume a deferred book at the earliest
provider pause end. A skipped metadata lookup no longer clears a
provider's failure streak; a per-item answer such as NotFound does.
Sweep without the advisory lock on a one-connection pool, mask secrets
in the stored last_error, start backfilled failure streaks at one, and
restore the no-match count in attempts on rollback.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai The outside-diff finding in your review (pause-only errors in the author-mismatch branch at enrichment.go:824) is fixed in 17f288b. That branch now defers the book when every error came from a paused provider, the same as the no-metadata branch, so the book isn't charged a failure.
Revises an earlier Kody suggestion on internal/audiobooks/enrichment.go:213 (2026-11-14 23:04 UTC).
Separate batches can hit the same throttled provider concurrently because per-item claims do not ensure cluster-wide exclusion. Arrange a lock connection for pools with MaxConns below 2 rather than bypassing the lock.
Prompt for LLM
File internal/audiobooks/enrichment.go, lines 265-267:
**Revises an earlier Kody suggestion** on `internal/audiobooks/enrichment.go:213` (2026-11-14 23:04 UTC).
Single-connection nodes bypass cluster-wide sweep exclusion
A node with a one-connection pool runs without acquiring the cluster lock, so it sweeps concurrently with every other node even when they hold that lock; per-item claims do not prevent their separate batches from simultaneously hitting the same throttled provider. The earlier deadlock fix needs a lock connection arrangement that preserves cluster-wide exclusion instead of bypassing it.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 5c17f23 by removing the bypass. The sweep lock now lives on its own session, opened with the pool's configuration but outside the pool, the way the backup lock (backup.PostgresLocker) and the migration lock already do. Every node goes through the same lock, including one whose pool allows a single connection, and the sweep's own queries still have the pool's connection. Closing that session releases the lock, including when the process dies. The pending-items check reads pg_locks for the key instead of opening a session every five minutes. The one-connection Postgres test still finishes, and the test that holds the lock from another session still sees the sweep and the pending-items check stand down.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for addressing this. The dedicated lock session resolves the concern as described: even nodes with a single-connection pool participate in cluster-wide sweep exclusion without blocking their own queries. The reported tests also cover both the single-connection case and standing down when another session holds the lock.
I haven’t independently verified the commit or test results.
The reason will be displayed to describe this comment to others. Learn more.
Successful metadata requests do not reset the outage streak
Intermittent metadata failures can pause a healthy provider despite successful requests between them. Reset the failure streak when result proves a request succeeded, while keeping (nil, nil) as a no-op.
Prompt for LLM
File internal/audiobooks/enrichment_gate.go, lines 237-239:
Successful metadata requests do not reset the outage streak
Successful metadata responses never clear the provider's failure streak, so three intermittent metadata failures can pause a healthy metadata-only provider despite successful requests between them. Reset the streak when `result` proves a real metadata request succeeded, while retaining the no-op handling for `(nil, nil)`.
Suggested code:
if err != nil || result != nil {
p.gate.observe(ctx, p.Slug(), err)
}
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 5c17f23. A metadata request that returns a result now clears the failure streak and the outage escalation. (nil, nil) still changes nothing, because the adapter returns it without a request. TestSuccessfulMetadataLookupClearsTheFailureStreak repeats two failures and a successful lookup three times and checks that the provider isn't paused. It fails without the fix.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for addressing this. The described fix resolves the concern: a successful metadata result clears the outage streak, while (nil, nil) remains a no-op. The regression test covers the intermittent-failure scenario.
The reason will be displayed to describe this comment to others. Learn more.
Rollback retains total attempts for pending and skipped books
After rollback, pending or skipped books can reach the no-match limit prematurely because the older code interprets attempts as a no-match streak. Restore attempts from no_matches for those rows as well.
Prompt for LLM
File migrations/sql/20261114222928_audiobook_enrichment_retry_counters.sql, lines 32-34:
Rollback retains total attempts for pending and skipped books
Rollback leaves total attempt counts on pending and skipped rows even though the older code interprets `attempts` as the no-match streak. After rollback, a book with multiple failures or skips can reach the no-match limit on its next clean lookup and stop being retried prematurely; restore the appropriate no-match count for those rows as well.
Suggested code:
UPDATE audiobook_enrichment_state
SET attempts = no_matches;
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 5c17f23, in the same migration. On the way down, attempts is reset to the no-match count on every row whose outcome isn't success: pending, skipped, failed and no_match. In a down/up round trip on seeded rows, a pending row with 4 attempts and 1 no-match went back to 1, a skipped row with 5 and 1 went back to 1, and the success row kept its count.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the update. Resetting attempts to no_matches for all non-success rows addresses the rollback concern, and the seeded round-trip results cover the pending and skipped cases raised in the suggestion.
…adata successes
The sweep lock now lives on a session opened outside the pool, as the
backup and migration locks do, so a one-connection pool no longer has to
skip it; the pending-items check reads pg_locks instead of opening a
session. A metadata request that returns a result clears the provider's
failure streak. The down migration restores attempts from the no-match
count on every unfinished row.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 settingsReview Options
The following review options are enabled or disabled:
Options
Enabled
Bug
✅
Performance
✅
Security
✅
Business Logic
❌
⚠️ 4 Kody Rule(s) were not evaluated
These rules declare that they need repository context beyond this diff, and the review could not retrieve it, so they were not judged on this pull request:
Preserve optional store capabilities through production wrappers
Detach mandatory cleanup from request cancellation and bound its lifetime
Preserve durable media identity and share identity-evidence precedence
Bound decoder throughput trades and share direct-play eligibility
The reason will be displayed to describe this comment to others. Learn more.
Sweep lock probe matches locks held in other databases
A sweep in another database with the same advisory lock key can make HasPendingItems report no work, suppressing enrichment in this database. Filter pg_locks.database to the current database's OID.
Prompt for LLM
File internal/audiobooks/enrichment.go, lines 295-296:
Sweep lock probe matches locks held in other databases
The lock probe matches advisory locks from every database on the PostgreSQL server, although advisory locks are scoped to individual databases. A sweep in another database with the same key can therefore make `HasPendingItems` report no work and suppress this database's enrichment; filter `pg_locks.database` to the current database's OID.
Suggested code:
WHERE locktype = 'advisory' AND granted AND objsubid = 1
AND database = (SELECT oid FROM pg_database WHERE datname = current_database())
AND classid::bigint = $1 AND objid::bigint = $2
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 01a524f. The probe now matches only locks in this database (pg_locks.database equal to the current database's OID), so a sweep in another Silo database on the same server no longer hides this one's work. It's the only pg_locks read in the change. The Postgres test now takes the same lock key while connected to the server's postgres database and checks that this database doesn't treat it as its own sweep. That check failed without the filter and passes with it. It skips only if the server has no reachable postgres database.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the update. Filtering by the current database’s OID addresses the reported cross-database lock issue, and the regression test covers the scenario. The test will skip if the postgres database is unreachable, as noted.
The reason will be displayed to describe this comment to others. Learn more.
Scope the sweep-lock lookup to the current database
When two Silo deployments use separate databases on the same PostgreSQL cluster, this query also sees the other database's sweep lock: pg_locks is cluster-wide, while advisory locks are database-local. Consequently, HasPendingItems returns false during the other deployment's sweep, and SyncAudiobookMetadataTask.ShouldRun suppresses scheduled enrichment even though this deployment could acquire its own lock. Filter database to the current database's OID so independent deployments do not delay each other's backlog processing.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 01a524f. The pending-items check now reads only advisory locks held in its own database, and a contract test holds the same lock key from the server's postgres database to show it is not counted. This is the same finding as the Kody thread on this line.
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 settingsReview Options
The following review options are enabled or disabled:
Options
Enabled
Bug
✅
Performance
✅
Security
✅
Business Logic
❌
⚠️ 4 Kody Rule(s) were not evaluated
These rules declare that they need repository context beyond this diff, and the review could not retrieve it, so they were not judged on this pull request:
Preserve optional store capabilities through production wrappers
Detach mandatory cleanup from request cancellation and bound its lifetime
Preserve durable media identity and share identity-evidence precedence
Bound decoder throughput trades and share direct-play eligibility
…tched
#4204 added the terminal enrichment outcome 'failed'. List those books
in the admin unmatched list beside 'no_match', so an admin can find and
match them; the matched predicate and the scanner already treat them as
unmatched. Describe split credits and the failure path in the ownership
doc.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* fix(audiobooks): keep a provider match intact across rescans
A rescan of a matched audiobook replaced the provider's year with the tag
year (or 0), replaced its credits with the tag credits, and merged tag
genres back in, while the provider's overview and cover stayed. A match
deleted a narrator read from tags when the provider had none, wrote
credits outside its transaction, and replaced the book's own cover with
the provider poster while keeping the old thumbhash.
Give each field one owner. Once a provider matched a book (it has a
provider ID other than the scanner's ASIN), the provider owns year,
genres, studios and credits, and the tags only fill what is empty. Tags
keep the title and series. A match replaces credits only for the kinds
the provider names, inside the match transaction, and fills a cover
only when the book has none. Both writers decide under the item's row
lock.
The admin unmatched-items list now includes audiobooks whose enrichment
found no provider match, derived from the enrichment state so no
backfill is needed and media_items.status stays empty for books.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* fix(audiobooks): count a match that stored only the ASIN as matched
A successful enrichment stores the provider IDs that survive identity
admission. When those are only the tagged ASIN, the scanner treated the
book as unmatched and let tags overwrite the provider's values, while
the unmatched list hid it as a success. Count the enrichment success
outcome as a match too, in the one predicate both use.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* fix(audiobooks): count an admin match as matched and find renamed matched books
Match Item can apply only the ASIN. It writes status 'matched' through
the metadata pipeline but no enrichment outcome, so the book stayed in
the unmatched list and a rescan let tags overwrite the match. Count that
status in the matched predicate.
The duplicate check for a renamed or moved folder compared the tag year
with media_items.year, which a match now owns. Compare it with the tag
year stored on the files, so a matched book whose provider year differs
keeps its content ID and progress.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* fix(scanner): fall back to the item year for audiobook files without base_year
Migration 078 left media_files.base_year at 0 for files that existed
then, and an unchanged audiobook folder is never rewritten. The renamed
folder check now compares the files' tag year when it is set and the
item year when none of the item's files has one.
Document that rename detection still needs the stored author and
narrator to match the tags.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* fix(audiobooks): list audiobooks whose providers kept failing as unmatched
#4204 added the terminal enrichment outcome 'failed'. List those books
in the admin unmatched list beside 'no_match', so an admin can find and
match them; the matched predicate and the scanner already treat them as
unmatched. Describe split credits and the failure path in the ownership
doc.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---------
Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bugSomething isn't workinggoPull requests that update go codepriority: P2Limited scope, workaround exists, or polishsize/XXL1000–2999 added + deleted lines (all files); change volume, not priority.
1 participant
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Related issue: N/A
Validation tasks: changes #1254 C2 (not yet run; no passed case affected)
Other clients: N/A (no client-visible change)
When the audiobook metadata provider has trouble, the enrichment sweep handles it badly. A throttled request can keep a book out of enrichment for 30 days. A book whose lookups always fail is retried forever. A rate-limited provider keeps getting the rest of a 250-book sweep. Every API node runs its own sweep, so each added node adds provider load. This change makes the sweep back off on throttling, stop on persistent failures, and run on one node at a time. It affects audiobook libraries only, which are beta.
GetMetadatareturns source errors such asitunes: HTTP 403with no gRPC code. The host read the bare 403 as permanent, which parks the book for 30 days. Apple's API answers throttling with 403.Approach
Classification.
metadata.ProviderErrorPolicygains an opt-inForbiddenIsRateLimitthat the audiobook enricher sets. An untyped 403 then backs the book off as rate limited. A 401, typed gRPC denials, and not-found or invalid-argument errors stay permanent. Movie, series, ebook and manga callers keep the default policy, and their existing tests pass unchanged.Retry counters. A migration adds
no_matchesandfailurestoaudiobook_enrichment_stateand backfills them fromattempts, which now counts every attempt.failed. The sweep no longer claims it, and the last error class and message stay on the row.Pausing a provider. For the rest of the sweep and beyond, the enricher stops calling a provider that:
A book whose providers are all paused goes back in the queue until the pause ends, and the deferral doesn't count as an attempt. A provider outage therefore costs a few probe attempts instead of pushing the whole backlog to
failed. An untyped 403 backs off that one book but does not pause the provider: a source that rejects every request with 403 would otherwise stall the sweep for every other book.One sweeping node.
Runtakes a Postgres advisory lock on a session of its own, opened outside the pool like the backup and migration locks, andHasPendingItemsreports nothing to do while another node holds it. That check readspg_locksfor this database only, so another Silo database on the same Postgres server sweeps independently. This is simpler than a shared request budget and behaves the same on one node or many. The pause lives in process memory. When the next sweep starts on a different node, that node relearns the pause from the provider's next answer.Smaller fixes.
claimBatchloads provider IDs for the whole batch in one query instead of one per book.Degraded searches (left conservative). The plugin's
Searchsucceeds when any one source answers, so if the strongest source is throttled and another returns non-matching results, the host still sees a clean empty answer. The host can't detect that with plugin 0.1.7. This change doesn't alter how a no-match becomes final: it still takes three clean answers about 24 hours apart. The host already refuses a no-match whenever any provider in the chain reports an error, and that now includes a provider the enricher skipped because it was paused. A plugin follow-up should report which sources failed even when the search partly succeeds, and sendGetMetadataerrors with gRPC codes (ResourceExhaustedwithRetryInfofor 429 or throttling 403,Unavailablefor outages,NotFoundonly when the source says the ID doesn't exist).Validation
go build ./...,gofmt -l .,go mod tidy -diff,go vet ./...: clean.make lint-changed,make lint-router-recovery,verify-local-paths,verify-case-collisions,verify-bidi,verify-migrations,verify-size-ratchet: pass.make test-go: passed on the full change before the review fixes. After those fixes,internal/playbackTestCopyRemuxSubtitleRenditionRealFFmpegfails. It also fails on unchangedmainin the same environment, andinternal/playbackimports no package this change touches.internal/audiobooks,internal/metadata,internal/ebooksandinternal/mangapass, and thedbpinsrunner passes the newdb-contracts.txtentries.01a524f55d), after all review fixes: the Postgres-backed tests, those packages plusdatabase/pglock, and thedbpinsrunner pass again, and a down/up round trip of the new migration on seeded rows gives the expected counts.Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/pr-4204/
Nothing user-visible changes. The new tests simulate provider errors and never call live providers:
itunes: HTTP 403classifies as rate limited for audiobooks and stays permanent under the default policy. A 401 and typed denials stay permanent.failed. A retry-after raises the backoff.Rundoes nothing while another session holds the sweep lock, never claims afailedbook, parks the throttled book for the provider's 3h retry-after, and defers the rest of the batch without another provider call, including a book whose second provider answered empty.Risks
audiobook_enrichment_state. It adds two columns with defaults; no-match rows take their count fromattempts, and rows pending after a failure start with a failure count of 1. The down migration turnsfailedrows back into pending failures and resetsattemptsto the no-match count on every unfinished row.failedneeds an admin refresh or match. Nothing re-queues it automatically.Checklist
AI Disclosure
failed; paused-only failures counted as attempts; retry-after was taken from unrelated providers; 401 was treated as a throttle; a folder ID of 403 could be misread as an HTTP status. Kept as described above: the in-memory pause across a node handover, and the lock connection. Bot reviews on the PR (Codex, Kody, CodeRabbit) found further problems, all fixed and answered on their threads: a skipped metadata lookup cleared the failure streak; pause-only errors before an author mismatch were charged as failures; a deferred book waited for the longest pause rather than the earliest; a NotFound answer didn't break the failure streak; the sweep hung on a one-connection pool, now fixed by taking the lock on its own session; a successful metadata lookup didn't clear the failure streak; the storedlast_errorwasn't redacted; and the migration's backfill and rollback miscounted.🤖 Generated with Claude Code
Note
Add provider pause gating and bounded retry backoff to audiobook enrichment
providerGate(enrichment_gate.go) that pauses providers on rate limits (15-minute default) and on transient-failure streaks (3 failures, doubling up to 6 hours). Paused providers receive no calls; items whose whole provider chain is paused are deferred instead of counted as no-match or failure.failedoutcome after 10 transient/rate-limited or 2 permanent failures, retry-after capped at 7 days, error text redacted before storing. Newno_matchesandfailurescolumns added by migration.ProviderErrorPolicyin provider_error.go; HTTP 401 and typed gRPC denials stay permanent.no_matchescounter rather thanattempts, failed rows are excluded from pending work, unclaimed writes can create state rows, and claim writes require an unexpired lease. Rolling back the migration clears failed outcomes and restoresattemptsfromno_matches.Macroscope summarized 01a524f.