carlos / platform Public

console: the alert watcher keeps a projection of what is firing now

alertPass rebuilds s.alertsNow from the alerts/boxes/*.json objects it already
reads: a box it read and parsed is replaced, a box whose read or parse failed
keeps its last entries, a box no longer listed drops out. A failed listing
leaves it as it was; it is unknown until the first listing succeeds. Rule
names come from the objects, so a geoip firing is one entry, never the
geoip@N delivery rows in alert_seen. No new S3 request.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a276d0f2797b923efc2446d75e342dc7142ce47b parent 33f4b38
5 files changed, +360 −0
  • .amadan/test-weights.tsv +5 −0
  • internal/console/alertnow.go +100 −0
  • internal/console/alertnow_test.go +238 −0
  • internal/console/alertwatch.go +14 −0
  • internal/console/server.go +3 −0

CI failed — run details

diff --git a/.amadan/test-weights.tsv b/.amadan/test-weights.tsv
index ea572abdc..4a665b859 100644
--- a/.amadan/test-weights.tsv
+++ b/.amadan/test-weights.tsv
@@ -111,10 +111,14 @@ github.com/carlosframework/platform/internal/console TestAssetsStatusIsIncomplet
github.com/carlosframework/platform/internal/console TestDBReadResultAfterTheDeadlineIsNotRelayed 1.4
github.com/carlosframework/platform/internal/console TestAPIShipRefusesReassetingAReship 1.3
github.com/carlosframework/platform/internal/console TestOverBudgetPageIsLogged 1.3
+github.com/carlosframework/platform/internal/console TestAlertsNowGeoipIsOneEntry 1.3
github.com/carlosframework/platform/internal/console TestAPIShipRefusesAssetsOnStatic 1.2
github.com/carlosframework/platform/internal/console TestJ4HostDoorRoutesOnlyMoveKinds 1.2
github.com/carlosframework/platform/internal/console TestJ4MoveDoorInspectsThenDeclares 1.2
github.com/carlosframework/platform/internal/console TestJ4MoveDoorStaleSubmission 1.2
+github.com/carlosframework/platform/internal/console TestAlertsNowFiringThenClearedWithARecipientChange 1.2
+github.com/carlosframework/platform/internal/console TestAlertsNowUnknownBeforeTheFirstPass 1.2
+github.com/carlosframework/platform/internal/console TestAlertsNowKeepsABoxWhoseReadFailedAndDropsAGoneBox 1.2
github.com/carlosframework/platform/internal/console TestAPIPromoteRetryResignsThePointer 1.1
github.com/carlosframework/platform/internal/console TestMoveDoorRefusesAnIneligibleSource 1.1
github.com/carlosframework/platform/internal/console TestPlan9RollbackCASConflictIsAConflictAndNotRetried 1.1
@@ -122,6 +126,7 @@ github.com/carlosframework/platform/internal/console TestAnIncompletePlacementRe
github.com/carlosframework/platform/internal/console TestClaimLossPagesScanProgressSurvivesRestartAndWraps 1.0
github.com/carlosframework/platform/internal/console TestCreateDoorsRefuseWithNoRoomBeforeRegistering 1.0
github.com/carlosframework/platform/internal/console TestDBReadRequestBoundClampsAForgedDeadline 1.0
+github.com/carlosframework/platform/internal/console TestAlertsNowWithoutKeymailStaysUnknownAndReadsNothing 1.0
github.com/carlosframework/platform/internal/console TestAssetsStatusIsUnknownWhereEdgesWouldDisagree 0.6
github.com/carlosframework/platform/internal/console TestAssetsStatusSkipsAHomeNoEdgeCanDial 0.5
github.com/carlosframework/platform/internal/console TestRegionNamesRequestBudget 0.62
diff --git a/internal/console/alertnow.go b/internal/console/alertnow.go
new file mode 100644
index 000000000..1c62f24cc
--- /dev/null
+++ b/internal/console/alertnow.go
@@ -0,0 +1,100 @@
+package console
+
+import (
+ "sort"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/metrics"
+)
+
+// What is firing now, as the alert watcher last read it from
+// alerts/boxes/*.json (alertPass). The operator pages read this rather than
+// alert_seen, which is per-recipient delivery history: a row there says who
+// was told what, and stays "firing" for an operator who lost their grant
+// before the clear was mailed. The projection is rebuilt from the objects
+// on every pass, so it reads nothing the watcher does not already read.
+//
+// A box whose object cannot be read or parsed keeps its last entries (the
+// run is marked Failed); a box whose object is gone drops out. Until the
+// first pass whose listing succeeds, the projection is unknown.
+
+// FiringAlert is one rule firing on one box, since when.
+type FiringAlert struct {
+ Box, Rule string
+ Since time.Time
+}
+
+type alertNow struct {
+ mu sync.Mutex
+ known bool
+ boxes map[string]map[string]time.Time // box -> rule -> since
+}
+
+func newAlertNow() *alertNow { return &alertNow{boxes: map[string]map[string]time.Time{}} }
+
+// setBox replaces box's entries with its rules that are firing. Since is the
+// rule's FiredAt, or, without one, the since it already had while firing,
+// else now.
+func (a *alertNow) setBox(box string, rules map[string]metrics.RuleState, now time.Time) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ prev := a.boxes[box]
+ next := map[string]time.Time{}
+ for rule, rs := range rules {
+ if !rs.Firing {
+ continue
+ }
+ since := rs.FiredAt
+ if since.IsZero() {
+ if p, ok := prev[rule]; ok {
+ since = p
+ } else {
+ since = now
+ }
+ }
+ next[rule] = since
+ }
+ if len(next) == 0 {
+ delete(a.boxes, box)
+ return
+ }
+ a.boxes[box] = next
+}
+
+// keepOnly drops the boxes not in boxes: their object is gone.
+func (a *alertNow) keepOnly(boxes map[string]bool) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ for box := range a.boxes {
+ if !boxes[box] {
+ delete(a.boxes, box)
+ }
+ }
+}
+
+// markKnown records that a pass has listed the alert objects.
+func (a *alertNow) markKnown() {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.known = true
+}
+
+// Firing is every firing rule, sorted by box then rule, as a copy; known is
+// false until the first pass whose listing succeeded.
+func (a *alertNow) Firing() (alerts []FiringAlert, known bool) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ for box, rules := range a.boxes {
+ for rule, since := range rules {
+ alerts = append(alerts, FiringAlert{Box: box, Rule: rule, Since: since})
+ }
+ }
+ sort.Slice(alerts, func(i, j int) bool {
+ if alerts[i].Box != alerts[j].Box {
+ return alerts[i].Box < alerts[j].Box
+ }
+ return alerts[i].Rule < alerts[j].Rule
+ })
+ return alerts, a.known
+}
diff --git a/internal/console/alertnow_test.go b/internal/console/alertnow_test.go
new file mode 100644
index 000000000..3d1908adb
--- /dev/null
+++ b/internal/console/alertnow_test.go
@@ -0,0 +1,238 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "slices"
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// alertNowFixture is newPerfFixture (the console on the real S3 client over
+// s3fake) with Paul an operator holding a grant, and the alert mail
+// captured, so a pass runs through fx.srv.alertPass as the watcher runs it.
+func alertNowFixture(t *testing.T) (*consoleFixture, *perfLatency, *[]sentMail) {
+ t.Helper()
+ fx, lat := newPerfFixture(t)
+ if err := fx.st.SetGrantToken("paul@keymail.dev", "grant-p", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ sent := &[]sentMail{}
+ fx.srv.sendApp = func(_ context.Context, token, to, subject, body string) (string, error) {
+ *sent = append(*sent, sentMail{token, to, subject, body})
+ return "msg-1", nil
+ }
+ return fx, lat, sent
+}
+
+// publishAlert writes st as its box's alert object in the bucket under the
+// fake, replacing what is there as the agent's CAS publish does.
+func publishAlert(t *testing.T, rel release.Store, st metrics.AlertState) {
+ t.Helper()
+ b, err := json.Marshal(st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ putAlertBody(t, rel, metrics.AlertKey(st.Box), b)
+}
+
+func putAlertBody(t *testing.T, rel release.Store, key string, b []byte) {
+ t.Helper()
+ etag := ""
+ if _, cur, err := rel.Get(context.Background(), key); err == nil {
+ etag = cur
+ }
+ if _, err := rel.Put(context.Background(), key, b, etag); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func boxAlert(box, rule string, rs metrics.RuleState) metrics.AlertState {
+ return metrics.AlertState{V: 1, Box: box, UpdatedAt: time.Date(2026, 10, 26, 10, 5, 0, 0, time.UTC),
+ Rules: map[string]metrics.RuleState{rule: rs}}
+}
+
+var alertNowFiredAt = time.Date(2026, 10, 26, 10, 0, 0, 0, time.UTC)
+
+func alertNowPass(t *testing.T, fx *consoleFixture) {
+ t.Helper()
+ if err := fx.srv.alertPass(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func wantFiring(t *testing.T, fx *consoleFixture, want []FiringAlert) {
+ t.Helper()
+ got, known := fx.srv.alertsNow.Firing()
+ if !known {
+ t.Fatal("the projection is unknown after a pass")
+ }
+ if len(got) != len(want) {
+ t.Fatalf("firing = %+v, want %+v", got, want)
+ }
+ for i := range want {
+ if got[i].Box != want[i].Box || got[i].Rule != want[i].Rule || !got[i].Since.Equal(want[i].Since) {
+ t.Fatalf("firing = %+v, want %+v", got, want)
+ }
+ }
+}
+
+// TestAlertsNowFiringThenClearedWithARecipientChange: what is firing comes
+// from the alert objects, not from alert_seen. After the recipients change
+// and the alert clears, alert_seen still says Paul was told it fired (the
+// history the dashboard must not read), and the projection is empty.
+func TestAlertsNowFiringThenClearedWithARecipientChange(t *testing.T) {
+ fx, _, sent := alertNowFixture(t)
+ publishAlert(t, fx.rel, boxAlert("box-1", "disk", metrics.RuleState{Firing: true, Value: 0.95, FiredAt: alertNowFiredAt}))
+ alertNowPass(t, fx)
+ wantFiring(t, fx, []FiringAlert{{Box: "box-1", Rule: "disk", Since: alertNowFiredAt}})
+ if len(*sent) != 1 {
+ t.Fatalf("sent %d mails, want 1 to Paul", len(*sent))
+ }
+
+ if err := fx.st.SetGrantToken("paul@keymail.dev", "", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.SetOperator("ann@example.com", true); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.SetGrantToken("ann@example.com", "grant-a", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ publishAlert(t, fx.rel, boxAlert("box-1", "disk", metrics.RuleState{Firing: false, Value: 0.5}))
+ alertNowPass(t, fx)
+ wantFiring(t, fx, nil)
+ seen, known, err := fx.st.AlertSeen("box-1", "disk", "paul@keymail.dev")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !known || !seen {
+ t.Fatalf("alert_seen for Paul = seen %v known %v; the test needs the stale firing row it pins", seen, known)
+ }
+}
+
+// TestAlertsNowGeoipIsOneEntry: a geoip firing writes six alert_seen rows
+// (geoip and geoip@1 to geoip@5) and is one firing entry.
+func TestAlertsNowGeoipIsOneEntry(t *testing.T) {
+ fx, _, _ := alertNowFixture(t)
+ publishAlert(t, fx.rel, boxAlert("box-1", "geoip", metrics.RuleState{Firing: true, Value: 2, FiredAt: alertNowFiredAt}))
+ alertNowPass(t, fx)
+ for code := 1; code <= 5; code++ {
+ rule := "geoip@" + strconv.Itoa(code)
+ seen, known, err := fx.st.AlertSeen("box-1", rule, "paul@keymail.dev")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !known || seen != (code == 2) {
+ t.Errorf("alert_seen %s = seen %v known %v", rule, seen, known)
+ }
+ }
+ wantFiring(t, fx, []FiringAlert{{Box: "box-1", Rule: "geoip", Since: alertNowFiredAt}})
+}
+
+// TestAlertsNowKeepsABoxWhoseReadFailedAndDropsAGoneBox: a box whose object
+// cannot be read or parsed keeps its last entries; a box whose object is
+// gone drops out.
+func TestAlertsNowKeepsABoxWhoseReadFailedAndDropsAGoneBox(t *testing.T) {
+ fx, lat, _ := alertNowFixture(t)
+ key := metrics.AlertKey("box-1")
+ publishAlert(t, fx.rel, boxAlert("box-1", "disk", metrics.RuleState{Firing: true, Value: 0.95, FiredAt: alertNowFiredAt}))
+ publishAlert(t, fx.rel, boxAlert("box-2", "mem", metrics.RuleState{Firing: true, Value: 0.97}))
+ before := time.Now()
+ alertNowPass(t, fx)
+ got, _ := fx.srv.alertsNow.Firing()
+ if len(got) != 2 || got[1].Box != "box-2" || got[1].Since.Before(before) {
+ t.Fatalf("firing = %+v, want box-1/disk and box-2/mem (since the pass, as it has no FiredAt)", got)
+ }
+ // box-2's mem has no FiredAt: every later pass keeps the since it had.
+ mem := got[1]
+
+ // A read the bucket refuses keeps the box.
+ rec := recordS3(lat, func(q s3Req) bool { return q.Method == http.MethodGet && q.Key == key })
+ alertNowPass(t, fx)
+ wantFiring(t, fx, []FiringAlert{{Box: "box-1", Rule: "disk", Since: alertNowFiredAt}, mem})
+ if rec.touching(key) == 0 {
+ t.Fatal("the pass never asked for box-1's object")
+ }
+
+ // An object that does not parse keeps the box too.
+ recordS3(lat, nil)
+ putAlertBody(t, fx.rel, key, []byte("{not json"))
+ alertNowPass(t, fx)
+ wantFiring(t, fx, []FiringAlert{{Box: "box-1", Rule: "disk", Since: alertNowFiredAt}, mem})
+
+ // A gone object drops the box.
+ if err := fx.rel.Delete(context.Background(), key); err != nil {
+ t.Fatal(err)
+ }
+ alertNowPass(t, fx)
+ wantFiring(t, fx, []FiringAlert{mem})
+}
+
+// TestAlertsNowUnknownBeforeTheFirstPass: a fresh console does not know what
+// is firing; a failed listing leaves it unknown; a pass over an empty prefix
+// knows that nothing is.
+func TestAlertsNowUnknownBeforeTheFirstPass(t *testing.T) {
+ fx, lat, _ := alertNowFixture(t)
+ if got, known := fx.srv.alertsNow.Firing(); known || len(got) != 0 {
+ t.Fatalf("fresh console: firing %+v known %v, want unknown", got, known)
+ }
+ recordS3(lat, func(q s3Req) bool { return q.Key == "" && q.Prefix == alertPrefix })
+ if err := fx.srv.alertPass(context.Background()); err == nil {
+ t.Fatal("a pass whose listing is refused returned nil")
+ }
+ if _, known := fx.srv.alertsNow.Firing(); known {
+ t.Fatal("a failed listing made the projection known")
+ }
+ recordS3(lat, nil)
+ alertNowPass(t, fx)
+ wantFiring(t, fx, nil)
+}
+
+// TestAlertsNowWithoutKeymailStaysUnknownAndReadsNothing: with no sender
+// the watcher does nothing at all, so it reads nothing and knows nothing.
+func TestAlertsNowWithoutKeymailStaysUnknownAndReadsNothing(t *testing.T) {
+ fx, lat, _ := alertNowFixture(t)
+ publishAlert(t, fx.rel, boxAlert("box-1", "disk", metrics.RuleState{Firing: true, FiredAt: alertNowFiredAt}))
+ fx.srv.sendApp = nil
+ rec := recordS3(lat, nil)
+ alertNowPass(t, fx)
+ if reqs := rec.all(); len(reqs) != 0 {
+ t.Errorf("a pass with no sender made S3 requests: %+v", reqs)
+ }
+ if got, known := fx.srv.alertsNow.Firing(); known || len(got) != 0 {
+ t.Errorf("firing %+v known %v, want unknown", got, known)
+ }
+}
+
+// TestAlertNowSetBoxReplaces pins setBox and Firing (not acceptance: a unit
+// test of alertNow): a box's entries are replaced, cleared rules go, the
+// result is sorted and a copy.
+func TestAlertNowSetBoxReplaces(t *testing.T) {
+ a := newAlertNow()
+ t0 := time.Date(2026, 10, 26, 9, 0, 0, 0, time.UTC)
+ a.setBox("b", map[string]metrics.RuleState{"mem": {Firing: true}, "disk": {Firing: true, FiredAt: t0}, "cpu": {}}, t0.Add(time.Minute))
+ a.setBox("a", map[string]metrics.RuleState{"lag": {Firing: true, FiredAt: t0}}, t0)
+ a.markKnown()
+ got, known := a.Firing()
+ want := []FiringAlert{{"a", "lag", t0}, {"b", "disk", t0}, {"b", "mem", t0.Add(time.Minute)}}
+ if !known || !slices.Equal(got, want) {
+ t.Fatalf("firing = %+v known %v, want %+v", got, known, want)
+ }
+ got[0].Box = "changed"
+ a.setBox("b", map[string]metrics.RuleState{"mem": {Firing: true}}, t0.Add(time.Hour))
+ got, _ = a.Firing()
+ want = []FiringAlert{{"a", "lag", t0}, {"b", "mem", t0.Add(time.Minute)}}
+ if !slices.Equal(got, want) {
+ t.Fatalf("firing = %+v, want %+v (a copy, disk cleared, mem keeps its since)", got, want)
+ }
+ a.keepOnly(map[string]bool{"b": true})
+ if got, _ = a.Firing(); len(got) != 1 || got[0].Box != "b" {
+ t.Fatalf("after keepOnly(b): %+v", got)
+ }
+}
diff --git a/internal/console/alertwatch.go b/internal/console/alertwatch.go
index 416885e76..48c20402b 100644
--- a/internal/console/alertwatch.go
+++ b/internal/console/alertwatch.go
@@ -99,6 +99,11 @@ const noMailboxAddress = ""
// mailing and recording per recipient. It returns an error only for a failure
// that makes the whole pass meaningless (listing the bucket, or reading the
// operator list); per-box and per-rule trouble is logged and stepped over.
+//
+// It also rebuilds s.alertsNow from the objects it reads, whoever the
+// recipients are: a box it read is replaced, a box it could not read keeps
+// its last entries, a box no longer listed drops out. A failed listing
+// leaves the projection as it was.
func (s *Server) alertPass(ctx context.Context) error {
if s.cfg.Releases == nil || s.sendApp == nil {
return nil
@@ -108,16 +113,21 @@ func (s *Server) alertPass(ctx context.Context) error {
return fmt.Errorf("list %s: %w", alertPrefix, err)
}
if len(keys) == 0 {
+ s.alertsNow.keepOnly(nil)
+ s.alertsNow.markKnown()
return nil // no box has ever published an alert: nothing to do
}
run, err := s.alertRecipients()
if err != nil {
return err
}
+ now := time.Now()
+ listed := map[string]bool{}
for _, key := range keys {
if !strings.HasSuffix(key, ".json") {
continue
}
+ listed[strings.TrimSuffix(strings.TrimPrefix(key, alertPrefix), ".json")] = true
body, _, err := s.cfg.Releases.Get(ctx, key)
if err != nil {
log.Printf("console: alert watch: read %s: %v", key, err)
@@ -136,6 +146,8 @@ func (s *Server) alertPass(ctx context.Context) error {
// publisher's own AlertKey produced.
box = strings.TrimSuffix(strings.TrimPrefix(key, alertPrefix), ".json")
}
+ listed[box] = true
+ s.alertsNow.setBox(box, st.Rules, now)
names := make([]string, 0, len(st.Rules))
for name := range st.Rules {
names = append(names, name)
@@ -145,6 +157,8 @@ func (s *Server) alertPass(ctx context.Context) error {
s.alertRule(ctx, run, box, name, st.Rules[name], st.UpdatedAt)
}
}
+ s.alertsNow.keepOnly(listed)
+ s.alertsNow.markKnown()
return nil
}
diff --git a/internal/console/server.go b/internal/console/server.go
index 7a5daee52..c7d9606e8 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -951,6 +951,8 @@ type Server struct {
// jobs is what each claim worker's runs last did (jobs.go), for the
// operator pages. Made before registerClaimWorkers declares the workers.
jobs *jobRegistry
+ // alertsNow is what the alert watcher last read as firing (alertnow.go).
+ alertsNow *alertNow
// perf records every request but /healthz; handler is the mux wrapped
// in its middleware, and is what serveAdmitted serves (NewServer).
perf *perf.Recorder
@@ -1576,6 +1578,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
km.SetSigningKey(key)
s := &Server{
jobs: newJobRegistry(time.Now),
+ alertsNow: newAlertNow(),
cfg: cfg,
store: st,
km: km,