Skip to content

Fix run_sync failure when called from a running event loop#3407

Open
pingsutw wants to merge 1 commit intoflyteorg:masterfrom
pingsutw:fix/async-loop-manager-running-loop
Open

Fix run_sync failure when called from a running event loop#3407
pingsutw wants to merge 1 commit intoflyteorg:masterfrom
pingsutw:fix/async-loop-manager-running-loop

Conversation

@pingsutw
Copy link
Member

Summary

  • Fix RuntimeError: Cannot run the event loop while another loop is running when FlyteRemote.execute() is called from within an already-running async event loop (e.g., Flask with Gunicorn)
  • _AsyncLoopManager.run_sync() now detects a running loop and spawns a short-lived thread with its own event loop via asyncio.run(), preserving context variables with contextvars.copy_context()
  • The original _TaskRunner path remains unchanged for non-async contexts

Test plan

  • Added test_run_sync_from_running_event_loop — verifies run_sync works when called from within a running event loop
  • Added test_run_sync_from_running_event_loop_with_exception — verifies exceptions propagate correctly in this path
  • All existing tests in tests/flytekit/unit/utils/test_asyn.py pass (8/8)

When `run_sync` is called from within an already-running async event loop
(e.g., Flask/Gunicorn), the `_TaskRunner` approach fails with
"Cannot run the event loop while another loop is running". This detects
the running loop and instead spawns a short-lived thread with its own
event loop via `asyncio.run()`, preserving context variables.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Kevin Su <pingsutw@apache.org>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant