Skip to content

Commit ca54146

Browse files
fix: honor timed Translation receives during terminal cleanup (#4132)
A sync Translation `recv(timeout=...)` could exceed its timeout after receiving `session.closed` because it also waited for the peer's close handshake. Return the terminal promptly and complete that close as an owned operation; explicit close and context exit still wait for completion and propagate cleanup failures. Untimed receives continue to close synchronously. Verification: the terminal regression fails before the change; all 51 Translation tests pass with websockets 13.0 and 15.0.1, including concurrent closes, error handoff, worker-start failure, and timed/untimed close interruption. Ruff, pinned Pyright and mypy pass. The trusted public budget passes (7455/10000) and isolation passes. The local `scripts/lint` wrapper stops at the same `uv --locked` error on unchanged main and this branch; no lockfile changed.
1 parent 8a2a2e0 commit ca54146

2 files changed

Lines changed: 306 additions & 3 deletions

File tree

‎src/openai/lib/realtime_translation.py‎

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import threading
66
from types import TracebackType
77
from typing import TYPE_CHECKING, Any, Literal, cast
8+
from concurrent.futures import Future
89

910
import httpx2
1011
from pydantic import BaseModel
@@ -72,6 +73,8 @@ class TranslationConnection:
7273
def __init__(self, connection: TranslationsConnection) -> None:
7374
self._connection = connection
7475
self._send_lock = threading.Lock()
76+
self._close_lock = threading.Lock()
77+
self._close_result: Future[None] | None = None
7578
self._state: Literal["open", "finishing", "closed"] = "open"
7679

7780
def send(self, event: RealtimeTranslationClientEvent | RealtimeTranslationClientEventParam) -> None:
@@ -100,13 +103,48 @@ def recv(self, *, timeout: float | None = None) -> RealtimeTranslationServerEven
100103
self._connection.recv_bytes() if timeout is None else self._connection._connection.recv(timeout=timeout)
101104
)
102105
if isinstance(event, RealtimeTranslationSessionClosedEvent):
103-
self.close()
106+
if timeout is None:
107+
self.close()
108+
else:
109+
self._close(background=True)
104110
return event
105111

106112
def close(self) -> None:
113+
self._close(background=False)
114+
115+
def _close(self, *, background: bool) -> None:
107116
# Do not wait for a blocked writer before aborting the transport.
108-
self._state = "closed"
109-
self._connection.close()
117+
with self._close_lock:
118+
self._state = "closed"
119+
result = self._close_result
120+
first = result is None
121+
if result is None:
122+
result = self._close_result = Future()
123+
124+
if first:
125+
if background:
126+
try:
127+
threading.Thread(target=self._finish_close, args=(result,), daemon=True).start()
128+
except BaseException as starting:
129+
# Keep ownership if the close worker couldn't start.
130+
self._finish_close(result)
131+
try:
132+
result.result()
133+
except BaseException as closing:
134+
raise starting from closing
135+
raise
136+
else:
137+
self._finish_close(result)
138+
if not background:
139+
result.result()
140+
141+
def _finish_close(self, result: Future[None]) -> None:
142+
try:
143+
self._connection.close()
144+
except BaseException as error:
145+
result.set_exception(error)
146+
else:
147+
result.set_result(None)
110148

111149

