Skip to content

[codex] Expand provider image cache queue - #176

Merged
Quick104 merged 2 commits into
mainfrom
codex/metadata-image-cache-queue
Jun 18, 2026
Merged

Quick104 merged 2 commits into
mainfrom
codex/metadata-image-cache-queue

Conversation

@Quick104

@Quick104 Quick104 commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Move provider-origin metadata artwork through the durable image-cache queue instead of inline caching.
  • Expand cache coverage to item poster/backdrop/logo, localized artwork, season posters, episode stills, and people profile photos.
  • Add source-path tracking, language-scoped cache keys, profile image support, conditional writebacks, retry/backoff handling, and startup/interval task processing.
  • Replace inline remote artwork caching in metadata/person/ebook/audiobook/manga enrichment flows with queue enqueueing.
  • Fix existing-artwork discovery so already-succeeded jobs do not starve later targets like people/profile photos.

Root Cause

Episode and season artwork cache work was being performed inline during metadata refreshes and later queue discovery still scanned already-succeeded rows first. Large catalogs could spend cache runs repeatedly re-reading already-cached episode rows, which delayed or prevented later image types from being reached.

Validation

  • GOWORK=off go test ./internal/metadata ./internal/imagecache ./internal/catalog ./internal/audiobooks ./internal/ebooks ./internal/manga ./internal/taskmanager/tasks ./cmd/silo ./migrations
  • git diff --check
  • Deployed to dev with make dev-deploy and verified live DB state.

Live validation after deploy:

  • Item poster visible provider paths dropped from 6,172 to 25.
  • Item backdrop visible provider paths dropped from 168 to 5.
  • Episode still visible provider paths dropped from 577 to 83.
  • Season poster visible provider paths dropped to 2.
  • People/profile cache jobs are now being discovered and processed: observed 357 succeeded, 221 running, and queued backlog continuing to drain.
  • Sample people rows now write tmdb/people/.../profile/original.webp while retaining photo_source_path = tmdb://profile/....

Full GOWORK=off go test ./... was also run; unrelated environment-sensitive failures remain in internal/jellycompat process-lock tests and internal/playback NVENC probe tests.

Impact

Scans and metadata refreshes no longer block on large remote image downloads/uploads. Provider images are cached asynchronously with durable retries, while manual/generated/local/S3 artwork is excluded from recaching.

AI Use

Implemented with AI assistance in Codex.

Summary by CodeRabbit

  • New Features
    • Asynchronous metadata artwork caching via background job processing (items, seasons/episodes, people, and enriched audiobooks/ebooks/manga), instead of immediate downloads.
    • Support for caching “profile” images in addition to posters/stills/logos/backdrops.
    • Language-scoped caching for localized artwork (saved under language-specific storage paths).
    • Automatic retry handling for transient object-storage upload failures, improving caching reliability.

@coderabbitai

coderabbitai Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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: 52afc406-14fc-447a-930d-beb4d553822b

📥 Commits

Reviewing files that changed from the base of the PR and between c56542a and 953e52a.

📒 Files selected for processing (6)
  • cmd/silo/main.go
  • internal/imagecache/imagecache.go
  • internal/metadata/image_cache_job_repo.go
  • internal/metadata/image_cache_processor.go
  • internal/metadata/image_cache_processor_test.go
  • migrations/sql/20260617184537_metadata_image_cache_queue.sql
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/metadata/image_cache_processor_test.go
  • cmd/silo/main.go
  • internal/imagecache/imagecache.go

📝 Walkthrough

Walkthrough

Introduces an asynchronous metadata image caching pipeline: a metadata_image_cache_jobs queue table, a ImageCacheJobRepository, and an ImageCacheProcessor that claims, downloads, and uploads provider artwork to S3 in the background. All relevant models and repositories gain *_source_path provenance fields to track where cached artwork originated. The metadata service, person refresh service, and audiobook/ebook/manga enrichers are refactored to enqueue jobs instead of caching inline. A new CacheMetadataImagesTask drives the processor on a schedule. Two DB migrations add the queue infrastructure and source-path columns. A concurrent fix to trigger goroutine variable capture prevents races on stop/restart cycles.

Changes

Metadata Image Cache Pipeline

