-
Notifications
You must be signed in to change notification settings - Fork 148
Add support for async workflow activities #1053
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
Merged
Merged
Changes from 21 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
872e75c
Add support for async activities
413f16f
Merge branch 'main' into async-compat
seherv b52139c
Address Copilot feedback (1)
seherv 0c64d1a
Address Copilot feedback (2)
seherv 69ea96e
Address Copilot feedback (3)
seherv 81fa323
Address Copilot feedback (4)
seherv dadaa9a
Fix linter
seherv 8c4ce88
Merge branch 'main' into async-compat
seherv e8c4c05
Address Copilot feedback (5)
seherv 7ec820e
Address Copilot feedback (6)
seherv 9185482
Merge branch 'main' into async-compat
seherv 73add2e
Reword warning
seherv 5709bcd
Cleanup
seherv e68141c
Remove strands-agents-tools dependency
seherv feb60db
Redo benchmarks and add performance regression tests
seherv 70c6fad
Merge branch 'main' into async-compat
seherv 5fb88e6
Relax performance thresholds for CI
seherv 6eb9ce0
More async detection tests
seherv 8cf248b
Create gRPC channel in the caller's event loop
seherv a73e994
Silence gRPC error spam on EAGAIN
seherv a2d4ad8
Merge branch 'main' into async-compat
sicoyle b1e0c3f
Remove async benchmark code
seherv a4d23de
Address PR feedback (2)
seherv 3f80ed6
Merge branch 'main' into async-compat
seherv 7f86c10
Merge branch 'main' into async-compat
sicoyle 67915a2
Merge origin/main into async-compat
seherv 152f058
Update docs to match new dapr[ext] structure
seherv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| # -*- coding: utf-8 -*- | ||
| # Copyright 2026 The Dapr Authors | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """Async activities running alongside a sync one in a fan-out/fan-in workflow. | ||
|
|
||
| Each async activity simulates an I/O-bound call: it takes a payload, awaits a fixed | ||
| delay (standing in for a network round-trip), and returns a result payload. The async | ||
| instances run concurrently on the worker's event loop; a final sync activity aggregates | ||
| the results. Fan-out width, input/output payload sizes, and the delay are configurable | ||
| via environment variables. | ||
|
|
||
| Run with: | ||
|
|
||
| dapr run --app-id async-activities --app-protocol grpc --dapr-grpc-port 50001 \\ | ||
| -- python async_activities.py | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import os | ||
| import random | ||
| import string | ||
| from time import sleep | ||
|
|
||
| import dapr.ext.workflow as wf | ||
| from pydantic import BaseModel | ||
|
|
||
| FAN_OUT = int(os.environ.get('WORKFLOW_FAN_OUT', '5')) | ||
| INPUT_BYTES = int(os.environ.get('WORKFLOW_INPUT_BYTES', '2048')) | ||
| OUTPUT_BYTES = int(os.environ.get('WORKFLOW_OUTPUT_BYTES', '1024')) | ||
| IO_SECONDS = float(os.environ.get('WORKFLOW_IO_SECONDS', '1.0')) | ||
|
|
||
| wfr = wf.WorkflowRuntime() | ||
|
|
||
|
|
||
| def _random_digits(n: int) -> str: | ||
| return ''.join(random.choices(string.digits, k=n)) | ||
|
|
||
|
|
||
| class Payload(BaseModel): | ||
| index: int | ||
| data: str | ||
|
|
||
|
|
||
| @wfr.workflow(name='fan_out_fan_in_workflow') | ||
| def fan_out_fan_in_workflow(ctx: wf.DaprWorkflowContext, payloads: list[dict]): | ||
| tasks = [ctx.call_activity(process_payload, input=p) for p in payloads] | ||
| results = yield wf.when_all(tasks) | ||
| summary = yield ctx.call_activity(summarize, input=results) | ||
| return summary | ||
|
|
||
|
|
||
| @wfr.activity(name='process_payload') | ||
| async def process_payload(ctx: wf.WorkflowActivityContext, payload: Payload) -> str: | ||
| """Async activity: simulate an I/O-bound call. Instances run concurrently on the loop.""" | ||
| await asyncio.sleep(IO_SECONDS) | ||
| result = _random_digits(OUTPUT_BYTES) | ||
| print( | ||
| f'[async] payload {payload.index}: {len(payload.data)}B in -> {len(result)}B out', | ||
| flush=True, | ||
| ) | ||
| return result | ||
|
|
||
|
|
||
| @wfr.activity(name='summarize') | ||
| def summarize(ctx: wf.WorkflowActivityContext, results: list[str]) -> str: | ||
| """Sync activity: aggregate the fan-out results on the thread pool.""" | ||
| summary = f'{len(results)} results, {sum(len(r) for r in results)} bytes' | ||
| print(f'[sync] {summary}', flush=True) | ||
| return summary | ||
|
|
||
|
|
||
| def main() -> None: | ||
| payloads = [ | ||
| Payload(index=i, data=_random_digits(INPUT_BYTES)).model_dump() for i in range(FAN_OUT) | ||
| ] | ||
|
|
||
| wfr.start() | ||
| sleep(5) # wait for workflow runtime to start | ||
|
|
||
| wf_client = wf.DaprWorkflowClient() | ||
| instance_id = wf_client.schedule_new_workflow(workflow=fan_out_fan_in_workflow, input=payloads) | ||
| print(f'Workflow started. Instance ID: {instance_id}') | ||
|
|
||
| state = wf_client.wait_for_workflow_completion(instance_id, timeout_in_seconds=60) | ||
| assert state is not None | ||
| print(f'Workflow completed! Status: {state.runtime_status.name}') | ||
| print(f'Workflow result: {state.serialized_output.strip(chr(34))}') | ||
|
|
||
| wfr.shutdown() | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,223 @@ | ||
| # -*- coding: utf-8 -*- | ||
| # Copyright 2026 The Dapr Authors | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """Run-environment capture and Markdown formatting for the benchmark report.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| import platform | ||
| import shutil | ||
| import subprocess | ||
| from dataclasses import dataclass | ||
| from datetime import datetime, timezone | ||
| from pathlib import Path | ||
|
|
||
| from dapr.ext.workflow._bench_harness import IS_DARWIN, ScenarioMetrics, SustainedMetrics | ||
|
|
||
|
|
||
| def _read_text(path: str) -> str: | ||
| try: | ||
| return Path(path).read_text(encoding='utf-8', errors='ignore') | ||
| except OSError: | ||
| return '' | ||
|
seherv marked this conversation as resolved.
Outdated
|
||
|
|
||
|
|
||
| def _cpu_model() -> str: | ||
| """Best-effort CPU model name. Cross-platform; returns a placeholder on failure.""" | ||
| if IS_DARWIN: | ||
| sysctl = shutil.which('sysctl') | ||
| if sysctl is not None: | ||
| try: | ||
| out = subprocess.run( | ||
| [sysctl, '-n', 'machdep.cpu.brand_string'], | ||
| capture_output=True, | ||
| text=True, | ||
| timeout=2, | ||
| ) | ||
| if out.returncode == 0 and out.stdout.strip(): | ||
| return out.stdout.strip() | ||
| except (subprocess.SubprocessError, OSError): | ||
| pass | ||
| cpuinfo = _read_text('/proc/cpuinfo') | ||
| for line in cpuinfo.splitlines(): | ||
| if line.startswith('model name'): | ||
| return line.split(':', 1)[1].strip() | ||
| return platform.processor() or platform.machine() or 'unknown' | ||
|
|
||
|
|
||
| def _total_memory_gb() -> float: | ||
| """Best-effort total physical memory in GB. Returns 0 on failure.""" | ||
| if IS_DARWIN: | ||
| sysctl = shutil.which('sysctl') | ||
| if sysctl is not None: | ||
| try: | ||
| out = subprocess.run( | ||
| [sysctl, '-n', 'hw.memsize'], | ||
| capture_output=True, | ||
| text=True, | ||
| timeout=2, | ||
| ) | ||
| if out.returncode == 0 and out.stdout.strip().isdigit(): | ||
| return int(out.stdout.strip()) / (1024**3) | ||
| except (subprocess.SubprocessError, OSError): | ||
| pass | ||
| meminfo = _read_text('/proc/meminfo') | ||
| for line in meminfo.splitlines(): | ||
| if line.startswith('MemTotal:'): | ||
| parts = line.split() | ||
| if len(parts) >= 2 and parts[1].isdigit(): | ||
| return int(parts[1]) / (1024**2) | ||
| return 0.0 | ||
|
|
||
|
|
||
| def _git_commit() -> str: | ||
| """Short git commit hash, or 'unknown' if not in a git repo.""" | ||
| git = shutil.which('git') | ||
| if git is None: | ||
| return 'unknown' | ||
| try: | ||
| out = subprocess.run( | ||
| [git, 'rev-parse', '--short', 'HEAD'], | ||
| capture_output=True, | ||
| text=True, | ||
| timeout=2, | ||
| cwd=Path(__file__).parent, | ||
| ) | ||
| if out.returncode == 0: | ||
| commit = out.stdout.strip() | ||
| # Mark dirty if there are uncommitted changes. | ||
| status = subprocess.run( | ||
| [git, 'status', '--porcelain'], | ||
| capture_output=True, | ||
| text=True, | ||
| timeout=2, | ||
| cwd=Path(__file__).parent, | ||
| ) | ||
| if status.returncode == 0 and status.stdout.strip(): | ||
| return f'{commit}-dirty' | ||
| return commit | ||
| except (subprocess.SubprocessError, OSError): | ||
| pass | ||
| return 'unknown' | ||
|
|
||
|
|
||
| @dataclass(slots=True) | ||
| class RunEnvironment: | ||
| """Snapshot of the machine the benchmark ran on.""" | ||
|
|
||
| timestamp_utc: str | ||
| git_commit: str | ||
| python_version: str | ||
| python_implementation: str | ||
| platform: str | ||
| os_release: str | ||
| cpu_model: str | ||
| cpu_logical_cores: int | ||
| cpu_physical_cores_hint: int | ||
| total_memory_gb: float | ||
| is_ci: bool | ||
|
|
||
| @classmethod | ||
| def capture(cls) -> 'RunEnvironment': | ||
| return cls( | ||
| timestamp_utc=datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC'), | ||
| git_commit=_git_commit(), | ||
| python_version=platform.python_version(), | ||
| python_implementation=platform.python_implementation(), | ||
| platform=platform.platform(), | ||
| os_release=f'{platform.system()} {platform.release()} ({platform.machine()})', | ||
| cpu_model=_cpu_model(), | ||
| cpu_logical_cores=os.cpu_count() or 0, | ||
| cpu_physical_cores_hint=os.cpu_count() or 0, | ||
| total_memory_gb=_total_memory_gb(), | ||
| is_ci=any(os.environ.get(k) for k in ('CI', 'GITHUB_ACTIONS', 'TRAVIS', 'BUILDKITE')), | ||
| ) | ||
|
|
||
|
|
||
| def _format_environment_block(env: RunEnvironment) -> str: | ||
| mem_str = f'{env.total_memory_gb:.1f} GB' if env.total_memory_gb > 0 else 'unknown' | ||
| return ( | ||
| '## Run environment\n' | ||
| '\n' | ||
| f'- **Timestamp**: {env.timestamp_utc}\n' | ||
| f'- **Git commit**: `{env.git_commit}`\n' | ||
| f'- **Python**: {env.python_implementation} {env.python_version}\n' | ||
| f'- **OS**: {env.os_release}\n' | ||
| f'- **CPU**: {env.cpu_model} ({env.cpu_logical_cores} logical cores)\n' | ||
| f'- **Memory**: {mem_str}\n' | ||
| '\n' | ||
| 'Numbers are specific to this machine; the sync-vs-async gap is what transfers across' | ||
| ' hardware, not the absolute values.' | ||
| ) | ||
|
|
||
|
|
||
| def _speedup_cell(speedup: float) -> str: | ||
| if speedup > 1.2: | ||
| dot = '🟢' | ||
| elif speedup >= 0.8: | ||
| dot = '⚪' | ||
| else: | ||
| dot = '🔴' | ||
| return f'{dot} {speedup:.1f}x' | ||
|
|
||
|
|
||
| def _format_comparison_table( | ||
| rows: list[tuple[str, ScenarioMetrics, ScenarioMetrics]], | ||
| key_label: str = 'N', | ||
| show_async_rss: bool = False, | ||
| ) -> str: | ||
| rss_header = ' Async RAM (MB) |' if show_async_rss else '' | ||
| rss_rule = ' ---: |' if show_async_rss else '' | ||
| header = ( | ||
| f'| {key_label} | Sync (s) | Async (s) | Speedup |{rss_header}\n' | ||
| f'| ---: | ---: | ---: | ---: |{rss_rule}\n' | ||
| ) | ||
| lines = [] | ||
| for key, sync_m, async_m in rows: | ||
| speedup = sync_m.wallclock_s / async_m.wallclock_s if async_m.wallclock_s > 0 else 0.0 | ||
| rss = f' {async_m.peak_rss_delta_mb:.0f} |' if show_async_rss else '' | ||
| lines.append( | ||
| f'| {key} | {sync_m.wallclock_s:.2f} | {async_m.wallclock_s:.2f} |' | ||
| f' {_speedup_cell(speedup)} |{rss}' | ||
| ) | ||
| return header + '\n'.join(lines) | ||
|
|
||
|
|
||
| def _format_sustained_table(sync_m: SustainedMetrics, async_m: SustainedMetrics) -> str: | ||
| def row(label: str, sync_val: str, async_val: str) -> str: | ||
| return f'| {label} | {sync_val} | {async_val} |' | ||
|
|
||
| header = '| Metric | Sync | Async |\n| --- | ---: | ---: |\n' | ||
| rows = [ | ||
| row( | ||
| 'Effective throughput', | ||
| f'{sync_m.throughput_per_s:.0f}/s', | ||
| f'{async_m.throughput_per_s:.0f}/s', | ||
| ), | ||
| row( | ||
| 'p99 latency', | ||
| f'{sync_m.latency_overall.p99_ms:.0f} ms', | ||
| f'{async_m.latency_overall.p99_ms:.0f} ms', | ||
| ), | ||
| row( | ||
| 'p99 first quarter', | ||
| f'{sync_m.latency_first_quarter.p99_ms:.0f} ms', | ||
| f'{async_m.latency_first_quarter.p99_ms:.0f} ms', | ||
| ), | ||
| row( | ||
| 'p99 last quarter', | ||
| f'{sync_m.latency_last_quarter.p99_ms:.0f} ms', | ||
| f'{async_m.latency_last_quarter.p99_ms:.0f} ms', | ||
| ), | ||
| ] | ||
| return header + '\n'.join(rows) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.