alerts: backhaul_shed box rule from the edge's refusal counters
The agent's metrics loop reads Edge.BackhaulSheds through the same in-process seam the geoip code and static tree use (a func the edge-ready callback publishes), records the cumulative counters in each metrics sample (backhaul_sheds, omitted when nil) and feeds the per-tick change to a new box rule. backhaul_shed fires when more than 10 hops were refused in a minute and clears after a minute with none. It is a warning published in alerts/boxes/<box>.json like the other box rules, and the console's alert engine knows its level, order and words. All of its operator text is one const block in internal/alerting. Refs #1535
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+417
−16
internal/alerting/ruletext.go+26 −0internal/console/alertengine_pass.go+3 −1internal/console/alertnotify.go+7 −0internal/console/alertpages.go+7 −1internal/console/alertpages_test.go+39 −0internal/console/alertsignals.go+1 −0internal/host/agent.go+18 −0internal/host/metrics_backhaul_test.go+124 −0internal/host/metrics_loop.go+43 −9internal/metrics/alert.go+27 −1internal/metrics/backhaul.go+33 −0internal/metrics/backhaul_test.go+81 −0internal/metrics/sample.go+8 −4
diff --git a/internal/alerting/ruletext.go b/internal/alerting/ruletext.go| index 76f7ef2d8..d7a429a79 100644 |
| --- a/internal/alerting/ruletext.go |
| +++ b/internal/alerting/ruletext.go |
| @@ -86,8 +86,34 @@ var BoxRuleText = map[string]RuleText{ |
| HowLong: "Nothing is down. Owners see an old test date until it catches up.", |
| WhatToDo: "Give the nightly run more time on that box, or spread its instances over more boxes.", |
| }, |
| + "backhaul_shed": { |
| + Title: BackhaulShedTitle, |
| + HowLong: BackhaulShedHowLong, |
| + WhatToDo: BackhaulShedWhatToDo, |
| + }, |
| } |
| +// The backhaul_shed rule's words (#1535), every one in this block: a box |
| +// refused requests it was forwarding to the box that hosts their app |
| +// (the backhaul), because that box had too many in flight from it, or one |
| +// visitor held too many. The console's messages and Rules page read the |
| +// rest of them from here too. Not yet copy reviewed. |
| +const ( |
| + BackhaulShedTitle = "Forwarded requests refused" |
| + BackhaulShedHowLong = "Visitors are already getting errors, and keep getting them while the limit is reached." |
| + BackhaulShedWhatToDo = "Read the box's journal for backhaul lines to see which box was full and why. If real traffic needs more room, raise CARLOS_BACKHAUL_MAX_INFLIGHT or CARLOS_BACKHAUL_MAX_STREAMS in its host.env." |
| + // BackhaulShedWhat and BackhaulShedWhatNone open a message; %s is |
| + // the box. |
| + BackhaulShedWhat = "%s refused requests it was forwarding to another box." |
| + BackhaulShedWhatNone = "A box refused requests it was forwarding to another box." |
| + // BackhaulShedWhen and BackhaulShedThreshold are the Rules page's |
| + // lines. The number is metrics.DefaultRules().BackhaulShedCount. |
| + BackhaulShedWhen = "A box refuses more than 10 requests in a minute that it was forwarding to another box." |
| + BackhaulShedThreshold = "Fixed at more than 10 in a minute. Clears after a minute with none. Not configurable." |
| + // BackhaulShedValue is the last reading; %d is the count. |
| + BackhaulShedValue = "%d refused in a minute" |
| +) |
| + |
| // VerifyReason is one reason code a restore test's verdict carries |
| // (dbverify.Verdict.Reason) and the words for it. |
| type VerifyReason struct { |
diff --git a/internal/console/alertengine_pass.go b/internal/console/alertengine_pass.go| index 476f970b3..a549c0a3a 100644 |
| --- a/internal/console/alertengine_pass.go |
| +++ b/internal/console/alertengine_pass.go |
| @@ -382,7 +382,7 @@ func alertRuleConnectors(st alertRuleSetting, conns []alertConnector) []int64 { |
| // alertValued are the rules whose value means something in a message. |
| var alertValued = map[string]bool{ |
| "disk": true, "mem": true, "cpu": true, "lag": true, "geoip": true, "disk_eta": true, "box_silent": true, "cert_expiring": true, |
| - "restarts": true, |
| + "restarts": true, "backhaul_shed": true, |
| } |
| // alertEmitNote is what one emit says, stored without links (ruling R-2). |
| @@ -761,6 +761,8 @@ func alertValueText(rule string, value float64) string { |
| return fmt.Sprintf("%.0f days left", value) |
| case "restarts": |
| return fmt.Sprintf("%d restarts in 10 minutes", int(value)) |
| + case "backhaul_shed": |
| + return fmt.Sprintf(alerting.BackhaulShedValue, int(value)) |
| case "verify_unverified": |
| // A reason, not a measurement (alerting.VerifyReasons). |
| if label, ok := alerting.VerifyReasonLabel(value); ok { |
diff --git a/internal/console/alertnotify.go b/internal/console/alertnotify.go| index 85359abf2..e4d2812fa 100644 |
| --- a/internal/console/alertnotify.go |
| +++ b/internal/console/alertnotify.go |
| @@ -224,6 +224,13 @@ var alertCopy = map[string]string{ |
| "rule.verify_coverage.how_long": alerting.BoxRuleText["verify_coverage"].HowLong, |
| "rule.verify_coverage.what_to_do": alerting.BoxRuleText["verify_coverage"].WhatToDo, |
| + // The backhaul refusal rule (#1535): every line is alerting's. |
| + "rule.backhaul_shed.title": alerting.BackhaulShedTitle, |
| + "rule.backhaul_shed.what": alerting.BackhaulShedWhat, |
| + "rule.backhaul_shed.what.none": alerting.BackhaulShedWhatNone, |
| + "rule.backhaul_shed.how_long": alerting.BackhaulShedHowLong, |
| + "rule.backhaul_shed.what_to_do": alerting.BackhaulShedWhatToDo, |
| + |
| "rule.box_silent.title": "Box silent", |
| "rule.box_silent.what": "%s has stopped reporting.", |
| "rule.box_silent.what.none": "A box has stopped reporting.", |
diff --git a/internal/console/alertpages.go b/internal/console/alertpages.go| index b55ef7d12..44d2a6b41 100644 |
| --- a/internal/console/alertpages.go |
| +++ b/internal/console/alertpages.go |
| @@ -14,6 +14,8 @@ import ( |
| "strings" |
| "time" |
| "unicode" |
| + |
| + "github.com/carlosframework/platform/internal/alerting" |
| ) |
| // alertPageCopy is every word of the Alerts pages and the token doors: the |
| @@ -194,6 +196,10 @@ var alertPageCopy = map[string]string{ |
| "rules.th.verify_unverified": "Fixed at 3 nights in a row. Not configurable.", |
| "rules.when.verify_coverage": "An instance on a box hasn't had a restore test for more than 7 days.", |
| "rules.th.verify_coverage": "Fixed at 7 days. Not configurable.", |
| + |
| + // The backhaul refusal rule (#1535); its words are alerting's. |
| + "rules.when.backhaul_shed": alerting.BackhaulShedWhen, |
| + "rules.th.backhaul_shed": alerting.BackhaulShedThreshold, |
| } |
| // The operator Alerts pages (fleet alerts spec §5, plan 1 Task 10): |
| @@ -224,7 +230,7 @@ const ( |
| // the console's. It names every rule in alertRuleLevels |
| // (TestAlertRuleOrderCoversEveryRule). |
| var alertRuleOrder = []string{"disk_eta", "disk", "mem", "cpu", "lag", "geoip", "engine_silent", "restarts", |
| - "verify_failed", "verify_unverified", "verify_coverage", |
| + "verify_failed", "verify_unverified", "verify_coverage", "backhaul_shed", |
| "box_silent", "service_down", "cert_expiring", "alert_delivery_broken", "mailer_unarmed", "demo_sandbox", "seal_key"} |
| // alertThresholdBounds are the editable thresholds' whole-number bounds: |
diff --git a/internal/console/alertpages_test.go b/internal/console/alertpages_test.go| index ccc22e512..74d0554eb 100644 |
| --- a/internal/console/alertpages_test.go |
| +++ b/internal/console/alertpages_test.go |
| @@ -14,6 +14,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/alerting" |
| + "github.com/carlosframework/platform/internal/metrics" |
| ) |
| // alertsPageFixture is an operator signed in to a console whose alert |
| @@ -944,3 +945,41 @@ func TestAlertRuleOrderCoversVerify(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// The backhaul refusal rule (#1535) is a box rule the console knows: a |
| +// warning, after the restore drill's rules, with its words from alerting and |
| +// its value read as a count. The Rules page's number is the box's default. |
| +func TestAlertRuleBackhaulShed(t *testing.T) { |
| + const rule = "backhaul_shed" |
| + if rule != metrics.BackhaulShedRule { |
| + t.Fatalf("rule ID %q, the box publishes %q", rule, metrics.BackhaulShedRule) |
| + } |
| + if i := slices.Index(alertRuleOrder, "verify_coverage"); i < 0 || i+1 >= len(alertRuleOrder) || alertRuleOrder[i+1] != rule { |
| + t.Fatalf("alertRuleOrder = %v, want %s after verify_coverage", alertRuleOrder, rule) |
| + } |
| + if alertRuleLevel(rule) != alerting.LevelWarning { |
| + t.Fatalf("level = %q, want a warning", alertRuleLevel(rule)) |
| + } |
| + v := alertRuleRow(rule, nil, nil, alertNoise{}) |
| + if v.When != alerting.BackhaulShedWhen || v.Threshold != alerting.BackhaulShedThreshold || v.Editable || v.BoxEnv { |
| + t.Fatalf("row: when %q, threshold %q (editable %v, box env %v)", v.When, v.Threshold, v.Editable, v.BoxEnv) |
| + } |
| + if n := metrics.DefaultRules().BackhaulShedCount; !strings.Contains(alerting.BackhaulShedWhen, "more than 10 ") || n != 10 { |
| + t.Fatalf("the page says more than 10, the box fires above %v", n) |
| + } |
| + if got := alertRuleTitle(rule); got != alerting.BackhaulShedTitle { |
| + t.Fatalf("title = %q", got) |
| + } |
| + if got := alertValueText(rule, 37); got != "37 refused in a minute" { |
| + t.Fatalf("value = %q", got) |
| + } |
| + if !alertValued[rule] { |
| + t.Fatal("the value is not shown in a message") |
| + } |
| + for _, s := range []string{alerting.BackhaulShedTitle, alerting.BackhaulShedHowLong, alerting.BackhaulShedWhatToDo, |
| + alerting.BackhaulShedWhat, alerting.BackhaulShedWhatNone, alerting.BackhaulShedWhen, alerting.BackhaulShedThreshold, alerting.BackhaulShedValue} { |
| + if strings.ContainsAny(s, "—–") { |
| + t.Errorf("dash in %q", s) |
| + } |
| + } |
| +} |
diff --git a/internal/console/alertsignals.go b/internal/console/alertsignals.go| index bca6e7280..57a4e9546 100644 |
| --- a/internal/console/alertsignals.go |
| +++ b/internal/console/alertsignals.go |
| @@ -848,6 +848,7 @@ var alertRuleLevels = map[string]string{ |
| "verify_failed": alerting.LevelIncident, |
| "verify_unverified": alerting.LevelWarning, |
| "verify_coverage": alerting.LevelWarning, |
| + "backhaul_shed": alerting.LevelWarning, |
| "box_silent": alerting.LevelIncident, |
| "service_down": alerting.LevelIncident, |
| "cert_expiring": alerting.LevelWarning, |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 9af566614..2e1ff3de0 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -1402,6 +1402,9 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| heldStreamsSource.Store(e.HeldStreamsForStatus) |
| geoIPAlertSource.Store(e.GeoIPAlertCode) |
| staticTreeSource.Store(e.LargestStaticTree) |
| + // The backhaul's refusal counters for the backhaul_shed rule |
| + // (#1535), the same way: in-process, no store read. |
| + backhaulShedSource.Store(e.BackhaulSheds) |
| // The layout pass reloads routing through this as soon as a move |
| // commits, instead of waiting for the 2s registry poll. |
| reload := func() { _ = e.Reload() } |
| @@ -4915,6 +4918,21 @@ var geoIPAlertSource atomic.Value // func(time.Time) (float64, bool) |
| // edge exists, for the disk rule's line (diskAlertFrac). |
| var staticTreeSource atomic.Value // func() int64 |
| +// backhaulShedSource is the edge's Edge.BackhaulSheds, published once the |
| +// edge exists, for the metrics sample and the backhaul_shed rule (#1535). |
| +var backhaulShedSource atomic.Value // func() edge.BackhaulSheds |
| + |
| +// sampleBackhaulSheds reads it as a sample carries it, nil before the edge |
| +// is ready (no reading never fires and never clears). |
| +func sampleBackhaulSheds() *metrics.BackhaulShedSample { |
| + fn, _ := backhaulShedSource.Load().(func() edge.BackhaulSheds) |
| + if fn == nil { |
| + return nil |
| + } |
| + c := fn() |
| + return &metrics.BackhaulShedSample{Requests: c.Requests, Streams: c.Streams, FairShare: c.FairShare} |
| +} |
| + |
| // largestStaticTree reads it, 0 before the edge is ready. |
| func largestStaticTree() int64 { |
| fn, _ := staticTreeSource.Load().(func() int64) |
diff --git a/internal/host/metrics_backhaul_test.go b/internal/host/metrics_backhaul_test.go| new file mode 100644 |
| index 000000000..34090ca9b |
| --- /dev/null |
| +++ b/internal/host/metrics_backhaul_test.go |
| @@ -0,0 +1,124 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The edge's backhaul refusal counters reach the metrics loop through the |
| +// same in-process seam as the geoip code: a func the edge-ready callback |
| +// publishes. Before the edge is ready there is no reading. |
| +func TestSampleBackhaulShedsReadsTheEdge(t *testing.T) { |
| + old := backhaulShedSource.Load() |
| + t.Cleanup(func() { |
| + if old != nil { |
| + backhaulShedSource.Store(old) |
| + } else { |
| + backhaulShedSource.Store((func() edge.BackhaulSheds)(nil)) |
| + } |
| + }) |
| + backhaulShedSource.Store((func() edge.BackhaulSheds)(nil)) |
| + if got := sampleBackhaulSheds(); got != nil { |
| + t.Fatalf("before the edge is ready: %+v, want nil", got) |
| + } |
| + backhaulShedSource.Store(func() edge.BackhaulSheds { return edge.BackhaulSheds{Requests: 1, Streams: 2, FairShare: 3} }) |
| + got := sampleBackhaulSheds() |
| + if got == nil || *got != (metrics.BackhaulShedSample{Requests: 1, Streams: 2, FairShare: 3}) { |
| + t.Fatalf("sampleBackhaulSheds = %+v, want the edge's counters", got) |
| + } |
| +} |
| + |
| +// A sample carries the counters, and the watch turns consecutive samples |
| +// into the per-tick reading the rule wants. |
| +func TestSamplerCarriesBackhaulSheds(t *testing.T) { |
| + counts := &metrics.BackhaulShedSample{} |
| + at := time.Date(2026, 12, 2, 12, 0, 0, 0, time.UTC) |
| + probes := sampleProbes{ |
| + procStat: func() *metrics.CPUCounters { return nil }, |
| + loadavg: func() (*float64, *float64, *float64) { return nil, nil, nil }, |
| + memFrac: func() *float64 { return nil }, |
| + diskFrac: func() *float64 { return nil }, |
| + units: func() map[string]unitRaw { return nil }, |
| + now: func() time.Time { return at }, |
| + backhaulSheds: func() *metrics.BackhaulShedSample { c := *counts; return &c }, |
| + } |
| + sm := &sampler{} |
| + var w backhaulShedWatch |
| + var readings []float64 |
| + for _, c := range []metrics.BackhaulShedSample{{Requests: 5}, {Requests: 5, Streams: 20}, {Requests: 5, Streams: 20}} { |
| + *counts = c |
| + sm.tick(probes) |
| + latest := sm.buf[len(sm.buf)-1] |
| + if latest.BackhaulSheds == nil || *latest.BackhaulSheds != c { |
| + t.Fatalf("sample carries %+v, want %+v", latest.BackhaulSheds, c) |
| + } |
| + r := w.read(latest.BackhaulSheds) |
| + if r == nil { |
| + t.Fatal("no reading from a sample with counters") |
| + } |
| + readings = append(readings, *r) |
| + } |
| + if want := []float64{5, 20, 0}; readings[0] != want[0] || readings[1] != want[1] || readings[2] != want[2] { |
| + t.Fatalf("readings = %v, want %v", readings, want) |
| + } |
| + if r := w.read(nil); r != nil { |
| + t.Fatalf("no counters read %v, want nil", *r) |
| + } |
| + b, err := json.Marshal(sm.buf[1]) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var back metrics.Sample |
| + if err := json.Unmarshal(b, &back); err != nil || back.BackhaulSheds == nil || back.BackhaulSheds.Streams != 20 { |
| + t.Fatalf("chunk round trip: %s (%v)", b, err) |
| + } |
| +} |
| + |
| +// backhaul_shed is published to the box's alert object like every box |
| +// rule, fires and clears there, and is not a box-sink rule: it reaches |
| +// operators through the console's alert engine. |
| +func TestAlertTickPublishesBackhaulShed(t *testing.T) { |
| + ctx := context.Background() |
| + store := release.NewDirStore(t.TempDir()) |
| + statePath := filepath.Join(t.TempDir(), "monitor", "alerts.json") |
| + box := "box-a" |
| + st := &metrics.AlertState{V: 1, Box: box, Rules: map[string]metrics.RuleState{}} |
| + var posts int |
| + sinks := webhookSinks("http://example.test/webhook", func(string, []byte) error { posts++; return nil }) |
| + at := time.Date(2026, 12, 2, 12, 0, 0, 0, time.UTC) |
| + published := func(n float64) metrics.RuleState { |
| + t.Helper() |
| + at = at.Add(time.Minute) |
| + if err := alertTick(ctx, store, box, metrics.DefaultRules(), st, metrics.Sample{At: at}, alertReadings{backhaulSheds: &n}, statePath, sinks, nil, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + body, _, err := store.Get(ctx, metrics.AlertKey(box)) |
| + if err != nil { |
| + t.Fatalf("published state: %v", err) |
| + } |
| + var pub metrics.AlertState |
| + if err := json.Unmarshal(body, &pub); err != nil { |
| + t.Fatal(err) |
| + } |
| + return pub.Rules[metrics.BackhaulShedRule] |
| + } |
| + if rs := published(40); !rs.Firing || rs.Value != 40 { |
| + t.Fatalf("40 refusals in a minute: published %+v, want firing with 40", rs) |
| + } |
| + if rs := published(0); rs.Firing { |
| + t.Fatalf("a quiet minute: published %+v, want cleared", rs) |
| + } |
| + if posts != 0 { |
| + t.Fatalf("the box's own sink got %d post(s), want none: backhaul_shed is not a box-sink rule", posts) |
| + } |
| + if boxSinkRule(metrics.BackhaulShedRule) { |
| + t.Fatal("backhaul_shed is a box-sink rule") |
| + } |
| +} |
diff --git a/internal/host/metrics_loop.go b/internal/host/metrics_loop.go| index 8ac3df446..7cf02bce4 100644 |
| --- a/internal/host/metrics_loop.go |
| +++ b/internal/host/metrics_loop.go |
| @@ -50,6 +50,9 @@ type sampleProbes struct { |
| demoDisk func() *status.DemoDisk |
| now func() time.Time |
| departures func() *metrics.DepartureSample |
| + // backhaulSheds is the edge's backhaul refusal counters |
| + // (sampleBackhaulSheds); nil, or nil from it, is no reading. |
| + backhaulSheds func() *metrics.BackhaulShedSample |
| } |
| // samplerMaxBuf hard-caps sm.buf at ~2h of 60s ticks. metricsFlush only |
| @@ -149,9 +152,14 @@ func (sm *sampler) tick(p sampleProbes) { |
| if p.departures != nil { |
| departures = p.departures() |
| } |
| + var sheds *metrics.BackhaulShedSample |
| + if p.backhaulSheds != nil { |
| + sheds = p.backhaulSheds() |
| + } |
| sm.buf = append(sm.buf, metrics.Sample{ |
| - HADepartures: departures, |
| - At: now, |
| + HADepartures: departures, |
| + BackhaulSheds: sheds, |
| + At: now, |
| Host: metrics.HostSample{ |
| CPUFrac: hostCPU, |
| Load1: l1, |
| @@ -563,6 +571,8 @@ func alertTick(ctx context.Context, s release.Store, box string, rules metrics.R |
| GeoIP: geoIPAlertReading(latest.At), |
| Restarts: extra.restarts, |
| Verify: extra.verify, |
| + // backhaul_shed (#1535): refusals since the last tick. |
| + BackhaulSheds: extra.backhaulSheds, |
| } |
| if trend != nil { |
| v, eta := trend.verdict(latest.At) |
| @@ -640,6 +650,24 @@ type alertReadings struct { |
| // rule reads the higher of it and the data disk's blocks. nil on any |
| // other box. |
| demoFill *diskReading |
| + // backhaulSheds is how many hops the edge's backhaul refused since the |
| + // last tick (backhaulShedWatch); nil leaves backhaul_shed as it was. |
| + backhaulSheds *float64 |
| +} |
| + |
| +// backhaulShedWatch turns the cumulative counters each sample carries into |
| +// the backhaul_shed rule's per-tick reading. One for the life of the loop. |
| +type backhaulShedWatch struct{ prev *metrics.BackhaulShedSample } |
| + |
| +// read is the refusals cur counts that the last reading did not, or nil |
| +// when cur is nil (the edge is not ready), which keeps the last reading. |
| +func (w *backhaulShedWatch) read(cur *metrics.BackhaulShedSample) *float64 { |
| + if cur == nil { |
| + return nil |
| + } |
| + v := metrics.BackhaulShedsSince(w.prev, cur) |
| + w.prev = cur |
| + return v |
| } |
| // verifyWatch reads the restore drill's local copy of this box's record |
| @@ -789,12 +817,13 @@ type unitSources struct { |
| func realSampleProbes(execRoot string, src unitSources, owners func() map[string]metrics.Vouch) sampleProbes { |
| return sampleProbes{ |
| - departures: sampleDepartures, |
| - procStat: readProcStat, |
| - loadavg: readLoadAvg, |
| - memFrac: readMemFrac, |
| - diskFrac: readDiskFrac, |
| - diskBytes: readDiskBytes, |
| + departures: sampleDepartures, |
| + backhaulSheds: sampleBackhaulSheds, |
| + procStat: readProcStat, |
| + loadavg: readLoadAvg, |
| + memFrac: readMemFrac, |
| + diskFrac: readDiskFrac, |
| + diskBytes: readDiskBytes, |
| units: func() map[string]unitRaw { |
| var stamped, nested []string |
| if src.stamped != nil { |
| @@ -1014,6 +1043,9 @@ func metricsLoop(execRoot string, src unitSources, owners func() map[string]metr |
| // alerted is what keeps a standing refusal from paging every minute. |
| // dataDir() is the bake dir the agent hands release.BakeDir. |
| var refusals refusalWatch |
| + // The backhaul's refusal counters are cumulative; the rule reads the |
| + // change from one tick to the next. |
| + var sheds backhaulShedWatch |
| // The restart watch is the one reading taken before the first sleep. It |
| // is loaded from the last run and sampled at once, so an agent that is |
| @@ -1061,7 +1093,9 @@ func metricsLoop(execRoot string, src unitSources, owners func() map[string]metr |
| sm.tick(probes) |
| latest := sm.buf[len(sm.buf)-1] |
| recordDiskPoint(&processDiskTrend, probes.diskBytes, latest.At) |
| - if err := alertTick(ctx, s, box, rules, &st, latest, restartTick(latest.At), statePath, sinks, &processDiskTrend, beat); err != nil { |
| + extra := restartTick(latest.At) |
| + extra.backhaulSheds = sheds.read(latest.BackhaulSheds) |
| + if err := alertTick(ctx, s, box, rules, &st, latest, extra, statePath, sinks, &processDiskTrend, beat); err != nil { |
| log.Printf("agent: alert tick: %v", err) |
| } |
diff --git a/internal/metrics/alert.go b/internal/metrics/alert.go| index c9077f902..0a8cddfa9 100644 |
| --- a/internal/metrics/alert.go |
| +++ b/internal/metrics/alert.go |
| @@ -33,6 +33,10 @@ type Rules struct { |
| // reporter's window before that unit's restarts rule fires. It is a |
| // count, not a fraction; see UnitRestarts for what clears it. |
| RestartCount float64 // fire >, default 3 |
| + // BackhaulShedCount is how many backhaul refusals one tick may count |
| + // before backhaul_shed fires. A count, not a fraction; the rule clears |
| + // on the first tick with none. |
| + BackhaulShedCount float64 // fire >, default 10 |
| } |
| // DefaultRules are the thresholds shipped with the platform. |
| @@ -51,6 +55,8 @@ func DefaultRules() Rules { |
| DiskETAHours: 72, |
| DiskETAHold: 2 * time.Hour, |
| RestartCount: 3, |
| + // backhaul_shed (#1535): fixed, like the restart count. |
| + BackhaulShedCount: 10, |
| } |
| } |
| @@ -128,6 +134,10 @@ type Observation struct { |
| // of its record (ReadVerify). nil is "no reading" and leaves every |
| // verify rule as it was. |
| Verify *VerifyReading |
| + // BackhaulSheds is how many hops the edge's backhaul refused since the |
| + // last tick (BackhaulShedsSince). nil is no reading and leaves the |
| + // backhaul_shed rule as it was. |
| + BackhaulSheds *float64 |
| } |
| // UnitRestarts is one unit's restart reading. |
| @@ -185,7 +195,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","geoip","disk_eta","engine_silent","verify_coverage"; "restarts@<unit>" per unit; "verify_failed@<host>", "verify_unverified@<host>" per host |
| + Rules map[string]RuleState `json:"rules"` // "disk","mem","cpu","lag","geoip","disk_eta","engine_silent","verify_coverage","backhaul_shed"; "restarts@<unit>" per unit; "verify_failed@<host>", "verify_unverified@<host>" per host |
| } |
| // Event is emitted on a firing or clearing transition — never on every |
| @@ -470,5 +480,21 @@ func Evaluate(r Rules, st AlertState, obs Observation) (AlertState, []Event) { |
| events = append(events, evalVerify(out.Rules, obs.Verify, obs.At, st.Box)...) |
| } |
| + // backhaul_shed: a count over the last tick, so no sustain. It fires |
| + // above BackhaulShedCount and clears on the first tick with none, so a |
| + // box still refusing a few hops keeps it up. |
| + if obs.BackhaulSheds != nil { |
| + val := *obs.BackhaulSheds |
| + cur := out.Rules[BackhaulShedRule] |
| + switch { |
| + case !cur.Firing && val > r.BackhaulShedCount: |
| + out.Rules[BackhaulShedRule] = RuleState{Firing: true, Since: obs.At, FiredAt: obs.At, Value: val} |
| + emit(BackhaulShedRule, true, val) |
| + case cur.Firing && val == 0: |
| + out.Rules[BackhaulShedRule] = RuleState{} |
| + emit(BackhaulShedRule, false, 0) |
| + } |
| + } |
| + |
| return out, events |
| } |
diff --git a/internal/metrics/backhaul.go b/internal/metrics/backhaul.go| new file mode 100644 |
| index 000000000..b6eeb4c88 |
| --- /dev/null |
| +++ b/internal/metrics/backhaul.go |
| @@ -0,0 +1,33 @@ |
| +package metrics |
| + |
| +// BackhaulShedRule is the box rule for hops the sending edge's backhaul |
| +// refused (#1535): a request-pool or stream-pool saturation (503) or a |
| +// fair-share refusal (429). Its value is how many in the last tick. |
| +const BackhaulShedRule = "backhaul_shed" |
| + |
| +// BackhaulShedSample is the edge's refusal counters, cumulative since the |
| +// edge started (edge.BackhaulSheds), as a sample carries them. |
| +type BackhaulShedSample struct { |
| + Requests uint64 `json:"requests"` |
| + Streams uint64 `json:"streams"` |
| + FairShare uint64 `json:"fair_share"` |
| +} |
| + |
| +func (s BackhaulShedSample) total() uint64 { return s.Requests + s.Streams + s.FairShare } |
| + |
| +// BackhaulShedsSince is the backhaul_shed reading: how many refusals cur |
| +// counts that prev did not. nil cur is no reading. nil prev counts from zero, |
| +// which is right because the edge's counters start at zero in the same |
| +// process as the reader. A total lower than prev's is a new edge, counted |
| +// from zero too. |
| +func BackhaulShedsSince(prev, cur *BackhaulShedSample) *float64 { |
| + if cur == nil { |
| + return nil |
| + } |
| + n := cur.total() |
| + if prev != nil && prev.total() <= n { |
| + n -= prev.total() |
| + } |
| + v := float64(n) |
| + return &v |
| +} |
diff --git a/internal/metrics/backhaul_test.go b/internal/metrics/backhaul_test.go| new file mode 100644 |
| index 000000000..4e856bf83 |
| --- /dev/null |
| +++ b/internal/metrics/backhaul_test.go |
| @@ -0,0 +1,81 @@ |
| +package metrics |
| + |
| +import ( |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The backhaul_shed rule (#1535): fires when more than BackhaulShedCount |
| +// hops were refused in the last tick, holds while any are, clears on the |
| +// first tick with none. nil is no reading and leaves it alone. |
| +func TestEvaluateBackhaulShed(t *testing.T) { |
| + r := DefaultRules() |
| + if r.BackhaulShedCount != 10 { |
| + t.Fatalf("default BackhaulShedCount = %v, want 10", r.BackhaulShedCount) |
| + } |
| + st := AlertState{V: 1, Box: "box-a", Rules: map[string]RuleState{}} |
| + at := time.Date(2026, 12, 2, 12, 0, 0, 0, time.UTC) |
| + step := func(v *float64) []Event { |
| + t.Helper() |
| + at = at.Add(time.Minute) |
| + var evs []Event |
| + st, evs = Evaluate(r, st, Observation{At: at, BackhaulSheds: v}) |
| + return evs |
| + } |
| + f := func(v float64) *float64 { return &v } |
| + |
| + if evs := step(f(10)); len(evs) != 0 || st.Rules[BackhaulShedRule].Firing { |
| + t.Fatalf("10 sheds (at the line) = %+v, want quiet", evs) |
| + } |
| + evs := step(f(11)) |
| + if len(evs) != 1 || evs[0].Rule != BackhaulShedRule || !evs[0].Firing || evs[0].Value != 11 || evs[0].Box != "box-a" { |
| + t.Fatalf("11 sheds = %+v, want one fire with value 11", evs) |
| + } |
| + if evs := step(nil); len(evs) != 0 || !st.Rules[BackhaulShedRule].Firing { |
| + t.Fatalf("nil while firing = %+v, want held", evs) |
| + } |
| + if evs := step(f(1)); len(evs) != 0 || !st.Rules[BackhaulShedRule].Firing { |
| + t.Fatalf("1 shed while firing = %+v, want held: only a quiet minute clears", evs) |
| + } |
| + evs = step(f(0)) |
| + if len(evs) != 1 || evs[0].Firing || evs[0].Value != 0 { |
| + t.Fatalf("0 sheds while firing = %+v, want one clear", evs) |
| + } |
| + if rs, ok := st.Rules[BackhaulShedRule]; !ok || rs.Firing { |
| + t.Fatalf("cleared state = %+v (present %v), want a quiet entry", rs, ok) |
| + } |
| + if evs := step(f(0)); len(evs) != 0 { |
| + t.Fatalf("0 sheds while quiet = %+v, want nothing", evs) |
| + } |
| +} |
| + |
| +func TestBackhaulShedsSince(t *testing.T) { |
| + s := func(req, str, fair uint64) *BackhaulShedSample { |
| + return &BackhaulShedSample{Requests: req, Streams: str, FairShare: fair} |
| + } |
| + for _, tc := range []struct { |
| + name string |
| + prev, cur *BackhaulShedSample |
| + want *float64 |
| + }{ |
| + {"no reading", s(1, 1, 1), nil, nil}, |
| + {"first reading counts from the edge's start", nil, s(2, 3, 4), ptr(9)}, |
| + {"delta", s(2, 3, 4), s(5, 3, 10), ptr(9)}, |
| + {"none", s(2, 3, 4), s(2, 3, 4), ptr(0)}, |
| + {"a counter went back: a new edge, counted from zero", s(50, 0, 0), s(3, 1, 0), ptr(4)}, |
| + } { |
| + got := BackhaulShedsSince(tc.prev, tc.cur) |
| + if (got == nil) != (tc.want == nil) || (got != nil && *got != *tc.want) { |
| + t.Errorf("%s: got %v, want %v", tc.name, deref(got), deref(tc.want)) |
| + } |
| + } |
| +} |
| + |
| +func ptr(v float64) *float64 { return &v } |
| + |
| +func deref(p *float64) any { |
| + if p == nil { |
| + return nil |
| + } |
| + return *p |
| +} |
diff --git a/internal/metrics/sample.go b/internal/metrics/sample.go| index a2ac8f816..edf6b320f 100644 |
| --- a/internal/metrics/sample.go |
| +++ b/internal/metrics/sample.go |
| @@ -36,10 +36,14 @@ type UnitSample struct { |
| // (e.g. carlos-exec@x.example.com — no .service suffix; written by the |
| // sampler's exec-subtree scan since exec-child accounting). |
| type Sample struct { |
| - HADepartures *DepartureSample `json:"ha_departures,omitempty"` |
| - At time.Time `json:"at"` |
| - Host HostSample `json:"host"` |
| - Units map[string]UnitSample `json:"units"` |
| + HADepartures *DepartureSample `json:"ha_departures,omitempty"` |
| + // BackhaulSheds is the edge's backhaul refusal counters (#1535), nil |
| + // before the edge is ready. Omitted when nil, so older chunks read the |
| + // same. |
| + BackhaulSheds *BackhaulShedSample `json:"backhaul_sheds,omitempty"` |
| + At time.Time `json:"at"` |
| + Host HostSample `json:"host"` |
| + Units map[string]UnitSample `json:"units"` |
| } |
| // RawChunk is an hour's worth of raw samples for one box, the unit of |