carlos / platform Public

edge, status: held-stream counters in the box snapshot (#432)

Human

Prompt

Task 7 of the edge-held streams plan.

From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.

Summary

counters on the held set (held per host, resumes, over cap, closes
by reason), published as held_streams in the box metrics; nil until the
edge has held a stream.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev c9bcf63def2b6837a9dcbc934b571ff786da4f7b parent edba0ba
5 files changed, +196 −4
  • internal/edge/heldstream.go +86 −2
  • internal/edge/heldstream_test.go +58 −0
  • internal/host/agent.go +15 −0
  • internal/status/snapshot.go +20 −2
  • internal/status/snapshot_test.go +17 −0
diff --git a/internal/edge/heldstream.go b/internal/edge/heldstream.go
index 05ce566ca..cd619bbf5 100644
--- a/internal/edge/heldstream.go
+++ b/internal/edge/heldstream.go
@@ -13,6 +13,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/status"
)
// Edge-held event streams (spec 2026-10-28-edge-held-streams-design.md §3.3,
@@ -81,6 +82,11 @@ type heldSet struct {
mu sync.Mutex
byHost map[string]map[*heldStream]struct{}
total int
+ // Counters (spec §3.9), under mu.
+ everHeld bool
+ resumes int64
+ overCap int64
+ closes map[string]int64
// onFinish is a test seam, nil in production: called after a stream
// has left the set.
onFinish func(host string, r heldCloseReason)
@@ -106,7 +112,9 @@ func newHeldSet(cfg HeldConfig) *heldSet {
func (s *heldSet) register(host string) *heldStream {
s.mu.Lock()
defer s.mu.Unlock()
+ s.everHeld = true
if s.total >= s.cfg.PerBox || len(s.byHost[host]) >= s.cfg.PerHost {
+ s.overCap++
return nil
}
st := &heldStream{host: host, wakeC: make(chan struct{}, 1), closeC: make(chan struct{})}
@@ -120,10 +128,83 @@ func (s *heldSet) register(host string) *heldStream {
return st
}
-// finish removes st from the set. Every held stream ends here, with its
-// reason (counters, spec §3.9, attach here).
+// statCloseName maps an internal close reason to a published counter name
+// (spec §3.9). Reasons that are not on the list (the browser leaving, a
+// first answer passed through or turned into a 502, an oversized event) are
+// ordinary ends, not counted. write_deadline also takes any other failed
+// downstream write: the task cannot tell a deadline from a reset.
+func statCloseName(r heldCloseReason) (string, bool) {
+ switch r {
+ case heldCloseRefused, heldCloseRedirect, heldCloseMaxHold, heldCloseShortLegs, heldCloseUnmanaged:
+ return r.String(), true
+ case heldCloseWriteFailed:
+ return "write_deadline", true
+ }
+ return "", false
+}
+
+// noteResume counts a leg reopened after its stream was held.
+func (s *heldSet) noteResume() {
+ s.mu.Lock()
+ s.resumes++
+ s.mu.Unlock()
+}
+
+// stats copies the counters. ok is false when the edge has never held (or
+// refused) a stream.
+func (s *heldSet) stats() (hs status.HeldStreams, ok bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if !s.everHeld {
+ return status.HeldStreams{}, false
+ }
+ hs = status.HeldStreams{Held: s.total, Resumes: s.resumes, OverCap: s.overCap}
+ if len(s.byHost) > 0 {
+ hs.Hosts = make(map[string]int, len(s.byHost))
+ for h, m := range s.byHost {
+ hs.Hosts[h] = len(m)
+ }
+ }
+ if len(s.closes) > 0 {
+ hs.Closes = make(map[string]int64, len(s.closes))
+ for k, v := range s.closes {
+ hs.Closes[k] = v
+ }
+ }
+ return hs, true
+}
+
+// HeldStreamStats is a copy of the held-stream counters (spec §3.9).
+func (e *Edge) HeldStreamStats() status.HeldStreams {
+ if e.held == nil {
+ return status.HeldStreams{}
+ }
+ hs, _ := e.held.stats()
+ return hs
+}
+
+// HeldStreamsForStatus is HeldStreamStats for the box snapshot: nil when the
+// edge has never held a stream, so the key is absent.
+func (e *Edge) HeldStreamsForStatus() *status.HeldStreams {
+ if e.held == nil {
+ return nil
+ }
+ if hs, ok := e.held.stats(); ok {
+ return &hs
+ }
+ return nil
+}
+
+// finish removes st from the set and counts its close. Every held stream
+// ends here, with its reason.
func (s *heldSet) finish(st *heldStream, r heldCloseReason) {
s.mu.Lock()
+ if name, ok := statCloseName(r); ok {
+ if s.closes == nil {
+ s.closes = make(map[string]int64)
+ }
+ s.closes[name]++
+ }
if m := s.byHost[st.host]; m != nil {
if _, ok := m[st]; ok {
delete(m, st)
@@ -487,6 +568,9 @@ func (t *heldTask) hold() error {
// openLeg runs the route's proxy for an admitted leg (§3.3a).
func (t *heldTask) openLeg(leg HeldLeg, exempt bool) {
ctx, cancel := context.WithCancel(leg.Context())
+ if exempt {
+ t.e.held.noteResume() // opened after a hold (§3.9)
+ }
run := &heldLegRun{leg: leg, cancel: cancel, quit: make(chan struct{}), start: time.Now(), exempt: exempt}
t.leg, t.lastLegStart = run, run.start
req := t.legRequest(ctx)
diff --git a/internal/edge/heldstream_test.go b/internal/edge/heldstream_test.go
index c8a757de2..cb276111f 100644
--- a/internal/edge/heldstream_test.go
+++ b/internal/edge/heldstream_test.go
@@ -688,3 +688,61 @@ func TestHeldFirstLegStripsLocation(t *testing.T) {
})
}
}
+
+func TestHeldStreamStatsCounts(t *testing.T) {
+ cfg := heldTestConfig()
+ cfg.PerHost = 1
+ h := newHeldHarness(t, cfg, func(_ int, w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, "/login", http.StatusSeeOther)
+ })
+ if _, ok := h.e.held.stats(); ok {
+ t.Fatal("stats before any stream")
+ }
+ if got := h.e.HeldStreamsForStatus(); got != nil {
+ t.Fatalf("never held: %+v", got)
+ }
+ h.start(t)
+ h.get(t, "/live?carlos_hold=1", nil) // redirect: 204, closes by redirect
+ <-h.ends
+ h.act.asleep.Store(true)
+ req, _ := http.NewRequest(http.MethodGet, h.srv.URL+"/live?carlos_hold=1", nil)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ first, err := h.srv.Client().Do(req.WithContext(ctx))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer first.Body.Close()
+ waitFor(t, time.Second, "first held", func() bool { return len(h.e.held.hosts()) == 1 })
+ body, _ := io.ReadAll(h.get(t, "/live?carlos_hold=1", nil).Body) // over cap
+ if string(body) != "retry: 30000\n\n" {
+ t.Fatalf("over cap body %q", body)
+ }
+ got := h.e.HeldStreamStats()
+ if got.Held != 1 || got.Hosts[heldTestHost] != 1 || got.OverCap != 1 || got.Closes["redirect"] != 1 || got.Resumes != 0 {
+ t.Fatalf("stats = %+v", got)
+ }
+ got.Hosts[heldTestHost] = 9 // a copy
+ if h.e.HeldStreamStats().Hosts[heldTestHost] != 1 {
+ t.Fatal("HeldStreamStats shares its map")
+ }
+ cancel()
+ waitFor(t, time.Second, "host absent", func() bool { return len(h.e.HeldStreamStats().Hosts) == 0 })
+ if got := h.e.HeldStreamStats(); got.Held != 0 || got.OverCap != 1 {
+ t.Fatalf("after close: %+v", got)
+ }
+}
+
+func TestHeldStreamStatsResume(t *testing.T) {
+ h := newHeldHarness(t, heldTestConfig(), func(_ int, w http.ResponseWriter, r *http.Request) {
+ sseHead(w)
+ <-r.Context().Done()
+ })
+ h.act.asleep.Store(true)
+ h.start(t)
+ h.get(t, "/live?carlos_hold=1", nil)
+ waitFor(t, time.Second, "held", func() bool { return len(h.e.held.hosts()) == 1 })
+ h.act.asleep.Store(false)
+ h.e.HeldWake(heldTestHost)
+ waitFor(t, time.Second, "resumed", func() bool { return h.e.HeldStreamStats().Resumes == 1 })
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 9f7d8daf8..9bc90380f 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1085,6 +1085,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
setUpstreamSource(e.UpstreamStates)
// The GeoIP block for the heartbeat (geoip spec §5.5), the same way.
geoIPSource.Store(e.GeoIPState)
+ heldStreamsSource.Store(e.HeldStreamsForStatus)
geoIPAlertSource.Store(e.GeoIPAlertCode)
// The layout pass reloads routing through this as soon as a move
// commits, instead of waiting for the 2s registry poll.
@@ -4311,6 +4312,19 @@ 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
+// heldStreamsSource is the edge's held-stream counters for the heartbeat
+// (edge-held streams spec §3.9), published from the same ready callback.
+var heldStreamsSource atomic.Value // func() *status.HeldStreams
+
+// heldStreamsState reads it, or nil before the edge is ready.
+func heldStreamsState() *status.HeldStreams {
+ fn, _ := heldStreamsSource.Load().(func() *status.HeldStreams)
+ if fn == nil {
+ return nil
+ }
+ return fn()
+}
+
// 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)
@@ -4561,6 +4575,7 @@ func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func
System: systemStateProbe(release.OptDir()),
Tunnel: tunnelState(),
GeoIP: geoIPState(),
+ HeldStreams: heldStreamsState(),
// 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/status/snapshot.go b/internal/status/snapshot.go
index 7e3e54eb4..414dfb7af 100644
--- a/internal/status/snapshot.go
+++ b/internal/status/snapshot.go
@@ -125,6 +125,9 @@ type Probes struct {
// GeoIP is the edge's GeoIP mirror state (geoip spec §5.5); nil when
// the edge has not published one (no edge yet, or an older binary).
GeoIP *GeoIPState
+ // HeldStreams is the edge's held-stream counters (edge-held streams
+ // spec §3.9); nil until the edge has held a stream.
+ HeldStreams *HeldStreams
// Platform is runtime.GOOS-runtime.GOARCH, so the console knows which
// artifacts a platform promote must mirror. SystemChannel is the box's
// CARLOS_SYSTEM_CHANNEL, so the console knows which boxes a promote
@@ -585,6 +588,9 @@ type BoxMetrics struct {
// spec §5.5); its absence is how the rollout verdict tells an older
// binary, which does not strip forged geo headers.
GeoIP *GeoIPState `json:"geoip,omitempty"`
+ // HeldStreams is present once the edge has held a stream (edge-held
+ // streams spec §3.9).
+ HeldStreams *HeldStreams `json:"held_streams,omitempty"`
// UpdateSettings is the instance-update-settings protocol this binary
// implements: it applies pin, manual and major, and its retention
// protects the builds they name (settings spec §4.4). Absent (0) is a
@@ -1157,7 +1163,7 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box {
p.InstanceID != "" || p.Platform != "" || p.SystemChannel != "" || p.System != nil ||
len(routeVersions) > 0 || len(routeServing) > 0 || len(aliasReadings) > 0 || p.AliasesRead || len(p.Upstreams) > 0 ||
len(routeDBBytes) > 0 || p.Layout != nil || len(p.ConfigRefusals) > 0 || len(p.ReleaseRefusals) > 0 || len(p.ProofWaits) > 0 || p.Rollout != nil || p.ConfigGuard != "" ||
- p.Alerts != nil || p.GeoIP != nil || len(p.BuildStates) > 0 || p.BuildStatesErr != "" ||
+ p.Alerts != nil || p.GeoIP != nil || p.HeldStreams != nil || len(p.BuildStates) > 0 || p.BuildStatesErr != "" ||
p.UpdateSettings != 0 || len(p.Updates) > 0 || len(p.Egress) > 0 || p.SizeCommittedMiB != nil {
box.Metrics = &BoxMetrics{
ConsoleProcesses: p.ConsoleProcesses,
@@ -1176,7 +1182,7 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box {
MemTotalBytes: p.MemTotalBytes, MemAvailBytes: p.MemAvailBytes,
Load1: p.Load1, DiskFreeBytes: p.DiskFreeBytes, DiskFullETAHours: p.DiskFullETAHours,
- Release: p.Release, Tunnel: p.Tunnel, GeoIP: p.GeoIP,
+ Release: p.Release, Tunnel: p.Tunnel, GeoIP: p.GeoIP, HeldStreams: p.HeldStreams,
Platform: p.Platform, SystemChannel: p.SystemChannel, System: p.System,
InstanceID: p.InstanceID,
Alerts: p.Alerts,
@@ -1274,3 +1280,15 @@ type GeoIPState struct {
Type string `json:"type,omitempty"`
Error string `json:"error,omitempty"`
}
+
+// HeldStreams is the edge's held-stream counters (edge-held streams spec
+// §3.9). Hosts counts streams held now, per host; a host with none is absent.
+// Closes is by reason: refused, redirect, max_hold, short_legs, unmanaged,
+// write_deadline.
+type HeldStreams struct {
+ Held int `json:"held"`
+ Hosts map[string]int `json:"hosts,omitempty"`
+ Resumes int64 `json:"resumes"`
+ OverCap int64 `json:"over_cap"`
+ Closes map[string]int64 `json:"closes,omitempty"`
+}
diff --git a/internal/status/snapshot_test.go b/internal/status/snapshot_test.go
index 366850db7..a8bf774be 100644
--- a/internal/status/snapshot_test.go
+++ b/internal/status/snapshot_test.go
@@ -3,6 +3,7 @@ package status
import (
"context"
"encoding/json"
+ "reflect"
"strings"
"testing"
"time"
@@ -395,3 +396,19 @@ func TestCollectBoxCarriesAliasesRead(t *testing.T) {
t.Fatalf("an all-unknown Probes attached metrics: %+v", none.Metrics)
}
}
+
+func TestSnapshotCarriesHeldStreams(t *testing.T) {
+ hs := &HeldStreams{Held: 1, Hosts: map[string]int{"a.example.com": 1}, Resumes: 2, OverCap: 3, Closes: map[string]int64{"redirect": 1}}
+ box := CollectBox(nil, Probes{HeldStreams: hs}, time.Now())
+ if box.Metrics == nil || box.Metrics.HeldStreams == nil || !reflect.DeepEqual(box.Metrics.HeldStreams, hs) {
+ t.Fatalf("metrics = %+v", box.Metrics)
+ }
+ raw, _ := json.Marshal(box)
+ if !strings.Contains(string(raw), `"held_streams":{"held":1,"hosts":{"a.example.com":1},"resumes":2,"over_cap":3,"closes":{"redirect":1}}`) {
+ t.Fatalf("json = %s", raw)
+ }
+ raw, _ = json.Marshal(CollectBox(nil, Probes{GeoIP: &GeoIPState{Mode: "none"}}, time.Now()))
+ if strings.Contains(string(raw), "held_streams") {
+ t.Fatalf("nil HeldStreams published: %s", raw)
+ }
+}