alerts: restore drill rules verify_failed, _unverified, _coverage (#898)
The agent reads the drill's local copy of its record (dbverify.LocalPath, <data>/monitor/verify.json) each tick through metrics.ReadVerify. Evaluate raises verify_failed@<host> on a failed verdict, verify_unverified@<host> once the record's streak reaches 3 (not_reached, no_assignment and no_record hold it), and verify_coverage while any host's last decided verdict, or its first sighting, is more than 7 days old. No copy is no reading; an unreadable one holds. verify_unverified carries its reason as its value, an index into alerting.VerifyReasons, which holds the approved reason labels beside BoxRuleText. The console adds the label as its own line after the what line. Levels: verify_failed incident (as restarts), the other two warning (as disk_eta and geoip). Task 0 folded in: the approved copy record docs/superpowers/plans/member-backups-slice2a-copy.json (25 strings, Paul 2026-11-11) and TestApprovedMemberBackups2aCopy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
approved_member_backups_2a_copy_test.go+67 −0docs/superpowers/plans/member-backups-slice2a-copy.json+31 −0internal/alerting/alerting_test.go+32 −0internal/alerting/ruletext.go+65 −0internal/console/alertdetail_test.go+52 −0internal/console/alertengine_pass.go+16 −0internal/console/alertnotify.go+22 −0internal/console/alertpages.go+8 −0internal/console/alertpages_test.go+27 −0internal/console/alertsignals.go+3 −0internal/dbverify/dbverify.go+9 −0internal/host/metrics_loop.go+27 −1internal/host/verifyalert_test.go+79 −0internal/metrics/alert.go+9 −1internal/metrics/verify.go+172 −0internal/metrics/verify_test.go+241 −0internal/ops/ops.go+1 −1
Intent
<task-notification> <task-id>acbf56ea0ec4fbd9c</task-id> <tool-use-id>toolu_011XRW4z4gJ8dTjPgmYDcbXM</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/acbf56ea0ec4fbd9c.output</output-file> <status>completed</status> <summary>Agent "Implement slice 2a Task 7" 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. Task 4 had already wired the hook and fixed every stub the brief lists, so this change adds only a test and no production code. Commit: 86eb0563, "host: test that landing clears only this box's verify record" (not pushed). Tests: the new test is `TestLandingRemovesHostFromOwnVerifyRecord`, which lands through production's hook from `armPhase1`. - **RED:** two temporary changes to the wiring each made it fail. A no-op hook left the host in `control/verify/uk-box.json`. Clearing the host from every record changed the bytes of `ie-box.json`. I restored the file before committing. - **GREEN:** `-run 'Landing|MovesLand|MovesInstall|MovesCut'` passes (75s); gofmt, `go vet` and `go build ./...` are clean. Concerns: - The test stops the landing just after the verify step, because the full landing test is skipped (parked secret flow). - Minor: the hook reads `cfg.Box` when it runs, not when it is set up. That is correct today, but if anything later reassigned `cfg.Box`, the hook would silently clear a different record. I left it alone rather than churn Task 4's code. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups-2a/.superpowers/sdd/2026-11-11-member-backups-slice2a/task-7-report.md</result> <usage><subagent_tokens>80299</subagent_tokens><tool_uses>23</tool_uses><duration_ms>335649</duration_ms></usage> </task-notification>
This needs a UX pass so that it's much more clear and dashboardy. Can we update AGENTS.md that any UI updates need a UX pass to make sure they're presentable and make the user not have to think too much or read too much before being able to understand what a screen is showing.
Attributed to this commit: 51.1 g CO₂e (6,571,078 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on member-backups-2a, 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/approved_member_backups_2a_copy_test.go b/approved_member_backups_2a_copy_test.go| new file mode 100644 |
| index 000000000..3cb0f2fb9 |
| --- /dev/null |
| +++ b/approved_member_backups_2a_copy_test.go |
| @@ -0,0 +1,67 @@ |
| +package main |
| + |
| +import ( |
| + "encoding/json" |
| + "os" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/alerting" |
| +) |
| + |
| +// memberBackups2aCopyRecordPath is the copy record of member backups slice |
| +// 2a: the restore drill's operator alerts, approved by Paul on 2026-11-11. |
| +const memberBackups2aCopyRecordPath = "docs/superpowers/plans/member-backups-slice2a-copy.json" |
| + |
| +// memberBackups2aCopyIDs is the record's inventory, pinned as a literal: a |
| +// record that loses an entry fails here even though every entry left in it |
| +// is applied. |
| +var memberBackups2aCopyIDs = []string{ |
| + "rule.verify_failed.title", "rule.verify_failed.what", "rule.verify_failed.what.none", |
| + "rule.verify_failed.how_long", "rule.verify_failed.what_to_do", |
| + "rule.verify_unverified.title", "rule.verify_unverified.what", "rule.verify_unverified.what.none", |
| + "rule.verify_unverified.how_long", "rule.verify_unverified.what_to_do", |
| + "rule.verify_coverage.title", "rule.verify_coverage.what", "rule.verify_coverage.what.none", |
| + "rule.verify_coverage.how_long", "rule.verify_coverage.what_to_do", |
| + "verify.reason.record_changed", "verify.reason.moving", "verify.reason.not_reached", |
| + "verify.reason.nothing_replicated", "verify.reason.no_assignment", "verify.reason.restore_error", |
| + "verify.reason.stale", "verify.reason.plan_moved", "verify.reason.record_unreadable", |
| + "verify.reason.no_record", |
| +} |
| + |
| +// Every approved string is in the file the record names, byte for byte, and |
| +// each reason label is the one alerting.VerifyReasons gives its own code, so |
| +// a label cannot sit beside the wrong reason. |
| +func TestApprovedMemberBackups2aCopy(t *testing.T) { |
| + raw, err := os.ReadFile(memberBackups2aCopyRecordPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + checkApprovedCopy(t, raw, ".", memberBackups2aCopyIDs, nil) |
| + |
| + var rec struct{ Entries []struct{ ID, Text string } } |
| + if err := json.Unmarshal(raw, &rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + labels := map[string]string{} |
| + for _, r := range alerting.VerifyReasons { |
| + labels[r.Code] = r.Label |
| + } |
| + reasons := 0 |
| + for _, e := range rec.Entries { |
| + code, ok := strings.CutPrefix(e.ID, "verify.reason.") |
| + if !ok { |
| + continue |
| + } |
| + reasons++ |
| + if labels[code] != e.Text { |
| + t.Errorf("%s: alerting.VerifyReasons gives %q, want %q", e.ID, labels[code], e.Text) |
| + } |
| + if strings.ContainsAny(e.Text, "—–") { |
| + t.Errorf("%s has an em or en dash", e.ID) |
| + } |
| + } |
| + if reasons != len(alerting.VerifyReasons) { |
| + t.Errorf("the record has %d reasons, alerting.VerifyReasons %d", reasons, len(alerting.VerifyReasons)) |
| + } |
| +} |
diff --git a/docs/superpowers/plans/member-backups-slice2a-copy.json b/docs/superpowers/plans/member-backups-slice2a-copy.json| new file mode 100644 |
| index 000000000..52ca93ac8 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/member-backups-slice2a-copy.json |
| @@ -0,0 +1,31 @@ |
| +{ |
| + "approved_by": "Paul", |
| + "approved_on": "2026-11-11", |
| + "entries": [ |
| + {"id": "rule.verify_failed.title", "file": "internal/alerting/ruletext.go", "text": "Restore test failed"}, |
| + {"id": "rule.verify_failed.what", "file": "internal/console/alertnotify.go", "text": "A restore test of an instance's copy failed on %s."}, |
| + {"id": "rule.verify_failed.what.none", "file": "internal/console/alertnotify.go", "text": "A restore test of an instance's copy failed."}, |
| + {"id": "rule.verify_failed.how_long", "file": "internal/alerting/ruletext.go", "text": "The live instance is not affected, but its copy may not restore if it's needed."}, |
| + {"id": "rule.verify_failed.what_to_do", "file": "internal/alerting/ruletext.go", "text": "Read the drill's journal on that box, then restore the copy by hand with carlos db pull to see what fails."}, |
| + {"id": "rule.verify_unverified.title", "file": "internal/alerting/ruletext.go", "text": "Restore test not running"}, |
| + {"id": "rule.verify_unverified.what", "file": "internal/console/alertnotify.go", "text": "%s couldn't test an instance's copy three nights in a row."}, |
| + {"id": "rule.verify_unverified.what.none", "file": "internal/console/alertnotify.go", "text": "An instance's copy couldn't be tested three nights in a row."}, |
| + {"id": "rule.verify_unverified.how_long", "file": "internal/alerting/ruletext.go", "text": "Nothing is down, but nobody knows whether this copy would restore."}, |
| + {"id": "rule.verify_unverified.what_to_do", "file": "internal/alerting/ruletext.go", "text": "Check the reason below. If the instance is moving or was just recreated, it clears on its own."}, |
| + {"id": "rule.verify_coverage.title", "file": "internal/alerting/ruletext.go", "text": "Restore tests behind"}, |
| + {"id": "rule.verify_coverage.what", "file": "internal/console/alertnotify.go", "text": "Some instances on %s haven't had a restore test for more than 7 days."}, |
| + {"id": "rule.verify_coverage.what.none", "file": "internal/console/alertnotify.go", "text": "Some instances haven't had a restore test for more than 7 days."}, |
| + {"id": "rule.verify_coverage.how_long", "file": "internal/alerting/ruletext.go", "text": "Nothing is down. Owners see an old test date until it catches up."}, |
| + {"id": "rule.verify_coverage.what_to_do", "file": "internal/alerting/ruletext.go", "text": "Give the nightly run more time on that box, or spread its instances over more boxes."}, |
| + {"id": "verify.reason.record_changed", "file": "internal/alerting/ruletext.go", "text": "the instance was deleted or recreated during the test"}, |
| + {"id": "verify.reason.moving", "file": "internal/alerting/ruletext.go", "text": "the instance was moving to another box"}, |
| + {"id": "verify.reason.not_reached", "file": "internal/alerting/ruletext.go", "text": "the night's run ran out of time before reaching it"}, |
| + {"id": "verify.reason.nothing_replicated", "file": "internal/alerting/ruletext.go", "text": "nothing has been copied yet"}, |
| + {"id": "verify.reason.no_assignment", "file": "internal/alerting/ruletext.go", "text": "no box was given this instance to test"}, |
| + {"id": "verify.reason.restore_error", "file": "internal/alerting/ruletext.go", "text": "the copy couldn't be restored"}, |
| + {"id": "verify.reason.stale", "file": "internal/alerting/ruletext.go", "text": "the copy is behind the live database"}, |
| + {"id": "verify.reason.plan_moved", "file": "internal/alerting/ruletext.go", "text": "the copy was tidied up while the test was starting, on both tries"}, |
| + {"id": "verify.reason.record_unreadable", "file": "internal/alerting/ruletext.go", "text": "the instance's details couldn't be read"}, |
| + {"id": "verify.reason.no_record", "file": "internal/alerting/ruletext.go", "text": "there's no instance record for it"} |
| + ] |
| +} |
diff --git a/internal/alerting/alerting_test.go b/internal/alerting/alerting_test.go| index d738e2cc6..11a08d5c4 100644 |
| --- a/internal/alerting/alerting_test.go |
| +++ b/internal/alerting/alerting_test.go |
| @@ -401,3 +401,35 @@ func TestPostJSONErrorsCarryNoURL(t *testing.T) { |
| t.Fatalf("page: %v", err) |
| } |
| } |
| + |
| +// Every restore-test reason has a label and a value that maps back to it; |
| +// an unknown code, or a value no reason has, has neither. |
| +func TestVerifyReasonValuesRoundTrip(t *testing.T) { |
| + seen := map[float64]bool{} |
| + for _, r := range VerifyReasons { |
| + v := VerifyReasonValue(r.Code) |
| + if v < 1 || seen[v] { |
| + t.Errorf("%s: value %v", r.Code, v) |
| + } |
| + seen[v] = true |
| + if l, ok := VerifyReasonLabel(v); !ok || l != r.Label || l == "" { |
| + t.Errorf("%s: label %q %v", r.Code, l, ok) |
| + } |
| + } |
| + if len(VerifyReasons) != 10 { |
| + t.Errorf("%d reasons, want the 10 approved", len(VerifyReasons)) |
| + } |
| + if v := VerifyReasonValue("no_such_reason"); v != 0 { |
| + t.Errorf("unknown code = %v, want 0", v) |
| + } |
| + for _, v := range []float64{0, -1, 1.5, float64(len(VerifyReasons) + 1)} { |
| + if l, ok := VerifyReasonLabel(v); ok { |
| + t.Errorf("value %v has label %q", v, l) |
| + } |
| + } |
| + for _, rule := range []string{"verify_failed", "verify_unverified", "verify_coverage"} { |
| + if tx := BoxRuleText[rule]; tx.Title == "" || tx.HowLong == "" || tx.WhatToDo == "" { |
| + t.Errorf("%s has no rule text: %+v", rule, tx) |
| + } |
| + } |
| +} |
diff --git a/internal/alerting/ruletext.go b/internal/alerting/ruletext.go| index 58a838dd6..2ff82ca4b 100644 |
| --- a/internal/alerting/ruletext.go |
| +++ b/internal/alerting/ruletext.go |
| @@ -67,4 +67,69 @@ var BoxRuleText = map[string]RuleText{ |
| HowLong: "The service may be down or unreliable after repeated restarts.", |
| WhatToDo: "Read the service's journal on that box to find out why it restarted repeatedly.", |
| }, |
| + // The nightly restore drill's three rules (member backups slice 2a, |
| + // approved 2026-11-11, docs/superpowers/plans/member-backups-slice2a-copy.json). |
| + // verify_failed and verify_unverified are per host, reported as |
| + // "verify_failed@<host>"; verify_coverage is one per box. |
| + "verify_failed": { |
| + Title: "Restore test failed", |
| + HowLong: "The live instance is not affected, but its copy may not restore if it's needed.", |
| + WhatToDo: "Read the drill's journal on that box, then restore the copy by hand with carlos db pull to see what fails.", |
| + }, |
| + "verify_unverified": { |
| + Title: "Restore test not running", |
| + HowLong: "Nothing is down, but nobody knows whether this copy would restore.", |
| + WhatToDo: "Check the reason below. If the instance is moving or was just recreated, it clears on its own.", |
| + }, |
| + "verify_coverage": { |
| + Title: "Restore tests behind", |
| + HowLong: "Nothing is down. Owners see an old test date until it catches up.", |
| + WhatToDo: "Give the nightly run more time on that box, or spread its instances over more boxes.", |
| + }, |
| +} |
| + |
| +// VerifyReason is one reason code a restore test's verdict carries |
| +// (dbverify.Verdict.Reason) and the words for it. |
| +type VerifyReason struct { |
| + Code string |
| + Label string |
| +} |
| + |
| +// VerifyReasons are the restore drill's reason codes and their labels, in |
| +// the order that numbers them: a verify_unverified alert carries its reason |
| +// as its value, the reason's place here counted from 1, because a box rule's |
| +// value is a number. Append only: a console reads the number a box of any |
| +// version wrote. |
| +var VerifyReasons = []VerifyReason{ |
| + {"record_changed", "the instance was deleted or recreated during the test"}, |
| + {"moving", "the instance was moving to another box"}, |
| + {"not_reached", "the night's run ran out of time before reaching it"}, |
| + {"nothing_replicated", "nothing has been copied yet"}, |
| + {"no_assignment", "no box was given this instance to test"}, |
| + {"restore_error", "the copy couldn't be restored"}, |
| + {"stale", "the copy is behind the live database"}, |
| + {"plan_moved", "the copy was tidied up while the test was starting, on both tries"}, |
| + {"record_unreadable", "the instance's details couldn't be read"}, |
| + {"no_record", "there's no instance record for it"}, |
| +} |
| + |
| +// VerifyReasonValue is code's alert value, 0 for a code VerifyReasons does |
| +// not have. |
| +func VerifyReasonValue(code string) float64 { |
| + for i, r := range VerifyReasons { |
| + if r.Code == code { |
| + return float64(i + 1) |
| + } |
| + } |
| + return 0 |
| +} |
| + |
| +// VerifyReasonLabel is the label of the reason whose alert value is v; |
| +// false for a value no reason has (0, or a newer box's reason). |
| +func VerifyReasonLabel(v float64) (string, bool) { |
| + i := int(v) |
| + if float64(i) != v || i < 1 || i > len(VerifyReasons) { |
| + return "", false |
| + } |
| + return VerifyReasons[i-1].Label, true |
| } |
diff --git a/internal/console/alertdetail_test.go b/internal/console/alertdetail_test.go| index c2f4f4a2f..001a7036a 100644 |
| --- a/internal/console/alertdetail_test.go |
| +++ b/internal/console/alertdetail_test.go |
| @@ -128,3 +128,55 @@ func TestAlertRestartsRuleRowStatesItsThreshold(t *testing.T) { |
| t.Fatalf("restarts when = %q", v.When) |
| } |
| } |
| + |
| +// TestAlertVerifyRulesWords: the restore drill's per-host rules name the |
| +// host in their title and the box in their what line. verify_unverified's |
| +// message carries its reason's label on its own line after the what line, |
| +// read from the rule's value, and the metrics page shows the label too. An |
| +// unknown reason adds no line. verify_coverage is one per box. |
| +func TestAlertVerifyRulesWords(t *testing.T) { |
| + now := alertT0 |
| + note := func(rule string, value float64) alertNote { |
| + sig := newAlertSignals() |
| + sig.add(alertSignal{Key: alertKey{alertScopeFleet, rule, "box-a"}, Level: alertRuleLevel(rule), Firing: true, Value: value, At: now}) |
| + in := alertIncident{Scope: alertScopeFleet, Rule: rule, Level: alertRuleLevel(rule), Members: []string{"box-a"}, OpenedAt: now} |
| + return alertEmitNote(alertEmit{Incident: in, Kind: alertKindFire}, sig, now) |
| + } |
| + |
| + n := note("verify_failed@shop", 1) |
| + if h := alertHeadline(n); h != "Restore test failed (shop) on box-a" { |
| + t.Errorf("failed headline = %q", h) |
| + } |
| + if n.What != "A restore test of an instance's copy failed on box-a." { |
| + t.Errorf("failed what = %q", n.What) |
| + } |
| + if n.HowLong != alerting.BoxRuleText["verify_failed"].HowLong || n.WhatToDo != alerting.BoxRuleText["verify_failed"].WhatToDo { |
| + t.Errorf("failed lines = %q / %q", n.HowLong, n.WhatToDo) |
| + } |
| + |
| + moving := alerting.VerifyReasonValue("moving") |
| + n = note("verify_unverified@blog", moving) |
| + if h := alertHeadline(n); h != "Restore test not running (blog) on box-a" { |
| + t.Errorf("unverified headline = %q", h) |
| + } |
| + if n.What != "box-a couldn't test an instance's copy three nights in a row.\nthe instance was moving to another box" { |
| + t.Errorf("unverified what = %q", n.What) |
| + } |
| + if _, body := renderEmail(n); !strings.Contains(body, "three nights in a row.\nthe instance was moving to another box\n") { |
| + t.Errorf("email body does not put the reason on its own line:\n%s", body) |
| + } |
| + if got := alertValueText("verify_unverified@blog", moving); got != "the instance was moving to another box" { |
| + t.Errorf("metrics page value = %q", got) |
| + } |
| + if n = note("verify_unverified@blog", 0); n.What != "box-a couldn't test an instance's copy three nights in a row." { |
| + t.Errorf("unknown reason what = %q", n.What) |
| + } |
| + |
| + n = note("verify_coverage", 2) |
| + if h := alertHeadline(n); h != "Restore tests behind on box-a" { |
| + t.Errorf("coverage headline = %q", h) |
| + } |
| + if n.What != "Some instances on box-a haven't had a restore test for more than 7 days." { |
| + t.Errorf("coverage what = %q", n.What) |
| + } |
| +} |
diff --git a/internal/console/alertengine_pass.go b/internal/console/alertengine_pass.go| index 7b12d4776..254cd2672 100644 |
| --- a/internal/console/alertengine_pass.go |
| +++ b/internal/console/alertengine_pass.go |
| @@ -16,6 +16,8 @@ import ( |
| "time" |
| "unicode" |
| "unicode/utf8" |
| + |
| + "github.com/carlosframework/platform/internal/alerting" |
| ) |
| // The alert engine (fleet alerts spec §4, §6): one pass a minute, as the |
| @@ -432,6 +434,14 @@ func alertEmitNote(em alertEmit, sig *alertSignals, now time.Time) alertNote { |
| if v, ok := sig.value(alertKey{in.Scope, in.Rule, n.Subject}); ok && alertValued[alertRuleKind(in.Rule)] && named { |
| n.What += " " + fmt.Sprintf(alertCopy["what.value"], alertValueText(in.Rule, v)) |
| } |
| + // verify_unverified's value is its reason: the label goes on a line of |
| + // its own after the what line. A reason this console has no label for |
| + // (a newer box's) adds nothing. |
| + if v, ok := sig.value(alertKey{in.Scope, in.Rule, n.Subject}); ok && alertRuleKind(in.Rule) == "verify_unverified" && named { |
| + if label, ok := alerting.VerifyReasonLabel(v); ok { |
| + n.What += "\n" + label |
| + } |
| + } |
| switch { |
| case em.Kind == alertKindUpdate && len(em.Joined) > 0: |
| n.What = fmt.Sprintf(alertCopy["update.what"], strings.Join(em.Joined, ", ")) + " " + n.What |
| @@ -751,6 +761,12 @@ func alertValueText(rule string, value float64) string { |
| return fmt.Sprintf("%.0f days left", value) |
| case "restarts": |
| return fmt.Sprintf("%d restarts in 10 minutes", int(value)) |
| + case "verify_unverified": |
| + // A reason, not a measurement (alerting.VerifyReasons). |
| + if label, ok := alerting.VerifyReasonLabel(value); ok { |
| + return label |
| + } |
| + return strconv.FormatFloat(value, 'g', -1, 64) |
| default: |
| return strconv.FormatFloat(value, 'g', -1, 64) |
| } |
diff --git a/internal/console/alertnotify.go b/internal/console/alertnotify.go| index 850a1ec9d..3c85189a3 100644 |
| --- a/internal/console/alertnotify.go |
| +++ b/internal/console/alertnotify.go |
| @@ -202,6 +202,28 @@ var alertCopy = map[string]string{ |
| "rule.restarts.how_long": alerting.BoxRuleText["restarts"].HowLong, |
| "rule.restarts.what_to_do": alerting.BoxRuleText["restarts"].WhatToDo, |
| + // The restore drill's rules (member backups slice 2a). verify_failed |
| + // and verify_unverified are per host: the title names the host, the |
| + // what names the box. verify_unverified's message adds its reason's |
| + // label as a line of its own (alertEmitNote). |
| + "rule.verify_failed.title": alerting.BoxRuleText["verify_failed"].Title, |
| + "rule.verify_failed.what": "A restore test of an instance's copy failed on %s.", |
| + "rule.verify_failed.what.none": "A restore test of an instance's copy failed.", |
| + "rule.verify_failed.how_long": alerting.BoxRuleText["verify_failed"].HowLong, |
| + "rule.verify_failed.what_to_do": alerting.BoxRuleText["verify_failed"].WhatToDo, |
| + |
| + "rule.verify_unverified.title": alerting.BoxRuleText["verify_unverified"].Title, |
| + "rule.verify_unverified.what": "%s couldn't test an instance's copy three nights in a row.", |
| + "rule.verify_unverified.what.none": "An instance's copy couldn't be tested three nights in a row.", |
| + "rule.verify_unverified.how_long": alerting.BoxRuleText["verify_unverified"].HowLong, |
| + "rule.verify_unverified.what_to_do": alerting.BoxRuleText["verify_unverified"].WhatToDo, |
| + |
| + "rule.verify_coverage.title": alerting.BoxRuleText["verify_coverage"].Title, |
| + "rule.verify_coverage.what": "Some instances on %s haven't had a restore test for more than 7 days.", |
| + "rule.verify_coverage.what.none": "Some instances haven't had a restore test for more than 7 days.", |
| + "rule.verify_coverage.how_long": alerting.BoxRuleText["verify_coverage"].HowLong, |
| + "rule.verify_coverage.what_to_do": alerting.BoxRuleText["verify_coverage"].WhatToDo, |
| + |
| "rule.box_silent.title": "Box silent", |
| "rule.box_silent.what": "%s has stopped reporting.", |
| "rule.box_silent.what.none": "A box has stopped reporting.", |
diff --git a/internal/console/alertpages.go b/internal/console/alertpages.go| index 47652e092..b9286cef6 100644 |
| --- a/internal/console/alertpages.go |
| +++ b/internal/console/alertpages.go |
| @@ -183,6 +183,13 @@ var alertPageCopy = map[string]string{ |
| "door.err.gone": "The connector for this link no longer exists.", |
| // derived (Task 10): an unsubscribe or snooze that failed on our side. |
| "door.err.failed": "That did not work. Try the link again in a few minutes.", |
| + |
| + // derived (member backups 2a Task 8): the Rules section's "fires when" |
| + // for the restore drill's rules. The approved copy has no such line, so |
| + // each is its rule's approved subjectless what line. |
| + "rules.when.verify_failed": alertCopy["rule.verify_failed.what.none"], |
| + "rules.when.verify_unverified": alertCopy["rule.verify_unverified.what.none"], |
| + "rules.when.verify_coverage": alertCopy["rule.verify_coverage.what.none"], |
| } |
| // The operator Alerts pages (fleet alerts spec §5, plan 1 Task 10): |
| @@ -213,6 +220,7 @@ const ( |
| // the console's. It names every rule in alertRuleLevels |
| // (TestAlertRuleOrderCoversEveryRule). |
| var alertRuleOrder = []string{"disk_eta", "disk", "mem", "cpu", "lag", "geoip", "engine_silent", "restarts", |
| + "verify_failed", "verify_unverified", "verify_coverage", |
| "box_silent", "service_down", "cert_expiring", "alert_delivery_broken", "seal_key"} |
| // alertThresholdBounds are the editable thresholds' whole-number bounds: |
diff --git a/internal/console/alertpages_test.go b/internal/console/alertpages_test.go| index 5d621bc4a..46744d4ed 100644 |
| --- a/internal/console/alertpages_test.go |
| +++ b/internal/console/alertpages_test.go |
| @@ -12,6 +12,8 @@ import ( |
| "strings" |
| "testing" |
| "time" |
| + |
| + "github.com/carlosframework/platform/internal/alerting" |
| ) |
| // alertsPageFixture is an operator signed in to a console whose alert |
| @@ -907,3 +909,28 @@ func TestFleetAlertsHistoryLimitOnlyWhenHidden(t *testing.T) { |
| t.Fatalf("%d incidents: want the note, %d rows, the oldest hidden", alertHistoryLimit+1, alertHistoryLimit) |
| } |
| } |
| + |
| +// The restore drill's three box rules have a place in the Rules section, |
| +// after restarts, and their levels: a failed restore test is an incident, |
| +// like restarts; a test that is not running or is behind is a warning, |
| +// like disk_eta and geoip. |
| +func TestAlertRuleOrderCoversVerify(t *testing.T) { |
| + i := slices.Index(alertRuleOrder, "restarts") |
| + want := []string{"verify_failed", "verify_unverified", "verify_coverage"} |
| + if i < 0 || len(alertRuleOrder) < i+4 || !slices.Equal(alertRuleOrder[i+1:i+4], want) { |
| + t.Fatalf("alertRuleOrder = %v, want %v after restarts", alertRuleOrder, want) |
| + } |
| + for rule, level := range map[string]string{ |
| + "verify_failed": alerting.LevelIncident, "verify_unverified": alerting.LevelWarning, "verify_coverage": alerting.LevelWarning, |
| + } { |
| + if alertRuleLevels[rule] != level { |
| + t.Errorf("%s level = %q, want %q", rule, alertRuleLevels[rule], level) |
| + } |
| + if alertRuleLevel(rule+"@shop") != level { |
| + t.Errorf("%s@shop level = %q, want the kind's", rule, alertRuleLevel(rule+"@shop")) |
| + } |
| + if alertPageCopy["rules.when."+rule] != alertCopy["rule."+rule+".what.none"] { |
| + t.Errorf("%s: rules.when = %q, want its approved what.none", rule, alertPageCopy["rules.when."+rule]) |
| + } |
| + } |
| +} |
diff --git a/internal/console/alertsignals.go b/internal/console/alertsignals.go| index 7b83b5279..4b00a1f03 100644 |
| --- a/internal/console/alertsignals.go |
| +++ b/internal/console/alertsignals.go |
| @@ -454,6 +454,9 @@ var alertRuleLevels = map[string]string{ |
| "geoip": alerting.LevelWarning, |
| "engine_silent": alerting.LevelIncident, |
| "restarts": alerting.LevelIncident, |
| + "verify_failed": alerting.LevelIncident, |
| + "verify_unverified": alerting.LevelWarning, |
| + "verify_coverage": alerting.LevelWarning, |
| "box_silent": alerting.LevelIncident, |
| "service_down": alerting.LevelIncident, |
| "cert_expiring": alerting.LevelWarning, |
diff --git a/internal/dbverify/dbverify.go b/internal/dbverify/dbverify.go| index 5e53bc3e2..e7574c60d 100644 |
| --- a/internal/dbverify/dbverify.go |
| +++ b/internal/dbverify/dbverify.go |
| @@ -20,6 +20,7 @@ import ( |
| "errors" |
| "fmt" |
| "os" |
| + "path/filepath" |
| "time" |
| "github.com/carlosframework/platform/internal/boxself" |
| @@ -45,6 +46,14 @@ func KeyFor(ref string) string { |
| return keyPrefix + ref + ".json" |
| } |
| +// LocalPath is the box's local copy of its own record, |
| +// <data>/monitor/verify.json, beside the agent's self record. The drill |
| +// writes it whole after each publish; the agent's alert rules read it |
| +// (metrics.ReadVerify). |
| +func LocalPath(dataDir string) string { |
| + return filepath.Join(filepath.Dir(boxself.SelfPath(dataDir)), "verify.json") |
| +} |
| + |
| // The three results. |
| const ( |
| ResultPassed = "passed" |
diff --git a/internal/host/metrics_loop.go b/internal/host/metrics_loop.go| index 3023811df..e05d07f60 100644 |
| --- a/internal/host/metrics_loop.go |
| +++ b/internal/host/metrics_loop.go |
| @@ -19,6 +19,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/alerting" |
| + "github.com/carlosframework/platform/internal/dbverify" |
| "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/status" |
| @@ -543,6 +544,7 @@ func alertTick(ctx context.Context, s release.Store, box string, rules metrics.R |
| LagSecs: nil, // v1: no lag reading feeds the agent loop yet |
| GeoIP: geoIPAlertReading(latest.At), |
| Restarts: extra.restarts, |
| + Verify: extra.verify, |
| } |
| if trend != nil { |
| v, eta := trend.verdict(latest.At) |
| @@ -608,6 +610,29 @@ type alertReadings struct { |
| // (diskAlertFrac). Zero total leaves the configured line. |
| diskTotal uint64 |
| staticTree int64 |
| + // verify is the restore drill's standing, read from its local copy |
| + // each tick (verifyWatch); nil leaves the verify rules as they were. |
| + verify *metrics.VerifyReading |
| +} |
| + |
| +// verifyWatch reads the restore drill's local copy of this box's record |
| +// (dbverify.LocalPath) for the alert rules. A read that fails is logged |
| +// once, not every minute, until it reads again. |
| +type verifyWatch struct { |
| + path string |
| + lastErr string |
| +} |
| + |
| +func (w *verifyWatch) read(at time.Time) *metrics.VerifyReading { |
| + v, err := metrics.ReadVerify(w.path, at) |
| + switch { |
| + case err == nil: |
| + w.lastErr = "" |
| + case err.Error() != w.lastErr: |
| + w.lastErr = err.Error() |
| + log.Printf("agent: restore test record: %v; its alerts hold until it reads", err) |
| + } |
| + return v |
| } |
| // diskAlertFrac is the disk rule's line on a disk of total bytes: the |
| @@ -955,8 +980,9 @@ func metricsLoop(execRoot string, src unitSources, owners func() map[string]metr |
| log.Printf("agent: restart watch: agent runs as root, so the watch is kept in memory only") |
| } |
| restarts := watchFile.load() |
| + verify := &verifyWatch{path: dbverify.LocalPath(dataDir())} |
| restartTick := func(at time.Time) alertReadings { |
| - extra := alertReadings{restarts: restarts.tick(at, probes.restarts())} |
| + extra := alertReadings{restarts: restarts.tick(at, probes.restarts()), verify: verify.read(at)} |
| if _, total, ok := probes.diskBytes(); ok { |
| extra.diskTotal, extra.staticTree = total, largestStaticTree() |
| } |
diff --git a/internal/host/verifyalert_test.go b/internal/host/verifyalert_test.go| new file mode 100644 |
| index 000000000..4d7085e89 |
| --- /dev/null |
| +++ b/internal/host/verifyalert_test.go |
| @@ -0,0 +1,79 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/dbverify" |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The agent reads the drill's local copy where the drill writes it |
| +// (dbverify.LocalPath) and alertTick publishes the verify rules it raises. |
| +// No copy yet is no reading: nothing fires and nothing is published. |
| +func TestAlertTickReadsVerifyRecord(t *testing.T) { |
| + ctx := context.Background() |
| + data := t.TempDir() |
| + s := release.NewDirStore(t.TempDir()) |
| + at := time.Date(2026, 11, 11, 3, 30, 0, 0, time.UTC) |
| + st := &metrics.AlertState{V: 1, Box: "box-a", Rules: map[string]metrics.RuleState{}} |
| + w := &verifyWatch{path: dbverify.LocalPath(data)} |
| + tick := func() { |
| + t.Helper() |
| + if err := alertTick(ctx, s, "box-a", metrics.DefaultRules(), st, metrics.Sample{At: at}, |
| + alertReadings{verify: w.read(at)}, filepath.Join(t.TempDir(), "alerts.json"), nil, nil, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + |
| + tick() |
| + if len(st.Rules) != 0 { |
| + t.Fatalf("no record raised %+v", st.Rules) |
| + } |
| + |
| + rec := &dbverify.Record{V: 2, Box: "box-a", CheckedAt: at, Hosts: map[string]dbverify.Verdict{ |
| + "shop": {Result: dbverify.ResultFailed, Reason: "restore_error", LastDecidedAt: at, FirstSeen: at.Add(-time.Hour)}, |
| + "blog": {Result: dbverify.ResultUnverified, Reason: "moving", UnverifiedRuns: 3, FirstSeen: at.Add(-8 * 24 * time.Hour)}, |
| + }} |
| + body, err := json.Marshal(rec) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.MkdirAll(filepath.Dir(w.path), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(w.path, body, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + tick() |
| + for _, rule := range []string{"verify_failed@shop", "verify_unverified@blog", "verify_coverage"} { |
| + if !st.Rules[rule].Firing { |
| + t.Errorf("%s not firing: %+v", rule, st.Rules) |
| + } |
| + } |
| + pub, _, err := s.Get(ctx, metrics.AlertKey("box-a")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var got metrics.AlertState |
| + if err := json.Unmarshal(pub, &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !got.Rules["verify_failed@shop"].Firing || !got.Rules["verify_coverage"].Firing { |
| + t.Fatalf("published %+v", got.Rules) |
| + } |
| + |
| + // A copy that no longer parses holds the rules. |
| + if err := os.WriteFile(w.path, []byte("{"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + tick() |
| + if !st.Rules["verify_failed@shop"].Firing || w.lastErr == "" { |
| + t.Fatalf("an unreadable copy changed the rules: %+v (err %q)", st.Rules, w.lastErr) |
| + } |
| +} |
diff --git a/internal/metrics/alert.go b/internal/metrics/alert.go| index 6bef2d875..d28256cce 100644 |
| --- a/internal/metrics/alert.go |
| +++ b/internal/metrics/alert.go |
| @@ -124,6 +124,10 @@ type Observation struct { |
| // "the reporter could not ask this tick" and leaves every restarts rule |
| // as it was. A unit missing from a non-nil map is no longer loaded. |
| Restarts map[string]UnitRestarts |
| + // Verify is the box's restore drill standing, read from its local copy |
| + // of its record (ReadVerify). nil is "no reading" and leaves every |
| + // verify rule as it was. |
| + Verify *VerifyReading |
| } |
| // UnitRestarts is one unit's restart reading. |
| @@ -181,7 +185,7 @@ type AlertState struct { |
| V int `json:"v"` // 1 |
| Box string `json:"box"` |
| UpdatedAt time.Time `json:"updated_at"` |
| - Rules map[string]RuleState `json:"rules"` // "disk","mem","cpu","lag","geoip","disk_eta","engine_silent", and "restarts@<unit>" per unit |
| + Rules map[string]RuleState `json:"rules"` // "disk","mem","cpu","lag","geoip","disk_eta","engine_silent","verify_coverage"; "restarts@<unit>" per unit; "verify_failed@<host>", "verify_unverified@<host>" per host |
| } |
| // Event is emitted on a firing or clearing transition — never on every |
| @@ -457,5 +461,9 @@ func Evaluate(r Rules, st AlertState, obs Observation) (AlertState, []Event) { |
| events = append(events, changed...) |
| } |
| + if obs.Verify != nil { |
| + events = append(events, evalVerify(out.Rules, obs.Verify, obs.At, st.Box)...) |
| + } |
| + |
| return out, events |
| } |
diff --git a/internal/metrics/verify.go b/internal/metrics/verify.go| new file mode 100644 |
| index 000000000..ac75079f6 |
| --- /dev/null |
| +++ b/internal/metrics/verify.go |
| @@ -0,0 +1,172 @@ |
| +package metrics |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io/fs" |
| + "os" |
| + "sort" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/alerting" |
| + "github.com/carlosframework/platform/internal/dbverify" |
| +) |
| + |
| +// The restore drill's rules (member backups slice 2a). verify_failed and |
| +// verify_unverified are per host, like restarts; verify_coverage is one per |
| +// box. |
| +const ( |
| + verifyFailedRule = "verify_failed" |
| + verifyUnverifiedRule = "verify_unverified" |
| + verifyCoverageRule = "verify_coverage" |
| +) |
| + |
| +// VerifyUnverifiedRuns is how many unverified runs in a row fire a host's |
| +// verify_unverified rule. The record's streak already leaves out the runs |
| +// that tried nothing (not_reached, no_assignment, no_record). |
| +const VerifyUnverifiedRuns = 3 |
| + |
| +// VerifyBehindAfter is how old a host's last decided verdict (passed or |
| +// failed), or its first sighting if it has none, may be before the box's |
| +// verify_coverage rule fires. |
| +const VerifyBehindAfter = 7 * 24 * time.Hour |
| + |
| +// VerifyReading is one box's restore drill standing as the alert rules read |
| +// it, from the box's local copy of its record. |
| +type VerifyReading struct { |
| + // Box is the record's box reference. |
| + Box string |
| + // Hosts is every host in the record, sorted. |
| + Hosts []string |
| + // Failed is the hosts whose latest verdict is failed, or a result this |
| + // version does not know (never read as fine), sorted. |
| + Failed []string |
| + // UnverifiedStreak and UnverifiedReason are each unverified host's |
| + // streak (dbverify.Verdict.UnverifiedRuns) and its latest reason code. |
| + UnverifiedStreak map[string]int |
| + UnverifiedReason map[string]string |
| + // Behind is the hosts past VerifyBehindAfter, sorted. |
| + Behind []string |
| +} |
| + |
| +// ReadVerify reads the record at path (the drill's local copy, |
| +// dbverify.LocalPath) as it stands at now. A missing file is no reading and |
| +// no error: a box that has never drilled raises nothing. A file that does |
| +// not parse, or is a record version this does not know, is an error and no |
| +// reading, so the rules hold. |
| +func ReadVerify(path string, now time.Time) (*VerifyReading, error) { |
| + body, err := os.ReadFile(path) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + var rec dbverify.Record |
| + if err := json.Unmarshal(body, &rec); err != nil { |
| + return nil, fmt.Errorf("%s: %w", path, err) |
| + } |
| + if rec.V != 2 { |
| + return nil, fmt.Errorf("%s: record version %d, want 2", path, rec.V) |
| + } |
| + v := &VerifyReading{Box: rec.Box, UnverifiedStreak: map[string]int{}, UnverifiedReason: map[string]string{}} |
| + for host, vd := range rec.Hosts { |
| + v.Hosts = append(v.Hosts, host) |
| + switch { |
| + case vd.Unverified(): |
| + v.UnverifiedStreak[host] = vd.UnverifiedRuns |
| + v.UnverifiedReason[host] = vd.Reason |
| + case !vd.OK(): |
| + v.Failed = append(v.Failed, host) |
| + } |
| + since := vd.LastDecidedAt |
| + if since.IsZero() { |
| + since = vd.FirstSeen |
| + } |
| + if !since.IsZero() && now.Sub(since) > VerifyBehindAfter { |
| + v.Behind = append(v.Behind, host) |
| + } |
| + } |
| + sort.Strings(v.Hosts) |
| + sort.Strings(v.Failed) |
| + sort.Strings(v.Behind) |
| + return v, nil |
| +} |
| + |
| +// evalVerify advances the verify rules in rules (Evaluate's fresh map) by |
| +// one reading and returns their transitions, sorted by rule. |
| +// |
| +// verify_failed@<host> fires while the host's latest verdict is failed, and |
| +// verify_unverified@<host> while its streak is VerifyUnverifiedRuns or more; |
| +// each clears when that stops, or when the host leaves the record. A cleared |
| +// rule stays as a quiet key, as restarts' do, so the console reads the |
| +// clear. Unlike a box's units, hosts come and go, so a quiet key whose host |
| +// has left the record is dropped on a later tick, after its clear went out. |
| +// verify_unverified's value is its reason (alerting.VerifyReasonValue). A |
| +// reason that changes while it fires is a firing event with the new value, |
| +// as geoip's is: an event is what publishes the state, so without it the |
| +// console would go on naming the old reason. verify_coverage fires while any |
| +// host is behind, its value how many. |
| +func evalVerify(rules map[string]RuleState, v *VerifyReading, at time.Time, box string) []Event { |
| + present := map[string]bool{} |
| + for _, h := range v.Hosts { |
| + present[h] = true |
| + } |
| + perHost := func(rule string) (host string, ok bool) { |
| + name, host := SplitRule(rule) |
| + return host, host != "" && (name == verifyFailedRule || name == verifyUnverifiedRule) |
| + } |
| + for rule, cur := range rules { |
| + if host, ok := perHost(rule); ok && !cur.Firing && !present[host] { |
| + delete(rules, rule) |
| + } |
| + } |
| + |
| + want := map[string]float64{} |
| + for _, h := range v.Failed { |
| + want[RuleFor(verifyFailedRule, h)] = 1 |
| + } |
| + for h, n := range v.UnverifiedStreak { |
| + if n >= VerifyUnverifiedRuns { |
| + want[RuleFor(verifyUnverifiedRule, h)] = alerting.VerifyReasonValue(v.UnverifiedReason[h]) |
| + } |
| + } |
| + |
| + var changed []Event |
| + for rule, val := range want { |
| + switch cur := rules[rule]; { |
| + case !cur.Firing: |
| + rules[rule] = RuleState{Firing: true, Since: at, FiredAt: at, Value: val} |
| + changed = append(changed, Event{Rule: rule, Firing: true, Value: val, Box: box}) |
| + case cur.Value != val: |
| + // A new reason while firing: the alert stays up, but the event |
| + // gets the new value published, as geoip's does. |
| + cur.Value = val |
| + rules[rule] = cur |
| + changed = append(changed, Event{Rule: rule, Firing: true, Value: val, Box: box}) |
| + } |
| + } |
| + for rule, cur := range rules { |
| + if _, ok := perHost(rule); !ok || !cur.Firing { |
| + continue |
| + } |
| + if _, still := want[rule]; !still { |
| + rules[rule] = RuleState{} |
| + changed = append(changed, Event{Rule: rule, Firing: false, Box: box}) |
| + } |
| + } |
| + |
| + switch behind, cur := len(v.Behind), rules[verifyCoverageRule]; { |
| + case behind > 0 && !cur.Firing: |
| + rules[verifyCoverageRule] = RuleState{Firing: true, Since: at, FiredAt: at, Value: float64(behind)} |
| + changed = append(changed, Event{Rule: verifyCoverageRule, Firing: true, Value: float64(behind), Box: box}) |
| + case behind == 0 && cur.Firing: |
| + rules[verifyCoverageRule] = RuleState{} |
| + changed = append(changed, Event{Rule: verifyCoverageRule, Firing: false, Box: box}) |
| + } |
| + |
| + // Map order is random; the events of one tick are not. |
| + sort.Slice(changed, func(i, j int) bool { return changed[i].Rule < changed[j].Rule }) |
| + return changed |
| +} |
diff --git a/internal/metrics/verify_test.go b/internal/metrics/verify_test.go| new file mode 100644 |
| index 000000000..42a70617a |
| --- /dev/null |
| +++ b/internal/metrics/verify_test.go |
| @@ -0,0 +1,241 @@ |
| +package metrics |
| + |
| +import ( |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/alerting" |
| + "github.com/carlosframework/platform/internal/dbverify" |
| +) |
| + |
| +// writeVerify writes rec where the drill writes its local copy and reads it |
| +// back the way the agent does. |
| +func writeVerify(t *testing.T, rec *dbverify.Record, now time.Time) *VerifyReading { |
| + t.Helper() |
| + path := filepath.Join(t.TempDir(), "verify.json") |
| + body, err := json.Marshal(rec) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(path, body, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + v, err := ReadVerify(path, now) |
| + if err != nil || v == nil { |
| + t.Fatalf("ReadVerify = %+v, %v", v, err) |
| + } |
| + return v |
| +} |
| + |
| +// Each verify rule fires and clears on its own, one rule per host for |
| +// failed and unverified. A nil reading changes nothing, a host that leaves |
| +// the record clears, and its quiet key goes on a later tick. |
| +func TestEvaluateVerifyRules(t *testing.T) { |
| + r := DefaultRules() |
| + t0 := time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC) |
| + failed, unverified := RuleFor("verify_failed", "shop"), RuleFor("verify_unverified", "blog") |
| + st := AlertState{V: 1, Box: "b"} |
| + |
| + st, ev := Evaluate(r, st, Observation{At: t0}) |
| + if len(ev) != 0 || len(st.Rules) != 0 { |
| + t.Fatalf("no reading fired: %v %+v", ev, st.Rules) |
| + } |
| + |
| + st, ev = Evaluate(r, st, Observation{At: t0, Verify: &VerifyReading{ |
| + Box: "b", Hosts: []string{"blog", "shop"}, Failed: []string{"shop"}, |
| + UnverifiedStreak: map[string]int{"blog": 2}, UnverifiedReason: map[string]string{"blog": "plan_moved"}, |
| + }}) |
| + if len(ev) != 1 || ev[0] != (Event{Rule: failed, Firing: true, Value: 1, Box: "b"}) { |
| + t.Fatalf("failed host: %+v", ev) |
| + } |
| + if rs := st.Rules[failed]; !rs.Firing || !rs.FiredAt.Equal(t0) { |
| + t.Fatalf("state after firing: %+v", rs) |
| + } |
| + |
| + // The third unverified run fires, its value naming the reason. |
| + moved := alerting.VerifyReasonValue("plan_moved") |
| + st, ev = Evaluate(r, st, Observation{At: t0.Add(24 * time.Hour), Verify: &VerifyReading{ |
| + Box: "b", Hosts: []string{"blog", "shop"}, Failed: []string{"shop"}, |
| + UnverifiedStreak: map[string]int{"blog": 3}, UnverifiedReason: map[string]string{"blog": "plan_moved"}, |
| + }}) |
| + if len(ev) != 1 || ev[0] != (Event{Rule: unverified, Firing: true, Value: moved, Box: "b"}) { |
| + t.Fatalf("third unverified run: %+v", ev) |
| + } |
| + if l, ok := alerting.VerifyReasonLabel(st.Rules[unverified].Value); !ok || l != "the copy was tidied up while the test was starting, on both tries" { |
| + t.Fatalf("reason label = %q %v", l, ok) |
| + } |
| + |
| + // A new reason while firing keeps the alert up, and is an event with |
| + // the new value so the state carrying it is published; the alert's |
| + // FiredAt stays. The same reason the next night is no event. |
| + movingVal := alerting.VerifyReasonValue("moving") |
| + reading := &VerifyReading{ |
| + Box: "b", Hosts: []string{"blog", "shop"}, Failed: []string{"shop"}, |
| + UnverifiedStreak: map[string]int{"blog": 4}, UnverifiedReason: map[string]string{"blog": "moving"}, |
| + } |
| + st, ev = Evaluate(r, st, Observation{At: t0.Add(48 * time.Hour), Verify: reading}) |
| + if len(ev) != 1 || ev[0] != (Event{Rule: unverified, Firing: true, Value: movingVal, Box: "b"}) { |
| + t.Fatalf("reason changed while firing: %+v", ev) |
| + } |
| + if rs := st.Rules[unverified]; !rs.Firing || rs.Value != movingVal || !rs.FiredAt.Equal(t0.Add(24*time.Hour)) { |
| + t.Fatalf("state after the reason changed: %+v", rs) |
| + } |
| + st, ev = Evaluate(r, st, Observation{At: t0.Add(48*time.Hour + time.Minute), Verify: reading}) |
| + if len(ev) != 0 { |
| + t.Fatalf("same reason again: %+v", ev) |
| + } |
| + |
| + // No reading: both stay up. |
| + st, ev = Evaluate(r, st, Observation{At: t0.Add(49 * time.Hour)}) |
| + if len(ev) != 0 || !st.Rules[failed].Firing || !st.Rules[unverified].Firing { |
| + t.Fatalf("a nil reading changed the rules: %v %+v", ev, st.Rules) |
| + } |
| + |
| + // shop passes, blog leaves the box: both clear, and the keys stay quiet |
| + // so the console reads the clears. |
| + st, ev = Evaluate(r, st, Observation{At: t0.Add(72 * time.Hour), Verify: &VerifyReading{ |
| + Box: "b", Hosts: []string{"shop"}, |
| + }}) |
| + want := []Event{{Rule: failed, Firing: false, Box: "b"}, {Rule: unverified, Firing: false, Box: "b"}} |
| + if !reflect.DeepEqual(ev, want) { |
| + t.Fatalf("clears = %+v, want %+v", ev, want) |
| + } |
| + for _, rule := range []string{failed, unverified} { |
| + if rs, kept := st.Rules[rule]; !kept || rs.Firing { |
| + t.Fatalf("%s after clearing: %+v (kept %v)", rule, rs, kept) |
| + } |
| + } |
| + // A tick later, blog's quiet key goes (it is no longer on the box); |
| + // shop's stays, since shop is. |
| + st, ev = Evaluate(r, st, Observation{At: t0.Add(73 * time.Hour), Verify: &VerifyReading{Box: "b", Hosts: []string{"shop"}}}) |
| + if len(ev) != 0 { |
| + t.Fatalf("a quiet tick emitted: %v", ev) |
| + } |
| + if _, kept := st.Rules[unverified]; kept { |
| + t.Fatalf("a departed host's quiet key stayed: %+v", st.Rules) |
| + } |
| + if _, kept := st.Rules[failed]; !kept { |
| + t.Fatalf("a present host's quiet key went: %+v", st.Rules) |
| + } |
| +} |
| + |
| +// The coverage rule is one per box: it fires while any host is behind and |
| +// clears when none is. |
| +func TestEvaluateVerifyCoverage(t *testing.T) { |
| + r := DefaultRules() |
| + t0 := time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC) |
| + st := AlertState{V: 1, Box: "b"} |
| + st, ev := Evaluate(r, st, Observation{At: t0, Verify: &VerifyReading{Box: "b", Hosts: []string{"a", "c"}, Behind: []string{"a", "c"}}}) |
| + if len(ev) != 1 || ev[0] != (Event{Rule: "verify_coverage", Firing: true, Value: 2, Box: "b"}) { |
| + t.Fatalf("behind: %+v", ev) |
| + } |
| + st, ev = Evaluate(r, st, Observation{At: t0.Add(time.Hour), Verify: &VerifyReading{Box: "b", Hosts: []string{"a", "c"}, Behind: []string{"c"}}}) |
| + if len(ev) != 0 || !st.Rules["verify_coverage"].Firing { |
| + t.Fatalf("one host still behind: %v %+v", ev, st.Rules) |
| + } |
| + st, ev = Evaluate(r, st, Observation{At: t0.Add(2 * time.Hour)}) |
| + if len(ev) != 0 || !st.Rules["verify_coverage"].Firing { |
| + t.Fatalf("a nil reading changed the rule: %v", ev) |
| + } |
| + st, ev = Evaluate(r, st, Observation{At: t0.Add(3 * time.Hour), Verify: &VerifyReading{Box: "b", Hosts: []string{"a", "c"}}}) |
| + if len(ev) != 1 || ev[0] != (Event{Rule: "verify_coverage", Firing: false, Box: "b"}) { |
| + t.Fatalf("caught up: %+v", ev) |
| + } |
| + if rs, kept := st.Rules["verify_coverage"]; !kept || rs.Firing { |
| + t.Fatalf("after clearing: %+v (kept %v)", rs, kept) |
| + } |
| +} |
| + |
| +// The streak comes from the record as dbverify.Merge keeps it: not_reached |
| +// (and no_assignment, no_record) runs hold it, so a host the run never |
| +// reaches never fires verify_unverified, however many nights it goes on; |
| +// only runs that tried and could not decide count. |
| +func TestEvaluateVerifyNotReachedNeverCounts(t *testing.T) { |
| + r := DefaultRules() |
| + t0 := time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC) |
| + fleet := []string{"idle", "flaky"} |
| + var rec *dbverify.Record |
| + st := AlertState{V: 1, Box: "b"} |
| + night := func(i int, flaky string) []Event { |
| + at := t0.Add(time.Duration(i) * 24 * time.Hour) |
| + rec = dbverify.Merge(rec, "b", at, fleet, map[string]dbverify.Verdict{ |
| + "idle": {Result: dbverify.ResultUnverified, Reason: dbverify.ReasonNotReached}, |
| + "flaky": {Result: dbverify.ResultUnverified, Reason: flaky}, |
| + }) |
| + var ev []Event |
| + st, ev = Evaluate(r, st, Observation{At: at, Verify: writeVerify(t, rec, at)}) |
| + return ev |
| + } |
| + for i, reason := range []string{"plan_moved", dbverify.ReasonNotReached, "plan_moved", dbverify.ReasonNoAssignment, dbverify.ReasonNotReached} { |
| + if ev := night(i, reason); len(ev) != 0 { |
| + t.Fatalf("night %d (%s): %+v, want nothing (flaky's streak is 2 at most)", i, reason, ev) |
| + } |
| + } |
| + ev := night(5, "record_changed") |
| + if len(ev) != 1 || ev[0].Rule != RuleFor("verify_unverified", "flaky") || !ev[0].Firing || |
| + ev[0].Value != alerting.VerifyReasonValue("record_changed") { |
| + t.Fatalf("third counted night: %+v", ev) |
| + } |
| + if _, ok := st.Rules[RuleFor("verify_unverified", "idle")]; ok { |
| + t.Fatalf("a never-reached host has a streak rule: %+v", st.Rules) |
| + } |
| +} |
| + |
| +// A host is behind when its last decided verdict, or its first sighting if |
| +// it has never been decided, is more than 7 days old. Exactly 7 days is not |
| +// behind. |
| +func TestReadVerifyBehind(t *testing.T) { |
| + now := time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC) |
| + week := 7 * 24 * time.Hour |
| + rec := &dbverify.Record{V: 2, Box: "b", CheckedAt: now, Hosts: map[string]dbverify.Verdict{ |
| + "at-boundary": {Result: dbverify.ResultPassed, LastDecidedAt: now.Add(-week), FirstSeen: now.Add(-30 * week)}, |
| + "past-boundary": {Result: dbverify.ResultPassed, LastDecidedAt: now.Add(-week - time.Second), FirstSeen: now.Add(-30 * week)}, |
| + // Decided long ago, unverified since: behind, by its decision. |
| + "held": {Result: dbverify.ResultUnverified, Reason: dbverify.ReasonNotReached, LastDecidedAt: now.Add(-2 * week), |
| + FirstSeen: now.Add(-3 * week), UnverifiedRuns: 1}, |
| + "new-never": {Result: dbverify.ResultUnverified, Reason: dbverify.ReasonNotReached, FirstSeen: now.Add(-week)}, |
| + "old-never": {Result: dbverify.ResultUnverified, Reason: "moving", FirstSeen: now.Add(-week - time.Hour), UnverifiedRuns: 4}, |
| + "failed-host": {Result: dbverify.ResultFailed, Reason: "restore_error", LastDecidedAt: now, FirstSeen: now}, |
| + // A result this version does not know is never read as fine. |
| + "odd-host": {Result: "exploded", LastDecidedAt: now, FirstSeen: now}, |
| + }} |
| + v := writeVerify(t, rec, now) |
| + want := &VerifyReading{ |
| + Box: "b", |
| + Hosts: []string{"at-boundary", "failed-host", "held", "new-never", "odd-host", "old-never", "past-boundary"}, |
| + Failed: []string{"failed-host", "odd-host"}, |
| + UnverifiedStreak: map[string]int{"held": 1, "new-never": 0, "old-never": 4}, |
| + UnverifiedReason: map[string]string{"held": "not_reached", "new-never": "not_reached", "old-never": "moving"}, |
| + Behind: []string{"held", "old-never", "past-boundary"}, |
| + } |
| + if !reflect.DeepEqual(v, want) { |
| + t.Fatalf("ReadVerify =\n %+v\nwant\n %+v", v, want) |
| + } |
| +} |
| + |
| +// No local copy is no reading, not an error: a box that has never drilled |
| +// raises nothing. A copy that does not parse is an error, and no reading. |
| +func TestReadVerifyMissingAndBroken(t *testing.T) { |
| + dir := t.TempDir() |
| + if v, err := ReadVerify(filepath.Join(dir, "verify.json"), time.Now()); v != nil || err != nil { |
| + t.Fatalf("missing = %+v, %v", v, err) |
| + } |
| + bad := filepath.Join(dir, "bad.json") |
| + if err := os.WriteFile(bad, []byte("{"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if v, err := ReadVerify(bad, time.Now()); v != nil || err == nil { |
| + t.Fatalf("broken = %+v, %v", v, err) |
| + } |
| + other := filepath.Join(dir, "v9.json") |
| + if err := os.WriteFile(other, []byte(`{"v":9,"box":"b","hosts":{}}`), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if v, err := ReadVerify(other, time.Now()); v != nil || err == nil { |
| + t.Fatalf("unknown version = %+v, %v", v, err) |
| + } |
| +} |
diff --git a/internal/ops/ops.go b/internal/ops/ops.go| index 369d34230..793f8983b 100644 |
| --- a/internal/ops/ops.go |
| +++ b/internal/ops/ops.go |
| @@ -545,7 +545,7 @@ func (p *verifyPublisher) publish(results map[string]dbverify.Verdict) { |
| // localVerifyPath is the local alert copy, beside the agent's self record: |
| // <data>/monitor/verify.json. |
| func localVerifyPath(dataDir string) string { |
| - return filepath.Join(filepath.Dir(boxself.SelfPath(dataDir)), "verify.json") |
| + return dbverify.LocalPath(dataDir) |
| } |
| // writeLocalVerify writes rec to the local alert copy whole (a temp file |