gateway: a new connection closed before Go wrote a byte of the request goes again, though Go says only "EOF" (#5519)

TestClosedBeforeSentIsSentAgain failed on CI's race run (b77400826) and
in a full suite on mote with `Post "https://127.0.0.1:…": EOF`. It is a
product gap, not the test's timing: the same happens to a user whose
proxy or TUN closes a new connection right after the TLS handshake while
the machine is busy.

Cause, read from Go 1.26.8's net/http transport: the issue's guess (the
8 MiB write had begun) is the other way round. Once the write goroutine
starts the body, any write failure is kept as the request's error
(doBodyCopy's bodyReadError, then mapRoundTripError's req.err), so
replayable sees a write error and sends again. A bare "EOF" comes only
when the reader sees the close and closes the connection before the
write goroutine has picked the request up at all (writeLoop takes
closech): nothing was written, WroteRequest never fires, and Go turns
nothingWrittenError{transportReadFromServerError{EOF}} into io.EOF. Go
doesn't retry on a new connection, and closedBeforeSent took only write
errors, so the turn failed as a 502 counted against the account.

replayable now also sends again on a new HTTP/1.1 connection that ended
with "EOF" or a read error (a reset) while the request's write had not
finished: no WroteRequest without an error (httptrace). Once Go has
written the whole request the same end may follow a vendor that read it,
and that is never sent again, as before.

Tests: TestEndedBeforeWriteBeganIsSentAgain gives replayable what Go's
transport gives it on that path (GotConn new, no WroteRequest, io.EOF or
a read reset) twice, then an answer. A real transport can't be held at
that point from outside net/http (a held connection write already counts
as a body write error), so the order is injected with a fake transport,
not left to the scheduler. TestEndedAfterWriteIsNotSentAgain gives it a
whole write then EOF. TestClosedAfterSentIsNotSentAgain now also ends the
real TLS connection cleanly (EOF) after reading the whole 8 MiB request,
besides the reset.

Run (all on mote via mote-run, at this tree on 778b8e075):
- Before the fix (upstream_transport.go at 778b8e075, new tests in):
  TestEndedBeforeWriteBeganIsSentAgain red 3 of 3 with the issue's error,
  `Post "https://127.0.0.1:1/backend-api/codex/responses": EOF`.
- go test -race -count=50 -run 'TestClosed|TestEnded' ./internal/gateway/:
  ok.
- go test -timeout 45m -count=1 ./internal/gateway/...: ok (internal/gateway 859s; exit 0)
- gofmt -l .: clean. go vet ./internal/gateway/, GOOS=linux go vet -tags
  nogui ./..., GOOS=windows go vet ./...: ok.

Broken by hand: without `wrote.Load() ||` (an EOF resent whatever was
written), TestEndedAfterWriteIsNotSentAgain goes red (err nil, the request
sent again) and TestClosedAfterSentIsNotSentAgain goes red for both the
reset and the clean end (3 connections, called unsent), 3 of 3. With
endedUnwritten taken out (the old code), TestEndedBeforeWriteBeganIsSentAgain
goes red as above.

Measured, not injected: 1,200 real closes after the handshake on mote,
with -race, -cpu 1,2,4 and 20 busy loops beside them, gave write errors
and one "server closed idle connection", no bare EOF; the race is rare,
as on CI.

Not tried: a real TUN proxy.

Fixes #5519
This commit is contained in:
yetone
2026-11-08 05:56:59 +08:00
parent 778b8e0753
commit d4a6e9315b
2 changed files with 126 additions and 24 deletions
+100 -19
View File
@@ -9,25 +9,35 @@ import (
"net"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"strconv"
"strings"
"sync/atomic"
"syscall"
"testing"
"time"
)
// closingUpstream is a TLS vendor whose first closeFirst new connections are
// ended by the far side as soon as the handshake is done, before the
// request is read (a TUN proxy's fake IP doing so, dealyang_ on X), or,
// with afterSent, once the whole request was read. The rest are
// answered 200 with the body's length.
// request is read (a TUN proxy's fake IP doing so, dealyang_ on X), or
// once the whole request was read: reset (afterSentReset) or ended
// (afterSentEnd). The rest are answered 200 with the body's length.
type closingUpstream struct {
addr string
accepts atomic.Int32
answered atomic.Int32
}
func newClosingUpstream(t *testing.T, closeFirst int32, afterSent bool) *closingUpstream {
type closeWhen int
const (
atHandshake closeWhen = iota
afterSentReset
afterSentEnd
)
func newClosingUpstream(t *testing.T, closeFirst int32, when closeWhen) *closingUpstream {
t.Helper()
srv := httptest.NewUnstartedServer(nil)
srv.StartTLS()
@@ -55,11 +65,15 @@ func newClosingUpstream(t *testing.T, closeFirst int32, afterSent bool) *closing
return
}
if n <= closeFirst {
if afterSent {
// the whole request, then reset
if when != atHandshake {
// the whole request, then reset or ended
if r, err := http.ReadRequest(bufio.NewReader(tc)); err == nil {
io.Copy(io.Discard, r.Body)
}
if when == afterSentEnd {
tc.Close()
return
}
c.(*net.TCPConn).SetLinger(0)
c.Close()
return
@@ -142,7 +156,7 @@ func closedUnsentPost(t *testing.T, cl *http.Client, addr string) (*http.Respons
// before a byte of the request went out, is not the vendor's answer: the
// request goes again on another new connection and is answered, whole.
func TestClosedBeforeSentIsSentAgain(t *testing.T) {
u := newClosingUpstream(t, 2, false)
u := newClosingUpstream(t, 2, atHandshake)
res, err := closedUnsentPost(t, closedUnsentClient(t), u.addr)
if err != nil {
t.Fatalf("a request whose first two new connections were closed before it was sent failed: %v", err)
@@ -157,10 +171,74 @@ func TestClosedBeforeSentIsSentAgain(t *testing.T) {
}
}
// goEnded is Go's HTTP/1.1 transport as replayable sees it when a new
// connection ends under a request: GotConn for a new connection, then,
// if wrote, WroteRequest without an error, then err. The first ends
// calls end so, the rest are answered 200.
type goEnded struct {
ends int32
wrote bool
err error
tries atomic.Int32
}
func (g *goEnded) RoundTrip(r *http.Request) (*http.Response, error) {
trace := httptrace.ContextClientTrace(r.Context())
if trace.GotConn != nil {
trace.GotConn(httptrace.GotConnInfo{})
}
if g.tries.Add(1) > g.ends {
return &http.Response{StatusCode: 200, Body: http.NoBody, Request: r}, nil
}
if g.wrote && trace.WroteRequest != nil {
trace.WroteRequest(httptrace.WroteRequestInfo{})
}
return nil, g.err
}
// On a busy machine the reader can see a proxy's close right after the
// handshake before Go's write goroutine has run: Go then drops the
// request unwritten (no WroteRequest) and says only "EOF", not a write
// error (#5519, red on CI's race run). Nothing went out, so the request
// goes again; so too for a reset seen first.
func TestEndedBeforeWriteBeganIsSentAgain(t *testing.T) {
closedUnsentClient(t) // the short pauses
reset := &net.OpError{Op: "read", Net: "tcp", Err: syscall.ECONNRESET}
for _, end := range []error{io.EOF, reset} {
g := &goEnded{ends: 2, err: end}
res, err := closedUnsentPost(t, &http.Client{Transport: replayable{g}}, "127.0.0.1:1")
if err != nil {
t.Fatalf("a request whose first two new connections ended (%v) before its write began failed: %v", end, err)
}
res.Body.Close()
if n := g.tries.Load(); n != 3 {
t.Errorf("%v: %d tries, want 3: two ended, one answered", end, n)
}
}
}
// Once Go has written the whole request, the same end may follow a
// vendor that read it and acted on it: not sent again.
func TestEndedAfterWriteIsNotSentAgain(t *testing.T) {
closedUnsentClient(t)
g := &goEnded{ends: 2, wrote: true, err: io.EOF}
_, err := closedUnsentPost(t, &http.Client{Transport: replayable{g}}, "127.0.0.1:1")
if !errors.Is(err, io.EOF) {
t.Fatalf("err = %v, want the EOF as it was", err)
}
var cu errClosedUnsent
if errors.As(err, &cu) {
t.Errorf("err = %v: a request written whole was called unsent", err)
}
if n := g.tries.Load(); n != 1 {
t.Errorf("%d tries, want 1", n)
}
}
// Closed on every try, the request fails with why, in the words the
// routing reads to rest nobody for it.
func TestClosedBeforeSentEveryTimeSaysWhy(t *testing.T) {
u := newClosingUpstream(t, 100, false)
u := newClosingUpstream(t, 100, atHandshake)
_, err := closedUnsentPost(t, closedUnsentClient(t), u.addr)
var cu errClosedUnsent
if !errors.As(err, &cu) {
@@ -179,18 +257,21 @@ func TestClosedBeforeSentEveryTimeSaysWhy(t *testing.T) {
// A connection closed after the vendor read the whole request may have
// had it acted on: that is not sent again here.
// Reset or ended ("EOF"), the same.
func TestClosedAfterSentIsNotSentAgain(t *testing.T) {
u := newClosingUpstream(t, 100, true)
_, err := closedUnsentPost(t, closedUnsentClient(t), u.addr)
if err == nil {
t.Fatal("no error from a connection closed under the request")
}
var cu errClosedUnsent
if errors.As(err, &cu) {
t.Errorf("err = %v: a request whose bytes went out was called unsent", err)
}
if n := u.accepts.Load(); n != 1 {
t.Errorf("%d connections for a request the vendor had read whole, want 1 (%v)", n, err)
for _, when := range []closeWhen{afterSentReset, afterSentEnd} {
u := newClosingUpstream(t, 100, when)
_, err := closedUnsentPost(t, closedUnsentClient(t), u.addr)
if err == nil {
t.Fatalf("close %d: no error from a connection closed under the request", when)
}
var cu errClosedUnsent
if errors.As(err, &cu) {
t.Errorf("close %d: err = %v: a request whose bytes went out was called unsent", when, err)
}
if n := u.accepts.Load(); n != 1 {
t.Errorf("close %d: %d connections for a request the vendor had read whole, want 1 (%v)", when, n, err)
}
}
}
+26 -5
View File
@@ -173,7 +173,10 @@ type replayable struct{ http.RoundTripper }
// one: "write tcp …: use of closed network connection". The vendor never
// had the whole request, so it is sent again on another new connection,
// after a moment, up to unsentAgain times (dealyang_ on X: a Codex turn through a TUN proxy's
// fake IP, 198.18.0.17, failed with it on every reconnect). Still closed,
// fake IP, 198.18.0.17, failed with it on every reconnect). When the
// reader saw the close before the write began, as on a busy machine, Go
// says only "EOF"; that too goes again, as long as the request's write
// had not finished (#5519). Still closed,
// the error says why (errClosedUnsent), and the routing rests nobody for
// it (failProxy).
func (t replayable) RoundTrip(req *http.Request) (*http.Response, error) {
@@ -189,16 +192,19 @@ func (t replayable) RoundTrip(req *http.Request) (*http.Response, error) {
r.Header["X-Idempotency-Key"] = nil
}
for n := 0; ; n++ {
var fresh, h2 atomic.Bool
var fresh, h2, wrote atomic.Bool
trace := &httptrace.ClientTrace{GotConn: func(i httptrace.GotConnInfo) {
fresh.Store(!i.Reused)
if tc, ok := i.Conn.(interface{ ConnectionState() tls.ConnectionState }); ok {
h2.Store(tc.ConnectionState().NegotiatedProtocol == "h2")
}
}, WroteRequest: func(i httptrace.WroteRequestInfo) {
wrote.Store(i.Err == nil)
}}
try := r.WithContext(httptrace.WithClientTrace(r.Context(), trace))
res, err := t.RoundTripper.RoundTrip(try)
if err == nil || !fresh.Load() || h2.Load() || !closedBeforeSent(err) || req.Context().Err() != nil {
if err == nil || !fresh.Load() || h2.Load() || req.Context().Err() != nil ||
!closedBeforeSent(err) && (wrote.Load() || !endedUnwritten(err)) {
return res, err
}
if n >= len(unsentAgain) || (r.Body != nil && r.Body != http.NoBody && r.GetBody == nil) {
@@ -235,14 +241,29 @@ var unsentAgain = []time.Duration{250 * time.Millisecond, time.Second}
// "nothing written" doesn't hold over TLS: a server had read 1186 bytes
// of a request Go called unwritten.) A TLS connection the reader closed
// first fails the write with a bare net.ErrClosed; the reader's own end is
// "EOF" or a read error. A close the reader saw before the write began is
// Go's errServerClosedIdle (seen on Windows).
// "EOF" or a read error, read by endedUnwritten. A close the reader saw
// before the request was handed to the connection is Go's
// errServerClosedIdle (seen on Windows).
func closedBeforeSent(err error) bool {
var op *net.OpError
return errors.As(err, &op) && op.Op == "write" || errors.Is(err, net.ErrClosed) ||
strings.Contains(err.Error(), "http: server closed idle connection")
}
// endedUnwritten says err is the reader's end of a connection the far
// side closed — "EOF", or a read error such as a reset — which counts as
// closed before sent only while the request's write had not finished
// (no WroteRequest without an error): on a busy machine Go's write
// goroutine may not have run yet when a proxy's close right after the
// handshake arrives, so the reader sees the end first and Go returns a
// bare "EOF", not a write error (#5519). Once the whole request was
// written, the same end may follow a vendor that read and acted on it,
// and it is never sent again here.
func endedUnwritten(err error) bool {
var op *net.OpError
return errors.Is(err, io.EOF) || errors.As(err, &op) && op.Op == "read" && !op.Timeout()
}
// errClosedUnsent is a request's error once every new connection it was
// tried on was closed before the whole of it was sent: what went wrong and
// where to look, read by failure as nobody's fault (closedUnsentWords).