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

TestRestartHandsTheGatewayOver went red on ubuntu CI at b3edcabf2 (run
40676722560: "4 of 5 requests during the restart answered", connection
reset by peer), and three times under load since 10-25 with no owner.
It is a real gap a user meets on an update: once the gateway is handed
to the new magpie, the old one's end calls Shutdown, which closes every
idle kept-alive connection at once. An agent that has just sent its next
request on one (Go's transport, Node's agent and curl reuse them) gets
the connection reset, and a POST is not retried. #3568 made the end wait
only for connections taken whose first request was unread.

Now:
- unreadConns also counts kept-alive connections idle between requests
  (StateIdle until the next state), and a handover's end waits for them
  as for new ones, unreadWait (5s) at most, before Shutdown;
- once the gateway takes no connection (stopAccepting), each reply it
  gives says Connection: close (closesWhenHandedOff), so the agent's
  next request dials the magpie serving the port after it;
- the SSE writer keeps a Connection value already set, where it wrote
  keep-alive over the close.
A connection its agent leaves idle the whole 5s is closed by Shutdown,
as its idle timeout would close it. `make dev`'s ending backend
(Handover) takes the same path.

Run on mote (macOS 27, arm64) at this tree on 51e3169fb:
- new TestHandedOffGatewayAnswersAKeptAliveConnection (handed off and
  make dev): a request on a connection answered before the handover,
  sent 100ms after the end began, is answered "quick" with the
  connection closed, and the old one ends within 3s. Red on the old code
  with this test, both subtests: "" unexpected EOF, as #3451 reads.
- go test -count=3 -run 'TestHandedOff|TestHandedOver|TestInherited|
  TestToolCallOfTheMagpieBefore' ./internal/gateway: ok; the same
  handover tests -race -count=3: ok.
- go test -count=8 -run '^TestRestartHandsTheGatewayOver$'
  ./internal/gui: ok.
- go test -timeout 45m ./internal/gateway ./internal/gui
  ./internal/handoff: gateway ok (459s), handoff ok; gui red only on
  TestMainWindowCorners/macOS_26_SDK, mote's macOS 27, filed as #3949.
- gofmt -l clean; go vet ./internal/gateway ./internal/gui;
  GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway ok.
Not broken by hand separately: the Connection: close alone (the test's
r.Close check guards it) and the SSE writer's keep, which no test
streams through after a handover.
Not run: the full ./... suite; Linux (the CI red's OS) only through CI.
This commit is contained in:
yetone
2026-10-28 19:43:39 +08:00
parent 0c17aac2d7
commit 68ab4c06da
4 changed files with 125 additions and 20 deletions
+4 -4
View File
@@ -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)
}
+40 -15
View File
@@ -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
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
}
if u.conns == nil {
u.conns = map[net.Conn]bool{}
}
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
+78
View File
@@ -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.
+3 -1
View File
@@ -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()