From 9d694e4419eff01fd488ef4dbec7c840e2633bec Mon Sep 17 00:00:00 2001 From: MasterCoderK <8674856+DiamondGo@users.noreply.github.com> Date: Sun, 30 Aug 2026 22:41:59 -0700 Subject: [PATCH 1/2] Add atomic idle session close Add CloseSessionIfNoPollInFlight and synchronize poll, stream, WebSocket, sweeper, and close lifecycle transitions. Cover transport races and exactly-once disconnect behavior, fix race-prone test state, and ignore cross-repo plans. --- .gitignore | 1 + atomic_idle_close_test.go | 201 ++++++++++++++++++++++++++++++++++++++ client_test.go | 9 +- handler.go | 40 +++++--- handler_test.go | 46 +++++++++ relay_topology_test.go | 9 +- session.go | 64 ++++++++++-- session_test.go | 9 +- store.go | 43 +++++--- store_test.go | 6 +- websocket.go | 17 ++-- websocket_test.go | 17 ++++ 12 files changed, 408 insertions(+), 54 deletions(-) create mode 100644 atomic_idle_close_test.go diff --git a/.gitignore b/.gitignore index 49735dd..648266a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ # Cross-repo planning document, kept out of the standalone library. DESIGN.md +plans diff --git a/atomic_idle_close_test.go b/atomic_idle_close_test.go new file mode 100644 index 0000000..7c839d8 --- /dev/null +++ b/atomic_idle_close_test.go @@ -0,0 +1,201 @@ +package pollmux + +import ( + "net/http" + "sync" + "testing" + "time" +) + +func TestCloseSessionIfNoPollInFlight(t *testing.T) { + st := NewSessionStore() + s := newSession("idle", nil) + st.add(s) + + var mu sync.Mutex + calls := 0 + h := Hooks{OnDisconnect: func(got *Session, reason DisconnectReason) { + mu.Lock() + defer mu.Unlock() + if got != s || reason != ReasonServerClose { + t.Errorf("OnDisconnect(%p, %v), want (%p, %v)", got, reason, s, ReasonServerClose) + } + calls++ + }} + + if !CloseSessionIfNoPollInFlight(st, h, s, ReasonServerClose) { + t.Fatal("idle close returned false") + } + if !s.IsClosed() || st.Len() != 0 { + t.Fatal("idle close did not close and remove the session") + } + if CloseSessionIfNoPollInFlight(st, h, s, ReasonServerClose) { + t.Fatal("second idle close returned true") + } + mu.Lock() + defer mu.Unlock() + if calls != 1 { + t.Fatalf("OnDisconnect called %d times, want 1", calls) + } +} + +func TestCloseSessionIfNoPollInFlightRejectsAttachedTransport(t *testing.T) { + st := NewSessionStore() + s := newSession("busy", nil) + st.add(s) + if !s.beginPoll() { + t.Fatal("beginPoll failed") + } + + if CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) { + t.Fatal("closed a session with a poll attached") + } + if s.IsClosed() || st.Len() != 1 { + t.Fatal("failed conditional close changed the session") + } + + s.endPoll() + if !CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) { + t.Fatal("close failed after poll detached") + } +} + +func TestCloseSessionIfNoPollInFlightChecksStoreIdentity(t *testing.T) { + st := NewSessionStore() + old := newSession("same", nil) + current := newSession("same", nil) + st.add(current) + + if CloseSessionIfNoPollInFlight(st, Hooks{}, old, ReasonServerClose) { + t.Fatal("closed a non-current session object") + } + if got, ok := st.Get("same"); !ok || got != current { + t.Fatal("store's current session was changed") + } +} + +func TestCloseSessionIfNoPollInFlightRejectsWebSocketThenClosesAfterDetach(t *testing.T) { + st := NewSessionStore() + s := newSession("ws", nil) + st.add(s) + if !s.beginWebSocket() { + t.Fatal("beginWebSocket failed") + } + if CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) { + t.Fatal("closed a session with a websocket attached") + } + s.endWebSocket() + if !CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) { + t.Fatal("close failed after websocket detached") + } +} + +func TestBeginPollAndConditionalCloseAreLinearizable(t *testing.T) { + for i := 0; i < 1000; i++ { + st := NewSessionStore() + s := newSession("race", nil) + st.add(s) + + start := make(chan struct{}) + var wg sync.WaitGroup + wg.Add(2) + var began, closed bool + go func() { defer wg.Done(); <-start; began = s.beginPoll() }() + go func() { + defer wg.Done() + <-start + closed = CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) + }() + close(start) + wg.Wait() + + if began == closed { + t.Fatalf("iteration %d: beginPoll=%v close=%v; exactly one must win", i, began, closed) + } + if began { + s.endPoll() + } + } +} + +func TestConditionalCloseRacesCloseSessionExactlyOnce(t *testing.T) { + for i := 0; i < 200; i++ { + st := NewSessionStore() + s := newSession("race-close", nil) + st.add(s) + var mu sync.Mutex + calls := 0 + h := Hooks{OnDisconnect: func(*Session, DisconnectReason) { mu.Lock(); calls++; mu.Unlock() }} + start := make(chan struct{}) + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); <-start; CloseSession(st, h, s, ReasonServerClose) }() + go func() { defer wg.Done(); <-start; CloseSessionIfNoPollInFlight(st, h, s, ReasonEvicted) }() + close(start) + wg.Wait() + mu.Lock() + if calls != 1 { + t.Fatalf("iteration %d: OnDisconnect calls = %d, want 1", i, calls) + } + mu.Unlock() + } +} + +func TestConditionalCloseRacesDeleteExactlyOnce(t *testing.T) { + var mu sync.Mutex + calls := 0 + h := Hooks{OnDisconnect: func(*Session, DisconnectReason) { mu.Lock(); calls++; mu.Unlock() }} + ts, st := newTestServer(t, testServerConfig(), h) + cr := connectOK(t, ts) + s, _ := st.Get(cr.SessionID) + + start := make(chan struct{}) + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + <-start + req, _ := http.NewRequest(http.MethodDelete, ts.URL+"/tunnel/"+cr.SessionID, nil) + resp, err := ts.Client().Do(req) + if err == nil { + resp.Body.Close() + } + }() + go func() { defer wg.Done(); <-start; CloseSessionIfNoPollInFlight(st, h, s, ReasonEvicted) }() + close(start) + wg.Wait() + mu.Lock() + defer mu.Unlock() + if calls != 1 { + t.Fatalf("OnDisconnect calls = %d, want 1", calls) + } +} + +func TestConditionalCloseRacesSweeperExactlyOnce(t *testing.T) { + st := NewSessionStore() + s := newSession("sweep-race", nil) + s.mu.Lock() + s.lastActive = time.Now().Add(-time.Hour) + s.mu.Unlock() + st.add(s) + var mu sync.Mutex + calls := 0 + callback := func(*Session) { mu.Lock(); calls++; mu.Unlock() } + + start := make(chan struct{}) + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); <-start; st.sweep(time.Millisecond, callback) }() + go func() { + defer wg.Done() + <-start + CloseSessionIfNoPollInFlight(st, Hooks{OnDisconnect: func(*Session, DisconnectReason) { callback(s) }}, s, ReasonEvicted) + }() + close(start) + wg.Wait() + mu.Lock() + defer mu.Unlock() + if calls != 1 { + t.Fatalf("disconnect/eviction calls = %d, want 1", calls) + } +} diff --git a/client_test.go b/client_test.go index 9bec1d0..1cfde49 100644 --- a/client_test.go +++ b/client_test.go @@ -114,6 +114,7 @@ func (f *fakeServer) serveConnect(w http.ResponseWriter, r *http.Request) { json.NewDecoder(r.Body).Decode(&req) f.mu.Lock() f.connects = append(f.connects, req) + sessionID := f.sessionID f.mu.Unlock() for k, v := range f.connectHeader { @@ -131,7 +132,7 @@ func (f *fakeServer) serveConnect(w http.ResponseWriter, r *http.Request) { } resp := ConnectResponse{ ProtocolVersion: ProtocolVersion, - SessionID: f.sessionID, + SessionID: sessionID, Limits: f.limits, Meta: f.connectMeta, } @@ -578,13 +579,19 @@ func TestPoll410IgnoredWhenSessionSuperseded(t *testing.T) { f := newFakeServer(t) connector := f.connector() + f.mu.Lock() f.sessionID = "sess-a" + f.mu.Unlock() conn1 := mustConnect(t, connector) + f.mu.Lock() f.sessionID = "sess-b" + f.mu.Unlock() conn2 := mustConnect(t, connector) + f.mu.Lock() f.goneSessions = map[string]struct{}{"sess-a": {}} + f.mu.Unlock() select { case <-conn1.SessionSuperseded(): diff --git a/handler.go b/handler.go index ae739ab..bc624cf 100644 --- a/handler.go +++ b/handler.go @@ -370,6 +370,11 @@ func PollHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { return } + if !s.beginPoll() { + writeError(w, http.StatusGone, "session closed") + return + } + defer s.endPoll() s.touch() // Before the wait, not after: a callback that runs after a 30-second @@ -421,12 +426,6 @@ func PollHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler { return } - // A parked poll is proof the client is still there, and the count - // drops the moment this handler returns — including when the TCP - // connection breaks underneath it. - s.pollInFlight.Add(1) - defer s.pollInFlight.Add(-1) - buf := make([]byte, cfg.PollBufferSize) n, err := s.toClient.ReadAvailable(buf, cfg.PollTimeout, cfg.CoalesceWindow) @@ -466,8 +465,7 @@ func pollStream(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerCo return } - s.pollInFlight.Add(1) - defer s.pollInFlight.Add(-1) + // PollHandler owns the lifecycle attachment for this request. // Headers must go out now, not on the first frame. The client's // ResponseHeaderTimeout for a stream-mode poll is short (it only needs @@ -534,8 +532,7 @@ func pollStream(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerCo // is safely between frames (see DESIGN.md's "谁来决定轮转" section). This // handler just reads until told to stop. func pollSendStream(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerConfig) { - s.pollInFlight.Add(1) - defer s.pollInFlight.Add(-1) + // PollHandler owns the lifecycle attachment for this request. // A read-idle watchdog is this handler's only liveness signal: unlike // pollStream (where the server is the writer and controls the pace @@ -641,12 +638,27 @@ func CloseSession(st *SessionStore, h Hooks, s *Session, reason DisconnectReason } func closeSession(st *SessionStore, h Hooks, s *Session, reason DisconnectReason) { - st.Remove(s.ID) - // closeOnce is the guard: exactly one caller gets true, so a delete racing - // an eviction cannot fire OnDisconnect twice. - if s.closeOnce() && h.OnDisconnect != nil { + if !st.removeAndMarkClosed(s, false) { + return + } + s.closePipes() + if h.OnDisconnect != nil { + h.OnDisconnect(s, reason) + } +} + +// CloseSessionIfNoPollInFlight atomically closes s only when it is still the +// current store entry and no poll or persistent transport is attached. It +// returns true only when this call completed the removal and close. +func CloseSessionIfNoPollInFlight(st *SessionStore, h Hooks, s *Session, reason DisconnectReason) bool { + if !st.removeAndMarkClosed(s, true) { + return false + } + s.closePipes() + if h.OnDisconnect != nil { h.OnDisconnect(s, reason) } + return true } // StartSweeper runs the store's expiry scan with this config's timings, wired diff --git a/handler_test.go b/handler_test.go index a7d2a82..912e66f 100644 --- a/handler_test.go +++ b/handler_test.go @@ -434,6 +434,52 @@ func TestPollInFlightIsVisibleWhileParked(t *testing.T) { waitFor(t, time.Second, func() bool { return s.PollInFlight() == 0 }) } +func TestConditionalCloseRejectsBatchPollThenPollsClosedSession(t *testing.T) { + ts, st := newTestServer(t, testServerConfig(), Hooks{}) + cr := connectOK(t, ts) + s, _ := st.Get(cr.SessionID) + + done := make(chan *http.Response, 1) + go func() { done <- poll(t, ts, cr.SessionID, nil, map[string]string{HeaderReceiveOnly: "true"}) }() + waitFor(t, time.Second, func() bool { return s.PollInFlight() == 1 }) + if CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) { + t.Fatal("closed a session with a batch poll in flight") + } + resp := <-done + resp.Body.Close() + if !CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) { + t.Fatal("close failed after batch poll returned") + } + resp = poll(t, ts, cr.SessionID, nil, map[string]string{HeaderReceiveOnly: "true"}) + resp.Body.Close() + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("poll after close = %d, want 404", resp.StatusCode) + } +} + +func TestConditionalCloseRejectsStreamPoll(t *testing.T) { + cfg := testServerConfig() + cfg.PollMode = PollModeStream + cfg.HeartbeatInterval = 20 * time.Millisecond + cfg.StreamMaxDuration = 500 * time.Millisecond + ts, st := newTestServer(t, cfg, Hooks{}) + resp, cr := postConnect(t, ts, ConnectRequest{ProtocolVersion: ProtocolVersion, PreferStreamMode: true}) + if resp.StatusCode != http.StatusOK || cr.PollMode != PollModeStream { + t.Fatalf("stream connect = %d mode %q", resp.StatusCode, cr.PollMode) + } + s, _ := st.Get(cr.SessionID) + + done := make(chan *http.Response, 1) + go func() { done <- poll(t, ts, cr.SessionID, nil, map[string]string{HeaderReceiveOnly: "true"}) }() + waitFor(t, time.Second, func() bool { return s.PollInFlight() == 1 }) + if CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) { + t.Fatal("closed a session with a stream poll in flight") + } + CloseSession(st, Hooks{}, s, ReasonServerClose) + got := <-done + got.Body.Close() +} + // OnPoll runs before the wait, so a health report is acted on now rather than // a poll timeout later. func TestOnPollRunsBeforeTheWait(t *testing.T) { diff --git a/relay_topology_test.go b/relay_topology_test.go index 9fdc041..926c0a9 100644 --- a/relay_topology_test.go +++ b/relay_topology_test.go @@ -1170,5 +1170,12 @@ func TestStoreReflectsLiveSessionsForStatus(t *testing.T) { } cancel() - waitFor(t, 15*time.Second, func() bool { return b.store.Len() == 0 }) + // ReconnectLoop cancellation stops transport activity, but it does not send + // DELETE: production servers remove these sessions through their normal + // shutdown/expiry path. Exercise graceful shutdown explicitly so this test + // does not depend on a 60-second sweeper timeout. + for _, s := range b.store.All() { + CloseSession(b.store, b.hooks, s, ReasonServerClose) + } + waitFor(t, 5*time.Second, func() bool { return b.store.Len() == 0 }) } diff --git a/session.go b/session.go index 5f6dbc5..7f6fbbd 100644 --- a/session.go +++ b/session.go @@ -4,7 +4,6 @@ import ( "log/slog" "maps" "sync" - "sync/atomic" "time" ) @@ -54,7 +53,7 @@ type Session struct { // Connect for a fresh session id rather than reattaching to an old one — // but WebSocketHandler still checks this defensively rather than // assuming the caller never will. - wsAttached atomic.Bool + wsAttached bool // pollInFlight counts long polls currently parked in the handler. A value // above zero means a TCP connection is being held open by this client right @@ -62,7 +61,7 @@ type Session struct { // when that TCP connection does break, the handler returns and the count // drops immediately, which is what turns a silent client death into a fast // detection instead of a session_timeout wait (A3). - pollInFlight atomic.Int32 + pollInFlight int32 mu sync.Mutex lastActive time.Time @@ -115,18 +114,64 @@ func (s *Session) Close() error { // happens exactly once even when a delete and an eviction race. func (s *Session) closeOnce() bool { s.mu.Lock() + won := s.markClosedLocked() + s.mu.Unlock() + if won { + s.closePipes() + } + return won +} + +// markClosedLocked performs the session lifecycle transition. s.mu must be held. +func (s *Session) markClosedLocked() bool { if s.closed { - s.mu.Unlock() return false } s.closed = true - s.mu.Unlock() + return true +} +func (s *Session) closePipes() { s.toServer.Close() s.toClient.Close() +} + +// beginPoll atomically attaches a poll or persistent transport unless the +// session has already been closed. +func (s *Session) beginPoll() bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return false + } + s.pollInFlight++ return true } +func (s *Session) endPoll() { + s.mu.Lock() + s.pollInFlight-- + s.mu.Unlock() +} + +func (s *Session) beginWebSocket() bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed || s.wsAttached { + return false + } + s.wsAttached = true + s.pollInFlight++ + return true +} + +func (s *Session) endWebSocket() { + s.mu.Lock() + s.wsAttached = false + s.pollInFlight-- + s.mu.Unlock() +} + // writeUpstream queues data the client sent for the application to read. func (s *Session) writeUpstream(p []byte) (int, error) { return s.toServer.Write(p) @@ -153,10 +198,13 @@ func (s *Session) touch() { s.mu.Unlock() } -// PollInFlight returns the number of long polls currently parked on this -// session. Above zero means the client is demonstrably still connected. +// PollInFlight returns an observational snapshot of attached polls and +// persistent transports. It must not be used to decide whether to close the +// session; use CloseSessionIfNoPollInFlight for that atomic operation. func (s *Session) PollInFlight() int32 { - return s.pollInFlight.Load() + s.mu.Lock() + defer s.mu.Unlock() + return s.pollInFlight } // Meta returns a copy of the metadata the client declared at connect time, diff --git a/session_test.go b/session_test.go index 831055f..0966654 100644 --- a/session_test.go +++ b/session_test.go @@ -93,14 +93,15 @@ func TestSessionPollInFlightCounts(t *testing.T) { t.Fatalf("PollInFlight = %d on a fresh session, want 0", got) } - s.pollInFlight.Add(1) - s.pollInFlight.Add(1) + if !s.beginPoll() || !s.beginPoll() { + t.Fatal("beginPoll failed on an open session") + } if got := s.PollInFlight(); got != 2 { t.Fatalf("PollInFlight = %d, want 2", got) } - s.pollInFlight.Add(-1) - s.pollInFlight.Add(-1) + s.endPoll() + s.endPoll() if got := s.PollInFlight(); got != 0 { t.Fatalf("PollInFlight = %d after both polls returned, want 0", got) } diff --git a/store.go b/store.go index 7a77b8c..a45b046 100644 --- a/store.go +++ b/store.go @@ -103,32 +103,47 @@ func (st *SessionStore) StartSweeper(interval, timeout time.Duration, onEvict fu } } +// removeAndMarkClosed removes s only if it is still the store's current object. +// Lock order throughout lifecycle operations is SessionStore.mu -> Session.mu. +func (st *SessionStore) removeAndMarkClosed(s *Session, requireIdle bool) bool { + st.mu.Lock() + defer st.mu.Unlock() + if current, ok := st.sessions[s.ID]; !ok || current != s { + return false + } + s.mu.Lock() + defer s.mu.Unlock() + if s.closed || (requireIdle && s.pollInFlight != 0) { + return false + } + s.closed = true + delete(st.sessions, s.ID) + return true +} + // sweep evicts every session that has gone quiet past timeout with no poll -// parked on it. +// parked on it. The final expiry and transport checks happen while holding both +// lifecycle locks, so a poll cannot attach between checking and removal. func (st *SessionStore) sweep(timeout time.Duration, onEvict func(*Session)) { now := time.Now() var expired []*Session st.mu.Lock() for id, s := range st.sessions { - if s.PollInFlight() > 0 { - continue - } - if now.Sub(s.LastActive()) <= timeout { - continue + s.mu.Lock() + if !s.closed && s.pollInFlight == 0 && now.Sub(s.lastActive) > timeout { + s.closed = true + delete(st.sessions, id) + expired = append(expired, s) } - delete(st.sessions, id) - expired = append(expired, s) + s.mu.Unlock() } st.mu.Unlock() - // Closing and notifying happen outside the store lock: onEvict runs - // application code, which must not be able to deadlock the store. - // - // closeOnce gates the callback so that a session already closed elsewhere - // — a DELETE landing at the same moment, say — is not announced twice. + // Pipe closing and application callbacks always happen outside locks. for _, s := range expired { - if s.closeOnce() && onEvict != nil { + s.closePipes() + if onEvict != nil { onEvict(s) } } diff --git a/store_test.go b/store_test.go index 2ce1f3c..c913453 100644 --- a/store_test.go +++ b/store_test.go @@ -92,7 +92,9 @@ func TestSweeperEvictsIdleSession(t *testing.T) { func TestSweeperSkipsSessionWithPollInFlight(t *testing.T) { st := NewSessionStore() s := newSession("polling", nil) - s.pollInFlight.Add(1) + if !s.beginPoll() { + t.Fatal("beginPoll failed") + } st.add(s) evicted := make(chan *Session, 1) @@ -112,7 +114,7 @@ func TestSweeperSkipsSessionWithPollInFlight(t *testing.T) { } // Once the poll returns, the normal idle rule applies again. - s.pollInFlight.Add(-1) + s.endPoll() select { case got := <-evicted: if got != s { diff --git a/websocket.go b/websocket.go index b4676e4..1a3ac5a 100644 --- a/websocket.go +++ b/websocket.go @@ -63,15 +63,15 @@ func WebSocketHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler writeError(w, http.StatusBadRequest, "session was not negotiated for websocket transport") return } - if !s.wsAttached.CompareAndSwap(false, true) { - // In practice unreachable — ReconnectLoop always calls Connect - // for a fresh session id rather than reattaching to an old one - // — but a session having two WebSockets fighting over the same - // toClient/toServer pipes would be a real, confusing bug, so - // this stays a hard error rather than an assumption. - writeError(w, http.StatusConflict, "session already has a websocket attached") + if !s.beginWebSocket() { + if s.IsClosed() { + writeError(w, http.StatusGone, "session closed") + } else { + writeError(w, http.StatusConflict, "session already has a websocket attached") + } return } + defer s.endWebSocket() s.touch() c, err := websocket.Accept(w, r, &websocket.AcceptOptions{ @@ -88,9 +88,6 @@ func WebSocketHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler } c.SetReadLimit(int64(cfg.MaxSendBytes) + 1) // +1 for wsEncode's type byte - s.pollInFlight.Add(1) - defer s.pollInFlight.Add(-1) - // Not r.Context(): coder/websocket's Accept doc warns that using the // request context after Accept returns "may lead to unexpected // behavior" (it has hijacked the connection out from under net/http diff --git a/websocket_test.go b/websocket_test.go index b8178d9..9e8a959 100644 --- a/websocket_test.go +++ b/websocket_test.go @@ -218,6 +218,23 @@ func TestWebSocketSessionCloseIsNoticedPromptly(t *testing.T) { } } +func TestConditionalCloseRejectsLiveWebSocketThenClosesAfterDisconnect(t *testing.T) { + ts, st := newWebSocketTestServer(t, testWebSocketServerConfig(), Hooks{}) + cr := connectOKWebSocket(t, ts) + s, _ := st.Get(cr.SessionID) + ws := dialWS(t, ts, cr.SessionID) + waitFor(t, time.Second, func() bool { return s.PollInFlight() == 1 }) + + if CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) { + t.Fatal("closed a session with a websocket attached") + } + ws.CloseNow() + waitFor(t, time.Second, func() bool { return s.PollInFlight() == 0 }) + if !CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) { + t.Fatal("close failed after websocket disconnected") + } +} + func TestWebSocketDoubleAttachIsRejected(t *testing.T) { ts, _ := newWebSocketTestServer(t, testWebSocketServerConfig(), Hooks{}) cr := connectOKWebSocket(t, ts) From dfa6a9975b4334fc3044ffc79a597fdd8d18031d Mon Sep 17 00:00:00 2001 From: Master Coder Date: Sun, 30 Aug 2026 22:43:55 -0700 Subject: [PATCH 2/2] Update session.go Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com> --- session.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/session.go b/session.go index 7f6fbbd..9123985 100644 --- a/session.go +++ b/session.go @@ -55,8 +55,11 @@ type Session struct { // assuming the caller never will. wsAttached bool - // pollInFlight counts long polls currently parked in the handler. A value - // above zero means a TCP connection is being held open by this client right + // pollInFlight counts active poll requests and persistent transports attached + // to the session, including send-only requests, stream requests before they + // park, and WebSocket attachments. A nonzero value means a client transport + // is currently attached and prevents eviction; it does not necessarily mean + // a long poll is parked. // now, so the session is demonstrably alive and must not be evicted — and // when that TCP connection does break, the handler returns and the count // drops immediately, which is what turns a silent client death into a fast