Skip to content

[AI-3616] A relayed socket cut by its holder says the relay ended - #2419

Merged
kanat merged 3 commits into
mainfrom
kanat/ai-3616-relay-close-reason
Nov 25, 2026
Merged

kanat merged 3 commits into
mainfrom
kanat/ai-3616-relay-close-reason

Conversation

@kanat

@kanat kanat commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

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

…y ended

When the node running a session gave back the proxy watcher of a socket on
another node (expireProxies) while the session went on, that socket logged
close_reason=session_ended and closed with 1000 "the session ended", so every
SDK took the conversation for over.

The holder now marks relay.Closed as detached when its session had not ended,
and the socket's node logs close_reason=relay_ended and closes with 1011
"the relay to the session ended", which SDKs read as a dropped socket.

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: GO

Security round 1 on head 016e5f0. No findings.

  • Only the node holding the session sets Detached; client frames travel as a different message type on the command topic and never reach the field. A probe sending such frames from a client left the socket open and the session's own end still closed it as session_ended.
  • A running session reads Detached, and an ended one does not, because Ended is set before the watchers close. Halted and close-command ends keep their old close.
  • Detached is read only through the existing watcher and owner lookup, so it adds no new state across apps or users. A probe showed one expired watcher closes only its own socket and leaves a sibling socket of the same session open.
  • The close text and the new log cause are constants. The diff has no err.Error() or error-formatting hit.
  • Removing the store of Detached in deliver fails the new test.

Unverified: access control on the relay bus in a deployment. A node with bus access can already close any watcher's socket, so Detached adds nothing there.

@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 1 at 016e5f0ae, merged onto main at cd3f7371d (merges clean, no conflict). CI: draft, so go and integration are skipped on this head. They run at gh pr ready.

The verdict rests on R1.1 (Should fix): the README row and the PR body say a caller reconnects. Only one client does that. The code change itself is sound.

[Nit] R1.4 acceleration/internal/api/handwritten.go:249-250 (not in the diff): the events socket's spec description names the 1000 and 1012 closes. It does not name the new 1011 "the relay to the session ended", and a relayed socket can now get that close whether it is resumable or not. Client authors read the spec. Ticket: add one sentence and run go run ./cmd/openapi.

Checked and sound:

  • Ordering: session.go sets Ended in one place only (close(), :1982), and it does so under s.mu before the watchers close (:1992). Every end goes through close(): Close, halt and abandon. A watcher channel closes in only three places. :619 is a watch on a session that has already ended, so State reads Ended. :1992 is the end. :704 is the detach, which is the case this PR flags. The reverse race (a detach, then the end, then the running() read) reports session_ended for a session that did end. A node drain halts sessions through close(), so it reads Halted and not Detached, and closes 1012 as before.
  • Mixed builds: relay.Response has one decoder, deliver, which uses plain json.Unmarshal, so an old socket node ignores detached. An old holder omits it, so Detached is false and the socket behaves as on base.
  • Reconnect: Go reconnects with resumable, cursor and request_id. The dispatch path asks again only for an interrupted command (sdks/go/agents/dispatch.go:454), and only a router stopping produces that, not this path. A replayed tool call is re-sent only while it still waits (session.go:634-640). An expiry needs 90 s of missed refreshes, and failed reconnects back off, so neither a tight loop nor a duplicate turn follows.
  • 1011 is not used on the events socket elsewhere, so it does not collide with 1012 (shutdown) or 1000.
  • Generated files are in step (generated.sh). gofmt and vet are clean. Unit tests for ./internal/api and ./internal/relay pass. Integration suites SocketCloseLogSuite, RelayedSessionSuite, CrossShardSessionSuite, ForwardedSessionSuite and NodeRetrySuite pass on the merged tree, and the two new tests pass at -count=5.
  • Mutants: 13 run, 11 killed. They are 6 of the author's 14, rerun, plus 7 new ones: Detached derived from !byCommand() or !halted(), the session state read once at attach, no close frame, falling through to the session-end branch, the tick skipping dropExpired, and the store moved after the close. The tick (R1.2) and the store ordering (R1.3) survived. Both are Nits.

Comment thread acceleration/README.md Outdated
| `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` and `/v1/{modality}/stream` |
| `session_ended` | The session ended for another reason. `end_reason` says which. Session sockets only |
| `relay_ended` | A socket relayed from another node lost the watcher the node running the session held for it, such as one given back for a socket it had not heard from in time, while the session went on (`1011`). The caller reconnects to go on watching. Events socket only |

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 caller reconnects to go on watching" holds only for Go, and there only for a text session's resumable socket (sdks/go/stream/accelerated.go:377 resumable := session.CallId == "", :948). JS (socket.ts:285 → session.ts:905 end), Kotlin (SessionSocket.kt:30-33 "No automatic reconnection, on purpose"; AgentSession.kt:502-507 ends with a failure) and Dart (socket.dart:16-17, :120-123) report a failure and stop. Swift (SessionSocket.swift:116-119) reports socketClosed for any close, 1000 included (.claude/skills/sdk/SKILL.md:758). The PR body says the same thing twice: in the table ("Every SDK reads anything but 1000 as a dropped socket, so a caller reconnects") and in "Who reads this" ("Each treats 1000 as the end").

The behaviour is right: the session still runs. Fix the wording, for example: "A resumable socket's caller reconnects (the Go SDK, for a text session); other clients see the socket fail, not the session end." Correct the body to match.

"watcher", watcher)
state.dropProxy(watcher)
}
s.dropExpired(state)

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.2 No test reaches this tick. A mutant that deletes the dropExpired call survives. The wiring is moved code and had no test on base either, and pingEvery is a 30 s const. Ticket only.

socket.byCommand.Store(true)
}
if response.Detached {
socket.detached.Store(true)

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 No test pins "set before closed". Moving this store after socket.close() survived 10 of 10 runs. It is the same pattern as halted and byCommand above, and no deterministic test can see the gap between two adjacent statements. Ticket only, or accept.

… socket spec names the 1011 relay close

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: GO

Delta round 2 at 014a887e1 (was 016e5f0ae), merged onto main at dca845c2e. The delta changes the README row, one spec sentence, the PR body and the generated clients. No Go, SDK or test code changed.

Prior findings:

  • R1.1 (Should fix, the relay_ended row and the PR body): fixed. Each SDK checked against its code: Go reconnects only a resumable socket (sdks/go/stream/accelerated.go:377, :948; dropped at :1031). JS socket.ts:285, Kotlin SessionSocket.kt:30-34, Dart socket.dart:119-120, Swift SessionSocket.swift:117-118. The PR table row, "Who reads this" and the first Why paragraph now match.
  • R1.4 (Nit, spec text): fixed. handwritten.go names the 1011 relay close. Mutation: openapi.yaml reset to 016e5f0ae, and handwritten.go reset to 016e5f0ae, each makes TestPostureSuite/TestTheCommittedSpecIsRenderedFromTheOperations fail; the head passes.
  • R1.2, R1.3 (Nits): left for tickets by decision. Not re-checked in this delta.

New findings:

  • Nit, not blocking (changed hunk): the relay_ended row says the other clients "see the socket fail, not the session end". That holds for the signal the router sends. Kotlin still ends the local conversation on any socket failure (AgentSession.kt:194-195, :502-507 sets Conversation.State.Ended), and JS does the same (sdks/js/src/session.ts:909-912). Wording option: "the other clients see their socket fail with that code; the session still runs."

Checks:

  • go run ./cmd/openapi, uv run plugins/stream/generate.py, uv run sdks/swift/generate.py --check, and npm run types after npm ci: no diff against the head. The tree has no dashboard/.
  • go test ./internal/api ./cmd/openapi (unit) passes. Integration TestPostureSuite (including the freshness test) and TestSocketCloseLogSuite pass, on the head merged onto dca845c2e.
  • CI: the PR is a draft; gh pr checks shows Analyze, CodeQL, labeler and GitGuardian passing, the rest skipped.
  • Code behaviour: the only Go change is a string in the events socket's description.

Comment thread acceleration/README.md Outdated
| `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` and `/v1/{modality}/stream` |
| `session_ended` | The session ended for another reason. `end_reason` says which. Session sockets only |
| `relay_ended` | A socket relayed from another node lost the watcher the node running the session held for it, such as one given back for a socket it had not heard from in time, while the session went on (`1011`). A resumable socket's caller reconnects to go on watching (the Go SDK does, for a text session); the other clients see the socket fail, not the session end. Events socket only |

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, not blocking (wording). "The other clients see the socket fail, not the session end" holds for the signal the router sends. Kotlin still ends the local conversation on any socket failure (AgentSession.kt:502-507 sets Conversation.State.Ended) and JS does too (sdks/js/src/session.ts:909-912). Option: "the other clients see their socket fail with that code; the session still runs."

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kanat
kanat marked this pull request as ready for review November 25, 2026 04:09
@kanat
kanat merged commit 32f4de2 into main Nov 25, 2026
28 checks passed
@kanat
kanat deleted the kanat/ai-3616-relay-close-reason branch November 25, 2026 04:45
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