Skip to content

Commit 337769b

Browse files
fix: end sync WebSocket recovery when an attempt is interrupted (#4129)
A `KeyboardInterrupt` or `SystemExit` during synchronous WebSocket reconnect could leave later sends in a queue with no recovery running. End queue admission whenever the attempt exits, preserve the interruption, and let a later receive retry without replaying rejected sends. Validation: 143 focused recovery and queue tests pass, including 36 interruption cases across nine public modes that failed before the fix. Ruff, Mypy, Pyright and the trusted custom-code budget (7351/10000) pass. The local `scripts/lint` wrapper stops at the unchanged baseline `uv.lock` with both the host and CI-pinned uv versions. The same failure reproduces on the base revision; the underlying lint and type checks pass. No dependency or lockfile changes are included. Hosted CI remains the check of the complete wrapper.
1 parent 07abe06 commit 337769b

2 files changed

Lines changed: 144 additions & 67 deletions

File tree

‎src/openai/_websocket_connection.py‎

Lines changed: 63 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -98,74 +98,74 @@ def _reconnect(self, exc: Exception) -> bool:
9898
else:
9999
self._is_reconnecting = True
100100

101-
for attempt in range(self._reconnect_attempt + 1, self._max_retries + 1):
102-
self._reconnect_attempt = attempt
103-
base_delay = min(self._initial_delay * (2 ** (attempt - 1)), self._max_delay)
104-
jitter = 0.75 + random.random() * 0.25
105-
delay = base_delay * jitter
106-
107-
event = ReconnectingEvent(
108-
attempt=attempt,
109-
max_attempts=self._max_retries,
110-
delay=delay,
111-
close_code=close_code,
112-
extra_query=self._extra_query,
113-
extra_headers=self._extra_headers,
114-
)
115-
116-
try:
117-
result = self._on_reconnecting(event)
118-
except Exception:
119-
self._is_reconnecting = False
120-
return False
121-
122-
if result is not None and result.get("abort"):
123-
self._is_reconnecting = False
124-
return False
125-
126-
if result is not None:
127-
if "extra_query" in result:
128-
self._extra_query = result["extra_query"]
129-
if "extra_headers" in result:
130-
self._extra_headers = result["extra_headers"]
101+
try:
102+
for attempt in range(self._reconnect_attempt + 1, self._max_retries + 1):
103+
self._reconnect_attempt = attempt
104+
base_delay = min(self._initial_delay * (2 ** (attempt - 1)), self._max_delay)
105+
jitter = 0.75 + random.random() * 0.25
106+
delay = base_delay * jitter
107+
108+
event = ReconnectingEvent(
109+
attempt=attempt,
110+
max_attempts=self._max_retries,
111+
delay=delay,
112+
close_code=close_code,
113+
extra_query=self._extra_query,
114+
extra_headers=self._extra_headers,
115+
)
116+
117+
try:
118+
result = self._on_reconnecting(event)
119+
except Exception:
120+
return False
131121

132-
self._logger.info(
133-
"Reconnecting to WebSocket API (attempt %d/%d) after %.1fs delay",
134-
attempt,
135-
self._max_retries,
136-
delay,
137-
)
138-
if self._interruptible_reconnect:
139-
closed = self._close_event.wait(delay)
140-
else:
141-
time.sleep(delay)
142-
closed = self._intentionally_closed
143-
if closed:
144-
self._is_reconnecting = False
145-
return False
122+
if result is not None and result.get("abort"):
123+
return False
146124

147-
try:
148-
connection = self._make_ws(self._extra_query, self._extra_headers)
125+
if result is not None:
126+
if "extra_query" in result:
127+
self._extra_query = result["extra_query"]
128+
if "extra_headers" in result:
129+
self._extra_headers = result["extra_headers"]
130+
131+
self._logger.info(
132+
"Reconnecting to WebSocket API (attempt %d/%d) after %.1fs delay",
133+
attempt,
134+
self._max_retries,
135+
delay,
136+
)
149137
if self._interruptible_reconnect:
150-
with self._connection_lock:
151-
closed = self._intentionally_closed
152-
if not closed:
153-
self._connection = connection
154-
if closed:
155-
connection.close()
156-
self._is_reconnecting = False
157-
return False
138+
closed = self._close_event.wait(delay)
158139
else:
159-
self._connection = connection
160-
self._logger.info("Reconnected to WebSocket API")
161-
self._is_reconnecting = False
162-
self._flush_send_queue()
163-
return True
164-
except Exception:
165-
pass
140+
time.sleep(delay)
141+
closed = self._intentionally_closed
142+
if closed:
143+
return False
166144

167-
self._is_reconnecting = False
168-
return False
145+
try:
146+
connection = self._make_ws(self._extra_query, self._extra_headers)
147+
if self._interruptible_reconnect:
148+
with self._connection_lock:
149+
closed = self._intentionally_closed
150+
if not closed:
151+
self._connection = connection
152+
if closed:
153+
connection.close()
154+
return False
155+
else:
156+
self._connection = connection
157+
self._logger.info("Reconnected to WebSocket API")
158+
self._is_reconnecting = False
159+
self._flush_send_queue()
160+
return True
161+
except Exception:
162+
# Ordinary setup failures consume an attempt. The outer
163+
# finally ends queue admission when recovery exits.
164+
pass
165+
166+
return False
167+
finally:
168+
self._is_reconnecting = False
169169

170170
def _flush_send_queue(self) -> None:
171171
"""Send all queued messages over the current connection."""

‎tests/lib/test_websocket_recovery_lifecycle.py‎

Lines changed: 81 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import asyncio
44
import threading
5-
from typing import Any
5+
from typing import Any, Callable
66
from typing_extensions import override
77

88
import pytest
@@ -13,17 +13,25 @@
1313
PRODUCTS = ["realtime", "transcription", "sideband", "responses", "live"]
1414

1515

16-
def manager(client: Any, product: str) -> Any:
17-
def on_reconnecting(_event: Any) -> None:
16+
def manager(client: Any, product: str, on_reconnecting: Callable[[Any], Any] | None = None) -> Any:
17+
def allow_reconnecting(_event: Any) -> None:
1818
pass
1919

20-
options = {"on_reconnecting": on_reconnecting, "initial_delay": 0}
20+
options = {"on_reconnecting": on_reconnecting or allow_reconnecting, "initial_delay": 0}
2121
if product == "realtime":
2222
return client.realtime.connect(model="test-model", **options)
2323
if product == "transcription":
2424
return client.realtime.connect(extra_query={"intent": "transcription"}, **options)
2525
if product == "sideband":
2626
return client.realtime.connect(call_id="test-call", **options)
27+
if product == "beta_responses":
28+
return client.beta.responses.connect(**options)
29+
if product == "live_forks":
30+
return client.live.forks.connect(session_id="test-session", **options)
31+
if product == "live_sideband":
32+
return client.live.sideband.connect(session_id="test-session", **options)
33+
if product == "translations":
34+
return client.realtime.translations.connect(model="test-model", **options)
2735
return getattr(client, product).connect(**options)
2836

2937

@@ -267,3 +275,72 @@ def receive() -> None:
267275
release.set()
268276
worker.join(10)
269277
iterator.close()
278+
279+
280+
@pytest.mark.parametrize("product", PRODUCTS + ["beta_responses", "live_forks", "live_sideband", "translations"])
281+
@pytest.mark.parametrize("interrupt_from", ["callback", "handshake"])
282+
@pytest.mark.parametrize("error_type", [KeyboardInterrupt, SystemExit])
283+
def test_interrupted_sync_recovery_rejects_sends_until_retried(
284+
monkeypatch: pytest.MonkeyPatch, product: str, interrupt_from: str, error_type: type[BaseException]
285+
) -> None:
286+
original, replacement = Socket(True), Socket(False)
287+
failure = error_type("synthetic recovery interruption")
288+
opens = 0
289+
callbacks = 0
290+
291+
def connect(*_args: Any, **_kwargs: Any) -> Socket:
292+
nonlocal opens
293+
opens += 1
294+
if opens == 1:
295+
return original
296+
if opens == 2 and interrupt_from == "handshake":
297+
raise failure
298+
return replacement
299+
300+
def reconnecting(_event: Any) -> None:
301+
nonlocal callbacks
302+
callbacks += 1
303+
if callbacks == 1 and interrupt_from == "callback":
304+
raise failure
305+
306+
monkeypatch.setattr("websockets.sync.client.connect", connect)
307+
with OpenAI(api_key="fake-key") as client:
308+
with manager(client, product, reconnecting) as connection:
309+
with pytest.raises(error_type) as caught:
310+
next(iter(connection))
311+
assert caught.value is failure
312+
with pytest.raises(ConnectionClosedError):
313+
connection.send_raw('{"type":"synthetic.after_interrupt_raw"}')
314+
with pytest.raises(ConnectionClosedError):
315+
connection.send({"type": "synthetic.after_interrupt_typed"})
316+
# A later receive may start another recovery. The failed sends
317+
# above must not be silently transmitted as a result.
318+
event = next(iter(connection))
319+
assert getattr(event, "type", None) == "synthetic.progress"
320+
assert callbacks == 2
321+
assert opens == (3 if interrupt_from == "handshake" else 2)
322+
assert original.sent == []
323+
assert replacement.sent == []
324+
325+
326+
@pytest.mark.parametrize("product", PRODUCTS)
327+
def test_ordinary_sync_reconnecting_error_preserves_original_close(
328+
monkeypatch: pytest.MonkeyPatch, product: str
329+
) -> None:
330+
original = Socket(True)
331+
332+
def connect(*_args: Any, **_kwargs: Any) -> Socket:
333+
return original
334+
335+
monkeypatch.setattr("websockets.sync.client.connect", connect)
336+
337+
def reconnecting(_event: Any) -> None:
338+
raise ValueError("synthetic callback error")
339+
340+
with OpenAI(api_key="fake-key") as client:
341+
with manager(client, product, reconnecting) as connection:
342+
with pytest.raises(ConnectionClosedError):
343+
next(iter(connection))
344+
with pytest.raises(ConnectionClosedError):
345+
connection.send_raw('{"type":"synthetic.after_error"}')
346+
assert original.sent == []

0 commit comments

Comments
 (0)