Repository navigation
[AI-3615] Log why dispatch and stream sockets closed - #2271
Conversation
/v1/dispatch and /v1/{modality}/stream now record close_reason and
close_code on their "served a request" line, with #2218's socketEnd,
readEnd and recordClose. No frame or close code sent to a client changes.
AI-3615
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
Round-1 review of 3194268 merged onto current main (e416613).
Checked and sound: touched suites pass with -race (StreamsSuite, SocketCloseLogSuite, SocketEndSuite, the dispatch suites, SocketHangUpSuite). A control probe of 30 stream and dispatch scenarios showed the frames, close codes and close texts sent to clients are byte-identical to base. The full access line is identical to base apart from the new fields and the stack line numbers. A non-socket request line is unchanged. Under concurrent ends the first cause wins: a drain racing the worker's close, and the worker's close after a drain, both log shutdown 1001. An internal APIError (the failed config read after #2249) logs server_error. An unknown target and an oversized frame log refused 1008 and refused 1009. Mutations: 10 of my own, 9 killed (R1.2 survives). The author's ping-write survivor is accepted: pingEvery is a 30 s constant.
[Question] R1.4 (author's QUESTION): a refused stream start still closes with 1011 where /v1/agents/socket sends 1008. This goes to a ticket, because this PR changes no close code.
[Question] R1.5: the session sockets from #2218 have the same pattern as R1.1, at sessionws.go:334,340 and relayws.go:249,255 (grep -n 'return socketEnd{cause: clientGone}' internal/api/*.go). I did not probe them. This goes to a ticket, because the code is unchanged here.
Verdict: request changes, for R1.1 and R1.2 (Should fix).
| connection.SetWriteDeadline(time.Now().Add(writeWait)) | ||
| if err := connection.WriteJSON(frame{"type": "pong", "at": at}); err != nil { | ||
| return | ||
| return socketEnd{cause: clientGone} |
There was a problem hiding this comment.
[Should fix] R1.1 The worker sent a close frame, but this line logs client_gone. The reader answers the close, and then the next write fails with websocket.ErrCloseSent. I probed it: a worker sends {"type":"ping"} and then closes with 4005. Over 40 runs the line said client_gone 37 times and client_closed close_code=4005 3 times. The PR body and the README say that a caller who sent a close frame is client_closed.
Fix: send all seven write failures in writeCalls (the ready, pong, reply, tool call, call, message and ping writes) through one helper. On errors.Is(err, websocket.ErrCloseSent) it waits on gone (bounded by closeWait) and returns readEnd(stopped). Any other error stays clientGone. In a scratch copy, that change gave client_closed 4005 40 times out of 40, and SocketEndSuite and SocketCloseLogSuite still pass.
Test row for SocketCloseLogSuite: the worker sends a ping frame and then a close with 4005, 5 times in a loop. Each line must contain close_reason=client_closed close_code=4005. The row fails on this head and passes with the fix.
| s.stopped = err | ||
| return err | ||
| } | ||
| if err := json.NewDecoder(bytes.NewReader(payload)).Decode(v); err != nil { |
There was a problem hiding this comment.
[Should fix] R1.2 One mutant survives. Replace the Decoder with json.Unmarshal(bytes.TrimSpace(payload), v): every touched suite still passes. With Unmarshal, a frame with bytes after its JSON value is refused. Base's ReadJSON accepts it, so the control does not pin "reads as ReadJSON does".
Test row for StreamsSuite: open /v1/llm/stream and send the text frame {"type":"start","target":"echo/echo-model"} trailing. Expect a started frame. I checked the row: it passes on this head and on base, and it fails under the mutant.
| | `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 a setting the model cannot take), and a frame it cannot read after the start (`tts`, `llm`) with `1000` | |
There was a problem hiding this comment.
[Nit] R1.3 "1008 for a setting the model cannot take" is incomplete. An unknown target (routing: unknown target) and a money refusal also close with 1008 and log refused, as my probe showed. Suggested wording: "1008 for a start the router refused (routing.ErrRequest) or refused for money". This goes to a ticket.
…h-stream-close-reason
A write that fails with ErrCloseSent, because the reader already answered the worker's close frame, was logged client_gone. writeEnd takes the reader's end from gone instead, bounded by closeWait. AI-3615 R1.1 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…its close The events socket, local and relayed, logged a write that failed with ErrCloseSent as client_gone, like /v1/dispatch did. Both writers now end through writeEnd. AI-3615 R1.5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
readJSON decodes the frame's first JSON value, as base's ReadJSON did; json.Unmarshal would refuse the frame. AI-3615 R1.2 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…r money AI-3615 R1.3 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…h-stream-close-reason
kanat
left a comment
There was a problem hiding this comment.
VERDICT: NO-GO
Round 2 (delta fde1b5f, merged onto main 2d4fdac). The three fixes work; one survivor needs a test row.
Prior findings
- R1.1 fixed: dispatch ping then close 4005, 5 rounds per run, 40 runs each with plain, -race and -cpu 1: client_closed 4005 every round. Mutant (the 7 dispatch writeEnd calls back to clientGone) killed.
- R1.5 fixed: the session socket (command answer racing the close) and the relayed socket (25 rounds x 20 commands) pass 40 runs each plain, -race and -cpu 1. Mutants of both killed.
- R1.2 fixed: mutant R3 (json.Unmarshal in readJSON) killed by TestAStartFrameWithBytesAfterItsJSONStarts.
- R1.3 fixed: the README row names 1008 for an unknown target, a setting or money, and the new "an unknown target" row pins it.
- R1.4 stays a ticket.
Checked, no finding
- writeEnd writes nothing; it only picks the logged cause, so no frame or close code sent to a client changed. A probe of dispatch, session and relay close sequences gave the same close codes and frames as the all-clientGone control.
- It waits on
goneonly for ErrCloseSent, bounded by closeWait (1 s); any other write error returns at once. ErrCloseSent means the reader already sent its close, so it cannot be stuck handing a pong to the writer.
Details: AI-3615/reviewer-2.md in the ship-task ledger.
| connection.SetWriteDeadline(time.Now().Add(writeWait)) | ||
| if err := connection.WriteJSON(reply); err != nil { | ||
| return | ||
| return writeEnd(err, gone) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
VERDICT: GO
Delta round 3 at 728c309 (test commit 5b755c1 and a merge of origin/main whose only conflict was readWorker's signature).
PRIOR:
- R2.1 (dispatchws.go:186, reply write to host_tools): fixed. The new row passes on head (3 of 3 runs). With the reply write mutated alone to a clientGone end, it fails 3 of 3, with close_reason=client_gone where the row expects client_closed close_code=4005.
- R1.1, R1.2, R1.3, R1.5: fixed in round 2, unchanged here.
- R1.4: ticket at exit, not blocking.
NEW FINDINGS: none.
The merge keeps main's behaviour: the only lines it changes are main's ctx threading and the PR's own write sites. The PR body lists the 7 unpinned writeEnd sites (ready, the three pings, tool call, call, message).
Checked on the merged tree over the current origin/main: the touched suites (SocketCloseLog, SocketEnd, Dispatch, ForwardedDispatch, Streams) pass with -race, 203 subtests. The new row also passes under -race with -cpu 1,4 and -count=20.
Not run: golangci-lint (unverified). CI is not run on a draft.
MUTATIONS: 1 checked, 0 survived.
) ## 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
#2218 (AI-3418) added
close_reason,close_codeandend_reasonto the access line of the session sockets only. A/v1/dispatchsocket and a/v1/{modality}/streamsocket still log theirserved a requestline 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, andwithRequestLogwrites the reason on the line it already writes. There is no newmsgand no newclose_reasonvalue.readEnd(socketend.go) reads why a reader stopped, as on the session sockets. For dispatch,readWorkernow returns its read error. It returned nil, so every end looked the same. The stream socket keeps the reader's error onsocket.stopped.socket.readJSONisReadJSONsplit intoReadMessageand ajson.Decoder, so a frame that is not JSON is told apart from a read that failed.startRefusedmarks a start failure that is the caller's. AnAPIErrorother 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:
1001, "router restarting")shutdown1012for a resumable session; here the code says which1011)server_errorrefusedwould send the reader to the start frame1011refused1011(TestAStartWithNoTargetEndsWithTheSameClose). This PR does not change that code, soclose_codeis1011tts/llmframe after the start (1000)refused1000, 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):
ClickHouse: the line stays in
logs.agent_requests(msg="served a request"). That view has noclose_reasonorclose_codecolumn yet, the same as after #2218. Until it gets one (a separate chat ticket), the fields can be read only frombody.Changes
internal/api/dispatchws.go:writeCallsreturns asocketEnd,readWorkerreturns its read error, anddispatchCallsrecords the end.internal/api/streamws.go:socket.stopped,socket.readJSONandstartRefused.socket.endreturns why the socket closed (closedWith), andstreamModalityrecords 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. Theclose_reasontable covers their ends.Validation
SocketCloseLogSuitedispatch testsclient_gone(the reader's error dropped); a drop with a code; an unreadable frame not a refusal; a drain not ashutdownwith1001SocketEndSuitedispatch write testsStreamsSuiteTestEachStreamSocketLogsTheCallersCloseWithItsCodeStreamsSuiterefusal testsserver_error; a first frame that is not JSON logged as a drop; an unreadablellmframe logged as a dropStreamsSuiteTestAProviderThatFailsToStartIsAServerError,TestAConfigThatCannotBeReadIsAServerErrorStreamsSuitebefore the start framerefusedStreamsSuiteandDispatchSuiteclose-code tests (base)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, eachstartRefusedwrap, each read loop'sstopped, eachclosedWithcase (internalAPIErrorincluded) and eachrecordClosecall.writeEndsite mutated alone toclientGone)dispatchws.goready write (written before any read, so no close can race it)dispatchws.go,sessionws.go,relayws.gopingEveryis a 30 s constantdispatchws.gotool call, call and message writesThe 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(pongWaitis 90 s,startWait30 s) and the read limit (1009).🤖 Generated with Claude Code