Skip to content

fix(metadata): gate book enrichment on a credible match, and drain the no_match backlog - #520

Merged
Quick104 merged 20 commits into
Silo-Server:mainfrom
RXWatcher:fix/ebook-pending-status-promotion
Aug 20, 2026
Merged

Quick104 merged 20 commits into
Silo-Server:mainfrom
RXWatcher:fix/ebook-pending-status-promotion

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

The whole book-enrichment stack, in one place

This branch is the superset of the two open enrichment PRs, plus two commits that exist in neither. It is exactly what production ran from 27 July until today, when the server was moved onto an official image and every one of these commits was rolled off it.

Supersedes #496 (11 commits) and #514 (15 commits) — both are strict subsets of this branch and can be closed in its favour. Reviewing three overlapping PRs for one body of work is how one gets merged and the others quietly rot.

Two commits are here and nowhere else — they have never been part of any PR:

  • 032b7785 fix(ebooks): promote ebooks resolved from complete local metadata
  • a59fef7c chore(docker): keep agent scratch dirs out of the build context

032b7785 is the commit the production image was named after (pending-promotion-032b7785). Until this PR, it existed only on a fork branch and inside a container image that has now been replaced.

Why it exists

Enrichment was accepting the first result a provider returned, with no scoring. A search for a title would match a different book, a different volume, or a different author, and store it as though it were correct. Separately, audiobook enrichment gated on cover art rather than on identity, so items with no artwork never enriched at all.

The result was a large no_match backlog that never drained, and a body of confidently wrong metadata.

What changed

Match gating — a provider result must now clear a credible-title check before it is accepted. Scoring drops stopwords, folds numerals, normalises Unicode, breaks ties on year, and refuses to mix IDs across providers. The author is verified after fetching, not merely assumed from the search hit.

Audiobook enrichment gates on identity rather than cover art, and gets its own state table so a failure is recorded durably instead of inferred. Failure recording is atomic and UTF-8 safe.

Ebook search queries the bare title and disambiguates volumes afterwards, rather than folding volume information into the query where it corrupts the match.

The no_match drain counts real no_match cycles and escalates their retry horizon, so a genuinely unmatchable item stops consuming the same budget forever, and 032b7785 promotes ebooks that already resolve from complete local metadata rather than holding them behind a provider lookup that will never succeed.

Commits

  • 45c1409b1 fix(audiobooks): gate enrichment on identity, not cover art
  • 850044867 fix(metadata): require a credible title match before accepting a provider result
  • 22feeb3ba fix(metadata): drop stopwords when scoring title similarity
  • 269f52027 fix(ebooks): search the bare title and disambiguate volumes after the search
  • fa92497db fix(metadata): make title normalisation Unicode-aware
  • 2690b7f03 fix(metadata): fold numerals, break ties on year, and stop cross-provider ID mixing
  • 56f1c5783 fix(metadata): verify the author after fetching, not just the title
  • c9dc35dda feat(audiobooks): give enrichment its own state table
  • 631609327 fix(metadata): close four review findings on the match gate
  • 5b28b42df fix(audiobooks): make failure recording atomic and UTF-8 safe
  • 4d9de39e5 fix(metadata): harden book enrichment admission
  • c46667305 fix(ebooks): count real no_match cycles and escalate their retry horizon
  • 1179b2161 Merge remote-tracking branch 'upstream/main' into fix/ebook-nomatch-drain
  • 7674ddeaa test(access): implement onboarding methods on the resolver stub store
  • c6a5be48c test(jellycompat): implement onboarding methods on progress stub stores
  • 032b7785b fix(ebooks): promote ebooks resolved from complete local metadata
  • a59fef7cc chore(docker): keep agent scratch dirs out of the build context

Provenance and testing

This ran in production for three days on real libraries — a far larger corpus than any fixture — and the enrichment backlog behaviour was observed against it directly. It is no longer deployed: production moved to ghcr.io/silo-server/silo-server:latest (revision b1b09300) today to pick up the cross-platform settings API from #479, which meant dropping all 17 of these commits. That trade is the reason this PR exists now rather than later.

1179b2161 is a merge of upstream/main taken on 29 July; the two test(...) commits alongside it implement onboarding methods on stub stores that the merge required.

Summary by CodeRabbit

  • New Features

    • Improved audiobook, ebook, and manga metadata matching across providers.
    • Added stronger safeguards against conflicting titles, authors, and duplicate provider identities.
    • Added smarter retry scheduling for temporary, rate-limited, and permanent enrichment failures.
  • Bug Fixes

    • Prevented partial metadata updates when enrichment persistence fails.
    • Improved handling of locally complete ebooks and failed provider updates.
    • Refined title cleanup for editions, volumes, and series markers.
  • Reliability

    • Enrichment jobs now pause and resume according to retry eligibility, reducing repeated unsuccessful attempts.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Quick104, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 6 minutes

Limit details: You’ve used all 2 included reviews currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

Wait for the limit to reset, then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4ce251eb-fbdd-4f30-9286-d27b9f60875e

📥 Commits

Reviewing files that changed from the base of the PR and between d332b54 and 19cdab2.

