carlos / platform Public

Fleet alerts Plan 2 plan rev 2 (Astra R1: 4 P1, 1 P2 accepted)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev cda7a661d48f7229cc70d5d3d41503b1d28bc168 parent 95377f5
2 files changed, +197 −46
  • docs/superpowers/plans/2026-11-01-fleet-alerts-2-traffic.md +142 −46
  • docs/superpowers/reviews/CODEX-FINDINGS-fleet-alerts-2-plan-R1.md +55 −0

Intent

Human

<task-notification> <task-id>bo1i7crtn</task-id> <tool-use-id>toolu_019G1LRdpHqwCyDETA1P8PC5</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1f8653ea-6b78-4712-b1ac-1eb863a870a6/tasks/bo1i7crtn.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra plan review R1 to finish" completed (exit code 0)</summary> </task-notification>

diff --git a/docs/superpowers/plans/2026-11-01-fleet-alerts-2-traffic.md b/docs/superpowers/plans/2026-11-01-fleet-alerts-2-traffic.md
index 96feaf700..d8ea45f0b 100644
--- a/docs/superpowers/plans/2026-11-01-fleet-alerts-2-traffic.md
+++ b/docs/superpowers/plans/2026-11-01-fleet-alerts-2-traffic.md
@@ -13,7 +13,11 @@
**Spec:** `docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md` (APPROVED 2026-10-30). Read §6, §7.1, §7.2, §9, §10 and §11 item 2 before any task. Plan 1 (`docs/superpowers/plans/2026-10-30-fleet-alerts-1-engine-connectors.md`, merged 27173ed) built the engine this plan extends. Its build rulings are in amadan discussion 495. R-25 (the 24 h heartbeat horizon), R-41 (no unconditional fallbacks) and R-27 (job label) bind here.
-**Review budget:** at most three Astra plan rounds (AGENTS.md stopping rules). This is rev 1, round 1.
+**Review budget:** at most three Astra plan rounds (AGENTS.md stopping rules).
+
+**Review history:**
+- Astra R1 on 95377f52 was NOT READY, with 4 P1s and 1 P2 (`docs/superpowers/reviews/CODEX-FINDINGS-fleet-alerts-2-plan-R1.md`). Every finding is accepted. Dispositions are at the end.
+- This is rev 2, for round 2.
## Recon: what main already counts (2026-11-01, at 11c8c864)
@@ -38,6 +42,14 @@ The usage edge day is a bucket object read by `/fleet/protection`. Reading it fo
- `Requests == S2xx + S3xx + S4xx + S404 + S5xx + Refused`. 404 is not in `S4xx`, as in reqrec.
- Unknown-host requests are counted only in `UnknownHost`.
- **Top lists:** 10 entries a window on the box, 20 in an hourly rollup.
+- **One counting owner per client answer (R1 #2).** The edge that writes the response to the client counts it, and no other edge does.
+ - **Route answers.** A request this box serves for a route is counted in the `ServeHTTP` observer defer. That includes a hopped request whose answer goes back over the hop to the forwarding edge, because the forwarding edge doesn't count an answer the home delivered.
+ - **Forwarded requests.** A request this box forwards by backhaul (`backhaulTo`) or region HA (`forwardHA`) is counted here only when the answer is local: an admission refusal (`backhaulAdmit` 429 or 503), a proxy `ErrorHandler` or `onError` 502/503, or `answerHolderUnreachable`. A response that came from the home is not counted here. The `ModifyResponse`/`onResponse` hook marks it delivered.
+ - **Far-asset answers.** `serveAssetFar` owns every answer it writes, including its `backhaulAdmit` refusals and failed fills. The home skips traffic counting for the acknowledged fill hop (`out.unbilled`), the predicate billing already uses.
+- **Window wire size (R1 #5):**
+ - A completed window encodes to at most 12 KiB of JSON, so 3 windows are at most 36 KiB.
+ - `status.TrimTrafficWindow` enforces it. It drops the lowest-ranked entry of whichever list encodes largest, ties broken in the order Paths, Hosts, Apps, RateApps, Sources, until the window fits. Scalars are never dropped.
+ - The edge applies it at close, and the console re-applies it on ingest.
- **Edge memory bounds, per window, in distinct keys:**
- apps 4096
- rate-limited apps 1024
@@ -52,14 +64,29 @@ The usage edge day is a bucket object read by `/fleet/protection`. Reading it fo
- the console re-applies the same caps on ingest
- hostnames are never rendered as links
- **Retention:** 5-minute rows for 7 days, hourly rows for 90 days. There is no backfill. A missing window is a gap, never zero and never estimated.
+- **Coverage and evaluation (R1 #1, #3):**
+ - A rule is judged on an *interval* of windows: 3 for `fleet_5xx`, 12 for `abuse_surge`.
+ - An interval is *complete* when the pass read every listed heartbeat (no `unreadBoxes`) and every *expected box* has a row for every window in it. An expected box is one read this pass, not stale (`status.BoxStale(b, now, status.SnapshotPeriod)`), whose heartbeat carries traffic.
+ - A silent or stale box is `box_silent`'s incident. The traffic rules judge the boxes that report.
+ - The *watermark* is the oldest of the expected boxes' newest reported window starts. Intervals end at or before the watermark, so all their data has arrived.
+ - Each heartbeat pass evaluates every interval end after the last one evaluated, up to the watermark, at most 12.
+ - **Missing evidence never clears:**
+ - If any interval meets the fire condition, the rule fires, complete or not.
+ - If the rule is firing and any interval meets its stay condition, it stays firing.
+ - It clears, or stays clear, only when the newest interval is complete.
+ - Otherwise the state holds, with the subject reported unknown.
- **Rules (spec §7.1), both warning level, subject `fleet`:**
- - `fleet_5xx`
- - fires when 5xx > threshold % (default 1) of at least 500 answered requests over the three windows ending 5 min before the current window
- - while open, stays open until the rate is ≤ half the threshold or requests fall under 500
- - `abuse_surge`, where B is blocked + watched over the last 12 windows
- - fires when B ≥ 1,000 and B > multiple (default 5) × the median of the same UTC hour on each of the previous 7 days
- - while open, stays open until B < 500 or B ≤ half the multiple × the median
- - until all 7 baseline hours exist, it fires above 10,000 and clears at ≤ 5,000
+ - `fleet_5xx`, over an interval of 3 windows (15 minutes):
+ - fire: answered requests ≥ 500 and 5xx > threshold % (default 1) of them
+ - stay: answered requests ≥ 500 and 5xx > half the threshold
+ - `abuse_surge`, where B is blocked + watched over an interval of 12 windows (an hour):
+ - with a full baseline:
+ - fire: B ≥ 1,000 and B > multiple (default 5) × the median of the baseline hours
+ - stay: B ≥ 500 and B > half the multiple × the median
+ - the baseline hours are the `traffic_hours` row of the interval's middle UTC hour on each of the 7 previous days, each counted only with all 12 windows present
+ - with fewer than 7 baseline hours (spec: "until 7 days of history exist"):
+ - fire: B > 10,000
+ - stay: B > 5,000
- **Editable thresholds (§5.2), whole numbers:**
- `fleet_5xx` percent, bounds 1..50
- `abuse_surge` multiple, bounds 2..50
@@ -80,9 +107,9 @@ The usage edge day is a bucket object read by `/fleet/protection`. Reading it fo
## Review Focus
-1. **A flood of junk:** 100,000 distinct random hostnames or paths in one window. Edge memory stays within the key caps, the heartbeat's traffic block stays under 16 KiB, and a `<script>` hostname renders as escaped text with no link. Tests in Tasks 2, 4 and 7.
-2. **Missed data is not zero:** a box that restarts, or a console down for 30 minutes. The chart shows a gap, `fleet_5xx` and `abuse_surge` neither fire nor clear on the missing windows, and a restarted box reports no partial window. Tests in Tasks 2, 4 and 5.
-3. **Counted once:** a backhauled (hopped) request, a tunnelled request, a refusal (429 or a block page), a far-asset answer. Each counts once fleet-wide, a refusal is not also a 4xx, and blocked plus watched equal what the usage meter counted for `/fleet/protection`. Tests in Task 2.
+1. **A flood of junk:** 100,000 distinct random hostnames or paths in one window. Edge memory stays within the key caps, each window encodes to ≤ 12 KiB even with maximum-length keys full of `<`, and a `<script>` hostname renders as escaped text with no link. Tests in Tasks 2, 4 and 7.
+2. **Missed data is not zero:** a box that restarts, a heartbeat that can't be read, or a console down for 30 minutes. The chart shows a gap or a partial bar. `fleet_5xx` and `abuse_surge` never clear on incomplete intervals, and with heartbeats every 5-6 minutes no interval is skipped. A restarted box reports no partial window. Tests in Tasks 2, 4 and 5.
+3. **Counted once:** a backhauled request (delivered, refused at admission, or failed to dial), a region HA forward, a tunnelled request, a refusal (429 or a block page), a far-asset answer and its acknowledged home fill. Each client answer counts once fleet-wide, and a refusal is not also a 4xx. Blocked plus watched equal what the usage meter counted for `/fleet/protection`, except on acknowledged fills, where the meter counts at both edges. Tests in Task 2.
4. **A forged or broken heartbeat:** windows with unaligned or future starts, negative or huge counts, more than 3 windows, over-long strings or lists. They are dropped or trimmed on ingest, and nothing panics. Tests in Task 4.
5. **A quiet fleet:** under 500 requests with some 5xx never fires. Abuse surge with under 7 days of history uses the 10,000 floor. A zero median still needs 1,000. Tests in Task 5.
@@ -142,6 +169,10 @@ The usage edge day is a bucket object read by `/fleet/protection`. Reading it fo
type TrafficCount struct { Key string; Hits int64 } // json key, hits
type TrafficSource struct { Client, Country string; Hits int64 } // json client, country, hits
func (w TrafficWindow) Answered() int64 // S2xx+S3xx+S4xx+S404+S5xx
+ const TrafficWindowMaxBytes = 12 << 10
+ // TrimTrafficWindow drops list entries, per the Global Constraints order,
+ // until json.Marshal(*w) is at most maxBytes. It never changes a scalar.
+ func TrimTrafficWindow(w *TrafficWindow, maxBytes int)
```
- `Probes.Traffic []TrafficWindow`
- `BoxMetrics.Traffic []TrafficWindow` with `json:"traffic,omitempty"` and a "Private Metrics only: names hosts and paths" comment
@@ -150,6 +181,8 @@ The usage edge day is a bucket object read by `/fleet/protection`. Reading it fo
- `TestTrafficWindowJSONNames` pins every JSON name above.
- `TestCollectBoxCarriesTraffic`: Probes with only `Traffic` set still attaches `Metrics` and round-trips the windows.
- `TestTrafficWindowAnswered`
+ - `TestTrimTrafficWindowWorstCase`: 10 entries in every list, each at the maximum key length (paths 512 bytes, hosts 253, account and app 128, client 64), with keys full of `<` (6 bytes each once JSON-escaped). After trimming the window encodes to ≤ 12 KiB, every scalar is unchanged, and the entries left are the highest-ranked of each list.
+ - `TestTrimTrafficWindowSmallUnchanged`
- [ ] **Step 2: Run, expect FAIL.** `go test ./internal/status -run 'Traffic' -count=1`
- [ ] **Step 3: Implement.** `len(p.Traffic) > 0` joins the any-known condition.
- [ ] **Step 4: Run, expect PASS.**
@@ -166,7 +199,9 @@ The usage edge day is a bucket object read by `/fleet/protection`. Reading it fo
- `internal/edge/guard.go`: `observeGuardCount` :106
- `internal/edge/ratelimit.go`: `rateAdmit` :126, `noteRateLimited` :159
- `internal/edge/planthrottle.go`: :44-95
- - `internal/edge/assetcatch.go`: `serveAssetFar`'s defer :1074-1093
+ - `internal/edge/assetcatch.go`: `serveAssetFar`'s defer :1074-1093, so that it covers every answer it writes
+ - `internal/edge/edge.go`: around the backhaul calls at :1983-1985 (`backhaulTo`, `backhaulAdmit` :3899, the backhaul proxy's `ModifyResponse` and `ErrorHandler` near :4060-4075)
+ - `internal/edge/forwardha.go`: `forwardHA` :180, with its `onError`, `onResponse` and `answerHolderUnreachable`
**Interfaces:**
- Consumes: Task 1 types.
@@ -200,20 +235,32 @@ The usage edge day is a bucket object read by `/fleet/protection`. Reading it fo
- Sources for guard matches only, keyed on `clientID(ip, at)`, or on `reqrec.ClientPrefix(ip)` when that is "". Country comes from `geoAnswerFrom(ctx).Country`. Call `clientID` before taking the counter's mutex.
- Hosts from the unknown-host sites: the port is stripped, the host lower-cased and cut to 253 bytes, `strings.ToValidUTF8(…, "?")` is applied, and control characters become `?`.
- **Unknown host** is counted only at `edge.go:1986` (after the far-asset and backhaul tries) and in the :80 handler at :2965. The door-caller sites at :1835, :1970 and :2120 are the platform's own calls and are not counted.
-- **Top-N** is taken at close by a stable sort on hits, descending, then key, ascending. Truncate to `TrafficTopN`.
+- **Top-N** is taken at close by a stable sort on hits, descending, then key, ascending. Truncate to `TrafficTopN`, then apply `status.TrimTrafficWindow(&w, status.TrafficWindowMaxBytes)`.
+- **Forwarded requests (R1 #2).** A forwarded request gets a small status-capturing writer and a `delivered` flag on its context. The flag is set by the hop proxy's `ModifyResponse` (backhaul) or `onResponse` (`forwardHA`) when the home's response arrives.
+ - When the call returns with `delivered` unset and a status written, the counter records one request with no app attribution and no list entries. A `backhaulAdmit` 429 counts as `Refused`, and any other status counts as its class.
+ - A delivered response is the home's to count.
+ - A home that hangs up mid-response after its headers arrived is the home's count. `delivered` was already set, so it is counted once.
+- **Acknowledged home fills.** The `ServeHTTP` defer's traffic call sits under `!out.unbilled`, as billing does. `serveAssetFar` at the far edge owns that client answer. `observeGuardCount` is unchanged, so `/fleet/protection` keeps counting as it does.
- [ ] **Step 1: Write failing tests** in `traffic_test.go`, driving the counter with an injected clock:
- `TestTrafficWindowsRotateAndKeepThree`: traffic in 5 consecutive windows. `windows` returns the last 3 completed windows, oldest first, with exact counts.
- `TestTrafficIdleWindowsAreZero`: after 12 idle minutes, `windows` returns zero windows, not nil.
- `TestTrafficPartialFirstWindowNotReported`: a counter started at 10:02 reports nothing for 10:00. At 10:15 it reports 10:05 and 10:10 only.
- `TestTrafficClassesSumToRequests`: a mix of 200, 0, 301, 404, 403, 503 and refused requests. Assert `Requests == Answered()+Refused`, and that a refused 429 is not in `S4xx`.
- - `TestTrafficKeyCapsHold`: 100,000 distinct hosts and paths in one window. The internal map sizes stay ≤ 256 and ≤ 1024, `UnknownHost == 100000`, and `json.Marshal(windows)` is under 16 KiB.
+ - `TestTrafficKeyCapsHold`: 100,000 distinct hosts and paths in one window. The internal map sizes stay ≤ 256 and ≤ 1024, `UnknownHost == 100000`, and each window encodes to ≤ 12 KiB.
- `TestTrafficHostSanitised`: a 400-byte host with `\x00` and invalid UTF-8 is cut to 253 bytes, is valid UTF-8, and has no control bytes.
- `TestTrafficTopNOrder`: ties are broken by key.
- Through `ServeHTTP`, in an existing edge test harness with a usage meter:
- `TestEdgeTrafficGuardMatchesUsageMeter`: in block mode, one blocked probe and one watched path. Traffic `Blocked`/`Watched` equal the meter's `GuardDelta` Block/Watch, and the blocked request is `Refused`.
- `TestEdgeTrafficRateEnforcedVsObserved`: an enforcing refusal counts `RateShed` or `RateCeiling` and `Refused`. Observe mode counts only `RateObserved`, and the request is served and classed.
- `TestEdgeTrafficTunnelNotCounted`
+ - `TestEdgeTrafficBackhaulOwnership`, with two edges in one test, A forwarding to home B:
+ - a delivered request counts once, at B, with its app
+ - an admission 429 counts once, at A, as Refused
+ - a saturated 503 counts once, at A, as S5xx
+ - a dial failure (B closed) counts once, at A, as S5xx
+ - `TestEdgeTrafficForwardHAOwnership`: the same three outcomes through `forwardHA`, including `answerHolderUnreachable`.
+ - `TestEdgeTrafficFarAssetFillOnce`: a far-asset answer filled from the home counts once, at the far edge. The home's acknowledged fill hop adds nothing to traffic, while its usage-meter guard count is unchanged.
- `TestEdgeTrafficUnknownHostOutsiderOnly`: an outsider's unknown host counts. A door caller's out-of-scope request does not.
- `TestRecorderClientIDMatchesRecords`: `ClientID` equals the `cid` field the recorder writes for the same IP and day. A nil recorder returns "".
- [ ] **Step 2: Run, expect FAIL.** `go test ./internal/edge -run 'Traffic' -count=1` and `go test ./internal/reqrec -run ClientID -count=1`
@@ -256,17 +303,23 @@ The usage edge day is a bucket object read by `/fleet/protection`. Reading it fo
- Produces:
```sql
CREATE TABLE IF NOT EXISTS traffic_windows (box TEXT NOT NULL, start INTEGER NOT NULL, body TEXT NOT NULL, PRIMARY KEY (box, start));
- CREATE TABLE IF NOT EXISTS traffic_hours (start INTEGER PRIMARY KEY, windows INTEGER NOT NULL, boxes INTEGER NOT NULL, body TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS traffic_hours (start INTEGER PRIMARY KEY, windows INTEGER NOT NULL, boxes INTEGER NOT NULL, box_windows INTEGER NOT NULL, body TEXT NOT NULL);
```
- - `traffic_hours.windows` is the number of distinct 5-minute starts with any row in that hour, 0..12. `body` is a `trafficSum` as JSON.
+ - In `traffic_hours`:
+ - `windows` is the number of distinct 5-minute starts with any row in that hour, 0..12.
+ - `boxes` is the distinct boxes with a row.
+ - `box_windows` is the number of (box, start) rows.
+ - `body` is a `trafficSum` as JSON.
+ - A past hour is *partial* when `windows < 12` or `box_windows < boxes*12`. The chart shows it as partial (R1 #1).
- `type trafficSum struct`: the totals of `status.TrafficWindow` (without `Start`), its five lists (each trimmed to 20 when stored), and `Starts int`, the distinct window starts summed.
- `func addTraffic(sum *trafficSum, w status.TrafficWindow)` merges lists by key: (account, app) for app lists, `Key` for counts, (client, country) for sources.
- `func (s trafficSum) trimmed(n int) trafficSum`
- `func sanitizeTrafficWindow(w status.TrafficWindow, now time.Time) (status.TrafficWindow, bool)`
- `func (s *Store) IngestTraffic(byBox map[string][]status.TrafficWindow, now time.Time) (inserted int, err error)`
- `func (s *Store) PruneTraffic(now time.Time) error`
+ - `func (s *Store) TrafficBoxRows(from, to int64) (map[string]map[int64]bool, error)`
- `func (s *Store) TrafficRange(from, to time.Time) (sum trafficSum, starts map[int64]bool, err error)`, read from 5-minute rows. `starts` is the window starts present.
- - `func (s *Store) TrafficHours(from, to time.Time) ([]trafficHour, error)`, with `type trafficHour struct { Start time.Time; Windows, Boxes int; Sum trafficSum }`. Hours with no row are absent, and the caller draws them as gaps.
+ - `func (s *Store) TrafficHours(from, to time.Time) ([]trafficHour, error)`, with `type trafficHour struct { Start time.Time; Windows, Boxes, BoxWindows int; Sum trafficSum }` and `func (h trafficHour) Partial(now time.Time) bool`. Hours with no row are absent, and the caller draws them as gaps.
**Decisions:**
- **Sanitising** drops the whole window when any of these fail:
@@ -278,6 +331,7 @@ The usage edge day is a bucket object read by `/fleet/protection`. Reading it fo
Otherwise it keeps at most `TrafficTopN` entries a list, drops entries with negative hits, and applies these caps:
- account and app: 128 bytes
- path keys: 512 bytes
+ - then `status.TrimTrafficWindow` at `TrafficWindowMaxBytes`
- host keys: 253 bytes
- client: 64 bytes
- country: exactly two letters A-Z, else ""
@@ -295,7 +349,7 @@ The usage edge day is a bucket object read by `/fleet/protection`. Reading it fo
- `TestTrafficIngestDedupesByBoxAndStart`: the same 3 windows ingested twice give 3 rows, `inserted` 3 then 0.
- `TestTrafficIngestRejectsForgedWindows`: unaligned, future, too old, a negative count, a sum mismatch, and 5 windows (only the latest 3 kept).
- `TestTrafficIngestTrimsHostileStrings`: a 1 KiB host, 20 list entries, a `\x00`, invalid UTF-8 and country `"<s"`.
- - `TestTrafficHourRollupMergesBoxesAndLists`: two boxes and the same app in both. The hour row sums them, the lists merge by key, and `Windows` counts distinct starts.
+ - `TestTrafficHourRollupMergesBoxesAndLists`: two boxes and the same app in both. The hour row sums them, the lists merge by key, `Windows` counts distinct starts, and `BoxWindows` and `Boxes` are exact. With one box missing one window, `Partial` is true.
- `TestTrafficHourRecomputedOnLateWindow`: a window arriving after its hour row exists updates it.
- `TestTrafficPruneKeeps7DaysAnd90Days`
- `TestTrafficHoursGapIsAbsent`: no rows for an hour means no `trafficHour` for it, not a zero one.
@@ -318,44 +372,60 @@ The usage edge day is a bucket object read by `/fleet/protection`. Reading it fo
**Interfaces:**
- Consumes: Task 4.
-- Produces:
- - `func fleet5xxVerdict(sum trafficSum, complete bool, thresholdPct float64, wasFiring bool) (firing bool, value float64, ok bool)`. `ok` is false when not `complete`, and `value` is the 5xx percentage.
- - `func abuseSurgeVerdict(b int64, complete bool, baseline []int64, multiple float64, wasFiring bool) (firing bool, value float64, ok bool)`. `baseline` holds the 7 same-hour totals; fewer than 7 means "no history yet".
- - `func (s *Server) trafficSignals(ctx context.Context, settings map[string]alertRuleSetting, now time.Time, sig *alertSignals)`
+- Produces, in `trafficrules.go`, all pure except `trafficSignals`:
+ - `type trafficInterval struct { End int64; Sum trafficSum; Complete bool }`. `End` is the start of its last window.
+ - `type trafficJudgement struct { Fire, Stay bool; Value float64 }`
+ - `func fleet5xxJudge(sum trafficSum, thresholdPct float64) trafficJudgement`. `Value` is the 5xx percentage of answered requests.
+ - `func abuseSurgeJudge(b int64, baseline []int64, multiple float64) trafficJudgement`. `baseline` is the qualifying same-hour totals, and fewer than 7 selects the floors. The median of 7 is the 4th value in order. `Value` is B.
+ - `func combineTraffic(js []trafficJudgement, newestComplete, wasFiring bool) (firing bool, value float64, ok bool)`, which applies "missing evidence never clears" from the Global Constraints. `value` is the newest judgement's, or the firing one's when firing. `ok` false means hold.
+ - `func trafficCoverage(expected []string, rows map[string]map[int64]bool, unread bool, starts []int64) bool`
+ - `func trafficWatermark(expected []status.Box) (int64, bool)`: the oldest of each expected box's newest `Metrics.Traffic` start.
+ - `func (s *Server) trafficSignals(ctx context.Context, boxes []status.Box, unread map[string]bool, settings map[string]alertRuleSetting, now time.Time, sig *alertSignals)`
- `func (s *Store) AlertFiring(k alertKey) (bool, error)`: true when an open incident for k's scope and rule lists k's subject as a firing member.
+ - `alertEngineState` gains `trafficEvaluated map[string]int64` (rule to the last interval `End` judged) and `trafficPrunedAt time.Time`.
- Rule IDs `fleet_5xx` and `abuse_surge`, both `alerting.LevelWarning`, both console rules. Threshold defaults are 1 and 5, with bounds {1, 50} and {2, 50}.
+- Task 4 adds `func (s *Store) TrafficBoxRows(from, to int64) (map[string]map[int64]bool, error)`, which reports for each box the window starts it has rows for.
**Decisions:**
-- **Ingest.** In `heartbeatSignals`, after `r.boxes` succeeds, call `IngestTraffic` with each box's `Metrics.Traffic`. Boxes with nil `Metrics` contribute nothing. Then call `trafficSignals`.
+- **Ingest.** In `heartbeatSignals`, after `r.boxes` succeeds, call `IngestTraffic` with each box's `Metrics.Traffic`. Boxes with nil `Metrics` contribute nothing. Then call `trafficSignals(boxes, r.unreadBoxes, …)`.
- If the listing failed, nothing is ingested or evaluated, and neither rule is covered, so their state holds.
- If ingest fails, `alertReadFailed` runs and neither rule is covered.
- - After a successful ingest, call `PruneTraffic` when `now - alertEngineState.trafficPrunedAt ≥ 1h`. A prune error is logged and fails the run, and evaluation still proceeds.
-- **`fleet_5xx` evaluation.** Let `cur = floor5(now)`. The windows are the starts `cur-20m`, `cur-15m` and `cur-10m`. `complete` means all three starts are present.
-- **`abuse_surge` evaluation.**
- - The windows are the 12 starts `cur-65m` to `cur-10m`, and `complete` means at least 9 of them are present.
- - The baseline is `traffic_hours` rows at `floorHour(cur-40m) - d*24h` for d = 1..7, each with `Windows ≥ 9`. A missing or thin row makes the baseline short, which selects the 10,000 floor.
- - The median of 7 is the 4th value in order.
-- **Signals.** Each verdict with `ok` adds one signal, keyed `(fleet, rule, "fleet")`, and covers the rule with no unknowns. A verdict that is not `ok` covers the rule with `unknown = {"fleet": true}`, so the member keeps its state (Review Focus 2). `wasFiring` comes from `AlertFiring`.
+ - After a successful ingest, call `PruneTraffic` when `now - trafficPrunedAt ≥ 1h`. A prune error is logged and fails the run, and evaluation still proceeds.
+- **Expected boxes.** These are boxes in `boxes`, not stale by `status.BoxStale(b, now, status.SnapshotPeriod)`, with a non-empty `Metrics.Traffic`. With none, both rules hold.
+- **Interval ends.** For each rule:
+ 1. Judge every end `t` from `trafficEvaluated[rule]+5m` to the watermark, at most the newest 12. With no `trafficEvaluated` entry (after a console restart), judge only the watermark.
+ 2. A `fleet_5xx` interval covers starts `t-10m..t`. An `abuse_surge` interval covers `t-55m..t`. Its baseline is the `traffic_hours` row at `floorHour(t-25m) - d*24h` for d = 1..7, counted only when its `windows == 12`.
+ 3. `Complete` is `trafficCoverage` over the interval's starts.
+ 4. Set `trafficEvaluated[rule]` to the watermark after judging.
+
+ Because the watermark trails the slowest expected box, a box that publishes every 6 minutes delays judging. It doesn't skip any end.
+- **Signals.** An `ok` result adds one signal, keyed `(fleet, rule, "fleet")`, and covers the rule with no unknowns. A hold covers the rule with `unknown = {"fleet": true}`, so the member keeps its state and gets no Gone. `wasFiring` comes from `AlertFiring`.
- **Value text.** `fleet_5xx` reads like "1.4% of requests", `abuse_surge` like "12,400 an hour". The drafts are finalised in Task 6.
- [ ] **Step 1: Write failing tests.**
- - `TestFleet5xxVerdictTable`, rows of (answered, 5xx, threshold, wasFiring) and the expected result:
- - (499, 100, 1, f): not firing
- - (500, 6, 1, f): firing
- - (500, 5, 1, f): not firing
- - (1000, 6, 1, t): still firing at 0.6%
- - (1000, 5, 1, t): clears at 0.5%
- - (400, 50, 1, t): clears under 500
- - not complete: `ok` false
- - `TestAbuseSurgeVerdictTable`:
- - with a 7-day median of 300: B 1,500 fires; B 999 doesn't; open at B 800 stays open; open at B 750 clears (≤ 2.5 × 300); open at B 499 clears
- - with no history (6 rows): 10,001 fires, 10,000 doesn't; open at 5,001 stays; open at 5,000 clears
- - a zero median needs B ≥ 1,000
- - `TestTrafficSignalsGapKeepsState`: an open `fleet_5xx` incident, then a pass whose windows are missing. No Gone signal and the incident stays open.
+ - `TestFleet5xxJudgeTable`, rows of (answered, 5xx, threshold) and the expected Fire and Stay:
+ - (499, 100, 1): F, F
+ - (500, 6, 1): T, T
+ - (500, 5, 1): F, T
+ - (1000, 6, 1): F, T
+ - (1000, 5, 1): F, F
+ - (400, 50, 1): F, F
+ - `TestAbuseSurgeJudgeTable`:
+ - median 300: 1,501 fires and 1,500 doesn't (spec "above 5x"); 999 doesn't, even with a median of 0; 1,000 with a median of 0 fires; 751 stays, 750 doesn't; 499 doesn't stay
+ - 6 baseline rows: 10,001 fires, 10,000 doesn't; 5,001 stays, 5,000 doesn't
+ - `TestCombineTrafficMissingEvidenceNeverClears`:
+ - an incomplete interval that fires: firing
+ - incomplete, quiet and was firing: hold
+ - newest complete and quiet: clear
+ - an older interval fires while the newest is quiet: firing
+ - `TestTrafficCoverageOneBoxCannotHideAnother` (R1 #1): box A has all windows and B misses one. Incomplete. With B's heartbeat in `unread`, also incomplete.
+ - `TestTrafficSignalsHeartbeatCadenceNoSkippedInterval` (R1 #3): engine passes at minute offsets 0, 1, … with heartbeats every 5.5 minutes from two unaligned boxes, and a 5xx breach confined to one 15-minute interval. The rule fires exactly once, and every interval end in the run is judged exactly once.
+ - `TestTrafficSignalsGapKeepsState`: an open `fleet_5xx` incident, then a pass whose newest interval is incomplete and quiet. No Gone signal, and the incident stays open.
+ - `TestTrafficSignalsStaleBoxNotExpected`: a stale box with old windows doesn't block a clear.
- `TestTrafficSignalsListingFailedNoCover`
- `TestEnginePassFiveCycleRequests` (extend): heartbeats now carry 3 traffic windows each, and the pass's store call counts are exactly the existing assertion's.
- `TestAlertRuleOrderCoversEveryRule` (existing) passes with both rules added.
-- [ ] **Step 2: Run, expect FAIL.** `go test ./internal/console -run 'Fleet5xx|AbuseSurge|TrafficSignals|EnginePassFiveCycle|AlertRuleOrder' -count=1`
+- [ ] **Step 2: Run, expect FAIL.** `go test ./internal/console -run 'Fleet5xx|AbuseSurge|CombineTraffic|TrafficCoverage|TrafficSignals|EnginePassFiveCycle|AlertRuleOrder' -count=1`
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run, expect PASS.**
- [ ] **Step 5: Commit.** `git commit -m "console: fleet 5xx and abuse surge rules on the traffic series"`
@@ -411,8 +481,9 @@ Tasks 6 and 7 may swap order. Task 7 renders drafts until Task 6 lands, and Task
- **Range.** `range` is `24h`, `7d` or `30d`; anything else means 24h, and the page never answers 400. 24h and 7d draw hourly bars; 30d draws daily bars, each the sum of that day's hours.
- **Gaps.**
- A bar with no data is a gap, drawn as an empty, labelled column, never zero.
- - A day with some hours present is drawn from those hours.
- - The current hour is drawn as it stands.
+ - A partial hour (`trafficHour.Partial`) is drawn from what arrived and marked partial, with a lighter fill and a "partial" label for screen readers.
+ - A day is drawn from the hours present, and marked partial when any hour is partial or missing.
+ - The current hour is drawn as it stands, marked as still counting.
- **Stacks:**
- served = S2xx+S3xx
- 4xx = S4xx+S404
@@ -438,6 +509,7 @@ Tasks 6 and 7 may swap order. Task 7 renders drafts until Task 6 lands, and Task
- `TestFleetTrafficNotOperator404`
- `TestFleetTrafficTilesFollowIncidents`: open `abuse_surge` gives Abuse Watch linked to `#incident-<id>`. Open `cpu` gives Load Watch. With none open, all four are OK. Check for every rule in the tile table.
- `TestFleetTrafficChartGapNotZero`: hours 1-3 present, 4 missing, 5 present. Column 4 renders as a gap with no bar height.
+ - `TestFleetTrafficChartPartialMarked`: an hour with `BoxWindows < Boxes*12` renders marked partial, as does the 30d day that contains it.
- `TestFleetTrafficChartThirtyDaysDaily`
- `TestFleetTrafficHostileHostEscaped`: an unknown host `<script>x</script>.example` renders escaped, with no `<a` around it.
- `TestFleetTrafficRangeDefaults`: `?range=junk` gives 24h and status 200.
@@ -485,3 +557,27 @@ Tasks 6 and 7 may swap order. Task 7 renders drafts until Task 6 lands, and Task
- A region filter on the chart.
- Capacity tile gains "region has no room" when that rule moves onto the engine.
- Managed-fleet boxes' heartbeats (`fleets/<f>/status/boxes/`) are not read by the engine. Their traffic arrives through the hub's tunnel and is counted by the hub.
+
+---
+
+## R1 dispositions (Astra, `CODEX-FINDINGS-fleet-alerts-2-plan-R1.md`)
+
+1. **P1, one box hides another's missing windows.** Accepted.
+ - Completeness is now per expected box and window, and fails on any unread heartbeat.
+ - Missing evidence never clears; it can still fire.
+ - Hour rows carry `boxes` and `box_windows`, and partial hours and days are marked on the chart.
+ - A stale box is not expected: its silence is `box_silent`'s incident.
+ - Fault family: missing observations must not become healthy fleet measurements.
+2. **P1, backhaul and forward answers uncounted.** Accepted. There is now one counting owner per client answer (Global Constraints):
+ - forwarded requests' local answers are counted at the forwarding edge, by a delivered flag
+ - acknowledged home fills are skipped by the home under `!out.unbilled`
+ - integration tests cover admission refusal, saturation, dial failure, a delivered hop, an HA forward and a far fill
+3. **P1, the evaluation lag is shorter than the heartbeat cadence.** Accepted.
+ - Judging now runs to a watermark, the oldest of the expected boxes' newest window, over every interval end since the last judged.
+ - A timeline test with 5.5-minute heartbeats and unaligned passes pins that no end is skipped.
+4. **P1, the abuse test contradicts "above 5x".** Accepted. 1,501 fires and 1,500 doesn't.
+5. **P2, the payload bound.** Accepted.
+ - `status.TrimTrafficWindow` caps each window at 12 KiB encoded and drops list tail entries, never scalars.
+ - It is applied at the edge and on ingest.
+ - The worst-case test uses maximum-length `<` keys.
+
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-fleet-alerts-2-plan-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-fleet-alerts-2-plan-R1.md
new file mode 100644
index 000000000..afec27980
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-fleet-alerts-2-plan-R1.md
@@ -0,0 +1,55 @@
+Review of `95377f5269b056a140e69760967809f8e9e5defc`, round 1 of 3. References below are verified against that commit. No files were edited or test suites run.
+
+1. **P1 — Tasks 4–5: one box’s data can conceal another box’s missing windows.**
+
+ **Problem and evidence:** The plan defines completeness using distinct timestamps across all boxes (`docs/superpowers/plans/2026-11-01-fleet-alerts-2-traffic.md:261`, `:268`, `:333`). `r.boxes` returns successfully when an individual heartbeat cannot be read, recording that failure separately in `unreadBoxes` (`internal/console/alertsignals.go:151–175`). Task 5 does not incorporate those failures into traffic completeness.
+
+ **Failure scenario:** Boxes A and B previously contributed to an open `fleet_5xx` incident. B stops reporting while A supplies three healthy windows. All three timestamps exist, so evaluation emits a clear using A alone. `stepIncidents` removes the firing member on that false signal (`internal/console/alertengine.go:206–224`). The unknown-subject protection never applies because the plan declares this input complete.
+
+ The same problem affects abuse evaluation: nine of twelve timestamps qualify as complete (`plan:335`), allowing missing high-abuse windows to produce a false clear. Hourly and daily charts also conceal partial coverage (`plan:413–415`).
+
+ **Fix:** Track coverage per expected `(box, window)` using the existing heartbeat reads, with explicit participation rules for rollout and retirement. Carry incomplete coverage into rollups and charts. Hold rule state when required contributions are missing; do not treat nine windows as a complete hour.
+
+ **Fault family:** Missing observations must not become healthy fleet measurements.
+
+2. **P1 — Task 2: ordinary backhaul failures bypass both proposed counting hooks.**
+
+ **Problem and evidence:** Task 2 counts responses in the route observer and `serveAssetFar` (`plan:189–195`). Ordinary backhaul returns before the route observer is installed (`internal/edge/edge.go:1983–1985`, `:2182`). Backhaul admission can answer locally with 429 or 503 (`internal/edge/edge.go:3899–3912`), and a failed dial answers 502 (`internal/edge/edge.go:4074–4075`). None of these responses reaches either proposed hook.
+
+ **Failure scenario:** A known app’s home edge becomes unreachable. Visitors receive 502s from the forwarding edge, but no traffic counter records those failures. The home edge received nothing, and the forwarding edge returned before its observer. Fleet error totals and `fleet_5xx` therefore omit the outage.
+
+ **Fix:** Add explicit counting for answers produced by the forwarding path, with ownership rules preventing successful forwarded requests from being counted twice. Specify ownership for far-asset fills as well: their billing predicate and protection predicate differ (`internal/edge/assetcatch.go:1074–1092`), while acknowledged home fills still reach the home observer (`internal/edge/edge.go:2183–2198`). Add integration cases for admission refusal, failed dial, successful hop, acknowledged fill and fallback forwarding.
+
+ **Fault family:** Every client answer must have exactly one fleet counting owner.
+
+3. **P1 — Task 5: the evaluation lag is shorter than the normal heartbeat interval.**
+
+ **Problem and evidence:** The newest evaluated window starts at `cur-10m`, ending only five minutes before `cur` (`plan:333`). Heartbeats wait five minutes plus up to one minute of jitter (`internal/host/agent.go:4338`; `internal/status/fleet.go:120`). Evaluation runs only on every fifth engine pass (`internal/console/alertengine_pass.go:188–191`).
+
+ **Failure scenario:** A box publishes at 09:54:30 and next at 10:00:10, a valid cadence. At the 10:00 evaluation, its latest published window starts at 09:45. The required 09:50 window is missing. At 10:05, evaluation advances to starts 09:45, 09:50 and 09:55; it never evaluates the previously incomplete 09:40–09:55 interval. A threshold breach confined to that interval can be missed despite every heartbeat succeeding.
+
+ **Fix:** Define an evaluation watermark that accommodates the heartbeat cadence and publication delay, or evaluate previously pending intervals once their data arrives. Add a timeline test with unaligned engine passes and 5–6 minute heartbeat intervals, including a breach that qualifies in only one interval.
+
+ **Fault family:** Sampling and evaluation must not silently skip complete qualifying intervals.
+
+4. **P1 — Task 5: the abuse-surge test contradicts the specified comparison.**
+
+ **Problem and evidence:** The firing rule requires `B > multiple × median` (`plan:60`), consistent with “above 5x” in the approved spec (`docs/superpowers/specs/2026-10-30-fleet-alerts-and-traffic-design.md:331`). The test requires B = 1,500 to fire with median 300 and the default multiple 5 (`plan:351`).
+
+ **Failure scenario:** A correct implementation evaluates `1500 > 5 × 300` as false and fails the prescribed test. Making that test pass changes the approved boundary.
+
+ **Fix:** Require 1,500 not to fire and 1,501 to fire. Retain separate equality tests for the clear boundary.
+
+ **Fault family:** Tests and implementation must enforce the same threshold contract.
+
+5. **P2 — Tasks 1–2: the list caps cannot guarantee a traffic payload below 16 KiB.**
+
+ **Problem and evidence:** The plan carries three windows with up to ten entries per list (`plan:119–121`), allowing 512-byte paths and 253-byte hosts (`plan:49–50`), while promising a traffic block below 16 KiB (`plan:83`, `:210`). It specifies no serialized-byte budget.
+
+ **Failure scenario:** Ten maximum-length paths and ten maximum-length hosts in each of three windows already contain 22,950 bytes of key text. An in-memory compact JSON witness using those permitted lengths measured 24,400 bytes before adding the other three lists and most scalar fields. Escaping can increase the size further.
+
+ **Fix:** Reconcile the payload budget with the permitted representation. Enforce a serialized-byte limit with deterministic trimming that preserves scalar totals, or explicitly revise the bound. Test all three windows with maximum-length entries and JSON-escaping expansion.
+
+ **Fault family:** Cardinality limits must also enforce the promised wire-size bound.
+
+**NOT READY:** P1 findings 1–4 block implementation as written.
\ No newline at end of file