Layer / File(s) Summary
Data shapes: models, types, update struct
internal/models/media.go, internal/models/metadata_image_cache_job.go, internal/metadata/types.go, internal/catalog/update.go
Adds *SourcePath fields to Person, MediaItem, Season, Episode, MediaItemLocalization, and SeasonLocalization. Introduces MetadataImageCacheJob model, ImageCacheJobEnqueuer interface, ImageProfile image type, Language on CacheImageRequest, and source-path fields on SeasonResult/EpisodeResult/PersonDetailResult. MetadataUpdate gains PosterSourcePath, BackdropSourcePath, and StillSourcePath pointer fields.
DB migrations
migrations/sql/20260617184537_metadata_image_cache_queue.sql, migrations/sql/20260617203000_expand_metadata_image_cache_jobs.sql
Migration 1 adds poster_source_path/still_source_path to seasons/episodes and creates metadata_image_cache_jobs with check constraints, uniqueness, and queue indexes. Migration 2 adds *_source_path columns to media_items, people, media_item_localizations, and season_localizations with backfill, and expands metadata_image_cache_jobs with target_language and updated constraints.
Catalog repository source-path extensions
internal/catalog/item_repo.go, internal/catalog/season_repo.go, internal/catalog/episode_repo.go, internal/catalog/localization_repo.go, internal/catalog/person_repo.go, internal/catalog/localize.go, internal/catalog/episode_catalog_source.go
All repos add new *_source_path columns to select/scan/upsert/bulk-upsert paths. Each gains an UpdateXxxIfSourceMatches method that conditionally overwrites cached artwork only when the stored source matches. UpdateMetadata clears source paths when a path override omits an explicit source. Localization merge propagates source paths onto cloned models.
Image cache job repository
internal/metadata/image_cache_job_repo.go, internal/metadata/image_cache_job_repo_test.go
ImageCacheJobRepository implements Enqueue/EnqueueBatch (input normalization, chunked upsert), ClaimDue (lease recovery + FOR UPDATE SKIP LOCKED), MarkSucceeded/MarkFailed (exponential backoff), DeleteSucceededBefore, and EnqueueExistingProviderArtwork (backfill query across all entity types filtered to provider URL schemes). Tests cover retry delay, normalization, and migration SQL content.
ImageCacheProcessor: claim, cache, dispatch, mark
internal/metadata/image_cache_processor.go, internal/metadata/image_cache_processor_test.go
Defines pluggable updater interfaces and ImageCacheProcessorTargets. RunOnce enqueues existing artwork, claims jobs, processes them concurrently (semaphore-bounded), dispatches per TargetType to UpdateIfSourceMatches, and marks jobs succeeded/skipped/failed. RunUntilIdle loops until idle or maxRuntime. Full test suite covers all target types, skip/fail/empty-result paths, and RunUntilIdle drain.
Metadata service: sync-to-async caching refactor
internal/metadata/service.go, internal/metadata/person_refresh.go, internal/metadata/merge.go, internal/metadata/plugin_provider.go, internal/metadata/fallback_unification_test.go, internal/metadata/image_cache_enqueue_test.go
Replaces inline cacheSeriesChildImages/cachePersonPhoto calls with enqueueItemImages, enqueueSeriesChildImages, and enqueuePersonPhoto. Adds preserveCachedArtwork, prepareItemImagesForQueue, and providerIDFromPluginURL helpers. persistSeasonsAndEpisodes accepts series *models.MediaItem and builds image jobs for seasons/episodes/localizations. ImageTypeToString/ImageTypeFromString gain ImageProfile. Person merge and plugin provider include PhotoSourcePath and "profile" kind.
imagecache layer: language, retry, profile; enrichers async wiring
internal/imagecache/imagecache.go, internal/imagecache/imagecache_test.go, internal/audiobooks/enrichment.go, internal/ebooks/enrichment.go, internal/manga/enrichment.go
buildBasePath inserts localizations/{lang} segments for localized requests. putObjectWithRetry retries S3 uploads up to 3 times. ImageProfile type maps to "profile" with variant widths. All three enrichers replace synchronous cacheRemotePoster with enqueueRemoteArtwork, gain SetImageCacheJobEnqueuer, and write *SourcePath fields in persist. Tests cover localized path, profile image path, and transient S3 retry.
CacheMetadataImagesTask and server wiring
internal/taskmanager/tasks/cache_metadata_images.go, internal/taskmanager/tasks/cache_metadata_images_test.go, cmd/silo/main.go
CacheMetadataImagesTask runs RunUntilIdle on startup and a fixed interval with a nil-runner guard and hostname-derived workerID. cmd/silo/main.go creates ImageCacheJobRepository and ImageCacheProcessor with all catalog targets when S3 is available, sets the enqueuer on enrichers and person refresh service, and conditionally registers the task. Tests validate task metadata and progress message format.

