Skip to content

Swift: resume a text session's socket, and notice when it's gone - #2802

Open
martinmitrevski wants to merge 4 commits into
mainfrom
feat/swift-resume-socket
Open

martinmitrevski wants to merge 4 commits into
mainfrom
feat/swift-resume-socket

Conversation

@martinmitrevski

@martinmitrevski martinmitrevski commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Why

When a text session's socket drops today, the conversation stops updating on this device. The network going, a while in the background, or a router deploy all leave session.turns frozen and events() finished, and the app has to notice and attach again. The router has been able to resume a socket since #1211 (2026-10-26), and Go resumes with it; Swift never did.

Worse, some drops are never noticed at all. URLSessionWebSocketTask answers the router's pings but never says one came. It never reads a connection that went away without a close as gone, whether out of a network's range or a router node lost. I checked this with a macOS command-line client against a local server that took the upgrade and went silent: receive() was still waiting after 20 s, even with a 3 s request timeout. I haven't checked it on iOS, but it's the same URLSession, and nothing in this PR depends on iOS behaving differently. Such a session stays "connected" and frozen.

This uses the healthcheck frame from #2811 (merged) for those silent drops. Until a router with #2811 is deployed, the healthcheck part does nothing: a router without it sends no healthchecks, and nothing is timed before the first one.

It replaces the Swift skill paragraph #2794 wrote, which said reconnection was not built yet.

How it works

  • Resume, as the router's contract says. A text session's socket opens with resumable=true and healthcheck=true. AgentSession keeps the last cursor a frame carried and skips the resumed a first socket starts with.
    • When it reopens: on any close but 1000 or 1005, on a connection lost without a close, or when it lets the socket go itself (next three bullets). It reopens with the cursor and the request_id of the last question asked through responses.
    • When it stops:
      • when the socket opens;
      • when a 4xx refuses it, except that a 401 is tried once more with a fresh token and a 429 is tried again;
      • when the session is closed or detached.
    • A call's socket is not resumable and behaves as before. That's decided when the socket first opens: a text session moved onto a call is still resumed, because its conversation outlives the call.
  • A connection that went quiet. Once a healthcheck has come, three of its intervals going by with nothing read is a lost connection. That's 30 s at the router's 10 s.
  • The network. Recovery (Reconnection.swift) watches the network for as long as the session is followed, as StreamCore's DefaultConnectionRecoveryHandler does for Stream Chat.
    • When the network goes, the socket is let go at once, rather than read on.
    • No attempt is made while the network is gone. The first after it comes back is at once.
    • Only a change counts: a first reading of no network, with a socket that just opened, is not believed.
  • The background. The socket is kept for one background task, as Stream Chat keeps its own (staysConnectedInBackground), so a reply in flight or a tool running can finish.
    • It is let go when the task's time runs out, or at once when iOS gives no task, before the app is suspended with it open.
    • No attempt is made in the background. The first after the app comes back is at once.
    • A session moved onto a call with startVoice() keeps its socket, as Video exempts a call in progress: the call keeps the app running, and the agent still calls its tools.
    • The background task is ended on every way out: the foreground, close(), detach(), the socket stopping, and the session being released. One left running past its time gets the app killed.
    • Background state comes from the app's notifications, not isAppActive. That reads false where there is no UIApplication, as in an app extension or a test, and would stop every reconnect there.
  • A socket let go here reads as a drop. SessionSocket.drop ends the stream with socketClosed itself, then cancels the task, and only for the opening it was decided for. A plain close() would finish the stream quietly, which reads as the session ending.
  • The waits are StreamCore's. DefaultRetryStrategy gives the backoff Stream Chat and Video use: the first retry at once, growing to 25 s.
    • One strategy per session. Failures count across reconnects and start over only after a socket stayed open 10 s (Reconnection.steadyAfter, one healthcheck interval), as Chat starts over once a socket is connected.
    • Why not start over on every accepted upgrade: a router that takes the socket and closes it at once would then be asked again with no wait, forever.
    • It's reset rather than copied, since copies share their failure count, which lives in a class.
    • StreamCore's WebSocketClient and ping controller are not used. Both wait for Stream's own health-check event, which the router never sends, and the client retries a refused upgrade forever.
  • Nothing is let go while it reconnects. isConnected is false, but readers of events() read on, approvals wait, and tools keep running.
    • A result that could not be sent waits for the socket that carries on. The router never resends a call delivered before the cursor, so a dropped result would leave it waiting until the tool times out.
  • What the socket missed. A reconnected socket's resumed reaches events(). When complete is false:
    • Calls waiting for approval are dropped. A restarted router no longer has them; right after resumed, it asks again about any it still waits on.
    • The reply in flight is finished in Conversation when the receipt says the question is settled, or there is no receipt, so nothing streams forever.
    • A question the receipt says was interrupted is asked once more under a new request id, as the contract says. That happens once only, and only if the question was asked in the last five minutes. close() waits for that request before stopping the session, so the router doesn't carry on a conversation that was just ended.
  • The cursor. A reconnected socket's resumed names the newest frame, and the missed frames follow it, so its cursor is taken only when complete is false. A drop before the missed frames arrive then asks for them again.
  • 1012 was read as the session ending. URLSession has no name for close code 1012, which the router uses to say it is restarting. It reports 1005 and puts the whole close payload, code bytes included, in closeReason. SessionSocket.closing reads the code back.

Docs: no public API changes, so no CHANGELOG line. The Swift skill, the sdk skill's resume paragraph and the README describe it. #2811's healthcheck note is corrected where it says Swift neither asks for healthchecks nor resumes. .claude/skills/sdk/notes/2026-11-30-swift-resumes-text-sockets.md tells the other SDKs what they'll meet, including starting the healthcheck watch again on every opening.

Differences from Go

  • No time limit. Go gives up after 5 minutes. An app holding the conversation wants it back whenever the network or the app is, and no attempt is made while either is gone. After 5 minutes unwatched the router has ended the session, and reconnecting carries it on, which is what attaching again would do.
  • Results kept across the reconnect. Go drops a tool result finished while it reconnects (sdks/go/stream/accelerated.go:1257); Swift keeps it. The note flags it for Go, along with approvals, the resumed cursor and the re-ask's time limit.

Not done

  • Missed turns are not read back into session.turns when complete is false. Responses list oldest first and carry no turn ids to match, so it needs its own design. A conversation kept in Stream Chat is unaffected, since its views read the channel.
  • The re-ask most likely shows the question twice in the Chat channel, because each command writes the person's message. Go does the same. replaces with empty text may be the better retry; that's a contract question for the router.
  • No public "reconnecting" state. A view sees isConnected false and failure nil.
  • A tool step whose tool_ran was among the lost frames stays "running" in a reply that is otherwise finished. The existing interrupted handling leaves steps the same way, and Swift: a tool call's state is kept in its turn's steps #2800 rewrites these steps.
  • A failed re-ask isn't reported anywhere. The SDK has no logger, and nobody is waiting on that request to throw to. The reply stays interrupted, as the transcript shows.
  • A call's own socket (a session attached as voice) still has no healthcheck. It isn't resumed, so a 30 s stall would end following the call for good. Making call sockets resumable is its own change.

Validation

  • New tests in SessionsTests, against a local server scripting each upgrade:
    • Resume:
      • carrying on from the last cursor through a 1012, with readers reading on;
      • a dropped connection reopened;
      • 1000 not reconnected;
      • a call's socket neither resumable nor reconnected;
      • a reconnect after a socket that worked starting at once;
      • one after a socket closed as soon as it opened waiting longer each time;
      • a drop before the missed frames arrive asking for them again.
    • Refusals:
      • a 4xx refusing for good;
      • 503 and 429 retried;
      • a 401 retried once with a fresh token.
    • While reconnecting:
      • a tool result finished mid-reconnect sent on the new socket;
      • approvals kept or dropped by complete;
      • an interrupted question asked once more, and only once, within five minutes;
      • closing while reconnecting.
    • Healthchecks:
      • a socket whose healthchecks stop is dropped, told to the router, and reopened from its cursor, with no healthcheck reaching events();
      • a socket that never had a healthcheck, after one that did, is not taken for dead.
    • Network:
      • the network going drops the socket, no attempt is made until it's back, and the first after is at once;
      • a first reading of no network holds nothing back.
    • Background:
      • with a background task, the socket is kept, then dropped when the time runs out; without one, it's dropped at once. Either way no attempt is made until the app comes back, and the first after is at once;
      • a socket that opens in the background is dropped;
      • a session on a call keeps its socket;
      • the background task ends on coming back, on close(), on detach(), and when the router ends the session;
      • the network or the app coming back cuts a wait short.
  • One parameterized test in ConversationTests for settling the reply in flight.
  • Existing tests:
    • Four that dropped a text session's socket now drop a call's, which keeps their point (a socket that isn't resumed).
    • The foreground test now drives a fake app state instead of posting UIKit's notification to every session in the run.
  • Break checks: I broke each piece of the change on its own and confirmed the matching test fails. That's 19 checks for resume, 20 for the healthcheck, network and background, and 2 for the backoff, all caught. A few showed up only as hangs, so those tests have a one-minute limit.
  • Not covered by a test:
    • close() waiting for a re-ask in flight;
    • a declined result surviving a drop;
    • the app going to the background during the very first connect (only during a reconnect is tested);
    • the drop at the end of background time racing the app's suspension.
  • Suite runs:
  • Not run against a real router or on a device. That includes iOS's real background-task timing and a real network change.

Self-review

Two fresh reviewers read the diff, and the review bot read it after.

First round (resume):

  • the backoff never resetting;
  • approvals outliving a router restart;
  • the resumed cursor skipping the missed frames;
  • the re-ask having no time limit and racing close();
  • declined results bypassing the queue;
  • the README overstating when it stops.

Second round (healthcheck, network, background):

  • a first reading of no network blocked every reconnect;
  • the app going to the background while a socket was opening was missed;
  • the background-expiry close was documented as guaranteed;
  • one test check could never fail;
  • the foreground test reached every session in the run.

The review bot:

  • the backoff starting over on every accepted upgrade, so a router that took the socket and closed it at once was asked again with no wait;
  • detach() and delete() waiting on a question being asked again;
  • a text session moved onto a call still being resumed, which is now documented as intended.

Everything is fixed except the spinning tool step, which is left as described above. My own testing found:

  • URLSession reading 1012 as the session ending;
  • a Combine closure inferred as main-actor-isolated, which trapped when the network monitor called it;
  • the background test racing its own first frame under the suite's concurrency.

🤖 Generated with Claude Code

@martinmitrevski
martinmitrevski changed the base branch from main to oliver/router-session-heartbeat December 1, 2026 10:19
@martinmitrevski
martinmitrevski force-pushed the feat/swift-resume-socket branch from 04adf4f to 9a9eb57 Compare December 1, 2026 10:19
@martinmitrevski martinmitrevski changed the title Swift: resume a text session's socket Swift: resume a text session's socket, and notice when it's gone Dec 1, 2026
@martinmitrevski
martinmitrevski force-pushed the feat/swift-resume-socket branch 2 times, most recently from 34268bc to d096cff Compare December 1, 2026 10:27
@martinmitrevski
martinmitrevski marked this pull request as ready for review December 1, 2026 11:24
@getstream-metis

getstream-metis Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

👋 Thanks, Martin! I'm on it.

How to work with me

  • 💬 Disagree with a finding? Reply in its thread and tell me why. I'll withdraw it, or answer with evidence.
  • 🔁 Fixed it? Just push. The next round checks your fix and resolves the thread.
  • 👍 👎 Rate my findings. I learn what your team doesn't want flagged.
  • ✅ I approve once nothing blocking is left: must-fix always blocks, should-fix only in the first two rounds. CI isn't part of that; branch protection still holds the merge until it's green. On repos that require a human approval, a teammate still has to approve too.
Commands

Comment any of these on the PR:

  • /jeffery review · start a review
  • /jeffery next-round · start the next round now
  • /jeffery pause · /jeffery resume · stop or restart reviews on this PR
  • /jeffery status · where things stand
  • /jeffery help · all commands

@getstream-metis getstream-metis Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 1 · 🆕 3 new · 1 should-fix to go

Finding Where
🟡 Should Fix Reconnect backoff restarts on every accepted upgrade AgentSession.swift:323

🆕 New commit 85beb56 · the next round starts at 11:55 UTC, once you've stopped pushing.

  • Start the next round now

let recovery = recovery
// Isolated to the main actor as this is, so it runs only once `lifecycle` names it.
let retrying = Task { [weak self] in
var retries = reconnection.retries()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should Fix] Reconnect backoff restarts on every accepted upgrade
Issue: A router that accepts the upgrade and then closes at once gets an immediate retry every time, so each client loops upgrade, close, token fetch with no growing wait.
Cause: reconnect builds a fresh reconnection.retries() at line 323 whose first delay is zero, and reopen returns true as soon as the upgrade opens (lines 370-380), so the backoff never grows.
Fix: Keep the retry strategy across drops and start a new one only after a frame is read from the reconnected socket. Or: enforce a minimum wait when the last socket lived only briefly.
Side effect: everyReconnectStartsAtOnce in SessionsTests.swift pins the current behaviour and needs updating.

Evidence
  • AgentSession.swift:300-301 follow() sends every socketClosed of a resumable session to reconnect(), whatever the close code
  • AgentSession.swift:323 each reconnect() creates a new retries() strategy; its first delay is zero
  • AgentSession.swift:370-380 reopen() returns true once the upgrade opens, so nothing carries the failure count forward
  • SessionsTests.swift ~909-926 everyReconnectStartsAtOnce has the server close 1012 right after each upgrade and expects the next request at once
  • Nothing in the diff caps attempts or total time

private func connect(_ attempt: UUID) async {
// A text session outlives its socket, so its socket can be resumed. A call's cannot:
// the call is the router's, and ends with it.
let resumable = session.callID.isEmpty

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consider: Resumable is fixed at connect but a session can move onto a call
resumable is read once from session.callID here, while lost() and mayTry read callID live. A text session that calls startVoice() keeps reconnecting with a cursor, which the docs say a call's socket does not do. Either re-read callID at drop time or say in the docs that such a session keeps being resumed.

approvals = []
unsent = []
// Asked before the session is stopped, so the router does not carry it on after.
await askingAgain?.value

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consider: detach() and delete() wait on the re-ask request
finish awaits askingAgain for detach() and delete() too, though only close() needs the re-ask to land before the stop. Guarding it with if stopping stops them blocking on an HTTP call.

Suggested change
await askingAgain?.value
if stopping { await askingAgain?.value }

Base automatically changed from oliver/router-session-heartbeat to main December 1, 2026 11:31
@martinmitrevski
martinmitrevski force-pushed the feat/swift-resume-socket branch 2 times, most recently from 9653db9 to 298f8ad Compare December 1, 2026 11:44
martinmitrevski and others added 4 commits December 1, 2026 12:45
A text session's socket that drops is opened again after the last
cursor, asking after the question waited on, with StreamCore's retry
strategy, network monitor and app-state notifications deciding when.
Readers of events(), approvals and running tools carry on across it,
and a tool result that could not be sent goes on the next socket. A
question the router interrupted on its way down is asked once more.
URLSession reports the router's 1012 as 1005, so the code is read back
from the close payload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A fresh retry strategy for each reconnect: StreamCore's counts its
  failures in a class every copy shares, so the backoff never reset.
- Calls waiting for approval are dropped when a reconnected socket
  missed frames: a restarted router no longer has them, and allowing
  one would run the tool for nothing. The router asks again about the
  ones it still has.
- A reconnected socket's resumed cursor is taken only when complete is
  false, so a drop before the missed frames arrive asks for them again.
- An interrupted question is asked again only if asked in the last five
  minutes, and closing waits for that request before stopping.
- Declined results go through deliver, so a drop doesn't lose them.
- The network wakes a reconnect only when it comes back, not on the
  monitor's first reading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
URLSession never reads a connection that went away without a close as
gone: receive() waits on, and the request timeout does not apply once the
socket is open. A text session now:

- asks for the router's healthchecks (#2811) and, once one has come,
  takes three intervals with nothing read as a lost connection. Nothing
  is timed before a socket's first, so a router without them is not
  taken for dead;
- lets its socket go when the network goes, and makes no attempt to
  reopen it until the network is back. Only a change counts: a first
  reading of no network is not believed;
- keeps its socket for one background task, then lets it go, and makes
  no attempt until the app is back. A socket that opens in the background
  with no time left is let go at once, and a session moved onto a call
  keeps its socket. The background task ends on every way out.

A socket let go here ends its stream with socketClosed itself, for the
opening it was decided for, so it reads as a drop and is resumed.

Reviewed by a fresh agent: a first reading of no network stopped every
reconnect, the app going to the background while a socket opened was
missed, and two test checks could not fail. All fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The backoff is one strategy for the session, counted across reconnects
  and started over only after a socket stayed open 10 s (one healthcheck
  interval). Started over on every accepted upgrade, a router that took
  the socket and closed it at once was asked again with no wait, for good.
- detach() and delete() no longer wait for a question being asked again:
  only close() stops the session, which is what that wait is for.
- Say that a text session moved onto a call is still resumed: whether a
  socket is resumable is decided when it first opens, and the
  conversation outlives the call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@martinmitrevski
martinmitrevski force-pushed the feat/swift-resume-socket branch from 298f8ad to 85beb56 Compare December 1, 2026 11:45

This branch has not been deployed

No deployments
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