diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 0a29dd46..e8e3a075 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -6,6 +6,7 @@ import asyncio import json import logging +import os import uuid from abc import ABC, abstractmethod from contextlib import asynccontextmanager @@ -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. @@ -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 @@ -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 @@ -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 diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index c0fc028c..bb8fc664 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -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") diff --git a/diagrid/agent/strands/durable_agent.py b/diagrid/agent/strands/durable_agent.py index a1ebcf3d..a64c6177 100644 --- a/diagrid/agent/strands/durable_agent.py +++ b/diagrid/agent/strands/durable_agent.py @@ -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__( diff --git a/tests/agent/core/test_workflow_runner.py b/tests/agent/core/test_workflow_runner.py index 2f63c42c..3b44f9e7 100644 --- a/tests/agent/core/test_workflow_runner.py +++ b/tests/agent/core/test_workflow_runner.py @@ -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.""" diff --git a/tests/agent/langgraph/test_runner.py b/tests/agent/langgraph/test_runner.py index e1a43cf8..2fa18ffc 100644 --- a/tests/agent/langgraph/test_runner.py +++ b/tests/agent/langgraph/test_runner.py @@ -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()