Skip to content

fix(metadata): publish artwork revisions atomically - #399

Merged
Quick104 merged 5 commits into
Silo-Server:mainfrom
Rhainland:fix/poster-noops
Jul 16, 2026
Merged

Quick104 merged 5 commits into
Silo-Server:mainfrom
Rhainland:fix/poster-noops

Conversation

@Rhainland

@Rhainland Rhainland commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • publish cached artwork under immutable content-revision keys
  • update poster URLs immediately through the existing realtime metadata event flow
  • atomically publish manual selections and preserve image locks
  • track every immutable upload before S3 writes, including background cache jobs
  • reclaim unpublished and displaced revisions with a delayed, reference-aware garbage collector

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

  • derive one SHA-256 revision from the complete generated variant set and include it in every variant key
  • verify existing immutable objects with stored SHA-256 metadata before skipping uploads
  • register exact revision manifests before uploading; failed or skipped publications remain collectible
  • use database triggers on every cached-artwork catalog surface to reactivate displaced manifests regardless of which writer performs the update
  • park referenced manifests with no scheduled polling and reactivate them only when displaced
  • hold the revision row lock across the collector's final reference check and S3 deletion, serializing deletion with concurrent retracking/re-upload
  • publish realtime metadata events after the database transaction commits
  • make DetailHero track load state per URL so a changed revision fades in only after the replacement has loaded

Impact 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 test for all changed backend packages
  • PostgreSQL integration tests for delete/retrack serialization, referenced-revision parking, and trigger-driven displacement
  • golangci-lint run --new-from-rev=HEAD (zero new findings)
  • make build
  • make migrate-validate
  • make verify-local-paths
  • pnpm run lint (zero errors; existing warnings remain)
  • pnpm run format:check
  • focused DetailHero Vitest

The 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

    • Artwork image updates now use immutable revisions for consistent replacements.
    • Admin image applications now return the applied image URL and revision details.
    • Added automatic cleanup for displaced, no-longer-used artwork revisions.
    • Season items now show poster-only image options in the image selector.
  • Bug Fixes

    • Prevented stale poster/backdrop thumbnails by resetting image load state per URL.
    • Improved support for cached artwork variants across posters, backdrops, logos, covers, and stills.
    • Added safeguards to avoid incomplete uploads when revision tracking fails.

@coderabbitai

coderabbitai Bot commented Jul 14, 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: 26 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: 7f1247ba-6bb2-4024-b5f5-20142d6b86ba

📥 Commits

Reviewing files that changed from the base of the PR and between 4a5e5f5 and 378d11e.

📒 Files selected for processing (11)
  • internal/audiobooks/enrichment_test.go
  • internal/catalog/artwork_selection.go
  • internal/catalog/artwork_selection_test.go
  • internal/imagecache/imagecache.go
  • internal/imagecache/imagecache_test.go
  • internal/metadata/artwork_revision_gc.go
  • internal/metadata/artwork_revision_gc_test.go
  • internal/scanner/audiobook_cover_test.go
  • internal/scanner/audiobook_test.go
  • internal/scanner/ebook_test.go
  • migrations/sql/20260714120826_artwork_revision_gc.sql
📝 Walkthrough

Walkthrough

Artwork 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.

Changes

Artwork revision lifecycle

