Skip to content

feat(metadata): reconcile artwork cache after public S3 provider changes - #349

Merged
Quick104 merged 4 commits into
mainfrom
feat/artwork-cache-reconcile
Jul 9, 2026
Merged

Quick104 merged 4 commits into
mainfrom
feat/artwork-cache-reconcile

Conversation

@Quick104

@Quick104 Quick104 commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Part of #348

Problem

Changing the public S3 provider (endpoint, bucket, or key prefix) silently and permanently breaks every cached image. Stored paths are bucket-relative keys resolved against the current S3 config; the cached path in the row is the image cache pipeline's dedup marker so nothing re-enqueues; and clients fetch from S3 directly so the server never observes the 404s. The same applies to chapter thumbnails, collection artwork, library posters, branding assets, and embedded book covers.

Approach

Automatic verify-and-reconcile with no admin decisions (design spec included in this PR at docs/superpowers/specs/2026-07-08-s3-artwork-reconcile-design.md):

  • Fingerprint: s3.public_storage_identity (endpoint|bucket|key_prefix of the public write config — read-endpoint/URL-auth changes don't move data) stored in server_settings, seeded via SetIfAbsent at boot.
  • reconcile_artwork_cache task: startup trigger gated by ShouldRun (fingerprint comparison via the existing ScheduledConditionalTask mechanism); manual runs always sweep, doubling as recovery from bucket data loss. Probes ~200 random cached keys: ≥95% missing → bulk reset; otherwise per-row verification (keyset pagination, 16 concurrent HEADs with retry).
  • Recovery is per-surface: provider-sourced artwork resets *_path → *_source_path (the existing 60s enqueue loop re-caches it; its upsert already re-queues succeeded job rows). Chapter thumbnails (JSONB rewrite preserving unknown fields) refill via the 6h backfill task; media_items clears also null last_refreshed so book enrichment re-extracts embedded covers; collections fall back to generated collages; branding refs are verified/cleared by a new branding.Service.ReconcileMissingAssets. Thumbhashes are kept throughout so placeholders keep rendering.
  • Safety: transport errors never reset rows (error-budget abort; an all-error probe aborts outright, leaving the stale fingerprint so the next startup retries). Small upload-holding tables (library_collections, user_personal_collections, media_folders) are alwaysVerify so bulk mode cannot blind-clear an upload that survived migration. Guarded UPDATEs (... AND path = $stored) make the sweep safe against concurrent metadata refreshes. The fingerprint is only certified after a completed sweep, so interrupted runs re-trigger.
  • UX: users never see broken images — reset rows serve the provider's original URL via the existing absolute-URL pass-through until re-cached. The storage settings page shows a callout while endpoint/bucket/key-prefix is edited, warning that uploads can't be re-downloaded.

Out of scope (per spec): the private bucket (profile avatars live there), S3→S3 migration tooling, serve-time 404 fallback.

API surface

Additive only: one new task key (reconcile_artwork_cache) in the existing tasks API; one new machine-managed server_settings key. No endpoint or response-field changes. No schema migration.

Testing

  • DB-backed tests (fresh migrated database) covering: intact rows untouched, missing-with-provider-source reset, upload-sourced cleared with last_refreshed nulled, provider URLs never HEAD-checked, chapters JSONB rewrite (unknown fields preserved, retry state cleared), collection/library-poster clears, and storage errors leaving rows untouched.
  • Unit tests for fingerprint normalization, ShouldRun gating, fingerprint-only-on-success semantics, and branding composition.
  • Component tests for the settings callout (hidden when clean, shown when an identity field is dirty).
  • go build ./..., go vet, golangci-lint clean on touched code; web ESLint/Prettier clean; make verify-local-paths passes.

Risks / follow-up

  • A shared-bucket setup where another system deletes Silo's objects would trigger resets — that is the intended "heal what's missing" behavior, but worth knowing.
  • Template-derived collection posters are cleared rather than re-uploaded (the original template reference isn't stored); the collage generator covers the fallback.
  • The private bucket deserves its own pass later; the fingerprint/task mechanism is reusable for it.

AI-use disclosure

Implemented by Claude (Claude Code) from a human-directed design discussion; reviewed test output and lint locally.

Summary by CodeRabbit

  • New Features
    • Added automatic startup reconciliation to recover missing cached artwork after public storage location/identity changes.
    • Added a public-assets storage warning in admin settings, including guidance about re-caching after restart.
    • Improved branding asset recovery by clearing missing public branding references and reloading them.
  • Bug Fixes
    • Fixed task scheduling so conditional tasks are skipped when preflight checks error, preventing unintended runs.
    • Improved resilience by aborting identity certification when reconciliation reports sweep errors, and allowing branding reconciliation failures without blocking cache recovery.

Changing the public S3 provider previously broke every cached image
permanently: the DB keeps bucket-relative keys, the image cache pipeline
treats a cached path as its durable dedup marker and never re-enqueues,
and clients eat the 404s straight from S3 so the server never notices.

Add a storage identity fingerprint (s3.public_storage_identity, seeded
via SetIfAbsent at boot) and a reconcile_artwork_cache task whose
startup trigger only fires when the identity changed; manual runs
always sweep, doubling as bucket-data-loss recovery. The task probes a
random sample of cached objects, then either bulk-resets (near-total
miss) or per-row verifies. Missing provider-sourced artwork is reset to
its *_source_path so the existing enqueue loop re-caches it; surfaces
without a re-downloadable source (chapter thumbnails, collection
artwork, library posters, branding refs, embedded book covers) are
cleared so their owning pipelines refill them. Small upload-holding
tables are always per-row verified so bulk mode cannot blind-clear an
upload that survived migration, and transport errors never reset rows.

Users never see broken images during the transition: reset rows serve
the provider's original URL via the existing absolute-URL pass-through
and thumbhashes are preserved. The storage settings page now warns that
uploads cannot be re-downloaded when the identity fields are edited.

Part of #348

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e58b2a4b-b6b3-4bf2-9539-6270b2b3d1fc

📥 Commits

Reviewing files that changed from the base of the PR and between 8f864ef and b529256.

📒 Files selected for processing (4)
  • cmd/silo/main.go
  • internal/s3client/client.go
  • internal/taskmanager/manager.go
  • internal/taskmanager/manager_test.go

📝 Walkthrough

Walkthrough

Adds public S3 artwork-cache reconciliation with storage-identity fingerprinting, a reconcile task and runner, branding asset cleanup, startup wiring, and an admin warning when public storage identity fields change.

Changes

Artwork Cache Reconciliation

Layer / File(s) Summary
Design specification
docs/superpowers/specs/2026-07-08-s3-artwork-reconcile-design.md
Documents the fingerprint approach, task behavior, failure modes, out-of-scope items, and implementation mapping.
Storage identity plumbing
internal/s3client/client.go, internal/metadata/image_cache_job_repo.go
Exports key-prefix normalization and updates provider-artwork query rendering to use shared scheme filters.
Artwork reconciler core implementation
internal/metadata/artwork_reconcile.go, internal/metadata/artwork_reconcile_test.go
Implements ArtworkCacheReconciler with probing, bulk-reset vs per-row verify modes, HEAD-check concurrency, surface sweeps, and chapter-thumbnail JSONB reconciliation, with database-backed tests.
Branding asset reconciliation
internal/branding/service.go
Adds ReconcileMissingAssets to clear branding asset refs whose backing S3 objects are missing.
Reconcile task definition and scheduling
internal/taskmanager/tasks/reconcile_artwork_cache.go, internal/taskmanager/tasks/reconcile_artwork_cache_test.go, internal/taskmanager/manager.go, internal/taskmanager/manager_test.go
Adds ReconcileArtworkCacheTask with identity fingerprinting, ShouldRun gating, and Execute combining reconciler and branding results, plus task manager preflight handling and tests.
Application startup wiring
cmd/silo/main.go
Constructs a shared brandingSvc early, seeds the artwork storage identity, registers the reconcile task, and reuses brandingSvc for router and frontend exposure.
Admin storage-change warning UI
web/src/pages/admin-settings/StorageSettings.tsx, web/src/pages/admin-settings/StorageSettings.test.tsx
Adds a conditional warning callout when public S3 identity fields are edited, with corresponding tests.

Estimated code review effort: 5 (Critical) | ~90 minutes

Possibly related issues

Suggested labels: v1

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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: artwork cache reconciliation triggered by public S3 provider changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/artwork-cache-reconcile

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

@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: 58694ffcc8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread internal/metadata/artwork_reconcile.go Outdated
Comment on lines +286 to +290
present, missing, errored := r.headBatch(ctx, keys)
stats.Sampled = present + missing
stats.SampleMissing = missing
stats.Errors += errored
if errored == len(keys) {

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 Abort bulk reset when probe HEADs mostly error

When the probe gets a few real 404s but most sampled HEADs return transport errors, errored requests are excluded from Sampled, so shouldBulkReset can see a 100% miss rate (for example 1 missing object plus 199 errors) and proceed to bulk-reset every non-upload artwork surface. In a partial S3 outage this violates the stated transport-error safety guarantee and can clear/requeue large parts of the cache based on an unreliable sample; abort or require a sufficient low-error successful sample before entering bulk mode.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 8f864ef. Two guards now protect bulk mode from a degraded probe: the run aborts when more than half the probe HEADs error (errored*2 > len(keys) — an outage is not a miss), and shouldBulkReset additionally requires at least artworkReconcileBulkMinSample (25) successful samples, so 1 missing + 199 errors can no longer read as a 100% miss rate. Thinned probes and tiny catalogs fall through to the per-row verify path, which never resets on errors.

Comment on lines +24 to +25
normalize := func(v string) string { return strings.ToLower(strings.TrimSpace(v)) }
return normalize(endpoint) + "|" + normalize(bucket) + "|" + normalize(keyPrefix)

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 Keep S3 key prefix case-sensitive in fingerprint

If an admin changes only the case of s3.public_key_prefix (for example Art to art), the S3 client reads and writes a different key namespace because object keys/prefixes are case-sensitive, but this fingerprint lowercases the prefix and ShouldRun treats the storage identity as unchanged. The startup reconcile is skipped and existing cached paths keep resolving under the new prefix to missing objects; trim equivalent syntax if needed, but do not lowercase the key prefix.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c5b8f6d (pre-dating this thread's visibility): the key prefix is no longer lowercased — it keeps its case and is normalized exactly like the S3 client applies it (slash/whitespace-trimmed via the newly exported s3client.NormalizeKeyPrefix), so a case-only prefix edit changes the fingerprint and reconciles, while slash-only edits don't trigger pointless sweeps. Covered by TestArtworkStorageIdentityNormalizes.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 8, 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: 4

🧹 Nitpick comments (3)
internal/taskmanager/tasks/reconcile_artwork_cache.go (1)

100-105: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

stats.Checked is incremented by cleared count, not by items actually checked.

ReconcileMissingAssets only returns a cleared count, but stats.Checked += brandingCleared treats "checked" and "cleared" as the same quantity for branding assets. This under-reports how many branding assets were actually probed (all of them, not just the cleared ones), skewing the reported stats.

🤖 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/taskmanager/tasks/reconcile_artwork_cache.go` around lines 100 -
105, The branding reconciliation in reconcileArtworkCache is updating
stats.Checked with the cleared count from t.branding.ReconcileMissingAssets,
which misreports how many assets were actually checked. Update the reconcile
flow so stats.Checked reflects the total branding assets probed (not
brandingCleared), and keep stats.Cleared driven only by the returned cleared
count from ReconcileMissingAssets. Use the reconcileArtworkCache logic and the
ReconcileMissingAssets call site to locate and adjust the accounting.
cmd/silo/main.go (1)

1841-1841: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Dead nil-check on settingsRepo.

settingsRepo is unconditionally constructed earlier (never nil in this path), so this guard never evaluates false. Harmless, but slightly misleading — a reader might assume settingsRepo can legitimately be nil here.

🤖 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 `@cmd/silo/main.go` at line 1841, The `settingsRepo` nil guard is dead code
because `settingsRepo` is always constructed before this branch, so the `if
settingsRepo != nil` check in `main` is misleading. Remove the unnecessary
conditional and keep the enclosed logic directly in the existing flow, or
replace it with a more meaningful check if there is an actual failure path
elsewhere in the setup. Use the `settingsRepo` initialization and the
surrounding code in `main` to locate the branch and simplify it consistently.
internal/metadata/artwork_reconcile.go (1)

260-284: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

ORDER BY random() sampling doesn't scale to large tables.

Both the per-surface sample query (Lines 262-266) and the chapter-thumbnail sample query (Lines 272-277, which also does an implicit cross join against jsonb_array_elements) use ORDER BY random() LIMIT $1. Postgres has to materialize and sort the entire filtered result set to satisfy this, which is O(n log n) with no index usable — potentially very slow on large media_items/chapter catalogs. Since this only runs on a fingerprint mismatch or manual trigger it's not a hot path, but it can make an otherwise "fast no-op" startup task unexpectedly slow on large libraries.

Consider a cheaper sampling strategy (e.g. TABLESAMPLE, or WHERE random() < p combined with the existing predicate) to avoid the full sort.

🤖 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/artwork_reconcile.go` around lines 260 - 284, The sampling
in the artwork reconciliation flow is using ORDER BY random() in both the
per-surface query inside the surfaces loop and the chapter thumbnail query that
reads from media_files/jsonb_array_elements, which forces a full scan and sort.
Update this logic in the reconcile/sampling path to use a cheaper random
sampling approach instead of ORDER BY random() LIMIT $1, such as TABLESAMPLE or
a probabilistic WHERE random() < p filter combined with the existing predicates.
Keep the existing error handling and key aggregation in place, but make sure the
queries in the surface sampling block and chapterKeys fetch avoid the expensive
full-table sort.
🤖 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 `@docs/superpowers/specs/2026-07-08-s3-artwork-reconcile-design.md`:
- Around line 93-110: The probe sample size and HEAD concurrency described in
the design doc are inconsistent with the actual constants used by artwork
reconciliation. Update the wording in the Phase 1 “probe” and Phase 2 “sweep and
reset” sections to match the symbols artworkReconcileSampleTarget and
artworkReconcileHeadWorkers in internal/metadata/artwork_reconcile.go, or
clearly mark the numbers as illustrative so readers don’t assume the wrong
operational values.

In `@internal/metadata/artwork_reconcile.go`:
- Around line 286-294: The probe summary in headBatch-driven reconciliation is
still being trusted when many head requests fail, which can let shouldBulkReset
act on too few successful samples. Update the reconcile flow around headBatch so
partial probe errors are treated as an unsafe signal: either abort
reconciliation or fall back to per-row verify when the error rate is too high,
and require a minimum number of successful samples before using stats.Sampled
and stats.SampleMissing. Keep the check alongside the existing errored count and
the stats aggregation in artwork reconcile logic so bulk reset cannot be
triggered from a statistically weak probe.
- Around line 355-376: The retry loop in
ArtworkCacheReconciler.objectExistsWithRetry currently calls r.s3.ObjectExists
with only the parent ctx, so a stalled request can block all three attempts
until the outer context expires. Wrap each per-attempt ObjectExists call in its
own timeout context inside objectExistsWithRetry, cancel it after each attempt,
and keep the existing retry/backoff behavior and lastErr handling intact.

In `@internal/taskmanager/tasks/reconcile_artwork_cache.go`:
- Around line 99-117: The fingerprint certification in Execute is happening even
when the sweep completed with storage errors, because it only checks err and
ignores stats.Errors from ArtworkCacheReconciler.Run. Update the Execute flow to
treat non-zero stats.Errors as a failed run or explicitly block the
t.settings.Set call unless stats.Errors == 0. Use the existing stats, err,
t.runner.Run, t.branding.ReconcileMissingAssets, and ArtworkStorageIdentityKey
logic to keep the certification step tied only to a truly clean sweep.

---

Nitpick comments:
In `@cmd/silo/main.go`:
- Line 1841: The `settingsRepo` nil guard is dead code because `settingsRepo` is
always constructed before this branch, so the `if settingsRepo != nil` check in
`main` is misleading. Remove the unnecessary conditional and keep the enclosed
logic directly in the existing flow, or replace it with a more meaningful check
if there is an actual failure path elsewhere in the setup. Use the
`settingsRepo` initialization and the surrounding code in `main` to locate the
branch and simplify it consistently.

In `@internal/metadata/artwork_reconcile.go`:
- Around line 260-284: The sampling in the artwork reconciliation flow is using
ORDER BY random() in both the per-surface query inside the surfaces loop and the
chapter thumbnail query that reads from media_files/jsonb_array_elements, which
forces a full scan and sort. Update this logic in the reconcile/sampling path to
use a cheaper random sampling approach instead of ORDER BY random() LIMIT $1,
such as TABLESAMPLE or a probabilistic WHERE random() < p filter combined with
the existing predicates. Keep the existing error handling and key aggregation in
place, but make sure the queries in the surface sampling block and chapterKeys
fetch avoid the expensive full-table sort.

In `@internal/taskmanager/tasks/reconcile_artwork_cache.go`:
- Around line 100-105: The branding reconciliation in reconcileArtworkCache is
updating stats.Checked with the cleared count from
t.branding.ReconcileMissingAssets, which misreports how many assets were
actually checked. Update the reconcile flow so stats.Checked reflects the total
branding assets probed (not brandingCleared), and keep stats.Cleared driven only
by the returned cleared count from ReconcileMissingAssets. Use the
reconcileArtworkCache logic and the ReconcileMissingAssets call site to locate
and adjust the accounting.
🪄 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: e0ae7ced-8998-4459-9346-e5c9371948bf

📥 Commits

Reviewing files that changed from the base of the PR and between 7ab55cb and 58694ff.

📒 Files selected for processing (9)
  • cmd/silo/main.go
  • docs/superpowers/specs/2026-07-08-s3-artwork-reconcile-design.md
  • internal/branding/service.go
  • internal/metadata/artwork_reconcile.go
  • internal/metadata/artwork_reconcile_test.go
  • internal/taskmanager/tasks/reconcile_artwork_cache.go
  • internal/taskmanager/tasks/reconcile_artwork_cache_test.go
  • web/src/pages/admin-settings/StorageSettings.test.tsx
  • web/src/pages/admin-settings/StorageSettings.tsx

Comment thread internal/metadata/artwork_reconcile.go Resolved
Comment thread internal/metadata/artwork_reconcile.go Resolved
Address the confirmed findings from the PR review:

- Fingerprint the key prefix case-sensitively and slash-trimmed exactly
  as s3client applies it (new exported NormalizeKeyPrefix): a case-only
  prefix edit is a real storage move and must reconcile; a slash-only
  edit is not and must not.
- Certify the storage fingerprint immediately after the artwork sweep
  succeeds and make the 4-object branding check non-fatal (reported in
  the task message), so a transient branding error cannot discard a
  completed catalog sweep and force it to repeat every boot.
- Fail closed on conditional-task preflight errors in the task manager
  (previously fail-open ran the task), and retry transient settings
  reads in ShouldRun since the startup trigger fires once per process.
- Track probe HEAD errors against a separate baseline so a flaky probe
  cannot consume the sweep's error budget.
- Probe before counting: bulk mode skips the per-surface count(*)
  full scans entirely, and probe sampling drops ORDER BY random()
  (plain LIMIT answers "is the cache in this bucket" just as well).
- Verify chapter thumbnails across a whole 500-file batch in one HEAD
  fan-out instead of per file, keeping the worker pool saturated.
- Replace the 10 inline non-provider-scheme ARRAY literals in the
  enqueue query with the shared nonProviderImageSchemesSQL constant.

Part of #348

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Quick104 commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

Pushed c5b8f6d addressing the confirmed findings from a high-effort code review of this PR (8 finder angles + adversarial verification per finding):

Correctness

  • Fingerprint normalization now matches real S3 semantics. The key prefix was being lowercased, so a case-only prefix edit (a genuine storage move — S3 keys are case-sensitive) produced an identical fingerprint and the reconcile never fired. It now stays case-sensitive and is slash-trimmed exactly like the client applies it (s3client.NormalizeKeyPrefix, newly exported), so slash-only cosmetic edits no longer trigger pointless sweeps either.
  • A completed sweep is certified before the branding check runs. Previously a transient error on the 4-object branding pass discarded the finished catalog sweep (fingerprint never persisted), repeating the full HEAD sweep every boot until branding storage recovered. Branding failures are now non-fatal and surfaced in the task completion message.
  • Conditional-task preflight now fails closed in the task manager. A ShouldRun error used to log "running task" and fail open — a startup DB blip would launch the full sweep for an unchanged provider. It now skips and rearms (covers all ScheduledConditionalTasks), and this task's ShouldRun retries transient settings reads since the startup trigger fires once per process.
  • Probe errors no longer consume the sweep's error budget — they're tracked against a separate baseline, so a flaky-but-reachable probe can't abort the sweep early.

Efficiency

  • Probe runs first and bulk mode skips the per-surface count(*) full scans entirely; probe sampling drops ORDER BY random() (which forced full scan + sort per surface) for plain LIMIT sampling.
  • Chapter thumbnails are verified across a whole 500-file batch in one HEAD fan-out instead of per file, keeping the 16-worker pool saturated.

Conventions

  • The 10 inline non-provider-scheme ARRAY[...] literals in the enqueue query now use the shared nonProviderImageSchemesSQL constant.

Two PLAUSIBLE (unconfirmed) findings were intentionally left as-is and are noted for posterity: a narrow read-then-clear race in ReconcileMissingAssets vs a concurrent branding upload (fix would need a compare-and-set on the settings store), and per-row UPDATEs in verify mode vs set-based grouping (pgx.Batch already pipelines round-trips; the remaining cost is parse/plan overhead near the bulk threshold).

New/updated tests: fail-closed manager preflight, fingerprint case/slash semantics, branding-failure-is-non-fatal with fingerprint certification, storage-unreachable abort leaving rows untouched, and the sweep-level skip-on-error path. Full suites for internal/metadata, internal/taskmanager/..., internal/s3client, and internal/branding pass against a fresh migrated DB; lint clean on touched lines.

🤖 Generated with Claude Code

… clean sweeps

Address bot review feedback on the reconcile hardening:

- A probe where more than half the HEAD requests error aborts the run:
  errored requests are excluded from the sample, so a partial outage
  could otherwise present a handful of surviving 404s as a ~100% miss
  rate and bulk-reset the catalog. Bulk mode additionally requires a
  minimum number of successful samples; thinned probes and tiny
  catalogs take the safe per-row verify path.
- Track sweep errors separately from probe/branding errors
  (stats.sweep_errors) and certify the storage fingerprint only when
  the sweep completed with zero of them — skipped rows were never
  verified, so the next startup retries. Applied resets stay durable.
- Give each ObjectExists attempt its own timeout so a stalled HEAD
  fails that attempt instead of pinning the retry loop to the run
  context.
- Report branding assets checked (not just cleared) in stats.Checked.
- Drop the dead settingsRepo/brandingSvc nil guards in cmd/silo and
  sync spec numbers with the implementation constants.

Part of #348

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Quick104 commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 8f864ef addressing the remaining review feedback (Codex P1/P2 + CodeRabbit actionable comments and nitpicks):

  • Bulk reset is now guarded against degraded probes (Codex P1, CodeRabbit Major): the run aborts when >50% of probe HEADs error, and bulk mode requires ≥25 successful samples — a partial outage can no longer present a handful of surviving 404s as a catalog-wide miss.
  • Fingerprint certification requires a clean sweep (CodeRabbit Major): sweep errors are tracked separately (stats.sweep_errors) from probe/branding errors; any skipped-unverified row leaves the fingerprint stale so the next startup retries, while applied resets stay durable. Probe errors intentionally don't block certification (probed keys are re-checked by the sweep) — that's what keeps a single flaky probe HEAD from repeating the whole sweep forever.
  • Per-attempt HEAD timeout (CodeRabbit Minor): each ObjectExists attempt runs under its own 15s context.
  • Nitpicks: branding now reports assets checked (not just cleared) in stats.Checked via a widened ReconcileMissingAssets signature; the dead settingsRepo/brandingSvc nil guards in cmd/silo are gone; spec numbers are synced to the implementation constants. The ORDER BY random() comment was already resolved in c5b8f6d (plain LIMIT sampling).
  • Codex P2 (prefix case-sensitivity) was already fixed in c5b8f6d.

New tests: below-minimum-sample bulk suppression, sweep-errors-block-certification, branding checked/cleared accounting. All suites pass against a fresh migrated DB; lint clean on touched lines; make verify-local-paths passes.

🤖 Generated with Claude Code

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

🧹 Nitpick comments (2)
internal/taskmanager/tasks/reconcile_artwork_cache.go (2)

97-117: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Skip the wait after the final failed attempt.

The loop still waits out the timer after the last (3rd) failed attempt before returning the error, adding an unnecessary ~3s delay to an already-failing preflight.

♻️ Suggested fix
 	for attempt := 0; attempt < 3; attempt++ {
 		stored, err = t.settings.Get(ctx, ArtworkStorageIdentityKey)
 		if err == nil {
 			return stored != "" && stored != t.identity, nil
 		}
+		if attempt == 2 {
+			break
+		}
 		timer := time.NewTimer(time.Duration(attempt+1) * time.Second)
 		select {
 		case <-timer.C:
 		case <-ctx.Done():
 			timer.Stop()
 			return false, ctx.Err()
 		}
 	}
 	return false, fmt.Errorf("reading artwork storage identity: %w", 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/taskmanager/tasks/reconcile_artwork_cache.go` around lines 97 - 117,
The retry loop in ShouldRun still sleeps after the final failed Get attempt,
causing an unnecessary delay before returning the error. Update the retry logic
in ReconcileArtworkCacheTask.ShouldRun so the timer/backoff is only applied when
another attempt will follow, and skip waiting after the third failure before
returning the wrapped error.

146-151: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Attach result data before returning on the fingerprint-persist error path too.

Unlike the other two error returns in this function (runner error, sweep errors), the t.settings.Set failure path returns without calling progress.SetResultData, dropping the completed sweep's stats from the task result.

🩹 Suggested fix
 	if setErr := t.settings.Set(ctx, ArtworkStorageIdentityKey, t.identity); setErr != nil {
+		if data, marshalErr := json.Marshal(stats); marshalErr == nil {
+			progress.SetResultData(data)
+		}
 		return fmt.Errorf("persisting artwork storage identity: %w", setErr)
 	}
🤖 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/taskmanager/tasks/reconcile_artwork_cache.go` around lines 146 -
151, The t.settings.Set failure path in reconcileArtworkCache currently returns
before progress.SetResultData, so the completed sweep stats are lost on
fingerprint-persist errors. Update reconcileArtworkCache to attach the same
result data on this error path as the runner and sweep error paths, using the
existing progress.SetResultData flow before returning the formatted error, so
the task result still records the sweep outcome.
🤖 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.

Nitpick comments:
In `@internal/taskmanager/tasks/reconcile_artwork_cache.go`:
- Around line 97-117: The retry loop in ShouldRun still sleeps after the final
failed Get attempt, causing an unnecessary delay before returning the error.
Update the retry logic in ReconcileArtworkCacheTask.ShouldRun so the
timer/backoff is only applied when another attempt will follow, and skip waiting
after the third failure before returning the wrapped error.
- Around line 146-151: The t.settings.Set failure path in reconcileArtworkCache
currently returns before progress.SetResultData, so the completed sweep stats
are lost on fingerprint-persist errors. Update reconcileArtworkCache to attach
the same result data on this error path as the runner and sweep error paths,
using the existing progress.SetResultData flow before returning the formatted
error, so the task result still records the sweep outcome.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f03de320-e9a1-4952-88da-f1abe0cf2ccf

📥 Commits

Reviewing files that changed from the base of the PR and between 58694ff and 8f864ef.

📒 Files selected for processing (11)
  • cmd/silo/main.go
  • docs/superpowers/specs/2026-07-08-s3-artwork-reconcile-design.md
  • internal/branding/service.go
  • internal/metadata/artwork_reconcile.go
  • internal/metadata/artwork_reconcile_test.go
  • internal/metadata/image_cache_job_repo.go
  • internal/s3client/client.go
  • internal/taskmanager/manager.go
  • internal/taskmanager/manager_test.go
  • internal/taskmanager/tasks/reconcile_artwork_cache.go
  • internal/taskmanager/tasks/reconcile_artwork_cache_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • cmd/silo/main.go
  • internal/metadata/artwork_reconcile.go

Resolve taskmanager conflicts: keep this branch's fail-closed preflight
(skip the task when ShouldRun errors) while adopting main's WarnContext
slog standardization.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 merged commit ca6d0e4 into main Jul 9, 2026
1 check was pending
@Quick104
Quick104 deleted the feat/artwork-cache-reconcile branch July 9, 2026 16:00
Quick104 added a commit that referenced this pull request Jul 10, 2026
…ges (#349)

* feat(metadata): reconcile artwork cache after public S3 provider changes

Changing the public S3 provider previously broke every cached image
permanently: the DB keeps bucket-relative keys, the image cache pipeline
treats a cached path as its durable dedup marker and never re-enqueues,
and clients eat the 404s straight from S3 so the server never notices.

Add a storage identity fingerprint (s3.public_storage_identity, seeded
via SetIfAbsent at boot) and a reconcile_artwork_cache task whose
startup trigger only fires when the identity changed; manual runs
always sweep, doubling as bucket-data-loss recovery. The task probes a
random sample of cached objects, then either bulk-resets (near-total
miss) or per-row verifies. Missing provider-sourced artwork is reset to
its *_source_path so the existing enqueue loop re-caches it; surfaces
without a re-downloadable source (chapter thumbnails, collection
artwork, library posters, branding refs, embedded book covers) are
cleared so their owning pipelines refill them. Small upload-holding
tables are always per-row verified so bulk mode cannot blind-clear an
upload that survived migration, and transport errors never reset rows.

Users never see broken images during the transition: reset rows serve
the provider's original URL via the existing absolute-URL pass-through
and thumbhashes are preserved. The storage settings page now warns that
uploads cannot be re-downloaded when the identity fields are edited.

Part of #348

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(metadata): harden artwork reconcile per code review

Address the confirmed findings from the PR review:

- Fingerprint the key prefix case-sensitively and slash-trimmed exactly
  as s3client applies it (new exported NormalizeKeyPrefix): a case-only
  prefix edit is a real storage move and must reconcile; a slash-only
  edit is not and must not.
- Certify the storage fingerprint immediately after the artwork sweep
  succeeds and make the 4-object branding check non-fatal (reported in
  the task message), so a transient branding error cannot discard a
  completed catalog sweep and force it to repeat every boot.
- Fail closed on conditional-task preflight errors in the task manager
  (previously fail-open ran the task), and retry transient settings
  reads in ShouldRun since the startup trigger fires once per process.
- Track probe HEAD errors against a separate baseline so a flaky probe
  cannot consume the sweep's error budget.
- Probe before counting: bulk mode skips the per-surface count(*)
  full scans entirely, and probe sampling drops ORDER BY random()
  (plain LIMIT answers "is the cache in this bucket" just as well).
- Verify chapter thumbnails across a whole 500-file batch in one HEAD
  fan-out instead of per file, keeping the worker pool saturated.
- Replace the 10 inline non-provider-scheme ARRAY literals in the
  enqueue query with the shared nonProviderImageSchemesSQL constant.

Part of #348

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(metadata): guard bulk reset against degraded probes, certify only clean sweeps

Address bot review feedback on the reconcile hardening:

- A probe where more than half the HEAD requests error aborts the run:
  errored requests are excluded from the sample, so a partial outage
  could otherwise present a handful of surviving 404s as a ~100% miss
  rate and bulk-reset the catalog. Bulk mode additionally requires a
  minimum number of successful samples; thinned probes and tiny
  catalogs take the safe per-row verify path.
- Track sweep errors separately from probe/branding errors
  (stats.sweep_errors) and certify the storage fingerprint only when
  the sweep completed with zero of them — skipped rows were never
  verified, so the next startup retries. Applied resets stay durable.
- Give each ObjectExists attempt its own timeout so a stalled HEAD
  fails that attempt instead of pinning the retry loop to the run
  context.
- Report branding assets checked (not just cleared) in stats.Checked.
- Drop the dead settingsRepo/brandingSvc nil guards in cmd/silo and
  sync spec numbers with the implementation constants.

Part of #348

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request Aug 19, 2026
2 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.

1 participant