gateway: a silent HTTP/2 connection to a vendor is pinged and dropped (#2843)

pinewhite (#2843, v0.1.1279, Linux): for ~30 minutes every request to
group/auto-deepseek-v4-1-flash hung with no first byte. The WorkBuddy
member was resting on a 429, so they all went to ClinePass, and usage
shows only 499s with in=0. A restart answered the same request in 1.6s.

Cause: the gateway's transport (upstreamTransport) speaks HTTP/2 to
any vendor that offers it, so every request to api.cline.bot shares one
connection. It had no HTTP/2 health check. A connection that goes silent
without closing (a local proxy whose own way out died, or a NAT that
forgot the flow) stays in the pool. Every new request is multiplexed
onto it and waits for the 10-minute ResponseHeaderTimeout while the
kernel takes the writes. The agent gives up first, so nothing fails over
and nothing rests the member. Restarting dropped the connection.

Fix: netproxy.HTTP2Health() (SendPingTimeout 20s, PingTimeout 10s) on
upstreamTransport. Go now pings a connection that has had no frame for
20s and closes it when no answer comes within 10s. The requests on it
fail as a 502 ("http2: client connection lost"), so a group moves on,
and the next request dials a new connection. A live vendor answers a
ping whatever its streams are doing, so a long wait for a first byte is
not cut. The same setting goes on http.DefaultTransport in
netproxy.Install, the sibling pool that usage cards, catalogs and
sign-ins use. Not covered: requests a plugin sends from Bun.

Tests (new):
- TestSilentHTTP2ConnectionIsDropped: an HTTP/2 TLS httptest vendor
  behind a TCP relay that can go silent on its open connections (it
  takes writes, passes nothing). After the relay goes silent, a request
  must end well inside 10s, and the next one must succeed on a second
  connection.
- TestGroupMovesOnFromSilentHTTP2Connection: the same through the real
  Handler, with an ordered group a/m then b/m. Once a's connection is
  silent, the request must get b's reply.
- TestInstallChecksHTTP2Connections (netproxy).

What was run (worktree on origin/main 1a3b92688, sandbox HOME, pinned
GOCACHE/GOMODCACHE, go1.26.8 darwin/arm64):
- Red without the fix (HTTP2 lines removed, tests kept):
  TestSilentHTTP2ConnectionIsDropped FAIL "hung 10.003s, until the
  client gave up: context deadline exceeded";
  TestGroupMovesOnFromSilentHTTP2Connection FAIL "200 <empty> after
  10.005s; want b's reply"; TestInstallChecksHTTP2Connections FAIL
  "HTTP/2 after Install: <nil>".
- Green with it: those, TestCodexBackendOverHTTP1 and the Stale tests,
  -race -count=3: ok.
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok. go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build: ok.
- go test -timeout 45m ./...: 59 packages ok. The machine's load average
  was 400-460 (other sessions' GUI suites and builds).
  internal/agent, internal/gateway and internal/library hit the 45m
  alarm while a test that had just started was running (0-40s in), not
  stuck in one test. Four tests failed on a time bound:
  TestIntentClassifierGroup, TestClaudeAccountsSpentFallBackToCodex
  (gateway), TestSetAnswersWhileDevinAndProvidersHang (gui; a set took
  18s against its bar) and TestGatewayHookWaitsForStartingHost (plugin).
  None of them uses HTTP/2. Rerun alone on this change: gateway,
  gui and plugin ok. internal/library alone: ok
  (2220s). internal/agent alone hit 45m again at load ~400, as filed
  in #2723/#2544 (it doesn't call netproxy.Install or upstreamTransport
  in a test this touches). The reds are filed: #1813, #2858/#2859,
  #1375, #2723/#2544, #2853, #2870, and #2871 (new, the plugin one).

Not verified: no real ClinePass account behind a proxy that goes silent,
so the reporter's path is reproduced with an injected silent relay, not
seen live. Not tried on Linux or Windows beyond vet and build. The GUI
is not touched, so the GUI suite was not run.
This commit is contained in:
yetone
2026-10-19 08:00:04 +08:00
parent 47eb42f1a1
commit 94919109cb
5 changed files with 281 additions and 2 deletions
File diff suppressed because one or more lines are too long
+233
View File
@@ -0,0 +1,233 @@
package gateway
import (
"context"
"crypto/tls"
"crypto/x509"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/provider"
)
// silentPath sits between the gateway and a vendor and can go silent on
// the connections open through it: it goes on taking what the gateway
// writes, so every write succeeds, and passes nothing either way, as a
// local proxy whose own way out died, or a NAT that forgot the flow, does.
// A connection opened after it went silent passes as before.
type silentPath struct {
ln net.Listener
to string
mu sync.Mutex
open []*silentConn
wg sync.WaitGroup
}
type silentConn struct {
a, b net.Conn
silent atomic.Bool
}
func newSilentPath(t *testing.T, to string) *silentPath {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
p := &silentPath{ln: ln, to: to}
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
}
c := &silentConn{a: a, b: b}
p.mu.Lock()
p.open = append(p.open, c)
p.mu.Unlock()
pipe := func(dst, src net.Conn) {
defer p.wg.Done()
buf := make([]byte, 32<<10)
for {
n, err := src.Read(buf)
if n > 0 && !c.silent.Load() {
if _, werr := dst.Write(buf[:n]); werr != nil {
return
}
}
if err != nil {
return
}
}
}
p.wg.Add(2)
go pipe(b, a)
go pipe(a, b)
}
}()
t.Cleanup(func() {
p.ln.Close()
p.mu.Lock()
for _, c := range p.open {
c.a.Close()
c.b.Close()
}
p.mu.Unlock()
p.wg.Wait()
})
return p
}
// hush silences every connection open now.
func (p *silentPath) hush() int {
p.mu.Lock()
defer p.mu.Unlock()
for _, c := range p.open {
c.silent.Store(true)
}
return len(p.open)
}
func (p *silentPath) conns() int {
p.mu.Lock()
defer p.mu.Unlock()
return len(p.open)
}
// quickPings has the gateway's transports, made after it, ping a quiet
// HTTP/2 connection after 200ms and drop it 300ms later, and trust
// vendor's certificate.
func quickPings(t *testing.T, vendor *httptest.Server) {
pool := x509.NewCertPool()
pool.AddCert(vendor.Certificate())
wasTLS, wasAfter, wasWait := upstreamTLS, netproxy.PingAfter, netproxy.PingWait
upstreamTLS = &tls.Config{RootCAs: pool, ServerName: "127.0.0.1"}
netproxy.PingAfter, netproxy.PingWait = 200*time.Millisecond, 300*time.Millisecond
t.Cleanup(func() { upstreamTLS, netproxy.PingAfter, netproxy.PingWait = wasTLS, wasAfter, wasWait })
}
func h2Vendor(t *testing.T, h http.HandlerFunc) *httptest.Server {
vendor := httptest.NewUnstartedServer(h)
vendor.EnableHTTP2 = true
vendor.StartTLS()
t.Cleanup(vendor.Close)
return vendor
}
// #2843 (pinewhite): every request of a group to ClinePass hung with no
// first byte for half an hour, and a restart answered the same request in
// 1.6s. Over HTTP/2 every request to a vendor shares one connection, and
// one gone silent without closing (a proxy's way out died, a NAT dropped
// the flow) was kept and given every new request, each waiting up to the
// 10-minute ResponseHeaderTimeout, while the kernel took the writes. The
// gateway's transport now pings a connection quiet for a while and drops
// it when the ping goes unanswered: the request on it fails (so the group
// moves on) and the next one dials a new connection.
func TestSilentHTTP2ConnectionIsDropped(t *testing.T) {
fresh(t)
vendor := h2Vendor(t, func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
io.WriteString(w, r.Proto)
})
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(within time.Duration) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), within)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, u, nil)
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
}
if got, err := ask(10 * time.Second); err != nil || got != "HTTP/2.0" {
t.Fatalf("first request: %q, %v; want HTTP/2.0", got, err)
}
if n := path.hush(); n != 1 {
t.Fatalf("%d connections open before the path went silent, want 1", n)
}
// the stalled request ends well before a client gives up (curl -m 55
// in the report), here 10s against a ping bound of 0.5s
began := time.Now()
_, err := ask(10 * time.Second)
if err == nil {
t.Fatal("a request on the silent connection was answered")
}
if d := time.Since(began); d >= 10*time.Second {
t.Fatalf("a request on the silent connection hung %v, until the client gave up: %v", d, err)
}
// and the one after it goes out on a new connection, without a restart
if got, err := ask(10 * time.Second); err != nil || got != "HTTP/2.0" {
t.Fatalf("request after the silent connection: %q, %v; want HTTP/2.0 on a new connection", got, err)
}
if n := path.conns(); n != 2 {
t.Errorf("%d connections dialled, want 2: the silent one and a new one", n)
}
}
// The same through a routing group, as in the report: a group's first
// member on a connection gone silent is given up on and the next member
// answers, where before the request hung until its agent gave up and the
// next one hung the same way.
func TestGroupMovesOnFromSilentHTTP2Connection(t *testing.T) {
fresh(t)
vendor := h2Vendor(t, func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"a","choices":[{"message":{"role":"assistant","content":"from a"}}]}`)
})
path := newSilentPath(t, vendor.Listener.Addr().String())
quickPings(t, vendor)
if err := provider.Save(provider.Provider{ID: "a", Name: "A", Key: "k", Models: []string{"m"},
Chat: "https://" + path.ln.Addr().String() + "/v1"}); err != nil {
t.Fatal(err)
}
serveOn(t, "b", "k", []string{"m"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"b","choices":[{"message":{"role":"assistant","content":"from b"}}]}`)
}))
if err := provider.SaveGroup(provider.Group{Name: "Auto", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
s := New()
t.Cleanup(s.client.CloseIdleConnections)
ask := func() (int, string, time.Duration) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/chat/completions",
strings.NewReader(`{"model":"group/auto","messages":[{"role":"user","content":"hi"}]}`)).WithContext(ctx)
began := time.Now()
s.Handler().ServeHTTP(rec, req)
return rec.Code, rec.Body.String(), time.Since(began)
}
if code, body, _ := ask(); code != http.StatusOK || !strings.Contains(body, "from a") {
t.Fatalf("first group request: %d %s; want a's reply", code, body)
}
path.hush()
code, body, took := ask()
if code != http.StatusOK || !strings.Contains(body, "from b") {
t.Fatalf("group request with a's connection silent: %d %s after %v; want b's reply", code, body, took)
}
}
+2
View File
@@ -26,6 +26,8 @@ func upstreamTransport() http.RoundTripper {
IdleConnTimeout: 90 * time.Second,
ForceAttemptHTTP2: true,
TLSClientConfig: upstreamTLS,
// a silent HTTP/2 connection is pinged and dropped (#2843)
HTTP2: netproxy.HTTP2Health(),
})}
}
+23
View File
@@ -0,0 +1,23 @@
package netproxy
import (
"net/http"
"testing"
)
// http.DefaultClient's HTTP/2 connections (usage cards, catalogs,
// sign-ins) are checked as the gateway's are: one gone silent is pinged
// and dropped rather than given every request after it (#2843).
func TestInstallChecksHTTP2Connections(t *testing.T) {
d, ok := http.DefaultTransport.(*http.Transport)
if !ok {
t.Skip("http.DefaultTransport is not an *http.Transport")
}
was, wasClient, wasProxy := d.HTTP2, http.DefaultClient.Transport, d.Proxy
t.Cleanup(func() { d.HTTP2, http.DefaultClient.Transport, d.Proxy = was, wasClient, wasProxy })
d.HTTP2 = nil
Install()
if d.HTTP2 == nil || d.HTTP2.SendPingTimeout != PingAfter || d.HTTP2.PingTimeout != PingWait {
t.Fatalf("http.DefaultTransport's HTTP/2 after Install: %+v; want pings after %v, dropped after %v", d.HTTP2, PingAfter, PingWait)
}
}
+22 -1
View File
@@ -25,14 +25,35 @@ import (
// Install routes http.DefaultTransport (and so http.DefaultClient) through
// Func, and http.DefaultClient's requests made on a provider's behalf
// (With) through a transport of that provider's proxy (Dispatch).
// (With) through a transport of that provider's proxy (Dispatch). Its
// HTTP/2 connections are checked as the gateway's are (HTTP2Health).
func Install() {
if t, ok := http.DefaultTransport.(*http.Transport); ok {
t.Proxy = Func
if t.HTTP2 == nil {
t.HTTP2 = HTTP2Health()
}
http.DefaultClient.Transport = Dispatch(t)
}
}
// PingAfter and PingWait: an HTTP/2 connection that has had no frame for
// PingAfter is pinged, and dropped when no answer comes within PingWait.
var PingAfter, PingWait = 20 * time.Second, 10 * time.Second
// HTTP2Health is the HTTP/2 setting of a transport to the vendors. Every
// request to one host shares one HTTP/2 connection, and one gone silent
// without closing (a proxy's way out died, a NAT forgot the flow) was
// given every new request, each waiting for its transport's
// ResponseHeaderTimeout while the kernel took the writes, until a restart
// (#2843). A ping finds it, and the requests on it fail, so a group moves
// on and the next request dials anew. A live vendor answers a ping
// whatever its streams are doing, so a long wait for a first byte is
// never cut by it.
func HTTP2Health() *http.HTTP2Config {
return &http.HTTP2Config{SendPingTimeout: PingAfter, PingTimeout: PingWait}
}
// Func is an http.Transport Proxy function: the proxy the request's
// context names (With), or else the global one, which a host on the
// user's own network goes around (onLAN).