carlos / platform Public

edge: retry a never-reached replica request on a survivor (#511 R22)

The hub classified every request that got past the channel lookup as
dispatched, so a copy whose tunnel had died or refused new streams
answered 502 "not repeated" for a POST, and stayed in the live set until
a probe or the ping loop noticed.

replicaRoundTrip now reports "never reached" only when the HEADERS frame
was provably never handed to the connection: no channel, a wire whose
closed notice had already fired (the transport is not called), or a
ClientConn failure before its WroteHeaders trace fired with the attempt
context still live (x/net v0.62's abort path waits for the writer
goroutine, so the unfired trace is final). Anything else, a fired trace,
a cancelled context, a reset stream or any upgrade failure, may have
reached the box and keeps the GET/HEAD-only retry rule.

A never-reached request is retried on another healthy copy whatever its
method, with its body intact: each attempt reads the body through its
own view, whose Close is held back until the attempt has read. The copy
leaves the live set on the failure itself when its connection is gone or
closing (replicaChannelLost), and never on a request's own failure.

TestReplicaNeverReachedBoundary pins the boundary against the real
ClientConn with a frame-level box that counts the HEADERS it receives;
TestReplicaDeadCopyRetriedOnSurvivor is the witness through ServeHTTP.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 83ea17bbe1d0a341d999d816f44bd138d8f717a6 parent 6d561e2
4 files changed, +378 −10
  • internal/edge/replica_reach_test.go +278 −0
  • internal/edge/replicaprober.go +3 −2
  • internal/edge/replicaproxy.go +45 −3
  • internal/edge/tunnel.go +52 −5

Intent

Human

<task-notification> <task-id>aacfe3301fd962cd0</task-id> <tool-use-id>toolu_01WKe5aBPgxgQ2nPTbaWJpwM</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/aacfe3301fd962cd0.output</output-file> <status>completed</status> <summary>Agent "Investigate fleet box record enumeration" 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>The cause is the startup HA ingress pass, which reuses the normal instances scan: - `runHAIngressStartup` at `internal/host/agent.go:1048` and `internal/host/haingress.go:172` calls `scanInstanceRecords` at `internal/provision/reconcile.go:1177`. - On a fleet box that scan lists all of `apps/` (`reconcile.go:3362`). The store door turns that into a full listing of the account's own folder, `apps/bab/` (`internal/edge/storedoor.go:889`). - It then reads every record, because a record's placement is only inside its body. Records placed elsewhere are dropped afterwards (`reconcile.go:1388-1401`). - The 39 lines were reads that hit the 5-second startup deadline; nothing was read and acted on. **Tenancy: no issue.** The fleet box has no IAM access to the deployment bucket. The door lets it read only its own account's `apps/bab/**`, which the spec grants on purpose. It can't write any record. All three replica workers, including the deploy worker this branch added, drop records that don't name the box. The HA ingress step can never produce a forwarding route on a fleet box. **Cost: real but modest.** Every fleet box lists the whole account folder, including log, error and analytics files, and makes about 2 GETs per record, every 5 minutes, on each serial change, and up to 4 times at startup. One unreadable record from any app in the account also leaves the pass incomplete. I didn't count live requests, since this was read-only. **Predates the branch:** yes. The scan is from 98c43eea (11-06), the listing fallback from 91bb1a2e (10-05) and the door scoping from 99e45920 (08-11), all on main. **Recommendation:** no tenancy change, and Plan 4 isn't blocked. - Small fix, about 10-20 lines: skip the startup HA ingress scan on fleet boxes but keep the startup alias pass. - Medium fix, about 200-400 lines: have the door list only the records placed on the calling fleet. - Narrowing the credential would be a large job and gains nothing across tenants. Findings (70 lines) are in `/home/paulca/.cache/tmp/claude-1001/sr4-drill2/record-enumeration.md`.</result> <usage><subagent_tokens>117589</subagent_tokens><tool_uses>49</tool_uses><duration_ms>350645</duration_ms></usage> </task-notification>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="93cdaf34-af50-4605-8c98-92d96f7156a3"> Agent manager 8a3d302: thanks, good to know there&apos;s no tenancy issue. Yes, file (a) as an amadan discussion on carlos/platform with your write-up: skip the HA ingress record scan on fleet boxes (startup AND the 5-min/serial-change pass, if the periodic one is the same scan), keep the alias pass, and a test that a fleet box makes no records LIST for HA ingress. Mention memory s3-requests-cost-money: it&apos;s per-box polling of the whole account folder. (b) as a follow-up note in the same discussion. Send me the number; another agent builds it, not you (stay on Plan 4). </paseo-system>

Human

<task-notification> <task-id>af71f49622e203003</task-id> <tool-use-id>toolu_01CTC7foSiXg9XvyMh7UuNAK</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/af71f49622e203003.output</output-file> <status>failed</status> <summary>Agent "Merge main (v0.34.49) into Plan 4" failed: Agent terminated early due to an API error: You've hit your weekly limit · resets Nov 17, 9pm (Europe/Dublin) (error type rate_limit, HTTP 429, request id req_011CgxyKan5BLBMqLzZgJMAV, model sent to the API: claude-opus-5-5)</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. This agent's work so far is saved. The limit resets Nov 17, 9pm (Europe/Dublin). Once its requests are accepted again, send the agent a message (SendMessage) to let it continue from where it stopped instead of starting a new agent.</note> <result>Resolve the chain first: main's lines, then ours.</result> </task-notification>

Human

<task-notification> <task-id>botc7riod</task-id> <tool-use-id>toolu_019wsk3ygD1paXDcuAAZg8PB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/botc7riod.output</output-file> <status>completed</status> <summary>Background command "Astra census review of merge-main2 card" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bxa3qx0nm</task-id> <tool-use-id>toolu_01LM95Kp6Z88FgcGyvcDdwj6</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/bxa3qx0nm.output</output-file> <status>completed</status> <summary>Background command "Wait for CI on the merge" completed (exit code 0)</summary> </task-notification>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="82664493-e48e-4bd2-bfe5-5ea92f288c9e" message-id="990ceffc-bf97-4c8e-a90a-48b3dcc0ea78" source-agent-title="Release v0.34.41 (HA-only) resumed"> From the v0.34.49 release agent: the dev console (sophie) is now v0.34.49 (promoted forward at 11:28Z; it was v0.34.46 after your drill-2 cleanup). Your drill rollback target for the dev console changes from v0.34.46 to v0.34.49. Dev canary and stable are v0.34.49 too; #421 is free. </paseo-system>

Human

<task-notification> <task-id>a65c46718fe5ba3f4</task-id> <tool-use-id>toolu_01DHzXGr1MYPBJiSp5VhAjiC</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/a65c46718fe5ba3f4.output</output-file> <status>completed</status> <summary>Agent "Run stateless replicas dev drill 3" 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>**FAIL.** The drill ran end to end (13:02-13:39Z) on v0.35.901, and two checks failed: the hard stop and the evidence cross-check. - **Hard stop:** 9 reads failed, all 503s from the hub (sophie) in the 0.8 s between box-2's tunnel dying and the hub dropping it. 2 streams were cut at the stop and 2 more when box-2's old build stopped in the d2 deploy. - **Evidence cross-check:** the hub counted 41 more successful responses than the client (35,599 vs 35,558), unexplained. - **Passed:** spread 5,999/6,000, "1 of 2" in 2.8 s, websocket reconnect 1.4 s, return 6,000/6,000, release ran once in the good deploy and once in the failing one, ordered switch, no copy moved on the failing deploy, scale-down to one copy. - **Copies 1 to 2:** all three expectations held (serving copy stayed up, box-2 joined through a permit with no release run, 2 of 2), and the old first-wake config bug did not recur. But the hub answered 503 for 9 s after rewriting its forward row, while box-1's copy kept running. I logged it as a finding, not a stop; you may count it as a failure. - **B2 window on v0.34.49:** passed, 558 names, HA rows unchanged. My scan-URL substitution bug forced one extra console stop, so the console was down about 105 s across three stops. The hostname floor is now v0.34.49. **Cleanup is done.** The dev console is back on v0.34.49 by promote (exe 4fe296d2, as recorded). The v0.35.901 release objects, sophie's staged copy, both drill boxes, the bucket, security group, IAM user and local scratch are deleted. Canary and stable never changed, and the #421 lock was released at 13:45Z. **Left for you:** - Rule whether the 9 s hub gap during the raise counts as a failure. - Product follow-ups: the hub keeps picking a dead copy until it drops the channel; overlap swaps cut in-flight streams; the 41-response mismatch. Fleet boxes also get 404s for config acks and box snapshots. - Retained: the drill-sr3 fleet row (the next re-complete needs `-close-fleet drill-sr3`), the trashed srdrill3 app, and backups on sophie in /root/console-db-backups/*drill3 and /root/hu-sr43. - The console pointer history now names v0.35.901, so the next drill needs v0.35.902. - The drill-scope export line for "serving" doesn't exist on the overlap-swap path; I used another source, explained in the report. Report: /home/paulca/.cache/tmp/claude-1001/sr4-drill3/drill-report.md (log and evidence/ alongside).</result> <usage><subagent_tokens>336447</subagent_tokens><tool_uses>166</tool_uses><duration_ms>4330015</duration_ms></usage> </task-notification>

diff --git a/internal/edge/replica_reach_test.go b/internal/edge/replica_reach_test.go
new file mode 100644
index 000000000..40100d259
--- /dev/null
+++ b/internal/edge/replica_reach_test.go
@@ -0,0 +1,278 @@
+package edge
+
+import (
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "golang.org/x/net/http2"
+
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+// framerBox is a box at the HTTP/2 frame level: it counts every HEADERS
+// frame that reaches it, so a test can tell exactly whether a request was
+// written to the tunnel stream (R22's "reached the box" boundary).
+type framerBox struct {
+ headers atomic.Int32
+ box net.Conn
+ tc *tunnelConn
+ done chan struct{}
+}
+
+// Box behaviours for replicaFramerBox.
+const (
+ framerGoAway = "goaway" // refuse every stream with GOAWAY(0), keep the wire open
+ framerDieOnHeaders = "die-on-headers" // close the wire when a HEADERS frame arrives
+ framerHangUp = "hang-up" // close the wire once the handshake is done
+ framerDiesOnPick = "dies-on-pick" // like hang-up, but only once the hub has picked the copy
+)
+
+// replicaFramerBox replaces box's channel on hub with a framerBox and points
+// the prober's job for it at the new connection, keeping its sample healthy.
+func replicaFramerBox(t *testing.T, hub *TunnelHub, p *replicaProber, host, box, mode string) *framerBox {
+ t.Helper()
+ channel := "pi/" + box
+ hub.CloseChannel(channel)
+ a, b := net.Pipe()
+ fb := &framerBox{box: b, done: make(chan struct{})}
+ settled := make(chan struct{})
+ var once sync.Once
+ go func() {
+ defer close(fb.done)
+ preface := make([]byte, len(http2.ClientPreface))
+ if _, err := io.ReadFull(b, preface); err != nil {
+ return
+ }
+ fr := http2.NewFramer(b, b)
+ var wmu sync.Mutex
+ write := func(f func() error) {
+ // The hub reads only once NewClientConn has flushed, so the
+ // box writes from its own goroutine and keeps reading.
+ go func() { wmu.Lock(); defer wmu.Unlock(); _ = f() }()
+ }
+ write(func() error { return fr.WriteSettings() })
+ for {
+ f, err := fr.ReadFrame()
+ if err != nil {
+ return
+ }
+ switch f := f.(type) {
+ case *http2.SettingsFrame:
+ if f.IsAck() {
+ once.Do(func() { close(settled) })
+ continue
+ }
+ write(func() error { return fr.WriteSettingsAck() })
+ if mode == framerGoAway {
+ write(func() error { return fr.WriteGoAway(0, http2.ErrCodeNo, nil) })
+ }
+ case *http2.HeadersFrame:
+ fb.headers.Add(1)
+ if mode == framerDieOnHeaders {
+ b.Close()
+ return
+ }
+ }
+ }
+ }()
+ wire := &tunnelWire{Conn: a, closed: make(chan struct{})}
+ cc, err := (&http2.Transport{}).NewClientConn(wire)
+ if err != nil {
+ t.Fatal(err)
+ }
+ hub.mu.Lock()
+ hub.nextGeneration++
+ fb.tc = &tunnelConn{raw: wire, cc: cc, closed: wire.closed, generation: hub.nextGeneration, caps: tunnelclient.CapUpgrade}
+ hub.conns[channel] = fb.tc
+ hub.mu.Unlock()
+ p.mu.Lock()
+ p.jobs[replicaSlot{host, box}].conn = fb.tc
+ p.mu.Unlock()
+ t.Cleanup(func() {
+ cc.Close()
+ b.Close()
+ <-fb.done
+ })
+ select {
+ case <-settled:
+ case <-time.After(5 * time.Second):
+ t.Fatal("framer box handshake did not finish")
+ }
+ switch mode {
+ case framerGoAway:
+ replicaAwait(t, "the hub's connection to take the GOAWAY", func() bool { return cc.State().Closing })
+ case framerHangUp:
+ fb.hangUp(t)
+ }
+ return fb
+}
+
+// hangUp closes the box's end of the wire and waits for the hub's reader to
+// see it end (the closed notice). Nothing unregisters the channel: no ping
+// loop runs in these fixtures, as in the ~0.8 s before a real one notices.
+func (fb *framerBox) hangUp(t *testing.T) {
+ fb.box.Close()
+ replicaAwait(t, "the hub to see the wire end", func() bool {
+ select {
+ case <-fb.tc.closed:
+ return true
+ default:
+ return false
+ }
+ })
+}
+
+// TestReplicaNeverReachedBoundary pins R22's boundary against the real
+// x/net ClientConn, from both sides of the HEADERS write, with a box that
+// counts the HEADERS frames it receives:
+// - a stream the connection refuses before writing it (GOAWAY received,
+// wire still open) never reaches the box, and is classified so;
+// - a wire whose end the hub has seen is never written to;
+// - a request whose HEADERS reached the box, after which the box died
+// before answering, is classified as possibly reached.
+//
+// A toolchain or x/net change that moved the WroteHeaders trace or the
+// abort path's wait fails one side of this.
+func TestReplicaNeverReachedBoundary(t *testing.T) {
+ for _, tc := range []struct {
+ mode string
+ wantReached bool
+ wantHeaders int32
+ }{
+ {framerGoAway, false, 0},
+ {framerHangUp, false, 0},
+ {framerDieOnHeaders, true, 1},
+ } {
+ t.Run(tc.mode, func(t *testing.T) {
+ hub, p, rt := replicaProxyFixture(t, func(http.ResponseWriter, *http.Request) {}, func(http.ResponseWriter, *http.Request) {})
+ fb := replicaFramerBox(t, hub, p, rt.Host, "box-00", tc.mode)
+ if tc.mode == framerGoAway {
+ select {
+ case <-fb.tc.closed:
+ t.Fatal("the GOAWAY case must reach ClientConn with its wire still open")
+ default:
+ }
+ }
+ body := &replicaReadCounter{Reader: strings.NewReader("payload")}
+ _, reached, err := hub.replicaRoundTrip("pi/box-00", replicaDispatchRequest(t, "POST", body))
+ if err == nil {
+ t.Fatal("a dead or refusing box answered")
+ }
+ // TestReplicaNeverReachedBoundary
+ if reached != tc.wantReached || fb.headers.Load() != tc.wantHeaders {
+ t.Fatalf("reached %v with %d HEADERS at the box, want %v with %d (%v)", reached, fb.headers.Load(), tc.wantReached, tc.wantHeaders, err)
+ }
+ if !reached && body.reads != 0 {
+ t.Fatal("a request that never reached the box read its body")
+ }
+ if !hub.replicaChannelLost("pi/box-00") {
+ t.Fatal("a dead or refusing connection was not seen as lost")
+ }
+ })
+ }
+}
+
+// TestReplicaDeadCopyRetriedOnSurvivor is R22's witness, through the hub's
+// front door (ServeHTTP, request records) and the real replica transport:
+// the hub selects a copy whose tunnel channel has died or refuses new
+// streams, and the request, a POST, is served by the surviving copy with
+// its body intact and no 503. The dead copy leaves the live set on that
+// failure, before any probe or channel-close cleanup runs (this fixture
+// runs neither). A POST whose HEADERS reached the box before it died keeps
+// the GET/HEAD-only rule: it is not repeated, and a GET in the same case
+// is.
+func TestReplicaDeadCopyRetriedOnSurvivor(t *testing.T) {
+ serve := func(t *testing.T, mode, method string) (int, string, *framerBox, *replicaProber, *memRecorder, int32) {
+ var survivor atomic.Int32
+ hub, p, rt := replicaProxyFixture(t, func(http.ResponseWriter, *http.Request) {}, func(w http.ResponseWriter, r *http.Request) {
+ survivor.Add(1)
+ b, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Errorf("survivor body: %v", err)
+ }
+ io.WriteString(w, r.Method+" "+string(b))
+ })
+ fb := replicaFramerBox(t, hub, p, rt.Host, "box-00", mode)
+ e := edgeWithBackend(t, http.NotFoundHandler())
+ proxy := replicaProxy(rt.Host, "pi", p, hub)
+ if mode == framerDiesOnPick {
+ proxy.Transport.(*replicaTransport).beforeAttempt = func(box string) {
+ if box == "box-00" {
+ fb.hangUp(t)
+ }
+ }
+ }
+ ups := map[string]upstream{rt.Host: {route: rt, proxy: proxy, viaTunnel: true}}
+ e.upstreams.Store(&ups)
+ records := &memRecorder{}
+ e.EnableRequestRecords(records)
+ var body io.Reader
+ if method == "POST" {
+ body = strings.NewReader("once")
+ }
+ w := httptest.NewRecorder()
+ // The first request of a fresh transport selects box-00.
+ e.ServeHTTP(w, httptest.NewRequest(method, "http://"+rt.Host+"/", body))
+ return w.Code, w.Body.String(), fb, p, records, survivor.Load()
+ }
+ for _, mode := range []string{framerDiesOnPick, framerGoAway} {
+ t.Run(mode, func(t *testing.T) {
+ code, got, fb, p, records, survivor := serve(t, mode, "POST")
+ live := p.Live("shop.example.com")
+ // TestReplicaDeadCopyRetriedOnSurvivor
+ if code != 200 || got != "POST once" || survivor != 1 || fb.headers.Load() != 0 {
+ t.Fatalf("never-reached POST: %d %q, survivor calls %d, HEADERS at dead box %d", code, got, survivor, fb.headers.Load())
+ }
+ if len(live) != 1 || live[0].Box != "box-01" {
+ t.Fatalf("dead copy not ejected on the failure: %+v", live)
+ }
+ if len(records.resp) != 1 || records.resp[0].Status != 200 || records.resp[0].Attempts != 2 || records.resp[0].SelectedBox != "box-01" {
+ t.Fatalf("records: %+v", records.resp)
+ }
+ })
+ }
+ t.Run("reached POST is not repeated", func(t *testing.T) {
+ code, _, fb, p, records, survivor := serve(t, framerDieOnHeaders, "POST")
+ if code != http.StatusBadGateway || survivor != 0 || fb.headers.Load() != 1 {
+ t.Fatalf("possibly reached POST: %d, survivor calls %d, HEADERS at dead box %d", code, survivor, fb.headers.Load())
+ }
+ if live := p.Live("shop.example.com"); len(live) != 1 || live[0].Box != "box-01" {
+ t.Fatalf("dead copy not ejected: %+v", live)
+ }
+ if len(records.resp) != 1 || records.resp[0].Status != http.StatusBadGateway {
+ t.Fatalf("records: %+v", records.resp)
+ }
+ })
+ t.Run("reached GET is retried", func(t *testing.T) {
+ code, got, fb, _, _, survivor := serve(t, framerDieOnHeaders, "GET")
+ if code != 200 || got != "GET " || survivor != 1 || fb.headers.Load() != 1 {
+ t.Fatalf("possibly reached GET: %d %q, survivor calls %d, HEADERS at dead box %d", code, got, survivor, fb.headers.Load())
+ }
+ })
+}
+
+// TestReplicaRefusedStreamKeepsHealthyCopy: a failure that says nothing
+// about the box (here a header the HTTP/2 encoder refuses, so nothing is
+// written) is never "reached", but it does not eject a healthy copy
+// either: only a lost connection does (replicaChannelLost).
+func TestReplicaRefusedStreamKeepsHealthyCopy(t *testing.T) {
+ var calls atomic.Int32
+ f := func(http.ResponseWriter, *http.Request) { calls.Add(1) }
+ hub, p, rt := replicaProxyFixture(t, f, f)
+ req := replicaDispatchRequest(t, "POST", strings.NewReader("x"))
+ req.Header["Bad Name"] = []string{"v"}
+ _, err := replicaProxy(rt.Host, "pi", p, hub).Transport.RoundTrip(req)
+ if err == nil || calls.Load() != 0 {
+ t.Fatalf("invalid header reached a box: %v %d", err, calls.Load())
+ }
+ if len(p.Live(rt.Host)) != 2 {
+ t.Fatal("a request's own failure ejected healthy copies")
+ }
+}
diff --git a/internal/edge/replicaprober.go b/internal/edge/replicaprober.go
index 93cf8dd5d..a94efc066 100644
--- a/internal/edge/replicaprober.go
+++ b/internal/edge/replicaprober.go
@@ -343,8 +343,9 @@ func (p *replicaProber) Live(host string) []replicas.Copy {
return live
}
-// Eject is for a pre-dispatch missing channel or a closed tunnel only. An
-// ordinary dispatched request error must be left to the health probes.
+// Eject is for a copy whose connection is gone or refusing new streams
+// (TunnelHub.replicaChannelLost), found on a request's failure (R22). An
+// ordinary request error must be left to the health probes.
func (p *replicaProber) Eject(host, box string) {
p.mu.Lock()
defer p.mu.Unlock()
diff --git a/internal/edge/replicaproxy.go b/internal/edge/replicaproxy.go
index 88da5c925..30a6b831c 100644
--- a/internal/edge/replicaproxy.go
+++ b/internal/edge/replicaproxy.go
@@ -37,6 +37,9 @@ type replicaTransport struct {
cursor atomic.Uint64
// Test seam for the interval between transport completion and timer stop.
afterRoundTrip func(context.Context)
+ // Test seam for the interval between selecting a copy and dispatching
+ // to it: a channel that dies there was chosen while it was live.
+ beforeAttempt func(box string)
}
func replicaProxy(host, fleet string, p *replicaProber, hub *TunnelHub) *httputil.ReverseProxy {
@@ -174,15 +177,27 @@ func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error)
},
})
attempt := req.Clone(ctx)
- attempt.Body = body
+ // Each attempt sees the body through its own view, so a ClientConn
+ // that refuses the stream before writing it (and closes the body as
+ // it does on every exit) leaves the body whole for the next copy.
+ var view *replicaAttemptBody
+ if body != nil {
+ view = &replicaAttemptBody{src: body}
+ attempt.Body = view
+ }
// Only this loop may reproduce a body. ClientConn itself has no retry
// loop; never expose GetBody to a lower transport or an upgrade helper.
attempt.GetBody = nil
+ if t.beforeAttempt != nil {
+ t.beforeAttempt(box)
+ }
resp, didDispatch, err := t.hub.replicaRoundTrip(t.fleet+"/"+box, attempt)
if t.afterRoundTrip != nil {
t.afterRoundTrip(ctx)
}
- dispatched = didDispatch
+ // A body read at all means the headers went first: never "not
+ // reached", whatever the transport said.
+ dispatched = didDispatch || (view != nil && view.read.Load())
anyDispatched = anyDispatched || dispatched
owned = owned || dispatched
stopTimer()
@@ -207,7 +222,11 @@ func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error)
if dispatched && body != nil {
body.Close()
}
- if !dispatched || t.hub.probeConnection(t.fleet+"/"+box) == nil {
+ // R22: a copy whose connection is gone or refusing streams leaves
+ // the set on this failure, not on the later channel-close cleanup.
+ // Any other failure (a reset stream, an invalid header) is left to
+ // the health probes.
+ if t.hub.replicaChannelLost(t.fleet + "/" + box) {
t.p.Eject(t.host, box)
}
if !replicas.RetryAllowed(req.Method, dispatched, responseStarted) {
@@ -220,6 +239,29 @@ func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error)
return nil, last
}
+// replicaAttemptBody is one attempt's view of the request body. Close is
+// passed on only once the attempt has started reading: a ClientConn closes
+// the body on every exit, and on a stream refused before its headers were
+// written (R22) that close must not spend a body the next copy still needs.
+// A body nobody read is closed by the transport's own cleanup, or by the
+// server when the request ends.
+type replicaAttemptBody struct {
+ src io.ReadCloser
+ read atomic.Bool
+}
+
+func (b *replicaAttemptBody) Read(p []byte) (int, error) {
+ b.read.Store(true)
+ return b.src.Read(p)
+}
+
+func (b *replicaAttemptBody) Close() error {
+ if b.read.Load() {
+ return b.src.Close()
+ }
+ return nil
+}
+
// A one-shot wrapper hides optional replay interfaces and closes once even
// when the h2 writer and the failed-attempt cleanup finish concurrently.
type replicaRequestBody struct {
diff --git a/internal/edge/tunnel.go b/internal/edge/tunnel.go
index 0bdb35cc0..f379b28d5 100644
--- a/internal/edge/tunnel.go
+++ b/internal/edge/tunnel.go
@@ -18,9 +18,11 @@ import (
"log"
"net"
"net/http"
+ "net/http/httptrace"
"slices"
"strings"
"sync"
+ "sync/atomic"
"time"
"golang.org/x/net/http/httpguts"
@@ -828,19 +830,64 @@ func (h *TunnelHub) matchReplicaBoot(c *tunnelConn, boot string, learn bool) boo
return c.probeBoot == "" || c.probeBoot == boot
}
-// replicaRoundTrip reports false only before touching the body or calling a
-// transport. ClientConn.RoundTrip (unlike http2.Transport) never retries. All
-// errors after entering that boundary are ambiguous, including stream resets
-// and upgrade admission failures; none proves an app did not act.
+// replicaRoundTrip sends req down channel and reports whether it may have
+// reached the box (R22). It reports false only when the request's HEADERS
+// frame was provably never handed to the connection, so the box cannot
+// have seen it:
+// - the channel has no connection;
+// - the connection's wire had already ended (its closed notice), so this
+// never calls the transport;
+// - ClientConn.RoundTrip failed before its WroteHeaders trace fired, with
+// the attempt's context still live and no Request.Cancel. x/net/http2
+// (v0.62.0, transport.go internalRoundTrip) returns such an error only
+// on its abort path, which waits for the request's writer goroutine to
+// finish (waitDone on cs.donec) before returning. That goroutine fires
+// WroteHeaders right after its only HEADERS write, so an unfired trace
+// at that point is final: nothing was or will be written. A refused
+// stream on a closed or GOAWAY'd connection (errClientConnUnusable) is
+// this case.
+//
+// Everything else may have reached the box: a fired WroteHeaders (even if
+// the write then failed), any failure on a cancelled context (the writer
+// may still be running), stream resets, and every upgrade failure after
+// the closed-notice check, admission refusals included. None of them proves
+// an app did not act. ClientConn.RoundTrip (unlike http2.Transport) never
+// retries. TestReplicaNeverReachedBoundary pins this against the real
+// ClientConn, from both sides of the HEADERS write.
func (h *TunnelHub) replicaRoundTrip(channel string, req *http.Request) (*http.Response, bool, error) {
tc := h.channel(channel)
if tc == nil {
return nil, false, fmt.Errorf("tunnel %q not connected", channel)
}
+ select {
+ case <-tc.closed:
+ return nil, false, fmt.Errorf("tunnel %q: its connection has ended", channel)
+ default:
+ }
if isUpgradeRequest(req) {
resp, err := h.roundTripUpgrade(channel, req)
return resp, true, err
}
- resp, err := tc.cc.RoundTrip(req)
+ var wrote atomic.Bool
+ ctx := httptrace.WithClientTrace(req.Context(), &httptrace.ClientTrace{WroteHeaders: func() { wrote.Store(true) }})
+ resp, err := tc.cc.RoundTrip(req.WithContext(ctx))
+ if err != nil && resp == nil && !wrote.Load() && req.Context().Err() == nil && req.Cancel == nil {
+ return nil, false, err
+ }
return resp, true, err
}
+
+// replicaChannelLost reports whether channel's current connection can carry
+// no new request: none, a wire whose closed notice has fired, or a
+// ClientConn that is closed or closing (a GOAWAY, sent or received). The
+// replica transport ejects a copy on a failure only when this holds, so a
+// request whose own failure says nothing about the box (an invalid header,
+// a reset stream) never takes a healthy copy out of the set.
+func (h *TunnelHub) replicaChannelLost(channel string) bool {
+ c := h.probeConnection(channel)
+ if c == nil {
+ return true
+ }
+ st := c.cc.State()
+ return st.Closed || st.Closing
+}