-
Notifications
You must be signed in to change notification settings - Fork 2.8k
fix: improve run_sync's python 3.14 compatibility #2006
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+196
−5
Merged
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
e0e57a2
fix: improve run_sync's python 3.14 compatibility
seratch baed3fe
fix
seratch 3537b62
fix review comment
seratch cff7495
fix review comment and add more comments
seratch 6406a2f
fix lint error
seratch 30c2edc
make format
seratch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| import asyncio | ||
| from collections.abc import Generator | ||
| from typing import Any | ||
|
|
||
| import pytest | ||
|
|
||
| from agents.agent import Agent | ||
| from agents.run import AgentRunner | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def fresh_event_loop_policy() -> Generator[asyncio.AbstractEventLoopPolicy, None, None]: | ||
| policy_before = asyncio.get_event_loop_policy() | ||
| new_policy = asyncio.DefaultEventLoopPolicy() | ||
| asyncio.set_event_loop_policy(new_policy) | ||
| try: | ||
| yield new_policy | ||
| finally: | ||
| asyncio.set_event_loop_policy(policy_before) | ||
|
|
||
|
|
||
| def test_run_sync_reuses_existing_default_loop(monkeypatch, fresh_event_loop_policy): | ||
| runner = AgentRunner() | ||
| observed_loops: list[asyncio.AbstractEventLoop] = [] | ||
|
|
||
| async def fake_run(self, *_args, **_kwargs): | ||
| observed_loops.append(asyncio.get_running_loop()) | ||
| return object() | ||
|
|
||
| monkeypatch.setattr(AgentRunner, "run", fake_run, raising=False) | ||
|
|
||
| test_loop = asyncio.new_event_loop() | ||
| fresh_event_loop_policy.set_event_loop(test_loop) | ||
|
|
||
| try: | ||
| runner.run_sync(Agent(name="test-agent"), "input") | ||
| assert observed_loops and observed_loops[0] is test_loop | ||
| finally: | ||
| fresh_event_loop_policy.set_event_loop(None) | ||
| test_loop.close() | ||
|
|
||
|
|
||
| def test_run_sync_creates_default_loop_when_missing(monkeypatch, fresh_event_loop_policy): | ||
| runner = AgentRunner() | ||
| observed_loops: list[asyncio.AbstractEventLoop] = [] | ||
|
|
||
| async def fake_run(self, *_args, **_kwargs): | ||
| observed_loops.append(asyncio.get_running_loop()) | ||
| return object() | ||
|
|
||
| monkeypatch.setattr(AgentRunner, "run", fake_run, raising=False) | ||
|
|
||
| fresh_event_loop_policy.set_event_loop(None) | ||
|
|
||
| runner.run_sync(Agent(name="test-agent"), "input") | ||
| created_loop = observed_loops[0] | ||
| assert created_loop is fresh_event_loop_policy.get_event_loop() | ||
|
|
||
| fresh_event_loop_policy.set_event_loop(None) | ||
| created_loop.close() | ||
|
|
||
|
|
||
| def test_run_sync_errors_when_loop_already_running(monkeypatch, fresh_event_loop_policy): | ||
| runner = AgentRunner() | ||
|
|
||
| async def fake_run(self, *_args, **_kwargs): | ||
| return object() | ||
|
|
||
| monkeypatch.setattr(AgentRunner, "run", fake_run, raising=False) | ||
|
|
||
| async def invoke(): | ||
| with pytest.raises(RuntimeError): | ||
| runner.run_sync(Agent(name="test-agent"), "input") | ||
|
|
||
| asyncio.run(invoke()) | ||
|
|
||
|
|
||
| def test_run_sync_cancels_task_when_interrupted(monkeypatch, fresh_event_loop_policy): | ||
| runner = AgentRunner() | ||
|
|
||
| async def fake_run(self, *_args, **_kwargs): | ||
| await asyncio.sleep(3600) | ||
|
|
||
| monkeypatch.setattr(AgentRunner, "run", fake_run, raising=False) | ||
|
|
||
| test_loop = asyncio.new_event_loop() | ||
| fresh_event_loop_policy.set_event_loop(test_loop) | ||
|
|
||
| created_tasks: list[asyncio.Task[Any]] = [] | ||
| original_create_task = test_loop.create_task | ||
|
|
||
| def capturing_create_task(coro): | ||
| task = original_create_task(coro) | ||
| created_tasks.append(task) | ||
| return task | ||
|
|
||
| original_run_until_complete = test_loop.run_until_complete | ||
| call_count = {"value": 0} | ||
|
|
||
| def interrupt_once(future): | ||
| call_count["value"] += 1 | ||
| if call_count["value"] == 1: | ||
| raise KeyboardInterrupt() | ||
| return original_run_until_complete(future) | ||
|
|
||
| monkeypatch.setattr(test_loop, "create_task", capturing_create_task) | ||
| monkeypatch.setattr(test_loop, "run_until_complete", interrupt_once) | ||
|
|
||
| try: | ||
| with pytest.raises(KeyboardInterrupt): | ||
| runner.run_sync(Agent(name="test-agent"), "input") | ||
|
|
||
| assert created_tasks, "Expected run_sync to schedule a task." | ||
| assert created_tasks[0].done() | ||
| assert created_tasks[0].cancelled() | ||
| assert call_count["value"] >= 2 | ||
| finally: | ||
| monkeypatch.undo() | ||
| fresh_event_loop_policy.set_event_loop(None) | ||
| test_loop.close() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The new
run_syncimplementation stops usingasyncio.run/Runner, but it never performs the cleanup thatRunner.close()used to do. After thedefault_loop.run_until_complete(task)call the code simply returns, so_asyncgensis never drained withloop.shutdown_asyncgens(). Any async generators created insideAgentRunner.run(or user hooks/tools) that aren’t fully consumed now keep theirfinallyblocks from running unless another loop run happens later. You can reproduce the regression by invokingrun_syncon a coroutine that doesg = agen(); await g.asend(None)whereagenhas afinally: cleanup. Before this changecleanupwould run as soon asrun_syncreturned; now it never runs because the loop is left open and the registered async generators are never closed. This leaks resources and makes async generators accumulate across runs. Please calldefault_loop.run_until_complete(default_loop.shutdown_asyncgens())(and then return the result) so the loop still stays open but async generators are finalized after every synchronous run.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@codex improved this; can you review the changes again?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Codex Review: Didn't find any major issues. What shall we delve into next?
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".