Skip to content

Add resumable sessions: yamux survives transport failures - #2

Merged
DiamondGo merged 3 commits into
mainfrom
resumable-session
Sep 3, 2026
Merged

DiamondGo merged 3 commits into
mainfrom
resumable-session

Conversation

@DiamondGo

Copy link
Copy Markdown
Owner

Summary

Implements plans/pollmux-resumable-session-design.md: an opt-in, purely additive resumable session mode. When both ends enable it (client Connector.PreferResume, server ServerConfig.EnableResume) on WebSocket or two-way stream transport, a transport failure no longer kills the yamux session. The client resumes the same session id via POST {prefix}/{id}/resume, both sides replay the bytes lost at the seam, and every stream (e.g. an SSH connection through the tunnel) carries on. This is the fix for the "CDN max-connection-age kills the tunnel once an hour" problem described in the design.

What changed

  • reliable.go — the byte layer shared verbatim by client and server. Data frames on a resumable session are frameSeqData (8-byte absolute offset + data); frameAck acknowledges cumulatively. Unacked bytes are retained for replay; receivers dedup by offset and refuse gaps. ACKs piggyback on reverse traffic and are sent eagerly after half a yamux window. Exceeding MaxReplayBytes only ends resumability — a live connection keeps working.
  • resume_server.go — one attachment per direction on the server: a newer transport kicks a stale one (pipe interrupt + write/read deadline / CloseNow) and waits for it to leave, so offsets are trustworthy and the stream is never interleaved. ResumeHandler performs the offset exchange (200/404/409/410/426/503 semantics documented on the handler).
  • resumable_client.go — resumableConn: yamux is built once; a supervisor tears down failed legs, resumes with backoff within the server-handed resume_grace_ms, and only closes TransportFailed when resuming is impossible (session gone, offsets unhonourable, replay overflow, grace exhausted). ReconnectLoop is unchanged and remains the fallback.
  • Session / SessionStore — detached resumable sessions are judged by ResumeGrace (default 30s, capped at 5m) instead of SessionTimeout; CloseSessionIfNoPollInFlight refuses them while in grace (so a periodic reaper like HttpBroker's needs no change); MaxDetachedResumable caps the memory a burst of disconnects can hold; Session.Resumable() / ResumeDeadline() for observability.
  • BufferedPipe.interrupt — level-triggered wake for ReadAvailable; unexported, unused by non-resumable paths.
  • Negotiation — ConnectRequest.PreferResume, ConnectResponse.Resumable, Limits.ResumeGraceMS. ProtocolVersion unchanged; old×new in either direction degrades to today's behaviour; batch mode never negotiates resume. If the upload auto-probe fails on a resumable connect, the client deletes that session and reconnects once without resume.

Deviations from the design are recorded in §17 of the plan (notably: data frames must carry offsets for dedup to be possible; the frameResume frame was not needed). README gains a "六、跨重连会话恢复" section.

Tests

  • Unit: reliable layer (numbering/replay/dedup/gap/overflow/eager ack), frame codec, pipe interrupt, attachments.
  • Handler-level: negotiation matrix, resume status codes, deterministic seam-loss replay from the declared offset, upstream dedup and gap refusal, kicking a parked poll, newer poll displacing older, grace vs SessionTimeout, conditional close, detached cap, DELETE race with hook exactly-once.
  • End-to-end through a fault-injecting TCP proxy, for stream and WebSocket: 3MB transfer with the link killed 7 times mid-flight is byte-exact with no reconnect; idle kill; grace expiry → TransportFailed + eviction; server-closed session not resurrected; server-off / client-not-asking degrade; probe failure fallback; replay overflow gives up cleanly.
  • Two-hop mini-broker relay: both hops killed repeatedly, tunnelled stream survives, neither role reconnects; control test with resume off dies as today.
  • go test ./..., go test -race ./..., and the resume suite at -count=15 all pass.

Follow-up (HttpBroker repo)

Config passthrough for PreferResume / EnableResume / ResumeGrace, mount ResumeHandler behind the same auth middleware, and enable it on both hops.

🤖 Generated with Claude Code

https://claude.ai/code/session_012vJHFMFrjk4Y3qcWW1eWHh

Implement plans/pollmux-resumable-session-design.md. A session that
negotiates Resumable (client PreferResume && server EnableResume, on
WebSocket or two-way stream mode) keeps its yamux session and every
stream alive across a transport failure: the client resumes the same
session id through POST {prefix}/{id}/resume instead of reconnecting.

- reliable.go: the byte layer shared by both ends. Data frames become
  frameSeqData carrying an absolute offset; frameAck acknowledges.
  Unacknowledged bytes are retained for replay; the receiver dedups by
  offset and refuses gaps. Overflowing MaxReplayBytes only ends
  resumability, never a live connection.
- resume_server.go: one attachment per direction on the server (a newer
  transport kicks a stale one and waits for it to leave), and
  ResumeHandler, which exchanges recv offsets after kicking whatever is
  still attached.
- resumable_client.go: resumableConn, whose supervisor tears down failed
  legs, resumes with backoff within the server's grace, and only falls
  back to TransportFailed when resuming is impossible.
- Session/SessionStore: detached resumable sessions live for ResumeGrace
  instead of SessionTimeout, are refused by CloseSessionIfNoPollInFlight
  while in grace, and are capped by MaxDetachedResumable.
- BufferedPipe.interrupt: level-triggered wake for ReadAvailable, used to
  detach stale writers promptly and to send eager acks.

Negotiation is purely additive; old and new binaries mix freely and
batch mode never resumes. §17 of the plan records where the
implementation deviates from the design and why.

Tests: unit tests for the reliable layer, frame codec, pipe interrupt
and attachments; handler-level tests for the handshake, deterministic
seam-loss replay, dedup/gap handling, grace/sweeper/conditional-close
behaviour; end-to-end tests through a fault-injecting TCP proxy for
stream and WebSocket (repeated kills mid-transfer, idle kills, grace
expiry, degradation paths, probe fallback, replay overflow); and a
two-hop relay test where both hops are killed and the tunnelled stream
survives.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vJHFMFrjk4Y3qcWW1eWHh

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Sorry @DiamondGo, your pull request is larger than the review limit of 150,000 diff characters

… docs

- resumableConn.ws becomes an atomic.Pointer. Close already ordered its
  read after the supervisor's writes via wg.Wait, but the safety of that
  should not hinge on a reader knowing the ordering.
- resume's backoff gets ±20% jitter: the failure this feature exists for
  (a CDN closing every connection at its maximum age) hits a fleet of
  clients in the same second, and they should not all retry on one beat.
- BufferedPipe.ReadAvailable documents that errPipeInterrupted says
  nothing about the pipe's contents: an interrupt landing during the
  coalesce window is reported on the following call, after that call's
  data has been returned, so callers must only re-check and call again.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vJHFMFrjk4Y3qcWW1eWHh
@DiamondGo

Copy link
Copy Markdown
Owner Author

Addressed the review in the latest commit:

  1. c.ws access — switched to atomic.Pointer[websocket.Conn]. Note that Close() already read it after wg.Wait() had waited the supervisor (the only writer) out, and the dial context derives from c.ctx so cancel() interrupts an in-flight dial; the change removes the reliance on that ordering rather than fixing an observed race.
  2. Pipe interrupt during the coalesce window — behaviour kept (consuming the flag there would lose the interrupt); the ReadAvailable doc now states explicitly that errPipeInterrupted says nothing about buffered contents and callers must only re-check state and call again, which every caller does.
  3. Backoff jitter — resume retries now spread by ±20%.

Full suite, -race on the resume/relay tests, and the resume suite at -count=3 pass.

@DiamondGo

Copy link
Copy Markdown
Owner Author

Review item 3 (offset validation / markBroken on 409): behaviour kept, reasoning documented on ResumeHandler and in the README security notes.

  • A wrong offset can only come from a peer whose state has drifted or from someone holding the session id. The honest peer abandons the session on 409 anyway (it falls back to a fresh session and DELETEs this one on Close), so ending resumability costs it nothing.
  • Marking broken is what stops a drifted peer from retrying with other offsets until one lands inside the replayable range — resuming from a guessed offset is exactly the silent corruption the layer exists to prevent.
  • Authorization is identical to /poll, DELETE and /ws: the 128-bit session id plus the application's middleware; the docs now say explicitly that /resume must sit behind the very same middleware. A caller who can reach it could equally DELETE the session, so it adds no capability the id did not already confer.

@DiamondGo
DiamondGo merged commit d3330dc into main Sep 3, 2026
2 checks passed
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