From 05d54904ae68ffd701f9687a3499eba7503c7257 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 14:55:38 +0100 Subject: [PATCH 1/8] feat(api): log why a session socket closed The "served a request" line of a session socket (events socket, its relayed twin, /v1/agents/socket) now says close_reason (client_closed, client_gone, timeout, refused, server_error, shutdown, session_ended), close_code when a close frame was sent or received, and end_reason, the session's own, when the session ended. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/relayws.go | 31 ++- acceleration/internal/api/requestid.go | 13 +- acceleration/internal/api/server.go | 3 +- acceleration/internal/api/sessionws.go | 40 ++- .../internal/api/socket_close_log_test.go | 227 ++++++++++++++++++ acceleration/internal/api/socketend.go | 82 +++++++ acceleration/internal/api/socketend_test.go | 91 +++++++ acceleration/internal/api/socketws.go | 27 +++ acceleration/internal/session/metrics.go | 4 + 9 files changed, 494 insertions(+), 24 deletions(-) create mode 100644 acceleration/internal/api/socket_close_log_test.go create mode 100644 acceleration/internal/api/socketend.go create mode 100644 acceleration/internal/api/socketend_test.go diff --git a/acceleration/internal/api/relayws.go b/acceleration/internal/api/relayws.go index 9ef733d18d..5fc2b97e46 100644 --- a/acceleration/internal/api/relayws.go +++ b/acceleration/internal/api/relayws.go @@ -188,15 +188,22 @@ func (s *Server) watchRemoteSession(w http.ResponseWriter, r *http.Request, id s connection.SetReadLimit(maxSocketMessage) gone := make(chan error, 1) + var closing atomic.Bool go func() { - gone <- s.readRelayedCommands(connection, state, watcher, id) + gone <- s.readRelayedCommands(connection, state, watcher, id, &closing) }() - s.writeRelayedEvents(connection, state, socket, watcher, id, watching(r), gone, endingOf(asked, socket.halted.Load)) + ended := s.writeRelayedEvents(connection, state, socket, watcher, id, watching(r), gone, endingOf(asked, socket.halted.Load)) + // The holder ends the session on a close command, which reaches this node as its end. + if closing.Load() && ended.cause == sessionEnded { + ended.cause = closedByClient + } + recordClose(r.Context(), ended) return true } // writeRelayedEvents writes what arrives on the bus out to the caller, and keeps both the -// socket and the watcher behind it alive. +// socket and the watcher behind it alive. It says why the socket closed; the session's end +// reason is the holder's to log. // // The ping and the refresh share a tick because they say the same thing in each // direction: this socket is still being read, and the watcher standing for it elsewhere @@ -209,7 +216,7 @@ func (s *Server) writeRelayedEvents( asked wanted, gone <-chan error, ended ending, -) { +) socketEnd { ping := time.NewTicker(pingEvery) defer ping.Stop() @@ -218,13 +225,14 @@ func (s *Server) writeRelayedEvents( case stopped := <-gone: if errors.Is(stopped, errUnreadableFrame) { refuseUnreadable(connection) + return socketEnd{cause: refusedByRouter, code: websocket.ClosePolicyViolation} } - return + return readEnd(stopped) case <-socket.closed: code, reason := ended() closeBeforeReader(connection, code, reason, gone) - return + return sessionEnd(code) case payload := <-socket.frames: if !asked.takesFrame(frameType(payload)) { @@ -233,13 +241,13 @@ func (s *Server) writeRelayedEvents( connection.SetWriteDeadline(time.Now().Add(writeWait)) if err := connection.WriteMessage(websocket.TextMessage, payload); err != nil { s.logger.Debug("relayed session socket write failed", "error", err) - return + return socketEnd{cause: clientGone} } case <-ping.C: connection.SetWriteDeadline(time.Now().Add(writeWait)) if err := connection.WriteMessage(websocket.PingMessage, nil); err != nil { - return + return socketEnd{cause: clientGone} } if err := state.bus.Publish(context.Background(), state.bus.Commands(), relay.Request{ Type: relay.Refresh, Node: state.bus.Node(), Session: id, Watcher: watcher, @@ -258,8 +266,8 @@ func (s *Server) writeRelayedEvents( // a command ends this socket as it ends a local one; the holder would only report it. // // It returns errUnreadableFrame for a frame that is not a command, and the read's own error -// when the connection ended. -func (s *Server) readRelayedCommands(connection *websocket.Conn, state *relayed, watcher, id string) error { +// when the connection ended. closing is set before a close command is carried. +func (s *Server) readRelayedCommands(connection *websocket.Conn, state *relayed, watcher, id string, closing *atomic.Bool) error { connection.SetReadDeadline(time.Now().Add(pongWait)) connection.SetPongHandler(func(string) error { return connection.SetReadDeadline(time.Now().Add(pongWait)) @@ -278,6 +286,9 @@ func (s *Server) readRelayedCommands(connection *websocket.Conn, state *relayed, if json.Unmarshal(payload, &command) != nil { return errUnreadableFrame } + if command.Type == "close" { + closing.Store(true) + } if err := state.bus.Publish(context.Background(), state.bus.Commands(), relay.Request{ Type: relay.Command, diff --git a/acceleration/internal/api/requestid.go b/acceleration/internal/api/requestid.go index 40e1a33e85..aefc699a37 100644 --- a/acceleration/internal/api/requestid.go +++ b/acceleration/internal/api/requestid.go @@ -64,13 +64,14 @@ func validRequestID(id string) bool { // requestFailure is the error behind a request's answer, left for withRequestLog to report: // the answer itself is deliberately vaguer than the error. It also holds the name of the -// operation that served the request (nameOperation) and the app of a hook it verified -// (loggedHook). +// operation that served the request (nameOperation), the app of a hook it verified +// (loggedHook) and why the socket it upgraded to closed (recordClose). type requestFailure struct { err error trace string operation string app string + closed socketEnd } type requestFailureContextKey struct{} @@ -82,6 +83,14 @@ func nameOperation(ctx context.Context, name string) { } } +// recordClose names why the request's socket closed, for its access line. Only the handler's +// own goroutine may call it, once its socket's other goroutines have stopped. +func recordClose(ctx context.Context, ended socketEnd) { + if failure, ok := ctx.Value(requestFailureContextKey{}).(*requestFailure); ok { + failure.closed = ended + } +} + func recordFailure(ctx context.Context, err error, trace string) { if failure, ok := ctx.Value(requestFailureContextKey{}).(*requestFailure); ok { failure.err = err diff --git a/acceleration/internal/api/server.go b/acceleration/internal/api/server.go index a8bd4db3b1..cf2a24c449 100644 --- a/acceleration/internal/api/server.go +++ b/acceleration/internal/api/server.go @@ -1046,7 +1046,7 @@ func (s *Server) withRequestLog(routes *chi.Mux, next http.Handler) http.Handler customer, _ := CustomerFrom(r.Context()) // A socket reports the life of the connection rather than a time to respond, - // since it is logged once it has closed. + // since it is logged once it has closed, and why it closed (socketEnd). fields := []any{ "method", r.Method, "path", loggedPath(routes, r), @@ -1058,6 +1058,7 @@ func (s *Server) withRequestLog(routes *chi.Mux, next http.Handler) http.Handler if recorder.written > 0 { fields = append(fields, "bytes", recorder.written) } + fields = append(fields, failure.closed.fields()...) if failure.err != nil { fields = append(fields, "error", failure.err.Error()) } diff --git a/acceleration/internal/api/sessionws.go b/acceleration/internal/api/sessionws.go index 916ad871b2..889f2c6d86 100644 --- a/acceleration/internal/api/sessionws.go +++ b/acceleration/internal/api/sessionws.go @@ -9,6 +9,7 @@ import ( "net/http" "net/url" "strings" + "sync/atomic" "time" "github.com/danielgtaylor/huma/v2" @@ -168,10 +169,19 @@ func (s *Server) watchSession(w http.ResponseWriter, r *http.Request) { // Reading and writing each own the connection in one direction, which is what gorilla // requires: two goroutines writing to one socket interleave frames. gone := make(chan error, 1) + var closing atomic.Bool go func() { - gone <- s.readCommands(connection, found, seat, CallerFrom(r.Context())) + gone <- s.readCommands(connection, found, seat, CallerFrom(r.Context()), &closing) }() - s.writeEvents(connection, events, watching(r), gone, endingOf(resuming, found.Halted)) + ended := s.writeEvents(connection, events, watching(r), gone, endingOf(resuming, found.Halted)) + // A close command ends the session before the reader stops, so the writer sees the end first. + if closing.Load() && ended.cause == sessionEnded { + ended.cause = closedByClient + } + if ended.cause == sessionEnded { + ended.endReason = found.EndedFor() + } + recordClose(r.Context(), ended) } // resuming is what a resumable watcher asked for: cursor is the last frame it was sent, @@ -276,9 +286,9 @@ func (w wanted) takesFrame(kind string) bool { } // writeEvents pushes the conversation to the caller until the session ends or the socket -// breaks. gone carries why the reader stopped, which is answered here because this is the -// goroutine that writes. -func (s *Server) writeEvents(connection *websocket.Conn, events <-chan session.Event, asked wanted, gone <-chan error, ended ending) { +// breaks, and says why the socket closed. gone carries why the reader stopped, which is +// answered here because this is the goroutine that writes. +func (s *Server) writeEvents(connection *websocket.Conn, events <-chan session.Event, asked wanted, gone <-chan error, ended ending) socketEnd { ping := time.NewTicker(pingEvery) defer ping.Stop() @@ -288,15 +298,17 @@ func (s *Server) writeEvents(connection *websocket.Conn, events <-chan session.E switch { case stopped == nil: closeSocket(connection, websocket.CloseNormalClosure, "the session ended") + return socketEnd{cause: closedByClient, code: websocket.CloseNormalClosure} case errors.Is(stopped, errUnreadableFrame): refuseUnreadable(connection) + return socketEnd{cause: refusedByRouter, code: websocket.ClosePolicyViolation} } - return + return readEnd(stopped) case event, open := <-events: if !open { code, reason := ended() closeBeforeReader(connection, code, reason, gone) - return + return sessionEnd(code) } if !asked.takes(event) { continue @@ -308,13 +320,13 @@ func (s *Server) writeEvents(connection *websocket.Conn, events <-chan session.E connection.SetWriteDeadline(time.Now().Add(writeWait)) if err := connection.WriteJSON(encoded); err != nil { s.logger.Debug("session socket write failed", "error", err) - return + return socketEnd{cause: clientGone} } case <-ping.C: connection.SetWriteDeadline(time.Now().Add(writeWait)) if err := connection.WriteMessage(websocket.PingMessage, nil); err != nil { - return + return socketEnd{cause: clientGone} } } } @@ -359,8 +371,11 @@ type watcherCommand struct { // with it. A frame that is not JSON it can read ends the socket. // // It returns nil once a command closed the session, errUnreadableFrame for a frame that is not -// a command, and the read's own error when the connection ended. -func (s *Server) readCommands(connection *websocket.Conn, found *session.Session, seat session.Seat, sender routing.Caller) error { +// a command, and the read's own error when the connection ended. closing is set before a close +// command is applied. +func (s *Server) readCommands( + connection *websocket.Conn, found *session.Session, seat session.Seat, sender routing.Caller, closing *atomic.Bool, +) error { connection.SetReadDeadline(time.Now().Add(pongWait)) connection.SetPongHandler(func(string) error { return connection.SetReadDeadline(time.Now().Add(pongWait)) @@ -379,6 +394,9 @@ func (s *Server) readCommands(connection *websocket.Conn, found *session.Session if json.Unmarshal(payload, &command) != nil { return errUnreadableFrame } + if command.Type == "close" { + closing.Store(true) + } if !s.applyCommand(found, seat, sender, command) { return nil diff --git a/acceleration/internal/api/socket_close_log_test.go b/acceleration/internal/api/socket_close_log_test.go new file mode 100644 index 0000000000..9d56d95d35 --- /dev/null +++ b/acceleration/internal/api/socket_close_log_test.go @@ -0,0 +1,227 @@ +//go:build integration + +package api + +import ( + "crypto/rand" + "log/slog" + "net/http/httptest" + "testing" + "time" + + "github.com/gorilla/websocket" +) + +// SocketCloseLogSuite covers why a session socket closed, as its access line says it: the +// events socket on the node running the session and on another one, and /v1/agents/socket. +type SocketCloseLogSuite struct { + RouterSuite + logged *lockedLog + // other is a node running nothing, logging to logged too. + other *httptest.Server +} + +func TestSocketCloseLogSuite(t *testing.T) { + runSuite(t, new(SocketCloseLogSuite)) +} + +func (s *SocketCloseLogSuite) SetupSuite() { + s.logged = &lockedLog{} + s.logs = s.logged + s.RouterSuite.SetupSuite() + s.other, _ = s.otherRouterSealedBy(nil, s.sealer, + slog.New(NewLogHandler(slog.NewTextHandler(s.logged, nil)))) +} + +func (s *SocketCloseLogSuite) SetupTest() { + s.useFixture("standard") +} + +// watched opens a session that keeps no transcript and its events socket, on node (nil for +// the suite's own), named by a request id of its own. +func (s *SocketCloseLogSuite) watched(node *httptest.Server) (Session, *websocket.Conn, string) { + opened := s.serverClient.createSession(CreateSessionRequest{Incognito: pointerTo(true), Llm: pointerTo("llm-flow")}) + id := rand.Text() + client := s.serverClient.withRequestID(id) + if node != nil { + client = client.on(node) + } + return opened, client.opens("/v1/agents/sessions/" + opened.Id + "/events"), id +} + +// socketSession opens /v1/agents/socket and starts a session on it, named by a request id +// of its own. +func (s *SocketCloseLogSuite) socketSession() (*websocket.Conn, string, string) { + id := rand.Text() + connection := s.serverClient.withRequestID(id).opens("/v1/agents/socket") + s.Require().NoError(connection.WriteJSON(map[string]any{ + "type": "start", "session": map[string]any{"greeting": map[string]any{"text": "hello"}}, + })) + answered := s.await(connection, "session") + return connection, answered["session"].(map[string]any)["id"].(string), id +} + +// closeLine is the access line of the socket opened with request id once it has closed. +func (s *SocketCloseLogSuite) closeLine(id string) string { + var found string + s.Require().Eventually(func() bool { + found = lineWith(s.logged, `msg="served a request"`, " request_id="+id) + return found != "" + }, settleFor, 20*time.Millisecond, "the socket left no access line") + return found +} + +// closesWith sends a close frame of code and waits for the router's answer. +func (s *SocketCloseLogSuite) closesWith(connection *websocket.Conn, code int) { + s.Require().NoError(connection.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(code, ""))) + _, _ = s.socketEnd(connection) +} + +func (s *SocketCloseLogSuite) TestACloseCommandIsTheCallersClose() { + // Catches the session's end, which the command causes before the reader stops, logged in + // place of the command. + _, connection, id := s.watched(nil) + + s.Require().NoError(connection.WriteJSON(map[string]any{"type": "close"})) + _, _ = s.socketEnd(connection) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=1000 ") +} + +func (s *SocketCloseLogSuite) TestACloseFrameIsLoggedWithTheCallersCode() { + // Catches the caller's code dropped, or replaced by the one the router answers with. + _, connection, id := s.watched(nil) + + s.closesWith(connection, 4000) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=4000 ") +} + +func (s *SocketCloseLogSuite) TestADroppedConnectionIsClientGoneWithNoCode() { + // Catches gorilla's 1006 for a dropped connection logged as a close frame the caller sent. + _, connection, id := s.watched(nil) + + s.Require().NoError(connection.UnderlyingConn().Close()) + + line := s.closeLine(id) + s.Contains(line, " close_reason=client_gone ") + s.NotContains(line, "close_code=") +} + +func (s *SocketCloseLogSuite) TestAnUnreadableFrameIsARefusal() { + _, connection, id := s.watched(nil) + + s.Require().NoError(connection.WriteMessage(websocket.TextMessage, []byte("not json"))) + _, _ = s.socketEnd(connection) + + s.Contains(s.closeLine(id), " close_reason=refused close_code=1008 ") +} + +func (s *SocketCloseLogSuite) TestASessionThatEndsNamesItsEndReason() { + // Catches a session's end logged without why the session ended, or as the caller's close. + opened, connection, id := s.watched(nil) + + s.serverClient.stopSession(opened.Id) + _, _ = s.socketEnd(connection) + + s.Contains(s.closeLine(id), " close_reason=session_ended close_code=1000 end_reason=closed ") +} + +func (s *SocketCloseLogSuite) TestARelayedSocketLogsWhyItClosedOnTheNodeItLandedOn() { + // Catches the relayed socket's own reasons left out: its end reason is the holder's to log. + opened, connection, id := s.watched(s.other) + + s.serverClient.stopSession(opened.Id) + _, _ = s.socketEnd(connection) + + line := s.closeLine(id) + s.Contains(line, " close_reason=session_ended close_code=1000 ") + s.NotContains(line, "end_reason=") +} + +func (s *SocketCloseLogSuite) TestARelayedCloseCommandIsTheCallersClose() { + // Catches the session's end, which the holder reports back, logged in place of the command. + _, connection, id := s.watched(s.other) + + s.Require().NoError(connection.WriteJSON(map[string]any{"type": "close"})) + _, _ = s.socketEnd(connection) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=1000 ") +} + +func (s *SocketCloseLogSuite) TestARelayedSocketLogsTheCallersClose() { + _, connection, id := s.watched(s.other) + + s.closesWith(connection, 4001) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=4001 ") +} + +func (s *SocketCloseLogSuite) TestARelayedSocketLogsAnUnreadableFrameAsARefusal() { + _, connection, id := s.watched(s.other) + + s.Require().NoError(connection.WriteMessage(websocket.TextMessage, []byte("[1]"))) + _, _ = s.socketEnd(connection) + + s.Contains(s.closeLine(id), " close_reason=refused close_code=1008 ") +} + +func (s *SocketCloseLogSuite) TestAStopOnTheVoiceSocketIsTheCallersClose() { + connection, _, id := s.socketSession() + + s.Require().NoError(connection.WriteJSON(map[string]any{"type": "stop"})) + _, _ = s.socketEnd(connection) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=1000 ") +} + +func (s *SocketCloseLogSuite) TestACloseFrameOnTheVoiceSocketIsLoggedWithTheCallersCode() { + connection, _, id := s.socketSession() + + s.closesWith(connection, 4002) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=4002 ") +} + +func (s *SocketCloseLogSuite) TestADroppedVoiceSocketIsClientGone() { + connection, _, id := s.socketSession() + + s.Require().NoError(connection.UnderlyingConn().Close()) + + line := s.closeLine(id) + s.Contains(line, " close_reason=client_gone ") + s.NotContains(line, "close_code=") +} + +func (s *SocketCloseLogSuite) TestAVoiceSessionThatEndsIsNotTheCallersClose() { + // Catches the caller's answer to the router's close logged as a close of the caller's own. + connection, session, id := s.socketSession() + + s.serverClient.stopSession(session) + _, _ = s.socketEnd(connection) + + s.Contains(s.closeLine(id), " close_reason=session_ended close_code=1000 end_reason=closed ") +} + +func (s *SocketCloseLogSuite) TestAVoiceSocketWithNoStartFrameIsARefusal() { + id := rand.Text() + connection := s.serverClient.withRequestID(id).opens("/v1/agents/socket") + + s.Require().NoError(connection.WriteJSON(map[string]any{"type": "hello"})) + _, _ = s.socketEnd(connection) + + s.Contains(s.closeLine(id), " close_reason=refused close_code=1008 ") +} + +func (s *SocketCloseLogSuite) TestAVoiceSocketNamingACallIsARefusal() { + // Catches a refusal that names its failure's code (refuseWith) left unlogged. + id := rand.Text() + connection := s.serverClient.withRequestID(id).opens("/v1/agents/socket") + + s.Require().NoError(connection.WriteJSON(map[string]any{ + "type": "start", "session": map[string]any{"call": map[string]any{"id": "a-call", "type": "default"}}, + })) + _, _ = s.socketEnd(connection) + + s.Contains(s.closeLine(id), " close_reason=refused close_code=1008 ") +} diff --git a/acceleration/internal/api/socketend.go b/acceleration/internal/api/socketend.go new file mode 100644 index 0000000000..4145b3d2b1 --- /dev/null +++ b/acceleration/internal/api/socketend.go @@ -0,0 +1,82 @@ +package api + +import ( + "errors" + "net" + + "github.com/gorilla/websocket" + + "github.com/GetStream/Vision-Agents/acceleration/internal/session" +) + +// closeCause is why a session socket closed, logged as close_reason on its access line. +type closeCause string + +const ( + // closedByClient is a caller that sent a close frame, or a command that closed the session. + closedByClient closeCause = "client_closed" + // clientGone is a connection that broke with no close frame: it dropped, or a write to it + // failed. + clientGone closeCause = "client_gone" + // timedOut is a caller that answered no ping within pongWait. + timedOut closeCause = "timeout" + // sessionEnded is a session that ended, for the end_reason logged beside it. + sessionEnded closeCause = "session_ended" + // refusedByRouter is a caller the router refused: a start frame, a session it would not + // open, a frame it could not read or one past maxSocketMessage. + refusedByRouter closeCause = "refused" + // serverFailed is a failure of the router's own. + serverFailed closeCause = "server_error" + // routerShutdown is a session the router stopped as it went away. + routerShutdown closeCause = "shutdown" +) + +// socketEnd is why a socket closed: the cause, the code of the close frame the router sent or +// the caller did (0 when neither did), and the session's end reason when the session ended. +type socketEnd struct { + cause closeCause + code int + endReason session.EndReason +} + +// fields are socketEnd's fields on the access line, none for a request that opened no socket. +func (e socketEnd) fields() []any { + if e.cause == "" { + return nil + } + fields := []any{"close_reason", string(e.cause)} + if e.code != 0 { + fields = append(fields, "close_code", e.code) + } + if e.endReason != "" { + fields = append(fields, "end_reason", string(e.endReason)) + } + return fields +} + +// readEnd is why a socket's reader stopped on err. gorilla reports a connection that dropped +// as a close with 1006, which no peer may send (RFC 6455 section 7.4.1, +// https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1), and answers a frame past the read +// limit with 1009 itself. +func readEnd(err error) socketEnd { + var closed *websocket.CloseError + var failed net.Error + switch { + case errors.Is(err, websocket.ErrReadLimit): + return socketEnd{cause: refusedByRouter, code: websocket.CloseMessageTooBig} + case errors.As(err, &closed) && closed.Code != websocket.CloseAbnormalClosure: + return socketEnd{cause: closedByClient, code: closed.Code} + case errors.As(err, &failed) && failed.Timeout(): + return socketEnd{cause: timedOut} + } + return socketEnd{cause: clientGone} +} + +// sessionEnd is why a socket closed with code once its session's events stopped: a router +// restarting (1012, endingOf) or the session's end. +func sessionEnd(code int) socketEnd { + if code == websocket.CloseServiceRestart { + return socketEnd{cause: routerShutdown, code: code} + } + return socketEnd{cause: sessionEnded, code: code} +} diff --git a/acceleration/internal/api/socketend_test.go b/acceleration/internal/api/socketend_test.go new file mode 100644 index 0000000000..0e648a4688 --- /dev/null +++ b/acceleration/internal/api/socketend_test.go @@ -0,0 +1,91 @@ +package api + +import ( + "bytes" + "errors" + "io" + "log/slog" + "net" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/go-chi/chi/v5" + "github.com/gorilla/websocket" + "github.com/stretchr/testify/suite" + + "github.com/GetStream/Vision-Agents/acceleration/internal/session" + "github.com/GetStream/Vision-Agents/acceleration/internal/stack" +) + +// SocketEndSuite is why a socket closed, as its access line names it. +type SocketEndSuite struct{ suite.Suite } + +func TestSocketEndSuite(t *testing.T) { suite.Run(t, new(SocketEndSuite)) } + +// served is the access line of a request whose handler recorded ended, none recorded when +// ended is nil. +func (s *SocketEndSuite) served(ended *socketEnd) string { + logged := &bytes.Buffer{} + routes := chi.NewRouter() + routes.Get("/v1/agents/socket", func(w http.ResponseWriter, r *http.Request) { + if ended != nil { + recordClose(r.Context(), *ended) + } + }) + server := &Server{logger: slog.New(slog.NewTextHandler(logged, nil))} + server.withRequestLog(routes, routes).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/v1/agents/socket", nil)) + return logged.String() +} + +func (s *SocketEndSuite) TestTheAccessLineNamesWhyTheSocketClosed() { + line := s.served(&socketEnd{cause: sessionEnded, code: websocket.CloseNormalClosure, endReason: session.EndAgentHangup}) + + s.Contains(line, " close_reason=session_ended close_code=1000 end_reason=agent_hangup") +} + +func (s *SocketEndSuite) TestACloseWithNoFrameOrSessionEndLogsNeither() { + line := s.served(&socketEnd{cause: clientGone}) + + s.Contains(line, " close_reason=client_gone") + s.NotContains(line, "close_code=") + s.NotContains(line, "end_reason=") +} + +func (s *SocketEndSuite) TestARequestThatOpenedNoSocketLogsNoCloseReason() { + // The control: the line of a request that recorded no close is the line it was on base + // 4bee273a1, which had no close fields at all. + line := s.served(nil) + + s.Contains(line, `msg="served a request"`) + s.False(strings.Contains(line, "close_"), line) +} + +func (s *SocketEndSuite) TestACloseFrameIsTheCallersCloseWithItsCode() { + // Catches a wrapped close (readCommands wraps its read error) left unrecognised. + s.Equal(socketEnd{cause: closedByClient, code: 4001}, readEnd(stack.Wrap(&websocket.CloseError{Code: 4001}))) + s.Equal(socketEnd{cause: closedByClient, code: websocket.CloseGoingAway}, + readEnd(&websocket.CloseError{Code: websocket.CloseGoingAway})) +} + +func (s *SocketEndSuite) TestADroppedConnectionIsClientGoneWithNoCode() { + // gorilla reports a dropped connection as 1006; no peer sends that code. + s.Equal(socketEnd{cause: clientGone}, readEnd(&websocket.CloseError{Code: websocket.CloseAbnormalClosure})) + s.Equal(socketEnd{cause: clientGone}, readEnd(stack.Wrap(io.ErrUnexpectedEOF))) + s.Equal(socketEnd{cause: clientGone}, readEnd(&net.OpError{Op: "read", Err: errors.New("connection reset by peer")})) +} + +func (s *SocketEndSuite) TestAReadPastItsDeadlineIsATimeout() { + s.Equal(socketEnd{cause: timedOut}, readEnd(stack.Wrap(&net.OpError{Op: "read", Err: os.ErrDeadlineExceeded}))) +} + +func (s *SocketEndSuite) TestAFramePastTheReadLimitIsRefusedWith1009() { + s.Equal(socketEnd{cause: refusedByRouter, code: websocket.CloseMessageTooBig}, readEnd(stack.Wrap(websocket.ErrReadLimit))) +} + +func (s *SocketEndSuite) TestARouterRestartingIsAShutdownAndAnyOtherEndTheSessions() { + s.Equal(socketEnd{cause: routerShutdown, code: websocket.CloseServiceRestart}, sessionEnd(websocket.CloseServiceRestart)) + s.Equal(socketEnd{cause: sessionEnded, code: websocket.CloseNormalClosure}, sessionEnd(websocket.CloseNormalClosure)) +} diff --git a/acceleration/internal/api/socketws.go b/acceleration/internal/api/socketws.go index 5e04a43ca3..8567681df3 100644 --- a/acceleration/internal/api/socketws.go +++ b/acceleration/internal/api/socketws.go @@ -92,15 +92,18 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { } // A refusal ends the socket with closeSocket: nothing else reads it yet, and the caller // is held to answer the close so the error frame before it is not lost. + refused := socketEnd{cause: refusedByRouter, code: websocket.ClosePolicyViolation} refuse := func(message string) { _ = writeFrame(frame{"type": "error", "error": message}) closeSocket(connection, websocket.ClosePolicyViolation, "") + recordClose(r.Context(), refused) } // refuseWith also names the failure's code and type, which are what // POST /v1/agents/sessions answers the same failure with. refuseWith := func(failure APIError) { _ = writeFrame(frame{"type": "error", "error": failure.Message, "code": failure.Code, "error_type": failure.Type}) closeSocket(connection, websocket.ClosePolicyViolation, "") + recordClose(r.Context(), refused) } _ = connection.SetReadDeadline(time.Now().Add(startWait)) @@ -139,6 +142,7 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { if _, answered := errors.AsType[APIError](failure); failure != nil && !answered { s.logger.Error("could not read the agent config of a socket session", "error", failure) refuseWith(internalError()) + recordClose(r.Context(), socketEnd{cause: serverFailed, code: websocket.ClosePolicyViolation}) return } if failure != nil { @@ -165,6 +169,7 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { if errors.Is(err, session.ErrAppSettingsUnreadable) { s.logger.Error("could not open a socket session", "error", err) refuseWith(internalError()) + recordClose(r.Context(), socketEnd{cause: serverFailed, code: websocket.ClosePolicyViolation}) return } if errors.Is(err, session.ErrSessionExists) || err != nil { @@ -173,6 +178,14 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { } s.rememberTimezone(ctx, customerID, spec) owner := OwnerFrom(ctx) + // Deferred before the session is closed, so it runs once the session has ended. + var ended socketEnd + defer func() { + if ended.cause == sessionEnded { + ended.endReason = created.EndedFor() + } + recordClose(r.Context(), ended) + }() defer func() { if _, err := s.sessions.Close(created.ID(), owner); err != nil { s.logger.Debug("could not close the socket session", "session", created.ID(), "error", err) @@ -180,6 +193,7 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { }() if err := writeFrame(frame{"type": "session", "session": sessionOf(ctx, created), "sample_rate": edge.SampleRate()}); err != nil { + ended = socketEnd{cause: clientGone} return } @@ -190,6 +204,7 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { // so the close is still sent; closeBeforeReader bounds the wait for it to closeWait. events, detach := created.Watch() readDone := make(chan struct{}) + over := make(chan struct{}) hungUp := make(chan struct{}) defer func() { close(readDone) @@ -200,6 +215,7 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { defer close(hungUp) for range events { } + close(over) closeBeforeReader(connection, websocket.CloseNormalClosure, "the conversation is over", readDone) // A caller that never answers leaves the read loop reading; closing ends it. _ = connection.Close() @@ -208,11 +224,21 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { for { kind, payload, err := connection.ReadMessage() if err != nil { + // The caller's answer to the close sent once the conversation was over is no close of + // the caller's own. + select { + case <-over: + ended = socketEnd{cause: sessionEnded, code: websocket.CloseNormalClosure} + default: + ended = readEnd(err) + } return } switch kind { case websocket.BinaryMessage: + // The agent left the call, so the conversation is over. if err := edge.Hear(payload); err != nil { + ended = socketEnd{cause: sessionEnded, code: websocket.CloseNormalClosure} return } case websocket.TextMessage: @@ -220,6 +246,7 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { Type string `json:"type"` } if json.Unmarshal(payload, &command) == nil && command.Type == "stop" { + ended = socketEnd{cause: closedByClient, code: websocket.CloseNormalClosure} return } } diff --git a/acceleration/internal/session/metrics.go b/acceleration/internal/session/metrics.go index 464609e5a0..bbd8b60f22 100644 --- a/acceleration/internal/session/metrics.go +++ b/acceleration/internal/session/metrics.go @@ -103,6 +103,10 @@ func (s *Session) kept() EndReason { return s.endLabel() } +// EndedFor is why the session ended, as its row keeps it. It is read once the session has +// ended: before, it is the reason a session closed now would be kept under. +func (s *Session) EndedFor() EndReason { return s.kept() } + // counted takes the session's end into the session metrics if the manager held it. Called // once, from close. func (s *Session) counted() { From 6160a553c93d4377a11989119744fa2cf3874992 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 15:38:06 +0100 Subject: [PATCH 2/8] AI-3418: log a session's end that a close command followed as the session's A close command or stop that crosses the router's close for the session's end was logged client_closed. The events socket now counts a close command only when the session was still held, the relayed socket reads it as the end arrives, and the voice socket's stop checks whether the conversation was already over. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/relayws.go | 17 ++++--- acceleration/internal/api/sessionws.go | 11 +++-- .../internal/api/socket_close_log_test.go | 48 +++++++++++++++++++ acceleration/internal/api/socketws.go | 8 +++- 4 files changed, 73 insertions(+), 11 deletions(-) diff --git a/acceleration/internal/api/relayws.go b/acceleration/internal/api/relayws.go index 5fc2b97e46..4f42903cd9 100644 --- a/acceleration/internal/api/relayws.go +++ b/acceleration/internal/api/relayws.go @@ -192,18 +192,15 @@ func (s *Server) watchRemoteSession(w http.ResponseWriter, r *http.Request, id s go func() { gone <- s.readRelayedCommands(connection, state, watcher, id, &closing) }() - ended := s.writeRelayedEvents(connection, state, socket, watcher, id, watching(r), gone, endingOf(asked, socket.halted.Load)) - // The holder ends the session on a close command, which reaches this node as its end. - if closing.Load() && ended.cause == sessionEnded { - ended.cause = closedByClient - } + ended := s.writeRelayedEvents(connection, state, socket, watcher, id, watching(r), gone, endingOf(asked, socket.halted.Load), &closing) recordClose(r.Context(), ended) return true } // writeRelayedEvents writes what arrives on the bus out to the caller, and keeps both the // socket and the watcher behind it alive. It says why the socket closed; the session's end -// reason is the holder's to log. +// reason is the holder's to log. closing is whether the caller had sent a close command: the +// holder ends the session on one, which reaches this node as its end. // // The ping and the refresh share a tick because they say the same thing in each // direction: this socket is still being read, and the watcher standing for it elsewhere @@ -216,6 +213,7 @@ func (s *Server) writeRelayedEvents( asked wanted, gone <-chan error, ended ending, + closing *atomic.Bool, ) socketEnd { ping := time.NewTicker(pingEvery) defer ping.Stop() @@ -231,8 +229,13 @@ func (s *Server) writeRelayedEvents( case <-socket.closed: code, reason := ended() + // Read as the end arrives: a close command sent after it did not cause it. + end := sessionEnd(code) + if closing.Load() && end.cause == sessionEnded { + end.cause = closedByClient + } closeBeforeReader(connection, code, reason, gone) - return sessionEnd(code) + return end case payload := <-socket.frames: if !asked.takesFrame(frameType(payload)) { diff --git a/acceleration/internal/api/sessionws.go b/acceleration/internal/api/sessionws.go index a2fcd8a054..4f5fe60629 100644 --- a/acceleration/internal/api/sessionws.go +++ b/acceleration/internal/api/sessionws.go @@ -183,6 +183,7 @@ func (s *Server) watchSession(w http.ResponseWriter, r *http.Request) { }() ended := s.writeEvents(connection, events, watching(r), gone, endingOf(resuming, found.Halted)) // A close command ends the session before the reader stops, so the writer sees the end first. + // One that came once the session had ended set no closing, and the end stays the session's. if closing.Load() && ended.cause == sessionEnded { ended.cause = closedByClient } @@ -305,8 +306,10 @@ func (s *Server) writeEvents(connection *websocket.Conn, events <-chan session.E case stopped := <-gone: switch { case stopped == nil: + // The reader stops on a close command, whoever ended the session; watchSession + // tells the two apart. closeSocket(connection, websocket.CloseNormalClosure, "the session ended") - return socketEnd{cause: closedByClient, code: websocket.CloseNormalClosure} + return socketEnd{cause: sessionEnded, code: websocket.CloseNormalClosure} case errors.Is(stopped, errUnreadableFrame): refuseUnreadable(connection) return socketEnd{cause: refusedByRouter, code: websocket.ClosePolicyViolation} @@ -380,7 +383,8 @@ type watcherCommand struct { // // It returns nil once a command closed the session, errUnreadableFrame for a frame that is not // a command, and the read's own error when the connection ended. closing is set before a close -// command is applied. +// command is applied, unless the session had already left the manager: then its end was not +// the command's. func (s *Server) readCommands( connection *websocket.Conn, found *session.Session, seat session.Seat, sender routing.Caller, closing *atomic.Bool, ) error { @@ -403,7 +407,8 @@ func (s *Server) readCommands( return errUnreadableFrame } if command.Type == "close" { - closing.Store(true) + _, held := s.sessions.Get(found.ID(), seat.Owner) + closing.Store(held) } if !s.applyCommand(found, seat, sender, command) { diff --git a/acceleration/internal/api/socket_close_log_test.go b/acceleration/internal/api/socket_close_log_test.go index 9d56d95d35..e71171d08c 100644 --- a/acceleration/internal/api/socket_close_log_test.go +++ b/acceleration/internal/api/socket_close_log_test.go @@ -77,6 +77,54 @@ func (s *SocketCloseLogSuite) closesWith(connection *websocket.Conn, code int) { _, _ = s.socketEnd(connection) } +// awaitRouterClose reads until the router's close frame arrives and leaves it unanswered, so +// the caller can still send what it would have sent as the close crossed it. +func (s *SocketCloseLogSuite) awaitRouterClose(connection *websocket.Conn) { + connection.SetCloseHandler(func(int, string) error { return nil }) + s.Require().NoError(connection.SetReadDeadline(time.Now().Add(settleFor))) + for { + if _, _, err := connection.ReadMessage(); err != nil { + s.Require().True(websocket.IsCloseError(err, websocket.CloseNormalClosure), "the router sent no close: %v", err) + return + } + } +} + +// commandAfterTheEnd stops the session, then sends command once the router's close for the +// session's end has arrived, then answers that close. +func (s *SocketCloseLogSuite) commandAfterTheEnd(connection *websocket.Conn, session, command string) { + s.serverClient.stopSession(session) + s.awaitRouterClose(connection) + s.Require().NoError(connection.WriteJSON(map[string]any{"type": command})) + s.Require().NoError(connection.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))) +} + +func (s *SocketCloseLogSuite) TestACloseCommandAfterTheSessionEndedIsTheSessionsEnd() { + // Catches the first cause lost: an SDK hanging up sends close as the router's close for + // the session's end crosses it. + opened, connection, id := s.watched(nil) + + s.commandAfterTheEnd(connection, opened.Id, "close") + + s.Contains(s.closeLine(id), " close_reason=session_ended close_code=1000 end_reason=closed ") +} + +func (s *SocketCloseLogSuite) TestARelayedCloseCommandAfterTheSessionEndedIsTheSessionsEnd() { + opened, connection, id := s.watched(s.other) + + s.commandAfterTheEnd(connection, opened.Id, "close") + + s.Contains(s.closeLine(id), " close_reason=session_ended close_code=1000 ") +} + +func (s *SocketCloseLogSuite) TestAStopOnTheVoiceSocketAfterTheSessionEndedIsTheSessionsEnd() { + connection, session, id := s.socketSession() + + s.commandAfterTheEnd(connection, session, "stop") + + s.Contains(s.closeLine(id), " close_reason=session_ended close_code=1000 end_reason=closed ") +} + func (s *SocketCloseLogSuite) TestACloseCommandIsTheCallersClose() { // Catches the session's end, which the command causes before the reader stops, logged in // place of the command. diff --git a/acceleration/internal/api/socketws.go b/acceleration/internal/api/socketws.go index a647c2e409..3661d4dfae 100644 --- a/acceleration/internal/api/socketws.go +++ b/acceleration/internal/api/socketws.go @@ -265,7 +265,13 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { Type string `json:"type"` } if json.Unmarshal(payload, &command) == nil && command.Type == "stop" { - ended = socketEnd{cause: closedByClient, code: websocket.CloseNormalClosure} + // A stop sent once the conversation was over did not end it. + select { + case <-over: + ended = socketEnd{cause: sessionEnded, code: websocket.CloseNormalClosure} + default: + ended = socketEnd{cause: closedByClient, code: websocket.CloseNormalClosure} + } return } } From 2d89515ff7f25c090ec06a85d3e75c35135ace78 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 15:51:44 +0100 Subject: [PATCH 3/8] AI-3418: let the holder say whether a relayed close command ended the session The socket's node learns of the end over the bus, often after a close command the caller sent once the session had ended. The holder now marks its Closed with by_command when the command it applied ended the session, and both the holder and the local socket ask the manager (closesSession) whether it still held the session. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/relayws.go | 48 +++++++++++-------- acceleration/internal/api/sessionws.go | 14 ++++-- .../internal/api/socket_close_log_test.go | 12 +++++ acceleration/internal/relay/bus.go | 2 + 4 files changed, 51 insertions(+), 25 deletions(-) diff --git a/acceleration/internal/api/relayws.go b/acceleration/internal/api/relayws.go index 4f42903cd9..4d14e5951b 100644 --- a/acceleration/internal/api/relayws.go +++ b/acceleration/internal/api/relayws.go @@ -66,6 +66,9 @@ type remoteSocket struct { once sync.Once // halted is set before closed when the holder's router stopped the session. halted atomic.Bool + // byCommand is set before closed when a close command this socket carried ended the + // session. + byCommand atomic.Bool } func (r *remoteSocket) close() { r.once.Do(func() { close(r.closed) }) } @@ -88,6 +91,8 @@ type proxyWatcher struct { // saying so has gone, and the watcher it left behind would otherwise hold a // persistent conversation open and go on being offered the model's tool calls. seen time.Time + // closing is set before a close command that ends the session is applied (closesSession). + closing atomic.Bool } // newRelayed starts both subscriptions and returns once they are live, so a session @@ -188,19 +193,16 @@ func (s *Server) watchRemoteSession(w http.ResponseWriter, r *http.Request, id s connection.SetReadLimit(maxSocketMessage) gone := make(chan error, 1) - var closing atomic.Bool go func() { - gone <- s.readRelayedCommands(connection, state, watcher, id, &closing) + gone <- s.readRelayedCommands(connection, state, watcher, id) }() - ended := s.writeRelayedEvents(connection, state, socket, watcher, id, watching(r), gone, endingOf(asked, socket.halted.Load), &closing) - recordClose(r.Context(), ended) + recordClose(r.Context(), s.writeRelayedEvents(connection, state, socket, watcher, id, watching(r), gone, endingOf(asked, socket.halted.Load))) return true } // writeRelayedEvents writes what arrives on the bus out to the caller, and keeps both the // socket and the watcher behind it alive. It says why the socket closed; the session's end -// reason is the holder's to log. closing is whether the caller had sent a close command: the -// holder ends the session on one, which reaches this node as its end. +// reason is the holder's to log. // // The ping and the refresh share a tick because they say the same thing in each // direction: this socket is still being read, and the watcher standing for it elsewhere @@ -213,7 +215,6 @@ func (s *Server) writeRelayedEvents( asked wanted, gone <-chan error, ended ending, - closing *atomic.Bool, ) socketEnd { ping := time.NewTicker(pingEvery) defer ping.Stop() @@ -229,9 +230,10 @@ func (s *Server) writeRelayedEvents( case <-socket.closed: code, reason := ended() - // Read as the end arrives: a close command sent after it did not cause it. + // The holder says whether the caller's close command ended the session: one sent + // after the end did not, and the end may reach this node after it. end := sessionEnd(code) - if closing.Load() && end.cause == sessionEnded { + if socket.byCommand.Load() && end.cause == sessionEnded { end.cause = closedByClient } closeBeforeReader(connection, code, reason, gone) @@ -269,8 +271,8 @@ func (s *Server) writeRelayedEvents( // a command ends this socket as it ends a local one; the holder would only report it. // // It returns errUnreadableFrame for a frame that is not a command, and the read's own error -// when the connection ended. closing is set before a close command is carried. -func (s *Server) readRelayedCommands(connection *websocket.Conn, state *relayed, watcher, id string, closing *atomic.Bool) error { +// when the connection ended. +func (s *Server) readRelayedCommands(connection *websocket.Conn, state *relayed, watcher, id string) error { connection.SetReadDeadline(time.Now().Add(pongWait)) connection.SetPongHandler(func(string) error { return connection.SetReadDeadline(time.Now().Add(pongWait)) @@ -289,9 +291,6 @@ func (s *Server) readRelayedCommands(connection *websocket.Conn, state *relayed, if json.Unmarshal(payload, &command) != nil { return errUnreadableFrame } - if command.Type == "close" { - closing.Store(true) - } if err := state.bus.Publish(context.Background(), state.bus.Commands(), relay.Request{ Type: relay.Command, @@ -401,7 +400,7 @@ func (s *Server) attachProxy(ctx context.Context, state *relayed, request relay. } go s.runRelayedCommands(found, proxy) - go s.publishSessionEvents(ctx, state, events, request.Watcher, request.Session, key, found.Halted) + go s.publishSessionEvents(ctx, state, events, request.Watcher, request.Session, key, found.Halted, proxy.closing.Load) } // publishSessionEvents puts one session's events on the bus for the socket watching it @@ -411,7 +410,7 @@ func (s *Server) publishSessionEvents( state *relayed, events <-chan session.Event, watcher, id, key string, - halted func() bool, + halted, byCommand func() bool, ) { // The events channel closing is either the session ending or the watcher being // detached, and both end the watcher: dropping it here is what closes its command @@ -443,11 +442,12 @@ func (s *Server) publishSessionEvents( } if err := state.bus.Publish(ctx, state.bus.Events(), relay.Response{ - Type: relay.Closed, - Node: state.bus.Node(), - Owner: key, - Watcher: watcher, - Halted: halted(), + Type: relay.Closed, + Node: state.bus.Node(), + Owner: key, + Watcher: watcher, + Halted: halted(), + ByCommand: byCommand(), }); err != nil { s.logger.Debug("could not relay the end of a session", "session", id, "error", err) } @@ -465,6 +465,9 @@ func (s *Server) runRelayedCommands(found *session.Session, proxy *proxyWatcher) // The other node holds the socket's address, so only its user is counted here. sender := routing.Caller{UserID: proxy.owner.UserID, ServerSide: proxy.owner.Kind == auth.KindServer, Verified: proxy.owner.UserID != "" && proxy.owner.Kind.Verified()} + if command.Type == "close" { + proxy.closing.Store(s.closesSession(found, proxy.seat.Owner)) + } s.applyCommand(found, proxy.seat, sender, command) } } @@ -521,6 +524,9 @@ func (r *relayed) deliver(payload []byte) { if response.Halted { socket.halted.Store(true) } + if response.ByCommand { + socket.byCommand.Store(true) + } socket.close() return } diff --git a/acceleration/internal/api/sessionws.go b/acceleration/internal/api/sessionws.go index 4f5fe60629..48b4598449 100644 --- a/acceleration/internal/api/sessionws.go +++ b/acceleration/internal/api/sessionws.go @@ -383,8 +383,7 @@ type watcherCommand struct { // // It returns nil once a command closed the session, errUnreadableFrame for a frame that is not // a command, and the read's own error when the connection ended. closing is set before a close -// command is applied, unless the session had already left the manager: then its end was not -// the command's. +// command that ends the session is applied (closesSession). func (s *Server) readCommands( connection *websocket.Conn, found *session.Session, seat session.Seat, sender routing.Caller, closing *atomic.Bool, ) error { @@ -407,8 +406,7 @@ func (s *Server) readCommands( return errUnreadableFrame } if command.Type == "close" { - _, held := s.sessions.Get(found.ID(), seat.Owner) - closing.Store(held) + closing.Store(s.closesSession(found, seat.Owner)) } if !s.applyCommand(found, seat, sender, command) { @@ -417,6 +415,14 @@ func (s *Server) readCommands( } } +// closesSession is whether a close command from owner ends found: the manager still holds it. +// A session that already left the manager was ended by something else, which a close command +// sent as its end crossed it only follows. +func (s *Server) closesSession(found *session.Session, owner session.Owner) bool { + _, held := s.sessions.Get(found.ID(), owner) + return held +} + // errNoApprovalWaits answers a tool_approval no call waits for. var errNoApprovalWaits = errors.New("tool_approval reached no call waiting for it: the call was already " + "answered or stopped, or its tool_call_id, request_id or turn_id names none") diff --git a/acceleration/internal/api/socket_close_log_test.go b/acceleration/internal/api/socket_close_log_test.go index e71171d08c..56e6d76856 100644 --- a/acceleration/internal/api/socket_close_log_test.go +++ b/acceleration/internal/api/socket_close_log_test.go @@ -117,6 +117,18 @@ func (s *SocketCloseLogSuite) TestARelayedCloseCommandAfterTheSessionEndedIsTheS s.Contains(s.closeLine(id), " close_reason=session_ended close_code=1000 ") } +func (s *SocketCloseLogSuite) TestARelayedCloseCommandAheadOfTheEndItFollowedIsTheSessionsEnd() { + // Catches the end judged on the socket's node: the holder's word of the end may reach it + // after a close command the caller sent once the session had ended. + opened, connection, id := s.watched(s.other) + + s.serverClient.stopSession(opened.Id) + s.Require().NoError(connection.WriteJSON(map[string]any{"type": "close"})) + _, _ = s.socketEnd(connection) + + s.Contains(s.closeLine(id), " close_reason=session_ended close_code=1000 ") +} + func (s *SocketCloseLogSuite) TestAStopOnTheVoiceSocketAfterTheSessionEndedIsTheSessionsEnd() { connection, session, id := s.socketSession() diff --git a/acceleration/internal/relay/bus.go b/acceleration/internal/relay/bus.go index 371be8cf93..396abdb286 100644 --- a/acceleration/internal/relay/bus.go +++ b/acceleration/internal/relay/bus.go @@ -109,6 +109,8 @@ type Response struct { Payload json.RawMessage `json:"payload,omitempty"` // Halted is a Closed for a session the holder's router stopped on its way down. Halted bool `json:"halted,omitempty"` + // ByCommand is a Closed for a session that a close command from the watcher ended. + ByCommand bool `json:"by_command,omitempty"` } // Options configures a Bus. From a61c661f3f0c9f20dbad4f67adf92cfdab752af1 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 15:53:25 +0100 Subject: [PATCH 4/8] AI-3418: pin the socket close reasons the tests left open Rows for a command other than close before the session's end (local and relayed), audio sent after the end on the voice socket, and a write that fails on the events and relayed sockets. Co-Authored-By: Claude Opus 5.5 --- .../internal/api/socket_close_log_test.go | 38 ++++++++++++++++ acceleration/internal/api/socketend_test.go | 43 +++++++++++++++++++ 2 files changed, 81 insertions(+) diff --git a/acceleration/internal/api/socket_close_log_test.go b/acceleration/internal/api/socket_close_log_test.go index 56e6d76856..a9153d3057 100644 --- a/acceleration/internal/api/socket_close_log_test.go +++ b/acceleration/internal/api/socket_close_log_test.go @@ -137,6 +137,44 @@ func (s *SocketCloseLogSuite) TestAStopOnTheVoiceSocketAfterTheSessionEndedIsThe s.Contains(s.closeLine(id), " close_reason=session_ended close_code=1000 end_reason=closed ") } +// commandThenTheEnd sends a command other than close, waits for the session's answer to it, +// then stops the session. +func (s *SocketCloseLogSuite) commandThenTheEnd(connection *websocket.Conn, session string) { + s.Require().NoError(connection.WriteJSON(map[string]any{"type": "not-a-command"})) + s.await(connection, "error") + s.serverClient.stopSession(session) + _, _ = s.socketEnd(connection) +} + +func (s *SocketCloseLogSuite) TestAnotherCommandBeforeTheSessionEndsIsNotTheCallersClose() { + // Catches any command taken for a close command. + opened, connection, id := s.watched(nil) + + s.commandThenTheEnd(connection, opened.Id) + + s.Contains(s.closeLine(id), " close_reason=session_ended close_code=1000 end_reason=closed ") +} + +func (s *SocketCloseLogSuite) TestAnotherRelayedCommandBeforeTheSessionEndsIsNotTheCallersClose() { + opened, connection, id := s.watched(s.other) + + s.commandThenTheEnd(connection, opened.Id) + + s.Contains(s.closeLine(id), " close_reason=session_ended close_code=1000 ") +} + +func (s *SocketCloseLogSuite) TestAudioOnTheVoiceSocketAfterTheSessionEndedIsTheSessionsEnd() { + // Catches audio the agent can no longer hear taken for a connection that broke. + connection, session, id := s.socketSession() + + s.serverClient.stopSession(session) + s.awaitRouterClose(connection) + s.Require().NoError(connection.WriteMessage(websocket.BinaryMessage, make([]byte, 640))) + s.Require().NoError(connection.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))) + + s.Contains(s.closeLine(id), " close_reason=session_ended close_code=1000 end_reason=closed ") +} + func (s *SocketCloseLogSuite) TestACloseCommandIsTheCallersClose() { // Catches the session's end, which the command causes before the reader stops, logged in // place of the command. diff --git a/acceleration/internal/api/socketend_test.go b/acceleration/internal/api/socketend_test.go index 0e648a4688..da5a384022 100644 --- a/acceleration/internal/api/socketend_test.go +++ b/acceleration/internal/api/socketend_test.go @@ -2,6 +2,7 @@ package api import ( "bytes" + "encoding/json" "errors" "io" "log/slog" @@ -16,6 +17,7 @@ import ( "github.com/gorilla/websocket" "github.com/stretchr/testify/suite" + "github.com/GetStream/Vision-Agents/acceleration/internal/agent" "github.com/GetStream/Vision-Agents/acceleration/internal/session" "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) @@ -63,6 +65,47 @@ func (s *SocketEndSuite) TestARequestThatOpenedNoSocketLogsNoCloseReason() { s.False(strings.Contains(line, "close_"), line) } +// brokenSocket is the router's side of a real socket whose connection is closed under it in +// both directions, so the next write to it fails. +func (s *SocketEndSuite) brokenSocket() *websocket.Conn { + upgraded := make(chan *websocket.Conn, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + connection, err := (&websocket.Upgrader{}).Upgrade(w, r, nil) + s.Require().NoError(err) + upgraded <- connection + <-r.Context().Done() + })) + s.T().Cleanup(server.Close) + client, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http"), nil) + s.Require().NoError(err) + routerSide := <-upgraded + s.Require().NoError(client.UnderlyingConn().Close()) + s.Require().NoError(routerSide.UnderlyingConn().Close()) + return routerSide +} + +func (s *SocketEndSuite) TestAnEventTheCallerCannotBeSentIsClientGone() { + // Catches a failed write left with no reason. + events := make(chan session.Event, 1) + events <- agent.Said{TurnID: "a-turn", Text: "hello"} + server := &Server{logger: slog.New(slog.DiscardHandler)} + + ended := server.writeEvents(s.brokenSocket(), events, wanted{}, make(chan error), endingOf(resuming{}, func() bool { return false })) + + s.Equal(socketEnd{cause: clientGone}, ended) +} + +func (s *SocketEndSuite) TestARelayedFrameTheCallerCannotBeSentIsClientGone() { + socket := &remoteSocket{frames: make(chan json.RawMessage, 1), closed: make(chan struct{})} + socket.frames <- json.RawMessage(`{"type":"said"}`) + server := &Server{logger: slog.New(slog.DiscardHandler)} + + ended := server.writeRelayedEvents(s.brokenSocket(), nil, socket, "a-watcher", "a-session", wanted{}, make(chan error), + endingOf(resuming{}, func() bool { return false })) + + s.Equal(socketEnd{cause: clientGone}, ended) +} + func (s *SocketEndSuite) TestACloseFrameIsTheCallersCloseWithItsCode() { // Catches a wrapped close (readCommands wraps its read error) left unrecognised. s.Equal(socketEnd{cause: closedByClient, code: 4001}, readEnd(stack.Wrap(&websocket.CloseError{Code: 4001}))) From 4192be6adf8425915cc8761e16136a289f2c8abd Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 15:58:05 +0100 Subject: [PATCH 5/8] AI-3418: document the access line's close_reason, close_code and end_reason Co-Authored-By: Claude Opus 5.5 --- acceleration/README.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/acceleration/README.md b/acceleration/README.md index 71a405569b..0f3787f8f7 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -2138,9 +2138,24 @@ is left out when the request has none: | `request_size` | The request's `Content-Length`. None for a chunked body | | `user_id` | The end user of a request from a user's device, cut to 256 bytes. None for a backend's request, even one that names a user | | `build_version` | The release the router was built from. None in a local build | +| `close_reason` | Why a session socket closed: the events socket (`/v1/agents/sessions/{id}/events`) and `/v1/agents/socket`. None for any other request or socket. The values are below | +| `close_code` | The code of the close frame the caller sent, or of the one the router sent. None for `client_gone` and `timeout` | +| `end_reason` | Why the session ended, as its row keeps it (`closed`, `agent_hangup` and the rest), with `session_ended` only. None on a socket relayed from another node: the node running the session keeps it | A socket is logged once, when it closes, so its `duration` is how long the connection lived -rather than a time to respond and its status is the `101` of the upgrade. A `5xx` is logged +rather than a time to respond and its status is the `101` of the upgrade. A session socket's +`close_reason` is one of these: + +| `close_reason` | When | +| --- | --- | +| `client_closed` | The caller sent a close frame, or a `close` command (a `stop` on `/v1/agents/socket`) that ended the session. A command sent once the session had ended is not counted: the line says `session_ended` | +| `client_gone` | The connection broke with no close frame, or a write to the caller failed | +| `timeout` | The caller answered no ping in time, or sent no start frame in time on `/v1/agents/socket` | +| `session_ended` | The session ended for another reason. `end_reason` says which | +| `refused` | The router refused the caller: a start frame it would not take, a session it would not open, a frame it could not read (`1008`) or one past the size limit (`1009`) | +| `server_error` | `/v1/agents/socket` could not open the session for a failure of the router's own, such as a database read. The caller is sent `1008` | +| `shutdown` | The router stopped a resumable socket's session on its way down (`1012`) | + A `5xx` is logged at error instead, because an access log at a busy deployment is the one stream nobody reads all of. A preflight is not logged, nor is a `/health` probe answered below `400` with no error: the load balancer and kubelet ask every few seconds. A probe that fails is logged. The query From ba8790bf67254a4e450ed7a52649d063f0dc7280 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 16:01:22 +0100 Subject: [PATCH 6/8] AI-3418: pass a voice socket refusal's cause in, and log a caller that left before its start frame refuseWith takes the cause (refused, or server_error for the router's own failure) instead of the caller overwriting it, and the socketEnd it shared is renamed so the refused bools no longer shadow it (R1.4). A caller that closed or dropped before its start frame is logged as such, not as refused (R1.5): ReadJSON is split into the NextReader and the decode it is made of. Co-Authored-By: Claude Opus 5.5 --- .../internal/api/channel_team_test.go | 20 +++++++- .../internal/api/socket_close_log_test.go | 21 ++++++++ acceleration/internal/api/socketws.go | 49 +++++++++++-------- 3 files changed, 67 insertions(+), 23 deletions(-) diff --git a/acceleration/internal/api/channel_team_test.go b/acceleration/internal/api/channel_team_test.go index 396a9e8263..a9c48463ef 100644 --- a/acceleration/internal/api/channel_team_test.go +++ b/acceleration/internal/api/channel_team_test.go @@ -3,6 +3,7 @@ package api import ( + "crypto/rand" "maps" "net/http" "os" @@ -10,6 +11,7 @@ import ( "strings" "time" + "github.com/gorilla/websocket" "github.com/redis/rueidis" "github.com/GetStream/Vision-Agents/acceleration/internal/store" @@ -182,7 +184,8 @@ func (s *AgentTeamsSuite) TestASocketSessionIsRefusedWhenTheSettingsCannotBeRead config := s.configOf("red") s.makeSettingsUnreadable() logBefore := len(s.logged.String()) - connection := s.serverClient.opens("/v1/agents/socket") + id := rand.Text() + connection := s.serverClient.withRequestID(id).opens("/v1/agents/socket") s.Require().NoError(connection.WriteJSON(map[string]any{ "type": "start", "sample_rate": 24_000, "session": map[string]any{"config_id": config.Id}, })) @@ -194,6 +197,17 @@ func (s *AgentTeamsSuite) TestASocketSessionIsRefusedWhenTheSettingsCannotBeRead s.Equal(somethingWentWrong, refused["error"]) s.Contains(s.logged.String()[logBefore:], "the app's settings could not be read", "the 500 is logged with its error") s.Equal(string(ErrorTypeInternal), refused["error_type"]) + s.closedForTheRoutersFailure(connection, id) +} + +// closedForTheRoutersFailure is a refused socket session's access line naming the router's +// own failure, not the caller's refusal. +func (s *AgentTeamsSuite) closedForTheRoutersFailure(connection *websocket.Conn, id string) { + _, _ = s.socketEnd(connection) + s.Require().Eventually(func() bool { + return lineWith(s.logged, `msg="served a request"`, " request_id="+id) != "" + }, settleFor, 20*time.Millisecond, "the socket left no access line") + s.Contains(lineWith(s.logged, `msg="served a request"`, " request_id="+id), " close_reason=server_error close_code=1008 ") } // The device gets no text of the database error, and the router logs the error. @@ -201,7 +215,8 @@ func (s *AgentTeamsSuite) TestASocketSessionWhoseConfigTheDatabaseCannotReadIsRe id := s.utils.uuid() s.failQueries(id) logBefore := len(s.logged.String()) - connection := s.serverClient.opens("/v1/agents/socket") + request := rand.Text() + connection := s.serverClient.withRequestID(request).opens("/v1/agents/socket") s.Require().NoError(connection.WriteJSON(map[string]any{ "type": "start", "sample_rate": 24_000, "session": map[string]any{"config_id": id}, })) @@ -212,6 +227,7 @@ func (s *AgentTeamsSuite) TestASocketSessionWhoseConfigTheDatabaseCannotReadIsRe s.Equal("error", refused["type"], "%v", refused) s.Equal(somethingWentWrong, refused["error"]) s.Contains(s.logged.String()[logBefore:], "could not read the agent config of a socket session") + s.closedForTheRoutersFailure(connection, request) } // A chat that ended here is carried on by the next message, a create like any other. diff --git a/acceleration/internal/api/socket_close_log_test.go b/acceleration/internal/api/socket_close_log_test.go index a9153d3057..804220975b 100644 --- a/acceleration/internal/api/socket_close_log_test.go +++ b/acceleration/internal/api/socket_close_log_test.go @@ -311,6 +311,27 @@ func (s *SocketCloseLogSuite) TestAVoiceSocketWithNoStartFrameIsARefusal() { s.Contains(s.closeLine(id), " close_reason=refused close_code=1008 ") } +func (s *SocketCloseLogSuite) TestAVoiceSocketClosedBeforeItsStartFrameIsTheCallersClose() { + // Catches a caller that left before saying what it wanted logged as refused. + id := rand.Text() + connection := s.serverClient.withRequestID(id).opens("/v1/agents/socket") + + s.closesWith(connection, 4003) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=4003 ") +} + +func (s *SocketCloseLogSuite) TestAVoiceSocketDroppedBeforeItsStartFrameIsClientGone() { + id := rand.Text() + connection := s.serverClient.withRequestID(id).opens("/v1/agents/socket") + + s.Require().NoError(connection.UnderlyingConn().Close()) + + line := s.closeLine(id) + s.Contains(line, " close_reason=client_gone ") + s.NotContains(line, "close_code=") +} + func (s *SocketCloseLogSuite) TestAVoiceSocketNamingACallIsARefusal() { // Catches a refusal that names its failure's code (refuseWith) left unlogged. id := rand.Text() diff --git a/acceleration/internal/api/socketws.go b/acceleration/internal/api/socketws.go index 3661d4dfae..48695bfa9f 100644 --- a/acceleration/internal/api/socketws.go +++ b/acceleration/internal/api/socketws.go @@ -103,27 +103,36 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { // A refusal ends the socket with closeSocket: nothing else reads it yet, and the caller // is held to answer the close so the error frame before it is not lost. Its code is // noted for the activity record, which would count the 101 as answered; the frame says - // only the message, as it always has. - refused := socketEnd{cause: refusedByRouter, code: websocket.ClosePolicyViolation} - refuse := func(code, message string) { + // only the message, as it always has. ended is why the socket closed, for its access line. + refusal := socketEnd{cause: refusedByRouter, code: websocket.ClosePolicyViolation} + refuse := func(ended socketEnd, code, message string) { noteRefusal(w, code) _ = writeFrame(frame{"type": "error", "error": message}) closeSocket(connection, websocket.ClosePolicyViolation, "") - recordClose(r.Context(), refused) + recordClose(r.Context(), ended) } // refuseWith also names the failure's code and type, which are what - // POST /v1/agents/sessions answers the same failure with. - refuseWith := func(failure APIError) { + // POST /v1/agents/sessions answers the same failure with. cause is refusedByRouter, or + // serverFailed for a failure of the router's own. + refuseWith := func(cause closeCause, failure APIError) { noteRefusal(w, failure.Code) _ = writeFrame(frame{"type": "error", "error": failure.Message, "code": failure.Code, "error_type": failure.Type}) closeSocket(connection, websocket.ClosePolicyViolation, "") - recordClose(r.Context(), refused) + recordClose(r.Context(), socketEnd{cause: cause, code: websocket.ClosePolicyViolation}) } _ = connection.SetReadDeadline(time.Now().Add(startWait)) + // ReadJSON split in two, so that a caller that closed or dropped before its start frame is + // logged as one rather than as refused. + const startFirst = "the first frame must be a start frame naming the session" + _, message, err := connection.NextReader() + if err != nil { + refuse(readEnd(err), invalidRequest("").Code, startFirst) + return + } var start socketStart - if err := connection.ReadJSON(&start); err != nil || start.Type != "start" { - refuse(invalidRequest("").Code, "the first frame must be a start frame naming the session") + if err := json.NewDecoder(message).Decode(&start); err != nil || start.Type != "start" { + refuse(refusal, invalidRequest("").Code, startFirst) return } _ = connection.SetReadDeadline(time.Time{}) @@ -131,11 +140,11 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { // The start frame carries POST /v1/agents/sessions's body, so a request is refused here // as it is refused there. if failure, refused := refuseSessionRequest(ctx, start.Session); refused { - refuseWith(failure) + refuseWith(refusedByRouter, failure) return } if start.Session.Call != nil { - refuseWith(errSocketCall) + refuseWith(refusedByRouter, errSocketCall) return } @@ -146,7 +155,7 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { Cleared: func() { _ = writeFrame(frame{"type": "cleared"}) }, }) if err != nil { - refuseWith(errSocketSampleRate) + refuseWith(refusedByRouter, errSocketSampleRate) return } @@ -155,16 +164,15 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { // device gets no text of it. if _, answered := errors.AsType[APIError](failure); failure != nil && !answered { s.logger.Error("could not read the agent config of a socket session", "error", failure) - refuseWith(internalError()) - recordClose(r.Context(), socketEnd{cause: serverFailed, code: websocket.ClosePolicyViolation}) + refuseWith(serverFailed, internalError()) return } if failure != nil { - refuse(refusalCode(failure), store.RedactLogText(failure.Error())) + refuse(refusal, refusalCode(failure), store.RedactLogText(failure.Error())) return } if failure, refused := s.sessionFloorRefusal(ctx, start.Session); refused { - refuseWith(failure) + refuseWith(refusedByRouter, failure) return } spec := specOf(start.Session, customerID, config) @@ -177,22 +185,21 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { created, err := s.sessions.Create(ctx, spec) if answer, refused := moneyError(err); refused { - refuseWith(answer) + refuseWith(refusedByRouter, answer) return } if errors.Is(err, session.ErrAppSettingsUnreadable) { s.logger.Error("could not open a socket session", "error", err) - refuseWith(internalError()) - recordClose(r.Context(), socketEnd{cause: serverFailed, code: websocket.ClosePolicyViolation}) + refuseWith(serverFailed, internalError()) return } // Noted with the codes POST /v1/agents/sessions answers the same failures with. if errors.Is(err, session.ErrSessionExists) { - refuse(conflict("").Code, store.RedactLogText(err.Error())) + refuse(refusal, conflict("").Code, store.RedactLogText(err.Error())) return } if err != nil { - refuse(invalidRequest("").Code, store.RedactLogText(err.Error())) + refuse(refusal, invalidRequest("").Code, store.RedactLogText(err.Error())) return } s.rememberTimezone(ctx, customerID, spec) From 3a902626c14caa11b966ba711badefc0661ead64 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 16:40:33 +0100 Subject: [PATCH 7/8] AI-3418: a second close command no longer clears the first's mark closesSession is false for a close sent after the session ended, so Store overwrote the true the first close set; the socket then logged session_ended. Only set the mark. The local socket stops reading after its first close. Co-Authored-By: Claude Sonnet 5.5 --- acceleration/internal/api/relayws.go | 4 +++- acceleration/internal/api/socket_close_log_test.go | 12 ++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/api/relayws.go b/acceleration/internal/api/relayws.go index 4d14e5951b..171544df2e 100644 --- a/acceleration/internal/api/relayws.go +++ b/acceleration/internal/api/relayws.go @@ -466,7 +466,9 @@ func (s *Server) runRelayedCommands(found *session.Session, proxy *proxyWatcher) sender := routing.Caller{UserID: proxy.owner.UserID, ServerSide: proxy.owner.Kind == auth.KindServer, Verified: proxy.owner.UserID != "" && proxy.owner.Kind.Verified()} if command.Type == "close" { - proxy.closing.Store(s.closesSession(found, proxy.seat.Owner)) + if s.closesSession(found, proxy.seat.Owner) { + proxy.closing.Store(true) + } } s.applyCommand(found, proxy.seat, sender, command) } diff --git a/acceleration/internal/api/socket_close_log_test.go b/acceleration/internal/api/socket_close_log_test.go index 804220975b..d3f46c9769 100644 --- a/acceleration/internal/api/socket_close_log_test.go +++ b/acceleration/internal/api/socket_close_log_test.go @@ -247,6 +247,18 @@ func (s *SocketCloseLogSuite) TestARelayedCloseCommandIsTheCallersClose() { s.Contains(s.closeLine(id), " close_reason=client_closed close_code=1000 ") } +func (s *SocketCloseLogSuite) TestARelayedCloseCommandSentTwiceIsTheCallersClose() { + // Catches the second close, which finds the session already gone, clearing the first. + _, connection, id := s.watched(s.other) + + s.Require().NoError(connection.WriteJSON(map[string]any{"type": "close"})) + _ = connection.WriteJSON(map[string]any{"type": "close"}) + _ = connection.WriteJSON(map[string]any{"type": "close"}) + _, _ = s.socketEnd(connection) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=1000 ") +} + func (s *SocketCloseLogSuite) TestARelayedSocketLogsTheCallersClose() { _, connection, id := s.watched(s.other) From aff12063894338976d8101c7dc2dd75bea435081 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 16:40:33 +0100 Subject: [PATCH 8/8] AI-3418: end the close_reason table before the next paragraph Co-Authored-By: Claude Sonnet 5.5 --- acceleration/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/acceleration/README.md b/acceleration/README.md index 0f3787f8f7..cc72044cb5 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -2155,7 +2155,8 @@ rather than a time to respond and its status is the `101` of the upgrade. A sess | `refused` | The router refused the caller: a start frame it would not take, a session it would not open, a frame it could not read (`1008`) or one past the size limit (`1009`) | | `server_error` | `/v1/agents/socket` could not open the session for a failure of the router's own, such as a database read. The caller is sent `1008` | | `shutdown` | The router stopped a resumable socket's session on its way down (`1012`) | - A `5xx` is logged + +A `5xx` is logged at error instead, because an access log at a busy deployment is the one stream nobody reads all of. A preflight is not logged, nor is a `/health` probe answered below `400` with no error: the load balancer and kubelet ask every few seconds. A probe that fails is logged. The query