carlos / platform Public

edge: drain tracking no longer ends the request's context early

CI 26b51463 failed TestTunnelWebSocketEndToEnd/case12_no_leaks: with
a writer whose Hijack answers http.ErrNotSupported, the upgrade
reservation was released while the request was still live.

Root cause: connDrain.track's untrack func cancelled the tracked
request's derived context when Edge.ServeHTTP returned. The upgrade
reservation's backstop is context.AfterFunc on that context, so it
fired at ServeHTTP's return rather than at the request's end; case 12
serves the hub behind a wrapping handler that keeps the request live.

untrack now only stops counting the request. The context is a child of
the inbound one and ends with the request; the drain's bound still
cancels it early. Regression tests: the tracked context outlives
untrack and ends with its parent or the bound, and a hijack works
through the tracked path and through handoverExit's exitWriter, which
passes http.ErrNotSupported through unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 389be364672dda19e76280aba6687718f5a567df parent 26b5146
2 files changed, +124 −1
  • internal/edge/hadrainconns.go +7 −1
  • internal/edge/hadrainconns_test.go +117 −0

Intent

Human

<task-notification> <task-id>a31b971fc5b7a2b7f</task-id> <tool-use-id>toolu_01EAD6xXXzpMoHyfq8iXCu3E</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/a31b971fc5b7a2b7f.output</output-file> <status>completed</status> <summary>Agent "Resolve main-merge conflicts" 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: merge committed (not pushed), worktree clean. Merge commit: 26b51463 Tests run, all passing: - `go build ./...` builds. `gofmt -l` and `go vet` on host, edge and provision are clean. - `internal/provision` `TestPlan14RootReadCensus`: ok, after `make census-propose`. The new seal is `1372fc6e…`. - `internal/host` `TestGroupNameClassCensus`, `TestEdgesNamedPoolsGolden`, and `-run` filters `HADrain|Drain|EdgesFile`: ok. - `internal/edge` `-run 'Handover|Replay|HADrain|Take|Held|Page'`: ok. - `internal/registry` and `internal/status` (full): ok. Concerns: - A third conflict, not in your brief, was in `internal/edge/edge.go` (the held-stream branch of `ServeHTTP`). I kept both sides: this branch's `ReleaseMoveTicket(r)` and main's `w = e.pageDiagnostics(...).wrap(w)`. Please look at that one. - The `edgesFileWriteClaims` merged body is the union of both sides: main's `assets.manifests.Load().prune` plus this branch's drain, `HATake` and publish logic. I set the fingerprint to the value the test reported, `00876c0a…`. - The census needed no new claims. Its card regenerated and the test passes. - I ran activator, compute and console tests only through the build and vet. I did not run their tests.</result> <usage><subagent_tokens>55073</subagent_tokens><tool_uses>15</tool_uses><duration_ms>469289</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>ada115aae1bb1d3b0</task-id> <tool-use-id>toolu_01JbLAJQFyjDDPGQFawwv98e</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/ada115aae1bb1d3b0.output</output-file> <status>completed</status> <summary>Agent "Fable whole-branch review" 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>NOT READY — 1 P1 (B1.1: roll's restarted agent is fenced but placeable, cold wakes get 503 until fence-clear), 1 P2 (B1.2: dropped SSM session read as a failed drain while the agent keeps draining), 4 P3 (IAM list delimiter, floor spec/tool mismatch, lock-sweep budget, fence-clear/stale comment). Deferred items: one "fix before merge" (run the committed tftest once; CI runs none), the rest can follow. Census: APPROVE every unit and envelope. Review written to `.superpowers/sdd/2026-11-08-region-ha-held-requests/branch-review-r1-fable.md`.</result> <usage><subagent_tokens>325466</subagent_tokens><tool_uses>54</tool_uses><duration_ms>1063106</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>brbe4rq6x</task-id> <tool-use-id>toolu_01Xi2xBy3edyJ4wCWMNf5iAT</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/brbe4rq6x.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra branch review; check CI" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/edge/hadrainconns.go b/internal/edge/hadrainconns.go
index 3e6546b98..fcbb6eda2 100644
--- a/internal/edge/hadrainconns.go
+++ b/internal/edge/hadrainconns.go
@@ -103,6 +103,13 @@ type drainConnKey struct{}
// false once the drain's barrier is closed: the caller refuses r. While
// draining, the response says Connection: close (HTTP/2 reads it as a
// graceful GOAWAY).
+//
+// The returned func only stops counting r: it does not cancel r's
+// context. That context is a child of the inbound one, which ends when
+// the request ends, and a request can outlive Edge.ServeHTTP's return
+// (a wrapping handler, or the upgrade reservation's backstop, which must
+// fire at the request's end and not at ServeHTTP's). Only the drain's
+// bound cancels it early.
func (d *connDrain) track(w http.ResponseWriter, r *http.Request) (*http.Request, func(), bool) {
c, _ := r.Context().Value(drainConnKey{}).(net.Conn)
d.mu.Lock()
@@ -122,7 +129,6 @@ func (d *connDrain) track(w http.ResponseWriter, r *http.Request) (*http.Request
w.Header().Set("Connection", "close")
}
return r.WithContext(ctx), func() {
- cancel()
d.mu.Lock()
delete(d.active, id)
if d.changed != nil {
diff --git a/internal/edge/hadrainconns_test.go b/internal/edge/hadrainconns_test.go
index 024f35a86..af23ecf1a 100644
--- a/internal/edge/hadrainconns_test.go
+++ b/internal/edge/hadrainconns_test.go
@@ -1,9 +1,11 @@
package edge
import (
+ "bufio"
"context"
"errors"
"io"
+ "net"
"net/http"
"net/http/httptest"
"slices"
@@ -348,3 +350,118 @@ func TestDrainConnectionsThroughServeHTTP(t *testing.T) {
}
_, _ = io.ReadAll(resp.Body)
}
+
+// The connection drain's tracking ends with Edge.ServeHTTP, but the
+// request's context ends with the request (CI 26b51463, case 12): a
+// handler wrapping the edge keeps the request live after ServeHTTP
+// returns, and the upgrade reservation's backstop must not fire until
+// then. Only the drain's bound cancels the tracked context early.
+func TestDrainTrackLeavesTheContextToTheRequest(t *testing.T) {
+ e := &Edge{}
+ parent, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ r := httptest.NewRequest("GET", "/", nil).WithContext(parent)
+ tr, untrack, ok := e.conns.track(httptest.NewRecorder(), r)
+ if !ok {
+ t.Fatal("refused before any drain")
+ }
+ if e.InFlight() != 1 {
+ t.Fatalf("in flight %d, want 1", e.InFlight())
+ }
+ untrack()
+ if e.InFlight() != 0 {
+ t.Fatalf("in flight %d after untrack, want 0", e.InFlight())
+ }
+ if err := tr.Context().Err(); err != nil {
+ t.Fatalf("untrack ended the request's context: %v", err)
+ }
+ cancel()
+ if tr.Context().Err() == nil {
+ t.Fatal("the tracked context outlived the request")
+ }
+
+ // The bound still cancels a tracked request's context.
+ r = httptest.NewRequest("GET", "/", nil)
+ tr, untrack, _ = e.conns.track(httptest.NewRecorder(), r)
+ defer untrack()
+ if n, _ := e.DrainConnections(context.Background(), 10*time.Millisecond); n != 1 {
+ t.Fatalf("the bound ended %d requests, want 1", n)
+ }
+ if tr.Context().Err() == nil {
+ t.Fatal("the drain's bound did not cancel the tracked context")
+ }
+}
+
+// A hijack works through each writer this branch wraps around the
+// client's: Edge.ServeHTTP's tracked request (no writer wrap; its
+// context must stay live while the hijacked stream runs) and the bounded
+// exit's exitWriter, which also passes http.ErrNotSupported through
+// unchanged so the reverse proxy reads it as it does on the bare writer.
+func TestHijackThroughTheBranchWrappers(t *testing.T) {
+ cases := map[string]func(http.ResponseWriter, *http.Request, http.HandlerFunc){
+ "tracked": func(w http.ResponseWriter, r *http.Request, h http.HandlerFunc) {
+ d := &connDrain{}
+ r, done, ok := d.track(w, r)
+ if !ok {
+ t.Error("refused")
+ return
+ }
+ defer done()
+ h(w, r)
+ },
+ "exitWriter": func(w http.ResponseWriter, r *http.Request, h http.HandlerFunc) {
+ handoverExit(w, r, h)
+ },
+ "tracked then exitWriter": func(w http.ResponseWriter, r *http.Request, h http.HandlerFunc) {
+ d := &connDrain{}
+ r, done, _ := d.track(w, r)
+ defer done()
+ handoverExit(w, r, h)
+ },
+ }
+ for name, wrap := range cases {
+ t.Run(name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ wrap(w, r, func(w http.ResponseWriter, r *http.Request) {
+ conn, brw, err := http.NewResponseController(w).Hijack()
+ if err != nil {
+ t.Errorf("hijack: %v", err)
+ return
+ }
+ defer conn.Close()
+ if r.Context().Err() != nil {
+ t.Error("the request's context ended at the hijack")
+ }
+ brw.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: test\r\nConnection: Upgrade\r\n\r\nhijacked")
+ brw.Flush()
+ })
+ }))
+ defer srv.Close()
+ c, err := net.Dial("tcp", srv.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ c.SetDeadline(time.Now().Add(5 * time.Second))
+ io.WriteString(c, "GET / HTTP/1.1\r\nHost: x\r\nConnection: Upgrade\r\nUpgrade: test\r\n\r\n")
+ got, _ := io.ReadAll(c)
+ if !strings.HasPrefix(string(got), "HTTP/1.1 101 ") || !strings.HasSuffix(string(got), "hijacked") || strings.Contains(string(got), "close") {
+ t.Fatalf("through %s the client read %q", name, got)
+ }
+ })
+ }
+
+ // http.ErrNotSupported from the writer below reaches the caller as is.
+ rec := notSupportedHijacker{httptest.NewRecorder()}
+ handoverExit(rec, httptest.NewRequest("GET", "/", nil), func(w http.ResponseWriter, r *http.Request) {
+ if _, _, err := http.NewResponseController(w).Hijack(); !errors.Is(err, http.ErrNotSupported) {
+ t.Fatalf("through exitWriter: %v, want http.ErrNotSupported", err)
+ }
+ })
+}
+
+type notSupportedHijacker struct{ http.ResponseWriter }
+
+func (notSupportedHijacker) Hijack() (net.Conn, *bufio.ReadWriter, error) {
+ return nil, nil, http.ErrNotSupported
+}