carlos / platform Public

console: alert drain fix round 1 (bounded pass, holds, scope and health guards)

A drain pass now makes at most 50 sends within 60 s, re-reading the
outbox until nothing new is due. After a connector's first failed send
its other due rows are deferred to that row's retry time, unsent and
uncounted, so a dead endpoint costs one timeout a pass. Held rows
(unconfirmed for non-verify, suspended, needs re-entry, no seal) wait
5 minutes without an attempt or a health change (R-14), so they never
stand in front of a row that can go.

R-16: a completed send is recorded even if ctx ended just after; a
connector deleted mid-pass drops its row and the pass goes on; a row
whose note names another scope is dropped and logged; sendTestAlert
checks scope before the operator check; unconfirmed connectors get no
health record, so a failing confirmation never suspends; a suspension
with nobody to tell is logged.

Store: HoldConnectorOutbox, DeferConnectorOutbox.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a4c02cd705e39fc108fdda29da5c5744bc03f038 parent 1c6f176
4 files changed, +372 −68
  • internal/console/alertnotify.go +149 −60
  • internal/console/alertnotify_test.go +191 −2
  • internal/console/alertstore.go +24 −0
  • internal/console/server.go +8 −6

CI failed — run details

Intent

Human

<task-notification> <task-id>a03e8134cf429db95</task-id> <tool-use-id>toolu_01B7MCMVJBSFfo5VRqqYoy3Y</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a03e8134cf429db95.output</output-file> <status>completed</status> <summary>Agent "Implement Task 6: senders and outbox drain" 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:** 1c6f176f console: alert senders and outbox drain - **Tests:** all 13 tests the brief names pass, plus 4 extras (the R-11 suspension lift, test-send confirms, cancelled-context and 50-row batch). The `-race` run, vet, gofmt and the darwin/windows builds pass. The nearby alert, census and delivery tests pass too. The implementation passed first time, so I broke three guards on purpose to check the tests catch them; five tests failed, as they should. - **Concerns:** 1. `alertNote` has one field the brief's struct doesn't: `ConfirmURL`. Without it, verify rows had nowhere to carry the confirm link R-2 asks for. 2. I chose the confirm link shape, `&lt;origin&gt;/alerts/confirm/&lt;token&gt;`, since R-2 gives none. Task 10's route must match it. 3. Verify emails end with the confirm link, and the suspension email sent straight to owners has no unsubscribe link. Both depart from "always ends with the unsubscribe link". 4. Held rows (unconfirmed, suspended, needs re-entry, no seal) are put back as failed attempts and back off to 12 h. This stops them filling every batch, but a row may go out up to 12 h after the connector is confirmed or resumed. 5. A test to a confirmed Slack connector carries an unsubscribe link, not a confirm link. 6. The incident link is the `/fleet/alerts/history` page for every scope, including accounts. 7. Tokens are minted again on each retry, and nothing prunes them. 8. Adding the Server fields meant editing `server.go`. One new seal `Open` call is added to the authority census fixture and named in the commit. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-6-report.md</result> <usage><subagent_tokens>209171</subagent_tokens><tool_uses>63</tool_uses><duration_ms>1203771</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>ac563aa7e35434157</task-id> <tool-use-id>toolu_01VzssFu91AM3dyvAbKkQscT</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/ac563aa7e35434157.output</output-file> <status>completed</status> <summary>Agent "Review Task 6 (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 for everything the brief lists. Both new files are present. `alertNote` has every field the brief names. `renderSlack`, `renderWebhook` (all 14 keys), `renderEmail`, `alertDrainOutbox` (50 rows), `sendTestAlert` (refuses unconfirmed email, 10 per connector per hour, Slack confirm link, webhook confirmed by a 2xx), email through `s.deliver(…, 12s)`, `FinishOutbox` on every row, the one suspension notice, and all 13 named tests are there. - The brief's struct has one extra field, `ConfirmURL`, and verify emails end with the confirm link. R-15 accepts both. - ⚠️ Cannot verify from the diff: - **Confirmation-send limit (5 per scope per hour, 20 per day):** neither the drain nor `sendTestAlert` enforces it. A test to an unconfirmed Slack connector carries a confirm link, so it is a confirmation send, but it only counts against the 10-per-connector limit (`alertnotify.go:586`). Check that Task 10 enforces the scope limit when it queues `verify` rows, and decide whether unconfirmed Slack tests count toward it. - **Owner-email notice has no unsubscribe link** (`alertnotify.go:519-526`). The direct suspension email to owners breaks "every email ends with an unsubscribe link". No connector is involved, so there is nothing to bind an unsubscribe token to. The controller should accept this or rule on it. - **Incident link always points at `/fleet/alerts/history`** (`alertnotify.go:443`), including for `account:` scopes. Task 10 owns that route. - **Pass duration and the engine loop:** whether a long drain pass delays engine evaluation depends on how Task 8 schedules the drain. ### Strengths - The connector is read fresh for every row, retries included (`alertnotify.go:284`, via `usableAlertConnector`). The operator re-check runs before every send and before every test. A revoked operator's connector is deleted, and `DeleteAlertConnector` (`alertstore.go:600-625`, checked) also deletes its unsent rows, subscriptions and tokens. - **Consent (risk 1), clean.** - `alertWithheld` (`:374`) holds every non-`verify` row to an unconfirmed connector of any kind, and runs again on each retry. - `tellAlertSuspended` only queues to connectors that pass `alertWithheld`. - Test sends refuse unconfirmed email. - Connector targets are never updated in place (checked: no `UPDATE … target_sealed` in `alertstore.go`), so there is no window between reading the connector and reading its target. - **Secrets (risk 3).** - Only categories reach `err_category` and the log (`:321-323`). Seal errors become `"seal"` (`:400-402`), and test errors are `"alert test: &lt;cat&gt;"`. - `deliver` (`delivery.go:41-81`, checked) logs the address and the provider error, never the body. Tokens live only in the body. - The opened target is a local of `drainAlertRow` and is not stored on the Server. - **Signature (risk 4).** `signAlert(key, now, body)` signs the same `body` slice that goes to `postAlert` (`:464-468`). The drain test checks the signature over the bytes that were received. `delivery_id`, `what`, `how_long`, `what_to_do` and a snooze token bound to the incident key are all asserted in `TestRenderWebhookCarriesContent`. - **Suspension (risk 5).** `SetConnectorHealth` returns `suspendedNow` only on the transition (`alertstore.go:656-658`). The notice excludes the connector itself (`o.ID != c.ID`) and any other suspended connector. If a fallback is suspended later, its notice can't go back to the first connector because that one is suspended, so there is no loop. - Slack escaping stops `&lt;!channel&gt;` injection, email subjects have CR/LF stripped, and the copy map is tested for em dashes. Held rows and no-seal rows mint no tokens, because links are minted only after `alertTarget` (`:303-310`). The mutation check in the report is real evidence that the tests can fail. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) 1. **`alertnotify.go:264-277`: a drain pass has no time bound, and a dead connector pays a full timeout on every one of its rows.** - **What's wrong:** Each row is bounded: 5 s for HTTP (`alertdial.go:42,161`, checked) and 20 s for email (`:455`). But the loop keeps sending to a connector that just timed out, so a pass can run for up to 50 × 5 s ≈ 4 min of HTTP, or 50 × 20 s ≈ 17 min of email. The owner-email fallback (`:519`) adds 20 s per owner on top. This is the answer to named risk 6: each row is bounded, but the pass is not. - **Starvation:** with `DueOutbox` ordered `next_at, id` (`alertstore.go:438`, checked), a failed row moves to a later `next_at`, so a dead connector can't starve others for good. It does delay every other connector's due rows by minutes per pass. - **Fix:** after a connector's first failed send in a pass, push its remaining due rows forward without sending them (one `UPDATE … next_at` per connector, so they also leave the batch). Also add a pass deadline (for example 60 s), after which the remaining rows stay due. - **Note for the R-14 fix:** if held rows stop counting as attempts but stay due at the same `next_at`, they will sit at the head of `ORDER BY next_at, id` and fill every 50-row batch. Exclude held connectors in `DueOutbox`'s SQL, or move `next_at` without touching `attempts`. #### Minor (Nice to Have) 1. **`alertnotify.go:317`: a send that succeeded is thrown away if ctx ends just after it returns.** The row stays due and is sent again on the next start: a visible duplicate on Slack or email. The cancellation ruling covers an interrupted send, not a finished one. Only return early when `cat != ""`. 2. **`alertnotify.go:389-392`: deleting a connector between `AlertConnector` and `AlertConnectorTarget` aborts the whole pass.** `AlertConnectorTarget` returns `sql.ErrNoRows`, which is passed up as an error. The next pass drops the row, so this heals itself. Mapping `ErrNoRows` to `DropOutbox` here is cleaner. 3. **`alertnotify.go:285-287, 310-315, 464-467`: one console-side error on a single row (token insert, signing-key read) ends the pass for all later rows.** `ed25519Key` creates the key on first use (`store.go:3012`, checked), so only a corrupt key fails every time. Consider logging and skipping the row instead. 4. **`alertnotify.go:428`: the snooze token is bound to `n.Scope` from `body_json`, while the unsubscribe token uses `c.Scope`.** If the engine ever queued a fleet note to an `account:` connector, that account could snooze a fleet rule. As defence in depth, drop or hold a row whose note scope is set and differs from `c.Scope`. 5. **`alertnotify.go:573-577`: `sendTestAlert` runs the operator check, and possibly the delete, before the scope check.** A caller in another scope can trigger deletion of a revoked operator's fleet connector. That connector should be deleted anyway, but checking scope first keeps each request acting only on its own scope. 6. **`alertnotify.go:332`: failed `verify` sends count against an unconfirmed connector's health.** - After 24 h of a bouncing confirmation, the unconfirmed email connector is suspended. - Its owners are then told "alerts have stopped" about a connector that never worked. - Its later `verify` rows are held as "suspended" (`:376-377` comes before the verify check). - A test can't lift the suspension, because tests are refused for unconfirmed email. - It stays stuck until someone deletes it. Consider skipping health updates for unconfirmed connectors. 7. **`alertnotify.go:586-592`: the test limit is spent before `alertTarget`'s hold.** A "no seal key" result still uses up one of the 10 tests. 8. **`alertnotify.go:541`: a deleted account means no owners, and nothing is sent or logged.** The suspension notice is lost silently. Log it. 9. **Test gaps (`alertnotify_test.go`):** - No test has the fallback connector fail as well (the no-loop case of risk 5). - `TestDrainSuspendsAfter24hTellsOnce`'s "owner email" subtest (`:456`) only covers the fleet scope, not `account:` owners. - No test sends a test to a revoked operator's connector (report concern 9). 10. **`alertnotify.go:400-405`: the decrypted bytes `p` are not cleared after `string(p)`.** Go strings can't be wiped either, so the gain is small. It would also be tidier to open the target after `addAlertLinks`, just before the send, so the URL is held only for the send itself. ### Assessment **Task quality:** Needs fixes **Reasoning:** Consent, the operator re-check, keeping secrets out, the signature and the suspension notice are all correct and tested. What needs fixing is that a pass has no time bound: a dead or timing-out connector costs a full timeout on each of up to 50 rows per pass. The R-14 fix must also avoid making held rows block the head of the 50-row batch.</result> <usage><subagent_tokens>104002</subagent_tokens><tool_uses>11</tool_uses><duration_ms>218831</duration_ms></usage> </task-notification>

Attributed to this commit: 20.1 g CO₂e (2,535,061 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/alertnotify.go b/internal/console/alertnotify.go
index cc4e2b80e..6f1b6821e 100644
--- a/internal/console/alertnotify.go
+++ b/internal/console/alertnotify.go
@@ -37,13 +37,19 @@ import (
)
const (
- // alertDrainBatch is the most rows one drain pass reads.
+ // alertDrainBatch is the most sends one drain pass makes, and the rows
+ // it reads at a time.
alertDrainBatch = 50
// An email send's whole budget, and Keymail's share of it (deliver).
alertEmailTimeout = 20 * time.Second
alertKeymailShare = 12 * time.Second
alertSnoozeLinkTTL = 30 * 24 * time.Hour
alertConfirmLinkTTL = 7 * 24 * time.Hour
+ // alertPassBudget bounds one drain pass. A send in flight finishes.
+ alertPassBudget = 60 * time.Second
+ // alertHoldRecheck is how long a held row waits before it is looked at
+ // again (ruling R-14).
+ alertHoldRecheck = 5 * time.Minute
// alertTestsPerHour is each connector's test sends in an hour (spec
// §5.3).
alertTestsPerHour = 10
@@ -257,120 +263,193 @@ func (s *Server) alertClient() *http.Client {
return s.alertHTTP
}
-// alertDrainOutbox sends up to alertDrainBatch due outbox rows, each ending
-// in FinishOutbox. When ctx ends (the console shutting down) it stops and
-// returns ctx's error, leaving the row in hand due and its connector's
-// health untouched: shutdown is not a connector failing.
+// alertDrainOutbox sends what is due, at most alertDrainBatch sends a pass
+// and for at most alertPassBudget, reading the outbox alertDrainBatch rows
+// at a time. Every row it reads leaves the due set (sent, backed off, held,
+// deferred or dropped), so rows that cannot go never fill the head of the
+// queue in front of one that can.
+//
+// One failed send per connector a pass: the connector's other due rows are
+// deferred to the failed row's retry time unsent, so a dead endpoint costs
+// one timeout a pass, not one per row. When ctx ends (the console shutting
+// down) the drain stops and returns ctx's error, leaving the row in hand
+// due and its connector's health untouched: shutdown is not a connector
+// failing. When the budget runs out it stops and leaves the rest due.
func (s *Server) alertDrainOutbox(ctx context.Context) error {
- rows, err := s.store.DueOutbox(s.alertClockNow(), alertDrainBatch)
- if err != nil {
- return err
- }
- for _, r := range rows {
- if err := ctx.Err(); err != nil {
+ start := time.Now()
+ budget := s.alertPassBudget
+ if budget == 0 {
+ budget = alertPassBudget
+ }
+ failed := map[int64]bool{}
+ seen := map[int64]bool{}
+ sends := 0
+ for {
+ rows, err := s.store.DueOutbox(s.alertClockNow(), alertDrainBatch)
+ if err != nil {
return err
}
- if err := s.drainAlertRow(ctx, r); err != nil {
- return err
+ fresh := false
+ for _, r := range rows {
+ if seen[r.ID] {
+ continue
+ }
+ fresh, seen[r.ID] = true, true
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if sends >= alertDrainBatch || time.Since(start) >= budget {
+ return nil
+ }
+ if failed[r.ConnectorID] {
+ continue // deferred with the failure
+ }
+ out, err := s.drainAlertRow(ctx, r)
+ if err != nil {
+ return err
+ }
+ switch out {
+ case alertRowFailed:
+ failed[r.ConnectorID] = true
+ sends++
+ case alertRowSent:
+ sends++
+ }
+ }
+ // A short read had everything that was due; a read with nothing new
+ // is a row that did not leave the due set, which must not spin.
+ if len(rows) < alertDrainBatch || !fresh {
+ return nil
}
}
- return nil
}
-func (s *Server) drainAlertRow(ctx context.Context, r alertOutboxRow) error {
+// alertRowOutcome is what drainAlertRow did with a row.
+type alertRowOutcome int
+
+const (
+ alertRowSkipped alertRowOutcome = iota // held, dropped, or not tried
+ alertRowSent
+ alertRowFailed
+)
+
+func (s *Server) drainAlertRow(ctx context.Context, r alertOutboxRow) (alertRowOutcome, error) {
now := s.alertClockNow()
- c, ok, err := s.usableAlertConnector(r.ConnectorID)
+ c, err := s.store.AlertConnector(r.ConnectorID)
+ if errors.Is(err, sql.ErrNoRows) {
+ return alertRowSkipped, s.store.DropOutbox(r.ID) // nothing is owed to a deleted connector
+ }
if err != nil {
- return err
+ return alertRowSkipped, err
}
- if !ok {
- // Deleted, or deleted just now for a revoked operator: nothing is
- // owed to it any more.
- return s.store.DropOutbox(r.ID)
+ if revoked, err := s.alertOwnerRevoked(c); err != nil || revoked {
+ return alertRowSkipped, err // deleted with its rows
}
if hold := alertWithheld(c, r.Kind); hold != "" {
- return s.store.FinishOutbox(r.ID, hold, false, now)
+ return alertRowSkipped, s.holdAlertRows(c, hold, now)
}
var n alertNote
if err := json.Unmarshal(r.Body, &n); err != nil {
log.Printf("console: alert outbox row %d does not decode, dropping it: %v", r.ID, err)
- return s.store.DropOutbox(r.ID)
+ return alertRowSkipped, s.store.DropOutbox(r.ID)
+ }
+ // One scope's alert never reaches another scope's connector, whatever
+ // queued it.
+ if n.Scope != "" && n.Scope != c.Scope {
+ log.Printf("console: alert outbox row %d is for scope %s but connector %d is in %s, dropping it", r.ID, n.Scope, c.ID, c.Scope)
+ return alertRowSkipped, s.store.DropOutbox(r.ID)
}
n.Kind, n.DeliveryID = r.Kind, r.DeliveryID
if n.At.IsZero() {
n.At = now
}
target, hold, err := s.alertTarget(c)
+ if errors.Is(err, sql.ErrNoRows) {
+ return alertRowSkipped, s.store.DropOutbox(r.ID) // deleted since it was read
+ }
if err != nil {
- return err
+ return alertRowSkipped, err
}
if hold != "" {
- return s.store.FinishOutbox(r.ID, hold, false, now)
+ return alertRowSkipped, s.holdAlertRows(c, hold, now)
}
if err := s.addAlertLinks(c, r.IncidentID, &n, now); err != nil {
- return err
+ return alertRowSkipped, err
}
cat, err := s.sendAlertNote(ctx, c, target, n, now)
if err != nil {
- return err
- }
- if err := ctx.Err(); err != nil {
- return err
+ return alertRowSkipped, err
}
sent := cat == ""
+ // A send cut short by shutdown is not the connector's failure. One that
+ // completed is recorded, even if ctx ended just after.
+ if !sent && ctx.Err() != nil {
+ return alertRowSkipped, ctx.Err()
+ }
if !sent {
log.Printf("console: alert %s to %s connector %d not sent: %s", r.Kind, c.Kind, c.ID, cat)
}
if err := s.store.FinishOutbox(r.ID, string(cat), sent, now); err != nil {
- return err
+ return alertRowSkipped, err
+ }
+ if !sent {
+ if err := s.store.DeferConnectorOutbox(c.ID, r.ID); err != nil {
+ return alertRowFailed, err
+ }
}
if sent && r.Kind == "verify" && c.Kind == alertConnectorWebhook && !c.Confirmed {
if err := s.store.ConfirmAlertConnector(c.ID); err != nil {
- return err
+ return alertRowSent, err
}
}
+ out := alertRowSent
+ if !sent {
+ out = alertRowFailed
+ }
+ // Health is a confirmed connector's: a connector that never worked is
+ // not suspended for failing its confirmation.
+ if !c.Confirmed {
+ return out, nil
+ }
suspendedNow, err := s.store.SetConnectorHealth(c.ID, sent, now)
if err != nil {
- return err
+ return out, err
}
if suspendedNow {
if err := s.tellAlertSuspended(ctx, c, now); err != nil {
log.Printf("console: alert connector %d suspended, and telling its owners failed: %v", c.ID, err)
}
}
- return nil
+ return out, nil
}
-// usableAlertConnector reads connector id before a send. ok is false when
-// it is gone, including when its owner is no longer an operator: such a
-// connector is deleted here, with its queued rows (Review Focus 4).
-func (s *Server) usableAlertConnector(id int64) (c alertConnector, ok bool, err error) {
- c, err = s.store.AlertConnector(id)
- if errors.Is(err, sql.ErrNoRows) {
- return c, false, nil
+// holdAlertRows puts c's due rows that hold applies to aside for
+// alertHoldRecheck (ruling R-14): not an attempt, nothing against the
+// connector's health. An unconfirmed connector's verify rows are not held.
+func (s *Server) holdAlertRows(c alertConnector, hold string, now time.Time) error {
+ return s.store.HoldConnectorOutbox(c.ID, hold, hold != "unconfirmed", now.Add(alertHoldRecheck))
+}
+
+// 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).
+func (s *Server) alertOwnerRevoked(c alertConnector) (bool, error) {
+ if c.OwnerAddress == "" {
+ return false, nil
}
- if err != nil {
- return c, false, err
+ op, err := s.store.IsOperator(c.OwnerAddress)
+ if err != nil || op {
+ return false, err
}
- if c.OwnerAddress != "" {
- op, err := s.store.IsOperator(c.OwnerAddress)
- if err != nil {
- return c, false, err
- }
- if !op {
- 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) {
- return c, false, err
- }
- return c, false, nil
- }
+ 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) {
+ return false, err
}
- return c, true, nil
+ return true, nil
}
// alertWithheld is why a row of kind may not go to c now, "" when it may.
-// A withheld row is retried on the outbox's backoff and never counts
-// against the connector's health.
+// A withheld row is held (holdAlertRows), never counted as an attempt.
func alertWithheld(c alertConnector, kind string) string {
switch {
case c.NeedsReentry:
@@ -515,6 +594,9 @@ func (s *Server) tellAlertSuspended(ctx context.Context, c alertConnector, now t
if err != nil {
return err
}
+ if len(owners) == 0 {
+ log.Printf("console: alert connector %d in %s suspended, and there is no other connector and no owner to tell", c.ID, c.Scope)
+ }
subject, text := renderEmail(n)
for _, addr := range owners {
ectx, cancel := context.WithTimeout(ctx, alertEmailTimeout)
@@ -570,11 +652,18 @@ var (
// no such connector in scope.
func (s *Server) sendTestAlert(ctx context.Context, scope string, id int64) error {
now := s.alertClockNow()
- c, ok, err := s.usableAlertConnector(id)
+ c, err := s.store.AlertConnector(id)
if err != nil {
return err
}
- if !ok || c.Scope != scope {
+ // Scope first: a request from another scope must not get as far as
+ // deleting anything.
+ if c.Scope != scope {
+ return sql.ErrNoRows
+ }
+ if revoked, err := s.alertOwnerRevoked(c); err != nil {
+ return err
+ } else if revoked {
return sql.ErrNoRows
}
if c.Kind == alertConnectorEmail && !c.Confirmed {
diff --git a/internal/console/alertnotify_test.go b/internal/console/alertnotify_test.go
index df2c13e94..d0aac23ad 100644
--- a/internal/console/alertnotify_test.go
+++ b/internal/console/alertnotify_test.go
@@ -45,7 +45,9 @@ type hookRecorder struct {
// hold, when set, keeps each request open until the request's own
// context ends.
hold bool
- got chan struct{}
+ // holdPath holds only requests to this path.
+ holdPath string
+ got chan struct{}
}
type hookReq struct {
@@ -58,7 +60,7 @@ func (h *hookRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
h.mu.Lock()
h.reqs = append(h.reqs, hookReq{path: r.URL.Path, sig: r.Header.Get("Carlos-Signature"), body: body})
- status, hold := h.status, h.hold
+ status, hold := h.status, h.hold || (h.holdPath != "" && r.URL.Path == h.holdPath)
h.mu.Unlock()
select {
case h.got <- struct{}{}:
@@ -886,3 +888,190 @@ func TestDrainBatchOf50(t *testing.T) {
t.Errorf("%d sends in one pass, want 50", n)
}
}
+
+// Fix round 1, item 1: a connector that times out costs one timeout a pass.
+// Its other rows are deferred to the failed row's retry unsent, with no
+// attempt counted, and another connector's row in the same batch still goes.
+func TestDrainDeadConnectorOneTimeoutAPass(t *testing.T) {
+ nf := newNotifyFixture(t)
+ c := pointAlertClientAt(t, nf.hookSrv, allowLoopback)
+ c.Timeout = 300 * time.Millisecond
+ nf.srv.alertHTTP = c
+ nf.hook.mu.Lock()
+ nf.hook.holdPath = "/dead"
+ nf.hook.mu.Unlock()
+ dead := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/dead", true)
+ live := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/live", true)
+ for i := 0; i < 10; i++ {
+ nf.queue(t, dead, 0, "fire", fireNote())
+ }
+ nf.queue(t, live, 0, "fire", fireNote())
+ deadHits := func() (n int) {
+ for _, r := range nf.hook.requests() {
+ if r.path == "/dead" {
+ n++
+ }
+ }
+ return n
+ }
+ nf.drain(t)
+ if n := deadHits(); n != 1 {
+ t.Fatalf("%d sends to the dead connector in one pass, want 1", n)
+ }
+ if got := nf.outbox(t, live); len(got) != 1 || !got[0].sent {
+ t.Errorf("the live connector's row: %+v, want sent", got)
+ }
+ tried := 0
+ for _, o := range nf.outbox(t, dead) {
+ if o.sent || o.attempts > 1 {
+ t.Errorf("dead row %+v", o)
+ }
+ tried += o.attempts
+ }
+ if tried != 1 {
+ t.Errorf("%d attempts counted, want 1", tried)
+ }
+ var due int
+ if err := nf.st.db.QueryRow(`SELECT COUNT(*) FROM alert_outbox WHERE connector_id = ? AND next_at != ?`,
+ dead, alertT0.Add(time.Minute).Unix()).Scan(&due); err != nil {
+ t.Fatal(err)
+ }
+ if due != 0 {
+ t.Errorf("%d dead rows not deferred to the failed row's retry", due)
+ }
+ nf.drain(t) // nothing due
+ nf.now = alertT0.Add(time.Minute)
+ nf.drain(t)
+ if n := deadHits(); n != 2 {
+ t.Errorf("%d sends to the dead connector after two passes with rows due, want 2", n)
+ }
+}
+
+// Fix round 1, item 1: a pass past its budget stops and leaves rows due.
+func TestDrainPassDeadline(t *testing.T) {
+ nf := newNotifyFixture(t)
+ id := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", true)
+ nf.queue(t, id, 0, "fire", fireNote())
+ nf.srv.alertPassBudget = time.Nanosecond
+ nf.drain(t)
+ if got := nf.outbox(t, id); len(got) != 1 || got[0].sent || got[0].attempts != 0 {
+ t.Errorf("outbox = %+v, want the row left due", got)
+ }
+ nf.srv.alertPassBudget = 0
+ nf.drain(t)
+ if got := nf.outbox(t, id); !got[0].sent {
+ t.Errorf("outbox = %+v, want sent by the next pass", got)
+ }
+}
+
+// Ruling R-14: held rows are not attempts and never stand in front of a row
+// that can go. A hold is looked at again after 5 minutes.
+func TestDrainHeldRowsDoNotBlock(t *testing.T) {
+ nf := newNotifyFixture(t)
+ held := nf.addEmail(t, "fleet", "new@example.com", "", false)
+ ok := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", true)
+ for i := 0; i < 60; i++ {
+ nf.queue(t, held, 0, "fire", fireNote())
+ }
+ nf.queue(t, ok, 0, "fire", fireNote())
+ nf.drain(t)
+ if got := nf.outbox(t, ok); !got[0].sent {
+ t.Fatalf("the sendable row behind 60 held rows: %+v", got)
+ }
+ for _, o := range nf.outbox(t, held) {
+ if o.sent || o.attempts != 0 || o.cat != "unconfirmed" {
+ t.Fatalf("held row %+v, want unsent with no attempt", o)
+ }
+ }
+ if c := nf.connector(t, held); !c.FailingSince.IsZero() {
+ t.Error("a hold counted against the connector's health")
+ }
+ if err := nf.st.ConfirmAlertConnector(held); err != nil {
+ t.Fatal(err)
+ }
+ nf.now = alertT0.Add(4 * time.Minute)
+ nf.drain(t)
+ if n := len(nf.mail.sentCopy()); n != 0 {
+ t.Fatalf("%d sent before the recheck", n)
+ }
+ nf.now = alertT0.Add(alertHoldRecheck)
+ nf.drain(t)
+ nf.drain(t) // 50 sends a pass
+ if n := len(nf.mail.sentCopy()); n != 60 {
+ t.Errorf("%d of the 60 held rows sent at the recheck after confirming", n)
+ }
+}
+
+// A row whose note names another scope never reaches this connector.
+func TestDrainDropsOtherScopeRow(t *testing.T) {
+ var logs bytes.Buffer
+ prev := log.Writer()
+ log.SetOutput(&logs)
+ t.Cleanup(func() { log.SetOutput(prev) })
+ nf := newNotifyFixture(t)
+ id := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", true)
+ n := fireNote()
+ n.Scope = "account:other"
+ nf.queue(t, id, 0, "fire", n)
+ nf.drain(t)
+ if r := nf.hook.requests(); len(r) != 0 {
+ t.Fatalf("%d sends of another scope's alert", len(r))
+ }
+ if got := nf.outbox(t, id); len(got) != 0 {
+ t.Errorf("outbox = %+v, want the row dropped", got)
+ }
+ if !strings.Contains(logs.String(), "account:other") {
+ t.Errorf("the drop was not logged:\n%s", logs.String())
+ }
+}
+
+// A connector that never worked is not suspended for failing its
+// confirmation: health is only a confirmed connector's.
+func TestDrainUnconfirmedFailingNotSuspended(t *testing.T) {
+ nf := newNotifyFixture(t)
+ id := nf.addHook(t, alertConnectorSlack, "https://hooks.slack.com/services/T/B/x", false)
+ nf.hook.setStatus(http.StatusNotFound)
+ nf.queue(t, id, 0, "verify", alertNote{Scope: "fleet", Kind: "verify", Subject: "slack",
+ What: "A test", HowLong: "7 days", WhatToDo: "Open the link"})
+ nf.drain(t)
+ nf.now = alertT0.Add(25 * time.Hour)
+ nf.drain(t)
+ if n := len(nf.hook.requests()); n != 2 {
+ t.Fatalf("%d sends, want 2", n)
+ }
+ if c := nf.connector(t, id); c.Suspended || !c.FailingSince.IsZero() {
+ t.Errorf("unconfirmed connector: suspended %v, failing since %v", c.Suspended, c.FailingSince)
+ }
+ if n := alertCount(t, nf.st, "alert_outbox"); n != 1 {
+ t.Errorf("%d outbox rows, want only the verify (no suspension notice)", n)
+ }
+}
+
+// A test asked for from another scope fails before the operator check, so
+// it can delete nothing.
+func TestTestSendScopeBeforeOperatorCheck(t *testing.T) {
+ nf := newNotifyFixture(t)
+ const op = "ops-a@example.com"
+ if err := nf.st.SetOperator(op, true); err != nil {
+ t.Fatal(err)
+ }
+ id := nf.addEmail(t, "fleet", op, op, true)
+ if err := nf.st.SetOperator(op, false); err != nil {
+ t.Fatal(err)
+ }
+ if err := nf.srv.sendTestAlert(context.Background(), "account:other", id); !errors.Is(err, sql.ErrNoRows) {
+ t.Fatalf("another scope's test = %v, want sql.ErrNoRows", err)
+ }
+ if _, err := nf.st.AlertConnector(id); err != nil {
+ t.Fatalf("another scope's test touched the connector: %v", err)
+ }
+ if err := nf.srv.sendTestAlert(context.Background(), "fleet", id); !errors.Is(err, sql.ErrNoRows) {
+ t.Fatalf("own scope's test = %v, want sql.ErrNoRows", err)
+ }
+ if _, err := nf.st.AlertConnector(id); !errors.Is(err, sql.ErrNoRows) {
+ t.Errorf("the revoked operator's connector: %v, want deleted", err)
+ }
+ if sent := nf.mail.sentCopy(); len(sent) != 0 {
+ t.Errorf("sent %q", sent)
+ }
+}
diff --git a/internal/console/alertstore.go b/internal/console/alertstore.go
index a8253871b..0908a7273 100644
--- a/internal/console/alertstore.go
+++ b/internal/console/alertstore.go
@@ -489,6 +489,30 @@ func (s *Store) DropOutbox(id int64) error {
return err
}
+// HoldConnectorOutbox moves connector id's unsent rows due before until to
+// until, recording cat, without counting an attempt (ruling R-14): rows
+// that may not go to it yet (suspended, unconfirmed, needing re-entry) wait
+// in one statement instead of filling the head of the queue. verifyToo
+// false leaves its verify rows due, which an unconfirmed connector may
+// still receive.
+func (s *Store) HoldConnectorOutbox(id int64, cat string, verifyToo bool, until time.Time) error {
+ _, err := s.db.Exec(`UPDATE alert_outbox SET next_at = ?, err_category = ?
+ WHERE connector_id = ? AND sent_at IS NULL AND next_at < ? AND (? OR kind != 'verify')`,
+ until.Unix(), cat, id, until.Unix(), verifyToo)
+ return err
+}
+
+// DeferConnectorOutbox moves connector id's other unsent rows due before
+// failed row's retry time to that time, unsent and without counting an
+// attempt: one dead endpoint costs one failed send a pass, not one per
+// row queued for it.
+func (s *Store) DeferConnectorOutbox(id, failed int64) error {
+ _, err := s.db.Exec(`UPDATE alert_outbox SET next_at = (SELECT next_at FROM alert_outbox WHERE id = ?)
+ WHERE connector_id = ? AND sent_at IS NULL AND id != ? AND next_at < (SELECT next_at FROM alert_outbox WHERE id = ?)`,
+ failed, id, failed, failed)
+ return err
+}
+
func alertRetryBackoff(attempts int) time.Duration {
d := alertRetryFirst
for i := 0; i < attempts && d < alertRetryCap; i++ {
diff --git a/internal/console/server.go b/internal/console/server.go
index bfec2b1fc..4e154484b 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1003,12 +1003,14 @@ type Server struct {
// alertSeal opens connector targets once the engine has read its key;
// nil until then, and every sealed target is unusable meanwhile.
// alertTests is each connector's test sends in the last hour.
- // alertClock is time.Now outside tests.
- alertHTTP *http.Client
- alertHTTPOnce sync.Once
- alertSeal atomic.Pointer[connectorSeal]
- alertTests alertTestWindow
- alertClock func() time.Time
+ // alertClock is time.Now outside tests, and alertPassBudget 0 (one
+ // drain pass's alertPassBudget) outside tests.
+ alertHTTP *http.Client
+ alertHTTPOnce sync.Once
+ alertSeal atomic.Pointer[connectorSeal]
+ alertTests alertTestWindow
+ alertClock func() time.Time
+ alertPassBudget time.Duration
// perf records every request but /healthz; handler is the mux wrapped
// in its middleware, and is what serveAdmitted serves (NewServer).
perf *perf.Recorder