carlos / platform Public

console: alert engine fix round 1 (drain on a failed step, read failures close nothing, seeding every pass)

- The drain runs whatever the step returned while ctx is live; the beat
  is still written only after a step that committed.
- Unreachable operators are named on every pass from the daily check
  until a check finds them reachable.
- Operators are seeded every pass, idempotently (R-20).
- An unusable seal key is a job note, not a failure (R-21): jobNoteOn and
  JobStatus.Note, shown for a run that succeeded.
- On a host-claim console the worker is off: it logs and returns before
  any run, so the job drops off the list (R-23). The probe captures the
  log and counts zero store calls.
- box_silent keeps a box whose heartbeat is past the 24 h horizon; the
  horizon, on the engine clock, only orders reads under the key cap.
- One name per box (the key's); a mismatched body field is logged.
- Cutover encode errors are returned; per-source read failures under a
  cancelled ctx do not fail the run.
- Tests: the drain despite a listing failure, a failed read per source
  keeping its incident with no clear, a later operator seeded, the
  unreachable line held until reachable.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 4aaa411e10abfe8c97f29834814331c537f6b5da parent b14accf
7 files changed, +351 −127
  • internal/console/alertengine_pass.go +91 −48
  • internal/console/alertengine_pass_test.go +160 −21
  • internal/console/alertsignals.go +50 −39
  • internal/console/claim_invariant_fixtures_test.go +1 −1
  • internal/console/claim_invariant_probes_worker_test.go +18 −12
  • internal/console/jobs.go +28 −4
  • internal/console/jobs_test.go +3 −2

Intent

Attributed to this commit: 7.39 g CO₂e (930,628 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_pass.go b/internal/console/alertengine_pass.go
index f742e43ae..39035c04a 100644
--- a/internal/console/alertengine_pass.go
+++ b/internal/console/alertengine_pass.go
@@ -24,14 +24,16 @@ import (
// what is firing, and writes the beat the console box's agent watches
// (spec §8).
//
-// The first pass of a process opens the connector seal, seeds each operator
-// an email connector, and, once per database, migrates the watcher's
-// delivery history (alert_seen) so nobody is told twice, or not told a
-// clear they are owed.
+// The first pass of a process opens the connector seal and, once per
+// database, migrates the watcher's delivery history (alert_seen) so nobody
+// is told twice, or not told a clear they are owed. Every pass seeds each
+// operator an email connector, idempotently, so an operator made later is
+// reached within a minute (ruling R-20).
//
-// One console per deployment runs it (spec §5.2): a host-claim console,
-// which may be one of several, refuses before any read or write and says so
-// in its job status.
+// One console per deployment runs it (spec §5.2): on a host-claim console,
+// which may be one of several, the worker is off. It says so in the log and
+// returns before any read or write, so the job drops off the operator
+// pages' list, as the other workers that are off there do.
//
// The watcher's per-recipient keymail helpers stay in alertwatch.go.
@@ -52,7 +54,8 @@ const (
// (metrics.AlertKey).
const alertPrefix = "alerts/boxes/"
-// errAlertEngineRefused is the host-claim console's job status.
+// errAlertEngineRefused is what a pass answers on a host-claim console. The
+// worker never runs one there; this guards a pass called some other way.
var errAlertEngineRefused = errors.New("refused: host-claim console")
// alertEngineState is what the engine keeps between passes, in memory: a
@@ -71,24 +74,24 @@ type alertEngineState struct {
// since is each box rule firing on the dashboard, since when.
since map[alertKey]time.Time
// unreachableAt is when operators were last checked for a usable
- // connector.
+ // connector, and unreachable who that check found none reaches.
unreachableAt time.Time
+ unreachable []string
}
// StartAlertEngine runs alertEnginePass now and then every minute until ctx
// is done. Started from cmd/console's serve(), never from NewServer, so no
-// test server grows a goroutine or sends anything. A host-claim console's
-// first pass refuses, and the worker returns.
+// test server grows a goroutine or sends anything. On a host-claim console
+// it is off: it logs that and returns without a run.
func (s *Server) StartAlertEngine(ctx context.Context) {
+ if s.cfg.HostClaim {
+ log.Printf("console: alert engine: off on a host-claim console; one console per deployment runs it (fleet alerts spec §5.2)")
+ return
+ }
t := time.NewTicker(alertEngineInterval)
defer t.Stop()
for {
- err := s.jobs.Run(ctx, "StartAlertEngine", s.alertEnginePass)
- if errors.Is(err, errAlertEngineRefused) {
- log.Printf("console: alert engine: %v; one console per deployment runs it (fleet alerts spec §5.2)", err)
- return
- }
- if err != nil {
+ if err := s.jobs.Run(ctx, "StartAlertEngine", s.alertEnginePass); err != nil {
log.Printf("console: alert engine: %v", err)
}
select {
@@ -99,35 +102,46 @@ func (s *Server) StartAlertEngine(ctx context.Context) {
}
}
-// alertEnginePass is one pass: signals, the step and its commit, the drain,
-// the dashboard's view, and the beat. It returns an error only for a
+// alertEnginePass is one pass: signals, the step and its commit, the
+// dashboard's view, the drain, and the beat. It returns an error only for a
// failure that makes the pass meaningless (listing alerts/boxes/, reading
// or committing the step, the drain's own); one source's trouble is logged
// and fails the run (jobFailed). A pass cut short by shutdown records no
// failure.
+//
+// The drain runs whatever the step did: rows already queued are owed even
+// when this pass cannot read its signals. The beat is written only after a
+// step that committed, so an engine that cannot step trips engine_silent
+// on its box (spec §8).
func (s *Server) alertEnginePass(ctx context.Context) error {
if s.cfg.HostClaim {
- return errAlertEngineRefused
+ return errAlertEngineRefused // StartAlertEngine never gets here
}
if s.cfg.Releases == nil {
return nil
}
now := s.alertClockNow()
- open, sig, err := s.alertEngineStep(ctx, now)
- if err == nil {
- // The view follows what was committed, whatever the drain does.
+ open, sig, stepErr := s.alertEngineStep(ctx, now)
+ if stepErr == nil {
s.feedAlertsNow(open, sig, now)
- err = s.alertDrainOutbox(ctx)
}
- if err != nil {
- if ctx.Err() != nil {
- return nil
+ var drainErr error
+ if ctx.Err() == nil {
+ drainErr = s.alertDrainOutbox(ctx)
+ }
+ if ctx.Err() != nil {
+ return nil
+ }
+ if stepErr != nil {
+ if drainErr != nil {
+ log.Printf("console: alert engine: drain: %v", drainErr)
+ jobFailed(ctx, fmt.Errorf("drain: %w", drainErr))
}
- return err
+ return stepErr
}
s.noteUnreachableOperators(ctx, now)
s.writeAlertEngineBeat(ctx, now)
- return nil
+ return drainErr
}
// alertEngineStep reads the signals and commits one step: the incident
@@ -141,11 +155,14 @@ func (s *Server) alertEngineStep(ctx context.Context, now time.Time) (open []ale
return nil, nil, err
}
if !e.started {
- s.openAlertSeal(ctx)
+ s.openAlertSeal()
if err := s.alertCutover(boxes, sig, now); err != nil {
return nil, nil, fmt.Errorf("alert cutover: %w", err)
}
e.started = true
+ } else if err := s.seedOperatorConnectors(now); err != nil {
+ log.Printf("console: alert engine: seed operator connectors: %v", err)
+ jobFailed(ctx, fmt.Errorf("seed operator connectors: %w", err))
}
if e.reentryPending {
if n, err := s.store.MarkSealedConnectorsNeedReentry(); err != nil {
@@ -171,9 +188,11 @@ func (s *Server) alertEngineStep(ctx context.Context, now time.Time) (open []ale
}
e.passes++
// seal_key fires while the key cannot be used or any connector needs
- // re-entering, and clears otherwise (Review Focus 5).
+ // re-entering, and clears otherwise (Review Focus 5). The key itself is
+ // not the job failing: the pass works around it, and seal_key is what
+ // alerts, so the job status carries it as a note (ruling R-21).
if e.sealErr != nil {
- jobFailed(ctx, e.sealErr)
+ jobNoteOn(ctx, fmt.Sprintf("%v; Slack and webhook connectors are held", e.sealErr))
}
reentry := slices.ContainsFunc(conns, func(c alertConnector) bool { return c.NeedsReentry })
sig.add(alertSignal{Key: alertKey{alertScopeFleet, "seal_key", alertSealSubject}, Level: alertRuleLevel("seal_key"),
@@ -194,10 +213,11 @@ func (s *Server) alertEngineStep(ctx context.Context, now time.Time) (open []ale
// openAlertSeal opens the connector seal on the first pass (spec §5.1). A
// key that cannot be used leaves every sealed connector held (the drain's
-// "no seal key") and fires seal_key on every pass; a key made fresh, while
-// sealed connectors exist, marks them as needing re-entry. A seal already
-// open (a test's) or no key path (tests) is left as it is.
-func (s *Server) openAlertSeal(ctx context.Context) {
+// "no seal key"), fires seal_key and notes it in the job status on every
+// pass; a key made fresh, while sealed connectors exist, marks them as
+// needing re-entry. A seal already open (a test's) or no key path (tests)
+// is left as it is.
+func (s *Server) openAlertSeal() {
e := &s.alertEngine
if s.alertSeal.Load() != nil || s.cfg.AlertSealKeyPath == "" {
return
@@ -205,7 +225,6 @@ func (s *Server) openAlertSeal(ctx context.Context) {
seal, created, err := openConnectorSeal(s.cfg.AlertSealKeyPath)
if err != nil {
log.Printf("console: alert engine: %v; Slack and webhook connectors are held", err)
- jobFailed(ctx, err)
e.sealErr = err
return
}
@@ -213,6 +232,17 @@ func (s *Server) openAlertSeal(ctx context.Context) {
e.reentryPending = created
}
+// seedOperatorConnectors gives every operator their email connector,
+// idempotently (ruling R-20). An operator made since the last pass is
+// reached from this one.
+func (s *Server) seedOperatorConnectors(now time.Time) error {
+ ops, err := s.store.Operators()
+ if err != nil {
+ return fmt.Errorf("operators: %w", err)
+ }
+ return s.store.SeedOperatorAlertConnectors(ops, now)
+}
+
// alertSnoozed is the step's snooze check at now. A failed read is logged,
// fails the run and counts as not snoozed: a message too many beats one
// missed.
@@ -385,7 +415,10 @@ func (s *Server) alertCutover(boxes boxAlerts, sig *alertSignals, now time.Time)
if err != nil {
return err
}
- opened, clears := planAlertCutover(boxes, seen, ops, conns, sig, now)
+ opened, clears, err := planAlertCutover(boxes, seen, ops, conns, sig, now)
+ if err != nil {
+ return err
+ }
for _, ci := range opened {
id, err := insertAlertIncidentTx(tx, ci.in)
if err != nil {
@@ -426,7 +459,7 @@ type cutoverIncident struct {
// and the watcher's history. seen is alert_seen's firing rows; conns each
// operator's seeded connector. Migrated incidents open with LastSeenAt zero
// (ruling R-17), notified, and their fire counted as now.
-func planAlertCutover(boxes boxAlerts, seen map[[2]string][]string, ops []string, conns map[string]int64, sig *alertSignals, now time.Time) (opened []cutoverIncident, clears []alertOutboxRow) {
+func planAlertCutover(boxes boxAlerts, seen map[[2]string][]string, ops []string, conns map[string]int64, sig *alertSignals, now time.Time) (opened []cutoverIncident, clears []alertOutboxRow, err error) {
byRule := map[string]int{}
keys := slices.Collect(maps.Keys(seen))
slices.SortFunc(keys, func(a, b [2]string) int { return strings.Compare(a[0]+"\x00"+a[1], b[0]+"\x00"+b[1]) })
@@ -454,7 +487,10 @@ func planAlertCutover(boxes boxAlerts, seen map[[2]string][]string, ops []string
OpenedAt: now, NotifyAt: now.Add(alertNotifyDelay), Notified: true, LastReminderAt: now}})
}
opened[i].in.Members = append(opened[i].in.Members, box)
- body, _ := json.Marshal(alertEmitNote(alertEmit{Incident: member, Kind: alertKindFire}, sig, now))
+ body, err := json.Marshal(alertEmitNote(alertEmit{Incident: member, Kind: alertKindFire}, sig, now))
+ if err != nil {
+ return nil, nil, fmt.Errorf("encode a fire for %s on %s: %w", rule, box, err)
+ }
for _, op := range ops {
if !slices.Contains(told, op) {
opened[i].fires = append(opened[i].fires, alertOutboxRow{ConnectorID: conns[op], Kind: alertKindFire, Body: body, NextAt: now})
@@ -466,12 +502,15 @@ func planAlertCutover(boxes boxAlerts, seen map[[2]string][]string, ops []string
if !listed || !has {
member.CloseReason = alertCloseGone
}
- body, _ := json.Marshal(alertEmitNote(alertEmit{Incident: member, Kind: alertKindClear}, sig, now))
+ body, err := json.Marshal(alertEmitNote(alertEmit{Incident: member, Kind: alertKindClear}, sig, now))
+ if err != nil {
+ return nil, nil, fmt.Errorf("encode a clear for %s on %s: %w", rule, box, err)
+ }
for _, op := range told {
clears = append(clears, alertOutboxRow{ConnectorID: conns[op], Kind: alertKindClear, Body: body, NextAt: now})
}
}
- return opened, clears
+ return opened, clears, nil
}
// ---- after the step ----------------------------------------------------------
@@ -505,13 +544,14 @@ func (s *Server) feedAlertsNow(open []alertIncident, sig *alertSignals, now time
s.alertsNow.set(firing)
}
-// noteUnreachableOperators names, once a day, the operators no usable
-// connector of their own reaches, in the job status (Review Focus 4): an
-// operator made after this process seeded, or whose connector is
-// suspended, needs re-entry or was removed.
+// noteUnreachableOperators names the operators no usable connector of
+// their own reaches (one suspended or needing re-entry), failing the run
+// (Review Focus 4). With everyone reachable it checks once a day; once a
+// check finds someone, it checks and names them on every pass until a
+// check finds them reachable, so the job status says so the whole time.
func (s *Server) noteUnreachableOperators(ctx context.Context, now time.Time) {
e := &s.alertEngine
- if !e.unreachableAt.IsZero() && now.Sub(e.unreachableAt) < alertUnreachableEvery {
+ if len(e.unreachable) == 0 && !e.unreachableAt.IsZero() && now.Sub(e.unreachableAt) < alertUnreachableEvery {
return
}
ops, err := s.store.Operators()
@@ -526,7 +566,6 @@ func (s *Server) noteUnreachableOperators(ctx context.Context, now time.Time) {
jobFailed(ctx, fmt.Errorf("alert connectors: %w", err))
return
}
- e.unreachableAt = now
var missing []string
for _, op := range ops {
if !slices.ContainsFunc(conns, func(c alertConnector) bool {
@@ -535,6 +574,10 @@ func (s *Server) noteUnreachableOperators(ctx context.Context, now time.Time) {
missing = append(missing, op)
}
}
+ if len(e.unreachable) == 0 || len(missing) == 0 {
+ e.unreachableAt = now // a daily check, or the one that cleared it
+ }
+ e.unreachable = missing
if len(missing) > 0 {
err := fmt.Errorf("no usable alert connector reaches %s", strings.Join(missing, ", "))
log.Printf("console: alert engine: %v", err)
diff --git a/internal/console/alertengine_pass_test.go b/internal/console/alertengine_pass_test.go
index 2c26ecddf..1d6165775 100644
--- a/internal/console/alertengine_pass_test.go
+++ b/internal/console/alertengine_pass_test.go
@@ -462,7 +462,8 @@ func TestEnginePassCrashBetweenCommitAndSend(t *testing.T) {
}
// Review Focus 5: a seal key that cannot be read holds every sealed
-// connector, fires one seal_key incident, and email keeps working.
+// connector, fires one seal_key incident, and email keeps working. The
+// job status notes it without failing.
func TestEnginePassSealKeyUnreadable(t *testing.T) {
key := filepath.Join(t.TempDir(), "alert-connectors.key")
if err := os.WriteFile(key, []byte("short"), 0o600); err != nil {
@@ -478,8 +479,9 @@ func TestEnginePassSealKeyUnreadable(t *testing.T) {
if err := ef.srv.jobs.Run(ctx, "StartAlertEngine", ef.srv.alertEnginePass); err != nil {
t.Fatal(err)
}
- if st, _ := jobStatusOf(ef.srv, "StartAlertEngine"); st.State != JobFailed || !strings.Contains(st.Err, "alert seal key") {
- t.Fatalf("job status %+v, want Failed naming the seal key", st)
+ // Not a job failure (ruling R-21): the pass completes and notes it.
+ if st, _ := jobStatusOf(ef.srv, "StartAlertEngine"); st.State != JobOK || !strings.Contains(st.Note, "alert seal key") {
+ t.Fatalf("job status %+v, want OK with a note naming the seal key", st)
}
ef.passesTo(t, time.Minute, 5*time.Minute)
got := ef.mailsTo(opA)
@@ -512,8 +514,9 @@ func TestEnginePassNewSealKeyMarksReentry(t *testing.T) {
}
}
-// R2 #1, spec §5.2: a host-claim console refuses before any read or write,
-// and says so in its job status.
+// Spec §5.2, R2 #2, R-23: on a host-claim console the engine is off. It
+// logs that and returns before any read or write, and the job drops off the
+// list as the other off-on-host-claim workers do.
func TestEngineRefusesInHostClaim(t *testing.T) {
beat := filepath.Join(t.TempDir(), "alert-engine.beat")
ef := newEngineFixture(t, func(c *Config) { c.AlertEngineBeatPath = beat })
@@ -523,27 +526,33 @@ func TestEngineRefusesInHostClaim(t *testing.T) {
ef.srv.cfg.HostClaim = true
rec := recordS3(ef.lat, nil)
+ var logs strings.Builder
+ restore := captureLogTo(&logs)
done := make(chan struct{})
- go func() { defer close(done); ef.srv.StartAlertEngine(context.Background()) }()
+ go func() { defer close(done); ef.srv.RunClaimWorker(context.Background(), "StartAlertEngine") }()
select {
case <-done:
case <-time.After(5 * time.Second):
+ restore()
t.Fatal("the engine on a host-claim console did not return")
}
- st, _ := jobStatusOf(ef.srv, "StartAlertEngine")
- if st.State != JobFailed || st.Err != "refused: host-claim console" {
- t.Fatalf("job status %+v, want the refusal", st)
+ restore()
+ if !strings.Contains(logs.String(), "alert engine: off on a host-claim console") {
+ t.Errorf("log %q does not say the engine is off", logs.String())
+ }
+ if st, ok := jobStatusOf(ef.srv, "StartAlertEngine"); ok {
+ t.Fatalf("job still listed as %+v, want it dropped like the other off workers", st)
}
if reqs := rec.all(); len(reqs) != 0 {
- t.Fatalf("a refused engine made bucket requests: %+v", reqs)
+ t.Fatalf("an engine that is off made bucket requests: %+v", reqs)
}
for _, table := range []string{"alert_connectors", "alert_incidents", "alert_fires", "alert_outbox", "alert_meta"} {
if n := ef.count(t, "SELECT COUNT(*) FROM "+table); n != 0 {
- t.Errorf("%s has %d rows after a refusal", table, n)
+ t.Errorf("%s has %d rows from an engine that is off", table, n)
}
}
if _, err := os.Stat(beat); !os.IsNotExist(err) {
- t.Errorf("a refused engine wrote its beat (%v)", err)
+ t.Errorf("an engine that is off wrote its beat (%v)", err)
}
}
@@ -597,10 +606,11 @@ func TestEnginePassWritesBeat(t *testing.T) {
}
// Review Focus 4: an operator no connector reaches is named in the job
-// status, once a day.
+// status from the daily check on, every pass, until a check finds them
+// reachable again.
func TestEnginePassNamesUnreachableOperators(t *testing.T) {
ef := newEngineFixture(t, nil)
- ef.operator(t, opA)
+ ef.operator(t, opA, opB)
ctx := context.Background()
run := func(d time.Duration) JobStatus {
t.Helper()
@@ -612,18 +622,147 @@ func TestEnginePassNamesUnreachableOperators(t *testing.T) {
return st
}
if st := run(0); st.State != JobOK {
- t.Fatalf("first pass %+v, want OK: A was seeded", st)
+ t.Fatalf("first pass %+v, want OK: both were seeded", st)
+ }
+ var connB int64
+ if err := ef.st.db.QueryRow(`SELECT id FROM alert_connectors WHERE owner_address = ?`, opB).Scan(&connB); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := ef.st.db.Exec(`UPDATE alert_connectors SET suspended_at = ? WHERE id = ?`, alertT0.Unix(), connB); err != nil {
+ t.Fatal(err)
}
- ef.operator(t, opB) // made after this process seeded
if st := run(time.Minute); st.State != JobOK {
- t.Fatalf("pass within the day %+v, want OK", st)
+ t.Fatalf("pass within the day %+v, want OK until the daily check", st)
}
- if st := run(24 * time.Hour); st.State != JobFailed || !strings.Contains(st.Err, opB) || strings.Contains(st.Err, opA) {
- t.Fatalf("daily check %+v, want Failed naming B alone", st)
+ named := func(st JobStatus) bool {
+ return st.State == JobFailed && strings.Contains(st.Err, opB) && !strings.Contains(st.Err, opA)
}
- if st := run(24*time.Hour + time.Minute); st.State != JobOK {
- t.Fatalf("pass after the daily check %+v, want OK", st)
+ for _, d := range []time.Duration{24 * time.Hour, 24*time.Hour + time.Minute, 24*time.Hour + 5*time.Minute} {
+ if st := run(d); !named(st) {
+ t.Fatalf("pass at +%v %+v, want Failed naming B alone", d, st)
+ }
+ }
+ if err := ef.st.ResumeAlertConnector(connB); err != nil {
+ t.Fatal(err)
+ }
+ if st := run(24*time.Hour + 6*time.Minute); st.State != JobOK {
+ t.Fatalf("pass after B is reachable %+v, want OK", st)
+ }
+}
+
+// Ruling R-20: seeding runs every pass, so an operator made after the
+// console started is reached from the next pass.
+func TestEnginePassSeedsALaterOperator(t *testing.T) {
+ ef := newEngineFixture(t, nil)
+ ef.operator(t, opA)
+ ef.passAt(t, 0)
+ ef.operator(t, opB)
+ ef.passAt(t, time.Minute)
+ conns, err := ef.st.AlertConnectors(alertScopeFleet)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var owners []string
+ for _, c := range conns {
+ owners = append(owners, c.OwnerAddress)
+ }
+ if !slices.Equal(owners, []string{opA, opB}) {
+ t.Fatalf("owners %v a minute after B was made, want A and B", owners)
+ }
+}
+
+// A failed step does not hold up rows already owed: the drain runs anyway,
+// and the beat is not written, so engine_silent can still trip.
+func TestEnginePassDrainsWhenTheListingFails(t *testing.T) {
+ beat := filepath.Join(t.TempDir(), "alert-engine.beat")
+ ef := newEngineFixture(t, func(c *Config) { c.AlertEngineBeatPath = beat })
+ ef.operator(t, opA)
+ ef.passAt(t, 0)
+ if err := os.Remove(beat); err != nil {
+ t.Fatal(err)
+ }
+ conns, err := ef.st.AlertConnectors(alertScopeFleet)
+ if err != nil || len(conns) != 1 {
+ t.Fatalf("connectors %+v (%v), want A's", conns, err)
}
+ ef.now = alertT0.Add(time.Minute)
+ ef.queue(t, conns[0].ID, 0, alertKindClear, fireNote())
+ recordS3(ef.lat, func(q s3Req) bool { return q.Key == "" && q.Prefix == alertPrefix })
+ if err := ef.srv.alertEnginePass(context.Background()); err == nil {
+ t.Fatal("a pass whose listing failed returned nil")
+ }
+ if got := ef.mailsTo(opA); len(got) != 1 {
+ t.Fatalf("A got %v, want the queued row delivered", got)
+ }
+ if _, err := os.Stat(beat); !os.IsNotExist(err) {
+ t.Errorf("a pass whose step failed wrote the beat (%v)", err)
+ }
+}
+
+// ---- a failed read closes nothing ------------------------------------------
+
+// openAndQuiet asserts rule's incident is still open and that no clear has
+// been queued: a source that could not be read is not a source that
+// stopped reporting.
+func (ef *engineFixture) openAndQuiet(t *testing.T, rule string) {
+ t.Helper()
+ if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents WHERE closed_at IS NULL AND rule = '`+rule+`'`); n != 1 {
+ t.Fatalf("%d open %s incidents after a failed read, want 1", n, rule)
+ }
+ if n := ef.count(t, `SELECT COUNT(*) FROM alert_outbox WHERE kind = 'clear'`); n != 0 {
+ t.Fatalf("%d clears queued after a failed read, want none", n)
+ }
+}
+
+func TestEnginePassJunkAlertObjectKeepsItsIncident(t *testing.T) {
+ ef := newEngineFixture(t, nil)
+ ef.operator(t, opA)
+ publishAlert(t, ef.rel, diskState("box-1", true))
+ ef.passesTo(t, 0, 5*time.Minute)
+ putAlertBody(t, ef.rel, metrics.AlertKey("box-1"), []byte("{not json"))
+ ef.passesTo(t, 6*time.Minute, 8*time.Minute)
+ ef.openAndQuiet(t, "disk")
+ publishAlert(t, ef.rel, diskState("box-1", true))
+ key := metrics.AlertKey("box-1")
+ recordS3(ef.lat, func(q s3Req) bool { return q.Method == "GET" && q.Key == key })
+ ef.passesTo(t, 9*time.Minute, 11*time.Minute)
+ ef.openAndQuiet(t, "disk")
+}
+
+func TestEnginePassCorruptHeartbeatKeepsBoxSilent(t *testing.T) {
+ ef := newEngineFixture(t, nil)
+ ef.operator(t, opA)
+ ef.heartbeat(t, "box-9", alertT0.Add(-time.Hour), nil)
+ ef.passesTo(t, 0, 5*time.Minute)
+ putAlertBody(t, ef.rel, "status/boxes/box-9.json", []byte("{not json"))
+ ef.passesTo(t, 6*time.Minute, 15*time.Minute) // two heartbeat passes
+ ef.openAndQuiet(t, "box_silent")
+}
+
+func TestEnginePassUnparsableFleetKeepsServiceDown(t *testing.T) {
+ ef := newEngineFixture(t, nil)
+ ef.operator(t, opA)
+ ef.fleetServices(t, map[string]bool{"keymail": false})
+ ef.passesTo(t, 0, 5*time.Minute)
+ putAlertBody(t, ef.rel, alertFleetKey, []byte("{not json"))
+ ef.passesTo(t, 6*time.Minute, 15*time.Minute)
+ ef.openAndQuiet(t, "service_down")
+}
+
+func TestEnginePassUnreadHeartbeatKeepsCertExpiring(t *testing.T) {
+ ef := newEngineFixture(t, nil)
+ ef.operator(t, opA)
+ expiring := &status.BoxMetrics{Aliases: map[string]status.AliasReading{
+ "shop.example.com": {Route: "shop.example.com", CertExpiresAt: alertT0.Add(3 * 24 * time.Hour).Unix()}}}
+ ef.heartbeat(t, "box-1", alertT0, expiring)
+ ef.heartbeat(t, "box-2", alertT0, nil)
+ ef.passesTo(t, 0, 5*time.Minute)
+ if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents WHERE closed_at IS NULL AND rule = 'cert_expiring'`); n != 1 {
+ t.Fatalf("%d open cert_expiring incidents, want 1", n)
+ }
+ putAlertBody(t, ef.rel, "status/boxes/box-1.json", []byte("{not json"))
+ ef.passesTo(t, 6*time.Minute, 10*time.Minute)
+ ef.openAndQuiet(t, "cert_expiring")
}
// An alert object that does not parse is stepped over: the box beside it
diff --git a/internal/console/alertsignals.go b/internal/console/alertsignals.go
index fba8ab90c..44114300a 100644
--- a/internal/console/alertsignals.go
+++ b/internal/console/alertsignals.go
@@ -40,9 +40,11 @@ const (
// their size is trusted.
engineBoxKeys = 200
engineBoxBodyBytes = 1 << 20
- // engineListingHorizon drops heartbeat objects not written for a day
- // before any read, as status.LoadBoxes does: a replaced box's report
- // leaves the listing, and its incidents close as gone.
+ // engineListingHorizon puts heartbeat objects not written for a day
+ // after the current ones, so they cannot crowd current reports out of
+ // the key cap (status.LoadBoxes drops them; the engine keeps them,
+ // because a dead box stays a box_silent member until its object is
+ // removed, ruling R-23).
engineListingHorizon = 24 * time.Hour
)
@@ -112,14 +114,15 @@ func (r *engineReads) forget(prefix string, keys []string) {
}
}
-// boxes lists status/boxes/ and reads each object, decoding as
-// status.LoadBoxes does: an object that cannot be read, is over the size
-// cap or does not parse is logged and skipped, and keys past the cap are
-// not read. Each box's Label is its key's, the name the engine keys its
-// heartbeat signals on. listedBoxes and unreadBoxes record what the listing
-// held and what of it could not be read.
-func (r *engineReads) boxes(ctx context.Context, store release.Store) ([]status.Box, error) {
- keys, err := engineBoxKeyList(ctx, store)
+// boxes lists status/boxes/ and reads each object conditionally, decoding
+// as status.LoadBoxes does: an object that cannot be read, is over the size
+// cap or does not parse is logged, fails the run and is skipped, and keys
+// past the cap are not read. Every listed box is a member, however old its
+// object: an unchanged old heartbeat costs a 304. Each box's Label is its
+// key's, the name the engine keys its heartbeat signals on. listedBoxes and
+// unreadBoxes record what the listing held and what of it could not be read.
+func (r *engineReads) boxes(ctx context.Context, store release.Store, now time.Time) ([]status.Box, error) {
+ keys, err := engineBoxKeyList(ctx, store, now)
if err != nil {
return nil, err
}
@@ -138,18 +141,18 @@ func (r *engineReads) boxes(ctx context.Context, store release.Store) ([]status.
}
body, _, err := r.get(ctx, store, key)
if err != nil {
- log.Printf("console: alert engine: skipping %s: read failed: %v", key, err)
+ alertReadFailed(ctx, fmt.Errorf("read %s: %w", key, err))
r.unreadBoxes[label] = true
continue
}
var b status.Box
if len(body) > engineBoxBodyBytes {
- log.Printf("console: alert engine: skipping %s: body %d bytes exceeds %d", key, len(body), engineBoxBodyBytes)
+ alertReadFailed(ctx, fmt.Errorf("%s: body %d bytes exceeds %d", key, len(body), engineBoxBodyBytes))
r.unreadBoxes[label] = true
continue
}
if err := json.Unmarshal(body, &b); err != nil {
- log.Printf("console: alert engine: skipping %s: corrupt snapshot: %v", key, err)
+ alertReadFailed(ctx, fmt.Errorf("corrupt %s: %w", key, err))
r.unreadBoxes[label] = true
continue
}
@@ -162,10 +165,11 @@ func (r *engineReads) boxes(ctx context.Context, store release.Store) ([]status.
return boxes, nil
}
-// engineBoxKeyList is one listing of status/boxes/ without the objects the
-// horizon drops, as status.LoadBoxes lists it. A store that cannot say when
-// an object was written is listed whole.
-func engineBoxKeyList(ctx context.Context, store release.Store) ([]string, error) {
+// engineBoxKeyList is one listing of status/boxes/, every key, with the
+// objects written within the horizon of now first so the key cap reads
+// current reports before old ones. A store that cannot say when an object
+// was written is listed in its own order.
+func engineBoxKeyList(ctx context.Context, store release.Store, now time.Time) ([]string, error) {
ml, ok := store.(release.ModLister)
if !ok {
return store.List(ctx, alertStatusBoxesPrefix)
@@ -174,14 +178,16 @@ func engineBoxKeyList(ctx context.Context, store release.Store) ([]string, error
if err != nil {
return store.List(ctx, alertStatusBoxesPrefix)
}
- cut := time.Now().Add(-engineListingHorizon)
- keys := make([]string, 0, len(mods))
+ cut := now.Add(-engineListingHorizon)
+ var current, old []string
for _, m := range mods {
if m.Mod.IsZero() || !m.Mod.Before(cut) {
- keys = append(keys, m.Key)
+ current = append(current, m.Key)
+ } else {
+ old = append(old, m.Key)
}
}
- return keys, nil
+ return append(current, old...), nil
}
// fleet reads status/fleet.json conditionally. No object is a fleet that
@@ -301,26 +307,23 @@ func (s *Server) boxAlertSignals(ctx context.Context, sig *alertSignals) (boxAle
if !strings.HasSuffix(key, ".json") {
continue
}
- name := strings.TrimSuffix(strings.TrimPrefix(key, alertPrefix), ".json")
+ // The key names the box: it is what the publisher's own AlertKey
+ // produced. Unknown boxes and members are tracked by this one name.
+ box := strings.TrimSuffix(strings.TrimPrefix(key, alertPrefix), ".json")
body, _, err := r.get(ctx, s.cfg.Releases, key)
if err != nil {
- log.Printf("console: alert engine: read %s: %v", key, err)
- jobFailed(ctx, fmt.Errorf("read %s: %w", key, err))
- got.unread[name] = true
+ alertReadFailed(ctx, fmt.Errorf("read %s: %w", key, err))
+ got.unread[box] = true
continue
}
var st metrics.AlertState
if err := json.Unmarshal(body, &st); err != nil {
- log.Printf("console: alert engine: unparsable %s: %v", key, err)
- jobFailed(ctx, fmt.Errorf("unparsable %s: %w", key, err))
- got.unread[name] = true
+ alertReadFailed(ctx, fmt.Errorf("unparsable %s: %w", key, err))
+ got.unread[box] = true
continue
}
- box := st.Box
- if box == "" {
- // Trust the key over an empty body field: the key is what the
- // publisher's own AlertKey produced.
- box = name
+ if st.Box != "" && st.Box != box {
+ log.Printf("console: alert engine: %s says it is box %q; using the key's name", key, st.Box)
}
got.states[box] = st
for rule, rs := range st.Rules {
@@ -344,20 +347,28 @@ func (s *Server) boxAlertSignals(ctx context.Context, sig *alertSignals) (boxAle
// nothing.
func (s *Server) heartbeatSignals(ctx context.Context, settings map[string]alertRuleSetting, now time.Time, sig *alertSignals) {
r := &s.alertEngine.reads
- if boxes, err := r.boxes(ctx, s.cfg.Releases); err != nil {
- log.Printf("console: alert engine: list %s: %v", alertStatusBoxesPrefix, err)
- jobFailed(ctx, fmt.Errorf("list %s: %w", alertStatusBoxesPrefix, err))
+ if boxes, err := r.boxes(ctx, s.cfg.Releases, now); err != nil {
+ alertReadFailed(ctx, fmt.Errorf("list %s: %w", alertStatusBoxesPrefix, err))
} else {
heartbeatBoxSignals(boxes, r.unreadBoxes, settings, now, sig)
}
if f, err := r.fleet(ctx, s.cfg.Releases); err != nil {
- log.Printf("console: alert engine: read %s: %v", alertFleetKey, err)
- jobFailed(ctx, fmt.Errorf("read %s: %w", alertFleetKey, err))
+ alertReadFailed(ctx, fmt.Errorf("read %s: %w", alertFleetKey, err))
} else {
serviceSignals(f, now, sig)
}
}
+// alertReadFailed logs one source's failed read and fails the run, unless
+// the run is being cancelled: shutdown is not a source failing.
+func alertReadFailed(ctx context.Context, err error) {
+ if ctx.Err() != nil {
+ return
+ }
+ log.Printf("console: alert engine: %v", err)
+ jobFailed(ctx, err)
+}
+
// heartbeatBoxSignals adds, for each box with a heartbeat object, box_silent
// (Review Focus 3: every box with an object is a member, whether or not it
// ever fired anything) and alert_delivery_broken, and cert_expiring for
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 208aa3ff2..3a6cf01e6 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -2171,7 +2171,7 @@ var claimFixtures = map[string]claimFixture{
"worker StartLifetimesCutoverWatch": claimRead("off on a host-claim console, where lifetimes are not for it: it logs that and reads nothing"),
"worker StartLifetimeRecoveryPass": claimRead("off on a host-claim console, where lifetimes are not for it: it logs that and reads nothing"),
"worker StartIncarnationMigrationPass": claimRead("off on a host-claim console, where lifetimes are not for it: it logs that and reads nothing"),
- "worker StartAlertEngine": claimRead("off on a host-claim console, one console per deployment runs it (fleet alerts spec §5.2): it records the refusal in its job status and reads and writes nothing"),
+ "worker StartAlertEngine": claimRead("off on a host-claim console, one console per deployment runs it (fleet alerts spec §5.2): it logs that and reads and writes nothing"),
"worker StartEconomicsPass": claimNonApp("daily usage census, statements and bills: deployment and account economics"),
"worker StartGeoipJobs": claimNonApp("GeoIP orphan sweep, D1 expiry and feed status under control/geoip/: the platform database, no app"),
"worker StartHostReports": claimNonApp("this console's census report (status/consoles) and roster activation release"),
diff --git a/internal/console/claim_invariant_probes_worker_test.go b/internal/console/claim_invariant_probes_worker_test.go
index 86ec2d0cb..6d2a7cb01 100644
--- a/internal/console/claim_invariant_probes_worker_test.go
+++ b/internal/console/claim_invariant_probes_worker_test.go
@@ -104,11 +104,11 @@ var claimWorkerProbes = map[string]claimProbe{
},
},
"worker StartAlertEngine": {
- // The world is a host-claim console, so the engine refuses (R2 #2).
- // One box with a disk alert firing and an operator: an engine that
- // did not refuse would read them and write alert_* rows. Successful
- // incident creation is pinned off host-claim in
- // alertengine_pass_test.go.
+ // The world is a host-claim console, so the engine is off (R2 #2,
+ // R-23). One box with a disk alert firing: an engine that ran would
+ // read it and write alert_* rows. Successful incident creation is
+ // pinned off host-claim in alertengine_pass_test.go.
+ serial: "captures the process-wide log output (captureLogTo): another case's log lines would land in its answer",
setup: func(t *testing.T, cx *claimCase) {
now := time.Now().UTC()
state := metrics.AlertState{V: 1, Box: "box1", UpdatedAt: now,
@@ -121,23 +121,29 @@ var claimWorkerProbes = map[string]claimProbe{
t.Fatal(err)
}
},
- // The reply is the job's status, and its count of the store calls
- // the worker made, through a counting store swapped in for the run
- // (after quiesce, so nothing else is reading cfg.Releases).
+ // The reply is what the worker logged and its count of store calls,
+ // through a counting store swapped in for the run (after quiesce, so
+ // nothing else is reading cfg.Releases).
do: func(t *testing.T, cx *claimCase) claimReply {
+ claimMustRunAlone(t, "worker StartAlertEngine")
counting := &claimCountingStore{Store: cx.srv.cfg.Releases}
cx.srv.cfg.Releases = counting
+ var logs strings.Builder
+ restore := captureLogTo(&logs)
reply := claimWorkerReply("StartAlertEngine")(t, cx)
+ restore()
cx.srv.cfg.Releases = counting.Store
- st, _ := jobStatusOf(cx.srv, "StartAlertEngine")
- reply.Body = fmt.Sprintf("%s; store calls %d", st.Err, counting.calls.Load())
+ reply.Body = fmt.Sprintf("%s; store calls %d", logs.String(), counting.calls.Load())
return reply
},
- body: []string{"refused: host-claim console; store calls 0"},
+ body: []string{"alert engine: off on a host-claim console", "; store calls 0"},
effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ if st, ok := jobStatusOf(cx.srv, "StartAlertEngine"); ok {
+ return fmt.Sprintf("the job is still listed (%+v): an off worker drops off the list", st)
+ }
for _, table := range []string{"alert_connectors", "alert_incidents", "alert_fires", "alert_outbox", "alert_meta"} {
if n := cx.sqlCount(t, "SELECT COUNT(*) FROM "+table); n != 0 {
- return fmt.Sprintf("the refused engine wrote %d %s rows", n, table)
+ return fmt.Sprintf("the engine wrote %d %s rows", n, table)
}
}
return ""
diff --git a/internal/console/jobs.go b/internal/console/jobs.go
index d06a05d1d..0b6bf18e3 100644
--- a/internal/console/jobs.go
+++ b/internal/console/jobs.go
@@ -40,7 +40,9 @@ const (
)
// JobStatus is one job as the registry last saw it. LastRan is when the
-// last run finished; Err is that run's error, "" when it succeeded.
+// last run finished; Err is that run's error, "" when it succeeded. Note is
+// what a run that succeeded still had to say (jobNoteOn): a condition the
+// job works around rather than a failure of it.
//
// Runs is how many runs have finished since the console started. Calls is
// every outbound request the job's runs made since then, by span name
@@ -52,6 +54,7 @@ type JobStatus struct {
State JobState
LastRan time.Time
Err string
+ Note string
Runs int64
Calls map[string]int64
RunCalls map[string]int64
@@ -129,8 +132,9 @@ func (j *jobRegistry) exited(name string) {
// pass may fan out (the mail push sends per app in parallel), hence the
// lock.
type jobRun struct {
- mu sync.Mutex
- err error
+ mu sync.Mutex
+ err error
+ note []string
reg *jobRegistry
name string
@@ -198,6 +202,7 @@ func (j *jobRegistry) Run(ctx context.Context, name string, pass func(context.Co
}
run.finished = true
calls := run.calls
+ note := strings.Join(run.note, "; ")
run.mu.Unlock()
j.mu.Lock()
e = j.entry(name)
@@ -211,6 +216,7 @@ func (j *jobRegistry) Run(ctx context.Context, name string, pass func(context.Co
e.status.RunCalls[k] += n
}
e.status.LastRan = j.now()
+ e.status.Note = note
if recorded != nil {
e.status.State = JobFailed
e.status.Err = recorded.Error()
@@ -251,6 +257,23 @@ func jobFailed(ctx context.Context, err error) {
run.mu.Unlock()
}
+// jobNoteOn adds note to the run ctx carries: shown with a run that
+// succeeded, for a condition the pass works around and reports elsewhere
+// (the alert engine's unusable seal key, which seal_key alerts on). A no-op
+// with no run on ctx.
+func jobNoteOn(ctx context.Context, note string) {
+ if note == "" || ctx == nil {
+ return
+ }
+ run, ok := ctx.Value(jobRunKey{}).(*jobRun)
+ if !ok || run == nil {
+ return
+ }
+ run.mu.Lock()
+ run.note = append(run.note, note)
+ run.mu.Unlock()
+}
+
// Snapshot is every configured job, sorted by name.
// A nil registry has none.
func (j *jobRegistry) Snapshot() []JobStatus {
@@ -314,7 +337,7 @@ const jobNoteRunes = 160
// opJobRow is op_jobs's data: one job's label, status pill, last finish,
// its S3 requests since the console started and per finished run, and the
-// first line of its last error.
+// first line of its last error, or of a successful run's note.
type opJobRow struct {
Label string
Status opPill
@@ -343,6 +366,7 @@ func opJobRows(snap []JobStatus) []opJobRow {
switch st.State {
case JobOK:
row.Status = opPill{Label: jobWordOK, Tone: "positive"}
+ row.Note = jobNote(st.Note)
case JobFailed:
row.Status = opPill{Label: jobWordFailed, Tone: "negative"}
row.Note = jobNote(st.Err)
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go
index 42d176a9b..4d957877f 100644
--- a/internal/console/jobs_test.go
+++ b/internal/console/jobs_test.go
@@ -31,10 +31,11 @@ import (
// unchanged). Not listed: deliver, which returns every failure it logs
// (its fallback lines are not failures); audit and auditActivity, which take
// no ctx and are called from some 180 sites; domainHostPolicy's account
-// lookup, which fails closed and takes no ctx.
+// lookup, which fails closed and takes no ctx; openAlertSeal, whose unusable
+// key is a job note rather than a failure (ruling R-21).
var jobPassFuncs = map[string][]string{
"StartHostReports": {"localHostReport", "putHostReport"},
- "StartAlertEngine": {"alertEnginePass", "alertEngineStep", "boxAlertSignals", "heartbeatSignals", "openAlertSeal",
+ "StartAlertEngine": {"alertEnginePass", "alertEngineStep", "boxAlertSignals", "heartbeatSignals", "alertReadFailed",
"alertSnoozed", "alertEmitRows", "noteUnreachableOperators", "writeAlertEngineBeat"},
"StartGeoipJobs": {"geoipPass"},
"PublishMovesConsole": {"PublishMovesConsole"},