Skip to content

fix(ebooks): count real no_match cycles, escalate retry horizons, strip retail edition suffixes - #514

Closed
RXWatcher wants to merge 15 commits into
Silo-Server:mainfrom
RXWatcher:fix/ebook-nomatch-drain
Closed

RXWatcher wants to merge 15 commits into
Silo-Server:mainfrom
RXWatcher:fix/ebook-nomatch-drain

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #496 (fix/audiobook-enrichment-identity-gate) — merge that first; this branch builds on its tip plus a merge of current main.

Problem

  • 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) consume the same daily retry quota as books that were never actually tried.
  • Search queries still carried retail edition suffixes ("(AmazonClassics Edition)", "(Kindle Single)", "(A Novel)") that no provider catalogue indexes — same failure mode as the series-marker noise already stripped.

Fix

  • failures 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 stripped in cleanEbookSearchTitle — anything ending in Edition(s)/Classics, "Kindle Single", "A Novel". "(Illustrated)"/"(Annotated)" deliberately survive, consistent with the meaningful-parenthetical rule.
  • Test-stub fixes for internal/access and internal/jellycompat: feat: emailed invitations, claim + household setup, and server-driven onboarding tour #501 extended userstore.UserStore with the onboarding methods without updating these test doubles, so both packages fail to compile under test on current main.

Testing

go test ./internal/... green except pre-existing failures on the #496 lineage (jellycompat autoscan sidecar + BeginWebOperation process-lock tests), which fail identically at the branch point before these changes.

Running in production since 2026-07-29 (silo-server:nomatch-drain-c6a5be4): failures incrementing correctly with base horizons on first cycle.

AI-use disclosure: implemented with Claude Code.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Improvements
    • Improved audiobook, ebook, and manga metadata matching across providers.
    • Better handling of title variations, volumes, editions, accented text, and author names.
    • Prevented conflicting or already-assigned provider identifiers from being applied.
    • Enrichment updates now avoid partial changes when saving related metadata fails.
    • Failed or incomplete enrichment attempts are tracked and retried automatically with scheduled backoff.
    • Added clearer handling for rate limits, temporary service issues, and permanent errors.

RXWatcher and others added 15 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
…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]>
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds shared metadata matching, author validation, provider error classification, and identity admission. Audiobook enrichment gains durable retry state and transactional persistence. Ebook and manga enrichment adopt the admission and retry flows, with expanded database and unit-test coverage.

Changes

Enrichment pipeline

