Skip to content

fix(metadata): select and cache refresh artwork correctly - #676

Merged
Quick104 merged 2 commits into
Silo-Server:mainfrom
blurbery:agent/metadata-artwork-refresh
Aug 19, 2026
Merged

Quick104 merged 2 commits into
Silo-Server:mainfrom
blurbery:agent/metadata-artwork-refresh

Conversation

@blurbery

@blurbery blurbery commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related to #211; this PR does not close it.

Manual Quick and Complete Refresh can finish metadata while the selected item's artwork remains queued behind the global image-cache backlog. Poster selection also has no way to distinguish a genuinely text-bearing poster from a language-tagged but textless poster, so an English library can keep the wrong artwork.

Approach

  • Add an optional, backward-compatible includes_text image signal and use four explicit poster tiers: preferred-language text, English text, other text, then textless. Local sidecars remain authoritative; backgrounds remain language-neutral; logos retain language-aware fallbacks.
  • Give interactive refreshes a target-scoped cache path that retries failed/backed-off jobs, waits for a concurrent worker, reports cache failures, and never drains unrelated artwork. A concurrent index keeps those target operations independent of global backlog size.
  • Wire both Quick and Complete Refresh through that path, including the remapped content ID after Complete Refresh.
  • Replace the Web UI's loading toast in place with the final success or failure toast.

Authorship and live verification

All of this work is mine. I tested it end-to-end in my live Silo installation and confirmed that it works.

Codex assisted with upstream cleanup, tests, adversarial review, and PR preparation as disclosed below.

Testing

Focused Go tests:

$ go test ./internal/metadata ./internal/adminjob
ok  github.com/Silo-Server/silo-server/internal/metadata  (cached)
ok  github.com/Silo-Server/silo-server/internal/adminjob  (cached)

$ go test -race ./internal/metadata ./internal/adminjob
ok  github.com/Silo-Server/silo-server/internal/metadata  2.006s
ok  github.com/Silo-Server/silo-server/internal/adminjob  2.199s

CI-equivalent changed-line lint:

$ golangci-lint run --new-from-merge-base=upstream/main ./...
0 issues.

Changed Web tests and formatting:

$ pnpm exec vitest run src/hooks/queries/items.test.ts
Test Files  1 passed (1)
Tests       8 passed (8)

$ pnpm exec prettier --check src/hooks/queries/items.ts src/hooks/queries/items.test.ts
Checking formatting...
All matched files use Prettier code style!

Additional successful checks:

  • go vet ./internal/metadata ./internal/adminjob ./cmd/silo
  • go build ./internal/... ./cmd/...
  • make migrate-validate
  • make verify-local-paths
  • pnpm exec eslint src/hooks/queries/items.ts src/hooks/queries/items.test.ts
  • Full Web suite: 278 files and 1,960 tests passed
  • Full Web lint: 0 errors (151 existing warnings)
  • Full Web format check and production build passed

The legacy unscoped make lint was run and reported the documented upstream baseline of 300 findings; the PR/CI changed-line gate above is clean. A full local make test-go also reached unrelated macOS-sensitive failures in internal/jellycompat process-lock identity tests and fake-NVENC playback probes; all changed packages passed, and a transient internal/transcodenode timing failure passed in isolation.

A new screenshot/recording is not attached because capturing the transient toast would require triggering another metadata-changing live refresh. The behavior has already been live-tested; visual evidence can be added if maintainers require it.

Adversarial review

The diff review found two material issues and both were fixed before publishing:

  1. A background worker could release a failed target job after the interactive loop checked it, causing a false success. The loop now requeues target failures/backoff on every pass and has a regression test for the concurrent-worker handoff.
  2. The first optional-target SQL predicate could prevent efficient index use on the global path. Targeted and global claims now use fixed query shapes, backed by a dedicated target/status/due index.

The final pass also checked local artwork precedence, provider ordering within tiers, background/logo fallbacks, Complete Refresh ID remapping, error propagation, and per-mutation toast identity. No material findings remain.

Risks & follow-up

  • Metadata providers must emit the canonical optional includes_text field to distinguish language-tagged textless posters. Providers that do not emit it retain the current language-based fallback.
  • The index is created concurrently and the migration handles an invalid prior index safely.
  • No REST API contract, Android client, Apple client, deployment configuration, or database data is changed.
  • Coordinated TVDB and TMDB provider PRs will carry the provider-side signal.

