Skip to content

Commit d5abd9f

Browse files
authored
fix(extensions): close owned event streams when runs fail (#5060)
1 parent 987b083 commit d5abd9f

2 files changed

Lines changed: 70 additions & 13 deletions

File tree

‎src/agents/extensions/experimental/codex/thread.py‎

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -168,19 +168,20 @@ async def run(self, input: Input, turn_options: TurnOptions | None = None) -> Tu
168168
usage: Usage | None = None
169169
turn_failure: ThreadError | None = None
170170

171-
async for event in generator:
172-
if isinstance(event, ItemCompletedEvent):
173-
item = event.item
174-
if is_agent_message_item(item):
175-
final_response = item.text
176-
items.append(item)
177-
elif isinstance(event, TurnCompletedEvent):
178-
usage = event.usage
179-
elif isinstance(event, TurnFailedEvent):
180-
turn_failure = event.error
181-
break
182-
elif isinstance(event, ThreadErrorEvent):
183-
raise RuntimeError(f"Codex stream error: {event.message}")
171+
async with contextlib.aclosing(generator):
172+
async for event in generator:
173+
if isinstance(event, ItemCompletedEvent):
174+
item = event.item
175+
if is_agent_message_item(item):
176+
final_response = item.text
177+
items.append(item)
178+
elif isinstance(event, TurnCompletedEvent):
179+
usage = event.usage
180+
elif isinstance(event, TurnFailedEvent):
181+
turn_failure = event.error
182+
break
183+
elif isinstance(event, ThreadErrorEvent):
184+
raise RuntimeError(f"Codex stream error: {event.message}")
184185

185186
if turn_failure is not None:
186187
raise RuntimeError(turn_failure.message)

‎tests/extensions/experiemental/codex/test_codex_exec_thread.py‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -833,6 +833,62 @@ async def test_thread_run_raises_on_stream_error() -> None:
833833
await thread.run("hello")
834834

835835

836+
@pytest.mark.asyncio
837+
@pytest.mark.parametrize(
838+
"event, error_message",
839+
[
840+
({"type": "turn.failed", "error": {"message": "boom"}}, "boom"),
841+
({"type": "error", "message": "boom"}, "Codex stream error: boom"),
842+
(
843+
{
844+
"type": "turn.completed",
845+
"usage": {"input_tokens": 2, "cached_input_tokens": 1, "output_tokens": 3},
846+
},
847+
None,
848+
),
849+
],
850+
ids=["turn-failed", "stream-error", "success"],
851+
)
852+
async def test_thread_run_cleans_up_owned_resources(
853+
monkeypatch: pytest.MonkeyPatch, event: dict[str, Any], error_message: str | None
854+
) -> None:
855+
# Keep the subprocess live after its event to exercise ownership at Thread.run().
856+
process = FakeProcess(stdout_lines=[json.dumps(event) + "\n"], returncode=None)
857+
schema_path: Path | None = None
858+
859+
async def fake_create_subprocess_exec(*args: Any, **kwargs: Any) -> FakeProcess:
860+
nonlocal schema_path
861+
schema_path = Path(args[args.index("--output-schema") + 1])
862+
assert schema_path.is_file()
863+
return process
864+
865+
monkeypatch.setattr(exec_module.asyncio, "create_subprocess_exec", fake_create_subprocess_exec)
866+
thread = Thread(
867+
exec_client=CodexExec(executable_path="/bin/codex"),
868+
options=CodexOptions(),
869+
thread_options=ThreadOptions(),
870+
)
871+
options = TurnOptions(output_schema={"type": "object"})
872+
generator = thread._run_streamed_internal("hello", options)
873+
# Retain the owned iterator so garbage collection cannot stand in for explicit cleanup.
874+
monkeypatch.setattr(thread, "_run_streamed_internal", lambda *args: generator)
875+
876+
try:
877+
if error_message is not None:
878+
with pytest.raises(RuntimeError, match=error_message):
879+
await thread.run("hello", options)
880+
else:
881+
result = await thread.run("hello", options)
882+
assert result.usage == Usage(input_tokens=2, cached_input_tokens=1, output_tokens=3)
883+
884+
assert process.killed is (error_message is not None)
885+
assert process.returncode == 0
886+
assert schema_path is not None
887+
assert not schema_path.exists()
888+
finally:
889+
await generator.aclose()
890+
891+
836892
@pytest.mark.asyncio
837893
async def test_thread_run_streamed_raises_on_parse_error(
838894
monkeypatch: pytest.MonkeyPatch,

0 commit comments

Comments
 (0)