Skip to content

Ignore WebSocket errors after the signal connection has opened on web - #1303

Open
j-mercker wants to merge 1 commit into
livekit:mainfrom
j-mercker:j-mercker/ws-double-complete
Open

j-mercker wants to merge 1 commit into
livekit:mainfrom
j-mercker:j-mercker/ws-double-complete

Conversation

@j-mercker

Copy link
Copy Markdown

Problem

On web, every signal connection that fails after it opened throws an uncaught Bad state: Future already completed. The connection itself is handled correctly (the socket is disposed and the engine reconnects), but each drop shows up in the app's error reporting as an uncaught exception.

Seen on web with 2.13.2 on LiveKit Cloud: 10 reports from 9 users over 2 days on one build, each within about a second of the SDK starting a reconnect. Symbolicated:

Bad state: Future already completed
  _Completer.completeError                         dart:async/future_impl.dart:81
  LiveKitWebSocketWeb.connect.<anonymous closure>  package:livekit_client/src/support/websocket/web.dart:87
  _EventStreamSubscription.<anonymous closure>     package:web/src/helpers/events/streams.dart:165

Cause

LiveKitWebSocketWeb.connect completes its Completer on open and calls completeError on error, and the error listener stays attached after connect returns. When an open connection later fails, the browser fires error and then close, so completeError runs on a completed Completer. The close listener set up in LiveKitWebSocketWeb._ already handles the failure.

Reproduces in Chrome 158 with a server that completes the handshake and then sends a frame with reserved bits set: open at 6 ms, error at 1008 ms, close 1006, then the second completion throws.

Repro: python3 bad_ws_server.py and python3 -m http.server 8766 --bind 127.0.0.1, then open http://127.0.0.1:8766/index.html

bad_ws_server.py

"""Accepts one WebSocket handshake per connection, waits 1 s, then sends a frame with reserved bits set,
which the browser must treat as a protocol error (fail the connection: `error`, then `close`)."""
import base64, hashlib, socket, threading, time
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
def handle(c):
    req = c.recv(4096).decode(errors="replace")
    key = next(l.split(":", 1)[1].strip() for l in req.split("\r\n") if l.lower().startswith("sec-websocket-key"))
    acc = base64.b64encode(hashlib.sha1((key + GUID).encode()).digest()).decode()
    c.sendall(f"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {acc}\r\n\r\n".encode())
    time.sleep(1)
    c.sendall(bytes([0xF1, 0x00]))  # FIN + RSV1-3 set, opcode 1, no extension negotiated -> protocol error
    time.sleep(2); c.close()
s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1); s.bind(("127.0.0.1", 8765)); s.listen()
while True:
    c, _ = s.accept(); threading.Thread(target=handle, args=(c,), daemon=True).start()

index.html

<!doctype html><meta charset="utf-8"><title>ws error after open</title><pre id="out">running…</pre>
<script>
(async () => {
  const t0 = performance.now(); const ev = []; let completed = false; const completerErrors = [];
  // Same listener shape as livekit_client's LiveKitWebSocketWeb.connect: complete on open, completeError on error.
  const complete = how => { if (completed) completerErrors.push(`Bad state: Future already completed (${how})`); completed = true; };
  const ws = new WebSocket('ws://127.0.0.1:8765/rtc');
  ws.onopen = () => { ev.push(['open', Math.round(performance.now() - t0)]); complete('complete'); };
  ws.onerror = () => { ev.push(['error', Math.round(performance.now() - t0), 'readyState ' + ws.readyState]); complete('completeError'); };
  await new Promise(r => { ws.onclose = e => { ev.push(['close', Math.round(performance.now() - t0), e.code, e.wasClean]); r(); }; setTimeout(r, 6000); });
  document.getElementById('out').textContent = JSON.stringify({ua: navigator.userAgent, events: ev, completerErrors}, null, 2);
})();
</script>

Fix

  • The error listener completes the Completer only if it has not completed yet.

Testing

  • New browser test test/support/websocket_web_test.dart, "an open connection that fails is disposed without an uncaught error". A spawnHybridUri server (test/support/websocket_web_error_server.dart) opens the socket and then breaks the protocol, and the test checks that onDispose runs and nothing reaches the zone. It fails on main with Bad state: Future already completed and passes here. Like the other @TestOn('browser') tests it runs with flutter test --platform chrome, not in the VM run in CI.
  • Full suite: 607 passed, 1 skipped. Analyze, format, import order and version checks pass.

Notes

  • Not a regression. 2.13.2, 2.14.0 and main behave the same.

@CLAassistant

CLAassistant commented Nov 22, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@devin-ai-integration devin-ai-integration 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.

🔍 Devin Review: 1 flag

Not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants