carlos / platform Public

region HA: relay a closing answer in full before the cleanup bound

An upstream answer that closes its connection while the client's
streamed body is unfinished set the client's 1 s read deadline as soon
as its headers arrived. A valid answer streaming for longer than that
was cut short: the transport's pending read of the withheld body timed
out, and net/http cancelled the request, upstream answer included.
This hit ordinary closing answers too, on the forward and the backhaul.

closeAfterEarlyAnswer now only marks the connection closing. The
deadline is armed in finishEarlyAnswer, after the relay, so the bound
of about 1 s applies to the cleanup only.

Witness TestEarlyAnswerRelaysASlowAnswerWhole: a closing answer that
streams for about 3 s while the client withholds its body arrives whole,
then EOF within about 1 s, in region and across regions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 0ca0bc7bb3a0b47229b80d898a084bea1f643a0e parent 3b8dc18
2 files changed, +101 −17
  • internal/edge/replay.go +20 −17
  • internal/edge/replay_test.go +81 −0

Intent

Human

<task-notification> <task-id>aef76dee7dd89daec</task-id> <tool-use-id>toolu_01LLez8ympKZCyX2uovJ72JJ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/aef76dee7dd89daec.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: replay + attempts" 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 Commits: `31162a92` (fix), `3b8dc18a` (census). FIX_BASE `f9b17c0f`. Not pushed. Tests: the replay tests and the new stalled-client test pass at `-count=50`. All 4 round-3 mutations are caught. The edge regression set, the census test, gofmt, vet and the darwin/windows builds pass. Fix: - **Cause:** once the handler returns, net/http resets the client connection's read deadline to none. It then waits for the rest of the request body with no limit, so a deadline set during the handler did nothing. - **Change:** after relaying an early closing answer, the forwarding box sets the client connection's read deadline 1 s ahead and flushes the answer. Before the handler returns, it reads and throws away the client's body until the body ends or the deadline passes. The connection then closes within about 1 s. This applies to both the in-region forward and the backhaul. - **Witness** (`TestEarlyAnswerClosesAStalledClient`): a client sends 10 bytes of a `Content-Length: 100000` POST, then nothing. It gets the full 503 with `Retry-After: 10`, and the connection closes within about 1 s while it still holds back the rest of its body. This holds in region and across regions. Concerns: - The 503's headers and body are flushed straight away, but the very end of the response arrives up to 1 s later, when the cleanup finishes. - A client that keeps sending is read for at most that 1 s. The cross-region small-body item stays parked, and that behaviour is unchanged. Census: re-proposed (seal `3fd7b3fe...`) and the census test passes. The cross-family verdict on #280 is still owed. Report (fix round 3 appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-held-build/.superpowers/sdd/2026-11-08-region-ha-held-requests/task-3-report.md</result> <usage><subagent_tokens>445730</subagent_tokens><tool_uses>18</tool_uses><duration_ms>965473</duration_ms></usage> </task-notification>

