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
18 changes: 17 additions & 1 deletion acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2138,9 +2138,25 @@ 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
Expand Down
20 changes: 18 additions & 2 deletions acceleration/internal/api/channel_team_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
package api

import (
"crypto/rand"
"maps"
"net/http"
"os"
"slices"
"strings"
"time"

"github.com/gorilla/websocket"
"github.com/redis/rueidis"

"github.com/GetStream/Vision-Agents/acceleration/internal/store"
Expand Down Expand Up @@ -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},
}))
Expand All @@ -194,14 +197,26 @@ 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.
func (s *AgentTeamsSuite) TestASocketSessionWhoseConfigTheDatabaseCannotReadIsRefusedWithoutTheError() {
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},
}))
Expand All @@ -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.
Expand Down
50 changes: 36 additions & 14 deletions acceleration/internal/api/relayws.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) }) }
Expand All @@ -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
Expand Down Expand Up @@ -191,12 +196,13 @@ func (s *Server) watchRemoteSession(w http.ResponseWriter, r *http.Request, id s
go func() {
gone <- s.readRelayedCommands(connection, state, watcher, id)
}()
s.writeRelayedEvents(connection, state, socket, watcher, id, watching(r), gone, endingOf(asked, socket.halted.Load))
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.
// 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
Expand All @@ -209,7 +215,7 @@ func (s *Server) writeRelayedEvents(
asked wanted,
gone <-chan error,
ended ending,
) {
) socketEnd {
ping := time.NewTicker(pingEvery)
defer ping.Stop()

Expand All @@ -218,13 +224,20 @@ 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()
// 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 socket.byCommand.Load() && end.cause == sessionEnded {
end.cause = closedByClient
}
closeBeforeReader(connection, code, reason, gone)
return
return end

case payload := <-socket.frames:
if !asked.takesFrame(frameType(payload)) {
Expand All @@ -233,13 +246,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,
Expand Down Expand Up @@ -387,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
Expand All @@ -397,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
Expand Down Expand Up @@ -429,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)
}
Expand All @@ -451,6 +465,11 @@ 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" {
if s.closesSession(found, proxy.seat.Owner) {
proxy.closing.Store(true)
}
}
s.applyCommand(found, proxy.seat, sender, command)
}
}
Expand Down Expand Up @@ -507,6 +526,9 @@ func (r *relayed) deliver(payload []byte) {
if response.Halted {
socket.halted.Store(true)
}
if response.ByCommand {
socket.byCommand.Store(true)
}
socket.close()
return
}
Expand Down
13 changes: 11 additions & 2 deletions acceleration/internal/api/requestid.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion acceleration/internal/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -1046,7 +1046,7 @@ func (s *Server) withRequestLog(routes *chi.Mux, next http.Handler) http.Handler
}

// 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),
Expand All @@ -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())
}
Expand Down
Loading
Loading