Bound demo delivery after fleet alert evaluation
7 files changed,
+170
−20
docs/superpowers/notes/demo-abuse-alerts.md+9 −6docs/superpowers/reviews/REVIEW-CHECK-demo-abuse-alerts-R1.md+47 −0docs/superpowers/reviews/REVIEW-FINDINGS-demo-abuse-alerts-R1.md+35 −0internal/console/alertengine_pass.go+6 −4internal/console/demo_alert_copy.go+1 −0internal/console/demo_alerts.go+19 −4internal/console/demo_alerts_test.go+53 −6
diff --git a/docs/superpowers/notes/demo-abuse-alerts.md b/docs/superpowers/notes/demo-abuse-alerts.md| index 268a9ce25..e00b50dad 100644 |
| --- a/docs/superpowers/notes/demo-abuse-alerts.md |
| +++ b/docs/superpowers/notes/demo-abuse-alerts.md |
| @@ -55,6 +55,8 @@ site allocation; it is a concentration hint, not proof of one person. |
| Old admission rows have NULL prefixes until they expire. No raw address is |
| added. Prefixes disappear with their admission rows after 24h. Refusals store |
| only bounded minute counters, pruned after 24h, including during quiet periods. |
| +Refusals include serving-off and readiness denials, but exclude invalid uploads |
| +and updates. Counting remains active while notifications are disabled. |
| Existing app abuse metadata and its retention are unchanged. |
| A persistent firing bit per recipient prevents repeated mail while a condition |
| @@ -93,18 +95,19 @@ zero. Windows must be whole minutes from 1m through 24h. Invalid settings fail |
| startup. To enable, set ENABLED=true, configure CARLOS_SYSTEM_OPERATORS (ops |
| owners also receive notices), and use an already verified console mail sender |
| or the operator's existing Keymail grant. A newly verified identity needs an |
| -ordinary mail readiness check or a console restart before alerts can use it. Settings do not change demo limits. |
| - |
| -The worker runs once a minute while enabled, including when serving is off. |
| +ordinary mail readiness check or a console restart before alerts can use it. |
| +The existing minute loop attempts the fleet pass and heartbeat, then demo |
| +alerts, even if fleet reads failed. Demo sends have a 60s pass budget and stop |
| +on a transport timeout. Demo errors are logged separately from the fleet job. |
| Immediate reports therefore arrive on the next pass rather than waiting for |
| the digest. Costs are a handful of indexed SQLite aggregates per minute, |
| local counter writes on refused admissions, and mail only on transitions or |
| nonempty digests. Alert text contains aggregate counts, never IP hashes, |
| report details, demo names or claim tokens. |
| -Implementation: `internal/console/demo_alerts.go:101` evaluates signals and |
| -`:162` runs the guarded pass before fleet reads. `:235` handles digests. |
| -The settings loader is at `:27`; `demo_alert_admission.go:76` persists refusals. |
| +Implementation: `internal/console/demo_alerts.go:101` evaluates signals; |
| +`:162` runs the guarded pass. The settings loader is at `:27`; |
| +`demo_alert_admission.go:76` persists refusals. |
| ## Open questions before activation |
diff --git a/docs/superpowers/reviews/REVIEW-CHECK-demo-abuse-alerts-R1.md b/docs/superpowers/reviews/REVIEW-CHECK-demo-abuse-alerts-R1.md| new file mode 100644 |
| index 000000000..74657f6fc |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/REVIEW-CHECK-demo-abuse-alerts-R1.md |
| @@ -0,0 +1,47 @@ |
| +# Demo abuse alerts: round 1 fix check |
| + |
| +Review history: Opus round 1 reviewed `9622c65a..5c9fb44b` and found no P1, |
| +two P2, verdict READY AFTER FIXES. See REVIEW-FINDINGS-demo-abuse-alerts-R1.md. |
| +The full review is closed under AGENTS.md. This is the required check of the |
| +new storage/mail behaviour in its fixes, within round 1, not a new full review. |
| + |
| +Repo carlos/platform, branch demo-abuse-alerts. The launch prompt supplies the |
| +exact tip. Check only `5c9fb44b..tip` in these files: |
| + |
| +- internal/console/demo_alerts.go and demo_alerts_test.go |
| +- internal/console/consolemail.go |
| +- internal/console/alertengine_pass.go |
| +- internal/console/store_gate.go |
| + |
| +The fixed task and authorities are in REVIEW-BRIEF-demo-abuse-alerts-R1.md. |
| +No previous P1; no findings declined. P3 suggestions remain follow-ups in the |
| +findings file. Do not reopen those or review the whole branch again. |
| + |
| +## Fixes to check |
| + |
| +1. P2.1, fleet liveness: the existing loop finishes its fleet pass and heartbeat |
| + before demo delivery. A demo pass has a 60s deadline and stops on the first |
| + transport timeout. Demo errors are logged separately; they no longer mark |
| + the fleet job failed. The isolated signals still require no S3 reads. |
| +2. P2.2, report completeness: b9f4b53a replaces timestamp-only delivery progress |
| + with a per-recipient JSON snapshot of observed report IDs. Check the schema, |
| + bound (existing report queue max 2,000), exact snapshot committed only after |
| + successful delivery, late commits, empty-day pruning and first-digest window. |
| + The new table does not exist on main; this branch has never been deployed. |
| +3. Mail cache correction from b9f4b53a: a later readiness check returning a |
| + non-verified status clears the startup cached config set. Existing Send |
| + semantics remain intact and SendReady still makes no control-store reads. |
| +4. The only SQL gate change is the NonApp description of the digest receipt; |
| + report IDs confer no app mutation authority. |
| + |
| +Read code only. Do not run tests: the author has run the focused tests, and the |
| +longer demo/alert selection is already running. The prior review's broad SQL |
| +probe command hit the default timeout; do not repeat it. No edits, commits, |
| +subagents, AWS, other checkouts or HANDOFF. Scratch only under the task scratch |
| +path if needed; report any file you create so the parent can remove it. |
| + |
| +Use the original severity definitions. State resolved/partial/not resolved for |
| +P2.1 and P2.2, then any concrete regression introduced by these fixes, with |
| +file:line evidence and its fault family. End with READY, READY AFTER FIXES or |
| +NOT READY. A missing P1 closes review; P2 fixes do not reopen it. The total |
| +budget remains at most three rounds and two rounds per fault family. |
diff --git a/docs/superpowers/reviews/REVIEW-FINDINGS-demo-abuse-alerts-R1.md b/docs/superpowers/reviews/REVIEW-FINDINGS-demo-abuse-alerts-R1.md| new file mode 100644 |
| index 000000000..3c0d044e6 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/REVIEW-FINDINGS-demo-abuse-alerts-R1.md |
| @@ -0,0 +1,35 @@ |
| +# Opus review: demo abuse alerts, round 1 |
| + |
| +I found no P1s and two P2s, so the verdict is **READY AFTER FIXES**. I reviewed `9622c65a..5c9fb44b` against the brief. A follow-up commit, `b9f4b53a` ("Keep late report arrivals in digests and invalidate rejected mail"), landed on the branch while I was reviewing. It is outside the reviewed range and I did not review it. |
| + |
| +**Tests run:** the 17 new `TestDemoAlert*` tests plus `TestClaimSQLTablesClassified` and `TestDemoProtectionsSQLScopes` all passed (`-count=1`, niced, default Go cache). That run already included the two new tests from `b9f4b53a`. The sandbox mounts the Go cache read-only, so I ran the tests outside it. A wider first run that also matched the heavy `TestClaimConsoleMutationInvariant` suite hit the 10-minute test timeout, and I did not rerun that suite. |
| + |
| +## P1 |
| +None. |
| + |
| +## P2 |
| + |
| +**1. A slow or failing mail path holds up fleet alerting** |
| +- **Problem:** the demo pass runs inside the fleet alert pass, before the fleet step and its heartbeat (`internal/console/alertengine_pass.go:125`). |
| +- **Evidence:** each send gets its own 20-second timeout (`alertnotify.go:48`, used at `demo_alerts.go:216`). Sends loop over every recipient, every firing unseen signal and the digest (`demo_alerts.go:186-211`). Failures are retried on every pass, and `SendReady` can also wait on a stalled mail lock. |
| +- **Failure scenario:** Keymail or SES stops answering while 2 recipients have 5 firing signals each. That is 10 sends plus 2 digests at 20 seconds each, about 4 minutes. This repeats every minute, so fleet incidents and reminders run minutes late, and the heartbeat can be delayed enough to trip `engine_silent`. |
| +- **Fix:** run the demo pass after the fleet step and heartbeat, or as its own worker. Give the whole pass one deadline, and stop sending for the pass after the first transport timeout. |
| +- **Fault family:** fleet alert liveness must not depend on demo delivery. |
| + |
| +**2. The digest skips late-committed reports for good (fixed by `b9f4b53a`, not reviewed)** |
| +- **Problem:** in the reviewed commit, the digest counts `created_at>=through AND created_at<now` and then moves `through` to `now` (`demo_alerts.go:247`, `:257`). |
| +- **Failure scenario:** a report's timestamp is taken before its upload is read. If it commits after a digest has already moved the watermark past that timestamp, no digest ever counts it. |
| +- **Fix:** `b9f4b53a` keeps a per-recipient list of report IDs already counted. It needs its own check: its migration and that ID list have not been reviewed. |
| +- **Fault family:** every report reaches the digest. |
| + |
| +## P3 |
| +- **Demo errors turn the fleet job red** (`alertengine_pass.go:146`, `:150`). The demo error is joined into the "Alert checks" job result. A demo setup problem, such as no recipients or mail not ready, marks that job failed every minute even when fleet alerts are fine. Report it under its own job name or just log it. |
| +- **Refusals are written even with alerts off** (`apidemo.go:363`, `demo_alert_admission.go:70`). |
| + - Every refused create runs a SQLite write transaction on the request path, which takes the `demo_settings` lock with a 5-second timeout. This happens even when `ENABLED=false` and when edge protections are off, while the budget check before it only reads. Skip recording when alerts are disabled. |
| + - Line 362 also counts refusals while serving is switched off. Turning serving off for a takedown will trigger the refusal alert from clients that keep retrying. Either leave serving-off refusals out or say so in the note. |
| +- **Signals can re-alert as they cross the threshold back and forth** (`demo_alerts.go:193-197`). One quiet pass rearms a signal, and all windows are rolling. A count sitting near the threshold, such as the 80% budget as old rows expire, can send mail on every crossing. This is within the design you fixed, but a minimum quiet time or a small margin below the threshold would cut the noise. |
| +- **Alerts go silent in claims mode with no log** (`demo_alerts.go:162`). With `ENABLED=true` on a claim-gated store, the pass returns nil and logs nothing. The impact is low because demos refuse claims mode anyway. |
| + |
| +Everything else in the brief checked out against the code: the thresholds, UTC windows and top-K grouping, the salted /24 and /48 prefix hashes, 24-hour retention, the migration, refusal counting, the SQL table classifications, recipients, the dedupe and retry state, the fleet-cutover exclusion and the `SendReady` cache-only path. |
| + |
| +**Verdict: READY AFTER FIXES** |
diff --git a/internal/console/alertengine_pass.go b/internal/console/alertengine_pass.go| index b15f80e15..7b12d4776 100644 |
| --- a/internal/console/alertengine_pass.go |
| +++ b/internal/console/alertengine_pass.go |
| @@ -99,6 +99,9 @@ func (s *Server) StartAlertEngine(ctx context.Context) { |
| if err := s.jobs.Run(ctx, "StartAlertEngine", s.alertEnginePass); err != nil { |
| log.Printf("console: alert engine: %v", err) |
| } |
| + if err := s.demoAlertPass(ctx); err != nil { |
| + log.Printf(demoAlertPassLog, err) |
| + } |
| select { |
| case <-ctx.Done(): |
| return |
| @@ -122,9 +125,8 @@ func (s *Server) alertEnginePass(ctx context.Context) error { |
| if s.cfg.HostClaim { |
| return errAlertEngineRefused // StartAlertEngine never gets here |
| } |
| - demoErr := s.demoAlertPass(ctx) |
| if s.cfg.Releases == nil { |
| - return demoErr |
| + return nil |
| } |
| now := s.alertClockNow() |
| open, sig, stepErr := s.alertEngineStep(ctx, now) |
| @@ -143,11 +145,11 @@ func (s *Server) alertEnginePass(ctx context.Context) error { |
| log.Printf("console: alert engine: drain: %v", drainErr) |
| jobFailed(ctx, fmt.Errorf("drain: %w", drainErr)) |
| } |
| - return errors.Join(stepErr, demoErr) |
| + return stepErr |
| } |
| s.noteUnreachableOperators(ctx, now) |
| s.writeAlertEngineBeat(ctx, now) |
| - return errors.Join(drainErr, demoErr) |
| + return drainErr |
| } |
| // alertEngineStep reads the signals and commits one step: the incident |
diff --git a/internal/console/demo_alert_copy.go b/internal/console/demo_alert_copy.go| index 295f3aa27..3502624d5 100644 |
| --- a/internal/console/demo_alert_copy.go |
| +++ b/internal/console/demo_alert_copy.go |
| @@ -2,6 +2,7 @@ package console |
| // Draft operator copy. Paul reviews these strings before this branch lands. |
| const ( |
| + demoAlertPassLog = "console: demo alerts: %v" |
| demoAlertConfigError = "console: invalid demo alert setting %s" |
| demoAlertNoRecipients = "console: demo alerts have no system operator or ops owner recipient" |
| demoAlertDeliveryError = "console: demo alert delivery failed for %s: %w" |
diff --git a/internal/console/demo_alerts.go b/internal/console/demo_alerts.go| index 447788739..c24396bbc 100644 |
| --- a/internal/console/demo_alerts.go |
| +++ b/internal/console/demo_alerts.go |
| @@ -156,7 +156,7 @@ func (s *Server) demoAlertRecipients() (*alertRun, error) { |
| return s.grantRecipients(addrs) |
| } |
| -// Runs before the fleet engine's bucket-dependent step, on its existing minute |
| +// Runs after the fleet engine's pass and heartbeat, on its existing minute |
| // cadence. The server mutex prevents overlapping passes; serve already holds |
| // the deployment's exclusive console database lock. |
| func (s *Server) demoAlertPass(ctx context.Context) error { |
| @@ -169,6 +169,8 @@ func (s *Server) demoAlertPass(ctx context.Context) error { |
| } |
| s.demoAlertMu.Lock() |
| defer s.demoAlertMu.Unlock() |
| + ctx, cancel := context.WithTimeout(ctx, alertPassBudget) |
| + defer cancel() |
| now := s.alertClockNow().UTC() |
| signals, err := s.store.demoAlertSignals(ctx, c, s.cfg.Demo.CreateGlobalDay, now) |
| if err != nil { |
| @@ -204,30 +206,43 @@ func (s *Server) demoAlertPass(ctx context.Context) error { |
| body := fmt.Sprintf(demoAlertBody, signal.text, s.cfg.Origin) |
| if err := s.sendDemoAlert(ctx, recipient, demoAlertSubject, body); err != nil { |
| failures = append(failures, fmt.Errorf(demoAlertDeliveryError, recipient.address, err)) |
| + if demoAlertTimedOut(ctx, err) { |
| + return errors.Join(failures...) |
| + } |
| continue |
| } |
| failures = append(failures, s.store.SetAlertSeen(demoAlertSeenBox, signal.rule, recipient.address, true)) |
| } |
| if c.Digest { |
| - failures = append(failures, s.demoReportDigest(ctx, recipient, now)) |
| + err := s.demoReportDigest(ctx, recipient, now) |
| + failures = append(failures, err) |
| + if demoAlertTimedOut(ctx, err) { |
| + return errors.Join(failures...) |
| + } |
| } |
| } |
| return errors.Join(failures...) |
| } |
| +func demoAlertTimedOut(ctx context.Context, err error) bool { |
| + var timeout interface{ Timeout() bool } |
| + return ctx.Err() != nil || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) || (errors.As(err, &timeout) && timeout.Timeout()) |
| +} |
| + |
| func (s *Server) sendDemoAlert(ctx context.Context, recipient operatorGrant, subject, body string) error { |
| ctx, cancel := context.WithTimeout(ctx, alertEmailTimeout) |
| defer cancel() |
| if recipient.token != "" && s.sendApp != nil { |
| _, err := s.sendApp(ctx, recipient.token, recipient.address, subject, body) |
| - return err |
| + return errors.Join(err, ctx.Err()) |
| } |
| // Send would ensure/verify the identity on a cold cache, including S3 |
| // reads. This optional interface uses only an already verified identity. |
| if sender, ok := s.consoleMail.(interface { |
| SendReady(context.Context, string, string, string) error |
| }); ok { |
| - return sender.SendReady(ctx, recipient.address, subject, body) |
| + err := sender.SendReady(ctx, recipient.address, subject, body) |
| + return errors.Join(err, ctx.Err()) |
| } |
| return ErrConsoleMailNotReady |
| } |
diff --git a/internal/console/demo_alerts_test.go b/internal/console/demo_alerts_test.go| index 81725db3c..57b270512 100644 |
| --- a/internal/console/demo_alerts_test.go |
| +++ b/internal/console/demo_alerts_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "errors" |
| "fmt" |
| + "os" |
| "strings" |
| "testing" |
| "time" |
| @@ -161,15 +162,25 @@ func TestDemoAlertSignalWindowsAndConcentration(t *testing.T) { |
| } |
| type demoAlertMail struct { |
| - calls []string |
| - fail bool |
| + calls []string |
| + fail bool |
| + err error |
| + attempts int |
| + onSend func(context.Context) |
| } |
| func (m *demoAlertMail) Ready(context.Context) bool { panic("alert called readiness") } |
| func (m *demoAlertMail) Send(context.Context, string, string, string) error { |
| panic("alert used uncached mail") |
| } |
| -func (m *demoAlertMail) SendReady(_ context.Context, to, subject, body string) error { |
| +func (m *demoAlertMail) SendReady(ctx context.Context, to, subject, body string) error { |
| + m.attempts++ |
| + if m.onSend != nil { |
| + m.onSend(ctx) |
| + } |
| + if m.err != nil { |
| + return m.err |
| + } |
| if m.fail { |
| return errors.New("offline") |
| } |
| @@ -392,12 +403,48 @@ func TestDemoAlertEmailUsesVerifiedCacheOnly(t *testing.T) { |
| func TestDemoAlertEngineRunsWithoutBucket(t *testing.T) { |
| s, m, now := demoAlertServer(t) |
| + s.jobs = newJobRegistry(s.alertClock) |
| alertAttempt(t, s.store, *now, 1, 1) |
| - if err := s.alertEnginePass(t.Context()); err != nil { |
| - t.Fatal(err) |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + m.onSend = func(sendCtx context.Context) { |
| + status, ok := jobStatusOf(s, "StartAlertEngine") |
| + if !ok || status.Runs != 1 || status.State != JobOK { |
| + t.Errorf("demo delivery ran before fleet pass finished: %+v", status) |
| + } |
| + if _, ok := sendCtx.Deadline(); !ok { |
| + t.Error("unbounded demo send") |
| + } |
| + cancel() |
| } |
| + s.StartAlertEngine(ctx) |
| if len(m.calls) != 1 { |
| - t.Fatal("bucket-free pass did not send") |
| + t.Fatal("bucket-free loop did not send") |
| + } |
| + status, _ := jobStatusOf(s, "StartAlertEngine") |
| + if status.State != JobOK { |
| + t.Fatal("demo delivery changed fleet job status") |
| + } |
| +} |
| + |
| +func TestDemoAlertPassStopsOnTransportTimeout(t *testing.T) { |
| + for _, timeout := range []error{context.DeadlineExceeded, os.ErrDeadlineExceeded} { |
| + t.Run(timeout.Error(), func(t *testing.T) { |
| + s, m, now := demoAlertServer(t) |
| + s.cfg.SystemOperators = append(s.cfg.SystemOperators, "second@example.test") |
| + s.cfg.DemoAlerts.IPCount = 1 |
| + s.cfg.DemoAlerts.PrefixCount = 1 |
| + s.cfg.DemoAlerts.Digest = true |
| + alertAttempt(t, s.store, *now, 1, 1) |
| + alertReport(t, s.store, now.Add(-time.Second), "report") |
| + m.err = timeout |
| + if err := s.demoAlertPass(t.Context()); !errors.Is(err, timeout) { |
| + t.Fatalf("timeout lost: %v", err) |
| + } |
| + if m.attempts != 1 { |
| + t.Fatalf("continued sending after timeout: %d", m.attempts) |
| + } |
| + }) |
| } |
| } |