console: incident step with noise rules
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/console/alertengine.go+257 −0internal/console/alertengine_test.go+445 −0
Intent
<task-notification> <task-id>a03e8134cf429db95</task-id> <tool-use-id>toolu_01XFffGG3XcUgwzdJJs8QL4f</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a03e8134cf429db95.output</output-file> <status>completed</status> <summary>Agent "Implement Task 6: senders and outbox drain" 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 - **Commit:** a4c02cd7 console: alert drain fix round 1 (bounded pass, holds, scope and health guards) - **Tests:** the alert, outbox, census and delivery tests all pass (87 s), plus 6 new tests. The `-race` run on the Task 6 tests passes, and vet and gofmt are clean. With the fixes reverted, the 5 new tests that cover them fail. - **What changed:** - **Bounded pass:** at most 50 sends and 60 s a pass. After a connector's first failed send, one UPDATE pushes its other due rows to that row's retry time, unsent and with no attempt counted. - **R-14 holds:** held rows wait 5 minutes with no attempt and no health record, via the new store accessor `HoldConnectorOutbox`. - **R-16:** all six minor items are fixed as listed. - **Concerns:** - "50 a pass" now counts sends, not rows read. Without that, the sendable row behind 60 held rows could not go in the first pass. - Minors 1 and 2 have no direct test. Each needs a send that finishes just as the drain's context ends, or a connector deleted mid-row, and I found no reliable way to set either up. - A hold overwrites `err_category` with the hold reason, so an earlier send failure is no longer shown. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-6-report.md (fix report appended)</result> <usage><subagent_tokens>236878</subagent_tokens><tool_uses>9</tool_uses><duration_ms>477047</duration_ms></usage> </task-notification>
<task-notification> <task-id>a40fc8c6dfe21d344</task-id> <tool-use-id>toolu_01ALnbDS1stoVKpZPjPfaHBr</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a40fc8c6dfe21d344.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 6 fix round 1" 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>### Finding Verdicts - **1. A pass had no time bound (Important)**: ADDRESSED. - After a connector's first failed send, `DeferConnectorOutbox` (alertstore.go:509) runs one UPDATE. It moves that connector's other unsent rows to the failed row's new `next_at`. It does not send them and does not touch `attempts`. The call is at alertnotify.go:396. The `failed` map skips that connector's rows already in hand (alertnotify.go:304, :313). - The 60 s deadline and the 50-send cap are checked before each fresh row (alertnotify.go:301). - Tests: `TestDrainDeadConnectorOneTimeoutAPass` (alertnotify_test.go:895) checks one dead request, one attempt in total, all 10 rows at T0+1m and the live row sent. `TestDrainPassDeadline` (:951) checks the deadline. - One caveat: the deadline is checked only between rows. A send already running gets its full timeout (5 s webhook, 20 s email), so a pass can last about 80 s at worst. The fix report says so. It is acceptable. - **2. R-14 held rows**: ADDRESSED. - `holdAlertRows` → `HoldConnectorOutbox` (alertnotify.go:349, :374, :429; alertstore.go:498) moves the connector's unsent rows to now+5m in one UPDATE. - It leaves `attempts` alone and does not call `SetConnectorHealth`. The unconfirmed hold leaves verify rows due. The "no seal key" and "seal" holds go through the same path. - Held rows leave the due set, and the re-read loop (alertnotify.go:321) reaches the sendable row in the same pass. - `TestDrainHeldRowsDoNotBlock` (alertnotify_test.go:969) covers 60 held plus 1 sendable, 0 attempts, no health change, nothing sent at +4m and delivery at +5m after confirmation. - **3. Cancelled ctx leaves a row due only when the send failed**: ADDRESSED. The check is `if !sent && ctx.Err() != nil` (alertnotify.go:386), and a completed send goes on to `FinishOutbox`. There is no test for it, which the report admits. The finding did not ask for one. - **4. `sql.ErrNoRows` from `AlertConnectorTarget`**: ADDRESSED. `alertTarget` passes the Scan error through unwrapped, and alertnotify.go:367 drops that row and continues. - **5. A row from another scope is dropped and logged**: ADDRESSED. The check is at alertnotify.go:358, after decode and before any token is minted or anything is sent. `TestDrainDropsOtherScopeRow` (alertnotify_test.go:1006) asserts no send, no row, and the scope in the log. - **6. `sendTestAlert` checks scope first**: ADDRESSED. The scope check is at alertnotify.go:661, before `alertOwnerRevoked`. `TestTestSendScopeBeforeOperatorCheck` (alertnotify_test.go:1052) confirms that a test from another scope leaves the revoked operator's connector in place, and one from its own scope deletes it. - **7. No `SetConnectorHealth` for unconfirmed connectors**: ADDRESSED. alertnotify.go:411 returns before the health call. `TestDrainUnconfirmedFailingNotSuspended` (alertnotify_test.go:1030) checks that after 25 h of 404s the connector is not suspended, `failing_since` is 0, and no notice was queued. - **8. A lost suspension notice is logged**: ADDRESSED at alertnotify.go:597. A failure to queue the notice was already logged by the caller. **The "50 a pass" change from rows read to sends.** The change is justified, and nothing caps the rows a pass reads except the time budget. - The change is needed for R-14. If a pass stopped after reading 50 rows, the sendable row behind 60 held rows would wait for the next pass. - A pass reads 50 rows at a time and keeps going until a read comes back short or has nothing new. There is no cap on the number of reads or rows. - The read is still bounded in practice: - every fresh row leaves the due set or ends the pass, and `seen` stops a row being handled twice - held rows go 5 minutes out, so they cannot come back within the pass - the 60 s check runs before every fresh row, held or dropped ones included - So a pass reads at most the rows due when it started plus any queued during it, and it stops at 60 s. - Each held or dropped row still costs a few statements: - Every held row left in the slice re-reads its connector, checks the operator again and repeats the hold UPDATE, which by then does nothing. - Each undecodable or other-scope row costs its own DELETE. - A backlog of many thousands of such rows could therefore use the full 60 s of SQLite work with no sends, once every 5 minutes per held connector. I rate this Minor, below. ### New Breakage in the Fix Diff - **Minor.** No hard cap on rows read per pass (alertnotify.go:289–323). Only the 60 s budget bounds it. A backstop such as at most N reads per pass, or skipping in-slice rows of a connector already held this pass (as is done for `failed`), would save the repeated connector read, operator check and hold UPDATE for each held row. - **Minor.** A failed send defers rows that a hold had pushed out, and the deferral can be long. - Hold and defer both write `next_at`. When an unconfirmed Slack connector's `verify` row fails with a long backoff, `DeferConnectorOutbox` (alertstore.go:509) pushes the held non-verify rows from +5m out to that backoff, which can be up to 12 h. - If the connector is then confirmed some other way (a test send's confirm link), those rows wait for the old verify row's retry time instead of the 5-minute recheck R-14 promises. - This is an edge case. Excluding rows whose `err_category` is a hold reason, or deferring only when the connector is confirmed, would close it. - **Minor.** `TestDrainPassDeadline` (alertnotify_test.go:951) relies on `time.Since(start) >= 1ns` holding on the first row. That is safe on Linux, but on a platform with a coarse monotonic clock it could read 0. CI only builds darwin and windows, so this is a nit. - **Minor, carried over and acknowledged.** A hold overwrites `err_category`, hiding an earlier send failure. ### Out-of-Scope Observations None. ### Verdict **Fix round:** All findings addressed, no new Critical/Important breakage.</result> <usage><subagent_tokens>79934</subagent_tokens><tool_uses>7</tool_uses><duration_ms>157278</duration_ms></usage> </task-notification>
Attributed to this commit: 17.5 g CO₂e (2,157,725 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/console/alertengine.go b/internal/console/alertengine.go| new file mode 100644 |
| index 000000000..111040cc7 |
| --- /dev/null |
| +++ b/internal/console/alertengine.go |
| @@ -0,0 +1,257 @@ |
| +package console |
| + |
| +// The incident step (fleet alerts spec §6). stepIncidents is pure: from |
| +// the open incidents, the last hour of fires and one pass's signals it |
| +// works out which incidents changed, which keys newly fired and which |
| +// messages are owed. The engine pass commits all three in one transaction |
| +// (§6.1), so a step replayed after a restart finds nothing left to do. |
| +// |
| +// An incident is one (scope, rule). Its Members are the subjects firing |
| +// now, in the order they joined. A subject leaves when it reports not |
| +// firing or gone, and the incident closes when the last one leaves; the |
| +// closed row keeps the members it had going into that step, so the clear |
| +// and the history say what cleared. A key with no signal in a pass keeps |
| +// its state, because some sources report only every 5th pass. |
| +// |
| +// A flapping incident (§6.7) does not close when its last member leaves. |
| +// It goes quiet: it keeps the members that left, and LastSeenAt records |
| +// when. LastSeenAt is zero while any member fires, which is how a quiet |
| +// incident is told apart without a column of its own. A firing signal |
| +// wakes it with just the subjects firing now; an hour quiet closes it. |
| + |
| +import ( |
| + "slices" |
| + "time" |
| +) |
| + |
| +// alertSignal is one source's state for one key in one pass. Gone means the |
| +// source vanished: a member leaves, and an incident it was the last member |
| +// of closes with alertCloseGone. |
| +type alertSignal struct { |
| + Key alertKey |
| + Level string |
| + Firing bool |
| + Value float64 |
| + At time.Time |
| + Gone bool |
| +} |
| + |
| +// alertEmit is one message owed for an incident. Incident is the incident |
| +// as committed, except that Members leaves out snoozed subjects. |
| +type alertEmit struct { |
| + Incident alertIncident |
| + Kind string |
| +} |
| + |
| +// Message kinds, as alert_outbox.kind. |
| +const ( |
| + alertKindFire = "fire" |
| + alertKindClear = "clear" |
| + alertKindUpdate = "update" |
| + alertKindReminder = "reminder" |
| +) |
| + |
| +// Close reasons. A gone close's clear says "no further reports" rather |
| +// than "resolved" (§6.8). |
| +const ( |
| + alertCloseCleared = "cleared" |
| + alertCloseGone = "box gone" |
| +) |
| + |
| +const ( |
| + // alertNotifyDelay is how long an incident gathers members before its |
| + // first message (§6.2). |
| + alertNotifyDelay = 5 * time.Minute |
| + // A member joining an incident younger than alertUpdateQuiet is |
| + // silent; after that, at most one update per alertUpdateEvery (§6.2). |
| + alertUpdateQuiet = 30 * time.Minute |
| + alertUpdateEvery = time.Hour |
| + // alertReminderEvery is the daily reminder (§6.1). |
| + alertReminderEvery = 24 * time.Hour |
| + // alertFlapFires fires of one key inside alertFlapWindow mark its |
| + // incident flapping, held open until quiet for alertFlapHold (§6.7). |
| + alertFlapFires = 3 |
| + alertFlapHold = time.Hour |
| +) |
| + |
| +// stepIncidents runs one pass of the noise rules. changed holds only the |
| +// incidents whose stored fields moved (new ones with ID 0), fires the keys |
| +// that went from not firing to firing, and emits the messages owed. An |
| +// incident opened in this step has no ID yet and is never emitted (ruling |
| +// R-10): its first message comes at NotifyAt, after it is committed. |
| +func stepIncidents(open []alertIncident, recentFires map[alertKey][]time.Time, signals []alertSignal, snoozed func(alertKey) bool, now time.Time) (changed []alertIncident, fires []alertFire, emits []alertEmit) { |
| + // One signal per key: the last one wins, except that gone sticks. Keys |
| + // are grouped by (scope, rule) in the order they first appear. |
| + type group struct{ scope, rule string } |
| + var order []group |
| + keysOf := map[group][]alertKey{} |
| + latest := map[alertKey]alertSignal{} |
| + for _, sg := range signals { |
| + g := group{sg.Key.Scope, sg.Key.Rule} |
| + prev, seen := latest[sg.Key] |
| + if !seen { |
| + if len(keysOf[g]) == 0 { |
| + order = append(order, g) |
| + } |
| + keysOf[g] = append(keysOf[g], sg.Key) |
| + } |
| + if !seen || !prev.Gone { |
| + latest[sg.Key] = sg |
| + } |
| + } |
| + // A fire flaps when it is the third for its key inside the window. |
| + flaps := func(k alertKey) bool { |
| + n := 1 |
| + for _, at := range recentFires[k] { |
| + if !at.Before(now.Add(-alertFlapWindow)) { |
| + n++ |
| + } |
| + } |
| + return n >= alertFlapFires |
| + } |
| + |
| + seen := map[group]bool{} |
| + for _, in := range open { |
| + g := group{in.Scope, in.Rule} |
| + if seen[g] { |
| + continue // one open incident per (scope, rule) |
| + } |
| + seen[g] = true |
| + out, f, e := stepIncident(in, keysOf[g], latest, flaps, snoozed, now) |
| + fires = append(fires, f...) |
| + emits = append(emits, e...) |
| + if !sameAlertIncident(in, out) { |
| + changed = append(changed, out) |
| + } |
| + } |
| + for _, g := range order { |
| + if seen[g] { |
| + continue |
| + } |
| + var in alertIncident |
| + for _, k := range keysOf[g] { |
| + sg := latest[k] |
| + if !sg.Firing || sg.Gone { |
| + continue |
| + } |
| + if in.Members == nil { |
| + in = alertIncident{Scope: g.scope, Rule: g.rule, Level: sg.Level, OpenedAt: now, NotifyAt: now.Add(alertNotifyDelay)} |
| + } |
| + in.Members = append(in.Members, k.Subject) |
| + fires = append(fires, alertFire{Key: k, At: now}) |
| + in.Flapping = in.Flapping || flaps(k) |
| + } |
| + if in.Members != nil { |
| + changed = append(changed, in) |
| + } |
| + } |
| + return changed, fires, emits |
| +} |
| + |
| +// stepIncident applies one pass's signals for its (scope, rule) to an open |
| +// incident, then works out what that incident is owed. |
| +func stepIncident(in alertIncident, keys []alertKey, latest map[alertKey]alertSignal, flaps func(alertKey) bool, |
| + snoozed func(alertKey) bool, now time.Time) (out alertIncident, fires []alertFire, emits []alertEmit) { |
| + out = in |
| + quiet := in.Flapping && !in.LastSeenAt.IsZero() |
| + var firingNow []string |
| + if !quiet { |
| + firingNow = slices.Clone(in.Members) |
| + } |
| + kept := slices.Clone(in.Members) // members not gone, for a quiet hold |
| + var joined []string |
| + anyGone := false |
| + for _, k := range keys { |
| + sg := latest[k] |
| + switch { |
| + case sg.Gone: |
| + anyGone = anyGone || slices.Contains(in.Members, k.Subject) |
| + firingNow = slices.DeleteFunc(firingNow, func(m string) bool { return m == k.Subject }) |
| + kept = slices.DeleteFunc(kept, func(m string) bool { return m == k.Subject }) |
| + case sg.Firing: |
| + if !slices.Contains(firingNow, k.Subject) { |
| + firingNow = append(firingNow, k.Subject) |
| + joined = append(joined, k.Subject) |
| + fires = append(fires, alertFire{Key: k, At: now}) |
| + out.Flapping = out.Flapping || flaps(k) |
| + } |
| + default: |
| + firingNow = slices.DeleteFunc(firingNow, func(m string) bool { return m == k.Subject }) |
| + } |
| + } |
| + |
| + if len(firingNow) == 0 && !quiet { |
| + out.LastSeenAt = now // the last member left in this pass |
| + } |
| + closing := false |
| + switch { |
| + case len(firingNow) > 0: |
| + out.Members = firingNow |
| + out.LastSeenAt = time.Time{} |
| + case out.Flapping && len(kept) > 0: |
| + out.Members = kept |
| + closing = !now.Before(out.LastSeenAt.Add(alertFlapHold)) |
| + default: |
| + closing = true |
| + } |
| + if closing { |
| + out.Members = slices.Clone(in.Members) |
| + out.ClosedAt = now |
| + out.CloseReason = alertCloseCleared |
| + if anyGone { |
| + out.CloseReason = alertCloseGone |
| + } |
| + } |
| + |
| + if in.ID == 0 { |
| + return out, fires, nil // not committed yet (R-10) |
| + } |
| + // visible leaves out snoozed subjects (§6.5): a snoozed key is still |
| + // tracked, but nothing is sent about it. |
| + visible := func(subjects []string) []string { |
| + return slices.DeleteFunc(slices.Clone(subjects), func(s string) bool { |
| + return snoozed(alertKey{in.Scope, in.Rule, s}) |
| + }) |
| + } |
| + emit := func(kind string, members []string) { |
| + e := alertEmit{Incident: out, Kind: kind} |
| + e.Incident.Members = members |
| + emits = append(emits, e) |
| + } |
| + since := func(last time.Time, every time.Duration) bool { |
| + return last.IsZero() || !now.Before(last.Add(every)) |
| + } |
| + switch { |
| + case closing: |
| + // One closed before its first message sends nothing (§6.2). |
| + if v := visible(out.Members); in.Notified && len(v) > 0 { |
| + emit(alertKindClear, v) |
| + } |
| + case !out.Notified: |
| + // Not notified past NotifyAt means every member was snoozed: the |
| + // fire goes out once one isn't. |
| + if v := visible(out.Members); !now.Before(out.NotifyAt) && len(v) > 0 { |
| + out.Notified = true |
| + emit(alertKindFire, v) |
| + } |
| + case !now.Before(out.OpenedAt.Add(alertReminderEvery)) && since(out.LastReminderAt, alertReminderEvery) && |
| + len(visible(out.Members)) > 0: |
| + // The reminder lists every member, so it stands in for an update. |
| + out.LastReminderAt = now |
| + emit(alertKindReminder, visible(out.Members)) |
| + case !out.Flapping && len(visible(joined)) > 0 && !now.Before(out.OpenedAt.Add(alertUpdateQuiet)) && |
| + since(out.LastUpdateAt, alertUpdateEvery): |
| + out.LastUpdateAt = now |
| + emit(alertKindUpdate, visible(out.Members)) |
| + } |
| + return out, fires, emits |
| +} |
| + |
| +// sameAlertIncident reports whether a and b would store the same row. |
| +func sameAlertIncident(a, b alertIncident) bool { |
| + return a.ID == b.ID && a.Scope == b.Scope && a.Rule == b.Rule && a.Level == b.Level && |
| + a.OpenedAt.Equal(b.OpenedAt) && a.NotifyAt.Equal(b.NotifyAt) && a.LastSeenAt.Equal(b.LastSeenAt) && |
| + a.ClosedAt.Equal(b.ClosedAt) && a.CloseReason == b.CloseReason && slices.Equal(a.Members, b.Members) && |
| + a.Flapping == b.Flapping && a.Notified == b.Notified && |
| + a.LastReminderAt.Equal(b.LastReminderAt) && a.LastUpdateAt.Equal(b.LastUpdateAt) |
| +} |
diff --git a/internal/console/alertengine_test.go b/internal/console/alertengine_test.go| new file mode 100644 |
| index 000000000..a594f819b |
| --- /dev/null |
| +++ b/internal/console/alertengine_test.go |
| @@ -0,0 +1,445 @@ |
| +package console |
| + |
| +import ( |
| + "slices" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The incident step's tests are scripted timelines: stepSim plays the part |
| +// of Task 8's pass, feeding each step's changed incidents back in as the |
| +// next step's open set and keeping the flap history the way |
| +// AlertStepInputs and CommitAlertStep do. |
| + |
| +type stepSim struct { |
| + t *testing.T |
| + now time.Time |
| + open []alertIncident |
| + history []alertFire |
| + nextID int64 |
| + snoozedUntil map[alertKey]time.Time |
| + emits []simEmit |
| +} |
| + |
| +type simEmit struct { |
| + at time.Time |
| + alertEmit |
| +} |
| + |
| +func newStepSim(t *testing.T) *stepSim { |
| + return &stepSim{t: t, nextID: 1, snoozedUntil: map[alertKey]time.Time{}} |
| +} |
| + |
| +func diskKey(subject string) alertKey { return alertKey{"fleet", "disk_eta", subject} } |
| + |
| +func firing(subject string) alertSignal { |
| + return alertSignal{Key: diskKey(subject), Level: "warning", Firing: true} |
| +} |
| + |
| +func quiet(subject string) alertSignal { |
| + return alertSignal{Key: diskKey(subject), Level: "warning"} |
| +} |
| + |
| +func gone(subject string) alertSignal { |
| + return alertSignal{Key: diskKey(subject), Level: "warning", Gone: true} |
| +} |
| + |
| +func (s *stepSim) snoozed(k alertKey) bool { return s.now.Before(s.snoozedUntil[k]) } |
| + |
| +// recentFires is the flap history inside the last hour, as AlertStepInputs |
| +// returns it. |
| +func (s *stepSim) recentFires(now time.Time) map[alertKey][]time.Time { |
| + out := map[alertKey][]time.Time{} |
| + for _, f := range s.history { |
| + if !f.At.Before(now.Add(-alertFlapWindow)) { |
| + out[f.Key] = append(out[f.Key], f.At) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// step runs one pass at now and commits it: new incidents get ids, changed |
| +// ones replace their old row, closed ones leave the open set. |
| +func (s *stepSim) step(now time.Time, sigs ...alertSignal) (changed []alertIncident, emits []alertEmit) { |
| + s.t.Helper() |
| + s.now = now |
| + changed, fires, emits := stepIncidents(s.open, s.recentFires(now), sigs, s.snoozed, now) |
| + for _, e := range emits { |
| + if e.Incident.ID == 0 { |
| + s.t.Fatalf("%v: %s emit for an unsaved incident (R-10)", now.Sub(alertT0), e.Kind) |
| + } |
| + s.emits = append(s.emits, simEmit{now, e}) |
| + } |
| + s.history = append(s.history, fires...) |
| + s.open = mergeChanged(s.open, changed, &s.nextID) |
| + return changed, emits |
| +} |
| + |
| +// mergeChanged is what CommitAlertStep and the next AlertStepInputs do to |
| +// the open set: insert ID 0 incidents with fresh ids, update the rest, and |
| +// drop any that closed. |
| +func mergeChanged(open, changed []alertIncident, nextID *int64) []alertIncident { |
| + out := slices.Clone(open) |
| + for _, c := range changed { |
| + if c.ID == 0 { |
| + c.ID = *nextID |
| + *nextID++ |
| + out = append(out, c) |
| + continue |
| + } |
| + i := slices.IndexFunc(out, func(o alertIncident) bool { return o.ID == c.ID }) |
| + if i < 0 { |
| + panic("changed incident not open") |
| + } |
| + out[i] = c |
| + } |
| + return slices.DeleteFunc(out, func(o alertIncident) bool { return !o.ClosedAt.IsZero() }) |
| +} |
| + |
| +// run steps once a minute from minute `from` up to, not including, minute |
| +// `to`, with the signals state gives for each minute. |
| +func (s *stepSim) run(from, to int, state func(m int) []alertSignal) { |
| + s.t.Helper() |
| + for m := from; m < to; m++ { |
| + s.step(alertT0.Add(time.Duration(m)*time.Minute), state(m)...) |
| + } |
| +} |
| + |
| +func minute(m int) time.Time { return alertT0.Add(time.Duration(m) * time.Minute) } |
| + |
| +// emitsAre checks every emit so far by minute, kind and members. |
| +func (s *stepSim) emitsAre(want ...simWant) { |
| + s.t.Helper() |
| + got := make([]simWant, len(s.emits)) |
| + for i, e := range s.emits { |
| + got[i] = simWant{int(e.at.Sub(alertT0) / time.Minute), e.Kind, e.Incident.Members} |
| + } |
| + if len(got) != len(want) { |
| + s.t.Fatalf("emits = %v, want %v", got, want) |
| + } |
| + for i := range want { |
| + if got[i].minute != want[i].minute || got[i].kind != want[i].kind || !slices.Equal(got[i].members, want[i].members) { |
| + s.t.Fatalf("emits = %v, want %v", got, want) |
| + } |
| + } |
| +} |
| + |
| +type simWant struct { |
| + minute int |
| + kind string |
| + members []string |
| +} |
| + |
| +func TestStepGroupsStaggeredFiveBoxes(t *testing.T) { |
| + sim := newStepSim(t) |
| + boxes := []string{"b1", "b2", "b3", "b4", "b5"} |
| + sim.run(0, 30, func(m int) []alertSignal { |
| + var sigs []alertSignal |
| + for i, b := range boxes { |
| + if m >= i { |
| + sigs = append(sigs, firing(b)) |
| + } else { |
| + sigs = append(sigs, quiet(b)) |
| + } |
| + } |
| + return sigs |
| + }) |
| + sim.emitsAre(simWant{5, "fire", boxes}) |
| + if len(sim.open) != 1 || !sim.open[0].Notified || !sim.open[0].NotifyAt.Equal(minute(5)) { |
| + t.Fatalf("open = %+v, want one notified incident with NotifyAt at minute 5", sim.open) |
| + } |
| + if len(sim.history) != 5 { |
| + t.Fatalf("fires = %v, want one per box", sim.history) |
| + } |
| +} |
| + |
| +func TestStepFireClearInsideWindowSilent(t *testing.T) { |
| + // Clearing at minute 5 is the step the fire would have gone out in: it |
| + // closes first, so nothing is sent. |
| + for _, clearAt := range []int{1, 3, 5} { |
| + sim := newStepSim(t) |
| + sim.run(0, 30, func(m int) []alertSignal { |
| + if m < clearAt { |
| + return []alertSignal{firing("b1")} |
| + } |
| + return []alertSignal{quiet("b1")} |
| + }) |
| + sim.emitsAre() |
| + if len(sim.open) != 0 { |
| + t.Fatalf("clear at %d: open = %+v, want none", clearAt, sim.open) |
| + } |
| + } |
| +} |
| + |
| +func TestStepOneFireOneClear(t *testing.T) { |
| + // Two boxes that clear at different times: one fire, one clear, and |
| + // every step in between changes nothing. |
| + sim := newStepSim(t) |
| + var closed alertIncident |
| + for m := 0; m < 180; m++ { |
| + sigs := []alertSignal{firing("b1"), firing("b2")} |
| + if m >= 30 { |
| + sigs[0] = quiet("b1") |
| + } |
| + if m >= 60 { |
| + sigs[1] = quiet("b2") |
| + } |
| + changed, _ := sim.step(minute(m), sigs...) |
| + idle := m != 0 && m != 5 && m != 30 && m != 60 |
| + if idle && len(changed) != 0 { |
| + t.Fatalf("minute %d: changed = %+v, want nothing", m, changed) |
| + } |
| + if m == 60 { |
| + if len(changed) != 1 { |
| + t.Fatalf("minute 60: changed = %+v, want the close", changed) |
| + } |
| + closed = changed[0] |
| + } |
| + } |
| + sim.emitsAre(simWant{5, "fire", []string{"b1", "b2"}}, simWant{60, "clear", []string{"b2"}}) |
| + if !closed.ClosedAt.Equal(minute(60)) || closed.CloseReason != alertCloseCleared { |
| + t.Fatalf("closed = %+v, want closed at minute 60 as %q", closed, alertCloseCleared) |
| + } |
| +} |
| + |
| +func TestStepLateMemberUpdateHourly(t *testing.T) { |
| + // b2 joins inside the first 30 minutes: silent. b3 at 35 is the first |
| + // update; b4 at 50 is inside that hour: silent. b5 at 96 is the next. |
| + joins := map[string]int{"b1": 0, "b2": 10, "b3": 35, "b4": 50, "b5": 96, "b6": 100} |
| + order := []string{"b1", "b2", "b3", "b4", "b5", "b6"} |
| + sim := newStepSim(t) |
| + sim.run(0, 120, func(m int) []alertSignal { |
| + var sigs []alertSignal |
| + for _, b := range order { |
| + if m >= joins[b] { |
| + sigs = append(sigs, firing(b)) |
| + } |
| + } |
| + return sigs |
| + }) |
| + sim.emitsAre( |
| + simWant{5, "fire", []string{"b1"}}, |
| + simWant{35, "update", []string{"b1", "b2", "b3"}}, |
| + simWant{96, "update", []string{"b1", "b2", "b3", "b4", "b5"}}, |
| + ) |
| + if got := sim.open[0].Members; !slices.Equal(got, order) { |
| + t.Fatalf("members = %v, want %v", got, order) |
| + } |
| +} |
| + |
| +func TestStepFlappingAcrossIncidents(t *testing.T) { |
| + // b1 fires at minutes 0, 2 and 4, each fire cleared a minute later, so |
| + // the first two incidents close silently inside their 5 minutes. The |
| + // third fire is the third in an hour: that incident is flapping and is |
| + // held open through b1's clears and a later fire, and through b2 |
| + // joining and leaving. It closes an hour after the last firing signal. |
| + firesAt := map[int]bool{0: true, 2: true, 4: true, 10: true} |
| + sim := newStepSim(t) |
| + for m := 0; m < 120; m++ { |
| + b1, b2 := quiet("b1"), quiet("b2") |
| + if firesAt[m] { |
| + b1 = firing("b1") |
| + } |
| + if m == 20 { |
| + b2 = firing("b2") |
| + } |
| + changed, _ := sim.step(minute(m), b1, b2) |
| + if m == 4 && (len(changed) != 1 || changed[0].ID != 0 || !changed[0].Flapping) { |
| + t.Fatalf("minute 4: changed = %+v, want a new incident marked flapping", changed) |
| + } |
| + if m < 4 && slices.ContainsFunc(changed, func(in alertIncident) bool { return in.Flapping }) { |
| + t.Fatalf("minute %d: flapping before the third fire: %+v", m, changed) |
| + } |
| + } |
| + sim.emitsAre(simWant{9, "fire", []string{"b1"}}, simWant{81, "clear", []string{"b2"}}) |
| + for _, e := range sim.emits { |
| + if !e.Incident.Flapping || e.Incident.ID != 3 { |
| + t.Fatalf("emit %+v, want incident 3 marked flapping", e) |
| + } |
| + } |
| + if r := sim.emits[1].Incident.CloseReason; r != alertCloseCleared { |
| + t.Fatalf("close reason = %q, want %q", r, alertCloseCleared) |
| + } |
| + if len(sim.history) != 5 { |
| + t.Fatalf("fires = %v, want b1 four times and b2 once", sim.history) |
| + } |
| +} |
| + |
| +func TestStepFlappingHeldOneHour(t *testing.T) { |
| + // The hold ends exactly an hour after the incident went quiet, not |
| + // before. |
| + sim := newStepSim(t) |
| + sim.run(0, 65, func(m int) []alertSignal { |
| + if m == 0 || m == 2 || m == 4 { |
| + return []alertSignal{firing("b1")} |
| + } |
| + return []alertSignal{quiet("b1")} |
| + }) |
| + if len(sim.open) != 1 || !sim.open[0].Flapping { |
| + t.Fatalf("open at minute 64 = %+v, want the flapping incident", sim.open) |
| + } |
| + if !sim.open[0].LastSeenAt.Equal(minute(5)) { |
| + t.Fatalf("LastSeenAt = %v, want minute 5, when it went quiet", sim.open[0].LastSeenAt.Sub(alertT0)) |
| + } |
| + changed, emits := sim.step(minute(65), quiet("b1")) |
| + if len(changed) != 1 || !changed[0].ClosedAt.Equal(minute(65)) || len(emits) != 1 || emits[0].Kind != "clear" { |
| + t.Fatalf("minute 65: changed %+v, emits %+v, want the close and its clear", changed, emits) |
| + } |
| +} |
| + |
| +func TestStepDailyReminder(t *testing.T) { |
| + sim := newStepSim(t) |
| + const day = 24 * 60 |
| + sim.run(0, 2*day+60, func(m int) []alertSignal { |
| + if m < 2*day+30 { |
| + return []alertSignal{firing("b1")} |
| + } |
| + return []alertSignal{quiet("b1")} |
| + }) |
| + one := []string{"b1"} |
| + sim.emitsAre( |
| + simWant{5, "fire", one}, |
| + simWant{day, "reminder", one}, |
| + simWant{2 * day, "reminder", one}, |
| + simWant{2*day + 30, "clear", one}, |
| + ) |
| +} |
| + |
| +func TestStepGoneCloses(t *testing.T) { |
| + t.Run("last member gone", func(t *testing.T) { |
| + sim := newStepSim(t) |
| + sim.run(0, 30, func(m int) []alertSignal { |
| + switch { |
| + case m < 10: |
| + return []alertSignal{firing("b1"), firing("b2")} |
| + case m < 20: |
| + return []alertSignal{firing("b1"), gone("b2")} |
| + default: |
| + return []alertSignal{gone("b1"), gone("b2")} |
| + } |
| + }) |
| + sim.emitsAre(simWant{5, "fire", []string{"b1", "b2"}}, simWant{20, "clear", []string{"b1"}}) |
| + if r := sim.emits[1].Incident.CloseReason; r != alertCloseGone { |
| + t.Fatalf("close reason = %q, want %q", r, alertCloseGone) |
| + } |
| + if len(sim.open) != 0 { |
| + t.Fatalf("open = %+v", sim.open) |
| + } |
| + }) |
| + t.Run("gone before notify is silent", func(t *testing.T) { |
| + sim := newStepSim(t) |
| + sim.run(0, 30, func(m int) []alertSignal { |
| + if m < 2 { |
| + return []alertSignal{firing("b1")} |
| + } |
| + return []alertSignal{gone("b1")} |
| + }) |
| + sim.emitsAre() |
| + if len(sim.open) != 0 { |
| + t.Fatalf("open = %+v", sim.open) |
| + } |
| + }) |
| + t.Run("gone ends a flapping hold", func(t *testing.T) { |
| + sim := newStepSim(t) |
| + sim.run(0, 15, func(m int) []alertSignal { |
| + switch { |
| + case m == 0 || m == 2 || m == 4: |
| + return []alertSignal{firing("b1")} |
| + case m < 12: |
| + return []alertSignal{quiet("b1")} |
| + default: |
| + return []alertSignal{gone("b1")} |
| + } |
| + }) |
| + sim.emitsAre(simWant{9, "fire", []string{"b1"}}, simWant{12, "clear", []string{"b1"}}) |
| + if r := sim.emits[1].Incident.CloseReason; r != alertCloseGone { |
| + t.Fatalf("close reason = %q, want %q", r, alertCloseGone) |
| + } |
| + }) |
| +} |
| + |
| +func TestStepSnoozeSuppresses(t *testing.T) { |
| + t.Run("snoozed fire waits, snoozed clear is dropped", func(t *testing.T) { |
| + sim := newStepSim(t) |
| + sim.snoozedUntil[diskKey("b1")] = minute(30) |
| + sim.run(0, 30, func(int) []alertSignal { return []alertSignal{firing("b1")} }) |
| + sim.emitsAre() |
| + if len(sim.open) != 1 || sim.open[0].Notified { |
| + t.Fatalf("open = %+v, want one tracked, unnotified incident", sim.open) |
| + } |
| + sim.run(30, 40, func(int) []alertSignal { return []alertSignal{firing("b1")} }) |
| + sim.emitsAre(simWant{30, "fire", []string{"b1"}}) |
| + sim.snoozedUntil[diskKey("b1")] = minute(24 * 60) |
| + sim.run(40, 60, func(m int) []alertSignal { |
| + if m < 50 { |
| + return []alertSignal{firing("b1")} |
| + } |
| + return []alertSignal{quiet("b1")} |
| + }) |
| + sim.emitsAre(simWant{30, "fire", []string{"b1"}}) |
| + if len(sim.open) != 0 { |
| + t.Fatalf("open = %+v, want the incident closed", sim.open) |
| + } |
| + }) |
| + t.Run("a snoozed member is left out", func(t *testing.T) { |
| + sim := newStepSim(t) |
| + sim.snoozedUntil[diskKey("b1")] = minute(24 * 60) |
| + sim.run(0, 60, func(m int) []alertSignal { |
| + if m < 40 { |
| + return []alertSignal{firing("b1")} |
| + } |
| + return []alertSignal{firing("b1"), firing("b2")} |
| + }) |
| + // b1 alone is never sent; b2 joining makes the first message. |
| + sim.emitsAre(simWant{40, "fire", []string{"b2"}}) |
| + if got := sim.open[0].Members; !slices.Equal(got, []string{"b1", "b2"}) { |
| + t.Fatalf("members = %v, want both still tracked", got) |
| + } |
| + }) |
| +} |
| + |
| +func TestStepRestartNoDuplicate(t *testing.T) { |
| + // A console that commits a step and restarts runs the step again at the |
| + // same minute with the same signals. Every replay finds nothing to do. |
| + sim := newStepSim(t) |
| + state := func(m int) []alertSignal { |
| + sigs := []alertSignal{firing("b1"), quiet("b2"), quiet("b3")} |
| + if m >= 2 { |
| + sigs[1] = firing("b2") |
| + } |
| + if m >= 40 { |
| + sigs[2] = firing("b3") |
| + } |
| + if m >= 70 { |
| + sigs[1] = gone("b2") |
| + } |
| + if m >= 1500 { |
| + sigs[0], sigs[2] = quiet("b1"), quiet("b3") |
| + } |
| + return sigs |
| + } |
| + for m := 0; m < 1600; m++ { |
| + sigs := state(m) |
| + sim.step(minute(m), sigs...) |
| + changed, fires, emits := stepIncidents(sim.open, sim.recentFires(minute(m)), sigs, sim.snoozed, minute(m)) |
| + if len(changed) != 0 || len(fires) != 0 || len(emits) != 0 { |
| + t.Fatalf("minute %d replay: changed %+v, fires %+v, emits %+v", m, changed, fires, emits) |
| + } |
| + } |
| + sim.emitsAre( |
| + simWant{5, "fire", []string{"b1", "b2"}}, |
| + simWant{40, "update", []string{"b1", "b2", "b3"}}, |
| + simWant{24 * 60, "reminder", []string{"b1", "b3"}}, |
| + simWant{1500, "clear", []string{"b1", "b3"}}, |
| + ) |
| +} |
| + |
| +func TestStepDoesNotModifyOpen(t *testing.T) { |
| + in := alertIncident{ID: 7, Scope: "fleet", Rule: "disk_eta", Level: "warning", |
| + OpenedAt: minute(0), NotifyAt: minute(5), Members: []string{"b1", "b2"}} |
| + open := []alertIncident{in} |
| + stepIncidents(open, nil, []alertSignal{quiet("b1"), firing("b3")}, func(alertKey) bool { return false }, minute(6)) |
| + if !slices.Equal(open[0].Members, []string{"b1", "b2"}) || open[0].Notified { |
| + t.Fatalf("open changed under the step: %+v", open[0]) |
| + } |
| +} |