Skip to content

Lightweight server monitoring with historical data, docker stats, and alerts.

fix(hub): improve exclusion of previous-interval records from rollup averages (#2807)

Santhi Prakash437066ac550c
diff --git a/internal/records/monitor_averaging_test.go b/internal/records/monitor_averaging_test.go
index da00330fa..d79a26db5 100644
--- a/internal/records/monitor_averaging_test.go
+++ b/internal/records/monitor_averaging_test.go
@@ -224,3 +224,80 @@ func TestSparseMonitorRollups(t *testing.T) {
})
}
}
+
+// TestMonitorRollupExcludesPreviousInterval verifies that a monitor rollup created one full
+// period ago is not merged into the next longer record, which would double count its probes.
+func TestMonitorRollupExcludesPreviousInterval(t *testing.T) {
+ hub, err := tests.NewTestHub(t.TempDir())
+ require.NoError(t, err)
+ defer hub.Cleanup()
+ user, err := tests.CreateUser(hub, "[email protected]", "testtesttest")
+ require.NoError(t, err)
+ sys, err := tests.CreateRecord(hub, "systems", map[string]any{
+ "name": "m", "host": "localhost", "port": "45876", "status": "up", "users": []string{user.Id},
+ })
+ require.NoError(t, err)
+ monitor, err := tests.CreateRecord(hub, "network_monitors", map[string]any{
+ "system": sys.Id, "target": "1.1.1.1", "protocol": "icmp", "interval": 60, "enabled": true,
+ })
+ require.NoError(t, err)
+ now := time.Now()
+ seed := func(typ string, created time.Time, total int) {
+ _, err := tests.CreateRecord(hub, "network_monitor_stats", map[string]any{
+ "system": sys.Id, "monitor": monitor.Id, "type": typ, "created": created.UnixMilli(),
+ "res_min": 8, "res_max": 20, "total_count": total, "success_count": total, "res_sum": total,
+ })
+ require.NoError(t, err)
+ }
+ seed("1m", now.Add(-time.Minute), 4) // becomes this run's 10m record
+ seed("10m", now.Add(-10*time.Minute+50*time.Millisecond), 4) // previous run
+ seed("10m", now.Add(-20*time.Minute+50*time.Millisecond), 100) // run before that: previous 20m interval
+ records.NewRecordManager(hub).CreateLongerRecords()
+ rollups, err := hub.FindAllRecords("network_monitor_stats", dbx.HashExp{"monitor": monitor.Id, "type": "20m"})
+ require.NoError(t, err)
+ require.Len(t, rollups, 1)
+ require.Equal(t, 8, rollups[0].GetInt("total_count"))
+}
+
+// TestMonitorRollupOffsetPhase covers 20m monitor records whose phase is offset 10 minutes from the 120m rollup
+// (e.g. after the hub missed one run). The oldest one was created 110 minutes
+// ago, just after the previous 120m rollup, and has not been rolled up yet.
+func TestMonitorRollupOffsetPhase(t *testing.T) {
+ hub, err := tests.NewTestHub(t.TempDir())
+ require.NoError(t, err)
+ defer hub.Cleanup()
+ user, err := tests.CreateUser(hub, "[email protected]", "testtesttest")
+ require.NoError(t, err)
+ sys, err := tests.CreateRecord(hub, "systems", map[string]any{
+ "name": "m", "host": "localhost", "port": "45876", "status": "up", "users": []string{user.Id},
+ })
+ require.NoError(t, err)
+ monitor, err := tests.CreateRecord(hub, "network_monitors", map[string]any{
+ "system": sys.Id, "target": "1.1.1.1", "protocol": "icmp", "interval": 60, "enabled": true,
+ })
+ require.NoError(t, err)
+ now := time.Now()
+ seed := func(typ string, created time.Time, total int) {
+ _, err := tests.CreateRecord(hub, "network_monitor_stats", map[string]any{
+ "system": sys.Id, "monitor": monitor.Id, "type": typ, "created": created.UnixMilli(),
+ "res_min": 8, "res_max": 20, "total_count": total, "success_count": total, "res_sum": total,
+ })
+ require.NoError(t, err)
+ }
+ seed("120m", now.Add(-120*time.Minute-50*time.Millisecond), 1000) // previous 120m rollup
+ for i := range 6 {
+ // created at -110m, -90m, ... -10m, by runs that started 50ms earlier in their second than this one
+ seed("20m", now.Add(-time.Duration(10+20*i)*time.Minute-50*time.Millisecond), 4)
+ }
+ records.NewRecordManager(hub).CreateLongerRecords()
+ rollups, err := hub.FindAllRecords("network_monitor_stats", dbx.HashExp{"monitor": monitor.Id, "type": "120m"})
+ require.NoError(t, err)
+ require.Len(t, rollups, 2)
+ got := 0
+ for _, r := range rollups {
+ if c := r.GetInt("total_count"); c != 1000 {
+ got = c
+ }
+ }
+ require.Equal(t, 24, got)
+}
diff --git a/internal/records/records.go b/internal/records/records.go
index 94d58a2cb..80b670537 100644
--- a/internal/records/records.go
+++ b/internal/records/records.go
@@ -26,6 +26,21 @@ type LongerRecordData struct {
minShorterRecords int
}
+// shorterRecordCutoff returns the time after which shorter records are included in a longer record.
+//
+// 1m records are samples created independently of this job, so the window is the full longer period.
+// Other types are created by this job, a few ms after it starts. The record created one full period
+// ago covers the previous period but lands right on the window boundary. Records created by this job
+// are always a multiple of the job interval (10 minutes) apart, so moving the cutoff forward by half
+// that interval excludes it without ever landing on another record.
+func (d *LongerRecordData) shorterRecordCutoff(now time.Time) time.Time {
+ cutoff := now.Add(d.longerTimeDuration)
+ if d.shorterType != "1m" {
+ cutoff = cutoff.Add(5 * time.Minute)
+ }
+ return cutoff
+}
+
type RecordIds []struct {
Id string `db:"id"`
}
@@ -101,8 +116,7 @@ func (rm *RecordManager) CreateLongerRecords() {
// log.Println("processing longer record type", recordData.longerType)
// add one minute padding for longer records because they are created slightly later than the job start time
longerRecordPeriod := now.Add(recordData.longerTimeDuration + time.Minute)
- // shorter records are created independently of longer records, so we shouldn't need to add padding
- shorterRecordPeriod := now.Add(recordData.longerTimeDuration)
+ shorterRecordPeriod := recordData.shorterRecordCutoff(now)
for _, collection := range collections {
// check creation time of last longer record if not 10m, since 10m is created every run
if recordData.longerType != "10m" {
@@ -179,7 +193,7 @@ func (rm *RecordManager) CreateLongerRecords() {
for i := range longerRecordData {
recordData := longerRecordData[i]
longerRecordPeriod := now.Add(recordData.longerTimeDuration + time.Minute)
- shorterRecordPeriod := now.Add(recordData.longerTimeDuration)
+ shorterRecordPeriod := recordData.shorterRecordCutoff(now)
if recordData.longerType != "10m" {
count, err := txApp.CountRecords(monitorStatsColl.Id, dbx.NewExp(
diff --git a/internal/records/records_rollup_test.go b/internal/records/records_rollup_test.go
index 16f0076af..334104b8f 100644
--- a/internal/records/records_rollup_test.go
+++ b/internal/records/records_rollup_test.go
@@ -3,6 +3,8 @@
package records_test
import (
+ "encoding/json"
+ "fmt"
"testing"
"time"
@@ -10,6 +12,7 @@ import (
"github.com/henrygd/beszel/internal/tests"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/types"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -84,3 +87,151 @@ func TestLongerRecordsPreventDuplicates(t *testing.T) {
}
}
}
+
+// TestLongerRecordsExcludePreviousInterval verifies that a shorter record saved
+// just after the cutoff still belongs to the previous interval and must not be
+// averaged into the rollup. See https://github.com/henrygd/beszel/issues/2805.
+func TestLongerRecordsExcludePreviousInterval(t *testing.T) {
+ for _, collection := range []string{"system_stats", "container_stats"} {
+ for _, tier := range []struct {
+ shorter, longer string
+ window time.Duration
+ count int
+ }{
+ {"10m", "20m", 20 * time.Minute, 2},
+ {"20m", "120m", 120 * time.Minute, 6},
+ } {
+ t.Run(collection+"/"+tier.longer, func(t *testing.T) {
+ hub, err := tests.NewTestHub(t.TempDir())
+ require.NoError(t, err)
+ defer hub.Cleanup()
+
+ user, err := tests.CreateUser(hub, "[email protected]", "testtesttest")
+ require.NoError(t, err)
+ sys, err := tests.CreateRecord(hub, "systems", map[string]any{
+ "name": "rollup-system", "host": "localhost", "port": "45876",
+ "status": "up", "users": []string{user.Id},
+ })
+ require.NoError(t, err)
+
+ now := time.Now().UTC()
+ shorterPeriod := tier.window / time.Duration(tier.count)
+ stats := func(cpu int) string {
+ if collection == "container_stats" {
+ return fmt.Sprintf(`[{"n":"test","c":%d}]`, cpu)
+ }
+ return fmt.Sprintf(`{"cpu":%d}`, cpu)
+ }
+ seed := func(created time.Time, cpu int) {
+ record, err := tests.CreateRecord(hub, collection, map[string]any{
+ "system": sys.Id, "type": tier.shorter, "stats": stats(cpu),
+ })
+ require.NoError(t, err)
+ // created is an autodate field, so we need to set it manually
+ record.SetRaw("created", created.Format(types.DefaultDateLayout))
+ require.NoError(t, hub.SaveNoValidate(record))
+ }
+ // records covering the intervals inside the rollup window, each saved
+ // slightly after its interval ends like a real rollup write; the last
+ // one lands around the job's `now`, like the record the same run just
+ // wrote in the previous aggregation tier
+ for i := range tier.count {
+ seed(now.Add(-tier.window+time.Duration(i+1)*shorterPeriod+400*time.Millisecond), 10)
+ }
+ // a record saved just after the cutoff still covers the previous
+ // interval and must not be included
+ seed(now.Add(-tier.window+5*time.Second), 100)
+
+ rm := records.NewRecordManager(hub)
+ rm.CreateLongerRecords()
+
+ rollups, err := hub.FindAllRecords(collection, dbx.HashExp{"system": sys.Id, "type": tier.longer})
+ require.NoError(t, err)
+ require.Len(t, rollups, 1)
+
+ var decoded []struct {
+ Cpu float64 `json:"cpu"`
+ C float64 `json:"c"`
+ }
+ statsJSON := rollups[0].GetString("stats")
+ if collection == "system_stats" {
+ statsJSON = "[" + statsJSON + "]"
+ }
+ require.NoError(t, json.Unmarshal([]byte(statsJSON), &decoded))
+ for _, d := range decoded {
+ assert.Equal(t, 10.0, max(d.Cpu, d.C), "rollup must average only the records covering its interval")
+ }
+ })
+ }
+ }
+}
+
+// TestLongerRecordsKeepValidInputs verifies that excluding the previous interval does not
+// drop inputs that belong to the window: 1m samples arrive on their own timer and must all
+// count, and a job that starts a couple of seconds late must still find its shorter records.
+func TestLongerRecordsKeepValidInputs(t *testing.T) {
+ for _, collection := range []string{"system_stats", "container_stats"} {
+ for _, tc := range []struct {
+ name, shorter, longer string
+ count int
+ period, newestAge time.Duration
+ missing int
+ wantCPU float64
+ }{
+ {"minute_samples", "1m", "10m", 10, time.Minute, 30 * time.Second, -1, 19},
+ {"minute_samples_one_missing", "1m", "10m", 10, time.Minute, 30 * time.Second, 5, 20},
+ {"delayed_20m_job", "10m", "20m", 2, 10 * time.Minute, 2 * time.Second, -1, 55},
+ {"delayed_120m_job", "20m", "120m", 6, 20 * time.Minute, 2 * time.Second, -1, 25},
+ {"delayed_480m_job", "120m", "480m", 4, 120 * time.Minute, 2 * time.Second, -1, 32.5},
+ } {
+ t.Run(collection+"/"+tc.name, func(t *testing.T) {
+ hub, err := tests.NewTestHub(t.TempDir())
+ require.NoError(t, err)
+ defer hub.Cleanup()
+ user, err := tests.CreateUser(hub, "[email protected]", "testtesttest")
+ require.NoError(t, err)
+ sys, err := tests.CreateRecord(hub, "systems", map[string]any{
+ "name": "review", "host": "localhost", "port": "45876", "status": "up", "users": []string{user.Id},
+ })
+ require.NoError(t, err)
+ now := time.Now().UTC()
+ for i := range tc.count {
+ if i == tc.missing {
+ continue
+ }
+ cpu := 10
+ if i == 0 {
+ cpu = 100
+ }
+ stats := fmt.Sprintf(`{"cpu":%d}`, cpu)
+ if collection == "container_stats" {
+ stats = fmt.Sprintf(`[{"n":"test","c":%d}]`, cpu)
+ }
+ rec, err := tests.CreateRecord(hub, collection, map[string]any{"system": sys.Id, "type": tc.shorter, "stats": stats})
+ require.NoError(t, err)
+ created := now.Add(-tc.newestAge - time.Duration(tc.count-1-i)*tc.period)
+ rec.SetRaw("created", created.Format(types.DefaultDateLayout))
+ require.NoError(t, hub.SaveNoValidate(rec))
+ }
+ records.NewRecordManager(hub).CreateLongerRecords()
+ rollups, err := hub.FindAllRecords(collection, dbx.HashExp{"system": sys.Id, "type": tc.longer})
+ require.NoError(t, err)
+ require.Len(t, rollups, 1, "valid shorter inputs must produce a rollup")
+ if collection == "system_stats" {
+ var stats struct {
+ CPU float64 `json:"cpu"`
+ }
+ require.NoError(t, rollups[0].UnmarshalJSONField("stats", &stats))
+ require.Equal(t, tc.wantCPU, stats.CPU)
+ } else {
+ var stats []struct {
+ CPU float64 `json:"c"`
+ }
+ require.NoError(t, rollups[0].UnmarshalJSONField("stats", &stats))
+ require.Len(t, stats, 1)
+ require.Equal(t, tc.wantCPU, stats[0].CPU)
+ }
+ })
+ }
+ }
+}