Skip to content
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

eager workflow: use event loop instead of asyncio.run #2737

Merged
merged 7 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion flytekit/bin/entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import sys
import tempfile
import traceback
import warnings
from sys import exit
from typing import Callable, List, Optional

Expand Down Expand Up @@ -68,6 +69,23 @@ def _compute_array_job_index():
return offset


def _get_working_loop():
"""Returns a running event loop."""
try:
return asyncio.get_running_loop()
except RuntimeError:
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
try:
return asyncio.get_event_loop_policy().get_event_loop()
# Since version 3.12, DeprecationWarning is emitted if there is no
# current event loop.
except DeprecationWarning:
loop = asyncio.get_event_loop_policy().new_event_loop()
asyncio.set_event_loop(loop)
return loop


def _dispatch_execute(
ctx: FlyteContext,
load_task: Callable[[], PythonTask],
Expand Down Expand Up @@ -107,7 +125,7 @@ def _dispatch_execute(
if inspect.iscoroutine(outputs):
# Handle eager-mode (async) tasks
logger.info("Output is a coroutine")
outputs = asyncio.run(outputs)
outputs = _get_working_loop().run_until_complete(outputs)

# Step3a
if isinstance(outputs, VoidPromise):
Expand Down
32 changes: 32 additions & 0 deletions tests/flytekit/unit/experimental/test_eager_workflows.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import mock
import os
import sys
import typing
Expand All @@ -9,8 +10,13 @@
from hypothesis import given

from flytekit import dynamic, task, workflow

from flytekit.bin.entrypoint import _get_working_loop, _dispatch_execute
from flytekit.core import context_manager
from flytekit.core.promise import VoidPromise
from flytekit.exceptions.user import FlyteValidationException
from flytekit.experimental import EagerException, eager
from flytekit.models import literals as _literal_models
from flytekit.types.directory import FlyteDirectory
from flytekit.types.file import FlyteFile
from flytekit.types.structured import StructuredDataset
Expand Down Expand Up @@ -275,3 +281,29 @@ async def eager_wf_flyte_directory() -> str:

result = asyncio.run(eager_wf_flyte_directory())
assert result == "some data"


@mock.patch("flytekit.core.utils.load_proto_from_file")
@mock.patch("flytekit.core.data_persistence.FileAccessProvider.get_data")
@mock.patch("flytekit.core.data_persistence.FileAccessProvider.put_data")
@mock.patch("flytekit.core.utils.write_proto_to_file")
def test_eager_workflow_dispatch(*args):
"""Test that event loop is preserved after executing eager workflow via dispatch."""

@eager
async def eager_wf():
await asyncio.sleep(0.1)
return

ctx = context_manager.FlyteContext.current_context()
with context_manager.FlyteContextManager.with_context(
ctx.with_execution_state(
ctx.execution_state.with_params(mode=context_manager.ExecutionState.Mode.TASK_EXECUTION)
)
) as ctx:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
asyncio.events.set_event_loop(loop)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is setting the event loop safe to do in a test?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

@cosmicBboy cosmicBboy Sep 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

even better, the pytest-asyncio library has an event_loop fixture 👇

_dispatch_execute(ctx, lambda: eager_wf, "inputs path", "outputs prefix")
loop_after_execute = asyncio.get_event_loop_policy().get_event_loop()
assert loop == loop_after_execute
Loading