Layer / File(s) Summary
Metadata matching and error contracts
internal/metadata/*
Adds title scoring, author agreement, provider error classification, and provider-ID ownership interfaces with tests.
Admission policy
internal/metadata/match_admission.go, internal/*/enrichment.go
Admits provider results only when title, author, and durable identity checks pass; ownership conflicts are excluded.
Audiobook retry and persistence
internal/audiobooks/*, internal/catalog/item_repo.go, migrations/sql/*audiobook*
Adds persistent retry state, eligibility gating, exponential backoff, and atomic provider-ID and metadata persistence.
Ebook and manga integration
internal/ebooks/*, internal/manga/*, migrations/sql/*manga*
Applies admission and error classification to ebook and manga enrichment, including retry scheduling and provider-ID failure propagation.
Supporting test updates
internal/access/resolver_test.go, internal/jellycompat/content_direct_test.go, internal/audiobooks/smartcoll/*
Updates test doubles for expanded store contracts and adjusts test formatting.

Estimated code review effort: 5 (Critical) | ~120 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 41.76% 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 accurately captures the main ebook retry and title-cleanup changes, though it omits the broader stacked changes.
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 29, 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: 5

🧹 Nitpick comments (7)
internal/audiobooks/enrichment_test.go (1)

197-209: 🗄️ Data Integrity & Integration | 🔵 Trivial | 🏗️ Heavy lift

Cover the transaction-backed failure path.

Because pool and itemRepo are nil, this test calls legacy ReplaceByContentID; it never exercises ReplaceByContentIDTx, which is the production path. Add transaction-backed coverage, or an equivalent seam, to verify errors.Is for the actual persistence flow.

🤖 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_test.go` around lines 197 - 209, The test
TestPersistReturnsProviderIDFailure currently uses nil pool and itemRepo, so it
exercises legacy ReplaceByContentID instead of production transaction-backed
ReplaceByContentIDTx. Update the test setup or add an equivalent seam with
configured pool and itemRepo so persist uses the transaction path, then preserve
the assertion that errors.Is(err, replaceErr) succeeds for the provider-ID
failure.
internal/metadata/match_confidence.go (1)

302-313: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Doc comment for BestMatchYear is attached to bestMatchSelection.

Godoc renders lines 302-308 as documentation for the unexported struct, leaving the exported BestMatchYear (line 373) undocumented. Move the block above the function.

🤖 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 302 - 313, Move the
documentation block beginning “BestMatchYear is BestMatch...” from above
bestMatchSelection to immediately above the exported BestMatchYear function,
leaving the struct declaration without that unrelated comment.
internal/metadata/match_admission.go (1)

134-139: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

A candidate ID that contradicts an existing ID for the same provider disappears silently.

When existing[provider] differs from the candidate, the branch skips without recording anything — the disagreement (a strong signal the match is wrong) is invisible in Conflicts and in logs. Either record it as a conflict (OwnedBy: req.ContentID) or document explicitly that same-provider replacements are intentionally ignored.

🤖 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 134 - 139, Update the
existing-provider branch in the metadata admission logic so a candidate provider
ID that differs from existing[provider] is recorded as a conflict with OwnedBy
set to req.ContentID; preserve the current usable-identity behavior when the IDs
match and continue processing afterward.
internal/audiobooks/enrichment_claim_db_test.go (1)

111-111: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use newTestEnricher here.

Its doc comment argues against hand-assembled structs that can drift, yet both tests build an Enricher inline without state — the field the eligibility predicate now depends on.

Also applies to: 146-146

🤖 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_claim_db_test.go` at line 111, Update both
test setup sites to use the existing newTestEnricher helper instead of
constructing Enricher inline. Ensure the helper initializes all required fields,
including state, so the tests exercise the same eligibility behavior without
duplicated setup.
internal/manga/enrichment.go (2)

305-313: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

ORDER BY COALESCE(ees.next_attempt_at, '-infinity') cannot use the new partial index.

The migration's index is (next_attempt_at) WHERE next_attempt_at IS NOT NULL, so this expression-based sort (plus the COALESCE(failures,0) tiebreak) will force a sort over the joined set on every sweep. Worth checking the plan at production row counts; an expression index matching the ordering, or next_attempt_at NULLS FIRST, would be index-friendly.

🤖 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, Update the enrichment
query’s ORDER BY near the eligibility predicates to use the indexed
ees.next_attempt_at column directly with NULLS FIRST, and replace the
COALESCE(ees.failures, 0) tiebreak with an index-compatible ordering where
applicable. Preserve the existing ordering semantics while allowing the partial
next_attempt_at index to support the sweep.

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

Search-admission and provider-ID-admission glue is duplicated verbatim from the ebook enricher.

The admission switch, conflict logging, author-agreement gate, and admittedResult copy differ from internal/ebooks/enrichment.go only by content type, log component, and the provider-ID filter. A small shared helper in internal/metadata taking those three as parameters would keep the three media pipelines from drifting.

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-admission and provider-ID-admission flow from the manga and ebook
enrichers into a shared helper in internal/metadata. Parameterize the content
type, log component, and provider-ID filtering behavior, while preserving the
admission switch, conflict logging, author-agreement gate, and admittedResult
copy semantics. Update both enrichment pipelines to call the helper so their
behavior remains unchanged and future media pipelines reuse the same logic.

Source: Coding guidelines

internal/ebooks/enrichment.go (1)

1246-1255: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚖️ Poor tradeoff

Provider-ID writes are now fail-fast but still not atomic with the metadata update. Both enrichers write durable provider IDs first and only then update metadata/timestamps outside a transaction, so a failure in the second write leaves committed provider IDs for an item that was never stamped — the exact partial state the audiobook layer removed with a transactional persist.

  • internal/ebooks/enrichment.go#L1246-L1255: wrap ReplaceByContentID and updateMetadataAndTimestamps in one transaction, mirroring the audiobook persist path.
  • internal/manga/enrichment.go#L803-L808: apply the same transactional wrapping around ReplaceByContentID and updateMetadataAndTimestamps.
🤖 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 1246 - 1255, Make provider-ID
replacement and metadata/timestamp updates atomic by wrapping both operations in
the same transaction, mirroring the audiobook persist path. Update
internal/ebooks/enrichment.go lines 1246-1255 and internal/manga/enrichment.go
lines 803-808 around ReplaceByContentID and updateMetadataAndTimestamps; commit
only after both succeed and propagate failures so neither write remains
committed independently.
🤖 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_state_db_test.go`:
- Around line 183-196: The test TestHasPendingItemsRespectsParkedRetries must
invoke HasPendingItems and assert that no pending items are reported for its
seeded parked fixture. Scope or isolate the check to this fixture so shared
test-database state cannot make the assertion unreliable, while preserving the
existing unclaimable-item assertion.

In `@internal/audiobooks/enrichment_state.go`:
- Around line 140-149: Update the ON CONFLICT update clause in RecordFailure to
clear the existing terminal outcome and completed_at fields when recording a
failure. Preserve the current retry, error, attempt, and timestamp updates so
failed rows remain explicitly non-terminal and eligible for retry.

In `@internal/audiobooks/enrichment.go`:
- Around line 552-564: In the provider loop around AuthorsAgree, handle a
mismatching provider by logging it and continuing to the next provider instead
of recording a terminal no-match and returning. Preserve accepted data from
earlier providers, and let the existing no-match path apply only when the shared
accumulator remains empty.

In `@internal/metadata/match_confidence.go`:
- Around line 165-186: Update the title normalization flow around normaliseTitle
and the bare-number scan so literal-digit detection uses an unfurled word form
rather than the number-folded form. Add or reuse normaliseTitleWords for this
form, keep volumeMarkerRE matching on normaliseTitle so Roman and spelled
numerals in explicit markers remain supported, and scan the word-normalized
fields for bare volumes.

In `@internal/metadata/provider_error.go`:
- Around line 102-128: Update classifyProviderErrorText so the numeric
status-code checks for 429, 401, and 403 match only standalone codes using
word-boundary anchoring, while preserving the existing textual error checks and
classifications.

---

Nitpick comments:
In `@internal/audiobooks/enrichment_claim_db_test.go`:
- Line 111: Update both test setup sites to use the existing newTestEnricher
helper instead of constructing Enricher inline. Ensure the helper initializes
all required fields, including state, so the tests exercise the same eligibility
behavior without duplicated setup.

In `@internal/audiobooks/enrichment_test.go`:
- Around line 197-209: The test TestPersistReturnsProviderIDFailure currently
uses nil pool and itemRepo, so it exercises legacy ReplaceByContentID instead of
production transaction-backed ReplaceByContentIDTx. Update the test setup or add
an equivalent seam with configured pool and itemRepo so persist uses the
transaction path, then preserve the assertion that errors.Is(err, replaceErr)
succeeds for the provider-ID failure.

In `@internal/ebooks/enrichment.go`:
- Around line 1246-1255: Make provider-ID replacement and metadata/timestamp
updates atomic by wrapping both operations in the same transaction, mirroring
the audiobook persist path. Update internal/ebooks/enrichment.go lines 1246-1255
and internal/manga/enrichment.go lines 803-808 around ReplaceByContentID and
updateMetadataAndTimestamps; commit only after both succeed and propagate
failures so neither write remains committed independently.

In `@internal/manga/enrichment.go`:
- Around line 305-313: Update the enrichment query’s ORDER BY near the
eligibility predicates to use the indexed ees.next_attempt_at column directly
with NULLS FIRST, and replace the COALESCE(ees.failures, 0) tiebreak with an
index-compatible ordering where applicable. Preserve the existing ordering
semantics while allowing the partial next_attempt_at index to support the sweep.
- Around line 540-649: Extract the duplicated search-admission and
provider-ID-admission flow from the manga and ebook enrichers into a shared
helper in internal/metadata. Parameterize the content type, log component, and
provider-ID filtering behavior, while preserving the admission switch, conflict
logging, author-agreement gate, and admittedResult copy semantics. Update both
enrichment pipelines to call the helper so their behavior remains unchanged and
future media pipelines reuse the same logic.

In `@internal/metadata/match_admission.go`:
- Around line 134-139: Update the existing-provider branch in the metadata
admission logic so a candidate provider ID that differs from existing[provider]
is recorded as a conflict with OwnedBy set to req.ContentID; preserve the
current usable-identity behavior when the IDs match and continue processing
afterward.

In `@internal/metadata/match_confidence.go`:
- Around line 302-313: Move the documentation block beginning “BestMatchYear is
BestMatch...” from above bestMatchSelection to immediately above the exported
BestMatchYear function, leaving the struct declaration without that unrelated
comment.
🪄 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: e7e59209-0d5b-49c5-9d89-abbc2207c297

📥 Commits

Reviewing files that changed from the base of the PR and between 08035f3 and c6a5be4.

📒 Files selected for processing (27)
  • 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 +183 to +196
func TestHasPendingItemsRespectsParkedRetries(t *testing.T) {
pool := newClaimTestPool(t)
ctx := context.Background()
e := newTestEnricher(pool)

only := seedAudiobook(t, pool, "onlyparked", "/covers/embedded.jpg", false)
if err := e.state.RecordFailure(ctx, only, EnrichmentErrorPermanent, "403 forbidden"); err != nil {
t.Fatalf("RecordFailure: %v", err)
}

if claimedIDs(t, e)[only] {
t.Fatal("parked item was claimable; the rest of this test is meaningless")
}
}

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

This test never calls HasPendingItems, so it does not guard the invariant it names.

It only asserts the parked item is unclaimable. A shared test DB makes a bare HasPendingItems() == false assertion unreliable, but the gate can still be checked scoped to the fixture.

💚 Suggested addition
 	if claimedIDs(t, e)[only] {
 		t.Fatal("parked item was claimable; the rest of this test is meaningless")
 	}
+
+	// The scheduler gate must not count the parked fixture as work either.
+	var pending bool
+	if err := pool.QueryRow(ctx, `
+		SELECT EXISTS(
+			SELECT 1 FROM media_items mi
+			WHERE mi.content_id = $1
+			  AND NOT EXISTS (SELECT 1 FROM media_item_provider_ids p WHERE p.content_id = mi.content_id)
+			  AND mi.last_refreshed IS NULL
+			  AND NOT EXISTS (
+			      SELECT 1 FROM audiobook_enrichment_state s
+			      WHERE s.content_id = mi.content_id
+			        AND s.next_attempt_at IS NOT NULL
+			        AND s.next_attempt_at > now()
+			  )
+		)
+	`, only).Scan(&pending); err != nil {
+		t.Fatalf("gate query: %v", err)
+	}
+	if pending {
+		t.Error("the HasPendingItems predicate still counts a parked item as work")
+	}
📝 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
func TestHasPendingItemsRespectsParkedRetries(t *testing.T) {
pool := newClaimTestPool(t)
ctx := context.Background()
e := newTestEnricher(pool)
only := seedAudiobook(t, pool, "onlyparked", "/covers/embedded.jpg", false)
if err := e.state.RecordFailure(ctx, only, EnrichmentErrorPermanent, "403 forbidden"); err != nil {
t.Fatalf("RecordFailure: %v", err)
}
if claimedIDs(t, e)[only] {
t.Fatal("parked item was claimable; the rest of this test is meaningless")
}
}
func TestHasPendingItemsRespectsParkedRetries(t *testing.T) {
pool := newClaimTestPool(t)
ctx := context.Background()
e := newTestEnricher(pool)
only := seedAudiobook(t, pool, "onlyparked", "/covers/embedded.jpg", false)
if err := e.state.RecordFailure(ctx, only, EnrichmentErrorPermanent, "403 forbidden"); err != nil {
t.Fatalf("RecordFailure: %v", err)
}
if claimedIDs(t, e)[only] {
t.Fatal("parked item was claimable; the rest of this test is meaningless")
}
// The scheduler gate must not count the parked fixture as work either.
var pending bool
if err := pool.QueryRow(ctx, `
SELECT EXISTS(
SELECT 1 FROM media_items mi
WHERE mi.content_id = $1
AND NOT EXISTS (SELECT 1 FROM media_item_provider_ids p WHERE p.content_id = mi.content_id)
AND mi.last_refreshed IS NULL
AND NOT EXISTS (
SELECT 1 FROM audiobook_enrichment_state s
WHERE s.content_id = mi.content_id
AND s.next_attempt_at IS NOT NULL
AND s.next_attempt_at > now()
)
)
`, only).Scan(&pending); err != nil {
t.Fatalf("gate query: %v", err)
}
if pending {
t.Error("the HasPendingItems predicate still counts a parked item as work")
}
}
🤖 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_state_db_test.go` around lines 183 - 196, The
test TestHasPendingItemsRespectsParkedRetries must invoke HasPendingItems and
assert that no pending items are reported for its seeded parked fixture. Scope
or isolate the check to this fixture so shared test-database state cannot make
the assertion unreliable, while preserving the existing unclaimable-item
assertion.

Comment on lines +140 to +149
ON CONFLICT (content_id) DO UPDATE SET
attempts = audiobook_enrichment_state.attempts + 1,
last_error_class = EXCLUDED.last_error_class,
last_error = EXCLUDED.last_error,
next_attempt_at = now() + make_interval(secs => LEAST(
$4::double precision * (audiobook_enrichment_state.attempts + 1),
$5::double precision
)),
last_attempt_at = now(),
updated_at = now()

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 | 🟡 Minor | ⚡ Quick win

RecordFailure leaves a stale terminal outcome on the row.

On conflict the update never touches outcome, so a row that previously recorded success/no_match/skipped and then fails again reads as terminal and parked for retry — the ambiguity this table was introduced to remove. Clearing it (and completed_at) keeps "failed, not finished" unambiguous.

🛠️ Proposed fix
 		ON CONFLICT (content_id) DO UPDATE SET
 			attempts         = audiobook_enrichment_state.attempts + 1,
+			outcome          = NULL,
+			completed_at     = NULL,
 			last_error_class = EXCLUDED.last_error_class,
📝 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
ON CONFLICT (content_id) DO UPDATE SET
attempts = audiobook_enrichment_state.attempts + 1,
last_error_class = EXCLUDED.last_error_class,
last_error = EXCLUDED.last_error,
next_attempt_at = now() + make_interval(secs => LEAST(
$4::double precision * (audiobook_enrichment_state.attempts + 1),
$5::double precision
)),
last_attempt_at = now(),
updated_at = now()
ON CONFLICT (content_id) DO UPDATE SET
attempts = audiobook_enrichment_state.attempts + 1,
outcome = NULL,
completed_at = NULL,
last_error_class = EXCLUDED.last_error_class,
last_error = EXCLUDED.last_error,
next_attempt_at = now() + make_interval(secs => LEAST(
$4::double precision * (audiobook_enrichment_state.attempts + 1),
$5::double precision
)),
last_attempt_at = now(),
updated_at = now()
🤖 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_state.go` around lines 140 - 149, Update the
ON CONFLICT update clause in RecordFailure to clear the existing terminal
outcome and completed_at fields when recording a failure. Preserve the current
retry, error, attempt, and timestamp updates so failed rows remain explicitly
non-terminal and eligible for retry.

Comment on lines +552 to +564
// Validate each provider before its fields or IDs enter the shared
// accumulator. Checking only the aggregate lets a later correct author
// validate an earlier same-title result for a different book.
if !metadata.AuthorsAgree(item.Author, result.People) {
slog.InfoContext(ctx, "audiobook enrichment: author mismatch; treating as no match", "component", "audiobooks",
"provider", p.Slug(),
"content_id", item.ContentID,
"title", item.Title,
"item_author", item.Author,
)
e.recordOutcome(ctx, item.ContentID, EnrichmentOutcomeNoMatch)
return e.stampLastRefreshed(ctx, item.ContentID)
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd -t f 'author_match.go' -x cat -n {}

Repository: Silo-Server/silo-server

Length of output: 5840


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate enrichment.go =="
fd -t f '^enrichment\.go$' internal | sed 's#^\./##'

echo
echo "== relevant enrichment.go lines =="
file="$(fd -t f '^enrichment\.go$' internal | head -n 1)"
wc -l "$file"
sed -n '520,590p' "$file" | cat -n
echo "--- later paths ---"
sed -n '590,645p' "$file" | cat -n

echo
echo "== claimBatch author COALESCE usages =="
rg -n "COALESCE|last_refreshed|claimBatch|AuthorsAgree|AdmitSearchMatch" internal/api internal -g '*.go' -g '*.sql' | head -n 200

Repository: Silo-Server/silo-server

Length of output: 25907


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== audiobook claimBatchQuery =="
sed -n '200,340p' internal/audiobooks/enrichment.go | cat -n

echo
echo "== ebook enrichment around author mismatch (for comparison) =="
sed -n '600,665p' internal/ebooks/enrichment.go | cat -n

echo
echo "== deterministic probe: AuthorsAgree empty-author behavior and loop outcomes =="
python3 - <<'PY'
sample_codes = {
    "return_terminal": lambda result: "stamped-no-match" if not result["agree"] else "later",
    "continue_provider": lambda result: "stamped-no-match" if result["agree"] == False else "later",
    "empty_auth_agree": sample_codes["return_terminal"]({"agree": True})
}
for name, fn in sample_codes.items():
    print(name, "=", fn({"agree": False}))
PY

echo
echo "== exact file symbols for internal/audiobooks/enrichment.go =="
ast-grep outline internal/audiobooks/enrichment.go --match claimBatch --view expanded || true

Repository: Silo-Server/silo-server

Length of output: 8345


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== audiobook claimBatchQuery continued =="
sed -n '340,430p' internal/audiobooks/enrichment.go | cat -n

echo
echo "== audiobook enrichItem eligibility/phase 1 =="
sed -n '430,530p' internal/audiobooks/enrichment.go | cat -n

echo
echo "== exact author mismatch lines again =="
sed -n '550,570p' internal/audiobooks/enrichment.go | cat -n

echo
echo "== search for audiobook_enrichment_state writer =="
rg -n "audiobook_enrichment_state|last_refreshed|EnrichmentOutcomeNoMatch|recordOutcome" internal/audiobooks internal -g '*.go' | head -n 200

Repository: Silo-Server/silo-server

Length of output: 23050


Handle author mismatches per provider, not for the whole item.

Returning here from inside the GetMetadata provider loop dumps IDs/metadata already admitted by earlier providers and stamps the audiobook as terminally no_match, which prevents future claimBatch selection despite possible matches from later providers. Use continue, and only rely on the existing no-match path when the accumulator remains empty. Also, AuthorsAgree already treats a missing item author or missing provider author credits as agreement.

🤖 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 552 - 564, In the provider
loop around AuthorsAgree, handle a mismatching provider by logging it and
continuing to the next provider instead of recording a terminal no-match and
returning. Preserve accepted data from earlier providers, and let the existing
no-match path apply only when the shared accumulator remains empty.

Comment on lines +165 to +186
// Work on the normalised form from here so that spelled and Roman numerals
// are already digits: "Book II" has to agree with "Book 2", and
// "Slaughterhouse-Five" with "Slaughterhouse 5".
folded := normaliseTitle(s)

if m := volumeMarkerRE.FindStringSubmatch(folded); m != nil {
if n, err := strconv.Atoi(m[1]); err == nil {
return volumeIdentity{first: n, last: n}, true
}
}

// 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)
for _, f := range fields {
n, err := strconv.Atoi(f)
if err != nil || n <= 0 || n > 999 {
continue
}
return volumeIdentity{first: n, last: n}, true
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Spelled-out numerals in the title body are read as volume numbers, so correct matches score 0.

The bare-number scan runs on the number-folded form, so Three Body Problem yields volume 3 and Fifty Shades of Grey yields 50. When the provider answers with an explicit marker (The Three-Body Problem, Book 1), titleVolume reports a contradiction and TitleScore returns 0 — a correct match is permanently recorded as no_match.

Restricting the bare scan to literal digits fixes it without weakening any existing case: Book II vs Book 3 still disagrees via volumeMarkerRE (which runs on the folded form), and bare-digit pairs like Dungeon In My Closet 2 vs ..., Book 5 still disagree.

🐛 Proposed fix: only literal digits count as a bare volume
-	// Work on the normalised form from here so that spelled and Roman numerals
-	// are already digits: "Book II" has to agree with "Book 2", and
-	// "Slaughterhouse-Five" with "Slaughterhouse 5".
-	folded := normaliseTitle(s)
+	// Markers work on the folded form so that spelled and Roman numerals are
+	// already digits: "Book II" has to agree with "Book 2".
+	normalised := normaliseTitleWords(s)
+	folded := foldNumberWords(normalised)
 
 	if m := volumeMarkerRE.FindStringSubmatch(folded); m != nil {
 		if n, err := strconv.Atoi(m[1]); err == nil {
 			return volumeIdentity{first: n, last: n}, true
 		}
 	}
 
 	// 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)
+	// rather than number a volume. Only literal digits count here: a spelled
+	// numeral is far more often part of the title ("Three Body Problem",
+	// "Fifty Shades of Grey") than a volume, and reading it as one made those
+	// titles contradict a genuine "Book 1" marker.
+	fields := strings.Fields(normalised)

Split normaliseTitle so both forms are available:

// normaliseTitleWords is normaliseTitle without number-word folding.
func normaliseTitleWords(s string) string {
	s = norm.NFC.String(s)
	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 {
	return foldNumberWords(normaliseTitleWords(s))
}
🤖 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 165 - 186, Update the
title normalization flow around normaliseTitle and the bare-number scan so
literal-digit detection uses an unfurled word form rather than the number-folded
form. Add or reuse normaliseTitleWords for this form, keep volumeMarkerRE
matching on normaliseTitle so Roman and spelled numerals in explicit markers
remain supported, and scan the word-normalized fields for bare volumes.

Comment on lines +102 to +128
func classifyProviderErrorText(message string) ProviderErrorClass {
msg := strings.ToLower(message)
switch {
case strings.Contains(msg, "resourceexhausted"),
strings.Contains(msg, "resource exhausted"),
strings.Contains(msg, "429"),
strings.Contains(msg, "rate limit"),
strings.Contains(msg, "ratelimit"),
strings.Contains(msg, "too many requests"),
strings.Contains(msg, "quota"):
return ProviderErrorRateLimited
case strings.Contains(msg, "invalidargument"),
strings.Contains(msg, "invalid argument"),
strings.Contains(msg, "notfound"),
strings.Contains(msg, "not found"),
strings.Contains(msg, "permissiondenied"),
strings.Contains(msg, "permission denied"),
strings.Contains(msg, "unauthenticated"),
strings.Contains(msg, "unauthorized"),
strings.Contains(msg, "failedprecondition"),
strings.Contains(msg, "failed precondition"),
strings.Contains(msg, "unimplemented"),
strings.Contains(msg, "not implemented"),
strings.Contains(msg, "401"),
strings.Contains(msg, "403"),
strings.Contains(msg, "forbidden"):
return ProviderErrorPermanent

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Bare numeric substrings misclassify provider errors.

strings.Contains(msg, "429") (and "401"/"403") matches any digits embedded in identifiers or URLs — openlibrary work OL4291W not found classifies as rate_limited instead of permanent, so a genuinely dead ID keeps getting retried on the rate-limit path. Anchor the numeric codes on word boundaries.

🐛 Proposed fix: boundary-anchored status codes
+var (
+	rateLimitCodeRE = regexp.MustCompile(`\b429\b`)
+	permanentCodeRE = regexp.MustCompile(`\b(401|403)\b`)
+)
+
 func classifyProviderErrorText(message string) ProviderErrorClass {
 	msg := strings.ToLower(message)
 	switch {
 	case strings.Contains(msg, "resourceexhausted"),
 		strings.Contains(msg, "resource exhausted"),
-		strings.Contains(msg, "429"),
+		rateLimitCodeRE.MatchString(msg),
 		strings.Contains(msg, "rate limit"),
@@
-		strings.Contains(msg, "401"),
-		strings.Contains(msg, "403"),
+		permanentCodeRE.MatchString(msg),
 		strings.Contains(msg, "forbidden"):
 		return ProviderErrorPermanent
📝 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
func classifyProviderErrorText(message string) ProviderErrorClass {
msg := strings.ToLower(message)
switch {
case strings.Contains(msg, "resourceexhausted"),
strings.Contains(msg, "resource exhausted"),
strings.Contains(msg, "429"),
strings.Contains(msg, "rate limit"),
strings.Contains(msg, "ratelimit"),
strings.Contains(msg, "too many requests"),
strings.Contains(msg, "quota"):
return ProviderErrorRateLimited
case strings.Contains(msg, "invalidargument"),
strings.Contains(msg, "invalid argument"),
strings.Contains(msg, "notfound"),
strings.Contains(msg, "not found"),
strings.Contains(msg, "permissiondenied"),
strings.Contains(msg, "permission denied"),
strings.Contains(msg, "unauthenticated"),
strings.Contains(msg, "unauthorized"),
strings.Contains(msg, "failedprecondition"),
strings.Contains(msg, "failed precondition"),
strings.Contains(msg, "unimplemented"),
strings.Contains(msg, "not implemented"),
strings.Contains(msg, "401"),
strings.Contains(msg, "403"),
strings.Contains(msg, "forbidden"):
return ProviderErrorPermanent
var (
rateLimitCodeRE = regexp.MustCompile(`\b429\b`)
permanentCodeRE = regexp.MustCompile(`\b(401|403)\b`)
)
func classifyProviderErrorText(message string) ProviderErrorClass {
msg := strings.ToLower(message)
switch {
case strings.Contains(msg, "resourceexhausted"),
strings.Contains(msg, "resource exhausted"),
rateLimitCodeRE.MatchString(msg),
strings.Contains(msg, "rate limit"),
strings.Contains(msg, "ratelimit"),
strings.Contains(msg, "too many requests"),
strings.Contains(msg, "quota"):
return ProviderErrorRateLimited
case strings.Contains(msg, "invalidargument"),
strings.Contains(msg, "invalid argument"),
strings.Contains(msg, "notfound"),
strings.Contains(msg, "not found"),
strings.Contains(msg, "permissiondenied"),
strings.Contains(msg, "permission denied"),
strings.Contains(msg, "unauthenticated"),
strings.Contains(msg, "unauthorized"),
strings.Contains(msg, "failedprecondition"),
strings.Contains(msg, "failed precondition"),
strings.Contains(msg, "unimplemented"),
strings.Contains(msg, "not implemented"),
permanentCodeRE.MatchString(msg),
strings.Contains(msg, "forbidden"):
return ProviderErrorPermanent
🤖 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/provider_error.go` around lines 102 - 128, Update
classifyProviderErrorText so the numeric status-code checks for 429, 401, and
403 match only standalone codes using word-boundary anchoring, while preserving
the existing textual error checks and classifications.

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