carlos / platform Public

tunnel: a fleet box refuses new streams once it begins shutdown (#511 R24)

Drill 3's 9 hard-stop 503s were box-2's own answers: systemd stopped the
app, the edge began draining, and the box's tunnel kept taking the hub's
streams, which met the activator's stopped wake. R24: a draining box
refuses new tunnel streams before any activator or app sees them.

tunnelclient.Config.Drain: when it closes, the live connection's h2
server sends a graceful GOAWAY (through a per-connection base server's
Shutdown, after the connection is registered), and Loop never dials
again; it returns once that connection ends. Proof the refusal comes
first: a stream whose handler starts after the drain is reset by
drainGate before the wrapped handler; once goAway has run, x/net's
processFrame (server.go:1464, v0.62.0) discards every frame of a later
stream before processHeaders; and once the hub reads the GOAWAY, its
ClientConn refuses new streams before writing them, which the R22 path
retries on another copy whatever the method. Accepted streams run to
their end, as before.

The agent closes the drain in the edge's shutdown-started callback,
which runs before tenant admission closes. Only a fleet channel drains
(<fleet>/<label>): a static tunnel and a link's home keep serving until
the process exits. HA members and fixed boxes run no fleet tunnel, and
nothing here touches admission, leases, listeners or the ingress drain.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ab6a7810100a9835d82ae602b5b31988873546c8 parent be827bf
6 files changed, +283 −9
  • internal/host/agent.go +7 −1
  • internal/host/tunnel_client.go +20 −1
  • internal/host/tunnel_client_test.go +17 −2
  • internal/tunnelclient/drain_test.go +137 −0
  • internal/tunnelclient/tunnelclient.go +31 −4
  • internal/tunnelclient/upgrade.go +71 −1

Intent

Human

<task-notification> <task-id>a41c5fc02dcfea0c5</task-id> <tool-use-id>toolu_01TgsLwYm1YEbiqKh48PQL4g</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/a41c5fc02dcfea0c5.output</output-file> <status>completed</status> <summary>Agent "Fix drill-3 hub routing gaps" 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>- **Status: DONE_WITH_CONCERNS.** The R22 fix won't stop drill 3's 9 hard-stop failures. The hub didn't pick a dead copy: box-2's own edge sent those 503s through a tunnel that stayed open while it shut down (each one matches an "activator stopped during startup" line in its journal). Stopping them needs a box-side decision, so I built nothing there. Options: (1) the box refuses new tunnel requests as soon as it starts shutting down, so the hub retries them on another copy (recommended); (2) the box marks refusals no app saw, for the hub to retry; (3) document it. - **Commits** (6, base 6d561e2f, not pushed): - 83ea17bb R22: a request that never reached the box is retried on a survivor, and the dead copy is ejected on that failure - 8a629cd6 R23: the old forward row keeps serving until a copy of the new set has passed its health check - 214da4fc H2, hub: a relayed websocket is recorded as 101, not 200 - 38b1f4b2 H2, drill tool: the drill starts on a fresh minute - ab4cd5c3 H4: docs, new row SR-4-C94 - be827bfd census overlay stateless-replicas-4-drill3; `make census-card` is clean at the tip - **Tests:** the required gates pass (grouproll, `TestRegionHA`, three cross-compiles), as do the targeted edge, census and copy-gate tests. The new witnesses fail without the fixes: 11 hub 503s across the copies raise, and never-reached POSTs answered 502. - **The 41 extra 2xx:** 36 were the operator's raise probe, which shared the drill's first minute; 5 were websocket dials the hub counted as 200. - **Concerns:** - The R22 boundary relies on how the HTTP/2 library behaves under Go 1.26. A boundary test checks it, so re-run that test on any Go or x/net bump. - Under R23, websockets open on the forward row are cut at the conversion. This predates this work. - Recording relayed websockets as 101 changes request records and minute counts for every app. - The drill tool now waits up to about 62 s before starting. - Astra's census review is still owed. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-4/.superpowers/sdd/2026-11-01-stateless-replicas-4-deploy-and-drill/task-drill3-report.md</result> <usage><subagent_tokens>394371</subagent_tokens><tool_uses>133</tool_uses><duration_ms>2433487</duration_ms></usage> </task-notification>

diff --git a/internal/host/agent.go b/internal/host/agent.go
index ce349764a..fba02eb76 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1165,6 +1165,11 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// tunnelLoop is handed off to its own goroutine rather than called here —
// calling it directly would block the front door forever.
var shutdownDeadline time.Time
+ // tunnelDrain closes when the edge begins its graceful shutdown, before
+ // it closes tenant admission (edge.beginShutdown): a fleet box's tunnel
+ // then refuses new streams (#511 R24, tunnelDrainFor).
+ tunnelDrain := make(chan struct{})
+ var tunnelDrainOnce sync.Once
// The fixed box's ingress drain (W6, ingressdrain.go). Its arming is
// read when a drain is asked for, so an identity IMDS answers late
// still arms it. The agent's own shutdown disarms its 3-minute exit.
@@ -1184,6 +1189,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
edge.WithShutdownStarted(func(at time.Time) {
shutdownDeadline = at.Add(agentShutdownBudget)
ingress.shutdownStarted()
+ tunnelDrainOnce.Do(func() { close(tunnelDrain) })
}),
// Certificate issuance is a deployment-global duty, so it runs where
// the housekeeper runs (housekeeper.go). The gate goes DOWN into the
@@ -1298,7 +1304,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
serveHADrainSocket(healthCtx, haDrainSocketPath, driver)
}()
}
- go tunnelLoop(e)
+ go tunnelLoop(e, tunnelDrain)
// The home side of a linked deployment (linked deployments spec
// §6.2): a second, registry-driven loop that dials the link's hub
// while this box holds the link, serving only published apps.
diff --git a/internal/host/tunnel_client.go b/internal/host/tunnel_client.go
index 555605a00..641416047 100644
--- a/internal/host/tunnel_client.go
+++ b/internal/host/tunnel_client.go
@@ -12,8 +12,10 @@ import (
"log"
"net/http"
"os"
+ "strings"
"sync/atomic"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/tunnelclient"
)
@@ -32,7 +34,7 @@ func tunnelState() string {
// tunnelLoop dials CARLOS_TUNNEL_URL and serves handler over the inverted
// conn, forever, with jittered capped backoff. Inert unless all three env
// vars are set — the same convention as every other optional agent loop.
-func tunnelLoop(handler http.Handler) {
+func tunnelLoop(handler http.Handler, drain <-chan struct{}) {
rawURL := os.Getenv("CARLOS_TUNNEL_URL")
token := os.Getenv("CARLOS_TUNNEL_TOKEN")
name := os.Getenv("CARLOS_TUNNEL_NAME")
@@ -51,9 +53,26 @@ func tunnelLoop(handler http.Handler) {
Name: name,
Token: token,
Handler: handler,
+ Drain: tunnelDrainFor(name, drain),
OnState: func(s string) { tunnelStateVal.Store(s) },
// The "agent: " prefix is what operators grep the journal for, so it
// is preserved here rather than baked into the leaf package.
Logf: func(format string, args ...any) { log.Printf("agent: "+format, args...) },
})
}
+
+// tunnelDrainFor is the drain a channel named name follows (#511 R24): a
+// fleet box's channel ("<fleet>/<label>", the hub's dynamic credentials)
+// drains when the edge begins its graceful shutdown, so the hub retries
+// the box's new requests on another copy instead of meeting its shutdown
+// answers. A static channel (no "/", a `carlos route -tunnel` binding)
+// keeps today's behaviour: it serves until the process exits. A link's
+// home channel ("link:<id>/home", outside the fleet name alphabet) runs
+// its own loop (link_client.go) and is refused here too.
+func tunnelDrainFor(name string, drain <-chan struct{}) <-chan struct{} {
+ fleet, label, ok := strings.Cut(name, "/")
+ if !ok || !registry.ValidTunnelName(fleet) || !registry.ValidTunnelName(label) {
+ return nil
+ }
+ return drain
+}
diff --git a/internal/host/tunnel_client_test.go b/internal/host/tunnel_client_test.go
index ed8904d87..1d2e0e5bd 100644
--- a/internal/host/tunnel_client_test.go
+++ b/internal/host/tunnel_client_test.go
@@ -43,7 +43,7 @@ func TestTunnelLoopStateTransitions(t *testing.T) {
// forever on context.Background()), so this goroutine outlives the test;
// the fake edge is torn down via defer, and any further redial attempts
// just fail fast against a closed listener.
- go tunnelLoop(http.NewServeMux())
+ go tunnelLoop(http.NewServeMux(), nil)
waitForTunnelState(t, "connected")
@@ -75,7 +75,7 @@ func TestTunnelLoopInertUnlessFullyConfigured(t *testing.T) {
done := make(chan struct{})
go func() {
- tunnelLoop(http.NewServeMux())
+ tunnelLoop(http.NewServeMux(), nil)
close(done)
}()
select {
@@ -98,3 +98,18 @@ func waitForTunnelState(t *testing.T, want string) {
}
t.Fatalf("tunnelState() = %q, want %q before deadline", tunnelState(), want)
}
+
+// TestTunnelDrainOnlyForFleetChannels (#511 R24): only a fleet box's
+// channel drains at shutdown; a static channel and a link's home channel
+// keep serving until the process exits, as before.
+func TestTunnelDrainOnlyForFleetChannels(t *testing.T) {
+ drain := make(chan struct{})
+ if tunnelDrainFor("drill-sr3/box-2", drain) == nil {
+ t.Fatal("a fleet channel does not drain")
+ }
+ for _, name := range []string{"pi-box", "link:abc123/home", "link:0123456789abcdef0123456789abcdef/home", "/box-1", "pi/", ""} {
+ if tunnelDrainFor(name, drain) != nil {
+ t.Fatalf("%q drains", name)
+ }
+ }
+}
diff --git a/internal/tunnelclient/drain_test.go b/internal/tunnelclient/drain_test.go
new file mode 100644
index 000000000..b3d9045f2
--- /dev/null
+++ b/internal/tunnelclient/drain_test.go
@@ -0,0 +1,137 @@
+package tunnelclient
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "golang.org/x/net/http2"
+)
+
+// TestLoopDrain (#511 R24): once Drain closes, the box's tunnel refuses
+// new streams before its handler sees them, lets the stream it accepted
+// before the drain finish, and then Loop returns by itself without
+// dialing again. A drain closed before Loop starts dials nothing.
+func TestLoopDrain(t *testing.T) {
+ var registrations atomic.Int32
+ conns := make(chan *http2.ClientConn, 4)
+ edge := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ registrations.Add(1)
+ conn, bufrw, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ t.Errorf("hijack: %v", err)
+ return
+ }
+ fmt.Fprintf(bufrw, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: carlos-tunnel/1\r\nConnection: Upgrade\r\n\r\n")
+ bufrw.Flush()
+ cc, err := (&http2.Transport{}).NewClientConn(conn)
+ if err != nil {
+ t.Errorf("h2 client: %v", err)
+ return
+ }
+ conns <- cc
+ }))
+ defer edge.Close()
+
+ var seen sync.Map
+ accepted := make(chan struct{})
+ release := make(chan struct{})
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ seen.Store(r.URL.Path, true)
+ if r.URL.Path == "/accepted" {
+ close(accepted)
+ <-release
+ }
+ io.WriteString(w, "ok")
+ })
+ drain := make(chan struct{})
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ Loop(context.Background(), Config{URL: edge.URL, Name: "pi/box-1", Token: "t", Handler: handler, Drain: drain, Logf: t.Logf})
+ }()
+ var cc *http2.ClientConn
+ select {
+ case cc = <-conns:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the box never connected")
+ }
+ result := make(chan string, 1)
+ go func() {
+ req, _ := http.NewRequest("POST", "https://shop.example.com/accepted", nil)
+ resp, err := cc.RoundTrip(req)
+ if err != nil {
+ result <- err.Error()
+ return
+ }
+ b, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ result <- string(b)
+ }()
+ <-accepted
+
+ close(drain)
+ deadline := time.Now().Add(5 * time.Second)
+ for !cc.State().Closing {
+ if time.Now().After(deadline) {
+ t.Fatal("the box's GOAWAY never reached the hub side")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ req, _ := http.NewRequest("POST", "https://shop.example.com/after-drain", nil)
+ if _, err := cc.RoundTrip(req); err == nil {
+ t.Fatal("a draining box took a new stream")
+ }
+ if _, ok := seen.Load("/after-drain"); ok {
+ t.Fatal("a stream opened after the drain reached the handler")
+ }
+ close(release)
+ if got := <-result; got != "ok" {
+ t.Fatalf("the stream accepted before the drain: %q", got)
+ }
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("a drained Loop did not return once its connection ended")
+ }
+ // TestLoopDrain
+ if n := registrations.Load(); n != 1 {
+ t.Fatalf("a drained Loop dialed again: %d registrations", n)
+ }
+
+ // Drained before it starts: no dial at all.
+ early := make(chan struct{})
+ close(early)
+ Loop(context.Background(), Config{URL: edge.URL, Name: "pi/box-1", Token: "t", Handler: handler, Drain: early, Logf: t.Logf})
+ if n := registrations.Load(); n != 1 {
+ t.Fatalf("a Loop drained before it started dialed: %d registrations", n)
+ }
+}
+
+// TestDrainGateRefusesBeforeHandler: a stream whose handler starts after
+// the drain is reset (http.ErrAbortHandler) before the wrapped handler,
+// the upgrade shim, the edge, an activator or an app sees it.
+func TestDrainGateRefusesBeforeHandler(t *testing.T) {
+ drain := make(chan struct{})
+ var calls atomic.Int32
+ g := drainGate{h: http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls.Add(1) }), drain: drain}
+ g.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
+ close(drain)
+ func() {
+ defer func() {
+ if r := recover(); r != http.ErrAbortHandler {
+ t.Fatalf("drained stream: recovered %v, want http.ErrAbortHandler", r)
+ }
+ }()
+ g.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("POST", "/", nil))
+ }()
+ if calls.Load() != 1 {
+ t.Fatalf("handler calls %d, want only the one before the drain", calls.Load())
+ }
+}
diff --git a/internal/tunnelclient/tunnelclient.go b/internal/tunnelclient/tunnelclient.go
index 464840926..ce331bfe6 100644
--- a/internal/tunnelclient/tunnelclient.go
+++ b/internal/tunnelclient/tunnelclient.go
@@ -78,6 +78,11 @@ type Config struct {
// the tunnel conn; nil means DefaultLimits. Tests pass small ones to
// reach the limits without production-sized traffic.
Limits *Limits
+ // Drain, when it closes, starts the channel's drain (#511 R24): the
+ // live connection refuses new streams at the tunnel (serveConn) and
+ // finishes the ones it has, and Loop never dials again; it returns
+ // once that connection has ended. nil never drains.
+ Drain <-chan struct{}
}
// Loop dials cfg.URL and serves cfg.Handler over the inverted conn, forever,
@@ -101,7 +106,7 @@ func Loop(ctx context.Context, cfg Config) {
limits = *cfg.Limits
}
backoff := BackoffFloor
- for ctx.Err() == nil {
+ for ctx.Err() == nil && !closed(cfg.Drain) {
// Set BEFORE dialing, not only on error: Dial can block for up to
// HandshakeTimeout on a black-holed handshake, and a stale "" or
// "connected" during that window would read to the agent's heartbeat
@@ -109,6 +114,11 @@ func Loop(ctx context.Context, cfg Config) {
// we're actually hung waiting on a dead edge.
setState(StateReconnecting)
conn, err := Dial(ctx, cfg.URL, cfg.Name, cfg.Token)
+ if err == nil && closed(cfg.Drain) {
+ // Drained while dialing: this connection never serves.
+ conn.Close()
+ return
+ }
if err != nil {
sleep := backoff + rand.N(backoff/2)
logf("tunnel dial: %v (retry in %s)", err, sleep)
@@ -123,7 +133,11 @@ func Loop(ctx context.Context, cfg Config) {
setState(StateConnected)
logf("tunnel connected as %q", cfg.Name)
connectedAt := time.Now()
- serveUntilDead(ctx, conn, Mark(cfg.Handler), limits) // blocks until the conn dies
+ serveUntilDead(ctx, conn, Mark(cfg.Handler), limits, cfg.Drain) // blocks until the conn dies
+ if closed(cfg.Drain) {
+ logf("tunnel drained: no new streams, not re-dialing")
+ return
+ }
setState(StateReconnecting)
logf("tunnel lost — re-dialing")
// A connection that stayed up a while earns a fast retry (the
@@ -161,7 +175,7 @@ func wait(ctx context.Context, d time.Duration) bool {
// serveUntilDead is ServeWith plus cancellation: http2.Server.ServeConn blocks
// until the conn dies and has no other stop signal, so closing the conn is
// how a cancelled ctx gets Loop back.
-func serveUntilDead(ctx context.Context, conn net.Conn, handler http.Handler, l Limits) {
+func serveUntilDead(ctx context.Context, conn net.Conn, handler http.Handler, l Limits, drain <-chan struct{}) {
done := make(chan struct{})
go func() {
select {
@@ -171,7 +185,20 @@ func serveUntilDead(ctx context.Context, conn net.Conn, handler http.Handler, l
}
}()
defer close(done)
- ServeWith(conn, handler, l)
+ serveConn(conn, handler, l, drain)
+}
+
+// closed reports whether ch has closed; a nil ch never does.
+func closed(ch <-chan struct{}) bool {
+ if ch == nil {
+ return false
+ }
+ select {
+ case <-ch:
+ return true
+ default:
+ return false
+ }
}
// bufferedConn replays bytes the handshake's bufio.Reader over-read (the h2
diff --git a/internal/tunnelclient/upgrade.go b/internal/tunnelclient/upgrade.go
index f3f8a8485..4110bd4b5 100644
--- a/internal/tunnelclient/upgrade.go
+++ b/internal/tunnelclient/upgrade.go
@@ -91,12 +91,82 @@ func ValidUpgradeToken(tok string) bool {
// ServeWith serves handler over the inverted conn until it dies, with the
// server's stream count and receive windows taken from l.
func ServeWith(conn net.Conn, handler http.Handler, l Limits) {
+ serveConn(conn, handler, l, nil)
+}
+
+// serveConn is ServeWith, refusing new streams once drain closes (#511
+// R24). A nil drain never closes: the server is exactly ServeWith's.
+//
+// Draining refuses at the tunnel, before any handler (the upgrade shim,
+// the box's edge, its activator or an app) sees a new stream:
+// - drainGate: a stream whose handler starts once drain is closed is
+// reset (http.ErrAbortHandler, RST_STREAM) before it reaches handler;
+// - a graceful GOAWAY: once the connection's serve goroutine runs
+// goAway, x/net's processFrame (server.go:1464, v0.62.0) discards
+// every frame of a stream above the last stream it saw, before
+// processHeaders, so no handler starts for it; and the hub's
+// ClientConn, once it has read the GOAWAY, refuses new streams
+// before writing their HEADERS, which the hub classifies as never
+// reached and retries on another copy whatever the method.
+//
+// Streams already accepted run to their end: the server closes the
+// connection only once they are done (goAwayTimeout after the last), or
+// the process exits under them, as before.
+func serveConn(conn net.Conn, handler http.Handler, l Limits, drain <-chan struct{}) {
srv := &http2.Server{
MaxConcurrentStreams: l.MaxStreams,
MaxUploadBufferPerStream: l.StreamWindow,
MaxUploadBufferPerConnection: l.ConnWindow,
}
- srv.ServeConn(conn, &http2.ServeConnOpts{Handler: handler})
+ if drain == nil {
+ srv.ServeConn(conn, &http2.ServeConnOpts{Handler: handler})
+ return
+ }
+ // The base server exists only to carry the graceful shutdown to this
+ // one connection: ConfigureServer registers its onShutdown, and
+ // ServeConn registers the connection before its first ConnState call,
+ // so the drain waits for that call before shutting down.
+ registered := make(chan struct{})
+ var once sync.Once
+ base := &http.Server{ConnState: func(net.Conn, http.ConnState) { once.Do(func() { close(registered) }) }}
+ if err := http2.ConfigureServer(base, srv); err != nil {
+ conn.Close()
+ return
+ }
+ done := make(chan struct{})
+ defer close(done)
+ go func() {
+ select {
+ case <-drain:
+ case <-done:
+ return
+ }
+ select {
+ case <-registered:
+ case <-done:
+ return
+ }
+ // No listener and no tracked connection: Shutdown runs the
+ // onShutdown hook (the GOAWAY) and returns.
+ _ = base.Shutdown(context.Background())
+ }()
+ srv.ServeConn(conn, &http2.ServeConnOpts{Handler: drainGate{h: handler, drain: drain}, BaseConfig: base})
+}
+
+// drainGate resets a stream whose handler starts after drain has closed,
+// before the handler it wraps runs (serveConn).
+type drainGate struct {
+ h http.Handler
+ drain <-chan struct{}
+}
+
+func (g drainGate) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-g.drain:
+ panic(http.ErrAbortHandler)
+ default:
+ }
+ g.h.ServeHTTP(w, r)
}
// upgradeShim is the box half of an upgrade, applied by Mark. A request