carlos / platform Public

console: traffic series in console.db

Task 4 of fleet-alerts Plan 2 rev 3. Store validated box/window rows
once, recompute affected hourly totals in the same transaction, and keep
7 days of windows and 90 days of hourly history. Merge and rank all five
lists, preserve distinct-start and per-box coverage, and leave gaps absent.

Add 19 storage tests covering forged windows, scalar and list count bounds,
hostile text, encoded payload and list limits, late arrivals, completeness,
rollback/retry, retention boundaries, range endpoints and reopen behavior.
Targeted console tests and one targeted race run pass. Console vet, gofmt
on touched files and the staged whitespace check are clean.

Eight mutations were caught: timestamp alignment, scalar bounds, request
partition, string byte caps, encoded payload cap, committing source rows
on rollup failure, and each of the 7-day and 90-day retention cutoffs.
The source was restored before the race and vet checks.

Code drift: the claim SQL gate also requires classifying the new tables.
Register both as NonApp fleet telemetry and cover gated ingest and the
schema census. Add a start index for range reads and pruning. The first
late-window test fixture crossed an hour boundary; correct the fixture.

The prescribed joint Task 4/5 Opus review remains pending. Task 5 waits
on the ruling and was not started. No push, merge or census update.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
claude agent, operated by paul@keymail.dev 879b53d9bc08867dee7487e8c14ad5be04b03328 parent a1ecbd7
4 files changed, +1,188 −0
  • internal/console/alertstore.go +16 −0
  • internal/console/store_gate.go +2 −0
  • internal/console/trafficstore.go +443 −0
  • internal/console/trafficstore_test.go +727 −0

Intent

Human

<task-notification> <task-id>bi3m2g9os</task-id> <tool-use-id>toolu_01S7hqtjCMgRpQb8bGFraK8C</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1f8653ea-6b78-4712-b1ac-1eb863a870a6/tasks/bi3m2g9os.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra build run B" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a291e1f8f5d6d1aca</task-id> <tool-use-id>toolu_01FcJ37HGua2aktAkhNQ9dNE</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1f8653ea-6b78-4712-b1ac-1eb863a870a6/tasks/a291e1f8f5d6d1aca.output</output-file> <status>completed</status> <summary>Agent "Opus review of Task 2 edge counters" 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>**Verdict: FIXES NEEDED.** Task 2 (5984c7f7) gets the counting right, but two small things need fixing first: a 404 flood does path masking under the edge's single traffic mutex, and the integration tests use the wall clock, so they will occasionally flake in CI. Task 3 (a1ecbd75) is fine. I found nothing Critical. The targeted runs pass: `go test ./internal/edge -run Traffic -count=1` (5.9s) and `go test ./internal/reqrec -run ClientID -count=1`. `gofmt -l` and `go vet ./internal/edge` are clean. ## Critical None. ## Important **I1. A 404 flood serialises every request on the counter's mutex.** In `internal/edge/traffic.go:214-240`, `answer` takes `c.mu` and only then computes `trafficText(reqrec.MaskPath(path), 512)` for each 404. That means two stack arrays of roughly 6 KB, escaping, `strings.Map` and `strings.Clone`, all while holding the lock every answer on the edge needs. In Review Focus 1's scenario (a flood of random paths), every answer on the box queues behind this work, so the edge's request rate falls to what one locked section can do. - Fix: when `code == 404`, compute `key` before `c.mu.Lock()`, as `unknownHost` and `served` already do (`:250`, `:269`). **I2. The integration tests depend on the wall clock and flake near 5-minute boundaries.** `enableTestTraffic` (`internal/edge/traffic_test.go:172-180`) starts the counter at `floor5(time.Now())`, and `observeIngress`, `served`, `guard` and `rate` all use `time.Now()` directly. If a boundary falls between `enableTestTraffic` and the last answer, the answer lands in the next window. `trafficWindow(…, end)` then reports zero requests and the test fails. The test runs take about 4-6s of wall time, so expect roughly 1-2% of CI runs to fail. - Fix: give `trafficCounter` a `now func() time.Time` field, defaulting to `time.Now`. Use `c.now()` in `observeIngress`'s finish function and at the decision sites, and pin it in `enableTestTraffic`. ## Minor **M1. Answers can be dropped at window boundaries.** `answer`, `unknownHost`, `served`, `guard` and `rate` each return when `at.Unix() &lt; c.current.Start` (`traffic.go:217, 254, 273, 306, 329`). A goroutine that read `time.Now()` just before a boundary, then lost the lock to one that rotated, drops its count. `guard` is the most exposed, because `clientID` can wait for disk between taking `at` and locking. The result is a few lost answers per boundary under load, which breaks "every answer counted once". - Fix: count a late `at` into `current`. Only discard counts from before `first`. **M2. Guard counts still depend on the usage meter.** `observeGuardCount` returns at `guard.go:110-112` when `m == nil`, so Blocked and Watched are never counted without a meter. That contradicts the comment on the `traffic` field (`edge.go:184`, "independently of the optional usage and log sinks"). Production always arms the meter first (`agent.go:1052-1053`), so this has no effect today. - Fix: guard only `m.RecordGuard` with `m != nil`, and let the traffic call run regardless. **M3. An app can mark its own 404s as Refused.** The block-page test at `traffic.go:458` trusts any 404 that carries `X-Carlos-Ref`. Nothing strips that header from app responses (`guard.go:161` is its only writer, and there is no scrub on the response side). A tenant's own 404s then move from `S404` into `Refused`, which shrinks the answered denominator that `fleet_5xx` uses. The effect is small. - Fix: strip `X-Carlos-Ref` in the app proxy's ModifyResponse. Keep it on backhaul and forward hops, where the home's block page has to survive. **M4. Long-lived requests are counted when they end, not when they're answered.** The finish function stamps `time.Now()` at return (`traffic.go:439, 442`). A 6-hour WebSocket or SSE stream counts in the window where it closes, and is never counted if the box restarts first. - Fix: record the time in `WriteHeader` (or at Hijack), and count with that time in `finish`. **M5. Small per-request allocations.** Every request allocates the note, a context value, a request copy, the writer and a closure. `served` clones account and app on every call (`traffic.go:205, 269`) even when the key already exists. - Fix: merge the note and the writer into one struct, and clone strings only when inserting a new key. **M6. Redundant check.** `hopDoorFrom` in `observeIngress` (`traffic.go:429`) is always false on an incoming request, because only `acceptHop` sets it. The hop skip at `edge.go:1890` already covers that case. Drop it. **M7. The Task 3 test doesn't cover the real wiring line.** `TestStatusProbesCarryTraffic` (`internal/host/agent_traffic_test.go:57`) builds `Probes` itself, so the `Traffic: trafficWindows(time.Now())` line in `statusLoop` (`agent.go:4430`) isn't exercised. That's acceptable if the existing `geoIPState` test uses the same seam. ## Checked and correct - **One counting owner per answer.** These exits are all skipped: steering probe (`edge.go:1851`), tunnel hostname and store door (`:1865`), verified hop (`:1890`), status host (`:1921`, `:80` at `:2975`), LB health (`:2950`), and `:80` steering (`:2959`). Door and tunnel callers are skipped at entry (`traffic.go:429`). `forwardHA` and the far-asset fallback travel as signed hops (`forwardha.go:180-220`), so only the edge the visitor connected to counts them. A forged hop is counted (test at `traffic_test.go:566`). Upgrades and hijacks count as S2xx. Panics still run the deferred finish. Nothing in the edge rewrites `r.URL.Path` in place. - **Decision counters match the meter exactly.** Burst exclusion (`guard.go:119` matches `usagemeter.go:104`; `/admin` is a burst rule and the test checks it), the `Allow` filter, observe mode split into `RateObserved`, and plan throttling. - **Window rotation.** Skipped slots close as zero windows, a long idle period closes at most three, `first = ceil5(start)` hides the partial first window, and `windows` returns starts in `[floor-15m, floor)`. All maps are capped at the planned sizes, the counter resets its maps each slot, and it copies lists out to callers. - **Hostile strings.** Hosts are lower-cased, made valid UTF-8, stripped of controls and cut to 253 bytes. Paths are masked then cut to 512. `TrimTrafficWindow` runs at close. Sources leave the box only as the hash or the /24 (or /48) prefix. `clientIP` reads X-Forwarded-For only on a verified hop. - **Tests.** The named integration tests are real: two-edge backhaul, forward and asset scenes through `ServeHTTP`. Each asserts the fleet total is exactly one and which edge counted it. - **Style.** Comment density and the wrapper idiom match `statusCapture` and `countingWriter`. To pass: fix I1 and I2. M1 and M2 are one-line changes worth doing at the same time.</result> <usage><subagent_tokens>128773</subagent_tokens><tool_uses>32</tool_uses><duration_ms>402081</duration_ms></usage> </task-notification>

Attributed to this commit: 5.05 g CO₂e (662,770 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on fleet-alerts-2-traffic, 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/alertstore.go b/internal/console/alertstore.go
index c7c5a78f8..3c15e3fe5 100644
--- a/internal/console/alertstore.go
+++ b/internal/console/alertstore.go
@@ -133,6 +133,22 @@ func (s *Store) migrateAlerts() error {
`CREATE TABLE IF NOT EXISTS alert_meta (
k TEXT PRIMARY KEY,
v TEXT NOT NULL
+);`,
+ // Traffic rides the heartbeat. Keep each box/window once, then
+ // retain hourly summaries after the short-lived source rows expire.
+ `CREATE TABLE IF NOT EXISTS traffic_windows (
+ box TEXT NOT NULL,
+ start INTEGER NOT NULL,
+ body TEXT NOT NULL,
+ PRIMARY KEY (box, start)
+);`,
+ `CREATE INDEX IF NOT EXISTS traffic_windows_start ON traffic_windows (start);`,
+ `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
);`,
} {
if _, err := s.db.Exec(stmt); err != nil {
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index afd308024..b4b501b46 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -259,6 +259,8 @@ var claimSQLTables = map[string]claimSQLTable{
"alert_tokens": {NonApp: "alert confirm, unsubscribe and snooze links, keyed by token hash; names no app"},
"alert_snoozes": {NonApp: "alert snoozes per scope, rule and subject; no app state"},
"alert_meta": {NonApp: "the alert engine's one-shot markers"},
+ "traffic_windows": {NonApp: "fleet traffic observations keyed by box and start; app names in JSON are telemetry, with no app state or lifecycle authority"},
+ "traffic_hours": {NonApp: "hourly fleet traffic totals; app names in JSON are telemetry, with no app state or lifecycle authority"},
// The launch sponsorship rule (plansponsor.go).
"plan_launch_sponsorship": {NonApp: "the launch sponsorship rule the console started with (cutoff, plan, sponsored limits); one row, names no app"},
diff --git a/internal/console/trafficstore.go b/internal/console/trafficstore.go
new file mode 100644
index 000000000..26e686e64
--- /dev/null
+++ b/internal/console/trafficstore.go
@@ -0,0 +1,443 @@
+package console
+
+import (
+ "cmp"
+ "database/sql"
+ "encoding/json"
+ "slices"
+ "strings"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// trafficSum carries the observed totals without inventing missing windows.
+// Starts counts distinct slots, even when several boxes report the same slot.
+type trafficSum struct {
+ Requests int64 `json:"requests"`
+ S2xx int64 `json:"s2xx"`
+ S3xx int64 `json:"s3xx"`
+ S4xx int64 `json:"s4xx"`
+ S404 int64 `json:"s404"`
+ S5xx int64 `json:"s5xx"`
+ Refused int64 `json:"refused"`
+ Blocked int64 `json:"blocked"`
+ Watched int64 `json:"watched"`
+ RateShed int64 `json:"rate_shed"`
+ RateCeiling int64 `json:"rate_ceiling"`
+ RateObserved int64 `json:"rate_observed"`
+ PlanThrottled int64 `json:"plan_throttled"`
+ UnknownHost int64 `json:"unknown_host"`
+ Apps []status.TrafficApp `json:"apps,omitempty"`
+ RateApps []status.TrafficApp `json:"rate_apps,omitempty"`
+ Paths []status.TrafficCount `json:"paths,omitempty"`
+ Sources []status.TrafficSource `json:"sources,omitempty"`
+ Hosts []status.TrafficCount `json:"hosts,omitempty"`
+ Starts int `json:"starts"`
+}
+
+// Answered excludes refusals so callers use the same denominator as the edge.
+func (s trafficSum) Answered() int64 {
+ return s.S2xx + s.S3xx + s.S4xx + s.S404 + s.S5xx
+}
+
+// trafficHour keeps both fleet and per-box coverage: one reporting box must
+// not hide a missing slot from another box that contributed to this hour.
+type trafficHour struct {
+ Start time.Time
+ Windows, Boxes, BoxWindows int
+ Sum trafficSum
+}
+
+// Partial marks a still-counting hour or incomplete observations. An absent
+// hour has no trafficHour at all, so callers can draw a gap separately.
+func (h trafficHour) Partial(now time.Time) bool {
+ return now.Before(h.Start.Add(time.Hour)) || h.Windows < 12 || h.BoxWindows < h.Boxes*12
+}
+
+// addTraffic merges complete observations before any top-list truncation.
+// Callers count distinct starts separately because a fleet has many boxes.
+func addTraffic(sum *trafficSum, w status.TrafficWindow) {
+ sum.Requests += w.Requests
+ sum.S2xx += w.S2xx
+ sum.S3xx += w.S3xx
+ sum.S4xx += w.S4xx
+ sum.S404 += w.S404
+ sum.S5xx += w.S5xx
+ sum.Refused += w.Refused
+ sum.Blocked += w.Blocked
+ sum.Watched += w.Watched
+ sum.RateShed += w.RateShed
+ sum.RateCeiling += w.RateCeiling
+ sum.RateObserved += w.RateObserved
+ sum.PlanThrottled += w.PlanThrottled
+ sum.UnknownHost += w.UnknownHost
+ sum.Apps = mergeTrafficApps(sum.Apps, w.Apps)
+ sum.RateApps = mergeTrafficApps(sum.RateApps, w.RateApps)
+ sum.Paths = mergeTrafficCounts(sum.Paths, w.Paths)
+ sum.Hosts = mergeTrafficCounts(sum.Hosts, w.Hosts)
+ sum.Sources = mergeTrafficSources(sum.Sources, w.Sources)
+}
+
+// mergeTrafficApps uses a tuple key so slashes in an account or app cannot
+// combine unrelated rows. All measures survive regardless of list ranking.
+func mergeTrafficApps(dst, src []status.TrafficApp) []status.TrafficApp {
+ for _, row := range src {
+ i := slices.IndexFunc(dst, func(x status.TrafficApp) bool { return x.Account == row.Account && x.App == row.App })
+ if i < 0 {
+ dst = append(dst, row)
+ continue
+ }
+ dst[i].Requests += row.Requests
+ dst[i].S5xx += row.S5xx
+ dst[i].Refused += row.Refused
+ dst[i].Observed += row.Observed
+ }
+ return dst
+}
+
+// mergeTrafficCounts combines repeated paths or hosts across boxes and slots.
+func mergeTrafficCounts(dst, src []status.TrafficCount) []status.TrafficCount {
+ for _, row := range src {
+ i := slices.IndexFunc(dst, func(x status.TrafficCount) bool { return x.Key == row.Key })
+ if i < 0 {
+ dst = append(dst, row)
+ } else {
+ dst[i].Hits += row.Hits
+ }
+ }
+ return dst
+}
+
+// mergeTrafficSources preserves country in the key, matching the edge's list.
+func mergeTrafficSources(dst, src []status.TrafficSource) []status.TrafficSource {
+ for _, row := range src {
+ i := slices.IndexFunc(dst, func(x status.TrafficSource) bool { return x.Client == row.Client && x.Country == row.Country })
+ if i < 0 {
+ dst = append(dst, row)
+ } else {
+ dst[i].Hits += row.Hits
+ }
+ }
+ return dst
+}
+
+// trimmed returns ranked copies so retaining a smaller list cannot reorder or
+// overwrite a caller's aggregate. A negative n retains every observed key.
+func (s trafficSum) trimmed(n int) trafficSum {
+ s.Apps = trimTrafficApps(s.Apps, n, false)
+ s.RateApps = trimTrafficApps(s.RateApps, n, true)
+ s.Paths = trimTrafficCounts(s.Paths, n)
+ s.Hosts = trimTrafficCounts(s.Hosts, n)
+ s.Sources = slices.Clone(s.Sources)
+ slices.SortFunc(s.Sources, func(a, b status.TrafficSource) int {
+ if c := cmp.Compare(b.Hits, a.Hits); c != 0 {
+ return c
+ }
+ if c := strings.Compare(a.Client, b.Client); c != 0 {
+ return c
+ }
+ return strings.Compare(a.Country, b.Country)
+ })
+ if n >= 0 && len(s.Sources) > n {
+ s.Sources = slices.Clone(s.Sources[:n])
+ }
+ return s
+}
+
+// trimTrafficApps ranks served apps by requests and rate apps by all decisions,
+// breaking ties by identity so persisted JSON does not depend on arrival order.
+func trimTrafficApps(rows []status.TrafficApp, n int, rate bool) []status.TrafficApp {
+ rows = slices.Clone(rows)
+ slices.SortFunc(rows, func(a, b status.TrafficApp) int {
+ x, y := a.Requests, b.Requests
+ if rate {
+ x, y = a.Refused+a.Observed, b.Refused+b.Observed
+ }
+ if c := cmp.Compare(y, x); c != 0 {
+ return c
+ }
+ if c := strings.Compare(a.Account, b.Account); c != 0 {
+ return c
+ }
+ return strings.Compare(a.App, b.App)
+ })
+ if n >= 0 && len(rows) > n {
+ rows = slices.Clone(rows[:n])
+ }
+ return rows
+}
+
+// trimTrafficCounts keeps the highest-hit keys, with stable ties for charts.
+func trimTrafficCounts(rows []status.TrafficCount, n int) []status.TrafficCount {
+ rows = slices.Clone(rows)
+ slices.SortFunc(rows, func(a, b status.TrafficCount) int {
+ if c := cmp.Compare(b.Hits, a.Hits); c != 0 {
+ return c
+ }
+ return strings.Compare(a.Key, b.Key)
+ })
+ if n >= 0 && len(rows) > n {
+ rows = slices.Clone(rows[:n])
+ }
+ return rows
+}
+
+// trafficText bounds the cleaned bytes without leaving a partial UTF-8 rune.
+// The clone releases a hostile input's possibly much larger backing string.
+func trafficText(s string, limit int) string {
+ s = strings.Map(func(r rune) rune {
+ if unicode.IsControl(r) {
+ return '?'
+ }
+ return r
+ }, strings.ToValidUTF8(s, "?"))
+ if len(s) > limit {
+ s = s[:limit]
+ for !utf8.ValidString(s) {
+ s = s[:len(s)-1]
+ }
+ }
+ return strings.Clone(s)
+}
+
+// sanitizeTrafficWindow treats heartbeat fields as untrusted. Bad scalar
+// counts or timestamps discard the observation; bad list entries can be
+// dropped without losing its totals. It never edits the caller's slices.
+func sanitizeTrafficWindow(w status.TrafficWindow, now time.Time) (status.TrafficWindow, bool) {
+ const maxCount = int64(1e12)
+ step := int64(status.TrafficWindowLen / time.Second)
+ if w.Start%step != 0 || w.Start < now.Add(-2*time.Hour).Unix() || w.Start > now.Add(time.Minute-status.TrafficWindowLen).Unix() {
+ return status.TrafficWindow{}, false
+ }
+ if time.Unix(w.Start, 0).Before(now.Add(-2 * time.Hour)) {
+ return status.TrafficWindow{}, false
+ }
+ for _, n := range []int64{w.Requests, w.S2xx, w.S3xx, w.S4xx, w.S404, w.S5xx, w.Refused,
+ w.Blocked, w.Watched, w.RateShed, w.RateCeiling, w.RateObserved, w.PlanThrottled, w.UnknownHost} {
+ if n < 0 || n > maxCount {
+ return status.TrafficWindow{}, false
+ }
+ }
+ if w.Requests != w.Answered()+w.Refused {
+ return status.TrafficWindow{}, false
+ }
+ for _, list := range []*[]status.TrafficApp{&w.Apps, &w.RateApps} {
+ var clean []status.TrafficApp
+ for _, row := range *list {
+ if row.Requests > maxCount || row.S5xx > maxCount || row.Refused > maxCount || row.Observed > maxCount {
+ return status.TrafficWindow{}, false
+ }
+ if row.Requests < 0 || row.S5xx < 0 || row.Refused < 0 || row.Observed < 0 {
+ continue
+ }
+ row.Account, row.App = trafficText(row.Account, 128), trafficText(row.App, 128)
+ clean = append(clean, row)
+ }
+ *list = clean
+ }
+ for i, list := range []*[]status.TrafficCount{&w.Paths, &w.Hosts} {
+ limit := 512
+ if i == 1 {
+ limit = 253
+ }
+ var clean []status.TrafficCount
+ for _, row := range *list {
+ if row.Hits > maxCount {
+ return status.TrafficWindow{}, false
+ }
+ if row.Hits < 0 {
+ continue
+ }
+ row.Key = trafficText(row.Key, limit)
+ clean = append(clean, row)
+ }
+ *list = clean
+ }
+ var sources []status.TrafficSource
+ for _, row := range w.Sources {
+ if row.Hits > maxCount {
+ return status.TrafficWindow{}, false
+ }
+ if row.Hits < 0 {
+ continue
+ }
+ row.Client = trafficText(row.Client, 64)
+ if len(row.Country) != 2 || row.Country[0] < 'A' || row.Country[0] > 'Z' || row.Country[1] < 'A' || row.Country[1] > 'Z' {
+ row.Country = ""
+ }
+ sources = append(sources, row)
+ }
+ lists := (trafficSum{Apps: w.Apps, RateApps: w.RateApps, Paths: w.Paths, Hosts: w.Hosts, Sources: sources}).trimmed(status.TrafficTopN)
+ w.Apps, w.RateApps, w.Paths, w.Hosts, w.Sources = lists.Apps, lists.RateApps, lists.Paths, lists.Hosts, lists.Sources
+ status.TrimTrafficWindow(&w, status.TrafficWindowMaxBytes)
+ return w, true
+}
+
+// IngestTraffic commits observations and refreshed hourly totals together.
+// Repeated heartbeats cannot overwrite an accepted (box, start), and a failed
+// rollup rolls back its source rows so the next heartbeat can retry them.
+func (s *Store) IngestTraffic(byBox map[string][]status.TrafficWindow, now time.Time) (inserted int, err error) {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return 0, err
+ }
+ defer tx.Rollback()
+ hours := make(map[int64]bool)
+ for box, input := range byBox {
+ var windows []status.TrafficWindow
+ for _, w := range input {
+ if clean, ok := sanitizeTrafficWindow(w, now); ok {
+ windows = append(windows, clean)
+ }
+ }
+ slices.SortStableFunc(windows, func(a, b status.TrafficWindow) int { return cmp.Compare(b.Start, a.Start) })
+ // Duplicate starts do not use up one of the three retained slots.
+ windows = slices.CompactFunc(windows, func(a, b status.TrafficWindow) bool { return a.Start == b.Start })
+ if len(windows) > status.TrafficWindowsKept {
+ windows = windows[:status.TrafficWindowsKept]
+ }
+ for _, w := range windows {
+ body, err := json.Marshal(w)
+ if err != nil {
+ return 0, err
+ }
+ result, err := tx.Exec(`INSERT OR IGNORE INTO traffic_windows (box, start, body) VALUES (?, ?, ?)`, box, w.Start, string(body))
+ if err != nil {
+ return 0, err
+ }
+ n, err := result.RowsAffected()
+ if err != nil {
+ return 0, err
+ }
+ if n > 0 {
+ inserted += int(n)
+ hours[time.Unix(w.Start, 0).UTC().Truncate(time.Hour).Unix()] = true
+ }
+ }
+ }
+ for hour := range hours {
+ if err := recomputeTrafficHour(tx, hour); err != nil {
+ return 0, err
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ return 0, err
+ }
+ return inserted, nil
+}
+
+// recomputeTrafficHour reads every surviving source row before trimming lists,
+// so late arrivals can change both totals and which keys belong in the top 20.
+func recomputeTrafficHour(tx *sql.Tx, hour int64) error {
+ rows, err := tx.Query(`SELECT box, start, body FROM traffic_windows WHERE start >= ? AND start < ? ORDER BY start, box`, hour, hour+3600)
+ if err != nil {
+ return err
+ }
+ var sum trafficSum
+ starts, boxes := make(map[int64]bool), make(map[string]bool)
+ boxWindows := 0
+ for rows.Next() {
+ var box, body string
+ var start int64
+ if err := rows.Scan(&box, &start, &body); err != nil {
+ rows.Close()
+ return err
+ }
+ var w status.TrafficWindow
+ if err := json.Unmarshal([]byte(body), &w); err != nil {
+ rows.Close()
+ return err
+ }
+ addTraffic(&sum, w)
+ starts[start], boxes[box] = true, true
+ boxWindows++
+ }
+ err = rows.Err()
+ rows.Close()
+ if err != nil {
+ return err
+ }
+ sum.Starts = len(starts)
+ body, err := json.Marshal(sum.trimmed(20))
+ if err != nil {
+ return err
+ }
+ _, err = tx.Exec(`INSERT INTO traffic_hours (start, windows, boxes, box_windows, body) VALUES (?, ?, ?, ?, ?)
+ON CONFLICT (start) DO UPDATE SET windows=excluded.windows, boxes=excluded.boxes, box_windows=excluded.box_windows, body=excluded.body`,
+ hour, len(starts), len(boxes), boxWindows, string(body))
+ return err
+}
+
+// PruneTraffic preserves hourly history after its source windows expire. It
+// does not rebuild hours from the now-incomplete seven-day source series.
+func (s *Store) PruneTraffic(now time.Time) error {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ if _, err := tx.Exec(`DELETE FROM traffic_windows WHERE start < ?`, now.Add(-7*24*time.Hour).Unix()); err != nil {
+ return err
+ }
+ if _, err := tx.Exec(`DELETE FROM traffic_hours WHERE start < ?`, now.Add(-90*24*time.Hour).Unix()); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// TrafficRange sums [from, to) from observed five-minute rows only. Returning
+// the actual starts lets a rule distinguish missing slots from zero traffic.
+func (s *Store) TrafficRange(from, to time.Time) (sum trafficSum, starts map[int64]bool, err error) {
+ rows, err := s.db.Query(`SELECT start, body FROM traffic_windows WHERE start >= ? AND start < ? ORDER BY start, box`, from.Unix(), to.Unix())
+ if err != nil {
+ return trafficSum{}, nil, err
+ }
+ defer rows.Close()
+ starts = make(map[int64]bool)
+ for rows.Next() {
+ var start int64
+ var body string
+ if err := rows.Scan(&start, &body); err != nil {
+ return trafficSum{}, nil, err
+ }
+ var w status.TrafficWindow
+ if err := json.Unmarshal([]byte(body), &w); err != nil {
+ return trafficSum{}, nil, err
+ }
+ addTraffic(&sum, w)
+ starts[start] = true
+ }
+ if err := rows.Err(); err != nil {
+ return trafficSum{}, nil, err
+ }
+ sum.Starts = len(starts)
+ return sum.trimmed(-1), starts, nil
+}
+
+// TrafficHours returns only persisted hours in [from, to), oldest first.
+// Callers draw missing rows as gaps rather than filling them with zeroes.
+func (s *Store) TrafficHours(from, to time.Time) ([]trafficHour, error) {
+ rows, err := s.db.Query(`SELECT start, windows, boxes, box_windows, body FROM traffic_hours WHERE start >= ? AND start < ? ORDER BY start`, from.Unix(), to.Unix())
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var hours []trafficHour
+ for rows.Next() {
+ var h trafficHour
+ var start int64
+ var body string
+ if err := rows.Scan(&start, &h.Windows, &h.Boxes, &h.BoxWindows, &body); err != nil {
+ return nil, err
+ }
+ h.Start = time.Unix(start, 0).UTC()
+ if err := json.Unmarshal([]byte(body), &h.Sum); err != nil {
+ return nil, err
+ }
+ hours = append(hours, h)
+ }
+ return hours, rows.Err()
+}
diff --git a/internal/console/trafficstore_test.go b/internal/console/trafficstore_test.go
new file mode 100644
index 000000000..dfeef464e
--- /dev/null
+++ b/internal/console/trafficstore_test.go
@@ -0,0 +1,727 @@
+package console
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/carlosframework/platform/internal/status"
+)
+
+var trafficStoreNow = time.Date(2026, 11, 1, 12, 17, 0, 0, time.UTC)
+
+// trafficStoreWindow builds a valid one-request window so storage tests can
+// vary the row's identity without accidentally testing the validator instead.
+func trafficStoreWindow(start time.Time) status.TrafficWindow {
+ return status.TrafficWindow{
+ Start: start.Unix(), Requests: 1, S2xx: 1,
+ }
+}
+
+// trafficStoreAt returns a UTC five-minute boundary relative to the fixed
+// test clock, keeping every fixture independent of the wall clock.
+func trafficStoreAt(minutesAgo int) time.Time {
+ return trafficStoreNow.Truncate(5 * time.Minute).Add(-time.Duration(minutesAgo) * time.Minute)
+}
+
+// TestTrafficIngestDedupesByBoxAndStart pins the stable identity of a window:
+// one box can contribute a start only once, while separate starts remain.
+func TestTrafficIngestDedupesByBoxAndStart(t *testing.T) {
+ s := openTestStore(t)
+ windows := []status.TrafficWindow{
+ trafficStoreWindow(trafficStoreAt(15)),
+ trafficStoreWindow(trafficStoreAt(10)),
+ trafficStoreWindow(trafficStoreAt(5)),
+ }
+ byBox := map[string][]status.TrafficWindow{"box-a": windows}
+ inserted, err := s.IngestTraffic(byBox, trafficStoreNow)
+ if err != nil || inserted != 3 {
+ t.Fatalf("first ingest = %d, %v; want 3 rows", inserted, err)
+ }
+ inserted, err = s.IngestTraffic(byBox, trafficStoreNow)
+ if err != nil || inserted != 0 {
+ t.Fatalf("duplicate ingest = %d, %v; want 0 rows", inserted, err)
+ }
+ if got := alertCount(t, s, "traffic_windows"); got != 3 {
+ t.Fatalf("stored windows = %d, want 3", got)
+ }
+ for _, w := range windows {
+ got, starts, err := s.TrafficRange(time.Unix(w.Start, 0), time.Unix(w.Start+300, 0))
+ if err != nil || got.Requests != 1 || !starts[w.Start] || len(starts) != 1 {
+ t.Fatalf("range for start %d = requests %d, starts %v, err %v", w.Start, got.Requests, starts, err)
+ }
+ }
+}
+
+// TestTrafficIngestRejectsForgedWindows checks the heartbeat trust boundary:
+// invalid windows are discarded and only a box's newest three can be stored.
+func TestTrafficIngestRejectsForgedWindows(t *testing.T) {
+ tests := []struct {
+ name string
+ edit func(*status.TrafficWindow)
+ }{
+ {"unaligned start", func(w *status.TrafficWindow) { w.Start++ }},
+ {"future window", func(w *status.TrafficWindow) {
+ w.Start = trafficStoreNow.Truncate(5 * time.Minute).Add(5 * time.Minute).Unix()
+ }},
+ {"too old window", func(w *status.TrafficWindow) {
+ w.Start = trafficStoreNow.Truncate(5 * time.Minute).Add(-2*time.Hour - 5*time.Minute).Unix()
+ }},
+ {"scalar negative", func(w *status.TrafficWindow) { w.Blocked = -1 }},
+ {"request mismatch", func(w *status.TrafficWindow) { w.Requests = 2 }},
+ {"scalar over maximum", func(w *status.TrafficWindow) { w.Requests, w.S2xx = 1_000_000_000_001, 1_000_000_000_001 }},
+ {"list count over maximum", func(w *status.TrafficWindow) {
+ w.Paths = []status.TrafficCount{{Key: "/huge", Hits: 1_000_000_000_001}}
+ }},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ s := openTestStore(t)
+ w := trafficStoreWindow(trafficStoreAt(10))
+ tc.edit(&w)
+ inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow)
+ if err != nil || inserted != 0 {
+ t.Fatalf("ingest = %d, %v; want invalid window rejected", inserted, err)
+ }
+ if got := alertCount(t, s, "traffic_windows"); got != 0 {
+ t.Fatalf("invalid window stored %d rows", got)
+ }
+ })
+ }
+
+ // Five distinct, valid starts in deliberately shuffled order must be cut
+ // to the latest three, independently of the forged-window checks above.
+ s := openTestStore(t)
+ starts := []time.Time{trafficStoreAt(5), trafficStoreAt(20), trafficStoreAt(10), trafficStoreAt(15), trafficStoreAt(25)}
+ windows := make([]status.TrafficWindow, 0, len(starts))
+ for _, start := range starts {
+ windows = append(windows, trafficStoreWindow(start))
+ }
+ inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": windows}, trafficStoreNow)
+ if err != nil || inserted != 3 {
+ t.Fatalf("latest-window ingest = %d, %v; want 3", inserted, err)
+ }
+ _, got, err := s.TrafficRange(time.Time{}, trafficStoreNow.Add(time.Second))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := map[int64]bool{trafficStoreAt(15).Unix(): true, trafficStoreAt(10).Unix(): true, trafficStoreAt(5).Unix(): true}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("kept starts = %v, want %v", got, want)
+ }
+}
+
+// TestTrafficIngestChecksEveryScalarBound pins the inclusive 0..1e12 range
+// for each wire count and accepts the exact upper boundary on a valid window.
+func TestTrafficIngestChecksEveryScalarBound(t *testing.T) {
+ fields := []string{"Requests", "S2xx", "S3xx", "S4xx", "S404", "S5xx", "Refused", "Blocked", "Watched", "RateShed", "RateCeiling", "RateObserved", "PlanThrottled", "UnknownHost"}
+ for _, field := range fields {
+ for _, value := range []int64{-1, 1_000_000_000_001} {
+ field, value := field, value
+ t.Run(fmt.Sprintf("%s/%s", field, map[bool]string{true: "negative", false: "over"}[value < 0]), func(t *testing.T) {
+ s := openTestStore(t)
+ w := trafficStoreWindow(trafficStoreAt(5))
+ setTrafficScalar(&w, field, value)
+ inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow)
+ if err != nil || inserted != 0 {
+ t.Fatalf("%s=%d ingest = %d, %v; want rejected", field, value, inserted, err)
+ }
+ if got := alertCount(t, s, "traffic_windows"); got != 0 {
+ t.Fatalf("%s=%d stored %d rows", field, value, got)
+ }
+ })
+ }
+ }
+ s := openTestStore(t)
+ w := trafficStoreWindow(trafficStoreAt(5))
+ w.Requests, w.S2xx = 1_000_000_000_000, 1_000_000_000_000
+ if inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow); err != nil || inserted != 1 {
+ t.Fatalf("exact maximum count ingest = %d, %v; want accepted", inserted, err)
+ }
+}
+
+// TestTrafficIngestChecksEveryListCountBound rejects oversized values in each
+// numeric field of every list shape, regardless of the list's ranking type.
+func TestTrafficIngestChecksEveryListCountBound(t *testing.T) {
+ tests := []struct {
+ name string
+ edit func(*status.TrafficWindow)
+ }{
+ {"apps.requests", func(w *status.TrafficWindow) {
+ w.Apps = []status.TrafficApp{{Account: "a", App: "b", Requests: 1_000_000_000_001}}
+ }},
+ {"apps.s5xx", func(w *status.TrafficWindow) {
+ w.Apps = []status.TrafficApp{{Account: "a", App: "b", S5xx: 1_000_000_000_001}}
+ }},
+ {"apps.refused", func(w *status.TrafficWindow) {
+ w.Apps = []status.TrafficApp{{Account: "a", App: "b", Refused: 1_000_000_000_001}}
+ }},
+ {"apps.observed", func(w *status.TrafficWindow) {
+ w.Apps = []status.TrafficApp{{Account: "a", App: "b", Observed: 1_000_000_000_001}}
+ }},
+ {"rateapps.requests", func(w *status.TrafficWindow) {
+ w.RateApps = []status.TrafficApp{{Account: "a", App: "b", Requests: 1_000_000_000_001}}
+ }},
+ {"rateapps.s5xx", func(w *status.TrafficWindow) {
+ w.RateApps = []status.TrafficApp{{Account: "a", App: "b", S5xx: 1_000_000_000_001}}
+ }},
+ {"rateapps.refused", func(w *status.TrafficWindow) {
+ w.RateApps = []status.TrafficApp{{Account: "a", App: "b", Refused: 1_000_000_000_001}}
+ }},
+ {"rateapps.observed", func(w *status.TrafficWindow) {
+ w.RateApps = []status.TrafficApp{{Account: "a", App: "b", Observed: 1_000_000_000_001}}
+ }},
+ {"paths.hits", func(w *status.TrafficWindow) { w.Paths = []status.TrafficCount{{Key: "/p", Hits: 1_000_000_000_001}} }},
+ {"hosts.hits", func(w *status.TrafficWindow) { w.Hosts = []status.TrafficCount{{Key: "h", Hits: 1_000_000_000_001}} }},
+ {"sources.hits", func(w *status.TrafficWindow) {
+ w.Sources = []status.TrafficSource{{Client: "c", Country: "US", Hits: 1_000_000_000_001}}
+ }},
+ }
+ for _, tc := range tests {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ s := openTestStore(t)
+ w := trafficStoreWindow(trafficStoreAt(5))
+ tc.edit(&w)
+ if inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow); err != nil || inserted != 0 {
+ t.Fatalf("oversized %s ingest = %d, %v; want rejected", tc.name, inserted, err)
+ }
+ if got := alertCount(t, s, "traffic_windows"); got != 0 {
+ t.Fatalf("oversized %s stored %d rows", tc.name, got)
+ }
+ })
+ }
+}
+
+// TestTrafficIngestTimestampBoundaries covers the inclusive age and tolerated
+// future edges, plus extreme signed timestamps that could overflow arithmetic.
+func TestTrafficIngestTimestampBoundaries(t *testing.T) {
+ accepted := []struct {
+ name string
+ now time.Time
+ at time.Time
+ }{
+ {"exact two-hour age", time.Date(2026, 11, 1, 12, 20, 0, 0, time.UTC), time.Date(2026, 11, 1, 10, 20, 0, 0, time.UTC)},
+ {"window ends one minute ahead", time.Date(2026, 11, 1, 12, 19, 0, 0, time.UTC), time.Date(2026, 11, 1, 12, 15, 0, 0, time.UTC)},
+ }
+ for _, tc := range accepted {
+ tc := tc
+ t.Run("accept/"+tc.name, func(t *testing.T) {
+ s := openTestStore(t)
+ if inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {trafficStoreWindow(tc.at)}}, tc.now); err != nil || inserted != 1 {
+ t.Fatalf("boundary ingest = %d, %v; want accepted", inserted, err)
+ }
+ })
+ }
+ rejected := []struct {
+ name string
+ now time.Time
+ at int64
+ }{
+ {"five minutes beyond age", time.Date(2026, 11, 1, 12, 20, 0, 0, time.UTC), time.Date(2026, 11, 1, 10, 15, 0, 0, time.UTC).Unix()},
+ {"future end one second too late", time.Date(2026, 11, 1, 12, 18, 59, 0, time.UTC), time.Date(2026, 11, 1, 12, 15, 0, 0, time.UTC).Unix()},
+ {"minimum int64", trafficStoreNow, math.MinInt64},
+ {"maximum int64", trafficStoreNow, math.MaxInt64},
+ }
+ for _, tc := range rejected {
+ tc := tc
+ t.Run("reject/"+tc.name, func(t *testing.T) {
+ s := openTestStore(t)
+ w := trafficStoreWindow(time.Unix(tc.at, 0))
+ w.Start = tc.at
+ if inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, tc.now); err != nil || inserted != 0 {
+ t.Fatalf("boundary ingest = %d, %v; want rejected", inserted, err)
+ }
+ if got := alertCount(t, s, "traffic_windows"); got != 0 {
+ t.Fatalf("rejected timestamp stored %d rows", got)
+ }
+ })
+ }
+}
+
+// setTrafficScalar changes one scalar while preserving a well-formed request
+// partition where the selected field allows one.
+func setTrafficScalar(w *status.TrafficWindow, field string, value int64) {
+ switch field {
+ case "Requests":
+ w.Requests, w.S2xx = value, value
+ case "S2xx":
+ w.Requests, w.S2xx = value, value
+ case "S3xx", "S4xx", "S404", "S5xx", "Refused":
+ w.Requests, w.S2xx, w.S3xx, w.S4xx, w.S404, w.S5xx, w.Refused = 0, 0, 0, 0, 0, 0, 0
+ switch field {
+ case "S3xx":
+ w.S3xx = value
+ case "S4xx":
+ w.S4xx = value
+ case "S404":
+ w.S404 = value
+ case "S5xx":
+ w.S5xx = value
+ case "Refused":
+ w.Refused = value
+ }
+ w.Requests = value
+ default:
+ w.Requests, w.S2xx = 1, 1
+ reflect.ValueOf(w).Elem().FieldByName(field).SetInt(value)
+ }
+}
+
+// TestTrafficIngestDropsNegativeListCounts ensures invalid top-list entries
+// disappear without discarding an otherwise valid scalar window.
+func TestTrafficIngestDropsNegativeListCounts(t *testing.T) {
+ s := openTestStore(t)
+ w := trafficStoreWindow(trafficStoreAt(5))
+ w.Apps = []status.TrafficApp{
+ {Account: "acct", App: "bad-requests", Requests: -1},
+ {Account: "acct", App: "bad-s5xx", S5xx: -1},
+ {Account: "acct", App: "bad-refused", Refused: -1},
+ {Account: "acct", App: "bad-observed", Observed: -1},
+ {Account: "acct", App: "good", Requests: 3, S5xx: 1},
+ }
+ w.RateApps = []status.TrafficApp{
+ {Account: "acct", App: "bad-requests", Requests: -1},
+ {Account: "acct", App: "bad-s5xx", S5xx: -1},
+ {Account: "acct", App: "bad-refused", Refused: -1},
+ {Account: "acct", App: "bad-observed", Observed: -1},
+ {Account: "acct", App: "good", Refused: 1},
+ }
+ w.Paths = []status.TrafficCount{{Key: "/bad", Hits: -1}, {Key: "/good", Hits: 2}}
+ inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow)
+ if err != nil || inserted != 1 {
+ t.Fatalf("ingest = %d, %v; want valid window retained", inserted, err)
+ }
+ sum, _, err := s.TrafficRange(time.Unix(w.Start, 0), time.Unix(w.Start+300, 0))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(sum.Apps) != 1 || sum.Apps[0].App != "good" || sum.Apps[0].Requests != 3 || len(sum.RateApps) != 1 || sum.RateApps[0].App != "good" || len(sum.Paths) != 1 || sum.Paths[0].Key != "/good" {
+ t.Fatalf("negative list entries were not dropped: apps=%+v rate apps=%+v paths=%+v", sum.Apps, sum.RateApps, sum.Paths)
+ }
+}
+
+// TestTrafficIngestTrimsHostileStrings ensures every persisted list is bounded,
+// ranked, and safe to pass to later rendering code.
+func TestTrafficIngestTrimsHostileStrings(t *testing.T) {
+ s := openTestStore(t)
+ w := trafficStoreWindow(trafficStoreAt(10))
+ bad := func(n int) string { return strings.Repeat("<", n-2) + "\x00" + string([]byte{0xff}) }
+ w.Apps = []status.TrafficApp{{Account: bad(128), App: bad(128), Requests: 10}}
+ w.RateApps = []status.TrafficApp{{Account: bad(128), App: bad(128), Refused: 10}}
+ w.Paths = []status.TrafficCount{{Key: "bad\x00" + string([]byte{0xff}) + strings.Repeat("p", 510), Hits: 10}}
+ w.Sources = []status.TrafficSource{{Client: bad(64), Country: "<s", Hits: 10}}
+ w.Hosts = []status.TrafficCount{{Key: bad(253) + strings.Repeat("h", 2000), Hits: 10}}
+ before := w
+ before.Apps = append([]status.TrafficApp(nil), w.Apps...)
+ before.RateApps = append([]status.TrafficApp(nil), w.RateApps...)
+ before.Paths = append([]status.TrafficCount(nil), w.Paths...)
+ before.Sources = append([]status.TrafficSource(nil), w.Sources...)
+ before.Hosts = append([]status.TrafficCount(nil), w.Hosts...)
+ if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(w, before) {
+ t.Fatal("ingest mutated the heartbeat's input slices")
+ }
+ sum, _, err := s.TrafficRange(time.Unix(w.Start, 0), time.Unix(w.Start+300, 0))
+ if err != nil {
+ t.Fatal(err)
+ }
+ check := func(label, value string, cap int) {
+ t.Helper()
+ if len(value) > cap || !utf8.ValidString(value) || strings.IndexFunc(value, unicode.IsControl) >= 0 {
+ t.Errorf("%s = %q (bytes %d), want valid, control-free UTF-8 at most %d bytes", label, value, len(value), cap)
+ }
+ }
+ check("account", sum.Apps[0].Account, 128)
+ check("app", sum.Apps[0].App, 128)
+ check("rate account", sum.RateApps[0].Account, 128)
+ check("rate app", sum.RateApps[0].App, 128)
+ check("path", sum.Paths[0].Key, 512)
+ check("host", sum.Hosts[0].Key, 253)
+ check("client", sum.Sources[0].Client, 64)
+ if sum.Sources[0].Country != "" {
+ t.Errorf("country = %q, want empty for invalid two-letter code", sum.Sources[0].Country)
+ }
+
+ // Worst-case keys make JSON escape each '<' as six bytes. Even this full
+ // ten-entry payload must fit the 12 KiB wire budget without changing totals.
+ worst := trafficStoreWindow(trafficStoreAt(5))
+ worst.Requests, worst.S2xx, worst.Blocked = 19, 19, 23
+ for i := 0; i < 10; i++ {
+ hits := int64(10 - i)
+ worst.Apps = append(worst.Apps, status.TrafficApp{Account: strings.Repeat("<", 128), App: strings.Repeat("<", 128), Requests: hits})
+ worst.RateApps = append(worst.RateApps, status.TrafficApp{Account: strings.Repeat("<", 128), App: strings.Repeat("<", 128), Refused: hits})
+ worst.Paths = append(worst.Paths, status.TrafficCount{Key: strings.Repeat("<", 512), Hits: hits})
+ worst.Hosts = append(worst.Hosts, status.TrafficCount{Key: strings.Repeat("<", 253), Hits: hits})
+ worst.Sources = append(worst.Sources, status.TrafficSource{Client: strings.Repeat("<", 64), Country: "US", Hits: hits})
+ }
+ worstBefore := worst
+ worstBefore.Apps = append([]status.TrafficApp(nil), worst.Apps...)
+ worstBefore.RateApps = append([]status.TrafficApp(nil), worst.RateApps...)
+ worstBefore.Paths = append([]status.TrafficCount(nil), worst.Paths...)
+ worstBefore.Hosts = append([]status.TrafficCount(nil), worst.Hosts...)
+ worstBefore.Sources = append([]status.TrafficSource(nil), worst.Sources...)
+ if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {worst}}, trafficStoreNow); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(worst, worstBefore) {
+ t.Fatal("worst-case ingest mutated the heartbeat's input slices")
+ }
+ var body string
+ if err := s.db.QueryRow(`SELECT body FROM traffic_windows WHERE box = 'box-a' AND start = ?`, worst.Start).Scan(&body); err != nil {
+ t.Fatal(err)
+ }
+ if len(body) > status.TrafficWindowMaxBytes {
+ t.Fatalf("stored worst-case window is %d bytes, want at most %d", len(body), status.TrafficWindowMaxBytes)
+ }
+ sum, _, err = s.TrafficRange(time.Unix(worst.Start, 0), time.Unix(worst.Start+300, 0))
+ if err != nil || sum.Requests != 19 || sum.S2xx != 19 || sum.Blocked != 23 {
+ t.Fatalf("worst-case scalar totals = %+v, %v; want requests/s2xx=19 and blocked=23", sum, err)
+ }
+}
+
+// TestTrafficIngestCapsEveryList checks the ten-entry limit independently of
+// the byte limit: small keys must not let an oversized list into the database.
+func TestTrafficIngestCapsEveryList(t *testing.T) {
+ s := openTestStore(t)
+ w := trafficStoreWindow(trafficStoreAt(5))
+ for i := 0; i < 20; i++ {
+ key := fmt.Sprintf("key-%02d", i)
+ w.Apps = append(w.Apps, status.TrafficApp{Account: "acct", App: key, Requests: int64(i)})
+ w.RateApps = append(w.RateApps, status.TrafficApp{Account: "acct", App: key, Observed: int64(20 - i)})
+ w.Paths = append(w.Paths, status.TrafficCount{Key: key, Hits: int64(i)})
+ w.Hosts = append(w.Hosts, status.TrafficCount{Key: key, Hits: int64(i)})
+ w.Sources = append(w.Sources, status.TrafficSource{Client: key, Country: "IE", Hits: int64(i)})
+ }
+ if n, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box": {w}}, trafficStoreNow); err != nil || n != 1 {
+ t.Fatalf("ingest = %d, %v; want one row", n, err)
+ }
+ var body string
+ if err := s.db.QueryRow(`SELECT body FROM traffic_windows WHERE box = 'box' AND start = ?`, w.Start).Scan(&body); err != nil {
+ t.Fatal(err)
+ }
+ var got status.TrafficWindow
+ if err := json.Unmarshal([]byte(body), &got); err != nil {
+ t.Fatal(err)
+ }
+ for name, n := range map[string]int{"apps": len(got.Apps), "rate apps": len(got.RateApps), "paths": len(got.Paths), "hosts": len(got.Hosts), "sources": len(got.Sources)} {
+ if n != status.TrafficTopN {
+ t.Fatalf("%s has %d entries, want %d", name, n, status.TrafficTopN)
+ }
+ }
+ if got.Apps[0].App != "key-19" || got.RateApps[0].App != "key-00" || got.Paths[0].Key != "key-19" || got.Hosts[0].Key != "key-19" || got.Sources[0].Client != "key-19" {
+ t.Fatalf("lists lost their highest-ranked entry: %+v", got)
+ }
+}
+
+// TestTrafficHourRollupMergesBoxesAndLists pins the hourly aggregates, exact
+// distinct-start and box counts, and the per-box completeness calculation.
+func TestTrafficHourRollupMergesBoxesAndLists(t *testing.T) {
+ s := openTestStore(t)
+ start := trafficStoreAt(25).Truncate(time.Hour)
+ first := trafficStoreWindow(start)
+ first.Requests, first.S2xx, first.S3xx, first.S4xx, first.S404, first.S5xx = 7, 1, 1, 1, 1, 1
+ first.Refused, first.Blocked, first.Watched = 2, 3, 4
+ first.RateShed, first.RateCeiling, first.RateObserved, first.PlanThrottled, first.UnknownHost = 5, 6, 7, 8, 9
+ first.Apps = []status.TrafficApp{{Account: "acct", App: "same", Requests: 5, S5xx: 1}}
+ first.RateApps = []status.TrafficApp{{Account: "acct", App: "same", Refused: 2, Observed: 3}}
+ first.Paths = []status.TrafficCount{{Key: "/same", Hits: 2}}
+ first.Hosts = []status.TrafficCount{{Key: "same.example", Hits: 3}}
+ first.Sources = []status.TrafficSource{{Client: "hash", Country: "IE", Hits: 4}}
+ second := first
+ second.Start += 5 * 60
+ second.Requests, second.S2xx, second.S3xx, second.S4xx, second.S404, second.S5xx = 14, 2, 2, 2, 2, 2
+ second.Refused, second.Blocked, second.Watched = 4, 6, 8
+ second.RateShed, second.RateCeiling, second.RateObserved, second.PlanThrottled, second.UnknownHost = 10, 12, 14, 16, 18
+ second.Apps = []status.TrafficApp{{Account: "acct", App: "same", Requests: 10, S5xx: 2}}
+ second.RateApps = []status.TrafficApp{{Account: "acct", App: "same", Refused: 4, Observed: 6}}
+ second.Paths = []status.TrafficCount{{Key: "/same", Hits: 4}}
+ second.Hosts = []status.TrafficCount{{Key: "same.example", Hits: 6}}
+ second.Sources = []status.TrafficSource{{Client: "hash", Country: "IE", Hits: 8}}
+ if n, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {first, second}, "box-b": {first}}, trafficStoreNow); err != nil || n != 3 {
+ t.Fatalf("ingest = %d, %v; want 3", n, err)
+ }
+ hours, err := s.TrafficHours(start, start.Add(time.Hour))
+ if err != nil || len(hours) != 1 {
+ t.Fatalf("hours = %+v, %v; want one hour", hours, err)
+ }
+ h := hours[0]
+ wantTotals := trafficSum{
+ Requests: 28, S2xx: 4, S3xx: 4, S4xx: 4, S404: 4, S5xx: 4,
+ Refused: 8, Blocked: 12, Watched: 16, RateShed: 20, RateCeiling: 24,
+ RateObserved: 28, PlanThrottled: 32, UnknownHost: 36, Starts: 2,
+ Apps: []status.TrafficApp{{Account: "acct", App: "same", Requests: 20, S5xx: 4}},
+ RateApps: []status.TrafficApp{{Account: "acct", App: "same", Refused: 8, Observed: 12}},
+ Paths: []status.TrafficCount{{Key: "/same", Hits: 8}},
+ Hosts: []status.TrafficCount{{Key: "same.example", Hits: 12}},
+ Sources: []status.TrafficSource{{Client: "hash", Country: "IE", Hits: 16}},
+ }
+ if h.Windows != 2 || h.Boxes != 2 || h.BoxWindows != 3 || !reflect.DeepEqual(h.Sum, wantTotals) {
+ t.Fatalf("hour = %+v; want windows=2 boxes=2 box_windows=3 sum=%+v", h, wantTotals)
+ }
+ if !h.Partial(trafficStoreNow) {
+ t.Fatal("hour missing one box/window was not marked partial")
+ }
+}
+
+// TestTrafficHourRecomputedOnLateWindow confirms a new window refreshes the
+// already materialised hour rather than leaving a stale aggregate.
+func TestTrafficHourRecomputedOnLateWindow(t *testing.T) {
+ s := openTestStore(t)
+ start := trafficStoreAt(30)
+ first := trafficStoreWindow(start)
+ if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {first}}, trafficStoreNow); err != nil {
+ t.Fatal(err)
+ }
+ late := trafficStoreWindow(start.Add(5 * time.Minute))
+ late.Requests, late.S2xx = 7, 7
+ if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {late}}, trafficStoreNow); err != nil {
+ t.Fatal(err)
+ }
+ hours, err := s.TrafficHours(start.Truncate(time.Hour), start.Truncate(time.Hour).Add(time.Hour))
+ if err != nil || len(hours) != 1 || hours[0].Sum.Requests != 8 || hours[0].Windows != 2 || hours[0].BoxWindows != 2 {
+ t.Fatalf("late recompute = %+v, %v; want 8 requests over 2 windows", hours, err)
+ }
+}
+
+// TestTrafficHourRollupRanksTwentyEntries checks that the stored hourly top
+// lists merge across windows and boxes before retaining the 20 highest counts.
+func TestTrafficHourRollupRanksTwentyEntries(t *testing.T) {
+ s := openTestStore(t)
+ byBox := make(map[string][]status.TrafficWindow)
+ starts := []time.Time{trafficStoreAt(75), trafficStoreAt(70), trafficStoreAt(65)}
+ for boxIndex, box := range []string{"box-a", "box-b", "box-c"} {
+ for _, start := range starts {
+ w := trafficStoreWindow(start)
+ for offset := 0; offset < 10; offset++ {
+ index := boxIndex*10 + offset
+ key := string(rune('a'+index/26)) + string(rune('a'+index%26))
+ count := int64(30 - index)
+ w.Apps = append(w.Apps, status.TrafficApp{Account: "acct", App: key, Requests: count, S5xx: 1})
+ w.RateApps = append(w.RateApps, status.TrafficApp{Account: "acct", App: key, Refused: count, Observed: count})
+ w.Paths = append(w.Paths, status.TrafficCount{Key: "/" + key, Hits: count})
+ w.Hosts = append(w.Hosts, status.TrafficCount{Key: key + ".example", Hits: count})
+ w.Sources = append(w.Sources, status.TrafficSource{Client: key, Country: "US", Hits: count})
+ }
+ // One request answer keeps the scalar partition valid; list totals
+ // are independent samples of their own decisions and hits.
+ byBox[box] = append(byBox[box], w)
+ }
+ }
+ if n, err := s.IngestTraffic(byBox, trafficStoreNow); err != nil || n != 9 {
+ t.Fatalf("ingest = %d, %v; want 9 rows", n, err)
+ }
+ hour := starts[0].Truncate(time.Hour)
+ hours, err := s.TrafficHours(hour, hour.Add(time.Hour))
+ if err != nil || len(hours) != 1 {
+ t.Fatalf("hour = %+v, %v; want one", hours, err)
+ }
+ sum := hours[0].Sum
+ if len(sum.Apps) != 20 || len(sum.RateApps) != 20 || len(sum.Paths) != 20 || len(sum.Hosts) != 20 || len(sum.Sources) != 20 {
+ t.Fatalf("hourly list sizes = apps %d rate apps %d paths %d hosts %d sources %d; want 20 each",
+ len(sum.Apps), len(sum.RateApps), len(sum.Paths), len(sum.Hosts), len(sum.Sources))
+ }
+ if sum.Apps[0].App != "aa" || sum.Apps[0].Requests != 90 || sum.Apps[19].App != "at" || sum.Apps[19].Requests != 33 {
+ t.Fatalf("ranked apps = first %+v last %+v; want aa/90 through at/33", sum.Apps[0], sum.Apps[19])
+ }
+ if sum.Paths[0].Key != "/aa" || sum.Paths[19].Key != "/at" || sum.Hosts[0].Key != "aa.example" || sum.Hosts[19].Key != "at.example" || sum.Sources[0].Client != "aa" || sum.Sources[19].Client != "at" {
+ t.Fatalf("ranked list endpoints = paths %+v/%+v hosts %+v/%+v sources %+v/%+v",
+ sum.Paths[0], sum.Paths[19], sum.Hosts[0], sum.Hosts[19], sum.Sources[0], sum.Sources[19])
+ }
+}
+
+// TestTrafficPruneKeeps7DaysAnd90Days pins both retention cutoffs at their
+// exact boundary so pruning does not delete data one instant too early.
+func TestTrafficPruneKeeps7DaysAnd90Days(t *testing.T) {
+ s := openTestStore(t)
+ now := trafficStoreNow.Truncate(time.Hour)
+ oldWindow := now.Add(-7*24*time.Hour - 5*time.Minute)
+ keepWindow := now.Add(-7 * 24 * time.Hour)
+ for box, at := range map[string]time.Time{"old": oldWindow, "keep": keepWindow} {
+ body, _ := json.Marshal(trafficStoreWindow(at))
+ if _, err := s.db.Exec(`INSERT INTO traffic_windows(box, start, body) VALUES(?, ?, ?)`, box, at.Unix(), string(body)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ oldHour := now.Add(-90*24*time.Hour - time.Hour).Unix()
+ keepHour := now.Add(-90 * 24 * time.Hour).Unix()
+ body, _ := json.Marshal(trafficSum{})
+ for _, start := range []int64{oldHour, keepHour} {
+ if _, err := s.db.Exec(`INSERT INTO traffic_hours(start, windows, boxes, box_windows, body) VALUES(?, 0, 0, 0, ?)`, start, string(body)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.PruneTraffic(now); err != nil {
+ t.Fatal(err)
+ }
+ if got := alertCount(t, s, "traffic_windows"); got != 1 {
+ t.Fatalf("windows after prune = %d, want only the exact 7-day boundary", got)
+ }
+ var hours int
+ if err := s.db.QueryRow(`SELECT COUNT(*) FROM traffic_hours`).Scan(&hours); err != nil || hours != 1 {
+ t.Fatalf("hours after prune = %d, %v; want exact 90-day boundary only", hours, err)
+ }
+}
+
+// TestTrafficHoursGapIsAbsent ensures a missing hour remains a gap instead of
+// becoming a synthetic zero-valued traffic bar.
+func TestTrafficHoursGapIsAbsent(t *testing.T) {
+ s := openTestStore(t)
+ start := trafficStoreAt(5).Truncate(time.Hour)
+ if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {trafficStoreWindow(start)}}, trafficStoreNow); err != nil {
+ t.Fatal(err)
+ }
+ hours, err := s.TrafficHours(start.Add(-time.Hour), start.Add(time.Hour))
+ if err != nil || len(hours) != 1 || !hours[0].Start.Equal(start) {
+ t.Fatalf("hours across one missing hour = %+v, %v; want only %s", hours, err, start)
+ }
+}
+
+// TestTrafficHourCurrentIsPartial keeps the live bucket visibly incomplete
+// while it is still collecting windows, even when no heartbeat has been lost.
+func TestTrafficHourCurrentIsPartial(t *testing.T) {
+ s := openTestStore(t)
+ start := trafficStoreNow.Truncate(time.Hour)
+ if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {trafficStoreWindow(start)}}, trafficStoreNow); err != nil {
+ t.Fatal(err)
+ }
+ hours, err := s.TrafficHours(start, start.Add(time.Hour))
+ if err != nil || len(hours) != 1 || !hours[0].Partial(trafficStoreNow) {
+ t.Fatalf("current hour = %+v, %v; want one partial hour", hours, err)
+ }
+}
+
+// TestTrafficHourPerBoxCompleteness distinguishes a full set of starts from
+// complete per-box coverage, then proves one late window fills the only gap.
+func TestTrafficHourPerBoxCompleteness(t *testing.T) {
+ s := openTestStore(t)
+ hour := time.Date(2026, 11, 1, 11, 0, 0, 0, time.UTC)
+ missing := hour.Add(55 * time.Minute)
+ for batch := 0; batch < 4; batch++ {
+ byBox := map[string][]status.TrafficWindow{"box-a": {}, "box-b": {}}
+ for offset := 0; offset < 3; offset++ {
+ at := hour.Add(time.Duration(batch*3+offset) * 5 * time.Minute)
+ byBox["box-a"] = append(byBox["box-a"], trafficStoreWindow(at))
+ if !at.Equal(missing) {
+ byBox["box-b"] = append(byBox["box-b"], trafficStoreWindow(at))
+ }
+ }
+ if _, err := s.IngestTraffic(byBox, trafficStoreNow); err != nil {
+ t.Fatalf("batch %d ingest: %v", batch, err)
+ }
+ }
+ hours, err := s.TrafficHours(hour, hour.Add(time.Hour))
+ if err != nil || len(hours) != 1 || hours[0].Windows != 12 || hours[0].Boxes != 2 || hours[0].BoxWindows != 23 || !hours[0].Partial(trafficStoreNow) {
+ t.Fatalf("hour with one missing box window = %+v, %v; want 12 starts, 2 boxes, 23 rows, partial", hours, err)
+ }
+ if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-b": {trafficStoreWindow(missing)}}, trafficStoreNow); err != nil {
+ t.Fatal(err)
+ }
+ hours, err = s.TrafficHours(hour, hour.Add(time.Hour))
+ if err != nil || len(hours) != 1 || hours[0].BoxWindows != 24 || hours[0].Partial(trafficStoreNow) {
+ t.Fatalf("hour after late missing window = %+v, %v; want complete 24 rows", hours, err)
+ }
+}
+
+// TestTrafficIngestRollsBackAndRetries proves the rows and inserted count are
+// atomic when the hourly materialisation fails, and that retry can store them.
+func TestTrafficIngestRollsBackAndRetries(t *testing.T) {
+ s := openTestStore(t)
+ if _, err := s.db.Exec(`CREATE TRIGGER traffic_hours_fail BEFORE INSERT ON traffic_hours BEGIN SELECT RAISE(ABORT, 'forced'); END`); err != nil {
+ t.Fatal(err)
+ }
+ w := trafficStoreWindow(trafficStoreAt(5))
+ inserted, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow)
+ if err == nil || inserted != 0 {
+ t.Fatalf("failed ingest = %d, %v; want rollback and zero inserted", inserted, err)
+ }
+ if got := alertCount(t, s, "traffic_windows"); got != 0 {
+ t.Fatalf("rows survived failed rollup: %d", got)
+ }
+ if _, err := s.db.Exec(`DROP TRIGGER traffic_hours_fail`); err != nil {
+ t.Fatal(err)
+ }
+ inserted, err = s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow)
+ if err != nil || inserted != 1 {
+ t.Fatalf("retry = %d, %v; want one inserted row", inserted, err)
+ }
+}
+
+// TestTrafficRangeUsesHalfOpenEndpoints fixes the inclusive-from/exclusive-to
+// contract used by callers that combine adjacent chart ranges.
+func TestTrafficRangeUsesHalfOpenEndpoints(t *testing.T) {
+ s := openTestStore(t)
+ starts := []time.Time{trafficStoreAt(15), trafficStoreAt(10), trafficStoreAt(5)}
+ windows := []status.TrafficWindow{}
+ for _, start := range starts {
+ w := trafficStoreWindow(start)
+ w.Requests, w.S2xx = 2, 2
+ windows = append(windows, w)
+ }
+ if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": windows}, trafficStoreNow); err != nil {
+ t.Fatal(err)
+ }
+ sum, gotStarts, err := s.TrafficRange(starts[1], starts[2])
+ if err != nil || sum.Requests != 2 || !reflect.DeepEqual(gotStarts, map[int64]bool{starts[1].Unix(): true}) {
+ t.Fatalf("half-open range = requests %d starts %v err %v", sum.Requests, gotStarts, err)
+ }
+}
+
+// TestTrafficStoreSurvivesReopen verifies migration-on-open preserves the
+// traffic rows and their rollup body across a normal console restart.
+func TestTrafficStoreSurvivesReopen(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "console.db")
+ s, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w := trafficStoreWindow(trafficStoreAt(5))
+ w.Requests, w.S2xx, w.Blocked = 9, 9, 3
+ if n, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {w}}, trafficStoreNow); err != nil || n != 1 {
+ t.Fatalf("ingest = %d, %v", n, err)
+ }
+ if err := s.Close(); err != nil {
+ t.Fatal(err)
+ }
+ s, err = Open(path)
+ if err != nil {
+ t.Fatalf("reopen: %v", err)
+ }
+ defer s.Close()
+ sum, starts, err := s.TrafficRange(time.Unix(w.Start, 0), time.Unix(w.Start+300, 0))
+ if err != nil || sum.Requests != 9 || sum.Blocked != 3 || len(starts) != 1 {
+ t.Fatalf("after reopen = %+v starts=%v err=%v", sum, starts, err)
+ }
+ hours, err := s.TrafficHours(time.Unix(w.Start, 0).Truncate(time.Hour), time.Unix(w.Start, 0).Truncate(time.Hour).Add(time.Hour))
+ if err != nil || len(hours) != 1 || hours[0].Sum.Requests != 9 {
+ t.Fatalf("hour after reopen = %+v, %v", hours, err)
+ }
+}
+
+// TestTrafficIngestClaimGate checks that newly migrated traffic tables are
+// explicitly treated as non-app telemetry by the claim SQL census.
+func TestTrafficIngestClaimGate(t *testing.T) {
+ s := openGatedStore(t)
+ if _, err := s.IngestTraffic(map[string][]status.TrafficWindow{"box-a": {trafficStoreWindow(trafficStoreAt(5))}}, trafficStoreNow); err != nil {
+ t.Fatal(err)
+ }
+ present, err := claimSQLCensus(s.bootDB(), claimSQLTables)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{"traffic_windows", "traffic_hours"} {
+ spec, ok := present[name]
+ if !ok || spec.NonApp == "" {
+ t.Errorf("%s classification = %+v (present %v), want NonApp", name, spec, ok)
+ }
+ }
+}