Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
51 changes: 47 additions & 4 deletions diagrid/agent/core/workflow/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import asyncio
import json
import logging
import os
import uuid
from abc import ABC, abstractmethod
from contextlib import asynccontextmanager
Expand Down Expand Up @@ -33,6 +34,15 @@ def report_usage(package: str, **dimensions: object) -> None:

logger = logging.getLogger(__name__)

# The environment variable that sets whether this process executes workflows.
# Its values are documented on ``BaseWorkflowRunner``.
WORKER_ENV = "AGENT_WORKER"


def _is_worker_from_env() -> bool:
return os.environ.get(WORKER_ENV, "").strip().lower() not in ("false", "0")


# The distribution that carries each framework, keyed by the lower-cased
# framework label. First installed match wins. Used only for the
# ``framework_version`` usage dimension, so a miss costs nothing.
Expand Down Expand Up @@ -75,6 +85,25 @@ class BaseWorkflowRunner(SignalMixin, AgentRegistryMixin, ABC):
runtime down gracefully on SIGINT/SIGTERM (e.g. Kubernetes pod
termination), matching the dapr-agents behavior.

Environment variables:
``AGENT_WORKER``: whether this process executes workflows. Read once,
when the runner is constructed.

- Unset, or any value other than ``false`` or ``0``: ``start()``
starts the workflow runtime, which connects to Dapr and executes
the runner's workflow and activities, and creates the workflow
client. This is the default.
- ``false`` or ``0`` (case-insensitive, surrounding spaces ignored):
``start()`` creates only the workflow client. The process starts
workflows and reads their state, and a worker in another process
of the same App ID executes them. A workflow started with no
worker connected waits until one connects.

Use ``false`` to split one agent into a front end that serves
requests and separate workers that execute runs. Both must run the
same agent code, because the front end schedules the workflow by
the name the runner registers.

Subclasses must implement:
- ``_setup_telemetry(app)`` — framework-specific OTEL setup
- ``_build_serve_workflow_input(request)`` — map HTTP request to
Expand Down Expand Up @@ -110,6 +139,10 @@ def __init__(
self._port = port
self._max_iterations = max_iterations
self._state_store = state_store
self._worker = _is_worker_from_env()
# Subclasses register their workflow and activities on the runtime
# whether or not this process is a worker: registering opens no
# connection, and it sets the workflow name the client schedules by.
self._workflow_runtime = WorkflowRuntime(host=host, port=port)
self._workflow_client: Optional[DaprWorkflowClient] = None
self._started = False
Expand Down Expand Up @@ -139,25 +172,35 @@ def workflow_name(self) -> str:
# Shared lifecycle
# ------------------------------------------------------------------

@property
def is_worker(self) -> bool:
"""Whether this process executes workflows: false only for ``AGENT_WORKER=false`` or ``0``."""
return self._worker

def start(self) -> None:
"""Start the workflow runtime.
"""Create the workflow client and, in a worker, start the workflow runtime.

Must be called before running any workflows.
"""
if self._started:
return

self._workflow_runtime.start()
if self._worker:
self._workflow_runtime.start()
self._workflow_client = DaprWorkflowClient(host=self._host, port=self._port)
self._started = True
logger.info("Dapr Workflow runtime started")
logger.info(
"Dapr Workflow %s started",
"runtime" if self._worker else "client (not a worker)",
)

def shutdown(self) -> None:
"""Shutdown the workflow runtime and clean up resources."""
if not self._started:
return

self._workflow_runtime.shutdown()
if self._worker:
self._workflow_runtime.shutdown()
if self._state_store is not None:
self._state_store.close()
self._started = False
Expand Down
3 changes: 2 additions & 1 deletion diagrid/agent/langgraph/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,8 @@ def shutdown(self) -> None:
if not self._started:
return

self._workflow_runtime.shutdown()
if self._worker:
self._workflow_runtime.shutdown()
self._started = False
logger.info("Dapr Workflow runtime stopped")

Expand Down
5 changes: 5 additions & 0 deletions diagrid/agent/strands/durable_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ def search(query: str) -> str:
Like a plain Strands ``Agent``, a ``DurableAgent`` is one conversation:
each call starts from ``agent.messages`` and, when it finishes, writes the
full message list back to ``agent.messages``.

A ``DurableAgent`` always executes its own workflows: on the first call it
starts the workflow runtime in this process. It does not read
``AGENT_WORKER``. To split an agent into a front end and separate workers,
use ``DaprWorkflowAgentRunner``.
"""

def __init__(
Expand Down
48 changes: 48 additions & 0 deletions tests/agent/core/test_workflow_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,54 @@ def test_reports_usage_for_the_diagrid_package(
)


@mock.patch("diagrid.agent.core.workflow.runner.DaprWorkflowClient")
@mock.patch("diagrid.agent.core.workflow.runner.WorkflowRuntime")
class TestAgentWorkerEnv(TestCase):
"""``AGENT_WORKER`` decides whether the process starts the workflow runtime."""

def test_is_worker_by_value(self, mock_runtime_cls, mock_client_cls):
cases = {
"false": False,
"0": False,
" False ": False,
"FALSE": False,
"true": True,
"1": True,
"": True,
"no": True,
}
for value, expected in cases.items():
with self.subTest(value=value):
with mock.patch.dict("os.environ", {"AGENT_WORKER": value}):
self.assertIs(ConcreteRunner().is_worker, expected)

def test_is_worker_when_unset(self, mock_runtime_cls, mock_client_cls):
with mock.patch.dict("os.environ", clear=True):
self.assertTrue(ConcreteRunner().is_worker)

def test_not_worker_starts_only_the_client(self, mock_runtime_cls, mock_client_cls):
with mock.patch.dict("os.environ", {"AGENT_WORKER": "false"}):
runner = ConcreteRunner()
runner.start()

mock_runtime_cls.return_value.start.assert_not_called()
mock_client_cls.assert_called_once_with(host=None, port=None)
self.assertTrue(runner.is_running)

def test_not_worker_shutdown_skips_the_runtime(
self, mock_runtime_cls, mock_client_cls
):
mock_store = mock.MagicMock()
with mock.patch.dict("os.environ", {"AGENT_WORKER": "0"}):
runner = ConcreteRunner(state_store=mock_store)
runner.start()
runner.shutdown()

mock_runtime_cls.return_value.shutdown.assert_not_called()
mock_store.close.assert_called_once()
self.assertFalse(runner.is_running)


class TestFrameworkVersion(TestCase):
"""The ``framework_version`` dimension comes from the installed distribution."""

Expand Down
30 changes: 30 additions & 0 deletions tests/agent/langgraph/test_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,5 +458,35 @@ def test_node_named_like_a_generic_activity_runs_through_it(self):
self.assertEqual(ctx.scheduled, ["execute_node_activity"])


@mock.patch("diagrid.agent.core.workflow.runner.DaprWorkflowClient")
@mock.patch("diagrid.agent.core.workflow.runner.WorkflowRuntime")
class TestShutdownAgentWorker(_RunnerTestCase):
"""``shutdown`` stops the workflow runtime only in a worker."""

def _runner(self, worker: str) -> DaprWorkflowGraphRunner:
graph = StateGraph(_Value)
graph.add_node("node", lambda state: state)
graph.add_edge(START, "node")
with mock.patch.dict("os.environ", {"AGENT_WORKER": worker}):
return DaprWorkflowGraphRunner(graph=graph.compile(), name="shutdown")

def test_worker_stops_the_runtime(self, mock_runtime_cls, mock_client_cls):
runner = self._runner("true")
runner.start()
runner.shutdown()

mock_runtime_cls.return_value.shutdown.assert_called_once()
self.assertFalse(runner.is_running)

def test_not_worker_skips_the_runtime(self, mock_runtime_cls, mock_client_cls):
runner = self._runner("false")
runner.start()
runner.shutdown()

mock_runtime_cls.return_value.start.assert_not_called()
mock_runtime_cls.return_value.shutdown.assert_not_called()
self.assertFalse(runner.is_running)


if __name__ == "__main__":
unittest.main()