📒 Files selected for processing (25)
  • .dockerignore
  • internal/audiobooks/enrichment.go
  • internal/audiobooks/enrichment_claim_db_test.go
  • internal/audiobooks/enrichment_state.go
  • internal/audiobooks/enrichment_state_db_test.go
  • internal/audiobooks/enrichment_test.go
  • internal/catalog/item_repo.go
  • internal/ebooks/enrichment.go
  • internal/ebooks/enrichment_queue.go
  • internal/ebooks/enrichment_queue_test.go
  • internal/ebooks/enrichment_test.go
  • internal/manga/enrichment.go
  • internal/manga/enrichment_test.go
  • internal/metadata/author_match.go
  • internal/metadata/author_match_test.go
  • internal/metadata/match_admission.go
  • internal/metadata/match_admission_test.go
  • internal/metadata/match_confidence.go
  • internal/metadata/match_confidence_test.go
  • internal/metadata/provider_error.go
  • internal/metadata/provider_error_test.go
  • internal/metadata/provider_id_owner.go
  • migrations/sql/20260727181634_add_audiobook_enrichment_state.sql
  • migrations/sql/20260728225039_classify_manga_enrichment_failures.sql
  • migrations/sql/20260820162717_add_audiobook_enrichment_claims.sql
📝 Walkthrough

Walkthrough

Changes

Audiobook, ebook, and manga enrichment now use stricter metadata admission, author validation, provider-identity ownership checks, classified retry scheduling, and improved persistence error handling. Audiobooks add durable enrichment state and atomic persistence. Ebook and manga queues update retry eligibility and backoff behavior.

Audiobook, ebook, and manga enrichment

