carlos / platform Public

host: heartbeat carries traffic windows

Enable fleet traffic counting in the edge-ready callback, with the
recorder's ClientID when available and coarse-prefix fallback otherwise.
Publish the edge's completed-window source atomically and include its
current result in the existing status heartbeat's Probes.

Task 3 of fleet-alerts Plan 2 rev 3. The tests follow the existing upstream
probe seam through statusTick and its stored heartbeat JSON. They cover
startup with no edge, all three windows, and removal of old traffic when
the next source result is empty. Targeted host tests and the race run
pass; vet and gofmt are clean. Removing the startup nil-source guard was
caught by TestTrafficWindowsBeforeEdgeReadyIsNil.

Code drift: the recorder is constructed later in the ready callback than
the plan's GeoIP/EnableUsage anchor. Traffic is enabled and published next
to that actual construction, so the callback can use its ClientID.
No Task 4 or later work, push, merge or census update was attempted.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
claude agent, operated by paul@keymail.dev a1ecbd75f2f0e10c3bc9f6d695e61c95c6047024 parent 5984c7f
2 files changed, +115 −0
  • internal/host/agent.go +23 −0
  • internal/host/agent_traffic_test.go +92 −0

CI failed — run details

Intent

Attributed to this commit: 16.2 g CO₂e (1,955,194 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/host/agent.go b/internal/host/agent.go
index 21d84cbd6..83f82d5fb 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1092,8 +1092,14 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// as the edge's interface would not be nil to it.
if rec := newRequestRecorder(logSink, dataDir(), os.Getenv, time.Now); rec != nil {
e.EnableRequestRecords(rec)
+ e.EnableTraffic(rec.ClientID)
go reqrecLoop(rec, time.NewTicker(time.Minute).C)
+ } else {
+ // Fleet counting still runs with request records off. Sources then
+ // use the same coarse client prefix that records keep without salt.
+ e.EnableTraffic(nil)
}
+ trafficSource.Store(e.TrafficWindows)
// The edge asset cache (design §7, §10), last, so the meter, the rate
// ceiling and the plan throttle are in place before it answers
// anything: with CARLOS_ASSET_CACHE=1, the disk store under the data
@@ -4155,6 +4161,21 @@ var upstreamSource atomic.Value // func() map[string][]status.UpstreamState
// the edge-ready callback like upstreamSource (geoip spec §5.5).
var geoIPSource atomic.Value // func() edge.GeoIPState
+// trafficSource supplies completed edge windows to the existing heartbeat.
+// Like geoIPSource, it is published only after the edge is ready: statusLoop
+// starts earlier and must not report invented zero traffic while it waits.
+var trafficSource atomic.Value // func(time.Time) []status.TrafficWindow
+
+// trafficWindows reads the live edge's completed windows at this tick's time.
+// No source means no observation, so startup and boxes without an edge omit it.
+func trafficWindows(now time.Time) []status.TrafficWindow {
+ fn, _ := trafficSource.Load().(func(time.Time) []status.TrafficWindow)
+ if fn == nil {
+ return nil
+ }
+ return fn(now)
+}
+
// geoIPAlertSource is the edge's geoip reason code for the box alert rule
// (geoip spec §10.4), published from the same ready callback.
var geoIPAlertSource atomic.Value // func(time.Time) (float64, bool)
@@ -4405,6 +4426,8 @@ func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func
System: systemStateProbe(release.OptDir()),
Tunnel: tunnelState(),
GeoIP: geoIPState(),
+ // Completed windows ride this heartbeat; no extra store requests.
+ Traffic: trafficWindows(time.Now()),
// The edge's probe table, read WHOLE every tick (never merged
// with the last one), so a route this box has stopped probing
// leaves no ghost behind in the next snapshot. nil until the
diff --git a/internal/host/agent_traffic_test.go b/internal/host/agent_traffic_test.go
new file mode 100644
index 000000000..c7cf6516f
--- /dev/null
+++ b/internal/host/agent_traffic_test.go
@@ -0,0 +1,92 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "path/filepath"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// testTrafficSource replaces the published callback and restores it after the
+// test, so a source from one heartbeat cannot leak into another test's startup.
+func testTrafficSource(t *testing.T, source func(time.Time) []status.TrafficWindow) {
+ t.Helper()
+ previous, _ := trafficSource.Load().(func(time.Time) []status.TrafficWindow)
+ trafficSource.Store(source)
+ t.Cleanup(func() { trafficSource.Store(previous) })
+}
+
+// TestTrafficWindowsBeforeEdgeReadyIsNil prevents startup from inventing empty
+// observations before the edge has started its first complete traffic window.
+func TestTrafficWindowsBeforeEdgeReadyIsNil(t *testing.T) {
+ testTrafficSource(t, nil)
+ if got := trafficWindows(time.Now()); got != nil {
+ t.Fatalf("before edge ready: %+v", got)
+ }
+}
+
+// TestStatusProbesCarryTraffic follows the upstream-probe heartbeat test: read
+// the published source into Probes, run the real status tick, and read its JSON.
+func TestStatusProbesCarryTraffic(t *testing.T) {
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ store := release.NewDirStore(t.TempDir())
+ now := time.Date(2026, 11, 1, 10, 15, 0, 0, time.UTC)
+ want := []status.TrafficWindow{
+ {Start: now.Add(-15 * time.Minute).Unix(), Requests: 2, S2xx: 1, Refused: 1, Blocked: 1, Apps: []status.TrafficApp{{Account: "abc", App: "shop", Requests: 2}}},
+ {Start: now.Add(-10 * time.Minute).Unix()},
+ {Start: now.Add(-5 * time.Minute).Unix(), UnknownHost: 1, Hosts: []status.TrafficCount{{Key: "unknown.test", Hits: 1}}},
+ }
+ calls := 0
+ testTrafficSource(t, func(at time.Time) []status.TrafficWindow {
+ calls++
+ if !at.Equal(now) {
+ t.Fatalf("source time=%v want=%v", at, now)
+ }
+ return want
+ })
+ probes := status.Probes{MachineID: "test-traffic-machine", Traffic: trafficWindows(now)}
+ ctx := context.Background()
+ if err := statusTick(ctx, store, reg, probes, false, ""); err != nil {
+ t.Fatal(err)
+ }
+ key := "status/boxes/" + status.Label(probes.MachineID) + ".json"
+ raw, _, err := store.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var box status.Box
+ if err := json.Unmarshal(raw, &box); err != nil {
+ t.Fatal(err)
+ }
+ if calls != 1 || box.Metrics == nil || !reflect.DeepEqual(box.Metrics.Traffic, want) {
+ t.Fatalf("source calls=%d heartbeat=%s", calls, raw)
+ }
+
+ // A source with nothing complete must remove the prior tick's windows.
+ trafficSource.Store(func(time.Time) []status.TrafficWindow { return nil })
+ probes.Traffic = trafficWindows(now)
+ if err := statusTick(ctx, store, reg, probes, false, ""); err != nil {
+ t.Fatal(err)
+ }
+ raw, _, err = store.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ box = status.Box{}
+ if err := json.Unmarshal(raw, &box); err != nil {
+ t.Fatal(err)
+ }
+ if box.Metrics != nil && len(box.Metrics.Traffic) != 0 {
+ t.Fatalf("stale traffic: %s", raw)
+ }
+}