This is an automated email from the ASF dual-hosted git repository.
kaxil pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new cc9ecd1a96c Fix a second `run_durably_sync` call in a task failing
with "Event loop is closed" (#77384)
cc9ecd1a96c is described below
commit cc9ecd1a96cf515f4f8f5712507e0f43055fd402
Author: Kaxil Naik <[email protected]>
AuthorDate: Wed Nov 25 15:30:11 2026 +0000
Fix a second `run_durably_sync` call in a task failing with "Event loop is
closed" (#77384)
`run_durably_sync` drove each run with asyncio.run, which closes its event
loop
when it returns. The OpenAI Agents SDK sends every request on one
process-wide
HTTP client, and an AsyncOpenAI passed to several runs pools its
connections the
same way, so the second run in a task reused connections of a closed loop.
run_durably_sync now runs on the thread's event loop and leaves it open, as
Runner.run_sync does, and cancels the tasks a run leaves unfinished.
---
.../providers/common/ai/durable/openai_agents.py | 12 +-
.../providers/common/ai/utils/coroutines.py | 67 ++++++++++
.../common/ai/tests/unit/common/ai/conftest.py | 40 ++++++
.../unit/common/ai/durable/test_openai_agents.py | 32 +++++
.../tests/unit/common/ai/utils/test_coroutines.py | 143 ++++++++++++++++++++-
5 files changed, 290 insertions(+), 4 deletions(-)
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/durable/openai_agents.py
b/providers/common/ai/src/airflow/providers/common/ai/durable/openai_agents.py
index 35f0ae6e873..6f6031c4a54 100644
---
a/providers/common/ai/src/airflow/providers/common/ai/durable/openai_agents.py
+++
b/providers/common/ai/src/airflow/providers/common/ai/durable/openai_agents.py
@@ -67,7 +67,7 @@ from airflow.providers.common.ai.durable.journal import
_EXECUTING_STEP, current
from airflow.providers.common.ai.exceptions import DurableJournalError,
UnsupportedToolDeferralError
from airflow.providers.common.ai.mixins.approval import LLMApprovalMixin
from airflow.providers.common.ai.tools.openai_agents import _REPLAY_RETRY,
_RETRY_COUNT, _RetryLimitReached
-from airflow.providers.common.ai.utils.coroutines import run_coroutine_sync
+from airflow.providers.common.ai.utils.coroutines import
run_coroutine_on_thread_loop
from airflow.providers.common.ai.utils.masking import dumps_masked,
mask_secrets
from airflow.providers.common.ai.utils.task_logger import get_task_logger
from airflow.providers.common.compat.sdk import Param, get_current_context
@@ -242,8 +242,14 @@ def run_durably_sync(
run_config: RunConfig | None = None,
**kwargs: Any,
) -> RunResult:
- """Run :func:`run_durably` from synchronous code, such as a plain
``@task``."""
- return run_coroutine_sync(run_durably(starting_agent, input,
run_config=run_config, **kwargs))
+ """
+ Run :func:`run_durably` from synchronous code, such as a plain ``@task``.
+
+ Like ``Runner.run_sync``, it runs on the thread's event loop and leaves it
open, so several
+ calls in one task can share a client: the SDK's own shared HTTP client, or
one ``AsyncOpenAI``.
+ That holds for calls from synchronous code; in async code, ``await
run_durably(...)``.
+ """
+ return run_coroutine_on_thread_loop(run_durably(starting_agent, input,
run_config=run_config, **kwargs))
def _answer_approvals(
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/utils/coroutines.py
b/providers/common/ai/src/airflow/providers/common/ai/utils/coroutines.py
index 66b1cc27b55..4fb9c0fe0bd 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/utils/coroutines.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/utils/coroutines.py
@@ -21,6 +21,9 @@ from __future__ import annotations
import asyncio
import concurrent.futures
import contextvars
+import os
+import threading
+import warnings
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
@@ -45,3 +48,67 @@ def run_coroutine_sync(coroutine: Coroutine[Any, Any, Any])
-> Any:
return pool.submit(contextvars.copy_context().run, asyncio.run,
coroutine).result()
# Outside the except block, so what the coroutine raises is not chained to
the RuntimeError.
return asyncio.run(coroutine)
+
+
+def run_coroutine_on_thread_loop(coroutine: Coroutine[Any, Any, Any]) -> Any:
+ """
+ Run ``coroutine`` to completion on this thread's event loop, and leave the
loop open.
+
+ This is the loop ``asyncio.get_event_loop()`` returns, the one
``Runner.run_sync`` in the
+ OpenAI Agents SDK uses and keeps open between calls. An async client is
tied to the loop
+ it first runs in, so the SDK's shared HTTP client, or one ``AsyncOpenAI``
given to several
+ runs, keeps working across calls only on that loop. An ``asyncio.run()``
between two
+ calls clears the thread's current loop; the next call puts the kept one
back. Tasks the
+ call started and left unfinished are cancelled before it returns. When a
loop is already
+ running in this thread, the coroutine runs as :func:`run_coroutine_sync`
runs it, on a
+ new loop each time.
+ """
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ pass
+ else:
+ return run_coroutine_sync(coroutine)
+ loop = _get_thread_event_loop()
+ earlier_tasks = asyncio.all_tasks(loop)
+ task = loop.create_task(coroutine)
+ try:
+ return loop.run_until_complete(task)
+ finally:
+ # An exception raised from a signal handler (execution_timeout,
SIGTERM) stops the loop
+ # with the task still pending, and a failed gather() leaves its other
children running.
+ # Cancel them now, so their cleanup runs and they don't resume during
a later call.
+ leftovers = asyncio.all_tasks(loop) - earlier_tasks
+ for leftover in leftovers:
+ leftover.cancel()
+ if leftovers:
+ loop.run_until_complete(asyncio.gather(*leftovers,
return_exceptions=True))
+
+
+class _KeptLoop(threading.local):
+ pid: int | None = None
+ loop: asyncio.AbstractEventLoop | None = None
+
+
+_kept = _KeptLoop()
+
+
+def _get_thread_event_loop() -> asyncio.AbstractEventLoop:
+ with warnings.catch_warnings():
+ # Python 3.12 and 3.13 warn when the thread has no current loop yet;
3.14 raises instead.
+ warnings.simplefilter("ignore", DeprecationWarning)
+ try:
+ loop = asyncio.get_event_loop()
+ except RuntimeError:
+ loop = None
+ # Python 3.11 leaves the parent's loop current in a forked child (3.12+
clears it), and
+ # its selector is shared with the parent, so a child never uses the loop
its parent kept.
+ if loop is None or loop.is_closed() or (loop is _kept.loop and _kept.pid
!= os.getpid()):
+ # asyncio.run(), run_coroutine_sync() included, clears the current
loop when it
+ # finishes. Put back the loop the last call kept, unless it belongs to
the process
+ # this one was forked from.
+ kept = _kept.loop if _kept.pid == os.getpid() else None
+ loop = kept if kept is not None and not kept.is_closed() else
asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ _kept.pid, _kept.loop = os.getpid(), loop
+ return loop
diff --git a/providers/common/ai/tests/unit/common/ai/conftest.py
b/providers/common/ai/tests/unit/common/ai/conftest.py
index 85146376f18..55d6cf0870d 100644
--- a/providers/common/ai/tests/unit/common/ai/conftest.py
+++ b/providers/common/ai/tests/unit/common/ai/conftest.py
@@ -16,6 +16,9 @@
# under the License.
from __future__ import annotations
+import asyncio
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any
from unittest.mock import MagicMock
from uuid import uuid4
@@ -24,6 +27,7 @@ import pytest
from pydantic_ai.messages import ModelResponse
from pydantic_ai.usage import RunUsage
+from airflow.providers.common.ai.utils.coroutines import
run_coroutine_on_thread_loop
from airflow.providers.common.ai.utils.logging import MODEL_NAME_XCOM_KEY
from airflow.providers.common.ai.utils.usage_budget import
TaskStateStoreUsageBudget
@@ -258,3 +262,39 @@ def park():
return exc.value
return _park
+
+
[email protected]
+def close_thread_event_loop():
+ """Close the event loop run_coroutine_on_thread_loop keeps open on this
thread, after the test."""
+ yield
+
+ async def get_running_loop():
+ return asyncio.get_running_loop()
+
+ run_coroutine_on_thread_loop(get_running_loop()).close()
+ asyncio.set_event_loop(None)
+
+
+class _KeepAliveHandler(BaseHTTPRequestHandler):
+ # HTTP/1.1 keeps the connection open, so a client pools it for its next
request.
+ protocol_version = "HTTP/1.1"
+
+ def do_GET(self):
+ self.send_response(200)
+ self.send_header("Content-Length", "2")
+ self.end_headers()
+ self.wfile.write(b"ok")
+
+ def log_message(self, format, *args):
+ pass
+
+
[email protected]
+def keep_alive_url():
+ """URL of a local server that answers ``ok`` and keeps the connection
open."""
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _KeepAliveHandler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ yield f"http://127.0.0.1:{server.server_port}/"
+ server.shutdown()
+ server.server_close()
diff --git
a/providers/common/ai/tests/unit/common/ai/durable/test_openai_agents.py
b/providers/common/ai/tests/unit/common/ai/durable/test_openai_agents.py
index be738e68f58..fad80002c51 100644
--- a/providers/common/ai/tests/unit/common/ai/durable/test_openai_agents.py
+++ b/providers/common/ai/tests/unit/common/ai/durable/test_openai_agents.py
@@ -27,6 +27,7 @@ from collections.abc import Container
from typing import Any
from unittest import mock
+import httpx2
import pytest
import structlog
@@ -70,6 +71,7 @@ from airflow.providers.common.ai.exceptions import
DurableJournalError, Unsuppor
from airflow.providers.common.ai.tools import AirflowTool, ToolCallError,
ToolResult
from airflow.providers.common.ai.tools._from_toolset import
airflow_tools_from_toolset
from airflow.providers.common.ai.tools.openai_agents import AirflowTools
+from airflow.providers.common.ai.utils.coroutines import
run_coroutine_on_thread_loop
from airflow.providers.standard.operators.hitl import request_input
from airflow.sdk import DAG, BaseOperator, task
from airflow.sdk.execution_time.comms import AwaitInputTask,
CreateHITLDetailPayload, SetXCom
@@ -79,6 +81,9 @@ from airflow.utils.state import TaskInstanceState
from unit.common.ai.durable.memory_storage import MemoryStorage
+# run_durably_sync keeps the thread's event loop open; close it after each
test.
+pytestmark = pytest.mark.usefixtures("close_thread_event_loop")
+
# Tracing off, so no test exports spans to OpenAI.
NO_TRACING = RunConfig(tracing_disabled=True)
@@ -869,6 +874,33 @@ class TestRunDurably:
_attempt(storage, _TurnsModel([["a", "b"], ["d"]]), tool)
assert tool.calls == 2
+ def test_two_runs_in_a_task_can_share_one_pooled_client(self,
keep_alive_url):
+ # The SDK sends every request on one shared HTTP client, so the second
run reuses the
+ # connection the first run pooled, which belongs to the first run's
event loop. Each run
+ # builds its tools as a task builds its agent, which runs
asyncio.run() in between.
+ client = httpx2.AsyncClient()
+
+ class _PooledClientModel(_ScriptedModel):
+ async def get_response(self, *args: Any, **kwargs: Any) ->
ModelResponse:
+ await client.get(keep_alive_url)
+ return await super().get_response(*args, **kwargs)
+
+ lookup = _ToolsetLookup(max_retries=1, retry=())
+ try:
+ with journal_scope(DurableJournal(MemoryStorage(),
clean_up_after_run=True)):
+ answers = [
+ run_durably_sync(
+ Agent(name="a", model=_PooledClientModel(),
tools=AirflowTools(lookup.tool())),
+ prompt,
+ run_config=NO_TRACING,
+ ).final_output
+ for prompt in ("1", "2")
+ ]
+ finally:
+ run_coroutine_on_thread_loop(client.aclose())
+
+ assert answers == ["answer: k0=42", "answer: k0=42"]
+
def test_each_agent_run_in_a_task_restores_its_own_count(self):
"""A second run_durably call in the task replays its count after a
first one ran live."""
storage, tool = MemoryStorage(), _ToolsetLookup(max_retries=1,
retry={"k1", "k2"})
diff --git a/providers/common/ai/tests/unit/common/ai/utils/test_coroutines.py
b/providers/common/ai/tests/unit/common/ai/utils/test_coroutines.py
index 4531ff5b068..52882e4d9b7 100644
--- a/providers/common/ai/tests/unit/common/ai/utils/test_coroutines.py
+++ b/providers/common/ai/tests/unit/common/ai/utils/test_coroutines.py
@@ -17,12 +17,14 @@
from __future__ import annotations
import asyncio
+import os
import threading
from contextvars import ContextVar
+import httpx2
import pytest
-from airflow.providers.common.ai.utils.coroutines import run_coroutine_sync
+from airflow.providers.common.ai.utils.coroutines import
run_coroutine_on_thread_loop, run_coroutine_sync
_value: ContextVar[str] = ContextVar("value", default="unset")
@@ -35,6 +37,14 @@ async def _read_value() -> str:
return _value.get()
+async def _get_running_loop() -> asyncio.AbstractEventLoop:
+ return asyncio.get_running_loop()
+
+
+def _raise_keyboard_interrupt() -> None:
+ raise KeyboardInterrupt
+
+
class TestRunCoroutineSync:
def test_runs_on_the_calling_thread_when_no_loop_is_running(self):
assert run_coroutine_sync(_thread_name()) ==
threading.current_thread().name
@@ -60,3 +70,134 @@ class TestRunCoroutineSync:
run_coroutine_sync(fails())
assert raised.value.__context__ is None
+
+
[email protected]("close_thread_event_loop")
+class TestRunCoroutineOnThreadLoop:
+ def test_an_async_client_works_across_calls(self, keep_alive_url):
+ # Like the OpenAI Agents SDK's shared HTTP client: the connection it
pools on the first
+ # call belongs to that call's loop, so the second call needs the same
loop, still open.
+ client = httpx2.AsyncClient()
+ try:
+ first = run_coroutine_on_thread_loop(client.get(keep_alive_url))
+ second = run_coroutine_on_thread_loop(client.get(keep_alive_url))
+ finally:
+ run_coroutine_on_thread_loop(client.aclose())
+
+ assert (first.text, second.text) == ("ok", "ok")
+
+ def test_an_asyncio_run_between_calls_keeps_the_loop(self):
+ first = run_coroutine_on_thread_loop(_get_running_loop())
+ asyncio.run(asyncio.sleep(0))
+
+ assert run_coroutine_on_thread_loop(_get_running_loop()) is first
+
+ @pytest.mark.skipif(not hasattr(os, "fork"), reason="needs os.fork")
+ def test_a_forked_child_does_not_reuse_the_parents_loop(self):
+ # Python 3.11 keeps the parent's loop as the child's current loop;
3.12+ clears it.
+ parent_loop = run_coroutine_on_thread_loop(_get_running_loop())
+ read_end, write_end = os.pipe()
+ pid = os.fork()
+ if pid == 0:
+ try:
+ child_loop = run_coroutine_on_thread_loop(_get_running_loop())
+ os.write(write_end, b"same" if child_loop is parent_loop else
b"new")
+ finally:
+ os._exit(0)
+ os.close(write_end)
+ os.waitpid(pid, 0)
+ with os.fdopen(read_end, "rb") as reader:
+ assert reader.read() == b"new"
+
+ def test_replaces_a_closed_current_loop(self):
+ closed = asyncio.new_event_loop()
+ closed.close()
+ asyncio.set_event_loop(closed)
+
+ loop = run_coroutine_on_thread_loop(_get_running_loop())
+
+ assert loop is not closed
+ assert not loop.is_closed()
+
+ def test_an_interrupted_call_cleans_up_before_it_returns(self):
+ # execution_timeout and SIGTERM raise from a signal handler while the
loop waits, which
+ # leaves the call's task pending. A loop callback raising
KeyboardInterrupt does the same.
+ events: list[str] = []
+
+ async def wait_then_record() -> None:
+ asyncio.get_running_loop().call_soon(_raise_keyboard_interrupt)
+ try:
+ await asyncio.sleep(0.05)
+ events.append("resumed")
+ finally:
+ events.append("cleaned up")
+
+ with pytest.raises(KeyboardInterrupt):
+ run_coroutine_on_thread_loop(wait_then_record())
+
+ assert events == ["cleaned up"]
+ run_coroutine_on_thread_loop(asyncio.sleep(0.1))
+ assert events == ["cleaned up"]
+
+ def test_a_failed_gather_leaves_no_child_running(self):
+ events: list[str] = []
+
+ async def fail() -> None:
+ raise ValueError("boom")
+
+ async def record_later() -> None:
+ try:
+ await asyncio.sleep(0.05)
+ events.append("ran")
+ except asyncio.CancelledError:
+ events.append("cancelled")
+ raise
+
+ async def gather_both() -> None:
+ await asyncio.gather(fail(), record_later())
+
+ with pytest.raises(ValueError, match="boom"):
+ run_coroutine_on_thread_loop(gather_both())
+
+ assert events == ["cancelled"]
+ run_coroutine_on_thread_loop(asyncio.sleep(0.1))
+ assert events == ["cancelled"]
+
+ def test_leaves_tasks_started_before_the_call_alone(self):
+ loop = run_coroutine_on_thread_loop(_get_running_loop())
+ earlier = loop.create_task(asyncio.sleep(0.1))
+ try:
+ run_coroutine_on_thread_loop(asyncio.sleep(0))
+
+ assert not earlier.cancelled()
+ finally:
+ earlier.cancel()
+
+ def test_concurrent_calls_from_two_threads_run_on_separate_loops(self):
+ barrier = threading.Barrier(2)
+ main_loop = run_coroutine_on_thread_loop(_get_running_loop())
+ loops: list[asyncio.AbstractEventLoop] = []
+
+ async def get_loop_after_overlap() -> asyncio.AbstractEventLoop:
+ await asyncio.sleep(0.05) # overlaps the other thread's call
+ return asyncio.get_running_loop()
+
+ def call() -> None:
+ barrier.wait()
+
loops.append(run_coroutine_on_thread_loop(get_loop_after_overlap()))
+
+ threads = [threading.Thread(target=call) for _ in range(2)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+
+ assert len({main_loop, *loops}) == 3
+ for loop in loops:
+ loop.close()
+
+ def test_runs_on_another_thread_when_called_from_a_running_loop(self):
+ async def caller() -> str:
+ return run_coroutine_on_thread_loop(_thread_name())
+
+ assert asyncio.run(caller()) != threading.current_thread().name