Skip to content

Commit 85898e2

Browse files
fix: retain timeout callback outcomes with their owner
1 parent 2ac06a3 commit 85898e2

4 files changed

Lines changed: 98 additions & 11 deletions

File tree

‎packages/codex/src/_agents_codex/session.py‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8489,11 +8489,20 @@ def expire_body(cancel_body: bool = True) -> None:
84898489

84908490
timer = loop.call_at(cutoff, expire_body)
84918491

8492-
async def invoke_body() -> Any:
8492+
value = None
8493+
body_error: BaseException | None = None
8494+
8495+
async def invoke_body() -> None:
8496+
nonlocal value, body_error
84938497
try:
84948498
if admit_body():
8495-
return await _call_callback(entry.callback, admit_body, *args, **kwargs)
8496-
return None
8499+
value = await _call_callback(
8500+
entry.callback, admit_body, *args, **kwargs
8501+
)
8502+
except BaseException as error:
8503+
# Transport every exit to the owner without letting
8504+
# process-control exceptions escape this child task.
8505+
body_error = error
84978506
finally:
84988507
timer.cancel()
84998508
# Settle at body exit, before unrelated ready work can
@@ -8511,16 +8520,30 @@ async def invoke_body() -> Any:
85118520
cancel_once(body)
85128521

85138522
async def join_body() -> None:
8514-
await _join(body)
8523+
try:
8524+
await _join(body)
8525+
finally:
8526+
if body_error is not None and not isinstance(
8527+
body_error, asyncio.CancelledError
8528+
):
8529+
state.retain_cleanup_error(body_error)
85158530

85168531
await _close_after_error(error, join_body)
85178532
raise
85188533
finally:
85198534
timer.cancel()
8520-
body_error = None if body.cancelled() else body.exception()
85218535
if not self._admit_tool(state, request):
8536+
if body_error is not None and not isinstance(
8537+
body_error, asyncio.CancelledError
8538+
):
8539+
state.retain_cleanup_error(body_error)
85228540
return
8541+
if isinstance(body_error, (SystemExit, KeyboardInterrupt)):
8542+
raise body_error
85238543
if expired:
8544+
# Discard late output before a formatter can fail. The child
8545+
# task itself never owns a return value.
8546+
value = None
85248547
if body_error is not None:
85258548
timeout_error.__cause__ = body_error
85268549
# No late value is validated or serialized. Format only
@@ -8540,8 +8563,8 @@ async def join_body() -> None:
85408563
timeout_output = ToolOutput.error(text)
85418564
timeout_output._validate()
85428565
value = None
8543-
else:
8544-
value = body.result()
8566+
elif body_error is not None:
8567+
raise body_error
85458568
else:
85468569
loop = asyncio.get_running_loop()
85478570
cutoff = loop.time() + duration

‎packages/codex/tests/test_native_agent_lifecycle.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1442,17 +1442,18 @@ async def lookup(key: str) -> str:
14421442
assert len(responses.requests) == 3
14431443

14441444

1445+
@pytest.mark.parametrize("policy", ["raise_exception", "error_as_result"])
14451446
@pytest.mark.parametrize("operation", ["cancel", "aclose", "body"])
14461447
@pytest.mark.usefixtures("core_owner")
14471448
async def test_callback_cleanup_errors_survive_stopping(
1448-
responses: ResponsesFixture, operation: str
1449+
responses: ResponsesFixture, operation: str, policy: str
14491450
) -> None:
14501451
entered = asyncio.Event()
14511452
cleaned = asyncio.Event()
14521453
cleanup_error = OSError("tool cleanup failed")
14531454
body_error = ValueError("application body failed")
14541455

1455-
@function_tool
1456+
@function_tool(callback_timeout=30, timeout_behavior=policy)
14561457
async def pending() -> str:
14571458
entered.set()
14581459
try:

‎packages/codex/tests/test_native_function_results.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ async def debit(
225225
assert len(responses.requests) == 1
226226

227227

228-
@pytest.mark.parametrize("mode", ["async", "sync-with-deadline"])
228+
@pytest.mark.parametrize("mode", ["async", "sync-with-deadline", "result-policy"])
229229
async def test_invalid_callback_result_does_not_expose_rejected_input_or_validation_chain(
230230
responses, mode
231231
):
@@ -243,7 +243,8 @@ async def debit_async(ctx: ToolContext[Account], units: int, key: str) -> dict[s
243243

244244
debit = function_tool(
245245
name="debit",
246-
callback_timeout=10 if mode == "sync-with-deadline" else None,
246+
callback_timeout=10 if mode != "async" else None,
247+
timeout_behavior="error_as_result" if mode == "result-policy" else "raise_exception",
247248
)(debit_sync if mode == "sync-with-deadline" else debit_async)
248249

249250
responses.respond(function_call("debit", {"units": 7, "key": original}, "private-debit"))

‎packages/codex/tests/test_native_tool_timeout_policy.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
"""Timeout policies retain invocation ownership and publish only admitted results."""
22

33
import asyncio
4+
import os
5+
import subprocess
6+
import sys
7+
import textwrap
48
import threading
59
import time
610
from concurrent.futures import ThreadPoolExecutor
711
from dataclasses import replace
12+
from pathlib import Path
813
from typing import Any, get_args
914

1015
import pytest
@@ -667,3 +672,60 @@ async def lookup() -> str:
667672
assert tool_output(responses.requests[1], "eager-body") == "on-time"
668673
finally:
669674
loop.set_task_factory(original_factory)
675+
676+
677+
@pytest.mark.parametrize("error_name", ["SystemExit", "KeyboardInterrupt"])
678+
@pytest.mark.parametrize("stage", ["body", "timeout-cleanup"])
679+
def test_result_policy_transports_process_control_errors_to_turn(error_name, stage):
680+
# Keep a regression in asyncio's process-control handling inside a subprocess.
681+
script = textwrap.dedent(""" import asyncio
682+
import sys
683+
sys.path.insert(0, sys.argv[2])
684+
from aiohttp import web
685+
from aiohttp.test_utils import TestServer
686+
from agents import Agent, function_tool
687+
from tests.native_fixtures import ResponsesFixture, function_call
688+
from tests.test_native_agent import provider
689+
690+
async def main():
691+
error_type = {"SystemExit": SystemExit, "KeyboardInterrupt": KeyboardInterrupt}
692+
error = error_type[sys.argv[1]]()
693+
@function_tool(callback_timeout=0.01, timeout_behavior="error_as_result")
694+
async def lookup() -> str:
695+
if sys.argv[3] == "timeout-cleanup":
696+
try:
697+
await asyncio.Future()
698+
finally:
699+
raise error
700+
raise error
701+
702+
responses = ResponsesFixture()
703+
responses.respond(function_call("lookup", {}, "process-control"))
704+
app = web.Application()
705+
app.router.add_post("/v1/responses", responses.handle)
706+
async with TestServer(app) as server:
707+
responses.url = str(server.make_url("/v1"))
708+
survivor = asyncio.create_task(asyncio.sleep(0.05, result="alive"))
709+
async with Agent(
710+
instructions="Use lookup.", tools=[lookup], provider=provider(responses)
711+
).session() as session:
712+
turn = await session.submit("read")
713+
# Observe the owning turn without the separate result-waiter
714+
# task, which has its own process-control exception boundary.
715+
await asyncio.wait((turn._completion,))
716+
assert turn._completion.exception() is error
717+
assert await survivor == "alive"
718+
assert len(responses.requests) == 1
719+
print("parent retained process-control error")
720+
721+
asyncio.run(main())
722+
""")
723+
completed = subprocess.run(
724+
[sys.executable, "-c", script, error_name, str(Path(__file__).resolve().parents[1]), stage],
725+
env={key: value for key, value in os.environ.items() if key != "OPENAI_API_KEY"},
726+
capture_output=True,
727+
text=True,
728+
timeout=20,
729+
)
730+
assert completed.returncode == 0, completed.stdout + completed.stderr
731+
assert "parent retained process-control error" in completed.stdout

0 commit comments

Comments
 (0)