Skip to content

Bound WebSocket writes so a stalled peer cannot wedge the write loop - #63

Open
jphenow wants to merge 2 commits into
mainfrom
fix/ws-write-deadline
Open

jphenow wants to merge 2 commits into
mainfrom
fix/ws-write-deadline

Conversation

@jphenow

@jphenow jphenow commented Nov 3, 2026

Copy link
Copy Markdown
Member

wsAdapter.writeLoop calls WriteMessage with no deadline, while control frames in the same loop already use wsWriteWait:

case req := <-a.writeChan:
    err := a.conn.WriteMessage(req.messageType, req.data)   // unbounded
case <-ticker.C:
    a.conn.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(wsWriteWait))

Once a peer stops reading and the socket buffers fill, that call blocks indefinitely. Two things follow:

  1. Every caller waiting on WriteRaw waits forever.
  2. Pings stop. The ticker shares this select, so a wedged write silences the keepalive, and neither end ever concludes the connection is dead.

The read side is already defended against exactly this — wsPongWait, reset on pong, ping and any successful read. The write side had nothing.

Why this matters in practice

An interactive session can go half-open (laptop sleeps, NAT drops the mapping, network changes) and hang indefinitely with no timeout and no error. Keystrokes stop arriving, nothing is reported, and the only way out is killing the client from another terminal. This is one of the paths that can produce that, and it's the one where the connection is provably unable to report itself dead.

Change

  • Set a write deadline before each data write.
  • Close the connection if a write fails: a write that failed partway leaves an incomplete frame on the wire, so the connection can't carry another message. The error still reaches the waiting caller first. This is a behavior change — previously a failed data write was reported and the loop continued on a connection that may no longer be usable.
  • wsWriteWait becomes a var so the test can shorten it.

Test

A server that upgrades and then never reads. The client writes until the buffers fill.

  • Without the deadline: writes never return; the test hits its own 30s guard.
  • With it: an error surfaces in 250ms.

WriteMessage was called with no deadline while control frames already
used wsWriteWait. Once a peer stops reading and the socket buffers
fill, that call blocks indefinitely — and because the ping ticker
shares the same select, pings stop going out too, so neither end
concludes the connection is dead. The read side has wsPongWait for
exactly this case; the write side had nothing.

A write that failed partway leaves an incomplete frame on the wire, so
the connection is now closed rather than reused. The error still
reaches the waiting caller first.

wsWriteWait becomes a var so the test can shorten it. Without the
deadline that test hangs until its own 30s guard; with it, it finishes
in 250ms.
@jphenow
jphenow requested a review from a team as a code owner November 3, 2026 03:06
bodyclose flags the discarded *http.Response from the websocket dial: the
handshake response carries a body that has to be closed even when the
upgrade succeeded.

Claude-Session: https://claude.ai/code/session_01G2XvQ5dvdm32wf7K6mgdds
@aezell

aezell commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

This is far outside my go knowledge but my 🤖 said this:

1. On control-pool connections, the write error still ends in a permanent hang

This is the main one. When the sprite supports control connections — the default path in exec.go:212 — wsCmd.conn is the shared pooled controlConn.ws, and reads don't come from that socket directly. websocket.go:391:

func (c *wsCmd) readMessage() (messageType int, data []byte, err error) {
	if c.usingControl && c.controlConn != nil {
		select {
		case msg := <-c.controlConn.readCh:
		case <-c.ctx.Done():
		}
	}

With the new a.conn.Close() in writeLoop, the sequence is:

  1. The write deadline fires, and the error reaches the WriteRaw caller. That part works.
  2. a.conn.Close() closes the shared control socket.
  3. controlConn.readLoop (control_pool.go:312) gets a read error and plainly returns — it never closes readCh.
  4. runIO's read loop blocks on <-c.controlConn.readCh forever. readMessage has no closedCh case, and c.ctx is whatever the caller passed, commonly context.Background().
  5. runIO never returns, so c.doneChan never closes, so wsCmd.Wait() and Cmd.Wait() hang indefinitely.

So on the control path this converts "hang with no error" into "the caller gets an error, then Wait() hangs forever" — the user-visible symptom described in the PR body (session wedged, only way out is killing the client) is unchanged. A one-line addition in readMessage covers it:

case <-c.controlConn.closedCh:
    return 0, nil, errors.New("control connection closed")

The hang itself is pre-existing — any death of the control socket triggers it — but this PR adds a new and much more reachable trigger, and it's the difference between the fix working and not working on the default code path.

2. writeLoop returns without closing a.done

a.conn.Close()

return

a.done is only closed by wsAdapter.Close() (websocket.go:837). After writeLoop exits, writeChan has no reader, so every later WriteRaw/WriteControl enqueues into the 100-deep buffer and then blocks on result with nothing to release it. On direct connections the read loop rescues this by calling adapter.Close(); on control connections, per the point above, nothing does. Requests already sitting in writeChan when the loop exits are in the same position.

One trap if you fix this the obvious way: Close() is a bare close(a.done) with no sync.Once, and it's already called from several places (websocket.go:472, :531, :572, ...), so having writeLoop also close done needs a sync.Once or it's a close of closed channel panic. The same gap exists on the pre-existing ping-failure path, so one shared closeOnce would cover both.

Written by Claude!

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.

2 participants