Skip to content

🐛 Fix WebSocket reconnect upgrade, pending request fast-fail, send cancellation, and heartbeat probe - #5345

Merged
guiyanakuang merged 4 commits into
mainfrom
fix/ws-reconnect-stability
Nov 22, 2026
Merged

guiyanakuang merged 4 commits into
mainfrom
fix/ws-reconnect-stability

Conversation

@guiyanakuang

Copy link
Copy Markdown
Member

Summary

Fixes 4 WebSocket reconnection and transport stability issues in shared commonMain code (tracked downstream in CrossPaste/crosspaste-mobile#2710):

  1. Rebuild WebSocket in SyncResolver.verifyConnection() (and trust paths)

    • Previously attemptWebSocketUpgrade(host, port) was only invoked in authenticate(). When a peer remained SyncState.CONNECTED in DB while its WebSocket session was absent (e.g., iOS resuming after pause() called closeAll(), or any transient WS drop where HTTP heartbeat still succeeds), verifyConnection() returned connectState without ever re-upgrading to WebSocket, permanently degrading to 60s HTTP polling.
    • Now verifyConnection() invokes attemptWebSocketUpgrade(host, port) when HTTP heartbeat returns SyncState.CONNECTED (guarded by existing isConnected and WsConnectionPolicy.shouldInitiate checks), and initial trust paths also trigger opportunistic upgrade immediately.
  2. Fast-fail in-flight WsPendingRequests on session close / replacement / closeAll()

    • Bound each pending slot in WsPendingRequests to (appInstanceId, session) using a SynchronizedObject-guarded map, and added failForSession, failForPeer, and failAll (completing waiters with WsSessionClosedException).
    • Wired fast-fail into registerSession (on replacement for the old session), unregisterSession, notifySessionClosed, closeSession, and closeAll, and handled non-cancellation failures in WsSessionManager.sendPastePush as WsPayloadSendResult.Failed so in-flight pushes/pulls unwind immediately instead of hanging for 30s.
  3. Do not swallow CancellationException in WsSessionManager.send()

    • Replaced runCatching in send() (via sendToSession()) with try / catch (e: CancellationException) { throw e } catch (e: Exception) so cancelling a caller coroutine no longer tears down a healthy WebSocket session.
  4. Correlated application-level heartbeat probe for half-open detection

    • Added WsCapability.HEARTBEAT_ACK to handshake capability negotiation and echoed requestId in WsMessageHandler for HEARTBEAT / HEARTBEAT_ACK.
    • WsSessionManager.probe() now sends a correlated HEARTBEAT and awaits HEARTBEAT_ACK within timeoutMs (default WsSession.PING_TIMEOUT_MS) for peers advertising WsCapability.HEARTBEAT_ACK, eliminating half-open TCP false positives while preserving session.ping() fallback for legacy peers.

Verification

  • ./gradlew ktlintFormat && ./gradlew app:desktopTest ktlintCheck — all 2,358 fast-tier tests + ktlint passed.
  • ./gradlew app:desktopTest -PintegrationTests --tests "com.crosspaste.net.ws.WsAuthenticationIntegrationTest" — all 5 integration tests passed.

@guiyanakuang guiyanakuang left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

NEEDS FIX

Round 1 review covers 6452b2ed9cb1d3c55b03e89ddddfc750b150d1f8. Found 4 P1 issues covering underlying channel cancellation, half-open detection on standard devices, concurrent handshakes, and pending request cleanup on session close. See inline comments for details.

Ran 108 targeted desktop tests on a temporary copy of this commit (covering WebSocket session management, message handling, auth integration, and sync resolution) — all passed. Verified all 4 findings with dedicated temporary repro tests. git diff --check passed, and GitHub app-build and ci checks passed.

Real-device mobile background/foreground transitions and cross-version reconnection were not live-tested.

@guiyanakuang guiyanakuang left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

NEEDS FIX

Round 2 incremental review covers 6452b2ed..9a3b4c99. All 4 findings from round 1 have been verified as fixed and marked resolved.

Found 2 new P1 issues in this increment: application-level heartbeat timeouts can interrupt active sync transfers, and handshake deduplication can drop updated peer addresses/ports. See inline comments for details.

113 targeted desktop tests passed, along with the 2 previous repro tests on this commit. Verified both new findings with real Ktor loopback and MockEngine repro tests. git diff --check passed. Real-device mobile and cross-version reconnection remain untested.

@guiyanakuang guiyanakuang left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

NEEDS FIX

I reviewed the changes from 9a3b4c99 to e638e9a1. Endpoint changes now cancel the stale handshake and dial the new address immediately. I resolved that thread.

The slow-ingestion heartbeat case is fixed. The existing P1 remains open because the probe can still close a healthy connection while an incoming chunked paste is making progress. I posted the reproduction on the existing thread.

All 117 targeted desktop tests passed. The two previous reproductions now pass, and a focused frame-reader test reproduces the remaining receive-side case. git diff --check passed. Mobile lifecycle and mixed-version reconnects were not tested.

@guiyanakuang guiyanakuang left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

PASS / LGTM

I reviewed e638e9a1..0265b204 and found no high-confidence issues. Both the client and server now record inbound frame progress during message assembly. The previous reproduction confirms that the session stays connected when chunks arrive during the heartbeat timeout window. I marked the remaining P1 thread as resolved.

All 127 targeted desktop tests and the temporary reproduction passed. Coverage included WebSocket authentication, legacy frame decoding, malformed chunk sequences, and idle heartbeat timeout handling. git diff --check passed. Mobile lifecycle and mixed-version reconnects were not tested on devices.

@guiyanakuang
guiyanakuang merged commit a90af10 into main Nov 22, 2026
7 checks passed
@guiyanakuang
guiyanakuang deleted the fix/ws-reconnect-stability branch November 22, 2026 15:16
guiyanakuang added a commit that referenced this pull request Nov 23, 2026
…eartbeat_ack support (#5346)

Follow-up to #5345 improving WebSocket lifecycle and backpressure stability:

- Add pause/resume gating to WsSessionManager, WsClientConnector, and WsRouting so pausing atomically rejects new sessions/handshakes, cancels in-flight dials, and closes active sessions.
- Enforce per-session inbound business queue limits (128 MiB payload bytes / 256 messages) in dispatchWsSessionMessages, closing overflowing sessions with TRY_AGAIN_LATER (1013) so peers fall back to retry/HTTP without unbounded memory growth.
- Advertise heartbeat_ack capability in the browser extension and echo requestId in HEARTBEAT_ACK responses while remaining backwards-compatible with legacy heartbeats.
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