fix(stats): roll up every completed day still held hourly

The daily pass rolled up only yesterday, once a day at hour 0. A pass that ran before its last hour was aggregated, or that a restart skipped, left that day short or empty, and the hourly rows were deleted after seven days. Each pass now recomputes the six completed days before today.
This commit is contained in:
2026-11-23 13:15:33 +00:00
parent 990a1d3409
commit ad4e848e2b
4 changed files with 158 additions and 8 deletions
+21 -6
View File
@@ -7,11 +7,16 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// rollupDays is how many completed days each daily pass recomputes; it must stay
// below the hourly retention of 7 days.
const rollupDays = 6
// AggregationWorker handles background aggregation of download statistics // AggregationWorker handles background aggregation of download statistics
type AggregationWorker struct { type AggregationWorker struct {
db *gorm.DB db *gorm.DB
stopChan chan struct{} stopChan chan struct{}
ticker *time.Ticker ticker *time.Ticker
now func() time.Time // nil means time.Now
} }
// NewAggregationWorker creates a new aggregation worker // NewAggregationWorker creates a new aggregation worker
@@ -23,6 +28,14 @@ func NewAggregationWorker(db *gorm.DB) *AggregationWorker {
} }
} }
// clock returns the worker's current time.
func (w *AggregationWorker) clock() time.Time {
if w.now != nil {
return w.now()
}
return time.Now()
}
// Start begins the aggregation worker // Start begins the aggregation worker
func (w *AggregationWorker) Start() { func (w *AggregationWorker) Start() {
log.Info().Msg("Starting aggregation worker") log.Info().Msg("Starting aggregation worker")
@@ -69,7 +82,7 @@ func (w *AggregationWorker) AggregateHourly() error {
dialectName := w.db.Name() dialectName := w.db.Name()
// Calculate cutoff time (aggregate events older than 5 minutes to avoid partial data) // Calculate cutoff time (aggregate events older than 5 minutes to avoid partial data)
cutoff := time.Now().Add(-5 * time.Minute).Truncate(time.Hour) cutoff := w.clock().Add(-5 * time.Minute).Truncate(time.Hour)
return w.db.Transaction(func(tx *gorm.DB) error { return w.db.Transaction(func(tx *gorm.DB) error {
var aggregateSQL string var aggregateSQL string
@@ -245,9 +258,11 @@ func (w *AggregationWorker) AggregateDaily() error {
dialectName := w.db.Name() dialectName := w.db.Name()
// Aggregate yesterday's data // Roll up every completed day whose hourly rows are still held. A pass that
yesterday := time.Now().AddDate(0, 0, -1).Truncate(24 * time.Hour) // ran before its last hour was aggregated, or never ran, is repaired by the
dayEnd := yesterday.Add(24 * time.Hour) // next one; the hourly rows are kept for longer than rollupDays.
dayEnd := w.clock().UTC().Truncate(24 * time.Hour)
firstDay := dayEnd.Add(-rollupDays * 24 * time.Hour)
return w.db.Transaction(func(tx *gorm.DB) error { return w.db.Transaction(func(tx *gorm.DB) error {
var aggregateSQL string var aggregateSQL string
@@ -319,12 +334,12 @@ func (w *AggregationWorker) AggregateDaily() error {
` `
} }
if err := tx.Exec(aggregateSQL, yesterday, dayEnd).Error; err != nil { if err := tx.Exec(aggregateSQL, firstDay, dayEnd).Error; err != nil {
return err return err
} }
// Delete old hourly stats (keep last 7 days) // Delete old hourly stats (keep last 7 days)
deleteOlder := time.Now().AddDate(0, 0, -7) deleteOlder := w.clock().AddDate(0, 0, -7)
deleteResult := tx.Exec("DELETE FROM download_stats_hourly WHERE time_bucket < ?", deleteOlder) deleteResult := tx.Exec("DELETE FROM download_stats_hourly WHERE time_bucket < ?", deleteOlder)
if deleteResult.Error != nil { if deleteResult.Error != nil {
return deleteResult.Error return deleteResult.Error
+11 -2
View File
@@ -24,7 +24,8 @@ type GORMStoreV2 struct {
registryCache map[string]int32 // Cache registry name -> ID mapping registryCache map[string]int32 // Cache registry name -> ID mapping
aggregationWorker *AggregationWorker aggregationWorker *AggregationWorker
partitionManager *PartitionManager partitionManager *PartitionManager
registryCacheMu sync.RWMutex // Protects registryCache for concurrent access registryCacheMu sync.RWMutex // Protects registryCache for concurrent access
now func() time.Time // nil means time.Now
} }
// NewV2 creates a new GORM-based metadata store with V2 schema // NewV2 creates a new GORM-based metadata store with V2 schema
@@ -695,6 +696,14 @@ func (s *GORMStoreV2) Close() error {
return sqlDB.Close() return sqlDB.Close()
} }
// clock returns the store's current time.
func (s *GORMStoreV2) clock() time.Time {
if s.now != nil {
return s.now()
}
return time.Now()
}
// GetTimeSeriesStats returns time-series download statistics // GetTimeSeriesStats returns time-series download statistics
func (s *GORMStoreV2) GetTimeSeriesStats(ctx context.Context, period string, registry string) (*metadata.TimeSeriesStats, error) { func (s *GORMStoreV2) GetTimeSeriesStats(ctx context.Context, period string, registry string) (*metadata.TimeSeriesStats, error) {
stats := &metadata.TimeSeriesStats{ stats := &metadata.TimeSeriesStats{
@@ -703,7 +712,7 @@ func (s *GORMStoreV2) GetTimeSeriesStats(ctx context.Context, period string, reg
DataPoints: make([]*metadata.TimeSeriesDataPoint, 0), DataPoints: make([]*metadata.TimeSeriesDataPoint, 0),
} }
now := time.Now().UTC() now := s.clock().UTC()
var span, bucketDuration time.Duration var span, bucketDuration time.Duration
daily := false daily := false
switch period { switch period {
@@ -0,0 +1,45 @@
//go:build pgintegration
package gormstore
import (
"context"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/require"
)
// The missed-day repair on the production dialect: hourly rows are written directly so the
// test needs no download_events partition for a past month.
func TestPostgresDailyRollupCoversMissedDay(t *testing.T) {
ctx := context.Background()
store, _ := newPostgresStore(t)
day := time.Now().UTC().Truncate(24 * time.Hour).Add(-10 * 24 * time.Hour)
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
Size: 10, CachedAt: day, LastAccessed: day,
}))
registryID, err := store.getRegistryID("npm")
require.NoError(t, err)
var packageID int64
require.NoError(t, store.db.Table("packages").Select("id").Where("name = ?", "left-pad").Scan(&packageID).Error)
for _, hour := range []int{5, 6, 7} {
require.NoError(t, store.db.Exec(
`INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
VALUES (?, ?, ?, 1, 1, 0, NOW(), NOW())`, registryID, packageID, day.Add(time.Duration(hour)*time.Hour)).Error)
}
for d := 2; d <= 9; d++ {
at := day.Add(time.Duration(d)*24*time.Hour + 30*time.Minute)
store.aggregationWorker.now = func() time.Time { return at }
require.NoError(t, store.aggregationWorker.AggregateDaily())
}
store.now = func() time.Time { return day.Add(9*24*time.Hour + time.Hour) }
ts, err := store.GetTimeSeriesStats(ctx, "30day", "")
require.NoError(t, err)
require.EqualValues(t, 3, sumPoints(ts))
}
@@ -0,0 +1,81 @@
package gormstore
import (
"context"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/require"
)
// newRollupStore adds the unique indexes Postgres gets from the partition manager,
// so INSERT OR REPLACE upserts as the ON CONFLICT clauses do there.
func newRollupStore(t *testing.T) *GORMStoreV2 {
t.Helper()
store := newTimeSeriesStore(t)
for _, stmt := range statsUpsertIndexes {
require.NoError(t, store.db.Exec(stmt).Error)
}
return store
}
// tick mirrors AggregationWorker.Start: an hourly pass, plus the daily pass in hour 0.
func tick(t *testing.T, store *GORMStoreV2, at time.Time, daily bool) {
t.Helper()
store.aggregationWorker.now = func() time.Time { return at }
require.NoError(t, store.aggregationWorker.AggregateHourly())
if daily && at.Hour() == 0 {
require.NoError(t, store.aggregationWorker.AggregateDaily())
}
}
func seedEventsAt(t *testing.T, store *GORMStoreV2, times ...time.Time) {
t.Helper()
ctx := context.Background()
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
Size: 10, CachedAt: times[0], LastAccessed: times[0],
}))
for _, at := range times {
require.NoError(t, store.UpdateDownloadCount(ctx, "npm", "left-pad", "1.3.0"))
var id int64
require.NoError(t, store.db.Table("download_events").Select("MAX(id)").Scan(&id).Error)
require.NoError(t, store.db.Exec("UPDATE download_events SET downloaded_at = ? WHERE id = ?", at, id).Error)
}
}
func totalAt(t *testing.T, store *GORMStoreV2, at time.Time, period string) int64 {
t.Helper()
store.now = func() time.Time { return at }
ts, err := store.GetTimeSeriesStats(context.Background(), period, "")
require.NoError(t, err)
return sumPoints(ts)
}
// A download in the last hour of a day that the daily pass ran before that hour was aggregated.
func TestDailyRollupKeepsLastHourOfDay(t *testing.T) {
store := newRollupStore(t)
day := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
seedEventsAt(t, store, day.Add(10*time.Hour), day.Add(23*time.Hour+30*time.Minute))
tick(t, store, day.Add(24*time.Hour+2*time.Minute), true) // cutoff 23:00: the 23:30 event is not counted yet
tick(t, store, day.Add(25*time.Hour+2*time.Minute), true)
tick(t, store, day.Add(48*time.Hour+3*time.Minute), true)
require.EqualValues(t, 2, totalAt(t, store, day.Add(48*time.Hour+10*time.Minute), "7day"))
}
// A day whose midnight daily pass never ran must still be rolled up before its hourly rows expire.
func TestDailyRollupCoversMissedDay(t *testing.T) {
store := newRollupStore(t)
day := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
seedEventsAt(t, store, day.Add(5*time.Hour), day.Add(6*time.Hour), day.Add(7*time.Hour))
tick(t, store, day.Add(24*time.Hour+30*time.Minute), false) // process restarting at midnight: no daily pass
for d := 2; d <= 9; d++ {
tick(t, store, day.Add(time.Duration(d)*24*time.Hour+30*time.Minute), true)
}
require.EqualValues(t, 3, totalAt(t, store, day.Add(9*24*time.Hour+time.Hour), "30day"))
}