---
type: email
from: Lucas Wang <notifications@github.com>
subject: [openai/openai-agents-python] fix: prevent race condition in listener

 iteration (PR #1956)
received: 2026-03-06 08:10:55
date_header: Mon, 20 Oct 2025 22:38:01 -0700
priority: normal
status: awaiting_approval
uid: 33212
---

## Email Content

**From:** Lucas Wang <notifications@github.com>
**Subject:** [openai/openai-agents-python] fix: prevent race condition in listener

 iteration (PR #1956)
**Date:** Mon, 20 Oct 2025 22:38:01 -0700

### Body (preview)

## Summary

Fixed a race condition in `OpenAIRealtimeWebSocketModel._emit_event()` where the listeners list could be modified during async iteration, causing `RuntimeError: list changed size during iteration`.



## Problem

The `_emit_event()` method iterates over `self._listeners` while calling `await listener.on_event(event)`:



```python

for listener in self._listeners:  # Iteration

    await listener.on_event(event)  # Await point - yields control

```



During the `await`, other code (e.g., cleanup) can call `remove_listener()`, modifying the list mid-iteration.



**Crash scenario:**

1. Session emits event → `_emit_event()` starts iterating listeners

2. At `await listener.on_event()`, control returns to event loop

3. Cleanup runs → calls `remove_listener()` → modifies list

4. Control returns to iteration → RuntimeError



This is realistic because `remove_listener()` is called during session cleanup (session.py:761).



## Solution

Create a shallow copy of the listeners list before iteration:



```python

for listener in list(self._listeners):  # Copy prevents modification issues

    await listener.on_event(event)

```



This allows safe concurrent modifications without affecting the ongoing iteration.



## Testing

- All 23 existing tests in `tests/realtime/test_openai_realtime.py` pass

- No behavioral changes, only defensive coding



## Impact

- Prevents crashes during concurrent listener management

- Common in cleanup scenarios where session removes itself as listener

- Minimal performance impact (shallow copy of small list)

You can view, comment on, or merge this pull request online at:



  https://github.com/openai/openai-agents-python/pull/1956



-- Commit Summary --



  * fix: prevent race condition in listener iteration



-- File Changes --



    M src/agents/realtime/openai_realtime.py (3)



-- Patch Links --



https://github.com/openai/openai-agents-python/pull/1956.patch

https://github.com/openai/openai-agents-python/pull

---

## Suggested Actions
- [ ] Reply
- [ ] Archive
- [ ] Escalate
