Skip to content

Reduce metadata image cache R2 churn - #249

Merged
Quick104 merged 2 commits into
Silo-Server:mainfrom
RXWatcher:r2-image-cache-cost-controls
Jul 1, 2026
Merged

Quick104 merged 2 commits into
Silo-Server:mainfrom
RXWatcher:r2-image-cache-cost-controls

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • skip uploading metadata image variants that already exist in object storage and report uploaded/existing counts
  • normalize provider artwork through libvips so SVG logos and unusual JPEGs can cache successfully
  • allow larger provider originals to download while capping cached original.webp dimensions below oversized source dimensions
  • requeue stale succeeded cache jobs during discovery when live artwork still points at provider URLs
  • defer stable provider failures (403/404/410/418) for a 7-day retry cooldown instead of hot-looping

Verification

  • GOWORK=off GOCACHE=/private/tmp/silo-go-build GOMODCACHE=/private/tmp/silo-go-mod go test ./internal/imagecache ./internal/imageutil ./internal/metadata ./internal/taskmanager/tasks

Summary by CodeRabbit

  • New Features

    • Image caching now reports how many variants were uploaded versus already present.
    • Progress updates include the new variant counts during metadata image caching.
  • Bug Fixes

    • Improved handling for larger images and SVGs during caching.
    • Cached preview hashes are now generated more consistently across image types.
    • Failed image-cache jobs are retried more intelligently, with longer delays for stable provider errors.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

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

Next review available in: 41 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 509f8a7e-b98e-4dd4-9ec0-d24685abf82d

📥 Commits

Reviewing files that changed from the base of the PR and between d5305bc and a41f23b.

📒 Files selected for processing (2)
  • internal/metadata/image_cache_job_repo.go
  • internal/metadata/image_cache_job_repo_test.go
📝 Walkthrough

Walkthrough

The PR refactors image variant uploads to skip already-existing S3 objects and return uploaded/existing counts. It caps cached original image dimensions and normalizes thumbhash input. The metadata job repo gains failure-aware retry backoff for stable provider errors and a flag to requeue already-succeeded provider artwork jobs. Variant counts propagate through the processor and task completion reporting.

Changes

Image Cache: Skip-Existing Uploads, Dimension Caps, and Variant Count Reporting

Layer / File(s) Summary
CacheResult and CacheImageResult variant count fields
internal/imagecache/imagecache.go, internal/metadata/types.go
Adds UploadedVariants/ExistingVariants to CacheResult and CacheImageResult; introduces unexported objectExister interface.
Original dimension cap and thumbhash normalization
internal/imageutil/imageutil.go
New constants for max cached original and thumbhash source dimensions; GenerateVariants applies fitWithin on original WebP encode; Thumbhash normalizes input via normalizeThumbhashSource before hashing.
uploadVariants helper with existence check
internal/imagecache/imagecache.go
Raises maxDownloadBytes to 25MB; extracts shared uploadVariants helper that checks ObjectExists per variant before uploading; Cache/CacheBytes use it and forward counts through CacheImage.
mockS3 extensions and new cache behavior tests
internal/imagecache/imagecache_test.go
Extends mockS3 with ObjectExists tracking and data retrieval; adds tests for skip-all-existing, partial-upload counts, SVG conversion, and original dimension cap.
ImageCacheRunStats, processOne result struct, and task reporting
internal/metadata/image_cache_processor.go, internal/taskmanager/tasks/cache_metadata_images.go, internal/taskmanager/tasks/cache_metadata_images_test.go
ImageCacheRunStats accumulates UploadedVariants/ExistingVariants; processOne returns a struct with outcome and variant counts; RunOnce aggregates them; task completion message reports the new counters.

Image Cache Job Repo: Failure Backoff and Requeue-Succeeded

Layer / File(s) Summary
Failure-aware retry delay
internal/metadata/image_cache_job_repo.go, internal/metadata/image_cache_job_repo_test.go
Adds imageCacheDeferredRetry (7 days); imageCacheFailureRetryDelay detects 403/404/410/418 errors and defers retry; MarkFailed uses the new function; test asserts the 7-day delay for stable provider errors.
UPSERT requeue-succeeded and EnqueueExistingProviderArtwork wiring
internal/metadata/image_cache_job_repo.go
enqueueBatchChunk accepts requeueSucceeded; UPSERT resets succeeded rows to queued and clears lease/completion fields when flag is true; EnqueueExistingProviderArtwork selects succeeded rows and passes requeueSucceeded=true.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • Silo-Server/silo-server#176: Introduces putObjectWithRetry in the same variant upload flow that this PR refactors into the shared uploadVariants helper with existence checking.
🚥 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: reducing metadata image cache R2 churn by avoiding unnecessary re-uploads.
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 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.

Caution

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

⚠️ Outside diff range comments (1)
internal/metadata/image_cache_job_repo.go (1)

406-420: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Preserve the 7-day cooldown when failed jobs are rediscovered.

Line 406 stores a 7-day next_attempt_at for stable provider failures, but the enqueue/discovery paths still reactivate failed rows based on updated_at < NOW() - imageCacheFailedRetryAfter — currently 6 hours. Once a stable failure reaches status='failed', discovery can reset it to queued after 6 hours and bypass the intended cooldown. Prefer using next_attempt_at <= NOW() for failed-row eligibility in the UPSERT and existing-provider candidate query.

🤖 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_job_repo.go` around lines 406 - 420, The
failed-job rediscovery logic in imageCacheJobRepo is using updated_at-based age
checks, which can re-queue stable provider failures before their 7-day
next_attempt_at cooldown expires. Update the UPSERT path and the
existing-provider candidate query in
imageCacheFailureRetryDelay/imageCacheFailedRetryAfter handling so that rows
with status='failed' are only eligible when next_attempt_at <= NOW(), preserving
the intended cooldown. Keep the fix localized around the
metadata_image_cache_jobs selection and reactivation logic in imageCacheJobRepo.
🤖 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.

Outside diff comments:
In `@internal/metadata/image_cache_job_repo.go`:
- Around line 406-420: The failed-job rediscovery logic in imageCacheJobRepo is
using updated_at-based age checks, which can re-queue stable provider failures
before their 7-day next_attempt_at cooldown expires. Update the UPSERT path and
the existing-provider candidate query in
imageCacheFailureRetryDelay/imageCacheFailedRetryAfter handling so that rows
with status='failed' are only eligible when next_attempt_at <= NOW(), preserving
the intended cooldown. Keep the fix localized around the
metadata_image_cache_jobs selection and reactivation logic in imageCacheJobRepo.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a410f754-8110-4840-ad6f-39eca77a6000

📥 Commits

Reviewing files that changed from the base of the PR and between 712059c and d5305bc.

📒 Files selected for processing (9)
  • internal/imagecache/imagecache.go
  • internal/imagecache/imagecache_test.go
  • internal/imageutil/imageutil.go
  • internal/metadata/image_cache_job_repo.go
  • internal/metadata/image_cache_job_repo_test.go
  • internal/metadata/image_cache_processor.go
  • internal/metadata/types.go
  • internal/taskmanager/tasks/cache_metadata_images.go
  • internal/taskmanager/tasks/cache_metadata_images_test.go

@Quick104
Quick104 merged commit 7d8f090 into Silo-Server:main Jul 1, 2026
1 check passed
Quick104 pushed a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
* Reduce metadata image cache R2 churn

* Preserve image cache failure cooldowns

---------

Co-authored-by: rxwatcher <[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.

2 participants