Skip to content

fix(metadata): require a credible match before accepting provider metadata, and let audiobook enrichment run at all - #496

Closed
RXWatcher wants to merge 11 commits into
Silo-Server:mainfrom
RXWatcher:fix/audiobook-enrichment-identity-gate
Closed

RXWatcher wants to merge 11 commits into
Silo-Server:mainfrom
RXWatcher:fix/audiobook-enrichment-identity-gate

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Part of #510

Independent review remediation (2026-07-28)

The Standards and Spec reviews were rerun independently against the pinned PR diff. The remediation:

  • compares Unicode author initials by rune and rejects non-finite match thresholds;
  • treats complete volume ranges as identity, including range-end mismatches;
  • centralizes title agreement and durable provider-ID admission across audiobook, ebook, and manga;
  • revalidates metadata-response cross-IDs so an ownership conflict rejected during search cannot be reintroduced during merge;
  • validates each provider author before merging any fields;
  • shares typed gRPC/native provider-error classification, including joined failures;
  • commits audiobook provider IDs, metadata, search-index event, and terminal timestamp in one transaction;
  • gives manga transient and rate-limited failures durable backoff without applying the permanent-failure cap;
  • propagates provider-ID persistence conflicts instead of stamping terminal metadata.

Fresh verification

go test ./internal/metadata ./internal/audiobooks ./internal/ebooks ./internal/manga ./internal/catalog
PASS

go test -race ./internal/metadata ./internal/audiobooks ./internal/ebooks ./internal/manga ./internal/catalog
PASS

go vet ./internal/metadata ./internal/audiobooks ./internal/ebooks ./internal/manga ./internal/catalog
PASS

make migrate-validate
PASS

make verify-local-paths
PASS

DB-backed audiobook tests remain conditional on SILO_TEST_DATABASE_URL, which is not configured in this worktree. A repository-wide go test ./... also reaches all changed packages successfully but is not globally clean: web/dist is absent for the embed packages, and unrelated existing tests fail in internal/api/handlers and internal/jellycompat. golangci-lint is not installed locally; the original body records the known repo-wide lint baseline.

AI Disclosure — review remediation

  • Tool(s): Claude Code; T3 Code (Codex harness)
  • Model(s): claude-opus-5; gpt-5.6-sol
  • Involvement: original implementation and Codex review remediation fully AI-generated, reviewed by the operator
  • Adversarial review: independent Standards and Spec agents found process disclosure/dead-surface issues plus metadata-ID reintroduction, non-atomic audiobook persistence, and missing manga retry classification. All were fixed and the amended diff was sent through both axes again.

Problem

Book enrichment writes wrong metadata, and for audiobooks it never ran at all.

1. Any provider answer was accepted. internal/audiobooks, internal/ebooks
and internal/manga each took results[0] from every search provider with no
scoring of any kind. Search backends rank by their own relevance and answer
nearly every query with something, so a provider's best guess became the
item's identity. Enrichment stamps last_refreshed on success and never
revisits, so each wrong acceptance is a permanent mislabel — another book's
cover, overview and narrator.

Measured against production: 20 unidentified audiobooks queried through the
iTunes audiobook search returned 19 answers, and roughly a quarter of those top
hits were wrong. Two failure shapes dominate:

Library title Provider's top hit
The OP MC 8: God of Winning God of Winning: The OP MC, Book 1 — wrong volume
Legend of Randidly Ghosthound 1 The Legend of Randidly Ghosthound 8 — wrong volume
Star Force Origins - 002-Integration The Achilles Trap: Saddam Hussein… — unrelated
Looking for a Miracle Lucky You: A Novel — unrelated

2. Audiobook enrichment was permanently idle. claimBatch /
HasPendingItems defined "needs enrichment" as poster_path IS NULL OR ''. The
scanner extracts embedded cover art from audiobook files, so every item had a
poster before enrichment ever looked at it. In production this selected 0
rows
while 5,712 audiobooks had no provider ID at all — 5,710 of them
holding a scanner-supplied poster. The metadata providers had enriched 42
items in total
; the 235,780 ASINs in that library came from file scan, not
from a provider.

3. Ebook queries carried text no catalogue indexes. cleanEbookSearchTitle
unwrapped a trailing series marker — brackets removed, words kept — so
Icarus (Realm Book 3) went out as Icarus Realm Book 3.

Why this approach

The three are one problem seen from different sides, which is why they are one
PR: the ebook change depends on the match gate, and the audiobook
eligibility fix is what gives the gate anything to score.

The ebook unwrapping had a real justification, recorded in the code: 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 provider
work. That reasoning held only while acceptance was blind results[0]. With a
gate that scores candidates against the raw item.Title — which still carries
(Realm Book 3) — and treats a volume disagreement as fatal, the disambiguator
no longer has to be in the query. It never needed to be in the query; it
needed to be in the check.

metadata.BestMatch scores by word-set overlap (Dice) rather than edit
distance, because the differences that matter are whole words added or dropped:
an author prefix, a series parenthetical, an (Unabridged) suffix. A volume
disagreement returns 0 regardless of overlap, since wrong-volume pairs of the
right series share nearly every word. Stopwords are excluded — two unrelated
"Books 1-3" boxed sets otherwise scored 0.56 on the ×3 plus
complete/trilogy/1/3.

Callers treat "nothing credible" as a no-match, the same terminal-but-honest
outcome as an empty result set, rather than falling back to the top row.

