gateway: a large body whose h2 ping was lost goes again unpinged (#3909)
yxd-ym, on a 2-10KB/s uplink: every large turn to a Google upstream (Antigravity, Vertex, AI Studio) failed with "http2: client connection lost" after 35-45s while its body was still uploading, and the group's failover uploaded the same ~680KB again to every member. A small turn on the same uplink was answered in 14s. Cause (skygunner's diagnosis): the vendor transport's HTTP/2 health check (netproxy.HTTP2Health, #2843) pings a connection with no frame received for 20s and drops it when no answer comes in 10s. The ping is written behind the body's own DATA, so on a slow uplink its answer can only come after the last byte, and the check closed a working connection. skygunner's branch (8eaf63866) sent every body of 64KB or more, or of no stated length, to a transport without the ping. That is most agent traffic, and it takes #2843's protection away from it: a silent connection whose kernel takes a body that fits the send buffer then waits the 10-minute header wait (TestLargeBodyOnSilentConnectionIsSentAgain below hangs to its 10s bound on that branch). The change keeps the ping on every request by default. A large body (uploading) whose try fails with Go's lost-ping error (lostPing, closeForLostPing's "http2: client connection lost") is sent once more, through GetBody (provider.SetBody keeps it until LetGo), through uploadTransport: a new connection, no ping, given up on when a write moves no bytes for a minute (WriteByteTimeout); the response header wait still ends a vendor that never answers. For 30 minutes after (slowFor, drawsApart.slow, per transport), large bodies go there at once, so a slow uplink loses one try per half hour, not one per turn. A connection that really was dead costs nothing more: the retry dials a new one either way. Small bodies and drawings are unchanged. Co-authored-by: vincent <vincent@users.noreply.github.com> Reported-by: yxd-ym What was run, on mote at origin/mainea53eb126+ this: - gofmt -l internal/gateway: nothing. go vet ./internal/gateway/ ./internal/netproxy/, and GOOS=linux / GOOS=windows go vet ./internal/gateway/: nothing. - TestUploadStillUnderwayIsNotCutByHealthPing (skygunner's: 262212 bytes paced at 64KB/s, ping after 200ms, dropped 300ms later), TestSlowUplinkSkipsTheLostTry (new: the first large body reaches the vendor twice, the second once, body given through provider.SetBody), TestLargeBodyOnSilentConnectionIsSentAgain (new: 128KB body after the path went silent is answered on a second connection), TestSilentHTTP2ConnectionIsDropped, TestGroupMovesOnFromSilentHTTP2Connection: -race -count=5 all PASS (80s); -count=3 without -race PASS. - Broken by hand: - skygunner's transport alone: TestSlowUplinkSkipsTheLostTry FAIL ("saw 1 tries of the first body, want 2"), TestLargeBodyOnSilentConnection IsSentAgain FAIL (context deadline exceeded at 10.01s). - the retry removed: TestUploadStillUnderwayIsNotCutByHealthPing FAIL in 0.57s ("http2: client connection lost", vendor "client disconnected"), TestLargeBodyOnSilentConnectionIsSentAgain FAIL (client connection lost). - go test ./internal/gateway/ ./internal/netproxy/ ./internal/provider/ -count=1 -timeout 45m: ok (gateway 546s, netproxy 3.7s, provider 118s). Rebased ontof02d92c7b(no change to these files but a doc line elsewhere in gateway-routing.md): gofmt, go vet (darwin, linux, windows) ./internal/gateway/, and the five tests above with TestPromptText* and *Unmasked* -count=2: ok (32s). Not tried: the reporter's uplink and a real Google upstream; the path is a paced local one.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -0,0 +1,234 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// slowUplink sits between the gateway and a vendor like a saturated
|
||||
// uplink: the gateway's bytes get to the vendor at rate bytes a second,
|
||||
// while the vendor's own pass at once. The gateway's writes still land in
|
||||
// a socket, as they do on a slow link until its send buffer fills, and the
|
||||
// vendor hears nothing for as long as the body takes.
|
||||
type slowUplink struct {
|
||||
ln net.Listener
|
||||
to string
|
||||
rate int
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
open []net.Conn
|
||||
}
|
||||
|
||||
func newSlowUplink(t *testing.T, to string, rate int) *slowUplink {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := &slowUplink{ln: ln, to: to, rate: rate}
|
||||
p.wg.Add(1)
|
||||
go func() {
|
||||
defer p.wg.Done()
|
||||
for {
|
||||
a, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
b, err := net.Dial("tcp", to)
|
||||
if err != nil {
|
||||
a.Close()
|
||||
continue
|
||||
}
|
||||
p.mu.Lock()
|
||||
p.open = append(p.open, a, b)
|
||||
p.mu.Unlock()
|
||||
p.wg.Add(2)
|
||||
go p.paced(b, a)
|
||||
go p.splat(a, b)
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
p.ln.Close()
|
||||
p.mu.Lock()
|
||||
for _, c := range p.open {
|
||||
c.Close()
|
||||
}
|
||||
p.mu.Unlock()
|
||||
p.wg.Wait()
|
||||
})
|
||||
return p
|
||||
}
|
||||
|
||||
// paced carries what the gateway wrote to the vendor a twentieth of a
|
||||
// second of the uplink at a time.
|
||||
func (p *slowUplink) paced(dst, src net.Conn) {
|
||||
defer p.wg.Done()
|
||||
chunk := p.rate / 20
|
||||
if chunk < 1 {
|
||||
chunk = 1
|
||||
}
|
||||
buf := make([]byte, chunk)
|
||||
for {
|
||||
n, err := src.Read(buf)
|
||||
if n > 0 {
|
||||
if _, werr := dst.Write(buf[:n]); werr != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *slowUplink) splat(dst, src net.Conn) {
|
||||
defer p.wg.Done()
|
||||
io.Copy(dst, src)
|
||||
}
|
||||
|
||||
// #3909 (yxd-ym): a 175k-token turn (~680KB) on a 2-10KB/s uplink failed
|
||||
// every try with "http2: client connection lost" after 35-45s, while the
|
||||
// same uplink answered a small turn. The body is still going out, so the
|
||||
// vendor sends nothing; the read-idle ping is written behind the body's
|
||||
// own DATA and can only be answered once the last byte arrives, so the
|
||||
// health check closed a connection that was working. A body that may still
|
||||
// be under way is not watched by that ping.
|
||||
func TestUploadStillUnderwayIsNotCutByHealthPing(t *testing.T) {
|
||||
fresh(t)
|
||||
body := []byte(`{"model":"gemini-4-argon","messages":[{"role":"user","content":"` +
|
||||
strings.Repeat("a", 256<<10) + `"}]}`)
|
||||
vendor := h2Vendor(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
n, err := io.Copy(io.Discard, r.Body)
|
||||
if err != nil {
|
||||
t.Errorf("the vendor reading the body: %v", err)
|
||||
}
|
||||
fmt.Fprintf(w, "%s %d", r.Proto, n)
|
||||
})
|
||||
// 256KB at 64KB/s: the body is still being delivered for about 4s, and
|
||||
// the vendor's frames arrive more than the 0.5s a ping is given here
|
||||
// apart, as they do at 2KB/s in the report
|
||||
path := newSlowUplink(t, vendor.Listener.Addr().String(), 64<<10)
|
||||
quickPings(t, vendor)
|
||||
s := New()
|
||||
t.Cleanup(s.client.CloseIdleConnections)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
"https://"+path.ln.Addr().String()+"/v1/chat/completions", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
res, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("a %d-byte body an uplink was still delivering failed: %v; want the vendor's reply", len(body), err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
got, err := io.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := fmt.Sprintf("HTTP/2.0 %d", len(body)); string(got) != want {
|
||||
t.Fatalf("the vendor read %q; want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// After the first lost ping under a large body, the large bodies after it
|
||||
// go out unpinged at once, without a try lost first: one request reaches
|
||||
// the vendor per turn.
|
||||
func TestSlowUplinkSkipsTheLostTry(t *testing.T) {
|
||||
fresh(t)
|
||||
body := []byte(`{"model":"gemini-4-argon","messages":[{"role":"user","content":"` +
|
||||
strings.Repeat("a", 256<<10) + `"}]}`)
|
||||
var tries atomic.Int32
|
||||
vendor := h2Vendor(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
tries.Add(1)
|
||||
io.Copy(io.Discard, r.Body)
|
||||
io.WriteString(w, r.Proto)
|
||||
})
|
||||
path := newSlowUplink(t, vendor.Listener.Addr().String(), 64<<10)
|
||||
quickPings(t, vendor)
|
||||
s := New()
|
||||
t.Cleanup(s.client.CloseIdleConnections)
|
||||
send := func() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
// the body as the gateway gives a vendor's request one
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
"https://"+path.ln.Addr().String()+"/v1/chat/completions", nil)
|
||||
provider.SetBody(req, body)
|
||||
defer provider.LetGo(req)
|
||||
res, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
_, err = io.ReadAll(res.Body)
|
||||
return err
|
||||
}
|
||||
if err := send(); err != nil {
|
||||
t.Fatalf("first large body: %v", err)
|
||||
}
|
||||
if n := tries.Load(); n != 2 {
|
||||
t.Fatalf("the vendor saw %d tries of the first body, want 2: one cut by the ping, one unpinged", n)
|
||||
}
|
||||
if err := send(); err != nil {
|
||||
t.Fatalf("second large body: %v", err)
|
||||
}
|
||||
if n := tries.Load(); n != 3 {
|
||||
t.Errorf("the vendor saw %d tries in all, want 3: the second body went unpinged at once", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A large body keeps #2843's check: on a connection gone silent, whose
|
||||
// kernel takes the body whole, it is not left waiting the 10-minute header
|
||||
// wait, but cut by the ping and sent again on a new connection.
|
||||
func TestLargeBodyOnSilentConnectionIsSentAgain(t *testing.T) {
|
||||
fresh(t)
|
||||
body := []byte(`{"model":"m","messages":[{"role":"user","content":"` +
|
||||
strings.Repeat("a", 128<<10) + `"}]}`)
|
||||
vendor := h2Vendor(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
n, _ := io.Copy(io.Discard, r.Body)
|
||||
fmt.Fprintf(w, "%s %d", r.Proto, n)
|
||||
})
|
||||
path := newSilentPath(t, vendor.Listener.Addr().String())
|
||||
quickPings(t, vendor)
|
||||
s := New()
|
||||
t.Cleanup(s.client.CloseIdleConnections)
|
||||
u := "https://" + path.ln.Addr().String() + "/v1/chat/completions"
|
||||
ask := func() (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(body))
|
||||
res, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, err := io.ReadAll(res.Body)
|
||||
return string(b), err
|
||||
}
|
||||
want := fmt.Sprintf("HTTP/2.0 %d", len(body))
|
||||
if got, err := ask(); err != nil || got != want {
|
||||
t.Fatalf("first request: %q, %v; want %q", got, err, want)
|
||||
}
|
||||
path.hush()
|
||||
if got, err := ask(); err != nil || got != want {
|
||||
t.Fatalf("a large body on the silent connection: %q, %v; want %q on a new connection", got, err, want)
|
||||
}
|
||||
if n := path.conns(); n != 2 {
|
||||
t.Errorf("%d connections dialled, want 2: the silent one and a new one", n)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package gateway
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
@@ -16,7 +18,10 @@ var upstreamTLS *tls.Config
|
||||
// with a proxy of its own is sent through a transport kept for that proxy
|
||||
// (#237), and the ChatGPT backend over HTTP/1.1 (netproxy.HTTP1), a
|
||||
// streamed turn to it over its WebSocket (codexSocket). Every
|
||||
// other vendor is spoken HTTP/2 to wherever it offers it. A request that
|
||||
// other vendor is spoken HTTP/2 to wherever it offers it. A large body
|
||||
// whose connection was dropped for a lost ping goes again through a
|
||||
// transport that does not ping (#3909), and so do the large bodies after
|
||||
// it for a while (slowFor). A request that
|
||||
// finds its kept-alive connection dropped is sent again on a new one
|
||||
// (replayable). A vendor is given upstreamHeaderWait to begin answering,
|
||||
// but for a drawing, which an images API answers only once it has drawn:
|
||||
@@ -24,8 +29,10 @@ var upstreamTLS *tls.Config
|
||||
// Image generation timeout gives it (drawWithin), up to 60 minutes.
|
||||
func upstreamTransport() http.RoundTripper {
|
||||
return drawsApart{
|
||||
any: codexSocket{replayable{netproxy.Dispatch(vendorTransport(upstreamHeaderWait))}},
|
||||
draws: replayable{netproxy.Dispatch(vendorTransport(0))},
|
||||
any: codexSocket{replayable{netproxy.Dispatch(vendorTransport(upstreamHeaderWait))}},
|
||||
draws: replayable{netproxy.Dispatch(vendorTransport(0))},
|
||||
uploads: codexSocket{replayable{netproxy.Dispatch(uploadTransport(upstreamHeaderWait))}},
|
||||
slow: new(atomic.Int64),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +40,23 @@ func upstreamTransport() http.RoundTripper {
|
||||
// request that isn't a drawing.
|
||||
var upstreamHeaderWait = 10 * time.Minute
|
||||
|
||||
// uploadBytes is the body size from which a request goes to a vendor over
|
||||
// a connection the read-idle ping does not watch: on an uplink under about
|
||||
// 3KB/s a body this big is still being delivered when the ping is due
|
||||
// (netproxy.PingAfter), and the ping's answer can only come back after the
|
||||
// last byte, behind the body it was queued behind (netproxy.PingWait after
|
||||
// it). #3909 sent a 175k-token turn, ~680KB, on a 2-10KB/s uplink.
|
||||
var uploadBytes int64 = 64 << 10
|
||||
|
||||
// slowFor is how long, after a large body's connection was dropped for
|
||||
// a lost ping, the large bodies after it skip the ping and its lost try.
|
||||
var slowFor = 30 * time.Minute
|
||||
|
||||
// uploadStall is how long a request's write may put no bytes on its
|
||||
// connection before that connection is given up on: what the read-idle
|
||||
// ping cannot tell apart from a body still being delivered.
|
||||
var uploadStall = time.Minute
|
||||
|
||||
// vendorTransport is a transport to the vendors that gives one wait to
|
||||
// begin answering, none for 0: the request's context then bounds it.
|
||||
func vendorTransport(wait time.Duration) *http.Transport {
|
||||
@@ -48,15 +72,71 @@ func vendorTransport(wait time.Duration) *http.Transport {
|
||||
}
|
||||
}
|
||||
|
||||
// uploadTransport is vendorTransport for a request whose body may still be
|
||||
// under way when the connection has had no frame for a while: an HTTP/2
|
||||
// ping is written behind that body's own DATA, so its answer comes only
|
||||
// after the last byte a slow uplink is still delivering, and the health
|
||||
// check closed a connection that was working (#3909). No ping here; a
|
||||
// write that moves no bytes ends the connection (WriteByteTimeout), and a
|
||||
// vendor that never begins answering is ended by the response header wait.
|
||||
func uploadTransport(wait time.Duration) *http.Transport {
|
||||
t := vendorTransport(wait)
|
||||
t.HTTP2 = &http.HTTP2Config{WriteByteTimeout: uploadStall}
|
||||
return t
|
||||
}
|
||||
|
||||
// uploading says r's body can outlast the vendor's silence: one of a
|
||||
// length nobody stated (written as it is read), or one over uploadBytes.
|
||||
func uploading(r *http.Request) bool {
|
||||
return r.Body != nil && r.Body != http.NoBody &&
|
||||
(r.ContentLength < 0 || r.ContentLength >= uploadBytes)
|
||||
}
|
||||
|
||||
// drawsApart sends a drawing's request (drawWaitOf) through draws, every
|
||||
// other through any.
|
||||
type drawsApart struct{ any, draws http.RoundTripper }
|
||||
// other through any, but for a large body (uploading) on an uplink found
|
||||
// slow: through uploads.
|
||||
//
|
||||
// The ping stays on a large body by default, as a silent connection
|
||||
// (#2843) takes a body that fits its send buffer and answers nothing for
|
||||
// the 10-minute header wait. When the ping is lost under a large body, the
|
||||
// body may still have been on its way (#3909), so it is sent once more
|
||||
// through uploads, on a new connection, and the large bodies until
|
||||
// slowFor has passed go there first. A connection that really was dead
|
||||
// costs nothing more: the new one is dialled either way.
|
||||
type drawsApart struct {
|
||||
any, draws, uploads http.RoundTripper
|
||||
// slow is when the uplink was last found slow, in Unix nanoseconds.
|
||||
slow *atomic.Int64
|
||||
}
|
||||
|
||||
func (t drawsApart) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
if _, ok := drawWaitOf(r.Context()); ok {
|
||||
return t.draws.RoundTrip(r)
|
||||
}
|
||||
return t.any.RoundTrip(r)
|
||||
if !uploading(r) || t.slow == nil {
|
||||
return t.any.RoundTrip(r)
|
||||
}
|
||||
if time.Since(time.Unix(0, t.slow.Load())) < slowFor {
|
||||
return t.uploads.RoundTrip(r)
|
||||
}
|
||||
res, err := t.any.RoundTrip(r)
|
||||
if err == nil || !lostPing(err) || r.GetBody == nil || r.Context().Err() != nil {
|
||||
return res, err
|
||||
}
|
||||
body, gerr := r.GetBody()
|
||||
if gerr != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.slow.Store(time.Now().UnixNano())
|
||||
again := r.Clone(r.Context())
|
||||
again.Body = body
|
||||
return t.uploads.RoundTrip(again)
|
||||
}
|
||||
|
||||
// lostPing says err is Go's HTTP/2 transport closing a connection whose
|
||||
// health ping went unanswered (closeForLostPing).
|
||||
func lostPing(err error) bool {
|
||||
return strings.Contains(err.Error(), "http2: client connection lost")
|
||||
}
|
||||
|
||||
// replayable lets Go's transport send a request again, at once and on a new
|
||||
|
||||
Reference in New Issue
Block a user