Repository navigation
fix(helpers): propagate audio stream producer errors - #3817
Hughhhhcoder wants to merge 1 commit into
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
AI-assisted independent offline check at 4/4 controls pass on this head versus 1/4 on pinned main. Beyond the existing producer-error case, caller cancellation now leaves no pending internal tasks and finalizes the blocked generator. A raised output-stream setup error likewise leaves no pending producer task. An empty successful stream still finishes through the callback sentinel. Pending tasks are counted before harness cleanup; baseline cancellation/setup cases each left one pending task. Scope: Exact local_audio_player.py loaded directly to avoid the helpers package initializer. numpy dtype and sounddevice callbacks are explicit fakes. No native bindings, real device, array conversion, full buffered playback or saturated executor/backpressure proof. Python 3.14.7 / Pydantic 2.13.5 and shared local dependencies; this is a bounded matrix, not a full SDK suite or historical dependency matrix. Network denied by the sandbox. Standalone reproducer (run separately with each source tree on PYTHONPATH)import asyncio,importlib.util,json,pathlib
import openai
from types import SimpleNamespace
spec=importlib.util.spec_from_file_location('openai.helpers.local_audio_player',pathlib.Path(openai.__file__).parent/'helpers/local_audio_player.py')
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
class Stop(Exception):pass
class Data:
def __setitem__(self,key,value):pass
async def check(mode):
loop=asyncio.get_running_loop();prior=asyncio.all_tasks();started=asyncio.Event();closed=False;handles=[]
class Stream:
def __init__(self,**kwargs):self.callback=kwargs['callback']
def __enter__(self):
if mode=='enter_failure':raise ValueError('fictional stream setup')
if mode=='normal':handles.append(loop.call_later(.02,self.tick))
return self
def tick(self):
try:self.callback(Data(),1,None,None)
except Stop:return
handles.append(loop.call_later(.02,self.tick))
def __exit__(self,*args):
for h in handles:h.cancel()
async def buffers():
nonlocal closed
try:
started.set()
if mode=='producer_failure':raise RuntimeError('fictional producer')
if mode=='caller_cancel':await asyncio.Event().wait()
if False:yield None
finally:closed=True
m.np=SimpleNamespace(float32='float32');m.sd=SimpleNamespace(OutputStream=Stream,CallbackStop=Stop)
task=asyncio.create_task(m.LocalAudioPlayer().play_stream(buffers()));kind=None
try:
if mode=='caller_cancel':await asyncio.wait_for(started.wait(),.3);task.cancel()
await asyncio.wait_for(task,.4)
except BaseException as exc:kind=type(exc).__name__
await asyncio.sleep(0)
leaked=[x for x in asyncio.all_tasks()-prior if not x.done()]
expected={'normal':None,'producer_failure':'RuntimeError','caller_cancel':'CancelledError','enter_failure':'ValueError'}[mode]
row={'case':mode,'exception':kind,'expected_exception':expected,'pending_internal_tasks':len(leaked),'generator_finalized':closed,'pass':kind==expected and not leaked and (closed or mode=='enter_failure')}
# Retrieve/cancel leaked tasks only after recording the observation, to bound this probe.
for x in leaked:x.cancel()
await asyncio.gather(*leaked,return_exceptions=True)
return row
async def main():
rows=[await check(x) for x in ['normal','producer_failure','caller_cancel','enter_failure']]
print(json.dumps({'cases':rows,'passed':sum(x['pass'] for x in rows),'failed':sum(not x['pass'] for x in rows),'scope':'Actual play_stream coroutine; fake numpy dtype and sounddevice callbacks, no audio devices/native bindings/array conversion proof.'}))
asyncio.run(main()) |
Castiron custom codeEvaluated main: ✅ No new custom-code files detected. 36 mixed files remain; 0 existing customizations changed. Compared 36 existing customizations unchanged
A changed generated baseline means this report cannot reliably identify which handwritten lines changed. Inspect the custom-code diffDownload the exact patch produced by this run (requires repository access): gh run download 37729141162 --repo openai/openai-python \
--name castiron-custom-code-37729141162-1 --dir /tmp/castiron-custom-code-37729141162-1
git apply --stat /tmp/castiron-custom-code-37729141162-1/custom-code.patch
cat /tmp/castiron-custom-code-37729141162-1/custom-code.patchOr reproduce it from an SDK checkout containing the vendored reporter: git fetch --no-tags origin 4e152cdefe1844c2d5d78653310e9b9c0195c44e 54eb21ec7eebd0bb71cc188d5b9a143f078d381a
python3 scripts/castiron/custom_code_report.py report \
--base 4e152cdefe1844c2d5d78653310e9b9c0195c44e \
--head 54eb21ec7eebd0bb71cc188d5b9a143f078d381a --fetch --require-head-hash --public \
--out /tmp/castiron-custom-code-54eb21ec7eeb
cat /tmp/castiron-custom-code-54eb21ec7eeb/custom-code.patchThis is the current full custom patch for mixed files, not an attribution of only the handwritten lines changed by this PR. |
Changes being requested
LocalAudioPlayer.play_stream()currently waits only for the audio callback's completion event before it awaits the input producer task. If the supplied async generator raises, the producer task finishes with that exception but no one sets the playback event, so the public method hangs and asyncio reports that the task exception was never retrieved.This change waits for playback completion and producer completion together. A producer failure is propagated immediately; normal producer completion still waits for the callback to consume the queued completion sentinel, so buffered playback behavior is unchanged. The cleanup path also cancels and retrieves either internal task when the caller exits early.
A hardware-free regression replaces
sounddevice.OutputStreamwith a silent context manager and verifies that a synthetic input-generator failure reaches the caller instead of timing out.Validation:
uv run --locked --all-extras pytest -q tests/test_local_audio_player.py tests/lib/test_audio.py— 5 passed on Python 3.10.uv run --isolated --python 3.14— 5 passed../scripts/lintwith the repository-pinned Node.js 22.22.3 — Ruff passed; Pyright reported 0 errors; Mypy reported no issues in 1614 source files; import check passed.main: the same input timed out after 200 ms and emittedTask exception was never retrievedfor the originalRuntimeError.The generated API audio tests require the repository's Steady mock server. They were not counted as passing in this environment; without that server they returned HTTP 502 before exercising this helper.
Additional context & links
The affected file is under
src/openai/helpers/, whichCONTRIBUTING.mdidentifies as hand-maintained code. I searched open and closed issues and pull requests forplay_streamproducer failures and did not find an existing fix. Existing audio-helper PRs concernget_running_loop()or array shape handling rather than this failure path.