112150
class AsyncTranslationConnection:
Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,265 @@
1+
from __future__ import annotations
2+
3+
import time
4+
import threading
5+
from typing_extensions import override
6+
7+
import httpx2
8+
import pytest
9+
from websockets.exceptions import ConnectionClosed
10+
from websockets.sync.server import ServerConnection, serve
11+
12+
from openai import OpenAI, OpenAIError
13+
from openai.lib.realtime_translation import TranslationSession
14+
from openai.resources.realtime.translations.translations import TranslationsConnection
15+
16+
from .responses.test_websocket_session import script_server
17+
18+
19+
@pytest.mark.parametrize(
20+
"terminal,delay,timeout",
21+
[
22+
pytest.param(True, 0.35, 0.075, id="timed-terminal-delayed-close"),
23+
pytest.param(True, 0.0, 0.075, id="timed-terminal-normal-close"),
24+
pytest.param(False, 0.35, 0.075, id="timed-output-delayed-close"),
25+
pytest.param(True, 0.35, None, id="untimed-terminal-delayed-close"),
26+
],
27+
)
28+
def test_managed_translation_receive_close_deadline(
29+
terminal: bool, delay: float, timeout: float | None, monkeypatch: pytest.MonkeyPatch
30+
) -> None:
31+
monkeypatch.setenv("NO_PROXY", "127.0.0.1")
32+
monkeypatch.setenv("no_proxy", "127.0.0.1")
33+
sent = threading.Event()
34+
replied = threading.Event()
35+
finished = threading.Event()
36+
received: list[str | bytes] = []
37+
errors: list[Exception] = []
38+
event = (
39+
'{"type":"session.closed","event_id":"done"}'
40+
if terminal
41+
else '{"type":"session.output_audio.delta","event_id":"audio","delta":"AA=="}'
42+
)
43+
44+
class ReplyConnection(ServerConnection):
45+
@override
46+
def send_data(self) -> None:
47+
if self.protocol.close_rcvd is not None and not replied.is_set():
48+
replied.set()
49+
time.sleep(delay)
50+
super().send_data()
51+
52+
def handler(ws: ServerConnection) -> None:
53+
try:
54+
ws.send(event)
55+
sent.set()
56+
try:
57+
while True:
58+
received.append(ws.recv(timeout=5))
59+
except ConnectionClosed:
60+
# The managed connection owns and closes this socket.
61+
pass
62+
except Exception as exc:
63+
errors.append(exc)
64+
finally:
65+
finished.set()
66+
67+
with serve(handler, "127.0.0.1", 0, create_connection=ReplyConnection) as server:
68+
thread = threading.Thread(target=server.serve_forever, daemon=True)
69+
thread.start()
70+
try:
71+
url = f"http://127.0.0.1:{server.socket.getsockname()[1]}/v1"
72+
with OpenAI(api_key="local-test-key", base_url=url, http_client=httpx2.Client(trust_env=False)) as client:
73+
with TranslationSession(client.realtime.translations, model="gpt-realtime-translate") as connection:
74+
assert sent.wait(5), "fixture did not send its event"
75+
start = time.monotonic()
76+
result = connection.recv(timeout=timeout)
77+
elapsed = time.monotonic() - start
78+
assert result.type == ("session.closed" if terminal else "session.output_audio.delta")
79+
if timeout is not None:
80+
assert elapsed < timeout * 2, f"receive took {elapsed:.3f}s for a {timeout:.3f}s wait"
81+
elif terminal and delay:
82+
assert elapsed >= delay * 0.8, "untimed receive must still complete cleanup synchronously"
83+
if terminal:
84+
with pytest.raises(OpenAIError, match="input is closed"):
85+
connection.send({"type": "session.input_audio_buffer.append", "audio": "AA=="})
86+
assert finished.wait(5), "context exit did not finish native close"
87+
finally:
88+
server.shutdown()
89+
thread.join(timeout=5)
90+
assert not thread.is_alive()
91+
assert not errors, errors
92+
assert received == []
93+
94+
95+
def test_concurrent_explicit_closes_wait_for_one_timed_terminal_close(monkeypatch: pytest.MonkeyPatch) -> None:
96+
entered = threading.Event()
97+
release = threading.Event()
98+
completed = [threading.Event(), threading.Event()]
99+
failures: list[BaseException] = []
100+
calls = 0
101+
original_close = TranslationsConnection.close
102+
103+
def blocking_close(raw: TranslationsConnection, *, code: int = 1000, reason: str = "") -> None:
104+
nonlocal calls
105+
calls += 1
106+
entered.set()
107+
assert release.wait(5), "test did not release native close"
108+
original_close(raw, code=code, reason=reason)
109+
110+
def handler(ws: ServerConnection) -> None:
111+
ws.send('{"type":"session.closed","event_id":"done"}')
112+
with pytest.raises(ConnectionClosed):
113+
ws.recv(timeout=5)
114+
115+
with (
116+
script_server(handler) as url,
117+
OpenAI(api_key="local-test-key", base_url=url, http_client=httpx2.Client(trust_env=False)) as client,
118+
):
119+
with TranslationSession(client.realtime.translations, model="gpt-realtime-translate") as connection:
120+
monkeypatch.setattr(TranslationsConnection, "close", blocking_close)
121+
threads: list[threading.Thread] = []
122+
try:
123+
assert connection.recv(timeout=0.25).type == "session.closed"
124+
assert entered.wait(5), "owned close did not start"
125+
with pytest.raises(OpenAIError, match="input is closed"):
126+
connection.send({"type": "session.input_audio_buffer.append", "audio": "AA=="})
127+
128+
def close(index: int) -> None:
129+
try:
130+
connection.close()
131+
except Exception as exc:
132+
failures.append(exc)
133+
finally:
134+
completed[index].set()
135+
136+
for index in range(2):
137+
thread = threading.Thread(target=close, args=(index,))
138+
threads.append(thread)
139+
thread.start()
140+
assert not completed[0].wait(0.05), "first explicit close didn't wait"
141+
assert not completed[1].wait(0.05), "second explicit close didn't wait"
142+
finally:
143+
release.set()
144+
for thread in threads:
145+
thread.join(timeout=5)
146+
assert not thread.is_alive()
147+
assert all(done.is_set() for done in completed)
148+
assert failures == []
149+
assert calls == 1, "timed, concurrent and context closes must share one native close"
150+
151+
152+
@pytest.mark.parametrize("body_failure", [False, True], ids=["close-error", "block-error"])
153+
def test_timed_terminal_close_error_reaches_context_exit(monkeypatch: pytest.MonkeyPatch, body_failure: bool) -> None:
154+
original_close = TranslationsConnection.close
155+
closing = RuntimeError("fixture close failure")
156+
body = ValueError("fixture block failure")
157+
calls = 0
158+
159+
def fail_close(raw: TranslationsConnection, *, code: int = 1000, reason: str = "") -> None:
160+
nonlocal calls
161+
calls += 1
162+
original_close(raw, code=code, reason=reason)
163+
raise closing
164+
165+
def handler(ws: ServerConnection) -> None:
166+
ws.send('{"type":"session.closed","event_id":"done"}')
167+
with pytest.raises(ConnectionClosed):
168+
ws.recv(timeout=5)
169+
170+
with (
171+
script_server(handler) as url,
172+
OpenAI(api_key="local-test-key", base_url=url, http_client=httpx2.Client(trust_env=False)) as client,
173+
):
174+
expected = body if body_failure else closing
175+
with pytest.raises(type(expected)) as caught:
176+
with TranslationSession(client.realtime.translations, model="gpt-realtime-translate") as connection:
177+
monkeypatch.setattr(TranslationsConnection, "close", fail_close)
178+
assert connection.recv(timeout=0.25).type == "session.closed"
179+
if body_failure:
180+
raise body
181+
if body_failure:
182+
assert caught.value is body
183+
assert caught.value.__cause__ is closing
184+
else:
185+
assert caught.value is closing
186+
assert calls == 1
187+
188+
189+
@pytest.mark.parametrize("timeout", [0.25, None], ids=["timed-worker", "untimed-owner"])
190+
def test_interrupted_native_close_reaches_translation_owner(
191+
monkeypatch: pytest.MonkeyPatch, timeout: float | None
192+
) -> None:
193+
original_close = TranslationsConnection.close
194+
closing = KeyboardInterrupt("fixture close interrupted")
195+
caught: list[KeyboardInterrupt] = []
196+
calls = 0
197+
198+
def fail_close(raw: TranslationsConnection, *, code: int = 1000, reason: str = "") -> None:
199+
nonlocal calls
200+
calls += 1
201+
original_close(raw, code=code, reason=reason)
202+
raise closing
203+
204+
def handler(ws: ServerConnection) -> None:
205+
ws.send('{"type":"session.closed","event_id":"done"}')
206+
with pytest.raises(ConnectionClosed):
207+
ws.recv(timeout=5)
208+
209+
with (
210+
script_server(handler) as url,
211+
OpenAI(api_key="local-test-key", base_url=url, http_client=httpx2.Client(trust_env=False)) as client,
212+
):
213+
monkeypatch.setattr(TranslationsConnection, "close", fail_close)
214+
215+
def receive_and_close() -> None:
216+
try:
217+
with TranslationSession(client.realtime.translations, model="gpt-realtime-translate") as connection:
218+
assert connection.recv(timeout=timeout).type == "session.closed"
219+
except KeyboardInterrupt as exc:
220+
caught.append(exc)
221+
222+
# Bound even a broken Future completion: a stranded owner must fail this
223+
# test without preventing the test process from shutting down.
224+
owner = threading.Thread(target=receive_and_close, daemon=True)
225+
owner.start()
226+
owner.join(timeout=5)
227+
assert not owner.is_alive(), "Translation owner stayed blocked after close was interrupted"
228+
assert caught == [closing]
229+
assert calls == 1
230+
231+
232+
def test_failed_close_worker_start_still_closes_owned_translation(monkeypatch: pytest.MonkeyPatch) -> None:
233+
original_close = TranslationsConnection.close
234+
starting = RuntimeError("fixture worker could not start")
235+
calls = 0
236+
237+
def counted_close(raw: TranslationsConnection, *, code: int = 1000, reason: str = "") -> None:
238+
nonlocal calls
239+
calls += 1
240+
original_close(raw, code=code, reason=reason)
241+
242+
def fail_start(_thread: threading.Thread) -> None:
243+
raise starting
244+
245+
def handler(ws: ServerConnection) -> None:
246+
ws.send('{"type":"session.closed","event_id":"done"}')
247+
with pytest.raises(ConnectionClosed):
248+
ws.recv(timeout=5)
249+
250+
with (
251+
script_server(handler) as url,
252+
OpenAI(api_key="local-test-key", base_url=url, http_client=httpx2.Client(trust_env=False)) as client,
253+
):
254+
with TranslationSession(client.realtime.translations, model="gpt-realtime-translate") as connection:
255+
# Only inject failure after server and client transport workers exist.
256+
with monkeypatch.context() as patch:
257+
patch.setattr(TranslationsConnection, "close", counted_close)
258+
patch.setattr(threading.Thread, "start", fail_start)
259+
with pytest.raises(RuntimeError) as caught:
260+
connection.recv(timeout=0.25)
261+
assert caught.value is starting
262+
with pytest.raises(OpenAIError, match="input is closed"):
263+
connection.send({"type": "session.input_audio_buffer.append", "audio": "AA=="})
264+
connection.close()
265+
assert calls == 1

0 commit comments

Comments
 (0)