carlos / platform Public

edge: classify carlos_hold requests and hold them after the gate (#432)

Human

Prompt

Task 6 of #432: wire the held-stream task into Edge.ServeHTTP,
keep marked requests out of the shared cache and asset catch, close held
streams on reload, wire the activator's wake hook.

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

ServeHTTP records whether the request arrived marked
(heldMarkKey) before any branch. After the lookup and the HA forward, a
marked request to a hibernating route is a held-stream request (flagged)
or a 400; to a tunnel or fleet route it goes on untouched; elsewhere the
marker is stripped. The hold branch runs after the password gate with the
plan throttle and the rate limit (slot freed at headers via slotWriter).
The shared cache and the three asset catches skip marked requests on
every edge. Reload closes held streams for hosts no longer hibernating
here. carlos agent wires act.SetHeldWakeHook(e.HeldWake). Tests: dispatch
suite plus the tunnel witness TestTunnelForwardsHoldMarkerAndSkipsCache.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 85f8d00a996eb84f7fdc55c683d96b2e4cabf0c3 parent 63cc9cf
5 files changed, +566 −1
  • internal/edge/assetcatch.go +16 −0
  • internal/edge/edge.go +135 −1
  • internal/edge/heldstream_dispatch_test.go +303 −0
  • internal/edge/tunnel_e2e_test.go +105 −0
  • internal/host/agent.go +7 −0
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go
index 871da1093..757f874c1 100644
--- a/internal/edge/assetcatch.go
+++ b/internal/edge/assetcatch.go
@@ -290,6 +290,11 @@ func (e *Edge) localAssetCatch(r *http.Request, host string, up upstream) (HostA
// fill and uncached fallback then passes the per-instance rate limit, which
// still never limits a hit (D7).
func (e *Edge) serveAssetLocal(w http.ResponseWriter, r *http.Request, host string, up upstream) bool {
+ // A request that arrived carrying carlos_hold=1 is never an asset
+ // request (edge-held streams spec §3.8): passed through untouched.
+ if markedRequest(r) {
+ return false
+ }
a, ok := e.localAssetCatch(r, host, up)
if !ok {
return false
@@ -352,6 +357,11 @@ func (e *Edge) serveAssetFillForHop(w http.ResponseWriter, r *http.Request, host
return false
}
r.Header.Del(assetFillHeader)
+ // A marked request (edge-held streams spec §3.8) is never filled from
+ // here: it goes on to this edge's classification.
+ if markedRequest(r) {
+ return false
+ }
if !hopVerified(r.Context()) || r.Method != http.MethodGet || assetBuffered(r) || isUpgradeRequest(r) {
return false
}
@@ -1099,6 +1109,12 @@ func (e *Edge) AssetOwners() []registry.Route {
// them in ServeHTTP. A block is answered with the block page; a match it
// answers itself is recorded as a Match under the synthetic route.
func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string) bool {
+ // A marked request (edge-held streams spec §3.8) is not an asset
+ // request: it goes on to the backhaul and the home edge's
+ // classification, marker and all.
+ if markedRequest(r) {
+ return false
+ }
a, eip, box, key, ok := e.farAssetCatch(r, host)
if !ok {
return false
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index da3279d98..a6b494e5a 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -1364,6 +1364,17 @@ func (e *Edge) Reload() error {
if e.act != nil {
e.act.RetireExcept(managed)
}
+ // Edge-held streams (spec 2026-10-28 §3.4): a host this edge no longer
+ // holds streams for (removed, moved, made always-on, repointed to a
+ // tunnel or fleet box) has its held streams closed, after the swap, so
+ // each browser reconnects and is routed by the new map.
+ if e.held != nil {
+ for _, h := range e.held.hosts() {
+ if u, ok := m[h]; !ok || !u.hibernating || !u.route.Hibernate {
+ e.held.closeHost(h)
+ }
+ }
+ }
e.runReloadHooks()
return nil
}
@@ -1840,6 +1851,14 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
+ // Edge-held streams (spec 2026-10-28 §3.1, §3.8): whether the request as
+ // it arrived carried carlos_hold=1, recorded once, here, before any
+ // branch below can forward it or strip the marker. The shared cache and
+ // the asset catch read this mark (markedRequest), never the query. An
+ // unmarked request gets no context value.
+ if _, marked := stripHoldMarker(r.URL.RawQuery); marked {
+ r = r.WithContext(context.WithValue(r.Context(), heldMarkKey{}, true))
+ }
// GeoIP step 1 (geoip spec §8.1): capture and strip every geo header
// before ANY branch. Nothing trusts the captured values until step 3,
// after acceptHop and the tunnel mark have said whether the transport is
@@ -2030,6 +2049,38 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
+ // Edge-held streams: classification (spec 2026-10-28 §3.1, §3.8 step
+ // 2), on the upstream this box will serve, before the login POST
+ // handling, the gate or anything else can answer the request. After the
+ // HA forward above, which only proxies to the lease holder: that box
+ // classifies, as a tunnel's box does. A marked request to a hibernating
+ // route is either a held-stream request, flagged for the hold branch
+ // after the gate, or answered 400 here; to a route served over a tunnel
+ // or fleet channel it goes on untouched, for the receiving edge to
+ // classify; to any other route the marker is stripped and the request
+ // served as an ordinary one. up only changes after this through the
+ // login POST's re-resolution, and a login POST is always answered by
+ // the gate or passed down a tunnel, never handed to the activator.
+ //
+ // up.hibernating is false on every viaTunnel entry and whenever this
+ // edge has no activator (Reload), so the hold branch is unreachable on
+ // `carlos edge`.
+ held := false
+ if markedRequest(r) {
+ switch {
+ case up.hibernating && up.route.Hibernate:
+ if !isHeldStreamRequest(r) {
+ w.Header().Set("Cache-Control", "no-store")
+ http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+ return
+ }
+ held = true
+ case up.viaTunnel:
+ default:
+ r = withoutHoldMarker(r)
+ }
+ }
+
// A login POST re-resolves its upstream by the path in `next`, not by
// its own (spec §4.2). On a hostname that routes by path prefix,
// lookupUpstreamPath keys on the first segment; "/.carlos/gate" has no
@@ -2312,6 +2363,31 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
+ // The hold branch (spec 2026-10-28 §3.8 step 4): a flagged held-stream
+ // request goes no further than this. After the gate, so a stranger is
+ // held only on an ungated route; before the upgrade branch, the local
+ // asset catch, compression, the shared cache and the activator, none of
+ // which it may reach. It passes the plan throttle and the rate limit
+ // once each, as the ordinary path does; a refusal is answered as it is
+ // there, never proxied. The rate slot comes back when the held
+ // response's headers are written (slotWriter), not when the stream
+ // ends: an open held stream is not in-flight work for the instance.
+ if held {
+ if !e.planThrottleAdmit(w, r, up) {
+ return
+ }
+ release, ok := e.rateAdmit(w, r, up)
+ if !ok {
+ return
+ }
+ if release != nil {
+ defer release()
+ w = &slotWriter{ResponseWriter: w, release: release}
+ }
+ e.serveHeld(w, r, up.route, up.proxy)
+ return
+ }
+
// A Connection: Upgrade request (a WebSocket handshake, typically GET)
// must reach the activator/proxy with a hijackable ResponseWriter,
// completely untouched by caching: the stdlib reverse proxy's upgrade
@@ -2432,9 +2508,15 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// hub cannot see the fleet edge's gate, so a gated page stored here would
// be served without the cookie, and an app's Carlos-Purge stops at its
// own box.
+ //
+ // A request that arrived carrying carlos_hold=1 is never cached, looked
+ // up or stored, on any route and whatever happened to its query since
+ // (edge-held streams spec §3.8, r2 P2-7): a hub or hop that stored a
+ // finished stream would replay it instead of connecting the browser to
+ // the edge that holds it.
cacheable := e.cache != nil && (r.Method == http.MethodGet || r.Method == http.MethodHead) &&
up.route.Kind != "status" && up.route.Kind != "static" && up.route.ImportGate == "" &&
- !up.route.IsForward()
+ !up.route.IsForward() && !markedRequest(r)
var key CacheKey
if cacheable {
key = CacheKey{Host: host, Method: r.Method, Path: r.URL.Path, RawQuery: r.URL.RawQuery}
@@ -2508,6 +2590,58 @@ func isUpgradeRequest(r *http.Request) bool {
return false
}
+// heldMarkKey is the request-context key ServeHTTP sets, once, on a request
+// that arrived carrying carlos_hold=1 (edge-held streams spec §3.1).
+type heldMarkKey struct{}
+
+// markedRequest reports whether r arrived carrying carlos_hold=1. It reads
+// the mark ServeHTTP recorded before anything could strip the marker, so it
+// stays true after the query has been cleaned.
+func markedRequest(r *http.Request) bool {
+ marked, _ := r.Context().Value(heldMarkKey{}).(bool)
+ return marked
+}
+
+// isHeldStreamRequest reports whether r is a held-stream request (spec
+// §3.1): a GET whose Accept names text/event-stream, which every
+// EventSource sends, and not an upgrade.
+func isHeldStreamRequest(r *http.Request) bool {
+ if r.Method != http.MethodGet || isUpgradeRequest(r) {
+ return false
+ }
+ for _, mt := range strings.Split(joinHeader(r.Header, "Accept"), ",") {
+ mt, _, _ = strings.Cut(mt, ";")
+ if strings.EqualFold(strings.TrimSpace(mt), "text/event-stream") {
+ return true
+ }
+ }
+ return false
+}
+
+// withoutHoldMarker returns a shallow copy of r whose query has every
+// carlos_hold=1 pair removed and the rest kept byte for byte. r and its URL
+// are left as they were.
+func withoutHoldMarker(r *http.Request) *http.Request {
+ q, marked := stripHoldMarker(r.URL.RawQuery)
+ if !marked {
+ return r
+ }
+ r2 := r.WithContext(r.Context())
+ u := *r.URL
+ u.RawQuery = q
+ r2.URL = &u
+ return r2
+}
+
+// HeldWake tells this edge's held streams for host that it may have become
+// admissible (the activator's held wake hook, SetHeldWakeHook). It never
+// blocks.
+func (e *Edge) HeldWake(host string) {
+ if e.held != nil {
+ e.held.wake(host)
+ }
+}
+
// cacheMaxBody reports the body-size ceiling recordingResponseWriter should
// enforce, or 0 when caching is disabled (recordingResponseWriter is never
// constructed with cacheable=true in that case, so the value is unused).
diff --git a/internal/edge/heldstream_dispatch_test.go b/internal/edge/heldstream_dispatch_test.go
new file mode 100644
index 000000000..3d616b114
--- /dev/null
+++ b/internal/edge/heldstream_dispatch_test.go
@@ -0,0 +1,303 @@
+package edge
+
+// The held-stream dispatch in Edge.ServeHTTP (spec 2026-10-28 edge-held
+// streams §3.1, §3.4, §3.8): classification after the lookup, the hold
+// branch after the password gate, the shared cache and asset catch skipping
+// marked requests, and Reload closing streams for hosts it no longer holds.
+// Every request goes through Edge.ServeHTTP on a real listener.
+
+import (
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/gate"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// dispatchUpstream answers every request with serve, counting hits and
+// recording the raw query each one carried.
+type dispatchUpstream struct {
+ srv *httptest.Server
+ hits atomic.Int64
+ mu sync.Mutex
+ queries []string
+}
+
+func newDispatchUpstream(t *testing.T, serve func(w http.ResponseWriter, r *http.Request)) *dispatchUpstream {
+ t.Helper()
+ u := &dispatchUpstream{}
+ u.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ u.hits.Add(1)
+ u.mu.Lock()
+ u.queries = append(u.queries, r.URL.RawQuery)
+ u.mu.Unlock()
+ serve(w, r)
+ }))
+ t.Cleanup(u.srv.Close)
+ return u
+}
+
+func (u *dispatchUpstream) addr() string { return u.srv.Listener.Addr().String() }
+
+func (u *dispatchUpstream) lastQuery() string {
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ if len(u.queries) == 0 {
+ return ""
+ }
+ return u.queries[len(u.queries)-1]
+}
+
+func okUpstream(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, "ok") }
+
+// heldRoute is shop.example.com as a hibernating instance on addr.
+func heldRoute(addr string) registry.Route {
+ return registry.Route{Host: heldTestHost, Kind: "instance", Addr: addr, Status: "ready", App: "web", Hibernate: true}
+}
+
+// newDispatchEdge serves rt from an edge with act, the short held config and
+// a front server that turns rlPeerHeader into the peer address.
+func newDispatchEdge(t *testing.T, act Activator, cfg HeldConfig, rt registry.Route) (*Edge, *registry.Registry, *httptest.Server) {
+ t.Helper()
+ reg := openReg(t)
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ e, err := New(reg, act)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ e.SetHeldConfig(cfg)
+ front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if p := r.Header.Get(rlPeerHeader); p != "" {
+ r.Header.Del(rlPeerHeader)
+ r.RemoteAddr = net.JoinHostPort(p, "40000")
+ }
+ e.ServeHTTP(w, r)
+ }))
+ t.Cleanup(front.Close)
+ return e, reg, front
+}
+
+// dispatchDo sends one request to host through front and returns the
+// response with its body unread (closed at cleanup).
+func dispatchDo(t *testing.T, front *httptest.Server, method, host, target string, hdr map[string]string, body io.Reader) *http.Response {
+ t.Helper()
+ req, err := http.NewRequest(method, front.URL+target, body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = host
+ req.Header.Set("Accept-Encoding", "identity")
+ for k, v := range hdr {
+ req.Header.Set(k, v)
+ }
+ c := &http.Client{
+ Timeout: 10 * time.Second,
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+ }
+ resp, err := c.Do(req)
+ if err != nil {
+ t.Fatalf("%s %s: %v", method, target, err)
+ }
+ t.Cleanup(func() { resp.Body.Close() })
+ return resp
+}
+
+var sseAccept = map[string]string{"Accept": "text/event-stream"}
+
+// A marked request that is not a held-stream request is answered 400 at the
+// classification point and never reaches the activator (§3.1).
+func TestMarkedRequestNeverReachesActivator(t *testing.T) {
+ up := newDispatchUpstream(t, okUpstream)
+ act := &scriptActivator{}
+ act.asleep.Store(true)
+ _, _, front := newDispatchEdge(t, act, heldTestConfig(), heldRoute(up.addr()))
+ cases := []struct {
+ name, method string
+ hdr map[string]string
+ }{
+ {"POST", http.MethodPost, sseAccept},
+ {"PUT", http.MethodPut, sseAccept},
+ {"GET without SSE Accept", http.MethodGet, map[string]string{"Accept": "text/html"}},
+ {"upgrade", http.MethodGet, map[string]string{"Accept": "text/event-stream", "Connection": "Upgrade", "Upgrade": "websocket"}},
+ }
+ for _, c := range cases {
+ resp := dispatchDo(t, front, c.method, heldTestHost, "/live?carlos_hold=1", c.hdr, nil)
+ if resp.StatusCode != http.StatusBadRequest {
+ b, _ := io.ReadAll(resp.Body)
+ t.Errorf("%s: status %d %q, want 400", c.name, resp.StatusCode, b)
+ }
+ }
+ if n := act.served.Load(); n != 0 {
+ t.Fatalf("activator ServeHTTP called %d times, want 0", n)
+ }
+ if n := up.hits.Load(); n != 0 {
+ t.Fatalf("upstream hits = %d, want 0", n)
+ }
+}
+
+// A marked login POST is answered 400 before the login handling can answer
+// it with a redirect (§3.8, r2 P2-1).
+func TestMarkedLoginPostIs400(t *testing.T) {
+ act := &scriptActivator{}
+ act.asleep.Store(true)
+ e, srv, _, _ := gatedEdge(t, act, true)
+ e.SetHeldConfig(heldTestConfig())
+ form := url.Values{"password": {"correct horse"}, "next": {"/docs"}}
+ resp := dispatchDo(t, srv, http.MethodPost, "gated.example.com", gate.LoginPath+"?carlos_hold=1",
+ map[string]string{"Content-Type": "application/x-www-form-urlencoded"}, strings.NewReader(form.Encode()))
+ if resp.StatusCode != http.StatusBadRequest {
+ t.Fatalf("status %d (Location %q), want 400", resp.StatusCode, resp.Header.Get("Location"))
+ }
+ if gateCookie(resp) != "" {
+ t.Fatal("a marked login POST was given a gate cookie")
+ }
+ if n := act.served.Load(); n != 0 {
+ t.Fatalf("activator ServeHTTP called %d times, want 0", n)
+ }
+}
+
+// A held-stream request to a sleeping instance is answered by the edge's
+// hold branch: a 200 event stream with heartbeats, no activator call.
+func TestHeldStreamRequestDispatchesToHold(t *testing.T) {
+ up := newDispatchUpstream(t, okUpstream)
+ act := &scriptActivator{}
+ act.asleep.Store(true)
+ _, _, front := newDispatchEdge(t, act, heldTestConfig(), heldRoute(up.addr()))
+ resp := dispatchDo(t, front, http.MethodGet, heldTestHost, "/live?carlos_hold=1", sseAccept, nil)
+ if resp.StatusCode != http.StatusOK || resp.Header.Get("Content-Type") != "text/event-stream" {
+ t.Fatalf("status %d Content-Type %q, want 200 text/event-stream", resp.StatusCode, resp.Header.Get("Content-Type"))
+ }
+ got, _ := readFor(resp.Body, 300*time.Millisecond)
+ if !strings.Contains(got, ": ping\n") {
+ t.Fatalf("body %q, want heartbeats", got)
+ }
+ if n := act.served.Load(); n != 0 {
+ t.Fatalf("activator ServeHTTP called %d times, want 0", n)
+ }
+ if n := up.hits.Load(); n != 0 {
+ t.Fatalf("upstream hits = %d, want 0 while asleep", n)
+ }
+}
+
+// The hold branch gives its rate-limit slot back when the held response's
+// headers are written, not when the stream ends (plan review r1 P1-2).
+func TestHeldStreamFreesRateSlotAtHeaders(t *testing.T) {
+ t.Setenv("CARLOS_RATE_LIMIT", "enforce")
+ up := newDispatchUpstream(t, okUpstream)
+ act := &scriptActivator{}
+ act.asleep.Store(true)
+ rt := heldRoute(up.addr())
+ rt.RateLimit = `{"busy_at":1,"client_share":1}`
+ cfg := heldTestConfig()
+ cfg.MaxHold = 30 * time.Second
+ e, _, front := newDispatchEdge(t, act, cfg, rt)
+ const peer = "203.0.113.7"
+
+ held := dispatchDo(t, front, http.MethodGet, heldTestHost, "/live?carlos_hold=1",
+ map[string]string{"Accept": "text/event-stream", rlPeerHeader: peer}, nil)
+ if held.StatusCode != http.StatusOK || held.Header.Get("Content-Type") != "text/event-stream" {
+ t.Fatalf("held stream: status %d Content-Type %q", held.StatusCode, held.Header.Get("Content-Type"))
+ }
+ if n := e.rateLimiter.InFlight(heldTestHost); n != 0 {
+ t.Fatalf("InFlight = %d with a held stream open, want 0", n)
+ }
+ resp := dispatchDo(t, front, http.MethodGet, heldTestHost, "/page", map[string]string{rlPeerHeader: peer}, nil)
+ if resp.StatusCode != http.StatusOK {
+ b, _ := io.ReadAll(resp.Body)
+ t.Fatalf("ordinary request beside a held stream: status %d %q, want 200", resp.StatusCode, b)
+ }
+}
+
+// On a route that is not hibernating the marker is stripped and the request
+// proxied as an ordinary one (§3.1).
+func TestMarkerStrippedOnAlwaysOnRoute(t *testing.T) {
+ up := newDispatchUpstream(t, okUpstream)
+ rt := heldRoute(up.addr())
+ rt.Hibernate = false
+ act := &scriptActivator{}
+ _, _, front := newDispatchEdge(t, act, heldTestConfig(), rt)
+ resp := dispatchDo(t, front, http.MethodGet, heldTestHost, "/live?a=1&carlos_hold=1&b=%20x", sseAccept, nil)
+ b, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK || string(b) != "ok" {
+ t.Fatalf("status %d %q, want 200 ok", resp.StatusCode, b)
+ }
+ if q := up.lastQuery(); q != "a=1&b=%20x" {
+ t.Fatalf("upstream query %q, want %q", q, "a=1&b=%20x")
+ }
+ if n := act.served.Load(); n != 0 {
+ t.Fatalf("activator ServeHTTP called %d times on an always-on route", n)
+ }
+}
+
+// The shared cache neither answers nor stores a marked request, even once
+// the marker is stripped from its query (§3.8, r2 P2-7).
+func TestMarkedRequestSkipsSharedCacheAfterStrip(t *testing.T) {
+ up := newDispatchUpstream(t, func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "public, max-age=60")
+ io.WriteString(w, "data: x\n\n")
+ })
+ rt := heldRoute(up.addr())
+ rt.Hibernate = false
+ e, _, front := newDispatchEdge(t, &scriptActivator{}, heldTestConfig(), rt)
+ e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))
+
+ // Control: the same answer to an unmarked request is stored.
+ for range 2 {
+ resp := dispatchDo(t, front, http.MethodGet, heldTestHost, "/live", sseAccept, nil)
+ io.ReadAll(resp.Body)
+ }
+ if n := up.hits.Load(); n != 1 {
+ t.Fatalf("control: upstream hits = %d, want 1 (the answer is cacheable)", n)
+ }
+ for range 2 {
+ resp := dispatchDo(t, front, http.MethodGet, heldTestHost, "/live?carlos_hold=1", sseAccept, nil)
+ b, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK || string(b) != "data: x\n\n" {
+ t.Fatalf("marked request: status %d %q", resp.StatusCode, b)
+ }
+ }
+ if n := up.hits.Load(); n != 3 {
+ t.Fatalf("upstream hits = %d, want 3: both marked requests must reach the upstream", n)
+ }
+}
+
+// A reload that leaves the host not hibernating here closes its held
+// streams (§3.4).
+func TestReloadClosesHeldStreamsForUnmanagedHost(t *testing.T) {
+ up := newDispatchUpstream(t, okUpstream)
+ act := &scriptActivator{}
+ act.asleep.Store(true)
+ cfg := heldTestConfig()
+ cfg.MaxHold = 30 * time.Second
+ rt := heldRoute(up.addr())
+ e, reg, front := newDispatchEdge(t, act, cfg, rt)
+ resp := dispatchDo(t, front, http.MethodGet, heldTestHost, "/live?carlos_hold=1", sseAccept, nil)
+ if resp.StatusCode != http.StatusOK || resp.Header.Get("Content-Type") != "text/event-stream" {
+ t.Fatalf("held stream: status %d Content-Type %q", resp.StatusCode, resp.Header.Get("Content-Type"))
+ }
+ if got, err := readFor(resp.Body, 200*time.Millisecond); err != nil || !strings.Contains(got, ": ping") {
+ t.Fatalf("before reload: %q, %v; want an open stream with heartbeats", got, err)
+ }
+ rt.Hibernate = false
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readFor(resp.Body, 3*time.Second); err == nil {
+ t.Fatal("held stream still open 3s after a reload made the host always-on")
+ }
+}
diff --git a/internal/edge/tunnel_e2e_test.go b/internal/edge/tunnel_e2e_test.go
index 5aa4ef5a4..d1df3ece0 100644
--- a/internal/edge/tunnel_e2e_test.go
+++ b/internal/edge/tunnel_e2e_test.go
@@ -216,3 +216,108 @@ func waitForTunnelState(t *testing.T, hub *TunnelHub, name, want string, within
}
t.Fatalf("tunnel %s never reached state %q within %s", name, want, within)
}
+
+// TestTunnelForwardsHoldMarkerAndSkipsCache: a hub forwarding a marked
+// event-stream request down a tunnel does not classify or strip it (spec
+// 2026-10-28 edge-held streams §3.1, §3.4); the receiving box's edge does,
+// and holds the stream there without calling its activator. The hub's
+// shared cache neither answers the marked request from a stored entry nor
+// stores anything for it (§3.8, r2 P2-7). The box side is a real Edge
+// behind the production tunnel client loop.
+func TestTunnelForwardsHoldMarkerAndSkipsCache(t *testing.T) {
+ const host = "shop.example.com"
+ reg := tunnelRoute(t, registry.Route{
+ Host: host, Kind: "instance", Status: "ready", Tunnel: "pi-box", Hibernate: true,
+ })
+ hubEdge, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cache := NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes)
+ hubEdge.EnableCache(cache)
+ srv := httptest.NewServer(hubEdge)
+ defer srv.Close()
+ u, err := url.Parse(srv.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ hub := NewTunnelHub(u.Hostname(), map[string]string{"pi-box": "sekrit"})
+ hubEdge.EnableTunnels(hub)
+ if err := hubEdge.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ // A stored answer for the marked URL: the hub must not replay it.
+ cache.Put(CacheKey{Host: host, Method: http.MethodGet, Path: "/live", RawQuery: "carlos_hold=1"}, "",
+ &CachedResponse{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"text/event-stream"}},
+ Body: []byte("data: stale\n\n"), StoredAt: time.Now(), TTL: time.Minute})
+
+ // The box: its own edge, with a sleeping instance for host.
+ boxReg := openReg(t)
+ if err := boxReg.Upsert(registry.Route{Host: host, Kind: "instance", Addr: "127.0.0.1:1", Status: "ready", App: "web", Hibernate: true}); err != nil {
+ t.Fatal(err)
+ }
+ act := &scriptActivator{}
+ act.asleep.Store(true)
+ boxEdge, err := New(boxReg, act)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(boxEdge.probers.Stop)
+ cfg := heldTestConfig()
+ cfg.MaxHold = 30 * time.Second
+ boxEdge.SetHeldConfig(cfg)
+ var mu sync.Mutex
+ var boxQueries []string
+ boxHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ boxQueries = append(boxQueries, r.URL.RawQuery)
+ mu.Unlock()
+ boxEdge.ServeHTTP(w, r)
+ })
+ stop := startFakeRemoteHost(t, srv.URL, "pi-box", "sekrit", boxHandler)
+ defer stop()
+ waitForTunnelState(t, hub, "pi-box", "connected", e2eReconnectBound)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/live?carlos_hold=1", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = host
+ req.Header.Set("Accept", "text/event-stream")
+ req.Header.Set("Accept-Encoding", "identity")
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("held request through tunnel: %v", err)
+ }
+ got, _ := readFor(resp.Body, 500*time.Millisecond)
+ cancel()
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusOK || strings.Contains(got, "stale") || !strings.Contains(got, ": ping\n") {
+ t.Fatalf("status %d body %q: want the box's held stream (heartbeats), not the hub's stored entry", resp.StatusCode, got)
+ }
+ mu.Lock()
+ seen := append([]string(nil), boxQueries...)
+ mu.Unlock()
+ if len(seen) != 1 || seen[0] != "carlos_hold=1" {
+ t.Fatalf("box saw queries %q, want exactly [carlos_hold=1]: the hub must forward the marker untouched", seen)
+ }
+ if n := act.served.Load(); n != 0 {
+ t.Fatalf("box activator ServeHTTP called %d times, want 0: the box holds the stream", n)
+ }
+ // The stream has ended at the hub; nothing new may have been stored.
+ deadline := time.Now().Add(time.Second)
+ for {
+ cache.mu.Lock()
+ n := len(cache.entries)
+ cache.mu.Unlock()
+ if n != 1 {
+ t.Fatalf("hub cache holds %d entries, want only the seeded one", n)
+ }
+ if time.Now().After(deadline) {
+ break
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 82683b9c9..9f7d8daf8 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1069,6 +1069,13 @@ func runAgent(args []string, buildClaims ClaimFactory) {
edgeOpts = append(edgeOpts, edge.WithGeoTunnelClient())
}
edge.RunWithActivatorReady(args, act, cache, func(e *edge.Edge) {
+ // Edge-held streams (spec 2026-10-28 §3.2, §3.7): the activator
+ // signals the edge's held streams when a host may have become
+ // admissible. act is nil when hibernation is not armed; no route
+ // is held then.
+ if act != nil {
+ act.SetHeldWakeHook(e.HeldWake)
+ }
go tunnelLoop(e)
// The edge owns the health probers, so its state table is only
// reachable once it exists — statusLoop (already running above) reads