Layer / File(s) Summary
Metadata matching and admission contracts
internal/metadata/*
Adds title confidence scoring, author agreement, provider-ID admission, ownership checks, and provider error classification with comprehensive tests.
Audiobook retry state and atomic persistence
internal/audiobooks/enrichment.go, internal/audiobooks/enrichment_state.go, internal/catalog/item_repo.go, migrations/sql/20260727181634_add_audiobook_enrichment_state.sql, internal/audiobooks/*_db_test.go
Adds durable audiobook outcomes/failures, retry windows, identity-based claiming, transactional metadata persistence, and database coverage.
Audiobook provider admission and outcomes
internal/audiobooks/enrichment.go, internal/audiobooks/enrichment_test.go
Applies shared match and identity admission during search and metadata retrieval, records terminal outcomes, and propagates persistence failures.
Ebook promotion, admission, and retry scheduling
internal/ebooks/enrichment.go, internal/ebooks/enrichment_queue.go, internal/ebooks/*_test.go
Adds local-match promotion, author and identity validation, shared error classification, title-cleaning changes, and exponential no-match retry horizons.
Manga admission and classified retries
internal/manga/enrichment.go, internal/manga/enrichment_test.go, migrations/sql/20260728225039_classify_manga_enrichment_failures.sql
Adds retryable failure eligibility, durable backoff fields, provider admission, author validation, and provider-ID persistence error propagation.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related issues

Possibly related PRs

Suggested labels: v1

Suggested reviewers: quick104

Sequence Diagram(s)

sequenceDiagram
  participant EnrichmentSweep
  participant MetadataAdmission
  participant Provider
  participant EnrichmentState
  participant Database
  EnrichmentSweep->>Provider: Search and retrieve metadata
  Provider-->>EnrichmentSweep: titles, authors, provider IDs
  EnrichmentSweep->>MetadataAdmission: validate matches and identities
  MetadataAdmission-->>EnrichmentSweep: admitted metadata or rejection
  EnrichmentSweep->>Database: atomically persist metadata and provider IDs
  EnrichmentSweep->>EnrichmentState: record success, no-match, skipped, or failure
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 metadata matching and no_match backlog changes in the pull request.
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 unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@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: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/audiobooks/enrichment.go (1)

401-424: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

status promotion to matched is unconditional on skip/no-match, contradicting new outcome tracking.

stampLastRefreshed (unchanged, Lines 895-908) always runs status = CASE WHEN status = 'pending' THEN 'matched' ELSE status END. It is now invoked from the "no library folder" skip (Line 411), "no providers in chain" skip (Line 424), and the "providers ran cleanly but nothing matched" branch (Line 624) — all paths that also record EnrichmentOutcomeSkipped/EnrichmentOutcomeNoMatch into the new audiobook_enrichment_state table. The result: an item that was never actually identified gets media_items.status = 'matched' while audiobook_enrichment_state.outcome = 'no_match'/'skipped' for the same row — a direct contradiction between the two sources of truth this PR introduces. Any client or query relying on status to mean "successfully matched" (e.g. library filtering, "needs review" views) will misreport unmatched items as matched.

Consider gating the status promotion so it only happens on the genuine success path (mirroring persistMetadataAndProviderIDsTx's stamp at Lines 824-833), and using a separate "stamp last_refreshed only" helper for skip/no-match terminal states.

🔧 Suggested direction
-func (e *Enricher) stampLastRefreshed(ctx context.Context, contentID string) error {
+// stampLastRefreshedNoMatch stamps last_refreshed without promoting status,
+// used when enrichment concluded skipped/no-match rather than a real match.
+func (e *Enricher) stampLastRefreshedNoMatch(ctx context.Context, contentID string) error {
 	if e.pool == nil {
 		return nil
 	}
 	now := time.Now().UTC()
 	_, err := e.pool.Exec(ctx, `
 		UPDATE media_items
-		SET last_refreshed = $1,
-		    matched_at     = COALESCE(matched_at, $1),
-		    status         = CASE WHEN status = 'pending' THEN 'matched' ELSE status END
+		SET last_refreshed = $1
 		WHERE content_id = $2
 	`, now, contentID)
 	return err
 }

Then swap the calls at Lines 411, 424, and 624 to this variant.

Also applies to: 608-625, 895-908

🤖 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/audiobooks/enrichment.go` around lines 401 - 424, Separate
last-refreshed recording from pending-to-matched status promotion in
stampLastRefreshed and the enrichment flow. Add or reuse a helper that only
updates last_refreshed for the no-folder, no-provider, and no-match branches in
enrichItem, while retaining status promotion exclusively on the genuine
successful metadata persistence path (such as persistMetadataAndProviderIDsTx).
🧹 Nitpick comments (4)
migrations/sql/20260728225039_classify_manga_enrichment_failures.sql (1)

12-18: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Down migration: same concurrent-drop concern for the index; column drops are expected for a rollback.

Squawk's require-concurrent-index-deletion on Line 13 is worth applying for consistency with the Up migration's non-blocking approach; the ban-drop-column hits on Lines 17-18 are expected here since this is the rollback of columns added in this same migration.

🔧 Proposed tweak
 -- +goose Down
-DROP INDEX IF EXISTS idx_manga_enrichment_state_next_attempt;
+DROP INDEX CONCURRENTLY IF EXISTS idx_manga_enrichment_state_next_attempt;
🤖 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 `@migrations/sql/20260728225039_classify_manga_enrichment_failures.sql` around
lines 12 - 18, Update the Down migration’s index removal to use the concurrent
index-drop form, matching the non-blocking approach used by the Up migration.
Leave the rollback of the constraint and columns in the ALTER TABLE statement
unchanged.

Source: Linters/SAST tools

internal/manga/enrichment_test.go (1)

202-237: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Good coverage, but doesn't exercise the providerErrs-alongside-mismatch scenario flagged in enrichment.go.

This test correctly validates that a contradictory author fails the item closed without merging bad data. It doesn't cover the case where a different provider's search or metadata call independently errors (e.g., rate limit) while another provider's metadata disagrees on author — the scenario where the current authorMismatch short-circuit in enrichWithProviders discards providerErrs and stamps a terminal no-match prematurely (see the enrichment.go Lines 393-403/619-627 comment).

🤖 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/manga/enrichment_test.go` around lines 202 - 237, Extend
TestCollectMangaMetadataRejectsEachProviderAuthorBeforeMerging to include an
independent provider search or metadata error alongside the contradictory author
result. Assert that authorMismatch does not discard providerErrs or prematurely
stamp a terminal no-match, while still preventing the contradictory metadata
from merging.
migrations/sql/20260727181634_add_audiobook_enrichment_state.sql (1)

18-54: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Consider a CHECK constraint on outcome/last_error_class for the documented enum values.

The migration's own comments document outcome as 'success' | 'no_match' | 'skipped' and last_error_class as 'transient' | 'rate_limited' | 'permanent', but nothing enforces these at the DB level. Since the migration's stated purpose is reliable backlog reporting by outcome, a CHECK constraint would catch an application bug writing an unexpected string before it corrupts reporting queries.

🛡️ Suggested constraint
     outcome          TEXT,
+    CONSTRAINT audiobook_enrichment_state_outcome_check
+        CHECK (outcome IS NULL OR outcome IN ('success', 'no_match', 'skipped')),
🤖 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 `@migrations/sql/20260727181634_add_audiobook_enrichment_state.sql` around
lines 18 - 54, Add CHECK constraints to audiobook_enrichment_state enforcing
outcome as NULL or one of success, no_match, or skipped, and last_error_class as
NULL or one of transient, rate_limited, or permanent. Keep the documented NULL
semantics for unattempted or unclassified rows unchanged.
internal/audiobooks/enrichment.go (1)

806-839: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated terminal-stamp SQL between here and stampLastRefreshed.

The UPDATE media_items SET last_refreshed=..., matched_at=..., status=... block (Lines 825-833) is byte-for-byte the same statement as stampLastRefreshed (Lines 900-906), just running against a tx instead of e.pool. Consider extracting a shared query string/helper that accepts an Execer (satisfied by both *pgxpool.Pool and pgx.Tx) so the two copies can't drift.

As per path instructions for internal/**/*.go: "extract shared logic instead of duplicating it."

🤖 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/audiobooks/enrichment.go` around lines 806 - 839, The media_items
terminal-stamp SQL is duplicated between persistMetadataAndProviderIDsTx and
stampLastRefreshed. Extract the shared update statement or helper into a
reusable symbol accepting the common executor interface, then call it from both
functions while preserving the existing transaction and pool execution behavior.

Source: Path instructions

🤖 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/ebooks/enrichment.go`:
- Around line 1412-1418: Remove the unanchored bare-year alternative from
ebookSeriesNoiseRE, leaving bare-year handling to ebookYearOnlyRE in
cleanEbookSearchTitle. Preserve the anchored bare-number and volume-marker
alternatives so meaningful parentheticals containing years remain intact while
genuinely standalone years continue to be removed.
- Around line 787-800: Update the authorMismatch branch in the enrichment flow
around collectEbookMetadata to surface any accumulated providerErrs before
returning EnrichmentOutcomeNoMatch. Log or otherwise report those errors using
the same established handling as the nearby no-metadata branch, while preserving
the existing claim and stampLastRefreshed operations.