Evidence

Calibration, from the real probe pairs kept as fixtures: correct matches score
≥ 0.86, wrong ones ≤ 0.42
, against a 0.50 threshold. A test asserts the two
populations stay separated, so a change that narrows the gap fails there instead
of in production.

End-to-end on 40 parked no_match ebooks carrying a series parenthetical, with
both query forms produced by cleanEbookSearchTitle itself and both result sets
scored by the real gate:

Query form Open Library answered Gate accepted
current main 3 0
this branch 29 14

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

Scope note so the number is not over-read: 23,802 of 110,556 parked no_match
ebooks (21.5%) carry that title shape. This reaches about a fifth of that
backlog; the rest fail for reasons this does not touch.

Verify commands

$ make verify-local-paths
scripts/check-local-path-leaks.sh
EXIT=0

$ go test ./internal/metadata/ ./internal/audiobooks/ ./internal/ebooks/ ./internal/manga/
ok  	github.com/Silo-Server/silo-server/internal/metadata	0.492s
ok  	github.com/Silo-Server/silo-server/internal/audiobooks	0.714s
ok  	github.com/Silo-Server/silo-server/internal/ebooks	0.388s
ok  	github.com/Silo-Server/silo-server/internal/manga	1.008s

$ cd web && pnpm run format:check
Checking formatting...
All matched files use Prettier code style!

$ cd web && pnpm run lint
✖ 158 problems (0 errors, 158 warnings)      # pre-existing, all in web/vendor/

make lint fails on this branch and on main alike — 305 issues repo-wide.
None are in the files this PR touches. The three that name a touched file sit
outside every changed hunk (my hunks are ebooks 964-977 / 1365-1398, manga
516-529; the findings are at ebooks 445, ebooks 1152, manga 654 — pre-existing
lines that my insertions merely shifted):

internal/ebooks/enrichment.go:1152:67: inline: Constant reflect.Ptr should be inlined (govet)
internal/manga/enrichment.go:654:67:  inline: Constant reflect.Ptr should be inlined (govet)
internal/ebooks/enrichment.go:445:5:  QF1003: could use tagged switch on outcome (staticcheck)

internal/audiobooks/enrichment_claim_db_test.go is DB-backed and skips unless
SILO_TEST_DATABASE_URL is set. It was run for real against a migrated
throwaway Postgres, and both new tests fail against the old predicate and
pass against the new one — a test that has never failed proves nothing.

Since the body above was first written

The branch has grown from five commits to nine; the problem statement above is
unchanged, the additions harden the same gate:

  • Unicode-aware normalisation (fa92497d) — the first cut was ASCII-only
    and scored an identical Japanese title 0 against itself; found by the
    adversarial self-review below.
  • Numeral folding, year tiebreak, cross-provider agreement, ownership guard
    for audiobooks/manga, Info-level rejection logging, env-overridable
    threshold
    (2690b7f0).
  • Post-fetch author verification (56f1c578) — the plugin search contract
    carries no author, so same-title-different-author is caught against
    MetadataResult.People after GetMetadata; absence never counts as
    disagreement.
  • audiobook_enrichment_state (c9dc35dd) — goose migration + store.
    Audiobooks had no attempt count, error class or backoff at all; failures now
    park classified retries instead of burning the item, sitting deliberately
    between the manga failure counter and the full ebook lease queue.
  • Review fixes (63160932) — all four CodeRabbit correctness findings
    reproduced and fixed: NFC normalisation, alias-rescue of wrong-volume
    primaries, the (The Book Thief) series-regex false positive, and the
    fixture assertion; plus the duplicated ownership interface consolidated onto
    metadata.ProviderIDOwnerLookup.

Production evidence

This branch is running on a live deployment as of 2026-07-27, together with the
audnexus route fix in silo-plugin-metadata-audiobook#8. First hours of the
previously-idle audiobook sweep, on a library where 5,682 audiobooks had no
provider identity:

signal last 30 min observed
enriched (poster+overview+credits) 206
clean no-match 282
gate rejections (wrong book refused) 67
author-mismatch rejections 10
ownership skips (sibling volumes) 100

~42% recovery on items that were terminally unmatchable before, with the wrong
answers refused rather than stamped. One operational note worth a reviewer's
attention: deploying this server branch without the plugin route fix ran the
sweep into providers that could not answer, and clean empty results burned each
item's single attempt (bounded by the batch size; repaired by clearing
last_refreshed on the affected rows). The gate distinguishes provider errors
from clean no-matches, but it cannot know that a source which answers "nothing"
is broken rather than empty — sequencing the two PRs together avoids the
window.

Risks and follow-ups

  • Acceptance volume drops by design. On the audiobook sample the gate took
    19 accepts down to 12; all seven rejections were genuine mismatches. Raw
    success rate falling slightly after this lands is the fix working, not
    failing. Worth watching rather than alerting on.
  • The threshold is calibrated on English-language samples (20 audiobooks,
    40 ebooks). 0.50 sits in a wide gap, but it is one library's data.
  • minContainmentLen is byte-measured, documented as deliberate: for ASCII
    it is the character count it was calibrated on, and it is more permissive for
    multi-byte scripts, which is the wanted behaviour.
  • CJK matching is coarse. Scripts that do not space their words normalise to
    a single token, so Dice is 1 on an exact match and 0 otherwise, with
    containment carrying near-misses.
  • Not included, found while investigating: the first-party audiobook plugin
    queries audnexus at /books?q=, which is not a route (/books/search is), so
    its preferred source contributes nothing to ASIN-less items. Fixed separately
    in the plugin repo.
  • Scope tracking: Part of Harden book metadata identity matching and audiobook enrichment eligibility #510.

