Skip to content

Commit fbfc9bf

Browse files
committed
feat(worker): support async def activities
Registering an `async def` activity used to fail at runtime: the activity executor called it without awaiting, and the data converter then tried to serialize the coroutine ("Failed to serialize object of type 'coroutine'"). Coroutine activities now run on the worker's event loop instead of the thread pool, so an I/O-bound activity no longer holds a worker thread while it waits. Their concurrency stays bounded by `maximum_concurrent_activity_work_items`. Synchronous activities keep their existing path unchanged. - `_ActivityExecutor.execute_async` awaits awaitable results; input deserialization and output serialization are shared with `execute`. - The worker dispatches coroutine activities to `_execute_activity_async`, which keeps tracing, failure details and the activity execution hooks, and offloads the blocking calls (payload store, `CompleteActivityTask`) to a thread. - `wrap_with_release` keeps coroutine handlers awaitable; it previously wrapped every handler in a synchronous function, which would have sent coroutine handlers to the thread pool unawaited. - `call_activity()` gains an overload so an async activity's task is typed with the awaited result rather than a coroutine. - A synchronous activity that returns an awaitable now fails with a `TypeError` asking for `async def`, instead of a serialization error. Tests cover the executor, the activity hooks, handler selection, the activity span on both paths, end-to-end runs on the in-memory backend (including activities that must all be in flight at once to pass a barrier, with a single pool thread) and the static result types.
1 parent 5c842a3 commit fbfc9bf

11 files changed

Lines changed: 593 additions & 46 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ ADDED
1111

1212
- Added `OrchestrationQuery.task_hub_names` to filter orchestration instances
1313
by one or more task hubs.
14+
- Activities can now be `async def` functions. An async activity no longer
15+
occupies a worker thread while it waits on I/O; the number running at once is
16+
bounded by `ConcurrencyOptions.maximum_concurrent_activity_work_items`, and
17+
`call_activity()` types its task with the awaited result. See
18+
[activities](docs/features.md#activities).
1419

1520
CHANGED
1621

@@ -20,6 +25,8 @@ Python versions use the standard-library module.
2025
- Context managers now preserve subclass types in type checkers, including
2126
Azure Managed clients and workers.
2227
- Entity ID copy and pickle hooks now preserve subclass types in type checkers.
28+
- A synchronous activity that returns an awaitable now fails with a `TypeError`
29+
asking for `async def`, instead of a JSON serialization error.
2330
- Multiple task completion callback failures now raise the built-in
2431
`ExceptionGroup`, preserving each exception and its traceback in memory and
2532
the first callback error as the explicit cause and serialized inner failure.

‎docs/features.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,22 @@ guarantees, meaning that they will be executed at least once but may be executed
7676
the event of a transient failure. Activity functions are where the real "work" of any orchestration
7777
is done.
7878

79+
Activities can also be `async def` functions. The worker awaits them on its event loop instead of
80+
running them in its thread pool, so I/O-bound activities (HTTP or database calls, async SDK clients)
81+
don't each hold a thread while they wait. Their concurrency is bounded by
82+
`ConcurrencyOptions.maximum_concurrent_activity_work_items`.
83+
84+
```python
85+
async def fetch_profile(ctx: task.ActivityContext, user_id: str) -> dict:
86+
async with httpx.AsyncClient() as http:
87+
response = await http.get(f"https://example.com/users/{user_id}")
88+
return response.json()
89+
```
90+
91+
Async activities share the worker's event loop: avoid blocking calls in them (synchronous I/O or
92+
long CPU-bound work), which would delay every other async activity and the dispatch of new work
93+
items. Keep such work in ordinary `def` activities. Orchestrators remain generator functions.
94+
7995
### Durable timers
8096

8197
Orchestrations can schedule durable timers using the `create_timer` API. These timers are durable,

‎durabletask-azuremanaged/CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

88
## Unreleased
99

10+
ADDED
11+
12+
- With the corresponding core `durabletask` SDK change, `DurableTaskSchedulerWorker`
13+
runs `async def` activities without occupying a worker thread while they wait on I/O.
14+
1015
CHANGED
1116

1217
- Dropped Python 3.10 support. Python 3.11 or later is now required.

‎durabletask/task.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import logging
88
import math
99
from abc import ABC, abstractmethod
10-
from collections.abc import Callable, Generator, Sequence
10+
from collections.abc import Awaitable, Callable, Generator, Sequence
1111
from dataclasses import dataclass
1212
from datetime import UTC, datetime, timedelta
1313
from typing import Any, Generic, TypeAlias, TypeVar, cast, overload
@@ -140,6 +140,14 @@ def call_activity(self, activity: Activity[TInput, TOutput] | str, *,
140140
return_type: type[T]) -> CompletableTask[T]:
141141
...
142142

