carlos / platform Public

metrics: disk_eta forecast rule

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 059354bf820f94c5be93a4125fc1ff34438e60b4 parent a59a6d8
4 files changed, +421 −3
  • internal/metrics/alert.go +78 −3
  • internal/metrics/alert_test.go +143 −0
  • internal/metrics/forecast.go +105 −0
  • internal/metrics/forecast_test.go +95 −0

Intent

Attributed to this commit: 11.0 g CO₂e (1,366,559 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-fleet-alerts, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/metrics/alert.go b/internal/metrics/alert.go
index 24a404138..47a1a03d9 100644
--- a/internal/metrics/alert.go
+++ b/internal/metrics/alert.go
@@ -1,6 +1,7 @@
package metrics
import (
+ "math"
"strconv"
"time"
)
@@ -19,6 +20,13 @@ type Rules struct {
// GeoIPSustain is how long a geoip reason must hold before the rule
// fires (geoip spec §10.4); it clears on the first reading of 0.
GeoIPSustain time.Duration // default 30 * time.Minute
+ // DiskETAHours is the disk forecast threshold: fire when the disk is
+ // projected full within this many hours (fleet alerts spec §7.2). It
+ // clears at 1.5x this, or when the trend shows no growth.
+ DiskETAHours float64
+ // DiskETAHold is how long the projection must stay under DiskETAHours
+ // before the rule fires.
+ DiskETAHold time.Duration // default 2 * time.Hour
}
// DefaultRules are the thresholds shipped with the platform.
@@ -33,11 +41,15 @@ func DefaultRules() Rules {
ClearBy: 0.05,
// GeoIPSustain: geoip spec §10.4.
GeoIPSustain: 30 * time.Minute,
+ // Disk forecast: fleet alerts spec §7.2.
+ DiskETAHours: 72,
+ DiskETAHold: 2 * time.Hour,
}
}
// RulesFromEnv applies percent-integer overrides on top of DefaultRules:
-// CARLOS_ALERT_DISK_PCT, CARLOS_ALERT_MEM_PCT, CARLOS_ALERT_CPU_PCT. An
+// CARLOS_ALERT_DISK_PCT, CARLOS_ALERT_MEM_PCT, CARLOS_ALERT_CPU_PCT, plus
+// CARLOS_ALERT_DISK_ETA_HOURS (a positive number of hours). An
// unset, unparsable, or out-of-range (0..100) value keeps the default —
// deliberately pure (no logging); a caller that wants to log a rejected
// override asks PctFrac the same question this does, since this package
@@ -53,6 +65,9 @@ func RulesFromEnv(getenv func(string) string) Rules {
if v, ok := PctFrac(getenv("CARLOS_ALERT_CPU_PCT")); ok {
r.CPUFrac = v
}
+ if v, err := strconv.ParseFloat(getenv("CARLOS_ALERT_DISK_ETA_HOURS"), 64); err == nil && v > 0 && !math.IsInf(v, 0) {
+ r.DiskETAHours = v
+ }
return r
}
@@ -86,6 +101,12 @@ type Observation struct {
// 1 stale, 2 expiring, 3 expired, 4 not loaded, 5 feed failing. nil on
// a box whose edge has not published one.
GeoIP *float64
+ // DiskTrend is the box's disk forecast verdict (fleet alerts spec
+ // §7.2), with DiskETAHours the hours to full when it is TrendGrowing.
+ // nil on a tick with no forecast; TrendUnknown (too little history)
+ // is treated the same: the rule's state is left alone.
+ DiskTrend *TrendVerdict
+ DiskETAHours float64
}
// RuleState is one rule's sustain/hysteresis bookkeeping. Since and FiredAt
@@ -112,7 +133,7 @@ type AlertState struct {
V int `json:"v"` // 1
Box string `json:"box"`
UpdatedAt time.Time `json:"updated_at"`
- Rules map[string]RuleState `json:"rules"` // "disk","mem","cpu","lag"
+ Rules map[string]RuleState `json:"rules"` // "disk","mem","cpu","lag","geoip","disk_eta"
}
// Event is emitted on a firing or clearing transition — never on every
@@ -140,7 +161,8 @@ func AlertKey(box string) string {
// feeds diffs Rules[...].Firing on exactly that assumption — see two
// independent maps, never the same one mutated in place.
//
-// Semantics, per rule ("disk", "mem", "cpu", "lag"):
+// Semantics, per rule ("disk", "mem", "cpu", "lag"; disk_eta follows its
+// own verdict-based variant, see evalETA below):
// - nil reading: that rule's state is left exactly as-is. No data never
// fires and never clears — clearing needs evidence.
// - Not firing, reading > threshold: Since is set if it was zero; the
@@ -255,6 +277,57 @@ func Evaluate(r Rules, st AlertState, obs Observation) (AlertState, []Event) {
}
}
+ // evalETA is the forecast rule: it fires when the projected hours to
+ // full are at or under threshold and have stayed so for hold, and
+ // clears when the projection passes 1.5x threshold or the trend shows
+ // no growth (a deletion clears it). A nil or unknown verdict leaves the
+ // state untouched, like a nil reading. Value is the ETA in hours, 0 on a
+ // no-growth clear: an infinite ETA is never stored, it would not
+ // serialize. Spec §7.2.
+ evalETA := func(name string, verdict *TrendVerdict, eta float64, threshold float64, hold time.Duration) {
+ if verdict == nil || *verdict == TrendUnknown {
+ return
+ }
+ cur := out.Rules[name]
+ noGrowth := *verdict == TrendNoGrowth
+ if noGrowth {
+ eta = 0
+ }
+
+ if cur.Firing {
+ if noGrowth || eta > threshold*1.5 {
+ cur.Firing = false
+ cur.Since = time.Time{}
+ cur.FiredAt = time.Time{}
+ cur.Value = eta
+ out.Rules[name] = cur
+ emit(name, false, eta)
+ }
+ return
+ }
+
+ if !noGrowth && eta <= threshold {
+ if cur.Since.IsZero() {
+ cur.Since = obs.At
+ }
+ if obs.At.Sub(cur.Since) >= hold {
+ cur.Firing = true
+ cur.FiredAt = obs.At
+ cur.Value = eta
+ out.Rules[name] = cur
+ emit(name, true, eta)
+ return
+ }
+ out.Rules[name] = cur
+ return
+ }
+
+ if !cur.Since.IsZero() {
+ cur.Since = time.Time{}
+ out.Rules[name] = cur
+ }
+ }
+
evalFrac("disk", obs.DiskFrac, r.DiskFrac, 0)
evalFrac("mem", obs.MemFrac, r.MemFrac, r.MemSustain)
evalFrac("cpu", obs.CPUFrac, r.CPUFrac, r.CPUSustain)
@@ -274,5 +347,7 @@ func Evaluate(r Rules, st AlertState, obs Observation) (AlertState, []Event) {
}
}
+ evalETA("disk_eta", obs.DiskTrend, obs.DiskETAHours, r.DiskETAHours, r.DiskETAHold)
+
return out, events
}
diff --git a/internal/metrics/alert_test.go b/internal/metrics/alert_test.go
index e4f55fa2a..e29f4bb58 100644
--- a/internal/metrics/alert_test.go
+++ b/internal/metrics/alert_test.go
@@ -247,3 +247,146 @@ func TestGeoIPReasonChangeWhileFiring(t *testing.T) {
t.Fatalf("an unchanged reason re-fired: %v", ev)
}
}
+
+// etaObs is one disk_eta tick: a verdict and, for TrendGrowing, an ETA.
+func etaObs(at time.Time, v TrendVerdict, eta float64) Observation {
+ return Observation{At: at, DiskTrend: &v, DiskETAHours: eta}
+}
+
+func TestEvaluateDiskETAHoldsThenFires(t *testing.T) {
+ r := DefaultRules()
+ st := AlertState{V: 1, Box: "b", Rules: map[string]RuleState{}}
+ t0 := time.Date(2026, 10, 30, 10, 0, 0, 0, time.UTC)
+
+ st, ev := Evaluate(r, st, etaObs(t0, TrendGrowing, 60)) // under 72 h: hold starts
+ if len(ev) != 0 || st.Rules["disk_eta"].Firing {
+ t.Fatalf("must not fire before the hold: ev=%v", ev)
+ }
+ var fired []Event
+ for m := 1; m <= 130; m++ {
+ var e []Event
+ st, e = Evaluate(r, st, etaObs(t0.Add(time.Duration(m)*time.Minute), TrendGrowing, 60))
+ if len(e) > 0 && m < 120 {
+ t.Fatalf("fired early at minute %d", m)
+ }
+ fired = append(fired, e...)
+ }
+ if len(fired) != 1 || !fired[0].Firing || fired[0].Rule != "disk_eta" || fired[0].Value != 60 {
+ t.Fatalf("want exactly one fire event at 2 h, got %v", fired)
+ }
+}
+
+func TestEvaluateDiskETAHoldResetsWhenETARecovers(t *testing.T) {
+ r := DefaultRules()
+ st := AlertState{V: 1, Box: "b", Rules: map[string]RuleState{}}
+ t0 := time.Date(2026, 10, 30, 10, 0, 0, 0, time.UTC)
+
+ st, _ = Evaluate(r, st, etaObs(t0, TrendGrowing, 60))
+ st, _ = Evaluate(r, st, etaObs(t0.Add(time.Hour), TrendGrowing, 100)) // back over 72 h
+ if !st.Rules["disk_eta"].Since.IsZero() {
+ t.Fatal("an ETA over the threshold must reset the hold")
+ }
+ st, _ = Evaluate(r, st, etaObs(t0.Add(90*time.Minute), TrendNoGrowth, 0))
+ if !st.Rules["disk_eta"].Since.IsZero() {
+ t.Fatal("no growth must reset the hold")
+ }
+ _, ev := Evaluate(r, st, etaObs(t0.Add(2*time.Hour), TrendGrowing, 60))
+ if len(ev) != 0 {
+ t.Fatalf("hold restarts after a reset, must not fire: %v", ev)
+ }
+}
+
+func firingETA(t *testing.T, r Rules, t0 time.Time) AlertState {
+ t.Helper()
+ st := AlertState{V: 1, Box: "b", Rules: map[string]RuleState{}}
+ st, _ = Evaluate(r, st, etaObs(t0, TrendGrowing, 60))
+ st, ev := Evaluate(r, st, etaObs(t0.Add(r.DiskETAHold), TrendGrowing, 60))
+ if len(ev) != 1 || !st.Rules["disk_eta"].Firing {
+ t.Fatalf("setup: want disk_eta firing, ev=%v", ev)
+ }
+ return st
+}
+
+func TestEvaluateDiskETAClearsOnHighETA(t *testing.T) {
+ r := DefaultRules()
+ t0 := time.Date(2026, 10, 30, 10, 0, 0, 0, time.UTC)
+ st := firingETA(t, r, t0)
+ at := t0.Add(3 * time.Hour)
+
+ // Between 72 h and 108 h (1.5x): hysteresis band, still firing.
+ st, ev := Evaluate(r, st, etaObs(at, TrendGrowing, 100))
+ if len(ev) != 0 || !st.Rules["disk_eta"].Firing {
+ t.Fatalf("must hold inside the band: ev=%v", ev)
+ }
+ st, ev = Evaluate(r, st, etaObs(at.Add(time.Minute), TrendGrowing, 110))
+ if len(ev) != 1 || ev[0].Firing || ev[0].Rule != "disk_eta" || ev[0].Value != 110 {
+ t.Fatalf("want clear event with the ETA, got %v", ev)
+ }
+ if rs := st.Rules["disk_eta"]; rs.Firing || !rs.Since.IsZero() || !rs.FiredAt.IsZero() {
+ t.Fatalf("clear must zero Since and FiredAt: %+v", rs)
+ }
+}
+
+func TestEvaluateDiskETAClearsOnNoGrowth(t *testing.T) {
+ r := DefaultRules()
+ t0 := time.Date(2026, 10, 30, 10, 0, 0, 0, time.UTC)
+ st := firingETA(t, r, t0)
+
+ st, ev := Evaluate(r, st, etaObs(t0.Add(3*time.Hour), TrendNoGrowth, 0))
+ if len(ev) != 1 || ev[0].Firing || ev[0].Value != 0 {
+ t.Fatalf("want clear event with value 0, got %v", ev)
+ }
+ if rs := st.Rules["disk_eta"]; rs.Firing || rs.Value != 0 {
+ t.Fatalf("cleared state must hold value 0, got %+v", rs)
+ }
+}
+
+func TestEvaluateDiskETAUnknownKeepsState(t *testing.T) {
+ r := DefaultRules()
+ t0 := time.Date(2026, 10, 30, 10, 0, 0, 0, time.UTC)
+ st := firingETA(t, r, t0)
+ before := st.Rules["disk_eta"]
+
+ unknown := TrendUnknown
+ for _, obs := range []Observation{
+ {At: t0.Add(3 * time.Hour), DiskTrend: &unknown},
+ {At: t0.Add(4 * time.Hour)}, // nil: no forecast this tick
+ } {
+ var ev []Event
+ st, ev = Evaluate(r, st, obs)
+ if len(ev) != 0 || st.Rules["disk_eta"] != before {
+ t.Fatalf("unknown/nil must leave state alone: ev=%v state=%+v", ev, st.Rules["disk_eta"])
+ }
+ }
+
+ // A hold in progress survives an unknown tick too.
+ st2 := AlertState{V: 1, Box: "b", Rules: map[string]RuleState{}}
+ st2, _ = Evaluate(r, st2, etaObs(t0, TrendGrowing, 60))
+ st2, _ = Evaluate(r, st2, Observation{At: t0.Add(time.Hour), DiskTrend: &unknown})
+ if st2.Rules["disk_eta"].Since != t0 {
+ t.Fatalf("unknown must keep Since, got %v", st2.Rules["disk_eta"].Since)
+ }
+}
+
+func TestRulesFromEnvDiskETAHours(t *testing.T) {
+ env := func(v string) func(string) string {
+ return func(k string) string {
+ if k == "CARLOS_ALERT_DISK_ETA_HOURS" {
+ return v
+ }
+ return ""
+ }
+ }
+ def := DefaultRules()
+ if def.DiskETAHours != 72 || def.DiskETAHold != 2*time.Hour {
+ t.Fatalf("defaults: want 72 h and 2 h hold, got %v %v", def.DiskETAHours, def.DiskETAHold)
+ }
+ if r := RulesFromEnv(env("48")); r.DiskETAHours != 48 {
+ t.Fatalf("want 48, got %v", r.DiskETAHours)
+ }
+ for _, bad := range []string{"", "soon", "0", "-5", "NaN", "Inf"} {
+ if r := RulesFromEnv(env(bad)); r.DiskETAHours != 72 {
+ t.Fatalf("%q must keep the default, got %v", bad, r.DiskETAHours)
+ }
+ }
+}
diff --git a/internal/metrics/forecast.go b/internal/metrics/forecast.go
new file mode 100644
index 000000000..efbef3035
--- /dev/null
+++ b/internal/metrics/forecast.go
@@ -0,0 +1,105 @@
+package metrics
+
+import "time"
+
+// DiskPoint is one disk reading for the forecast: bytes used and the
+// filesystem size at a moment. Samples carry only a fraction (sample.go), so
+// the box converts to bytes with the statfs size before it feeds the fit
+// (fleet alerts spec §7.2).
+type DiskPoint struct {
+ At time.Time
+ UsedBytes uint64
+ TotalBytes uint64
+}
+
+// TrendVerdict is what DiskTrend can say about a series.
+type TrendVerdict int
+
+const (
+ // TrendUnknown: too little history to forecast. Callers leave rule
+ // state alone; silence is not evidence either way.
+ TrendUnknown TrendVerdict = iota
+ // TrendNoGrowth: the fitted slope is flat or falling. Nothing is
+ // filling, so there is no ETA.
+ TrendNoGrowth
+ // TrendGrowing: the fitted slope is positive; the ETA is meaningful.
+ TrendGrowing
+)
+
+const (
+ // trendWindow is how far back DiskTrend looks (spec §7.2: 6 hours).
+ trendWindow = 6 * time.Hour
+ // trendMinSpan and trendMinPoints are the least history it will
+ // forecast from (spec §7.2: 2 hours; 30 points so a few stray samples
+ // spread over the span don't draw a line).
+ trendMinSpan = 2 * time.Hour
+ trendMinPoints = 30
+)
+
+// DiskTrend fits an ordinary least-squares line to used bytes against time
+// over the points at most 6 hours old, and projects when the disk reaches
+// TotalBytes. It returns TrendUnknown below 2 hours of span or 30 points,
+// TrendNoGrowth when the slope is zero or negative (so a deletion reads as
+// no growth, spec §7.2), and TrendGrowing with the hours to full otherwise.
+// The ETA is measured from the fitted value at now, not the last raw point,
+// so one noisy reading doesn't move it; it is never negative and never
+// infinite (a flat line is TrendNoGrowth, not an infinite ETA). The points
+// need not be sorted. TotalBytes comes from the newest point.
+//
+// Pure, and the same fit can serve other used-vs-time series later.
+func DiskTrend(points []DiskPoint, now time.Time) (v TrendVerdict, etaHours float64) {
+ var in []DiskPoint
+ for _, p := range points {
+ if now.Sub(p.At) <= trendWindow {
+ in = append(in, p)
+ }
+ }
+ if len(in) < trendMinPoints {
+ return TrendUnknown, 0
+ }
+ first, last := in[0].At, in[0].At
+ newest := in[0]
+ for _, p := range in {
+ if p.At.Before(first) {
+ first = p.At
+ }
+ if p.At.After(last) {
+ last = p.At
+ newest = p
+ }
+ }
+ if last.Sub(first) < trendMinSpan {
+ return TrendUnknown, 0
+ }
+
+ // x is minutes since the first point and y is used bytes. The sums
+ // below are of deviations from the means, which keeps float64 precise
+ // on multi-terabyte disks.
+ n := float64(len(in))
+ var sx, sy float64
+ xs := make([]float64, len(in))
+ ys := make([]float64, len(in))
+ for i, p := range in {
+ xs[i] = p.At.Sub(first).Minutes()
+ ys[i] = float64(p.UsedBytes)
+ sx += xs[i]
+ sy += ys[i]
+ }
+ mx, my := sx/n, sy/n
+ var sxx, sxy float64
+ for i := range in {
+ dx := xs[i] - mx
+ sxx += dx * dx
+ sxy += dx * (ys[i] - my)
+ }
+ slope := sxy / sxx // bytes per minute; sxx > 0 because span >= 2 h
+ if !(slope > 0) {
+ return TrendNoGrowth, 0
+ }
+ fittedNow := my + slope*(now.Sub(first).Minutes()-mx)
+ remaining := float64(newest.TotalBytes) - fittedNow
+ if remaining < 0 {
+ remaining = 0
+ }
+ return TrendGrowing, remaining / slope / 60
+}
diff --git a/internal/metrics/forecast_test.go b/internal/metrics/forecast_test.go
new file mode 100644
index 000000000..a4c6881d4
--- /dev/null
+++ b/internal/metrics/forecast_test.go
@@ -0,0 +1,95 @@
+package metrics
+
+import (
+ "testing"
+ "time"
+)
+
+const gib = uint64(1) << 30
+
+// diskSeries builds n one-minute points ending at now, used bytes following
+// usedAt(minutesAgo).
+func diskSeries(now time.Time, n int, total uint64, usedAt func(minsAgo int) uint64) []DiskPoint {
+ pts := make([]DiskPoint, 0, n)
+ for i := n - 1; i >= 0; i-- {
+ pts = append(pts, DiskPoint{At: now.Add(-time.Duration(i) * time.Minute), UsedBytes: usedAt(i), TotalBytes: total})
+ }
+ return pts
+}
+
+func TestDiskTrendSteadyFill(t *testing.T) {
+ now := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
+ // +1 GiB/h for 6 h, 50 GiB used now on a 100 GiB disk: 50 h to full.
+ pts := diskSeries(now, 360, 100*gib, func(m int) uint64 {
+ return 50*gib - uint64(float64(m)/60*float64(gib))
+ })
+ v, eta := DiskTrend(pts, now)
+ if v != TrendGrowing {
+ t.Fatalf("want TrendGrowing, got %v", v)
+ }
+ if eta < 49.5 || eta > 50.5 {
+ t.Fatalf("want ETA 50 +-0.5 h, got %v", eta)
+ }
+}
+
+func TestDiskTrendBurstThenFlat(t *testing.T) {
+ now := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
+ // A 4 GiB jump 5.5 h ago (a log dump, say), flat since. A least-squares
+ // line through a step early in the window leans only slightly upward, so
+ // it must not read as an imminent fill. (A much larger step does tilt
+ // the line enough to forecast; that is inherent to the plain fit.)
+ pts := diskSeries(now, 360, 100*gib, func(m int) uint64 {
+ if m > 330 {
+ return 46 * gib
+ }
+ return 50 * gib
+ })
+ v, eta := DiskTrend(pts, now)
+ if v == TrendGrowing && eta <= 108 {
+ t.Fatalf("burst then flat must not forecast under 108 h, got growing eta=%v", eta)
+ }
+ if v == TrendUnknown {
+ t.Fatal("360 points over 6 h is enough to forecast")
+ }
+}
+
+func TestDiskTrendTooShort(t *testing.T) {
+ now := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
+ growing := func(m int) uint64 { return 50*gib - uint64(m)*(gib/10) }
+
+ // 90 minutes of points: under 2 h of span.
+ if v, _ := DiskTrend(diskSeries(now, 90, 100*gib, growing), now); v != TrendUnknown {
+ t.Fatalf("under 2 h of span: want TrendUnknown, got %v", v)
+ }
+ // 3 h of span but only 20 points (gaps): under 30 points.
+ sparse := diskSeries(now, 20, 100*gib, func(m int) uint64 { return 50*gib - uint64(m)*gib })
+ for i := range sparse {
+ sparse[i].At = now.Add(-time.Duration(19-i) * 10 * time.Minute)
+ }
+ if v, _ := DiskTrend(sparse, now); v != TrendUnknown {
+ t.Fatalf("under 30 points: want TrendUnknown, got %v", v)
+ }
+ if v, _ := DiskTrend(nil, now); v != TrendUnknown {
+ t.Fatalf("no points: want TrendUnknown, got %v", v)
+ }
+ // Points older than 6 h do not count towards the span.
+ old := diskSeries(now.Add(-7*time.Hour), 360, 100*gib, growing)
+ if v, _ := DiskTrend(old, now); v != TrendUnknown {
+ t.Fatalf("all points older than 6 h: want TrendUnknown, got %v", v)
+ }
+}
+
+func TestDiskTrendShrinking(t *testing.T) {
+ now := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
+ pts := diskSeries(now, 360, 100*gib, func(m int) uint64 {
+ return 50*gib + uint64(float64(m)/60*float64(gib))
+ })
+ if v, _ := DiskTrend(pts, now); v != TrendNoGrowth {
+ t.Fatalf("want TrendNoGrowth, got %v", v)
+ }
+ // Exactly flat is no growth too.
+ flat := diskSeries(now, 360, 100*gib, func(int) uint64 { return 50 * gib })
+ if v, eta := DiskTrend(flat, now); v != TrendNoGrowth || eta != 0 {
+ t.Fatalf("flat: want TrendNoGrowth and eta 0, got %v %v", v, eta)
+ }
+}