carlos / platform Public

host: disk trend ring, disk_eta, box sinks incident-only

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 0ea2aaf177d8408e625f130726eaaa1d557527a9 parent 83e1001
8 files changed, +480 −19
  • internal/host/agent.go +2 −0
  • internal/host/alertsink_test.go +3 −3
  • internal/host/disktrend.go +105 −0
  • internal/host/disktrend_test.go +102 −0
  • internal/host/metrics_loop.go +27 −7
  • internal/host/metrics_loop_test.go +219 −7
  • internal/host/probes.go +12 −0
  • internal/status/snapshot.go +10 −2

CI failed — run details

Intent

Human

<task-notification> <task-id>aa9707fd2c6c1a2ea</task-id> <tool-use-id>toolu_01ACy2Kyrh2mn2B9uvW2ukKq</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/aa9707fd2c6c1a2ea.output</output-file> <status>completed</status> <summary>Agent "Implement Task 1: disk forecast rule" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE_WITH_CONCERNS **Commits:** - 059354bf metrics: disk_eta forecast rule - 83e10015 metrics: disk trend uses Theil-Sen so a burst is not growth. It landed despite git's lock warning. **Tests:** `go test ./internal/metrics -count=1` passes, and gofmt and vet are clean. - Your original burst case (20 GiB step 5 h ago, then flat) now returns `TrendNoGrowth`. - `TestDiskTrendSteadyFill` still gives 50 h ±0.5. - The new mid-window test puts the 20 GiB step 4 h ago and 2 h ago; both return `TrendNoGrowth`. **Concern:** "At most half the pairs positive" is off by a hair, and a step at the exact centre of the window still forecasts. - With 360 points a centred step makes 50.14% of the pairs positive. I ran that case (step 3 h ago, 179/181 split) and got `TrendGrowing` with an ETA of 14.5 h. - This only happens for a step within about 10 minutes of the window's middle. A step crosses that band in about 20 minutes, well inside the 2 h hold, so the rule can't fire from it. - I left an exact-centre assertion out of the tests, because it would assert the wrong behaviour. The edge is documented in the `DiskTrend` comment. - If you want it closed anyway, count the n self-pairs as zero slopes so the median is 0 at the centre. Say so and I'll make the change. **Report:** `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-1-report.md` (fix report appended).</result> <usage><subagent_tokens>73132</subagent_tokens><tool_uses>14</tool_uses><duration_ms>217583</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>ad0a2ce31c729cf8b</task-id> <tool-use-id>toolu_01FopGeSC7W5Z3SsJomyA4Tp</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/ad0a2ce31c729cf8b.output</output-file> <status>completed</status> <summary>Agent "Review Task 1 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Spec Compliance - ✅ Spec compliant, with R-4 (Theil–Sen, projected from the latest used bytes) and R-6 (exact-centre edge accepted) applied. - Every listed file has its hunk: `forecast.go`, `forecast_test.go`, `alert.go` and `alert_test.go`. - The interfaces match the brief: `DiskPoint`, `TrendVerdict`, `DiskTrend`, `Rules.DiskETAHours` (72), `Rules.DiskETAHold` (2 h), `CARLOS_ALERT_DISK_ETA_HOURS`, `Observation.DiskTrend` and `Observation.DiskETAHours`. - The Unknown and NoGrowth thresholds are right (`forecast.go:501`, `514`, `535`). - `evalETA` (`alert.go:193-235`) fires on ETA ≤ threshold held for the hold. It clears on ETA &gt; 1.5x threshold or on NoGrowth. Nil and Unknown return before touching state. The cleared `Value` is the ETA, or 0 on NoGrowth, and infinity is never stored. - All eight named tests exist. - ⚠️ Cannot verify from the diff: - Whether the later callers bound the series passed to `DiskTrend` (see Minor 1). - Whether the later callers pass a series that ends near `now` (see Minor 3). - I did not run any tests, per the rules. ### Strengths - The Theil–Sen change is clean and well explained in the doc comment (`forecast.go:465-481`). There is no intercept, so no extrapolation error. The even-count median is averaged correctly (`:530-534`). The `!(slope &gt; 0)` form also catches NaN. `dt &lt;= 0` skips duplicate timestamps, so no divide-by-zero or Inf can occur. - The ETA cannot overflow. The smallest nonzero slope is about 1 byte / 360 min, and the remaining bytes are clamped to ≥ 0 (`:538-541`). - The `evalETA` clear path zeroes `Since` and `FiredAt`, like `evalFrac`. Both a non-qualifying Growing tick and a NoGrowth tick reset the hold (`alert.go:231-234`). - `RulesFromEnv` rejects `NaN`, `Inf`, 0, negatives and junk, and out-of-range values such as `1e400` fail through `err`. The test covers these (`alert_test.go:412`). - The tests use real series, not mocks. They cover the original 20 GiB burst, mid-window steps at 4 h and 2 h, the too-short cases (span, count, nil, all older than 6 h), exactly flat input, the hysteresis band (100 holds, 110 clears) and a hold surviving an Unknown tick. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) None. #### Minor (Nice to Have) 1. `forecast.go:518-528`. Time and memory are quadratic in the points in the window, and nothing enforces the "at most 360 points" the doc relies on (`:480-481`). With 10k points, the slope slice is about 50M floats (about 400 MB). If the series is ever built from box-supplied heartbeats, a misbehaving box could cause this. Fix: return `TrendUnknown` or thin to a stride when `len(in)` is above a cap such as 720. Confirm the Task 2+ callers bound the series. 2. `forecast.go:483-487` (R-6 edge). The "about 20 minutes, inside the 2 h hold" argument assumes uniform one-point-a-minute sampling. The straddle count is by point count, not time. Sparse or irregular sampling widens the band: at n=60 over 6 h it is about 42 min, and gaps widen it further. The implementer's own offered fix, counting the n self-pairs as zero slopes, makes a single step give median 0 for any n and spacing. It is one line, and it removes the edge and the caveat in the comment. I'm leaving this to the controller, since R-6 accepted it. 3. `forecast.go:495-516, 538-542`. Two staleness gaps: - The span is measured from the oldest to the newest point, not to `now`. A series that ended 5 h ago still yields a verdict. Its ETA is measured from the newest point's time, so it is overstated by the age of the newest point. - Points dated after `now` pass the window test (`now.Sub` is negative). - Fix: return `TrendUnknown` if `now.Sub(newest.At)` exceeds a few minutes, or subtract the age from the ETA. 4. `forecast.go:538-541`. A newest point with `TotalBytes == 0` (a failed statfs) gives remaining 0, so a Growing verdict with ETA 0. After the hold, that would fire. Treat `TotalBytes == 0` as `TrendUnknown`. 5. `alert_test.go:291-301`. `TestEvaluateDiskETAHoldsThenFires` claims "one fire event at exactly 2 h" but only asserts none before minute 120 and exactly one in 0..130. A fire at minute 125 would pass. Assert that the event arrives at m == 120. 6. `forecast_test.go`. Every series is exactly flat or exactly linear. There is no jittered series. With jitter, a burst verdict becomes `TrendGrowing` with a huge ETA, not `TrendNoGrowth`. That is harmless to the rule, but the burst-protection contract is untested under realistic noise. There is also no two-step series. Two steps in the window make more than half the pairs positive, so the median reads as growth. That is arguably correct, but the "burst is not growth" comment (`:473-481`) is only true for one step. 7. `forecast.go:483-490`. The comment paragraphs are ragged. "One edge" is hard-wrapped at an odd width, and "The ETA is measured…" follows without a separating `//` blank line, so it reads as part of the edge paragraph. ### Assessment **Task quality:** Approved **Reasoning:** The rule matches the brief as amended by R-4 and R-6, and the state machine is correct, including the hold, the hysteresis, the Unknown and nil handling, and the zero-or-finite `Value`. The remaining items are hardening and test-precision points, none of which block the task. The most worth taking are the point-count cap (1), the stale or zero-total guards (3, 4), and the one-line self-pair fix (2), which would remove the documented edge.</result> <usage><subagent_tokens>69392</subagent_tokens><tool_uses>6</tool_uses><duration_ms>102403</duration_ms></usage> </task-notification>

