Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: a handed-off gateway answers a kept-alive connection's next request rather than closing it under the agent (#3451)

yetone68ab4c06da98
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 377a46180..dfdffee2c 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -631,7 +631,7 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
// loops' next look (#3185)
go filememo.Watch(freshCtx, pluginrt.Path(), settings.Path(), provider.Path(), plugin.ListPath(), plugin.ToolsPath(), access.Path())
go pluginrt.KeepFresh(freshCtx, filememo.OthersEvery, settings.Path(), provider.Path(), plugin.ListPath(), plugin.ToolsPath(), access.Path())
- srv := &http.Server{Handler: s.Front(), ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 5 * time.Minute, ConnState: s.unread.note}
+ srv := &http.Server{Handler: s.closesWhenHandedOff(s.Front()), ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 5 * time.Minute, ConnState: s.unread.note}
// the magpie serving the gateway, and only it, keeps the saved accounts
// signed in, so two never refresh one sign-in at once
go provider.KeepLoginsAlive(ctx)
@@ -695,9 +695,9 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
defer cancel()
if s.handingOver() {
// another magpie takes every connection from here: this one
- // stops taking them, and each one it took has its first
- // request read before Shutdown, which closes one it reads
- // after it began unanswered (#3568)
+ // stops taking them, and each one it took, new or kept alive,
+ // has its next request read before Shutdown, which closes one
+ // it reads after it began unanswered (#3568, #3451)
s.stopAccepting()
s.unread.wait(c)
}
diff --git a/internal/gateway/handover.go b/internal/gateway/handover.go
index 6a4339b2f..3a3e3c8d8 100644
--- a/internal/gateway/handover.go
+++ b/internal/gateway/handover.go
@@ -175,6 +175,19 @@ func (s *Server) stopAccepting() {
}
}
+// closesWhenHandedOff has each reply the gateway gives once it takes no
+// connection (stopAccepting) close its connection, so the agent's next
+// request dials the magpie serving the port after this one rather than
+// waiting on a connection this one's end closes (unreadConns).
+func (s *Server) closesWhenHandedOff(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if s.notAccepting.Load() {
+ w.Header().Set("Connection", "close")
+ }
+ h.ServeHTTP(w, r)
+ })
+}
+
// handingOver is whether another magpie serves the port once this
// gateway ends: it was handed off, or `make dev` started one beside it.
func (s *Server) handingOver() bool { return Handover || s.handedOff.Load() }
@@ -192,30 +205,40 @@ func (s *Server) drainFor() time.Duration {
// nothing for 5s is idle.
var unreadWait = 5 * time.Second
-// unreadConns are the connections the gateway took whose first request it
-// hasn't read yet. Shutdown closes such a connection unanswered when its
-// request is read after it began, so a handover's end waits for them
-// first: the agent's request is answered here, not cut.
+// unreadConns are the connections the gateway took whose next request it
+// hasn't read yet: new ones, and kept-alive ones idle between requests.
+// Shutdown closes such a connection unanswered, and a request the agent
+// sent on it just then is cut ("connection reset", #3451), so a
+// handover's end waits for them first: each one's next request is
+// answered here, its reply closing it (closesWhenHandedOff), and the
+// agent's next one dials the magpie after this one.
type unreadConns struct {
mu sync.Mutex
conns map[net.Conn]bool
+ idle map[net.Conn]bool
// stopped: the server takes none from here on, its Serve returned
stopped bool
}
-// note is the server's ConnState: a connection is unread from StateNew to
-// its next state, whichever it is.
+// note is the server's ConnState: a connection is unread from StateNew,
+// and from StateIdle, to its next state, whichever it is.
func (u *unreadConns) note(c net.Conn, state http.ConnState) {
u.mu.Lock()
defer u.mu.Unlock()
- if state != http.StateNew {
- delete(u.conns, c)
- return
- }
- if u.conns == nil {
- u.conns = map[net.Conn]bool{}
+ delete(u.conns, c)
+ delete(u.idle, c)
+ switch state {
+ case http.StateNew:
+ if u.conns == nil {
+ u.conns = map[net.Conn]bool{}
+ }
+ u.conns[c] = true
+ case http.StateIdle:
+ if u.idle == nil {
+ u.idle = map[net.Conn]bool{}
+ }
+ u.idle[c] = true
}
- u.conns[c] = true
}
// stop is called once the server's Serve has returned. net/http notes a
@@ -229,11 +252,13 @@ func (u *unreadConns) stop() {
}
// wait returns once the server takes no more connections and none it took
-// is unread, after unreadWait at most, or when ctx ends.
+// is unread, after unreadWait at most, or when ctx ends. A kept-alive
+// connection its agent leaves idle that long is closed by Shutdown, as
+// its idle timeout would.
func (u *unreadConns) wait(ctx context.Context) {
for deadline := time.Now().Add(unreadWait); ; time.Sleep(10 * time.Millisecond) {
u.mu.Lock()
- done := u.stopped && len(u.conns) == 0
+ done := u.stopped && len(u.conns) == 0 && len(u.idle) == 0
u.mu.Unlock()
if done || time.Now().After(deadline) || ctx.Err() != nil {
return
diff --git a/internal/gateway/handover_test.go b/internal/gateway/handover_test.go
index 466d3bc45..d3ed04715 100644
--- a/internal/gateway/handover_test.go
+++ b/internal/gateway/handover_test.go
@@ -351,6 +351,84 @@ func TestHandedOffGatewayAnswersAConnectionItTook(t *testing.T) {
}
}
+// A kept-alive connection the gateway answered before it handed off,
+// idle as its end begins, has the next request its agent sends answered
+// there, the reply closing it: Shutdown closed it unanswered, and the
+// agent's request just sent on it was cut ("connection reset", #3451).
+// So too for a `make dev` backend ending beside the one started after it.
+func TestHandedOffGatewayAnswersAKeptAliveConnection(t *testing.T) {
+ for _, dev := range []bool{false, true} {
+ name := "handed off"
+ if dev {
+ name = "make dev"
+ }
+ t.Run(name, func(t *testing.T) {
+ was := Handover
+ Handover = dev
+ defer func() { Handover = was }()
+ old, addr, stopOld, oldDone := handOffSandbox(t)
+
+ c, err := net.Dial("tcp", addr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ rd := bufio.NewReader(c)
+ ask := func() (*http.Response, string, error) {
+ chatOn(t, c, addr)
+ c.SetReadDeadline(time.Now().Add(10 * time.Second))
+ r, err := http.ReadResponse(rd, nil)
+ if err != nil {
+ return nil, "", err
+ }
+ defer r.Body.Close()
+ b, err := io.ReadAll(r.Body)
+ return r, string(b), err
+ }
+ // answered, and kept alive: idle once the end begins
+ if r, b, err := ask(); err != nil || r.StatusCode != 200 || r.Close {
+ t.Fatalf("the request before the handover: %v %q %v", r, b, err)
+ }
+
+ if !dev {
+ f, err := old.ListenerFile()
+ if err != nil {
+ t.Fatal(err)
+ }
+ ln, err := net.FileListener(f) // the new one's copy, keeping the socket open
+ f.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+ old.HandOff()
+ }
+ stopOld()
+ // its agent sends its next request once the end has begun:
+ // well inside the 5s the end waits for it (unreadWait)
+ time.Sleep(100 * time.Millisecond)
+ r, b, err := ask()
+ if err != nil || r.StatusCode != 200 || !strings.Contains(b, "quick") {
+ t.Fatalf("a request on a kept-alive connection, sent once the end began: %q %v", b, err)
+ }
+ if !r.Close {
+ t.Fatal("the reply kept the connection alive, for a request the old one's end would cut")
+ }
+ select {
+ case err := <-oldDone:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("the old one never ended once its connections were answered")
+ }
+ if n := len(old.Recent()); n != 2 {
+ t.Fatalf("the old one answered %d of its 2 requests", n)
+ }
+ })
+ }
+}
+
// heldListener holds the next connection it takes, once told to, until
// let go: as a busy machine can hold the goroutine that took one, before
// net/http notes it.
diff --git a/internal/gateway/sse.go b/internal/gateway/sse.go
index c2879948d..24d682896 100644
--- a/internal/gateway/sse.go
+++ b/internal/gateway/sse.go
@@ -80,7 +80,9 @@ func (s *sseWriter) begin() {
h := s.w.Header()
h.Set("Content-Type", "text/event-stream; charset=utf-8")
h.Set("Cache-Control", "no-cache")
- h.Set("Connection", "keep-alive")
+ if h.Get("Connection") == "" { // a handed-off gateway's close stays (closesWhenHandedOff)
+ h.Set("Connection", "keep-alive")
+ }
h.Set("X-Accel-Buffering", "no")
s.w.WriteHeader(http.StatusOK)
s.flush()