In `@internal/manga/enrichment.go`:
- Around line 393-403: Update the authorMismatch branch in enrichWithProviders
to inspect providerErrs before stamping last_refreshed or returning
errEnrichmentNoMatch. When provider errors are present, preserve the
transient-error path and avoid terminal stamping; only treat authorMismatch as
terminal when no provider errors were accumulated. Ensure the corresponding
early return in collectMangaMetadata preserves the providerErrs needed for this
decision.

In `@internal/metadata/match_admission.go`:
- Around line 134-139: Update the existing-provider branch in the metadata
admission logic to record a ProviderIDConflict when current differs from
providerID, instead of silently continuing. Preserve the HasUsableIdentity
behavior for matching IDs and ensure mismatches are surfaced through the same
Conflicts mechanism used for cross-provider ownership conflicts.

In `@internal/metadata/provider_error.go`:
- Around line 102-132: Update classifyProviderErrorText so numeric HTTP-code
checks match standalone codes rather than arbitrary substrings within larger
numbers. Add the needed boundary-aware matching and apply it to 429, 401, and
403 while preserving the existing textual classifications and fallback behavior.

In `@migrations/sql/20260728225039_classify_manga_enrichment_failures.sql`:
- Around line 2-10: Update the migration’s transaction and schema-change
statements: add the goose NO TRANSACTION directive, create
idx_manga_enrichment_state_next_attempt with CREATE INDEX CONCURRENTLY, and add
manga_enrichment_state_error_class_check as NOT VALID followed by a separate
VALIDATE CONSTRAINT statement. Preserve the existing constraint condition and
partial-index predicate.

---

Outside diff comments:
In `@internal/audiobooks/enrichment.go`:
- Around line 401-424: Separate last-refreshed recording from pending-to-matched
status promotion in stampLastRefreshed and the enrichment flow. Add or reuse a
helper that only updates last_refreshed for the no-folder, no-provider, and
no-match branches in enrichItem, while retaining status promotion exclusively on
the genuine successful metadata persistence path (such as
persistMetadataAndProviderIDsTx).

---

Nitpick comments:
In `@internal/audiobooks/enrichment.go`:
- Around line 806-839: The media_items terminal-stamp SQL is duplicated between
persistMetadataAndProviderIDsTx and stampLastRefreshed. Extract the shared
update statement or helper into a reusable symbol accepting the common executor
interface, then call it from both functions while preserving the existing
transaction and pool execution behavior.

In `@internal/manga/enrichment_test.go`:
- Around line 202-237: Extend
TestCollectMangaMetadataRejectsEachProviderAuthorBeforeMerging to include an
independent provider search or metadata error alongside the contradictory author
result. Assert that authorMismatch does not discard providerErrs or prematurely
stamp a terminal no-match, while still preventing the contradictory metadata
from merging.

In `@migrations/sql/20260727181634_add_audiobook_enrichment_state.sql`:
- Around line 18-54: Add CHECK constraints to audiobook_enrichment_state
enforcing outcome as NULL or one of success, no_match, or skipped, and
last_error_class as NULL or one of transient, rate_limited, or permanent. Keep
the documented NULL semantics for unattempted or unclassified rows unchanged.

In `@migrations/sql/20260728225039_classify_manga_enrichment_failures.sql`:
- Around line 12-18: Update the Down migration’s index removal to use the
concurrent index-drop form, matching the non-blocking approach used by the Up
migration. Leave the rollback of the constraint and columns in the ALTER TABLE
statement unchanged.
🪄 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: 0ce52d50-ae95-4b80-854b-c29be3f4d4a7

📥 Commits

Reviewing files that changed from the base of the PR and between b1b0930 and a59fef7.

📒 Files selected for processing (28)
  • .dockerignore
  • internal/access/resolver_test.go
  • internal/audiobooks/enrichment.go
  • internal/audiobooks/enrichment_claim_db_test.go
  • internal/audiobooks/enrichment_state.go
  • internal/audiobooks/enrichment_state_db_test.go
  • internal/audiobooks/enrichment_test.go
  • internal/audiobooks/smartcoll/evaluator_test.go
  • internal/audiobooks/smartcoll/query_test.go
  • internal/catalog/item_repo.go
  • internal/ebooks/enrichment.go
  • internal/ebooks/enrichment_queue.go
  • internal/ebooks/enrichment_queue_test.go
  • internal/ebooks/enrichment_test.go
  • internal/jellycompat/content_direct_test.go
  • internal/manga/enrichment.go
  • internal/manga/enrichment_test.go
  • internal/metadata/author_match.go
  • internal/metadata/author_match_test.go
  • internal/metadata/match_admission.go
  • internal/metadata/match_admission_test.go
  • internal/metadata/match_confidence.go
  • internal/metadata/match_confidence_test.go
  • internal/metadata/provider_error.go
  • internal/metadata/provider_error_test.go
  • internal/metadata/provider_id_owner.go
  • migrations/sql/20260727181634_add_audiobook_enrichment_state.sql
  • migrations/sql/20260728225039_classify_manga_enrichment_failures.sql