Layer / File(s) Summary
Revision-aware artwork caching
internal/artworkkey/*, internal/imagecache/*, internal/metadata/*, internal/s3client/*, internal/catalog/detail.go, internal/catalog/folder_repo.go, internal/audiobooks/*, internal/ebooks/*, internal/manga/*
Adds deterministic revisioned artwork keys, richer cache results, manifest tracking before uploads, content-aware S3 matching, shared original-path derivation, and updated caching tests and callers.
Artwork selection and revision cleanup
internal/catalog/artwork_selection.go, internal/metadata/artwork_revision_gc.go, migrations/sql/20260714120826_artwork_revision_gc.sql, internal/taskmanager/tasks/cleanup_artwork_revisions.go, cmd/silo/main.go
Persists selected artwork and locked fields, queues displaced revisions, adds leased reference-aware GC with retries, creates database triggers and candidates, and registers the cleanup task.
Admin artwork application flow
internal/api/handlers/admin_images.go, internal/api/router.go
Validates and publishes artwork selections through the detail service, emits metadata events, resolves image URLs, and returns revision data.
Embedded cover cache contracts
internal/scanner/*, internal/audiobooks/*, internal/ebooks/*, internal/manga/*
Updates audiobook and ebook cover APIs and callers to receive complete stored paths and thumbhashes directly.
Frontend artwork response and loading state
web/src/api/types.ts, web/src/hooks/useImageLoaded.ts, web/src/components/*, web/src/pages/ItemDetail/*
Adds optional image URL and revision response fields, restricts image choices for selected item types, and resets image loading state when artwork URLs change.

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

Possibly related PRs

  • Silo-Server/silo-server#249 — Related to variant upload existence checks and cache result handling in internal/imagecache/imagecache.go.

Suggested labels: v1

Suggested reviewers: quick104

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.94% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main metadata change: atomic publication of artwork revisions.
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.

@Rhainland
Rhainland marked this pull request as ready for review July 14, 2026 13:16
@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 14, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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 trailing original.<revision>.ext filename. Using path.Dir/path.Base (as Directory() 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 win

Keep the artwork variant table in one place. artworkkey.ObjectKeys() and queue_displaced_artwork_revision() both encode the same image_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

📥 Commits

Reviewing files that changed from the base of the PR and between 28c6ddc and 5ab803b.

📒 Files selected for processing (33)
  • cmd/silo/main.go
  • internal/api/handlers/admin_images.go
  • internal/api/router.go
  • internal/artworkkey/artworkkey.go
  • internal/artworkkey/artworkkey_test.go
  • internal/audiobooks/enrichment.go
  • internal/audiobooks/enrichment_test.go
  • internal/catalog/artwork_selection.go
  • internal/catalog/detail.go
  • internal/catalog/folder_repo.go
  • internal/ebooks/enrichment.go
  • internal/imagecache/imagecache.go
  • internal/imagecache/imagecache_test.go
  • internal/manga/enrichment.go
  • internal/metadata/apply_item_image_test.go
  • internal/metadata/artwork_revision_gc.go
  • internal/metadata/artwork_revision_gc_test.go
  • internal/metadata/cache_result.go
  • internal/metadata/image_cache_processor.go
  • internal/metadata/person_refresh.go
  • internal/metadata/service.go
  • internal/metadata/types.go
  • internal/s3client/client.go
  • internal/scanner/audiobook_cover.go
  • internal/scanner/audiobook_cover_test.go
  • internal/scanner/audiobook_test.go
  • internal/scanner/ebook_scan.go
  • internal/scanner/ebook_test.go
  • internal/taskmanager/tasks/cleanup_artwork_revisions.go
  • migrations/sql/20260714120826_artwork_revision_gc.sql
  • web/src/api/types.ts
  • web/src/pages/ItemDetail/DetailHero.test.tsx
  • web/src/pages/ItemDetail/DetailHero.tsx

@Rhainland

Copy link
Copy Markdown
Contributor Author

Addressed the two additional review-body notes in ed86e97:

  • artworkkey.Variant now rewrites only the basename, with regression coverage for an earlier /original. path segment.
  • The displacement trigger now uses filename-anchored replacements, and a fresh-PostgreSQL regression compares its poster, backdrop, and logo fallback manifests against artworkkey.ObjectKeys.

Validation: focused Go tests, fresh-database migration and artwork GC integration tests, make migrate-validate, make verify-local-paths, and golangci-lint with zero issues.

Rhainland and others added 4 commits July 16, 2026 15:38
- 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>

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5ab803b and 4a5e5f5.

📒 Files selected for processing (41)
  • cmd/silo/main.go
  • internal/api/handlers/admin_images.go
  • internal/api/router.go
  • internal/artworkkey/artworkkey.go
  • internal/artworkkey/artworkkey_test.go
  • internal/audiobooks/enrichment.go
  • internal/audiobooks/enrichment_test.go
  • internal/catalog/artwork_selection.go
  • internal/catalog/artwork_selection_test.go
  • internal/catalog/detail.go
  • internal/catalog/folder_repo.go
  • internal/ebooks/enrichment.go
  • internal/imagecache/imagecache.go
  • internal/imagecache/imagecache_test.go
  • internal/manga/enrichment.go
  • internal/metadata/apply_item_image_test.go
  • internal/metadata/artwork_revision_gc.go
  • internal/metadata/artwork_revision_gc_test.go
  • internal/metadata/cache_result.go
  • internal/metadata/image_cache_processor.go
  • internal/metadata/person_refresh.go
  • internal/metadata/service.go
  • internal/metadata/types.go
  • internal/s3client/client.go
  • internal/scanner/audiobook_cover.go
  • internal/scanner/audiobook_cover_test.go
  • internal/scanner/audiobook_test.go
  • internal/scanner/ebook_scan.go
  • internal/scanner/ebook_test.go
  • internal/taskmanager/tasks/cleanup_artwork_revisions.go
  • migrations/sql/20260714120826_artwork_revision_gc.sql
  • web/src/api/types.ts
  • web/src/components/EditMetadataDialog.tsx
  • web/src/components/GlobalSearch.tsx
  • web/src/components/ImageSelectorTab.tsx
  • web/src/components/ItemCard.tsx
  • web/src/components/SectionItemCard.tsx
  • web/src/components/collections/CollectionPosterCard.tsx
  • web/src/hooks/useImageLoaded.ts
  • web/src/pages/ItemDetail/DetailHero.test.tsx
  • web/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

Comment thread internal/imagecache/imagecache.go Resolved
Comment thread internal/scanner/ebook_test.go Resolved
- 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>
@Quick104
Quick104 merged commit 1664c60 into Silo-Server:main Jul 16, 2026
20 checks passed
RXWatcher added a commit to RXWatcher/silo-server that referenced this pull request Sep 14, 2026
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.
Quick104 added a commit that referenced this pull request Sep 14, 2026
* 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>
Quick104 added a commit that referenced this pull request Sep 14, 2026
…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>
@zZebrahz zZebrahz mentioned this pull request Sep 26, 2026
12 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants