carlos / platform Public

console: alert engine fix round 2 (heartbeat horizon restored, revoked operators re-seed, unreachable is a note)

- R-25: the 24 h ListMod horizon on status/boxes/ is back, measured from
  the pass's clock as status.LoadBoxes does. A box whose heartbeat drops
  out is gone: its heartbeat incidents close as "no further reports".
  A stale object is not read, so it cannot block cert_expiring or fill
  the key cap.
- R-26: the drain deletes a revoked operator's seeded connector with
  their seeded marker in one transaction (DeleteRevokedOperatorConnector),
  so granting them again seeds them again. Unreachable operators are a
  job-status note, named on every pass until reachable; the job stays OK.
- The stale alertMessage mention in alertNote's comment is gone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 3fd70d49e5e08e932470cf1aa70214b9d8c2d2b3 parent 92e6052
5 files changed, +177 −46
  • internal/console/alertengine_pass.go +13 −8
  • internal/console/alertengine_pass_test.go +104 −9
  • internal/console/alertnotify.go +6 −5
  • internal/console/alertsignals.go +19 −20
  • internal/console/alertstore.go +35 −4

CI failed — run details

Intent

Human

<task-notification> <task-id>a228356c85f7c1bde</task-id> <tool-use-id>toolu_01Q7Jbmtpwtgr1B3CCJnC96u</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a228356c85f7c1bde.output</output-file> <status>completed</status> <summary>Agent "Implement Task 8: alert engine worker" 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 - **Commit:** 92e60520 `console: seed each operator address once ever (R-24)` - **What changed:** - When an operator is first given an email connector, the console also writes an `alert_meta` row `seeded:&lt;lowercased address&gt;` in the same transaction. Both the cutover and every later pass do this. - An address with that row is never given a connector again. So an operator who deletes their connector does not get it back, even after a restart. - An operator added later is still given one on the next pass, within a minute. - The cutover now queues a fire only to operators who still have a connector. - **Tests:** - The new test seeds an operator, deletes their connector, runs a pass, a restart and another pass, and nothing comes back; a newly added operator is still seeded. It fails if the connector is inserted every time, and passes as written. - Engine, Alert, Dashboard, Jobs, StoreNotify, the log-also-fails check and the route census pass (32.3 s). `go vet` is clean and the Step 5 guard prints nothing. - **Concerns:** none new. My earlier concern about re-seeding undoing an unsubscribe is resolved by R-24. One consequence: an operator whose connector was deleted and who is later made an operator again is not given a new one. They have to add a connector themselves on the alerts page (Task 10). - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-8-report.md (R-24 section appended)</result> <usage><subagent_tokens>429745</subagent_tokens><tool_uses>29</tool_uses><duration_ms>600998</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a8e04850fcf147fff</task-id> <tool-use-id>toolu_01Bz9hnbdXEzCi2a9Ki5eWXF</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a8e04850fcf147fff.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 8 fix round 1" 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>### Finding Verdicts 1. **A failed step skipped the outbox drain (Important): ADDRESSED.** In `internal/console/alertengine_pass.go:117-145`, `alertEnginePass` now runs `alertDrainOutbox` at line 131 whenever ctx is live, whatever the step returned. The beat and the unreachable check run only after a step that committed. When ctx is cancelled the pass returns nil. `TestEnginePassDrainsWhenTheListingFails` (`alertengine_pass_test.go:708`) makes the `alerts/boxes/` LIST answer 403, then checks that the queued row is delivered and no beat is written. 2. **The unreachable-operator line was visible about a minute a day (Important): ADDRESSED.** At `alertengine_pass.go:555`, the daily skip applies only while `e.unreachable` is empty. Lines 578-581 keep re-checking every pass until a check finds everyone reachable. `TestEnginePassNamesUnreachableOperators` (`:611`) asserts Failed naming B alone at +24h, +24h+1m and +24h+5m, and OK once B's connector is resumed. See new breakage item 2 for how this combines with R-24. 3. **No test showed a failed read never closes an incident (Important): ADDRESSED.** There is one test per source, each asserting the incident stays open and no clear row is queued: - `JunkAlertObjectKeepsItsIncident` (`:749`): a junk object, then a 403 GET. That is a non-404 failure rather than a 5xx, but it takes the same error path. - `CorruptHeartbeatKeepsBoxSilent` (`:764`): runs through two heartbeat passes. - `UnparsableFleetKeepsServiceDown` (`:774`) - `UnreadHeartbeatKeepsCertExpiring` (`:784`) The report's mutation check shows three of the four fail when their guard is removed. 4. **R-20, seeding every pass: ADDRESSED.** `alertengine_pass.go:164` calls `seedOperatorConnectors` on every pass after the first. The test is `TestEnginePassSeedsALaterOperator` (`:655`). 5. **R-21, an unusable seal key is a note, not a failure: ADDRESSED.** `openAlertSeal` no longer calls `jobFailed`. `alertengine_pass.go:196` adds a note through `jobNoteOn` (`jobs.go:264`). `jobs.go:219` records the note and `jobs.go:369` shows it on OK rows. `TestEnginePassSealKeyUnreadable` (`:467`) asserts JobOK with a note naming the seal key. The new `JobStatus.Note` field is sound: it is replaced on every run, appears only on OK rows, and no JSON output includes `JobStatus`. 6. **R-23, HostClaim recorded as off, with zero store calls: ADDRESSED.** `StartAlertEngine` logs that it is off and returns before `jobs.Run` (`alertengine_pass.go:87-91`), so `exited` drops the job from the list. The probe (`claim_invariant_probes_worker_test.go`) asserts the log line, "store calls 0", that the job is no longer listed and that the `alert_*` tables are empty. `TestEngineRefusesInHostClaim` (`:520`) goes through `RunClaimWorker` and also checks zero S3 requests and no beat. 7. **R-23, `box_silent` membership kept past the 24 h horizon, using `alertClockNow`: ADDRESSED as ruled.** `engineBoxKeyList` (`alertsignals.go:172-190`) keeps every key and puts current ones first. `cut` comes from the pass's `now`. No test makes an object older than the horizon: fixture objects carry the real write time, which is always after `alertT0 - 24h`. The ruling did not ask for one. See new breakage item 1 for the consequence. 8. **R-23, one box name, the object key's: ADDRESSED.** `alertsignals.go:310-328` uses the key's name everywhere. A body `st.Box` that disagrees is only logged, and that line repeats every minute while the mismatch lasts. 9. **R-23, the dead `alertMessage` is deleted: ADDRESSED.** No callers remain. One stale comment still names it at `alertnotify.go:59-60` ("Named to stay clear of alertwatch.go's alertMessage"). 10. **R-23, the `json.Marshal` errors are handled: ADDRESSED.** `planAlertCutover` returns both errors (`alertengine_pass.go:491-494` and `506-509`), and the cutover transaction rolls back. No unchecked Marshal calls are left in the engine files. 11. **R-23, no `jobFailed` on a cancelled ctx: ADDRESSED.** `alertReadFailed` (`alertsignals.go:364`) checks ctx first, and every per-source read failure goes through it. The drain-error `jobFailed` in the pass runs only after the ctx check. 12. **R-23, the engine moved to `alertengine_pass.go`: ADDRESSED.** I compared the removed and added blocks of b14accf7, both as sorted line multisets and as an in-order diff. The only differences are package and import lines, two header comments, and the deleted `alertMessage` (which takes the `metrics` import with it). Nothing in behaviour changed. 13. **R-24, each address seeded once ever: ADDRESSED.** `seedOperatorAlertConnectors` (`alertstore.go:509-540`) writes the `seeded:&lt;addr&gt;` marker with INSERT OR IGNORE and inserts the connector only when the marker is new, in the same transaction. A missing connector is skipped. The cutover's fire path now checks `conns[op]` (`alertengine_pass.go:496`). Its clear path was already safe, because `told` is filtered through `conns`. `TestEnginePassSeedsEachAddressOnce` (`:678`) covers the delete, a pass, a restart, another pass, and then a new operator B being seeded. **Heartbeat read failures now fail the run.** Consistent with how alert objects are handled, but with two side effects: - The job status flaps: Failed on each heartbeat pass, then OK for the next four. - With stale objects now kept (item 7), one old corrupt or oversized heartbeat from a replaced box fails one pass in five, permanently. Both are Minor and listed under new breakage. ### New Breakage in the Fix Diff 1. **Important: replaced boxes stay `box_silent` members forever.** Source: `alertsignals.go:172-190`, from R-23 Minor 2. Nothing deletes `status/boxes/` objects. `internal/status/fleet.go:240-249` says replaced boxes' reports "pile up, one per replaced box", which is why `LoadBoxes` drops them after a day. With every key kept: - Each replaced box becomes a permanent `box_silent` member. The incident never closes as gone, and it sends a daily reminder until someone deletes the S3 object by hand. - The stale objects count toward the 200-key cap. Over the cap, `unreadBoxes` is non-empty, so `cert_expiring` is never judged (`alertsignals.go:393`). - A single stale unparsable object also stops `cert_expiring` from being judged. The fix matches R-23's wording, but the ruling's cost needs re-weighing against the pile-up. Options: a longer horizon that closes members with "no further reports", or membership taken from the roster. 2. **Important: R-24 plus every-pass naming can leave the engine Failed for good.** - The drain's `alertOwnerRevoked` (`alertnotify.go:502-514`) deletes a revoked operator's seeded connector but leaves the `seeded:` marker. - If that person is granted operator again, `seedOperatorAlertConnectors` skips them (`alertstore.go:533`), so they never get a connector back. - `noteUnreachableOperators` (`alertengine_pass.go:555-586`) then calls `jobFailed` on every pass. The job shows Failed every minute, and the attention rail says "Alert engine failed on its last run." - Until Task 10 there is no page where they can add a connector, and a restart does not help. R-24's rationale covers an operator deleting their own connector, not this deletion done by the system. After Task 10, an operator who deletes their own connector on purpose will cause the same permanent Failed status, which is the per-minute noise R-21 was written to avoid. Suggested fixes: have the revoke path delete the marker in the same transaction, and decide whether "unreachable by choice" should be a note rather than a failure. 3. **Minor: the drain can now run before the seal is open.** If the listing fails on a process's first pass, `alertEngineStep` returns before `openAlertSeal`, but the drain still runs. Slack and webhook rows left from the previous process are held as "no seal key" for `alertHoldRecheck`, which is 5 minutes. They are delayed, not lost. 4. **Minor: heartbeat read failures flap the job status.** They fail only one pass in five, so the job reads Failed for one minute in five. This is the same short-window visibility that finding 2 fixed for unreachable operators. 5. **Minor: the job note's text is draft copy that Task 9 should pick up.** "…; Slack and webhook connectors are held" now shows on the operator page. No test covers `opJobRows` rendering a note on an OK row. 6. **Minor: stale `alertMessage` reference** in the comment at `alertnotify.go:59-60`. ### Out-of-Scope Observations None. ### Verdict **Fix round:** All 13 findings are addressed, but the fix diff adds two Important problems: replaced boxes stay `box_silent` members forever (item 1), and a revoked-then-regranted operator is never re-seeded and keeps the engine Failed (item 2). Both need a controller ruling or a small follow-up fix before this task closes.</result> <usage><subagent_tokens>125411</subagent_tokens><tool_uses>36</tool_uses><duration_ms>342185</duration_ms></usage> </task-notification>

Attributed to this commit: 22.7 g CO₂e (2,892,548 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 6941f0ee4..cb3e34471 100644
--- a/internal/console/alertengine_pass.go
+++ b/internal/console/alertengine_pass.go
@@ -546,10 +546,12 @@ func (s *Server) feedAlertsNow(open []alertIncident, sig *alertSignals, now time
}
// 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.
+// their own reaches (none at all, or one suspended or needing re-entry) in
+// a job-status note (Review Focus 4). Not a failure (ruling R-26): the
+// engine works around it, as with an unusable seal key. 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 len(e.unreachable) == 0 && !e.unreachableAt.IsZero() && now.Sub(e.unreachableAt) < alertUnreachableEvery {
@@ -578,12 +580,15 @@ func (s *Server) noteUnreachableOperators(ctx context.Context, now time.Time) {
if len(e.unreachable) == 0 || len(missing) == 0 {
e.unreachableAt = now // a daily check, or the one that cleared it
}
- e.unreachable = missing
+ note := ""
if len(missing) > 0 {
- err := fmt.Errorf("no usable alert connector reaches %s", strings.Join(missing, ", "))
- log.Printf("console: alert engine: %v", err)
- jobFailed(ctx, err)
+ note = "no usable alert connector reaches " + strings.Join(missing, ", ")
+ }
+ if !slices.Equal(missing, e.unreachable) && note != "" {
+ log.Printf("console: alert engine: %s", note) // once per change, not every pass
}
+ e.unreachable = missing
+ jobNoteOn(ctx, note)
}
// writeAlertEngineBeat replaces the beat file the console box's agent
diff --git a/internal/console/alertengine_pass_test.go b/internal/console/alertengine_pass_test.go
index 6764ed1f1..09ea00354 100644
--- a/internal/console/alertengine_pass_test.go
+++ b/internal/console/alertengine_pass_test.go
@@ -605,9 +605,9 @@ func TestEnginePassWritesBeat(t *testing.T) {
}
}
-// Review Focus 4: an operator no connector reaches is named in the job
-// status from the daily check on, every pass, until a check finds them
-// reachable again.
+// Review Focus 4: an operator no connector reaches is named in a job-status
+// note from the daily check on, every pass, until a check finds them
+// reachable again. The job stays OK (ruling R-26).
func TestEnginePassNamesUnreachableOperators(t *testing.T) {
ef := newEngineFixture(t, nil)
ef.operator(t, opA, opB)
@@ -631,22 +631,22 @@ func TestEnginePassNamesUnreachableOperators(t *testing.T) {
if _, err := ef.st.db.Exec(`UPDATE alert_connectors SET suspended_at = ? WHERE id = ?`, alertT0.Unix(), connB); err != nil {
t.Fatal(err)
}
- if st := run(time.Minute); st.State != JobOK {
- t.Fatalf("pass within the day %+v, want OK until the daily check", st)
+ if st := run(time.Minute); st.State != JobOK || st.Note != "" {
+ t.Fatalf("pass within the day %+v, want OK with no note until the daily check", st)
}
named := func(st JobStatus) bool {
- return st.State == JobFailed && strings.Contains(st.Err, opB) && !strings.Contains(st.Err, opA)
+ return st.State == JobOK && strings.Contains(st.Note, opB) && !strings.Contains(st.Note, opA)
}
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)
+ t.Fatalf("pass at +%v %+v, want OK with a note 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)
+ if st := run(24*time.Hour + 6*time.Minute); st.State != JobOK || st.Note != "" {
+ t.Fatalf("pass after B is reachable %+v, want OK with no note", st)
}
}
@@ -703,6 +703,101 @@ func TestEnginePassSeedsEachAddressOnce(t *testing.T) {
}
}
+// Ruling R-26: a revoked operator's seeded connector goes with their seeded
+// marker, so granting them again seeds them again.
+func TestEnginePassRevokedOperatorIsSeededOnRegrant(t *testing.T) {
+ ef := newEngineFixture(t, nil)
+ ef.operator(t, opA, opB)
+ ef.passAt(t, 0)
+ 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.SetOperator(opB, false); err != nil {
+ t.Fatal(err)
+ }
+ ef.now = alertT0.Add(time.Minute)
+ ef.queue(t, connB, 0, alertKindClear, fireNote())
+ ef.passAt(t, time.Minute) // the drain finds B revoked
+ if n := ef.count(t, `SELECT COUNT(*) FROM alert_connectors WHERE owner_address = '`+opB+`'`); n != 0 {
+ t.Fatalf("%d connectors for revoked B, want none", n)
+ }
+ if n := ef.count(t, `SELECT COUNT(*) FROM alert_meta WHERE k = 'seeded:`+opB+`'`); n != 0 {
+ t.Fatalf("B's seeded marker survived the revocation")
+ }
+ if got := ef.mailsTo(opB); len(got) != 0 {
+ t.Fatalf("revoked B got %v", got)
+ }
+ ef.operator(t, opB)
+ ef.passAt(t, 2*time.Minute)
+ if n := ef.count(t, `SELECT COUNT(*) FROM alert_connectors WHERE owner_address = '`+opB+`' AND confirmed_at != 0`); n != 1 {
+ t.Fatalf("%d confirmed connectors for re-granted B, want 1", n)
+ }
+}
+
+// ageObject sets key's modification time in the bucket under the fake.
+func (ef *engineFixture) ageObject(t *testing.T, key string, mod time.Time) {
+ t.Helper()
+ ds, ok := ef.rel.(*deletableStore)
+ if !ok {
+ t.Fatalf("fixture bucket is %T", ef.rel)
+ }
+ if err := os.Chtimes(filepath.Join(ds.root, filepath.FromSlash(key)), mod, mod); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// Ruling R-25: heartbeat objects are never deleted, so one not written for a
+// day leaves the listing, as status.LoadBoxes drops it. Its box_silent
+// incident closes as gone on the next heartbeat pass, with the clear sent.
+func TestEnginePassHeartbeatPastTheHorizonCloses(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)
+ if got := ef.mailsTo(opA); len(got) != 1 {
+ t.Fatalf("A got %v, want the box_silent fire", got)
+ }
+ ef.ageObject(t, "status/boxes/box-9.json", alertT0.Add(-48*time.Hour))
+ ef.passesTo(t, 6*time.Minute, 9*time.Minute)
+ if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents WHERE closed_at IS NULL AND rule = 'box_silent'`); n != 1 {
+ t.Fatalf("closed before the heartbeat pass")
+ }
+ ef.passAt(t, 10*time.Minute)
+ if n := ef.count(t, `SELECT COUNT(*) FROM alert_incidents WHERE rule = 'box_silent' AND close_reason = 'box gone'`); n != 1 {
+ t.Fatalf("%d box_silent incidents closed as gone, want 1", n)
+ }
+ got := ef.mailsTo(opA)
+ if len(got) != 2 || !strings.Contains(got[1], "No further reports of box_silent on box-9") {
+ t.Fatalf("A got %v, want the fire then a no further reports clear", got)
+ }
+}
+
+// Ruling R-25: a corrupt object past the horizon is not read at all, so it
+// neither blocks cert_expiring (which waits for every listed heartbeat) nor
+// counts toward the key cap.
+func TestEnginePassStaleCorruptHeartbeatIsNotListed(t *testing.T) {
+ ef := newEngineFixture(t, nil)
+ 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)
+ putAlertBody(t, ef.rel, "status/boxes/box-old.json", []byte("{not json"))
+ ef.ageObject(t, "status/boxes/box-old.json", alertT0.Add(-48*time.Hour))
+ ef.now = alertT0
+ if err := ef.srv.jobs.Run(context.Background(), "StartAlertEngine", ef.srv.alertEnginePass); err != nil {
+ t.Fatal(err)
+ }
+ if st, _ := jobStatusOf(ef.srv, "StartAlertEngine"); st.State != JobOK {
+ t.Fatalf("job %+v, want OK: the stale object is not read", st)
+ }
+ 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)
+ }
+ if r := ef.srv.alertEngine.reads; r.listedBoxes["box-old"] || !r.listedBoxes["box-1"] {
+ t.Fatalf("listed boxes %v, want box-1 and not box-old", r.listedBoxes)
+ }
+}
+
// 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) {
diff --git a/internal/console/alertnotify.go b/internal/console/alertnotify.go
index 30c811621..7a581c3ac 100644
--- a/internal/console/alertnotify.go
+++ b/internal/console/alertnotify.go
@@ -56,9 +56,9 @@ const (
)
// alertNote is one message: what the engine stores as body_json, plus the
-// links and delivery id the sender adds. Named to stay clear of
-// alertwatch.go's alertMessage. ConfirmURL is set only on a verify row to
-// an unconfirmed connector, in place of the snooze and unsubscribe links.
+// links and delivery id the sender adds. ConfirmURL is set only on a verify
+// row to an unconfirmed connector, in place of the snooze and unsubscribe
+// links.
type alertNote struct {
Scope string `json:"scope"`
Rule string `json:"rule"`
@@ -498,7 +498,8 @@ func (s *Server) holdAlertRows(c alertConnector, hold string, now time.Time) err
// alertOwnerRevoked reports whether c is an operator's seeded connector
// whose owner is no longer an operator, deleting it and its queued rows
-// when so (Review Focus 4).
+// when so (Review Focus 4). Their seeded marker goes with it (ruling
+// R-26), so an operator granted again is seeded again.
func (s *Server) alertOwnerRevoked(c alertConnector) (bool, error) {
if c.OwnerAddress == "" {
return false, nil
@@ -508,7 +509,7 @@ func (s *Server) alertOwnerRevoked(c alertConnector) (bool, error) {
return false, err
}
log.Printf("console: %s is no longer an operator, so their alert connector %d is deleted", c.OwnerAddress, c.ID)
- if err := s.store.DeleteAlertConnector(c.Scope, c.ID); err != nil && !errors.Is(err, sql.ErrNoRows) {
+ if err := s.store.DeleteRevokedOperatorConnector(c.Scope, c.ID, c.OwnerAddress); err != nil && !errors.Is(err, sql.ErrNoRows) {
return false, err
}
return true, nil
diff --git a/internal/console/alertsignals.go b/internal/console/alertsignals.go
index 44114300a..30daf48df 100644
--- a/internal/console/alertsignals.go
+++ b/internal/console/alertsignals.go
@@ -40,11 +40,12 @@ const (
// their size is trusted.
engineBoxKeys = 200
engineBoxBodyBytes = 1 << 20
- // 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 drops heartbeat objects not written for a day
+ // before any read, as status.LoadBoxes does (ruling R-25): those objects
+ // are never deleted, one piles up per replaced box, and kept they would
+ // be box_silent members for ever and crowd real boxes out of the key
+ // cap. A box that drops out is gone: its heartbeat incidents close as
+ // "no further reports", after a day of silence and its reminders.
engineListingHorizon = 24 * time.Hour
)
@@ -115,12 +116,12 @@ func (r *engineReads) forget(prefix string, keys []string) {
}
// 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.
+// as status.LoadBoxes does: objects past the horizon are not listed, 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.
+// 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 {
@@ -165,10 +166,10 @@ func (r *engineReads) boxes(ctx context.Context, store release.Store, now time.T
return boxes, nil
}
-// 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.
+// engineBoxKeyList is one listing of status/boxes/ without the objects not
+// written within the horizon of now (the pass's clock), 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, now time.Time) ([]string, error) {
ml, ok := store.(release.ModLister)
if !ok {
@@ -179,15 +180,13 @@ func engineBoxKeyList(ctx context.Context, store release.Store, now time.Time) (
return store.List(ctx, alertStatusBoxesPrefix)
}
cut := now.Add(-engineListingHorizon)
- var current, old []string
+ keys := make([]string, 0, len(mods))
for _, m := range mods {
if m.Mod.IsZero() || !m.Mod.Before(cut) {
- current = append(current, m.Key)
- } else {
- old = append(old, m.Key)
+ keys = append(keys, m.Key)
}
}
- return append(current, old...), nil
+ return keys, nil
}
// fleet reads status/fleet.json conditionally. No object is a fleet that
diff --git a/internal/console/alertstore.go b/internal/console/alertstore.go
index eadae919e..8d0416226 100644
--- a/internal/console/alertstore.go
+++ b/internal/console/alertstore.go
@@ -508,8 +508,7 @@ func alertSeenFiring(tx *sql.Tx) (map[[2]string][]string, error) {
func seedOperatorAlertConnectors(tx *sql.Tx, ops []string, now time.Time) (map[string]int64, error) {
out := map[string]int64{}
for _, addr := range ops {
- marker := "seeded:" + strings.ToLower(strings.TrimSpace(addr))
- res, err := tx.Exec(`INSERT OR IGNORE INTO alert_meta (k, v) VALUES (?, ?)`, marker, now.UTC().Format(time.RFC3339))
+ res, err := tx.Exec(`INSERT OR IGNORE INTO alert_meta (k, v) VALUES (?, ?)`, alertSeededMarker(addr), now.UTC().Format(time.RFC3339))
if err != nil {
return nil, err
}
@@ -535,6 +534,11 @@ func seedOperatorAlertConnectors(tx *sql.Tx, ops []string, now time.Time) (map[s
return out, nil
}
+// alertSeededMarker is the alert_meta key recording that addr was seeded.
+func alertSeededMarker(addr string) string {
+ return "seeded:" + strings.ToLower(strings.TrimSpace(addr))
+}
+
// SeedOperatorAlertConnectors is seedOperatorAlertConnectors in a
// transaction of its own, for a start after the cutover has run.
func (s *Store) SeedOperatorAlertConnectors(ops []string, now time.Time) error {
@@ -739,13 +743,40 @@ func (s *Store) ConfirmAlertConnector(id int64) error {
// DeleteAlertConnector deletes connector id from scope, with its
// subscriptions, its unsent outbox rows and its tokens. sql.ErrNoRows: no
-// such connector in that scope.
+// such connector in that scope. A seeded connector's owner keeps their
+// seeded marker, so it is not seeded again (ruling R-24).
func (s *Store) DeleteAlertConnector(scope string, id int64) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
+ if err := deleteAlertConnectorTx(tx, scope, id); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// DeleteRevokedOperatorConnector is DeleteAlertConnector for a seeded
+// connector whose owner is no longer an operator: it also deletes owner's
+// seeded marker in the same transaction (ruling R-26), so an operator
+// granted again is seeded again.
+func (s *Store) DeleteRevokedOperatorConnector(scope string, id int64, owner string) error {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ if err := deleteAlertConnectorTx(tx, scope, id); err != nil {
+ return err
+ }
+ if _, err := tx.Exec(`DELETE FROM alert_meta WHERE k = ?`, alertSeededMarker(owner)); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+func deleteAlertConnectorTx(tx *sql.Tx, scope string, id int64) error {
res, err := tx.Exec(`DELETE FROM alert_connectors WHERE scope = ? AND id = ?`, scope, id)
if err != nil {
return err
@@ -764,7 +795,7 @@ func (s *Store) DeleteAlertConnector(scope string, id int64) error {
return err
}
}
- return tx.Commit()
+ return nil
}
// AlertConnectorTarget is connector id's stored target: sealed for Slack