Attributed to this commit: 28.1 g CO₂e (3,580,132 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/host/agent.go b/internal/host/agent.go
index 8d2a63fb4..8a3d267d0 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -4365,6 +4365,8 @@ func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func
DiskFreeBytes: readDiskFreeBytes(),
Release: version.Build,
Platform: runtime.GOOS + "-" + runtime.GOARCH,
+ // The metrics loop's disk forecast, nil unless it is growing.
+ DiskFullETAHours: diskETAProbe(&processDiskTrend, time.Now()),
// The invalid-value line is newSystemLeg's to say, once at
// arming; this tick publishes the channel the box actually
// follows, five-minutely, and has nowhere to say it again.
diff --git a/internal/host/alertsink_test.go b/internal/host/alertsink_test.go
index bd162e674..8a033bf29 100644
--- a/internal/host/alertsink_test.go
+++ b/internal/host/alertsink_test.go
@@ -241,10 +241,10 @@ func TestAlertTickDeliversThroughSinks(t *testing.T) {
disk := 0.95
latest := metrics.Sample{At: sinkTestAt, Host: metrics.HostSample{DiskFrac: &disk}}
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, sinks); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, statePath, sinks, nil); err != nil {
t.Fatal(err)
}
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, sinks); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, statePath, sinks, nil); err != nil {
t.Fatal(err)
}
if len(pub.in) != 1 {
@@ -257,7 +257,7 @@ func TestAlertTickDeliversThroughSinks(t *testing.T) {
// Clearing is a transition too.
low := 0.30
cleared := metrics.Sample{At: sinkTestAt.Add(time.Minute), Host: metrics.HostSample{DiskFrac: &low}}
- if err := alertTick(ctx, store, box, rules, st, cleared, statePath, sinks); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, cleared, statePath, sinks, nil); err != nil {
t.Fatal(err)
}
if len(pub.in) != 2 || !strings.Contains(deref(pub.in[1].Subject), "cleared") {
diff --git a/internal/host/disktrend.go b/internal/host/disktrend.go
new file mode 100644
index 000000000..8b1562879
--- /dev/null
+++ b/internal/host/disktrend.go
@@ -0,0 +1,105 @@
+package host
+
+import (
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/metrics"
+)
+
+const (
+ // diskTrendCap is how many readings the ring keeps: 6 hours of 60s
+ // ticks, the window metrics.DiskTrend fits. It also bounds that fit,
+ // which compares every pair of points (fleet alerts spec §7.2).
+ diskTrendCap = 360
+ // diskTrendFresh is how old the newest reading may be before the series
+ // is not trusted. A sampler that stalled leaves its last good hours in
+ // the ring; forecasting from them would repeat a stale answer.
+ diskTrendFresh = 5 * time.Minute
+)
+
+// processDiskTrend is the box's one ring: the metrics loop writes it every
+// tick and the status loop reads it for the heartbeat. They are separate
+// goroutines, so this is the seam between them, like processAlertCounters.
+var processDiskTrend diskTrend
+
+// diskTrend is a ring of the last diskTrendCap disk readings. The zero value
+// is empty and ready. The mutex makes one writer and one reader safe; the fit
+// itself runs on a copy, outside the lock.
+type diskTrend struct {
+ mu sync.Mutex
+ buf [diskTrendCap]metrics.DiskPoint
+ next int // where the next point goes
+ n int // points held, at most diskTrendCap
+}
+
+// add appends p, dropping the oldest point once the ring is full.
+func (d *diskTrend) add(p metrics.DiskPoint) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.buf[d.next] = p
+ d.next = (d.next + 1) % diskTrendCap
+ if d.n < diskTrendCap {
+ d.n++
+ }
+}
+
+// snapshot returns the held points, oldest first.
+func (d *diskTrend) snapshot() []metrics.DiskPoint {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ out := make([]metrics.DiskPoint, 0, d.n)
+ start := (d.next - d.n + diskTrendCap) % diskTrendCap
+ for i := 0; i < d.n; i++ {
+ out = append(out, d.buf[(start+i)%diskTrendCap])
+ }
+ return out
+}
+
+// verdict is metrics.DiskTrend over the ring as of now. It is TrendUnknown
+// when the ring is empty or its newest point is more than diskTrendFresh
+// older than now.
+func (d *diskTrend) verdict(now time.Time) (metrics.TrendVerdict, float64) {
+ pts := d.snapshot()
+ if len(pts) == 0 || now.Sub(pts[len(pts)-1].At) > diskTrendFresh {
+ return metrics.TrendUnknown, 0
+ }
+ return metrics.DiskTrend(pts, now)
+}
+
+// recordDiskPoint adds one point stamped at, the tick time, when the probe
+// reads a filesystem with a size. A failed read, a zero size or an unwired
+// probe adds nothing: a gap is honest, a guessed point is not.
+func recordDiskPoint(d *diskTrend, read func() (used, total uint64, ok bool), at time.Time) {
+ if read == nil {
+ return
+ }
+ used, total, ok := read()
+ if !ok || total == 0 {
+ return
+ }
+ d.add(metrics.DiskPoint{At: at, UsedBytes: used, TotalBytes: total})
+}
+
+// diskETAProbe is the heartbeat's hours to full: the forecast's ETA while the
+// verdict is growing, nil for every other verdict so the key is absent
+// rather than a made-up number.
+func diskETAProbe(d *diskTrend, now time.Time) *float64 {
+ if d == nil {
+ return nil
+ }
+ v, eta := d.verdict(now)
+ if v != metrics.TrendGrowing {
+ return nil
+ }
+ return &eta
+}
+
+// boxSinkRule is whether a rule's transitions go to the box's own sinks. Only
+// incidents the console cannot see for itself do: a full disk, and an engine
+// that has gone silent. Everything else, the forecast included, reaches
+// people through the console's alert engine, so the box does not page for it
+// too (fleet alerts spec §7.2).
+func boxSinkRule(rule string) bool {
+ return rule == "disk" || rule == "engine_silent"
+}
diff --git a/internal/host/disktrend_test.go b/internal/host/disktrend_test.go
new file mode 100644
index 000000000..0a75bfd7e
--- /dev/null
+++ b/internal/host/disktrend_test.go
@@ -0,0 +1,102 @@
+package host
+
+import (
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/metrics"
+)
+
+const gib = uint64(1) << 30
+
+// fillTrend adds n points one minute apart, the last at end, used growing by
+// perMinute bytes a point from startUsed, on a 100 GiB disk.
+func fillTrend(tr *diskTrend, end time.Time, n int, startUsed, perMinute uint64) {
+ for i := 0; i < n; i++ {
+ tr.add(metrics.DiskPoint{
+ At: end.Add(-time.Duration(n-1-i) * time.Minute),
+ UsedBytes: startUsed + uint64(i)*perMinute,
+ TotalBytes: 100 * gib,
+ })
+ }
+}
+
+// TestDiskTrendRingKeeps360 pins the bound that keeps the O(n^2) fit cheap:
+// 400 adds leave the newest 360, oldest first.
+func TestDiskTrendRingKeeps360(t *testing.T) {
+ var tr diskTrend
+ end := time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)
+ fillTrend(&tr, end, 400, 10*gib, 1<<20)
+
+ pts := tr.snapshot()
+ if len(pts) != 360 {
+ t.Fatalf("ring holds %d points, want 360", len(pts))
+ }
+ if want := end.Add(-359 * time.Minute); !pts[0].At.Equal(want) {
+ t.Errorf("oldest point at %v, want %v (the 40 oldest are dropped)", pts[0].At, want)
+ }
+ if !pts[359].At.Equal(end) {
+ t.Errorf("newest point at %v, want %v", pts[359].At, end)
+ }
+ for i := 1; i < len(pts); i++ {
+ if !pts[i].At.After(pts[i-1].At) {
+ t.Fatalf("points out of order at %d", i)
+ }
+ }
+}
+
+// TestDiskTrendVerdictIgnoresStaleSeries: a sampler that stalled must not
+// forecast from its last good hours.
+func TestDiskTrendVerdictIgnoresStaleSeries(t *testing.T) {
+ var tr diskTrend
+ end := time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)
+ fillTrend(&tr, end, 360, 40*gib, gib/60)
+
+ if v, eta := tr.verdict(end); v != metrics.TrendGrowing || eta <= 0 {
+ t.Fatalf("fresh series: verdict %v eta %v, want growing", v, eta)
+ }
+ if v, _ := tr.verdict(end.Add(5 * time.Minute)); v != metrics.TrendGrowing {
+ t.Errorf("newest point exactly 5 minutes old: verdict %v, want still growing", v)
+ }
+ if v, eta := tr.verdict(end.Add(5*time.Minute + time.Second)); v != metrics.TrendUnknown || eta != 0 {
+ t.Errorf("newest point over 5 minutes old: verdict %v eta %v, want unknown", v, eta)
+ }
+ var empty diskTrend
+ if v, _ := empty.verdict(end); v != metrics.TrendUnknown {
+ t.Errorf("empty ring: verdict %v, want unknown", v)
+ }
+}
+
+// TestRecordDiskPoint: one point per good reading, none for a failed read, a
+// zero-size filesystem or an unwired probe.
+func TestRecordDiskPoint(t *testing.T) {
+ at := time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)
+ var tr diskTrend
+
+ recordDiskPoint(&tr, nil, at)
+ recordDiskPoint(&tr, func() (uint64, uint64, bool) { return 5, 100, false }, at)
+ recordDiskPoint(&tr, func() (uint64, uint64, bool) { return 0, 0, true }, at)
+ if n := len(tr.snapshot()); n != 0 {
+ t.Fatalf("%d points from readings that should add none", n)
+ }
+
+ recordDiskPoint(&tr, func() (uint64, uint64, bool) { return 30 * gib, 100 * gib, true }, at)
+ pts := tr.snapshot()
+ if len(pts) != 1 || !pts[0].At.Equal(at) || pts[0].UsedBytes != 30*gib || pts[0].TotalBytes != 100*gib {
+ t.Fatalf("points = %+v, want one point at the tick time", pts)
+ }
+}
+
+// TestBoxSinkRule: the box pages only for incidents; the forecast and the
+// other trend rules are the console's to group and send (fleet alerts spec
+// §7.2).
+func TestBoxSinkRule(t *testing.T) {
+ for rule, want := range map[string]bool{
+ "disk": true, "engine_silent": true,
+ "disk_eta": false, "mem": false, "cpu": false, "lag": false, "geoip": false, "": false,
+ } {
+ if got := boxSinkRule(rule); got != want {
+ t.Errorf("boxSinkRule(%q) = %v, want %v", rule, got, want)
+ }
+ }
+}
diff --git a/internal/host/metrics_loop.go b/internal/host/metrics_loop.go
index a45982ed6..ad2a27e7b 100644
--- a/internal/host/metrics_loop.go
+++ b/internal/host/metrics_loop.go
@@ -32,7 +32,10 @@ type sampleProbes struct {
loadavg func() (l1, l5, l15 *float64)
memFrac func() *float64
diskFrac func() *float64
- units func() map[string]unitRaw
+ // diskBytes is the disk in bytes (used, total, ok) for the forecast,
+ // read beside diskFrac. nil adds no forecast point.
+ diskBytes func() (used, total uint64, ok bool)
+ units func() map[string]unitRaw
// owners is the box's word on whose processes each exec cgroup holds
// (metricsOwners), read before and after units so a reading is tagged
// only when nothing changed during it. nil tags nothing.
@@ -488,6 +491,11 @@ func pruneStaleRaw(ctx context.Context, s release.Store, box string, now time.Ti
// once *st already says "firing", every later tick just confirms it's
// still firing with no new event and nothing left to retry.
//
+// trend is the box's disk ring (disktrend.go); its verdict at the tick time
+// feeds the disk_eta forecast rule. nil leaves that rule alone. Only
+// boxSinkRule's incident rules reach the sinks; every transition still
+// reaches the published and local state.
+//
// Delivery to the sinks is still attempted this tick regardless of whether
// publish succeeded — it's independently fire-and-forget, logged and counted
// on failure, never returned; it does not gate whether *st advances. Local persistence to statePath is also unconditionally
@@ -512,7 +520,7 @@ func pruneStaleRaw(ctx context.Context, s release.Store, box string, now time.Ti
// their very first over-threshold tick instead of a sustain deadline.
func alertTick(ctx context.Context, s release.Store, box string, rules metrics.Rules,
st *metrics.AlertState, latest metrics.Sample, statePath string,
- sinks *alertSinks) error {
+ sinks *alertSinks, trend *diskTrend) error {
obs := metrics.Observation{
At: latest.At,
@@ -522,6 +530,10 @@ func alertTick(ctx context.Context, s release.Store, box string, rules metrics.R
LagSecs: nil, // v1: no lag reading feeds the agent loop yet
GeoIP: geoIPAlertReading(latest.At),
}
+ if trend != nil {
+ v, eta := trend.verdict(latest.At)
+ obs.DiskTrend, obs.DiskETAHours = &v, eta
+ }
newState, events := metrics.Evaluate(rules, *st, obs)
var publishErr error
@@ -536,7 +548,13 @@ func alertTick(ctx context.Context, s release.Store, box string, rules metrics.R
// Fire-and-forget, independent of publish's outcome: an event still
// deserves a delivery attempt even if the store write for it failed.
+ // Only incidents page from the box; the rest reach people through the
+ // console's alert engine (boxSinkRule). The state file and the published
+ // state above carry every transition either way.
for _, ev := range events {
+ if !boxSinkRule(ev.Rule) {
+ continue
+ }
sinks.deliver(ctx, rules, latest.At, ev)
}
@@ -646,10 +664,11 @@ type unitSources struct {
func realSampleProbes(execRoot string, src unitSources, owners func() map[string]metrics.Vouch) sampleProbes {
return sampleProbes{
- procStat: readProcStat,
- loadavg: readLoadAvg,
- memFrac: readMemFrac,
- diskFrac: readDiskFrac,
+ procStat: readProcStat,
+ loadavg: readLoadAvg,
+ memFrac: readMemFrac,
+ diskFrac: readDiskFrac,
+ diskBytes: readDiskBytes,
units: func() map[string]unitRaw {
var stamped, nested []string
if src.stamped != nil {
@@ -865,7 +884,8 @@ func metricsLoop(execRoot string, src unitSources, owners func() map[string]metr
sm.tick(probes)
latest := sm.buf[len(sm.buf)-1]
- if err := alertTick(ctx, s, box, rules, &st, latest, statePath, sinks); err != nil {
+ recordDiskPoint(&processDiskTrend, probes.diskBytes, latest.At)
+ if err := alertTick(ctx, s, box, rules, &st, latest, statePath, sinks, &processDiskTrend); err != nil {
log.Printf("agent: alert tick: %v", err)
}
diff --git a/internal/host/metrics_loop_test.go b/internal/host/metrics_loop_test.go
index 6ce15716a..e175d2362 100644
--- a/internal/host/metrics_loop_test.go
+++ b/internal/host/metrics_loop_test.go
@@ -143,7 +143,7 @@ func TestMetricsLoopStoreHonorsFleetPrefix(t *testing.T) {
firing := 0.95
latest := metrics.Sample{At: at, Host: metrics.HostSample{DiskFrac: &firing}}
statePath := filepath.Join(t.TempDir(), "monitor", "alerts.json")
- if err := alertTick(ctx, s, box, rules, st, latest, statePath, nil); err != nil {
+ if err := alertTick(ctx, s, box, rules, st, latest, statePath, nil, nil); err != nil {
t.Fatal(err)
}
if _, _, err := under.Get(ctx, "fleets/pi/"+metrics.AlertKey(box)); err != nil {
@@ -222,7 +222,7 @@ func TestAlertTickPersistsPublishesAndPosts(t *testing.T) {
return nil
}
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post)); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil); err != nil {
t.Fatal(err)
}
@@ -248,7 +248,7 @@ func TestAlertTickPersistsPublishesAndPosts(t *testing.T) {
}
// Second, identical tick: already firing, no new transition -> no post.
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post)); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil); err != nil {
t.Fatal(err)
}
if len(posts) != 1 {
@@ -274,7 +274,7 @@ func TestAlertTickWebhookFailureDoesNotBlock(t *testing.T) {
}
post := func(url string, body []byte) error { return errors.New("webhook unreachable") }
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post)); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil); err != nil {
t.Fatalf("alertTick must not fail on a webhook error: %v", err)
}
if _, err := os.Stat(statePath); err != nil {
@@ -316,7 +316,7 @@ func TestAlertTickPersistFailureDoesNotSuppressPublish(t *testing.T) {
return nil
}
- if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post)); err != nil {
+ if err := alertTick(ctx, store, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil); err != nil {
t.Fatalf("alertTick must not fail just because the local state write failed: %v", err)
}
if !posted {
@@ -550,7 +550,7 @@ func TestAlertTickRetriesTransitionAfterPublishFailure(t *testing.T) {
}
failStore := &failingPutStore{Store: release.NewDirStore(t.TempDir())}
- if err := alertTick(ctx, failStore, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post)); err == nil {
+ if err := alertTick(ctx, failStore, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil); err == nil {
t.Fatal("expected alertTick to return the publish error against a Put-always-fails store")
}
if st.Rules["disk"].Firing {
@@ -563,7 +563,7 @@ func TestAlertTickRetriesTransitionAfterPublishFailure(t *testing.T) {
// Retry with the SAME observation against a working store: the pending
// transition must reproduce, publish, and post again.
workingStore := release.NewDirStore(t.TempDir())
- if err := alertTick(ctx, workingStore, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post)); err != nil {
+ if err := alertTick(ctx, workingStore, box, rules, st, latest, statePath, webhookSinks("http://example.test/webhook", post), nil); err != nil {
t.Fatalf("retry against a working store: %v", err)
}
if !st.Rules["disk"].Firing {
@@ -923,3 +923,215 @@ func TestMetricsBoxLabelUsesFleetIdentity(t *testing.T) {
func webhookSinks(url string, post func(url string, body []byte) error) *alertSinks {
return newAlertSinks(url, post, "", nil, &alertCounters{})
}
+
+// forecastRig drives alertTick one simulated minute at a time with a disk
+// reading fed to the trend, the way metricsLoop does, and reports each
+// disk_eta transition from the committed state.
+type forecastRig struct {
+ t *testing.T
+ store release.Store
+ statePath string
+ st *metrics.AlertState
+ trend *diskTrend
+ rules metrics.Rules
+ sinks *alertSinks
+ at time.Time
+ box string
+}
+
+func newForecastRig(t *testing.T, sinks *alertSinks) *forecastRig {
+ t.Helper()
+ box := "box-a"
+ return &forecastRig{
+ t: t,
+ store: release.NewDirStore(t.TempDir()),
+ statePath: filepath.Join(t.TempDir(), "monitor", "alerts.json"),
+ st: &metrics.AlertState{V: 1, Box: box, Rules: map[string]metrics.RuleState{}},
+ trend: &diskTrend{},
+ rules: metrics.DefaultRules(),
+ sinks: sinks,
+ at: time.Date(2026, 10, 31, 0, 0, 0, 0, time.UTC),
+ box: box,
+ }
+}
+
+// tick moves one minute on, records used bytes of a 100 GiB disk, runs
+// alertTick, and says whether disk_eta fired or cleared on it.
+func (r *forecastRig) tick(used uint64) (fired, cleared bool) {
+ r.t.Helper()
+ r.at = r.at.Add(time.Minute)
+ r.trend.add(metrics.DiskPoint{At: r.at, UsedBytes: used, TotalBytes: 100 * gib})
+ was := r.st.Rules["disk_eta"].Firing
+ latest := metrics.Sample{At: r.at}
+ if err := alertTick(context.Background(), r.store, r.box, r.rules, r.st, latest, r.statePath, r.sinks, r.trend); err != nil {
+ r.t.Fatal(err)
+ }
+ now := r.st.Rules["disk_eta"].Firing
+ return !was && now, was && !now
+}
+
+// TestAlertTickSinksIncidentOnly: a disk_eta fire is published to the store
+// and the state file but not to the box's sinks; a disk fire reaches both.
+func TestAlertTickSinksIncidentOnly(t *testing.T) {
+ var posted []metrics.Event
+ post := func(url string, body []byte) error {
+ var ev metrics.Event
+ if err := json.Unmarshal(body, &ev); err != nil {
+ t.Errorf("sink body is not an event: %v", err)
+ }
+ posted = append(posted, ev)
+ return nil
+ }
+ r := newForecastRig(t, webhookSinks("http://example.test/webhook", post))
+ r.rules.DiskETAHold = 0 // fire on the first tick that forecasts
+ fillTrend(r.trend, r.at, 360, 46*gib, gib/60)
+
+ if fired, _ := r.tick(46*gib + 6*gib); !fired {
+ t.Fatal("disk_eta did not fire on a steady 1 GiB/h series from 46 GiB")
+ }
+ if len(posted) != 0 {
+ t.Fatalf("the sink got %+v for a disk_eta fire, want nothing", posted)
+ }
+ for name, path := range map[string]string{"state file": r.statePath} {
+ body, err := os.ReadFile(path)
+ if err != nil || !strings.Contains(string(body), `"disk_eta"`) {
+ t.Errorf("%s lacks disk_eta: %v %s", name, err, body)
+ }
+ }
+ pub, _, err := r.store.Get(context.Background(), metrics.AlertKey(r.box))
+ if err != nil || !strings.Contains(string(pub), `"disk_eta"`) {
+ t.Errorf("published state lacks disk_eta: %v %s", err, pub)
+ }
+
+ r.at = r.at.Add(time.Minute)
+ full := 0.95
+ latest := metrics.Sample{At: r.at, Host: metrics.HostSample{DiskFrac: &full}}
+ if err := alertTick(context.Background(), r.store, r.box, r.rules, r.st, latest, r.statePath, r.sinks, r.trend); err != nil {
+ t.Fatal(err)
+ }
+ if len(posted) != 1 || posted[0].Rule != "disk" || !posted[0].Firing {
+ t.Fatalf("sink events = %+v, want exactly the disk fire", posted)
+ }
+ if !r.st.Rules["disk"].Firing {
+ t.Error("disk is not firing in the committed state")
+ }
+}
+
+// TestAlertTickDeletionClearsForecast (plan R3 #1): after the forecast fires,
+// deleting 4 GiB and growing no more clears it within two hours. The fit is
+// the median of pairwise slopes, so the clear comes once most pairs straddle
+// the drop.
+func TestAlertTickDeletionClearsForecast(t *testing.T) {
+ r := newForecastRig(t, nil)
+ perMinute := gib / 60
+
+ used := 46 * gib
+ fired := false
+ for i := 0; i < 12*60 && !fired; i++ {
+ used += perMinute
+ fired, _ = r.tick(used)
+ }
+ if !fired {
+ t.Fatal("the forecast never fired on 1 GiB/h from 46 GiB of 100")
+ }
+
+ used -= 4 * gib
+ clears := 0
+ for i := 0; i < 120; i++ {
+ f, c := r.tick(used)
+ if f {
+ t.Fatalf("minute %d after the deletion: fired again", i+1)
+ }
+ if c {
+ clears++
+ t.Logf("cleared %d minutes after the deletion", i+1)
+ }
+ }
+ if clears != 1 {
+ t.Fatalf("clears within 2 h of deleting 4 GiB = %d, want 1", clears)
+ }
+}
+
+// TestAlertTickSustainedFlatClears: usage that stops growing without a
+// deletion clears only once the fit stops seeing growth, which is by the time
+// the 6 h window holds nothing but the flat part, and not before.
+func TestAlertTickSustainedFlatClears(t *testing.T) {
+ r := newForecastRig(t, nil)
+ perMinute := gib / 60
+
+ used := 46 * gib
+ fired := false
+ for i := 0; i < 12*60 && !fired; i++ {
+ used += perMinute
+ fired, _ = r.tick(used)
+ }
+ if !fired {
+ t.Fatal("the forecast never fired")
+ }
+
+ clearedAt := 0
+ for i := 1; i <= 360 && clearedAt == 0; i++ {
+ _, c := r.tick(used)
+ v, eta := r.trend.verdict(r.at)
+ if c {
+ clearedAt = i
+ t.Logf("cleared %d minutes after usage went flat", i)
+ if v == metrics.TrendGrowing && eta <= r.rules.DiskETAHours*1.5 {
+ t.Fatalf("cleared at minute %d while the fit still forecasts %.1f h", i, eta)
+ }
+ continue
+ }
+ if v != metrics.TrendGrowing {
+ t.Fatalf("minute %d: verdict %v but no clear", i, v)
+ }
+ if eta > r.rules.DiskETAHours*1.5 {
+ t.Fatalf("minute %d: eta %.1f h is past the clear line but no clear", i, eta)
+ }
+ }
+ if clearedAt == 0 {
+ t.Fatal("no clear in the 6 h after usage went flat")
+ }
+ for i := 0; i < 30; i++ {
+ if f, c := r.tick(used); f || c {
+ t.Fatalf("flapped %d minutes after the clear (fired=%v cleared=%v)", i+1, f, c)
+ }
+ }
+}
+
+// TestSnapshotCarriesDiskETA: the heartbeat carries the forecast's hours to
+// full while it is growing, and no key at all otherwise.
+func TestSnapshotCarriesDiskETA(t *testing.T) {
+ end := time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)
+
+ var growing diskTrend
+ fillTrend(&growing, end, 360, 46*gib, gib/60)
+ eta := diskETAProbe(&growing, end)
+ if eta == nil || *eta <= 0 || *eta > 100 {
+ t.Fatalf("growing series: probe = %v, want a positive ETA", eta)
+ }
+ box := status.CollectBox(nil, status.Probes{DiskFullETAHours: eta}, end)
+ raw, _ := json.Marshal(box)
+ if !strings.Contains(string(raw), `"disk_full_eta_hours":`) {
+ t.Errorf("heartbeat lacks disk_full_eta_hours: %s", raw)
+ }
+ if box.Metrics == nil || box.Metrics.DiskFullETAHours == nil || *box.Metrics.DiskFullETAHours != *eta {
+ t.Errorf("metrics = %+v, want the probe's ETA", box.Metrics)
+ }
+
+ var flat diskTrend
+ fillTrend(&flat, end, 360, 46*gib, 0)
+ if got := diskETAProbe(&flat, end); got != nil {
+ t.Errorf("flat series: probe = %v, want nil", *got)
+ }
+ var none diskTrend
+ if got := diskETAProbe(&none, end); got != nil {
+ t.Errorf("empty ring: probe = %v, want nil", *got)
+ }
+ if got := diskETAProbe(nil, end); got != nil {
+ t.Errorf("nil trend: probe = %v, want nil", *got)
+ }
+ raw, _ = json.Marshal(status.CollectBox(nil, status.Probes{DiskFullETAHours: diskETAProbe(&flat, end), Release: "v1"}, end))
+ if strings.Contains(string(raw), "disk_full_eta_hours") {
+ t.Errorf("a non-growing disk must publish no ETA key: %s", raw)
+ }
+}
diff --git a/internal/host/probes.go b/internal/host/probes.go
index ff65b5c4a..9140019bb 100644
--- a/internal/host/probes.go
+++ b/internal/host/probes.go
@@ -215,6 +215,18 @@ func readDiskFrac() *float64 {
return &frac
}
+// readDiskBytes is readDiskFrac's byte form, for the disk forecast: bytes
+// used (total minus available, the same measure the fraction uses) and the
+// filesystem size of dataDir(). ok is false on a statfs failure or a
+// zero-size filesystem, so a caller never divides by nothing.
+func readDiskBytes() (used, total uint64, ok bool) {
+ total, avail, err := diskBytes(dataDir())
+ if err != nil || total == 0 || avail > total {
+ return 0, 0, false
+ }
+ return total - avail, total, true
+}
+
// listeningProbe reads /proc/net/unix — the kernel's own table of bound
// unix-domain sockets — rather than dialing sock. Dialing would itself be a
// connection attempt on a hibernating tenant's socket, which is exactly the
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go
index 5335a80ff..f5161dbd0 100644
--- a/internal/status/snapshot.go
+++ b/internal/status/snapshot.go
@@ -73,6 +73,9 @@ type Probes struct {
// "never asked / couldn't tell", and like every other nil here it must
// publish as null: a box that can't answer is not a box that is fine.
AdoptRunning *bool
+ // DiskFullETAHours is the disk forecast's hours to full while growing,
+ // nil otherwise (BoxMetrics.DiskFullETAHours).
+ DiskFullETAHours *float64
// ConfigPathRunning is whether this box's config-sync trigger unit
// (carlos-adopt.path) is ACTIVE — the issue #44 sibling of AdoptRunning,
// with the identical failure mode behind it: enabled writes a symlink,
@@ -548,6 +551,11 @@ type BoxMetrics struct {
Platform string `json:"platform,omitempty"` // runtime.GOOS-runtime.GOARCH
SystemChannel string `json:"system_channel,omitempty"` // CARLOS_SYSTEM_CHANNEL
System *SystemState `json:"system,omitempty"` // last self-update outcome
+ // DiskFullETAHours is the box's own forecast of hours until the data
+ // volume is full, present only while the fitted trend is growing (fleet
+ // alerts spec §7.2). Absent means no forecast or no growth, never "far
+ // off": the console reads absence as "nothing is filling".
+ DiskFullETAHours *float64 `json:"disk_full_eta_hours,omitempty"`
// Alerts is where this box's own alert rules (metrics.Evaluate) can send
// a fire or clear, and how many sends have failed since the agent
// started. nil means the box did not say (a snapshot from before the
@@ -1129,7 +1137,7 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box {
// exception is AliasesRead (#447): a successful read of no alias rows IS
// something to say, so it attaches the block on its own.
if p.MemTotalBytes != nil || p.MemAvailBytes != nil || p.Load1 != nil ||
- p.DiskFreeBytes != nil || p.Release != "" || p.Tunnel != "" ||
+ p.DiskFreeBytes != nil || p.DiskFullETAHours != nil || p.Release != "" || p.Tunnel != "" ||
p.InstanceID != "" || p.Platform != "" || p.SystemChannel != "" || p.System != nil ||
len(routeVersions) > 0 || len(routeServing) > 0 || len(aliasReadings) > 0 || p.AliasesRead || len(p.Upstreams) > 0 ||
len(routeDBBytes) > 0 || p.Layout != nil || len(p.ConfigRefusals) > 0 || len(p.ReleaseRefusals) > 0 || len(p.ProofWaits) > 0 || p.Rollout != nil || p.ConfigGuard != "" ||
@@ -1151,7 +1159,7 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box {
RetirementReceiptSHA256: p.RetirementReceiptSHA256,
MemTotalBytes: p.MemTotalBytes, MemAvailBytes: p.MemAvailBytes,
- Load1: p.Load1, DiskFreeBytes: p.DiskFreeBytes,
+ Load1: p.Load1, DiskFreeBytes: p.DiskFreeBytes, DiskFullETAHours: p.DiskFullETAHours,
Release: p.Release, Tunnel: p.Tunnel, GeoIP: p.GeoIP,
Platform: p.Platform, SystemChannel: p.SystemChannel, System: p.System,
InstanceID: p.InstanceID,