AI Disclosure

  • Tool(s): Claude Code

  • Model(s): claude-opus-5

  • Involvement: fully AI-generated (code, tests and measurements), reviewed by
    the operator

  • Adversarial review: a self-review of this diff found four defects, all
    fixed here rather than left for review:

    1. ASCII-only normalisation. [^a-z0-9] reduced every non-Latin title to
      the empty string, so 進撃の巨人 scored 0.00 against itself and was
      rejected, and Blåbærsyltetøy became bl b rsyltet y. A hard regression
      for non-English content, and a quiet one, since those items previously
      matched by accident when nothing was checked. Now strips [^\p{L}\p{N}]+,
      with tests for Japanese, Russian and Danish.
    2. Containment guard inverted. The length floor used ||, so a long
      candidate
      satisfied it and short queries still matched anything containing
      them. Now requires the shorter side to clear the floor.
    3. Stopword-inflated false accept, caught by scoring the full 20-title
      probe rather than only the hand-picked pairs: two unrelated boxed sets
      scored 0.56. Stopword exclusion takes them to 0.42.
    4. A fixture passing for the wrong reason. Three ebook tests supplied a
      SearchResult with no name, which the gate rejects;
      SkipsProviderIDOwnedByAnotherItem would have kept passing while never
      reaching the ownership check it exists to cover.

    Also corrected mid-work: an earlier measurement of "0% baseline" for the
    series-parenthetical lane was Open Library only — production also queries
    Hardcover and Google Books, and the true baseline is 12.3%. The figures above
    are stated per-source for that reason.

Summary by CodeRabbit

  • New Features
    • Durable audiobook enrichment state with scheduled retries and backoff.
    • Higher-confidence matching for audiobook, ebook, and manga metadata using normalized title matching, author consistency checks, and provider-identity admission.
  • Bug Fixes
    • Enrichment now gates work on credible title/author matches and avoids incorrect provider ID ownership merges.
    • Retry eligibility respects parked/failure schedules; author mismatches stop before persistence.
    • Provider errors are classified for consistent retry behavior.
  • Tests
    • Added DB and unit coverage for transactional rollback and the new matching/admission logic.

RXWatcher and others added 5 commits July 27, 2026 18:36
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
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Audiobook enrichment now persists outcomes and retry state, uses durable provider identities for eligibility, validates title and author agreement, and atomically persists metadata. Ebook and manga enrichment share provider admission, author validation, error classification, and retry scheduling improvements.

Changes

Enrichment matching and state