143+
@overload
144+
def call_activity(self, activity: AsyncActivity[TInput, TOutput], *,
145+
input: TInput | None = ...,
146+
retry_policy: RetryPolicy | None = ...,
147+
tags: dict[str, str] | None = ...,
148+
return_type: None = ...) -> CompletableTask[TOutput]:
149+
...
150+
143151
@overload
144152
def call_activity(self, activity: Activity[TInput, TOutput] | str, *,
145153
input: TInput | None = ...,
@@ -948,6 +956,9 @@ def task_id(self) -> int:
948956
# Activities are simple functions that can be scheduled by orchestrators
949957
Activity: TypeAlias = Callable[[ActivityContext, TInput], TOutput]
950958

959+
# Async activities are awaited by the worker; their tasks complete with the awaited result
960+
AsyncActivity: TypeAlias = Callable[[ActivityContext, TInput], Awaitable[TOutput]]
961+
951962
Entity: TypeAlias = Callable[[EntityContext, TInput], TOutput] | type[DurableEntity]
952963

953964

‎durabletask/worker.py‎

Lines changed: 197 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import time
1111
from collections.abc import Callable, Generator, Sequence
1212
from concurrent.futures import ThreadPoolExecutor
13+
from contextlib import contextmanager
1314
from dataclasses import dataclass, field
1415
from datetime import UTC, datetime, timedelta
1516
from threading import Event, Lock, Thread
@@ -830,6 +831,18 @@ def wrap_with_release(
830831
handler: Callable[..., Any],
831832
release: Callable[[], None],
832833
) -> Callable[..., Any]:
834+
if inspect.iscoroutinefunction(handler):
835+
# Keep coroutine handlers recognizable as such, so the worker
836+
# manager awaits them on its event loop rather than calling
837+
# them from the thread pool.
838+
async def wrapped_async(*args: Any, **kwargs: Any) -> Any:
839+
try:
840+
return await handler(*args, **kwargs)
841+
finally:
842+
release()
843+
844+
return wrapped_async
845+
833846
def wrapped(*args: Any, **kwargs: Any) -> Any:
834847
try:
835848
return handler(*args, **kwargs)
@@ -1025,7 +1038,7 @@ def stream_reader(response_stream: Any = response_stream) -> None:
10251038
elif work_item.HasField("activityRequest"):
10261039
submit_work_item(
10271040
self._async_worker_manager.submit_activity,
1028-
self._execute_activity,
1041+
self._get_activity_handler(work_item.activityRequest),
10291042
self._cancel_activity,
10301043
work_item.activityRequest,
10311044
stub,
@@ -1399,54 +1412,130 @@ def _execute_activity(
13991412
payload_helpers.deexternalize_payloads(req, self._payload_store)
14001413
try:
14011414
executor = _ActivityExecutor(self._registry, self._logger, self._data_converter)
1402-
with tracing.suppress_span_emission(not self._emit_trace_spans):
1403-
with tracing.start_span(
1404-
tracing.create_span_name("activity", req.name),
1405-
trace_context=req.parentTraceContext,
1406-
kind=tracing.SpanKind.SERVER,
1407-
attributes={
1408-
tracing.ATTR_TASK_TYPE: "activity",
1409-
tracing.ATTR_TASK_INSTANCE_ID: instance_id,
1410-
tracing.ATTR_TASK_NAME: req.name,
1411-
tracing.ATTR_TASK_TASK_ID: str(req.taskId),
1412-
},
1413-
) as span:
1414-
try:
1415-
result = executor.execute(
1416-
instance_id, req.name, req.taskId, req.input.value
1417-
)
1418-
except Exception as ex:
1419-
tracing.set_span_error(span, ex)
1420-
raise
1421-
res = pb.ActivityResponse(
1422-
instanceId=instance_id,
1423-
taskId=req.taskId,
1424-
result=ph.get_string_value(result),
1425-
completionToken=completionToken,
1426-
)
1415+
with self._start_activity_span(req) as span:
1416+
try:
1417+
result = executor.execute(
1418+
instance_id, req.name, req.taskId, req.input.value
1419+
)
1420+
except Exception as ex:
1421+
tracing.set_span_error(span, ex)
1422+
raise
1423+
res = self._new_activity_response(req, completionToken, result)
14271424
except Exception as ex:
1428-
res = pb.ActivityResponse(
1429-
instanceId=instance_id,
1430-
taskId=req.taskId,
1431-
failureDetails=ph.new_failure_details(
1432-
ex, self._exception_properties_provider, self._logger),
1433-
completionToken=completionToken,
1434-
)
1425+
res = self._new_activity_failure_response(req, completionToken, ex)
1426+
1427+
self._complete_activity_task(req, stub, res)
1428+
finally:
1429+
self._on_activity_execution_completed(req)
1430+
1431+
async def _execute_activity_async(
1432+
self,
1433+
req: pb.ActivityRequest,
1434+
stub: Any,
1435+
completionToken: Any,
1436+
) -> None:
1437+
"""Executes an ``async def`` activity on the worker's event loop.
14351438
1439+
Mirrors :meth:`_execute_activity`, but awaits the activity instead of
1440+
occupying a thread-pool worker. The blocking calls around it (payload
1441+
store access and the gRPC completion) are offloaded to a thread so
1442+
they don't stall the event loop.
1443+
"""
1444+
instance_id = req.orchestrationInstance.instanceId
1445+
self._on_activity_execution_started(req)
1446+
try:
1447+
# De-externalize any large-payload tokens in the incoming request
1448+
if self._payload_store is not None:
1449+
await asyncio.to_thread(
1450+
payload_helpers.deexternalize_payloads, req, self._payload_store
1451+
)
14361452
try:
1437-
# Externalize any large payloads in the response
1438-
if self._payload_store is not None:
1439-
payload_helpers.externalize_payloads(
1440-
res, self._payload_store, instance_id=instance_id,
1441-
)
1442-
stub.CompleteActivityTask(res)
1453+
executor = _ActivityExecutor(self._registry, self._logger, self._data_converter)
1454+
with self._start_activity_span(req) as span:
1455+
try:
1456+
result = await executor.execute_async(
1457+
instance_id, req.name, req.taskId, req.input.value
1458+
)
1459+
except Exception as ex:
1460+
tracing.set_span_error(span, ex)
1461+
raise
1462+
res = self._new_activity_response(req, completionToken, result)
14431463
except Exception as ex:
1444-
self._logger.exception(
1445-
f"Failed to deliver activity response for '{req.name}#{req.taskId}' of orchestration ID '{instance_id}' to sidecar: {ex}"
1446-
)
1464+
res = self._new_activity_failure_response(req, completionToken, ex)
1465+
1466+
await asyncio.to_thread(self._complete_activity_task, req, stub, res)
14471467
finally:
14481468
self._on_activity_execution_completed(req)
14491469

1470+
def _get_activity_handler(self, req: pb.ActivityRequest) -> Callable[..., Any]:
1471+
"""Returns the handler that executes the activity named by the request."""
1472+
fn = self._registry.get_activity(req.name)
1473+
if fn is not None and _is_async_callable(fn):
1474+
return self._execute_activity_async
1475+
return self._execute_activity
1476+
1477+
@contextmanager
1478+
def _start_activity_span(self, req: pb.ActivityRequest):
1479+
with tracing.suppress_span_emission(not self._emit_trace_spans):
1480+
with tracing.start_span(
1481+
tracing.create_span_name("activity", req.name),
1482+
trace_context=req.parentTraceContext,
1483+
kind=tracing.SpanKind.SERVER,
1484+
attributes={
1485+
tracing.ATTR_TASK_TYPE: "activity",
1486+
tracing.ATTR_TASK_INSTANCE_ID: req.orchestrationInstance.instanceId,
1487+
tracing.ATTR_TASK_NAME: req.name,
1488+
tracing.ATTR_TASK_TASK_ID: str(req.taskId),
1489+
},
1490+
) as span:
1491+
yield span
1492+
1493+
def _new_activity_response(
1494+
self,
1495+
req: pb.ActivityRequest,
1496+
completionToken: Any,
1497+
result: str | None,
1498+
) -> pb.ActivityResponse:
1499+
return pb.ActivityResponse(
1500+
instanceId=req.orchestrationInstance.instanceId,
1501+
taskId=req.taskId,
1502+
result=ph.get_string_value(result),
1503+
completionToken=completionToken,
1504+
)
1505+
1506+
def _new_activity_failure_response(
1507+
self,
1508+
req: pb.ActivityRequest,
1509+
completionToken: Any,
1510+
ex: Exception,
1511+
) -> pb.ActivityResponse:
1512+
return pb.ActivityResponse(
1513+
instanceId=req.orchestrationInstance.instanceId,
1514+
taskId=req.taskId,
1515+
failureDetails=ph.new_failure_details(
1516+
ex, self._exception_properties_provider, self._logger),
1517+
completionToken=completionToken,
1518+
)
1519+
1520+
def _complete_activity_task(
1521+
self,
1522+
req: pb.ActivityRequest,
1523+
stub: Any,
1524+
res: pb.ActivityResponse,
1525+
) -> None:
1526+
instance_id = req.orchestrationInstance.instanceId
1527+
try:
1528+
# Externalize any large payloads in the response
1529+
if self._payload_store is not None:
1530+
payload_helpers.externalize_payloads(
1531+
res, self._payload_store, instance_id=instance_id,
1532+
)
1533+
stub.CompleteActivityTask(res)
1534+
except Exception as ex:
1535+
self._logger.exception(
1536+
f"Failed to deliver activity response for '{req.name}#{req.taskId}' of orchestration ID '{instance_id}' to sidecar: {ex}"
1537+
)
1538+
14501539
def _cancel_activity(
14511540
self,
14521541
req: pb.ActivityRequest,
@@ -1878,6 +1967,18 @@ def call_activity(
18781967
) -> task.CompletableTask[T]:
18791968
...
18801969

1970+
@overload
1971+
def call_activity(
1972+
self,
1973+
activity: task.AsyncActivity[TInput, TOutput],
1974+
*,
1975+
input: TInput | None = ...,
1976+
retry_policy: task.RetryPolicy | None = ...,
1977+
tags: dict[str, str] | None = ...,
1978+
return_type: None = ...,
1979+
) -> task.CompletableTask[TOutput]:
1980+
...
1981+
18811982
@overload
18821983
def call_activity(
18831984
self,
@@ -3401,6 +3502,13 @@ def compare_versions(self, source_version: str | None, default_version: str | No
34013502
return (source_version > default_version) - (source_version < default_version)
34023503

34033504

3505+
def _is_async_callable(fn: Callable[..., Any]) -> bool:
3506+
"""Returns True for ``async def`` functions and objects with an ``async def __call__``."""
3507+
return inspect.iscoroutinefunction(fn) or inspect.iscoroutinefunction(
3508+
getattr(fn, "__call__", None)
3509+
)
3510+
3511+
34043512
class _ActivityExecutor:
34053513
def __init__(self, registry: _Registry, logger: logging.Logger,
34063514
data_converter: DataConverter):
@@ -3416,6 +3524,45 @@ def execute(
34163524
encoded_input: str | None,
34173525
) -> str | None:
34183526
"""Executes an activity function and returns the serialized result, if any."""
3527+
fn, ctx, activity_input = self._prepare(orchestration_id, name, task_id, encoded_input)
3528+
3529+
# Execute the activity function
3530+
activity_output = fn(ctx, activity_input)
3531+
if inspect.isawaitable(activity_output):
3532+
if inspect.iscoroutine(activity_output):
3533+
activity_output.close()
3534+
raise TypeError(
3535+
f"Activity '{name}' returned an awaitable from a synchronous call. "
3536+
"Declare the activity with 'async def' so the worker awaits it."
3537+
)
3538+
3539+
return self._serialize_output(orchestration_id, name, task_id, activity_output)
3540+
3541+
async def execute_async(
3542+
self,
3543+
orchestration_id: str,
3544+
name: str,
3545+
task_id: int,
3546+
encoded_input: str | None,
3547+
) -> str | None:
3548+
"""Executes an activity function, awaiting its result if it is awaitable,
3549+
and returns the serialized result, if any."""
3550+
fn, ctx, activity_input = self._prepare(orchestration_id, name, task_id, encoded_input)
3551+
3552+
# Execute the activity function
3553+
activity_output = fn(ctx, activity_input)
3554+
if inspect.isawaitable(activity_output):
3555+
activity_output = await activity_output
3556+
3557+
return self._serialize_output(orchestration_id, name, task_id, activity_output)
3558+
3559+
def _prepare(
3560+
self,
3561+
orchestration_id: str,
3562+
name: str,
3563+
task_id: int,
3564+
encoded_input: str | None,
3565+
) -> tuple[task.Activity[Any, Any], task.ActivityContext, Any]:
34193566
self._logger.debug(
34203567
f"{orchestration_id}/{task_id}: Executing activity '{name}'..."
34213568
)
@@ -3428,10 +3575,15 @@ def execute(
34283575
input_type = type_discovery.activity_input_type(fn, self._data_converter) if encoded_input else None
34293576
activity_input = self._data_converter.deserialize(encoded_input, input_type)
34303577
ctx = task.ActivityContext(orchestration_id, task_id)
3578+
return fn, ctx, activity_input
34313579

3432-
# Execute the activity function
3433-
activity_output = fn(ctx, activity_input)
3434-
3580+
def _serialize_output(
3581+
self,
3582+
orchestration_id: str,
3583+
name: str,
3584+
task_id: int,
3585+
activity_output: Any,
3586+
) -> str | None:
34353587
encoded_output = self._data_converter.serialize(activity_output)
34363588
chars = len(encoded_output) if encoded_output else 0
34373589
self._logger.debug(

0 commit comments

Comments
 (0)