diff --git a/acceleration/README.md b/acceleration/README.md index 988c054415..ac6f948482 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -2134,23 +2134,23 @@ 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_reason` | Why a socket closed: the events socket (`/v1/agents/sessions/{id}/events`), `/v1/agents/socket`, `/v1/dispatch` and `/v1/{modality}/stream`. 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 | +| `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. None on `/v1/dispatch` and `/v1/{modality}/stream`, which hold no session | 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 session socket's +rather than a time to respond and its status is the `101` of the upgrade. A 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`) | +| `timeout` | The caller answered no ping in time, or sent no start frame in time on `/v1/agents/socket` and `/v1/{modality}/stream` | +| `session_ended` | The session ended for another reason. `end_reason` says which. Session sockets only | +| `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`). A stream socket closes a refused start frame with the code it always has (`1011`, or `1008` for an unknown target, a setting the model cannot take or a refusal about money), and a frame it cannot read after the start (`tts`, `llm`) with `1000` | +| `server_error` | A failure that is not the caller's: `/v1/agents/socket` could not open the session for a failure of the router's own, such as a database read (`1008`), or a stream socket could not read the config it names or start a provider (`1011`) | +| `shutdown` | The router stopped a resumable socket's session on its way down (`1012`), or sent a dispatch worker to reconnect elsewhere (`1001`) | A `5xx` is logged at error instead, because an access log at a busy deployment is the one stream nobody reads diff --git a/acceleration/internal/api/dispatchws.go b/acceleration/internal/api/dispatchws.go index e36e6d3bb9..e6ef582574 100644 --- a/acceleration/internal/api/dispatchws.go +++ b/acceleration/internal/api/dispatchws.go @@ -13,6 +13,7 @@ import ( "github.com/gorilla/websocket" "github.com/GetStream/Vision-Agents/acceleration/internal/dispatch" + "github.com/GetStream/Vision-Agents/acceleration/internal/stack" "github.com/GetStream/Vision-Agents/acceleration/internal/store" ) @@ -100,9 +101,10 @@ func (s *Server) dispatchCalls(w http.ResponseWriter, r *http.Request) { go func() { gone <- s.readWorker(r.Context(), connection, worker, pongs, replies, writerDone) }() - s.writeCalls(connection, worker, gone, pongs, replies, stopTaking) + ended := s.writeCalls(connection, worker, gone, pongs, replies, stopTaking) s.logger.Info("a dispatch worker stopped waiting", "worker", worker.ID) + recordClose(r.Context(), ended) } // registrationOf reads what a worker says about itself off its query string, returning why @@ -152,9 +154,9 @@ func registrationOf(r *http.Request) (dispatch.Registration, string) { } // writeCalls pushes calls and messages to the worker until it goes away, is released, or -// the socket breaks. gone carries why the reader stopped, and stopTaking tells -// the reader the writer takes no more pongs or replies from it. -func (s *Server) writeCalls(connection *websocket.Conn, worker *dispatch.Worker, gone <-chan error, pongs <-chan float64, replies <-chan frame, stopTaking func()) { +// the socket breaks, and says why the socket closed. gone carries why the reader stopped, and +// stopTaking tells the reader the writer takes no more pongs or replies from it. +func (s *Server) writeCalls(connection *websocket.Conn, worker *dispatch.Worker, gone <-chan error, pongs <-chan float64, replies <-chan frame, stopTaking func()) socketEnd { // A reader left handing over a pong would never read the worker's answer to the close. end := func(code int, reason string) { stopTaking() @@ -164,7 +166,7 @@ func (s *Server) writeCalls(connection *websocket.Conn, worker *dispatch.Worker, ready := frame{"type": "ready", "worker_id": worker.ID} if err := connection.WriteJSON(ready); err != nil { s.logger.Debug("dispatch socket write failed", "worker", worker.ID, "error", err) - return + return writeEnd(err, gone) } ping := time.NewTicker(pingEvery) @@ -175,13 +177,13 @@ func (s *Server) writeCalls(connection *websocket.Conn, worker *dispatch.Worker, case at := <-pongs: connection.SetWriteDeadline(time.Now().Add(writeWait)) if err := connection.WriteJSON(frame{"type": "pong", "at": at}); err != nil { - return + return writeEnd(err, gone) } case reply := <-replies: connection.SetWriteDeadline(time.Now().Add(writeWait)) if err := connection.WriteJSON(reply); err != nil { - return + return writeEnd(err, gone) } case call := <-worker.ToolCalls(): @@ -191,7 +193,7 @@ func (s *Server) writeCalls(connection *websocket.Conn, worker *dispatch.Worker, // returning here leads to. s.logger.Error("could not hand a tool call to a worker", "worker", worker.ID, "tool", call.Name, "error", err) - return + return writeEnd(err, gone) } case call := <-worker.Calls(): @@ -201,7 +203,7 @@ func (s *Server) writeCalls(connection *websocket.Conn, worker *dispatch.Worker, // given to. Losing it is worth an error rather than a debug line. s.logger.Error("could not hand a call to a worker", "worker", worker.ID, "call", call.CallID, "error", err) - return + return writeEnd(err, gone) } case message := <-worker.Messages(): @@ -209,24 +211,25 @@ func (s *Server) writeCalls(connection *websocket.Conn, worker *dispatch.Worker, if err := connection.WriteJSON(messageFrame(message)); err != nil { s.logger.Error("could not hand a message to a worker", "worker", worker.ID, "channel", message.ChannelID, "error", err) - return + return writeEnd(err, gone) } case <-ping.C: connection.SetWriteDeadline(time.Now().Add(writeWait)) if err := connection.WriteMessage(websocket.PingMessage, nil); err != nil { - return + return writeEnd(err, gone) } case <-s.draining: end(websocket.CloseGoingAway, "router restarting") - return + return socketEnd{cause: routerShutdown, code: websocket.CloseGoingAway} case stopped := <-gone: if errors.Is(stopped, errUnreadableFrame) { refuseUnreadable(connection) + return socketEnd{cause: refusedByRouter, code: websocket.ClosePolicyViolation} } - return + return readEnd(stopped) } } } @@ -236,7 +239,8 @@ func (s *Server) writeCalls(connection *websocket.Conn, worker *dispatch.Worker, // // A message of a type it does not know is reported and skipped rather than closing the // socket: dropping a worker over one bad message would take the calls it is already in with -// it. A frame that is not JSON at all returns errUnreadableFrame. +// it. A frame that is not JSON at all returns errUnreadableFrame, and a read that failed +// returns the read's own error. func (s *Server) readWorker(ctx context.Context, connection *websocket.Conn, worker *dispatch.Worker, pongs chan<- float64, replies chan<- frame, writerDone <-chan struct{}) error { connection.SetReadDeadline(time.Now().Add(pongWait)) connection.SetPongHandler(func(string) error { @@ -284,7 +288,7 @@ func (s *Server) readWorker(ctx context.Context, connection *websocket.Conn, wor if websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) { s.logger.Debug("dispatch socket read failed", "worker", worker.ID, "error", err) } - return nil + return stack.Wrap(err) } connection.SetReadDeadline(time.Now().Add(pongWait)) if json.Unmarshal(payload, &report) != nil { diff --git a/acceleration/internal/api/relayws.go b/acceleration/internal/api/relayws.go index 1bb220e905..9c64795b75 100644 --- a/acceleration/internal/api/relayws.go +++ b/acceleration/internal/api/relayws.go @@ -247,13 +247,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 socketEnd{cause: clientGone} + return writeEnd(err, gone) } case <-ping.C: connection.SetWriteDeadline(time.Now().Add(writeWait)) if err := connection.WriteMessage(websocket.PingMessage, nil); err != nil { - return socketEnd{cause: clientGone} + return writeEnd(err, gone) } if err := state.bus.Publish(ctx, state.bus.Commands(), relay.Request{ Type: relay.Refresh, Node: state.bus.Node(), Session: id, Watcher: watcher, diff --git a/acceleration/internal/api/sessionws.go b/acceleration/internal/api/sessionws.go index 5c8e501757..dc5b3cbe1e 100644 --- a/acceleration/internal/api/sessionws.go +++ b/acceleration/internal/api/sessionws.go @@ -331,13 +331,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 socketEnd{cause: clientGone} + return writeEnd(err, gone) } case <-ping.C: connection.SetWriteDeadline(time.Now().Add(writeWait)) if err := connection.WriteMessage(websocket.PingMessage, nil); err != nil { - return socketEnd{cause: clientGone} + return writeEnd(err, gone) } } } diff --git a/acceleration/internal/api/socket_close_log_test.go b/acceleration/internal/api/socket_close_log_test.go index d3f46c9769..eaa5d64360 100644 --- a/acceleration/internal/api/socket_close_log_test.go +++ b/acceleration/internal/api/socket_close_log_test.go @@ -10,10 +10,13 @@ import ( "time" "github.com/gorilla/websocket" + + "github.com/GetStream/Vision-Agents/acceleration/internal/dispatch" ) -// 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. +// SocketCloseLogSuite covers why a socket closed, as its access line says it: the events +// socket on the node running the session and on another one, /v1/agents/socket and +// /v1/dispatch. StreamsSuite covers /v1/{modality}/stream. type SocketCloseLogSuite struct { RouterSuite logged *lockedLog @@ -63,9 +66,15 @@ func (s *SocketCloseLogSuite) socketSession() (*websocket.Conn, string, string) // closeLine is the access line of the socket opened with request id once it has closed. func (s *SocketCloseLogSuite) closeLine(id string) string { + return s.closeLineIn(s.logged, id) +} + +// closeLineIn is the access line in logged of the socket opened with request id once it has +// closed. +func (s *RouterSuite) closeLineIn(logged *lockedLog, id string) string { var found string s.Require().Eventually(func() bool { - found = lineWith(s.logged, `msg="served a request"`, " request_id="+id) + found = lineWith(logged, `msg="served a request"`, " request_id="+id) return found != "" }, settleFor, 20*time.Millisecond, "the socket left no access line") return found @@ -195,6 +204,38 @@ func (s *SocketCloseLogSuite) TestACloseFrameIsLoggedWithTheCallersCode() { s.Contains(s.closeLine(id), " close_reason=client_closed close_code=4000 ") } +// closesAfterCommands sends commands commands the session answers with an error frame, then a +// close frame of code while those answers are still being written. +func (s *SocketCloseLogSuite) closesAfterCommands(connection *websocket.Conn, commands, code int) { + for range commands { + s.Require().NoError(connection.WriteJSON(map[string]any{"type": "not-a-command"})) + } + s.closesWith(connection, code) +} + +func (s *SocketCloseLogSuite) TestACloseFrameAsAnEventIsWrittenIsLoggedWithTheCallersCode() { + // Catches the event write the reader's answer to the close refuses logged as client_gone: + // the command's answer reaches the writer as the close arrives, so most rounds race it. + for range 5 { + _, connection, id := s.watched(nil) + + s.closesAfterCommands(connection, 1, 4006) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=4006 ") + } +} + +func (s *SocketCloseLogSuite) TestARelayedCloseFrameAsAFrameIsWrittenIsLoggedWithTheCallersCode() { + // The answers come back over the bus, so about one round in five races the close. + for range 25 { + _, connection, id := s.watched(s.other) + + s.closesAfterCommands(connection, 20, 4006) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=4006 ") + } +} + 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) @@ -356,3 +397,93 @@ func (s *SocketCloseLogSuite) TestAVoiceSocketNamingACallIsARefusal() { s.Contains(s.closeLine(id), " close_reason=refused close_code=1008 ") } + +// worker opens /v1/dispatch on node (nil for the suite's own) and waits for its ready frame, +// named by a request id of its own. +func (s *SocketCloseLogSuite) worker(node *httptest.Server) (*websocket.Conn, string) { + id := rand.Text() + client := s.serverClient.withRequestID(id) + if node != nil { + client = client.on(node) + } + connection := client.opens("/v1/dispatch") + s.await(connection, "ready") + return connection, id +} + +func (s *SocketCloseLogSuite) TestADispatchWorkersCloseFrameIsLoggedWithItsCode() { + // Catches the reader's error dropped (it returned nil on base), which logs every close as + // client_gone. + connection, id := s.worker(nil) + + s.closesWith(connection, 4004) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=4004 ") +} + +func (s *SocketCloseLogSuite) TestADispatchWorkersCloseFrameAfterAPingIsLoggedWithItsCode() { + // Catches the pong write the reader's answer to the close refuses logged as client_gone: + // the writer is handed the ping as the close arrives, so most rounds race it. + for range 5 { + connection, id := s.worker(nil) + + s.Require().NoError(connection.WriteJSON(frame{"type": "ping", "at": 1})) + s.closesWith(connection, 4005) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=4005 ") + } +} + +func (s *SocketCloseLogSuite) TestADispatchWorkersCloseFrameAfterHostToolsIsLoggedWithItsCode() { + // Catches the write of the reply to host_tools, which the reader's answer to the close + // refuses, logged as client_gone. + for range 25 { + connection, id := s.worker(nil) + + s.Require().NoError(connection.WriteJSON(frame{ + "type": "host_tools", + "agent_id": "stream-support", + "tools": []frame{{ + "name": "lookup", + "description": "d", + "parameters": frame{"type": "object"}, + }}, + })) + s.closesWith(connection, 4005) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=4005 ") + } +} + +func (s *SocketCloseLogSuite) TestADroppedDispatchWorkerIsClientGone() { + connection, id := s.worker(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) TestAnUnreadableFrameFromADispatchWorkerIsARefusal() { + connection, id := s.worker(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) TestADispatchWorkerSentElsewhereByADrainIsAShutdown() { + // Catches the drain's close logged as the worker's own answer to it, or with no code. + other, router := s.otherRouterSealedBy(dispatch.NewPool(), s.sealer, + slog.New(NewLogHandler(slog.NewTextHandler(s.logged, nil)))) + connection, id := s.worker(other) + + router.Drain() + _, _ = s.socketEnd(connection) + + line := s.closeLine(id) + s.Contains(line, " close_reason=shutdown close_code=1001 ") + s.NotContains(line, "end_reason=") +} diff --git a/acceleration/internal/api/socketend.go b/acceleration/internal/api/socketend.go index 4145b3d2b1..e311ee0cb8 100644 --- a/acceleration/internal/api/socketend.go +++ b/acceleration/internal/api/socketend.go @@ -3,13 +3,15 @@ package api import ( "errors" "net" + "time" "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. +// closeCause is why a socket closed (a session socket, /v1/dispatch, /v1/{modality}/stream), +// logged as close_reason on its access line. type closeCause string const ( @@ -18,16 +20,19 @@ const ( // 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 is a caller that answered no ping within pongWait, or sent no start frame within + // startWait. 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 is a failure of the router's own, or of a provider a stream socket could not + // start. serverFailed closeCause = "server_error" - // routerShutdown is a session the router stopped as it went away. + // routerShutdown is a session the router stopped as it went away, or a dispatch worker it + // sent to reconnect elsewhere. routerShutdown closeCause = "shutdown" ) @@ -72,6 +77,21 @@ func readEnd(err error) socketEnd { return socketEnd{cause: clientGone} } +// writeEnd is why a socket closed on a write that failed with err. gorilla refuses a write with +// ErrCloseSent once its reader has sent a close frame (its answer to the caller's close, or 1009 +// for a frame past the read limit), so the reader's end is why: gone carries it, and closeWait +// bounds the wait for it. +func writeEnd(err error, gone <-chan error) socketEnd { + if errors.Is(err, websocket.ErrCloseSent) { + select { + case stopped := <-gone: + return readEnd(stopped) + case <-time.After(closeWait): + } + } + 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 { diff --git a/acceleration/internal/api/socketend_test.go b/acceleration/internal/api/socketend_test.go index 6156198b75..50addefd2a 100644 --- a/acceleration/internal/api/socketend_test.go +++ b/acceleration/internal/api/socketend_test.go @@ -12,12 +12,14 @@ import ( "os" "strings" "testing" + "time" "github.com/go-chi/chi/v5" "github.com/gorilla/websocket" "github.com/stretchr/testify/suite" "github.com/GetStream/Vision-Agents/acceleration/internal/agent" + "github.com/GetStream/Vision-Agents/acceleration/internal/dispatch" "github.com/GetStream/Vision-Agents/acceleration/internal/session" "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) @@ -68,6 +70,13 @@ func (s *SocketEndSuite) TestARequestThatOpenedNoSocketLogsNoCloseReason() { // 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 { + routerSide, client := s.connected() + s.breaks(routerSide, client) + return routerSide +} + +// connected is the router's side of a real socket and the caller's. +func (s *SocketEndSuite) connected() (*websocket.Conn, *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) @@ -78,10 +87,13 @@ func (s *SocketEndSuite) brokenSocket() *websocket.Conn { s.T().Cleanup(server.Close) client, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http"), nil) s.Require().NoError(err) - routerSide := <-upgraded + return <-upgraded, client +} + +// breaks closes a socket's connection under both its sides. +func (s *SocketEndSuite) breaks(routerSide, client *websocket.Conn) { s.Require().NoError(client.UnderlyingConn().Close()) s.Require().NoError(routerSide.UnderlyingConn().Close()) - return routerSide } func (s *SocketEndSuite) TestAnEventTheCallerCannotBeSentIsClientGone() { @@ -132,3 +144,63 @@ func (s *SocketEndSuite) TestARouterRestartingIsAShutdownAndAnyOtherEndTheSessio s.Equal(socketEnd{cause: routerShutdown, code: websocket.CloseServiceRestart}, sessionEnd(websocket.CloseServiceRestart)) s.Equal(socketEnd{cause: sessionEnded, code: websocket.CloseNormalClosure}, sessionEnd(websocket.CloseNormalClosure)) } + +func (s *SocketEndSuite) TestADispatchWorkerThatCannotBeSentItsReadyFrameIsClientGone() { + pool := dispatch.NewPool() + worker, release := pool.Register("a-customer", dispatch.Registration{Capacity: 1}) + defer release() + server := &Server{logger: slog.New(slog.DiscardHandler), draining: make(chan struct{})} + + ended := server.writeCalls(s.brokenSocket(), worker, make(chan error), nil, nil, func() {}) + + s.Equal(socketEnd{cause: clientGone}, ended) +} + +func (s *SocketEndSuite) TestWorkADispatchWorkerCannotBeSentIsClientGone() { + // Catches a failed write to a worker left with no reason, for each kind of frame it is sent. + hosted := []dispatch.Tool{{Name: "a-tool", Description: "does a thing"}} + for name, send := range map[string]func(*dispatch.Pool, *dispatch.Worker, chan<- float64, chan<- frame){ + "pong": func(_ *dispatch.Pool, _ *dispatch.Worker, pongs chan<- float64, _ chan<- frame) { pongs <- 1 }, + "reply": func(_ *dispatch.Pool, _ *dispatch.Worker, _ chan<- float64, replies chan<- frame) { + replies <- frame{"type": "hosting"} + }, + "call": func(pool *dispatch.Pool, _ *dispatch.Worker, _ chan<- float64, _ chan<- frame) { + _, err := pool.Assign("a-customer", dispatch.Call{CallID: "a-call"}) + s.Require().NoError(err) + }, + "message": func(pool *dispatch.Pool, _ *dispatch.Worker, _ chan<- float64, _ chan<- frame) { + _, err := pool.AssignMessage("a-customer", dispatch.Message{ChannelID: "a-channel"}) + s.Require().NoError(err) + }, + "tool call": func(pool *dispatch.Pool, worker *dispatch.Worker, _ chan<- float64, _ chan<- frame) { + s.Require().NoError(pool.Host(worker, "an-agent", hosted, time.Second)) + go func() { + _, _ = pool.RunHosted(s.T().Context(), "a-customer", "an-agent", dispatch.ToolCall{ID: "a-call", Name: "a-tool"}) + }() + }, + } { + s.Run(name, func() { + pool := dispatch.NewPool() + worker, release := pool.Register("a-customer", dispatch.Registration{Capacity: 1}) + defer release() + server := &Server{logger: slog.New(slog.DiscardHandler), draining: make(chan struct{})} + routerSide, client := s.connected() + pongs, replies := make(chan float64), make(chan frame) + ended := make(chan socketEnd, 1) + go func() { ended <- server.writeCalls(routerSide, worker, make(chan error), pongs, replies, func() {}) }() + var ready frame + s.Require().NoError(client.ReadJSON(&ready)) + s.Require().Equal("ready", ready["type"]) + s.breaks(routerSide, client) + + send(pool, worker, pongs, replies) + + select { + case got := <-ended: + s.Equal(socketEnd{cause: clientGone}, got) + case <-time.After(5 * time.Second): + s.Fail("the writer did not stop on a failed write") + } + }) + } +} diff --git a/acceleration/internal/api/stream_close_log_test.go b/acceleration/internal/api/stream_close_log_test.go new file mode 100644 index 0000000000..d1e3ba45a1 --- /dev/null +++ b/acceleration/internal/api/stream_close_log_test.go @@ -0,0 +1,177 @@ +//go:build integration + +package api + +import ( + "crypto/rand" + "fmt" + + "github.com/gorilla/websocket" + + "github.com/GetStream/Vision-Agents/acceleration/internal/stt" +) + +// The access line of a /v1/{modality}/stream socket says why it closed, with the values a +// session socket uses (SocketCloseLogSuite). These sockets hold no session, so none names an +// end_reason. + +// closeLine is the access line of the socket opened with request id once it has closed. +func (s *StreamsSuite) closeLine(id string) string { + line := s.closeLineIn(s.logged, id) + s.NotContains(line, "end_reason=", "a stream socket holds no session") + return line +} + +// started opens a socket on path that the router started a model for. +func (s *StreamsSuite) started(path string, opening frame) (*websocket.Conn, string) { + connection, id := s.startNamed(path, opening) + s.Require().Equal("started", s.nextConversationFrame(connection)["type"]) + return connection, id +} + +func (s *StreamsSuite) TestEachStreamSocketLogsTheCallersCloseWithItsCode() { + // Catches a read loop that left no reason when the caller closed: each modality reads in + // a loop of its own. + for code, opened := range map[int]struct { + path string + opening frame + }{ + 4011: {"/v1/stt/stream", frame{"target": "en-low-latency"}}, + 4012: {"/v1/tts/stream", frame{"target": "en-low-latency"}}, + 4013: {"/v1/llm/stream", frame{"target": "echo/echo-model"}}, + 4014: {"/v1/sts/stream", frame{"target": "stub/stub-sts"}}, + } { + s.Run(opened.path, func() { + connection, id := s.started(opened.path, opened.opening) + + s.Require().NoError(connection.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(code, ""))) + _, _ = s.ending(connection) + + s.Contains(s.closeLine(id), fmt.Sprintf(" close_reason=client_closed close_code=%d ", code)) + }) + } +} + +func (s *StreamsSuite) TestADroppedStreamSocketIsClientGone() { + connection, id := s.started("/v1/llm/stream", frame{"target": "echo/echo-model"}) + + s.Require().NoError(connection.UnderlyingConn().Close()) + + line := s.closeLine(id) + s.Contains(line, " close_reason=client_gone ") + s.NotContains(line, "close_code=") +} + +func (s *StreamsSuite) TestAFrameAStartedStreamSocketCannotReadIsARefusal() { + // Catches it logged as a dropped connection. The router closes it with 1000, as on base + // (TestASocketTheRouterEndsWithoutAFailureClosesNormally). + connection, id := s.started("/v1/llm/stream", frame{"target": "echo/echo-model"}) + + s.Require().NoError(connection.WriteMessage(websocket.TextMessage, []byte("not json"))) + _, _ = s.ending(connection) + + s.Contains(s.closeLine(id), " close_reason=refused close_code=1000 ") +} + +func (s *StreamsSuite) TestAStartFrameWithBytesAfterItsJSONStarts() { + // Catches a read stricter than base's ReadJSON, which decodes the frame's first JSON value + // and leaves what follows it. + connection := s.serverClient.opens("/v1/llm/stream") + + s.Require().NoError(connection.WriteMessage(websocket.TextMessage, []byte(`{"type":"start","target":"echo/echo-model"} trailing`))) + + s.Equal("started", s.nextConversationFrame(connection)["type"]) +} + +func (s *StreamsSuite) TestAStartTheCallerMustChangeIsARefusal() { + // Catches each refusal of the caller's start logged as the router's failure. The close + // codes are the ones the caller is sent on base: 1011 for a plain failure, 1008 for an + // unknown target or a setting the model cannot take + // (TestAStartPinnedToABatchModelEndsAsAPolicyViolation). + keyterms := make([]string, stt.MaxKeyterms+1) + for i := range keyterms { + keyterms[i] = fmt.Sprintf("term %d", i) + } + for name, refused := range map[string]struct { + path string + opening frame + code int + }{ + "no target": {"/v1/stt/stream", frame{"tts": frame{"target": "en-low-latency"}}, 1011}, + "an unknown config": {"/v1/stt/stream", frame{"config_id": "no such config " + s.utils.uuid()}, 1011}, + "a bad tag": {"/v1/stt/stream", frame{"target": "en-low-latency", "tags": frame{"Not A Key!": "x"}}, 1011}, + "an stt option": {"/v1/stt/stream", frame{"target": "en-low-latency", "stt": frame{"mode": "whichever"}}, 1011}, + "too many keyterms": {"/v1/stt/stream", frame{"target": "stub/stub-model", "stt": frame{"keyterms": keyterms}}, 1011}, + "a tts option": {"/v1/tts/stream", frame{"target": "en-low-latency", "tts": frame{"overwrites": frame{"": frame{}}}}, 1011}, + "an sts option": {"/v1/sts/stream", frame{"target": "stub/stub-sts", "sts": frame{"turn_detection": "whichever"}}, 1011}, + "a batch model": {"/v1/stt/stream", frame{"target": "batch/" + batchModel}, 1008}, + "an unknown target": {"/v1/stt/stream", frame{"target": "nobody/nothing"}, 1008}, + } { + s.Run(name, func() { + connection, id := s.startNamed(refused.path, refused.opening) + _, _ = s.ending(connection) + + s.Contains(s.closeLine(id), fmt.Sprintf(" close_reason=refused close_code=%d ", refused.code)) + }) + } +} + +func (s *StreamsSuite) TestAFirstFrameThatIsNoStartFrameIsARefusal() { + // Catches a frame the router could not read logged as a dropped connection. + for name, first := range map[string]string{ + "not JSON": "not json", + "another type": `{"type": "hello", "target": "en-low-latency"}`, + "JSON of no shape": "[1]", + } { + s.Run(name, func() { + id := rand.Text() + connection := s.serverClient.withRequestID(id).opens("/v1/stt/stream") + + s.Require().NoError(connection.WriteMessage(websocket.TextMessage, []byte(first))) + _, _ = s.ending(connection) + + s.Contains(s.closeLine(id), " close_reason=refused close_code=1011 ") + }) + } +} + +func (s *StreamsSuite) TestAProviderThatFailsToStartIsAServerError() { + // Catches a provider's failure logged as the caller's refusal. + connection, id := s.startNamed("/v1/stt/stream", frame{"target": "down/" + downModel}) + _, _ = s.ending(connection) + + s.Contains(s.closeLine(id), " close_reason=server_error close_code=1011 ") +} + +func (s *StreamsSuite) TestAConfigThatCannotBeReadIsAServerError() { + // Catches the internal error the router answers a failed read with taken for a refusal: + // both are an APIError. + config := s.utils.uuid() + s.failQueries(config) + connection, id := s.startNamed("/v1/stt/stream", frame{"config_id": config}) + _, _ = s.ending(connection) + + s.Contains(s.closeLine(id), " close_reason=server_error close_code=1011 ") +} + +func (s *StreamsSuite) TestAStreamSocketClosedBeforeItsStartFrameIsTheCallersClose() { + // Catches a caller that left before saying what it wanted logged as refused. + id := rand.Text() + connection := s.serverClient.withRequestID(id).opens("/v1/stt/stream") + + s.Require().NoError(connection.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(4015, ""))) + _, _ = s.ending(connection) + + s.Contains(s.closeLine(id), " close_reason=client_closed close_code=4015 ") +} + +func (s *StreamsSuite) TestAStreamSocketDroppedBeforeItsStartFrameIsClientGone() { + id := rand.Text() + connection := s.serverClient.withRequestID(id).opens("/v1/stt/stream") + + s.Require().NoError(connection.UnderlyingConn().Close()) + + line := s.closeLine(id) + s.Contains(line, " close_reason=client_gone ") + s.NotContains(line, "close_code=") +} diff --git a/acceleration/internal/api/streams_test.go b/acceleration/internal/api/streams_test.go index 12a0c39e37..394249b8ac 100644 --- a/acceleration/internal/api/streams_test.go +++ b/acceleration/internal/api/streams_test.go @@ -4,6 +4,7 @@ package api import ( "context" + "crypto/rand" "encoding/binary" "encoding/json" "errors" @@ -990,10 +991,17 @@ func (s *StreamsSuite) refused() *websocket.Conn { // start opens a modality socket and sends its start frame. func (s *StreamsSuite) start(path string, opening frame) *websocket.Conn { - connection := s.serverClient.opens(path) + connection, _ := s.startNamed(path, opening) + return connection +} + +// startNamed is start under a request id of its own, which names the socket's access line. +func (s *StreamsSuite) startNamed(path string, opening frame) (*websocket.Conn, string) { + id := rand.Text() + connection := s.serverClient.withRequestID(id).opens(path) opening["type"] = "start" s.Require().NoError(connection.WriteJSON(opening)) - return connection + return connection, id } // converse opens a speech-to-speech socket and returns the model it landed on, so a test diff --git a/acceleration/internal/api/streamws.go b/acceleration/internal/api/streamws.go index 77fa0355f4..cb9e10443f 100644 --- a/acceleration/internal/api/streamws.go +++ b/acceleration/internal/api/streamws.go @@ -1,6 +1,7 @@ package api import ( + "bytes" "context" "encoding/binary" "encoding/json" @@ -187,11 +188,11 @@ func (s *Server) streamModality(w http.ResponseWriter, r *http.Request) { recordFailure(r.Context(), err, trace) } - opening, err := readStart(connection, modality) + opening, err := readStart(out, modality) if err != nil { record(err) out.failed(err) - out.end(err) + recordClose(r.Context(), out.end(err)) return } @@ -208,7 +209,7 @@ func (s *Server) streamModality(w http.ResponseWriter, r *http.Request) { err = internalError() } out.failed(err) - out.end(err) + recordClose(r.Context(), out.end(err)) return } speech, voice, model, conversation := opening.options(config) @@ -223,7 +224,7 @@ func (s *Server) streamModality(w http.ResponseWriter, r *http.Request) { if err := request.Tags.Validate(); err != nil { record(err) out.failed(err) - out.end(err) + recordClose(r.Context(), out.end(startRefused{err})) return } @@ -255,7 +256,7 @@ func (s *Server) streamModality(w http.ResponseWriter, r *http.Request) { out.failed(err) } out.frame(frame{"type": "closed"}) - out.end(err) + recordClose(r.Context(), out.end(err)) } // serves reports whether this deployment routes a modality over a socket. @@ -284,13 +285,13 @@ func (s *Server) streamSTT( // A start frame is options the same way a stored config is, so it is held to the same // standard: a mode nothing recognises is refused rather than ignored. if err := held.Validate(); err != nil { - return err + return startRefused{err} } // The cap a session is held to, counted the same way. Deepgram takes whatever it is // sent, and the providers that do refuse a long list each word it differently. if keyterms := stt.CleanKeyterms(held.Keyterms); len(keyterms) > stt.MaxKeyterms { - return stack.Wrap(fmt.Errorf("stt: at most %d keyterms may be named, and this asks for %d", - stt.MaxKeyterms, len(keyterms))) + return startRefused{stack.Wrap(fmt.Errorf("stt: at most %d keyterms may be named, and this asks for %d", + stt.MaxKeyterms, len(keyterms)))} } session, err := s.streams.STT.Start(ctx, sttrouter.Request{ @@ -349,6 +350,7 @@ func (s *Server) streamSTT( for { kind, payload, err := out.connection.ReadMessage() if err != nil { + out.stopped = err break } if kind != websocket.BinaryMessage { @@ -378,7 +380,7 @@ func (s *Server) streamTTS( // A start frame is options the same way a stored config is, so a retention nothing // could be measured against is refused rather than ignored. if err := held.Validate(); err != nil { - return err + return startRefused{err} } session, err := s.streams.TTS.Start(ctx, ttsrouter.Request{ @@ -431,7 +433,7 @@ func (s *Server) streamTTS( Voice string `json:"voice"` Language string `json:"language"` } - if err := out.connection.ReadJSON(&command); err != nil { + if err := out.readJSON(&command); err != nil { break } @@ -499,7 +501,7 @@ func (s *Server) streamLLM( for { var command respond - if err := out.connection.ReadJSON(&command); err != nil { + if err := out.readJSON(&command); err != nil { break } @@ -591,7 +593,7 @@ func (s *Server) streamSTS( // A start frame is options the same way a stored config is, so a turn detector // nothing recognises is refused rather than ignored. if err := held.Validate(); err != nil { - return err + return startRefused{err} } session, err := s.streams.STS.Start(ctx, stsrouter.Request{ @@ -664,6 +666,7 @@ func (s *Server) streamSTS( for { kind, payload, err := out.connection.ReadMessage() if err != nil { + out.stopped = err break } out.connection.SetReadDeadline(time.Now().Add(pongWait)) @@ -1065,19 +1068,19 @@ const defaultSampleRate = 16000 // // A frame naming a config need not name a target, because the config it names may hold // one. A frame naming neither is refused: nothing about it says what to route to. -func readStart(connection *websocket.Conn, modality routing.Modality) (start, error) { - connection.SetReadDeadline(time.Now().Add(startWait)) - defer connection.SetReadDeadline(time.Time{}) +func readStart(out *socket, modality routing.Modality) (start, error) { + out.connection.SetReadDeadline(time.Now().Add(startWait)) + defer out.connection.SetReadDeadline(time.Time{}) var opening start - if err := connection.ReadJSON(&opening); err != nil { + if err := out.readJSON(&opening); err != nil { return start{}, errors.New("the socket opens with a start frame naming the target") } if opening.Type != "" && opening.Type != "start" { - return start{}, errors.New("the first frame must be a start frame") + return start{}, startRefused{errors.New("the first frame must be a start frame")} } if !opening.names(modality) && opening.ConfigID == "" { - return start{}, errors.New("routing needs a target, either sent or held in a config") + return start{}, startRefused{errors.New("routing needs a target, either sent or held in a config")} } return opening, nil } @@ -1267,6 +1270,30 @@ type socket struct { // it. Nil when nothing waits on it. started chan struct{} startOnce sync.Once + // stopped is why the caller's reads stopped: the read's error, or errUnreadableFrame for a + // frame that is not JSON of the shape read. Only the goroutine reading the socket sets it. + stopped error +} + +// startRefused marks a failure as the caller's start frame refused, for the close_reason of a +// stream socket. It reads as the failure itself, so the caller is sent the same frames. None +// of the failures it marks is a routing.ErrRequest or a refusal about money, so the close code +// is the same too. +type startRefused struct{ error } + +// readJSON reads the caller's next frame into v as ReadJSON does, keeping why the caller's +// reads stopped when the read fails or the frame is not JSON of v's shape. +func (s *socket) readJSON(v any) error { + _, payload, err := s.connection.ReadMessage() + if err != nil { + s.stopped = err + return err + } + if err := json.NewDecoder(bytes.NewReader(payload)).Decode(v); err != nil { + s.stopped = errUnreadableFrame + return err + } + return nil } // frame sends one JSON message under the write deadline. @@ -1318,8 +1345,9 @@ func (s *socket) failed(err error) { // redacted by errorText, as the reason. A request the router refused (routing.ErrRequest), // or refused for money, is the caller's to change, so it ends with 1008, policy violation; // any other failure, as often a provider's as a caller's, with 1011, an unexpected condition -// (RFC 6455 section 7.4.1, https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). -func (s *socket) end(failure error) { +// (RFC 6455 section 7.4.1, https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). It says +// why the socket closed (closedWith). +func (s *socket) end(failure error) socketEnd { code, reason := websocket.CloseNormalClosure, "" if failure != nil { code, reason = websocket.CloseInternalServerErr, errorText(failure) @@ -1331,6 +1359,26 @@ func (s *socket) end(failure error) { } } closeSocket(s.connection, code, reason) + return s.closedWith(failure, code) +} + +// closedWith is why the socket closed with code, on failure or once the caller's reads stopped. +// A frame the router could not read, a start frame it would not take (startRefused, or an +// APIError such as a config the caller does not have) and a refusal sent as 1008 are refused. +// Any other failure, a provider's or the router's own (an internal APIError, such as a config +// the database could not read), is server_error. +func (s *socket) closedWith(failure error, code int) socketEnd { + _, refused := errors.AsType[startRefused](failure) + answer, answered := errors.AsType[APIError](failure) + switch { + case errors.Is(s.stopped, errUnreadableFrame): + return socketEnd{cause: refusedByRouter, code: code} + case s.stopped != nil: + return readEnd(s.stopped) + case code == websocket.ClosePolicyViolation, refused, answered && answer.Type != ErrorTypeInternal: + return socketEnd{cause: refusedByRouter, code: code} + } + return socketEnd{cause: serverFailed, code: code} } // closeSocket sends the close frame after the last frame and reads until the caller answers