Trigger Goroutine Closure Fix

Layer / File(s) Summary
Trigger goroutine local-variable capture
internal/taskmanager/triggers/interval.go, internal/taskmanager/triggers/daily.go, internal/taskmanager/triggers/startup.go, internal/taskmanager/triggers/weekly.go, internal/taskmanager/triggers/interval_test.go
All four trigger Start methods now create stopCh and timer as local variables before the goroutine, capture them by closure instead of reading struct fields inside the goroutine, and assign them to the struct fields for external use. A regression test verifies the interval trigger fires correctly after stop/restart.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • Silo-Server/silo-server#128: Both PRs configure the config watcher to live-update metadata.cache_images to control the metadata auto image-caching behavior in the server.
  • Silo-Server/silo-server#138: Both PRs modify internal/manga/enrichment.go to handle remote artwork caching (this PR switching to async job enqueueing, the other introducing manga enrichment with poster/backdrop caching).
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: expanding the provider image cache queue system to handle more image types asynchronously.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/metadata-image-cache-queue

Comment @coderabbitai help to get the list of available commands and usage tips.

@Quick104
Quick104 marked this pull request as ready for review June 18, 2026 13:04

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c56542a090

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread cmd/silo/main.go
Comment on lines +1744 to +1745
if metadataImageCacheProcessor != nil {
taskMgr.Register(tasks.NewCacheMetadataImagesTask(metadataImageCacheProcessor))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Honor cache_images before scheduling automatic caching

When object storage is configured, this task is registered regardless of metadata.cache_images (which defaults to false). Its startup/interval executions call EnqueueExistingProviderArtwork, so merely configuring S3 causes the entire provider-artwork catalog to be downloaded and stored even when automatic image caching is disabled; the hot-reload flag only gates MetadataService enqueue sites and does not gate this task. Register or execute the processor conditionally on the setting, including configuration changes.

Useful? React with 👍 / 👎.

locked_by = '',
last_error = '',
updated_at = NOW()
WHERE id = $1

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Guard terminal updates with the claimed job version

If metadata changes an artwork source while its old job is running, EnqueueBatch rewrites the same row with the new source and requeues it, but the old worker later reaches this unconditional update and marks that new job succeeded after its source-matching target update was skipped. The new artwork then remains uncached until the succeeded row is eventually deleted. Both success and failure transitions should verify the claimed source/lease token or worker before updating the row.

Useful? React with 👍 / 👎.

}
stats.EnqueuedExisting = enqueued

jobs, err := p.jobs.ClaimDue(ctx, workerID, claimLimit)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Claim only work that fits inside the lease

The scheduled task passes a claim limit of 1,000 with concurrency 12, and this call leases every selected row before most of them can enter the semaphore. With the 30-second download timeout, jobs after roughly the first 360 can wait longer than the 15-minute lease before processing even starts; another worker calling recoverExpiredRunning can then reclaim them, causing duplicate downloads and competing terminal writes. Claim incrementally near the concurrency level or renew leases for jobs waiting in the local queue.

Useful? React with 👍 / 👎.

func (p *ImageCacheProcessor) cleanupSucceeded(ctx context.Context, stats *ImageCacheRunStats) {
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
deleted, err := p.jobs.DeleteSucceededBefore(cleanupCtx, time.Now().Add(-30*24*time.Hour), 1000)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Retain deduplication state when pruning successes

Deleting succeeded rows here removes the only marker used by EnqueueExistingProviderArtwork to distinguish already-cached source paths. Because successful writeback deliberately retains each *_source_path, the next batch sees j.id IS NULL, recreates the job, and downloads/uploads the same image again; this repeats for the catalog every 30 days. Preserve a compact success marker or make discovery verify the cached destination before pruning.

Useful? React with 👍 / 👎.

}
}