Layer / File(s) Summary
Title confidence, author validation, and provider admission
internal/metadata/*
Adds volume-aware title scoring, alias and year selection, normalized author checks, durable provider-ID ownership admission, and provider error classification.
Audiobook eligibility, state, and persistence
internal/audiobooks/enrichment.go, internal/audiobooks/enrichment_state.go, internal/catalog/item_repo.go, migrations/sql/...
Replaces cover-art eligibility with durable identity checks, records outcomes and classified retries, and commits provider IDs with scalar metadata transactionally.
Ebook and manga enrichment integration
internal/ebooks/enrichment.go, internal/manga/enrichment.go, internal/ebooks/enrichment_test.go, internal/manga/enrichment_test.go
Applies title agreement, author gates, ownership filtering, retry backoff, and provider-ID persistence error propagation; ebook title cleanup now removes concrete series-volume markers.
Validation and supporting tests
internal/audiobooks/*_test.go, internal/metadata/*_test.go, internal/audiobooks/smartcoll/*
Adds unit and database-backed coverage for matching, ownership, retry state, rollback, error classification, and title cleanup; smart-collection changes are formatting-only.

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

Possibly related issues

Possibly related PRs

Suggested labels: v1

Suggested reviewers: quick104

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.92% 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 Title clearly summarizes the main change: stricter metadata matching plus audiobook enrichment eligibility.
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 27, 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: 4

🤖 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/audiobooks/enrichment_claim_db_test.go`:
- Around line 132-145: The test should retain the content ID returned by seeding
the “mirror” audiobook and verify that this specific ID appears in the set from
claimedIDs, rather than only checking that the set is non-empty. Update the
fixture setup and assertion in the HasPendingItems test while preserving the
existing pending-work checks.

In `@internal/ebooks/enrichment.go`:
- Around line 1396-1398: Update the parenthetical-stripping logic around
ebookSeriesNoiseRE so it only removes suffixes containing an explicit volume
marker, such as “Book 4” or “#3”, rather than any occurrence of “book”; preserve
meaningful titles like “The Book Thief”. Narrow or replace the regex accordingly
and add a regression test covering the preserved title and valid volume
suffixes.

In `@internal/metadata/match_confidence.go`:
- Around line 221-227: Update the title-matching logic around r.TitleAliases and
TitleScore so a primary-title volume conflict remains a rejection even when a
volume-less alias scores above the threshold; aliases must not bypass explicit
mismatched-volume validation. Add a regression case covering a primary title
with the wrong volume and a generic volume-less alias, verifying the result is
not accepted or persisted.
- Around line 76-80: Update normaliseTitle to apply Unicode compatibility
decomposition and canonical composition before nonAlnumRE tokenization, ensuring
composed and decomposed accented spellings produce identical normalized titles.
Add a regression test comparing a decomposed example such as Cafe\u0301 with its
composed equivalent Café.
🪄 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: c01bb96c-25b3-4224-be16-d7481bad762a

📥 Commits

Reviewing files that changed from the base of the PR and between f235524 and fa92497.

📒 Files selected for processing (7)
  • internal/audiobooks/enrichment.go
  • internal/audiobooks/enrichment_claim_db_test.go
  • internal/ebooks/enrichment.go
  • internal/ebooks/enrichment_test.go
  • internal/manga/enrichment.go
  • internal/metadata/match_confidence.go
  • internal/metadata/match_confidence_test.go

Comment thread internal/ebooks/enrichment.go Resolved
Comment thread internal/metadata/match_confidence.go Resolved
Comment thread internal/metadata/match_confidence.go Resolved
RXWatcher and others added 3 commits July 27, 2026 20:06
…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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (3)
internal/metadata/match_confidence.go (2)

118-123: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Composed vs. decomposed Unicode spellings still score differently.

normaliseTitle still has no NFC/NFD canonicalization step before tokenization, so a decomposed accented title (e.g. Cafe\u0301) and its composed equivalent (Café) normalize to different strings and score 0 against each other. This is the same gap flagged on a previous commit and remains unresolved here.

🐛 Proposed fix
+	"golang.org/x/text/unicode/norm"
 )

 func normaliseTitle(s string) string {
-	s = strings.ToLower(strings.TrimSpace(s))
+	s = strings.ToLower(strings.TrimSpace(norm.NFC.String(s)))
 	s = editionNoiseRE.ReplaceAllString(s, " ")
 	s = nonAlnumRE.ReplaceAllString(s, " ")
 	return foldNumberWords(strings.Join(strings.Fields(s), " "))
 }

Note: unlike author_match.go's foldDiacritics, this should use NFC only (not strip combining marks), since titles deliberately keep diacritics as meaningful — only the encoding form needs to be canonicalized. Add a regression test comparing a decomposed vs. composed spelling of the same title.

🤖 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/metadata/match_confidence.go` around lines 118 - 123, Update
normaliseTitle to apply NFC Unicode normalization before lowercasing, noise
replacement, and tokenization, preserving diacritics while canonicalizing
composed and decomposed spellings to the same form. Add a regression test that
compares decomposed “Café” with composed “Café” and verifies they normalize or
score identically.

129-164: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Numeral folding creates phantom volume numbers for ordinary title vocabulary.

titleVolume's bare-number fallback (Line 152-162) now scans folded, which has already run through foldNumberWords. Any title where a spelled-out number is just an ordinary word — "One Piece", "Twenty Thousand Leagues Under the Sea", "The Magnificent Seven" — gets misread as carrying a volume marker: normaliseTitle("One Piece") → "one piece" → folded to "1 piece", and the bare-number loop returns (1, true).

Once titleVolume(want) wrongly reports a volume, TitleScore's hard volume-disagreement rejection kicks in against every differently-numbered real candidate — so "One Piece" would score 0 against "One Piece, Vol. 5", "One Piece, Vol. 12", etc. This is precisely the manga domain this PR calls out as most exposed to volume confusion.

The marker-based check (volumeMarkerRE, requiring an adjacent "book/vol/part/..." keyword) is a safe place to use folded text, since the keyword itself is the real signal. The bare-number fallback has no such guard and should scan the unfolded normalized text so only literal digits already present trigger it.

🐛 Proposed fix
+// normaliseTitleBase applies normalisation without numeral folding, for
+// callers that need to distinguish a genuine digit from a spelled-out word.
+func normaliseTitleBase(s string) string {
+	s = strings.ToLower(strings.TrimSpace(s))
+	s = editionNoiseRE.ReplaceAllString(s, " ")
+	s = nonAlnumRE.ReplaceAllString(s, " ")
+	return strings.Join(strings.Fields(s), " ")
+}
+
 func normaliseTitle(s string) string {
-	s = strings.ToLower(strings.TrimSpace(s))
-	s = editionNoiseRE.ReplaceAllString(s, " ")
-	s = nonAlnumRE.ReplaceAllString(s, " ")
-	return foldNumberWords(strings.Join(strings.Fields(s), " "))
+	return foldNumberWords(normaliseTitleBase(s))
 }
 	// A bare number standing as its own word, e.g. "Op-Center 4 - Acts of War"
-	// or "Dungeon In My Closet 2". Years are excluded: they date an edition
-	// rather than number a volume.
-	fields := strings.Fields(folded)
+	// or "Dungeon In My Closet 2". Deliberately scans the *unfolded* text:
+	// once numeral words are folded, ordinary vocabulary like "One" in "One
+	// Piece" becomes a bare digit and would be misread as a volume. Years are
+	// excluded: they date an edition rather than number a volume.
+	fields := strings.Fields(normaliseTitleBase(s))
 	for _, f := range fields {

Add a regression test, e.g. titleVolume("One Piece") must return ok=false, and BestMatch("One Piece", []SearchResult{{Name: "One Piece, Vol. 5"}}) must succeed.

🤖 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/metadata/match_confidence.go` around lines 129 - 164, Update the
bare-number fallback in titleVolume to scan the unfolded normalized title rather
than folded, while keeping volumeMarkerRE matching on folded text so explicit
volume markers still support spelled and Roman numerals. Add regression coverage
confirming titleVolume("One Piece") reports no volume and BestMatch accepts "One
Piece, Vol. 5" for that query.
internal/ebooks/enrichment.go (1)

1389-1389: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

ebookSeriesNoiseRE still strips meaningful "book" titles from the search query.

The regex (\b(book|bk|vol|...)\b) matches "book" as a bare word, so (The Book Thief)-style parenthetical suffixes are still discarded when building the search query, even though the surrounding peel-and-continue logic changed. This is the same regex flagged in a previous review; it wasn't tightened to require an actual volume marker (e.g. "Book 4", "#3").

Since matching now validates against the full item.Title post-search (via BestMatchYear), this no longer risks accepting a wrong match, but it still degrades search recall/precision for titles that legitimately contain "book" as prose.

Also applies to: 1407-1440

🤖 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` at line 1389, Update ebookSeriesNoiseRE to
stop treating bare “book” as series noise; require “book” to be part of an
actual volume marker such as “Book 4”, while preserving existing handling for
other valid markers like “#3”. Keep the surrounding enrichment and BestMatchYear
validation logic unchanged.
♻️ Duplicate comments (1)
internal/metadata/match_confidence.go (1)

285-325: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Volume-less aliases can still bypass a primary-title volume conflict.

BestMatchYear scores name (primary title) and then separately scores every r.TitleAliases entry, taking whichever is higher. If the primary title's volume disagrees with want (TitleScore returns 0 via the volume-conflict check), a generic alias with no identifiable volume is not blocked from scoring on its own merits and can push the candidate above threshold — persisting IDs for the wrong volume. This mirrors a previously flagged concern that appears not to have been carried through in this revision.

🐛 Proposed fix
 	for _, r := range results {
 		name := r.Name
 		if strings.TrimSpace(name) == "" {
 			name = r.OriginalTitle
 		}
+		if wv, wok := titleVolume(want); wok {
+			if cv, cok := titleVolume(name); cok && wv != cv {
+				continue
+			}
+		}
 		score := TitleScore(want, name)

Add a regression case: primary title with a mismatched volume plus a volume-less generic alias, asserting the result is rejected.

🤖 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/metadata/match_confidence.go` around lines 285 - 325, Update
BestMatchYear so a primary-title volume conflict cannot be bypassed by scoring a
volume-less alias independently: when TitleScore(want, name) returns zero
because of that conflict, reject or otherwise block alias-derived scoring for
the candidate. Add a regression test covering a mismatched-volume primary title
with a generic alias lacking a volume, and assert BestMatchYear rejects it.
🧹 Nitpick comments (1)
internal/metadata/author_match.go (1)

65-114: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Comma-reordered names with a middle name aren't matched.

The surname-plus-initial and reversal checks assume the surname is always the last token. For "Lastname, Firstname Middlename" (comma stripped, order preserved as [surname, given, middle]), the algorithm reads the middle name as the surname, so it won't match the corresponding "Firstname Middlename Lastname" credit via any of the three branches. The two-token reversal case ("King, Stephen" vs "Stephen King") is handled, but the docstring's broader claim of handling "comma-reordered names" doesn't hold once a middle name is involved — a common combination given item.Author typically comes from library/tag metadata using this exact convention.

Consider detecting the comma in normalisePersonName before stripping it (or passing the original string) so a "Lastname, Firstname ..." input can be explicitly reordered to surname-last before the rest of the comparison runs.

🤖 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/metadata/author_match.go` around lines 65 - 114, Update the
name-normalization flow used by personNamesMatch to preserve whether the
original input contained a comma and reorder comma-formatted “surname, given
names” into surname-last order before token comparison. Ensure this handles
middle names such as “Lastname, Firstname Middlename” while preserving existing
matching behavior for ordinary and two-token reordered names; use the existing
normalisePersonName path or its original input as the integration point.
🤖 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/manga/enrichment.go`:
- Around line 1087-1112: Extract the duplicated provider-ID lookup contract from
internal/manga and the existing internal/ebooks definition into a shared package
appropriate for catalog/content-ID ownership. Update internal/ebooks,
internal/manga, and internal/audiobooks to reference the shared
providerIDOwnerLookup contract, remove the local duplicate declarations, and
preserve the existing method signature and behavior.

---

Outside diff comments:
In `@internal/ebooks/enrichment.go`:
- Line 1389: Update ebookSeriesNoiseRE to stop treating bare “book” as series
noise; require “book” to be part of an actual volume marker such as “Book 4”,
while preserving existing handling for other valid markers like “#3”. Keep the
surrounding enrichment and BestMatchYear validation logic unchanged.

In `@internal/metadata/match_confidence.go`:
- Around line 118-123: Update normaliseTitle to apply NFC Unicode normalization
before lowercasing, noise replacement, and tokenization, preserving diacritics
while canonicalizing composed and decomposed spellings to the same form. Add a
regression test that compares decomposed “Café” with composed “Café” and
verifies they normalize or score identically.
- Around line 129-164: Update the bare-number fallback in titleVolume to scan
the unfolded normalized title rather than folded, while keeping volumeMarkerRE
matching on folded text so explicit volume markers still support spelled and
Roman numerals. Add regression coverage confirming titleVolume("One Piece")
reports no volume and BestMatch accepts "One Piece, Vol. 5" for that query.

---

Duplicate comments:
In `@internal/metadata/match_confidence.go`:
- Around line 285-325: Update BestMatchYear so a primary-title volume conflict
cannot be bypassed by scoring a volume-less alias independently: when
TitleScore(want, name) returns zero because of that conflict, reject or
otherwise block alias-derived scoring for the candidate. Add a regression test
covering a mismatched-volume primary title with a generic alias lacking a
volume, and assert BestMatchYear rejects it.

---

Nitpick comments:
In `@internal/metadata/author_match.go`:
- Around line 65-114: Update the name-normalization flow used by
personNamesMatch to preserve whether the original input contained a comma and
reorder comma-formatted “surname, given names” into surname-last order before
token comparison. Ensure this handles middle names such as “Lastname, Firstname
Middlename” while preserving existing matching behavior for ordinary and
two-token reordered names; use the existing normalisePersonName path or its
original input as the integration point.
🪄 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: 41497ac0-9cff-4747-b7eb-54545c6513a2

📥 Commits

Reviewing files that changed from the base of the PR and between fa92497 and 56f1c57.

📒 Files selected for processing (7)
  • internal/audiobooks/enrichment.go
  • internal/ebooks/enrichment.go
  • internal/manga/enrichment.go
  • internal/metadata/author_match.go
  • internal/metadata/author_match_test.go
  • internal/metadata/match_confidence.go
  • internal/metadata/match_confidence_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/audiobooks/enrichment.go

Comment thread internal/manga/enrichment.go Resolved
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

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

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)

327-381: 🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

claimBatch's "load durable provider IDs" step is now dead code.

The claim query's NOT EXISTS (... FROM media_item_provider_ids ...) predicate (327-331) guarantees every returned row has zero provider-ID rows. The follow-up loop at 373-381 that calls e.providerIDs.GetByContentID per item can therefore never populate anything — it's a guaranteed-empty N+1 query on every sweep now that eligibility itself requires provider-identity absence.

Consider removing the now-unreachable seeding loop (and the comment describing it) so the intent of the eligibility rewrite isn't undercut by leftover code implying otherwise.

♻️ Proposed removal
-	// Load any durable provider IDs for each item.
-	if e.providerIDs != nil {
-		for i := range items {
-			pids, err := e.providerIDs.GetByContentID(ctx, items[i].ContentID)
-			if err == nil {
-				items[i].ProviderIDs = providerIDMapFromRows(pids)
-			}
-		}
-	}
-
 	return items, 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/audiobooks/enrichment.go` around lines 327 - 381, Remove the “Load
any durable provider IDs” comment and the following e.providerIDs.GetByContentID
loop from claimBatch, since its query eligibility condition already excludes
items with provider IDs. Leave item scanning, deduplication, and rows.Err
handling unchanged.
🧹 Nitpick comments (1)
internal/audiobooks/enrichment.go (1)

219-231: 🗄️ Data Integrity & Integration | 🔵 Trivial

Metadata-matching behavior change may need client-side coordination.

Switching claim/pending eligibility from "no poster" to "no durable provider identity" changes which items get (re)enriched and can change their apparent match status client-side (e.g. items previously treated as done because a scanner-supplied cover existed). Worth confirming client apps handle the resulting state transitions gracefully.

As per coding guidelines: "Client-visible changes to API, authentication, playback, sessions, library, or metadata behavior generally require coordinated follow-up in both client repositories rather than leaving a platform behind."

Also applies to: 327-339

🤖 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 219 - 231, Coordinate this
metadata eligibility change with both client repositories before finalizing the
SQL conditions in the enrichment claim/pending queries around audiobook
enrichment. Verify clients handle items transitioning from scanner-supplied
cover-based completion to provider-identity-based enrichment, including changed
match status and re-enrichment states; update the client implementations or
defer the server-side behavior change until both clients are compatible.

Source: Coding guidelines

🤖 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/audiobooks/abs_smart_collection_store.go`:
- Line 25: Correct the column documentation comment near the canonical profile
schema to show SQL’s empty-string default as two straight single quotes,
replacing the curly quote in “DEFAULT ””.

In `@internal/audiobooks/enrichment_state.go`:
- Around line 123-128: Update the cause truncation logic in the enrichment state
flow to limit the string to 500 bytes without splitting a UTF-8 rune. Adjust the
boundary backward to the nearest valid rune boundary before slicing, preserving
the existing full-cause behavior when it is within the limit.
- Around line 114-157: Update enrichmentStateStore.RecordFailure so the upsert
and next_attempt_at update execute within one database transaction, committing
only after both succeed and rolling back on any error or cancellation. Preserve
the existing retry calculation, error wrapping, and no-op behavior for invalid
store inputs, using the transaction handle for both statements.

---

Outside diff comments:
In `@internal/audiobooks/enrichment.go`:
- Around line 327-381: Remove the “Load any durable provider IDs” comment and
the following e.providerIDs.GetByContentID loop from claimBatch, since its query
eligibility condition already excludes items with provider IDs. Leave item
scanning, deduplication, and rows.Err handling unchanged.

---

Nitpick comments:
In `@internal/audiobooks/enrichment.go`:
- Around line 219-231: Coordinate this metadata eligibility change with both
client repositories before finalizing the SQL conditions in the enrichment
claim/pending queries around audiobook enrichment. Verify clients handle items
transitioning from scanner-supplied cover-based completion to
provider-identity-based enrichment, including changed match status and
re-enrichment states; update the client implementations or defer the server-side
behavior change until both clients are compatible.
🪄 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: 50d87c0b-cd29-48b2-8a1c-5e073602e0a4

📥 Commits

Reviewing files that changed from the base of the PR and between 56f1c57 and 6316093.

📒 Files selected for processing (17)
  • internal/audiobooks/abs/bookmarks.go
  • internal/audiobooks/abs/jwt.go
  • internal/audiobooks/abs_smart_collection_store.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/podcastfeed/refresher_test.go
  • internal/audiobooks/smartcoll/evaluator_test.go
  • internal/audiobooks/smartcoll/query_test.go
  • internal/ebooks/enrichment.go
  • internal/ebooks/enrichment_test.go
  • internal/manga/enrichment.go
  • internal/metadata/match_confidence.go
  • internal/metadata/match_confidence_test.go
  • internal/metadata/provider_id_owner.go
  • migrations/sql/20260727181634_add_audiobook_enrichment_state.sql
🚧 Files skipped from review as they are similar to previous changes (6)
  • internal/ebooks/enrichment_test.go
  • internal/audiobooks/enrichment_claim_db_test.go
  • internal/manga/enrichment.go
  • internal/metadata/match_confidence.go
  • internal/metadata/match_confidence_test.go
  • internal/ebooks/enrichment.go

Comment thread internal/audiobooks/enrichment_state.go Resolved
Comment thread internal/audiobooks/enrichment_state.go Resolved
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

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

🧹 Nitpick comments (2)
internal/manga/enrichment.go (2)

305-313: 🚀 Performance & Scalability | 🔵 Trivial

Sort key is non-indexable; confirm the claim query stays cheap on large libraries.

ORDER BY COALESCE(ees.next_attempt_at, '-infinity'::timestamptz) cannot use a plain index on manga_enrichment_state.next_attempt_at, so each sweep sorts the full eligible set. If the accompanying migration doesn't already add an index covering (content_id, next_attempt_at, failures, last_error_class) on manga_enrichment_state, consider adding one and verifying the plan on a realistic backlog.

🤖 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.go` around lines 305 - 313, Review the enrichment
claim query around its ORDER BY and the corresponding migration, ensuring
manga_enrichment_state has an index covering content_id, next_attempt_at,
failures, and last_error_class to support large-backlog sweeps. Add the index if
absent, then verify the query plan against a realistic backlog so eligibility
and ordering remain unchanged.

540-649: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Admission/gating block is a near-verbatim copy of the ebook implementation.

Lines 540-649 duplicate collectEbookMetadata (internal/ebooks/enrichment.go Lines 954-1063) almost statement-for-statement: same admission request, same conflict logging, same status switch, same author gate, same AdmitProviderIDs + admittedResult replacement. Only the log component/prefix, filter*ProviderIDs, and content type differ. With audiobooks added in this stack, that's three copies that will drift independently. Consider extracting a shared helper in internal/metadata parameterized by content type, ID filter, and a log component string.

As per coding guidelines, "Place new backend code in the package that owns the behavior rather than in catch-all helpers; 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/manga/enrichment.go` around lines 540 - 649, Extract the duplicated
search-match and metadata identity admission flow from the manga enrichment path
and ebook equivalent into a shared helper owned by internal/metadata.
Parameterize content type, provider-ID filtering, and logging component/prefix
so manga, ebook, and audiobook callers retain their existing behavior and
messages, then replace each duplicated block with the helper.

Source: Coding guidelines

🤖 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/metadata/match_admission.go`:
- Around line 120-125: Update the normalization logic in the existing-provider
and requested-provider map handling within the admission function to detect when
multiple raw keys normalize to the same provider with different IDs, and reject
the request instead of allowing unordered map iteration to overwrite a value.
Preserve acceptance of duplicate normalized keys when their trimmed IDs match,
apply the same behavior to both maps, and add tests covering conflicting and
equivalent collisions.

In `@migrations/sql/20260728225039_classify_manga_enrichment_failures.sql`:
- Around line 2-13: The migration must avoid blocking writes to
manga_enrichment_state: configure it to run outside a transaction, create
idx_manga_enrichment_state_next_attempt with a concurrent index build, and add
manga_enrichment_state_error_class_check as NOT VALID before validating that
constraint afterward. Update the down migration to remove the constraint and
index safely.

---

Nitpick comments:
In `@internal/manga/enrichment.go`:
- Around line 305-313: Review the enrichment claim query around its ORDER BY and
the corresponding migration, ensuring manga_enrichment_state has an index
covering content_id, next_attempt_at, failures, and last_error_class to support
large-backlog sweeps. Add the index if absent, then verify the query plan
against a realistic backlog so eligibility and ordering remain unchanged.
- Around line 540-649: Extract the duplicated search-match and metadata identity
admission flow from the manga enrichment path and ebook equivalent into a shared
helper owned by internal/metadata. Parameterize content type, provider-ID
filtering, and logging component/prefix so manga, ebook, and audiobook callers
retain their existing behavior and messages, then replace each duplicated block
with the helper.
🪄 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: f9e35e0d-0b4a-4ee2-99e0-53b10ca7c70e

📥 Commits

Reviewing files that changed from the base of the PR and between 5b28b42 and 4d9de39.

📒 Files selected for processing (19)
  • 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_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
  • migrations/sql/20260728225039_classify_manga_enrichment_failures.sql
💤 Files with no reviewable changes (1)
  • internal/audiobooks/enrichment_state.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • internal/metadata/author_match_test.go
  • internal/metadata/author_match.go
  • internal/metadata/match_confidence.go
  • internal/metadata/match_confidence_test.go
  • internal/audiobooks/enrichment_state_db_test.go
  • internal/audiobooks/enrichment.go

Comment on lines +120 to +125
for provider, providerID := range req.ExistingProviderIDs {
provider = strings.ToLower(strings.TrimSpace(provider))
providerID = strings.TrimSpace(providerID)
if provider != "" && providerID != "" {
existing[provider] = providerID
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Reject conflicting normalized provider keys.

Line 124 and Line 157 overwrite entries after slug normalization, but map iteration is unordered. Inputs containing both OpenLibrary and openlibrary with different IDs can therefore admit or persist a different durable ID across runs. Reject conflicting normalized keys (in both maps) or canonicalize them before this function, and add collision tests.

As per coding guidelines, Go backend behavior must remain predictable under partial streams.

Also applies to: 128-158

🤖 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/metadata/match_admission.go` around lines 120 - 125, Update the
normalization logic in the existing-provider and requested-provider map handling
within the admission function to detect when multiple raw keys normalize to the
same provider with different IDs, and reject the request instead of allowing
unordered map iteration to overwrite a value. Preserve acceptance of duplicate
normalized keys when their trimmed IDs match, apply the same behavior to both
maps, and add tests covering conflicting and equivalent collisions.

Source: Coding guidelines

Comment on lines +2 to +13
ALTER TABLE manga_enrichment_state
ADD COLUMN last_error_class text,
ADD COLUMN next_attempt_at timestamptz,
ADD CONSTRAINT manga_enrichment_state_error_class_check
CHECK (last_error_class IS NULL OR last_error_class IN ('transient', 'rate_limited', 'permanent'));

CREATE INDEX idx_manga_enrichment_state_next_attempt
ON manga_enrichment_state (next_attempt_at)
WHERE next_attempt_at IS NOT NULL;

-- +goose Down
DROP INDEX IF EXISTS idx_manga_enrichment_state_next_attempt;

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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate migration =="
fd -a '20260728225039_classify_manga_enrichment_failures.sql|goose|sql' . | sed 's#^\./##' | head -200

echo
echo "== target migration =="
if [ -f migrations/sql/20260728225039_classify_manga_enrichment_failures.sql ]; then
  cat -n migrations/sql/20260728225039_classify_manga_enrichment_failures.sql
fi

echo
echo "== related source mentions =="
rg -n "manga_enrichment_state|last_error_class|next_attempt_at|error class|ratelimit|transient|rate_limited|permanent" . \
  -g '!vendor' -g '!node_modules' | head -300

Repository: Silo-Server/silo-server

Length of output: 13816


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== target migration exists? =="
ls -l migrations/sql/20260728225039_classify_manga_enrichment_failures.sql 2>/dev/null || true

echo
echo "== exact target migration =="
if [ -f migrations/sql/20260728225039_classify_manga_enrichment_failures.sql ]; then
  cat -n migrations/sql/20260728225039_classify_manga_enrichment_failures.sql
fi

echo
echo "== schema/table definition and relevant migrations =="
rg -n "CREATE TABLE manga_enrichment_state|ALTER TABLE manga_enrichment_state|manga_enrichment_state|last_error_class|next_attempt_at|rate_limited|transient|permanent" migrations/sql . \
  -g '!vendor' -g '!node_modules' -g '!dist' -g '!build' | head -500

Repository: Silo-Server/silo-server

Length of output: 50379


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== original manga table migration =="
cat -n migrations/sql/20260611003847_manga_enrichment_state.sql

echo
echo "== audiobook migration for reference =="
cat -n migrations/sql/20260727181634_add_audiobook_enrichment_state.sql

echo
echo "== goose usage / transaction config indicators =="
rg -n "-- \+goose|GOOSE|NO TRANSACTION|migrate-create|migrate" -g '!node_modules' -g '!vendor' -g '!dist' -g '!build' . | head -200

Repository: Silo-Server/silo-server

Length of output: 4283


Avoid blocking enrichment writes during this migration.

The checked constraint and regular index build can block writes on manga_enrichment_state. Run this migration outside a transaction, build the index concurrently, add the constraint as NOT VALID, then validate it afterward.

🧰 Tools
🪛 Squawk (2.61.0)

[warning] 5-6: By default new constraints require a table scan and block writes to the table while that scan occurs. Use NOT VALID with a later VALIDATE CONSTRAINT call.

(constraint-missing-not-valid)


[warning] 8-10: During normal index creation, table updates are blocked, but reads are still allowed. Use concurrently to avoid blocking writes.

(require-concurrent-index-creation)


[warning] 13-13: A normal DROP INDEX acquires an ACCESS EXCLUSIVE lock on the table, blocking other accesses until the index drop can complete. Drop the index CONCURRENTLY.

(require-concurrent-index-deletion)

🤖 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 2 - 13, The migration must avoid blocking writes to
manga_enrichment_state: configure it to run outside a transaction, create
idx_manga_enrichment_state_next_attempt with a concurrent index build, and add
manga_enrichment_state_error_class_check as NOT VALID before validating that
constraint afterward. Update the down migration to remove the constraint and
index safely.

Source: Linters/SAST tools

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