Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 86 additions & 3 deletions internal/metadata/artwork_storage_sweep.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strings"
"time"

"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"

"github.com/Silo-Server/silo-server/internal/blobstore"
Expand Down Expand Up @@ -86,6 +87,7 @@ type ArtworkStorageSweepStats struct {
Referenced int `json:"referenced"`
TooNew int `json:"too_new"`
LeftToGC int `json:"left_to_gc"`
Held int `json:"held"`
Unparsable int `json:"unparsable"`
Deleted int `json:"deleted"`
Pages int `json:"pages"`
Expand Down Expand Up @@ -355,8 +357,9 @@ func (s *ArtworkStorageSweeper) SweepPrefix(ctx context.Context, prefix, token s
}

if len(doomed) > 0 {
deleted, delErr := s.store.Delete(ctx, doomed)
requested, deleted, delErr := s.deleteUnlessRecached(ctx, doomed, doomedOriginals)
stats.Deleted += deleted
stats.Held += len(doomed) - len(requested)
if delErr != nil {
// Move the cursor past this page anyway. The objects stay
// unreferenced, so the next pass over this prefix retries them;
Expand All @@ -366,12 +369,12 @@ func (s *ArtworkStorageSweeper) SweepPrefix(ctx context.Context, prefix, token s
stats.PrefixDone = next == ""
return stats, fmt.Errorf("artwork storage sweep: delete: %w", delErr)
}
if deleted != len(doomed) {
if deleted != len(requested) {
// A short count means per-object failures. The objects stay
// unreferenced, so the next pass over this prefix retries
// them; there is nothing to repair and nothing is lost.
slog.WarnContext(ctx, "artwork storage sweep: partial delete",
"component", "metadata", "prefix", prefix, "requested", len(doomed), "deleted", deleted)
"component", "metadata", "prefix", prefix, "requested", len(requested), "deleted", deleted)
}
}

Expand All @@ -383,3 +386,83 @@ func (s *ArtworkStorageSweeper) SweepPrefix(ctx context.Context, prefix, token s
}
return stats, nil
}

// deleteUnlessRecached deletes the doomed objects (keys[i] belongs to the
// revision originals[i]) under the same row locks as the revision GC, sparing
// any revision the image cache is caching again. It returns the keys it asked
// storage to delete.
//
// The cache registers a revision with the tracker, finds its content-addressed
// objects already stored, skips the upload, and publishes the path. Deleting
// after that check leaves the catalog pointing at missing artwork. So each
// revision's candidate row is held for the delete: a placeholder row for an
// untracked revision, a row lock for a tracked one. A tracker upsert arriving
// meanwhile waits until the objects are gone, and the cache then uploads them
// again. A row the tracker touched within the age floor means a cache pass may
// be about to publish the path, and a row locked elsewhere is the GC's to
// collect; their objects stay for a later pass or the GC. (Inserting the
// placeholders waits for an upsert already in flight, so its row then shows
// as recently touched.)
//
// The transaction always rolls back: it only holds locks, and rolling back
// drops the placeholders.
func (s *ArtworkStorageSweeper) deleteUnlessRecached(ctx context.Context, keys, originals []string) ([]string, int, error) {
if s.pool == nil {
deleted, err := s.store.Delete(ctx, keys)
return keys, deleted, err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return nil, 0, fmt.Errorf("begin: %w", err)
}
defer func() {
// Bounded like the GC's tombstone commit, so a broken connection
// cannot hold the revisions after the sweep has given up.
rollbackCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_ = tx.Rollback(rollbackCtx)
}()

rows, err := tx.Query(ctx, `
INSERT INTO artwork_revision_gc_candidates (original_path, object_keys, not_before)
SELECT p, ARRAY[p], now() FROM unnest($1::text[]) AS p
ON CONFLICT (original_path) DO NOTHING
RETURNING original_path`, originals)
Comment thread
Quick104 marked this conversation as resolved.
Resolved
if err != nil {
return nil, 0, fmt.Errorf("hold untracked revisions: %w", err)
}
placeholders, err := pgx.CollectRows(rows, pgx.RowTo[string])
if err != nil {
return nil, 0, fmt.Errorf("hold untracked revisions: %w", err)
}
// The placeholders were inserted at now(), so this never returns them. A
// revision still inside the GC's grace period stays too.
rows, err = tx.Query(ctx, `
SELECT original_path FROM artwork_revision_gc_candidates
WHERE original_path = ANY($1) AND updated_at < now() - make_interval(secs => $2)
Comment thread
Quick104 marked this conversation as resolved.
Resolved
AND not_before <= now()
FOR UPDATE SKIP LOCKED`, originals, artworkSweepMinAge.Seconds())
if err != nil {
return nil, 0, fmt.Errorf("lock revisions: %w", err)
}
locked, err := pgx.CollectRows(rows, pgx.RowTo[string])
if err != nil {
return nil, 0, fmt.Errorf("lock revisions: %w", err)
}
held := make(map[string]struct{}, len(placeholders)+len(locked))
for _, p := range append(placeholders, locked...) {
held[p] = struct{}{}
}

deletable := make([]string, 0, len(keys))
for i, key := range keys {
if _, ok := held[originals[i]]; ok {
deletable = append(deletable, key)
}
}
if len(deletable) == 0 {
return nil, 0, nil
}
deleted, err := s.store.Delete(ctx, deletable)
return deletable, deleted, err
}
160 changes: 160 additions & 0 deletions internal/metadata/artwork_storage_sweep_recache_db_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
package metadata

import (
"context"
"errors"
"fmt"
"slices"
"testing"
"time"

"github.com/Silo-Server/silo-server/internal/blobstore"
"github.com/Silo-Server/silo-server/internal/catalog"
)

// recacheDuringSweepStorage lists one page and runs onDelete before recording
// a deletion, so a test can re-cache artwork while the sweep is deleting it.
type recacheDuringSweepStorage struct {
page []blobstore.ObjectInfo
onDelete func(keys []string)
deleted []string
}

func (s *recacheDuringSweepStorage) List(context.Context, string, string, int) ([]blobstore.ObjectInfo, string, error) {
return s.page, "", nil
}

func (s *recacheDuringSweepStorage) Delete(_ context.Context, keys []string) (int, error) {
if s.onDelete != nil {
s.onDelete(keys)
}
s.deleted = append(s.deleted, keys...)
return len(keys), nil
}

// separateArtworkRevisionTracker returns a tracker on its own connected pool,
// so a registration that times out can only have waited on the sweep's locks,
// not for a free connection.
func separateArtworkRevisionTracker(ctx context.Context, t *testing.T) *catalog.ArtworkRevisionTracker {
t.Helper()
pool := artworkRevisionGCTestPool(t)
if err := pool.Ping(ctx); err != nil {
t.Fatal(err)
}
return catalog.NewArtworkRevisionTracker(pool)
}

// TestArtworkSweepDeletionSerializesWithRecachingDB covers the image cache
// re-caching an unreferenced revision while the storage sweep deletes it. The
// revision is content-addressed, so the cache registers the same original path
// with the revision tracker, finds the objects already stored, skips the
// upload, and publishes the path. Deleting the objects after that leaves the
// catalog pointing at missing artwork.
func TestArtworkSweepDeletionSerializesWithRecachingDB(t *testing.T) {
pool := artworkRevisionGCTestPool(t)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
tracker := separateArtworkRevisionTracker(ctx, t)

suffix := time.Now().UnixNano()
old := time.Now().Add(-72 * time.Hour)
// ladder returns an aged revision's original path and stored objects, and
// removes any revision row the test leaves for it.
ladder := func(name string) (string, []blobstore.ObjectInfo) {
dir := fmt.Sprintf("tmdb/movies/sweep-%d-%s/poster/", suffix, name)
t.Cleanup(func() {
_, _ = pool.Exec(context.Background(),
`DELETE FROM artwork_revision_gc_candidates WHERE original_path = $1`, dir+"original.rev.webp")
})
return dir + "original.rev.webp", []blobstore.ObjectInfo{
{Key: dir + "original.rev.webp", ModTime: old},
{Key: dir + "w300.rev.webp", ModTime: old},
}
}

// parkRevision tracks a revision as the GC leaves live artwork, last
// touched before the age floor; its reference has since gone.
parkRevision := func(original string) {
t.Helper()
if _, err := pool.Exec(ctx, `
INSERT INTO artwork_revision_gc_candidates (original_path, image_type, not_before, next_attempt_at, updated_at)
VALUES ($1, 'poster', $2, NULL, $2)`, original, old); err != nil {
t.Fatal(err)
}
}

t.Run("a re-cache that starts during the delete waits for it", func(t *testing.T) {
untracked, untrackedObjects := ladder("untracked")
tracked, trackedObjects := ladder("tracked")
parkRevision(tracked)

recacheErrs := map[string]error{}
storage := &recacheDuringSweepStorage{
page: append(untrackedObjects, trackedObjects...),
onDelete: func([]string) {
for _, original := range []string{untracked, tracked} {
waitCtx, stop := context.WithTimeout(ctx, 200*time.Millisecond)
recacheErrs[original] = tracker.TrackArtworkRevision(waitCtx, original, "poster", nil)
stop()
}
},
}
if _, err := NewArtworkStorageSweeper(pool, storage).SweepPrefix(ctx, "tmdb/", "", 1); err != nil {
t.Fatal(err)
}
if len(storage.deleted) != 4 {
t.Fatalf("deleted %v, want both unreferenced ladders", storage.deleted)
}
// Registration must wait until the objects are gone: only then does the
// cache find them missing and upload them again.
for original, err := range recacheErrs {
if !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("re-cache of %s while the sweep was deleting it returned %v, want it to wait", original, err)
}
}
})

t.Run("a revision re-cached after the reference check is kept", func(t *testing.T) {
original, objects := ladder("recached")
storage := &recacheDuringSweepStorage{page: objects}
sweeper := NewArtworkStorageSweeper(pool, storage)
lookup := sweeper.lookup
sweeper.lookup = func(ctx context.Context, paths []string) (map[string]struct{}, error) {
referenced, err := lookup(ctx, paths)
if err == nil && slices.Contains(paths, original) {
// The cache registers the revision and is about to publish it.
err = tracker.TrackArtworkRevision(ctx, original, "poster", nil)
}
return referenced, err
}
if _, err := sweeper.SweepPrefix(ctx, "tmdb/", "", 1); err != nil {
t.Fatal(err)
}
if len(storage.deleted) != 0 {
t.Fatalf("deleted %v, a revision the cache just registered", storage.deleted)
}
})

t.Run("a revision the GC is deleting is left to it", func(t *testing.T) {
original, objects := ladder("collecting")
parkRevision(original)
// The GC holds the row while it deletes the revision's objects.
collecting, err := pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer func() { _ = collecting.Rollback(context.Background()) }()
if _, err := collecting.Exec(ctx,
`SELECT 1 FROM artwork_revision_gc_candidates WHERE original_path = $1 FOR UPDATE`, original); err != nil {
t.Fatal(err)
}

storage := &recacheDuringSweepStorage{page: objects}
if _, err := NewArtworkStorageSweeper(pool, storage).SweepPrefix(ctx, "tmdb/", "", 1); err != nil {
t.Fatal(err)
}
if len(storage.deleted) != 0 {
t.Fatalf("deleted %v, a revision the GC holds", storage.deleted)
}
})
}
3 changes: 3 additions & 0 deletions scripts/ci/db-contracts.txt
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,9 @@
./internal/metadata TestArtworkRevisionGCDormantSweep
./internal/metadata TestArtworkRevisionGCDormantSweepCycles
./internal/metadata TestArtworkRevisionGCDormantCycleEndsWhileRowsArrive
# The artwork storage sweep holds revision rows while it deletes, so a re-cache
# of the same artwork waits and uploads it again instead of reusing doomed objects.
./internal/metadata TestArtworkSweepDeletionSerializesWithRecachingDB

# Persisted notification, request, marker and preview contracts.
./internal/markers TestPopulationSyncResumesAfterQuotaAcrossRuns
Expand Down