Comment on lines +787 to +800
var owner metadata.ProviderIDOwnerLookup
if e.providerIDs != nil {
owner = e.providerIDs
}
accumulator, accumulatedIDs, providerErrs := collectEbookMetadata(ctx, item, providers, owner)
accumulator, accumulatedIDs, providerErrs, authorMismatch := collectEbookMetadata(ctx, item, providers, owner)
if authorMismatch {
if err := requireEnrichmentClaim(ctx); err != nil {
return "", err
}
if err := e.stampLastRefreshed(ctx, item.ContentID); err != nil {
return "", err
}
return EnrichmentOutcomeNoMatch, nil
}

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Provider errors collected before the author-mismatch short-circuit are silently dropped.

collectEbookMetadata can accumulate providerErrs (search/GetMetadata failures from other providers) before hitting the author-mismatch return at line 1050. When authorMismatch is true here, those errors are discarded entirely — never logged, never joined — unlike the "no metadata" branch a few lines below which explicitly surfaces providerErrs. This hides real transient/search failures behind what looks like a clean author-mismatch rejection, making backlog debugging harder.

🐛 Proposed fix: log dropped provider errors before returning
 	accumulator, accumulatedIDs, providerErrs, authorMismatch := collectEbookMetadata(ctx, item, providers, owner)
 	if authorMismatch {
+		if len(providerErrs) > 0 {
+			slog.WarnContext(ctx, "ebook enrichment: provider errors preceded author mismatch", "component", "ebooks",
+				"content_id", item.ContentID,
+				"errors", errors.Join(providerErrs...),
+			)
+		}
 		if err := requireEnrichmentClaim(ctx); err != nil {
 			return "", err
 		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var owner metadata.ProviderIDOwnerLookup
if e.providerIDs != nil {
owner = e.providerIDs
}
accumulator, accumulatedIDs, providerErrs := collectEbookMetadata(ctx, item, providers, owner)
accumulator, accumulatedIDs, providerErrs, authorMismatch := collectEbookMetadata(ctx, item, providers, owner)
if authorMismatch {
if err := requireEnrichmentClaim(ctx); err != nil {
return "", err
}
if err := e.stampLastRefreshed(ctx, item.ContentID); err != nil {
return "", err
}
return EnrichmentOutcomeNoMatch, nil
}
var owner metadata.ProviderIDOwnerLookup
if e.providerIDs != nil {
owner = e.providerIDs
}
accumulator, accumulatedIDs, providerErrs, authorMismatch := collectEbookMetadata(ctx, item, providers, owner)
if authorMismatch {
if len(providerErrs) > 0 {
slog.WarnContext(ctx, "ebook enrichment: provider errors preceded author mismatch", "component", "ebooks",
"content_id", item.ContentID,
"errors", errors.Join(providerErrs...),
)
}
if err := requireEnrichmentClaim(ctx); err != nil {
return "", err
}
if err := e.stampLastRefreshed(ctx, item.ContentID); err != nil {
return "", err
}
return EnrichmentOutcomeNoMatch, nil
}
🤖 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/ebooks/enrichment.go` around lines 787 - 800, Update the
authorMismatch branch in the enrichment flow around collectEbookMetadata to
surface any accumulated providerErrs before returning EnrichmentOutcomeNoMatch.
Log or otherwise report those errors using the same established handling as the
nearby no-metadata branch, while preserving the existing claim and
stampLastRefreshed operations.

Comment thread internal/ebooks/enrichment.go Resolved
Comment thread internal/manga/enrichment.go Resolved
Comment thread internal/metadata/match_admission.go Resolved
Comment thread internal/metadata/provider_error.go Resolved
RXWatcher and others added 20 commits August 20, 2026 13:19
The audiobook enrichment sweep had been permanently idle. Eligibility
required an empty poster_path, but the scanner extracts embedded cover
art from audiobook files, so every item had a poster before enrichment
ever looked at it. Cover presence says nothing about whether an item was
identified, and using it as the "already enriched" proxy meant the
predicate matched nothing.

On production this selected 0 rows while 5,712 audiobooks held no
provider ID at all -- 5,710 of them carrying a scanner-supplied poster.
The metadata providers had enriched 42 items in total; the 235,780 ASINs
in the library came from file scan, not from a provider. The 5-minute
trigger kept firing and finding nothing, so the gap could never drain.

Key both claimBatch and HasPendingItems on the absence of any row in
media_item_provider_ids instead. Sized against production this makes
5,682 items eligible rather than the 240,857 that dropping the poster
clause alone would have queued against Audible.

last_refreshed IS NULL is retained as the retry bound, and it is load
bearing: enrichItem stamps it on a clean no-match but deliberately
withholds it on provider error, so unmatchable items are attempted once
while transient failures still come back.

Adds DB-backed tests for both predicates, including the exact row the
regression hid (cover art present, no identity). Both fail against the
old predicate and pass against the new one. Neither query had any test
coverage before, which is how this survived.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
…ider result

Enrichment took results[0] from every search provider unconditionally.
Search backends rank by their own relevance and answer nearly every
query with something, so a provider's best guess became the item's
permanent identity -- and enrichment stamps last_refreshed on success
and never revisits, so a wrong acceptance is a permanent mislabel:
another book's cover, overview and narrator.

Measured rather than assumed. Twenty unidentified production audiobooks
were queried against the iTunes audiobook search: 19 returned a result
and roughly a quarter of those top hits were wrong -- either a different
volume of the right series ("The OP MC 8: God of Winning" answered by
"God of Winning: The OP MC, Book 1") or an unrelated title sharing one
common word ("Star Force Origins" answered by "The Achilles Trap").

Adds metadata.BestMatch, which scores candidates against the title we
hold on disk and returns nothing when none is credible -- callers treat
that as a no-match instead of falling back to the top row. Scoring is
word-set overlap (Dice) because the differences that matter are whole
words added or dropped: an author prefix, a series parenthetical, an
"(Unabridged)" suffix. A volume disagreement is fatal regardless of
overlap, since same-series wrong-volume pairs share nearly every word.

Wired into all three call sites that had the flaw: audiobooks, ebooks
and manga. Ebooks scores against item.Title rather than the outgoing
query, which is deliberately cleaned before it is sent.

Calibrated on the real probe pairs, kept as the test fixtures: correct
matches score >= 0.88, wrong ones <= 0.44, threshold 0.50. A test
asserts the two populations stay separated so a future tweak that
narrows the gap fails here rather than in production.

Three ebook fixtures needed a title on their SearchResult. They were
passing a result with no name at all, which the gate rejects; one of
them (SkipsProviderIDOwnedByAnotherItem) would otherwise have kept
passing for the wrong reason, never reaching the ownership check it
exists to cover.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
Validating the gate against the full 20-title production probe caught a
false accept it should have blocked. "All the Lies 1-3 - All the Lies:
The Complete Trilogy" was matched to "The Sentinel: The Complete Jane
Harper Trilogy: The Jane Harper Trilogy, Books 1-3" at 0.56, over the
0.50 threshold.

Both are "Books 1-3" boxed sets of unrelated series, and the score came
almost entirely from words that carry no identity: "the" three times,
plus "complete", "trilogy" and the 1 and 3 of the volume range. Neither
title's actual subject contributed. Excluding a small stopword set takes
the pair to 0.42, where it belongs, and leaves every correct match in
the sample above threshold.

The exclusion is skipped when it would leave fewer than two words to
compare, so titles that are mostly stopwords ("A Man in Full") still
have something to match on rather than scoring 0 against everything.

Rescored against all 20 probe pairs: 12 accepted, 7 rejected, 1 had no
answer. Every rejection is a genuine mismatch -- two wrong-volume pairs
of the right series, two unrelated titles, this boxed set, a bare common
noun, and a same-series different-book pair. Blind results[0] acceptance
would have taken 19 of these, roughly 6 of them wrong.

Fixtures now carry the untruncated provider strings, since the truncated
ones scored differently from what production actually returns -- which
is why the first version of this test passed while the real pair failed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
… search

cleanEbookSearchTitle unwrapped a trailing series marker -- brackets
removed, words kept -- so "Icarus (Realm Book 3)" went out as "Icarus
Realm Book 3". The reasoning was that the volume number is what tells
sibling volumes apart, and dropping it would make every entry in a
series search as the bare series name and collapse onto one work.

That held only while enrichment accepted results[0] blindly. It is no
longer true: metadata.BestMatch scores candidates against the raw
item.Title, which still carries "(Realm Book 3)", and treats a volume
disagreement as fatal. The disambiguator never needed to be in the
query -- it needed to be in the check, and now it is.

Meanwhile the unwrapped form was not disambiguating the search, it was
breaking it. "Realm Book 3" is retail furniture that no provider
catalogue indexes, so the query matched nothing at all.

Measured on 40 parked no_match ebooks that carry a series parenthetical,
with both query forms produced by this function and both result sets
scored by the real gate:

  what the server sends today : Open Library answered  3, accepted  0
  after this change           : Open Library answered 29, accepted 14

14 recovered, 0 lost. The gap between 29 answered and 14 accepted is the
scoring gate rejecting results that came back but are not the book --
15 wrong identities that blind results[0] would have stamped
permanently.

Scope, so the number is not read as more than it is: 23,802 of the
110,556 parked no_match ebooks (21.5%) carry a trailing series
parenthetical, so this reaches about a fifth of the backlog. The other
78.5% fail for reasons this does not touch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
Found reviewing this branch's own diff. normaliseTitle stripped via
[^a-z0-9] after lowercasing, which is ASCII-only. Every non-Latin title
reduced to the empty string, so TitleScore returned 0 and BestMatch
rejected it -- including against an identical title. "進撃の巨人" scored
0.00 against itself. Accented Latin fared little better:
"Blåbærsyltetøy" became "bl b rsyltet y".

That would have been a hard regression for non-English content, and a
quiet one: those items previously matched by accident, because
results[0] was accepted without any check at all. Manga is the obvious
exposure, but the library carries Danish and Norwegian ebooks too.

Strips [^\p{L}\p{N}]+ instead, so letters and digits in any script
survive. Tests cover Japanese, Russian and Danish titles matching
themselves and rejecting different titles in the same script.

For scripts that do not space their words, a whole title normalises to
one token, so Dice gives 1 on an exact match and 0 otherwise, with
containment carrying near-misses. Coarse, but correct, and strictly
better than what it replaces. minContainmentLen stays byte-measured,
now documented as deliberate: for ASCII it is the character count the
threshold was calibrated on, and for multi-byte scripts it is more
permissive, which is right because a four-character CJK title is
specific in a way that "Bitcoin" is not.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
…ider ID mixing

Follow-ups to the match gate, each closing a hole the first pass left.

Numeral folding. Providers and rippers disagree freely on form:
"Slaughterhouse 5" against "Slaughterhouse-Five" scored exactly at the
threshold and matched only by luck, and a "Part II" volume never agreed
with "Part 2" -- which the volume rule then read as a disagreement and
rejected outright. Spelled and Roman numerals now fold to digits before
scoring, capped at 30 so single letters like "X" and "I" stay letters
("Malcolm X" must not become "Malcolm 10").

Year as a tiebreak, never a gate. For books a year gap is weak evidence:
an audiobook edition of a 1994 novel is routinely dated by its recording
decades later, so rejecting on it would discard correct matches
wholesale. It only decides between candidates already tied on title.

Cross-provider agreement. Each provider was scored independently and
every accepted match was merged into one ID map, so two providers could
each clear the bar while naming different books and leave the item
holding IDs for two works -- worse than either answer alone, because
afterwards the wrong ID is indistinguishable from the right one. The
first accepted title is now the reference and later providers must agree
with it.

Ownership guard for audiobooks and manga. FindContentIDByProviderIDs
appeared three times in the ebook enricher and nowhere in the other two,
so sibling volumes resolving to one provider work all claimed the same
ID with nothing noticing -- the exact collapse the ebook code guards
against, and manga is the most exposed, with series running to dozens of
near-identical titles. Ported including the "don't claim an ID we
couldn't verify is free" path that retries rather than stamping
terminally.

Rejections now log at Info. During a backlog drain the rejection rate is
what separates "threshold too strict" from "providers answering badly",
and that cannot be read from a log level nobody enables.

The threshold is overridable via SILO_METADATA_MATCH_MIN_SCORE so it can
be retuned against a live library without a rebuild; out-of-range values
are ignored rather than obeyed, since a typo'd 0 would accept everything.

Acceptance is now strictly above the threshold rather than at it: a
two-word title sharing one word with a two-word candidate scores exactly
0.5, which is the weakest possible evidence, not a match. Nothing correct
is lost -- the worst true match in the calibration sample scores 0.86.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
Title scoring cannot separate two different books that share a title,
and for books that is not a rare edge -- generic titles recur constantly
across authors, so the gate would accept the wrong one on nothing more
than a title agreement.

The obvious fix is unavailable: the plugin contract's SearchResult
carries title, year, overview, image and provider IDs, and no author at
all. Checking it at search time would mean changing the SDK proto and
every plugin implementing it.

It is available one step later. Enrichment already calls GetMetadata on
the accepted match, and MetadataResult.People carries the credits, so
the author is verified after the fetch: a positive contradiction is
recorded as a no-match rather than written. Wired into all three
enrichers.

Absence is never disagreement. An item with no author, or a provider
returning no credits, passes -- most of this library is missing one or
the other, and treating that as a conflict would reject far more good
matches than bad ones. Only a name that actively contradicts rejects.

Name comparison allows for how the same person gets credited: surname
plus first initial (which survives middle names and
initials-vs-full-first-name), the "King, Stephen" reversal, and one form
contained in another ("Iain Banks" within "Iain M. Banks"). Non-author
credits are ignored, so a narrator neither confirms nor contradicts
authorship.

Diacritics ARE folded for names and deliberately are NOT for titles.
Providers transliterate people inconsistently -- "Émile Zola" and "Emile
Zola" are one person, and without folding they disagreed on their first
initial and the match was rejected. Titles are different: "Blåbær" and
"Blabaer" are not reliably the same work, and folding there would erase
a real distinction.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
Audiobook enrichment recorded its outcome in exactly one place:
media_items.last_refreshed. That stamp had to mean "matched",
"genuinely unmatchable" and "the provider was down that minute" all at
once, so a bad afternoon on a provider burned the item exactly as
terminally as a real no-match, with no attempt count, no error class and
no backoff. Ebooks have ebook_enrichment_state and manga has
manga_enrichment_state; audiobooks had nothing.

The new table sits deliberately between those two. It is not the full
ebook lease queue: audiobook sweeps run from a single task-manager
goroutine and claimBatch takes no row locks, so claim_token/lease_until
would be machinery with nothing to coordinate. It is more than the manga
table, which counts failures and nothing else.

last_refreshed stays authoritative for eligibility, so the migration
changes no behaviour by itself. What changes is that the sweep now skips
items parked for a later retry, and records why each item is where it
is.

Failures are classified, because the distinction is the one the ebook
backlog lost: 90,721 rows there carry outcome='no_match' with attempts=0
and an empty error class, which is why a rate-limited sweep on
2026-07-20 is indistinguishable from 90,721 genuine misses. Here a
failure records a class and parks a retry WITHOUT setting an outcome --
it has not reached a terminal state. Rate limiting backs off hardest
(retrying into a closed window is what turns a throttle into a backlog)
and permanent failures park far out rather than never, since "permanent"
is a classification and classifications are sometimes wrong.

attempts always increments, including on terminal rows, so "never tried"
and "tried and gave up" stay distinguishable.

Bookkeeping never fails the enrichment it describes: a state write error
is logged and swallowed, since last_refreshed remains the authoritative
signal and losing a state row costs reporting detail, not correctness.

Seven DB-backed tests, run against a migrated throwaway Postgres rather
than assumed: the two covering the parked-retry predicate fail with the
predicate removed and pass with it, so they guard something real.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
All four verified by reproduction before fixing; none were false
positives.

NFC-normalise before tokenising. A decomposed accent (e + U+0301) is a
combining mark to the punctuation strip and vanished, while the composed
spelling kept its letter, so two byte-level spellings of "Café" scored 0
against each other and an identical title was rejected.

A wrong-volume primary can no longer be rescued by its alias. Aliases
are often the bare series name; "Dungeon In My Closet, Book 5" was
accepted for a volume-2 item through its generic "Dungeon In My Closet"
alias, persisting IDs for the wrong book. A volume stated on the primary
title that contradicts the item's now disqualifies the whole result.

The ebook series-noise test requires volume syntax, not a marker word.
Bare "book" matched anywhere, so "(The Book Thief)" -- a title, not
furniture -- was stripped from the query. The parenthetical is now only
dropped for "Book 4" / "Silo-Server#3" / bare-number / bare-year shapes.

The scheduler-mirror test asserts its own fixture was claimed rather
than that the claimed set is non-empty, which unrelated rows in a shared
test database could satisfy.

Also consolidates the two identical providerIDOwnerLookup interfaces
(ebooks, manga) onto metadata.ProviderIDOwnerLookup per the repo rule
against duplicated contracts.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
Two review findings on the state store, both real.

RecordFailure was two round trips: an upsert incrementing attempts, then
an update parking next_attempt_at. Anything landing between them -- a
cancelled context, a dropped connection, a concurrent RecordOutcome on
the same row -- left the item with an incremented attempts count but no
backoff at all, immediately re-claimable against the very provider that
just failed; or let a terminal outcome be resurrected as a parked retry.
Now a single upsert computes min(step * attempts, cap) on the
post-increment attempts value inside the statement, so there is no
partial-write window rather than a transaction hiding one. retryAfterFor
remains as the Go mirror of the same math, built on shared
backoffParams so the two cannot drift.

The cause truncation cut at a byte index, which can split a multi-byte
rune; Postgres rejects invalid UTF-8, which would have silently failed
the entire failure/backoff write for that call -- the exact no-backoff
state the atomicity fix removes. Truncation now passes through
strings.ToValidUTF8, with a DB-backed regression test whose 500-byte
boundary lands mid-rune.

Also reverts four pre-existing files (abs/, podcastfeed/) that an
overly broad gofmt -w swept into the branch; they are not part of this
change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
Complete() zeroed attempts on every outcome, so a row bulk-stamped
no_match without a lookup was indistinguishable from one that failed
five real attempts, and every no_match returned on the same flat 30-day
horizon forever — permanently unmatchable titles (cover-scan artifacts,
bare file numbers) consumed the same daily recycler quota as books that
were never actually tried.

- failures now counts consecutive no_match completions (success resets)
- the no_match horizon doubles per prior failure, capped at 8x:
  30d, 60d, 120d, 240d
- retail edition suffixes are stripped from search queries — anything
  ending in Edition(s)/Classics, Kindle Single, A Novel — the same
  reasoning as the series-marker rule: providers index the work, not
  the storefront packaging. (Illustrated)/(Annotated) still survive.

Co-Authored-By: Claude Fable 5 <[email protected]>
Upstream Silo-Server#501 added GetOnboardingState/UpsertOnboardingState to
userstore.UserStore without extending this stub, so the access package
no longer compiles under test on main.

Co-Authored-By: Claude Fable 5 <[email protected]>
Same upstream gap as the access resolver stub: Silo-Server#501 extended
userstore.UserStore without updating these test doubles.

Co-Authored-By: Claude Fable 5 <[email protected]>
enrichClaimedItem returned EnrichmentOutcomeSuccess for items whose
embedded metadata already satisfied every field enrichment would fetch,
without ever running the status promotion. That was the only terminal
outcome to skip it: no_match, author-mismatch, and provider success all
reach stampLastRefreshed, the sole writer of status 'pending' -> 'matched'.

Those items therefore kept media_items.status = 'pending' permanently and
were counted by the library "unmatched" tile. On prod this is 43,653 of
the 44,014 reported unmatched items (99.2%) — every one of them with
outcome='success', last_refreshed IS NULL, matched_at IS NULL, and title,
author, overview and cover all populated. Rescanning cannot clear them,
because the short-circuit fires again and the queue re-parks the row.

last_refreshed is deliberately left untouched: it gates the admin
quick-refresh sweep, and no provider was consulted here, so these items
must stay eligible for a later refresh that could attach a provider
identity.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
.claude carries gitignored worktrees and caches that reached 2.8GB locally,
and .superpowers is similar. Neither is needed to build the image, but
.dockerignore did not exclude them, so both were shipped to the daemon as
build context (and rsync'd to deploy hosts).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Quick104
Quick104 force-pushed the fix/ebook-pending-status-promotion branch from a59fef7 to 19cdab2 Compare August 20, 2026 17:20
@Quick104
Quick104 merged commit d0b6503 into Silo-Server:main Aug 20, 2026
4 checks passed
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.

2 participants