feat(cache): purge soft-deleted package rows after a retention period

The cleanup worker now hard-deletes package rows whose deleted_at is
older than cache.deleted_retention. The default is 30 days. A value of
0 keeps the rows. The purge runs in bounded batches, with at most 100
batches per cleanup pass, and removes child rows with the package.

History tables have no foreign key to packages, and stats_snapshots
holds its own counts, so the purge leaves both untouched. The cleanup
log line now reports purged_deleted and deleted_retention.
This commit is contained in:
2026-11-23 14:55:26 +00:00
parent 1512230ab3
commit ba8bc392ec
13 changed files with 360 additions and 7 deletions
+1
View File
@@ -239,6 +239,7 @@ func (a *App) initializeComponents() error {
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
CleanupInterval: cleanupInterval,
IdleTTL: a.config.Cache.IdleTTL,
DeletedRetention: a.config.Cache.DeletedRetention,
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
FailClosed: a.config.Security.FailClosed,
})
+30
View File
@@ -85,6 +85,7 @@ type Config struct {
DefaultTTL time.Duration // Freshness TTL for metadata entries
CleanupInterval time.Duration // How often to run cleanup
IdleTTL time.Duration // Remove entries not requested for this long (0 = off)
DeletedRetention time.Duration // Hard-delete soft-deleted rows older than this (0 = keep forever)
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
MaxConcurrent int // Max concurrent upstream fetches
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
@@ -97,6 +98,9 @@ const defaultScanWaitTimeout = 30 * time.Second
// cleanupBatchSize bounds how many rows one cleanup query reads.
const cleanupBatchSize = metadata.DefaultBatchSize
// maxPurgeBatches bounds the soft-delete purge of one cleanup pass; the next pass continues.
const maxPurgeBatches = 100
// getAttempts bounds how often Get re-resolves an entry whose blob vanished.
const getAttempts = 2
@@ -917,14 +921,40 @@ func (m *Manager) cleanup(ctx context.Context) {
func(p *metadata.Package) bool { return p.LastAccessed.Before(cutoff) })
}
purged := m.purgeDeleted(ctx, start)
log.Info().
Int("expired", expired.count).
Int("idle", idle.count).
Int64("bytes_freed", expired.bytes+idle.bytes).
Dur("idle_ttl", m.config.IdleTTL).
Int64("purged_deleted", purged).
Dur("deleted_retention", m.config.DeletedRetention).
Msg("Cleanup completed")
}
// purgeDeleted hard-deletes soft-deleted rows past DeletedRetention in bounded
// batches and returns how many it removed.
func (m *Manager) purgeDeleted(ctx context.Context, now time.Time) int64 {
if m.config.DeletedRetention <= 0 {
return 0
}
cutoff := now.Add(-m.config.DeletedRetention)
var total int64
for i := 0; i < maxPurgeBatches && ctx.Err() == nil; i++ {
n, err := m.metadata.PurgeDeletedPackages(ctx, cutoff, cleanupBatchSize)
if err != nil {
log.Error().Err(err).Msg("Failed to purge soft-deleted packages")
break
}
total += n
if n < cleanupBatchSize {
break
}
}
return total
}
// generateStorageKey generates a storage key for a package
func (m *Manager) generateStorageKey(registry, name, version string) string {
return fmt.Sprintf("%s/%s/%s", registry, name, version)
+90
View File
@@ -0,0 +1,90 @@
package cache
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
)
// purgeRecorder plays a store holding `pending` soft-deleted rows.
type purgeRecorder struct {
*memMetadata
err error
cutoffs []time.Time
limits []int
pending int64
mu sync.Mutex
}
func (p *purgeRecorder) PurgeDeletedPackages(_ context.Context, before time.Time, limit int) (int64, error) {
p.mu.Lock()
defer p.mu.Unlock()
p.cutoffs = append(p.cutoffs, before)
p.limits = append(p.limits, limit)
if p.err != nil {
return 0, p.err
}
n := min(p.pending, int64(limit))
p.pending -= n
return n, nil
}
func newPurgeHarness(t *testing.T, retention time.Duration, pending int64) (*idleHarness, *purgeRecorder) {
t.Helper()
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
rec := &purgeRecorder{memMetadata: newMemMetadata(h.clock), pending: pending}
h.meta = rec.memMetadata
mgr, err := New(h.store, rec, nil, nil, Config{Now: h.clock.Now, CleanupInterval: 24 * time.Hour, DeletedRetention: retention})
require.NoError(t, err)
t.Cleanup(func() { _ = mgr.Close() })
h.mgr = mgr
return h, rec
}
func TestCleanupPurgesDeletedRowsPastRetention(t *testing.T) {
h, rec := newPurgeHarness(t, 30*day, 3*int64(cleanupBatchSize)+7)
h.mgr.cleanup(context.Background())
require.Zero(t, rec.pending, "batches continue until the store runs dry")
require.Len(t, rec.limits, 4, "three full batches and a short one")
for _, limit := range rec.limits {
require.Equal(t, cleanupBatchSize, limit, "every batch is bounded")
}
require.Equal(t, h.clock.Now().Add(-30*day), rec.cutoffs[0], "the cutoff is now minus the retention")
}
func TestCleanupPurgeIsBoundedPerPass(t *testing.T) {
_, rec := newPurgeHarness(t, 30*day, int64(maxPurgeBatches+50)*int64(cleanupBatchSize))
h := &Manager{config: Config{DeletedRetention: day, Now: time.Now}, metadata: rec}
got := h.purgeDeleted(context.Background(), time.Now())
require.EqualValues(t, maxPurgeBatches*cleanupBatchSize, got)
require.EqualValues(t, 50*cleanupBatchSize, rec.pending, "the next pass continues where this one stopped")
}
func TestCleanupSkipsPurgeWhenRetentionIsZero(t *testing.T) {
h, rec := newPurgeHarness(t, 0, 10)
h.mgr.cleanup(context.Background())
require.Empty(t, rec.limits, "zero keeps every row")
require.EqualValues(t, 10, rec.pending)
}
func TestCleanupPurgeFailureDoesNotStopCleanup(t *testing.T) {
h, rec := newPurgeHarness(t, 30*day, 10)
rec.err = errors.New("db down")
h.get(t, "lodash", "metadata")
h.clock.Advance(2 * day)
h.mgr.cleanup(context.Background())
require.Len(t, rec.limits, 1, "one failed attempt, no retry loop")
require.False(t, h.exists("lodash", "metadata"), "expired metadata is still removed")
}
+16 -7
View File
@@ -157,14 +157,19 @@ func (c CacheConfig) MetadataTTLOverrides() map[string]time.Duration {
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
const DefaultIdleTTL = 7 * 24 * time.Hour
// DefaultDeletedRetention is how long a soft-deleted package row is kept before cleanup purges it.
const DefaultDeletedRetention = 30 * 24 * time.Hour
// CacheConfig contains cache management configuration
type CacheConfig struct {
TTLOverrides map[string]time.Duration `mapstructure:"ttl_overrides" json:"ttl_overrides"`
DefaultTTL time.Duration `mapstructure:"default_ttl" json:"default_ttl"`
CleanupInterval time.Duration `mapstructure:"cleanup_interval" json:"cleanup_interval"`
IdleTTL time.Duration `mapstructure:"idle_ttl" json:"idle_ttl"` // 0 disables idle eviction
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
// DeletedRetention is how long soft-deleted package rows stay before cleanup purges them; 0 keeps them forever.
DeletedRetention time.Duration `mapstructure:"deleted_retention" json:"deleted_retention"`
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
}
// SecurityConfig contains security scanning configuration
@@ -377,11 +382,12 @@ func Default() *Config {
},
},
Cache: CacheConfig{
DefaultTTL: DefaultMetadataTTL,
CleanupInterval: 1 * time.Hour,
IdleTTL: DefaultIdleTTL,
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
DefaultTTL: DefaultMetadataTTL,
CleanupInterval: 1 * time.Hour,
IdleTTL: DefaultIdleTTL,
DeletedRetention: DefaultDeletedRetention,
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
},
Security: SecurityConfig{
Enabled: false,
@@ -541,6 +547,9 @@ func (c *Config) Validate() error {
return fmt.Errorf("cache.ttl_overrides.%s must be positive, got %s", key, ttl)
}
}
if c.Cache.DeletedRetention < 0 {
return fmt.Errorf("cache.deleted_retention cannot be negative")
}
if c.Cache.MaxSizeBytes < 0 {
return fmt.Errorf("cache.max_size_bytes cannot be negative")
}
+41
View File
@@ -0,0 +1,41 @@
package config
import (
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestDeletedRetentionDefaultsToThirtyDays(t *testing.T) {
require.Equal(t, 30*24*time.Hour, Default().Cache.DeletedRetention)
cfg, err := loadCacheYAML(t, "cache:\n default_ttl: 24h\n")
require.NoError(t, err)
require.Equal(t, 30*24*time.Hour, cfg.Cache.DeletedRetention, "an unset key keeps the default")
}
func TestDeletedRetentionParse(t *testing.T) {
tests := []struct {
name string
yaml string
want time.Duration
wantErr bool
}{
{name: "duration string", yaml: "cache:\n deleted_retention: 48h\n", want: 48 * time.Hour},
{name: "zero keeps rows", yaml: "cache:\n deleted_retention: 0\n", want: 0},
{name: "quoted duration", yaml: "cache:\n deleted_retention: \"720h\"\n", want: 720 * time.Hour},
{name: "negative rejected", yaml: "cache:\n deleted_retention: -1h\n", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg, err := loadCacheYAML(t, tt.yaml)
if tt.wantErr {
require.ErrorContains(t, err, "cache.deleted_retention")
return
}
require.NoError(t, err)
require.Equal(t, tt.want, cfg.Cache.DeletedRetention)
})
}
}
+44
View File
@@ -0,0 +1,44 @@
package gormstore
import (
"context"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/errors"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"gorm.io/gorm"
)
// PurgeDeletedPackages hard-deletes up to limit soft-deleted packages deleted
// before deletedBefore, oldest id first, with the rows that reference them.
// Download history and stats snapshots hold no reference and stay.
func (s *GORMStoreV2) PurgeDeletedPackages(ctx context.Context, deletedBefore time.Time, limit int) (int64, error) {
if limit <= 0 {
limit = metadata.DefaultBatchSize
}
var purged int64
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var ids []int64
if err := tx.Unscoped().Model(&PackageModel{}).
Where("deleted_at IS NOT NULL AND deleted_at < ?", deletedBefore).
Order("id").Limit(limit).Pluck("id", &ids).Error; err != nil {
return err
}
if len(ids) == 0 {
return nil
}
// The foreign keys cascade on PostgreSQL and MySQL; SQLite enforces them only when asked.
for _, child := range []interface{}{&PackageVulnerabilityModel{}, &ScanResultModel{}, &PackageMetadataModel{}} {
if err := tx.Unscoped().Where("package_id IN ?", ids).Delete(child).Error; err != nil {
return err
}
}
res := tx.Unscoped().Where("id IN ?", ids).Delete(&PackageModel{})
purged = res.RowsAffected
return res.Error
})
if err != nil {
return 0, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to purge deleted packages")
}
return purged, nil
}
+16
View File
@@ -0,0 +1,16 @@
//go:build pgintegration
package gormstore
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPostgresPurgeDeletedPackages(t *testing.T) {
store, _ := newPostgresStore(t)
require.NoError(t, store.db.Exec("TRUNCATE packages, stats_snapshots, download_stats_daily RESTART IDENTITY CASCADE").Error)
checkPurgeDeletedPackages(t, store)
}
+111
View File
@@ -0,0 +1,111 @@
package gormstore
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func checkPurgeDeletedPackages(t *testing.T, store *GORMStoreV2) {
t.Helper()
ctx := context.Background()
for i := 0; i < 5; i++ {
name := fmt.Sprintf("gone-%d", i)
seedAt(t, store, name, "1.0.0", 10, daysAgo(60))
scanAt(t, store, name, "1.0.0", daysAgo(59), "high")
require.NoError(t, store.db.Create(&PackageMetadataModel{PackageID: packageID(t, store, name)}).Error)
}
seedAt(t, store, "live", "1.0.0", 10, daysAgo(60))
scanAt(t, store, "live", "1.0.0", daysAgo(59), "high")
seedAt(t, store, "recent", "1.0.0", 10, daysAgo(60))
softDeleteAt(t, store, "recent", "1.0.0", daysAgo(5))
for i := 0; i < 5; i++ {
softDeleteAt(t, store, fmt.Sprintf("gone-%d", i), "1.0.0", daysAgo(40-i))
}
// History survives the purge: snapshots and download rows hold their own counts.
days, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
require.NoError(t, err)
require.Positive(t, days)
snapshotsBefore := trendByDay(t, store, daysAgo(100))
require.NoError(t, store.db.Create(&DownloadStatsDailyModel{
TimeBucket: daysAgo(45), RegistryID: 1, PackageID: ptr(packageIDUnscoped(t, store, "gone-0")), DownloadCount: 9,
}).Error)
cutoff := today().AddDate(0, 0, -30)
n, err := store.PurgeDeletedPackages(ctx, cutoff, 2)
require.NoError(t, err)
require.EqualValues(t, 2, n, "bounded by the batch limit")
require.EqualValues(t, 3, countRows(t, store, "gone-%", true), "oldest deletions go first")
n, err = store.PurgeDeletedPackages(ctx, cutoff, 100)
require.NoError(t, err)
require.EqualValues(t, 3, n)
n, err = store.PurgeDeletedPackages(ctx, cutoff, 100)
require.NoError(t, err)
require.Zero(t, n, "nothing left past the retention")
require.Zero(t, countRows(t, store, "gone-%", true))
require.EqualValues(t, 1, countRows(t, store, "recent", true), "a deletion inside the retention stays")
require.EqualValues(t, 1, countRows(t, store, "live", false), "an active package is never purged")
var children int64
for _, table := range []string{"scan_results", "package_vulnerabilities", "package_metadata"} {
var rows int64
require.NoError(t, store.db.Table(table).Count(&rows).Error)
children += rows
}
require.EqualValues(t, 1, children, "only the live package keeps its scan row; vulnerability and metadata rows left with their packages")
var scans int64
require.NoError(t, store.db.Model(&ScanResultModel{}).Count(&scans).Error)
require.EqualValues(t, 1, scans)
require.Equal(t, snapshotsBefore, trendByDay(t, store, daysAgo(100)), "snapshots are untouched")
var daily int64
require.NoError(t, store.db.Model(&DownloadStatsDailyModel{}).Count(&daily).Error)
require.EqualValues(t, 1, daily, "download history is untouched")
again, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
require.NoError(t, err)
require.Zero(t, again, "the backfill never rewrites history after a purge")
}
func packageID(t *testing.T, store *GORMStoreV2, name string) int64 {
t.Helper()
var id int64
require.NoError(t, store.db.Model(&PackageModel{}).Where("name = ?", name).Pluck("id", &id).Error)
return id
}
func packageIDUnscoped(t *testing.T, store *GORMStoreV2, name string) int64 {
t.Helper()
var id int64
require.NoError(t, store.db.Unscoped().Model(&PackageModel{}).Where("name = ?", name).Pluck("id", &id).Error)
return id
}
func countRows(t *testing.T, store *GORMStoreV2, namePattern string, deleted bool) int64 {
t.Helper()
q := store.db.Unscoped().Model(&PackageModel{}).Where("name LIKE ?", namePattern)
if deleted {
q = q.Where("deleted_at IS NOT NULL")
} else {
q = q.Where("deleted_at IS NULL")
}
var n int64
require.NoError(t, q.Count(&n).Error)
return n
}
func TestBackfillStatsSnapshots(t *testing.T) { checkBackfillStatsSnapshots(t, newTimeSeriesStore(t)) }
func TestBackfillWithoutScans(t *testing.T) { checkBackfillWithoutScans(t, newTimeSeriesStore(t)) }
func TestSnapshotStats(t *testing.T) { checkSnapshotStats(t, newTimeSeriesStore(t)) }
func TestTrendWindow(t *testing.T) { checkTrendWindow(t, newTimeSeriesStore(t)) }
func TestTrendStatementsAreConstant(t *testing.T) {
checkTrendStatementsAreConstant(t, newTimeSeriesStore(t))
}
func TestPurgeDeletedPackages(t *testing.T) { checkPurgeDeletedPackages(t, newTimeSeriesStore(t)) }
+5
View File
@@ -86,6 +86,11 @@ type MetadataStore interface {
// the given time, oldest first. A limit <= 0 means DefaultBatchSize.
ListExpiredPackages(ctx context.Context, expiredBefore time.Time, limit int) ([]*Package, error)
// PurgeDeletedPackages hard-deletes up to limit soft-deleted packages whose
// deletion is older than deletedBefore, with their scan and vulnerability
// rows, and returns the number removed. A limit <= 0 means DefaultBatchSize.
PurgeDeletedPackages(ctx context.Context, deletedBefore time.Time, limit int) (int64, error)
// GetStatsTrend returns the daily stats snapshots from the UTC day of since
// on, oldest first. Backends without history return none.
GetStatsTrend(ctx context.Context, since time.Time) ([]*StatsSnapshot, error)