carlos / platform Public

alerting: URL-free webhook errors; metrics: disarmed engine_silent clears

Review fix round 1 (R-9): PostJSON cuts the client's *url.Error down to
its cause, so a Slack webhook path never reaches the journal. A firing
engine_silent clears once and loses its key when the rule is disarmed;
alertTick holds the committed state while an armed watch is inside its
grace, so nil keeps meaning unarmed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 1916e24ff70be162604425fb54c116d666f0b206 parent ce69708
8 files changed, +192 −24
  • internal/alerting/alerting.go +12 −3
  • internal/alerting/alerting_test.go +46 −0
  • internal/host/alertsink_test.go +41 −0
  • internal/host/enginebeat.go +3 −2
  • internal/host/enginebeat_linux_test.go +31 −1
  • internal/host/metrics_loop.go +10 −1
  • internal/metrics/alert.go +18 −12
  • internal/metrics/alert_test.go +31 −5

CI failed — run details

Intent

Human

<task-notification> <task-id>a20e0a155120d0ca9</task-id> <tool-use-id>toolu_013qy12Ytbb2upVp93cQV3Uf</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a20e0a155120d0ca9.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: Slack sink and engine_silent" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **Status:** DONE_WITH_CONCERNS - **Commit:** ce697083 "alerting: Slack body, no redirects; host: engine_silent backstop, refused for root agents". It includes the census card, and the commit body carries the R-8 census claim. git printed the packed-refs.lock warning, but `git log -1` shows the commit. Not pushed. - **Tests:** all the new and touched tests pass in alerting, status, metrics, host and the `TestPrintLiveBoxes` group. `go build ./...`, vet of the touched packages, and the darwin and windows builds pass. darwin vet of `internal/host` still fails on `hawake_wiring_test.go` (`claimsOnEnv`), which fails the same way at base 0ea2aaf1. - **Concerns, all accepted by you:** - The census reviewer still has to classify `engineBeatLstat` at Task 11. - The 10-minute grace runs from the later of agent start and the last fresh read. Inside it the box reports "no evidence", so only a fresh beat clears the alert. - A stale beat fires immediately, so a console reboot longer than 10 minutes sends one fire and one clear. - The wording of `engine_silent` alerts is left to Task 9. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-3-report.md (it now has the "Census claim" section and the R-8 resolution).</result> <usage><subagent_tokens>181015</subagent_tokens><tool_uses>56</tool_uses><duration_ms>714539</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a5e49e11717125ed3</task-id> <tool-use-id>toolu_01H7RVKPgtozZziveTkQjxsN</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a5e49e11717125ed3.output</output-file> <status>completed</status> <summary>Agent "Review Task 3 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Spec Compliance - ✅ Spec compliant, with R-1 and R-8 applied. Every interface in the brief is present: - `IsSlackWebhook` at `internal/alerting/alerting.go:234`. - `SlackBody` at `alerting.go:246`. - `CheckRedirect` set to `http.ErrUseLastResponse` at `alerting.go:260`. - `NotDelivered` at `internal/status/snapshot.go:793`. It is used at `cli.go:4167`, and its condition is the same as the old `alertsWord` test (`len(sinks)==0 &amp;&amp; !SNSUnavailable`). - `engineBeatArmed` refuses `euid == 0` at `internal/host/enginebeat.go:81`. That is before `filepath.IsAbs` or `Clean` and before any filesystem call. - The five `beatState` values, and `readEngineBeat` using Lstat (`enginebeat.go:95`). - The grace counts from the later of arming and the last fresh read (`enginebeat.go:141`). - R-1's `Observation.EngineSilent *bool` fires and clears on transition only, so nil never creates the key (`internal/metrics/alert.go:363-369`). - `alertTick` takes `beat` (`metrics_loop.go:539`). - All 11 tests named in the brief are present in the diff, plus extra ones. - ⚠️ Cannot verify from the diff: whether the ce697083 commit body carries the census claim R-8 requires. The diff package shows only the subject line. Controller: run `git log -1 --format=%B ce697083`. - ⚠️ Extras beyond the brief, both reasonable and tested: - `deliverRelease` sends the Slack shape too (`alertsink.go:169`). - Slack `&amp;&lt;&gt;` escaping (`alerting.go:246`). - `EngineBeat`/`EngineBeatWhy` on the heartbeat, and the `agent.go` probe signature change, which the brief's file list did not name. ### Strengths - The root refusal is pure and ordered correctly. The only filesystem call is `engineBeatLstat` (`enginebeat.go:69`), and only a non-nil watch reaches it. `newEngineBeatWatch` returns nil for root, and `(*engineBeatWatch)(nil).silent` returns nil before any read. - The root test proves the stat counter is live with a non-root contrast, so "zero calls" means something. - Non-Slack bodies are built by the same `json.Marshal` calls as before, so they are unchanged byte for byte: - `Page`: `pagePayload` at `alerting.go:128` onward. - `deliver`: `json.Marshal(ev)`. - `deliverRelease`: the same struct as before. - `TestPageNonSlackUnchanged` covers look-alike hosts, a path containing the name, a query containing the name, and plain http. - The redirect test checks 301, 302, 307 and 308, and asserts the target is never contacted. - The restart tests cover all three cases: before the fire, after the fire with state kept, and after the fire with state lost. ### Named-risk checks 1. **Can root reach the stat?** No path found. - Checked that `metricsLoop`'s only caller is `agent.go:947`. - `euid` is read once at loop start (`metrics_loop.go:877`) through `os.Geteuid`, which is a live syscall with no cache. The process never changes uid, and if it started as root it fails safe. - The seam `engineBeatLstat` is only reassigned in `_test.go`. - `carlos-edge.service` grants only `CAP_NET_BIND_SERVICE` (`internal/host/units/carlos-edge.service:32-33`), so no DAC-bypass capability widens what a non-root Lstat can reach. - `alertDeliveryProbe` calls only the pure `engineBeatArmed` (`alertsink.go:275`). 2. **Slack logging and payloads.** No new log line carries a body. Non-Slack payloads are unchanged (see Strengths). One older leak remains (Minor 1). 3. **PostJSON callers.** There are two: the console `FromEnv` default (`alerting.go:212`) and `httpPostWebhook` (`metrics_loop.go:644`). Both are alert webhooks. - Before this change, a 301, 302 or 303 turned the POST into a body-less GET, so nothing could have depended on those working. - A configured `http://` URL that 307s or 308s to https used to deliver and now fails. It surfaces as `non-2xx status 308` and is counted in `WebhookFailures`, so the failure is visible. - ⚠️ Controller: confirm no box's `CARLOS_ALERT_WEBHOOK` relies on a 307 or 308 hop. 4. **Heartbeat compatibility.** Both directions work. - The new fields are `omitempty`. No `DisallowUnknownFields` appears in `internal/status` or `cli.go`. The strict decoders in `internal/console` are claim and auth decoders, not heartbeat ones. So an old console or CLI ignores the new keys. - A new CLI reading an old heartbeat sees `EngineBeat == ""`, so `engineBeatWord` returns `""` (`cli.go:4200`), and `NotDelivered` uses the same condition as before. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) None. #### Minor (Nice to Have) 1. **The Slack token can reach the journal on a transport error.** This is older than the change, but Slack is now a first-class target. - Where: `internal/alerting/alerting.go:257` (PostJSON) and `internal/host/alertsink.go:112,182`. - `client.Post` returns a `*url.Error` whose text includes the full URL. On a dial, TLS or timeout error, `deliver` logs it with `%v`. - A Slack incoming-webhook URL's path is its secret, so it lands in the journal. - The global constraint says errors are reduced to URL-free categories before anything stores or logs them. - This task didn't introduce it, and it applied to Slack URLs before too. Fix it in PostJSON, by unwrapping `*url.Error` to its `.Err`, or in the later connector-HTTP task. 2. **Slack text promises an email.** `internal/host/alertsink.go:367`: Slack bodies reuse `formatAlert`, which says "you will get another email when it clears." That is wrong on Slack. Hand it to Task 9's copy deck along with the default `engine_silent` sentence. 3. **A firing `engine_silent` can stick forever.** `internal/metrics/alert.go:363`: if the env is removed or the agent moves to root while the rule is firing, nil leaves it firing in `alerts/boxes/&lt;box&gt;.json` with nothing that can ever clear it. The report's concern 7 says the same. R-1 only forbids creating the key when unarmed. Clearing an existing firing key when unarmed would stop a permanent open incident later in the engine. 4. **A test ignores a setup error.** `internal/host/enginebeat_linux_test.go:237`: `_ = os.Symlink(...)` discards the error. If the symlink fails, the file is simply missing, and the case still passes because a missing beat also fires at minute 10. The symlink-specific branch would then go untested. Use `t.Fatal` on the error. 5. **A doc comment overstates.** `internal/status/snapshot.go:793`: the comment says "The live listing and the console read this one test", but no console code reads `AlertDelivery` today; grep finds `SNSUnavailable` only in `cli.go`. Reword it, or make it true when the console starts using it. 6. **Extra Lstat seam test.** `internal/host/enginebeat.go:95`: `readEngineBeat` has no euid guard of its own, so the refusal rests entirely on the watch being nil. That is correct today. A test that walks `metricsLoop`'s arming with `euid = 0` end to end exists only as a contrast inside `TestEngineBeatRootRefusedBeforeLookup`. Adequate, noted for whoever refactors the arming. ### Assessment **Task quality:** Approved **Reasoning:** Root is refused before any path work. The only filesystem call is reachable only through a non-nil watch, and the tests show zero calls. Non-Slack payloads and heartbeat compatibility are unchanged. The remaining items are copy, logging hygiene that predates this change, and test tightening.</result> <usage><subagent_tokens>111537</subagent_tokens><tool_uses>10</tool_uses><duration_ms>156180</duration_ms></usage> </task-notification>

