carlos / platform Public

console: incident step fix round 1 (message clocks, clears past snoozes, flap hold past gone, invariant simulation)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev ab44bb9969e0bebc0869f8d7e648ea526d8ec2e7 parent 8282ff5
3 files changed, +389 −85
  • internal/console/alertengine.go +88 −51
  • internal/console/alertengine_test.go +275 −33
  • internal/console/alertstore.go +26 −1

Intent

Human

<task-notification> <task-id>aece62afa08a0b8b3</task-id> <tool-use-id>toolu_01DFgmDeDjYy9CustNzNwF2C</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/aece62afa08a0b8b3.output</output-file> <status>completed</status> <summary>Agent "Implement Task 7: incident step" 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. The rules all work; three design choices need a reviewer to sign off. - **Commit:** 8282ff57 console: incident step with noise rules (base a4c02cd7) - **Tests:** all 11 step tests pass (the 9 named in the brief, plus the 1-hour flap hold and a check that `open` is never mutated). Each rule was checked by deliberately breaking it, and a test failed every time. `go vet` and `gofmt` are clean. - **Concerns:** 1. **`LastSeenAt` carries the flapping hold.** It is zero while any member fires and records when a flapping incident went quiet. No fields were added. The alternative is a new `quiet_since` column in Task 4's store. Refreshing it on every firing signal would have broken "an idle step returns an empty `changed`". 2. **`Members` means "firing now".** The closed row keeps the members it had going into the closing step. So a flapping incident's clear can name different boxes than its fire did (fire [b1], clear [b2] in the flapping test). 3. **Snooze and Gone choices:** - Emits leave snoozed subjects out of `Members`, so Task 8 must take message members from the emit, not the store. - A fire held back by a snooze goes out once the snooze ends. - A Gone close stores `CloseReason "box gone"`, and Task 8 shows that as "no further reports". - Task 8's cutover should open incidents with `LastSeenAt` zero. 4. **Flapping:** the final clear is emitted if the incident was notified. Members joining during the flap are added silently, and the daily reminder still applies. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-7-report.md</result> <usage><subagent_tokens>128883</subagent_tokens><tool_uses>30</tool_uses><duration_ms>832199</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>ad188111d1169a8e1</task-id> <tool-use-id>toolu_01Y9uf4bC7wXWBL48YXB336D</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/ad188111d1169a8e1.output</output-file> <status>completed</status> <summary>Agent "Review Task 7 (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 - ❌ Issues found. Three timelines break §6 noise rules. I ran each one against a scratch copy of `alertengine.go` (details under Issues): - a fire followed by a reminder one minute later - a clear that is lost because of a snooze - a flapping hold that a different member's Gone cuts short, so the subject fires again inside its hold - ✅ Each requirement in the brief has matching code: - grouping: `alertengine.go:127-147` - fire at `NotifyAt` and not after a close: `:230-236` - clear only when `Notified`: `:225-229` - flapping on the 3rd fire within the hour, counting `recentFires` plus this fire: `:103-111`. This follows spec §6.7 ("3 times in an hour"), not the brief's literal "3 entries in recentFires", which would mean a 4th fire. - daily reminder: `:237-241` - hourly update after 30 min: `:242-245` - Gone closes: `:167-170`, `:201-203` - snooze: `:211-215` - R-10, no emit for `ID == 0`: `:206-208` - all 9 named tests are present, plus `TestStepFlappingHeldOneHour` and `TestStepDoesNotModifyOpen` - ⚠️ Cannot verify from this diff (these need Task 8): - The brief says "a gone clear carries the reason 'no further reports'". The step sets `CloseReason = "box gone"` (`:62`, `:201-203`). Task 8 and Task 9 must turn that into the "no further reports" text. - The step leaves a key with no signal unchanged (`:13-14`). So a member whose source stops reporting without a Gone stays open forever, with daily reminders. Examples: a service dropped from `fleet.json`, an alias removed, a rule dropped from a box's alert object. Task 8 must send a quiet or Gone signal for every member of an open incident that is no longer reported. ### Strengths - The step is pure and deterministic: - the maps are only looked up by key - output order comes from the `open` slice and the `order` slice (`:89-101`) - Members keep their join order - `open` is never changed, because `Members` is always cloned (`:159-161`, `:189-198`, `:212`) - `sameAlertIncident` (`:251-257`) keeps `changed` small. Idle steps, both steady-firing and quiet-flapping, return nothing. `TestStepOneFireOneClear` (test `:174-203`) and the 1600-minute replay in `TestStepRestartNoDuplicate` (test `:401-435`) check this. - The tests are well designed. `stepSim` and `mergeChanged` behave like the store, it fails on any emit with `ID == 0`, and every mutation in the report's table is caught. - Clock edges hold: - a clear at exactly `NotifyAt` is silent (test `:156-172`) - the flap hold closes at exactly +1 h (test `:268-288`) - the reminder goes out at exactly 24 h (test `:290-306`) - a join at exactly 30 min sends an update (my probe) - a fire exactly 1 h old still counts toward flapping (my probe) ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) 1. **A fire delayed by a snooze is followed by a reminder one minute later** (`alertengine.go:230-241`). - Probe: b1 fires from minute 0 and is snoozed until 1450, the 1-day snooze option. Result: `fire` at 1450, then `reminder` at 1451. - Cause: the reminder clock starts at `OpenedAt`, and `LastReminderAt` is still zero when a late fire goes out. The 1-week snooze does the same. - The same cause sends an `update` one minute after a late fire when a member joins. - This breaks "one message on fire" and the daily cap. - Fix: when a fire goes out, set `LastReminderAt = now` if `now ≥ OpenedAt + 24h`, or start the reminder clock from the fire. Set `LastUpdateAt = now` on the fire too. Add a snooze-over-24h timeline test. 2. **A snoozed last member drops the clear for members who were announced** (`:225-229`, the visibility check over `out.Members` at `:227`). - Probe: the fire at minute 5 lists [b1 b2]. At minute 10 the user snoozes b1 with the link in that message. b2 clears at 30, b1 at 60. - Result: the incident closes with no clear at all. The recipient heard that b2 was failing and never hears that it recovered. - `in.Members` holds only the members firing just before the close, so the check never sees b2. - This is the "lost clear" named in risk 1. `TestStepSnoozeSuppresses` (test `:361-383`) only covers the single-member case, where dropping the clear is defensible. - Fix: once `Notified`, always emit the clear. Snooze then only filters the listed members, or the rule could be: drop the clear only when every subject ever announced is snoozed. A row that tracks no announced set can't do the second, so the first is the practical fix. 3. **A Gone on one member ends a flapping hold early, so the flapping subject fires again inside its hour** (`:156-161`, `:167-170`, `:194-195`). - Probe: b1 fires at minutes 0 and 2, then 4-14. b2 fires 4-15. b1 clears at 15, b2 is Gone at 16, b1 fires again at 40. - Result: incident 3 sends `fire` [b1 b2] at 9, then `clear` "box gone" at 16. Incident 4 opens flapping and sends `fire` [b1] at 45. - Spec §6.7 says one open incident, held until it has been clear for an hour. Here b1 was clear for only 25 minutes, and recipients got clear, fire, clear. - Cause: once a flapping incident has a firing member, `Members` drops the quiet members (`:189-190`). On a wake, `firingNow` also starts empty (`:157-160`). So when the last firing member goes Gone, `kept` is empty and the hold is skipped. - Fix: when a flapping incident's last firing member leaves by Gone, it should still enter the quiet hold if any other member left within the hour. Add a multi-member Gone-during-flap test. The existing "gone ends a flapping hold" test only has one member. 4. **R-17's reuse of `LastSeenAt` and "Members means firing now" is undocumented where Task 8 will look, and is partly untrue** (`:16-20`, `:156`, `:183-191`; struct at `alertstore.go:202-210`). - The field name says "last seen", but it is zero while anything fires. On a quiet flapping incident it is the time it went quiet, and on a closed row it is when the last member stopped. - "Quiet" can only be detected with `Flapping &amp;&amp; !LastSeenAt.IsZero()`, which lives in an expression inside `stepIncident`. - `Members` is not "firing now" in two cases: during the quiet hold (`kept`, `:191-192`) and on closed rows (`:198`). - Plan Task 8 step 6 feeds `s.alertsNow` from open box-rule incidents, and the dashboard reads that as currently firing (`opdashboard.go:419`). Read naively, it would show quiet boxes as alerting for up to an hour. - The reuse doesn't break the store. A zero time round-trips through `alertUnix`/`alertTime` (`alertstore.go:244-256`), and only the step ever sets `Flapping`, so the invariant holds today. - It will collide with §6.8 one-off events in a later plan, which need a last-report time that moves while the incident is open. - Fix for Plan 1, no new column needed: document the meaning on the `alertIncident` fields, and add helpers such as `quiet()` and `firingMembers()` that Task 8 must use for `alertsNow`. Record in progress notes that §6.8 will need its own column. #### Minor (Nice to Have) 1. **A reminder doesn't reset the update clock** (`:237-245`). A probe with joins at 1440 and 1441 sent a reminder at 1440 and an update at 1441. Set `LastUpdateAt` when a reminder goes out. 2. **An `update` emit carries the full member list, with no way to tell who joined** (`alertEmit`, `:41-44`; `:245`). Spec §6.2 calls these "now also" messages, so Task 8 can't name the newcomers. This is limited by the plan's interface. Either add the joined subjects to the emit or tell Task 9 the copy must list everyone. 3. **A second open incident for the same (scope, rule) is skipped forever** (`:116-118`). It would be stuck open and never closed. The store index `alert_incidents_open` is not `UNIQUE` (`alertstore.go:82`). The step never creates such duplicates, but closing the extra row, or making the index unique, would remove the risk. 4. **The flap-window boundary depends on sub-second `now`.** The store truncates `fired_at` to whole seconds (`alertstore.go:244-249`). With a non-whole-second `now`, a fire exactly one hour old fails `!at.Before(now-1h)` at `:106`, while the store's `&gt;= since` query (`alertstore.go:306`) still returns it. This is a one-second edge with low impact. ### Assessment **Task quality:** Needs fixes **Reasoning:** The step is pure, deterministic and minimal, and the tests are strong. But three timelines I ran break §6: a late fire followed by a reminder (Important 1), a lost clear under a snooze (Important 2), and a flap hold that a different member's Gone ends early (Important 3). The `LastSeenAt`/`Members` meaning needs documenting and helpers before Task 8 builds on it (Important 4). All probes ran on a scratch copy of `alertengine.go` under `$TMPDIR`. I deleted it afterwards and left the worktree untouched.</result> <usage><subagent_tokens>99092</subagent_tokens><tool_uses>15</tool_uses><duration_ms>278682</duration_ms></usage> </task-notification>

Attributed to this commit: 32.2 g CO₂e (3,999,600 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
index 111040cc7..6378ae204 100644
--- a/internal/console/alertengine.go
+++ b/internal/console/alertengine.go
@@ -15,9 +15,11 @@ package console
//
// 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.
+// when (alertIncident.quiet). A firing signal wakes it with just the
+// subjects firing now; an hour quiet closes it.
+//
+// Every message resets the clocks after it: a reminder is due 24 hours
+// after the last message of any kind, and an update an hour after.
import (
"slices"
@@ -37,10 +39,12 @@ type alertSignal struct {
}
// alertEmit is one message owed for an incident. Incident is the incident
-// as committed, except that Members leaves out snoozed subjects.
+// as committed, except that Members leaves out snoozed subjects. Joined,
+// on an update only, is the subjects whose joining sent it.
type alertEmit struct {
Incident alertIncident
Kind string
+ Joined []string
}
// Message kinds, as alert_outbox.kind.
@@ -53,9 +57,12 @@ const (
// Close reasons. A gone close's clear says "no further reports" rather
// than "resolved" (§6.8).
+// A duplicate is a second open incident for one (scope, rule), which the
+// step never makes; it is closed silently.
const (
- alertCloseCleared = "cleared"
- alertCloseGone = "box gone"
+ alertCloseCleared = "cleared"
+ alertCloseGone = "box gone"
+ alertCloseDuplicate = "duplicate"
)
const (
@@ -80,15 +87,14 @@ const (
// 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) {
+ st := incidentStep{latest: map[alertKey]alertSignal{}, recentFires: recentFires, snoozed: snoozed, now: now}
// 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{}
+ var order []alertGroup
+ keysOf := map[alertGroup][]alertKey{}
for _, sg := range signals {
- g := group{sg.Key.Scope, sg.Key.Rule}
- prev, seen := latest[sg.Key]
+ g := alertGroup{sg.Key.Scope, sg.Key.Rule}
+ prev, seen := st.latest[sg.Key]
if !seen {
if len(keysOf[g]) == 0 {
order = append(order, g)
@@ -96,28 +102,22 @@ func stepIncidents(open []alertIncident, recentFires map[alertKey][]time.Time, s
keysOf[g] = append(keysOf[g], sg.Key)
}
if !seen || !prev.Gone {
- latest[sg.Key] = sg
+ st.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{}
+ seen := map[alertGroup]bool{}
for _, in := range open {
- g := group{in.Scope, in.Rule}
+ g := alertGroup{in.Scope, in.Rule}
if seen[g] {
- continue // one open incident per (scope, rule)
+ // One open incident per (scope, rule): the first one stepped
+ // takes the signals, and the extra one is closed.
+ in.ClosedAt, in.CloseReason = now, alertCloseDuplicate
+ changed = append(changed, in)
+ continue
}
seen[g] = true
- out, f, e := stepIncident(in, keysOf[g], latest, flaps, snoozed, now)
+ out, f, e := st.advance(in, keysOf[g])
fires = append(fires, f...)
emits = append(emits, e...)
if !sameAlertIncident(in, out) {
@@ -130,7 +130,7 @@ func stepIncidents(open []alertIncident, recentFires map[alertKey][]time.Time, s
}
var in alertIncident
for _, k := range keysOf[g] {
- sg := latest[k]
+ sg := st.latest[k]
if !sg.Firing || sg.Gone {
continue
}
@@ -139,7 +139,7 @@ func stepIncidents(open []alertIncident, recentFires map[alertKey][]time.Time, s
}
in.Members = append(in.Members, k.Subject)
fires = append(fires, alertFire{Key: k, At: now})
- in.Flapping = in.Flapping || flaps(k)
+ in.Flapping = in.Flapping || st.flaps(k)
}
if in.Members != nil {
changed = append(changed, in)
@@ -148,23 +148,47 @@ func stepIncidents(open []alertIncident, recentFires map[alertKey][]time.Time, s
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)
+type alertGroup struct{ scope, rule string }
+
+// incidentStep is one pass's inputs, shared by every incident it steps.
+type incidentStep struct {
+ latest map[alertKey]alertSignal
+ recentFires map[alertKey][]time.Time
+ snoozed func(alertKey) bool
+ now time.Time
+}
+
+// recent counts k's fires inside the flap window before this pass.
+func (st incidentStep) recent(k alertKey) int {
+ n := 0
+ for _, at := range st.recentFires[k] {
+ if !at.Before(st.now.Add(-alertFlapWindow)) {
+ n++
+ }
}
+ return n
+}
+
+// flaps reports whether a fire of k in this pass is its third inside the
+// window.
+func (st incidentStep) flaps(k alertKey) bool { return st.recent(k)+1 >= alertFlapFires }
+
+// advance applies the pass's signals for in's (scope, rule) to in, then
+// works out what it is owed.
+func (st incidentStep) advance(in alertIncident, keys []alertKey) (out alertIncident, fires []alertFire, emits []alertEmit) {
+ now := st.now
+ out = in
+ quiet := in.quiet()
+ firingNow := in.firingMembers()
kept := slices.Clone(in.Members) // members not gone, for a quiet hold
var joined []string
anyGone := false
+ goneNow := map[string]bool{}
for _, k := range keys {
- sg := latest[k]
+ sg := st.latest[k]
switch {
case sg.Gone:
+ goneNow[k.Subject] = true
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 })
@@ -173,12 +197,23 @@ func stepIncident(in alertIncident, keys []alertKey, latest map[alertKey]alertSi
firingNow = append(firingNow, k.Subject)
joined = append(joined, k.Subject)
fires = append(fires, alertFire{Key: k, At: now})
- out.Flapping = out.Flapping || flaps(k)
+ out.Flapping = out.Flapping || st.flaps(k)
}
default:
firingNow = slices.DeleteFunc(firingNow, func(m string) bool { return m == k.Subject })
}
}
+ if out.Flapping && len(firingNow) == 0 && len(kept) == 0 {
+ // The last firing member left by going gone, but one that stopped
+ // firing earlier may still be flapping: anything that fired inside
+ // the window keeps the hold (§6.7).
+ for k := range st.recentFires {
+ if k.Scope == in.Scope && k.Rule == in.Rule && !goneNow[k.Subject] && st.recent(k) > 0 {
+ kept = append(kept, k.Subject)
+ }
+ }
+ slices.Sort(kept)
+ }
if len(firingNow) == 0 && !quiet {
out.LastSeenAt = now // the last member left in this pass
@@ -210,11 +245,11 @@ func stepIncident(in alertIncident, keys []alertKey, latest map[alertKey]alertSi
// 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})
+ return st.snoozed(alertKey{in.Scope, in.Rule, s})
})
}
- emit := func(kind string, members []string) {
- e := alertEmit{Incident: out, Kind: kind}
+ emit := func(kind string, members, joined []string) {
+ e := alertEmit{Incident: out, Kind: kind, Joined: joined}
e.Incident.Members = members
emits = append(emits, e)
}
@@ -223,26 +258,28 @@ func stepIncident(in alertIncident, keys []alertKey, latest map[alertKey]alertSi
}
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)
+ // One closed before its first message sends nothing (§6.2). Once
+ // told, the clear always goes: a snooze only drops names from it.
+ if in.Notified {
+ emit(alertKindClear, visible(out.Members), nil)
}
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)
+ out.LastReminderAt, out.LastUpdateAt = now, now
+ emit(alertKindFire, v, nil)
}
case !now.Before(out.OpenedAt.Add(alertReminderEvery)) && since(out.LastReminderAt, alertReminderEvery) &&
- len(visible(out.Members)) > 0:
+ since(out.LastUpdateAt, 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))
+ out.LastReminderAt, out.LastUpdateAt = now, now
+ emit(alertKindReminder, visible(out.Members), nil)
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))
+ emit(alertKindUpdate, visible(out.Members), visible(joined))
}
return out, fires, emits
}
diff --git a/internal/console/alertengine_test.go b/internal/console/alertengine_test.go
index a594f819b..6a0497ada 100644
--- a/internal/console/alertengine_test.go
+++ b/internal/console/alertengine_test.go
@@ -1,6 +1,8 @@
package console
import (
+ "fmt"
+ "math/rand/v2"
"slices"
"testing"
"time"
@@ -15,7 +17,8 @@ type stepSim struct {
t *testing.T
now time.Time
open []alertIncident
- history []alertFire
+ history []alertFire // the last hour, as AlertStepInputs keeps it
+ fireCount int
nextID int64
snoozedUntil map[alertKey]time.Time
emits []simEmit
@@ -70,7 +73,10 @@ func (s *stepSim) step(now time.Time, sigs ...alertSignal) (changed []alertIncid
}
s.emits = append(s.emits, simEmit{now, e})
}
- s.history = append(s.history, fires...)
+ s.fireCount += len(fires)
+ s.history = slices.DeleteFunc(append(s.history, fires...), func(f alertFire) bool {
+ return f.At.Before(now.Add(-alertFlapWindow))
+ })
s.open = mergeChanged(s.open, changed, &s.nextID)
return changed, emits
}
@@ -148,8 +154,8 @@ func TestStepGroupsStaggeredFiveBoxes(t *testing.T) {
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)
+ if sim.fireCount != 5 {
+ t.Fatalf("fires = %d, want one per box", sim.fireCount)
}
}
@@ -203,12 +209,14 @@ func TestStepOneFireOneClear(t *testing.T) {
}
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}
+ // The fire at 5 starts the update clock. b2 joins inside the first 30
+ // minutes and b3 inside the hour after the fire: both silent. b4 at 70
+ // is the first update; b5 at 100 is inside that hour: silent. b6 at 131
+ // is the next.
+ joins := map[string]int{"b1": 0, "b2": 10, "b3": 40, "b4": 70, "b5": 100, "b6": 131}
order := []string{"b1", "b2", "b3", "b4", "b5", "b6"}
sim := newStepSim(t)
- sim.run(0, 120, func(m int) []alertSignal {
+ sim.run(0, 150, func(m int) []alertSignal {
var sigs []alertSignal
for _, b := range order {
if m >= joins[b] {
@@ -219,12 +227,32 @@ func TestStepLateMemberUpdateHourly(t *testing.T) {
})
sim.emitsAre(
simWant{5, "fire", []string{"b1"}},
- simWant{35, "update", []string{"b1", "b2", "b3"}},
- simWant{96, "update", []string{"b1", "b2", "b3", "b4", "b5"}},
+ simWant{70, "update", order[:4]},
+ simWant{131, "update", order},
)
- if got := sim.open[0].Members; !slices.Equal(got, order) {
- t.Fatalf("members = %v, want %v", got, order)
+ if j := sim.emits[1].Joined; !slices.Equal(j, []string{"b4"}) {
+ t.Fatalf("first update Joined = %v, want [b4]", j)
+ }
+ if j := sim.emits[2].Joined; !slices.Equal(j, []string{"b6"}) {
+ t.Fatalf("second update Joined = %v, want [b6]", j)
}
+ if sim.emits[0].Joined != nil {
+ t.Fatalf("fire Joined = %v, want none", sim.emits[0].Joined)
+ }
+}
+
+func TestStepUpdateAfterLateFireWaits(t *testing.T) {
+ // A fire held back by a snooze until 25 h resets the update clock: a
+ // member joining a minute later is folded in silently.
+ sim := newStepSim(t)
+ sim.snoozedUntil[diskKey("b1")] = minute(25 * 60)
+ sim.run(0, 25*60+120, func(m int) []alertSignal {
+ if m > 25*60 {
+ return []alertSignal{firing("b1"), firing("b2")}
+ }
+ return []alertSignal{firing("b1")}
+ })
+ sim.emitsAre(simWant{25 * 60, "fire", []string{"b1"}})
}
func TestStepFlappingAcrossIncidents(t *testing.T) {
@@ -260,8 +288,8 @@ func TestStepFlappingAcrossIncidents(t *testing.T) {
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)
+ if sim.fireCount != 5 {
+ t.Fatalf("fires = %d, want b1 four times and b2 once", sim.fireCount)
}
}
@@ -287,21 +315,78 @@ func TestStepFlappingHeldOneHour(t *testing.T) {
}
}
+func TestStepFlappingSurvivesGone(t *testing.T) {
+ // b1 flaps and goes quiet; b2, firing alone, then goes gone. b1 fired
+ // inside the hour, so the hold goes on and b1's next fire, 25 minutes
+ // later, wakes the same incident instead of opening a new one.
+ sim := newStepSim(t)
+ sim.run(0, 120, func(m int) []alertSignal {
+ b1 := quiet("b1")
+ if m == 0 || m == 2 || m == 4 || m == 35 {
+ b1 = firing("b1")
+ }
+ b2 := quiet("b2")
+ switch {
+ case m >= 10:
+ b2 = gone("b2")
+ case m >= 6:
+ b2 = firing("b2")
+ }
+ return []alertSignal{b1, b2}
+ })
+ sim.emitsAre(simWant{9, "fire", []string{"b2"}}, simWant{96, "clear", []string{"b1"}})
+ for _, e := range sim.emits {
+ if e.Incident.ID != 3 {
+ t.Fatalf("emit %+v, want both from incident 3", e)
+ }
+ }
+ if r := sim.emits[1].Incident.CloseReason; r != alertCloseCleared {
+ t.Fatalf("close reason = %q, want %q", r, alertCloseCleared)
+ }
+}
+
+func TestStepDuplicateOpenClosed(t *testing.T) {
+ sim := newStepSim(t)
+ a := alertIncident{ID: 1, Scope: "fleet", Rule: "disk_eta", Level: "warning",
+ OpenedAt: minute(0), NotifyAt: minute(5), Members: []string{"b1"}, Notified: true,
+ LastReminderAt: minute(5), LastUpdateAt: minute(5)}
+ b := a
+ b.ID, b.Members = 2, []string{"b2"}
+ sim.open, sim.nextID = []alertIncident{a, b}, 3
+ changed, emits := sim.step(minute(10), firing("b1"), firing("b2"))
+ if len(emits) != 0 || len(changed) != 2 {
+ t.Fatalf("changed %+v, emits %+v, want both rows and no emit", changed, emits)
+ }
+ if c := changed[1]; c.ID != 2 || c.CloseReason != alertCloseDuplicate || !c.ClosedAt.Equal(minute(10)) {
+ t.Fatalf("extra = %+v, want incident 2 closed as %q", c, alertCloseDuplicate)
+ }
+ if c := changed[0]; c.ID != 1 || !slices.Equal(c.Members, []string{"b1", "b2"}) {
+ t.Fatalf("kept = %+v, want incident 1 taking b2", c)
+ }
+}
+
func TestStepDailyReminder(t *testing.T) {
+ // Each reminder is 24 h after the last message. b2 joining a minute
+ // after the first reminder is silent: the reminder reset the update
+ // clock too.
sim := newStepSim(t)
const day = 24 * 60
sim.run(0, 2*day+60, func(m int) []alertSignal {
- if m < 2*day+30 {
+ switch {
+ case m >= 2*day+30:
+ return []alertSignal{quiet("b1"), quiet("b2")}
+ case m >= day+6:
+ return []alertSignal{firing("b1"), firing("b2")}
+ default:
return []alertSignal{firing("b1")}
}
- return []alertSignal{quiet("b1")}
})
- one := []string{"b1"}
+ both := []string{"b1", "b2"}
sim.emitsAre(
- simWant{5, "fire", one},
- simWant{day, "reminder", one},
- simWant{2 * day, "reminder", one},
- simWant{2*day + 30, "clear", one},
+ simWant{5, "fire", []string{"b1"}},
+ simWant{day + 5, "reminder", []string{"b1"}},
+ simWant{2*day + 5, "reminder", both},
+ simWant{2*day + 30, "clear", both},
)
}
@@ -359,7 +444,7 @@ func TestStepGoneCloses(t *testing.T) {
}
func TestStepSnoozeSuppresses(t *testing.T) {
- t.Run("snoozed fire waits, snoozed clear is dropped", func(t *testing.T) {
+ t.Run("snoozed fire waits, clear still goes", func(t *testing.T) {
sim := newStepSim(t)
sim.snoozedUntil[diskKey("b1")] = minute(30)
sim.run(0, 30, func(int) []alertSignal { return []alertSignal{firing("b1")} })
@@ -369,6 +454,8 @@ func TestStepSnoozeSuppresses(t *testing.T) {
}
sim.run(30, 40, func(int) []alertSignal { return []alertSignal{firing("b1")} })
sim.emitsAre(simWant{30, "fire", []string{"b1"}})
+ // Snoozed again after the fire: the clear is still sent, naming
+ // nobody.
sim.snoozedUntil[diskKey("b1")] = minute(24 * 60)
sim.run(40, 60, func(m int) []alertSignal {
if m < 50 {
@@ -376,10 +463,25 @@ func TestStepSnoozeSuppresses(t *testing.T) {
}
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)
- }
+ sim.emitsAre(simWant{30, "fire", []string{"b1"}}, simWant{50, "clear", nil})
+ })
+ t.Run("a snoozed last member keeps the clear", func(t *testing.T) {
+ // fire [b1 b2], snooze b1, b2 clears, b1 clears: one clear.
+ sim := newStepSim(t)
+ sim.run(0, 60, func(m int) []alertSignal {
+ if m == 10 {
+ sim.snoozedUntil[diskKey("b1")] = minute(24 * 60)
+ }
+ b1, b2 := firing("b1"), firing("b2")
+ if m >= 20 {
+ b2 = quiet("b2")
+ }
+ if m >= 30 {
+ b1 = quiet("b1")
+ }
+ return []alertSignal{b1, b2}
+ })
+ sim.emitsAre(simWant{5, "fire", []string{"b1", "b2"}}, simWant{30, "clear", nil})
})
t.Run("a snoozed member is left out", func(t *testing.T) {
sim := newStepSim(t)
@@ -396,6 +498,14 @@ func TestStepSnoozeSuppresses(t *testing.T) {
t.Fatalf("members = %v, want both still tracked", got)
}
})
+ t.Run("a late fire starts the reminder clock", func(t *testing.T) {
+ // Snoozed past a day: the fire at 30 h is not followed by a
+ // reminder until 24 h after it.
+ sim := newStepSim(t)
+ sim.snoozedUntil[diskKey("b1")] = minute(30 * 60)
+ sim.run(0, 55*60, func(int) []alertSignal { return []alertSignal{firing("b1")} })
+ sim.emitsAre(simWant{30 * 60, "fire", []string{"b1"}}, simWant{54 * 60, "reminder", []string{"b1"}})
+ })
}
func TestStepRestartNoDuplicate(t *testing.T) {
@@ -407,18 +517,18 @@ func TestStepRestartNoDuplicate(t *testing.T) {
if m >= 2 {
sigs[1] = firing("b2")
}
- if m >= 40 {
+ if m >= 70 {
sigs[2] = firing("b3")
}
- if m >= 70 {
+ if m >= 100 {
sigs[1] = gone("b2")
}
- if m >= 1500 {
+ if m >= 1600 {
sigs[0], sigs[2] = quiet("b1"), quiet("b3")
}
return sigs
}
- for m := 0; m < 1600; m++ {
+ for m := 0; m < 1700; m++ {
sigs := state(m)
sim.step(minute(m), sigs...)
changed, fires, emits := stepIncidents(sim.open, sim.recentFires(minute(m)), sigs, sim.snoozed, minute(m))
@@ -428,9 +538,9 @@ func TestStepRestartNoDuplicate(t *testing.T) {
}
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"}},
+ simWant{70, "update", []string{"b1", "b2", "b3"}},
+ simWant{70 + 24*60, "reminder", []string{"b1", "b3"}},
+ simWant{1600, "clear", []string{"b1", "b3"}},
)
}
@@ -443,3 +553,135 @@ func TestStepDoesNotModifyOpen(t *testing.T) {
t.Fatalf("open changed under the step: %+v", open[0])
}
}
+
+// TestStepInvariantsRandom (ruling R-18) runs 500 seeded three-day
+// timelines over three boxes that fire, clear and go gone at random, with
+// passes that miss a box and snoozes that come and go, and checks the
+// noise rules' invariants after every step.
+func TestStepInvariantsRandom(t *testing.T) {
+ const seeds, steps = 500, 3 * 24 * 60
+ subjects := []string{"b1", "b2", "b3"}
+ for seed := range seeds {
+ if err := runStepInvariants(t, uint64(seed), steps, subjects); err != nil {
+ t.Fatalf("seed %d: %v", seed, err)
+ }
+ }
+}
+
+func runStepInvariants(t *testing.T, seed uint64, steps int, subjects []string) error {
+ rng := rand.New(rand.NewPCG(seed, 0))
+ // Each seed picks how often a box changes state, from steady to
+ // flapping hard.
+ flip := []float64{0.002, 0.02, 0.2}[seed%3]
+ const (
+ off = iota
+ on
+ vanished
+ )
+ state := map[string]int{}
+ sim := newStepSim(t)
+ notified := map[int64]bool{}
+ lastMsg := map[int64]time.Time{}
+ lastReminder := map[int64]time.Time{}
+ lastUpdate := map[int64]time.Time{}
+ cleared := map[int64]bool{}
+
+ for m := range steps {
+ now := minute(m)
+ var sigs []alertSignal
+ for _, b := range subjects {
+ switch {
+ case state[b] == vanished:
+ if rng.Float64() < 0.01 {
+ state[b] = off
+ }
+ case rng.Float64() < 0.0005:
+ state[b] = vanished
+ case rng.Float64() < flip:
+ state[b] ^= 1
+ }
+ if rng.Float64() < 0.002 {
+ sim.snoozedUntil[diskKey(b)] = now.Add(time.Duration(rng.IntN(36*60)) * time.Minute)
+ }
+ if rng.Float64() < 0.2 {
+ continue // this pass has no report for b
+ }
+ switch state[b] {
+ case on:
+ sigs = append(sigs, firing(b))
+ case off:
+ sigs = append(sigs, quiet(b))
+ default:
+ sigs = append(sigs, gone(b))
+ }
+ }
+
+ changed, emits := sim.step(now, sigs...) // (h) is checked in step
+
+ // (a) one open incident per (scope, rule).
+ if len(sim.open) > 1 {
+ return fmt.Errorf("minute %d: %d open incidents", m, len(sim.open))
+ }
+ clears := map[int64]int{}
+ for _, e := range emits {
+ id := e.Incident.ID
+ switch e.Kind {
+ case alertKindFire:
+ if notified[id] { // (b)
+ return fmt.Errorf("minute %d: second fire for incident %d", m, id)
+ }
+ if now.Before(e.Incident.NotifyAt) { // (d)
+ return fmt.Errorf("minute %d: fire for incident %d before NotifyAt", m, id)
+ }
+ notified[id] = true
+ case alertKindReminder:
+ if !notified[id] || now.Sub(lastMsg[id]) < alertReminderEvery { // (e)
+ return fmt.Errorf("minute %d: reminder for incident %d %v after its last message", m, id, now.Sub(lastMsg[id]))
+ }
+ if r, ok := lastReminder[id]; ok && now.Sub(r) < alertReminderEvery {
+ return fmt.Errorf("minute %d: reminders for incident %d %v apart", m, id, now.Sub(r))
+ }
+ lastReminder[id] = now
+ case alertKindUpdate:
+ if !notified[id] {
+ return fmt.Errorf("minute %d: update for unannounced incident %d", m, id)
+ }
+ if u, ok := lastUpdate[id]; ok && now.Sub(u) < alertUpdateEvery { // (f)
+ return fmt.Errorf("minute %d: updates for incident %d %v apart", m, id, now.Sub(u))
+ }
+ lastUpdate[id] = now
+ case alertKindClear:
+ clears[id]++
+ }
+ lastMsg[id] = now
+ }
+ // (c) a notified incident that closes sends exactly one clear, and
+ // nothing else sends one.
+ closing := map[int64]bool{}
+ for _, c := range changed {
+ if c.ID == 0 || c.ClosedAt.IsZero() {
+ continue
+ }
+ closing[c.ID] = true
+ want := 0
+ if notified[c.ID] {
+ want = 1
+ }
+ if clears[c.ID] != want || cleared[c.ID] {
+ return fmt.Errorf("minute %d: incident %d closed (notified %v) with %d clears", m, c.ID, notified[c.ID], clears[c.ID])
+ }
+ cleared[c.ID] = true
+ }
+ for id := range clears {
+ if !closing[id] {
+ return fmt.Errorf("minute %d: clear for incident %d, which did not close", m, id)
+ }
+ }
+ // (g) the same pass run again on what it committed is idle.
+ c2, f2, e2 := stepIncidents(sim.open, sim.recentFires(now), sigs, sim.snoozed, now)
+ if len(c2) != 0 || len(f2) != 0 || len(e2) != 0 {
+ return fmt.Errorf("minute %d replay: changed %+v, fires %+v, emits %+v", m, c2, f2, e2)
+ }
+ }
+ return nil
+}
diff --git a/internal/console/alertstore.go b/internal/console/alertstore.go
index 0908a7273..c090554cf 100644
--- a/internal/console/alertstore.go
+++ b/internal/console/alertstore.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "slices"
"time"
)
@@ -198,7 +199,17 @@ type alertRuleSetting struct {
}
// alertIncident is one alert_incidents row. A zero ClosedAt is open. ID 0
-// is an incident CommitAlertStep has not written yet.
+// is an incident CommitAlertStep has not written yet. stepIncidents
+// (alertengine.go) gives two fields a meaning of their own:
+//
+// - Members is the subjects firing now, in join order. On a quiet
+// flapping incident it is the set held for the quiet hour, and on a
+// closed row the members it had when it closed.
+// - LastSeenAt is zero while any member fires. On a flapping incident it
+// is the time it went quiet, and on a closed row when it stopped.
+//
+// LastReminderAt and LastUpdateAt are both set by every message, so a
+// reminder or update counts from the last message of any kind.
type alertIncident struct {
ID int64
Scope, Rule, Level string
@@ -209,6 +220,20 @@ type alertIncident struct {
LastReminderAt, LastUpdateAt time.Time
}
+// quiet reports whether an open flapping incident is in its quiet hold: no
+// member firing, held until an hour after LastSeenAt (spec §6.7).
+func (in alertIncident) quiet() bool {
+ return in.ClosedAt.IsZero() && in.Flapping && !in.LastSeenAt.IsZero()
+}
+
+// firingMembers is the subjects firing now: nil while quiet or closed.
+func (in alertIncident) firingMembers() []string {
+ if in.quiet() || !in.ClosedAt.IsZero() {
+ return nil
+ }
+ return slices.Clone(in.Members)
+}
+
// alertOutboxRow is one alert_outbox row. An empty DeliveryID is minted at
// insert; IncidentID 0 is a message tied to no incident (a cutover clear, a
// verify, a suspension notice).