edge: traffic counter fixes from the Task 2 review
Apply I1, I2, M1, M2, M3, M4 and M6 from the Opus Task 2 review. Mask answer paths before locking, inject the counter clock at every traffic hook, retain late counts in the current window, and record answer time at final headers or successful hijack. Count guard matches without a usage meter and remove the redundant ingress hop-door check. Strip app-supplied X-Carlos-Ref in the tenant response modifier while preserving guard references over backhaul and HA forward hops. Regression tests cover late and pre-first timestamps, forged app 404s, guard counts without usage, answer-time windows and forwarded blocks. Targeted internal/edge tests passed normally and with -race, with fixture-only retries: the long scratch path exceeded a Unix socket's limit, so that test used a /proc fd alias; storage fixtures reject that alias and were rerun with the original scratch path. All scratch stayed under /home/paulca/.cache/fleet-alerts-2/scratch. Go vet, gofmt and git diff --check passed. Three mutations were caught: dropping late counts, accepting pre-first counts, and retaining forged app references. No additional plan drift or unresolved uncertainty.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
internal/edge/assetcatch.go+3 −1internal/edge/cookiescope.go+1 −0internal/edge/edge.go+3 −1internal/edge/guard.go+7 −4internal/edge/planthrottle.go+3 −2internal/edge/ratelimit.go+3 −1internal/edge/traffic.go+29 −14internal/edge/traffic_test.go+148 −4
CI failed — run details
Intent
<task-notification> <task-id>bg8tl6gax</task-id> <tool-use-id>toolu_01TFAvhWAN3ggzcX5ghJWSoT</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1f8653ea-6b78-4712-b1ac-1eb863a870a6/tasks/bg8tl6gax.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra build run C" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 18.5 g CO₂e (2,351,697 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/edge/assetcatch.go b/internal/edge/assetcatch.go| index 983c7c300..e732ff5a8 100644 |
| --- a/internal/edge/assetcatch.go |
| +++ b/internal/edge/assetcatch.go |
| @@ -1075,7 +1075,9 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string |
| if m := e.usageMeter.Load(); m != nil { |
| m.Record(rt, 1, n, false) |
| } |
| - e.traffic.Load().served(time.Now(), release.RouteAccount(rt), rt.App, cw.status) |
| + if c := e.traffic.Load(); c != nil { |
| + c.served(c.now(), release.RouteAccount(rt), rt.App, cw.status) |
| + } |
| } |
| // Every answer this edge wrote itself is recorded here when a rule |
| // matched it, as ServeHTTP's observer defer records a matched |
diff --git a/internal/edge/cookiescope.go b/internal/edge/cookiescope.go| index 7223ec745..923884205 100644 |
| --- a/internal/edge/cookiescope.go |
| +++ b/internal/edge/cookiescope.go |
| @@ -91,6 +91,7 @@ func (e *Edge) responseModifier(rt registry.Route) func(*http.Response) error { |
| stripAssetResponseHeaders(resp.Header) |
| stripAssetTrailers(resp) |
| stripAppHolder(resp) |
| + resp.Header.Del("X-Carlos-Ref") |
| e.scopeCookies(rt, resp) |
| return nil |
| } |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 8a227c1c8..85538b63e 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -2200,7 +2200,9 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| if m := e.usageMeter.Load(); m != nil { |
| m.Record(up.route, 1, bytes, hopped) |
| } |
| - e.traffic.Load().served(time.Now(), release.RouteAccount(up.route), up.route.App, ob.status) |
| + if c := e.traffic.Load(); c != nil { |
| + c.served(c.now(), release.RouteAccount(up.route), up.route.App, ob.status) |
| + } |
| } |
| if ob.status >= 500 && !out.answered { |
| e.emitEdgeError(up.route, up.viaTunnel, r, ob.status, out.cause) |
diff --git a/internal/edge/guard.go b/internal/edge/guard.go| index 449fd0d7c..7ed38f1a0 100644 |
| --- a/internal/edge/guard.go |
| +++ b/internal/edge/guard.go |
| @@ -6,7 +6,6 @@ import ( |
| "log" |
| "net/http" |
| "strings" |
| - "time" |
| "github.com/carlosframework/platform/internal/edgeguard" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -107,7 +106,7 @@ func (e *Edge) newGuardState() *guardState { |
| // feeds fleet traffic; r supplies the client identity and country for its list. |
| func (e *Edge) observeGuardCount(rt registry.Route, r *http.Request, out *outcome) { |
| m := e.usageMeter.Load() |
| - if m == nil || out == nil || out.guard == nil { |
| + if out == nil || out.guard == nil { |
| return |
| } |
| var rule *edgeguard.Rule |
| @@ -115,10 +114,14 @@ func (e *Edge) observeGuardCount(rt registry.Route, r *http.Request, out *outcom |
| if v := out.guard.verdict; v != nil { |
| rule, blocked = v.rule, v.block |
| } |
| - m.RecordGuard(rt, rule, blocked) |
| + if m != nil { |
| + m.RecordGuard(rt, rule, blocked) |
| + } |
| if rule != nil && rule.Mode != edgeguard.ModeBurst { |
| country, _ := geoAnswerFrom(r.Context()) |
| - e.traffic.Load().guard(time.Now(), blocked, clientIP(r), country.Country) |
| + if c := e.traffic.Load(); c != nil { |
| + c.guard(c.now(), blocked, clientIP(r), country.Country) |
| + } |
| } |
| } |
diff --git a/internal/edge/planthrottle.go b/internal/edge/planthrottle.go| index d70391254..3c8c676af 100644 |
| --- a/internal/edge/planthrottle.go |
| +++ b/internal/edge/planthrottle.go |
| @@ -4,7 +4,6 @@ import ( |
| "context" |
| "net/http" |
| "net/netip" |
| - "time" |
| "github.com/carlosframework/platform/internal/plans" |
| "github.com/carlosframework/platform/internal/ratelimit" |
| @@ -46,7 +45,9 @@ func (e *Edge) notePlanThrottled(rt registry.Route, what string) { |
| if m := e.usageMeter.Load(); m != nil { |
| m.RecordPlanThrottled(rt) |
| } |
| - e.traffic.Load().rate(time.Now(), release.RouteAccount(rt), rt.App, ratePlan) |
| + if c := e.traffic.Load(); c != nil { |
| + c.rate(c.now(), release.RouteAccount(rt), rt.App, ratePlan) |
| + } |
| e.logThrottled("plan-throttle "+rt.Host, "plan throttle: refused "+what+" for "+rt.Host+" (the account is slowed down until the month ends)") |
| } |
diff --git a/internal/edge/ratelimit.go b/internal/edge/ratelimit.go| index 232dcbf56..9122a26b1 100644 |
| --- a/internal/edge/ratelimit.go |
| +++ b/internal/edge/ratelimit.go |
| @@ -169,7 +169,9 @@ func (e *Edge) noteRateLimited(rt registry.Route, d ratelimit.Decision, client s |
| kind = rateObserved |
| } |
| if d != ratelimit.Allow { |
| - e.traffic.Load().rate(time.Now(), release.RouteAccount(rt), rt.App, kind) |
| + if c := e.traffic.Load(); c != nil { |
| + c.rate(c.now(), release.RouteAccount(rt), rt.App, kind) |
| + } |
| } |
| reason := "backstop" |
| if d == ratelimit.Shed { |
diff --git a/internal/edge/traffic.go b/internal/edge/traffic.go| index 9700319e3..ab31a26a7 100644 |
| --- a/internal/edge/traffic.go |
| +++ b/internal/edge/traffic.go |
| @@ -38,6 +38,7 @@ type trafficSourceKey struct{ client, country string } |
| // The maps stop admitting new keys at their caps; totals still count every hit. |
| type trafficCounter struct { |
| mu sync.Mutex |
| + now func() time.Time |
| clientID func(string, time.Time) string |
| first int64 |
| current status.TrafficWindow |
| @@ -57,7 +58,7 @@ func newTrafficCounter(now time.Time, clientID func(string, time.Time) string) * |
| if now.After(start) { |
| first = first.Add(status.TrafficWindowLen) |
| } |
| - c := &trafficCounter{clientID: clientID, first: first.Unix()} |
| + c := &trafficCounter{now: time.Now, clientID: clientID, first: first.Unix()} |
| c.reset(start.Unix()) |
| return c |
| } |
| @@ -211,10 +212,14 @@ func (c *trafficCounter) answer(at time.Time, code int, blockPage bool, path str |
| if c == nil { |
| return |
| } |
| + key := "" |
| + if code == 404 { |
| + key = trafficText(reqrec.MaskPath(path), 512) |
| + } |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| c.rotate(at) |
| - if at.Unix() < c.current.Start { |
| + if at.Unix() < c.first { |
| return |
| } |
| w := &c.current |
| @@ -234,7 +239,6 @@ func (c *trafficCounter) answer(at time.Time, code int, blockPage bool, path str |
| w.S5xx++ |
| } |
| if code == 404 { |
| - key := trafficText(reqrec.MaskPath(path), 512) |
| if _, ok := c.paths[key]; ok || len(c.paths) < 1024 { |
| c.paths[key]++ |
| } |
| @@ -251,7 +255,7 @@ func (c *trafficCounter) unknownHost(at time.Time, host string) { |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| c.rotate(at) |
| - if at.Unix() < c.current.Start { |
| + if at.Unix() < c.first { |
| return |
| } |
| c.current.UnknownHost++ |
| @@ -270,7 +274,7 @@ func (c *trafficCounter) served(at time.Time, account, app string, code int) { |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| c.rotate(at) |
| - if at.Unix() < c.current.Start { |
| + if at.Unix() < c.first { |
| return |
| } |
| row, ok := c.apps[k] |
| @@ -303,7 +307,7 @@ func (c *trafficCounter) guard(at time.Time, blocked bool, clientIP, country str |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| c.rotate(at) |
| - if at.Unix() < c.current.Start { |
| + if at.Unix() < c.first { |
| return |
| } |
| if blocked { |
| @@ -326,7 +330,7 @@ func (c *trafficCounter) rate(at time.Time, account, app string, kind rateKind) |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| c.rotate(at) |
| - if at.Unix() < c.current.Start { |
| + if at.Unix() < c.first { |
| return |
| } |
| switch kind { |
| @@ -426,20 +430,24 @@ func (e *Edge) observeIngress(w http.ResponseWriter, r *http.Request) (http.Resp |
| return w, r, func() {} |
| } |
| note := &ingressNote{} |
| - if _, door := doorCallerFrom(r.Context()); door || fromTunnel(r.Context()) || hopDoorFrom(r.Context()) { |
| + if _, door := doorCallerFrom(r.Context()); door || fromTunnel(r.Context()) { |
| note.skip = true |
| } |
| r = r.WithContext(context.WithValue(r.Context(), ingressNoteKey{}, note)) |
| - out := &ingressWriter{ResponseWriter: w} |
| + out := &ingressWriter{ResponseWriter: w, now: c.now} |
| return out, r, func() { |
| if note.skip { |
| return |
| } |
| + at := out.answeredAt |
| + if at.IsZero() { |
| + at = c.now() |
| + } |
| if note.unknown { |
| - c.unknownHost(time.Now(), note.host) |
| + c.unknownHost(at, note.host) |
| return |
| } |
| - c.answer(time.Now(), out.status, out.blockPage, r.URL.Path) |
| + c.answer(at, out.status, out.blockPage, r.URL.Path) |
| } |
| } |
| @@ -447,14 +455,17 @@ func (e *Edge) observeIngress(w http.ResponseWriter, r *http.Request) (http.Resp |
| // headers or buffering bodies. Its optional interfaces preserve streams and hops. |
| type ingressWriter struct { |
| http.ResponseWriter |
| - status int |
| - blockPage bool |
| + status int |
| + blockPage bool |
| + now func() time.Time |
| + answeredAt time.Time |
| } |
| // WriteHeader ignores interim headers when selecting the answer's class. |
| func (w *ingressWriter) WriteHeader(code int) { |
| if w.status == 0 && (code >= 200 || code == http.StatusSwitchingProtocols) { |
| w.status = code |
| + w.answeredAt = w.now() |
| w.blockPage = code == 404 && w.Header().Get("X-Carlos-Ref") != "" |
| } |
| w.ResponseWriter.WriteHeader(code) |
| @@ -483,7 +494,11 @@ func (w *ingressWriter) Flush() { |
| // has the same S2xx classification as 101. |
| func (w *ingressWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { |
| if h, ok := w.ResponseWriter.(http.Hijacker); ok { |
| - return h.Hijack() |
| + conn, rw, err := h.Hijack() |
| + if err == nil && w.answeredAt.IsZero() { |
| + w.answeredAt = w.now() |
| + } |
| + return conn, rw, err |
| } |
| return nil, nil, fmt.Errorf("edge: underlying ResponseWriter does not support http.Hijacker") |
| } |
diff --git a/internal/edge/traffic_test.go b/internal/edge/traffic_test.go| index 0293e1db3..680583308 100644 |
| --- a/internal/edge/traffic_test.go |
| +++ b/internal/edge/traffic_test.go |
| @@ -1,10 +1,12 @@ |
| package edge |
| import ( |
| + "bufio" |
| "context" |
| "encoding/json" |
| "fmt" |
| "io" |
| + "net" |
| "net/http" |
| "net/http/httptest" |
| "strings" |
| @@ -170,10 +172,11 @@ func TestTrafficConcurrentCounts(t *testing.T) { |
| // enableTestTraffic includes the current slot so integration tests need no five-minute sleep. |
| func enableTestTraffic(edges ...*Edge) time.Time { |
| - at := time.Now().UTC().Truncate(status.TrafficWindowLen) |
| + at := trafficStart() |
| for _, e := range edges { |
| - e.EnableTraffic(nil) |
| - e.traffic.Store(newTrafficCounter(at, nil)) |
| + c := newTrafficCounter(at, nil) |
| + c.now = func() time.Time { return at } |
| + e.traffic.Store(c) |
| } |
| return at.Add(status.TrafficWindowLen) |
| } |
| @@ -637,7 +640,7 @@ func TestTrafficIngressWriterFinalStatus(t *testing.T) { |
| {"late ref", func(w http.ResponseWriter) { w.WriteHeader(404); w.Header().Set("X-Carlos-Ref", "ref") }, 404, false}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| - w := &ingressWriter{ResponseWriter: httptest.NewRecorder()} |
| + w := &ingressWriter{ResponseWriter: httptest.NewRecorder(), now: trafficStart} |
| tc.write(w) |
| if w.status != tc.code || w.blockPage != tc.block { |
| t.Fatalf("status=%d block=%v", w.status, w.blockPage) |
| @@ -705,3 +708,144 @@ func TestEdgeTrafficUpgrade(t *testing.T) { |
| t.Fatalf("upgrade counters: %+v", w) |
| } |
| } |
| + |
| +func TestTrafficLateCountsRetained(t *testing.T) { |
| + at := trafficStart() |
| + for _, tc := range []struct { |
| + name string |
| + when time.Time |
| + want int64 |
| + }{ |
| + {"before first", at.Add(4 * time.Minute), 0}, |
| + {"first", at.Add(5 * time.Minute), 1}, |
| + {"late", at.Add(9 * time.Minute), 1}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + c := newTrafficCounter(at.Add(2*time.Minute), nil) |
| + c.windows(at.Add(10 * time.Minute)) |
| + c.answer(tc.when, 404, false, "/missing") |
| + c.unknownHost(tc.when, "unknown.test") |
| + c.served(tc.when, "acct", "app", 503) |
| + c.guard(tc.when, true, "203.0.113.1", "IE") |
| + c.rate(tc.when, "acct", "app", rateShed) |
| + ws := c.windows(at.Add(15 * time.Minute)) |
| + w := ws[len(ws)-1] |
| + if w.Start != at.Add(10*time.Minute).Unix() || w.Requests != tc.want || w.S404 != tc.want || w.UnknownHost != tc.want || w.Blocked != tc.want || w.RateShed != tc.want { |
| + t.Fatalf("late counts: %+v", w) |
| + } |
| + if int64(len(w.Apps)) != tc.want || int64(len(w.RateApps)) != tc.want || int64(len(w.Paths)) != tc.want || int64(len(w.Hosts)) != tc.want || int64(len(w.Sources)) != tc.want { |
| + t.Fatalf("late lists: %+v", w) |
| + } |
| + if tc.want == 1 && (w.Apps[0].Requests != 1 || w.Apps[0].S5xx != 1 || w.RateApps[0].Refused != 1 || w.Paths[0].Hits != 1 || w.Hosts[0].Hits != 1 || w.Sources[0].Hits != 1) { |
| + t.Fatalf("late list counts: %+v", w) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestEdgeTrafficAppCannotForgeRefusal(t *testing.T) { |
| + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("X-Carlos-Ref", "forged") |
| + w.WriteHeader(http.StatusNotFound) |
| + io.WriteString(w, "app missing") |
| + })) |
| + t.Cleanup(backend.Close) |
| + s := newRateScene(t, "off", nil, rlRoute(backend.Listener.Addr().String(), "")) |
| + end := enableTestTraffic(s.e) |
| + resp := trafficGet(s.e, rlHost, "/missing") |
| + w := trafficWindow(t, s.e, end) |
| + if resp.Code != 404 || resp.Header().Get("X-Carlos-Ref") != "" || resp.Body.String() != "app missing" || w.Requests != 1 || w.S404 != 1 || w.Refused != 0 { |
| + t.Fatalf("app response: code=%d headers=%v body=%q traffic=%+v", resp.Code, resp.Header(), resp.Body.String(), w) |
| + } |
| +} |
| + |
| +func TestEdgeTrafficGuardWithoutUsageMeter(t *testing.T) { |
| + g := guardEdge(t, false, false, 200, "ok") |
| + if g.e.usageMeter.Load() != nil { |
| + t.Fatal("unexpected usage meter") |
| + } |
| + end := enableTestTraffic(g.e) |
| + g.e.guard = guardBlock |
| + g.get("/.env") |
| + g.get("/admin") |
| + g.e.guard = guardWatch |
| + g.get("/wp-login.php") |
| + w := trafficWindow(t, g.e, end) |
| + if w.Blocked != 1 || w.Watched != 1 || len(w.Sources) != 1 || w.Sources[0].Hits != 2 { |
| + t.Fatalf("guard without meter: %+v", w) |
| + } |
| +} |
| + |
| +type trafficHijackWriter struct { |
| + *httptest.ResponseRecorder |
| + conn net.Conn |
| +} |
| + |
| +func (w *trafficHijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { |
| + return w.conn, bufio.NewReadWriter(bufio.NewReader(w.conn), bufio.NewWriter(w.conn)), nil |
| +} |
| + |
| +func TestTrafficIngressAnswerTime(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + write func(http.ResponseWriter) |
| + implicit bool |
| + }{ |
| + {"header", func(w http.ResponseWriter) { w.WriteHeader(200) }, false}, |
| + {"upgrade header", func(w http.ResponseWriter) { w.WriteHeader(101) }, false}, |
| + {"write", func(w http.ResponseWriter) { io.WriteString(w, "stream") }, false}, |
| + {"flush", func(w http.ResponseWriter) { w.(http.Flusher).Flush() }, false}, |
| + {"hijack", func(w http.ResponseWriter) { |
| + if _, _, err := w.(http.Hijacker).Hijack(); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, false}, |
| + {"empty", func(http.ResponseWriter) {}, true}, |
| + {"interim only", func(w http.ResponseWriter) { w.WriteHeader(103) }, true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + for _, unknown := range []bool{false, true} { |
| + e := &Edge{} |
| + end := enableTestTraffic(e) |
| + at := end.Add(-time.Minute) |
| + e.traffic.Load().now = func() time.Time { return at } |
| + conn, peer := net.Pipe() |
| + t.Cleanup(func() { conn.Close(); peer.Close() }) |
| + under := &trafficHijackWriter{ResponseRecorder: httptest.NewRecorder(), conn: conn} |
| + w, r, finish := e.observeIngress(under, httptest.NewRequest("GET", "http://app.test/", nil)) |
| + if unknown { |
| + noteIngressUnknown(r, "app.test") |
| + } |
| + tc.write(w) |
| + at = end.Add(time.Minute) |
| + finish() |
| + ws := e.TrafficWindows(end.Add(status.TrafficWindowLen)) |
| + want := 0 |
| + if tc.implicit { |
| + want = 1 |
| + } |
| + if len(ws) != 2 || ws[want].Requests+ws[want].UnknownHost != 1 || ws[1-want].Requests+ws[1-want].UnknownHost != 0 { |
| + t.Fatalf("unknown=%v answer windows: %+v", unknown, ws) |
| + } |
| + if unknown && ws[want].UnknownHost != 1 || !unknown && ws[want].S2xx != 1 { |
| + t.Fatalf("unknown=%v answer class: %+v", unknown, ws[want]) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestEdgeTrafficForwardGuardKeepsRefusal(t *testing.T) { |
| + s := newFwScene(t, fwOpts{}) |
| + s.b.edge.guard = guardBlock |
| + end := enableTestTraffic(s.a.edge, s.b.edge) |
| + resp, _ := s.fetch(t, fwHost, "/.env") |
| + if resp.StatusCode != 404 || resp.Header.Get("X-Carlos-Ref") == "" { |
| + t.Fatalf("forwarded guard response: %d %v", resp.StatusCode, resp.Header) |
| + } |
| + trafficHandlersDone(t, s.backhaulScene) |
| + _, home := trafficOnce(t, s.a.edge, s.b.edge, end, 404) |
| + if home.Blocked != 1 { |
| + t.Fatalf("home guard: %+v", home) |
| + } |
| +} |