Attributed to this commit: 20.6 g CO₂e (2,629,510 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/alerting/alerting.go b/internal/alerting/alerting.go
index e9666abf6..6372bc3db 100644
--- a/internal/alerting/alerting.go
+++ b/internal/alerting/alerting.go
@@ -254,14 +254,23 @@ func SlackBody(subject, body string) []byte {
// content type. Any non-2xx status is an error. It follows no redirect: the
// 3xx is the answer, and an error, so a body meant for one URL is never
// re-sent somewhere the operator did not configure.
-func PostJSON(url string, body []byte) error {
+//
+// Its errors never carry the URL. A Slack incoming-webhook path is the
+// secret that lets anyone post to the channel, and callers log these
+// errors, so the *url.Error the client returns (whose text is the method,
+// the whole URL and the cause) is cut down to its cause.
+func PostJSON(endpoint string, body []byte) error {
client := &http.Client{
Timeout: 5 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
- resp, err := client.Post(url, "application/json", bytes.NewReader(body))
+ resp, err := client.Post(endpoint, "application/json", bytes.NewReader(body))
if err != nil {
- return err
+ var ue *url.Error
+ if errors.As(err, &ue) {
+ return fmt.Errorf("webhook: post: %w", ue.Err)
+ }
+ return fmt.Errorf("webhook: post failed")
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
diff --git a/internal/alerting/alerting_test.go b/internal/alerting/alerting_test.go
index 3bdb3c944..d738e2cc6 100644
--- a/internal/alerting/alerting_test.go
+++ b/internal/alerting/alerting_test.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"log"
+ "net"
"net/http"
"net/http/httptest"
"strings"
@@ -355,3 +356,48 @@ func TestPostJSONRefusesRedirect(t *testing.T) {
t.Fatalf("the redirect target was reached %d times", n)
}
}
+
+// refusedURL is a URL on 127.0.0.1 whose port nothing listens on, with the
+// secret-looking path a Slack incoming webhook has.
+func refusedURL(t *testing.T, path string) string {
+ t.Helper()
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ addr := l.Addr().String()
+ l.Close()
+ return "http://" + addr + path
+}
+
+// Fix round 1 (R-9 #1): a webhook URL is a secret (a Slack path lets anyone
+// post to the channel), and PostJSON's errors are logged, so none of them
+// carries it: not a refused connection, not a non-2xx status, not a URL
+// that does not parse. Page returns the same error.
+func TestPostJSONErrorsCarryNoURL(t *testing.T) {
+ const secret = "sekrit-XYZ"
+ refused := refusedURL(t, "/services/T000/B000/"+secret)
+ err := PostJSON(refused, []byte(`{}`))
+ if err == nil || strings.Contains(err.Error(), secret) || strings.Contains(err.Error(), refused) {
+ t.Fatalf("refused connection: %v", err)
+ }
+ if !strings.Contains(err.Error(), "refused") {
+ t.Errorf("refused connection lost its cause: %v", err)
+ }
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "no", http.StatusInternalServerError)
+ }))
+ defer srv.Close()
+ if err := PostJSON(srv.URL+"/services/"+secret, []byte(`{}`)); err == nil || strings.Contains(err.Error(), secret) {
+ t.Fatalf("non-2xx: %v", err)
+ }
+ if err := PostJSON("http://bad host/"+secret, []byte(`{}`)); err == nil || strings.Contains(err.Error(), secret) {
+ t.Fatalf("bad url: %v", err)
+ }
+
+ s := &Sinks{WebhookURL: refused, Post: PostJSON}
+ if err := s.Page(context.Background(), LevelIncident, "subj", "body"); err == nil || strings.Contains(err.Error(), secret) {
+ t.Fatalf("page: %v", err)
+ }
+}
diff --git a/internal/host/alertsink_test.go b/internal/host/alertsink_test.go
index fa0a7994c..ec0c95dc7 100644
--- a/internal/host/alertsink_test.go
+++ b/internal/host/alertsink_test.go
@@ -1,9 +1,12 @@
package host
import (
+ "bytes"
"context"
"encoding/json"
"errors"
+ "log"
+ "net"
"os"
"path/filepath"
"strings"
@@ -413,6 +416,44 @@ func TestBoxDeliverSlackBody(t *testing.T) {
}
}
+// Fix round 1 (R-9 #1): a failed post through the production webhook post
+// logs no part of the webhook URL. A Slack incoming-webhook path is a
+// secret, and the journal is not.
+func TestBoxDeliverLogsNoWebhookURL(t *testing.T) {
+ const secret = "sekrit-XYZ"
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ refused := "http://" + l.Addr().String() + "/services/T000/B000/" + secret
+ l.Close()
+
+ var buf bytes.Buffer
+ prev, flags := log.Writer(), log.Flags()
+ log.SetOutput(&buf)
+ t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) })
+
+ counts := &alertCounters{}
+ s := newAlertSinks(refused, httpPostWebhook, "", nil, counts)
+ s.deliver(context.Background(), metrics.DefaultRules(), sinkTestAt,
+ metrics.Event{Rule: "disk", Firing: true, Value: 0.95, Box: "box-a"})
+ s.deliverRelease(context.Background(), release.Refusal{Host: "shop.example", Version: "v2", RefusedAt: sinkTestAt})
+ err = s.PageOperator(context.Background(), "incident", "subj", "body")
+
+ if counts.webhook.Load() != 3 {
+ t.Fatalf("webhook failures = %d, want 3 (the posts must have failed)", counts.webhook.Load())
+ }
+ if !strings.Contains(buf.String(), "alert webhook post") {
+ t.Fatalf("no failure was logged: %q", buf.String())
+ }
+ if strings.Contains(buf.String(), secret) {
+ t.Fatalf("the journal carries the webhook URL: %q", buf.String())
+ }
+ if err == nil || strings.Contains(err.Error(), secret) {
+ t.Fatalf("page error: %v", err)
+ }
+}
+
// fakeClientFactory is the buildAlertSinks seam: it records the region it
// was asked for and either hands back a fake or fails.
type fakeClientFactory struct {
diff --git a/internal/host/enginebeat.go b/internal/host/enginebeat.go
index 21c5f808d..9c73e3660 100644
--- a/internal/host/enginebeat.go
+++ b/internal/host/enginebeat.go
@@ -136,8 +136,9 @@ func newEngineBeatWatch(getenv func(string) string, euid int, now time.Time) *en
// false and a stale one true. A missing, non-regular or future beat is true
// once engineBeatGrace has passed since arming or the last fresh read,
// whichever is later (plan R2 #3: whether or not a beat was ever seen), and
-// nil before that: no evidence either way, so a firing rule restored after a
-// restart neither clears nor pages again. Safe on nil, which is nil.
+// nil before that: no evidence either way. alertTick holds the committed
+// state on that nil, so a firing rule restored after a restart neither
+// clears nor pages again. Safe on nil, which is nil.
func (w *engineBeatWatch) silent(now time.Time) *bool {
if w == nil {
return nil
diff --git a/internal/host/enginebeat_linux_test.go b/internal/host/enginebeat_linux_test.go
index 9b314d194..f5420a90d 100644
--- a/internal/host/enginebeat_linux_test.go
+++ b/internal/host/enginebeat_linux_test.go
@@ -234,7 +234,11 @@ func TestEngineSilentNeverCreatedBeatFires(t *testing.T) {
// A symlink or a future mtime in its place is no better than nothing.
for _, setup := range []func(){
- func() { _ = os.Symlink("/dev/null", path) },
+ func() {
+ if err := os.Symlink("/dev/null", path); err != nil {
+ t.Fatal(err)
+ }
+ },
func() { writeBeat(t, path, beatT0.Add(time.Hour)) },
} {
_ = os.Remove(path)
@@ -336,3 +340,29 @@ func TestEngineSilentFiresThroughAlertTick(t *testing.T) {
t.Fatal("unset env created the engine_silent rule")
}
}
+
+// Fix round 1 (R-9 #2): a fire from when the backstop was armed clears once,
+// through the sink, on the first tick after it is disarmed (the env
+// removed, or the agent now root), and the key goes.
+func TestEngineSilentDisarmedClearsThroughAlertTick(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "alert-engine.beat")
+ writeBeat(t, path, beatT0.Add(-time.Hour))
+ r := newBeatRig(t)
+ if evs := r.tick(beatT0, newEngineBeatWatch(beatEnv(path), 1000, beatT0)); len(evs) != 1 || !evs[0].Firing {
+ t.Fatalf("armed: sink got %+v, want the fire", evs)
+ }
+
+ // Restarted as root with the same env: unarmed, no stat, one clear.
+ calls := countLstat(t)
+ disarmed := newEngineBeatWatch(beatEnv(path), 0, beatT0.Add(time.Minute))
+ fired, cleared := r.minutes(1, 15, disarmed)
+ if fired != nil || len(cleared) != 1 || cleared[0] != 1 {
+ t.Fatalf("disarmed: fired %v, cleared %v; want one clear at minute 1", fired, cleared)
+ }
+ if _, ok := r.st.Rules["engine_silent"]; ok {
+ t.Fatal("disarmed kept the engine_silent key")
+ }
+ if *calls != 0 {
+ t.Fatalf("root made %d stat calls", *calls)
+ }
+}
diff --git a/internal/host/metrics_loop.go b/internal/host/metrics_loop.go
index 8d16cc2f8..1a22737f5 100644
--- a/internal/host/metrics_loop.go
+++ b/internal/host/metrics_loop.go
@@ -536,7 +536,16 @@ func alertTick(ctx context.Context, s release.Store, box string, rules metrics.R
v, eta := trend.verdict(latest.At)
obs.DiskTrend, obs.DiskETAHours = &v, eta
}
- obs.EngineSilent = beat.silent(latest.At)
+ if beat != nil {
+ obs.EngineSilent = beat.silent(latest.At)
+ if obs.EngineSilent == nil {
+ // Armed, but no evidence either way yet (inside the grace): hold
+ // the committed state. nil would tell Evaluate the rule is
+ // unarmed and clear a fire restored after a restart.
+ held := st.Rules["engine_silent"].Firing
+ obs.EngineSilent = &held
+ }
+ }
newState, events := metrics.Evaluate(rules, *st, obs)
var publishErr error
diff --git a/internal/metrics/alert.go b/internal/metrics/alert.go
index 9b2fdd302..2d4cabab0 100644
--- a/internal/metrics/alert.go
+++ b/internal/metrics/alert.go
@@ -109,9 +109,9 @@ type Observation struct {
DiskETAHours float64
// EngineSilent is the engine_silent backstop on a console box (fleet
// alerts spec §8): true when the console's alert engine has gone
- // silent, false on a fresh beat. nil when the rule is unarmed, or when
- // the box cannot tell yet; the agent has already applied the 10 minute
- // grace and staleness, so the rule has no sustain here.
+ // silent, false when it has not. nil when the rule is unarmed. The
+ // agent has already applied the 10 minute grace and staleness, so the
+ // rule has no sustain here.
EngineSilent *bool
}
@@ -358,16 +358,22 @@ func Evaluate(r Rules, st AlertState, obs Observation) (AlertState, []Event) {
// engine_silent fires on the first silent reading and clears on the
// first fresh one. Value is 1 firing, 0 clear. Like every rule, only a
// transition writes the key, so an unarmed box (nil every tick) never
- // has one.
- if obs.EngineSilent != nil {
- if cur := out.Rules["engine_silent"]; cur.Firing != *obs.EngineSilent {
- if *obs.EngineSilent {
- out.Rules["engine_silent"] = RuleState{Firing: true, Since: obs.At, FiredAt: obs.At, Value: 1}
- } else {
- out.Rules["engine_silent"] = RuleState{Value: 0}
- }
- emit("engine_silent", *obs.EngineSilent, out.Rules["engine_silent"].Value)
+ // has one. Unlike the others, nil is not "no data": it is a rule that is
+ // no longer armed (the env was removed, or the agent now runs as root),
+ // so a fire left over from when it was armed clears once and its key
+ // goes. Otherwise nothing would ever clear it.
+ if obs.EngineSilent == nil {
+ if cur, ok := out.Rules["engine_silent"]; ok && cur.Firing {
+ delete(out.Rules, "engine_silent")
+ emit("engine_silent", false, 0)
+ }
+ } else if cur := out.Rules["engine_silent"]; cur.Firing != *obs.EngineSilent {
+ if *obs.EngineSilent {
+ out.Rules["engine_silent"] = RuleState{Firing: true, Since: obs.At, FiredAt: obs.At, Value: 1}
+ } else {
+ out.Rules["engine_silent"] = RuleState{Value: 0}
}
+ emit("engine_silent", *obs.EngineSilent, out.Rules["engine_silent"].Value)
}
return out, events
diff --git a/internal/metrics/alert_test.go b/internal/metrics/alert_test.go
index 8d320bbde..48d8b3a4c 100644
--- a/internal/metrics/alert_test.go
+++ b/internal/metrics/alert_test.go
@@ -394,7 +394,7 @@ func TestRulesFromEnvDiskETAHours(t *testing.T) {
// engine_silent (fleet alerts spec §8, plan ruling R-1): the host has
// already applied the grace and staleness, so Evaluate fires on the first
// silent reading and clears on the first fresh one. nil is unarmed: the key
-// is never created and a firing state is left alone.
+// is never created.
func TestEvaluateEngineSilent(t *testing.T) {
r := DefaultRules()
st := AlertState{V: 1, Box: "b", Rules: map[string]RuleState{}}
@@ -417,12 +417,38 @@ func TestEvaluateEngineSilent(t *testing.T) {
if len(ev) != 0 {
t.Fatalf("still silent emitted again: %v", ev)
}
- st, ev = Evaluate(r, st, Observation{At: at.Add(3 * time.Minute)})
- if len(ev) != 0 || !st.Rules["engine_silent"].Firing {
- t.Fatalf("no reading must leave the fire alone: %v %+v", ev, st.Rules)
- }
st, ev = Evaluate(r, st, Observation{At: at.Add(4 * time.Minute), EngineSilent: &no})
if len(ev) != 1 || ev[0] != (Event{Rule: "engine_silent", Firing: false, Value: 0, Box: "b"}) || st.Rules["engine_silent"].Firing {
t.Fatalf("fresh must clear at once: %v", ev)
}
}
+
+// Fix round 1 (R-9 #2): a fire left over from when the rule was armed (the
+// env removed, or the agent now root) clears once on the first unarmed tick
+// and its key goes, rather than firing forever. A key that is not firing is
+// left alone, and nothing more is emitted after.
+func TestEvaluateEngineSilentDisarmedClears(t *testing.T) {
+ r := DefaultRules()
+ at := time.Date(2026, 10, 31, 10, 0, 0, 0, time.UTC)
+ yes := true
+ st := AlertState{V: 1, Box: "b", Rules: map[string]RuleState{}}
+ st, _ = Evaluate(r, st, Observation{At: at, EngineSilent: &yes})
+
+ st, ev := Evaluate(r, st, Observation{At: at.Add(time.Minute)})
+ if len(ev) != 1 || ev[0] != (Event{Rule: "engine_silent", Firing: false, Value: 0, Box: "b"}) {
+ t.Fatalf("disarmed fire: events %v, want one clear", ev)
+ }
+ if _, ok := st.Rules["engine_silent"]; ok {
+ t.Fatalf("disarmed fire kept its key: %+v", st.Rules)
+ }
+ st, ev = Evaluate(r, st, Observation{At: at.Add(2 * time.Minute)})
+ if len(ev) != 0 || len(st.Rules) != 0 {
+ t.Fatalf("second unarmed tick: %v %+v", ev, st.Rules)
+ }
+
+ quiet := AlertState{V: 1, Box: "b", Rules: map[string]RuleState{"engine_silent": {Value: 0}}}
+ quiet, ev = Evaluate(r, quiet, Observation{At: at})
+ if _, ok := quiet.Rules["engine_silent"]; !ok || len(ev) != 0 {
+ t.Fatalf("unarmed with a quiet key: %v %+v, want it left alone", ev, quiet.Rules)
+ }
+}