Skip to content

[AI-3615] Log why dispatch and stream sockets closed - #2271

Merged
kanat merged 10 commits into
mainfrom
kanat/ai-3615-dispatch-stream-close-reason
Nov 25, 2026
Merged

kanat merged 10 commits into
mainfrom
kanat/ai-3615-dispatch-stream-close-reason

Conversation

@kanat

@kanat kanat commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

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

/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 kanat left a comment

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.

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

Comment thread acceleration/internal/api/dispatchws.go Outdated
connection.SetWriteDeadline(time.Now().Add(writeWait))
if err := connection.WriteJSON(frame{"type": "pong", "at": at}); err != nil {
return
return socketEnd{cause: clientGone}

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] 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 {

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] 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.

Comment thread acceleration/README.md Outdated
| `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` |

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.

[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.

kanat and others added 6 commits November 23, 2026 20:58
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>

@kanat kanat left a comment

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.

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 gone only 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)

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.

kanat and others added 2 commits November 24, 2026 08:59

@kanat kanat left a comment

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.

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.

@kanat
kanat marked this pull request as ready for review November 24, 2026 08:17
@kanat
kanat merged commit 9d21bda into main Nov 25, 2026
13 checks passed
@kanat
kanat deleted the kanat/ai-3615-dispatch-stream-close-reason branch November 25, 2026 03:17
kanat added a commit that referenced this pull request Nov 25, 2026
)

## 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant