Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 19 additions & 15 deletions acceleration/internal/api/dispatchws.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand All @@ -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)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R2.1: mutant socketEnd{cause: clientGone} at this reply write survives (I replaced each writeEnd site alone and ran SocketCloseLog+SocketEnd; only the pong, session event and relay event sites are killed). This one is reachable like the pong: add to SocketCloseLogSuite, 25 rounds:

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 ")

I ran it: passes on head x3, fails x3 under this mutant. The other survivors (ready at 169, pings at 220, sessionws.go:340, relayws.go:256, tool call/call/message at 196/206/214) are not reachable without a clock or a deterministic race with the close; list them as untested in the PR body and leave them.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5b755c1: SocketCloseLogSuite/TestADispatchWorkersCloseFrameAfterHostToolsIsLoggedWithItsCode (host_tools then close 4005, 25 rounds). Passes x3 on head; with the reply write at dispatchws.go:186 mutated to clientGone it fails x3. The 7 unreachable sites are listed in the PR body.

}

case call := <-worker.ToolCalls():
Expand All @@ -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():
Expand All @@ -201,32 +203,33 @@ 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():
connection.SetWriteDeadline(time.Now().Add(writeWait))
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)
}
}
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions acceleration/internal/api/relayws.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions acceleration/internal/api/sessionws.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
Expand Down
137 changes: 134 additions & 3 deletions acceleration/internal/api/socket_close_log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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=")
}
Loading
Loading