diff --git a/internal/edge/replay.go b/internal/edge/replay.go
index 13f36a6a7..f615c7de3 100644
--- a/internal/edge/replay.go
+++ b/internal/edge/replay.go
@@ -150,35 +150,38 @@ func watchBody(r *http.Request) (*http.Request, *streamedBody) {
// answer short). A body that did all go upstream leaves the connection
// as it is.
//
-// The cleanup is bounded too: the client connection's read deadline goes
-// exitLingerBound ahead. The answer is relayed first; then a client still
-// withholding its body interrupts, at that deadline, the transport's
-// pending read of it (which net/http's own close of the body would wait
-// behind), and the connection closes. A client that keeps sending only
-// lingers until the deadline. finishEarlyAnswer, after the relay, makes
-// that bound hold.
+// It runs when the answer's headers arrive and sets no deadline: the
+// answer, however long it streams, is relayed in full first. Until then
+// the transport's pending read of the client's body simply waits; a
+// deadline on it here would fail that read mid-answer, and net/http
+// cancels the request (and with it the upstream answer) on a failed body
+// read. finishEarlyAnswer bounds the cleanup once the relay is done.
func closeAfterEarlyAnswer(w http.ResponseWriter, r *http.Request, body *streamedBody, resp *http.Response) {
if body == nil || body.done.Load() || !resp.Close || r.ProtoMajor != 1 || resp.StatusCode == http.StatusSwitchingProtocols {
return
}
w.Header().Set("Connection", "close")
body.closing.Store(true)
- _ = http.NewResponseController(w).SetReadDeadline(time.Now().Add(exitLingerBound))
}
// finishEarlyAnswer runs after the relay when closeAfterEarlyAnswer
-// applied. It flushes the answer, then reads and discards the client's
-// body itself until the body ends or closeAfterEarlyAnswer's deadline
-// passes. That read waits behind the transport's pending read, which the
-// deadline interrupts; it must happen before the handler returns, because
-// net/http, once the handler is done, aborts a pending read by resetting
-// the read deadline to none and then drains the body with no bound. With
-// the body ended or the deadline spent, that drain ends at once, and the
-// connection closes within about exitLingerBound of the answer.
+// applied. Only now, with the whole answer relayed, it puts the client
+// connection's read deadline exitLingerBound ahead, flushes the answer,
+// then reads and discards the client's body itself until the body ends or
+// that deadline passes. That read waits behind the transport's pending
+// read, which the deadline interrupts; it must happen before the handler
+// returns, because net/http, once the handler is done, aborts a pending
+// read by resetting the read deadline to none and then drains the body
+// with no bound. With the body ended or the deadline spent, that drain
+// ends at once, and the connection closes within about exitLingerBound of
+// the end of the answer. A client that keeps sending only lingers until
+// the deadline.
func finishEarlyAnswer(w http.ResponseWriter, body *streamedBody) {
if body == nil || !body.closing.Load() {
return
}
- _ = http.NewResponseController(w).Flush()
+ rc := http.NewResponseController(w)
+ _ = rc.SetReadDeadline(time.Now().Add(exitLingerBound))
+ _ = rc.Flush()
_, _ = io.Copy(io.Discard, body.ReadCloser)
}
diff --git a/internal/edge/replay_test.go b/internal/edge/replay_test.go
index 3a1cc2187..e4c8d3751 100644
--- a/internal/edge/replay_test.go
+++ b/internal/edge/replay_test.go
@@ -47,6 +47,9 @@ const rpDoraEIP = "127.0.0.3"
// - "": nothing is moving, and the box serves.
//
// Path /reset is answered by closing the connection with no response.
+// Path /slow-close is an ordinary answer that closes its connection and
+// streams rpSlowChunks chunks, one every rpSlowEvery, without reading the
+// request body.
type rpMover struct {
*fwAct
mu sync.Mutex
@@ -70,9 +73,37 @@ func (m *rpMover) ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.
}
return true
}
+ if r.URL.Path == "/slow-close" {
+ w.Header().Set("Connection", "close")
+ w.WriteHeader(http.StatusOK)
+ for i := range rpSlowChunks {
+ if i > 0 {
+ time.Sleep(rpSlowEvery)
+ }
+ io.WriteString(w, rpSlowChunk(i))
+ http.NewResponseController(w).Flush()
+ }
+ return true
+ }
return m.fwAct.ServeHTTP(w, r, rt, next)
}
+// The /slow-close answer: about 3 s of chunks.
+const (
+ rpSlowChunks = 31
+ rpSlowEvery = 100 * time.Millisecond
+)
+
+func rpSlowChunk(i int) string { return fmt.Sprintf("chunk %02d %s\n", i, strings.Repeat("x", 500)) }
+
+func rpSlowBody() string {
+ var b strings.Builder
+ for i := range rpSlowChunks {
+ b.WriteString(rpSlowChunk(i))
+ }
+ return b.String()
+}
+
func (m *rpMover) MoveState(_ registry.Route, ask MoveAsk) MoveDecision {
m.mu.Lock()
defer m.mu.Unlock()
@@ -1011,3 +1042,53 @@ func TestEarlyAnswerClosesAStalledClient(t *testing.T) {
stalled(t, s.sender.tlsAddr, HAForwardHost, backhaulRootCAs)
})
}
+
+// Fix round 4: the cleanup bound applies only once the answer is relayed.
+// An ordinary closing answer that streams for about 3 s, while the client
+// withholds its body, reaches the client whole; EOF follows within about
+// a second. In region and across regions.
+func TestEarlyAnswerRelaysASlowAnswerWhole(t *testing.T) {
+ slow := func(t *testing.T, addr, host string, pool *x509.CertPool) {
+ t.Helper()
+ raw, err := net.DialTimeout("tcp", addr, 5*time.Second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c := tls.Client(raw, &tls.Config{ServerName: host, RootCAs: pool, MinVersion: tls.VersionTLS12})
+ defer c.Close()
+ c.SetDeadline(time.Now().Add(15 * time.Second))
+ start := time.Now()
+ fmt.Fprintf(c, "POST /slow-close HTTP/1.1\r\nHost: %s\r\nContent-Length: 100000\r\n\r\n0123456789", host)
+ br := bufio.NewReader(c)
+ resp, err := http.ReadResponse(br, nil)
+ if err != nil {
+ t.Fatalf("no answer: %v", err)
+ }
+ b, err := io.ReadAll(resp.Body)
+ if err != nil || resp.StatusCode != 200 || string(b) != rpSlowBody() || !resp.Close {
+ t.Fatalf("%d %v closing=%v, %d of %d bytes after %v: %v; want the whole slow answer, connection closing",
+ resp.StatusCode, resp.Header, resp.Close, len(b), len(rpSlowBody()), time.Since(start), err)
+ }
+ if took := time.Since(start); took < (rpSlowChunks-1)*rpSlowEvery {
+ t.Fatalf("the answer took %v; the witness needs one longer than %v", took, (rpSlowChunks-1)*rpSlowEvery)
+ }
+ answered := time.Now()
+ c.SetReadDeadline(time.Now().Add(3 * time.Second))
+ if _, err := br.ReadByte(); err != io.EOF {
+ t.Fatalf("the connection stayed open while the client withheld its body: %v", err)
+ }
+ if waited := time.Since(answered); waited > exitLingerBound+500*time.Millisecond {
+ t.Fatalf("closed %v after the answer, want about %v", waited, exitLingerBound)
+ }
+ }
+ t.Run("in region", func(t *testing.T) {
+ x := newRpScene(t)
+ x.drain.set("", "dora")
+ slow(t, x.a.tlsAddr, fwHost, x.ca.pool)
+ })
+ t.Run("cross region", func(t *testing.T) {
+ s, mv := newRpBackhaul(t)
+ mv.set("", "betty")
+ slow(t, s.sender.tlsAddr, HAForwardHost, backhaulRootCAs)
+ })
+}