diff --git a/pkg/metadata/gormstore/gormstore_v2.go b/pkg/metadata/gormstore/gormstore_v2.go index 803a559..c8714f3 100644 --- a/pkg/metadata/gormstore/gormstore_v2.go +++ b/pkg/metadata/gormstore/gormstore_v2.go @@ -24,8 +24,8 @@ type GORMStoreV2 struct { registryCache map[string]int32 // Cache registry name -> ID mapping aggregationWorker *AggregationWorker partitionManager *PartitionManager - registryCacheMu sync.RWMutex // Protects registryCache for concurrent access now func() time.Time // nil means time.Now + registryCacheMu sync.RWMutex // Protects registryCache for concurrent access } // NewV2 creates a new GORM-based metadata store with V2 schema @@ -764,13 +764,17 @@ func (s *GORMStoreV2) GetTimeSeriesStats(ctx context.Context, period string, reg } if daily { - // A completed day's rollup is authoritative over its leftover hourly rows. rollups, err := s.aggregateRows(ctx, "download_stats_daily", since, now, registryID) if err != nil { return nil, err } + // Hourly rows and events only ever undercount a day, so the larger of the + // two is the better figure; a rollup alone covers days already trimmed. for _, r := range rollups { - counts[r.Timestamp.UTC().Truncate(bucketDuration).Unix()] = r.Value + day := r.Timestamp.UTC().Truncate(bucketDuration).Unix() + if r.Value > counts[day] { + counts[day] = r.Value + } } } diff --git a/pkg/metadata/gormstore/rollup_coverage_test.go b/pkg/metadata/gormstore/rollup_coverage_test.go index aa2bf0b..776f2a3 100644 --- a/pkg/metadata/gormstore/rollup_coverage_test.go +++ b/pkg/metadata/gormstore/rollup_coverage_test.go @@ -79,3 +79,27 @@ func TestDailyRollupCoversMissedDay(t *testing.T) { require.EqualValues(t, 3, totalAt(t, store, day.Add(9*24*time.Hour+time.Hour), "30day")) } + +// Hourly rows and events never overcount a day, so a rollup that is behind them must not win. +func TestTimeSeriesKeepsLateDownloadsAheadOfRollup(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) // rollup counts one download + tick(t, store, day.Add(25*time.Hour+2*time.Minute), true) // the 23:30 download reaches the hourly table + + require.EqualValues(t, 2, totalAt(t, store, day.Add(26*time.Hour), "7day")) +} + +// A rollup larger than the hourly rows still wins once the hourly rows have been trimmed. +func TestTimeSeriesKeepsRollupWhenHourlyRowsAreGone(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(11*time.Hour), day.Add(12*time.Hour)) + + tick(t, store, day.Add(24*time.Hour+30*time.Minute), true) + require.NoError(t, store.db.Exec("DELETE FROM download_stats_hourly WHERE time_bucket = ?", day.Add(12*time.Hour)).Error) + + require.EqualValues(t, 3, totalAt(t, store, day.Add(26*time.Hour), "7day")) +}