Repository navigation
fix(metadata): publish artwork revisions atomically - #399
Conversation
|
Warning Review limit reached
Next review available in: 26 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (11)
📝 WalkthroughWalkthroughArtwork caching now uses immutable revisioned keys and manifests. Artwork selection persistence, delayed S3 garbage collection, admin API responses, embedded cover callers, and frontend image loading are updated to consume the new revision-aware contracts. ChangesArtwork revision lifecycle
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
internal/artworkkey/artworkkey.go (1)
39-48: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win
Variant()rewrites the first/original.match anywhere in the path, not necessarily the filename.
strings.Replace(..., 1)replaces the first occurrence of the marker in the whole string. If any earlier path segment (providerID/contentType/contentID) happened to contain the literal substring/original., the rewrite would target the wrong segment instead of the trailingoriginal.<revision>.extfilename. Usingpath.Dir/path.Base(asDirectory()already does) makes this immune to path-prefix content.♻️ Proposed fix using basename-anchored rewrite
func Variant(originalPath, variant string) string { if originalPath == "" || variant == "" || variant == OriginalVariant { return originalPath } - const marker = "/original." - if !strings.Contains(originalPath, marker) { + dir := path.Dir(originalPath) + base := path.Base(originalPath) + if !strings.HasPrefix(base, OriginalVariant+".") { return originalPath } - return strings.Replace(originalPath, marker, "/"+variant+".", 1) + return dir + "/" + variant + strings.TrimPrefix(base, OriginalVariant) }🤖 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/artworkkey/artworkkey.go` around lines 39 - 48, Update Variant to rewrite only the filename’s original marker, not the first matching substring in the full path. Use path.Dir and path.Base to isolate the basename, replace its leading original marker, then rejoin the directory and modified basename while preserving the existing early-return behavior.internal/catalog/artwork_selection.go (1)
168-184: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winKeep the artwork variant table in one place.
artworkkey.ObjectKeys()andqueue_displaced_artwork_revision()both encode the sameimage_type→ suffix mapping separately. Since the trigger can’t reuse the Go helper directly, add a shared regression test or generate the SQL case list from the Go definition so the cleanup keys don’t drift.🤖 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/catalog/artwork_selection.go` around lines 168 - 184, The artwork variant mapping is duplicated between artworkkey.ObjectKeys and queue_displaced_artwork_revision. Update internal/catalog/artwork_selection.go:168-184 and migrations/sql/20260714120826_artwork_revision_gc.sql:33-97 by adding a shared regression test or generating the SQL CASE mapping from the Go definition, ensuring every image_type-to-suffix mapping remains synchronized and cleanup keys cannot drift.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/metadata/artwork_revision_gc.go`:
- Around line 52-82: Update Run’s retry-error handling so a failure from g.retry
for one candidate does not return immediately or stop processing the remaining
candidates. Continue iterating through all claimed candidates, retain the first
retry-scheduling error, and return it only after the batch completes while
preserving the collected stats.
---
Nitpick comments:
In `@internal/artworkkey/artworkkey.go`:
- Around line 39-48: Update Variant to rewrite only the filename’s original
marker, not the first matching substring in the full path. Use path.Dir and
path.Base to isolate the basename, replace its leading original marker, then
rejoin the directory and modified basename while preserving the existing
early-return behavior.
In `@internal/catalog/artwork_selection.go`:
- Around line 168-184: The artwork variant mapping is duplicated between
artworkkey.ObjectKeys and queue_displaced_artwork_revision. Update
internal/catalog/artwork_selection.go:168-184 and
migrations/sql/20260714120826_artwork_revision_gc.sql:33-97 by adding a shared
regression test or generating the SQL CASE mapping from the Go definition,
ensuring every image_type-to-suffix mapping remains synchronized and cleanup
keys cannot drift.
🪄 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: a5a881be-279d-4ed6-ba66-128c69d39db2
📒 Files selected for processing (33)
cmd/silo/main.gointernal/api/handlers/admin_images.gointernal/api/router.gointernal/artworkkey/artworkkey.gointernal/artworkkey/artworkkey_test.gointernal/audiobooks/enrichment.gointernal/audiobooks/enrichment_test.gointernal/catalog/artwork_selection.gointernal/catalog/detail.gointernal/catalog/folder_repo.gointernal/ebooks/enrichment.gointernal/imagecache/imagecache.gointernal/imagecache/imagecache_test.gointernal/manga/enrichment.gointernal/metadata/apply_item_image_test.gointernal/metadata/artwork_revision_gc.gointernal/metadata/artwork_revision_gc_test.gointernal/metadata/cache_result.gointernal/metadata/image_cache_processor.gointernal/metadata/person_refresh.gointernal/metadata/service.gointernal/metadata/types.gointernal/s3client/client.gointernal/scanner/audiobook_cover.gointernal/scanner/audiobook_cover_test.gointernal/scanner/audiobook_test.gointernal/scanner/ebook_scan.gointernal/scanner/ebook_test.gointernal/taskmanager/tasks/cleanup_artwork_revisions.gomigrations/sql/20260714120826_artwork_revision_gc.sqlweb/src/api/types.tsweb/src/pages/ItemDetail/DetailHero.test.tsxweb/src/pages/ItemDetail/DetailHero.tsx
|
Addressed the two additional review-body notes in ed86e97:
Validation: focused Go tests, fresh-database migration and artwork GC integration tests, |
- restore image applies for all media_items types and reject unsupported target/image combinations with 400 before uploading; episodes coerce to stills and the web dialog no longer offers image tabs episodes can't use - add WHEN clauses to displacement triggers and hoist to_jsonb so bulk catalog upserts that assign unchanged artwork columns skip the trigger - make artworkkey the single variant-ladder owner: imagecache derives its widths from it and triggers store image_type instead of hardcoded variant arrays, expanded by the collector at deletion time - sweep dormant registry rows periodically so references lost through untriggered surfaces degrade to slow cleanup instead of leaking - park just-published revisions dormant, keep dormant rows dormant on re-cache, and batch the GC reference pre-check per run - heal rows re-referencing a just-deleted revision via reconciler-style resets after the deletion commits - share a per-URL image-loaded hook across DetailHero, ItemCard, SectionItemCard, GlobalSearch, and CollectionPosterCard - deduplicate Cache/CacheBytes finalization and drop unused VariantPaths plumbing Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Postgres cannot deduce one type for $3 used both as a plain value and inside a CASE arm; the dev deploy surfaced it as SQLSTATE 42P08 on every publication. Cast both uses and cover the arm/park/track upserts with database-backed tests. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
ed86e97 to
4a5e5f5
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 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/catalog/artwork_selection_test.go`:
- Around line 97-99: Update the assertion in the artwork selection test to
compare storedKeys and keys with slices.Equal, replacing the length-only check
while preserving the existing failure message and exact-manifest contract.
In `@internal/imagecache/imagecache.go`:
- Around line 358-362: Update objectMatches so only an ObjectPutter implementing
objectMatcher can return a content-match result; when it lacks objectMatcher,
return false rather than calling objectExists, ensuring stale or corrupted
revision-key data is rewritten.
In `@internal/metadata/artwork_revision_gc_test.go`:
- Around line 30-34: Update the blockingArtworkRevisionDeleter.DeleteObjects
method to honor context cancellation while waiting on the release channel.
Replace the blocking receive on d.release with a select statement that listens
to both d.release and ctx.Done(), returning an error if the context is cancelled
before the release signal arrives. Preserve the existing behavior for the normal
case where the release channel signals first.
In `@internal/metadata/artwork_revision_gc.go`:
- Around line 315-320: Update the post-delete handling in the artwork revision
GC flow around healDeletedReferences so a healing failure does not finalize
deletion without durable retry work. Preserve or recreate the candidate/healing
record needed to retry until healing succeeds, while retaining the existing
error logging and avoiding a plain error return after the candidate has been
removed.
In `@internal/scanner/ebook_test.go`:
- Line 55: Update the fake cover-path return value in the ebook test to use a
revisioned key instead of the legacy original.webp path, and update the
corresponding assertion to expect that same revisioned path.
🪄 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: 9af7d9e0-06a9-40b8-9707-3770c20d2e5c
📒 Files selected for processing (41)
cmd/silo/main.gointernal/api/handlers/admin_images.gointernal/api/router.gointernal/artworkkey/artworkkey.gointernal/artworkkey/artworkkey_test.gointernal/audiobooks/enrichment.gointernal/audiobooks/enrichment_test.gointernal/catalog/artwork_selection.gointernal/catalog/artwork_selection_test.gointernal/catalog/detail.gointernal/catalog/folder_repo.gointernal/ebooks/enrichment.gointernal/imagecache/imagecache.gointernal/imagecache/imagecache_test.gointernal/manga/enrichment.gointernal/metadata/apply_item_image_test.gointernal/metadata/artwork_revision_gc.gointernal/metadata/artwork_revision_gc_test.gointernal/metadata/cache_result.gointernal/metadata/image_cache_processor.gointernal/metadata/person_refresh.gointernal/metadata/service.gointernal/metadata/types.gointernal/s3client/client.gointernal/scanner/audiobook_cover.gointernal/scanner/audiobook_cover_test.gointernal/scanner/audiobook_test.gointernal/scanner/ebook_scan.gointernal/scanner/ebook_test.gointernal/taskmanager/tasks/cleanup_artwork_revisions.gomigrations/sql/20260714120826_artwork_revision_gc.sqlweb/src/api/types.tsweb/src/components/EditMetadataDialog.tsxweb/src/components/GlobalSearch.tsxweb/src/components/ImageSelectorTab.tsxweb/src/components/ItemCard.tsxweb/src/components/SectionItemCard.tsxweb/src/components/collections/CollectionPosterCard.tsxweb/src/hooks/useImageLoaded.tsweb/src/pages/ItemDetail/DetailHero.test.tsxweb/src/pages/ItemDetail/DetailHero.tsx
🚧 Files skipped from review as they are similar to previous changes (22)
- web/src/api/types.ts
- web/src/pages/ItemDetail/DetailHero.test.tsx
- internal/metadata/cache_result.go
- web/src/pages/ItemDetail/DetailHero.tsx
- internal/artworkkey/artworkkey_test.go
- internal/metadata/apply_item_image_test.go
- internal/audiobooks/enrichment_test.go
- internal/taskmanager/tasks/cleanup_artwork_revisions.go
- internal/audiobooks/enrichment.go
- internal/catalog/folder_repo.go
- cmd/silo/main.go
- internal/scanner/audiobook_cover.go
- internal/scanner/ebook_scan.go
- internal/scanner/audiobook_cover_test.go
- internal/api/router.go
- internal/catalog/detail.go
- internal/manga/enrichment.go
- internal/metadata/person_refresh.go
- internal/scanner/audiobook_test.go
- internal/s3client/client.go
- internal/api/handlers/admin_images.go
- internal/imagecache/imagecache_test.go
- keep a durable heal path: deletion marks deleted_at instead of removing the registry row, so a failed post-delete heal retries with backoff and broken references never park; trackers clear the marker on re-upload - never treat bare existence as an immutable-content match; backends without content verification rewrite the object - exercise revisioned cover keys in scanner/enrichment fakes, compare the tracked manifest exactly, and honor cancellation in the blocking test deleter Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The GC issues one DeleteObjects call per candidate. Measured against Backblaze B2 from the server itself: DeleteObjects(1 real key) 2.944s DeleteObjects(99 real keys) 2.057s The cost is per call, not per object. A 100-candidate run therefore spends ~290s in S3, and cleanup_artwork_revisions takes ~283s wall clock to collect 100 objects. On an hourly trigger that is ~2,400 objects a day. On a catalog of 625k items, 2.2M episodes and 1.2M people, displacement queues 1,800-5,400 new candidates a day, so the queue cannot drain. One deployment reached 6,727,014 candidates covering roughly 24M objects, accumulating since Silo-Server#399. Nothing looks wrong while it happens: the task reports {"claimed":100,"deleted":100} and succeeds on every run, so the only symptom is object storage growing without bound. Run now collects the keys for every claimed candidate and issues one batched DeleteObjects, then the per-candidate guard does its bookkeeping with its own S3 call skipped. DeleteObjects already chunks at 1000 keys. Deleting ahead of the per-candidate guard is consistent with the design's existing assumption that a path can race back into use after its objects are gone: that is what the pending-heal path repairs. If the batched call fails, predeleted is cleared and every candidate falls back to the existing per-candidate path and its retry backoff. Measured with an equivalent batched pass against that production queue: per-candidate calls 100 candidates / 283s = 0.35/sec one batched call 10,000 candidates / 21.7s = 461/sec 35,000 objects deleted in a single 8s call go build ./... and go test ./internal/metadata/ pass, including the 16 existing artwork revision GC tests.
* perf(metadata): batch the artwork revision GC's object deletes The GC issues one DeleteObjects call per candidate. Measured against Backblaze B2 from the server itself: DeleteObjects(1 real key) 2.944s DeleteObjects(99 real keys) 2.057s The cost is per call, not per object. A 100-candidate run therefore spends ~290s in S3, and cleanup_artwork_revisions takes ~283s wall clock to collect 100 objects. On an hourly trigger that is ~2,400 objects a day. On a catalog of 625k items, 2.2M episodes and 1.2M people, displacement queues 1,800-5,400 new candidates a day, so the queue cannot drain. One deployment reached 6,727,014 candidates covering roughly 24M objects, accumulating since #399. Nothing looks wrong while it happens: the task reports {"claimed":100,"deleted":100} and succeeds on every run, so the only symptom is object storage growing without bound. Run now collects the keys for every claimed candidate and issues one batched DeleteObjects, then the per-candidate guard does its bookkeeping with its own S3 call skipped. DeleteObjects already chunks at 1000 keys. Deleting ahead of the per-candidate guard is consistent with the design's existing assumption that a path can race back into use after its objects are gone: that is what the pending-heal path repairs. If the batched call fails, predeleted is cleared and every candidate falls back to the existing per-candidate path and its retry backoff. Measured with an equivalent batched pass against that production queue: per-candidate calls 100 candidates / 283s = 0.35/sec one batched call 10,000 candidates / 21.7s = 461/sec 35,000 objects deleted in a single 8s call go build ./... and go test ./internal/metadata/ pass, including the 16 existing artwork revision GC tests. * fix(metadata): treat a short batched delete as a failure DeleteObjects reports how many objects it actually removed, and a count below the request size means per-object failures without a top-level error. The result does not say which keys survived, so the batch result cannot be trusted to mark any candidate deleted. Treat a short count exactly like an error: discard the predeleted set so every candidate falls through to the per-candidate path, which re-deletes its own keys and retries with backoff. Marking them deleted here would finalize rows whose objects still exist, and the candidate row is the only record that those objects are collectable. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013LPxFvVsa6TUFv1dPvduoK * fix(metadata): guard batched artwork deletion with registry locks --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: Quick104 <31828688+Quick104@users.noreply.github.com>
…1088) * perf(metadata): batch the artwork revision GC's object deletes The GC issues one DeleteObjects call per candidate. Measured against Backblaze B2 from the server itself: DeleteObjects(1 real key) 2.944s DeleteObjects(99 real keys) 2.057s The cost is per call, not per object. A 100-candidate run therefore spends ~290s in S3, and cleanup_artwork_revisions takes ~283s wall clock to collect 100 objects. On an hourly trigger that is ~2,400 objects a day. On a catalog of 625k items, 2.2M episodes and 1.2M people, displacement queues 1,800-5,400 new candidates a day, so the queue cannot drain. One deployment reached 6,727,014 candidates covering roughly 24M objects, accumulating since #399. Nothing looks wrong while it happens: the task reports {"claimed":100,"deleted":100} and succeeds on every run, so the only symptom is object storage growing without bound. Run now collects the keys for every claimed candidate and issues one batched DeleteObjects, then the per-candidate guard does its bookkeeping with its own S3 call skipped. DeleteObjects already chunks at 1000 keys. Deleting ahead of the per-candidate guard is consistent with the design's existing assumption that a path can race back into use after its objects are gone: that is what the pending-heal path repairs. If the batched call fails, predeleted is cleared and every candidate falls back to the existing per-candidate path and its retry backoff. Measured with an equivalent batched pass against that production queue: per-candidate calls 100 candidates / 283s = 0.35/sec one batched call 10,000 candidates / 21.7s = 461/sec 35,000 objects deleted in a single 8s call go build ./... and go test ./internal/metadata/ pass, including the 16 existing artwork revision GC tests. * fix(metadata): treat a short batched delete as a failure DeleteObjects reports how many objects it actually removed, and a count below the request size means per-object failures without a top-level error. The result does not say which keys survived, so the batch result cannot be trusted to mark any candidate deleted. Treat a short count exactly like an error: discard the predeleted set so every candidate falls through to the per-candidate path, which re-deletes its own keys and retries with backoff. Marking them deleted here would finalize rows whose objects still exist, and the candidate row is the only record that those objects are collectable. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013LPxFvVsa6TUFv1dPvduoK * perf(metadata): raise the artwork revision GC batch to 10000 The batch of 100 was sized when each candidate cost its own ~2.9s DeleteObjects call and its own unindexed reference check, which made a 100-candidate run take ~283s. Both costs are gone: object deletes are batched into one call per run, and the reference check is indexed. Measured on the deployment this came from: per-candidate database work is 0.17ms (2000 candidates in 345ms), down from ~2.3s unindexed. Each candidate carries 4 objects and deletion runs at ~0.21ms per object, so a 10000-candidate batch completes in ~17.5s end to end. The ceiling is artworkRevisionGCLease, and it is a correctness bound rather than a performance one: a run that outlives its 15-minute lease has its rows re-claimed by the next worker mid-run. 17.5s is about 2% of that budget, so a deployment fifty times slower still finishes inside it. Depends on the reference-path indexes; without them a candidate still costs ~2.3s and this batch would exceed the lease by a wide margin. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013LPxFvVsa6TUFv1dPvduoK * fix(metadata): heal artwork predeletion races * fix(metadata): serialize bulk artwork deletion with uploads * fix(metadata): bound error reporting for failed GC batches --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com>
Summary
Related to #348. This addresses the separate artwork-overwrite path where a successful database update could continue resolving the previous mutable S3 object and cached URL.
Root cause
Artwork variants previously reused deterministic object keys. Replacing a poster overwrote those keys while presigned URLs, browser caches, and resolver caches still identified the old resource. The API could therefore report success without clients observing a new resource identity.
The first immutable-key implementation also left two lifecycle gaps: background cache jobs could orphan uploaded revisions, and garbage collection could race a concurrent re-selection between its reference check and S3 deletion.
Implementation
DetailHerotrack load state per URL so a changed revision fades in only after the replacement has loadedImpact and risk
The migration adds an artwork revision registry, displacement triggers, and an hourly cleanup task. Deletion retains a 24-hour grace period and checks every catalog artwork surface before touching S3. Existing legacy keys remain readable; new writes use immutable revision keys.
Validation
go testfor all changed backend packagesgolangci-lint run --new-from-rev=HEAD(zero new findings)make buildmake migrate-validatemake verify-local-pathspnpm run lint(zero errors; existing warnings remain)pnpm run format:checkDetailHeroVitestThe repository-wide Go suite still has unrelated host-sensitive failures in existing Jellyfin process-lock and NVENC detection tests. The complete frontend Vitest run also has existing failures in compatibility-proxy/setup-wizard tests. None of those files are modified here.
AI use disclosure
Implemented and reviewed with Codex assistance. The concurrency protocol, migration, and regression tests were exercised against the local PostgreSQL/S3 development environment before publication.
Summary by CodeRabbit
New Features
Bug Fixes