AI Disclosure

  • Tool(s): Codex
  • Model(s): gpt-5.6
  • Involvement: AI-assisted
  • Adversarial review: Found and fixed a concurrent-worker false-success race and a planner-hostile optional SQL predicate; re-reviewed the final diff with no material findings remaining.

Checklist

  • I ran an adversarial AI review of the diff and summarized findings above.
  • I ran the repository verification commands and documented both passing gates and known upstream/environmental failures above.

Summary by CodeRabbit

  • New Features

    • Metadata refreshes now cache refreshed artwork automatically and report artwork-processing progress.
    • Artwork selection better prioritizes local images, text-bearing posters, preferred languages, and image ratings.
    • Image metadata can indicate whether artwork contains text.
    • Artwork processing retries pending work and reports failures clearly.
  • Bug Fixes

    • Improved handling of artwork refresh jobs, including targeted retries and recovery of interrupted processing.
    • Refresh notifications now update the existing loading message with success or error results.
  • Documentation

    • Added a changelog entry describing the updated metadata refresh and artwork behavior.

@coderabbitai

coderabbitai Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

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

Next review available in: 59 minutes

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

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

How can I continue?

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

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

How do review limits work?

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

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

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: eb33d0df-7315-4420-920f-b6e97be6d722

📥 Commits

Reviewing files that changed from the base of the PR and between 19766af and b1ca4fb.

📒 Files selected for processing (11)
  • docs/feature-changelog.md
  • internal/adminjob/item_refresh.go
  • internal/adminjob/item_refresh_test.go
  • internal/adminjob/runner.go
  • internal/metadata/image_cache_job_repo.go
  • internal/metadata/image_cache_processor.go
  • internal/metadata/image_cache_processor_test.go
  • internal/metadata/local_image_source_test.go
  • internal/metadata/service.go
  • web/src/hooks/queries/items.test.ts
  • web/src/hooks/queries/items.ts

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 28d4729e-efc2-449a-97dd-8d4ccc0fb39c

📥 Commits

Reviewing files that changed from the base of the PR and between d285d0c and 19766af.

📒 Files selected for processing (15)
  • cmd/silo/main.go
  • docs/feature-changelog.md
  • internal/adminjob/item_refresh.go
  • internal/adminjob/item_refresh_test.go
  • internal/metadata/image_cache_job_repo.go
  • internal/metadata/image_cache_processor.go
  • internal/metadata/image_cache_processor_test.go
  • internal/metadata/local_image_source_test.go
  • internal/metadata/plugin_provider.go
  • internal/metadata/plugin_provider_test.go
  • internal/metadata/service.go
  • internal/metadata/types.go
  • migrations/sql/20260819060028_add_metadata_image_cache_target_index.sql
  • web/src/hooks/queries/items.test.ts
  • web/src/hooks/queries/items.ts

Included review availability: Your plan provides up to 2 included reviews per hour; 1 remains after this review.


📝 Walkthrough

Walkthrough

Metadata refresh now selects artwork by type, language, provider, rating, and text presence. It then caches artwork for the refreshed content target, reports cache failures, and updates web notifications from loading to success or failure.

Changes

Metadata refresh artwork