result, err := p.cacher.CacheImage(ctx, CacheImageRequest{

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Avoid uploading stale jobs to the live artwork key

A source-match check happens only after CacheImage has uploaded variants to the deterministic live key. If an admin applies another image while this job is in flight, the stale job can overwrite the newly selected object even though UpdateArtworkIfSourceMatches subsequently returns false; the database continues pointing at that key, so the stale image is displayed. Verify ownership before upload or write to versioned/source-specific keys and publish them only after the conditional update.

Useful? React with 👍 / 👎.

if err := rows.Err(); err != nil {
return 0, fmt.Errorf("iterating existing provider artwork: %w", err)
}
return r.EnqueueBatch(ctx, inputs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Release query rows before enqueueing the batch

rows retains its pgxpool connection until this function returns, but the return expression calls EnqueueBatch first and needs another connection. With a one-connection pool, or when every other connection is occupied, the cache task waits for a connection while holding the one that could satisfy the request; its runtime budget cannot interrupt this because the task context has no deadline. Close the rows after scanning and before calling EnqueueBatch.

Useful? React with 👍 / 👎.

Comment on lines +400 to +402
mi.tmdb_id,
mi.tvdb_id,
mi.imdb_id

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Coalesce nullable IDs before scanning discovery rows

The media_items external-ID columns are nullable, but this query returns them directly and later scans all three into Go strings. When an artwork candidate has a NULL tmdb_id, tvdb_id, or imdb_id—which is valid for existing and legacy rows—pgx fails the scan, aborting EnqueueExistingProviderArtwork and therefore the entire scheduled cache run before any jobs are claimed. Select COALESCE(..., '') for these columns or scan nullable values.

Useful? React with 👍 / 👎.

Comment on lines +403 to +405
FROM media_items mi
WHERE mi.poster_source_path LIKE '%://%'
AND lower(mi.poster_source_path) NOT LIKE ALL (ARRAY['s3://%', 'file://%', 'local://%', 'upload://%', 'generated://%'])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid rescanning the full catalog for every cache batch

EnqueueExistingProviderArtwork builds its candidates from multiple full-table branches using non-indexable LIKE '%://%' predicates, and RunUntilIdle invokes this query again for every 1,000-job batch. Large backlogs therefore repeatedly rescan and sort the entire item, localization, season, episode, and people catalogs during one run, while an idle installation still performs the same scans every minute. Discover work incrementally from indexed state or run the catalog sweep less frequently than queue draining.

Useful? React with 👍 / 👎.

@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 (2)
internal/metadata/image_cache_enqueue_test.go (1)

91-99: ⚡ Quick win

Assert the full queued job contract here.

This test would still pass if the jobs used the wrong SourcePath, TargetType, or ImageType. Add assertions for those fields so regressions in the processor payload are caught close to the enqueue path.

Suggested test hardening
 	if enqueuer.inputs[0].TargetContentID != season.ContentID {
 		t.Fatalf("season job target = %q, want %q", enqueuer.inputs[0].TargetContentID, season.ContentID)
 	}
+	if enqueuer.inputs[0].TargetType != ImageCacheTargetSeason ||
+		enqueuer.inputs[0].ImageType != ImageCacheImagePoster ||
+		enqueuer.inputs[0].SourcePath != "tvdb://banners/seasons/1.jpg" {
+		t.Fatalf("season job = %#v", enqueuer.inputs[0])
+	}
 	if enqueuer.inputs[1].TargetContentID != episode.ContentID {
 		t.Fatalf("episode job target = %q, want %q", enqueuer.inputs[1].TargetContentID, episode.ContentID)
 	}
+	if enqueuer.inputs[1].TargetType != ImageCacheTargetEpisode ||
+		enqueuer.inputs[1].ImageType != ImageCacheImageStill ||
+		enqueuer.inputs[1].SourcePath != "tvdb://banners/episodes/1.jpg" {
+		t.Fatalf("episode job = %#v", enqueuer.inputs[1])
+	}
🤖 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/image_cache_enqueue_test.go` around lines 91 - 99, The test
assertions in the enqueue validation block only verify the TargetContentID field
for both jobs but do not validate the complete job contract. Add additional
assertions for the SourcePath, TargetType, and ImageType fields for both
enqueuer.inputs[0] (the season job) and enqueuer.inputs[1] (the episode job) to
ensure regressions in the processor payload are caught at the enqueue path. Each
field should be checked against the corresponding expected value from the season
and episode objects to ensure the full job payload is correct.
internal/manga/enrichment.go (1)

745-777: ⚡ Quick win

Batch the full-enrichment image enqueue.

enqueueRemoteArtwork currently calls EnqueueBatch once per image via enqueueRemoteImage, so a result with poster, backdrop, and logo performs three queue upserts. Build the inputs and enqueue once.

♻️ Proposed refactor
 func (e *Enricher) enqueueRemoteArtwork(ctx context.Context, contentID string, result *metadata.MetadataResult) {
-	if e == nil || result == nil || contentID == "" {
+	if e == nil || e.imageCacheJobs == nil || result == nil || contentID == "" {
 		return
 	}
-	e.enqueueRemoteImage(ctx, contentID, result.PosterPath, metadata.ImagePoster)
-	e.enqueueRemoteImage(ctx, contentID, result.BackdropPath, metadata.ImageBackdrop)
-	e.enqueueRemoteImage(ctx, contentID, result.LogoPath, metadata.ImageLogo)
+	inputs := make([]metadata.EnqueueImageCacheJobInput, 0, 3)
+	add := func(sourcePath string, imageType metadata.ImageType) {
+		if !isRemoteHTTPImage(sourcePath) {
+			return
+		}
+		inputs = append(inputs, metadata.EnqueueImageCacheJobInput{
+			TargetType:        metadata.ImageCacheTargetItem,
+			TargetContentID:   contentID,
+			SeriesID:          contentID,
+			SourcePath:        sourcePath,
+			ProviderID:        mangaMetadataImageProviderID,
+			ProviderContentID: contentID,
+			ContentType:       mangaContentType(),
+			ImageType:         metadata.ImageTypeToString(imageType),
+		})
+	}
+	add(result.PosterPath, metadata.ImagePoster)
+	add(result.BackdropPath, metadata.ImageBackdrop)
+	add(result.LogoPath, metadata.ImageLogo)
+	if len(inputs) == 0 {
+		return
+	}
+
+	enqueueCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
+	defer cancel()
+	if _, err := e.imageCacheJobs.EnqueueBatch(enqueueCtx, inputs); err != nil {
+		slog.Warn("manga enrichment: failed to enqueue image cache jobs",
+			"content_id", contentID,
+			"count", len(inputs),
+			"error", err,
+		)
+	}
 }
🤖 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 745 - 777, The
enqueueRemoteArtwork function currently calls enqueueRemoteImage three separate
times (for poster, backdrop, and logo paths), resulting in three separate
EnqueueBatch calls and three database upserts. Refactor enqueueRemoteArtwork to
build all the metadata.EnqueueImageCacheJobInput objects in a single slice
within the function itself, then call e.imageCacheJobs.EnqueueBatch once with
all inputs together. This consolidates the remote image enqueuing into a single
batch operation instead of three separate ones, improving efficiency.
🤖 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/imagecache/imagecache.go`:
- Around line 281-298: The putObjectWithRetry function currently creates and
waits for a backoff timer even on the final attempt (attempt=2), unnecessarily
delaying the return of the permanent error. Modify the function to skip the
timer creation and delay on the last attempt by adding a condition to check if
this is the final iteration before creating the timer. When it is the final
attempt and PutObject fails, the function should immediately return the lastErr
without sleeping.

In `@internal/metadata/image_cache_job_repo.go`:
- Around line 153-225: The SQL update operations in the conflict resolution and
terminal job handlers lack guards against stale workers claiming old
source_paths and incorrectly marking newly queued replacement jobs as complete.
Add WHERE clause conditions in the `MarkSucceeded` and `MarkFailed` operations
to include verification of the claimed source_path and/or lease owner identity,
ensuring that only the worker who originally claimed a particular source can
mark it as terminal. Thread the claimed source_path and worker identifier
(locked_by value) through the processor interface and update the WHERE clauses
in these methods to match against these values in addition to the job id,
preventing a stale worker from mutating a row that has been repurposed with new
content.

In `@internal/metadata/image_cache_processor.go`:
- Around line 145-159: The issue is that jobs are claimed as running before it's
known whether they will actually be processed, so when a goroutine returns due
to context cancellation before acquiring the semaphore token, the claimed job
remains locked. Fix this by either acquiring the semaphore before spawning the
goroutine (move the semaphore acquisition logic outside the goroutine), or
explicitly handle the early return case in the context cancellation branch to
fail or requeue the claimed job. This ensures no jobs are left locked when
cancellation occurs before the semaphore token is obtained in the goroutine.

In `@internal/metadata/merge.go`:
- Around line 198-200: The `PhotoSourcePath` field is being merged independently
from `PhotoPath`, but it should be coupled to ensure they always represent the
same source image. Modify the merge logic so that `PhotoSourcePath` is only
updated when `PhotoPath` is accepted according to the merge mode. Instead of
calling mergeScalar separately for `PhotoSourcePath`, make its merge conditional
on whether `PhotoPath` was actually accepted, preventing the destination from
inheriting source provenance for a different photo. This same coupling should be
applied to the other related merge locations mentioned (around lines 365-370).

In `@migrations/sql/20260617184537_metadata_image_cache_queue.sql`:
- Around line 8-16: The UPDATE statements for the seasons table (updating
poster_source_path) and episodes table (updating still_source_path) are missing
the exclusion pattern that filters out S3 and special URL schemes. Add the
clause AND lower(poster_path) NOT LIKE ALL (ARRAY['s3://%', 'file://%',
'local://%', 'upload://%', 'generated://%']) to the WHERE condition of the
seasons UPDATE statement, and add AND lower(still_path) NOT LIKE ALL
(ARRAY['s3://%', 'file://%', 'local://%', 'upload://%', 'generated://%']) to the
WHERE condition of the episodes UPDATE statement to match the exclusion logic
used in other backfill migrations and ensure cached or system-generated artwork
is not recached.

---

Nitpick comments:
In `@internal/manga/enrichment.go`:
- Around line 745-777: The enqueueRemoteArtwork function currently calls
enqueueRemoteImage three separate times (for poster, backdrop, and logo paths),
resulting in three separate EnqueueBatch calls and three database upserts.
Refactor enqueueRemoteArtwork to build all the
metadata.EnqueueImageCacheJobInput objects in a single slice within the function
itself, then call e.imageCacheJobs.EnqueueBatch once with all inputs together.
This consolidates the remote image enqueuing into a single batch operation
instead of three separate ones, improving efficiency.

In `@internal/metadata/image_cache_enqueue_test.go`:
- Around line 91-99: The test assertions in the enqueue validation block only
verify the TargetContentID field for both jobs but do not validate the complete
job contract. Add additional assertions for the SourcePath, TargetType, and
ImageType fields for both enqueuer.inputs[0] (the season job) and
enqueuer.inputs[1] (the episode job) to ensure regressions in the processor
payload are caught at the enqueue path. Each field should be checked against the
corresponding expected value from the season and episode objects to ensure the
full job payload is correct.
🪄 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: 933cc980-f44f-4e43-91cb-a26b1dabc29c

📥 Commits

Reviewing files that changed from the base of the PR and between 381136a and c56542a.

📒 Files selected for processing (36)
  • cmd/silo/main.go
  • internal/audiobooks/enrichment.go
  • internal/catalog/episode_catalog_source.go
  • internal/catalog/episode_repo.go
  • internal/catalog/item_repo.go
  • internal/catalog/localization_repo.go
  • internal/catalog/localize.go
  • internal/catalog/person_repo.go
  • internal/catalog/season_repo.go
  • internal/catalog/update.go
  • internal/ebooks/enrichment.go
  • internal/imagecache/imagecache.go
  • internal/imagecache/imagecache_test.go
  • internal/manga/enrichment.go
  • internal/metadata/fallback_unification_test.go
  • internal/metadata/image_cache_enqueue_test.go
  • internal/metadata/image_cache_job_repo.go
  • internal/metadata/image_cache_job_repo_test.go
  • internal/metadata/image_cache_processor.go
  • internal/metadata/image_cache_processor_test.go
  • internal/metadata/merge.go
  • internal/metadata/person_refresh.go
  • internal/metadata/plugin_provider.go
  • internal/metadata/service.go
  • internal/metadata/types.go
  • internal/models/media.go
  • internal/models/metadata_image_cache_job.go
  • internal/taskmanager/tasks/cache_metadata_images.go
  • internal/taskmanager/tasks/cache_metadata_images_test.go
  • internal/taskmanager/triggers/daily.go
  • internal/taskmanager/triggers/interval.go
  • internal/taskmanager/triggers/interval_test.go
  • internal/taskmanager/triggers/startup.go
  • internal/taskmanager/triggers/weekly.go
  • migrations/sql/20260617184537_metadata_image_cache_queue.sql
  • migrations/sql/20260617203000_expand_metadata_image_cache_jobs.sql

Comment thread internal/imagecache/imagecache.go Resolved
Comment on lines 198 to 200
mergeScalar(&target.PhotoPath, source.PhotoPath, mode)
mergeScalar(&target.PhotoSourcePath, source.PhotoSourcePath, mode)
mergeScalar(&target.PhotoThumbhash, source.PhotoThumbhash, mode)

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Keep PhotoSourcePath coupled to the photo path it describes.

PhotoSourcePath is merged even when PhotoPath is not accepted, so a destination with an existing photo can inherit provenance for a different source image. That can make the async cache worker update/cache the wrong photo source.

Suggested fix
-	mergeScalar(&target.PhotoPath, source.PhotoPath, mode)
-	mergeScalar(&target.PhotoSourcePath, source.PhotoSourcePath, mode)
+	beforePhotoPath := target.PhotoPath
+	mergeScalar(&target.PhotoPath, source.PhotoPath, mode)
+	if target.PhotoPath == source.PhotoPath || beforePhotoPath == source.PhotoPath {
+		mergeScalar(&target.PhotoSourcePath, source.PhotoSourcePath, mode)
+	}
 	mergeScalar(&target.PhotoThumbhash, source.PhotoThumbhash, mode)
 	if dst.PhotoPath == "" {
 		dst.PhotoPath = src.PhotoPath
+		dst.PhotoSourcePath = src.PhotoSourcePath
 	}
-	if dst.PhotoSourcePath == "" {
+	if dst.PhotoSourcePath == "" && dst.PhotoPath == src.PhotoPath {
 		dst.PhotoSourcePath = src.PhotoSourcePath
 	}

Also applies to: 365-370

🤖 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/merge.go` around lines 198 - 200, The `PhotoSourcePath`
field is being merged independently from `PhotoPath`, but it should be coupled
to ensure they always represent the same source image. Modify the merge logic so
that `PhotoSourcePath` is only updated when `PhotoPath` is accepted according to
the merge mode. Instead of calling mergeScalar separately for `PhotoSourcePath`,
make its merge conditional on whether `PhotoPath` was actually accepted,
preventing the destination from inheriting source provenance for a different
photo. This same coupling should be applied to the other related merge locations
mentioned (around lines 365-370).

@Quick104

Copy link
Copy Markdown
Contributor Author

Code review

No issues found. Checked for bugs and CLAUDE.md compliance.

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

Addresses bug-review feedback from Codex/CodeRabbit on the metadata image
cache pipeline. All findings validated against the code before fixing;
false positives (rows/connection deadlock, PhotoSourcePath merge coupling)
were confirmed non-issues and left unchanged.

- Honor metadata.cache_images for the background processor. The
  cache_metadata_images task was registered whenever S3 was configured,
  so merely enabling object storage downloaded the entire provider-artwork
  catalog even with caching disabled. Add ImageCacheProcessor.SetEnabled,
  gate RunOnce/RunUntilIdle on it, and wire it (with hot reload) from
  cfg.Metadata.CacheImages in main.go.
- Guard terminal job updates with lease ownership. EnqueueBatch can
  repurpose a running row with a new source; MarkSucceeded/MarkFailed
  keyed on id alone let a stale worker finalize the replacement job and
  drop the new artwork. Thread locked_by through and add
  status='running' AND locked_by=$n guards.
- Avoid uploading stale jobs onto the live artwork key. Verify the
  target still references the job's source (CurrentTargetSourcePath)
  before CacheImage, so a job whose source an admin/refresh already
  replaced cannot overwrite the deterministic storage object.
- COALESCE nullable external IDs in EnqueueExistingProviderArtwork. A
  NULL tmdb_id/tvdb_id/imdb_id on any candidate failed the scan and
  aborted the whole cache run; matches the existing item_repo pattern.
- Stop re-downloading the catalog every 30 days. Discovery now skips
  targets whose *_path is already a cached relative path, making the
  cached row the durable dedup marker instead of the prunable job row.
- Decouple catalog sweeps from queue draining. RunOnce no longer runs
  discovery per batch; RunUntilIdle sweeps only when the queue drains and
  throttles full sweeps to every 15m, so idle installs stop full-scanning
  every entity table each minute.
- Requeue claimed-but-unstarted jobs on cancellation. Acquire the
  semaphore before spawning workers and RequeueClaimed any jobs not yet
  started, instead of leaving them locked until the 15m lease expires.
- Skip the backoff sleep after the final upload attempt in
  putObjectWithRetry (saves ~1.5s on permanent failures).
- Add the s3/file/local/upload/generated exclusion to the seasons and
  episodes backfill in migration 20260617184537 for consistency with the
  later migration (the bad backfill was inert downstream, but the
  asymmetry is removed).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Quick104
Quick104 merged commit 2fa0152 into main Jun 18, 2026
1 check passed
@Quick104
Quick104 deleted the codex/metadata-image-cache-queue branch June 18, 2026 14:08
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
* feat(metadata): expand provider image cache queue

* fix(metadata): harden provider image cache queue

Addresses bug-review feedback from Codex/CodeRabbit on the metadata image
cache pipeline. All findings validated against the code before fixing;
false positives (rows/connection deadlock, PhotoSourcePath merge coupling)
were confirmed non-issues and left unchanged.

- Honor metadata.cache_images for the background processor. The
  cache_metadata_images task was registered whenever S3 was configured,
  so merely enabling object storage downloaded the entire provider-artwork
  catalog even with caching disabled. Add ImageCacheProcessor.SetEnabled,
  gate RunOnce/RunUntilIdle on it, and wire it (with hot reload) from
  cfg.Metadata.CacheImages in main.go.
- Guard terminal job updates with lease ownership. EnqueueBatch can
  repurpose a running row with a new source; MarkSucceeded/MarkFailed
  keyed on id alone let a stale worker finalize the replacement job and
  drop the new artwork. Thread locked_by through and add
  status='running' AND locked_by=$n guards.
- Avoid uploading stale jobs onto the live artwork key. Verify the
  target still references the job's source (CurrentTargetSourcePath)
  before CacheImage, so a job whose source an admin/refresh already
  replaced cannot overwrite the deterministic storage object.
- COALESCE nullable external IDs in EnqueueExistingProviderArtwork. A
  NULL tmdb_id/tvdb_id/imdb_id on any candidate failed the scan and
  aborted the whole cache run; matches the existing item_repo pattern.
- Stop re-downloading the catalog every 30 days. Discovery now skips
  targets whose *_path is already a cached relative path, making the
  cached row the durable dedup marker instead of the prunable job row.
- Decouple catalog sweeps from queue draining. RunOnce no longer runs
  discovery per batch; RunUntilIdle sweeps only when the queue drains and
  throttles full sweeps to every 15m, so idle installs stop full-scanning
  every entity table each minute.
- Requeue claimed-but-unstarted jobs on cancellation. Acquire the
  semaphore before spawning workers and RequeueClaimed any jobs not yet
  started, instead of leaving them locked until the 15m lease expires.
- Skip the backoff sleep after the final upload attempt in
  putObjectWithRetry (saves ~1.5s on permanent failures).
- Add the s3/file/local/upload/generated exclusion to the seasons and
  episodes backfill in migration 20260617184537 for consistency with the
  later migration (the bad backfill was inert downstream, but the
  asymmetry is removed).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
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.

1 participant