Skip to content

fix(helpers): propagate audio stream producer errors - #3817

Open
Hughhhhcoder wants to merge 1 commit into
openai:mainfrom
Hughhhhcoder:codex/openai-python-audio-producer-failure
Open

Hughhhhcoder wants to merge 1 commit into
openai:mainfrom
Hughhhhcoder:codex/openai-python-audio-producer-failure

Conversation

@Hughhhhcoder

@Hughhhhcoder Hughhhhcoder commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor
  • I understand that this repository is auto-generated and my pull request may not be merged

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.OutputStream with 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.
  • The same focused command with uv run --isolated --python 3.14 — 5 passed.
  • ./scripts/lint with 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.
  • Reproduction against unmodified main: the same input timed out after 200 ms and emitted Task exception was never retrieved for the original RuntimeError.

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/, which CONTRIBUTING.md identifies as hand-maintained code. I searched open and closed issues and pull requests for play_stream producer failures and did not find an existing fix. Existing audio-helper PRs concern get_running_loop() or array shape handling rather than this failure path.

@Hughhhhcoder
Hughhhhcoder requested a review from a team as a code owner September 8, 2026 04:38
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-08T04:42:31.545616Z 54eb21e PR opened
🔒 Security Review ✅ Completed 2026-09-08T04:43:05.105278Z 54eb21e PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@jnohclee-rgb

Copy link
Copy Markdown

AI-assisted independent offline check at 54eb21ec7eebd0bb71cc188d5b9a143f078d381a, compared with pinned main 919b6236382f3f9f76d8453efb9f9ad03cff1126.

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())

@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Castiron custom code

Evaluated main: 4e152cdefe1844c2d5d78653310e9b9c0195c44e.

✅ No new custom-code files detected.

36 mixed files remain; 0 existing customizations changed.

Compared be928151372e → 54eb21ec7eeb. Generated baselines verified.

36 existing customizations unchanged
  • api.md
  • scripts/castiron/README.md
  • scripts/castiron/custom_code_report.py
  • scripts/castiron/test_custom_code_report.py
  • src/openai/init.py
  • src/openai/_client.py
  • src/openai/resources/audio/transcriptions.py
  • src/openai/resources/audio/translations.py
  • src/openai/resources/beta/beta.py
  • src/openai/resources/beta/responses/responses.py
  • src/openai/resources/beta/threads/runs/runs.py
  • src/openai/resources/beta/threads/threads.py
  • src/openai/resources/chat/completions/completions.py
  • src/openai/resources/embeddings.py
  • src/openai/resources/files.py
  • src/openai/resources/realtime/realtime.py
  • src/openai/resources/responses/responses.py
  • src/openai/resources/uploads/uploads.py
  • src/openai/resources/vector_stores/file_batches.py
  • src/openai/resources/vector_stores/files.py
  • src/openai/resources/videos.py
  • src/openai/resources/webhooks/init.py
  • src/openai/resources/webhooks/webhooks.py
  • src/openai/types/chat/init.py
  • src/openai/types/chat/chat_completion_message_tool_call.py
  • src/openai/types/fine_tuning/fine_tuning_job_integration.py
  • src/openai/types/responses/init.py
  • src/openai/types/responses/response.py
  • src/openai/types/responses/response_function_web_search.py
  • src/openai/types/responses/response_function_web_search_param.py
  • src/openai/types/responses/responses_client_event.py
  • src/openai/types/responses/responses_client_event_param.py
  • src/openai/types/responses/tool.py
  • src/openai/types/responses/tool_param.py
  • src/openai/types/webhooks/init.py
  • tests/api_resources/test_videos.py

A changed generated baseline means this report cannot reliably identify which handwritten lines changed.

Inspect the custom-code diff

Download 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.patch

Or 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.patch

This is the current full custom patch for mixed files, not an attribution of only the handwritten lines changed by this PR.

Full report and patch

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