phanikumv commented on code in PR #77384:
URL: https://github.com/apache/airflow/pull/77384#discussion_r4642384108
##########
providers/common/ai/src/airflow/providers/common/ai/utils/coroutines.py:
##########
@@ -45,3 +48,65 @@ 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 unsets 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
+ if loop is None or loop.is_closed():
Review Comment:
The fork guard does not work on Python 3.11, and this provider supports 3.11
(requires-python = ">=3.11")
Python 3.12 and later reset the current loop in a forked child
(`os.register_at_fork` in `asyncio/events.py`). Python 3.11 does not. So on
3.11, asyncio.get_event_loop() gives the child the parent's open loop, and the
code uses it.
Proposed fix: also make a new loop when the current loop is the kept loop
from another process
```suggestion
if loop is None or loop.is_closed() or (loop is _kept.loop and _kept.pid
!= os.getpid()):
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]