Layer / File(s) Summary
Language-aware artwork selection
internal/metadata/types.go, internal/metadata/plugin_provider.go, internal/metadata/service.go, internal/metadata/*_test.go
RemoteImage records text presence. Image selection prioritizes local artwork, requested languages, English, neutral images, provider order, and ratings according to image type.
Target-scoped artwork cache processing
internal/metadata/image_cache_job_repo.go, internal/metadata/image_cache_processor.go, internal/metadata/image_cache_processor_test.go, migrations/sql/20260819060028_add_metadata_image_cache_target_index.sql
The cache processor retries, claims, processes, monitors, and reports jobs for one content target. Repository queries support target filtering and use the new index.
Refresh executor artwork stage
internal/adminjob/item_refresh.go, internal/adminjob/item_refresh_test.go, cmd/silo/main.go, docs/feature-changelog.md
The refresh executor optionally caches refreshed artwork as a fourth progress stage and returns wrapped cache errors. The application wires the processor into the executor.
Refresh notification lifecycle
web/src/hooks/queries/items.ts, web/src/hooks/queries/items.test.ts
Refresh mutations show a loading toast and replace it with the final success or failure notification.

Estimated code review effort: 4 (Complex) | ~45 minutes

Merge Risk: ⚪ Minimal · up to 19766

The PR makes interactive metadata refreshes prioritize the selected item's artwork and improves poster selection and refresh feedback; no actionable merge-blocking risk remains after normal checks and review.

Sequence Diagram(s)

sequenceDiagram
  participant WebApp
  participant ItemRefreshExecutor
  participant ImageCacheProcessor
  participant ImageCacheJobRepository
  WebApp->>ItemRefreshExecutor: Start metadata refresh
  ItemRefreshExecutor->>ImageCacheProcessor: CacheTargetArtwork(targetContentID)
  ImageCacheProcessor->>ImageCacheJobRepository: Retry and claim target jobs
  ImageCacheJobRepository-->>ImageCacheProcessor: Claimed jobs and running state
  ImageCacheProcessor-->>ItemRefreshExecutor: Cache success or failure
  ItemRefreshExecutor-->>WebApp: Refresh result
  WebApp->>WebApp: Replace loading toast
Loading

Possibly related PRs

Suggested reviewers: quick104

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main changes to metadata artwork selection and refresh caching.
✨ 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.

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Review follow-ups on this branch.

An artwork failure no longer abandons a committed metadata refresh. Returning
the error from the last step jumped over the cache invalidation, both catalog
events, and the result payload -- including the remapped detail content id --
so a single 404 on a poster left the client sitting on an item id that no
longer resolved, with every query cache entry stale. The failure is now carried
on the result as a warning and surfaced as one in the UI; the refresh itself
still completes.

The target-scoped wait now reaches a series' children. Season, episode, and
localization jobs are queued under their own content ids with series_id
pointing at the series, so filtering on target_content_id alone meant a series
refresh waited for the two series-level rows, found nothing else, and reported
success while every episode still sat behind the global backlog -- the case
this branch set out to fix. Scope matching now covers both columns, which the
existing (series_id, status) index serves.

That wait is bounded. It had no deadline beyond the fifteen-minute lease and
polled four statements at 10Hz, so a worker that died holding a job parked an
interactive refresh on a spinner for the full lease. It now backs off from
100ms to 2s, gives up after 30s without progress, and reports the remainder as
pending rather than blocking.

retryTargetNow runs once per refresh instead of once per poll, and no longer
resets attempt_count or clears last_error. Running it every pass wiped backoff
that background workers had deliberately set on jobs that merely share a
target.

Backdrop selection has its terminal tier back. Narrowing it to language-neutral
with no fallback meant an item whose backdrops are all language-tagged -- common
for animation and title-card art -- kept an empty backdrop path permanently, and
no per-language localization row could ever pick one. Language-neutral still
wins; a tagged backdrop now beats none.

The step count reflects whether caching will actually run rather than whether
the cacher object exists, since it is wired whenever object storage is
configured regardless of metadata.cache_images. Failure and completion totals
track what the executor published, so progress no longer jumps from 4/4 back to
0/3.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Quick104 Quick104 mentioned this pull request Aug 19, 2026
2 tasks done
@Quick104

Copy link
Copy Markdown
Contributor

Pushed review fixes to this branch (b1ca4fb3)

I reviewed this branch, found seven defects, and pushed fixes rather than leaving them as comments. Happy to drop the commit if you'd rather take them yourself.

I did not touch the migration (verified correct — single file, NO TRANSACTION on both the concurrent create and the drop, StatementBegin-wrapped DO block, and the column order serves all four new predicates) or the poster tier ordering, which is a product call — see the bottom.

What changed

  1. An artwork failure abandoned a committed refresh (item_refresh.go:557). CacheTargetArtwork's error returned directly, jumping over publish(EventScanComplete/EventMetadataUpdated), both catalog publishes, and the result payload. Since web onSuccess owns every invalidateQueries and the onReplaced(detailContentID) navigation, a Complete Refresh that remapped old-episode-id → new-episode-id and then hit one 404 poster left the browser on an id that no longer resolved, with every cache entry stale. The failure is now a warning on the result, surfaced as one in the UI; the refresh completes.

  2. The target-scoped wait never reached a series' children (image_cache_processor.go:254) — the case the changelog claims to fix. Season and episode jobs are enqueued under their own content ids (service.go:4400,4419) with series_id pointing at the series, so filtering target_content_id alone meant a series refresh claimed the two series-level rows, found nothing, and reported success while 60 episode stills sat behind the global backlog. Scope now matches either column; the existing (series_id, status) index serves it. Person jobs have an empty series_id and stay out of scope.

  3. The wait was unbounded and hot-polled (:288-301). No deadline beyond the 15-minute lease, and four statements per 100ms pass. A worker killed mid-download parked an interactive refresh on a spinner for the full lease. Now backs off 100ms→2s, gives up after 30s without progress, and returns ErrTargetArtworkPending so the queue finishes the rest.

  4. retryTargetNow cleared backoff on unrelated jobs (image_cache_job_repo.go:343). It reset attempt_count = 0, next_attempt_at = NOW(), and last_error = '' for every row sharing the target, on every pass. It now runs once up front and preserves attempt_count/last_error — a manual refresh buys one immediate retry, it doesn't refund a budget a background worker already spent.

  5. Backdrop selection lost its terminal tier (service.go:6819). Narrowed to languageNeutral with no catch-all, while poster and logo kept theirs. An item whose backdrops are all language-tagged — common for animation and title-card art — kept an empty backdrop permanently, and no media_item_localizations row could ever pick a language-specific one. Language-neutral still wins; a tagged backdrop now beats none.

  6. Step count lied when caching was off (item_refresh.go:491). The cacher is wired whenever S3Public != nil, independently of metadata.cache_images, so every refresh advertised 4 steps and published "Caching refreshed artwork" at 4/4 while CacheTargetArtwork returned immediately. Now gated on whether caching would actually run.

  7. Failure progress went backwards (runner.go:756). containsPhase is a plain strings.Contains and matched none of the phases for the new message, so a job that had just published 4/4 finalized as 0/3. Totals now track what the executor published.

Worth your attention

  • Fix 2 makes a series refresh do materially more synchronous work. Waiting for every season poster and episode still is the point, but a 200-episode series now spends minutes on "Caching refreshed artwork" (16 per claim, concurrency 3) where it used to return immediately and lie. The 30s idle timeout bounds stalls, not total work, since it resets on progress. That's the intended trade but it deserves a conscious sign-off, since it's the most visible behavior change here.
  • The fallback backdrop tier isn't language-preference-ordered. Within hasLanguage it's first-provider-then-max-rating, so an English library with only de and fr backdrops picks arbitrarily. logoFilters orders by preferred-then-English. Not a regression — before this it got nothing — but an asymmetry worth closing.
  • The new SQL has no test that executes it. I checked all four statements by hand and against every enqueue site, but the (target_content_id = $n OR series_id = $n) predicate has never run against a database here.
  • Unchanged, needs your call: the new poster tier 3 (posterHasText) sits above posterTextless, so an English library with no English poster now deterministically prefers a Japanese-titled poster over a clean textless one, and local_image_source_test.go enshrines it. The old behavior was inconsistent rather than correct, so this reads as deliberate — but it's a taste decision that will show up in real libraries, and it shouldn't be settled by a test name.

go build ./internal/..., go vet, gofmt, go test -race on adminjob + metadata, tsc --noEmit, prettier, eslint, and the affected vitest files all pass. Two jellycompat failures are pre-existing on main (macOS PID reuse) and untouched by this diff.

Note this branch and #668 both rewrite image_cache_job_repo.go in opposite directions — #668 decides what stays parked, this adds a per-target revival path. They merge textually clean, so the order they land in matters.

Review and fixes produced with AI assistance (Claude), verified by building and running the branch. See docs/ai-contributions.md.

@Quick104
Quick104 merged commit 92b50f9 into Silo-Server:main Aug 19, 2026
1 check passed
Quick104 added a commit to blurbery/silo-server that referenced this pull request Aug 19, 2026
Preserve target-scoped image-cache recovery from Silo-Server#676 while retaining the cooldown for jobs that exhaust their lease-expiry budget.
@Rhainland Rhainland mentioned this pull request Oct 23, 2026
9 tasks done
@blurbery
blurbery deleted the agent/metadata-artwork-refresh branch November 6, 2026 00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants