Skip to content

Accept upgrade responses split across TCP segments - #91

Open
joshk wants to merge 1 commit into
CuatroElixir:mainfrom
joshk:fix/upgrade-response-across-segments
Open

joshk wants to merge 1 commit into
CuatroElixir:mainfrom
joshk:fix/upgrade-response-across-segments

Conversation

@joshk

@joshk joshk commented Oct 18, 2026

Copy link
Copy Markdown

Problem

The connection only recognises the response to the WebSocket upgrade when Mint returns {:status, ...} and {:headers, ...} in the same batch (lib/slipstream/connection/pipeline.ex:65). Mint emits :status as soon as it has parsed the status line. So when the headers arrive in a later TCP segment (large headers, proxies, slow links), both responses fall through to the frame-decoding clause, which ignores anything that isn't :data (pipeline.ex:113).

The connection then stays in the :opened state forever. There's no ChannelConnected, no ChannelConnectFailed and no heartbeat, so the client neither connects nor retries.

Also, any WebSocket frames that arrive in the same packet as the end of the 101 response are dropped (the _maybe_done tail).

Reproduction

A raw :gen_tcp server that reads the upgrade request and then sends a valid 101 response in two writes:

:gen_tcp.send(sock, "HTTP/1.1 101 Switching Protocols\r\n")
Process.sleep(50)
:gen_tcp.send(sock, "upgrade: websocket\r\nconnection: Upgrade\r\nsec-websocket-accept: #{accept}\r\n\r\n")

The client never calls handle_connect/1 or handle_disconnect/2, and the connection process sits in status: :opened with websocket: nil.

Changes

  • The status and headers are accumulated in the connection state until both have arrived, however many packets that takes.
  • Data that arrives with the end of the upgrade response is decoded once the WebSocket has been created. Its events are emitted after ChannelConnected.

Relation to #75 / #88

This is a separate bug from #75. #88's upgrade timeout would turn this hang into an {:error, :upgrade_timeout} disconnect after 10 seconds, but the server's response here is valid and should succeed. The two changes are complementary, and I've checked that this branch and #88 merge cleanly.

How this was found, and AI use

I found this during a review of Slipstream's memory and timeout behaviour that I did with Claude Code. Claude spotted the single-batch assumption, reproduced the hang against main with a raw-TCP server, and wrote this change and its tests.

The connection only recognised the upgrade response when Mint returned the
`:status` and `:headers` responses in the same batch. Mint emits `:status`
as soon as the status line is parsed, so when the headers arrive in a later
TCP segment (large headers, proxies, slow links) both responses fell
through to the frame-decoding clause which ignores non-`:data` responses.
The connection then stayed in the `:opened` state forever: no
ChannelConnected, no ChannelConnectFailed and no heartbeat.

The status and headers are now accumulated in the connection state until
both have been received.

Any `:data` which arrives in the same packet as the end of the upgrade
response (WebSocket frames sent immediately after the 101) was also
dropped. It is now decoded once the WebSocket has been created and its
events are emitted after ChannelConnected.

This is independent of (and complementary to) an upgrade timeout: a
timeout would turn this hang into a failed connection, but the server's
response was valid and should be accepted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
joshk added a commit to nerves-hub/nerves_hub_link that referenced this pull request Oct 21, 2026
Groundwork for dropping Slipstream. This is the protocol it provides,
written as something we can fix ourselves, with nothing using it yet.

`NervesHubLink.Channel` is a data structure rather than a process: the
process that owns it feeds it the messages it receives and acts on the
events it gets back. A device has one connection and one state machine
over it, and the process boundary Slipstream puts in between costs more
than it pays for - it turns a push into a cross-process call that can
exit its caller, it hides the connection's death from the thing that
depends on it, and it leaves the `Mint.HTTP` struct somewhere its owner
has to read out of another process's state with `:sys.get_state/2`.

Alongside it: `Channel.Message` for the envelope, `Channel.Serializer`
for the behaviour, and `Channel.Serializer.JSON` for the v2 wire format
in both its text and binary forms. `Backoff.at/2` indexes a delay list
by attempt, repeating the last delay, so a device that has been failing
for hours keeps retrying at the longest interval rather than starting
over at the shortest and stampeding a server that has just come back.

Four of the things our open Slipstream pull requests fix are handled
here rather than carried over:

  * the upgrade response is accumulated across messages, because it can
    be split across TCP segments, and frames arriving in the same packet
    as the end of it are still decoded (CuatroElixir/slipstream#91)
  * a frame that cannot be decoded is logged and dropped instead of
    taking the connection with it, and ping, pong and unexpected frames
    are handled rather than crashing (#93)
  * the upgrade response is bounded by a timeout, so a server that
    accepts the connection and then says nothing cannot park the device
    there (#88)
  * a failed push returns an error to its caller instead of exiting it,
    which needs no code at all now that pushing is a function call (#90)

Tests run against a real websocket server, including a hand-built one
that writes the upgrade response in pieces to cover the split response.
Writing them turned up a bug worth noting: a reply to a join that had
since been superseded was being taken as the answer to the join that
replaced it, reporting a topic joined while its join was still
unanswered. Phoenix sends `join_ref` precisely so the two can be told
apart, and the channel now checks it.

`.dialyzer_ignore.exs` gains one entry. Dialyzer cannot see the nonce
that `Mint.WebSocket.upgrade/5` leaves in the connection, so it reads
`Mint.WebSocket.new/4`'s success branch as unreachable; a minimal,
fully typed call reports the same thing. The ignore comment records
what was tried instead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant