Repository navigation
[AI-3418] Log why a session socket closed - #2218
Conversation
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 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
Reviewed 05d54904a merged onto main 73dc7bfa6. The draft runs no CI, so the go and integration checks are skipped; they run at gh pr ready. On the merged tree: build, vet and gofmt are clean. The touched suites (SocketCloseLog, SocketEnd, SocketHangUp, SessionEvents, RelayedSession, SocketSession, SessionResume, ByCustomerSocket, HTTPMetrics, request id) pass with -race: 195 pass, no data race.
[Should fix] R1.3 acceleration/README.md (The request log, about lines 2131-2147): the access-line field table ("The access line also carries these fields ... Each one is left out when the request has none") and the socket paragraph below it do not mention close_reason, close_code or end_reason. Add the three fields: the values, and when each one is left out.
[Question] R1.6 relayws.go: the holder also publishes Closed when its proxy watcher is dropped without the session ending (publishSessionEvents: "either the session ending or the watcher being detached", for example expireProxies after missed refreshes). That relayed socket is then logged session_ended while the session keeps running. The close frame says the same thing, and that part is unchanged code. For a ticket: should the holder say whether it was a detach?
Checked and sound:
- With a real gorilla connection, a read deadline is
timeout, a drop (1006) isclient_gonewith no code, and the read limit isrefused 1009, which is also what the client receives. - The access line for a request with no socket is unchanged.
- No frame or code sent to clients changed.
EndedForis read after the session's watchers close, whichSession.closedoes last, andnoteEndkeeps the first reason. A one-line export ofkept()is the smallest way:EndReason()alone losesclosed/agent_failed, which the mutant shows.- A relayed socket is logged once, on its own node, without
end_reason. - No text from the caller's close frame is logged.
Verdict: request changes, for R1.1 (a close after the session's end overrides the real cause), R1.2 and R1.3.
| 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 { |
There was a problem hiding this comment.
[Should fix] R1.1 A close command that arrives after the session already ended is logged as the caller's close, so the first cause loses.
How it happens: the session ends (a backend stop, agent_hangup, model_failed). The writer sees events close, sends close 1000 "the session ended", and then waits up to closeWait (1 s) in closeBeforeReader. During that wait the reader reads the caller's {"type":"close"} and sets closing. Its sessions.Close finds no session. This line then turns session_ended into client_closed, with no end_reason.
Probe on the head merged onto main (deterministic, 3/3 runs). I call stopSession and wait for it to return, then send the close command. The line reads close_reason=client_closed close_code=1000; it should read close_reason=session_ended close_code=1000 end_reason=closed. Every SDK sends this command on hang-up (JS VoiceSession.hangUp, Python leave_remote, Go Pipeline.Close). So any end followed within 1 s by a user's or an SDK's close gets the wrong answer to "who ended it?".
The same class appears at these sites:
relayws.go:197(relayed socket, same probe:client_closed)socketws.go:249: astopafter the conversation is over isclient_closed. The read-error branch checksover; this branch does not. Probe:stopSession, thenstop.sessionws.go:301:stopped == nilis also what a close command returns when itsClosefound no session.
Fix: decide when the end is seen. Read closing inside writeEvents/writeRelayedEvents when events/socket.closed fires, before closeBeforeReader. In the stop branch, select on over as the error branch does.
Test rows for SocketCloseLogSuite. Each fails on head and should pass after the fix:
stopSession(id)and wait, then send{"type":"close"}on the events socket. Expectclose_reason=session_ended close_code=1000 end_reason=closed.- The same on
watched(s.other). Expectclose_reason=session_ended close_code=1000. socketSession(),stopSession, then{"type":"stop"}. Expectclose_reason=session_ended close_code=1000 end_reason=closed.
There was a problem hiding this comment.
Fixed in 6160a55 and 2d89515: the events socket sets closing only when the manager still holds the session (closesSession); the holder of a relayed session checks the same and marks its Closed bus message by_command; the voice socket's stop checks over. Tests: TestACloseCommandAfterTheSessionEndedIsTheSessionsEnd, TestARelayedCloseCommandAfterTheSessionEndedIsTheSessionsEnd, TestARelayedCloseCommandAheadOfTheEndItFollowedIsTheSessionsEnd, TestAStopOnTheVoiceSocketAfterTheSessionEndedIsTheSessionsEnd. Your three probes pass 5/5. Reading closing on the socket's node as the end arrives was not enough for the relayed case: your relayed probe still failed 5/5 that way, since the holder's word of the end arrives after the caller's close.
| if err := connection.WriteJSON(encoded); err != nil { | ||
| s.logger.Debug("session socket write failed", "error", err) | ||
| return | ||
| return socketEnd{cause: clientGone} |
There was a problem hiding this comment.
[Should fix] R1.2 Several new rules have no test. I checked 13 mutants and 11 survive the PR's tests. Each row below was checked: it fails under its mutant and passes on head.
sessionws.go:397if command.Type == "close"→if true: survives. Row: send{"type":"interrupt"}, thenstopSession. Expectclose_reason=session_ended close_code=1000 end_reason=closed.relayws.go:289the same mutant: survives. Row: the same steps onwatched(s.other). Expectsession_ended close_code=1000.- This line (write failure) →
socketEnd{}: survives. Unit row: a real gorilla server/client pair with both underlying conns closed, oneagent.Saidqueued onevents, thenwriteEvents(...). Expectcause == clientGone. relayws.go:244, the same mutant: survives. Unit row: the same steps withwriteRelayedEvents(server, nil, &remoteSocket{frames: one frame, closed: open chan}, ...). ExpectclientGone.socketws.go:241edge.Hearfailure →clientGone: survives. Row:socketSession(),stopSession, then write a 640-byte binary frame. Expectclose_reason=session_ended close_code=1000 end_reason=closed.
I found no cheap row for 6 mutants. The ping failures at :329 and relayws.go:250 need the 30 s pingEvery. The session frame write failure (socketws.go:196), both serverFailed records (socketws.go:145,172, which need a DB failure) and stopped == nil (:301) have none either. The PR body names most of these; add a test or say why not, per site.
There was a problem hiding this comment.
Fixed in a61c661 and ba8790b. Killed now: ws-anycmd / relay-anycmd (TestAnother{,Relayed}CommandBeforeTheSessionEndsIsNotTheCallersClose), ws-write-fail / relay-write-fail (SocketEndSuite TestAnEventTheCallerCannotBeSentIsClientGone, TestARelayedFrameTheCallerCannotBeSentIsClientGone), sock-hear (TestAudioOnTheVoiceSocketAfterTheSessionEndedIsTheSessionsEnd), and both server_error refusals (AgentTeamsSuite TestASocketSession*, which can fail the config read and the settings read). Still surviving, with a reason for each in the PR body: the two ping failures, the session-frame write, and stopped == nil.
| 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}) |
There was a problem hiding this comment.
[Nit] R1.4 refuseWith records refused and this line then overwrites it with serverFailed (the same at :172). Also, the refused socketEnd at :95 is shadowed by the refused bools at :119, :152 and :165. Passing the cause into refuseWith would record it once and avoid the shadow.
There was a problem hiding this comment.
Fixed in ba8790b: refuseWith(cause, failure) records the cause it is given, and the shared socketEnd is renamed refusal. Test: AgentTeamsSuite TestASocketSessionIsRefusedWhenTheSettingsCannotBeRead and TestASocketSessionWhoseConfigTheDatabaseCannotReadIsRefusedWithoutTheError now assert close_reason=server_error close_code=1008.
| refuse := func(message string) { | ||
| _ = writeFrame(frame{"type": "error", "error": message}) | ||
| closeSocket(connection, websocket.ClosePolicyViolation, "") | ||
| recordClose(r.Context(), refused) |
There was a problem hiding this comment.
[Nit] R1.5 A caller that drops or sends a close frame before its start frame is logged refused close_code=1008, because the ReadJSON error at :111 goes to refuse. Its real cause is client_gone/client_closed/timeout (readEnd(err)). Only a frame that is not a start frame is a refusal.
There was a problem hiding this comment.
Fixed in ba8790b: the start frame is read with NextReader and then decoded, the two steps ReadJSON is made of, and a read error is recorded as readEnd(err). Tests: TestAVoiceSocketClosedBeforeItsStartFrameIsTheCallersClose (client_closed 4003), TestAVoiceSocketDroppedBeforeItsStartFrameIsClientGone.
…close-reason # Conflicts: # acceleration/internal/api/socketws.go
…sion'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 <noreply@anthropic.com>
… 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…reason Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t 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 <noreply@anthropic.com>
|
R1.3 fixed in 4192be6: |
kanat
left a comment
There was a problem hiding this comment.
Delta round 2 (05d5490 -> ba8790b, merged onto current main). Verdict: NO-GO, two small Should fix.
Prior findings
- R1.1 fixed. Holder-decides works: the bus field
by_commandis needed (with the socket node readingclosingas the end arrives, the relayed "close ahead of the end" row fails 9/10 under -race); it is wire compatible both ways (the only decoder is a plainjson.Unmarshal,omitempty, checked old<->new structs: no error,ByCommandfalse when absent); it changes only the logged cause, not frames, codes or the session. 6 R1.1 mutants killed again on head+main;SocketCloseLogSuiteok-race -count=20and-cpu 1 -count=20. - R1.2 fixed. 14 of 15 mutants killed on head. Survivors accepted: both ping failures (
pingEveryis a 30 s const), the session-frame write (cannot be timed),stopped == nil(the events channel wins the select, not deterministic),relay-held(see the first new finding). - R1.3 content matches code (see the second new finding for a rendering defect).
- R1.4 fixed, R1.5 fixed: killed by the new rows (sock-config-fail, sock-settings-fail, sock-refusewith-cause, sock-start-readend).
- R1.6 stays a ticket.
New findings
- [Should fix] relayws.go:469
proxy.closing.Store(s.closesSession(...))— a second close command after the first one ended the session storesfalseovertrue, and the Closed carries noby_command: loggedsession_ended, notclient_closed. The old code never stored false (regression of the delta). Probe (relayed socket, close sent 3 times back to back): fails 59/60 under-race -count=60. Fix:if s.closesSession(found, proxy.seat.Owner) { proxy.closing.Store(true) }; with it the probe passes 60/60 and the whole suite 0 FAIL. Add the probe asTestARelayedCloseCommandSentTwiceIsTheCallersClose. - [Should fix, small] README.md:2157-2158 — the
close_reasontable's last row is followed byA5xxis loggedwith no blank line, so the rest of that paragraph renders as table rows. Fix: blank line after theshutdownrow, drop the leading space.
CI: draft, go and integration skipped (#2130); CodeQL, GitGuardian pass.
| 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)) |
There was a problem hiding this comment.
[Should fix] A second close command, sent after the first one ended the session, finds the session gone and stores false over true; publishSessionEvents then sends a Closed with no by_command and the socket logs session_ended. 05d5490 never stored false. Probe: relayed socket, close sent 3 times back to back: fails 59/60 (-race -count=60). Fix: if s.closesSession(found, proxy.seat.Owner) { proxy.closing.Store(true) } (probe then 60/60); add the probe as a SocketCloseLogSuite row.
There was a problem hiding this comment.
Fixed in 3a90262: proxy.closing is only ever set now (relayws.go:469). Test: TestARelayedCloseCommandSentTwiceIsTheCallersClose (close sent 3 times). With the old Store line back it failed 60/60 under -race -count=60; with the fix it passes 60/60. The local socket has the same line (sessionws.go:409) but its reader returns after the first close (applyCommand returns false for close, sessionws.go:582-592), so a second close is never read there. I tried the mutation at that site too: 60/60 pass, so I left it unchanged.
| | `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 |
There was a problem hiding this comment.
[Should fix, small] No blank line between the close_reason table and this line (and a leading space), so this paragraph renders as table rows. Add a blank line after the shutdown row and drop the space.
There was a problem hiding this comment.
Fixed in aff1206: blank line after the shutdown row, leading space dropped. Rendered with python-markdown (tables): one table of 8 rows, then a separate paragraph starting with the 5xx sentence.
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 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
## Why #2218 (AI-3418) added `close_reason`, `close_code` and `end_reason` to the access line of the session sockets only. A `/v1/dispatch` socket and a `/v1/{modality}/stream` socket still log their `served a request` line with no reason. Dispatch sockets are most of the socket lines on staging: 111 of the 151 in the 7 days that #2218's probe read. ## How it works The same mechanism as #2218: the handler decides why its socket closed and calls `recordClose`, and `withRequestLog` writes the reason on the line it already writes. There is no new `msg` and no new `close_reason` value. ``` /v1/dispatch (writeCalls) ├─ caller sent a close frame ............ client_closed close_code=<its code> ├─ connection dropped, a write failed ... client_gone (ready, pong, reply, call, │ message, tool call, ping) ├─ no pong within pongWait .............. timeout ├─ frame that is not JSON ............... refused close_code=1008 └─ router draining ...................... shutdown close_code=1001 /v1/{modality}/stream (stt, tts, llm, sts; socket.end -> closedWith) ├─ caller sent a close frame ............ client_closed close_code=<its code> ├─ connection dropped ................... client_gone ├─ no start frame within startWait, │ or no pong on sts .................. timeout ├─ frame it cannot read ................. refused close_code=<code sent> ├─ start the caller must change ......... refused close_code=1011 | 1008 │ (not JSON, wrong type, no target, unknown config, bad tag, bad stt/tts/sts │ option, too many keyterms, a setting the model cannot take) └─ provider failed, or the config it names could not be read .................. server_error close_code=1011 ``` `readEnd` (socketend.go) reads why a reader stopped, as on the session sockets. For dispatch, `readWorker` now returns its read error. It returned nil, so every end looked the same. The stream socket keeps the reader's error on `socket.stopped`. `socket.readJSON` is `ReadJSON` split into `ReadMessage` and a `json.Decoder`, so a frame that is not JSON is told apart from a read that failed. `startRefused` marks a start failure that is the caller's. An `APIError` other than an internal one (an unknown config) is also the caller's. The internal error that #2249 answers a failed config read with is not. It reads as the failure, so the frame and the close code stay the same. Values with no exact fit, and the closest existing one I chose: | End | Value | Why | |---|---|---| | Dispatch drain (`1001`, "router restarting") | `shutdown` | The router is going away. On session sockets this value is `1012` for a resumable session; here the code says which | | Stream provider could not start (`1011`) | `server_error` | It is not the caller's to fix. `refused` would send the reader to the start frame | | Stream start refused with `1011` | `refused` | The router has always closed a refused start with `1011` (`TestAStartWithNoTargetEndsWithTheSameClose`). This PR does not change that code, so `close_code` is `1011` | | Unreadable `tts`/`llm` frame after the start (`1000`) | `refused` | The router ended the socket on the caller's frame. It closes with `1000`, as on base (`TestASocketTheRouterEndsWithoutAFailureClosesNormally`) | These sockets have no session, so they log no `end_reason`. Nothing a client is sent changes: frames and close codes are the same as on base. Before and after (fake ids): ``` before: msg="served a request" method=GET path=/v1/dispatch status=101 duration=2h3m1s customer=C1 request_id=R1 operation_type=DispatchCalls after: msg="served a request" method=GET path=/v1/dispatch status=101 duration=2h3m1s customer=C1 request_id=R1 close_reason=shutdown close_code=1001 operation_type=DispatchCalls after: msg="served a request" method=GET path=/v1/stt/stream status=101 duration=41s customer=C1 request_id=R2 close_reason=client_closed close_code=1000 operation_type=StreamModality ``` ClickHouse: the line stays in `logs.agent_requests` (`msg="served a request"`). That view has no `close_reason` or `close_code` column yet, the same as after #2218. Until it gets one (a separate chat ticket), the fields can be read only from `body`. ## Changes - `internal/api/dispatchws.go`: `writeCalls` returns a `socketEnd`, `readWorker` returns its read error, and `dispatchCalls` records the end. - `internal/api/streamws.go`: `socket.stopped`, `socket.readJSON` and `startRefused`. `socket.end` returns why the socket closed (`closedWith`), and `streamModality` records it at each exit. - `internal/api/socketend.go`: the value docs name the new sockets. - `acceleration/README.md`: the access line's table says which sockets carry the fields. The `close_reason` table covers their ends. ## Validation | Test | Defect it catches | |---|---| | `SocketCloseLogSuite` dispatch tests | the worker's close frame logged as `client_gone` (the reader's error dropped); a drop with a code; an unreadable frame not a refusal; a drain not a `shutdown` with `1001` | | `SocketEndSuite` dispatch write tests | a failed write of the ready, pong, reply, call, message or tool call frame left with no reason | | `StreamsSuite` `TestEachStreamSocketLogsTheCallersCloseWithItsCode` | any of the four read loops (stt, tts, llm, sts) leaving no reason | | `StreamsSuite` refusal tests | each start the caller must change logged as `server_error`; a first frame that is not JSON logged as a drop; an unreadable `llm` frame logged as a drop | | `StreamsSuite` `TestAProviderThatFailsToStartIsAServerError`, `TestAConfigThatCannotBeReadIsAServerError` | a provider's failure, or the internal error for a config read that failed, logged as the caller's refusal | | `StreamsSuite` before the start frame | a close or a drop before the start logged as `refused` | | Control: existing `StreamsSuite` and `DispatchSuite` close-code tests (base) | a frame or close code sent to clients changed | Mutations: 37 mutants, one batched run (each built with `-overlay`, then the three suites above run against it). 36 killed. Every changed branch, return and wrap site was broken alone: each write failure, the drain, the unreadable frame, the reader's error, each `startRefused` wrap, each read loop's `stopped`, each `closedWith` case (internal `APIError` included) and each `recordClose` call. | Survives (each `writeEnd` site mutated alone to `clientGone`) | Why no test | |---|---| | `dispatchws.go` ready write (written before any read, so no close can race it) | no close frame can arrive first | | pings: `dispatchws.go`, `sessionws.go`, `relayws.go` | `pingEvery` is a 30 s constant | | `dispatchws.go` tool call, call and message writes | written when the router hands work over; no deterministic race with the close | The other four sites are pinned: dispatch pong, dispatch reply to `host_tools` (`TestADispatchWorkersCloseFrameAfterHostToolsIsLoggedWithItsCode`), the session event write and the relay event write. Not reachable from a test, and covered by `readEnd`'s unit tests: `timeout` (`pongWait` is 90 s, `startWait` 30 s) and the read limit (`1009`). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
) ## Why A relayed events socket is one that lands on a node other than the one running its session. The node running the session holds a proxy watcher for it, and gives that watcher back when the socket's node stops refreshing it (`expireProxies`, `acceleration/internal/api/relayws.go`). On base, the socket's node then logs `close_reason=session_ended` and closes the socket with `1000` "the session ended", while the session still runs. The round-1 review of #2218 found it (R1.6). The close frame matters more than the log line. The Go SDK reads `1000` as the end of the conversation and does not reconnect (`dropped`, `sdks/go/stream/accelerated.go:1028-1032`), and Kotlin marks the conversation `Ended` (`AgentSessionTest.kt:1140-1159`: `1000` is `Conversation.State.Ended`, `1011` a `SocketClosed` failure). ## How it works ``` node running the session node holding the socket ------------------------- ----------------------- proxy watcher's events close publishSessionEvents relay.Closed{ Halted, ByCommand, Detached: session not Ended} --> deliver: socket.detached writeRelayedEvents ├─ detached ...... relay_ended 1011 │ "the relay to the session ended" ├─ halted, resumable shutdown 1012 (as base) ├─ close command .... client_closed 1000 (as base) └─ otherwise ........ session_ended 1000 (as base) ``` A session sets `Ended` before it closes its watchers (`acceleration/internal/session/session.go:1982` sets it, `:1992` closes them), so a watcher whose events closed while the session is not `Ended` was detached, not ended. The holder asks the session itself rather than flagging the expiry path, so any detach that leaves the session running reads the same way. Close code and value, chosen as #2218 and #2271 chose theirs: | End | Value | Code | Why | |---|---|---|---| | The holder gave back the watcher, the session goes on | `relay_ended` (new) | `1011` | The ticket asks for a reason that names the relay, not the session. `1011` is RFC 6455's "unexpected condition" (section 7.4.1): the holder lost a socket that was still open. `1000` told every caller the conversation was over; `1011` is a failure. Only the Go SDK reconnects, and only a text session's resumable socket (`accelerated.go:377`, `:948`) | `1012` was the other candidate. It says "router restarting", which this is not, and on a session socket it already means `shutdown`. Before and after (fake ids): ``` before: msg="served a request" method=GET path=/v1/agents/sessions/S1/events status=101 duration=4m2s customer=C1 request_id=R1 close_reason=session_ended close_code=1000 operation_type=WatchSession after: msg="served a request" method=GET path=/v1/agents/sessions/S1/events status=101 duration=4m2s customer=C1 request_id=R1 close_reason=relay_ended close_code=1011 operation_type=WatchSession ``` During a rolling deploy a holder on the old build sends no `detached`, so its sockets log and close as on base. A socket node on the old build ignores the field. ## Changes - `relay.Response` gets `Detached`, set on `Closed` by `publishSessionEvents` when the session had not ended. - `writeRelayedEvents` closes a detached socket with `1011` and logs `relay_ended`, with no `end_reason`. - `expireProxies`'s tick moves into `dropExpired`, which the test calls. - `acceleration/README.md` lists `relay_ended` with the other `close_reason` values; the events socket's spec text names the `1011` close (regenerated: `openapi.yaml`, the JS and Python clients). ## Who reads this - Client SDKs: none reads `close_reason`; it is in the access log only. The close code is read by the session socket of Go (`sdks/go/stream/accelerated.go:1031`), JS (`socket.ts:285`), Dart (`socket.dart:120`), Kotlin (`SessionSocket.kt`) and Swift (`SessionSocket.swift:118`). Go reconnects a text session's resumable socket on `1011`. JS, Kotlin and Dart treat `1000` as the end and any other code as a failure, and stop. Swift reports `socketClosed` for every close, `1000` included. No SDK changes here. - ClickHouse: no view change. `close_reason` is `LowCardinality(String)` and `close_code` `Nullable(UInt16)` in `agent_requests` and `agent_access_logs` (GetStream/chat `infra/charts/clickhouse/templates/init-schema-job.yaml`, master `6c2420c92e`), read as `kv['close_reason']`, with no enum of values. `dashboard/`, `tui/` and `plugins/stream` do not read the value. ## Validation | Test (`SocketCloseLogSuite`) | Base `cd3f7371d` | Head | |---|---|---| | `TestARelayedSocketWhoseWatcherExpiredIsTheRelaysEnd`: an expired proxy logs `relay_ended 1011`, closes `1011` "the relay to the session ended", and a new socket still watches the session | fails: `1000` "the session ended", `session_ended` | passes | | `TestARelayedSocketWhoseSessionEndedIsTheSessionsEnd` (control): a stopped session logs `session_ended 1000` and closes `1000` "the session ended" | passes (expected values from this run) | passes | The base run used the same test file with `dropExpired` inlined as `expired()` + `dropProxy`. Every added guard and constant was mutated (14 mutants, one script), and each failed at least one of the two tests. The one line no test covers: `expireProxies` calling `dropExpired` on its 30 s tick (the test calls `dropExpired` itself). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Why
A session socket is logged once, when it closes, as its
served a requestline. That line has the socket's duration, but not why it closed. An app that says "calls end on their own after a few minutes" cannot be answered from the logs: the caller may have hung up, the connection may have dropped, or the session may have ended on the router.A read-only probe of the staging logs (last 7 days,
logs.app_logs) found 151 socket lines (status=101). None of them has a close reason or a close code, and no other line names why a socket closed.How it works
The socket handler decides why its socket closed.
withRequestLogwrites that on the line it already writes. There is no newmsg.end_reasonis the reason the session's row keeps (session.EndReasons:agent_hangup,model_failed,shutdown,closedand the rest), so a session that ended says why without a join. A relayed socket (watched from a node that does not hold the session) logs noend_reason: the holding node knows it.The first cause wins. A close command ends the session before the reader returns, so the writer sees the session's end first; a flag set before the command is applied keeps that a
client_closed. The flag is set only when the command ends the session: a close (orstop) sent once the session had ended, as every SDK does on hang-up, leaves the linesession_ended.The relayed socket's node cannot tell on its own: the holder's word of the end can reach it after a close the caller sent once the session had ended. So the holder marks its
Closedbus messageby_command. During a rollout an older holder sends noby_command, and a relayed close command is loggedsession_endeduntil every node runs this. Nothing a client is sent changes: frames and close codes are as before.Before and after, one events socket closed by a close command (fake ids):
The reason text of a caller's close frame is never logged: only its code.
Changes
acceleration/README.md: the access line's field table and theclose_reasonvalues.internal/relay/bus.go:Response.ByCommand, set on aClosedwhen a close command from that watcher ended the session.internal/api/socketend.go(new): theclose_reasonvalues,readEnd(why a read stopped: close frame, gorilla's 1006 for a drop, a deadline, the read limit) andsessionEnd(1012 is a shutdown).requestid.go,server.go:requestFailurecarries the socket's end;withRequestLoglogs it.sessionws.go(/v1/agents/sessions/{id}/events),relayws.go(the same socket on another node),socketws.go(/v1/agents/socket): each records why its socket closed.session/metrics.go:EndedFor, the end reason the session's row keeps.Not in this PR:
/v1/{modality}/streamand/v1/dispatchare not session sockets and log noclose_reasonyet.ClickHouse: the line stays in
logs.agent_requests(msg="served a request"). The view has noclose_reason,close_codeorend_reasoncolumn, so they are readable only frombodyuntil the view gets them (a separate chat ticket).Validation
SocketEndSuite(unit)close_code=0or an emptyend_reasonlogged, close fields on a request with no socket (control: base 4bee273 has no close field), a wrapped close frame missed, 1006 logged as a caller's close, a deadline or the read limit misread, 1012 not a shutdownSocketCloseLogSuite(integration), events socketend_reasonclose(events, relayed) orstop(voice) sent once the router's close for the session's end arrived, and a relayedclosesent right after the stop returned, logged as the caller's closeend_reasonthere/v1/agents/socketstop, a close frame, a drop, a session that ended (the caller's answer to the router's close not logged as the caller's close), audio after the end, a missing start frame, a close frame or a drop before the start frame, a start frame naming a call (refuseWith)SocketEndSuitewrite failuresAgentTeamsSuitesocket refusalsserver_errorrefusals (config read, app settings) logged asrefusedTouched suites (
SocketCloseLogSuite,SocketEndSuite,SocketHangUpSuite,SessionEventsSuite,RelayedSessionSuite,SocketSessionSuite,SessionResumeSuite,ByCustomerSocketSuite,HTTPMetricsSuite,AgentTeamsSuite, the request id tests) pass under-race; the close-after-the-end and other-command rows also pass 20 times under-raceand 20 times with-cpu 1.Mutations: every changed branch was broken alone and run against these suites. Five survive, each for a reason a test cannot reach:
sessionws.gowriteEvents,relayws.gowriteRelayedEvents: a failed ping isclient_gonepingEveryis a 30 s constant; the failed write beside it is pinnedsocketws.go: the session frame cannot be written (client_gone)sessionws.gostopped == nil(session_ended, madeclient_closedby the flag)relayws.gorunRelayedCommands:closesSessionon the holder🤖 Generated with Claude Code