Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions native/codex/tests/test_function_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import asyncio
import inspect
import json
import threading
from dataclasses import asdict, fields, replace
from functools import wraps
from unittest.mock import AsyncMock
Expand Down Expand Up @@ -120,3 +121,53 @@ async def run():
assert not calls

asyncio.run(run())


@pytest.mark.parametrize("fail", [False, True])
def test_direct_sync_handler_preserves_cancellation_after_worker_finishes(fail):
async def run():
started = asyncio.Event()
release = threading.Event()
loop = asyncio.get_running_loop()

@function_tool
def callback() -> str:
loop.call_soon_threadsafe(started.set)
assert release.wait(10)
if fail:
raise ValueError("Late tool failure")
return "finished"

assert callback.handler is not None
task = asyncio.create_task(callback.handler({}))
try:
await asyncio.wait_for(started.wait(), 5)
task.cancel()
await asyncio.sleep(0)
task.cancel()
await asyncio.sleep(0)
assert not task.done()
release.set()
with pytest.raises(asyncio.CancelledError) as error:
await task
assert task.cancelled()
assert error.value.__context__ is None
assert error.value.__cause__ is None
finally:
release.set()
await asyncio.gather(task, return_exceptions=True)

asyncio.run(asyncio.wait_for(run(), 15))


def test_direct_sync_handler_keeps_uncancelled_failure():
@function_tool
def callback() -> str:
raise ValueError("Tool failure")

async def run():
assert callback.handler is not None
with pytest.raises(ValueError, match="Tool failure"):
await callback.handler({})

asyncio.run(run())
7 changes: 6 additions & 1 deletion src/openai_agents/codex/_threads.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
_T = TypeVar("_T")


async def run_sync(operation: Callable[[], _T]) -> _T:
async def run_sync(operation: Callable[[], _T], *, preserve_cancellation: bool = False) -> _T:
# Cancellation cannot stop an executor thread. Keep ownership of the
# turn or storage lock until its side effects have finished.
future = asyncio.get_running_loop().run_in_executor(None, copy_context().run, operation)
Expand All @@ -17,6 +17,11 @@ async def run_sync(operation: Callable[[], _T]) -> _T:
await asyncio.shield(future)
except asyncio.CancelledError:
cancelled = True
except Exception:
if not (cancelled and preserve_cancellation):
raise
if cancelled and preserve_cancellation and future.exception() is not None:
raise asyncio.CancelledError
result = future.result()
if cancelled:
if inspect.iscoroutine(result):
Expand Down
2 changes: 1 addition & 1 deletion src/openai_agents/codex/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def invoke() -> Any:
if inspect.iscoroutinefunction(fn):
result = invoke()
else:
result = await run_sync(invoke)
result = await run_sync(invoke, preserve_cancellation=True)
if inspect.isawaitable(result):
result = await result
if isinstance(result, str):
Expand Down
Loading