From fc296c6449d0e089c860b38c87feb25d6ce38f86 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Wed, 25 Nov 2026 23:55:25 +0100 Subject: [PATCH 01/73] feat(core): add a stream sink registry and SSE streaming to the workflow runner Activities run in worker threads, but the connection that wants their output lives on the API's event loop. Add a StreamSinkRegistry with an in-process sink as the hand-off between the two, a bounded buffer, and the SSE framing used to send chunks to a client. BaseWorkflowRunner.serve() now answers POST /agent/run with "stream": true as an event stream for runners that opt in through _serve_stream, and publishes the terminal result to the configured topic once the stream ends. The sink is looked up in one place, so a cross-replica transport can replace it later. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 58 ++++++- diagrid/agent/core/workflow/stream.py | 235 ++++++++++++++++++++++++++ 2 files changed, 290 insertions(+), 3 deletions(-) create mode 100644 diagrid/agent/core/workflow/stream.py diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 0a29dd46..29a14ed2 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -52,6 +52,22 @@ def report_usage(package: str, **dimensions: object) -> None: } +_FINAL_SSE_EVENTS = ("event: workflow_completed", "event: workflow_failed") + + +def _final_event_data(frame: str) -> Optional[dict[str, Any]]: + """Payload of a ``workflow_completed``/``workflow_failed`` SSE frame.""" + lines = frame.strip().split("\n") + if not any(line in _FINAL_SSE_EVENTS for line in lines): + return None + data = "\n".join(line[6:] for line in lines if line.startswith("data: ")) + try: + parsed = json.loads(data) + except (json.JSONDecodeError, TypeError): + return None + return parsed if isinstance(parsed, dict) else None + + def _framework_version(framework: str) -> Optional[str]: """Return the installed version of the library behind ``framework``, or None.""" for distribution in _FRAMEWORK_DISTRIBUTIONS.get( @@ -401,6 +417,7 @@ def serve( """ try: from fastapi import FastAPI, HTTPException, Request + from fastapi.responses import StreamingResponse import uvicorn except ImportError: raise ImportError( @@ -441,7 +458,11 @@ async def _run_and_collect(request: dict) -> dict: # type: ignore[type-arg] result.update(event) break - # Publish result to topic if configured + _publish_result(result) + return result + + def _publish_result(result: dict) -> None: # type: ignore[type-arg] + """Publish a result to the configured topic, if any.""" if pubsub_client and publish_topic: try: pubsub_client.publish(publish_topic, result) @@ -449,10 +470,28 @@ async def _run_and_collect(request: dict) -> dict: # type: ignore[type-arg] except Exception as e: logger.error("Failed to publish result: %s", str(e)) - return result + async def _stream_and_publish(frames: AsyncIterator[str]) -> AsyncIterator[str]: + """Forward SSE frames, then publish the terminal event's data.""" + result: dict[str, Any] = {} + async for frame in frames: + yield frame + final = _final_event_data(frame) + if final is not None: + result.update(final) + if result: + _publish_result(result) @app.post("/agent/run") - async def run_agent(request: dict) -> dict: # type: ignore[type-arg] + async def run_agent(request: dict) -> Any: # type: ignore[type-arg] + if request.get("stream") and self._supports_serve_stream: + session_id = request.get( + "session_id", + request.get("thread_id", uuid.uuid4().hex[:8]), + ) + return StreamingResponse( + _stream_and_publish(self._serve_stream(request, session_id)), + media_type="text/event-stream", + ) return await _run_and_collect(request) @app.get("/agent/run/{workflow_id}") @@ -533,6 +572,19 @@ async def _serve_run( # Make this an async generator yield # type: ignore[misc] # pragma: no cover + # Runners that can stream a run as Server-Sent Events set this and + # implement ``_serve_stream`` (used by ``POST /agent/run`` with + # ``"stream": true``). + _supports_serve_stream = False + + def _serve_stream( + self, + request: dict, # type: ignore[type-arg] + session_id: str, + ) -> AsyncIterator[str]: + """Yield SSE-framed strings for a run. Opt-in per runner.""" + raise NotImplementedError + @abstractmethod def _register_workflow_components(self) -> None: """Register workflow and activities on ``self._workflow_runtime``.""" diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py new file mode 100644 index 00000000..dc92e85f --- /dev/null +++ b/diagrid/agent/core/workflow/stream.py @@ -0,0 +1,235 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Transport for streaming chunks out of workflow activities. + +Activities run in worker threads; the HTTP connection that wants the chunks +lives on the asyncio loop of the API. A :class:`StreamSink` sits between them. +Only the in-process sink exists today (single replica: activity and API share +a process). :func:`get_stream_sink` is the seam for a later cross-replica sink: +it is the only place an activity looks a sink up. +""" + +import asyncio +import json +import logging +import threading +from dataclasses import dataclass +from typing import Any, Dict, Optional, Protocol, Tuple + +logger = logging.getLogger(__name__) + +# Upper bound on buffered chunks per run; extra chunks are dropped (and logged +# once) so a slow consumer cannot grow memory without limit. +MAX_BUFFERED_EVENTS = 10_000 + +NODE_RESET = "node_reset" +UPDATES = "updates" + + +@dataclass(frozen=True) +class StreamEvent: + """One chunk, wrapped with enough identity to order and de-duplicate it.""" + + workflow_id: str + step: int + node: str + attempt_id: str + seq: int + ns: Tuple[str, ...] + mode: str + data: Any + + +class StreamSink(Protocol): + """Where an activity attempt hands its chunks.""" + + def put(self, event: StreamEvent) -> None: ... + + +class StreamClosed: + """Last item a sink hands its consumer: the run is over.""" + + def __init__( + self, error: Optional[str] = None, final: Optional[Dict[str, Any]] = None + ) -> None: + self.error = error + self.final: Dict[str, Any] = final or {} + + +class InProcessSink: + """Per-run buffer fed from activity threads and drained on an event loop. + + Retry handling: activities are at-least-once. The first attempt to emit + for a ``(step, node)`` owns it. A chunk from a different attempt switches + ownership and emits a ``node_reset`` event so consumers can drop the + partial text; the old attempt's chunks are then ignored. After a node's + ``updates`` chunk was accepted, chunks from any other attempt are dropped. + """ + + def __init__(self, workflow_id: str, loop: asyncio.AbstractEventLoop) -> None: + self.workflow_id = workflow_id + self._loop = loop + self._queue: "asyncio.Queue[Any]" = asyncio.Queue() + self._lock = threading.Lock() + self._owner: Dict[Tuple[int, str], str] = {} + self._finished: Dict[Tuple[int, str], str] = {} + self._retired: set = set() + self._last_seq: Dict[Tuple[str, int], int] = {} + self._closed = False + self._warned_full = False + + def put(self, event: StreamEvent) -> None: + key = (event.step, event.node) + with self._lock: + if self._closed: + return + if self._finished.get(key, event.attempt_id) != event.attempt_id: + return + if (key, event.attempt_id) in self._retired: + return + seq_key = (event.attempt_id, event.step) + if event.seq <= self._last_seq.get(seq_key, -1): + return + self._last_seq[seq_key] = event.seq + owner = self._owner.get(key) + if owner is not None and owner != event.attempt_id: + self._retired.add((key, owner)) + self._enqueue( + StreamEvent( + event.workflow_id, + event.step, + event.node, + event.attempt_id, + event.seq, + event.ns, + NODE_RESET, + {"node": event.node, "step": event.step}, + ) + ) + self._owner[key] = event.attempt_id + if event.mode == UPDATES: + self._finished[key] = event.attempt_id + self._enqueue(event) + + def close( + self, error: Optional[str] = None, final: Optional[Dict[str, Any]] = None + ) -> None: + """Mark the run finished; the consumer stops after draining.""" + with self._lock: + if self._closed: + return + self._enqueue(StreamClosed(error, final)) + self._closed = True + + async def get(self) -> Any: + return await self._queue.get() + + def _enqueue(self, item: Any) -> None: + def _put() -> None: + if self._queue.qsize() >= MAX_BUFFERED_EVENTS and not isinstance( + item, StreamClosed + ): + if not self._warned_full: + self._warned_full = True + logger.warning( + "Stream buffer for %s is full; dropping chunks", + self.workflow_id, + ) + return + self._queue.put_nowait(item) + + try: + self._loop.call_soon_threadsafe(_put) + except RuntimeError: # loop already closed + self._closed = True + + +class StreamSinkRegistry: + """The sinks of the streams open in this process, keyed by workflow id. + + A runner owns one (see ``DaprWorkflowGraphRunner(stream_registry=...)``) and + binds it to the activities it registers, so two runners in one process never + see each other's runs. :data:`default_registry` is what an activity falls + back to when nothing was bound to it. + """ + + def __init__(self) -> None: + self._sinks: Dict[str, InProcessSink] = {} + self._lock = threading.Lock() + + def open(self, workflow_id: str) -> InProcessSink: + """Register a sink for ``workflow_id`` on the running event loop. + + Raises ``ValueError`` if a stream for this id is already open, so a + reused id cannot orphan the first run's sink. + """ + sink = InProcessSink(workflow_id, asyncio.get_running_loop()) + with self._lock: + if workflow_id in self._sinks: + raise ValueError(f"A stream for {workflow_id!r} is already open") + self._sinks[workflow_id] = sink + return sink + + def close(self, workflow_id: str, sink: Optional[InProcessSink] = None) -> None: + """Unregister and close the sink; later chunks for this run are dropped. + + With ``sink`` given, only that sink is removed, never a newer one that + took over the id. + """ + with self._lock: + current = self._sinks.get(workflow_id) + if current is None or (sink is not None and current is not sink): + return + del self._sinks[workflow_id] + current.close() + + def get(self, workflow_id: Optional[str]) -> Optional[InProcessSink]: + """The open sink for ``workflow_id``, or ``None``.""" + if not workflow_id: + return None + with self._lock: + return self._sinks.get(workflow_id) + + +#: Fallback for code that was not handed a registry. +default_registry = StreamSinkRegistry() + + +def open_stream( + workflow_id: str, *, registry: Optional[StreamSinkRegistry] = None +) -> InProcessSink: + """:meth:`StreamSinkRegistry.open` on ``registry`` (default: the module's).""" + return (registry or default_registry).open(workflow_id) + + +def close_stream( + workflow_id: str, + sink: Optional[InProcessSink] = None, + *, + registry: Optional[StreamSinkRegistry] = None, +) -> None: + """:meth:`StreamSinkRegistry.close` on ``registry`` (default: the module's).""" + (registry or default_registry).close(workflow_id, sink) + + +def get_stream_sink( + workflow_id: Optional[str], *, registry: Optional[StreamSinkRegistry] = None +) -> Optional[StreamSink]: + """Sink for the run an activity belongs to, or ``None`` when not streaming. + + Seam for the multi-replica case: a remote sink would be returned here when + the run's config names another replica as the stream target. + """ + return (registry or default_registry).get(workflow_id) + + +def format_sse(event: str, data: Any, event_id: Optional[int] = None) -> str: + """Frame one Server-Sent Event.""" + lines = [] + if event_id is not None: + lines.append(f"id: {event_id}") + lines.append(f"event: {event}") + payload = json.dumps(data, default=str) + lines.extend(f"data: {part}" for part in payload.split("\n")) + return "\n".join(lines) + "\n\n" From 90685d23fa7b712a1c36a19d9b3caa5b636762d5 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Wed, 25 Nov 2026 23:55:37 +0100 Subject: [PATCH 02/73] feat(langgraph): stream LLM tokens, node updates and custom events from node activities Each LangGraph node runs as a Dapr workflow activity, so the caller used to see nothing until the whole run finished. Run the node with LangGraph's own message handler and stream writer attached, and send what they produce to the run's sink in the shapes LangGraph's astream yields: "messages" for LLM tokens, "updates" for each node's writes, and "custom" for get_stream_writer() events. DaprWorkflowGraphRunner gains astream(), which starts the workflow and yields those chunks as they arrive, and serves "stream": true requests as SSE. The sink registry can be injected, so tests and embedders keep runs isolated. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/models.py | 7 +- diagrid/agent/langgraph/runner.py | 214 ++++++++++++++++++++++++-- diagrid/agent/langgraph/streaming.py | 171 +++++++++++++++++++++ diagrid/agent/langgraph/workflow.py | 216 ++++++++++++++++++--------- 4 files changed, 525 insertions(+), 83 deletions(-) create mode 100644 diagrid/agent/langgraph/streaming.py diff --git a/diagrid/agent/langgraph/models.py b/diagrid/agent/langgraph/models.py index c07993b2..99938670 100644 --- a/diagrid/agent/langgraph/models.py +++ b/diagrid/agent/langgraph/models.py @@ -206,14 +206,18 @@ class ExecuteNodeInput: channel_state: ChannelState config: Optional[Dict[str, Any]] = None thread_id: Optional[str] = None + step: Optional[int] = None def to_dict(self) -> Dict[str, Any]: - return { + data: Dict[str, Any] = { "node_name": self.node_name, "channel_state": self.channel_state.to_dict(), "config": self.config, "thread_id": self.thread_id, } + if self.step is not None: + data["step"] = self.step + return data @classmethod def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeInput": @@ -222,6 +226,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeInput": channel_state=ChannelState.from_dict(data["channel_state"]), config=data.get("config"), thread_id=data.get("thread_id"), + step=data.get("step"), ) diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index c0fc028c..0d52fe29 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -3,16 +3,32 @@ """Runner for executing LangGraph graphs as Dapr Workflows.""" +import asyncio import json import logging import time import uuid -from typing import Any, AsyncIterator, Callable, Dict, List, Optional, TYPE_CHECKING +from typing import ( + Any, + AsyncIterator, + Callable, + Dict, + List, + Optional, + TYPE_CHECKING, +) from dapr.ext.workflow import WorkflowStatus from diagrid.agent.core.types.type import SupportedFrameworks from diagrid.agent.core.workflow import BaseWorkflowRunner +from diagrid.agent.core.workflow.stream import ( + NODE_RESET, + StreamClosed, + StreamEvent, + StreamSinkRegistry, + format_sse, +) from .models import ( ChannelState, EdgeConfig, @@ -21,9 +37,9 @@ GraphWorkflowOutput, NodeConfig, ) +from .streaming import normalize_stream_mode, to_wire from .workflow import ( agent_workflow, - execute_node_activity, evaluate_condition_activity, GENERIC_NODE_ACTIVITY, make_node_activity, @@ -44,6 +60,28 @@ logger = logging.getLogger(__name__) +_FINAL_EVENTS = ( + "workflow_completed", + "workflow_failed", + "workflow_terminated", + "workflow_error", +) + + +def _final_error(final: Dict[str, Any]) -> Optional[str]: + if final.get("type") == "workflow_failed": + err = final.get("error") + return (err or {}).get("message") if isinstance(err, dict) else str(err) + if final.get("type") == "workflow_error": + return str(final.get("error") or "Workflow error") + if final.get("type") == "workflow_terminated": + return "Workflow was terminated" + return None + + +_TRANSPORT_KEYS = ("stream", "stream_mode") + + class DaprWorkflowGraphRunner(BaseWorkflowRunner): """Runner that executes LangGraph graphs as Dapr Workflows. @@ -109,6 +147,7 @@ def __init__( goal: Optional[str] = None, instructions: Optional[str] = None, registry_config: Optional[Any] = None, + stream_registry: Optional[StreamSinkRegistry] = None, ): """Initialize the runner. @@ -124,9 +163,15 @@ def __init__( goal when ``goal`` is not given. Without it, the registry looks for a module-level ``SystemMessage`` in node globals. registry_config: Optional registry configuration for metadata extraction + stream_registry: Where streamed runs register their sinks. The + activities this runner registers write into it. Defaults to a + new registry owned by this runner. """ self._graph = graph self._max_steps = max_steps + self._stream_registry = ( + stream_registry if stream_registry is not None else StreamSinkRegistry() + ) super().__init__( name, @@ -174,7 +219,8 @@ def _register_workflow_components(self) -> None: agent_workflow, name=self.workflow_name ) self._workflow_runtime.register_activity( - execute_node_activity, name="execute_node_activity" + make_node_activity(GENERIC_NODE_ACTIVITY, self._stream_registry), + name=GENERIC_NODE_ACTIVITY, ) self._workflow_runtime.register_activity( evaluate_condition_activity, name="evaluate_condition_activity" @@ -187,7 +233,7 @@ def _register_node_activities(self) -> None: if name == GENERIC_NODE_ACTIVITY: continue self._workflow_runtime.register_activity( - make_node_activity(node.name), name=name + make_node_activity(node.name, self._stream_registry), name=name ) def _extract_graph_config(self) -> GraphConfig: @@ -637,6 +683,96 @@ def _parse_output(wf_id: str, output_dict: dict) -> dict: # type: ignore[type-a except Exception as e: logger.debug(f"LangSmith parent trace close failed: {e}") + async def astream( + self, + input: Dict[str, Any], + *, + config: Optional[Dict[str, Any]] = None, + thread_id: Optional[str] = None, + workflow_id: Optional[str] = None, + stream_mode: Any = "updates", + subgraphs: bool = False, + poll_interval: float = 0.5, + ) -> AsyncIterator[Any]: + """Stream a run like ``CompiledStateGraph.astream``. + + Supports ``messages``, ``updates`` and ``custom``. A single mode + yields bare chunks; a list of modes yields ``(mode, chunk)`` tuples. + When a retried node restarts, a ``("node_reset", {...})`` tuple is + yielded in either form; discard that node's partial output. Streaming + works when the node activities run in this process (single replica). + + Chunks have the shape ``CompiledStateGraph.astream`` yields: + ``messages`` are ``(message_chunk, metadata)`` and ``updates`` are + ``{node: update}`` with the values exactly as the node returned them + (``None`` for a node that wrote nothing). One difference: LangGraph + merges the nodes of a parallel step into one ``updates`` chunk; here + each node yields its own. Over HTTP (``"stream": true``) the same + chunks are serialized with ``langchain_core.load.dumpd``. + """ + if subgraphs: + raise NotImplementedError("subgraphs=True is not supported yet") + modes, is_list = normalize_stream_mode(stream_mode) + async for item in self._stream_events( + input, + config=config, + thread_id=thread_id, + workflow_id=workflow_id, + poll_interval=poll_interval, + ): + if isinstance(item, StreamEvent): + if item.mode == NODE_RESET: + # Always delivered so a client can drop a failed attempt's + # partial output; a single mode yields it as a tuple too. + yield (NODE_RESET, item.data) + elif item.mode in modes: + yield (item.mode, item.data) if is_list else item.data + + async def _stream_events( + self, + input: Dict[str, Any], + *, + config: Optional[Dict[str, Any]], + thread_id: Optional[str], + workflow_id: Optional[str], + poll_interval: float, + ) -> AsyncIterator[Any]: + """Yield ``StreamEvent`` chunks, then the final control event dict.""" + thread_id = thread_id or str(uuid.uuid4()) + workflow_id = workflow_id or f"graph-{thread_id}-{uuid.uuid4().hex[:8]}" + sink = self._stream_registry.open(workflow_id) + + async def _pump() -> None: + final: Dict[str, Any] = {} + try: + async for event in self.run_async( + input, + thread_id=thread_id, + config=dict(config) if config else None, + workflow_id=workflow_id, + poll_interval=poll_interval, + ): + if event["type"] in _FINAL_EVENTS: + final = event + except Exception as e: + sink.close(error=str(e)) + return + sink.close(error=_final_error(final), final=final) + + task = asyncio.create_task(_pump()) + try: + while True: + item = await sink.get() + if isinstance(item, StreamClosed): + if item.error: + raise RuntimeError(item.error) + yield item.final + return + yield item + finally: + task.cancel() + self._stream_registry.close(workflow_id, sink) + def _serialize_input(self, input: Dict[str, Any]) -> Dict[str, Any]: """Serialize input values for storage.""" from .workflow import _serialize_value @@ -697,23 +833,75 @@ async def _serve_run( ) -> AsyncIterator[dict[str, Any]]: thread_id = request.get("thread_id") or request.get("session_id") or session_id - input_mapper = getattr(self, "_input_mapper", None) - if input_mapper: - graph_input = input_mapper(request) - else: - graph_input = request - if "messages" not in request: - task = request.get("task") - if task: - graph_input = {"messages": [{"role": "user", "content": task}]} + graph_input = self._request_to_input(request) async for event in self.run_async(input=graph_input, thread_id=thread_id): yield event + _supports_serve_stream = True + + async def _serve_stream( # type: ignore[override] + self, + request: dict, # type: ignore[type-arg] + session_id: str, + ) -> AsyncIterator[str]: + """Run the graph and frame its stream as Server-Sent Events. + + ``stream_mode`` in the request (a mode or list of modes) selects what + is sent; the default is all of ``messages``, ``updates`` and ``custom``. + Ends with ``workflow_completed`` or ``workflow_failed``. + """ + thread_id = request.get("thread_id") or request.get("session_id") or session_id + graph_input = self._request_to_input(request) + try: + modes, _ = normalize_stream_mode( + request.get("stream_mode") or ["messages", "updates", "custom"] + ) + except ValueError as e: + yield format_sse("workflow_failed", {"error": str(e)}) + return + + event_id = 0 + try: + async for item in self._stream_events( + graph_input, + config=None, + thread_id=thread_id, + workflow_id=None, + poll_interval=0.5, + ): + if isinstance(item, StreamEvent): + if item.mode != NODE_RESET and item.mode not in modes: + continue + name, data = item.mode, to_wire(item.mode, item.data) + else: + name, data = item.get("type", "workflow_completed"), item + event_id += 1 + yield format_sse(name, data, event_id) + except Exception as e: + logger.exception("Streaming run failed") + yield format_sse("workflow_failed", {"error": str(e)}) + + def _request_to_input(self, request: dict) -> Dict[str, Any]: # type: ignore[type-arg] + input_mapper = getattr(self, "_input_mapper", None) + if input_mapper: + return input_mapper(request) # type: ignore[no-any-return] + request = {k: v for k, v in request.items() if k not in _TRANSPORT_KEYS} + if "messages" not in request: + task = request.get("task") + if task: + return {"messages": [{"role": "user", "content": task}]} + return request + # ------------------------------------------------------------------ # Properties # ------------------------------------------------------------------ + @property + def stream_registry(self) -> StreamSinkRegistry: + """Where this runner's streamed runs register their sinks.""" + return self._stream_registry + @property def graph(self) -> "CompiledStateGraph": """The LangGraph being executed.""" diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py new file mode 100644 index 00000000..1a8f55a6 --- /dev/null +++ b/diagrid/agent/langgraph/streaming.py @@ -0,0 +1,171 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""LangGraph stream-mode support for node activities. + +Reuses what ``CompiledStateGraph.astream`` uses natively: LangGraph's +``StreamMessagesHandler`` (``messages``), ``Runtime.stream_writer`` +(``custom``) and the ``langgraph_*`` metadata keys the Pregel loop sets on +every task. Chunks go to a :class:`StreamSink` wrapped in a ``StreamEvent``. +""" + +import itertools +import uuid +from typing import Any, Dict, List, Tuple + +from langchain_core.load import dumpd + +from diagrid.agent.core.workflow.stream import StreamEvent, StreamSink + +MESSAGES = "messages" +UPDATES = "updates" +CUSTOM = "custom" +SUPPORTED_MODES = (MESSAGES, UPDATES, CUSTOM) + + +class NodeStreamer: + """Streams one activity attempt of one node into a sink.""" + + def __init__( + self, + sink: StreamSink, + *, + workflow_id: str, + step: int, + node: str, + task_id: Any, + ) -> None: + self._sink = sink + self._workflow_id = workflow_id + self._step = step + self._node = node + self._task_id = task_id + self._attempt_id = uuid.uuid4().hex + self._seq = itertools.count() + self._handler: Any = None + self._run_id = uuid.uuid4() + + @property + def metadata(self) -> Dict[str, Any]: + """The ``langgraph_*`` keys the Pregel loop sets on a task's config.""" + return { + # Pregel numbers the first node after START as step 1. + "langgraph_step": self._step + 1, + "langgraph_node": self._node, + "langgraph_triggers": (f"branch:to:{self._node}",), + "langgraph_path": ("__pregel_pull", self._node), + "langgraph_checkpoint_ns": f"{self._node}:{self._task_id}", + "checkpoint_ns": f"{self._node}:{self._task_id}", + } + + def _emit(self, ns: Tuple[str, ...], mode: str, data: Any) -> None: + self._sink.put( + StreamEvent( + workflow_id=self._workflow_id, + step=self._step, + node=self._node, + attempt_id=self._attempt_id, + seq=next(self._seq), + ns=tuple(ns), + mode=mode, + data=data, + ) + ) + + def _on_chunk(self, chunk: Tuple[Any, ...]) -> None: + """Receive ``(ns, mode, payload)`` from ``StreamMessagesHandler``.""" + ns, mode, payload = chunk + message, metadata = payload + self._emit(ns, mode, (message, metadata)) + + def _messages_handler(self) -> Any: + if self._handler is None: + from langgraph.pregel._messages import StreamMessagesHandler + + self._handler = StreamMessagesHandler(self._on_chunk, False) + return self._handler + + def callbacks(self) -> List[Any]: + return [self._messages_handler()] + + # The activity calls the node's bound runnable directly, which never + # starts the chain run Pregel's handler keys node-output messages on + # (StateGraph nodes are built with trace=False). Drive those two + # callbacks by hand so ToolNode / hand-built messages stream too. + def node_started(self, node_input: Any) -> None: + self._messages_handler().on_chain_start( + {}, + node_input, + run_id=self._run_id, + name=self._node, + metadata=self.metadata, + tags=[], + ) + + def node_finished(self, output: Any) -> None: + self._messages_handler().on_chain_end(output, run_id=self._run_id) + + def writer(self, chunk: Any) -> None: + """``Runtime.stream_writer``: what ``get_stream_writer()`` returns.""" + self._emit((), CUSTOM, chunk) + + def updates(self, writes: List[Tuple[str, Any]]) -> None: + """Emit the node's ``(channel, value)`` writes as ``{node: update}``. + + The shape is what ``CompiledStateGraph.astream(stream_mode="updates")`` + yields for one node, with the values exactly as the node returned + them: ``None`` when it wrote nothing, one dict of channel to value, or, + when a channel is written more than once (a list of Commands, repeated + ``files`` sends), a list of single-channel dicts so no write is lost. + """ + update: Any + channels = [ch for ch, _ in writes] + if not writes: + update = None + elif len(set(channels)) == len(channels): + update = dict(writes) + else: + update = [{ch: value} for ch, value in writes] + self._emit((), UPDATES, {self._node: update}) + + def patch_config(self, config: Dict[str, Any]) -> Dict[str, Any]: + """Copy of ``config`` with the handler and task metadata attached.""" + patched = dict(config) + existing = patched.get("callbacks") + if existing is None: + callbacks: Any = self.callbacks() + elif isinstance(existing, list): + callbacks = [*existing, *self.callbacks()] + else: # a CallbackManager + callbacks = existing.copy() + for handler in self.callbacks(): + callbacks.add_handler(handler, inherit=True) + patched["callbacks"] = callbacks + patched["metadata"] = {**(patched.get("metadata") or {}), **self.metadata} + return patched + + +def normalize_stream_mode(stream_mode: Any) -> Tuple[List[str], bool]: + """Return ``(modes, is_list)``; reject modes the runner cannot provide.""" + is_list = isinstance(stream_mode, (list, tuple)) + modes = list(stream_mode) if is_list else [stream_mode] + unsupported = [m for m in modes if m not in SUPPORTED_MODES] + if unsupported: + raise ValueError( + f"Unsupported stream_mode {unsupported!r}; " + f"supported: {list(SUPPORTED_MODES)}" + ) + return modes, is_list + + +def to_wire(mode: str, data: Any) -> Any: + """JSON-ready form of a chunk for a transport. + + ``messages`` and ``updates`` carry LangChain objects; ``dumpd`` turns them + into the form ``langchain_core.load.load`` restores, so a client sees the + same objects an in-process ``astream`` consumer does. Other chunks (the + ``custom`` payload a node chose to write, control events) go as they are. + """ + if mode in (MESSAGES, UPDATES): + return dumpd(data) + return data diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 8d3252b0..f7adb581 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -6,7 +6,7 @@ import contextlib import logging from datetime import timedelta -from typing import Any, Callable, Dict, Generator, List, Optional +from typing import Any, Callable, Dict, Generator, List, Optional, Tuple from dapr.ext.workflow import ( DaprWorkflowContext, @@ -15,6 +15,7 @@ when_all, ) +from langchain_core.runnables.config import set_config_context from langgraph.runtime import Runtime from langgraph.types import Command @@ -29,6 +30,9 @@ CONFIG_KEY_RUNTIME = "__pregel_runtime" CONF = "configurable" +from diagrid.agent.core.workflow.stream import StreamSinkRegistry, get_stream_sink + +from .streaming import NodeStreamer from .models import ( ChannelState, ExecuteNodeInput, @@ -82,17 +86,19 @@ def node_activity_name(node_name: str) -> str: def make_node_activity( node_name: str, + stream_registry: Optional[StreamSinkRegistry] = None, ) -> Callable[[WorkflowActivityContext, Dict[str, Any]], Dict[str, Any]]: """Build the activity registered for one node. Dapr registers each function object once, so every node gets its own - wrapper around ``execute_node_activity``. + wrapper around ``execute_node_activity``. ``stream_registry`` is where the + wrapper looks for the sink of a streamed run (default: the module's). """ def node_activity( ctx: WorkflowActivityContext, input_data: Dict[str, Any] ) -> Dict[str, Any]: - return execute_node_activity(ctx, input_data) + return execute_node_activity(ctx, input_data, stream_registry=stream_registry) return node_activity @@ -334,6 +340,7 @@ def agent_workflow( channel_state=channel_state, config=config, thread_id=thread_id, + step=step, ) activity: Any = execute_node_activity if node_activities_by_name: @@ -435,6 +442,7 @@ def _build_node_runtime( thread_id: Optional[str], ctx: WorkflowActivityContext, node_name: str, + stream_writer: Optional[Callable[[Any], None]] = None, ) -> Runtime: """Build a LangGraph ``Runtime`` carrying execution info for the node. @@ -449,12 +457,15 @@ def _build_node_runtime( thread_id: The execution thread identifier to expose to consumers. ctx: The workflow activity context (provides workflow/task ids). node_name: The node being executed (used as the checkpoint namespace). + stream_writer: Receives ``get_stream_writer()`` output; omitted when + the run is not streaming (the library no-op stays in place). Returns: A ``Runtime`` with ``execution_info`` populated, or a bare ``Runtime``. """ + extra: Dict[str, Any] = {"stream_writer": stream_writer} if stream_writer else {} if ExecutionInfo is None: - return Runtime() + return Runtime(**extra) try: execution_info = ExecutionInfo( checkpoint_id=str(getattr(ctx, "workflow_id", "") or ""), @@ -462,9 +473,9 @@ def _build_node_runtime( task_id=str(getattr(ctx, "task_id", "") or ""), thread_id=thread_id, ) - return Runtime(execution_info=execution_info) + return Runtime(execution_info=execution_info, **extra) except Exception: # pragma: no cover - signature drift / partial ctx - return Runtime() + return Runtime(**extra) def _is_async_only(runnable: Any) -> bool: @@ -480,7 +491,10 @@ def _is_async_only(runnable: Any) -> bool: def execute_node_activity( - ctx: WorkflowActivityContext, input_data: Dict[str, Any] + ctx: WorkflowActivityContext, + input_data: Dict[str, Any], + *, + stream_registry: Optional[StreamSinkRegistry] = None, ) -> Dict[str, Any]: """Activity that executes a single LangGraph node. @@ -493,6 +507,8 @@ def execute_node_activity( Args: ctx: The workflow activity context input_data: Dictionary containing ExecuteNodeInput data + stream_registry: Where to look up the sink of a streamed run + (default: the module's registry). Returns: ExecuteNodeOutput as a dictionary @@ -518,6 +534,22 @@ def execute_node_activity( # Extract tracing config config = node_input.config or {} + # Stream chunks only when a consumer registered a sink for this run; + # otherwise nothing below changes. + sink = get_stream_sink(getattr(ctx, "workflow_id", None), registry=stream_registry) + streamer = ( + NodeStreamer( + sink, + workflow_id=str(ctx.workflow_id), + step=node_input.step or 0, + node=node_name, + task_id=getattr(ctx, "task_id", ""), + ) + if sink is not None + else None + ) + stream_writer = streamer.writer if streamer else None + # Collect side-channel writes from CONFIG_KEY_SEND (used by StateBackend # to write to the "files" channel from sandbox tools). pending_sends: list = [] @@ -573,8 +605,10 @@ def _run_node() -> Any: # workflow owns a tool call via runtime.execution_info.thread_id. if CONFIG_KEY_RUNTIME not in _config[CONF]: _config[CONF][CONFIG_KEY_RUNTIME] = _build_node_runtime( - thread_id, ctx, node_name + thread_id, ctx, node_name, stream_writer ) + if streamer: + _config = streamer.patch_config(_config) # Inject CONFIG_KEY_READ / CONFIG_KEY_SEND so that deepagents # StateBackend (sandbox tools) can read/write the "files" @@ -590,20 +624,40 @@ def _run_node() -> Any: except ImportError: pass - if _is_async_only(node_func): - # A coroutine; run to completion below. - r = node_func.ainvoke(state, config=_config) # type: ignore[attr-defined] + def _invoke() -> Any: + if _is_async_only(node_func): + # A coroutine; run to completion by the caller. + return node_func.ainvoke(state, config=_config) # type: ignore[attr-defined] + return node_func.invoke(state, config=_config) + + if streamer is None: + r = _invoke() else: - r = node_func.invoke(state, config=_config) + # RunnableCallable.invoke only sets the ambient config when + # tracing; get_stream_writer() and the stream handler need it. + with set_config_context(_config) as ctx_: # type: ignore[arg-type] + return ctx_.run(lambda: _await_if_coroutine(_invoke())) else: - sig = inspect.signature(node_func) - params = list(sig.parameters.keys()) - if len(params) >= 2 and "config" in params: - r = node_func(state, config=config) - else: - r = node_func(state) + def _call_plain() -> Any: + sig = inspect.signature(node_func) + params = list(sig.parameters.keys()) + if len(params) >= 2 and "config" in params: + out = node_func(state, config=config) + else: + out = node_func(state) + return _await_if_coroutine(out) + if streamer is None: + return _call_plain() + # Plain callables get no config injected; expose the handler and + # writer through the ambient config instead. + with set_config_context(_plain_stream_config()) as ctx_: # type: ignore[arg-type] + return ctx_.run(_call_plain) + + return _await_if_coroutine(r) + + def _await_if_coroutine(r: Any) -> Any: import asyncio if asyncio.iscoroutine(r): @@ -615,9 +669,17 @@ def _run_node() -> Any: loop.close() return r + def _plain_stream_config() -> Dict[str, Any]: + assert streamer is not None + thread_id = node_input.thread_id or getattr(ctx, "workflow_id", None) + runtime = _build_node_runtime(thread_id, ctx, node_name, stream_writer) + return streamer.patch_config({CONF: {CONFIG_KEY_RUNTIME: runtime}}) + # Set up LangSmith child trace so LLM calls nest under the parent # "LangGraph" trace created by runner.invoke(). parent = _langsmith_parent(config) + if streamer: + streamer.node_started(state) if parent: import langsmith as ls @@ -630,14 +692,17 @@ def _run_node() -> Any: result = _run_node() else: result = _run_node() + if streamer: + streamer.node_finished(result) - # Convert result to writes - writes = _result_to_writes(result) + # Convert result to writes, then append any side-channel writes queued via + # CONFIG_KEY_SEND (e.g. StateBackend writing to the "files" channel from + # sandbox tools). + raw_writes = [*_result_to_raw_writes(result), *pending_sends] + writes = _serialize_writes(raw_writes) - # Append any side-channel writes queued via CONFIG_KEY_SEND (e.g. - # StateBackend writing to the "files" channel from sandbox tools). - for ch, val in pending_sends: - writes.append(NodeWrite(channel=ch, value=_serialize_value(val))) + if streamer: + streamer.updates(raw_writes) return ExecuteNodeOutput( node_name=node_name, @@ -878,78 +943,91 @@ def _reconstruct_state(channel_state: ChannelState) -> Dict[str, Any]: return state -def _result_to_writes(result: Any) -> List[NodeWrite]: - """Convert a node result to a list of writes. +def _result_to_raw_writes(result: Any) -> List[Tuple[str, Any]]: + """Convert a node result to ``(channel, value)`` pairs, values untouched. + + This is what LangGraph itself records as the node's channel writes (and + shows in ``stream_mode="updates"``); :func:`_result_to_writes` serializes + the same pairs for the workflow state. Args: result: The result from a node function Returns: - List of NodeWrite objects + ``(channel, value)`` pairs in write order """ - writes: List[NodeWrite] = [] - if result is None: - return writes + return [] # Handle LangGraph Command objects (used by Deep Agents and newer LangGraph) - try: - # Single Command - if isinstance(result, Command): - return _command_to_writes(result) - - # List of Commands - if isinstance(result, list) and result and isinstance(result[0], Command): - for cmd in result: - writes.extend(_command_to_writes(cmd)) - return writes - except ImportError: - pass + # Single Command + if isinstance(result, Command): + return _command_to_raw_writes(result) + + # List of Commands + if isinstance(result, list) and result and isinstance(result[0], Command): + writes: List[Tuple[str, Any]] = [] + for cmd in result: + writes.extend(_command_to_raw_writes(cmd)) + return writes if isinstance(result, dict): - for key, value in result.items(): - # Serialize value if needed - serialized_value = _serialize_value(value) - writes.append(NodeWrite(channel=key, value=serialized_value)) - else: - # Non-dict results - write to a default channel - serialized_value = _serialize_value(result) - writes.append(NodeWrite(channel="__result__", value=serialized_value)) + return list(result.items()) - return writes + # Non-dict results - write to a default channel + return [("__result__", result)] -def _command_to_writes(cmd: Any) -> List[NodeWrite]: - """Extract channel writes from the ``update`` field of a LangGraph Command. +def _command_to_raw_writes(cmd: Any) -> List[Tuple[str, Any]]: + """Extract ``(channel, value)`` pairs from the ``update`` of a Command. - This helper only inspects ``cmd.update`` to generate ``NodeWrite`` entries. - Any ``goto`` / control-flow information on the Command is ignored by this - workflow runner. + This helper only inspects ``cmd.update``. Any ``goto`` / control-flow + information on the Command is ignored by this workflow runner. Args: cmd: A LangGraph Command instance whose ``update`` field encodes channel writes. Returns: - List of NodeWrite objects derived from ``cmd.update`` + ``(channel, value)`` pairs derived from ``cmd.update`` """ - writes: List[NodeWrite] = [] update = getattr(cmd, "update", None) if update is None: - return writes + return [] if isinstance(update, dict): - for key, value in update.items(): - serialized_value = _serialize_value(value) - writes.append(NodeWrite(channel=key, value=serialized_value)) - elif isinstance(update, (list, tuple)): + return list(update.items()) + if isinstance(update, (list, tuple)): # update can be a list of (channel, value) tuples - for item in update: - if isinstance(item, tuple) and len(item) == 2: - key, value = item - serialized_value = _serialize_value(value) - writes.append(NodeWrite(channel=key, value=serialized_value)) + return [ + (item[0], item[1]) + for item in update + if isinstance(item, tuple) and len(item) == 2 + ] + return [] + + +def _serialize_writes(raw_writes: List[Tuple[str, Any]]) -> List[NodeWrite]: + return [ + NodeWrite(channel=channel, value=_serialize_value(value)) + for channel, value in raw_writes + ] + + +def _result_to_writes(result: Any) -> List[NodeWrite]: + """Convert a node result to a list of serialized writes. + + Args: + result: The result from a node function + + Returns: + List of NodeWrite objects + """ + return _serialize_writes(_result_to_raw_writes(result)) - return writes + +def _command_to_writes(cmd: Any) -> List[NodeWrite]: + """Serialized form of :func:`_command_to_raw_writes`.""" + return _serialize_writes(_command_to_raw_writes(cmd)) def _serialize_value(value: Any) -> Any: From 50164a0315a275ddb8f5e8a6626a19c3aeabdb3c Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Wed, 25 Nov 2026 23:55:50 +0100 Subject: [PATCH 03/73] feat(langgraph): end a streamed run in failure when the run failed A workflow can finish with status "error" or "max_steps_reached", or end terminated, errored or with no result at all. None of these is a success, but the stream used to end as if it were. Normalise whatever ends the run into a single terminal event that names the workflow and thread, and keep the error detail as a dict instead of a bare string. astream() raises GraphRunError for a failed run, and the SSE stream ends in workflow_failed. POST /agent/run with "stream": true now publishes the same result shape as the non-streaming call. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 67 ++++++++++++--------- diagrid/agent/core/workflow/stream.py | 17 +++--- diagrid/agent/langgraph/runner.py | 86 ++++++++++++++++----------- diagrid/agent/langgraph/streaming.py | 66 +++++++++++++++++++- 4 files changed, 163 insertions(+), 73 deletions(-) diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 29a14ed2..59153056 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -10,7 +10,7 @@ from abc import ABC, abstractmethod from contextlib import asynccontextmanager from importlib import metadata -from typing import Any, AsyncIterator, Optional +from typing import Any, AsyncIterator, Optional, Tuple from dapr.ext.workflow import DaprWorkflowClient, WorkflowRuntime, WorkflowStatus from dapr_agents.utils.signal.mixin import SignalMixin @@ -19,6 +19,7 @@ from diagrid.agent.core.metadata.mixins import AgentRegistryMixin from diagrid.agent.core.observability import resolve_observability_config from diagrid.agent.core.workflow.naming import build_workflow_name +from diagrid.agent.core.workflow.stream import format_sse # ``diagrid-core`` ships the reporter. This distribution only pins # ``diagrid-core>=0.1.0`` (through ``diagrid-cli``), so an application holding @@ -52,20 +53,8 @@ def report_usage(package: str, **dimensions: object) -> None: } -_FINAL_SSE_EVENTS = ("event: workflow_completed", "event: workflow_failed") - - -def _final_event_data(frame: str) -> Optional[dict[str, Any]]: - """Payload of a ``workflow_completed``/``workflow_failed`` SSE frame.""" - lines = frame.strip().split("\n") - if not any(line in _FINAL_SSE_EVENTS for line in lines): - return None - data = "\n".join(line[6:] for line in lines if line.startswith("data: ")) - try: - parsed = json.loads(data) - except (json.JSONDecodeError, TypeError): - return None - return parsed if isinstance(parsed, dict) else None +#: Event names that end a streamed run; the data of the last one is the result. +_TERMINAL_EVENTS = ("workflow_completed", "workflow_failed") def _framework_version(framework: str) -> Optional[str]: @@ -451,6 +440,8 @@ async def _run_and_collect(request: dict) -> dict: # type: ignore[type-arg] ): if event["type"] == "workflow_started": result["instance_id"] = event["workflow_id"] + if event.get("thread_id"): + result["thread_id"] = event["thread_id"] elif event["type"] == "workflow_completed": result.update(event) break @@ -470,15 +461,32 @@ def _publish_result(result: dict) -> None: # type: ignore[type-arg] except Exception as e: logger.error("Failed to publish result: %s", str(e)) - async def _stream_and_publish(frames: AsyncIterator[str]) -> AsyncIterator[str]: - """Forward SSE frames, then publish the terminal event's data.""" - result: dict[str, Any] = {} - async for frame in frames: - yield frame - final = _final_event_data(frame) - if final is not None: - result.update(final) - if result: + async def _frame_and_publish( + events: AsyncIterator[Tuple[str, Any]], + ) -> AsyncIterator[str]: + """Frame ``(event, data)`` pairs as SSE; publish the terminal one. + + The only place a streamed run is turned into SSE frames and into + the published result, so a runner just yields pairs. + """ + final: Optional[dict[str, Any]] = None + event_id = 0 + try: + async for name, data in events: + event_id += 1 + yield format_sse(name, data, event_id) + if name in _TERMINAL_EVENTS and isinstance(data, dict): + final = data + finally: + # A client that disconnects ends the generator at a yield; close + # the runner's stream now rather than when it is collected. + aclose = getattr(events, "aclose", None) + if aclose is not None: + await aclose() + if final is not None: + result = dict(final) + if final.get("workflow_id"): + result["instance_id"] = final["workflow_id"] _publish_result(result) @app.post("/agent/run") @@ -489,7 +497,7 @@ async def run_agent(request: dict) -> Any: # type: ignore[type-arg] request.get("thread_id", uuid.uuid4().hex[:8]), ) return StreamingResponse( - _stream_and_publish(self._serve_stream(request, session_id)), + _frame_and_publish(self._serve_stream(request, session_id)), media_type="text/event-stream", ) return await _run_and_collect(request) @@ -581,8 +589,13 @@ def _serve_stream( self, request: dict, # type: ignore[type-arg] session_id: str, - ) -> AsyncIterator[str]: - """Yield SSE-framed strings for a run. Opt-in per runner.""" + ) -> AsyncIterator[Tuple[str, Any]]: + """Yield ``(event_name, data)`` pairs for a run. Opt-in per runner. + + The last pair is ``workflow_completed`` or ``workflow_failed`` with the + run's terminal event as data. Framing as SSE and publishing the result + are done by ``serve()``, not here. + """ raise NotImplementedError @abstractmethod diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index dc92e85f..a198b096 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -48,12 +48,13 @@ def put(self, event: StreamEvent) -> None: ... class StreamClosed: - """Last item a sink hands its consumer: the run is over.""" + """Last item a sink hands its consumer: the run is over. - def __init__( - self, error: Optional[str] = None, final: Optional[Dict[str, Any]] = None - ) -> None: - self.error = error + ``final`` is the run's terminal event (``workflow_completed`` or + ``workflow_failed`` with its payload). + """ + + def __init__(self, final: Optional[Dict[str, Any]] = None) -> None: self.final: Dict[str, Any] = final or {} @@ -112,14 +113,12 @@ def put(self, event: StreamEvent) -> None: self._finished[key] = event.attempt_id self._enqueue(event) - def close( - self, error: Optional[str] = None, final: Optional[Dict[str, Any]] = None - ) -> None: + def close(self, final: Optional[Dict[str, Any]] = None) -> None: """Mark the run finished; the consumer stops after draining.""" with self._lock: if self._closed: return - self._enqueue(StreamClosed(error, final)) + self._enqueue(StreamClosed(final)) self._closed = True async def get(self) -> Any: diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 0d52fe29..28f14eaf 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -15,6 +15,7 @@ Dict, List, Optional, + Tuple, TYPE_CHECKING, ) @@ -27,7 +28,6 @@ StreamClosed, StreamEvent, StreamSinkRegistry, - format_sse, ) from .models import ( ChannelState, @@ -37,7 +37,12 @@ GraphWorkflowOutput, NodeConfig, ) -from .streaming import normalize_stream_mode, to_wire +from .streaming import ( + GraphRunError, + normalize_final, + normalize_stream_mode, + to_wire, +) from .workflow import ( agent_workflow, evaluate_condition_activity, @@ -68,17 +73,6 @@ ) -def _final_error(final: Dict[str, Any]) -> Optional[str]: - if final.get("type") == "workflow_failed": - err = final.get("error") - return (err or {}).get("message") if isinstance(err, dict) else str(err) - if final.get("type") == "workflow_error": - return str(final.get("error") or "Workflow error") - if final.get("type") == "workflow_terminated": - return "Workflow was terminated" - return None - - _TRANSPORT_KEYS = ("stream", "stream_mode") @@ -661,6 +655,7 @@ def _parse_output(wf_id: str, output_dict: dict) -> dict: # type: ignore[type-a "output": output.output, "steps": output.steps, "status": output.status, + **({"error": output.error} if output.error else {}), } async for event in self._poll_workflow( @@ -727,6 +722,8 @@ async def astream( yield (NODE_RESET, item.data) elif item.mode in modes: yield (item.mode, item.data) if is_list else item.data + elif item.get("type") == "workflow_failed": + raise GraphRunError(item) async def _stream_events( self, @@ -737,10 +734,16 @@ async def _stream_events( workflow_id: Optional[str], poll_interval: float, ) -> AsyncIterator[Any]: - """Yield ``StreamEvent`` chunks, then the final control event dict.""" + """Yield ``StreamEvent`` chunks, then the terminal event dict. + + The terminal event is always the last item: ``workflow_completed`` or + ``workflow_failed`` (see :func:`normalize_final`), carrying the run's + ``workflow_id`` and ``thread_id``. + """ thread_id = thread_id or str(uuid.uuid4()) workflow_id = workflow_id or f"graph-{thread_id}-{uuid.uuid4().hex[:8]}" sink = self._stream_registry.open(workflow_id) + task: Optional["asyncio.Task[None]"] = None async def _pump() -> None: final: Dict[str, Any] = {} @@ -755,23 +758,34 @@ async def _pump() -> None: if event["type"] in _FINAL_EVENTS: final = event except Exception as e: - sink.close(error=str(e)) - return - sink.close(error=_final_error(final), final=final) + logger.exception("Streamed run %s failed", workflow_id) + final = { + "type": "workflow_failed", + "error": {"message": str(e), "error_type": type(e).__name__}, + } + sink.close( + normalize_final(final, workflow_id=workflow_id, thread_id=thread_id) + ) - task = asyncio.create_task(_pump()) try: + task = asyncio.create_task(_pump()) while True: item = await sink.get() if isinstance(item, StreamClosed): - if item.error: - raise RuntimeError(item.error) + # Unregister before handing over the result: chunks a late + # activity attempt writes from here on are dropped. + self._stream_registry.close(workflow_id, sink) yield item.final return yield item finally: - task.cancel() + # Also reached when the consumer goes away (client disconnect, + # abandoned generator). That stops this stream only: the Dapr + # workflow itself keeps running to completion. self._stream_registry.close(workflow_id, sink) + if task is not None and not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) def _serialize_input(self, input: Dict[str, Any]) -> Dict[str, Any]: """Serialize input values for storage.""" @@ -844,25 +858,20 @@ async def _serve_stream( # type: ignore[override] self, request: dict, # type: ignore[type-arg] session_id: str, - ) -> AsyncIterator[str]: - """Run the graph and frame its stream as Server-Sent Events. + ) -> AsyncIterator[Tuple[str, Any]]: + """Run the graph and yield its stream as ``(event_name, data)`` pairs. ``stream_mode`` in the request (a mode or list of modes) selects what is sent; the default is all of ``messages``, ``updates`` and ``custom``. - Ends with ``workflow_completed`` or ``workflow_failed``. + Ends with ``workflow_completed`` or ``workflow_failed``, whose data is + the run's full terminal event. The base runner frames the pairs. """ thread_id = request.get("thread_id") or request.get("session_id") or session_id - graph_input = self._request_to_input(request) try: modes, _ = normalize_stream_mode( request.get("stream_mode") or ["messages", "updates", "custom"] ) - except ValueError as e: - yield format_sse("workflow_failed", {"error": str(e)}) - return - - event_id = 0 - try: + graph_input = self._request_to_input(request) async for item in self._stream_events( graph_input, config=None, @@ -873,14 +882,19 @@ async def _serve_stream( # type: ignore[override] if isinstance(item, StreamEvent): if item.mode != NODE_RESET and item.mode not in modes: continue - name, data = item.mode, to_wire(item.mode, item.data) + yield item.mode, to_wire(item.mode, item.data) else: - name, data = item.get("type", "workflow_completed"), item - event_id += 1 - yield format_sse(name, data, event_id) + yield item["type"], item except Exception as e: logger.exception("Streaming run failed") - yield format_sse("workflow_failed", {"error": str(e)}) + failed = { + "type": "workflow_failed", + "error": {"message": str(e), "error_type": type(e).__name__}, + } + yield ( + "workflow_failed", + normalize_final(failed, workflow_id=None, thread_id=thread_id), + ) def _request_to_input(self, request: dict) -> Dict[str, Any]: # type: ignore[type-arg] input_mapper = getattr(self, "_input_mapper", None) diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index 1a8f55a6..2094cee8 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -11,7 +11,7 @@ import itertools import uuid -from typing import Any, Dict, List, Tuple +from typing import Any, Dict, List, Optional, Tuple from langchain_core.load import dumpd @@ -169,3 +169,67 @@ def to_wire(mode: str, data: Any) -> Any: if mode in (MESSAGES, UPDATES): return dumpd(data) return data + + +# A finished workflow whose output says it did not get to the end of the graph. +FAILED_STATUSES = ("error", "max_steps_reached") +NO_RESULT_MESSAGE = "run ended without a result" + + +def failure_message(final: Dict[str, Any]) -> str: + """The human-readable reason a ``workflow_failed`` event carries.""" + error = final.get("error") + if isinstance(error, dict): + return str(error.get("message") or "Workflow failed") + return str(error) if error else "Workflow failed" + + +class GraphRunError(RuntimeError): + """A streamed run ended in failure; ``final`` is its terminal event.""" + + def __init__(self, final: Dict[str, Any]) -> None: + super().__init__(failure_message(final)) + self.final = final + + +def _failed(final: Dict[str, Any], message: str, error_type: str) -> Dict[str, Any]: + return { + **final, + "type": "workflow_failed", + "error": {"message": message, "error_type": error_type}, + } + + +def normalize_final( + final: Dict[str, Any], *, workflow_id: Optional[str], thread_id: str +) -> Dict[str, Any]: + """Turn whatever ended ``run_async`` into one terminal event. + + The result is a ``workflow_completed`` or ``workflow_failed`` event that + names the run. The workflow reports some failures as a completed run + (``status`` of ``error`` for a missing node or a failed condition, + ``max_steps_reached``); a run can also end terminated, errored, or with no + final event at all. None of those is a success. + """ + kind = final.get("type") + status = final.get("status") + if not final: + out = _failed({}, NO_RESULT_MESSAGE, "NoResult") + elif kind == "workflow_completed" and status in FAILED_STATUSES: + out = _failed( + final, + str(final.get("error") or f"Workflow ended with status {status!r}"), + "WorkflowStatus", + ) + elif kind == "workflow_error": + out = _failed( + final, str(final.get("error") or "Workflow error"), "WorkflowError" + ) + elif kind == "workflow_terminated": + out = _failed(final, "Workflow was terminated", "WorkflowTerminated") + else: + out = dict(final) + if workflow_id: + out.setdefault("workflow_id", workflow_id) + out.setdefault("thread_id", thread_id) + return out From ae111433702774b01266598819ac09baa732b37a Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Wed, 25 Nov 2026 23:55:59 +0100 Subject: [PATCH 04/73] feat(langgraph): keep updates under backpressure and report dropped or undelivered chunks Past the sink's buffer limit only "messages" and "custom" chunks are dropped. "updates", node resets and the close marker always get through. The sink counts what it dropped, logs the total when the run closes, and the terminal event and astream() report it as stream_dropped. An activity that finds no local sink, because it runs on another replica or after a restart, used to stream nothing without a trace. It now logs one warning per run, and the stream ends with stream_unavailable naming the steps nothing arrived for. Cross-replica delivery stays a follow-up. "stream" and "stream_mode" are now removed from the request only on the streaming path, so a graph with a state key of that name still works. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/stream.py | 58 ++++++++++++++++++++---- diagrid/agent/langgraph/runner.py | 64 +++++++++++++++++++++------ diagrid/agent/langgraph/streaming.py | 52 +++++++++++++++++++++- diagrid/agent/langgraph/workflow.py | 29 +++++++++++- 4 files changed, 177 insertions(+), 26 deletions(-) diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index a198b096..e3e29bfd 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -14,16 +14,26 @@ import json import logging import threading +from collections import OrderedDict from dataclasses import dataclass from typing import Any, Dict, Optional, Protocol, Tuple logger = logging.getLogger(__name__) -# Upper bound on buffered chunks per run; extra chunks are dropped (and logged -# once) so a slow consumer cannot grow memory without limit. +# Upper bound on buffered chunks per run. Past it, token and custom chunks are +# dropped (counted, and reported on the final event) so a slow consumer cannot +# grow memory without limit. Updates, node resets and the close marker are never +# dropped: they cannot be re-sent and are bounded by the size of the graph. MAX_BUFFERED_EVENTS = 10_000 NODE_RESET = "node_reset" +STREAM_UNAVAILABLE = "stream_unavailable" +STREAM_DROPPED = "stream_dropped" +# Events about the stream itself, delivered whatever stream modes were asked for. +CONTROL_MODES = (NODE_RESET, STREAM_UNAVAILABLE) + +# Runs remembered by StreamSinkRegistry.first_report; older ones are forgotten. +_MAX_REPORTED_RUNS = 1024 UPDATES = "updates" @@ -51,11 +61,13 @@ class StreamClosed: """Last item a sink hands its consumer: the run is over. ``final`` is the run's terminal event (``workflow_completed`` or - ``workflow_failed`` with its payload). + ``workflow_failed`` with its payload). ``dropped`` is how many chunks the + sink discarded because the consumer fell behind. """ def __init__(self, final: Optional[Dict[str, Any]] = None) -> None: self.final: Dict[str, Any] = final or {} + self.dropped = 0 class InProcessSink: @@ -78,7 +90,7 @@ def __init__(self, workflow_id: str, loop: asyncio.AbstractEventLoop) -> None: self._retired: set = set() self._last_seq: Dict[Tuple[str, int], int] = {} self._closed = False - self._warned_full = False + self._dropped = 0 def put(self, event: StreamEvent) -> None: key = (event.step, event.node) @@ -126,15 +138,23 @@ async def get(self) -> Any: def _enqueue(self, item: Any) -> None: def _put() -> None: - if self._queue.qsize() >= MAX_BUFFERED_EVENTS and not isinstance( - item, StreamClosed - ): - if not self._warned_full: - self._warned_full = True + # Runs on the loop thread in the order chunks were handed over, so + # the count on the close marker covers every chunk before it. + if isinstance(item, StreamClosed): + item.dropped = self._dropped + if self._dropped: + logger.warning( + "Stream %s dropped %d chunks: the consumer fell behind", + self.workflow_id, + self._dropped, + ) + elif self._queue.qsize() >= MAX_BUFFERED_EVENTS and not _is_control(item): + if not self._dropped: logger.warning( "Stream buffer for %s is full; dropping chunks", self.workflow_id, ) + self._dropped += 1 return self._queue.put_nowait(item) @@ -144,6 +164,11 @@ def _put() -> None: self._closed = True +def _is_control(item: Any) -> bool: + """Chunks that must not be dropped: they cannot be re-sent.""" + return isinstance(item, StreamEvent) and item.mode in (UPDATES, NODE_RESET) + + class StreamSinkRegistry: """The sinks of the streams open in this process, keyed by workflow id. @@ -156,6 +181,7 @@ class StreamSinkRegistry: def __init__(self) -> None: self._sinks: Dict[str, InProcessSink] = {} self._lock = threading.Lock() + self._reported: "OrderedDict[str, None]" = OrderedDict() def open(self, workflow_id: str) -> InProcessSink: """Register a sink for ``workflow_id`` on the running event loop. @@ -183,6 +209,20 @@ def close(self, workflow_id: str, sink: Optional[InProcessSink] = None) -> None: del self._sinks[workflow_id] current.close() + def first_report(self, workflow_id: str) -> bool: + """True the first time it is asked about ``workflow_id``. + + Lets an activity log a problem once per run instead of once per node. + Remembers the most recent runs only, so it cannot grow without limit. + """ + with self._lock: + if workflow_id in self._reported: + return False + self._reported[workflow_id] = None + while len(self._reported) > _MAX_REPORTED_RUNS: + self._reported.popitem(last=False) + return True + def get(self, workflow_id: Optional[str]) -> Optional[InProcessSink]: """The open sink for ``workflow_id``, or ``None``.""" if not workflow_id: diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 28f14eaf..3566bf05 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -15,6 +15,7 @@ Dict, List, Optional, + Set, Tuple, TYPE_CHECKING, ) @@ -24,7 +25,9 @@ from diagrid.agent.core.types.type import SupportedFrameworks from diagrid.agent.core.workflow import BaseWorkflowRunner from diagrid.agent.core.workflow.stream import ( - NODE_RESET, + CONTROL_MODES, + STREAM_DROPPED, + STREAM_UNAVAILABLE, StreamClosed, StreamEvent, StreamSinkRegistry, @@ -38,7 +41,9 @@ NodeConfig, ) from .streaming import ( + STREAM_RUN_KEY, GraphRunError, + stream_unavailable_event, normalize_final, normalize_stream_mode, to_wire, @@ -716,14 +721,18 @@ async def astream( poll_interval=poll_interval, ): if isinstance(item, StreamEvent): - if item.mode == NODE_RESET: - # Always delivered so a client can drop a failed attempt's - # partial output; a single mode yields it as a tuple too. - yield (NODE_RESET, item.data) + if item.mode in CONTROL_MODES: + # Always delivered, as a tuple even for a single mode: + # node_reset lets a client drop a failed attempt's partial + # output, stream_unavailable says chunks went missing. + yield (item.mode, item.data) elif item.mode in modes: yield (item.mode, item.data) if is_list else item.data - elif item.get("type") == "workflow_failed": - raise GraphRunError(item) + else: + if item.get("dropped"): + yield (STREAM_DROPPED, {"dropped": item["dropped"]}) + if item.get("type") == "workflow_failed": + raise GraphRunError(item) async def _stream_events( self, @@ -744,6 +753,7 @@ async def _stream_events( workflow_id = workflow_id or f"graph-{thread_id}-{uuid.uuid4().hex[:8]}" sink = self._stream_registry.open(workflow_id) task: Optional["asyncio.Task[None]"] = None + seen_steps: Set[int] = set() async def _pump() -> None: final: Dict[str, Any] = {} @@ -751,7 +761,7 @@ async def _pump() -> None: async for event in self.run_async( input, thread_id=thread_id, - config=dict(config) if config else None, + config={**(config or {}), STREAM_RUN_KEY: True}, workflow_id=workflow_id, poll_interval=poll_interval, ): @@ -775,8 +785,23 @@ async def _pump() -> None: # Unregister before handing over the result: chunks a late # activity attempt writes from here on are dropped. self._stream_registry.close(workflow_id, sink) - yield item.final + unavailable = stream_unavailable_event( + item.final, seen_steps, workflow_id + ) + if unavailable is not None: + logger.warning( + "Streamed run %s: no chunks for steps %s", + workflow_id, + unavailable.data["missing_steps"], + ) + yield unavailable + yield ( + {**item.final, "dropped": item.dropped} + if item.dropped + else item.final + ) return + seen_steps.add(item.step) yield item finally: # Also reached when the consumer goes away (client disconnect, @@ -871,7 +896,7 @@ async def _serve_stream( # type: ignore[override] modes, _ = normalize_stream_mode( request.get("stream_mode") or ["messages", "updates", "custom"] ) - graph_input = self._request_to_input(request) + graph_input = self._request_to_input(request, streaming=True) async for item in self._stream_events( graph_input, config=None, @@ -880,7 +905,7 @@ async def _serve_stream( # type: ignore[override] poll_interval=0.5, ): if isinstance(item, StreamEvent): - if item.mode != NODE_RESET and item.mode not in modes: + if item.mode not in CONTROL_MODES and item.mode not in modes: continue yield item.mode, to_wire(item.mode, item.data) else: @@ -896,11 +921,24 @@ async def _serve_stream( # type: ignore[override] normalize_final(failed, workflow_id=None, thread_id=thread_id), ) - def _request_to_input(self, request: dict) -> Dict[str, Any]: # type: ignore[type-arg] + def _request_to_input( + self, + request: dict, # type: ignore[type-arg] + *, + streaming: bool = False, + ) -> Dict[str, Any]: + """Map a ``POST /agent/run`` body to the graph's input. + + ``stream`` and ``stream_mode`` are transport keys of a streaming + request and are removed from it (before an ``input_mapper`` sees it, or + not) so they never reach the graph. On a plain request they are left + alone: a graph may have a state key of that name. + """ + if streaming: + request = {k: v for k, v in request.items() if k not in _TRANSPORT_KEYS} input_mapper = getattr(self, "_input_mapper", None) if input_mapper: return input_mapper(request) # type: ignore[no-any-return] - request = {k: v for k, v in request.items() if k not in _TRANSPORT_KEYS} if "messages" not in request: task = request.get("task") if task: diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index 2094cee8..241ee17e 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -11,17 +11,25 @@ import itertools import uuid -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Set, Tuple from langchain_core.load import dumpd -from diagrid.agent.core.workflow.stream import StreamEvent, StreamSink +from diagrid.agent.core.workflow.stream import ( + STREAM_UNAVAILABLE, + StreamEvent, + StreamSink, +) MESSAGES = "messages" UPDATES = "updates" CUSTOM = "custom" SUPPORTED_MODES = (MESSAGES, UPDATES, CUSTOM) +# Set in the workflow config of a run someone is streaming, so an activity that +# finds no sink to write to knows that is a problem and not just a plain run. +STREAM_RUN_KEY = "diagrid_streamed" + class NodeStreamer: """Streams one activity attempt of one node into a sink.""" @@ -233,3 +241,43 @@ def normalize_final( out.setdefault("workflow_id", workflow_id) out.setdefault("thread_id", thread_id) return out + + +UNAVAILABLE_REASON = ( + "No chunks arrived for the listed steps: their node activities ran in " + "another process (several replicas) or before this stream was opened. " + "Streaming only works while the activities run in the process that serves " + "the stream; the run's result is complete." +) + + +def stream_unavailable_event( + final: Dict[str, Any], seen_steps: Set[int], workflow_id: str +) -> Optional[StreamEvent]: + """The ``stream_unavailable`` event for a finished run, if it applies. + + Every node that runs here sends at least its ``updates`` chunk, so a step + of a completed run from which nothing arrived had its activities elsewhere. + A run that failed is just a failure, and one with no step count (or none + run) has nothing to report. + """ + steps = final.get("steps") + if final.get("type") != "workflow_completed" or not isinstance(steps, int): + return None + missing = [step for step in range(steps) if step not in seen_steps] + if not missing: + return None + return StreamEvent( + workflow_id=workflow_id, + step=missing[0], + node="", + attempt_id="", + seq=0, + ns=(), + mode=STREAM_UNAVAILABLE, + data={ + "workflow_id": workflow_id, + "reason": UNAVAILABLE_REASON, + "missing_steps": missing, + }, + ) diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index f7adb581..bd2a7b63 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -30,9 +30,13 @@ CONFIG_KEY_RUNTIME = "__pregel_runtime" CONF = "configurable" -from diagrid.agent.core.workflow.stream import StreamSinkRegistry, get_stream_sink +from diagrid.agent.core.workflow.stream import ( + StreamSinkRegistry, + default_registry, + get_stream_sink, +) -from .streaming import NodeStreamer +from .streaming import STREAM_RUN_KEY, NodeStreamer from .models import ( ChannelState, ExecuteNodeInput, @@ -490,6 +494,23 @@ def _is_async_only(runnable: Any) -> bool: ) +def _warn_stream_sink_missing( + registry: StreamSinkRegistry, workflow_id: str, node_name: str +) -> None: + """Say, once per run, that a streamed run's chunks are going nowhere.""" + if not registry.first_report(workflow_id): + return + logger.warning( + "Run %s is streamed but this process has no stream sink for it, so the " + "chunks of node %r (and of any node that runs here) are not delivered. " + "The activity is running in another process (several replicas) or the " + "run outlived the process that streams it. Cross-replica streaming is " + "not supported yet; the run itself is unaffected.", + workflow_id, + node_name, + ) + + def execute_node_activity( ctx: WorkflowActivityContext, input_data: Dict[str, Any], @@ -537,6 +558,10 @@ def execute_node_activity( # Stream chunks only when a consumer registered a sink for this run; # otherwise nothing below changes. sink = get_stream_sink(getattr(ctx, "workflow_id", None), registry=stream_registry) + if sink is None and config.get(STREAM_RUN_KEY): + _warn_stream_sink_missing( + stream_registry or default_registry, str(ctx.workflow_id), node_name + ) streamer = ( NodeStreamer( sink, From 3a4e421b7eb33d9a95df4237d54982cfe28b3c29 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Wed, 25 Nov 2026 23:56:08 +0100 Subject: [PATCH 05/73] feat(langgraph): close streams when the consumer leaves and match native astream chunks A caller that stopped iterating astream(), or an HTTP client that hung up, left the run's sink registered and kept filling its buffer. Both now close the inner stream. A streamed run's result is still published to the topic when the client disconnects mid-run, and in the same shape a plain call publishes. Chunks now follow native LangGraph more closely. Several threads of one node can emit at once without losing chunks, get_stream_writer() is a no-op in a run that is not streamed, values that are not LangChain objects are sent as plain data, "messages" metadata carries thread_id and the other configurable values, and control events (node_reset, stream_unavailable, stream_dropped) never appear in a single-mode astream. The node activity helpers are split out of the activity, and the README documents streaming, its single-replica limit and what a disconnect does. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 73 +++--- diagrid/agent/core/workflow/stream.py | 7 +- diagrid/agent/langgraph/README.md | 68 +++++ diagrid/agent/langgraph/runner.py | 132 +++++++--- diagrid/agent/langgraph/streaming.py | 117 +++++++-- diagrid/agent/langgraph/workflow.py | 344 ++++++++++++++++---------- 6 files changed, 511 insertions(+), 230 deletions(-) diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 59153056..7fdff711 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -10,7 +10,7 @@ from abc import ABC, abstractmethod from contextlib import asynccontextmanager from importlib import metadata -from typing import Any, AsyncIterator, Optional, Tuple +from typing import Any, AsyncIterator, Callable, Optional, Tuple from dapr.ext.workflow import DaprWorkflowClient, WorkflowRuntime, WorkflowStatus from dapr_agents.utils.signal.mixin import SignalMixin @@ -53,8 +53,22 @@ def report_usage(package: str, **dimensions: object) -> None: } -#: Event names that end a streamed run; the data of the last one is the result. -_TERMINAL_EVENTS = ("workflow_completed", "workflow_failed") +def fold_run_event(result: dict, event: dict) -> bool: # type: ignore[type-arg] + """Fold one event of a run into ``result``, the body of ``POST /agent/run``. + + Returns ``True`` when ``event`` is the run's last. The same fold builds the + returned body of a plain call and the result published for a streamed one, + so the two cannot drift apart. + """ + kind = event["type"] + if kind == "workflow_started": + result["instance_id"] = event["workflow_id"] + if event.get("thread_id"): + result["thread_id"] = event["thread_id"] + elif kind in ("workflow_completed", "workflow_failed"): + result.update(event) + return True + return False def _framework_version(framework: str) -> Optional[str]: @@ -392,6 +406,16 @@ def serve( Creates a FastAPI app, calls ``_setup_telemetry()``, starts the runtime, and registers POST/GET ``/agent/run`` endpoints. + A runner that supports it (the LangGraph runner does) answers + ``POST /agent/run`` with ``"stream": true`` as server-sent events. The + keys ``stream`` and ``stream_mode`` are reserved on such a request. The + last event is ``workflow_completed`` or ``workflow_failed``; its data is + also what gets published to ``publish_topic``. Streaming works while the + node activities run in the serving process (single replica; see the + runner's README). A client that disconnects ends the stream but not the + workflow, which keeps running; with ``publish_topic`` set its result is + still published when the run ends. + When pub/sub parameters are provided, also registers Dapr programmatic subscription endpoints so the agent can receive tasks via pub/sub and publish results. @@ -438,15 +462,7 @@ async def _run_and_collect(request: dict) -> dict: # type: ignore[type-arg] async for event in runner_ref._serve_run( request=request, session_id=session_id ): - if event["type"] == "workflow_started": - result["instance_id"] = event["workflow_id"] - if event.get("thread_id"): - result["thread_id"] = event["thread_id"] - elif event["type"] == "workflow_completed": - result.update(event) - break - elif event["type"] == "workflow_failed": - result.update(event) + if fold_run_event(result, event): break _publish_result(result) @@ -461,33 +477,26 @@ def _publish_result(result: dict) -> None: # type: ignore[type-arg] except Exception as e: logger.error("Failed to publish result: %s", str(e)) - async def _frame_and_publish( - events: AsyncIterator[Tuple[str, Any]], - ) -> AsyncIterator[str]: - """Frame ``(event, data)`` pairs as SSE; publish the terminal one. + async def _frame(events: AsyncIterator[Tuple[str, Any]]) -> AsyncIterator[str]: + """Frame ``(event, data)`` pairs as SSE. - The only place a streamed run is turned into SSE frames and into - the published result, so a runner just yields pairs. + The only place a streamed run is turned into SSE frames, so a runner + just yields pairs. Publishing is the runner's job (``on_result``). """ - final: Optional[dict[str, Any]] = None event_id = 0 try: async for name, data in events: event_id += 1 yield format_sse(name, data, event_id) - if name in _TERMINAL_EVENTS and isinstance(data, dict): - final = data finally: # A client that disconnects ends the generator at a yield; close # the runner's stream now rather than when it is collected. aclose = getattr(events, "aclose", None) if aclose is not None: await aclose() - if final is not None: - result = dict(final) - if final.get("workflow_id"): - result["instance_id"] = final["workflow_id"] - _publish_result(result) + + # Only a run that is published needs to outlive its client. + on_result = _publish_result if pubsub_client else None @app.post("/agent/run") async def run_agent(request: dict) -> Any: # type: ignore[type-arg] @@ -497,7 +506,9 @@ async def run_agent(request: dict) -> Any: # type: ignore[type-arg] request.get("thread_id", uuid.uuid4().hex[:8]), ) return StreamingResponse( - _frame_and_publish(self._serve_stream(request, session_id)), + _frame( + self._serve_stream(request, session_id, on_result=on_result) + ), media_type="text/event-stream", ) return await _run_and_collect(request) @@ -589,12 +600,16 @@ def _serve_stream( self, request: dict, # type: ignore[type-arg] session_id: str, + on_result: Optional[Callable[[dict], None]] = None, # type: ignore[type-arg] ) -> AsyncIterator[Tuple[str, Any]]: """Yield ``(event_name, data)`` pairs for a run. Opt-in per runner. The last pair is ``workflow_completed`` or ``workflow_failed`` with the - run's terminal event as data. Framing as SSE and publishing the result - are done by ``serve()``, not here. + run's terminal event as data. Framing as SSE is done by ``serve()``. + + ``on_result`` is how a run gets published: the runner calls it once + with the same result a plain ``POST /agent/run`` would return (see + :func:`fold_run_event`) when the run ends. """ raise NotImplementedError diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index e3e29bfd..beba134f 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -39,7 +39,7 @@ @dataclass(frozen=True) class StreamEvent: - """One chunk, wrapped with enough identity to order and de-duplicate it.""" + """One chunk, wrapped with enough identity to order it and tell attempts apart.""" workflow_id: str step: int @@ -88,7 +88,6 @@ def __init__(self, workflow_id: str, loop: asyncio.AbstractEventLoop) -> None: self._owner: Dict[Tuple[int, str], str] = {} self._finished: Dict[Tuple[int, str], str] = {} self._retired: set = set() - self._last_seq: Dict[Tuple[str, int], int] = {} self._closed = False self._dropped = 0 @@ -101,10 +100,6 @@ def put(self, event: StreamEvent) -> None: return if (key, event.attempt_id) in self._retired: return - seq_key = (event.attempt_id, event.step) - if event.seq <= self._last_seq.get(seq_key, -1): - return - self._last_seq[seq_key] = event.seq owner = self._owner.get(key) if owner is not None and owner != event.attempt_id: self._retired.add((key, owner)) diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 1f4c4d42..19398a4f 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -88,6 +88,74 @@ async def main(): asyncio.run(main()) ``` +## Streaming + +`astream` yields what `CompiledStateGraph.astream` yields, while each node runs +as a Dapr activity: LLM tokens (`messages`), node updates (`updates`) and +whatever a node writes with `get_stream_writer()` (`custom`). + +```python +async for mode, chunk in runner.astream( + {"messages": [{"role": "user", "content": "hi"}]}, + stream_mode=["messages", "updates", "custom"], +): + if mode == "messages": + message_chunk, metadata = chunk + print(message_chunk.content, end="") +``` + +A single mode yields bare chunks, as native `astream` does, and a list of modes +yields `(mode, chunk)`. Events about the stream itself are `StreamControl` +objects (`kind`, `data`): + +| `kind` | `data` | Meaning | +|---|---|---| +| `node_reset` | `{"node", "step"}` | A node was retried; drop its partial output. | +| `stream_unavailable` | `{"workflow_id", "reason", "missing_steps"}` | The run finished but nothing arrived for those steps (see the limit below). | +| `stream_dropped` | `{"dropped": n}` | The consumer fell behind and `n` token or custom chunks were dropped. `updates` are never dropped. | + +Pass `on_control=callback` to `astream` to receive them. A list of modes also +yields them as `(kind, data)` tuples; a single mode never does, so +`async for message, metadata in runner.astream(..., stream_mode="messages")` +never meets one. + +A run that fails (a node or condition error, max steps, a terminated workflow, +no result) raises `GraphRunError`; its `.final` is the full terminal event. +LangGraph merges the nodes of a parallel step into one `updates` chunk; here each +node yields its own. + +### Over HTTP + +`serve()` answers `POST /agent/run` with `"stream": true` as server-sent events. +`stream_mode` (a mode or a list; default all three) picks the chunks. The +messages and updates are serialized with `langchain_core.load.dumpd`, so +`langchain_core.load.load` restores them. The stream ends with +`workflow_completed` or `workflow_failed`; both carry `workflow_id` and +`thread_id`, a failure carries the error, and `dropped` is set when chunks were +dropped. The run's result is also published to `publish_topic`; it is exactly what +a non-streaming call returns and publishes for the same run, so a run that ends +with `status: "error"` is published as that call reports it (`workflow_completed` +with the error string) even though the stream's last event is `workflow_failed`. + +`stream` and `stream_mode` are reserved keys on a streaming request: they are +removed before the graph (or your `input_mapper`) sees it. On a plain request +they are left alone. + +### Limits + +- **Single replica.** Chunks travel from the activity to the HTTP connection + through an in-process queue. If an activity runs in another process (several + replicas of the app, or after a restart) its chunks are not delivered: the + activity logs a warning once per run and the stream sends `stream_unavailable` + before it ends. The run and its result are not affected. Delivery across + replicas is not implemented yet. +- **A disconnect does not cancel the run.** When the client goes away the stream + is closed, but the Dapr workflow keeps running to completion. Terminate it with + `terminate_workflow` if you need it stopped. + When `publish_topic` is set, the server keeps following the run after the + client left and publishes its result when it ends, as it does for a client + that stays. + ## Architecture ```text diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 3566bf05..fc9bedfc 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -8,8 +8,10 @@ import logging import time import uuid +from contextlib import aclosing from typing import ( Any, + AsyncGenerator, AsyncIterator, Callable, Dict, @@ -24,6 +26,7 @@ from diagrid.agent.core.types.type import SupportedFrameworks from diagrid.agent.core.workflow import BaseWorkflowRunner +from diagrid.agent.core.workflow.runner import fold_run_event from diagrid.agent.core.workflow.stream import ( CONTROL_MODES, STREAM_DROPPED, @@ -43,6 +46,7 @@ from .streaming import ( STREAM_RUN_KEY, GraphRunError, + StreamControl, stream_unavailable_event, normalize_final, normalize_stream_mode, @@ -171,6 +175,9 @@ def __init__( self._stream_registry = ( stream_registry if stream_registry is not None else StreamSinkRegistry() ) + # Pumps of streams whose consumer left while a result is still to be + # published; held here so they are not collected before they finish. + self._detached_pumps: Set["asyncio.Task[None]"] = set() super().__init__( name, @@ -693,14 +700,27 @@ async def astream( stream_mode: Any = "updates", subgraphs: bool = False, poll_interval: float = 0.5, + on_control: Optional[Callable[[StreamControl], None]] = None, ) -> AsyncIterator[Any]: """Stream a run like ``CompiledStateGraph.astream``. Supports ``messages``, ``updates`` and ``custom``. A single mode - yields bare chunks; a list of modes yields ``(mode, chunk)`` tuples. - When a retried node restarts, a ``("node_reset", {...})`` tuple is - yielded in either form; discard that node's partial output. Streaming - works when the node activities run in this process (single replica). + yields bare chunks, as native ``astream`` does, and a list of modes + yields ``(mode, chunk)`` tuples. + + Events about the stream itself are :class:`StreamControl` objects: + ``node_reset`` (a node was retried; discard its partial output), + ``stream_unavailable`` (the run finished but chunks for some of its + nodes never arrived: streaming works only when the node activities run + in this process, i.e. a single replica) and ``stream_dropped`` (the + consumer fell behind; ``{"dropped": n}``). Pass ``on_control`` to + receive them. A list of modes also yields them as ``(kind, data)`` + tuples; a single mode never does, so a consumer written against native + ``astream`` (``async for message, metadata in ...``) cannot trip over + one. A run that fails raises :class:`GraphRunError`. + + Stopping early (``break``, ``aclose()``) closes the stream but does not + cancel the Dapr workflow, which runs to completion. Chunks have the shape ``CompiledStateGraph.astream`` yields: ``messages`` are ``(message_chunk, metadata)`` and ``updates`` are @@ -713,26 +733,38 @@ async def astream( if subgraphs: raise NotImplementedError("subgraphs=True is not supported yet") modes, is_list = normalize_stream_mode(stream_mode) - async for item in self._stream_events( - input, - config=config, - thread_id=thread_id, - workflow_id=workflow_id, - poll_interval=poll_interval, - ): - if isinstance(item, StreamEvent): - if item.mode in CONTROL_MODES: - # Always delivered, as a tuple even for a single mode: - # node_reset lets a client drop a failed attempt's partial - # output, stream_unavailable says chunks went missing. - yield (item.mode, item.data) - elif item.mode in modes: - yield (item.mode, item.data) if is_list else item.data - else: - if item.get("dropped"): - yield (STREAM_DROPPED, {"dropped": item["dropped"]}) - if item.get("type") == "workflow_failed": - raise GraphRunError(item) + # aclosing: if the caller stops early, close the inner stream now (it + # unregisters the sink) instead of whenever the garbage collector runs. + async with aclosing( + self._stream_events( + input, + config=config, + thread_id=thread_id, + workflow_id=workflow_id, + poll_interval=poll_interval, + ) + ) as events: + async for item in events: + if isinstance(item, StreamEvent): + if item.mode in CONTROL_MODES: + control = StreamControl(item.mode, item.data) + if on_control is not None: + on_control(control) + if is_list: + yield (control.kind, control.data) + elif item.mode in modes: + yield (item.mode, item.data) if is_list else item.data + else: + if item.get("dropped"): + control = StreamControl( + STREAM_DROPPED, {"dropped": item["dropped"]} + ) + if on_control is not None: + on_control(control) + if is_list: + yield (control.kind, control.data) + if item.get("type") == "workflow_failed": + raise GraphRunError(item) async def _stream_events( self, @@ -742,12 +774,17 @@ async def _stream_events( thread_id: Optional[str], workflow_id: Optional[str], poll_interval: float, - ) -> AsyncIterator[Any]: + on_result: Optional[Callable[[Dict[str, Any]], None]] = None, + ) -> AsyncGenerator[Any, None]: """Yield ``StreamEvent`` chunks, then the terminal event dict. The terminal event is always the last item: ``workflow_completed`` or ``workflow_failed`` (see :func:`normalize_final`), carrying the run's ``workflow_id`` and ``thread_id``. + + ``on_result`` is called once, when the run ends, with the result a plain + ``POST /agent/run`` would return for it (not the normalized terminal + event), so a streamed run publishes exactly what a plain one does. """ thread_id = thread_id or str(uuid.uuid4()) workflow_id = workflow_id or f"graph-{thread_id}-{uuid.uuid4().hex[:8]}" @@ -757,6 +794,7 @@ async def _stream_events( async def _pump() -> None: final: Dict[str, Any] = {} + result: Dict[str, Any] = {} try: async for event in self.run_async( input, @@ -765,8 +803,11 @@ async def _pump() -> None: workflow_id=workflow_id, poll_interval=poll_interval, ): + fold_run_event(result, event) if event["type"] in _FINAL_EVENTS: final = event + if on_result is not None: + on_result(result) except Exception as e: logger.exception("Streamed run %s failed", workflow_id) final = { @@ -809,8 +850,14 @@ async def _pump() -> None: # workflow itself keeps running to completion. self._stream_registry.close(workflow_id, sink) if task is not None and not task.done(): - task.cancel() - await asyncio.gather(task, return_exceptions=True) + if on_result is not None: + # Someone is waiting for the result on a topic: let the + # pump finish the run and hand it over, with no consumer. + self._detached_pumps.add(task) + task.add_done_callback(self._detached_pumps.discard) + else: + task.cancel() + await asyncio.gather(task, return_exceptions=True) def _serialize_input(self, input: Dict[str, Any]) -> Dict[str, Any]: """Serialize input values for storage.""" @@ -883,6 +930,7 @@ async def _serve_stream( # type: ignore[override] self, request: dict, # type: ignore[type-arg] session_id: str, + on_result: Optional[Callable[[Dict[str, Any]], None]] = None, ) -> AsyncIterator[Tuple[str, Any]]: """Run the graph and yield its stream as ``(event_name, data)`` pairs. @@ -897,19 +945,23 @@ async def _serve_stream( # type: ignore[override] request.get("stream_mode") or ["messages", "updates", "custom"] ) graph_input = self._request_to_input(request, streaming=True) - async for item in self._stream_events( - graph_input, - config=None, - thread_id=thread_id, - workflow_id=None, - poll_interval=0.5, - ): - if isinstance(item, StreamEvent): - if item.mode not in CONTROL_MODES and item.mode not in modes: - continue - yield item.mode, to_wire(item.mode, item.data) - else: - yield item["type"], item + async with aclosing( + self._stream_events( + graph_input, + config=None, + thread_id=thread_id, + workflow_id=None, + poll_interval=0.5, + on_result=on_result, + ) + ) as events: + async for item in events: + if isinstance(item, StreamEvent): + if item.mode not in CONTROL_MODES and item.mode not in modes: + continue + yield item.mode, to_wire(item.mode, item.data) + else: + yield item["type"], item except Exception as e: logger.exception("Streaming run failed") failed = { diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index 241ee17e..5379a855 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -10,10 +10,13 @@ """ import itertools +import threading import uuid +from dataclasses import dataclass from typing import Any, Dict, List, Optional, Set, Tuple from langchain_core.load import dumpd +from langchain_core.load.serializable import Serializable from diagrid.agent.core.workflow.stream import ( STREAM_UNAVAILABLE, @@ -26,11 +29,27 @@ CUSTOM = "custom" SUPPORTED_MODES = (MESSAGES, UPDATES, CUSTOM) +# Configurable keys LangChain never copies into metadata (they are secrets). +_UNTRACED_CONFIGURABLE = frozenset(("api_key",)) + # Set in the workflow config of a run someone is streaming, so an activity that # finds no sink to write to knows that is a problem and not just a plain run. STREAM_RUN_KEY = "diagrid_streamed" +@dataclass(frozen=True) +class StreamControl: + """An event about the stream itself rather than a chunk of the run. + + ``kind`` is ``node_reset``, ``stream_unavailable`` or ``stream_dropped``; + ``data`` is its payload. ``astream`` hands these to its ``on_control`` + callback, and in list mode also yields them as ``(kind, data)``. + """ + + kind: str + data: Dict[str, Any] + + class NodeStreamer: """Streams one activity attempt of one node into a sink.""" @@ -42,14 +61,19 @@ def __init__( step: int, node: str, task_id: Any, + thread_id: Optional[str] = None, ) -> None: self._sink = sink + self._thread_id = thread_id self._workflow_id = workflow_id self._step = step self._node = node self._task_id = task_id self._attempt_id = uuid.uuid4().hex self._seq = itertools.count() + # A node may emit from several threads (parallel tool calls); seq is + # taken and the chunk handed over under one lock so they stay in order. + self._emit_lock = threading.Lock() self._handler: Any = None self._run_id = uuid.uuid4() @@ -67,18 +91,19 @@ def metadata(self) -> Dict[str, Any]: } def _emit(self, ns: Tuple[str, ...], mode: str, data: Any) -> None: - self._sink.put( - StreamEvent( - workflow_id=self._workflow_id, - step=self._step, - node=self._node, - attempt_id=self._attempt_id, - seq=next(self._seq), - ns=tuple(ns), - mode=mode, - data=data, + with self._emit_lock: + self._sink.put( + StreamEvent( + workflow_id=self._workflow_id, + step=self._step, + node=self._node, + attempt_id=self._attempt_id, + seq=next(self._seq), + ns=tuple(ns), + mode=mode, + data=data, + ) ) - ) def _on_chunk(self, chunk: Tuple[Any, ...]) -> None: """Receive ``(ns, mode, payload)`` from ``StreamMessagesHandler``.""" @@ -113,6 +138,13 @@ def node_started(self, node_input: Any) -> None: def node_finished(self, output: Any) -> None: self._messages_handler().on_chain_end(output, run_id=self._run_id) + def node_failed(self, error: BaseException) -> None: + """Close the chain run :meth:`node_started` opened. + + Without it the message handler keeps that run's state for good. + """ + self._messages_handler().on_chain_error(error, run_id=self._run_id) + def writer(self, chunk: Any) -> None: """``Runtime.stream_writer``: what ``get_stream_writer()`` returns.""" self._emit((), CUSTOM, chunk) @@ -149,9 +181,31 @@ def patch_config(self, config: Dict[str, Any]) -> Dict[str, Any]: for handler in self.callbacks(): callbacks.add_handler(handler, inherit=True) patched["callbacks"] = callbacks - patched["metadata"] = {**(patched.get("metadata") or {}), **self.metadata} + patched["metadata"] = { + **self._configurable_metadata(patched), + **(patched.get("metadata") or {}), + **self.metadata, + } return patched + def _configurable_metadata(self, config: Dict[str, Any]) -> Dict[str, Any]: + """What native LangGraph copies from ``configurable`` into metadata. + + ``thread_id`` and the other primitive, non-private configurable values, + so a client keying on ``metadata["thread_id"]`` sees what it would + from ``CompiledStateGraph.astream``. + """ + derived = { + key: value + for key, value in (config.get("configurable") or {}).items() + if not key.startswith("__") + and isinstance(value, (str, int, float, bool)) + and key not in _UNTRACED_CONFIGURABLE + } + if self._thread_id: + derived.setdefault("thread_id", self._thread_id) + return derived + def normalize_stream_mode(stream_mode: Any) -> Tuple[List[str], bool]: """Return ``(modes, is_list)``; reject modes the runner cannot provide.""" @@ -166,16 +220,43 @@ def normalize_stream_mode(stream_mode: Any) -> Tuple[List[str], bool]: return modes, is_list +def _plain_data(value: Any) -> Any: + """``value`` with everything but LangChain objects reduced to plain data. + + ``dumpd`` replaces what it cannot serialize (a pydantic model, a datetime, + a UUID) with a ``not_implemented`` stub that holds only a repr. Leaves go + through the same fallback the run's final output uses + (``workflow._serialize_value``) so a client sees the same data in a chunk + and in the final event. ``Serializable`` objects (messages, documents) stay + as they are for ``dumpd`` to turn into their ``load()``-able form. + """ + if value is None or isinstance(value, (str, int, float, bool)): + return value + if isinstance(value, Serializable): + return value + if isinstance(value, (list, tuple)): + return [_plain_data(v) for v in value] + if isinstance(value, dict): + return {k: _plain_data(v) for k, v in value.items()} + from diagrid.agent.langgraph.workflow import _serialize_value + + reduced = _serialize_value(value) + # A model dumps to a dict that can still hold a datetime or a UUID. + return str(value) if reduced is value else _plain_data(reduced) + + def to_wire(mode: str, data: Any) -> Any: """JSON-ready form of a chunk for a transport. - ``messages`` and ``updates`` carry LangChain objects; ``dumpd`` turns them - into the form ``langchain_core.load.load`` restores, so a client sees the - same objects an in-process ``astream`` consumer does. Other chunks (the - ``custom`` payload a node chose to write, control events) go as they are. + ``messages``, ``updates`` and ``custom`` chunks can carry LangChain objects + next to arbitrary values a node chose to return or write. ``dumpd`` turns + the objects into the form ``langchain_core.load.load`` restores, so a client + sees the same objects an in-process ``astream`` consumer does; everything + else becomes plain data first (see :func:`_plain_data`). Control events go + as they are. """ - if mode in (MESSAGES, UPDATES): - return dumpd(data) + if mode in (MESSAGES, UPDATES, CUSTOM): + return dumpd(_plain_data(data)) return data diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index bd2a7b63..0bbfd6bd 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -6,6 +6,7 @@ import contextlib import logging from datetime import timedelta +from dataclasses import dataclass from typing import Any, Callable, Dict, Generator, List, Optional, Tuple from dapr.ext.workflow import ( @@ -494,6 +495,184 @@ def _is_async_only(runnable: Any) -> bool: ) +@dataclass +class _NodeCall: + """Everything one execution of a node needs, gathered by the activity.""" + + ctx: WorkflowActivityContext + node_input: ExecuteNodeInput + node_func: Callable + state: Dict[str, Any] + config: Dict[str, Any] + streamer: Optional[NodeStreamer] + #: Side-channel writes queued via CONFIG_KEY_SEND while the node runs. + pending_sends: list + + @property + def node_name(self) -> str: + return self.node_input.node_name + + @property + def stream_writer(self) -> Optional[Callable[[Any], None]]: + return self.streamer.writer if self.streamer else None + + +def _make_activity_read( + channel_state: ChannelState, pending_sends: list +) -> Callable[..., Any]: + """Stand-in for CONFIG_KEY_READ inside a Dapr activity. + + In normal LangGraph execution the Pregel engine injects a read + function bound to live BaseChannel objects. Here the activity + only has a serialized ``channel_state``, so we read from that. + """ + + def _activity_read(select: Any, fresh: bool = False) -> Any: + if fresh: + # Apply any pending sends to a snapshot before reading. + merged = dict(channel_state.values) + for ch, val in pending_sends: + reducer = get_channel_reducer(ch) + if reducer and ch in merged: + try: + merged[ch] = reducer(merged[ch], val) + except Exception: + merged[ch] = val + else: + merged[ch] = val + source = merged + else: + source = channel_state.values + + if isinstance(select, str): + return source.get(select) + return {k: source.get(k) for k in select if k in source} + + return _activity_read + + +def _await_if_coroutine(r: Any) -> Any: + """Run ``r`` to completion on a private loop if it is a coroutine.""" + import asyncio + + if asyncio.iscoroutine(r): + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + r = loop.run_until_complete(r) + finally: + loop.close() + return r + + +def _runnable_config(call: _NodeCall) -> Dict[str, Any]: + """The config a Runnable node is invoked with. + + Copies before mutating so we never write back into the shared config dict + handed to this activity (immutability). + """ + _config = dict(call.config) if call.config else {} + _config[CONF] = dict(_config.get(CONF) or {}) + + thread_id = ( + call.node_input.thread_id + or _config.get("thread_id") + or getattr(call.ctx, "workflow_id", None) + ) + # Expose thread_id in the conventional LangGraph location too, + # so middleware reading config["configurable"]["thread_id"] works. + _config[CONF].setdefault("thread_id", thread_id) + + # Ensure the config has a Runtime object for deep agent middleware nodes + # that require it (runtime injection via RunnableCallable). It also lets + # sandbox/state backends resolve which workflow owns a tool call via + # runtime.execution_info.thread_id. + if CONFIG_KEY_RUNTIME not in _config[CONF]: + _config[CONF][CONFIG_KEY_RUNTIME] = _build_node_runtime( + thread_id, call.ctx, call.node_name, call.stream_writer + ) + if call.streamer: + _config = call.streamer.patch_config(_config) + + # Inject CONFIG_KEY_READ / CONFIG_KEY_SEND so that deepagents + # StateBackend (sandbox tools) can read/write the "files" + # channel when running inside a Dapr workflow activity. + try: + from langgraph._internal._constants import ( + CONFIG_KEY_READ, + CONFIG_KEY_SEND, + ) + + _config[CONF][CONFIG_KEY_READ] = _make_activity_read( + call.node_input.channel_state, call.pending_sends + ) + _config[CONF][CONFIG_KEY_SEND] = call.pending_sends.extend + except ImportError: + pass + return _config + + +def _invoke_runnable(call: _NodeCall, config: Dict[str, Any]) -> Any: + """Call a Runnable node; an async-only one returns a coroutine to await.""" + if _is_async_only(call.node_func): + return call.node_func.ainvoke(call.state, config=config) # type: ignore[attr-defined] + return call.node_func.invoke(call.state, config=config) # type: ignore[attr-defined] + + +def _call_plain(call: _NodeCall) -> Any: + """Call a plain function node (sync or async) and return its result.""" + sig = inspect.signature(call.node_func) + params = list(sig.parameters.keys()) + if len(params) >= 2 and "config" in params: + out = call.node_func(call.state, config=call.config) + else: + out = call.node_func(call.state) + return _await_if_coroutine(out) + + +def _plain_node_config(call: _NodeCall) -> Dict[str, Any]: + """Ambient config for a plain function node. + + Plain callables get no config injected, so what a node reaches through the + ambient config (``get_stream_writer()``, the stream handler and the task + metadata of a streamed run) is supplied here. Without a streamer the + runtime carries LangGraph's no-op writer, as ``invoke`` does natively. + """ + thread_id = call.node_input.thread_id or getattr(call.ctx, "workflow_id", None) + runtime = _build_node_runtime( + thread_id, call.ctx, call.node_name, call.stream_writer + ) + configurable = {**(call.config.get(CONF) or {}), CONFIG_KEY_RUNTIME: runtime} + config: Dict[str, Any] = {CONF: configurable} + return call.streamer.patch_config(config) if call.streamer else config + + +def _run_node(call: _NodeCall) -> Any: + """Run the node and return its raw result.""" + node_func = call.node_func + if hasattr(node_func, "invoke") and callable(getattr(node_func, "invoke")): + # A LangChain Runnable (e.g. RunnableCallable): call .invoke() so that + # argument injection (runtime, config, store) works. + node_config = _runnable_config(call) + + def run() -> Any: + return _await_if_coroutine(_invoke_runnable(call, node_config)) + + ambient = node_config + else: + + def run() -> Any: + return _call_plain(call) + + ambient = _plain_node_config(call) + + # RunnableCallable.invoke only sets the ambient config when tracing; + # get_stream_writer() and the stream handler need it, and a node that calls + # get_stream_writer() must find a (no-op) writer when the run is not streamed. + with set_config_context(ambient) as ctx_: # type: ignore[arg-type] + return ctx_.run(run) + + def _warn_stream_sink_missing( registry: StreamSinkRegistry, workflow_id: str, node_name: str ) -> None: @@ -550,7 +729,6 @@ def execute_node_activity( # Reconstruct state from channel values state = _reconstruct_state(node_input.channel_state) - channel_state = node_input.channel_state # Extract tracing config config = node_input.config or {} @@ -569,161 +747,53 @@ def execute_node_activity( step=node_input.step or 0, node=node_name, task_id=getattr(ctx, "task_id", ""), + thread_id=node_input.thread_id or config.get("thread_id"), ) if sink is not None else None ) - stream_writer = streamer.writer if streamer else None # Collect side-channel writes from CONFIG_KEY_SEND (used by StateBackend # to write to the "files" channel from sandbox tools). - pending_sends: list = [] - - def _activity_read(select: Any, fresh: bool = False) -> Any: - """Stand-in for CONFIG_KEY_READ inside a Dapr activity. - - In normal LangGraph execution the Pregel engine injects a read - function bound to live BaseChannel objects. Here the activity - only has a serialized ``channel_state``, so we read from that. - """ - if fresh: - # Apply any pending sends to a snapshot before reading. - merged = dict(channel_state.values) - for ch, val in pending_sends: - reducer = get_channel_reducer(ch) - if reducer and ch in merged: - try: - merged[ch] = reducer(merged[ch], val) - except Exception: - merged[ch] = val - else: - merged[ch] = val - source = merged - else: - source = channel_state.values - - if isinstance(select, str): - return source.get(select) - return {k: source.get(k) for k in select if k in source} - - def _run_node() -> Any: - # If the registered object is a LangChain Runnable (e.g. RunnableCallable), - # call .invoke() so that argument injection (runtime, config, store) works. - if hasattr(node_func, "invoke") and callable(getattr(node_func, "invoke")): - # Ensure the config has a Runtime object for deep agent middleware - # nodes that require it (runtime injection via RunnableCallable). - # Copy before mutating so we never write back into the shared - # config dict handed to this activity (immutability). - _config = dict(config) if config else {} - _config[CONF] = dict(_config.get(CONF) or {}) - - thread_id = ( - node_input.thread_id - or _config.get("thread_id") - or getattr(ctx, "workflow_id", None) - ) - # Expose thread_id in the conventional LangGraph location too, - # so middleware reading config["configurable"]["thread_id"] works. - _config[CONF].setdefault("thread_id", thread_id) - - # Populate the Runtime so sandbox/state backends can resolve which - # workflow owns a tool call via runtime.execution_info.thread_id. - if CONFIG_KEY_RUNTIME not in _config[CONF]: - _config[CONF][CONFIG_KEY_RUNTIME] = _build_node_runtime( - thread_id, ctx, node_name, stream_writer - ) - if streamer: - _config = streamer.patch_config(_config) - - # Inject CONFIG_KEY_READ / CONFIG_KEY_SEND so that deepagents - # StateBackend (sandbox tools) can read/write the "files" - # channel when running inside a Dapr workflow activity. - try: - from langgraph._internal._constants import ( - CONFIG_KEY_READ, - CONFIG_KEY_SEND, - ) - - _config[CONF][CONFIG_KEY_READ] = _activity_read - _config[CONF][CONFIG_KEY_SEND] = pending_sends.extend - except ImportError: - pass - - def _invoke() -> Any: - if _is_async_only(node_func): - # A coroutine; run to completion by the caller. - return node_func.ainvoke(state, config=_config) # type: ignore[attr-defined] - return node_func.invoke(state, config=_config) - - if streamer is None: - r = _invoke() - else: - # RunnableCallable.invoke only sets the ambient config when - # tracing; get_stream_writer() and the stream handler need it. - with set_config_context(_config) as ctx_: # type: ignore[arg-type] - return ctx_.run(lambda: _await_if_coroutine(_invoke())) - else: - - def _call_plain() -> Any: - sig = inspect.signature(node_func) - params = list(sig.parameters.keys()) - if len(params) >= 2 and "config" in params: - out = node_func(state, config=config) - else: - out = node_func(state) - return _await_if_coroutine(out) - - if streamer is None: - return _call_plain() - # Plain callables get no config injected; expose the handler and - # writer through the ambient config instead. - with set_config_context(_plain_stream_config()) as ctx_: # type: ignore[arg-type] - return ctx_.run(_call_plain) - - return _await_if_coroutine(r) - - def _await_if_coroutine(r: Any) -> Any: - import asyncio - - if asyncio.iscoroutine(r): - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - r = loop.run_until_complete(r) - finally: - loop.close() - return r - - def _plain_stream_config() -> Dict[str, Any]: - assert streamer is not None - thread_id = node_input.thread_id or getattr(ctx, "workflow_id", None) - runtime = _build_node_runtime(thread_id, ctx, node_name, stream_writer) - return streamer.patch_config({CONF: {CONFIG_KEY_RUNTIME: runtime}}) + call = _NodeCall( + ctx=ctx, + node_input=node_input, + node_func=node_func, + state=state, + config=config, + streamer=streamer, + pending_sends=[], + ) # Set up LangSmith child trace so LLM calls nest under the parent # "LangGraph" trace created by runner.invoke(). parent = _langsmith_parent(config) if streamer: streamer.node_started(state) - if parent: - import langsmith as ls - - with ls.trace( - name=node_name, - run_type="chain", - parent=parent, - inputs={"step": node_name}, - ): - result = _run_node() - else: - result = _run_node() + try: + if parent: + import langsmith as ls + + with ls.trace( + name=node_name, + run_type="chain", + parent=parent, + inputs={"step": node_name}, + ): + result = _run_node(call) + else: + result = _run_node(call) + except BaseException as exc: + if streamer: + streamer.node_failed(exc) + raise if streamer: streamer.node_finished(result) # Convert result to writes, then append any side-channel writes queued via # CONFIG_KEY_SEND (e.g. StateBackend writing to the "files" channel from # sandbox tools). - raw_writes = [*_result_to_raw_writes(result), *pending_sends] + raw_writes = [*_result_to_raw_writes(result), *call.pending_sends] writes = _serialize_writes(raw_writes) if streamer: From 8ad2c0f3f6205128b28817ce6bc7719ea50ffba4 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Wed, 25 Nov 2026 23:56:17 +0100 Subject: [PATCH 06/73] feat(langgraph): make the SSE endpoint and astream() safe to run behind a gateway The stream now starts with workflow_started, which gives the client the workflow id before anything else, so it can poll or terminate the run after a disconnect. An idle stream sends keepalive comments, and the response sets no-cache and no-buffering headers. A bad stream_mode is refused with a 422 before the stream starts, and only the JSON boolean true switches a request to SSE. A chunk that cannot be encoded becomes a placeholder and is counted as dropped instead of failing the stream. Blocking Dapr sidecar calls move off the event loop, and a failed status poll is retried for the LangGraph runner when the failure is transient, so a sidecar blip no longer reports a running workflow as failed. stream_unavailable is decided per node, node_reset and stream_unavailable number steps like langgraph_step, and a run survives a LangGraph message handler that can no longer be built. A node that returns Command(goto=...) now has its goto followed, and a Send payload that cannot be delivered is logged once per edge. Messages a node returns, such as a ToolMessage, carry the task metadata. astream() takes its config positionally and reads the thread id from it. serve() documents streaming, the streaming names are exported from the package, and the DeepAgents runner forwards the stream registry. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 102 ++++++++++- diagrid/agent/core/workflow/stream.py | 68 ++++--- diagrid/agent/deepagents/runner.py | 6 + diagrid/agent/langgraph/README.md | 59 +++++- diagrid/agent/langgraph/__init__.py | 6 + diagrid/agent/langgraph/models.py | 19 +- diagrid/agent/langgraph/runner.py | 250 ++++++++++++++++++++++---- diagrid/agent/langgraph/streaming.py | 133 +++++++++++--- diagrid/agent/langgraph/workflow.py | 93 +++++++++- 9 files changed, 636 insertions(+), 100 deletions(-) diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 7fdff711..8f020431 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -19,7 +19,7 @@ from diagrid.agent.core.metadata.mixins import AgentRegistryMixin from diagrid.agent.core.observability import resolve_observability_config from diagrid.agent.core.workflow.naming import build_workflow_name -from diagrid.agent.core.workflow.stream import format_sse +from diagrid.agent.core.workflow.stream import KEEPALIVE_EVENT, format_sse # ``diagrid-core`` ships the reporter. This distribution only pins # ``diagrid-core>=0.1.0`` (through ``diagrid-cli``), so an application holding @@ -53,6 +53,33 @@ def report_usage(package: str, **dimensions: object) -> None: } +#: A failed status poll is retried this many times in a row (only when the +#: caller asks, and only for a transient error: see ``_is_transient_poll_error``) +#: before the run's outcome is given up as unknown, waiting +#: ``POLL_RETRY_BASE_SECONDS`` (doubling, capped at ``POLL_RETRY_MAX_SECONDS``) +#: between tries: about a minute in all, enough for a sidecar restart or a +#: rolling update. +POLL_MAX_ERRORS = 10 +POLL_RETRY_BASE_SECONDS = 0.5 +POLL_RETRY_MAX_SECONDS = 10.0 + + +def _is_transient_poll_error(error: BaseException) -> bool: + """A failed poll worth retrying: the call failed to get through. + + A gRPC error or a connection/OS-level one (a sidecar restarting, a dropped + connection). A programming or credentials error is not transient and + surfaces at once. + """ + if isinstance(error, OSError): # ConnectionError, TimeoutError, ... + return True + try: + import grpc + except ImportError: # pragma: no cover - dapr depends on grpcio + return False + return isinstance(error, grpc.RpcError) + + def fold_run_event(result: dict, event: dict) -> bool: # type: ignore[type-arg] """Fold one event of a run into ``result``, the body of ``POST /agent/run``. @@ -274,6 +301,7 @@ async def _poll_workflow( *, poll_interval: float = 0.5, parse_output: Any = None, + retry_failed_polls: bool = False, ) -> AsyncIterator[dict[str, Any]]: """Poll a running workflow and yield status/completion events. @@ -284,6 +312,10 @@ async def _poll_workflow( parse_output: Optional callable to parse serialized output into a completion event dict. If None, raw output is returned. + retry_failed_polls: Ride out a failed poll when it looks transient + (see ``POLL_MAX_ERRORS``) instead of raising at once. Off by + default: a runner opts in when it can tell its caller that the + run's fate is unknown. Yields: Event dictionaries with workflow progress updates. @@ -291,11 +323,43 @@ async def _poll_workflow( assert self._workflow_client is not None previous_status = None + failed_polls = 0 while True: await asyncio.sleep(poll_interval) - state = self._workflow_client.get_workflow_state(instance_id=workflow_id) + try: + # A blocking gRPC call: off the loop, or every other run's + # tokens (and all HTTP handling) wait for the sidecar. + state = await asyncio.to_thread( + self._workflow_client.get_workflow_state, instance_id=workflow_id + ) + except Exception as e: + # The poll failed, not the workflow (a sidecar restart, a + # dropped call). Retry; only a poll that keeps failing is given + # up on, and the caller learns the run's fate is unknown. + failed_polls += 1 + if ( + not retry_failed_polls + or not _is_transient_poll_error(e) + or failed_polls > POLL_MAX_ERRORS + ): + raise + delay = min( + POLL_RETRY_BASE_SECONDS * 2 ** (failed_polls - 1), + POLL_RETRY_MAX_SECONDS, + ) + logger.warning( + "Polling workflow %s failed (%d of %d), retrying in %.1fs: %s", + workflow_id, + failed_polls, + POLL_MAX_ERRORS, + delay, + e, + ) + await asyncio.sleep(delay) + continue + failed_polls = 0 if state is None: yield { @@ -407,7 +471,8 @@ def serve( runtime, and registers POST/GET ``/agent/run`` endpoints. A runner that supports it (the LangGraph runner does) answers - ``POST /agent/run`` with ``"stream": true`` as server-sent events. The + ``POST /agent/run`` with ``"stream": true`` (the JSON boolean, nothing + else) as server-sent events. The keys ``stream`` and ``stream_mode`` are reserved on such a request. The last event is ``workflow_completed`` or ``workflow_failed``; its data is also what gets published to ``publish_topic``. Streaming works while the @@ -465,11 +530,14 @@ async def _run_and_collect(request: dict) -> dict: # type: ignore[type-arg] if fold_run_event(result, event): break - _publish_result(result) + await asyncio.to_thread(_publish_result, result) return result def _publish_result(result: dict) -> None: # type: ignore[type-arg] - """Publish a result to the configured topic, if any.""" + """Publish a result to the configured topic, if any. + + Blocking: callers run it off the event loop. + """ if pubsub_client and publish_topic: try: pubsub_client.publish(publish_topic, result) @@ -486,7 +554,8 @@ async def _frame(events: AsyncIterator[Tuple[str, Any]]) -> AsyncIterator[str]: event_id = 0 try: async for name, data in events: - event_id += 1 + if name != KEEPALIVE_EVENT: + event_id += 1 yield format_sse(name, data, event_id) finally: # A client that disconnects ends the generator at a yield; close @@ -500,7 +569,15 @@ async def _frame(events: AsyncIterator[Tuple[str, Any]]) -> AsyncIterator[str]: @app.post("/agent/run") async def run_agent(request: dict) -> Any: # type: ignore[type-arg] - if request.get("stream") and self._supports_serve_stream: + # Only the JSON value true streams. Anything else ("false", an + # object) is a plain request whose "stream" key may be the graph's own. + if request.get("stream") is True and self._supports_serve_stream: + # A bad request is refused with a 4xx now: once the response + # starts, its 200 is committed and an error can only be in-band. + try: + self._validate_stream_request(request) + except ValueError as e: + raise HTTPException(status_code=422, detail=str(e)) session_id = request.get( "session_id", request.get("thread_id", uuid.uuid4().hex[:8]), @@ -510,6 +587,9 @@ async def run_agent(request: dict) -> Any: # type: ignore[type-arg] self._serve_stream(request, session_id, on_result=on_result) ), media_type="text/event-stream", + # Without these an ingress or reverse proxy may buffer the + # stream and hand the client its tokens in one batch. + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, ) return await _run_and_collect(request) @@ -596,6 +676,14 @@ async def _serve_run( # ``"stream": true``). _supports_serve_stream = False + def _validate_stream_request(self, request: dict) -> None: # type: ignore[type-arg] + """Raise ``ValueError`` if a streaming request is invalid. + + Called before the SSE response is started, so the client gets a 422 + rather than a 200 whose only event is a failure. Default: accept all. + """ + return None + def _serve_stream( self, request: dict, # type: ignore[type-arg] diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index beba134f..6043add0 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -23,20 +23,39 @@ # Upper bound on buffered chunks per run. Past it, token and custom chunks are # dropped (counted, and reported on the final event) so a slow consumer cannot # grow memory without limit. Updates, node resets and the close marker are never -# dropped: they cannot be re-sent and are bounded by the size of the graph. +# dropped: they cannot be re-sent and are bounded by the size of the graph +# (the workflow_started event is sent once). MAX_BUFFERED_EVENTS = 10_000 NODE_RESET = "node_reset" STREAM_UNAVAILABLE = "stream_unavailable" STREAM_DROPPED = "stream_dropped" +#: First event of a stream: the ids a client needs to find or stop its run. +WORKFLOW_STARTED = "workflow_started" # Events about the stream itself, delivered whatever stream modes were asked for. -CONTROL_MODES = (NODE_RESET, STREAM_UNAVAILABLE) +CONTROL_MODES = (WORKFLOW_STARTED, NODE_RESET, STREAM_UNAVAILABLE) + +#: Seconds an idle SSE stream waits before it sends a keepalive comment, so a +#: proxy or load balancer does not cut it during a long tool call or LLM gap. +SSE_KEEPALIVE_SECONDS = 15.0 +#: The ``event`` name a runner yields for a keepalive; framed as an SSE comment. +KEEPALIVE_EVENT = "keepalive" # Runs remembered by StreamSinkRegistry.first_report; older ones are forgotten. _MAX_REPORTED_RUNS = 1024 UPDATES = "updates" +def display_step(step: int) -> int: + """A workflow step number as a client sees it. + + Workflow steps count from 0. Clients match ``node_reset`` and + ``stream_unavailable`` against the ``langgraph_step`` of a chunk's metadata, + which Pregel counts from 1, so every step a client sees is numbered from 1. + """ + return step + 1 + + @dataclass(frozen=True) class StreamEvent: """One chunk, wrapped with enough identity to order it and tell attempts apart.""" @@ -112,7 +131,7 @@ def put(self, event: StreamEvent) -> None: event.seq, event.ns, NODE_RESET, - {"node": event.node, "step": event.step}, + {"node": event.node, "step": display_step(event.step)}, ) ) self._owner[key] = event.attempt_id @@ -161,7 +180,11 @@ def _put() -> None: def _is_control(item: Any) -> bool: """Chunks that must not be dropped: they cannot be re-sent.""" - return isinstance(item, StreamEvent) and item.mode in (UPDATES, NODE_RESET) + return isinstance(item, StreamEvent) and item.mode in ( + UPDATES, + NODE_RESET, + WORKFLOW_STARTED, + ) class StreamSinkRegistry: @@ -177,6 +200,7 @@ def __init__(self) -> None: self._sinks: Dict[str, InProcessSink] = {} self._lock = threading.Lock() self._reported: "OrderedDict[str, None]" = OrderedDict() + self._closed: "OrderedDict[str, None]" = OrderedDict() def open(self, workflow_id: str) -> InProcessSink: """Register a sink for ``workflow_id`` on the running event loop. @@ -189,6 +213,7 @@ def open(self, workflow_id: str) -> InProcessSink: if workflow_id in self._sinks: raise ValueError(f"A stream for {workflow_id!r} is already open") self._sinks[workflow_id] = sink + self._closed.pop(workflow_id, None) return sink def close(self, workflow_id: str, sink: Optional[InProcessSink] = None) -> None: @@ -202,8 +227,22 @@ def close(self, workflow_id: str, sink: Optional[InProcessSink] = None) -> None: if current is None or (sink is not None and current is not sink): return del self._sinks[workflow_id] + self._closed[workflow_id] = None + self._closed.move_to_end(workflow_id) + while len(self._closed) > _MAX_REPORTED_RUNS: + self._closed.popitem(last=False) current.close() + def was_closed(self, workflow_id: str) -> bool: + """True when this process opened a stream for ``workflow_id`` and closed it. + + Tells a run whose consumer left (or whose stream ended) from one whose + activity runs in a process that never had a sink. Remembers the most + recent closes only. + """ + with self._lock: + return workflow_id in self._closed + def first_report(self, workflow_id: str) -> bool: """True the first time it is asked about ``workflow_id``. @@ -230,23 +269,6 @@ def get(self, workflow_id: Optional[str]) -> Optional[InProcessSink]: default_registry = StreamSinkRegistry() -def open_stream( - workflow_id: str, *, registry: Optional[StreamSinkRegistry] = None -) -> InProcessSink: - """:meth:`StreamSinkRegistry.open` on ``registry`` (default: the module's).""" - return (registry or default_registry).open(workflow_id) - - -def close_stream( - workflow_id: str, - sink: Optional[InProcessSink] = None, - *, - registry: Optional[StreamSinkRegistry] = None, -) -> None: - """:meth:`StreamSinkRegistry.close` on ``registry`` (default: the module's).""" - (registry or default_registry).close(workflow_id, sink) - - def get_stream_sink( workflow_id: Optional[str], *, registry: Optional[StreamSinkRegistry] = None ) -> Optional[StreamSink]: @@ -259,7 +281,9 @@ def get_stream_sink( def format_sse(event: str, data: Any, event_id: Optional[int] = None) -> str: - """Frame one Server-Sent Event.""" + """Frame one Server-Sent Event (a keepalive is a comment, not an event).""" + if event == KEEPALIVE_EVENT: + return ": keepalive\n\n" lines = [] if event_id is not None: lines.append(f"id: {event_id}") diff --git a/diagrid/agent/deepagents/runner.py b/diagrid/agent/deepagents/runner.py index ae62a6a1..257495e3 100644 --- a/diagrid/agent/deepagents/runner.py +++ b/diagrid/agent/deepagents/runner.py @@ -16,6 +16,7 @@ from diagrid.agent.langgraph.runner import DaprWorkflowGraphRunner if TYPE_CHECKING: + from diagrid.agent.core.workflow.stream import StreamSinkRegistry from langgraph.graph.state import CompiledStateGraph logger = logging.getLogger(__name__) @@ -65,6 +66,7 @@ def __init__( role: Optional[str] = None, goal: Optional[str] = None, registry_config: Optional[Any] = None, + stream_registry: Optional["StreamSinkRegistry"] = None, ): """Initialize the runner. @@ -77,6 +79,9 @@ def __init__( role: Optional role description for the agent registry. goal: Optional goal description for the agent registry. registry_config: Optional registry configuration for metadata. + stream_registry: Where streamed runs register their sinks (see + :class:`DaprWorkflowGraphRunner`); each runner owns one by + default. """ super().__init__( graph=agent, @@ -87,6 +92,7 @@ def __init__( role=role, goal=goal, registry_config=registry_config, + stream_registry=stream_registry, ) @property diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 19398a4f..5387c764 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -90,6 +90,15 @@ asyncio.run(main()) ## Streaming +```python +from diagrid.agent.langgraph import ( + DaprWorkflowGraphRunner, + GraphRunError, # raised when a streamed run fails + StreamControl, # what `on_control` receives + StreamSinkRegistry, # the type of the `stream_registry` argument +) +``` + `astream` yields what `CompiledStateGraph.astream` yields, while each node runs as a Dapr activity: LLM tokens (`messages`), node updates (`updates`) and whatever a node writes with `get_stream_writer()` (`custom`). @@ -110,8 +119,9 @@ objects (`kind`, `data`): | `kind` | `data` | Meaning | |---|---|---| -| `node_reset` | `{"node", "step"}` | A node was retried; drop its partial output. | -| `stream_unavailable` | `{"workflow_id", "reason", "missing_steps"}` | The run finished but nothing arrived for those steps (see the limit below). | +| `workflow_started` | `{"workflow_id", "thread_id"}` | Always the first event: the ids to use with `terminate_workflow` or `get_workflow_status`. Delivered only to `on_control`, never yielded. | +| `node_reset` | `{"node", "step"}` | A node was retried; drop its partial output. `step` is the `langgraph_step` of that node's `messages` metadata (numbered from 1). | +| `stream_unavailable` | `{"workflow_id", "reason", "missing_steps", "missing_nodes"}` | The run finished but a node's chunks never arrived (see the limit below). `missing_nodes` is a list of `{"step", "node"}`, one per node of a step that streamed nothing, even when other nodes of that step did. Steps are numbered from 1, like `langgraph_step`. | | `stream_dropped` | `{"dropped": n}` | The consumer fell behind and `n` token or custom chunks were dropped. `updates` are never dropped. | Pass `on_control=callback` to `astream` to receive them. A list of modes also @@ -119,15 +129,39 @@ yields them as `(kind, data)` tuples; a single mode never does, so `async for message, metadata in runner.astream(..., stream_mode="messages")` never meets one. +Dapr retries a failed node activity and the chunks the failed attempt already +sent cannot be taken back (native `astream` has no retries). A single-mode +consumer that passes no `on_control` therefore sees the failed attempt's partial +text followed by the retry's; a warning is logged for each such `node_reset`. +To discard the partial output, pass `on_control` or use a list of modes and drop +what the node sent before its `node_reset`. + A run that fails (a node or condition error, max steps, a terminated workflow, no result) raises `GraphRunError`; its `.final` is the full terminal event. -LangGraph merges the nodes of a parallel step into one `updates` chunk; here each -node yields its own. + +To stop reading early, close the stream. A bare `break` does not close an async +generator that is still referenced, so use `aclosing`: + +```python +from contextlib import aclosing + +async with aclosing(runner.astream(graph_input, stream_mode="messages")) as stream: + async for message, metadata in stream: + if done(message): + break +``` + +Closing the stream does not cancel the Dapr workflow, which runs to completion. ### Over HTTP `serve()` answers `POST /agent/run` with `"stream": true` as server-sent events. -`stream_mode` (a mode or a list; default all three) picks the chunks. The +`stream_mode` (a mode or a list; default all three) picks the chunks; an +unsupported one is refused with a `422` before the stream starts. The first +event is `workflow_started`. An idle stream sends a `: keepalive` comment every +15 seconds so a proxy does not cut it, and the response sets `Cache-Control: +no-cache` and `X-Accel-Buffering: no` so an nginx or ingress in front does not +buffer the tokens. The messages and updates are serialized with `langchain_core.load.dumpd`, so `langchain_core.load.load` restores them. The stream ends with `workflow_completed` or `workflow_failed`; both carry `workflow_id` and @@ -137,6 +171,12 @@ a non-streaming call returns and publishes for the same run, so a run that ends with `status: "error"` is published as that call reports it (`workflow_completed` with the error string) even though the stream's last event is `workflow_failed`. +A failed status poll (the sidecar restarting, a dropped call) is retried for +about a minute and does not fail the run. If the stream still cannot follow it, +it ends with `workflow_failed` whose `error.error_type` is `PollError` and +`workflow_still_running` is `true`: the workflow may yet complete, nothing is +published for it, and `GET /agent/run/{workflow_id}` tells how it ended. + `stream` and `stream_mode` are reserved keys on a streaming request: they are removed before the graph (or your `input_mapper`) sees it. On a plain request they are left alone. @@ -151,11 +191,18 @@ they are left alone. replicas is not implemented yet. - **A disconnect does not cancel the run.** When the client goes away the stream is closed, but the Dapr workflow keeps running to completion. Terminate it with - `terminate_workflow` if you need it stopped. + `terminate_workflow` if you need it stopped. The first event of every stream is + `workflow_started` with the `workflow_id` and `thread_id`, so a client that + loses its connection can still `GET /agent/run/{workflow_id}` or ask for the + run to be terminated. With `astream`, `on_control` receives the same event. When `publish_topic` is set, the server keeps following the run after the client left and publishes its result when it ends, as it does for a client that stays. +- **`Send` payloads.** A node run through `Send("node", arg)` (or `goto=Send(...)`) + reads the channel state, not `arg`; this is logged once per edge. A node that + reads the argument gets different data than under LangGraph. + ## Architecture ```text diff --git a/diagrid/agent/langgraph/__init__.py b/diagrid/agent/langgraph/__init__.py index 1a987e87..17c2cf87 100644 --- a/diagrid/agent/langgraph/__init__.py +++ b/diagrid/agent/langgraph/__init__.py @@ -40,7 +40,9 @@ def node_a(state: State) -> dict: ``` """ +from diagrid.agent.core.workflow.stream import StreamSinkRegistry from diagrid.agent.langgraph.runner import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.streaming import GraphRunError, StreamControl from diagrid.agent.langgraph.state import DaprMemoryCheckpointer from diagrid.agent.langgraph.models import ( ChannelState, @@ -69,6 +71,10 @@ def node_a(state: State) -> dict: __all__ = [ # Main runner "DaprWorkflowGraphRunner", + # Streaming + "GraphRunError", + "StreamControl", + "StreamSinkRegistry", # State "DaprMemoryCheckpointer", # Models diff --git a/diagrid/agent/langgraph/models.py b/diagrid/agent/langgraph/models.py index 99938670..294de267 100644 --- a/diagrid/agent/langgraph/models.py +++ b/diagrid/agent/langgraph/models.py @@ -238,18 +238,24 @@ class ExecuteNodeOutput: node_name: Name of the executed node writes: List of writes produced by the node error: Optional error message + goto: Nodes the node asked to run next through ``Command(goto=...)``, + in addition to the nodes its edges lead to """ node_name: str writes: List[NodeWrite] = field(default_factory=list) error: Optional[str] = None + goto: List[str] = field(default_factory=list) def to_dict(self) -> Dict[str, Any]: - return { + data: Dict[str, Any] = { "node_name": self.node_name, "writes": [w.to_dict() for w in self.writes], "error": self.error, } + if self.goto: + data["goto"] = list(self.goto) + return data @classmethod def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeOutput": @@ -257,6 +263,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeOutput": node_name=data["node_name"], writes=[NodeWrite.from_dict(w) for w in data.get("writes", [])], error=data.get("error"), + goto=list(data.get("goto") or []), ) @@ -386,6 +393,9 @@ class GraphWorkflowOutput: steps: Total number of steps executed status: Workflow status error: Optional error message + executed: The nodes that ran in each step, in order. Lets a streaming + consumer tell which node's chunks never arrived. ``None`` for an + output written before the field existed. """ output: Dict[str, Any] = field(default_factory=dict) @@ -393,9 +403,10 @@ class GraphWorkflowOutput: steps: int = 0 status: str = "completed" error: Optional[str] = None + executed: Optional[List[List[str]]] = None def to_dict(self) -> Dict[str, Any]: - return { + data: Dict[str, Any] = { "output": self.output, "channel_state": self.channel_state.to_dict() if self.channel_state @@ -404,6 +415,9 @@ def to_dict(self) -> Dict[str, Any]: "status": self.status, "error": self.error, } + if self.executed is not None: + data["executed"] = self.executed + return data @classmethod def from_dict(cls, data: Dict[str, Any]) -> "GraphWorkflowOutput": @@ -416,4 +430,5 @@ def from_dict(cls, data: Dict[str, Any]) -> "GraphWorkflowOutput": steps=data.get("steps", 0), status=data.get("status", "completed"), error=data.get("error"), + executed=data.get("executed"), ) diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index fc9bedfc..98fb299a 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -27,10 +27,14 @@ from diagrid.agent.core.types.type import SupportedFrameworks from diagrid.agent.core.workflow import BaseWorkflowRunner from diagrid.agent.core.workflow.runner import fold_run_event +from diagrid.agent.core.workflow import stream as stream_module from diagrid.agent.core.workflow.stream import ( CONTROL_MODES, + KEEPALIVE_EVENT, + NODE_RESET, STREAM_DROPPED, STREAM_UNAVAILABLE, + WORKFLOW_STARTED, StreamClosed, StreamEvent, StreamSinkRegistry, @@ -44,7 +48,9 @@ NodeConfig, ) from .streaming import ( + EXECUTED_KEY, STREAM_RUN_KEY, + UPDATES, GraphRunError, StreamControl, stream_unavailable_event, @@ -85,6 +91,95 @@ _TRANSPORT_KEYS = ("stream", "stream_mode") +def _encode_chunk(event: StreamEvent) -> Tuple[Any, bool]: + """``(wire form, ok)`` of a chunk; a chunk that cannot be encoded is replaced. + + ``to_wire`` runs arbitrary ``to_dict`` / ``model_dump`` on whatever a node + wrote to ``custom``, so it can raise. That is a problem with one chunk, not + with the run: the stream carries on with a placeholder. + """ + try: + return to_wire(event.mode, event.data), True + except Exception as e: + try: + text = repr(event.data)[:200] + except Exception: + text = f"<{type(event.data).__name__}>" + logger.warning( + "Run %s: a %r chunk of node %r could not be encoded (%s: %s); " + "sending a placeholder", + event.workflow_id, + event.mode, + event.node, + type(e).__name__, + e, + ) + return {"unserializable": text}, False + + +def _warn_reset_unseen(workflow_id: str, data: Dict[str, Any]) -> None: + """Say that a retried node's earlier chunks stay in a stream that cannot show it. + + A single-mode ``astream`` yields bare chunks, as native ``astream`` does, so + a node reset has no place in it; with no ``on_control`` either, the + consumer is never told and its text for that node holds both attempts. + """ + logger.warning( + "Run %s: node %r was retried (step %s) and its first attempt's chunks " + "were already yielded. This astream has no way to tell you: pass " + "on_control, or a list of stream modes, to receive node_reset and " + "discard the partial output.", + workflow_id, + data.get("node"), + data.get("step"), + ) + + +def _count_unencodable(final: Dict[str, Any], unencodable: int) -> Dict[str, Any]: + """``final`` with the chunks lost to encoding added to its ``dropped`` count.""" + if not unencodable: + return final + return {**final, "dropped": int(final.get("dropped") or 0) + unencodable} + + +#: Yielded by ``_stream_events`` (when asked) after an idle stretch. +KEEPALIVE = object() + + +def _started_event(event: Dict[str, Any], workflow_id: str, thread_id: str) -> Any: + """The stream's first event: the ids a client needs to find or stop its run.""" + return StreamEvent( + workflow_id=workflow_id, + step=-1, + node="", + attempt_id="", + seq=0, + ns=(), + mode=WORKFLOW_STARTED, + data={ + "workflow_id": event.get("workflow_id") or workflow_id, + "thread_id": event.get("thread_id") or thread_id, + }, + ) + + +def _without_executed(event: Dict[str, Any]) -> Dict[str, Any]: + """``event`` minus the per-step node list, which is for the stream only.""" + if EXECUTED_KEY not in event: + return event + return {k: v for k, v in event.items() if k != EXECUTED_KEY} + + +async def _next_item(sink: Any, keepalive: bool) -> Any: + """The next item of ``sink``, or :data:`KEEPALIVE` after an idle stretch.""" + if not keepalive: + return await sink.get() + try: + return await asyncio.wait_for(sink.get(), stream_module.SSE_KEEPALIVE_SECONDS) + except asyncio.TimeoutError: + return KEEPALIVE + + class DaprWorkflowGraphRunner(BaseWorkflowRunner): """Runner that executes LangGraph graphs as Dapr Workflows. @@ -645,7 +740,9 @@ async def run_async( json.dumps(workflow_input_dict) logger.info(f"Starting workflow: {workflow_id}") - self._workflow_client.schedule_new_workflow( + # Off the loop: this is a blocking gRPC call (see _poll_workflow). + await asyncio.to_thread( + self._workflow_client.schedule_new_workflow, workflow=agent_workflow, input=workflow_input_dict, instance_id=workflow_id, @@ -659,8 +756,13 @@ async def run_async( "graph_name": self._name, } + # Which nodes ran in each step is for the stream (stream_unavailable), + # not for a caller of run_async: only a streamed run asks for it. + streamed = bool(config.get(STREAM_RUN_KEY)) + def _parse_output(wf_id: str, output_dict: dict) -> dict: # type: ignore[type-arg] output = GraphWorkflowOutput.from_dict(output_dict) + with_executed = streamed and bool(output.executed) return { "type": "workflow_completed", "workflow_id": wf_id, @@ -668,6 +770,7 @@ def _parse_output(wf_id: str, output_dict: dict) -> dict: # type: ignore[type-a "steps": output.steps, "status": output.status, **({"error": output.error} if output.error else {}), + **({EXECUTED_KEY: output.executed} if with_executed else {}), } async for event in self._poll_workflow( @@ -675,6 +778,9 @@ def _parse_output(wf_id: str, output_dict: dict) -> dict: # type: ignore[type-a thread_id, poll_interval=poll_interval, parse_output=_parse_output, + # A poll that fails is reported as such (PollError) while the + # run may still finish: ride out a restarting sidecar first. + retry_failed_polls=True, ): yield event @@ -693,8 +799,8 @@ def _parse_output(wf_id: str, output_dict: dict) -> dict: # type: ignore[type-a async def astream( self, input: Dict[str, Any], - *, config: Optional[Dict[str, Any]] = None, + *, thread_id: Optional[str] = None, workflow_id: Optional[str] = None, stream_mode: Any = "updates", @@ -704,6 +810,11 @@ async def astream( ) -> AsyncIterator[Any]: """Stream a run like ``CompiledStateGraph.astream``. + ``config`` is positional or keyword, as in LangGraph. The run's thread + id is ``thread_id`` if given, else ``config["configurable"]["thread_id"]``, + else a new one; the same id is in the ``workflow_started`` control, the + ``messages`` metadata and the run's config. + Supports ``messages``, ``updates`` and ``custom``. A single mode yields bare chunks, as native ``astream`` does, and a list of modes yields ``(mode, chunk)`` tuples. @@ -717,18 +828,33 @@ async def astream( receive them. A list of modes also yields them as ``(kind, data)`` tuples; a single mode never does, so a consumer written against native ``astream`` (``async for message, metadata in ...``) cannot trip over - one. A run that fails raises :class:`GraphRunError`. - - Stopping early (``break``, ``aclose()``) closes the stream but does not + one. ``on_control`` also gets a ``workflow_started`` control first, with + the ``workflow_id`` and ``thread_id`` to use with ``terminate_workflow`` + or ``get_workflow_status``; it is never yielded. A run that fails raises + :class:`GraphRunError`. + + Dapr retries a failed node activity, and the chunks the failed attempt + already sent cannot be taken back. Native ``astream`` has no retries, + so a single-mode consumer that passes no ``on_control`` would see the + partial text of the failed attempt followed by the retry's. It is not + left unaware: a warning is logged for each such ``node_reset``. To + discard the partial output, pass ``on_control`` or use a list of modes + and drop what the node sent before its ``node_reset``. + + To stop early, close the stream: ``await stream.aclose()``, or iterate + inside ``async with contextlib.aclosing(runner.astream(...)) as stream``. + A bare ``break`` does not close an async generator that is still + referenced, so the run's stream stays open (and its ``workflow_id`` + reserved) until it is closed or garbage collected. Closing does not cancel the Dapr workflow, which runs to completion. Chunks have the shape ``CompiledStateGraph.astream`` yields: ``messages`` are ``(message_chunk, metadata)`` and ``updates`` are ``{node: update}`` with the values exactly as the node returned them - (``None`` for a node that wrote nothing). One difference: LangGraph - merges the nodes of a parallel step into one ``updates`` chunk; here - each node yields its own. Over HTTP (``"stream": true``) the same - chunks are serialized with ``langchain_core.load.dumpd``. + (``None`` for a node that wrote nothing); like LangGraph, a parallel + step yields one ``updates`` chunk per node. Over HTTP + (``"stream": true``) the same chunks are serialized with + ``langchain_core.load.dumpd``. """ if subgraphs: raise NotImplementedError("subgraphs=True is not supported yet") @@ -750,8 +876,16 @@ async def astream( control = StreamControl(item.mode, item.data) if on_control is not None: on_control(control) - if is_list: + # workflow_started only informs on_control: it is not + # something the stream modes of native astream have. + if is_list and item.mode != WORKFLOW_STARTED: yield (control.kind, control.data) + elif ( + item.mode == NODE_RESET + and not is_list + and on_control is None + ): + _warn_reset_unseen(item.workflow_id, control.data) elif item.mode in modes: yield (item.mode, item.data) if is_list else item.data else: @@ -775,6 +909,7 @@ async def _stream_events( workflow_id: Optional[str], poll_interval: float, on_result: Optional[Callable[[Dict[str, Any]], None]] = None, + keepalive: bool = False, ) -> AsyncGenerator[Any, None]: """Yield ``StreamEvent`` chunks, then the terminal event dict. @@ -785,12 +920,23 @@ async def _stream_events( ``on_result`` is called once, when the run ends, with the result a plain ``POST /agent/run`` would return for it (not the normalized terminal event), so a streamed run publishes exactly what a plain one does. + + The first item is a ``workflow_started`` event (``workflow_id`` and + ``thread_id``). With ``keepalive`` set, :data:`KEEPALIVE` is yielded + whenever nothing arrived for ``SSE_KEEPALIVE_SECONDS``. """ - thread_id = thread_id or str(uuid.uuid4()) + configurable = (config or {}).get("configurable") or {} + thread_id = str(thread_id or configurable.get("thread_id") or uuid.uuid4()) workflow_id = workflow_id or f"graph-{thread_id}-{uuid.uuid4().hex[:8]}" + # One thread id per run: the one the run reports is the one its nodes see. + run_config = { + **(config or {}), + "configurable": {**configurable, "thread_id": thread_id}, + STREAM_RUN_KEY: True, + } sink = self._stream_registry.open(workflow_id) task: Optional["asyncio.Task[None]"] = None - seen_steps: Set[int] = set() + seen_nodes: Set[Tuple[int, str]] = set() async def _pump() -> None: final: Dict[str, Any] = {} @@ -799,50 +945,62 @@ async def _pump() -> None: async for event in self.run_async( input, thread_id=thread_id, - config={**(config or {}), STREAM_RUN_KEY: True}, + config=run_config, workflow_id=workflow_id, poll_interval=poll_interval, ): - fold_run_event(result, event) + fold_run_event(result, _without_executed(event)) if event["type"] in _FINAL_EVENTS: final = event if on_result is not None: - on_result(result) + await asyncio.to_thread(on_result, result) except Exception as e: logger.exception("Streamed run %s failed", workflow_id) final = { "type": "workflow_failed", "error": {"message": str(e), "error_type": type(e).__name__}, } + if result.get("instance_id"): + # The workflow was started and this is the stream failing + # (its status polls gave out), not the workflow: it may + # still complete. Say so, and publish nothing: a failure + # published for a run that then succeeds is a lie. + final["error"]["error_type"] = "PollError" + final["workflow_still_running"] = True sink.close( normalize_final(final, workflow_id=workflow_id, thread_id=thread_id) ) try: + # Before the pump schedules the workflow: an activity can write the + # moment it is scheduled, and the event must come before its chunks. + sink.put(_started_event({}, workflow_id, thread_id)) task = asyncio.create_task(_pump()) while True: - item = await sink.get() + item = await _next_item(sink, keepalive) + if item is KEEPALIVE: + yield item + continue if isinstance(item, StreamClosed): # Unregister before handing over the result: chunks a late # activity attempt writes from here on are dropped. self._stream_registry.close(workflow_id, sink) unavailable = stream_unavailable_event( - item.final, seen_steps, workflow_id + item.final, seen_nodes, workflow_id ) if unavailable is not None: logger.warning( - "Streamed run %s: no chunks for steps %s", + "Streamed run %s: no chunks for steps %s (nodes %s)", workflow_id, unavailable.data["missing_steps"], + [m["node"] for m in unavailable.data["missing_nodes"]], ) yield unavailable - yield ( - {**item.final, "dropped": item.dropped} - if item.dropped - else item.final - ) + final = _without_executed(item.final) + yield {**final, "dropped": item.dropped} if item.dropped else final return - seen_steps.add(item.step) + if item.mode == UPDATES: + seen_nodes.add((item.step, item.node)) yield item finally: # Also reached when the consumer goes away (client disconnect, @@ -881,6 +1039,17 @@ def serve( ) -> None: """Start an HTTP server exposing /agent/run endpoints. + ``POST /agent/run`` with ``"stream": true`` answers as server-sent + events: ``workflow_started`` first, then the ``messages``, ``updates`` + and ``custom`` chunks picked by ``stream_mode``, then + ``workflow_completed`` or ``workflow_failed``. The keys ``stream`` and + ``stream_mode`` are reserved on such a request. Streaming works only on + a single replica: chunks reach the connection through an in-process + queue, so a node activity that runs in another process streams nothing + and the stream ends with ``stream_unavailable``. A client that + disconnects ends the stream, not the workflow; with ``publish_topic`` + set its result is still published when the run ends. + Args: port: Port to listen on (default: 5001) host: Host to bind to (default: 0.0.0.0) @@ -926,6 +1095,12 @@ async def _serve_run( _supports_serve_stream = True + _DEFAULT_STREAM_MODES = ["messages", "updates", "custom"] + + def _validate_stream_request(self, request: dict) -> None: # type: ignore[type-arg] + """Reject an unsupported ``stream_mode`` before the response starts.""" + normalize_stream_mode(request.get("stream_mode") or self._DEFAULT_STREAM_MODES) + async def _serve_stream( # type: ignore[override] self, request: dict, # type: ignore[type-arg] @@ -940,9 +1115,11 @@ async def _serve_stream( # type: ignore[override] the run's full terminal event. The base runner frames the pairs. """ thread_id = request.get("thread_id") or request.get("session_id") or session_id + workflow_id: Optional[str] = None + unencodable = 0 try: modes, _ = normalize_stream_mode( - request.get("stream_mode") or ["messages", "updates", "custom"] + request.get("stream_mode") or self._DEFAULT_STREAM_MODES ) graph_input = self._request_to_input(request, streaming=True) async with aclosing( @@ -953,24 +1130,37 @@ async def _serve_stream( # type: ignore[override] workflow_id=None, poll_interval=0.5, on_result=on_result, + keepalive=True, ) ) as events: async for item in events: - if isinstance(item, StreamEvent): + if item is KEEPALIVE: + yield KEEPALIVE_EVENT, None + elif isinstance(item, StreamEvent): if item.mode not in CONTROL_MODES and item.mode not in modes: continue - yield item.mode, to_wire(item.mode, item.data) + if item.mode == WORKFLOW_STARTED: + workflow_id = item.data["workflow_id"] + wire, ok = _encode_chunk(item) + unencodable += 0 if ok else 1 + yield item.mode, wire else: - yield item["type"], item + yield item["type"], _count_unencodable(item, unencodable) except Exception as e: logger.exception("Streaming run failed") - failed = { + failed: Dict[str, Any] = { "type": "workflow_failed", "error": {"message": str(e), "error_type": type(e).__name__}, } + if workflow_id: + # The workflow started and this is the stream failing, not the + # run: it goes on, and may well succeed. Say so, as _pump does + # for a failed status poll, rather than report it as failed. + failed["error"]["error_type"] = "StreamError" + failed["workflow_still_running"] = True yield ( "workflow_failed", - normalize_final(failed, workflow_id=None, thread_id=thread_id), + normalize_final(failed, workflow_id=workflow_id, thread_id=thread_id), ) def _request_to_input( diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index 5379a855..d01f4804 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -10,6 +10,7 @@ """ import itertools +import logging import threading import uuid from dataclasses import dataclass @@ -22,8 +23,11 @@ STREAM_UNAVAILABLE, StreamEvent, StreamSink, + display_step, ) +logger = logging.getLogger(__name__) + MESSAGES = "messages" UPDATES = "updates" CUSTOM = "custom" @@ -32,6 +36,10 @@ # Configurable keys LangChain never copies into metadata (they are secrets). _UNTRACED_CONFIGURABLE = frozenset(("api_key",)) +# Key of the run_async terminal event that lists the nodes each step ran. It +# serves the stream (see stream_unavailable_event) and is not part of a result. +EXECUTED_KEY = "executed" + # Set in the workflow config of a run someone is streaming, so an activity that # finds no sink to write to knows that is a problem and not just a plain run. STREAM_RUN_KEY = "diagrid_streamed" @@ -41,9 +49,12 @@ class StreamControl: """An event about the stream itself rather than a chunk of the run. - ``kind`` is ``node_reset``, ``stream_unavailable`` or ``stream_dropped``; + ``kind`` is ``workflow_started`` (``{"workflow_id", "thread_id"}``, always + first), ``node_reset``, ``stream_unavailable`` or ``stream_dropped``; ``data`` is its payload. ``astream`` hands these to its ``on_control`` - callback, and in list mode also yields them as ``(kind, data)``. + callback, and in list mode also yields them as ``(kind, data)``, except + ``workflow_started``, which is only ever given to ``on_control`` and never + yielded. """ kind: str @@ -53,6 +64,10 @@ class StreamControl: class NodeStreamer: """Streams one activity attempt of one node into a sink.""" + # Logged once per process, not per node of every run. + _handler_failure_logged = False + _failure_lock = threading.Lock() + def __init__( self, sink: StreamSink, @@ -75,6 +90,7 @@ def __init__( # taken and the chunk handed over under one lock so they stay in order. self._emit_lock = threading.Lock() self._handler: Any = None + self._handler_unusable = False self._run_id = uuid.uuid4() @property @@ -82,7 +98,7 @@ def metadata(self) -> Dict[str, Any]: """The ``langgraph_*`` keys the Pregel loop sets on a task's config.""" return { # Pregel numbers the first node after START as step 1. - "langgraph_step": self._step + 1, + "langgraph_step": display_step(self._step), "langgraph_node": self._node, "langgraph_triggers": (f"branch:to:{self._node}",), "langgraph_path": ("__pregel_pull", self._node), @@ -112,38 +128,89 @@ def _on_chunk(self, chunk: Tuple[Any, ...]) -> None: self._emit(ns, mode, (message, metadata)) def _messages_handler(self) -> Any: - if self._handler is None: - from langgraph.pregel._messages import StreamMessagesHandler + """LangGraph's ``StreamMessagesHandler``, or ``None`` if it is unusable. - self._handler = StreamMessagesHandler(self._on_chunk, False) + It is a private class of langgraph, and the dependency is not pinned + below the release that may move or change it. When it cannot be built, + the node still runs and its ``updates`` and ``custom`` chunks still + stream; only ``messages`` is lost, and that is logged once. + """ + if self._handler is None and not self._handler_unusable: + try: + from langgraph.pregel._messages import StreamMessagesHandler + + self._handler = StreamMessagesHandler(self._on_chunk, False) + except (ImportError, TypeError, AttributeError) as e: + self._handler_unusable = True + NodeStreamer._log_handler_failure(e) return self._handler + @staticmethod + def _log_handler_failure(error: BaseException) -> None: + with NodeStreamer._failure_lock: + if NodeStreamer._handler_failure_logged: + return + NodeStreamer._handler_failure_logged = True + logger.error( + "Cannot stream 'messages': langgraph's StreamMessagesHandler is not " + "usable (%s: %s). Nodes run as usual and 'updates' and 'custom' " + "still stream, but no LLM tokens are sent. This is expected after a " + "langgraph release that moved or changed that private class.", + type(error).__name__, + error, + ) + def callbacks(self) -> List[Any]: - return [self._messages_handler()] + handler = self._messages_handler() + return [] if handler is None else [handler] # The activity calls the node's bound runnable directly, which never # starts the chain run Pregel's handler keys node-output messages on # (StateGraph nodes are built with trace=False). Drive those two # callbacks by hand so ToolNode / hand-built messages stream too. - def node_started(self, node_input: Any) -> None: - self._messages_handler().on_chain_start( + def node_started( + self, node_input: Any, config: Optional[Dict[str, Any]] = None + ) -> None: + """Open the chain run node-output messages are keyed on. + + Native LangGraph gives that run the task's config metadata (the + caller's metadata, ``thread_id`` and the other configurable values, + ``ls_integration``, the ``langgraph_*`` keys), and every message a node + returns (a ``ToolNode``'s ``ToolMessage``) is sent with it. ``config`` + is the caller's run config. + """ + handler = self._messages_handler() + if handler is None: + return + config = config or {} + metadata = { + **self._configurable_metadata(config), + "ls_integration": "langgraph", + **(config.get("metadata") or {}), + **{k: v for k, v in self.metadata.items() if k != "checkpoint_ns"}, + } + handler.on_chain_start( {}, node_input, run_id=self._run_id, name=self._node, - metadata=self.metadata, - tags=[], + metadata=metadata, + tags=list(config.get("tags") or []), ) def node_finished(self, output: Any) -> None: - self._messages_handler().on_chain_end(output, run_id=self._run_id) + handler = self._messages_handler() + if handler is not None: + handler.on_chain_end(output, run_id=self._run_id) def node_failed(self, error: BaseException) -> None: """Close the chain run :meth:`node_started` opened. Without it the message handler keeps that run's state for good. """ - self._messages_handler().on_chain_error(error, run_id=self._run_id) + handler = self._messages_handler() + if handler is not None: + handler.on_chain_error(error, run_id=self._run_id) def writer(self, chunk: Any) -> None: """``Runtime.stream_writer``: what ``get_stream_writer()`` returns.""" @@ -325,32 +392,49 @@ def normalize_final( UNAVAILABLE_REASON = ( - "No chunks arrived for the listed steps: their node activities ran in " - "another process (several replicas) or before this stream was opened. " - "Streaming only works while the activities run in the process that serves " - "the stream; the run's result is complete." + "No chunks arrived for the listed nodes: their activities ran in another " + "process (several replicas) or before this stream was opened. Streaming only " + "works while the activities run in the process that serves the stream; the " + "run's result is complete." ) def stream_unavailable_event( - final: Dict[str, Any], seen_steps: Set[int], workflow_id: str + final: Dict[str, Any], seen: Set[Tuple[int, str]], workflow_id: str ) -> Optional[StreamEvent]: """The ``stream_unavailable`` event for a finished run, if it applies. - Every node that runs here sends at least its ``updates`` chunk, so a step - of a completed run from which nothing arrived had its activities elsewhere. - A run that failed is just a failure, and one with no step count (or none - run) has nothing to report. + ``seen`` holds the ``(step, node)`` pairs whose ``updates`` chunk arrived; + every node that runs here sends one when it finishes, so an executed node + without one had its activity (or its last attempt) elsewhere, even when + other nodes of its step streamed here. A final without ``executed`` (a run + started before the workflow reported it) is judged per step instead. A run + that failed is just a failure, and one with no step count has nothing to + report. """ steps = final.get("steps") if final.get("type") != "workflow_completed" or not isinstance(steps, int): return None - missing = [step for step in range(steps) if step not in seen_steps] + executed = final.get("executed") + missing_nodes: List[Dict[str, Any]] = [] + if isinstance(executed, list): + missing_nodes = [ + {"step": display_step(step), "node": node} + for step, nodes in enumerate(executed) + for node in nodes + if (step, node) not in seen + ] + missing = sorted({m["step"] for m in missing_nodes}) + else: + seen_steps = {step for step, _ in seen} + missing = [ + display_step(step) for step in range(steps) if step not in seen_steps + ] if not missing: return None return StreamEvent( workflow_id=workflow_id, - step=missing[0], + step=missing[0] - 1, node="", attempt_id="", seq=0, @@ -360,5 +444,6 @@ def stream_unavailable_event( "workflow_id": workflow_id, "reason": UNAVAILABLE_REASON, "missing_steps": missing, + "missing_nodes": missing_nodes, }, ) diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 0bbfd6bd..93af5c13 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -18,7 +18,7 @@ from langchain_core.runnables.config import set_config_context from langgraph.runtime import Runtime -from langgraph.types import Command +from langgraph.types import Command, Send try: from langgraph.runtime import ExecutionInfo @@ -63,6 +63,9 @@ _default_graph_config: Optional["GraphConfig"] = None _default_input_mapper: Optional[Callable] = None _default_max_steps: int = 100 +# (source, node) edges whose Send payload was already warned about; cleared with +# the other registries so a second runner in the process hears it too. +_WARNED_SENDS: set = set() # Special node names START = "__start__" @@ -226,6 +229,7 @@ def clear_registries() -> None: _node_registry.clear() _condition_registry.clear() _channel_reducers.clear() + _WARNED_SENDS.clear() global _serializer, _default_graph_config, _default_input_mapper, _default_max_steps _serializer = None _default_graph_config = None @@ -305,6 +309,9 @@ def agent_workflow( # Start with entry point pending_nodes = [graph_config.entry_point] step = 0 + # The nodes that ran in each step, reported on the output so a streaming + # consumer can tell which node's chunks never arrived. + executed: List[List[str]] = [] # Main execution loop while step < max_steps: @@ -322,6 +329,7 @@ def agent_workflow( output=_extract_output(channel_state, graph_config.output_channels), channel_state=channel_state, steps=step, + executed=executed, status="completed", ).to_dict() @@ -334,9 +342,12 @@ def agent_workflow( output=_extract_output(channel_state, graph_config.output_channels), channel_state=channel_state, steps=step, + executed=executed, status="completed", ).to_dict() + executed.append(list(nodes_to_execute)) + # Execute all triggered nodes in parallel (each as a separate activity) node_tasks = [] for node_name in nodes_to_execute: @@ -371,6 +382,7 @@ def agent_workflow( output=_extract_output(channel_state, graph_config.output_channels), channel_state=channel_state, steps=step, + executed=executed, status="error", error=f"Node '{output.node_name}' failed: {output.error}", ).to_dict() @@ -416,6 +428,7 @@ def agent_workflow( ), channel_state=channel_state, steps=step, + executed=executed, status="error", error=f"Condition evaluation failed: {cond_output.error}", ).to_dict() @@ -427,6 +440,12 @@ def agent_workflow( if edge.target not in next_nodes: next_nodes.append(edge.target) + # Nodes a Command(goto=...) asked for run next as well, as in LangGraph. + for output in node_outputs: + for target in output.goto: + if target not in next_nodes: + next_nodes.append(target) + # Move to next step pending_nodes = next_nodes step += 1 @@ -438,6 +457,7 @@ def agent_workflow( output=_extract_output(channel_state, graph_config.output_channels), channel_state=channel_state, steps=step, + executed=executed, status="max_steps_reached", error=f"Max steps ({max_steps}) reached", ).to_dict() @@ -679,6 +699,16 @@ def _warn_stream_sink_missing( """Say, once per run, that a streamed run's chunks are going nowhere.""" if not registry.first_report(workflow_id): return + if registry.was_closed(workflow_id): + # This process had the stream and it ended (the client left, or the + # run's stream was closed): not a second replica, nothing to act on. + logger.debug( + "Run %s: its stream was closed in this process (its consumer left " + "or the stream ended); chunks of node %r are not delivered", + workflow_id, + node_name, + ) + return logger.warning( "Run %s is streamed but this process has no stream sink for it, so the " "chunks of node %r (and of any node that runs here) are not delivered. " @@ -769,7 +799,7 @@ def execute_node_activity( # "LangGraph" trace created by runner.invoke(). parent = _langsmith_parent(config) if streamer: - streamer.node_started(state) + streamer.node_started(state, config) try: if parent: import langsmith as ls @@ -802,6 +832,7 @@ def execute_node_activity( return ExecuteNodeOutput( node_name=node_name, writes=writes, + goto=_result_to_gotos(result, node_name), ).to_dict() @@ -888,6 +919,7 @@ def evaluate_condition_activity( next_nodes = [] for item in items: if hasattr(item, "node"): + _warn_send_payload(cond_input.source_node, item) next_nodes.append(item.node) elif path_map is None: next_nodes.append(item if isinstance(item, str) else str(item)) @@ -1073,11 +1105,59 @@ def _result_to_raw_writes(result: Any) -> List[Tuple[str, Any]]: return [("__result__", result)] +def _warn_send_payload(source: str, send: Any) -> None: + """Say, once per edge, that a ``Send`` runs its node on the channel state. + + LangGraph hands the node the ``Send`` argument as its input. Here the node + reads the channel state, so a node that depends on the argument gets the + wrong data (the prebuilt agent's tools node, which passes the state, is fine). + """ + key = (source, send.node) + if getattr(send, "arg", None) is None or key in _WARNED_SENDS: + return + _WARNED_SENDS.add(key) + logger.warning( + "Send(%r, ...) from %r: the payload is not delivered, node %r runs on the " + "channel state. A node that reads the Send argument gets different data " + "than under LangGraph.", + send.node, + source, + send.node, + ) + + +def _result_to_gotos(result: Any, source: str) -> List[str]: + """The nodes a ``Command(goto=...)`` result asks to run next. + + ``END`` is skipped (it ends that branch, which running nothing does). A + ``Send`` in ``goto`` runs its node on the channel state; see + :func:`_warn_send_payload`. + """ + if isinstance(result, Command): + commands: List[Any] = [result] + elif isinstance(result, list) and result and isinstance(result[0], Command): + commands = result + else: + return [] + targets: List[str] = [] + for cmd in commands: + goto = getattr(cmd, "goto", None) or () + for item in [goto] if isinstance(goto, (str, Send)) else goto: + if isinstance(item, Send): + _warn_send_payload(source, item) + name = item.node + else: + name = str(item) + if name != END and name not in targets: + targets.append(name) + return targets + + def _command_to_raw_writes(cmd: Any) -> List[Tuple[str, Any]]: """Extract ``(channel, value)`` pairs from the ``update`` of a Command. - This helper only inspects ``cmd.update``. Any ``goto`` / control-flow - information on the Command is ignored by this workflow runner. + This helper only inspects ``cmd.update``; ``goto`` is read by + :func:`_result_to_gotos`. Args: cmd: A LangGraph Command instance whose ``update`` field encodes channel writes. @@ -1120,11 +1200,6 @@ def _result_to_writes(result: Any) -> List[NodeWrite]: return _serialize_writes(_result_to_raw_writes(result)) -def _command_to_writes(cmd: Any) -> List[NodeWrite]: - """Serialized form of :func:`_command_to_raw_writes`.""" - return _serialize_writes(_command_to_raw_writes(cmd)) - - def _serialize_value(value: Any) -> Any: """Serialize a value for storage. From 7857b0321baca464a81fa6e06574629eb884ca4f Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Wed, 25 Nov 2026 23:56:29 +0100 Subject: [PATCH 07/73] feat(langgraph): run START targets, waiting edges, subgraph and async nodes as LangGraph does The runner used to start at a single node and never read waiting edges, so a graph with several START edges, a conditional START edge or add_edge([a, b], c) ran fewer nodes than LangGraph and still ended completed. The graph config now lists every START target and the waiting edges, the first step runs all the targets, and a join fires in the step after its last source. A config written before this has no entry_points and starts as it did, so instances in flight replay unchanged. A step that reaches END no longer stops the other branches. A node that returns an instance of the state schema writes its fields, a subgraph node streams only its own output message, and a Runnable with an async entry runs through ainvoke while a plain sync node stays on the sync entry. The "messages" metadata lists every trigger channel of the node. The stream helpers used by astream() move into stream_events.py, and the poll retry is limited to gRPC statuses and errors that can pass. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 39 ++- diagrid/agent/langgraph/README.md | 19 +- diagrid/agent/langgraph/models.py | 35 ++- diagrid/agent/langgraph/runner.py | 347 +++++++++------------- diagrid/agent/langgraph/stream_events.py | 197 ++++++++++++ diagrid/agent/langgraph/streaming.py | 55 +++- diagrid/agent/langgraph/workflow.py | 362 ++++++++++++++++------- 7 files changed, 718 insertions(+), 336 deletions(-) create mode 100644 diagrid/agent/langgraph/stream_events.py diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 8f020431..537f0b65 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -64,20 +64,45 @@ def report_usage(package: str, **dimensions: object) -> None: POLL_RETRY_MAX_SECONDS = 10.0 -def _is_transient_poll_error(error: BaseException) -> bool: - """A failed poll worth retrying: the call failed to get through. +def _transient_grpc_codes() -> frozenset: # type: ignore[type-arg] + import grpc + + return frozenset( + { + grpc.StatusCode.UNAVAILABLE, + grpc.StatusCode.DEADLINE_EXCEEDED, + grpc.StatusCode.ABORTED, + grpc.StatusCode.RESOURCE_EXHAUSTED, + grpc.StatusCode.CANCELLED, + } + ) - A gRPC error or a connection/OS-level one (a sidecar restarting, a dropped - connection). A programming or credentials error is not transient and - surfaces at once. + +def _is_transient_poll_error(error: BaseException) -> bool: + """A failed poll worth retrying: the call may succeed if tried again. + + A gRPC error with a status that says the sidecar was briefly unreachable + or busy (``UNAVAILABLE``, ``DEADLINE_EXCEEDED``, ``ABORTED``, + ``RESOURCE_EXHAUSTED``, ``CANCELLED``), or a connection or timeout error. + Anything else cannot get better by waiting and surfaces at once: a + permission, authentication or argument status, a bad socket path + (``FileNotFoundError``), a TLS failure, a programming error. """ - if isinstance(error, OSError): # ConnectionError, TimeoutError, ... + if isinstance(error, (ConnectionError, TimeoutError)): return True try: import grpc except ImportError: # pragma: no cover - dapr depends on grpcio return False - return isinstance(error, grpc.RpcError) + if not isinstance(error, grpc.RpcError): + return False + code_of = getattr(error, "code", None) + if not callable(code_of): + return False + try: + return code_of() in _transient_grpc_codes() + except Exception: + return False def fold_run_event(result: dict, event: dict) -> bool: # type: ignore[type-arg] diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 5387c764..c5e3f05d 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -155,7 +155,9 @@ Closing the stream does not cancel the Dapr workflow, which runs to completion. ### Over HTTP -`serve()` answers `POST /agent/run` with `"stream": true` as server-sent events. +`serve()` answers `POST /agent/run` with `"stream": true` (the JSON boolean; +any other value is a plain request and the key reaches the graph) as +server-sent events. `stream_mode` (a mode or a list; default all three) picks the chunks; an unsupported one is refused with a `422` before the stream starts. The first event is `workflow_started`. An idle stream sends a `: keepalive` comment every @@ -171,11 +173,18 @@ a non-streaming call returns and publishes for the same run, so a run that ends with `status: "error"` is published as that call reports it (`workflow_completed` with the error string) even though the stream's last event is `workflow_failed`. -A failed status poll (the sidecar restarting, a dropped call) is retried for -about a minute and does not fail the run. If the stream still cannot follow it, -it ends with `workflow_failed` whose `error.error_type` is `PollError` and +A failed status poll that looks transient (a gRPC or connection error: the +sidecar restarting, a dropped call) is retried for about a minute and does not +fail the run. If the stream still cannot follow it, it ends with +`workflow_failed` whose `error.error_type` is `PollError` and `workflow_still_running` is `true`: the workflow may yet complete, nothing is -published for it, and `GET /agent/run/{workflow_id}` tells how it ended. +published for it, and `GET /agent/run/{workflow_id}` tells how it ended. A +failure of the stream itself after `workflow_started` is reported the same way +with `error_type` `StreamError`. + +A chunk that cannot be encoded (a `custom` value whose `to_dict` raises, say) is +sent as `{"unserializable": ""}`, counted in the final event's +`dropped`, and does not end the stream. `stream` and `stream_mode` are reserved keys on a streaming request: they are removed before the graph (or your `input_mapper`) sees it. On a plain request diff --git a/diagrid/agent/langgraph/models.py b/diagrid/agent/langgraph/models.py index 294de267..5b32e282 100644 --- a/diagrid/agent/langgraph/models.py +++ b/diagrid/agent/langgraph/models.py @@ -87,6 +87,26 @@ def from_dict(cls, data: Dict[str, Any]) -> "EdgeConfig": ) +@dataclass +class WaitingEdgeConfig: + """A join: ``add_edge([a, b], target)`` runs ``target`` once every source ran. + + Attributes: + sources: The nodes that must all have run + target: The node that runs after the last of them + """ + + sources: List[str] + target: str + + def to_dict(self) -> Dict[str, Any]: + return {"sources": list(self.sources), "target": self.target} + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "WaitingEdgeConfig": + return cls(sources=list(data["sources"]), target=data["target"]) + + @dataclass class GraphConfig: """Configuration for the entire LangGraph. @@ -95,10 +115,15 @@ class GraphConfig: name: Graph name nodes: List of node configurations edges: List of edge configurations - entry_point: The entry node name + entry_point: The entry node name (the first of ``entry_points``) finish_points: Nodes that lead to END input_channels: Channels that accept input output_channels: Channels that produce output + entry_points: Every node a START edge leads to, which all run in the + first step. Conditional START edges are in ``edges`` and are + evaluated before it. ``None`` for a config written before this + field existed: then ``entry_point`` alone starts the run. + waiting_edges: Joins; a node waits until all their sources have run. """ name: str @@ -108,6 +133,8 @@ class GraphConfig: finish_points: List[str] = field(default_factory=list) input_channels: List[str] = field(default_factory=list) output_channels: List[str] = field(default_factory=list) + entry_points: Optional[List[str]] = None + waiting_edges: List[WaitingEdgeConfig] = field(default_factory=list) def to_dict(self) -> Dict[str, Any]: return { @@ -118,6 +145,8 @@ def to_dict(self) -> Dict[str, Any]: "finish_points": self.finish_points, "input_channels": self.input_channels, "output_channels": self.output_channels, + "entry_points": self.entry_points, + "waiting_edges": [w.to_dict() for w in self.waiting_edges], } @classmethod @@ -130,6 +159,10 @@ def from_dict(cls, data: Dict[str, Any]) -> "GraphConfig": finish_points=data.get("finish_points", []), input_channels=data.get("input_channels", []), output_channels=data.get("output_channels", []), + entry_points=data.get("entry_points"), + waiting_edges=[ + WaitingEdgeConfig.from_dict(w) for w in data.get("waiting_edges") or [] + ], ) diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 98fb299a..b77a48ca 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -35,6 +35,7 @@ STREAM_DROPPED, STREAM_UNAVAILABLE, WORKFLOW_STARTED, + InProcessSink, StreamClosed, StreamEvent, StreamSinkRegistry, @@ -46,6 +47,7 @@ GraphWorkflowInput, GraphWorkflowOutput, NodeConfig, + WaitingEdgeConfig, ) from .streaming import ( EXECUTED_KEY, @@ -58,6 +60,18 @@ normalize_stream_mode, to_wire, ) +from .stream_events import ( + FINAL_EVENTS, + KEEPALIVE, + closing_events, + count_unencodable, + encode_chunk, + failure_event, + next_item, + route_astream_item, + started_event, + without_executed, +) from .workflow import ( agent_workflow, evaluate_condition_activity, @@ -65,6 +79,7 @@ make_node_activity, node_activity_name, register_node, + register_node_triggers, register_condition, register_channel_reducer, set_default_graph_config, @@ -79,105 +94,28 @@ logger = logging.getLogger(__name__) - -_FINAL_EVENTS = ( - "workflow_completed", - "workflow_failed", - "workflow_terminated", - "workflow_error", -) - - _TRANSPORT_KEYS = ("stream", "stream_mode") -def _encode_chunk(event: StreamEvent) -> Tuple[Any, bool]: - """``(wire form, ok)`` of a chunk; a chunk that cannot be encoded is replaced. - - ``to_wire`` runs arbitrary ``to_dict`` / ``model_dump`` on whatever a node - wrote to ``custom``, so it can raise. That is a problem with one chunk, not - with the run: the stream carries on with a placeholder. - """ - try: - return to_wire(event.mode, event.data), True - except Exception as e: - try: - text = repr(event.data)[:200] - except Exception: - text = f"<{type(event.data).__name__}>" - logger.warning( - "Run %s: a %r chunk of node %r could not be encoded (%s: %s); " - "sending a placeholder", - event.workflow_id, - event.mode, - event.node, - type(e).__name__, - e, - ) - return {"unserializable": text}, False - - -def _warn_reset_unseen(workflow_id: str, data: Dict[str, Any]) -> None: - """Say that a retried node's earlier chunks stay in a stream that cannot show it. +def _run_identity( + config: Optional[Dict[str, Any]], + thread_id: Optional[str], + workflow_id: Optional[str], +) -> Tuple[str, str, Dict[str, Any]]: + """``(thread_id, workflow_id, config)`` for a streamed run. - A single-mode ``astream`` yields bare chunks, as native ``astream`` does, so - a node reset has no place in it; with no ``on_control`` either, the - consumer is never told and its text for that node holds both attempts. + The thread id is the one given, else ``config["configurable"]["thread_id"]``, + else new. The config handed to the run carries that one id, so the id the + run reports is the one its nodes see. """ - logger.warning( - "Run %s: node %r was retried (step %s) and its first attempt's chunks " - "were already yielded. This astream has no way to tell you: pass " - "on_control, or a list of stream modes, to receive node_reset and " - "discard the partial output.", - workflow_id, - data.get("node"), - data.get("step"), - ) - - -def _count_unencodable(final: Dict[str, Any], unencodable: int) -> Dict[str, Any]: - """``final`` with the chunks lost to encoding added to its ``dropped`` count.""" - if not unencodable: - return final - return {**final, "dropped": int(final.get("dropped") or 0) + unencodable} - - -#: Yielded by ``_stream_events`` (when asked) after an idle stretch. -KEEPALIVE = object() - - -def _started_event(event: Dict[str, Any], workflow_id: str, thread_id: str) -> Any: - """The stream's first event: the ids a client needs to find or stop its run.""" - return StreamEvent( - workflow_id=workflow_id, - step=-1, - node="", - attempt_id="", - seq=0, - ns=(), - mode=WORKFLOW_STARTED, - data={ - "workflow_id": event.get("workflow_id") or workflow_id, - "thread_id": event.get("thread_id") or thread_id, - }, - ) - - -def _without_executed(event: Dict[str, Any]) -> Dict[str, Any]: - """``event`` minus the per-step node list, which is for the stream only.""" - if EXECUTED_KEY not in event: - return event - return {k: v for k, v in event.items() if k != EXECUTED_KEY} - - -async def _next_item(sink: Any, keepalive: bool) -> Any: - """The next item of ``sink``, or :data:`KEEPALIVE` after an idle stretch.""" - if not keepalive: - return await sink.get() - try: - return await asyncio.wait_for(sink.get(), stream_module.SSE_KEEPALIVE_SECONDS) - except asyncio.TimeoutError: - return KEEPALIVE + configurable = (config or {}).get("configurable") or {} + thread = str(thread_id or configurable.get("thread_id") or uuid.uuid4()) + run_config = { + **(config or {}), + "configurable": {**configurable, "thread_id": thread}, + STREAM_RUN_KEY: True, + } + return thread, workflow_id or f"graph-{thread}-{uuid.uuid4().hex[:8]}", run_config class DaprWorkflowGraphRunner(BaseWorkflowRunner): @@ -341,7 +279,6 @@ def _extract_graph_config(self) -> GraphConfig: """Extract configuration from the compiled graph.""" nodes = [] edges = [] - entry_point = None finish_points = [] graph_nodes = getattr(self._graph, "nodes", {}) @@ -362,6 +299,7 @@ def _extract_graph_config(self) -> GraphConfig: else list(node_spec.channels or []) ) + register_node_triggers(node_name, triggers) nodes.append( NodeConfig( name=node_name, @@ -379,8 +317,6 @@ def _extract_graph_config(self) -> GraphConfig: source_name = source if source != "__start__" else START target_name = target if target != "__end__" else END - if source_name == START: - entry_point = target_name if target_name == END: if source_name not in finish_points: finish_points.append(source_name) @@ -419,8 +355,23 @@ def _extract_graph_config(self) -> GraphConfig: ) ) - if not entry_point and nodes: - entry_point = nodes[0].name + entry_points = sorted( + {e.target for e in edges if e.source == START and not e.condition} + ) + has_start_branch = any(e.source == START and e.condition for e in edges) + if not entry_points and not has_start_branch and nodes: + entry_points = [nodes[0].name] + entry_point = ( + entry_points[0] if entry_points else (nodes[0].name if nodes else "") + ) + + waiting_edges = [ + WaitingEdgeConfig(sources=sorted(sources), target=target) + for sources, target in sorted( + getattr(builder, "waiting_edges", None) or (), + key=lambda w: (sorted(w[0]), w[1]), + ) + ] input_channels = [] output_channels = [] @@ -441,10 +392,12 @@ def _extract_graph_config(self) -> GraphConfig: name=self._name, nodes=nodes, edges=edges, - entry_point=entry_point or (nodes[0].name if nodes else ""), + entry_point=entry_point, finish_points=finish_points, input_channels=input_channels, output_channels=output_channels, + entry_points=entry_points, + waiting_edges=waiting_edges, ) def _register_graph_components(self) -> None: @@ -871,34 +824,8 @@ async def astream( ) ) as events: async for item in events: - if isinstance(item, StreamEvent): - if item.mode in CONTROL_MODES: - control = StreamControl(item.mode, item.data) - if on_control is not None: - on_control(control) - # workflow_started only informs on_control: it is not - # something the stream modes of native astream have. - if is_list and item.mode != WORKFLOW_STARTED: - yield (control.kind, control.data) - elif ( - item.mode == NODE_RESET - and not is_list - and on_control is None - ): - _warn_reset_unseen(item.workflow_id, control.data) - elif item.mode in modes: - yield (item.mode, item.data) if is_list else item.data - else: - if item.get("dropped"): - control = StreamControl( - STREAM_DROPPED, {"dropped": item["dropped"]} - ) - if on_control is not None: - on_control(control) - if is_list: - yield (control.kind, control.data) - if item.get("type") == "workflow_failed": - raise GraphRunError(item) + for out in route_astream_item(item, modes, is_list, on_control): + yield out async def _stream_events( self, @@ -925,81 +852,37 @@ async def _stream_events( ``thread_id``). With ``keepalive`` set, :data:`KEEPALIVE` is yielded whenever nothing arrived for ``SSE_KEEPALIVE_SECONDS``. """ - configurable = (config or {}).get("configurable") or {} - thread_id = str(thread_id or configurable.get("thread_id") or uuid.uuid4()) - workflow_id = workflow_id or f"graph-{thread_id}-{uuid.uuid4().hex[:8]}" - # One thread id per run: the one the run reports is the one its nodes see. - run_config = { - **(config or {}), - "configurable": {**configurable, "thread_id": thread_id}, - STREAM_RUN_KEY: True, - } + thread_id, workflow_id, run_config = _run_identity( + config, thread_id, workflow_id + ) sink = self._stream_registry.open(workflow_id) task: Optional["asyncio.Task[None]"] = None seen_nodes: Set[Tuple[int, str]] = set() - - async def _pump() -> None: - final: Dict[str, Any] = {} - result: Dict[str, Any] = {} - try: - async for event in self.run_async( - input, - thread_id=thread_id, - config=run_config, - workflow_id=workflow_id, - poll_interval=poll_interval, - ): - fold_run_event(result, _without_executed(event)) - if event["type"] in _FINAL_EVENTS: - final = event - if on_result is not None: - await asyncio.to_thread(on_result, result) - except Exception as e: - logger.exception("Streamed run %s failed", workflow_id) - final = { - "type": "workflow_failed", - "error": {"message": str(e), "error_type": type(e).__name__}, - } - if result.get("instance_id"): - # The workflow was started and this is the stream failing - # (its status polls gave out), not the workflow: it may - # still complete. Say so, and publish nothing: a failure - # published for a run that then succeeds is a lie. - final["error"]["error_type"] = "PollError" - final["workflow_still_running"] = True - sink.close( - normalize_final(final, workflow_id=workflow_id, thread_id=thread_id) - ) - try: # Before the pump schedules the workflow: an activity can write the # moment it is scheduled, and the event must come before its chunks. - sink.put(_started_event({}, workflow_id, thread_id)) - task = asyncio.create_task(_pump()) + sink.put(started_event({}, workflow_id, thread_id)) + task = asyncio.create_task( + self._pump_run( + sink, + input, + thread_id, + workflow_id, + run_config, + poll_interval, + on_result, + ) + ) while True: - item = await _next_item(sink, keepalive) - if item is KEEPALIVE: - yield item - continue + item = await next_item(sink, keepalive) if isinstance(item, StreamClosed): # Unregister before handing over the result: chunks a late # activity attempt writes from here on are dropped. self._stream_registry.close(workflow_id, sink) - unavailable = stream_unavailable_event( - item.final, seen_nodes, workflow_id - ) - if unavailable is not None: - logger.warning( - "Streamed run %s: no chunks for steps %s (nodes %s)", - workflow_id, - unavailable.data["missing_steps"], - [m["node"] for m in unavailable.data["missing_nodes"]], - ) - yield unavailable - final = _without_executed(item.final) - yield {**final, "dropped": item.dropped} if item.dropped else final + for event in closing_events(item, seen_nodes, workflow_id): + yield event return - if item.mode == UPDATES: + if isinstance(item, StreamEvent) and item.mode == UPDATES: seen_nodes.add((item.step, item.node)) yield item finally: @@ -1007,21 +890,66 @@ async def _pump() -> None: # abandoned generator). That stops this stream only: the Dapr # workflow itself keeps running to completion. self._stream_registry.close(workflow_id, sink) - if task is not None and not task.done(): - if on_result is not None: - # Someone is waiting for the result on a topic: let the - # pump finish the run and hand it over, with no consumer. - self._detached_pumps.add(task) - task.add_done_callback(self._detached_pumps.discard) - else: - task.cancel() - await asyncio.gather(task, return_exceptions=True) + await self._release_pump(task, detach=on_result is not None) + + async def _pump_run( + self, + sink: InProcessSink, + input: Dict[str, Any], + thread_id: str, + workflow_id: str, + run_config: Dict[str, Any], + poll_interval: float, + on_result: Optional[Callable[[Dict[str, Any]], None]], + ) -> None: + """Follow the run, publish its result, and close ``sink`` with the final.""" + final: Dict[str, Any] = {} + result: Dict[str, Any] = {} + try: + async for event in self.run_async( + input, + thread_id=thread_id, + config=run_config, + workflow_id=workflow_id, + poll_interval=poll_interval, + ): + fold_run_event(result, without_executed(event)) + if event["type"] in FINAL_EVENTS: + final = event + if on_result is not None: + await asyncio.to_thread(on_result, result) + except Exception as e: + logger.exception("Streamed run %s failed", workflow_id) + # If the workflow was started this is the stream failing (its + # status polls gave out), not the workflow: it may still complete. + # Say so, and publish nothing: a failure published for a run that + # then succeeds is a lie. + started = bool(result.get("instance_id")) + final = failure_event(e, "PollError" if started else None) + if started: + final["workflow_still_running"] = True + sink.close(normalize_final(final, workflow_id=workflow_id, thread_id=thread_id)) + + async def _release_pump( + self, task: Optional["asyncio.Task[None]"], *, detach: bool + ) -> None: + """Let a pump whose consumer left finish (``detach``) or stop it.""" + if task is None or task.done(): + return + if detach: + # Someone is waiting for the result on a topic: let the pump finish + # the run and hand it over, with no consumer. + self._detached_pumps.add(task) + task.add_done_callback(self._detached_pumps.discard) + else: + task.cancel() + await asyncio.gather(task, return_exceptions=True) def _serialize_input(self, input: Dict[str, Any]) -> Dict[str, Any]: """Serialize input values for storage.""" - from .workflow import _serialize_value + from .workflow import _serialize_input - return {k: _serialize_value(v) for k, v in input.items()} + return _serialize_input(input) # ------------------------------------------------------------------ # Serve overrides @@ -1141,22 +1069,17 @@ async def _serve_stream( # type: ignore[override] continue if item.mode == WORKFLOW_STARTED: workflow_id = item.data["workflow_id"] - wire, ok = _encode_chunk(item) + wire, ok = encode_chunk(item) unencodable += 0 if ok else 1 yield item.mode, wire else: - yield item["type"], _count_unencodable(item, unencodable) + yield item["type"], count_unencodable(item, unencodable) except Exception as e: logger.exception("Streaming run failed") - failed: Dict[str, Any] = { - "type": "workflow_failed", - "error": {"message": str(e), "error_type": type(e).__name__}, - } + # Once the workflow has started this is the stream failing, not the + # run: it goes on, and may well succeed (see _pump_run). + failed = failure_event(e, "StreamError" if workflow_id else None) if workflow_id: - # The workflow started and this is the stream failing, not the - # run: it goes on, and may well succeed. Say so, as _pump does - # for a failed status poll, rather than report it as failed. - failed["error"]["error_type"] = "StreamError" failed["workflow_still_running"] = True yield ( "workflow_failed", diff --git a/diagrid/agent/langgraph/stream_events.py b/diagrid/agent/langgraph/stream_events.py new file mode 100644 index 00000000..da62b6a5 --- /dev/null +++ b/diagrid/agent/langgraph/stream_events.py @@ -0,0 +1,197 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Pieces of the LangGraph runner's streaming: encoding, events and routing.""" + +import asyncio +import logging +from typing import Any, Callable, Dict, List, Optional, Set, Tuple + +from diagrid.agent.core.workflow import stream as stream_module +from diagrid.agent.core.workflow.stream import ( + CONTROL_MODES, + NODE_RESET, + STREAM_DROPPED, + WORKFLOW_STARTED, + StreamClosed, + StreamEvent, +) + +from .streaming import ( + EXECUTED_KEY, + GraphRunError, + StreamControl, + stream_unavailable_event, + to_wire, +) + +logger = logging.getLogger(__name__) + +FINAL_EVENTS = ( + "workflow_completed", + "workflow_failed", + "workflow_terminated", + "workflow_error", +) + + +def encode_chunk(event: StreamEvent) -> Tuple[Any, bool]: + """``(wire form, ok)`` of a chunk; a chunk that cannot be encoded is replaced. + + ``to_wire`` runs arbitrary ``to_dict`` / ``model_dump`` on whatever a node + wrote to ``custom``, so it can raise. That is a problem with one chunk, not + with the run: the stream carries on with a placeholder. + """ + try: + return to_wire(event.mode, event.data), True + except Exception as e: + try: + text = repr(event.data)[:200] + except Exception: + text = f"<{type(event.data).__name__}>" + logger.warning( + "Run %s: a %r chunk of node %r could not be encoded (%s: %s); " + "sending a placeholder", + event.workflow_id, + event.mode, + event.node, + type(e).__name__, + e, + ) + return {"unserializable": text}, False + + +def warn_reset_unseen(workflow_id: str, data: Dict[str, Any]) -> None: + """Say that a retried node's earlier chunks stay in a stream that cannot show it. + + A single-mode ``astream`` yields bare chunks, as native ``astream`` does, so + a node reset has no place in it; with no ``on_control`` either, the + consumer is never told and its text for that node holds both attempts. + """ + logger.warning( + "Run %s: node %r was retried (step %s) and its first attempt's chunks " + "were already yielded. This astream has no way to tell you: pass " + "on_control, or a list of stream modes, to receive node_reset and " + "discard the partial output.", + workflow_id, + data.get("node"), + data.get("step"), + ) + + +def count_unencodable(final: Dict[str, Any], unencodable: int) -> Dict[str, Any]: + """``final`` with the chunks lost to encoding added to its ``dropped`` count.""" + if not unencodable: + return final + return {**final, "dropped": int(final.get("dropped") or 0) + unencodable} + + +#: Yielded by ``_stream_events`` (when asked) after an idle stretch. +KEEPALIVE = object() + + +def started_event(event: Dict[str, Any], workflow_id: str, thread_id: str) -> Any: + """The stream's first event: the ids a client needs to find or stop its run.""" + return StreamEvent( + workflow_id=workflow_id, + step=-1, + node="", + attempt_id="", + seq=0, + ns=(), + mode=WORKFLOW_STARTED, + data={ + "workflow_id": event.get("workflow_id") or workflow_id, + "thread_id": event.get("thread_id") or thread_id, + }, + ) + + +def without_executed(event: Dict[str, Any]) -> Dict[str, Any]: + """``event`` minus the per-step node list, which is for the stream only.""" + if EXECUTED_KEY not in event: + return event + return {k: v for k, v in event.items() if k != EXECUTED_KEY} + + +async def next_item(sink: Any, keepalive: bool) -> Any: + """The next item of ``sink``, or :data:`KEEPALIVE` after an idle stretch.""" + if not keepalive: + return await sink.get() + try: + return await asyncio.wait_for(sink.get(), stream_module.SSE_KEEPALIVE_SECONDS) + except asyncio.TimeoutError: + return KEEPALIVE + + +def failure_event( + error: BaseException, error_type: Optional[str] = None +) -> Dict[str, Any]: + """A ``workflow_failed`` event for ``error``. + + ``error_type`` replaces the exception's own type name; it is how a stream + failure says it is not the run's (see ``PollError`` and ``StreamError``). + """ + return { + "type": "workflow_failed", + "error": { + "message": str(error), + "error_type": error_type or type(error).__name__, + }, + } + + +def route_astream_item( + item: Any, + modes: List[str], + is_list: bool, + on_control: Optional[Callable[[StreamControl], None]], +) -> List[Any]: + """What ``astream`` yields for one item of the event stream. + + Hands control events to ``on_control``, and raises :class:`GraphRunError` + for a terminal ``workflow_failed``. + """ + out: List[Any] = [] + if isinstance(item, StreamEvent): + if item.mode in CONTROL_MODES: + control = StreamControl(item.mode, item.data) + if on_control is not None: + on_control(control) + # workflow_started only informs on_control: it is not something the + # stream modes of native astream have. + if is_list and item.mode != WORKFLOW_STARTED: + out.append((control.kind, control.data)) + elif item.mode == NODE_RESET and not is_list and on_control is None: + warn_reset_unseen(item.workflow_id, control.data) + elif item.mode in modes: + out.append((item.mode, item.data) if is_list else item.data) + return out + if item.get("dropped"): + control = StreamControl(STREAM_DROPPED, {"dropped": item["dropped"]}) + if on_control is not None: + on_control(control) + if is_list: + out.append((control.kind, control.data)) + if item.get("type") == "workflow_failed": + raise GraphRunError(item) + return out + + +def closing_events( + closed: StreamClosed, seen_nodes: Set[Tuple[int, str]], workflow_id: str +) -> List[Any]: + """The items a stream ends with: ``stream_unavailable`` if due, then the final.""" + out: List[Any] = [] + unavailable = stream_unavailable_event(closed.final, seen_nodes, workflow_id) + if unavailable is not None: + logger.warning( + "Streamed run %s: no chunks for steps %s (nodes %s)", + workflow_id, + unavailable.data["missing_steps"], + [m["node"] for m in unavailable.data["missing_nodes"]], + ) + out.append(unavailable) + final = without_executed(closed.final) + out.append({**final, "dropped": closed.dropped} if closed.dropped else final) + return out diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index d01f4804..0ed54e9f 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -9,12 +9,13 @@ every task. Chunks go to a :class:`StreamSink` wrapped in a ``StreamEvent``. """ +import functools import itertools import logging import threading import uuid from dataclasses import dataclass -from typing import Any, Dict, List, Optional, Set, Tuple +from typing import Any, Dict, List, Optional, Sequence, Set, Tuple from langchain_core.load import dumpd from langchain_core.load.serializable import Serializable @@ -61,6 +62,45 @@ class StreamControl: data: Dict[str, Any] +@functools.lru_cache(maxsize=None) +def _own_node_handler_class() -> Any: + """``StreamMessagesHandler`` limited to the node the activity runs. + + Native LangGraph (``subgraphs=False``) tells a nested graph's runs by their + checkpoint namespace having more than one segment. Here a node that is a + compiled subgraph runs as a plain call inside the activity, so the nested + graph's namespace has a single segment and the stock handler would stream + its inner nodes' tokens under their own names. Everything whose + ``langgraph_checkpoint_ns`` is not this node's belongs to a nested graph and + is ignored; the node's own output message is still sent when it finishes, + as native does. + """ + from langgraph.pregel._messages import StreamMessagesHandler + + class OwnNodeMessagesHandler(StreamMessagesHandler): # type: ignore[misc] + def __init__(self, *args: Any, own_checkpoint_ns: str, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._own_checkpoint_ns = own_checkpoint_ns + + def _nested(self, metadata: Optional[Dict[str, Any]]) -> bool: + if not metadata: + return False + ns = metadata.get("langgraph_checkpoint_ns") + return ns is not None and ns != self._own_checkpoint_ns + + def on_chat_model_start(self, *args: Any, **kwargs: Any) -> Any: + if self._nested(kwargs.get("metadata")): + return None + return super().on_chat_model_start(*args, **kwargs) + + def on_chain_start(self, *args: Any, **kwargs: Any) -> Any: + if self._nested(kwargs.get("metadata")): + return None + return super().on_chain_start(*args, **kwargs) + + return OwnNodeMessagesHandler + + class NodeStreamer: """Streams one activity attempt of one node into a sink.""" @@ -77,6 +117,7 @@ def __init__( node: str, task_id: Any, thread_id: Optional[str] = None, + triggers: Optional[Sequence[str]] = None, ) -> None: self._sink = sink self._thread_id = thread_id @@ -84,6 +125,7 @@ def __init__( self._step = step self._node = node self._task_id = task_id + self._triggers = tuple(triggers) if triggers else None self._attempt_id = uuid.uuid4().hex self._seq = itertools.count() # A node may emit from several threads (parallel tool calls); seq is @@ -100,7 +142,8 @@ def metadata(self) -> Dict[str, Any]: # Pregel numbers the first node after START as step 1. "langgraph_step": display_step(self._step), "langgraph_node": self._node, - "langgraph_triggers": (f"branch:to:{self._node}",), + # Every trigger channel of the node, sorted, as Pregel lists them. + "langgraph_triggers": self._triggers or (f"branch:to:{self._node}",), "langgraph_path": ("__pregel_pull", self._node), "langgraph_checkpoint_ns": f"{self._node}:{self._task_id}", "checkpoint_ns": f"{self._node}:{self._task_id}", @@ -137,9 +180,11 @@ def _messages_handler(self) -> Any: """ if self._handler is None and not self._handler_unusable: try: - from langgraph.pregel._messages import StreamMessagesHandler - - self._handler = StreamMessagesHandler(self._on_chunk, False) + self._handler = _own_node_handler_class()( + self._on_chunk, + False, + own_checkpoint_ns=self.metadata["langgraph_checkpoint_ns"], + ) except (ImportError, TypeError, AttributeError) as e: self._handler_unusable = True NodeStreamer._log_handler_failure(e) diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 93af5c13..13892e75 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -4,10 +4,13 @@ """Dapr Workflow definitions for durable LangGraph execution.""" import contextlib +import dataclasses +import functools import logging +import uuid from datetime import timedelta from dataclasses import dataclass -from typing import Any, Callable, Dict, Generator, List, Optional, Tuple +from typing import Any, Callable, Dict, Generator, List, Optional, Set, Tuple from dapr.ext.workflow import ( DaprWorkflowContext, @@ -16,7 +19,8 @@ when_all, ) -from langchain_core.runnables.config import set_config_context +from langchain_core.runnables.config import run_in_executor, set_config_context +from pydantic import BaseModel from langgraph.runtime import Runtime from langgraph.types import Command, Send @@ -63,6 +67,8 @@ _default_graph_config: Optional["GraphConfig"] = None _default_input_mapper: Optional[Callable] = None _default_max_steps: int = 100 +# Every trigger channel of each node, as LangGraph lists them in a task's metadata. +_node_triggers: Dict[str, Tuple[str, ...]] = {} # (source, node) edges whose Send payload was already warned about; cleared with # the other registries so a second runner in the process hears it too. _WARNED_SENDS: set = set() @@ -116,6 +122,16 @@ def register_node(name: str, func: Callable) -> None: _node_registry[name] = func +def register_node_triggers(name: str, triggers: List[str]) -> None: + """Record the channels that trigger a node (for ``langgraph_triggers``).""" + _node_triggers[name] = tuple(sorted(triggers)) + + +def get_node_triggers(name: str) -> Optional[Tuple[str, ...]]: + """The trigger channels of a node, sorted as LangGraph reports them.""" + return _node_triggers.get(name) + + def get_registered_node(name: str) -> Optional[Callable]: """Get a registered node function by name.""" return _node_registry.get(name) @@ -230,6 +246,7 @@ def clear_registries() -> None: _condition_registry.clear() _channel_reducers.clear() _WARNED_SENDS.clear() + _node_triggers.clear() global _serializer, _default_graph_config, _default_input_mapper, _default_max_steps _serializer = None _default_graph_config = None @@ -306,13 +323,35 @@ def agent_workflow( max_retry_interval=timedelta(seconds=30), ) - # Start with entry point - pending_nodes = [graph_config.entry_point] step = 0 # The nodes that ran in each step, reported on the output so a streaming # consumer can tell which node's chunks never arrived. executed: List[List[str]] = [] + # Start with the nodes the START edges lead to; a conditional START edge is + # evaluated on the input, as LangGraph does. + if graph_config.entry_points is None: # a config from before entry_points + pending_nodes = [graph_config.entry_point] + else: + pending_nodes = list(graph_config.entry_points) + for edge in graph_config.edges: + if edge.source != START or not edge.condition: + continue + cond_output = yield from _evaluate_edge( + ctx, edge, START, channel_state, config, thread_id, retry_policy + ) + if cond_output.error: + if not ctx.is_replaying: + _close_langsmith_parent_trace_async(config) + return _condition_failed( + graph_config, channel_state, step, executed, cond_output.error + ) + for n in cond_output.next_nodes: + if n not in pending_nodes: + pending_nodes.append(n) + # Joins: how many of each waiting edge's sources have run since it last fired. + joined: List[Set[str]] = [set() for _ in graph_config.waiting_edges] + # Main execution loop while step < max_steps: # Log workflow step for debugging @@ -321,19 +360,8 @@ def agent_workflow( f" [WORKFLOW] Step {step}, pending_nodes={pending_nodes}", flush=True ) - # Check if END is reached - if END in pending_nodes or not pending_nodes: - if not ctx.is_replaying: - _close_langsmith_parent_trace_async(config) - return GraphWorkflowOutput( - output=_extract_output(channel_state, graph_config.output_channels), - channel_state=channel_state, - steps=step, - executed=executed, - status="completed", - ).to_dict() - - # Filter out END from nodes to execute + # END ends the run only when nothing else is pending: another branch of + # the step may still have nodes to run, as in LangGraph. nodes_to_execute = [n for n in pending_nodes if n != END] if not nodes_to_execute: if not ctx.is_replaying: @@ -405,33 +433,25 @@ def agent_workflow( if edge.source == node_name: if edge.condition: # Evaluate conditional edge (as activity) - cond_input = EvaluateConditionInput( - source_node=node_name, - condition_name=edge.condition, - channel_state=channel_state, - config=config, - thread_id=thread_id, - path_map=edge.path_map, + cond_output = yield from _evaluate_edge( + ctx, + edge, + node_name, + channel_state, + config, + thread_id, + retry_policy, ) - cond_result = yield ctx.call_activity( - evaluate_condition_activity, - input=cond_input.to_dict(), - retry_policy=retry_policy, - ) - cond_output = EvaluateConditionOutput.from_dict(cond_result) if cond_output.error: if not ctx.is_replaying: _close_langsmith_parent_trace_async(config) - return GraphWorkflowOutput( - output=_extract_output( - channel_state, graph_config.output_channels - ), - channel_state=channel_state, - steps=step, - executed=executed, - status="error", - error=f"Condition evaluation failed: {cond_output.error}", - ).to_dict() + return _condition_failed( + graph_config, + channel_state, + step, + executed, + cond_output.error, + ) for n in cond_output.next_nodes: if n not in next_nodes: next_nodes.append(n) @@ -440,6 +460,14 @@ def agent_workflow( if edge.target not in next_nodes: next_nodes.append(edge.target) + # A join fires, once, in the step after the last of its sources ran. + for seen, join in zip(joined, graph_config.waiting_edges): + seen.update(n for n in nodes_to_execute if n in join.sources) + if seen.issuperset(join.sources): + seen.clear() + if join.target not in next_nodes: + next_nodes.append(join.target) + # Nodes a Command(goto=...) asked for run next as well, as in LangGraph. for output in node_outputs: for target in output.goto: @@ -463,6 +491,50 @@ def agent_workflow( ).to_dict() +def _evaluate_edge( + ctx: DaprWorkflowContext, + edge: Any, + source_node: str, + channel_state: ChannelState, + config: Optional[Dict[str, Any]], + thread_id: Optional[str], + retry_policy: RetryPolicy, +) -> Generator[Any, Any, EvaluateConditionOutput]: + """Evaluate a conditional edge as an activity; ``yield from`` it.""" + cond_input = EvaluateConditionInput( + source_node=source_node, + condition_name=edge.condition, + channel_state=channel_state, + config=config, + thread_id=thread_id, + path_map=edge.path_map, + ) + cond_result = yield ctx.call_activity( + evaluate_condition_activity, + input=cond_input.to_dict(), + retry_policy=retry_policy, + ) + return EvaluateConditionOutput.from_dict(cond_result) + + +def _condition_failed( + graph_config: GraphConfig, + channel_state: ChannelState, + step: int, + executed: List[List[str]], + error: str, +) -> Dict[str, Any]: + """The workflow output for a conditional edge that could not be evaluated.""" + return GraphWorkflowOutput( + output=_extract_output(channel_state, graph_config.output_channels), + channel_state=channel_state, + steps=step, + executed=executed, + status="error", + error=f"Condition evaluation failed: {error}", + ).to_dict() + + def _build_node_runtime( thread_id: Optional[str], ctx: WorkflowActivityContext, @@ -515,6 +587,20 @@ def _is_async_only(runnable: Any) -> bool: ) +def _has_async_entry(runnable: Any) -> bool: + """Whether ``runnable`` has a real async entry point, which a node should use. + + ``ToolNode`` has a sync ``func`` and an ``afunc``; its sync one cannot run + an ``async def`` tool (MCP adapter tools are such), its async one runs both, + as native ``astream`` does. A plain sync node also gets an ``afunc``, but + only a ``run_in_executor`` wrapper around its function: that is not one. + """ + afunc = getattr(runnable, "afunc", None) + if afunc is None: + return False + return not (isinstance(afunc, functools.partial) and afunc.func is run_in_executor) + + @dataclass class _NodeCall: """Everything one execution of a node needs, gathered by the activity.""" @@ -633,8 +719,8 @@ def _runnable_config(call: _NodeCall) -> Dict[str, Any]: def _invoke_runnable(call: _NodeCall, config: Dict[str, Any]) -> Any: - """Call a Runnable node; an async-only one returns a coroutine to await.""" - if _is_async_only(call.node_func): + """Call a Runnable node; one with an async entry returns a coroutine to await.""" + if _has_async_entry(call.node_func): return call.node_func.ainvoke(call.state, config=config) # type: ignore[attr-defined] return call.node_func.invoke(call.state, config=config) # type: ignore[attr-defined] @@ -720,6 +806,83 @@ def _warn_stream_sink_missing( ) +def _make_streamer( + ctx: WorkflowActivityContext, + node_input: ExecuteNodeInput, + config: Dict[str, Any], + registry: Optional[StreamSinkRegistry], +) -> Optional[NodeStreamer]: + """The streamer for this attempt of the node, or ``None`` when not streaming. + + Chunks are streamed only when a consumer registered a sink for this run; + otherwise nothing about the node's execution changes. + """ + node_name = node_input.node_name + sink = get_stream_sink(getattr(ctx, "workflow_id", None), registry=registry) + if sink is None: + if config.get(STREAM_RUN_KEY): + _warn_stream_sink_missing( + registry or default_registry, str(ctx.workflow_id), node_name + ) + return None + return NodeStreamer( + sink, + workflow_id=str(ctx.workflow_id), + step=node_input.step or 0, + node=node_name, + task_id=getattr(ctx, "task_id", ""), + thread_id=node_input.thread_id or config.get("thread_id"), + triggers=get_node_triggers(node_name), + ) + + +def _run_with_stream_hooks(call: _NodeCall, parent: Optional[str]) -> Any: + """Run the node, telling its streamer when it starts, finishes or fails. + + ``parent`` is the LangSmith parent trace to nest the node's run under. + """ + streamer = call.streamer + if streamer: + streamer.node_started(call.state, call.config) + try: + if parent: + import langsmith as ls + + with ls.trace( + name=call.node_name, + run_type="chain", + parent=parent, + inputs={"step": call.node_name}, + ): + result = _run_node(call) + else: + result = _run_node(call) + except BaseException as exc: + if streamer: + streamer.node_failed(exc) + raise + if streamer: + streamer.node_finished(result) + return result + + +def _node_output(call: _NodeCall, result: Any) -> Dict[str, Any]: + """The activity's output for a node that returned ``result``. + + Converts the result to writes, appends any side-channel writes queued via + CONFIG_KEY_SEND (e.g. StateBackend writing to the "files" channel from + sandbox tools), and streams the node's update. + """ + raw_writes = [*_result_to_raw_writes(result), *call.pending_sends] + if call.streamer: + call.streamer.updates(raw_writes) + return ExecuteNodeOutput( + node_name=call.node_name, + writes=_serialize_writes(raw_writes), + goto=_result_to_gotos(result, call.node_name), + ).to_dict() + + def execute_node_activity( ctx: WorkflowActivityContext, input_data: Dict[str, Any], @@ -757,83 +920,26 @@ def execute_node_activity( error=f"Node '{node_name}' not found in registry", ).to_dict() - # Reconstruct state from channel values - state = _reconstruct_state(node_input.channel_state) - # Extract tracing config config = node_input.config or {} - # Stream chunks only when a consumer registered a sink for this run; - # otherwise nothing below changes. - sink = get_stream_sink(getattr(ctx, "workflow_id", None), registry=stream_registry) - if sink is None and config.get(STREAM_RUN_KEY): - _warn_stream_sink_missing( - stream_registry or default_registry, str(ctx.workflow_id), node_name - ) - streamer = ( - NodeStreamer( - sink, - workflow_id=str(ctx.workflow_id), - step=node_input.step or 0, - node=node_name, - task_id=getattr(ctx, "task_id", ""), - thread_id=node_input.thread_id or config.get("thread_id"), - ) - if sink is not None - else None - ) - # Collect side-channel writes from CONFIG_KEY_SEND (used by StateBackend # to write to the "files" channel from sandbox tools). call = _NodeCall( ctx=ctx, node_input=node_input, node_func=node_func, - state=state, + state=_reconstruct_state(node_input.channel_state), config=config, - streamer=streamer, + streamer=_make_streamer(ctx, node_input, config, stream_registry), pending_sends=[], ) - # Set up LangSmith child trace so LLM calls nest under the parent + # Run under the LangSmith child trace so LLM calls nest under the parent # "LangGraph" trace created by runner.invoke(). - parent = _langsmith_parent(config) - if streamer: - streamer.node_started(state, config) - try: - if parent: - import langsmith as ls + result = _run_with_stream_hooks(call, _langsmith_parent(config)) - with ls.trace( - name=node_name, - run_type="chain", - parent=parent, - inputs={"step": node_name}, - ): - result = _run_node(call) - else: - result = _run_node(call) - except BaseException as exc: - if streamer: - streamer.node_failed(exc) - raise - if streamer: - streamer.node_finished(result) - - # Convert result to writes, then append any side-channel writes queued via - # CONFIG_KEY_SEND (e.g. StateBackend writing to the "files" channel from - # sandbox tools). - raw_writes = [*_result_to_raw_writes(result), *call.pending_sends] - writes = _serialize_writes(raw_writes) - - if streamer: - streamer.updates(raw_writes) - - return ExecuteNodeOutput( - node_name=node_name, - writes=writes, - goto=_result_to_gotos(result, node_name), - ).to_dict() + return _node_output(call, result) def evaluate_condition_activity( @@ -967,8 +1073,24 @@ def _get_triggered_nodes( def _serialize_input(input_data: Dict[str, Any]) -> Dict[str, Any]: - """Serialize input values for channel storage.""" - return {k: _serialize_value(v) for k, v in input_data.items()} + """Serialize input values for channel storage. + + Messages given as dicts get an id, as the ``add_messages`` reducer gives + them when LangGraph writes the input. A node that returns the messages it + was handed (a subgraph does) is then understood to return the same + messages, not new ones: the stream does not send them again and the state + does not hold them twice. + """ + values = {k: _serialize_value(v) for k, v in input_data.items()} + messages = values.get("messages") + if isinstance(messages, list): + values["messages"] = [ + {**m, "id": str(uuid.uuid4())} + if isinstance(m, dict) and m.get("id") is None + else m + for m in messages + ] + return values def _extract_output( @@ -1101,10 +1223,38 @@ def _result_to_raw_writes(result: Any) -> List[Tuple[str, Any]]: if isinstance(result, dict): return list(result.items()) + # An instance of a state schema (a Pydantic model or a dataclass): LangGraph + # writes its fields. + fields = _state_object_writes(result) + if fields is not None: + return fields + # Non-dict results - write to a default channel return [("__result__", result)] +def _state_object_writes(result: Any) -> Optional[List[Tuple[str, Any]]]: + """``(field, value)`` pairs of a Pydantic model or dataclass instance. + + The rule LangGraph applies to a node that returns an instance of its state + schema (``get_update_as_tuples``): every field is a write, except that for a + Pydantic model a field whose value and default are both ``None`` is left out + unless the node set it. ``None`` for anything else. + """ + if isinstance(result, BaseModel): + model = type(result) + keep = result.model_fields_set + return [ + (name, value) + for name, info in model.model_fields.items() + for value in [getattr(result, name, None)] + if value is not None or info.default is not None or name in keep + ] + if dataclasses.is_dataclass(result) and not isinstance(result, type): + return [(f.name, getattr(result, f.name)) for f in dataclasses.fields(result)] + return None + + def _warn_send_payload(source: str, send: Any) -> None: """Say, once per edge, that a ``Send`` runs its node on the channel state. From bd3f5195f03a114c0e917d0d0a1b59b14223c50e Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Wed, 25 Nov 2026 23:56:38 +0100 Subject: [PATCH 08/73] feat(langgraph): replay-safe message ids, reducer first writes, recursion_limit and graph metadata Input messages get ids that are the same on every replay of the workflow; the orchestrator used to draw random ones, so a replay scheduled the first activity with a different input. The first write to a reducer channel now goes through its reducer, so add_messages assigns ids and reads (role, content) tuples. A node's keys that are not state channels are dropped, as LangGraph does. astream() honours recursion_limit and refuses a config that cannot travel as JSON up front instead of failing late. The "messages" metadata now includes the graph's with_config metadata and tags and the metadata given to add_node. A failed run yields its stream_dropped before its error is raised. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/stream.py | 9 +- diagrid/agent/langgraph/README.md | 5 + diagrid/agent/langgraph/runner.py | 120 ++++++++++++++-- diagrid/agent/langgraph/stream_events.py | 16 ++- diagrid/agent/langgraph/streaming.py | 37 ++++- diagrid/agent/langgraph/workflow.py | 176 +++++++++++++++++++---- 6 files changed, 313 insertions(+), 50 deletions(-) diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index 6043add0..c9d1a843 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -247,6 +247,7 @@ def first_report(self, workflow_id: str) -> bool: """True the first time it is asked about ``workflow_id``. Lets an activity log a problem once per run instead of once per node. + Any other key works the same way (the Send warning uses one per edge). Remembers the most recent runs only, so it cannot grow without limit. """ with self._lock: @@ -257,6 +258,11 @@ def first_report(self, workflow_id: str) -> bool: self._reported.popitem(last=False) return True + def clear_reports(self) -> None: + """Forget what :meth:`first_report` was asked, so it reports again.""" + with self._lock: + self._reported.clear() + def get(self, workflow_id: Optional[str]) -> Optional[InProcessSink]: """The open sink for ``workflow_id``, or ``None``.""" if not workflow_id: @@ -289,5 +295,6 @@ def format_sse(event: str, data: Any, event_id: Optional[int] = None) -> str: lines.append(f"id: {event_id}") lines.append(f"event: {event}") payload = json.dumps(data, default=str) - lines.extend(f"data: {part}" for part in payload.split("\n")) + # json.dumps escapes newlines, so the payload is always one line. + lines.append(f"data: {payload}") return "\n".join(lines) + "\n\n" diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index c5e3f05d..fca605e6 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -211,6 +211,11 @@ they are left alone. - **`Send` payloads.** A node run through `Send("node", arg)` (or `goto=Send(...)`) reads the channel state, not `arg`; this is logged once per edge. A node that reads the argument gets different data than under LangGraph. +- **The `config` of `astream` travels as JSON.** `tags`, `metadata`, + `configurable` and `recursion_limit` work; `recursion_limit` bounds the run's + steps as LangGraph counts them (N sequential nodes need a limit of N + 1) and + the runner's `max_steps` applies when it is absent. `callbacks` and any value + that is not JSON raise `ValueError` before a run starts. ## Architecture diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index b77a48ca..9127ea56 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -27,13 +27,9 @@ from diagrid.agent.core.types.type import SupportedFrameworks from diagrid.agent.core.workflow import BaseWorkflowRunner from diagrid.agent.core.workflow.runner import fold_run_event -from diagrid.agent.core.workflow import stream as stream_module from diagrid.agent.core.workflow.stream import ( CONTROL_MODES, KEEPALIVE_EVENT, - NODE_RESET, - STREAM_DROPPED, - STREAM_UNAVAILABLE, WORKFLOW_STARTED, InProcessSink, StreamClosed, @@ -53,12 +49,10 @@ EXECUTED_KEY, STREAM_RUN_KEY, UPDATES, - GraphRunError, + StaticConfig, StreamControl, - stream_unavailable_event, normalize_final, normalize_stream_mode, - to_wire, ) from .stream_events import ( FINAL_EVENTS, @@ -74,14 +68,16 @@ ) from .workflow import ( agent_workflow, - evaluate_condition_activity, + make_condition_activity, GENERIC_NODE_ACTIVITY, make_node_activity, node_activity_name, register_node, + register_node_static_config, register_node_triggers, register_condition, register_channel_reducer, + register_state_channels, set_default_graph_config, set_serializer, clear_registries, @@ -97,6 +93,67 @@ _TRANSPORT_KEYS = ("stream", "stream_mode") +# What a reducer channel holds before its first write; LangGraph's own marker +# when the channel type has no empty value. +_NO_DEFAULT: Any = object() +try: + from langgraph.channels.binop import MISSING as _LANGGRAPH_MISSING +except ImportError: # pragma: no cover - a LangGraph without the marker + _LANGGRAPH_MISSING = _NO_DEFAULT + + +def _check_run_config(config: Optional[Dict[str, Any]]) -> None: + """Refuse a LangGraph config the workflow cannot carry, before a run starts. + + The config travels to the activities as JSON, so ``callbacks`` (handler + objects) and any other value that is not JSON cannot be passed; an + invalid ``recursion_limit`` is refused too. Raises ``ValueError``. + """ + if not config: + return + if config.get("callbacks"): + raise ValueError( + "config['callbacks'] is not supported: the config travels to the " + "workflow as JSON. Attach handlers to the models inside the nodes." + ) + limit = config.get("recursion_limit") + if limit is not None and ( + isinstance(limit, bool) or not isinstance(limit, int) or limit < 1 + ): + raise ValueError( + f"config['recursion_limit'] must be a positive integer, got {limit!r}" + ) + for key, value in config.items(): + items = ( + value.items() + if key == "configurable" and isinstance(value, dict) + else [(key, value)] + ) + for name, item in items: + try: + json.dumps(item) + except (TypeError, ValueError) as e: + where = ( + f"config['configurable'][{name!r}]" + if key == "configurable" + else f"config[{name!r}]" + ) + raise ValueError( + f"{where} is not JSON serializable, and the config travels to " + f"the workflow as JSON: {e}" + ) from e + + +def _max_steps_for(config: Optional[Dict[str, Any]], default: int) -> int: + """The workflow's step bound: ``config['recursion_limit']`` as LangGraph counts it. + + LangGraph allows ``recursion_limit - 1`` node steps (its input is the + first), so a graph of N sequential nodes needs a limit of N + 1. + """ + limit = (config or {}).get("recursion_limit") + return limit - 1 if isinstance(limit, int) else default + + def _run_identity( config: Optional[Dict[str, Any]], thread_id: Optional[str], @@ -108,6 +165,7 @@ def _run_identity( else new. The config handed to the run carries that one id, so the id the run reports is the one its nodes see. """ + _check_run_config(config) configurable = (config or {}).get("configurable") or {} thread = str(thread_id or configurable.get("thread_id") or uuid.uuid4()) run_config = { @@ -262,7 +320,8 @@ def _register_workflow_components(self) -> None: name=GENERIC_NODE_ACTIVITY, ) self._workflow_runtime.register_activity( - evaluate_condition_activity, name="evaluate_condition_activity" + make_condition_activity(self._stream_registry), + name="evaluate_condition_activity", ) def _register_node_activities(self) -> None: @@ -300,6 +359,7 @@ def _extract_graph_config(self) -> GraphConfig: ) register_node_triggers(node_name, triggers) + register_node_static_config(node_name, self._static_config(node_spec)) nodes.append( NodeConfig( name=node_name, @@ -400,6 +460,16 @@ def _extract_graph_config(self) -> GraphConfig: waiting_edges=waiting_edges, ) + def _static_config(self, node_spec: Any) -> StaticConfig: + """The metadata and tags the compiled graph and this node give its tasks.""" + graph_config = getattr(self._graph, "config", None) or {} + return StaticConfig( + graph_metadata=dict(graph_config.get("metadata") or {}), + graph_tags=tuple(graph_config.get("tags") or ()), + node_metadata=dict(getattr(node_spec, "metadata", None) or {}), + node_tags=tuple(getattr(node_spec, "tags", None) or ()), + ) + def _register_graph_components(self) -> None: """Register graph nodes and other components in the global registries.""" clear_registries() @@ -435,9 +505,22 @@ def _register_graph_components(self) -> None: channel, "operator", None ) if reducer: - register_channel_reducer(channel_name, reducer) + default = getattr(channel, "value", _NO_DEFAULT) + if default is _NO_DEFAULT or default is _LANGGRAPH_MISSING: + register_channel_reducer(channel_name, reducer) + else: + register_channel_reducer(channel_name, reducer, default) logger.info(f"Registered reducer for channel: {channel_name}") + # A node's keys that are not state channels are dropped, as LangGraph + # does (CompiledStateGraph's ``_get_updates``). + state_channels = getattr( + getattr(self._graph, "builder", None), "channels", None + ) + if isinstance(state_channels, dict): + managed = getattr(self._graph.builder, "managed", None) or {} + register_state_channels([*state_channels, *managed]) + try: from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer @@ -494,6 +577,7 @@ def invoke( thread_id = thread_id or str(uuid.uuid4()) workflow_id = workflow_id or f"graph-{thread_id}-{uuid.uuid4().hex[:8]}" + _check_run_config(config) config = config or {} config["thread_id"] = thread_id @@ -541,7 +625,7 @@ def invoke( graph_config=self._graph_config, channel_state=channel_state, step=0, - max_steps=self._max_steps, + max_steps=_max_steps_for(config, self._max_steps), pending_nodes=[], config=config, thread_id=thread_id, @@ -637,6 +721,7 @@ async def run_async( thread_id = thread_id or str(uuid.uuid4()) workflow_id = workflow_id or f"graph-{thread_id}-{uuid.uuid4().hex[:8]}" + _check_run_config(config) config = config or {} config["thread_id"] = thread_id @@ -683,7 +768,7 @@ async def run_async( graph_config=self._graph_config, channel_state=channel_state, step=0, - max_steps=self._max_steps, + max_steps=_max_steps_for(config, self._max_steps), pending_nodes=[], config=config, thread_id=thread_id, @@ -801,6 +886,12 @@ async def astream( reserved) until it is closed or garbage collected. Closing does not cancel the Dapr workflow, which runs to completion. + ``config`` is a LangGraph config that travels to the workflow as JSON: + ``tags``, ``metadata``, ``configurable`` and ``recursion_limit`` work + (the limit bounds the run's steps as LangGraph counts them; the + runner's ``max_steps`` applies when it is absent). ``callbacks`` and any + value that is not JSON raise ``ValueError`` before a run starts. + Chunks have the shape ``CompiledStateGraph.astream`` yields: ``messages`` are ``(message_chunk, metadata)`` and ``updates`` are ``{node: update}`` with the values exactly as the node returned them @@ -824,8 +915,11 @@ async def astream( ) ) as events: async for item in events: - for out in route_astream_item(item, modes, is_list, on_control): + outs, error = route_astream_item(item, modes, is_list, on_control) + for out in outs: yield out + if error is not None: + raise error async def _stream_events( self, diff --git a/diagrid/agent/langgraph/stream_events.py b/diagrid/agent/langgraph/stream_events.py index da62b6a5..bdeb11cf 100644 --- a/diagrid/agent/langgraph/stream_events.py +++ b/diagrid/agent/langgraph/stream_events.py @@ -146,11 +146,13 @@ def route_astream_item( modes: List[str], is_list: bool, on_control: Optional[Callable[[StreamControl], None]], -) -> List[Any]: - """What ``astream`` yields for one item of the event stream. +) -> Tuple[List[Any], Optional[GraphRunError]]: + """What ``astream`` yields for one item of the event stream, and its error. - Hands control events to ``on_control``, and raises :class:`GraphRunError` - for a terminal ``workflow_failed``. + Hands control events to ``on_control``. The error is a + :class:`GraphRunError` for a terminal ``workflow_failed``: the caller + yields what came with it (a ``stream_dropped`` of a failed run, say) and + then raises it. """ out: List[Any] = [] if isinstance(item, StreamEvent): @@ -166,7 +168,7 @@ def route_astream_item( warn_reset_unseen(item.workflow_id, control.data) elif item.mode in modes: out.append((item.mode, item.data) if is_list else item.data) - return out + return out, None if item.get("dropped"): control = StreamControl(STREAM_DROPPED, {"dropped": item["dropped"]}) if on_control is not None: @@ -174,8 +176,8 @@ def route_astream_item( if is_list: out.append((control.kind, control.data)) if item.get("type") == "workflow_failed": - raise GraphRunError(item) - return out + return out, GraphRunError(item) + return out, None def closing_events( diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index 0ed54e9f..7e7f00a1 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -14,7 +14,7 @@ import logging import threading import uuid -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Sequence, Set, Tuple from langchain_core.load import dumpd @@ -101,6 +101,30 @@ def on_chain_start(self, *args: Any, **kwargs: Any) -> Any: return OwnNodeMessagesHandler +@dataclass(frozen=True) +class StaticConfig: + """The metadata and tags the graph itself gives a node's tasks. + + LangGraph merges the compiled graph's own config (``with_config``) under + the caller's, and the node's ``add_node(metadata=...)`` over both. They + are fixed by the graph, so a runner registers them once per node. + """ + + graph_metadata: Dict[str, Any] = field(default_factory=dict) + graph_tags: Tuple[str, ...] = () + node_metadata: Dict[str, Any] = field(default_factory=dict) + node_tags: Tuple[str, ...] = () + + def metadata(self, caller: Optional[Dict[str, Any]]) -> Dict[str, Any]: + """graph, then the caller's, then the node's own: later wins.""" + return {**self.graph_metadata, **(caller or {}), **self.node_metadata} + + def tags(self, caller: Optional[Sequence[str]]) -> List[str]: + """The graph's tags, the caller's, the node's, without repeats.""" + merged = [*self.graph_tags, *(caller or ()), *self.node_tags] + return list(dict.fromkeys(merged)) + + class NodeStreamer: """Streams one activity attempt of one node into a sink.""" @@ -118,7 +142,9 @@ def __init__( task_id: Any, thread_id: Optional[str] = None, triggers: Optional[Sequence[str]] = None, + static: Optional[StaticConfig] = None, ) -> None: + self._static = static or StaticConfig() self._sink = sink self._thread_id = thread_id self._workflow_id = workflow_id @@ -231,7 +257,7 @@ def node_started( metadata = { **self._configurable_metadata(config), "ls_integration": "langgraph", - **(config.get("metadata") or {}), + **self._static.metadata(config.get("metadata")), **{k: v for k, v in self.metadata.items() if k != "checkpoint_ns"}, } handler.on_chain_start( @@ -240,7 +266,7 @@ def node_started( run_id=self._run_id, name=self._node, metadata=metadata, - tags=list(config.get("tags") or []), + tags=self._static.tags(config.get("tags")), ) def node_finished(self, output: Any) -> None: @@ -295,9 +321,12 @@ def patch_config(self, config: Dict[str, Any]) -> Dict[str, Any]: patched["callbacks"] = callbacks patched["metadata"] = { **self._configurable_metadata(patched), - **(patched.get("metadata") or {}), + **self._static.metadata(patched.get("metadata")), **self.metadata, } + tags = self._static.tags(patched.get("tags")) + if tags or "tags" in patched: + patched["tags"] = tags return patched def _configurable_metadata(self, config: Dict[str, Any]) -> Dict[str, Any]: diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 13892e75..4beb6281 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -4,13 +4,24 @@ """Dapr Workflow definitions for durable LangGraph execution.""" import contextlib +import copy import dataclasses import functools import logging import uuid from datetime import timedelta from dataclasses import dataclass -from typing import Any, Callable, Dict, Generator, List, Optional, Set, Tuple +from typing import ( + Any, + Callable, + Dict, + Generator, + Iterable, + List, + Optional, + Set, + Tuple, +) from dapr.ext.workflow import ( DaprWorkflowContext, @@ -41,7 +52,7 @@ get_stream_sink, ) -from .streaming import STREAM_RUN_KEY, NodeStreamer +from .streaming import STREAM_RUN_KEY, NodeStreamer, StaticConfig from .models import ( ChannelState, ExecuteNodeInput, @@ -63,15 +74,20 @@ _node_registry: Dict[str, Callable] = {} _condition_registry: Dict[str, Callable] = {} _channel_reducers: Dict[str, Callable] = {} +# The value a reducer channel holds before its first write (``[]`` for a list). +_channel_defaults: Dict[str, Any] = {} +_NO_DEFAULT: Any = object() +# The graph's state channels: a node's other keys are not writes, as in LangGraph. +# ``None`` until a runner registers them (then nothing is dropped). +_state_channels: Optional[frozenset] = None _serializer: Optional[Any] = None _default_graph_config: Optional["GraphConfig"] = None _default_input_mapper: Optional[Callable] = None _default_max_steps: int = 100 # Every trigger channel of each node, as LangGraph lists them in a task's metadata. _node_triggers: Dict[str, Tuple[str, ...]] = {} -# (source, node) edges whose Send payload was already warned about; cleared with -# the other registries so a second runner in the process hears it too. -_WARNED_SENDS: set = set() +# The metadata and tags the graph and each node give their tasks (see StaticConfig). +_node_static: Dict[str, StaticConfig] = {} # Special node names START = "__start__" @@ -127,6 +143,16 @@ def register_node_triggers(name: str, triggers: List[str]) -> None: _node_triggers[name] = tuple(sorted(triggers)) +def register_node_static_config(name: str, static: StaticConfig) -> None: + """Record the graph's and the node's own metadata and tags for ``name``.""" + _node_static[name] = static + + +def get_node_static_config(name: str) -> Optional[StaticConfig]: + """What :func:`register_node_static_config` recorded for ``name``.""" + return _node_static.get(name) + + def get_node_triggers(name: str) -> Optional[Tuple[str, ...]]: """The trigger channels of a node, sorted as LangGraph reports them.""" return _node_triggers.get(name) @@ -147,9 +173,31 @@ def get_registered_condition(name: str) -> Optional[Callable]: return _condition_registry.get(name) -def register_channel_reducer(channel: str, reducer: Callable) -> None: - """Register a reducer function for a channel.""" +def register_channel_reducer( + channel: str, reducer: Callable, default: Any = _NO_DEFAULT +) -> None: + """Register a reducer function for a channel. + + ``default`` is what the channel holds before its first write; the first + write is reduced into it, as LangGraph does. Without one it is stored as is. + """ _channel_reducers[channel] = reducer + if default is _NO_DEFAULT: + _channel_defaults.pop(channel, None) + else: + _channel_defaults[channel] = default + + +def register_state_channels(channels: Iterable[str]) -> None: + """Record the graph's state channels, the only keys a node can write.""" + global _state_channels + _state_channels = frozenset(channels) + + +def _keep_channel(channel: str) -> bool: + """Whether a node's key is a state channel (everything is, before any is set).""" + names = _state_channels + return names is None or "__root__" in names or channel in names def get_channel_reducer(channel: str) -> Optional[Callable]: @@ -245,8 +293,12 @@ def clear_registries() -> None: _node_registry.clear() _condition_registry.clear() _channel_reducers.clear() - _WARNED_SENDS.clear() + _channel_defaults.clear() + global _state_channels + _state_channels = None + default_registry.clear_reports() _node_triggers.clear() + _node_static.clear() global _serializer, _default_graph_config, _default_input_mapper, _default_max_steps _serializer = None _default_graph_config = None @@ -293,7 +345,9 @@ def agent_workflow( graph_input = input_data channel_state = ChannelState( - values=_serialize_input(graph_input), + values=_serialize_input( + graph_input, lambda i: _replay_safe_id(ctx.instance_id, i) + ), versions={k: 1 for k in graph_input.keys()}, updated_channels=list(graph_input.keys()), ) @@ -353,7 +407,7 @@ def agent_workflow( joined: List[Set[str]] = [set() for _ in graph_config.waiting_edges] # Main execution loop - while step < max_steps: + while True: # Log workflow step for debugging if not ctx.is_replaying: print( @@ -374,6 +428,11 @@ def agent_workflow( status="completed", ).to_dict() + # The bound is checked after the end of the run, so a graph that needs + # exactly ``max_steps`` steps completes instead of being cut at the end. + if step >= max_steps: + break + executed.append(list(nodes_to_execute)) # Execute all triggered nodes in parallel (each as a separate activity) @@ -613,6 +672,8 @@ class _NodeCall: streamer: Optional[NodeStreamer] #: Side-channel writes queued via CONFIG_KEY_SEND while the node runs. pending_sends: list + #: The runner's registry (``None``: the module's), which remembers warnings. + registry: Optional[StreamSinkRegistry] = None @property def node_name(self) -> str: @@ -833,6 +894,7 @@ def _make_streamer( task_id=getattr(ctx, "task_id", ""), thread_id=node_input.thread_id or config.get("thread_id"), triggers=get_node_triggers(node_name), + static=get_node_static_config(node_name), ) @@ -879,7 +941,7 @@ def _node_output(call: _NodeCall, result: Any) -> Dict[str, Any]: return ExecuteNodeOutput( node_name=call.node_name, writes=_serialize_writes(raw_writes), - goto=_result_to_gotos(result, call.node_name), + goto=_result_to_gotos(result, call.node_name, call.registry), ).to_dict() @@ -933,6 +995,7 @@ def execute_node_activity( config=config, streamer=_make_streamer(ctx, node_input, config, stream_registry), pending_sends=[], + registry=stream_registry, ) # Run under the LangSmith child trace so LLM calls nest under the parent @@ -942,14 +1005,34 @@ def execute_node_activity( return _node_output(call, result) +def make_condition_activity( + stream_registry: Optional[StreamSinkRegistry] = None, +) -> Callable[[WorkflowActivityContext, Dict[str, Any]], Dict[str, Any]]: + """Build the conditional-edge activity of a runner (see ``make_node_activity``).""" + + def evaluate_condition( + ctx: WorkflowActivityContext, input_data: Dict[str, Any] + ) -> Dict[str, Any]: + return evaluate_condition_activity( + ctx, input_data, stream_registry=stream_registry + ) + + return evaluate_condition + + def evaluate_condition_activity( - ctx: WorkflowActivityContext, input_data: Dict[str, Any] + ctx: WorkflowActivityContext, + input_data: Dict[str, Any], + *, + stream_registry: Optional[StreamSinkRegistry] = None, ) -> Dict[str, Any]: """Activity that evaluates a conditional edge. Args: ctx: The workflow activity context input_data: Dictionary containing EvaluateConditionInput data + stream_registry: The runner's registry, which remembers which warnings + were given (default: the module's). Returns: EvaluateConditionOutput as a dictionary @@ -1025,7 +1108,7 @@ def evaluate_condition_activity( next_nodes = [] for item in items: if hasattr(item, "node"): - _warn_send_payload(cond_input.source_node, item) + _warn_send_payload(cond_input.source_node, item, stream_registry) next_nodes.append(item.node) elif path_map is None: next_nodes.append(item if isinstance(item, str) else str(item)) @@ -1072,7 +1155,20 @@ def _get_triggered_nodes( return [] -def _serialize_input(input_data: Dict[str, Any]) -> Dict[str, Any]: +def _replay_safe_id(instance_id: Any, index: int) -> str: + """The id of input message ``index`` of a workflow instance: same on every replay.""" + return str(uuid.uuid5(uuid.NAMESPACE_OID, f"{instance_id}:{index}")) + + +def _message_id(index: int) -> str: + """A fresh id for the message at ``index`` of the input (outside a workflow).""" + return str(uuid.uuid4()) + + +def _serialize_input( + input_data: Dict[str, Any], + message_id: Callable[[int], str] = _message_id, +) -> Dict[str, Any]: """Serialize input values for channel storage. Messages given as dicts get an id, as the ``add_messages`` reducer gives @@ -1080,19 +1176,39 @@ def _serialize_input(input_data: Dict[str, Any]) -> Dict[str, Any]: was handed (a subgraph does) is then understood to return the same messages, not new ones: the stream does not send them again and the state does not hold them twice. + + ``message_id`` makes the id of the message at a given index. Workflow code + is replayed from its first line for every decision, so it passes an id that + is the same on every replay; random ids are for callers outside a workflow. """ values = {k: _serialize_value(v) for k, v in input_data.items()} messages = values.get("messages") if isinstance(messages, list): + messages = [_pair_as_message(m) for m in messages] values["messages"] = [ - {**m, "id": str(uuid.uuid4())} + {**m, "id": message_id(i)} if isinstance(m, dict) and m.get("id") is None else m - for m in messages + for i, m in enumerate(messages) ] return values +def _pair_as_message(item: Any) -> Any: + """A ``(role, content)`` pair (a tuple, or the list it became) as a message dict. + + LangGraph's ``add_messages`` converts such a pair to a message; the stored + input is JSON, where a tuple is already a two-item list. + """ + if ( + isinstance(item, (list, tuple)) + and len(item) == 2 + and all(isinstance(part, str) for part in item) + ): + return {"role": item[0], "content": item[1]} + return item + + def _extract_output( channel_state: ChannelState, output_channels: List[str] ) -> Dict[str, Any]: @@ -1121,6 +1237,11 @@ def _apply_write(channel_state: ChannelState, channel: str, value: Any) -> None: value: Value to write """ reducer = get_channel_reducer(channel) + if reducer and channel not in channel_state.values: + # The first write is reduced into the channel's default, so add_messages + # gives its messages ids and objects, as it does natively. + if channel in _channel_defaults: + channel_state.values[channel] = copy.deepcopy(_channel_defaults[channel]) if reducer and channel in channel_state.values: # Apply reducer to combine values try: @@ -1221,7 +1342,7 @@ def _result_to_raw_writes(result: Any) -> List[Tuple[str, Any]]: return writes if isinstance(result, dict): - return list(result.items()) + return [(k, v) for k, v in result.items() if _keep_channel(k)] # An instance of a state schema (a Pydantic model or a dataclass): LangGraph # writes its fields. @@ -1255,17 +1376,20 @@ def _state_object_writes(result: Any) -> Optional[List[Tuple[str, Any]]]: return None -def _warn_send_payload(source: str, send: Any) -> None: +def _warn_send_payload( + source: str, send: Any, registry: Optional[StreamSinkRegistry] = None +) -> None: """Say, once per edge, that a ``Send`` runs its node on the channel state. LangGraph hands the node the ``Send`` argument as its input. Here the node reads the channel state, so a node that depends on the argument gets the wrong data (the prebuilt agent's tools node, which passes the state, is fine). """ - key = (source, send.node) - if getattr(send, "arg", None) is None or key in _WARNED_SENDS: + if getattr(send, "arg", None) is None: + return + # once per edge and runner: the memory is the runner's own registry + if not (registry or default_registry).first_report(f"send:{source}->{send.node}"): return - _WARNED_SENDS.add(key) logger.warning( "Send(%r, ...) from %r: the payload is not delivered, node %r runs on the " "channel state. A node that reads the Send argument gets different data " @@ -1276,7 +1400,9 @@ def _warn_send_payload(source: str, send: Any) -> None: ) -def _result_to_gotos(result: Any, source: str) -> List[str]: +def _result_to_gotos( + result: Any, source: str, registry: Optional[StreamSinkRegistry] = None +) -> List[str]: """The nodes a ``Command(goto=...)`` result asks to run next. ``END`` is skipped (it ends that branch, which running nothing does). A @@ -1294,7 +1420,7 @@ def _result_to_gotos(result: Any, source: str) -> List[str]: goto = getattr(cmd, "goto", None) or () for item in [goto] if isinstance(goto, (str, Send)) else goto: if isinstance(item, Send): - _warn_send_payload(source, item) + _warn_send_payload(source, item, registry) name = item.node else: name = str(item) @@ -1320,13 +1446,13 @@ def _command_to_raw_writes(cmd: Any) -> List[Tuple[str, Any]]: return [] if isinstance(update, dict): - return list(update.items()) + return [(k, v) for k, v in update.items() if _keep_channel(k)] if isinstance(update, (list, tuple)): # update can be a list of (channel, value) tuples return [ (item[0], item[1]) for item in update - if isinstance(item, tuple) and len(item) == 2 + if isinstance(item, tuple) and len(item) == 2 and _keep_channel(item[0]) ] return [] From e173444ab217de83a510660d39957184c51ebd8e Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Wed, 25 Nov 2026 23:57:16 +0100 Subject: [PATCH 09/73] feat(langgraph): run each Send as its own task and match LangGraph's state handling A Send from a conditional edge or Command(goto=...) used to run its node once on the whole channel state. Each Send is now an activity of its own that takes its argument as the node input, streams under its own key with the push trigger and path, and follows the node's outgoing edges. A router that calls an LLM or get_stream_writer() now streams its tokens and events too, and each conditional edge of a node streams under its own key, so one edge is no longer mistaken for a retry of another. State now follows LangGraph. A reducer channel nobody has written starts from its default, message input is read in every shape add_messages takes on every such channel, a node gets the state as its input schema shapes it, Overwrite replaces a reducer channel's value, and a message keeps its own fields. Ids of written messages are assigned in the activity, so replays see the recorded ones, and a reducer that raises fails the run. Async nodes run on one background loop that outlives the activity, so a chat model's pooled HTTP client no longer hits a closed loop. A bound recursion_limit and configurable apply as with LangGraph, invoke raises for a run that failed or hit its limit, and the error is a GraphRecursionError when it is the limit. serve(), _poll_workflow and agent_workflow are split into helpers, and the node_reset event names the real node and path. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 343 ++++--- diagrid/agent/core/workflow/stream.py | 49 +- diagrid/agent/langgraph/README.md | 38 +- diagrid/agent/langgraph/models.py | 35 +- diagrid/agent/langgraph/runner.py | 116 ++- diagrid/agent/langgraph/stream_events.py | 3 +- diagrid/agent/langgraph/streaming.py | 29 +- diagrid/agent/langgraph/workflow.py | 1149 ++++++++++++++-------- tests/agent/langgraph/test_workflow.py | 4 +- 9 files changed, 1178 insertions(+), 588 deletions(-) diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 537f0b65..3b939d97 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -19,7 +19,7 @@ from diagrid.agent.core.metadata.mixins import AgentRegistryMixin from diagrid.agent.core.observability import resolve_observability_config from diagrid.agent.core.workflow.naming import build_workflow_name -from diagrid.agent.core.workflow.stream import KEEPALIVE_EVENT, format_sse +from diagrid.agent.core.workflow.stream import frame_sse # ``diagrid-core`` ships the reporter. This distribution only pins # ``diagrid-core>=0.1.0`` (through ``diagrid-cli``), so an application holding @@ -105,6 +105,86 @@ def _is_transient_poll_error(error: BaseException) -> bool: return False +def _poll_retry_delay( + error: BaseException, failed_polls: int, retry: bool, workflow_id: str +) -> Optional[float]: + """Seconds to wait before polling again, or ``None`` to raise ``error``. + + ``failed_polls`` counts consecutive failures, this one included. + """ + if ( + not retry + or not _is_transient_poll_error(error) + or failed_polls > POLL_MAX_ERRORS + ): + return None + delay = min( + POLL_RETRY_BASE_SECONDS * 2 ** (failed_polls - 1), POLL_RETRY_MAX_SECONDS + ) + logger.warning( + "Polling workflow %s failed (%d of %d), retrying in %.1fs: %s", + workflow_id, + failed_polls, + POLL_MAX_ERRORS, + delay, + error, + ) + return delay + + +def _completed_event( + state: Any, workflow_id: str, parse_output: Optional[Callable[..., Any]] +) -> dict[str, Any]: + """The ``workflow_completed`` event for a finished workflow's ``state``.""" + output_data = state.serialized_output + if not output_data: + return {"type": "workflow_completed", "workflow_id": workflow_id} + try: + output_dict = ( + json.loads(output_data) if isinstance(output_data, str) else output_data + ) + if parse_output: + return parse_output(workflow_id, output_dict) # type: ignore[no-any-return] + return { + "type": "workflow_completed", + "workflow_id": workflow_id, + "output": output_dict, + } + except Exception as e: + return { + "type": "workflow_completed", + "workflow_id": workflow_id, + "raw_output": output_data, + "parse_error": str(e), + } + + +def _terminal_event( + state: Any, workflow_id: str, parse_output: Optional[Callable[..., Any]] +) -> Optional[dict[str, Any]]: + """The event that ends a poll for ``state``, or ``None`` while it is running.""" + status = state.runtime_status + if status == WorkflowStatus.COMPLETED: + return _completed_event(state, workflow_id, parse_output) + if status == WorkflowStatus.FAILED: + error_info = None + if state.failure_details: + fd = state.failure_details + error_info = { + "message": getattr(fd, "message", str(fd)), + "error_type": getattr(fd, "error_type", None), + "stack_trace": getattr(fd, "stack_trace", None), + } + return { + "type": "workflow_failed", + "workflow_id": workflow_id, + "error": error_info, + } + if status == WorkflowStatus.TERMINATED: + return {"type": "workflow_terminated", "workflow_id": workflow_id} + return None + + def fold_run_event(result: dict, event: dict) -> bool: # type: ignore[type-arg] """Fold one event of a run into ``result``, the body of ``POST /agent/run``. @@ -364,24 +444,11 @@ async def _poll_workflow( # dropped call). Retry; only a poll that keeps failing is given # up on, and the caller learns the run's fate is unknown. failed_polls += 1 - if ( - not retry_failed_polls - or not _is_transient_poll_error(e) - or failed_polls > POLL_MAX_ERRORS - ): - raise - delay = min( - POLL_RETRY_BASE_SECONDS * 2 ** (failed_polls - 1), - POLL_RETRY_MAX_SECONDS, - ) - logger.warning( - "Polling workflow %s failed (%d of %d), retrying in %.1fs: %s", - workflow_id, - failed_polls, - POLL_MAX_ERRORS, - delay, - e, + delay = _poll_retry_delay( + e, failed_polls, retry_failed_polls, workflow_id ) + if delay is None: + raise await asyncio.sleep(delay) continue failed_polls = 0 @@ -403,58 +470,9 @@ async def _poll_workflow( } previous_status = state.runtime_status - if state.runtime_status == WorkflowStatus.COMPLETED: - output_data = state.serialized_output - if output_data: - try: - output_dict = ( - json.loads(output_data) - if isinstance(output_data, str) - else output_data - ) - if parse_output: - yield parse_output(workflow_id, output_dict) - else: - yield { - "type": "workflow_completed", - "workflow_id": workflow_id, - "output": output_dict, - } - except Exception as e: - yield { - "type": "workflow_completed", - "workflow_id": workflow_id, - "raw_output": output_data, - "parse_error": str(e), - } - else: - yield { - "type": "workflow_completed", - "workflow_id": workflow_id, - } - break - - elif state.runtime_status == WorkflowStatus.FAILED: - error_info = None - if state.failure_details: - fd = state.failure_details - error_info = { - "message": getattr(fd, "message", str(fd)), - "error_type": getattr(fd, "error_type", None), - "stack_trace": getattr(fd, "stack_trace", None), - } - yield { - "type": "workflow_failed", - "workflow_id": workflow_id, - "error": error_info, - } - break - - elif state.runtime_status == WorkflowStatus.TERMINATED: - yield { - "type": "workflow_terminated", - "workflow_id": workflow_id, - } + terminal = _terminal_event(state, workflow_id, parse_output) + if terminal is not None: + yield terminal break # ------------------------------------------------------------------ @@ -481,6 +499,93 @@ def _run_sync(self, coro: Any, timeout: float = 300.0) -> Any: # Shared serve pattern # ------------------------------------------------------------------ + @staticmethod + def _result_publisher( + pubsub_name: Optional[str], publish_topic: Optional[str] + ) -> Optional[Callable[[dict], None]]: # type: ignore[type-arg] + """The function that publishes a run's result, or ``None`` without a topic. + + Blocking: callers run it off the event loop. A failure is logged, not + raised, so publishing never fails the run. + """ + if not (pubsub_name and publish_topic): + return None + from diagrid.agent.core.pubsub import DaprPubSub + + client = DaprPubSub(pubsub_name=pubsub_name) + + def publish(result: dict) -> None: # type: ignore[type-arg] + try: + client.publish(publish_topic, result) + logger.info("Published result to topic=%s", publish_topic) + except Exception as e: + logger.error("Failed to publish result: %s", str(e)) + + return publish + + @staticmethod + def _add_subscription_routes( + app: Any, + pubsub_name: str, + subscribe_topic: str, + run_and_collect: Callable[[dict], Any], # type: ignore[type-arg] + ) -> None: + """Register the Dapr programmatic subscription and its event route.""" + from fastapi import Request + + @app.get("/dapr/subscribe") + async def dapr_subscribe() -> list: # type: ignore[type-arg] + return [ + { + "pubsubname": pubsub_name, + "topic": subscribe_topic, + "route": f"/events/{subscribe_topic}", + } + ] + + @app.post(f"/events/{subscribe_topic}") + async def handle_topic_event(request: Request) -> dict: # type: ignore[type-arg] + body = await request.json() + + # Extract task from CloudEvent data + data = body.get("data", body) + if isinstance(data, str): + try: + data = json.loads(data) + except (json.JSONDecodeError, TypeError): + data = {"task": data} + if isinstance(data, dict) and "task" not in data: + data = {"task": json.dumps(data) if data else ""} + + logger.info("Received event on topic=%s", subscribe_topic) + return await run_and_collect(data) # type: ignore[no-any-return] + + def _stream_response( + self, + request: dict, # type: ignore[type-arg] + on_result: Optional[Callable[[dict], None]], # type: ignore[type-arg] + ) -> Any: + """The SSE response of a ``POST /agent/run`` with ``"stream": true``.""" + from fastapi import HTTPException + from fastapi.responses import StreamingResponse + + # A bad request is refused with a 4xx now: once the response starts, + # its 200 is committed and an error can only be in-band. + try: + self._validate_stream_request(request) + except ValueError as e: + raise HTTPException(status_code=422, detail=str(e)) + session_id = request.get( + "session_id", request.get("thread_id", uuid.uuid4().hex[:8]) + ) + return StreamingResponse( + frame_sse(self._serve_stream(request, session_id, on_result=on_result)), + media_type="text/event-stream", + # Without these an ingress or reverse proxy may buffer the stream + # and hand the client its tokens in one batch. + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, + ) + def serve( self, *, @@ -519,8 +624,7 @@ def serve( publish_topic: Topic to publish results to after completion. """ try: - from fastapi import FastAPI, HTTPException, Request - from fastapi.responses import StreamingResponse + from fastapi import FastAPI, HTTPException import uvicorn except ImportError: raise ImportError( @@ -533,12 +637,7 @@ def serve( self._setup_telemetry() self._setup_serve_defaults() - # Set up pub/sub publisher if configured - pubsub_client = None - if pubsub_name and publish_topic: - from diagrid.agent.core.pubsub import DaprPubSub - - pubsub_client = DaprPubSub(pubsub_name=pubsub_name) + publish = self._result_publisher(pubsub_name, publish_topic) runner_ref = self @@ -555,67 +654,19 @@ async def _run_and_collect(request: dict) -> dict: # type: ignore[type-arg] if fold_run_event(result, event): break - await asyncio.to_thread(_publish_result, result) + if publish: + await asyncio.to_thread(publish, result) return result - def _publish_result(result: dict) -> None: # type: ignore[type-arg] - """Publish a result to the configured topic, if any. - - Blocking: callers run it off the event loop. - """ - if pubsub_client and publish_topic: - try: - pubsub_client.publish(publish_topic, result) - logger.info("Published result to topic=%s", publish_topic) - except Exception as e: - logger.error("Failed to publish result: %s", str(e)) - - async def _frame(events: AsyncIterator[Tuple[str, Any]]) -> AsyncIterator[str]: - """Frame ``(event, data)`` pairs as SSE. - - The only place a streamed run is turned into SSE frames, so a runner - just yields pairs. Publishing is the runner's job (``on_result``). - """ - event_id = 0 - try: - async for name, data in events: - if name != KEEPALIVE_EVENT: - event_id += 1 - yield format_sse(name, data, event_id) - finally: - # A client that disconnects ends the generator at a yield; close - # the runner's stream now rather than when it is collected. - aclose = getattr(events, "aclose", None) - if aclose is not None: - await aclose() - # Only a run that is published needs to outlive its client. - on_result = _publish_result if pubsub_client else None + on_result = publish @app.post("/agent/run") async def run_agent(request: dict) -> Any: # type: ignore[type-arg] # Only the JSON value true streams. Anything else ("false", an # object) is a plain request whose "stream" key may be the graph's own. if request.get("stream") is True and self._supports_serve_stream: - # A bad request is refused with a 4xx now: once the response - # starts, its 200 is committed and an error can only be in-band. - try: - self._validate_stream_request(request) - except ValueError as e: - raise HTTPException(status_code=422, detail=str(e)) - session_id = request.get( - "session_id", - request.get("thread_id", uuid.uuid4().hex[:8]), - ) - return StreamingResponse( - _frame( - self._serve_stream(request, session_id, on_result=on_result) - ), - media_type="text/event-stream", - # Without these an ingress or reverse proxy may buffer the - # stream and hand the client its tokens in one batch. - headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, - ) + return self._stream_response(request, on_result) return await _run_and_collect(request) @app.get("/agent/run/{workflow_id}") @@ -625,36 +676,10 @@ async def get_status(workflow_id: str) -> dict: # type: ignore[type-arg] raise HTTPException(status_code=404, detail="Workflow not found") return status - # Register Dapr programmatic subscription if configured if pubsub_name and subscribe_topic: - - @app.get("/dapr/subscribe") - async def dapr_subscribe() -> list: # type: ignore[type-arg] - return [ - { - "pubsubname": pubsub_name, - "topic": subscribe_topic, - "route": f"/events/{subscribe_topic}", - } - ] - - @app.post(f"/events/{subscribe_topic}") - async def handle_topic_event(request: Request) -> dict: # type: ignore[type-arg] - body = await request.json() - - # Extract task from CloudEvent data - data = body.get("data", body) - if isinstance(data, str): - try: - data = json.loads(data) - except (json.JSONDecodeError, TypeError): - data = {"task": data} - if isinstance(data, dict) and "task" not in data: - data = {"task": json.dumps(data) if data else ""} - - logger.info("Received event on topic=%s", subscribe_topic) - result = await _run_and_collect(data) - return result + self._add_subscription_routes( + app, pubsub_name, subscribe_topic, _run_and_collect + ) uvicorn.run(app, host=host, port=port) diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index c9d1a843..0088ec2a 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -16,7 +16,7 @@ import threading from collections import OrderedDict from dataclasses import dataclass -from typing import Any, Dict, Optional, Protocol, Tuple +from typing import Any, AsyncIterator, Dict, Optional, Protocol, Tuple logger = logging.getLogger(__name__) @@ -68,6 +68,25 @@ class StreamEvent: ns: Tuple[str, ...] mode: str data: Any + #: The node name the chunk's metadata carries (``langgraph_node``), when + #: ``node`` is a key of the sink's own (a ``Send`` task or a router). + display_node: Optional[str] = None + #: The task's ``langgraph_path`` when it is not the node's own (a ``Send``). + path: Optional[Tuple[Any, ...]] = None + + def reset_data(self) -> Dict[str, Any]: + """The ``node_reset`` payload for a retry of this event's task. + + It names the node and step as the chunks do, so a client can match them + (plus the path of a ``Send`` task, as the chunk's metadata has it). + """ + data: Dict[str, Any] = { + "node": self.display_node or self.node, + "step": display_step(self.step), + } + if self.path: + data["path"] = list(self.path) + return data class StreamSink(Protocol): @@ -131,7 +150,7 @@ def put(self, event: StreamEvent) -> None: event.seq, event.ns, NODE_RESET, - {"node": event.node, "step": display_step(event.step)}, + event.reset_data(), ) ) self._owner[key] = event.attempt_id @@ -247,7 +266,6 @@ def first_report(self, workflow_id: str) -> bool: """True the first time it is asked about ``workflow_id``. Lets an activity log a problem once per run instead of once per node. - Any other key works the same way (the Send warning uses one per edge). Remembers the most recent runs only, so it cannot grow without limit. """ with self._lock: @@ -258,11 +276,6 @@ def first_report(self, workflow_id: str) -> bool: self._reported.popitem(last=False) return True - def clear_reports(self) -> None: - """Forget what :meth:`first_report` was asked, so it reports again.""" - with self._lock: - self._reported.clear() - def get(self, workflow_id: Optional[str]) -> Optional[InProcessSink]: """The open sink for ``workflow_id``, or ``None``.""" if not workflow_id: @@ -298,3 +311,23 @@ def format_sse(event: str, data: Any, event_id: Optional[int] = None) -> str: # json.dumps escapes newlines, so the payload is always one line. lines.append(f"data: {payload}") return "\n".join(lines) + "\n\n" + + +async def frame_sse(events: AsyncIterator[Tuple[str, Any]]) -> AsyncIterator[str]: + """Frame ``(event, data)`` pairs as SSE. + + The only place a streamed run is turned into SSE frames, so a runner just + yields pairs. Publishing is the runner's job (``on_result``). + """ + event_id = 0 + try: + async for name, data in events: + if name != KEEPALIVE_EVENT: + event_id += 1 + yield format_sse(name, data, event_id) + finally: + # A client that disconnects ends the generator at a yield; close the + # runner's stream now rather than when it is collected. + aclose = getattr(events, "aclose", None) + if aclose is not None: + await aclose() diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index fca605e6..a615c471 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -120,8 +120,8 @@ objects (`kind`, `data`): | `kind` | `data` | Meaning | |---|---|---| | `workflow_started` | `{"workflow_id", "thread_id"}` | Always the first event: the ids to use with `terminate_workflow` or `get_workflow_status`. Delivered only to `on_control`, never yielded. | -| `node_reset` | `{"node", "step"}` | A node was retried; drop its partial output. `step` is the `langgraph_step` of that node's `messages` metadata (numbered from 1). | -| `stream_unavailable` | `{"workflow_id", "reason", "missing_steps", "missing_nodes"}` | The run finished but a node's chunks never arrived (see the limit below). `missing_nodes` is a list of `{"step", "node"}`, one per node of a step that streamed nothing, even when other nodes of that step did. Steps are numbered from 1, like `langgraph_step`. | +| `node_reset` | `{"node", "step"}`, plus `"path"` for a `Send` task | A node was retried; drop its partial output. `node` and `step` are the `langgraph_node` and `langgraph_step` of that node's `messages` metadata (`step` is numbered from 1). A task started by a `Send` also carries `path`, the `langgraph_path` of its chunks (`["__pregel_push", index, false]`), which tells apart the tasks of one node in a step. | +| `stream_unavailable` | `{"workflow_id", "reason", "missing_steps", "missing_nodes"}` | The run finished but a node's chunks never arrived (see the limit below). `missing_nodes` is a list of `{"step", "node"}`, one per node of a step that streamed nothing, even when other nodes of that step did. Steps are numbered from 1, like `langgraph_step`. A `Send` task is named `node#k` there (`k` is its position among the step's `Send` tasks). | | `stream_dropped` | `{"dropped": n}` | The consumer fell behind and `n` token or custom chunks were dropped. `updates` are never dropped. | Pass `on_control=callback` to `astream` to receive them. A list of modes also @@ -137,7 +137,11 @@ To discard the partial output, pass `on_control` or use a list of modes and drop what the node sent before its `node_reset`. A run that fails (a node or condition error, max steps, a terminated workflow, -no result) raises `GraphRunError`; its `.final` is the full terminal event. +no result) raises `GraphRunError`; its `.final` is the full terminal event. A run +that hits its step limit raises an error that is also LangGraph's +`GraphRecursionError`, so `except GraphRecursionError` works as it does with +native LangGraph. `invoke` raises the same errors for such a run, instead of +returning its partial output. To stop reading early, close the stream. A bare `break` does not close an async generator that is still referenced, so use `aclosing`: @@ -208,14 +212,26 @@ they are left alone. client left and publishes its result when it ends, as it does for a client that stays. -- **`Send` payloads.** A node run through `Send("node", arg)` (or `goto=Send(...)`) - reads the channel state, not `arg`; this is logged once per edge. A node that - reads the argument gets different data than under LangGraph. -- **The `config` of `astream` travels as JSON.** `tags`, `metadata`, - `configurable` and `recursion_limit` work; `recursion_limit` bounds the run's - steps as LangGraph counts them (N sequential nodes need a limit of N + 1) and - the runner's `max_steps` applies when it is absent. `callbacks` and any value - that is not JSON raise `ValueError` before a run starts. +- **`Send` tasks.** Every `Send("node", arg)` (from a conditional edge or + `goto=Send(...)`) runs the node once, as its own activity, with `arg` as its + input, and streams with the `__pregel_push` trigger and path as LangGraph does + (`create_agent`'s tool calls and map-reduce graphs). In `stream_unavailable`'s + `missing_nodes` such a task is named `node#k`, `k` being its position among + the step's `Send` tasks. The + `arg` travels through the workflow as the checkpoint serializer's bytes, so it + must be something that serializer handles. +- **Routers stream after their node's update.** The LLM tokens and + `get_stream_writer()` events of a conditional edge's function are sent as its + source node's (`langgraph_node` and step), as LangGraph does, but the router + runs after the node finished, so they follow that node's `updates` chunk + where LangGraph sends them before it. +- **The `config` of `astream`, `invoke` and `run_async` travels as JSON.** + `tags`, `metadata`, `configurable` and `recursion_limit` work; `recursion_limit` + bounds the run's steps as LangGraph counts them (N sequential nodes need a limit + of N + 1) and the runner's `max_steps` applies when it is absent. A + `recursion_limit` and `configurable` bound with `compiled.with_config(...)` + apply unless the call sets its own. `callbacks` and any value that is not JSON + raise `ValueError` before a run starts. ## Architecture diff --git a/diagrid/agent/langgraph/models.py b/diagrid/agent/langgraph/models.py index 5b32e282..79551c3c 100644 --- a/diagrid/agent/langgraph/models.py +++ b/diagrid/agent/langgraph/models.py @@ -233,6 +233,11 @@ class ExecuteNodeInput: thread_id: Thread identifier for the execution. Propagated into the LangGraph ``Runtime`` so sandbox/state backends can resolve which workflow owns a given tool call. + send: Set when the node runs for a ``Send``: ``{"arg": ..., "index": i, + "slot": k}``, the argument the node takes as its input, the + ``Send``'s position in the list its source returned, and its + position among the step's ``Send`` tasks. ``None`` for a node + that runs on the channel state. """ node_name: str @@ -240,6 +245,7 @@ class ExecuteNodeInput: config: Optional[Dict[str, Any]] = None thread_id: Optional[str] = None step: Optional[int] = None + send: Optional[Dict[str, Any]] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -250,6 +256,8 @@ def to_dict(self) -> Dict[str, Any]: } if self.step is not None: data["step"] = self.step + if self.send is not None: + data["send"] = self.send return data @classmethod @@ -260,6 +268,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeInput": config=data.get("config"), thread_id=data.get("thread_id"), step=data.get("step"), + send=data.get("send"), ) @@ -273,12 +282,15 @@ class ExecuteNodeOutput: error: Optional error message goto: Nodes the node asked to run next through ``Command(goto=...)``, in addition to the nodes its edges lead to + sends: The ``Send`` objects of that ``goto``, each ``{"node", "arg"}``: + every one runs its node once, on its argument """ node_name: str writes: List[NodeWrite] = field(default_factory=list) error: Optional[str] = None goto: List[str] = field(default_factory=list) + sends: List[Dict[str, Any]] = field(default_factory=list) def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -288,6 +300,8 @@ def to_dict(self) -> Dict[str, Any]: } if self.goto: data["goto"] = list(self.goto) + if self.sends: + data["sends"] = list(self.sends) return data @classmethod @@ -297,6 +311,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeOutput": writes=[NodeWrite.from_dict(w) for w in data.get("writes", [])], error=data.get("error"), goto=list(data.get("goto") or []), + sends=list(data.get("sends") or []), ) @@ -313,6 +328,10 @@ class EvaluateConditionInput: thread_id: Thread identifier for the execution path_map: Optional mapping from the condition's return values to node names (see ``EdgeConfig.path_map``) + step: The workflow step of the source node (``-1`` for a START edge), + so a streamed run can give the condition's chunks that node's + step. ``None`` (an older workflow): the condition's chunks are not + streamed. """ source_node: str @@ -321,9 +340,10 @@ class EvaluateConditionInput: config: Optional[Dict[str, Any]] = None thread_id: Optional[str] = None path_map: Optional[Dict[str, str]] = None + step: Optional[int] = None def to_dict(self) -> Dict[str, Any]: - return { + data: Dict[str, Any] = { "source_node": self.source_node, "condition_name": self.condition_name, "channel_state": self.channel_state.to_dict(), @@ -331,6 +351,9 @@ def to_dict(self) -> Dict[str, Any]: "thread_id": self.thread_id, "path_map": self.path_map, } + if self.step is not None: + data["step"] = self.step + return data @classmethod def from_dict(cls, data: Dict[str, Any]) -> "EvaluateConditionInput": @@ -341,6 +364,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "EvaluateConditionInput": config=data.get("config"), thread_id=data.get("thread_id"), path_map=data.get("path_map"), + step=data.get("step"), ) @@ -351,22 +375,29 @@ class EvaluateConditionOutput: Attributes: next_nodes: List of next node names to execute error: Optional error message + sends: The ``Send`` objects the condition returned, each ``{"node", + "arg"}``: every one runs its node once, on its argument """ next_nodes: List[str] = field(default_factory=list) error: Optional[str] = None + sends: List[Dict[str, Any]] = field(default_factory=list) def to_dict(self) -> Dict[str, Any]: - return { + data: Dict[str, Any] = { "next_nodes": self.next_nodes, "error": self.error, } + if self.sends: + data["sends"] = list(self.sends) + return data @classmethod def from_dict(cls, data: Dict[str, Any]) -> "EvaluateConditionOutput": return cls( next_nodes=data.get("next_nodes", []), error=data.get("error"), + sends=list(data.get("sends") or []), ) diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 9127ea56..ff732e41 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -23,6 +23,7 @@ ) from dapr.ext.workflow import WorkflowStatus +from langchain_core.runnables.config import DEFAULT_RECURSION_LIMIT from diagrid.agent.core.types.type import SupportedFrameworks from diagrid.agent.core.workflow import BaseWorkflowRunner @@ -50,9 +51,11 @@ STREAM_RUN_KEY, UPDATES, StaticConfig, + FAILED_STATUSES, StreamControl, normalize_final, normalize_stream_mode, + run_error, ) from .stream_events import ( FINAL_EVENTS, @@ -74,6 +77,8 @@ node_activity_name, register_node, register_node_static_config, + register_condition_input, + register_node_input, register_node_triggers, register_condition, register_channel_reducer, @@ -144,6 +149,35 @@ def _check_run_config(config: Optional[Dict[str, Any]]) -> None: ) from e +def _merge_graph_config( + graph_config: Optional[Dict[str, Any]], config: Optional[Dict[str, Any]] +) -> Dict[str, Any]: + """``config`` over the config bound to the graph (``compiled.with_config(...)``). + + LangGraph merges the two for every run: the bound ``configurable`` is the + base of the caller's, and the bound ``recursion_limit`` applies unless the + caller sets one (LangGraph takes the default, 25, for no limit). The bound + ``metadata`` and ``tags`` reach the tasks through ``StaticConfig``, and bound + ``callbacks`` (handler objects) cannot travel to the workflow as JSON. + Returns a new dict. + """ + bound = graph_config or {} + merged = dict(config or {}) + configurable = { + **(bound.get("configurable") or {}), + **(merged.get("configurable") or {}), + } + if configurable: + merged["configurable"] = configurable + limit = bound.get("recursion_limit") + if limit is not None and merged.get("recursion_limit") in ( + None, + DEFAULT_RECURSION_LIMIT, + ): + merged["recursion_limit"] = limit + return merged + + def _max_steps_for(config: Optional[Dict[str, Any]], default: int) -> int: """The workflow's step bound: ``config['recursion_limit']`` as LangGraph counts it. @@ -359,6 +393,9 @@ def _extract_graph_config(self) -> GraphConfig: ) register_node_triggers(node_name, triggers) + register_node_input( + node_name, node_spec.channels, getattr(node_spec, "mapper", None) + ) register_node_static_config(node_name, self._static_config(node_spec)) nodes.append( NodeConfig( @@ -396,6 +433,9 @@ def _extract_graph_config(self) -> GraphConfig: if path_func: condition_name = f"{source}_{branch_name}_condition" register_condition(condition_name, path_func) + self._register_condition_input( + condition_name, source, branch_spec + ) # ``ends`` is the edge's path_map ({return value: node}), # either given to add_conditional_edges or inferred from @@ -460,6 +500,41 @@ def _extract_graph_config(self) -> GraphConfig: waiting_edges=waiting_edges, ) + def _run_config(self, config: Optional[Dict[str, Any]]) -> Dict[str, Any]: + """The config a run starts with: the caller's over the graph's own. + + Checked for what cannot travel to the workflow before anything starts. + """ + merged = _merge_graph_config(getattr(self._graph, "config", None), config) + _check_run_config(merged) + return merged + + def _register_condition_input( + self, condition_name: str, source: str, branch_spec: Any + ) -> None: + """Record the state a conditional edge's function is handed. + + LangGraph reads it through the edge's input schema (taken from the + annotation of the function's parameter), else its source node's, else the + graph's state schema: the channels of that schema, coerced to the schema + class for pydantic and dataclass state. A function with no input schema + of its own is also given the keys its source node wrote, so the state is + not cut to the channels then (unless it is coerced to a class). + """ + builder = self._graph.builder + node = builder.nodes.get(source) + schema = branch_spec.input_schema or ( + node.input_schema if node is not None else builder.state_schema + ) + channels = builder.schemas.get(schema) + if channels is None: + return + mapper = getattr(self._graph, "schema_to_mapper", {}).get(schema) + cut = branch_spec.input_schema is not None or mapper is not None + register_condition_input( + condition_name, list(channels) if cut else None, mapper + ) + def _static_config(self, node_spec: Any) -> StaticConfig: """The metadata and tags the compiled graph and this node give its tasks.""" graph_config = getattr(self._graph, "config", None) or {} @@ -562,13 +637,25 @@ def invoke( Args: input: Input values for the graph channels thread_id: Thread identifier for the execution - config: Optional LangGraph config dict + config: Optional LangGraph config dict. It travels to the workflow + as JSON: ``tags``, ``metadata``, ``configurable`` and + ``recursion_limit`` work (the limit bounds the run's steps as + LangGraph counts them; ``recursion_limit`` and ``configurable`` + bound to the graph with ``with_config`` apply unless the caller + sets its own). ``callbacks`` and any value that is not JSON + raise ``ValueError`` before a run starts. workflow_id: Optional workflow instance ID (generated if not provided) poll_interval: How often to poll for workflow status (seconds) timeout: Optional timeout in seconds Returns: Final output values from the graph + + Raises: + GraphRecursionError: The run hit its step limit (the error is also a + :class:`GraphRunError`). + GraphRunError: The run failed (a node or a condition raised). + RuntimeError: The workflow failed or was terminated. """ if not self._started: raise RuntimeError("Runner not started. Call start() first.") @@ -577,8 +664,7 @@ def invoke( thread_id = thread_id or str(uuid.uuid4()) workflow_id = workflow_id or f"graph-{thread_id}-{uuid.uuid4().hex[:8]}" - _check_run_config(config) - config = config or {} + config = self._run_config(config) config["thread_id"] = thread_id # Create LangSmith parent trace and pass dotted_order to activities via config. @@ -668,6 +754,21 @@ def invoke( else state.serialized_output ) output = GraphWorkflowOutput.from_dict(output_dict) + if output.status in FAILED_STATUSES: + # Not a result: a run that hit its step limit or + # failed in a node raises, as native invoke does. + raise run_error( + normalize_final( + { + "type": "workflow_completed", + "status": output.status, + "error": output.error, + "output": output.output, + }, + workflow_id=workflow_id, + thread_id=thread_id, + ) + ) return output.output return {} @@ -707,7 +808,9 @@ async def run_async( Args: input: Input values for the graph channels thread_id: Thread identifier for the execution - config: Optional LangGraph config dict + config: Optional LangGraph config dict, with the rules of + :meth:`invoke`: JSON only, ``callbacks`` and values that are not + JSON raise ``ValueError``, and ``recursion_limit`` bounds the steps workflow_id: Optional workflow instance ID (generated if not provided) poll_interval: How often to poll for workflow status (seconds) @@ -721,8 +824,7 @@ async def run_async( thread_id = thread_id or str(uuid.uuid4()) workflow_id = workflow_id or f"graph-{thread_id}-{uuid.uuid4().hex[:8]}" - _check_run_config(config) - config = config or {} + config = self._run_config(config) config["thread_id"] = thread_id # Create LangSmith parent trace and pass dotted_order to activities via config. @@ -947,7 +1049,7 @@ async def _stream_events( whenever nothing arrived for ``SSE_KEEPALIVE_SECONDS``. """ thread_id, workflow_id, run_config = _run_identity( - config, thread_id, workflow_id + self._run_config(config), thread_id, workflow_id ) sink = self._stream_registry.open(workflow_id) task: Optional["asyncio.Task[None]"] = None diff --git a/diagrid/agent/langgraph/stream_events.py b/diagrid/agent/langgraph/stream_events.py index bdeb11cf..d81b1d9a 100644 --- a/diagrid/agent/langgraph/stream_events.py +++ b/diagrid/agent/langgraph/stream_events.py @@ -21,6 +21,7 @@ EXECUTED_KEY, GraphRunError, StreamControl, + run_error, stream_unavailable_event, to_wire, ) @@ -176,7 +177,7 @@ def route_astream_item( if is_list: out.append((control.kind, control.data)) if item.get("type") == "workflow_failed": - return out, GraphRunError(item) + return out, run_error(item) return out, None diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index 7e7f00a1..d5aa2428 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -19,6 +19,7 @@ from langchain_core.load import dumpd from langchain_core.load.serializable import Serializable +from langgraph.errors import GraphRecursionError from diagrid.agent.core.workflow.stream import ( STREAM_UNAVAILABLE, @@ -143,7 +144,14 @@ def __init__( thread_id: Optional[str] = None, triggers: Optional[Sequence[str]] = None, static: Optional[StaticConfig] = None, + sink_node: Optional[str] = None, + path: Optional[Sequence[Any]] = None, ) -> None: + self._path = tuple(path) if path else None + # ``sink_node`` is the name chunks are keyed under in the sink when it + # is not the node's own: a conditional edge's function streams as its + # source node but must not share that node's attempts and ``updates``. + self._sink_node = sink_node or node self._static = static or StaticConfig() self._sink = sink self._thread_id = thread_id @@ -170,7 +178,7 @@ def metadata(self) -> Dict[str, Any]: "langgraph_node": self._node, # Every trigger channel of the node, sorted, as Pregel lists them. "langgraph_triggers": self._triggers or (f"branch:to:{self._node}",), - "langgraph_path": ("__pregel_pull", self._node), + "langgraph_path": self._path or ("__pregel_pull", self._node), "langgraph_checkpoint_ns": f"{self._node}:{self._task_id}", "checkpoint_ns": f"{self._node}:{self._task_id}", } @@ -181,12 +189,14 @@ def _emit(self, ns: Tuple[str, ...], mode: str, data: Any) -> None: StreamEvent( workflow_id=self._workflow_id, step=self._step, - node=self._node, + node=self._sink_node, attempt_id=self._attempt_id, seq=next(self._seq), ns=tuple(ns), mode=mode, data=data, + display_node=self._node, + path=self._path, ) ) @@ -422,6 +432,21 @@ def __init__(self, final: Dict[str, Any]) -> None: self.final = final +class GraphRecursionRunError(GraphRunError, GraphRecursionError): + """A run cut by its step limit: a :class:`GraphRunError` that is also LangGraph's. + + ``except GraphRecursionError`` (the usual guard around an agent loop) catches + it, as it catches the error native LangGraph raises. + """ + + +def run_error(final: Dict[str, Any]) -> GraphRunError: + """The exception for a ``workflow_failed`` terminal event.""" + if final.get("status") == "max_steps_reached": + return GraphRecursionRunError(final) + return GraphRunError(final) + + def _failed(final: Dict[str, Any], message: str, error_type: str) -> Dict[str, Any]: return { **final, diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 4beb6281..17d992e3 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -3,14 +3,17 @@ """Dapr Workflow definitions for durable LangGraph execution.""" +import asyncio +import base64 import contextlib import copy import dataclasses import functools import logging +import threading import uuid from datetime import timedelta -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import ( Any, Callable, @@ -30,10 +33,16 @@ when_all, ) +from langchain_core.messages import ( + AnyMessage, + convert_to_messages, + message_chunk_to_message, +) from langchain_core.runnables.config import run_in_executor, set_config_context -from pydantic import BaseModel +from langgraph.graph.message import add_messages +from pydantic import BaseModel, TypeAdapter, ValidationError from langgraph.runtime import Runtime -from langgraph.types import Command, Send +from langgraph.types import Command, Overwrite, Send try: from langgraph.runtime import ExecutionInfo @@ -80,6 +89,11 @@ # The graph's state channels: a node's other keys are not writes, as in LangGraph. # ``None`` until a runner registers them (then nothing is dropped). _state_channels: Optional[frozenset] = None +# What a node and a conditional edge are handed: the channels of its input schema +# and the function that coerces the state dict to a schema class (pydantic or +# dataclass state). Conditions are keyed by their name. +_node_inputs: Dict[str, "_InputShape"] = {} +_condition_inputs: Dict[str, "_InputShape"] = {} _serializer: Optional[Any] = None _default_graph_config: Optional["GraphConfig"] = None _default_input_mapper: Optional[Callable] = None @@ -89,6 +103,9 @@ # The metadata and tags the graph and each node give their tasks (see StaticConfig). _node_static: Dict[str, StaticConfig] = {} +# The key a write that replaces a reducer channel's value is stored under. +OVERWRITE = "__overwrite__" + # Special node names START = "__start__" END = "__end__" @@ -98,9 +115,21 @@ # every node as ``execute_node_activity``; the patch keeps them replaying. NODE_ACTIVITY_NAMES_PATCH = "langgraph-node-activity-names" GENERIC_NODE_ACTIVITY = "execute_node_activity" -_GENERIC_ACTIVITY_NAMES = frozenset( - {GENERIC_NODE_ACTIVITY, "evaluate_condition_activity"} -) +CONDITION_ACTIVITY = "evaluate_condition_activity" +# What LangGraph names the trigger (and path) of a task started by a ``Send``. +PUSH_TRIGGER = "__pregel_push" + + +def send_key(node: str, slot: int) -> str: + """The name a ``Send`` task's chunks and ``executed`` entry go by. + + Several ``Send`` tasks may run the same node in one step; each needs a name + of its own so their attempts and ``updates`` are not taken for one node's. + """ + return f"{node}#{slot}" + + +_GENERIC_ACTIVITY_NAMES = frozenset({GENERIC_NODE_ACTIVITY, CONDITION_ACTIVITY}) def node_activity_name(node_name: str) -> str: @@ -188,6 +217,40 @@ def register_channel_reducer( _channel_defaults[channel] = default +@dataclass(frozen=True) +class _InputShape: + """The channels a node reads and the mapper that builds the object it takes.""" + + channels: Optional[Tuple[str, ...]] = None + mapper: Optional[Callable[[Dict[str, Any]], Any]] = None + + def apply(self, state: Dict[str, Any]) -> Any: + """``state`` cut to the channels and coerced to the schema class.""" + channels = self.channels + if channels is not None: + state = {k: v for k, v in state.items() if k in channels} + return self.mapper(state) if self.mapper else state + + +def _input_shape(channels: Any, mapper: Optional[Callable]) -> _InputShape: + """The shape for an input schema's ``channels`` (a single root channel is not cut).""" + names = [channels] if isinstance(channels, str) else list(channels or ()) + keep = tuple(names) if names and "__root__" not in names else None + return _InputShape(channels=keep, mapper=mapper) + + +def register_node_input(name: str, channels: Any, mapper: Optional[Callable]) -> None: + """Record what node ``name`` is handed as its state.""" + _node_inputs[name] = _input_shape(channels, mapper) + + +def register_condition_input( + name: str, channels: Any, mapper: Optional[Callable] +) -> None: + """Record what the conditional edge ``name`` is handed as its state.""" + _condition_inputs[name] = _input_shape(channels, mapper) + + def register_state_channels(channels: Iterable[str]) -> None: """Record the graph's state channels, the only keys a node can write.""" global _state_channels @@ -296,9 +359,10 @@ def clear_registries() -> None: _channel_defaults.clear() global _state_channels _state_channels = None - default_registry.clear_reports() _node_triggers.clear() _node_static.clear() + _node_inputs.clear() + _condition_inputs.clear() global _serializer, _default_graph_config, _default_input_mapper, _default_max_steps _serializer = None _default_graph_config = None @@ -306,6 +370,77 @@ def clear_registries() -> None: _default_max_steps = 100 +def _workflow_input( + ctx: DaprWorkflowContext, input_data: Dict[str, Any] +) -> GraphWorkflowInput: + """The workflow's input: a full ``GraphWorkflowInput`` or a ``{"task": ...}``.""" + if "graph_config" in input_data: + # Normal internal call with full GraphWorkflowInput + return GraphWorkflowInput.from_dict(input_data) + + # Orchestrator call with simple {"task": "..."} input + if _default_graph_config is None: + raise ValueError( + "Received simple task input but no default graph config is set. " + "Ensure the runner has been started before the workflow is invoked." + ) + # Build graph input from the task using the stored mapper + if _default_input_mapper: + graph_input = _default_input_mapper(input_data) + elif "task" in input_data: + graph_input = {"messages": [{"role": "user", "content": input_data["task"]}]} + else: + graph_input = input_data + + channel_state = ChannelState( + values=_serialize_input( + graph_input, lambda c, i: _replay_safe_id(ctx.instance_id, i, c) + ), + versions={k: 1 for k in graph_input.keys()}, + updated_channels=list(graph_input.keys()), + ) + return GraphWorkflowInput( + graph_config=_default_graph_config, + channel_state=channel_state, + step=0, + max_steps=_default_max_steps, + thread_id=str(ctx.instance_id), + ) + + +@dataclass +class _Run: + """What every step of one ``agent_workflow`` execution shares.""" + + ctx: DaprWorkflowContext + graph_config: GraphConfig + channel_state: ChannelState + config: Optional[Dict[str, Any]] + thread_id: Optional[str] + retry_policy: RetryPolicy + node_activities_by_name: bool + #: The nodes that ran in each step, reported on the output so a streaming + #: consumer can tell which node's chunks never arrived. + executed: List[List[str]] = field(default_factory=list) + + def finish( + self, step: int, status: str, error: Optional[str] = None + ) -> Dict[str, Any]: + """Close the run's trace and build the workflow output.""" + if not self.ctx.is_replaying: + _close_langsmith_parent_trace_async(self.config) + return GraphWorkflowOutput( + output=_extract_output( + self.channel_state, self.graph_config.output_channels + ), + channel_state=self.channel_state, + steps=step, + executed=self.executed, + status=status, + **({"error": error} if error else {}), + ).to_dict() + + def agent_workflow( ctx: DaprWorkflowContext, input_data: Dict[str, Any] ) -> Generator[Any, Any, Dict[str, Any]]: @@ -324,87 +459,34 @@ def agent_workflow( Returns: GraphWorkflowOutput as a dictionary """ - if "graph_config" in input_data: - # Normal internal call with full GraphWorkflowInput - workflow_input = GraphWorkflowInput.from_dict(input_data) - else: - # Orchestrator call with simple {"task": "..."} input - if _default_graph_config is None: - raise ValueError( - "Received simple task input but no default graph config is set. " - "Ensure the runner has been started before the workflow is invoked." - ) - # Build graph input from the task using the stored mapper - if _default_input_mapper: - graph_input = _default_input_mapper(input_data) - elif "task" in input_data: - graph_input = { - "messages": [{"role": "user", "content": input_data["task"]}] - } - else: - graph_input = input_data - - channel_state = ChannelState( - values=_serialize_input( - graph_input, lambda i: _replay_safe_id(ctx.instance_id, i) - ), - versions={k: 1 for k in graph_input.keys()}, - updated_channels=list(graph_input.keys()), - ) - workflow_input = GraphWorkflowInput( - graph_config=_default_graph_config, - channel_state=channel_state, - step=0, - max_steps=_default_max_steps, - thread_id=str(ctx.instance_id), - ) + workflow_input = _workflow_input(ctx, input_data) # Ask before the first yield: a replay of an older instance must see the # patch as absent, and the answer is fixed for the rest of the execution. node_activities_by_name = ctx.is_patched(NODE_ACTIVITY_NAMES_PATCH) - graph_config = workflow_input.graph_config - channel_state = workflow_input.channel_state - max_steps = workflow_input.max_steps - config = workflow_input.config - thread_id = workflow_input.thread_id - - # Retry policy for activities - retry_policy = RetryPolicy( - max_number_of_attempts=3, - first_retry_interval=timedelta(seconds=1), - backoff_coefficient=2.0, - max_retry_interval=timedelta(seconds=30), + run = _Run( + ctx=ctx, + graph_config=workflow_input.graph_config, + channel_state=workflow_input.channel_state, + config=workflow_input.config, + thread_id=workflow_input.thread_id, + retry_policy=RetryPolicy( + max_number_of_attempts=3, + first_retry_interval=timedelta(seconds=1), + backoff_coefficient=2.0, + max_retry_interval=timedelta(seconds=30), + ), + node_activities_by_name=node_activities_by_name, ) - + max_steps = workflow_input.max_steps step = 0 - # The nodes that ran in each step, reported on the output so a streaming - # consumer can tell which node's chunks never arrived. - executed: List[List[str]] = [] - # Start with the nodes the START edges lead to; a conditional START edge is - # evaluated on the input, as LangGraph does. - if graph_config.entry_points is None: # a config from before entry_points - pending_nodes = [graph_config.entry_point] - else: - pending_nodes = list(graph_config.entry_points) - for edge in graph_config.edges: - if edge.source != START or not edge.condition: - continue - cond_output = yield from _evaluate_edge( - ctx, edge, START, channel_state, config, thread_id, retry_policy - ) - if cond_output.error: - if not ctx.is_replaying: - _close_langsmith_parent_trace_async(config) - return _condition_failed( - graph_config, channel_state, step, executed, cond_output.error - ) - for n in cond_output.next_nodes: - if n not in pending_nodes: - pending_nodes.append(n) + pending_nodes, pending_sends, error = yield from _start_nodes(run) + if error: + return run.finish(step, "error", f"Condition evaluation failed: {error}") # Joins: how many of each waiting edge's sources have run since it last fired. - joined: List[Set[str]] = [set() for _ in graph_config.waiting_edges] + joined: List[Set[str]] = [set() for _ in run.graph_config.waiting_edges] # Main execution loop while True: @@ -417,137 +499,198 @@ def agent_workflow( # END ends the run only when nothing else is pending: another branch of # the step may still have nodes to run, as in LangGraph. nodes_to_execute = [n for n in pending_nodes if n != END] - if not nodes_to_execute: - if not ctx.is_replaying: - _close_langsmith_parent_trace_async(config) - return GraphWorkflowOutput( - output=_extract_output(channel_state, graph_config.output_channels), - channel_state=channel_state, - steps=step, - executed=executed, - status="completed", - ).to_dict() + if not nodes_to_execute and not pending_sends: + return run.finish(step, "completed") # The bound is checked after the end of the run, so a graph that needs # exactly ``max_steps`` steps completes instead of being cut at the end. if step >= max_steps: break - executed.append(list(nodes_to_execute)) - - # Execute all triggered nodes in parallel (each as a separate activity) - node_tasks = [] - for node_name in nodes_to_execute: - node_input = ExecuteNodeInput( - node_name=node_name, - channel_state=channel_state, - config=config, - thread_id=thread_id, - step=step, - ) - activity: Any = execute_node_activity - if node_activities_by_name: - activity = node_activity_name(node_name) - task = ctx.call_activity( - activity, - input=node_input.to_dict(), - retry_policy=retry_policy, + run.executed.append( + [ + *nodes_to_execute, + *[send_key(t["node"], slot) for slot, t in enumerate(pending_sends)], + ] + ) + + node_outputs = yield from _run_nodes(run, nodes_to_execute, pending_sends, step) + failed = next((o for o in node_outputs if o.error), None) + if failed: + return run.finish( + step, "error", f"Node '{failed.node_name}' failed: {failed.error}" ) - node_tasks.append(task) - - # Wait for all node executions to complete - task_results = yield when_all(node_tasks) - - # Collect outputs and check for errors - node_outputs: List[ExecuteNodeOutput] = [] - for result_data in task_results: - output = ExecuteNodeOutput.from_dict(result_data) - if output.error: - if not ctx.is_replaying: - _close_langsmith_parent_trace_async(config) - return GraphWorkflowOutput( - output=_extract_output(channel_state, graph_config.output_channels), - channel_state=channel_state, - steps=step, - executed=executed, - status="error", - error=f"Node '{output.node_name}' failed: {output.error}", - ).to_dict() - node_outputs.append(output) # Apply writes to channels - updated_channels = [] - for output in node_outputs: - for write in output.writes: - _apply_write(channel_state, write.channel, write.value) - if write.channel not in updated_channels: - updated_channels.append(write.channel) - - channel_state.updated_channels = updated_channels - - # Determine next nodes based on edges from executed nodes - next_nodes = [] - for node_name in nodes_to_execute: - for edge in graph_config.edges: - if edge.source == node_name: - if edge.condition: - # Evaluate conditional edge (as activity) - cond_output = yield from _evaluate_edge( - ctx, - edge, - node_name, - channel_state, - config, - thread_id, - retry_policy, - ) - if cond_output.error: - if not ctx.is_replaying: - _close_langsmith_parent_trace_async(config) - return _condition_failed( - graph_config, - channel_state, - step, - executed, - cond_output.error, - ) - for n in cond_output.next_nodes: - if n not in next_nodes: - next_nodes.append(n) - else: - # Direct edge - if edge.target not in next_nodes: - next_nodes.append(edge.target) - - # A join fires, once, in the step after the last of its sources ran. - for seen, join in zip(joined, graph_config.waiting_edges): - seen.update(n for n in nodes_to_execute if n in join.sources) - if seen.issuperset(join.sources): - seen.clear() - if join.target not in next_nodes: - next_nodes.append(join.target) - - # Nodes a Command(goto=...) asked for run next as well, as in LangGraph. - for output in node_outputs: - for target in output.goto: - if target not in next_nodes: - next_nodes.append(target) - - # Move to next step - pending_nodes = next_nodes + try: + updated_channels = _apply_outputs(run.channel_state, node_outputs) + except ReducerError as e: + return run.finish(step, "error", str(e)) + run.channel_state.updated_channels = updated_channels + + ran = list( + dict.fromkeys([*nodes_to_execute, *[t["node"] for t in pending_sends]]) + ) + pending_nodes, pending_sends, error = yield from _next_nodes( + run, ran, node_outputs, joined, step + ) + if error: + return run.finish(step, "error", f"Condition evaluation failed: {error}") step += 1 # Max steps reached - if not ctx.is_replaying: - _close_langsmith_parent_trace_async(config) - return GraphWorkflowOutput( - output=_extract_output(channel_state, graph_config.output_channels), - channel_state=channel_state, - steps=step, - executed=executed, - status="max_steps_reached", - error=f"Max steps ({max_steps}) reached", - ).to_dict() + return run.finish(step, "max_steps_reached", f"Max steps ({max_steps}) reached") + + +def _apply_outputs( + channel_state: ChannelState, node_outputs: List[ExecuteNodeOutput] +) -> List[str]: + """Apply the writes of a step's nodes; the channels they updated, in order.""" + updated_channels: List[str] = [] + for output in node_outputs: + for write in output.writes: + _apply_write(channel_state, write.channel, write.value) + if write.channel not in updated_channels: + updated_channels.append(write.channel) + return updated_channels + + +_StartOrNext = Tuple[List[str], List[Dict[str, Any]], Optional[str]] + + +def _start_nodes(run: _Run) -> Generator[Any, Any, _StartOrNext]: + """The nodes (and ``Send`` tasks) the START edges lead to, and a condition error. + + A conditional START edge is evaluated on the input, as LangGraph does. + """ + graph_config = run.graph_config + if graph_config.entry_points is None: # a config from before entry_points + return [graph_config.entry_point], [], None + pending_nodes = list(graph_config.entry_points) + pending_sends: List[Dict[str, Any]] = [] + for edge in graph_config.edges: + if edge.source != START or not edge.condition: + continue + cond_output = yield from _evaluate_edge( + run.ctx, + edge, + START, + run.channel_state, + run.config, + run.thread_id, + run.retry_policy, + -1, # before the first node, so the first node is step 1 + ) + if cond_output.error: + return pending_nodes, pending_sends, cond_output.error + for n in cond_output.next_nodes: + if n not in pending_nodes: + pending_nodes.append(n) + pending_sends.extend(_indexed(cond_output.sends)) + return pending_nodes, pending_sends, None + + +def _indexed(sends: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """``sends`` numbered by their position in the list one source returned.""" + return [{**send, "index": i} for i, send in enumerate(sends)] + + +def _run_nodes( + run: _Run, + nodes_to_execute: List[str], + sends: List[Dict[str, Any]], + step: int, +) -> Generator[Any, Any, List[ExecuteNodeOutput]]: + """Run the nodes and ``Send`` tasks of one step in parallel, each as an activity.""" + node_tasks = [] + invocations: List[Tuple[str, Optional[Dict[str, Any]]]] = [ + *[(name, None) for name in nodes_to_execute], + *[ + (t["node"], {"arg": t["arg"], "index": t["index"], "slot": slot}) + for slot, t in enumerate(sends) + ], + ] + for node_name, send in invocations: + node_input = ExecuteNodeInput( + node_name=node_name, + channel_state=run.channel_state, + config=run.config, + thread_id=run.thread_id, + step=step, + send=send, + ) + activity: Any = execute_node_activity + if run.node_activities_by_name: + activity = node_activity_name(node_name) + node_tasks.append( + run.ctx.call_activity( + activity, + input=node_input.to_dict(), + retry_policy=run.retry_policy, + ) + ) + + # Wait for all node executions to complete + task_results = yield when_all(node_tasks) + return [ExecuteNodeOutput.from_dict(result) for result in task_results] + + +def _next_nodes( + run: _Run, + nodes_to_execute: List[str], + node_outputs: List[ExecuteNodeOutput], + joined: List[Set[str]], + step: int, +) -> Generator[Any, Any, _StartOrNext]: + """The nodes and ``Send`` tasks the next step runs, and a condition error. + + They follow from the edges of the nodes that ran, the joins those nodes + complete, and the ``Command(goto=...)`` they returned. + """ + next_nodes: List[str] = [] + next_sends: List[Dict[str, Any]] = [] + for node_name in nodes_to_execute: + for edge in run.graph_config.edges: + if edge.source != node_name: + continue + if not edge.condition: + # Direct edge + if edge.target not in next_nodes: + next_nodes.append(edge.target) + continue + # Evaluate conditional edge (as activity) + cond_output = yield from _evaluate_edge( + run.ctx, + edge, + node_name, + run.channel_state, + run.config, + run.thread_id, + run.retry_policy, + step, + ) + if cond_output.error: + return next_nodes, next_sends, cond_output.error + for n in cond_output.next_nodes: + if n not in next_nodes: + next_nodes.append(n) + next_sends.extend(_indexed(cond_output.sends)) + + # A join fires, once, in the step after the last of its sources ran. + for seen, join in zip(joined, run.graph_config.waiting_edges): + seen.update(n for n in nodes_to_execute if n in join.sources) + if seen.issuperset(join.sources): + seen.clear() + if join.target not in next_nodes: + next_nodes.append(join.target) + + # Nodes a Command(goto=...) asked for run next as well, as in LangGraph. + for output in node_outputs: + for target in output.goto: + if target not in next_nodes: + next_nodes.append(target) + next_sends.extend(_indexed(output.sends)) + return next_nodes, next_sends, None def _evaluate_edge( @@ -558,6 +701,7 @@ def _evaluate_edge( config: Optional[Dict[str, Any]], thread_id: Optional[str], retry_policy: RetryPolicy, + step: int, ) -> Generator[Any, Any, EvaluateConditionOutput]: """Evaluate a conditional edge as an activity; ``yield from`` it.""" cond_input = EvaluateConditionInput( @@ -567,33 +711,18 @@ def _evaluate_edge( config=config, thread_id=thread_id, path_map=edge.path_map, + step=step, ) + # By name, so the runner's own activity (the one that knows its stream + # registry) runs, not the module-level function. cond_result = yield ctx.call_activity( - evaluate_condition_activity, + CONDITION_ACTIVITY, input=cond_input.to_dict(), retry_policy=retry_policy, ) return EvaluateConditionOutput.from_dict(cond_result) -def _condition_failed( - graph_config: GraphConfig, - channel_state: ChannelState, - step: int, - executed: List[List[str]], - error: str, -) -> Dict[str, Any]: - """The workflow output for a conditional edge that could not be evaluated.""" - return GraphWorkflowOutput( - output=_extract_output(channel_state, graph_config.output_channels), - channel_state=channel_state, - steps=step, - executed=executed, - status="error", - error=f"Condition evaluation failed: {error}", - ).to_dict() - - def _build_node_runtime( thread_id: Optional[str], ctx: WorkflowActivityContext, @@ -667,13 +796,11 @@ class _NodeCall: ctx: WorkflowActivityContext node_input: ExecuteNodeInput node_func: Callable - state: Dict[str, Any] + state: Any config: Dict[str, Any] streamer: Optional[NodeStreamer] #: Side-channel writes queued via CONFIG_KEY_SEND while the node runs. pending_sends: list - #: The runner's registry (``None``: the module's), which remembers warnings. - registry: Optional[StreamSinkRegistry] = None @property def node_name(self) -> str: @@ -692,43 +819,84 @@ def _make_activity_read( In normal LangGraph execution the Pregel engine injects a read function bound to live BaseChannel objects. Here the activity only has a serialized ``channel_state``, so we read from that. + + It is a ``functools.partial`` whose second argument is the channel mapping, + as Pregel's is: the prebuilt tool node reads ``read.args[1]`` for the + channel names when ``create_agent`` sends it a bare list of tool calls. """ + return functools.partial( + _read_activity_channels, pending_sends, channel_state.values + ) - def _activity_read(select: Any, fresh: bool = False) -> Any: - if fresh: - # Apply any pending sends to a snapshot before reading. - merged = dict(channel_state.values) - for ch, val in pending_sends: - reducer = get_channel_reducer(ch) - if reducer and ch in merged: - try: - merged[ch] = reducer(merged[ch], val) - except Exception: - merged[ch] = val - else: + +def _read_activity_channels( + pending_sends: list, + channels: Dict[str, Any], + select: Any, + fresh: bool = False, +) -> Any: + if fresh: + # Apply any pending sends to a snapshot before reading. + merged = dict(channels) + for ch, val in pending_sends: + reducer = get_channel_reducer(ch) + if reducer and ch in merged: + try: + merged[ch] = reducer(merged[ch], val) + except Exception: merged[ch] = val - source = merged - else: - source = channel_state.values + else: + merged[ch] = val + source = merged + else: + source = channels - if isinstance(select, str): - return source.get(select) - return {k: source.get(k) for k in select if k in source} + if isinstance(select, str): + return source.get(select) + return {k: source.get(k) for k in select if k in source} - return _activity_read +class _BackgroundLoop: + """One event loop per process, in a daemon thread, that async nodes run on. -def _await_if_coroutine(r: Any) -> Any: - """Run ``r`` to completion on a private loop if it is a coroutine.""" - import asyncio + An async client a node keeps (a chat model's HTTP connection pool) is bound + to the loop it was first used on. A loop made and closed for each activity + would break that client for the next activity, so every coroutine runs on + this one, which is never closed. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + self._loop: Optional[asyncio.AbstractEventLoop] = None + + def _running_loop(self) -> asyncio.AbstractEventLoop: + with self._lock: + if self._loop is None or self._loop.is_closed(): + loop = asyncio.new_event_loop() + threading.Thread( + target=loop.run_forever, name="langgraph-node-loop", daemon=True + ).start() + self._loop = loop + return self._loop + def run(self, coro: Any) -> Any: + """Run ``coro`` to completion on the loop and return its result. + + ``run_coroutine_threadsafe`` starts the task in a copy of the calling + thread's context, so the ambient config ``set_config_context`` set for + the node is what the coroutine sees. + """ + future = asyncio.run_coroutine_threadsafe(coro, self._running_loop()) + return future.result() + + +_background_loop = _BackgroundLoop() + + +def _await_if_coroutine(r: Any) -> Any: + """Run ``r`` to completion on the process's node loop if it is a coroutine.""" if asyncio.iscoroutine(r): - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - r = loop.run_until_complete(r) - finally: - loop.close() + return _background_loop.run(r) return r @@ -878,7 +1046,37 @@ def _make_streamer( Chunks are streamed only when a consumer registered a sink for this run; otherwise nothing about the node's execution changes. """ - node_name = node_input.node_name + send = node_input.send + return _streamer_for( + ctx, + node_input.node_name, + node_input.step or 0, + node_input.thread_id, + config, + registry, + # a Send is a task of its own, keyed apart from the node's other runs + sink_node=None + if send is None + else send_key(node_input.node_name, send["slot"]), + send_index=None if send is None else send["index"], + ) + + +def _streamer_for( + ctx: WorkflowActivityContext, + node_name: str, + step: int, + thread_id: Optional[str], + config: Dict[str, Any], + registry: Optional[StreamSinkRegistry], + sink_node: Optional[str] = None, + send_index: Optional[int] = None, +) -> Optional[NodeStreamer]: + """A streamer that emits as ``node_name`` at ``step``, or ``None``. + + ``send_index`` is set for a node that runs for a ``Send``: LangGraph tags + such a task with the ``__pregel_push`` trigger and path. + """ sink = get_stream_sink(getattr(ctx, "workflow_id", None), registry=registry) if sink is None: if config.get(STREAM_RUN_KEY): @@ -889,15 +1087,32 @@ def _make_streamer( return NodeStreamer( sink, workflow_id=str(ctx.workflow_id), - step=node_input.step or 0, + step=step, node=node_name, task_id=getattr(ctx, "task_id", ""), - thread_id=node_input.thread_id or config.get("thread_id"), - triggers=get_node_triggers(node_name), + thread_id=thread_id or config.get("thread_id"), + triggers=_task_triggers(node_name, send_index), static=get_node_static_config(node_name), + sink_node=sink_node, + path=None if send_index is None else (PUSH_TRIGGER, send_index, False), ) +def _task_triggers( + node_name: str, send_index: Optional[int] +) -> Optional[Tuple[str, ...]]: + """The ``langgraph_triggers`` of a task: what LangGraph lists for it. + + A ``Send`` task is triggered by the push channel, and a conditional START + edge's function (which is no node, so has no registered triggers) by START. + """ + if send_index is not None: + return (PUSH_TRIGGER,) + if node_name == START: + return (START,) + return get_node_triggers(node_name) + + def _run_with_stream_hooks(call: _NodeCall, parent: Optional[str]) -> Any: """Run the node, telling its streamer when it starts, finishes or fails. @@ -938,10 +1153,12 @@ def _node_output(call: _NodeCall, result: Any) -> Dict[str, Any]: raw_writes = [*_result_to_raw_writes(result), *call.pending_sends] if call.streamer: call.streamer.updates(raw_writes) + goto, sends = _result_to_gotos(result) return ExecuteNodeOutput( node_name=call.node_name, writes=_serialize_writes(raw_writes), - goto=_result_to_gotos(result, call.node_name, call.registry), + goto=goto, + sends=sends, ).to_dict() @@ -991,11 +1208,10 @@ def execute_node_activity( ctx=ctx, node_input=node_input, node_func=node_func, - state=_reconstruct_state(node_input.channel_state), + state=_node_state(node_input), config=config, streamer=_make_streamer(ctx, node_input, config, stream_registry), pending_sends=[], - registry=stream_registry, ) # Run under the LangSmith child trace so LLM calls nest under the parent @@ -1005,6 +1221,15 @@ def execute_node_activity( return _node_output(call, result) +def _node_state(node_input: ExecuteNodeInput) -> Any: + """What the node takes as input: the channel state, or a ``Send``'s argument.""" + if node_input.send is None: + state = _reconstruct_state(node_input.channel_state) + shape = _node_inputs.get(node_input.node_name) + return shape.apply(state) if shape else state + return _decode_arg(node_input.send["arg"]) + + def make_condition_activity( stream_registry: Optional[StreamSinkRegistry] = None, ) -> Callable[[WorkflowActivityContext, Dict[str, Any]], Dict[str, Any]]: @@ -1020,6 +1245,70 @@ def evaluate_condition( return evaluate_condition +def _call_condition( + ctx: WorkflowActivityContext, + cond_input: EvaluateConditionInput, + cond_func: Callable, + state: Any, + registry: Optional[StreamSinkRegistry], +) -> Any: + """Call a conditional edge's function and return what it routed to. + + In a streamed run the function's LLM tokens and ``get_stream_writer()`` + events are sent as its source node's (that is what LangGraph does), keyed + apart from the node's own chunks. + """ + config = dict(cond_input.config or {}) + config[CONF] = dict(config.get(CONF) or {}) + thread_id = ( + cond_input.thread_id + or config.get("thread_id") + or getattr(ctx, "workflow_id", None) + ) + config[CONF].setdefault("thread_id", thread_id) + streamer = None + if cond_input.step is not None: + streamer = _streamer_for( + ctx, + cond_input.source_node, + cond_input.step, + cond_input.thread_id, + config, + registry, + # one key per edge: a node's several conditional edges are several + # tasks, and a key they share would read as one retrying + sink_node=f"{cond_input.source_node}:branch:{cond_input.condition_name}", + ) + if CONFIG_KEY_RUNTIME not in config[CONF]: + config[CONF][CONFIG_KEY_RUNTIME] = _build_node_runtime( + thread_id, + ctx, + cond_input.condition_name, + streamer.writer if streamer else None, + ) + if streamer: + config = streamer.patch_config(config) + + # If the condition is a LangChain Runnable (e.g. RunnableCallable from Deep + # Agents branches), call .invoke() so runtime injection works. + is_runnable = hasattr(cond_func, "invoke") and callable( + getattr(cond_func, "invoke") + ) + + def run() -> Any: + if not is_runnable: + return _await_if_coroutine(cond_func(state)) + if _is_async_only(cond_func): + # A coroutine; run to completion + return _await_if_coroutine(cond_func.ainvoke(state, config=config)) # type: ignore[attr-defined] + return _await_if_coroutine(cond_func.invoke(state, config=config)) # type: ignore[attr-defined] + + # Runnable.invoke only sets the ambient config when tracing, and a plain + # function never does: get_stream_writer() and the stream handler need it. + with set_config_context(config) as ctx_: # type: ignore[arg-type] + return ctx_.run(run) + + def evaluate_condition_activity( ctx: WorkflowActivityContext, input_data: Dict[str, Any], @@ -1031,8 +1320,8 @@ def evaluate_condition_activity( Args: ctx: The workflow activity context input_data: Dictionary containing EvaluateConditionInput data - stream_registry: The runner's registry, which remembers which warnings - were given (default: the module's). + stream_registry: The runner's registry, where the sink of a streamed + run is (default: the module's). Returns: EvaluateConditionOutput as a dictionary @@ -1047,7 +1336,10 @@ def evaluate_condition_activity( ).to_dict() # Reconstruct state from channel values - state = _reconstruct_state(cond_input.channel_state) + state: Any = _reconstruct_state(cond_input.channel_state) + shape = _condition_inputs.get(cond_input.condition_name) + if shape: + state = shape.apply(state) # Evaluate under the parent "LangGraph" trace. A Runnable condition (every # add_conditional_edges path is one) traces itself, so without a parent @@ -1061,42 +1353,7 @@ def evaluate_condition_activity( trace_ctx = contextlib.nullcontext() with trace_ctx: - # Evaluate the condition. - # If the condition is a LangChain Runnable (e.g. RunnableCallable from - # Deep Agents branches), call .invoke() so runtime injection works. - if hasattr(cond_func, "invoke") and callable(getattr(cond_func, "invoke")): - # Copy before mutating; populate the Runtime so a Runnable condition - # can resolve workflow ownership the same way node activities do. - _config = dict(cond_input.config or {}) - _config[CONF] = dict(_config.get(CONF) or {}) - thread_id = ( - cond_input.thread_id - or _config.get("thread_id") - or getattr(ctx, "workflow_id", None) - ) - _config[CONF].setdefault("thread_id", thread_id) - if CONFIG_KEY_RUNTIME not in _config[CONF]: - _config[CONF][CONFIG_KEY_RUNTIME] = _build_node_runtime( - thread_id, ctx, cond_input.condition_name - ) - if _is_async_only(cond_func): - # A coroutine; run to completion below. - result = cond_func.ainvoke(state, config=_config) # type: ignore[attr-defined] - else: - result = cond_func.invoke(state, config=_config) - else: - result = cond_func(state) - - # Handle async functions - import asyncio - - if asyncio.iscoroutine(result): - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - result = loop.run_until_complete(result) - finally: - loop.close() + result = _call_condition(ctx, cond_input, cond_func, state, stream_registry) # Result should be a node name, list of node names, or Send objects. # LangGraph Send objects have a .node attribute with the target node name. @@ -1106,10 +1363,10 @@ def evaluate_condition_activity( items = list(result) if isinstance(result, (list, tuple)) else [result] next_nodes = [] + sends = [] for item in items: - if hasattr(item, "node"): - _warn_send_payload(cond_input.source_node, item, stream_registry) - next_nodes.append(item.node) + if isinstance(item, Send): + sends.append(_send_task(item)) elif path_map is None: next_nodes.append(item if isinstance(item, str) else str(item)) elif str(item) in path_map: @@ -1122,9 +1379,7 @@ def evaluate_condition_activity( ), ).to_dict() - return EvaluateConditionOutput( - next_nodes=next_nodes, - ).to_dict() + return EvaluateConditionOutput(next_nodes=next_nodes, sends=sends).to_dict() def _get_triggered_nodes( @@ -1155,58 +1410,47 @@ def _get_triggered_nodes( return [] -def _replay_safe_id(instance_id: Any, index: int) -> str: - """The id of input message ``index`` of a workflow instance: same on every replay.""" - return str(uuid.uuid5(uuid.NAMESPACE_OID, f"{instance_id}:{index}")) +def _replay_safe_id(instance_id: Any, index: int, channel: str = "messages") -> str: + """The id of input message ``index`` of ``channel``: same on every replay.""" + key = ( + f"{instance_id}:{index}" + if channel == "messages" + else (f"{instance_id}:{channel}:{index}") + ) + return str(uuid.uuid5(uuid.NAMESPACE_OID, key)) -def _message_id(index: int) -> str: +def _message_id(channel: str, index: int) -> str: """A fresh id for the message at ``index`` of the input (outside a workflow).""" return str(uuid.uuid4()) def _serialize_input( input_data: Dict[str, Any], - message_id: Callable[[int], str] = _message_id, + message_id: Callable[[str, int], str] = _message_id, ) -> Dict[str, Any]: """Serialize input values for channel storage. - Messages given as dicts get an id, as the ``add_messages`` reducer gives - them when LangGraph writes the input. A node that returns the messages it - was handed (a subgraph does) is then understood to return the same - messages, not new ones: the stream does not send them again and the state - does not hold them twice. - - ``message_id`` makes the id of the message at a given index. Workflow code - is replayed from its first line for every decision, so it passes an id that - is the same on every replay; random ids are for callers outside a workflow. + A message written to an ``add_messages`` channel (a message, a string, a + pair, a dict, or a list of them) is stored as a message dict with an id, as + the reducer gives it when LangGraph writes the input. A node that returns + the messages it was handed (a subgraph does) is then understood to return + the same messages, not new ones: the stream does not send them again and the + state does not hold them twice. + + ``message_id`` makes the id of the message at an index of a channel. + Workflow code is replayed from its first line for every decision, so it + passes an id that is the same on every replay; random ids are for callers + outside a workflow. """ - values = {k: _serialize_value(v) for k, v in input_data.items()} - messages = values.get("messages") - if isinstance(messages, list): - messages = [_pair_as_message(m) for m in messages] - values["messages"] = [ - {**m, "id": message_id(i)} - if isinstance(m, dict) and m.get("id") is None - else m - for i, m in enumerate(messages) - ] - return values - - -def _pair_as_message(item: Any) -> Any: - """A ``(role, content)`` pair (a tuple, or the list it became) as a message dict. - - LangGraph's ``add_messages`` converts such a pair to a message; the stored - input is JSON, where a tuple is already a two-item list. - """ - if ( - isinstance(item, (list, tuple)) - and len(item) == 2 - and all(isinstance(part, str) for part in item) - ): - return {"role": item[0], "content": item[1]} - return item + return { + channel: ( + _serialize_messages(value, functools.partial(message_id, channel)) + if channel == "messages" or _is_messages_channel(channel) + else _serialize_value(value) + ) + for channel, value in input_data.items() + } def _extract_output( @@ -1221,11 +1465,14 @@ def _extract_output( Returns: Dictionary of channel name to value """ - output = {} - for channel in output_channels: - if channel in channel_state.values: - output[channel] = channel_state.values[channel] - return output + values = {**channel_state.values, **_unwritten_defaults(channel_state.values)} + return { + channel: values[channel] for channel in output_channels if channel in values + } + + +class ReducerError(Exception): + """A channel's reducer raised while a write was applied; the run fails.""" def _apply_write(channel_state: ChannelState, channel: str, value: Any) -> None: @@ -1237,6 +1484,11 @@ def _apply_write(channel_state: ChannelState, channel: str, value: Any) -> None: value: Value to write """ reducer = get_channel_reducer(channel) + if reducer and isinstance(value, dict) and set(value) == {OVERWRITE}: + # Overwrite replaces the channel's value without calling the reducer. + channel_state.values[channel] = value[OVERWRITE] + channel_state.versions[channel] = channel_state.versions.get(channel, 0) + 1 + return if reducer and channel not in channel_state.values: # The first write is reduced into the channel's default, so add_messages # gives its messages ids and objects, as it does natively. @@ -1244,10 +1496,14 @@ def _apply_write(channel_state: ChannelState, channel: str, value: Any) -> None: channel_state.values[channel] = copy.deepcopy(_channel_defaults[channel]) if reducer and channel in channel_state.values: # Apply reducer to combine values + current = channel_state.values[channel] + if _is_messages_channel(channel): + # add_messages turns dicts into messages with convert_to_messages, + # which files a dump's metadata under additional_kwargs; hand it + # the messages themselves. + current, value = _as_messages(current), _as_messages(value) try: - channel_state.values[channel] = reducer( - channel_state.values[channel], value - ) + channel_state.values[channel] = reducer(current, value) # Re-serialize the reducer output so channel state stays # JSON-compatible (reducers like add_messages may return # BaseMessage objects from dict inputs). @@ -1257,9 +1513,9 @@ def _apply_write(channel_state: ChannelState, channel: str, value: Any) -> None: _serialize_value(item) for item in reduced ] except Exception as e: - # If reducer fails, just overwrite - logger.warning(f"Reducer failed for channel '{channel}': {e}") - channel_state.values[channel] = value + # LangGraph fails the run on a reducer that raises; overwriting the + # channel would hide the error and differ between a run and a replay. + raise ReducerError(f"Reducer failed for channel '{channel}': {e}") from e else: # No reducer or first value, just set channel_state.values[channel] = value @@ -1268,6 +1524,15 @@ def _apply_write(channel_state: ChannelState, channel: str, value: Any) -> None: channel_state.versions[channel] = channel_state.versions.get(channel, 0) + 1 +def _unwritten_defaults(values: Dict[str, Any]) -> Dict[str, Any]: + """A copy of the default of every reducer channel that ``values`` lacks.""" + return { + channel: copy.deepcopy(default) + for channel, default in _channel_defaults.items() + if channel not in values + } + + def _reconstruct_state(channel_state: ChannelState) -> Dict[str, Any]: """Reconstruct the state dictionary from channel values. @@ -1295,24 +1560,51 @@ def _reconstruct_state(channel_state: ChannelState) -> Dict[str, Any]: else: state[channel] = value + # A reducer channel nobody has written yet holds its default, as it does in + # LangGraph: a node reads ``state["log"]`` as ``[]``, not as a missing key. + state.update(_unwritten_defaults(channel_state.values)) + # Reconstruct LangChain message objects from serialized dicts. # Nodes (e.g. Deep Agent middleware) expect BaseMessage instances, not - # plain dicts, so we convert the "messages" channel back. - # Convert when items are dicts (either {"type": "human", ...} or - # {"role": "user", ...} format). - if "messages" in state and isinstance(state["messages"], list): - msgs = state["messages"] - if msgs and isinstance(msgs[0], dict): - try: - from langchain_core.messages import convert_to_messages - - state["messages"] = convert_to_messages(msgs) - except (ImportError, Exception): - pass + # plain dicts, so every add_messages channel (whatever it is named) is + # converted back. Items may be {"type": "human", ...} or + # {"role": "user", ...} dicts. + for channel, value in state.items(): + if channel == "messages" or _is_messages_channel(channel): + state[channel] = _as_messages(value) return state +_MESSAGE_ADAPTER: TypeAdapter = TypeAdapter(AnyMessage) + + +def _as_message(item: Any) -> Any: + """A stored message dict as the message it was dumped from. + + A dump (``type`` and the message's own fields) is validated as the message + class, which keeps ``response_metadata``, ``usage_metadata`` and the like. + ``convert_to_messages`` would take those fields for ``additional_kwargs``. + Anything else (a ``role`` dict, a ``RemoveMessage``) goes through it. + """ + if isinstance(item, dict) and "type" in item and "role" not in item: + try: + return _MESSAGE_ADAPTER.validate_python(item) + except ValidationError: + pass + return convert_to_messages([item])[0] + + +def _as_messages(value: Any) -> Any: + """``value``'s message dicts as message objects (left as is if it is not that).""" + if isinstance(value, list) and value and isinstance(value[0], dict): + try: + return [_as_message(item) for item in value] + except Exception: + return value + return value + + def _result_to_raw_writes(result: Any) -> List[Tuple[str, Any]]: """Convert a node result to ``(channel, value)`` pairs, values untouched. @@ -1376,57 +1668,59 @@ def _state_object_writes(result: Any) -> Optional[List[Tuple[str, Any]]]: return None -def _warn_send_payload( - source: str, send: Any, registry: Optional[StreamSinkRegistry] = None -) -> None: - """Say, once per edge, that a ``Send`` runs its node on the channel state. +def _encode_arg(arg: Any) -> Dict[str, Any]: + """A ``Send`` argument as JSON that gives the same object back. - LangGraph hands the node the ``Send`` argument as its input. Here the node - reads the channel state, so a node that depends on the argument gets the - wrong data (the prebuilt agent's tools node, which passes the state, is fine). + The node takes the argument as its input, as LangGraph hands it over, so + messages inside it must stay messages: the checkpoint serializer keeps them. """ - if getattr(send, "arg", None) is None: - return - # once per edge and runner: the memory is the runner's own registry - if not (registry or default_registry).first_report(f"send:{source}->{send.node}"): - return - logger.warning( - "Send(%r, ...) from %r: the payload is not delivered, node %r runs on the " - "channel state. A node that reads the Send argument gets different data " - "than under LangGraph.", - send.node, - source, - send.node, - ) + try: + from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer + kind, data = JsonPlusSerializer().dumps_typed(arg) + return {"typed": [kind, base64.b64encode(data).decode("ascii")]} + except ImportError: # pragma: no cover - the extra is always installed + return {"json": _serialize_value(arg)} -def _result_to_gotos( - result: Any, source: str, registry: Optional[StreamSinkRegistry] = None -) -> List[str]: - """The nodes a ``Command(goto=...)`` result asks to run next. - ``END`` is skipped (it ends that branch, which running nothing does). A - ``Send`` in ``goto`` runs its node on the channel state; see - :func:`_warn_send_payload`. +def _decode_arg(encoded: Dict[str, Any]) -> Any: + if "typed" in encoded: + from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer + + kind, data = encoded["typed"] + return JsonPlusSerializer().loads_typed((kind, base64.b64decode(data))) + return encoded.get("json") + + +def _send_task(send: Any) -> Dict[str, Any]: + """A ``Send`` as JSON: the node to run and the argument it takes as input.""" + return {"node": send.node, "arg": _encode_arg(send.arg)} + + +def _result_to_gotos(result: Any) -> Tuple[List[str], List[Dict[str, Any]]]: + """The nodes and ``Send`` tasks a ``Command(goto=...)`` result asks to run next. + + ``END`` is skipped (it ends that branch, which running nothing does). Every + ``Send`` is a task of its own, with its argument as the node's input. """ if isinstance(result, Command): commands: List[Any] = [result] elif isinstance(result, list) and result and isinstance(result[0], Command): commands = result else: - return [] + return [], [] targets: List[str] = [] + sends: List[Dict[str, Any]] = [] for cmd in commands: goto = getattr(cmd, "goto", None) or () for item in [goto] if isinstance(goto, (str, Send)) else goto: if isinstance(item, Send): - _warn_send_payload(source, item, registry) - name = item.node - else: - name = str(item) + sends.append(_send_task(item)) + continue + name = str(item) if name != END and name not in targets: targets.append(name) - return targets + return targets, sends def _command_to_raw_writes(cmd: Any) -> List[Tuple[str, Any]]: @@ -1457,9 +1751,70 @@ def _command_to_raw_writes(cmd: Any) -> List[Tuple[str, Any]]: return [] +def _is_messages_channel(channel: str) -> bool: + """Whether ``channel`` is reduced by ``add_messages`` (whatever it is named).""" + return get_channel_reducer(channel) is add_messages + + +def _new_message_id(index: int) -> str: + """A fresh id for a message a node wrote (the activity's result is recorded).""" + return str(uuid.uuid4()) + + +def _serialize_messages( + value: Any, message_id: Callable[[int], str] = _new_message_id +) -> List[Any]: + """What ``add_messages`` takes as one write, as JSON message dicts with ids. + + Mirrors the reducer: a single message is a list of one, and each item (a + string, a ``(role, content)`` pair, a dict or a message) becomes a message. + A message without an id gets ``message_id(index)`` here, because + ``add_messages`` would otherwise make a random one inside the orchestrator, + different on every replay. + """ + items = value if isinstance(value, list) else [value] + messages = [message_chunk_to_message(m) for m in convert_to_messages(items)] + return [ + _serialize_value( + m if m.id is not None else m.model_copy(update={"id": message_id(i)}) + ) + for i, m in enumerate(messages) + ] + + +def _overwrite_of(value: Any) -> Tuple[bool, Any]: + """Whether ``value`` is an ``Overwrite`` (in any form LangGraph takes), and its value.""" + if isinstance(value, Overwrite): + return True, value.value + if isinstance(value, dict): + if len(value) == 1 and OVERWRITE in value: + return True, value[OVERWRITE] + if value.get("type") == OVERWRITE and "value" in value: + return True, value["value"] + return False, None + + +def _serialize_channel_value( + channel: str, + value: Any, + message_id: Callable[[int], str] = _new_message_id, +) -> Any: + """``value`` as the JSON a write to (or an input of) ``channel`` is stored as. + + An ``Overwrite`` is kept as ``{"__overwrite__": value}`` so that applying the + write can bypass the reducer (``_apply_write``). + """ + is_overwrite, inner = _overwrite_of(value) + if is_overwrite: + return {OVERWRITE: _serialize_channel_value(channel, inner, message_id)} + if _is_messages_channel(channel): + return _serialize_messages(value, message_id) + return _serialize_value(value) + + def _serialize_writes(raw_writes: List[Tuple[str, Any]]) -> List[NodeWrite]: return [ - NodeWrite(channel=channel, value=_serialize_value(value)) + NodeWrite(channel=channel, value=_serialize_channel_value(channel, value)) for channel, value in raw_writes ] diff --git a/tests/agent/langgraph/test_workflow.py b/tests/agent/langgraph/test_workflow.py index 17ce0ee9..d7fb0c9e 100644 --- a/tests/agent/langgraph/test_workflow.py +++ b/tests/agent/langgraph/test_workflow.py @@ -496,7 +496,9 @@ def test_send_bypasses_path_map(self): ) self.assertIsNone(output.error) - self.assertEqual(output.next_nodes, ["worker"]) + # a Send is a task of its own, not a node name + self.assertEqual(output.next_nodes, []) + self.assertEqual([s["node"] for s in output.sends], ["worker"]) def test_async_only_runnable_condition(self): output = self._evaluate(_AsyncOnlyRunnable("next_node")) From c75d1addaf2b1d2986aa54ddee6d79899ce7f9c4 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Wed, 25 Nov 2026 23:57:28 +0100 Subject: [PATCH 10/73] feat(langgraph): match LangGraph's step order, limits, managed values and value types The nodes of a step ran in the order their edges were found, which changes with the hash seed. They now run in LangGraph's task order, pull tasks by name and then Send tasks numbered over the whole step, a task's goto Sends before its edge Sends, and a conditional edge is evaluated once per task on that task's own writes. A node added with defer=True runs once, when nothing else is pending. The new order sits behind a workflow patch, so an instance already in flight replays with the order it started under. recursion_limit is strict: a run takes that many steps, then fails, and a limit only the graph binds can be lowered by the runner's max_steps. A run the orchestrator starts gets the graph's own config. Nodes and routers get the RemainingSteps and IsLastStep managed values. Values keep the types they were written in between nodes, through LangGraph's serializer, while the run's output stays JSON. A subgraph's Command(graph=PARENT) becomes its node's result, a ChatMessage reads back as a ChatMessage, and a graph whose whole state is one channel works. A composite node with an async step runs through ainvoke, and a node that calls sys.exit no longer kills the shared loop. The setup shared by invoke and run_async, the per-edge evaluation, the node config builders and the poll retry move into helpers, the LangSmith parent trace and the step bound get their own modules, and the comments and docstrings that restated the code are trimmed. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 73 +- diagrid/agent/core/workflow/stream.py | 39 +- diagrid/agent/langgraph/README.md | 32 +- diagrid/agent/langgraph/langsmith_trace.py | 67 ++ diagrid/agent/langgraph/limits.py | 58 ++ diagrid/agent/langgraph/models.py | 47 +- diagrid/agent/langgraph/runner.py | 491 +++++----- diagrid/agent/langgraph/stream_events.py | 34 +- diagrid/agent/langgraph/streaming.py | 26 +- diagrid/agent/langgraph/values.py | 80 ++ diagrid/agent/langgraph/workflow.py | 998 +++++++++++++-------- 11 files changed, 1213 insertions(+), 732 deletions(-) create mode 100644 diagrid/agent/langgraph/langsmith_trace.py create mode 100644 diagrid/agent/langgraph/limits.py create mode 100644 diagrid/agent/langgraph/values.py diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 3b939d97..a9e85015 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -215,6 +215,32 @@ def _framework_version(framework: str) -> Optional[str]: return None +async def _next_state( + client: Any, workflow_id: str, poll_interval: float, retry_failed_polls: bool +) -> Any: + """The workflow's state after ``poll_interval``, retrying a failed poll. + + The poll failed, not the workflow (a sidecar restart, a dropped call): + retry, and give up only on a poll that keeps failing, so the caller learns + the run's fate is unknown. + """ + failed_polls = 0 + while True: + await asyncio.sleep(poll_interval) + try: + # A blocking gRPC call: off the loop, or every other run's + # tokens (and all HTTP handling) wait for the sidecar. + return await asyncio.to_thread( + client.get_workflow_state, instance_id=workflow_id + ) + except Exception as e: + failed_polls += 1 + delay = _poll_retry_delay(e, failed_polls, retry_failed_polls, workflow_id) + if delay is None: + raise + await asyncio.sleep(delay) + + class BaseWorkflowRunner(SignalMixin, AgentRegistryMixin, ABC): """Base class for all framework workflow runners. @@ -410,49 +436,18 @@ async def _poll_workflow( ) -> AsyncIterator[dict[str, Any]]: """Poll a running workflow and yield status/completion events. - Args: - workflow_id: The workflow instance ID. - session_id: Session identifier for event metadata. - poll_interval: Seconds between polls. - parse_output: Optional callable to parse serialized output - into a completion event dict. If None, raw output is - returned. - retry_failed_polls: Ride out a failed poll when it looks transient - (see ``POLL_MAX_ERRORS``) instead of raising at once. Off by - default: a runner opts in when it can tell its caller that the - run's fate is unknown. - - Yields: - Event dictionaries with workflow progress updates. + ``parse_output`` turns the serialized output into a completion event + dict (the raw output is returned without one). ``retry_failed_polls`` + rides out a failed poll that looks transient (see ``POLL_MAX_ERRORS``) + instead of raising at once; a runner opts in when it can tell its + caller that the run's fate is unknown. """ assert self._workflow_client is not None - previous_status = None - failed_polls = 0 - while True: - await asyncio.sleep(poll_interval) - - try: - # A blocking gRPC call: off the loop, or every other run's - # tokens (and all HTTP handling) wait for the sidecar. - state = await asyncio.to_thread( - self._workflow_client.get_workflow_state, instance_id=workflow_id - ) - except Exception as e: - # The poll failed, not the workflow (a sidecar restart, a - # dropped call). Retry; only a poll that keeps failing is given - # up on, and the caller learns the run's fate is unknown. - failed_polls += 1 - delay = _poll_retry_delay( - e, failed_polls, retry_failed_polls, workflow_id - ) - if delay is None: - raise - await asyncio.sleep(delay) - continue - failed_polls = 0 - + state = await _next_state( + self._workflow_client, workflow_id, poll_interval, retry_failed_polls + ) if state is None: yield { "type": "workflow_error", diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index 0088ec2a..28642157 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -27,6 +27,7 @@ # (the workflow_started event is sent once). MAX_BUFFERED_EVENTS = 10_000 +UPDATES = "updates" NODE_RESET = "node_reset" STREAM_UNAVAILABLE = "stream_unavailable" STREAM_DROPPED = "stream_dropped" @@ -34,6 +35,9 @@ WORKFLOW_STARTED = "workflow_started" # Events about the stream itself, delivered whatever stream modes were asked for. CONTROL_MODES = (WORKFLOW_STARTED, NODE_RESET, STREAM_UNAVAILABLE) +# What a full buffer never drops: the control events and node updates, which are +# a stream mode of their own but cannot be re-sent either. +_KEPT_WHEN_FULL = (*CONTROL_MODES, UPDATES) #: Seconds an idle SSE stream waits before it sends a keepalive comment, so a #: proxy or load balancer does not cut it during a long tool call or LLM gap. @@ -43,7 +47,6 @@ # Runs remembered by StreamSinkRegistry.first_report; older ones are forgotten. _MAX_REPORTED_RUNS = 1024 -UPDATES = "updates" def display_step(step: int) -> int: @@ -73,6 +76,9 @@ class StreamEvent: display_node: Optional[str] = None #: The task's ``langgraph_path`` when it is not the node's own (a ``Send``). path: Optional[Tuple[Any, ...]] = None + #: The conditional edge whose function sent the chunk, so a retry of that + #: function is not taken for a retry of the node itself. + branch: Optional[str] = None def reset_data(self) -> Dict[str, Any]: """The ``node_reset`` payload for a retry of this event's task. @@ -86,6 +92,8 @@ def reset_data(self) -> Dict[str, Any]: } if self.path: data["path"] = list(self.path) + if self.branch: + data["branch"] = self.branch return data @@ -181,7 +189,9 @@ def _put() -> None: self.workflow_id, self._dropped, ) - elif self._queue.qsize() >= MAX_BUFFERED_EVENTS and not _is_control(item): + elif self._queue.qsize() >= MAX_BUFFERED_EVENTS and not _is_kept_when_full( + item + ): if not self._dropped: logger.warning( "Stream buffer for %s is full; dropping chunks", @@ -197,13 +207,17 @@ def _put() -> None: self._closed = True -def _is_control(item: Any) -> bool: +def _is_kept_when_full(item: Any) -> bool: """Chunks that must not be dropped: they cannot be re-sent.""" - return isinstance(item, StreamEvent) and item.mode in ( - UPDATES, - NODE_RESET, - WORKFLOW_STARTED, - ) + return isinstance(item, StreamEvent) and item.mode in _KEPT_WHEN_FULL + + +def _remember(runs: "OrderedDict[str, None]", workflow_id: str) -> None: + """Record ``workflow_id`` as the latest run, forgetting the oldest past the bound.""" + runs[workflow_id] = None + runs.move_to_end(workflow_id) + while len(runs) > _MAX_REPORTED_RUNS: + runs.popitem(last=False) class StreamSinkRegistry: @@ -246,10 +260,7 @@ def close(self, workflow_id: str, sink: Optional[InProcessSink] = None) -> None: if current is None or (sink is not None and current is not sink): return del self._sinks[workflow_id] - self._closed[workflow_id] = None - self._closed.move_to_end(workflow_id) - while len(self._closed) > _MAX_REPORTED_RUNS: - self._closed.popitem(last=False) + _remember(self._closed, workflow_id) current.close() def was_closed(self, workflow_id: str) -> bool: @@ -271,9 +282,7 @@ def first_report(self, workflow_id: str) -> bool: with self._lock: if workflow_id in self._reported: return False - self._reported[workflow_id] = None - while len(self._reported) > _MAX_REPORTED_RUNS: - self._reported.popitem(last=False) + _remember(self._reported, workflow_id) return True def get(self, workflow_id: Optional[str]) -> Optional[InProcessSink]: diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index a615c471..8d7806eb 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -120,7 +120,7 @@ objects (`kind`, `data`): | `kind` | `data` | Meaning | |---|---|---| | `workflow_started` | `{"workflow_id", "thread_id"}` | Always the first event: the ids to use with `terminate_workflow` or `get_workflow_status`. Delivered only to `on_control`, never yielded. | -| `node_reset` | `{"node", "step"}`, plus `"path"` for a `Send` task | A node was retried; drop its partial output. `node` and `step` are the `langgraph_node` and `langgraph_step` of that node's `messages` metadata (`step` is numbered from 1). A task started by a `Send` also carries `path`, the `langgraph_path` of its chunks (`["__pregel_push", index, false]`), which tells apart the tasks of one node in a step. | +| `node_reset` | `{"node", "step"}`, plus `"path"` for a `Send` task | A node was retried; drop its partial output. `node` and `step` are the `langgraph_node` and `langgraph_step` of that node's `messages` metadata (`step` is numbered from 1). A task started by a `Send` also carries `path`, the `langgraph_path` of its chunks (`["__pregel_push", index, false]`), which tells apart the tasks of one node in a step. A retry of a conditional edge's function (the function runs in its own activity, after the node's) also carries `branch`, the edge's function name: only what that function sent since the node's `updates` chunk is stale, not the node's own output. | | `stream_unavailable` | `{"workflow_id", "reason", "missing_steps", "missing_nodes"}` | The run finished but a node's chunks never arrived (see the limit below). `missing_nodes` is a list of `{"step", "node"}`, one per node of a step that streamed nothing, even when other nodes of that step did. Steps are numbered from 1, like `langgraph_step`. A `Send` task is named `node#k` there (`k` is its position among the step's `Send` tasks). | | `stream_dropped` | `{"dropped": n}` | The consumer fell behind and `n` token or custom chunks were dropped. `updates` are never dropped. | @@ -202,15 +202,12 @@ they are left alone. activity logs a warning once per run and the stream sends `stream_unavailable` before it ends. The run and its result are not affected. Delivery across replicas is not implemented yet. -- **A disconnect does not cancel the run.** When the client goes away the stream - is closed, but the Dapr workflow keeps running to completion. Terminate it with - `terminate_workflow` if you need it stopped. The first event of every stream is - `workflow_started` with the `workflow_id` and `thread_id`, so a client that - loses its connection can still `GET /agent/run/{workflow_id}` or ask for the - run to be terminated. With `astream`, `on_control` receives the same event. - When `publish_topic` is set, the server keeps following the run after the - client left and publishes its result when it ends, as it does for a client - that stays. +- **A disconnect does not cancel the run.** The stream closes but the Dapr + workflow runs to completion; `terminate_workflow` stops it, and the ids in + `workflow_started` let a client that lost its connection `GET + /agent/run/{workflow_id}` or terminate the run. When `publish_topic` is set, + the server keeps following the run after the client left and publishes its + result when it ends. - **`Send` tasks.** Every `Send("node", arg)` (from a conditional edge or `goto=Send(...)`) runs the node once, as its own activity, with `arg` as its @@ -220,6 +217,12 @@ they are left alone. the step's `Send` tasks. The `arg` travels through the workflow as the checkpoint serializer's bytes, so it must be something that serializer handles. +- **State values keep their types between nodes.** A value of a state channel + that is not plain JSON (a message, a `datetime`, a `set`, a pydantic object) is + stored with the checkpoint serializer, so the next node and router read what + was written, as in LangGraph. It must be something that serializer handles. + A run's output (the `invoke` result and the final event) is JSON: such a value + appears there as its dump (a `set` as a sorted list, a `datetime` as a string). - **Routers stream after their node's update.** The LLM tokens and `get_stream_writer()` events of a conditional edge's function are sent as its source node's (`langgraph_node` and step), as LangGraph does, but the router @@ -227,10 +230,13 @@ they are left alone. where LangGraph sends them before it. - **The `config` of `astream`, `invoke` and `run_async` travels as JSON.** `tags`, `metadata`, `configurable` and `recursion_limit` work; `recursion_limit` - bounds the run's steps as LangGraph counts them (N sequential nodes need a limit - of N + 1) and the runner's `max_steps` applies when it is absent. A + bounds the run's steps as LangGraph counts them: that many node steps run and + then the run fails with `GraphRecursionError` (N sequential nodes need a limit + of N + 1 to complete). The runner's `max_steps` applies when it is absent. A `recursion_limit` and `configurable` bound with `compiled.with_config(...)` - apply unless the call sets its own. `callbacks` and any value that is not JSON + apply unless the call sets its own; a `max_steps` you pass to the runner + still caps a limit that is only bound to the graph (`create_agent` binds + 9999), so it stays a guard against a runaway loop. `callbacks` and any value that is not JSON raise `ValueError` before a run starts. ## Architecture diff --git a/diagrid/agent/langgraph/langsmith_trace.py b/diagrid/agent/langgraph/langsmith_trace.py new file mode 100644 index 00000000..29b7d697 --- /dev/null +++ b/diagrid/agent/langgraph/langsmith_trace.py @@ -0,0 +1,67 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The LangSmith parent trace a run's node activities nest under.""" + +import logging +import os +import uuid +from dataclasses import dataclass +from datetime import datetime, timezone +from typing import Any, Dict, Optional + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class ParentTrace: + """A ``LangGraph`` run opened in LangSmith, for the activities to nest under.""" + + run_id: str + dotted_order: str + client: Any + + @property + def config(self) -> Dict[str, str]: + """The keys that carry the trace to the workflow, in its config.""" + return { + "langsmith_dotted_order": self.dotted_order, + "langsmith_run_id": self.run_id, + } + + def end(self) -> None: + """Close the run. Harmless after the workflow closed it: it is idempotent.""" + try: + self.client.update_run(self.run_id, end_time=datetime.now(timezone.utc)) + self.client.flush() + except Exception as e: + logger.debug(f"LangSmith parent trace close failed: {e}") + + +def start_parent_trace(inputs: Any, thread_id: str) -> Optional[ParentTrace]: + """Open the parent trace when ``LANGSMITH_TRACING`` is on, else ``None``. + + A failure to open it is logged and the run goes untraced. + """ + if os.environ.get("LANGSMITH_TRACING", "").lower() not in ("true", "1"): + return None + try: + from langsmith import Client + + client = Client() + run_id = str(uuid.uuid4()) + now = datetime.now(timezone.utc) + dotted_order = f"{now.strftime('%Y%m%dT%H%M%S')}{now.microsecond:06d}Z{run_id}" + client.create_run( + id=run_id, + name="LangGraph", + run_type="chain", + inputs=inputs, + dotted_order=dotted_order, + trace_id=run_id, + extra={"metadata": {"thread_id": thread_id}}, + ) + return ParentTrace(run_id, dotted_order, client) + except Exception as e: + logger.debug(f"LangSmith parent trace creation failed: {e}") + return None diff --git a/diagrid/agent/langgraph/limits.py b/diagrid/agent/langgraph/limits.py new file mode 100644 index 00000000..fdee01c8 --- /dev/null +++ b/diagrid/agent/langgraph/limits.py @@ -0,0 +1,58 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""How many steps a run may take. + +Two things bound a run. LangGraph's ``recursion_limit`` (from the caller's +config, or bound to the graph with ``with_config``) counts steps as LangGraph +does: that many node steps run, and the run fails once it has taken them, even +if nothing more is pending. The runner's ``max_steps`` is its own guard: a graph +that needs exactly that many steps completes. +""" + +from dataclasses import dataclass +from typing import Any, Dict, Optional + +from langchain_core.runnables.config import DEFAULT_RECURSION_LIMIT + + +@dataclass(frozen=True) +class StepBound: + """The step limit of one run. + + ``strict`` is set when ``max_steps`` is a ``recursion_limit``: the run fails + after that many steps whether or not more is pending. Otherwise a run that + needs exactly ``max_steps`` steps completes. + """ + + max_steps: int + strict: bool = False + + +def step_bound( + caller_config: Optional[Dict[str, Any]], + graph_config: Optional[Dict[str, Any]], + max_steps: int, + *, + max_steps_given: bool, +) -> StepBound: + """The bound of a run started with ``caller_config`` on a graph bound to ``graph_config``. + + A ``recursion_limit`` the caller passes is the bound. One that only the + graph supplies (``with_config``; ``create_agent`` and Deep Agents bind + thousands) applies too, except that a ``max_steps`` the runner was given + explicitly is a guard it can lower. With no limit at all, ``max_steps`` + bounds the run. + """ + caller_limit = (caller_config or {}).get("recursion_limit") + graph_limit = (graph_config or {}).get("recursion_limit") + from_graph_only = graph_limit is not None and caller_limit in ( + None, + DEFAULT_RECURSION_LIMIT, + ) + limit = graph_limit if from_graph_only else caller_limit + if not isinstance(limit, int): + return StepBound(max_steps) + if from_graph_only and max_steps_given and max_steps < limit: + return StepBound(max_steps) + return StepBound(limit, strict=True) diff --git a/diagrid/agent/langgraph/models.py b/diagrid/agent/langgraph/models.py index 79551c3c..67301c35 100644 --- a/diagrid/agent/langgraph/models.py +++ b/diagrid/agent/langgraph/models.py @@ -124,6 +124,8 @@ class GraphConfig: evaluated before it. ``None`` for a config written before this field existed: then ``entry_point`` alone starts the run. waiting_edges: Joins; a node waits until all their sources have run. + deferred: Nodes added with ``defer=True``: one that is triggered waits + until no other node or ``Send`` task is pending, then runs. """ name: str @@ -135,6 +137,7 @@ class GraphConfig: output_channels: List[str] = field(default_factory=list) entry_points: Optional[List[str]] = None waiting_edges: List[WaitingEdgeConfig] = field(default_factory=list) + deferred: List[str] = field(default_factory=list) def to_dict(self) -> Dict[str, Any]: return { @@ -147,6 +150,7 @@ def to_dict(self) -> Dict[str, Any]: "output_channels": self.output_channels, "entry_points": self.entry_points, "waiting_edges": [w.to_dict() for w in self.waiting_edges], + "deferred": self.deferred, } @classmethod @@ -163,6 +167,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "GraphConfig": waiting_edges=[ WaitingEdgeConfig.from_dict(w) for w in data.get("waiting_edges") or [] ], + deferred=list(data.get("deferred") or []), ) @@ -233,11 +238,15 @@ class ExecuteNodeInput: thread_id: Thread identifier for the execution. Propagated into the LangGraph ``Runtime`` so sandbox/state backends can resolve which workflow owns a given tool call. - send: Set when the node runs for a ``Send``: ``{"arg": ..., "index": i, - "slot": k}``, the argument the node takes as its input, the - ``Send``'s position in the list its source returned, and its - position among the step's ``Send`` tasks. ``None`` for a node - that runs on the channel state. + send: Set when the node runs for a ``Send``: ``{"arg": ..., "slot": k}``, + the argument the node takes as its input and the ``Send``'s + position among all of the step's ``Send`` tasks (LangGraph numbers + its push tasks over the whole step, and that number is in each + task's ``langgraph_path``). ``None`` for a node that runs on the + channel state. + recursion_limit: The run's step limit as a LangGraph ``recursion_limit`` + (what ``RemainingSteps`` and ``IsLastStep`` count against), or + ``None`` for a workflow that did not send it. """ node_name: str @@ -246,6 +255,7 @@ class ExecuteNodeInput: thread_id: Optional[str] = None step: Optional[int] = None send: Optional[Dict[str, Any]] = None + recursion_limit: Optional[int] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -258,6 +268,8 @@ def to_dict(self) -> Dict[str, Any]: data["step"] = self.step if self.send is not None: data["send"] = self.send + if self.recursion_limit is not None: + data["recursion_limit"] = self.recursion_limit return data @classmethod @@ -269,6 +281,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeInput": thread_id=data.get("thread_id"), step=data.get("step"), send=data.get("send"), + recursion_limit=data.get("recursion_limit"), ) @@ -332,6 +345,11 @@ class EvaluateConditionInput: so a streamed run can give the condition's chunks that node's step. ``None`` (an older workflow): the condition's chunks are not streamed. + send_slot: Set when the source task ran for a ``Send``: its position + among the step's ``Send`` tasks. The condition then streams as that + task, apart from the node's other tasks of the step. + recursion_limit: The run's step limit as a LangGraph ``recursion_limit`` + (see ``ExecuteNodeInput``). """ source_node: str @@ -341,6 +359,8 @@ class EvaluateConditionInput: thread_id: Optional[str] = None path_map: Optional[Dict[str, str]] = None step: Optional[int] = None + send_slot: Optional[int] = None + recursion_limit: Optional[int] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -353,6 +373,10 @@ def to_dict(self) -> Dict[str, Any]: } if self.step is not None: data["step"] = self.step + if self.send_slot is not None: + data["send_slot"] = self.send_slot + if self.recursion_limit is not None: + data["recursion_limit"] = self.recursion_limit return data @classmethod @@ -365,6 +389,8 @@ def from_dict(cls, data: Dict[str, Any]) -> "EvaluateConditionInput": thread_id=data.get("thread_id"), path_map=data.get("path_map"), step=data.get("step"), + send_slot=data.get("send_slot"), + recursion_limit=data.get("recursion_limit"), ) @@ -410,6 +436,10 @@ class GraphWorkflowInput: channel_state: Initial/current channel state step: Current step number max_steps: Maximum steps before stopping + strict_limit: ``max_steps`` is a LangGraph ``recursion_limit``: a run + that has taken that many steps fails, even if nothing is pending + after them. Without it, a run that needs exactly ``max_steps`` + steps completes. pending_nodes: Nodes pending execution config: Optional LangGraph config dict thread_id: Thread identifier for the execution @@ -419,12 +449,13 @@ class GraphWorkflowInput: channel_state: ChannelState step: int = 0 max_steps: int = 100 + strict_limit: bool = False pending_nodes: List[str] = field(default_factory=list) config: Optional[Dict[str, Any]] = None thread_id: Optional[str] = None def to_dict(self) -> Dict[str, Any]: - return { + data: Dict[str, Any] = { "graph_config": self.graph_config.to_dict(), "channel_state": self.channel_state.to_dict(), "step": self.step, @@ -433,6 +464,9 @@ def to_dict(self) -> Dict[str, Any]: "config": self.config, "thread_id": self.thread_id, } + if self.strict_limit: + data["strict_limit"] = True + return data @classmethod def from_dict(cls, data: Dict[str, Any]) -> "GraphWorkflowInput": @@ -441,6 +475,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "GraphWorkflowInput": channel_state=ChannelState.from_dict(data["channel_state"]), step=data.get("step", 0), max_steps=data.get("max_steps", 100), + strict_limit=bool(data.get("strict_limit", False)), pending_nodes=data.get("pending_nodes", []), config=data.get("config"), thread_id=data.get("thread_id"), diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index ff732e41..822fb791 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -9,6 +9,7 @@ import time import uuid from contextlib import aclosing +from dataclasses import dataclass from typing import ( Any, AsyncGenerator, @@ -32,6 +33,7 @@ CONTROL_MODES, KEEPALIVE_EVENT, WORKFLOW_STARTED, + UPDATES, InProcessSink, StreamClosed, StreamEvent, @@ -49,7 +51,6 @@ from .streaming import ( EXECUTED_KEY, STREAM_RUN_KEY, - UPDATES, StaticConfig, FAILED_STATUSES, StreamControl, @@ -63,13 +64,17 @@ closing_events, count_unencodable, encode_chunk, - failure_event, + stream_failure_event, next_item, route_astream_item, started_event, without_executed, ) +from .langsmith_trace import ParentTrace, start_parent_trace +from .limits import StepBound, step_bound from .workflow import ( + IS_LAST_STEP, + REMAINING_STEPS, agent_workflow, make_condition_activity, GENERIC_NODE_ACTIVITY, @@ -82,12 +87,15 @@ register_node_triggers, register_condition, register_channel_reducer, + _NO_DEFAULT, + register_managed_channel, register_state_channels, set_default_graph_config, set_serializer, clear_registries, START, END, + ROOT, ) if TYPE_CHECKING: @@ -97,16 +105,40 @@ _TRANSPORT_KEYS = ("stream", "stream_mode") +#: The runner's step bound when it is given none (see ``max_steps``). +DEFAULT_MAX_STEPS = 100 + # What a reducer channel holds before its first write; LangGraph's own marker # when the channel type has no empty value. -_NO_DEFAULT: Any = object() try: from langgraph.channels.binop import MISSING as _LANGGRAPH_MISSING except ImportError: # pragma: no cover - a LangGraph without the marker _LANGGRAPH_MISSING = _NO_DEFAULT +def _managed_kinds(managed: Dict[str, Any]) -> Dict[str, str]: + """The state keys that are LangGraph's ``RemainingSteps`` or ``IsLastStep``. + + Any other managed value (one a library defines) is not supplied. + """ + try: + from langgraph.managed.is_last_step import ( + IsLastStepManager, + RemainingStepsManager, + ) + except ImportError: # pragma: no cover - a LangGraph without them + return {} + kinds: Dict[str, str] = {} + for name, spec in managed.items(): + cls = getattr(spec, "cls", spec) + if isinstance(cls, type) and issubclass(cls, RemainingStepsManager): + kinds[name] = REMAINING_STEPS + elif isinstance(cls, type) and issubclass(cls, IsLastStepManager): + kinds[name] = IS_LAST_STEP + return kinds + + def _check_run_config(config: Optional[Dict[str, Any]]) -> None: """Refuse a LangGraph config the workflow cannot carry, before a run starts. @@ -178,38 +210,47 @@ def _merge_graph_config( return merged -def _max_steps_for(config: Optional[Dict[str, Any]], default: int) -> int: - """The workflow's step bound: ``config['recursion_limit']`` as LangGraph counts it. - - LangGraph allows ``recursion_limit - 1`` node steps (its input is the - first), so a graph of N sequential nodes needs a limit of N + 1. - """ - limit = (config or {}).get("recursion_limit") - return limit - 1 if isinstance(limit, int) else default - - def _run_identity( config: Optional[Dict[str, Any]], + merged: Dict[str, Any], thread_id: Optional[str], workflow_id: Optional[str], ) -> Tuple[str, str, Dict[str, Any]]: - """``(thread_id, workflow_id, config)`` for a streamed run. + """``(thread_id, workflow_id, config)`` for a run, whichever way it is started. - The thread id is the one given, else ``config["configurable"]["thread_id"]``, - else new. The config handed to the run carries that one id, so the id the - run reports is the one its nodes see. + The thread id is the one given, else ``configurable["thread_id"]`` of + ``merged`` (the caller's config over the graph's own, already checked), else + new. The config handed to the run is the caller's ``config``, which the run + merges with the graph's own again, carrying that one id so the id the run + reports is the one its nodes see. """ - _check_run_config(config) - configurable = (config or {}).get("configurable") or {} - thread = str(thread_id or configurable.get("thread_id") or uuid.uuid4()) + thread = str( + thread_id or (merged.get("configurable") or {}).get("thread_id") or uuid.uuid4() + ) run_config = { **(config or {}), - "configurable": {**configurable, "thread_id": thread}, - STREAM_RUN_KEY: True, + "configurable": { + **((config or {}).get("configurable") or {}), + "thread_id": thread, + }, } return thread, workflow_id or f"graph-{thread}-{uuid.uuid4().hex[:8]}", run_config +@dataclass(frozen=True) +class _RunSetup: + """What a run needs once its identity, config and input are settled.""" + + workflow_id: str + thread_id: str + #: The config the workflow runs with, ``langsmith_*`` keys included. + config: Dict[str, Any] + #: The LangSmith parent trace to close if the run is abandoned. + trace: Optional[ParentTrace] + #: The workflow's input, as scheduled. + workflow_input: Dict[str, Any] + + class DaprWorkflowGraphRunner(BaseWorkflowRunner): """Runner that executes LangGraph graphs as Dapr Workflows. @@ -270,7 +311,7 @@ def __init__( name: str, host: Optional[str] = None, port: Optional[str] = None, - max_steps: int = 100, + max_steps: Optional[int] = None, role: Optional[str] = None, goal: Optional[str] = None, instructions: Optional[str] = None, @@ -284,7 +325,9 @@ def __init__( name: Required name for the graph host: Dapr sidecar host (default: localhost) port: Dapr sidecar port (default: 50001) - max_steps: Maximum number of steps before stopping (default: 100) + max_steps: Maximum number of steps before stopping (default: 100). + A ``recursion_limit`` bound to the graph (``with_config``) takes + over when this is not given; when it is, it caps that limit. role: Optional role description for registry (e.g. "Schedule Planner") goal: Optional goal description for registry instructions: Optional system prompt for registry, also used as the @@ -296,7 +339,8 @@ def __init__( new registry owned by this runner. """ self._graph = graph - self._max_steps = max_steps + self._max_steps = DEFAULT_MAX_STEPS if max_steps is None else max_steps + self._max_steps_given = max_steps is not None self._stream_registry = ( stream_registry if stream_registry is not None else StreamSinkRegistry() ) @@ -309,10 +353,9 @@ def __init__( framework=self._REGISTRY_FRAMEWORK, host=host, port=port, - max_iterations=max_steps, + max_iterations=self._max_steps, ) - # Attach metadata hints for the registry mapper if name: self._graph._diagrid_name = name # type: ignore[attr-defined] if role: @@ -323,9 +366,8 @@ def __init__( self._graph._diagrid_instructions = instructions # type: ignore[attr-defined] # Surface the runner's step budget so the registry reflects the actual # max_iterations instead of a hardcoded default (read by DeepAgentsMapper). - self._graph._diagrid_max_steps = max_steps # type: ignore[attr-defined] + self._graph._diagrid_max_steps = self._max_steps # type: ignore[attr-defined] - # Register metadata self._register_agent_metadata( agent=self._graph, framework=self._REGISTRY_FRAMEWORK, @@ -333,7 +375,6 @@ def __init__( name=self._name, ) - # Register workflow and activities self._register_workflow_components() # Register graph components (nodes, channels, serializer) first. @@ -498,6 +539,11 @@ def _extract_graph_config(self) -> GraphConfig: output_channels=output_channels, entry_points=entry_points, waiting_edges=waiting_edges, + deferred=sorted( + name + for name, spec in (getattr(builder, "nodes", None) or {}).items() + if getattr(spec, "defer", False) + ), ) def _run_config(self, config: Optional[Dict[str, Any]]) -> Dict[str, Any]: @@ -509,6 +555,57 @@ def _run_config(self, config: Optional[Dict[str, Any]]) -> Dict[str, Any]: _check_run_config(merged) return merged + def _step_bound(self, caller_config: Optional[Dict[str, Any]]) -> StepBound: + """The step limit of a run started with ``caller_config``.""" + return step_bound( + caller_config, + getattr(self._graph, "config", None), + self._max_steps, + max_steps_given=self._max_steps_given, + ) + + def _prepare_run( + self, + input: Any, + thread_id: Optional[str], + config: Optional[Dict[str, Any]], + workflow_id: Optional[str], + ) -> _RunSetup: + """Everything ``invoke`` and ``run_async`` settle before scheduling the run.""" + if not self._started: + raise RuntimeError("Runner not started. Call start() first.") + thread_id, workflow_id, caller_config = _run_identity( + config, self._run_config(config), thread_id, workflow_id + ) + bound = self._step_bound(config) + run_config = self._run_config(caller_config) + run_config["thread_id"] = thread_id + + # The parent trace is passed to the activities via config. The caller's + # finally closes it if the run is abandoned; on normal completion + # workflow.py closes it too (a benign double close). + trace = start_parent_trace(input, thread_id) + if trace: + run_config.update(trace.config) + + channels = self._channel_input(input) + workflow_input = GraphWorkflowInput( + graph_config=self._graph_config, + channel_state=ChannelState( + values=self._serialize_input(channels), + versions={k: 1 for k in channels.keys()}, + updated_channels=list(channels.keys()), + ), + step=0, + max_steps=bound.max_steps, + strict_limit=bound.strict, + pending_nodes=[], + config=run_config, + thread_id=thread_id, + ).to_dict() + json.dumps(workflow_input) + return _RunSetup(workflow_id, thread_id, run_config, trace, workflow_input) + def _register_condition_input( self, condition_name: str, source: str, branch_spec: Any ) -> None: @@ -581,20 +678,21 @@ def _register_graph_components(self) -> None: ) if reducer: default = getattr(channel, "value", _NO_DEFAULT) - if default is _NO_DEFAULT or default is _LANGGRAPH_MISSING: - register_channel_reducer(channel_name, reducer) - else: - register_channel_reducer(channel_name, reducer, default) + if default is _LANGGRAPH_MISSING: + default = _NO_DEFAULT + register_channel_reducer(channel_name, reducer, default) logger.info(f"Registered reducer for channel: {channel_name}") - # A node's keys that are not state channels are dropped, as LangGraph - # does (CompiledStateGraph's ``_get_updates``). + # A node's keys that are not state channels are dropped + # (CompiledStateGraph's ``_get_updates``). state_channels = getattr( getattr(self._graph, "builder", None), "channels", None ) if isinstance(state_channels, dict): managed = getattr(self._graph.builder, "managed", None) or {} register_state_channels([*state_channels, *managed]) + for name, kind in _managed_kinds(managed).items(): + register_managed_channel(name, kind) try: from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer @@ -624,14 +722,14 @@ def shutdown(self) -> None: def invoke( self, - input: Dict[str, Any], + input: Any, *, thread_id: Optional[str] = None, config: Optional[Dict[str, Any]] = None, workflow_id: Optional[str] = None, poll_interval: float = 0.5, timeout: Optional[float] = None, - ) -> Dict[str, Any]: + ) -> Any: """Run the graph synchronously and return the final output. Args: @@ -657,73 +755,14 @@ def invoke( GraphRunError: The run failed (a node or a condition raised). RuntimeError: The workflow failed or was terminated. """ - if not self._started: - raise RuntimeError("Runner not started. Call start() first.") - assert self._workflow_client is not None - - thread_id = thread_id or str(uuid.uuid4()) - workflow_id = workflow_id or f"graph-{thread_id}-{uuid.uuid4().hex[:8]}" - - config = self._run_config(config) - config["thread_id"] = thread_id - - # Create LangSmith parent trace and pass dotted_order to activities via config. - # The finally on the polling loop below closes the trace on FAILED/TERMINATED. - # On normal completion, _close_langsmith_parent_trace_async in workflow.py also - # closes it (benign double-close since update_run is idempotent). - _ls_run_id = None - _ls_client = None - try: - import os as _os - - if _os.environ.get("LANGSMITH_TRACING", "").lower() in ("true", "1"): - from langsmith import Client as _LsClient - from datetime import datetime, timezone - - _ls_client = _LsClient() - _ls_run_id = str(uuid.uuid4()) - _now = datetime.now(timezone.utc) - _ts = _now.strftime("%Y%m%dT%H%M%S") + f"{_now.microsecond:06d}Z" - _dotted_order = f"{_ts}{_ls_run_id}" - _ls_client.create_run( - id=_ls_run_id, - name="LangGraph", - run_type="chain", - inputs=input, - dotted_order=_dotted_order, - trace_id=_ls_run_id, - extra={"metadata": {"thread_id": thread_id}}, - ) - config["langsmith_dotted_order"] = _dotted_order - config["langsmith_run_id"] = _ls_run_id - except Exception as e: - logger.debug(f"LangSmith parent trace creation failed: {e}") - _ls_run_id = None - _ls_client = None - - channel_state = ChannelState( - values=self._serialize_input(input), - versions={k: 1 for k in input.keys()}, - updated_channels=list(input.keys()), - ) - - workflow_input = GraphWorkflowInput( - graph_config=self._graph_config, - channel_state=channel_state, - step=0, - max_steps=_max_steps_for(config, self._max_steps), - pending_nodes=[], - config=config, - thread_id=thread_id, - ) - - workflow_input_dict = workflow_input.to_dict() - json.dumps(workflow_input_dict) + run = self._prepare_run(input, thread_id, config, workflow_id) + workflow_id, thread_id, trace = run.workflow_id, run.thread_id, run.trace logger.info(f"Starting workflow: {workflow_id}") + assert self._workflow_client is not None self._workflow_client.schedule_new_workflow( workflow=agent_workflow, - input=workflow_input_dict, + input=run.workflow_input, instance_id=workflow_id, ) @@ -746,7 +785,7 @@ def invoke( if state.runtime_status == WorkflowStatus.COMPLETED: # Workflow completed normally; workflow.py already closes the trace. - _ls_run_id = None + trace = None if state.serialized_output: output_dict = ( json.loads(state.serialized_output) @@ -756,7 +795,7 @@ def invoke( output = GraphWorkflowOutput.from_dict(output_dict) if output.status in FAILED_STATUSES: # Not a result: a run that hit its step limit or - # failed in a node raises, as native invoke does. + # failed in a node raises. raise run_error( normalize_final( { @@ -769,6 +808,8 @@ def invoke( thread_id=thread_id, ) ) + if self._is_root_state() and ROOT in output.output: + return output.output[ROOT] return output.output return {} @@ -783,20 +824,12 @@ def invoke( elif state.runtime_status == WorkflowStatus.TERMINATED: raise RuntimeError(f"Workflow {workflow_id} was terminated") finally: - if _ls_run_id and _ls_client: - try: - from datetime import datetime, timezone - - _ls_client.update_run( - _ls_run_id, end_time=datetime.now(timezone.utc) - ) - _ls_client.flush() - except Exception as e: - logger.debug(f"LangSmith parent trace close failed: {e}") + if trace: + trace.end() async def run_async( self, - input: Dict[str, Any], + input: Any, *, thread_id: Optional[str] = None, config: Optional[Dict[str, Any]] = None, @@ -817,74 +850,16 @@ async def run_async( Yields: Event dictionaries with workflow progress updates """ - if not self._started: - raise RuntimeError("Runner not started. Call start() first.") - assert self._workflow_client is not None - - thread_id = thread_id or str(uuid.uuid4()) - workflow_id = workflow_id or f"graph-{thread_id}-{uuid.uuid4().hex[:8]}" - - config = self._run_config(config) - config["thread_id"] = thread_id - - # Create LangSmith parent trace and pass dotted_order to activities via config. - # The trace is closed by _close_langsmith_parent_trace_async in workflow.py on - # normal completion. The finally below closes it if the caller abandons the generator. - _ls_run_id = None - _ls_client = None - try: - import os as _os - - if _os.environ.get("LANGSMITH_TRACING", "").lower() in ("true", "1"): - from langsmith import Client as _LsClient - from datetime import datetime, timezone - - _ls_client = _LsClient() - _ls_run_id = str(uuid.uuid4()) - _now = datetime.now(timezone.utc) - _ts = _now.strftime("%Y%m%dT%H%M%S") + f"{_now.microsecond:06d}Z" - _dotted_order = f"{_ts}{_ls_run_id}" - _ls_client.create_run( - id=_ls_run_id, - name="LangGraph", - run_type="chain", - inputs=input, - dotted_order=_dotted_order, - trace_id=_ls_run_id, - extra={"metadata": {"thread_id": thread_id}}, - ) - config["langsmith_dotted_order"] = _dotted_order - config["langsmith_run_id"] = _ls_run_id - except Exception as e: - logger.debug(f"LangSmith parent trace creation failed: {e}") - _ls_run_id = None - _ls_client = None - - channel_state = ChannelState( - values=self._serialize_input(input), - versions={k: 1 for k in input.keys()}, - updated_channels=list(input.keys()), - ) - - workflow_input = GraphWorkflowInput( - graph_config=self._graph_config, - channel_state=channel_state, - step=0, - max_steps=_max_steps_for(config, self._max_steps), - pending_nodes=[], - config=config, - thread_id=thread_id, - ) - - workflow_input_dict = workflow_input.to_dict() - json.dumps(workflow_input_dict) + run = self._prepare_run(input, thread_id, config, workflow_id) + workflow_id, thread_id, trace = run.workflow_id, run.thread_id, run.trace logger.info(f"Starting workflow: {workflow_id}") + assert self._workflow_client is not None # Off the loop: this is a blocking gRPC call (see _poll_workflow). await asyncio.to_thread( self._workflow_client.schedule_new_workflow, workflow=agent_workflow, - input=workflow_input_dict, + input=run.workflow_input, instance_id=workflow_id, ) @@ -898,7 +873,7 @@ async def run_async( # Which nodes ran in each step is for the stream (stream_unavailable), # not for a caller of run_async: only a streamed run asks for it. - streamed = bool(config.get(STREAM_RUN_KEY)) + streamed = bool(run.config.get(STREAM_RUN_KEY)) def _parse_output(wf_id: str, output_dict: dict) -> dict: # type: ignore[type-arg] output = GraphWorkflowOutput.from_dict(output_dict) @@ -925,20 +900,12 @@ def _parse_output(wf_id: str, output_dict: dict) -> dict: # type: ignore[type-a yield event finally: - if _ls_run_id and _ls_client: - try: - from datetime import datetime, timezone - - _ls_client.update_run( - _ls_run_id, end_time=datetime.now(timezone.utc) - ) - _ls_client.flush() - except Exception as e: - logger.debug(f"LangSmith parent trace close failed: {e}") + if trace: + trace.end() async def astream( self, - input: Dict[str, Any], + input: Any, config: Optional[Dict[str, Any]] = None, *, thread_id: Optional[str] = None, @@ -950,57 +917,28 @@ async def astream( ) -> AsyncIterator[Any]: """Stream a run like ``CompiledStateGraph.astream``. - ``config`` is positional or keyword, as in LangGraph. The run's thread - id is ``thread_id`` if given, else ``config["configurable"]["thread_id"]``, - else a new one; the same id is in the ``workflow_started`` control, the - ``messages`` metadata and the run's config. - - Supports ``messages``, ``updates`` and ``custom``. A single mode - yields bare chunks, as native ``astream`` does, and a list of modes - yields ``(mode, chunk)`` tuples. - - Events about the stream itself are :class:`StreamControl` objects: - ``node_reset`` (a node was retried; discard its partial output), - ``stream_unavailable`` (the run finished but chunks for some of its - nodes never arrived: streaming works only when the node activities run - in this process, i.e. a single replica) and ``stream_dropped`` (the - consumer fell behind; ``{"dropped": n}``). Pass ``on_control`` to - receive them. A list of modes also yields them as ``(kind, data)`` - tuples; a single mode never does, so a consumer written against native - ``astream`` (``async for message, metadata in ...``) cannot trip over - one. ``on_control`` also gets a ``workflow_started`` control first, with - the ``workflow_id`` and ``thread_id`` to use with ``terminate_workflow`` - or ``get_workflow_status``; it is never yielded. A run that fails raises + ``messages``, ``updates`` and ``custom`` are supported; one mode yields + bare chunks, a list of modes yields ``(mode, chunk)``. The chunks have + the shape native ``astream`` yields: ``messages`` are + ``(message_chunk, metadata)``, ``updates`` are ``{node: update}`` with + the values as the node returned them (``None`` for a node that wrote + nothing), and a parallel step yields one ``updates`` chunk per node. + ``config`` follows the rules of :meth:`invoke`, and the run's thread id + is ``thread_id``, else ``config["configurable"]["thread_id"]``, else + new: the same id is in ``workflow_started``, the ``messages`` metadata + and the run's config. + + Events about the stream itself (retries, missing chunks, a consumer that + fell behind) are :class:`StreamControl` objects, given to ``on_control`` + and, in list mode only, yielded as ``(kind, data)``. Dapr retries a + failed node activity and its partial chunks cannot be taken back: a + single-mode consumer without ``on_control`` logs a warning for each + ``node_reset`` and sees the partial text. A run that fails raises :class:`GraphRunError`. - Dapr retries a failed node activity, and the chunks the failed attempt - already sent cannot be taken back. Native ``astream`` has no retries, - so a single-mode consumer that passes no ``on_control`` would see the - partial text of the failed attempt followed by the retry's. It is not - left unaware: a warning is logged for each such ``node_reset``. To - discard the partial output, pass ``on_control`` or use a list of modes - and drop what the node sent before its ``node_reset``. - - To stop early, close the stream: ``await stream.aclose()``, or iterate - inside ``async with contextlib.aclosing(runner.astream(...)) as stream``. - A bare ``break`` does not close an async generator that is still - referenced, so the run's stream stays open (and its ``workflow_id`` - reserved) until it is closed or garbage collected. Closing does not - cancel the Dapr workflow, which runs to completion. - - ``config`` is a LangGraph config that travels to the workflow as JSON: - ``tags``, ``metadata``, ``configurable`` and ``recursion_limit`` work - (the limit bounds the run's steps as LangGraph counts them; the - runner's ``max_steps`` applies when it is absent). ``callbacks`` and any - value that is not JSON raise ``ValueError`` before a run starts. - - Chunks have the shape ``CompiledStateGraph.astream`` yields: - ``messages`` are ``(message_chunk, metadata)`` and ``updates`` are - ``{node: update}`` with the values exactly as the node returned them - (``None`` for a node that wrote nothing); like LangGraph, a parallel - step yields one ``updates`` chunk per node. Over HTTP - (``"stream": true``) the same chunks are serialized with - ``langchain_core.load.dumpd``. + Close the stream to stop early (``async with aclosing(...)``): a bare + ``break`` leaves it open and its ``workflow_id`` reserved. Closing does + not cancel the Dapr workflow, which runs to completion. """ if subgraphs: raise NotImplementedError("subgraphs=True is not supported yet") @@ -1025,7 +963,7 @@ async def astream( async def _stream_events( self, - input: Dict[str, Any], + input: Any, *, config: Optional[Dict[str, Any]], thread_id: Optional[str], @@ -1049,15 +987,16 @@ async def _stream_events( whenever nothing arrived for ``SSE_KEEPALIVE_SECONDS``. """ thread_id, workflow_id, run_config = _run_identity( - self._run_config(config), thread_id, workflow_id + config, self._run_config(config), thread_id, workflow_id ) + run_config = {**run_config, STREAM_RUN_KEY: True} sink = self._stream_registry.open(workflow_id) task: Optional["asyncio.Task[None]"] = None seen_nodes: Set[Tuple[int, str]] = set() try: # Before the pump schedules the workflow: an activity can write the # moment it is scheduled, and the event must come before its chunks. - sink.put(started_event({}, workflow_id, thread_id)) + sink.put(started_event(workflow_id, thread_id)) task = asyncio.create_task( self._pump_run( sink, @@ -1091,7 +1030,7 @@ async def _stream_events( async def _pump_run( self, sink: InProcessSink, - input: Dict[str, Any], + input: Any, thread_id: str, workflow_id: str, run_config: Dict[str, Any], @@ -1116,14 +1055,9 @@ async def _pump_run( await asyncio.to_thread(on_result, result) except Exception as e: logger.exception("Streamed run %s failed", workflow_id) - # If the workflow was started this is the stream failing (its - # status polls gave out), not the workflow: it may still complete. - # Say so, and publish nothing: a failure published for a run that - # then succeeds is a lie. - started = bool(result.get("instance_id")) - final = failure_event(e, "PollError" if started else None) - if started: - final["workflow_still_running"] = True + final = stream_failure_event( + e, "PollError", bool(result.get("instance_id")) + ) sink.close(normalize_final(final, workflow_id=workflow_id, thread_id=thread_id)) async def _release_pump( @@ -1141,6 +1075,23 @@ async def _release_pump( task.cancel() await asyncio.gather(task, return_exceptions=True) + def _is_root_state(self) -> bool: + """Whether the graph's whole state is one ``__root__`` channel.""" + channels = getattr(getattr(self._graph, "builder", None), "channels", None) + return isinstance(channels, dict) and list(channels) == [ROOT] + + def _channel_input(self, input: Any) -> Dict[str, Any]: + """``input`` as values of channels. + + A graph whose state is one value takes that value as its input, so it is + the value of the ``__root__`` channel. + """ + if self._is_root_state() and not ( + isinstance(input, dict) and set(input) == {ROOT} + ): + return {ROOT: input} + return input # type: ignore[no-any-return] + def _serialize_input(self, input: Dict[str, Any]) -> Dict[str, Any]: """Serialize input values for storage.""" from .workflow import _serialize_input @@ -1161,26 +1112,16 @@ def serve( subscribe_topic: Optional[str] = None, publish_topic: Optional[str] = None, ) -> None: - """Start an HTTP server exposing /agent/run endpoints. - - ``POST /agent/run`` with ``"stream": true`` answers as server-sent - events: ``workflow_started`` first, then the ``messages``, ``updates`` - and ``custom`` chunks picked by ``stream_mode``, then - ``workflow_completed`` or ``workflow_failed``. The keys ``stream`` and - ``stream_mode`` are reserved on such a request. Streaming works only on - a single replica: chunks reach the connection through an in-process - queue, so a node activity that runs in another process streams nothing - and the stream ends with ``stream_unavailable``. A client that - disconnects ends the stream, not the workflow; with ``publish_topic`` - set its result is still published when the run ends. + """Start an HTTP server exposing ``/agent/run``. - Args: - port: Port to listen on (default: 5001) - host: Host to bind to (default: 0.0.0.0) - input_mapper: Optional function to map request dict to graph input. - pubsub_name: Dapr pub/sub component name. - subscribe_topic: Topic to subscribe to for incoming tasks. - publish_topic: Topic to publish results to. + ``POST /agent/run`` with ``"stream": true`` answers as server-sent events + (``workflow_started``, the chunks ``stream_mode`` picks, then + ``workflow_completed`` or ``workflow_failed``); the streaming README + has the details. Streaming works only on a single replica. A client that + disconnects ends the stream, not the workflow, and with ``publish_topic`` + set the result is still published when the run ends. + + ``input_mapper`` maps the request dict to the graph's input. """ self._input_mapper = input_mapper super().serve( @@ -1199,10 +1140,16 @@ def _setup_telemetry(self) -> None: def _setup_serve_defaults(self) -> None: input_mapper = getattr(self, "_input_mapper", None) + # A run an orchestrator starts has no caller config: it gets the graph's + # own, as every entry point of this runner gives it. + run_config = self._run_config(None) + bound = self._step_bound(None) set_default_graph_config( self._graph_config, input_mapper=input_mapper, - max_steps=self._max_steps, + max_steps=bound.max_steps, + strict_limit=bound.strict, + run_config=run_config, ) async def _serve_run( @@ -1272,11 +1219,7 @@ async def _serve_stream( # type: ignore[override] yield item["type"], count_unencodable(item, unencodable) except Exception as e: logger.exception("Streaming run failed") - # Once the workflow has started this is the stream failing, not the - # run: it goes on, and may well succeed (see _pump_run). - failed = failure_event(e, "StreamError" if workflow_id else None) - if workflow_id: - failed["workflow_still_running"] = True + failed = stream_failure_event(e, "StreamError", bool(workflow_id)) yield ( "workflow_failed", normalize_final(failed, workflow_id=workflow_id, thread_id=thread_id), diff --git a/diagrid/agent/langgraph/stream_events.py b/diagrid/agent/langgraph/stream_events.py index d81b1d9a..3148b9b5 100644 --- a/diagrid/agent/langgraph/stream_events.py +++ b/diagrid/agent/langgraph/stream_events.py @@ -24,6 +24,7 @@ run_error, stream_unavailable_event, to_wire, + workflow_failed, ) logger = logging.getLogger(__name__) @@ -65,8 +66,8 @@ def encode_chunk(event: StreamEvent) -> Tuple[Any, bool]: def warn_reset_unseen(workflow_id: str, data: Dict[str, Any]) -> None: """Say that a retried node's earlier chunks stay in a stream that cannot show it. - A single-mode ``astream`` yields bare chunks, as native ``astream`` does, so - a node reset has no place in it; with no ``on_control`` either, the + A single-mode ``astream`` yields bare chunks, so a node reset has no place + in it; with no ``on_control`` either, the consumer is never told and its text for that node holds both attempts. """ logger.warning( @@ -91,7 +92,7 @@ def count_unencodable(final: Dict[str, Any], unencodable: int) -> Dict[str, Any] KEEPALIVE = object() -def started_event(event: Dict[str, Any], workflow_id: str, thread_id: str) -> Any: +def started_event(workflow_id: str, thread_id: str) -> Any: """The stream's first event: the ids a client needs to find or stop its run.""" return StreamEvent( workflow_id=workflow_id, @@ -101,10 +102,7 @@ def started_event(event: Dict[str, Any], workflow_id: str, thread_id: str) -> An seq=0, ns=(), mode=WORKFLOW_STARTED, - data={ - "workflow_id": event.get("workflow_id") or workflow_id, - "thread_id": event.get("thread_id") or thread_id, - }, + data={"workflow_id": workflow_id, "thread_id": thread_id}, ) @@ -133,12 +131,24 @@ def failure_event( ``error_type`` replaces the exception's own type name; it is how a stream failure says it is not the run's (see ``PollError`` and ``StreamError``). """ + return workflow_failed({}, str(error), error_type or type(error).__name__) + + +def stream_failure_event( + error: BaseException, stream_error_type: str, started: bool +) -> Dict[str, Any]: + """A ``workflow_failed`` event for a failure of the stream, not necessarily the run. + + Once the workflow ``started``, the run goes on and may well succeed, so the + event is typed ``stream_error_type`` and says it is still running, and it + must not be published: a failure published for a run that then succeeds is + a lie. Before that, the run itself failed to start. + """ + if not started: + return failure_event(error) return { - "type": "workflow_failed", - "error": { - "message": str(error), - "error_type": error_type or type(error).__name__, - }, + **failure_event(error, stream_error_type), + "workflow_still_running": True, } diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index d5aa2428..ab9fabef 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -23,6 +23,7 @@ from diagrid.agent.core.workflow.stream import ( STREAM_UNAVAILABLE, + UPDATES, StreamEvent, StreamSink, display_step, @@ -31,7 +32,6 @@ logger = logging.getLogger(__name__) MESSAGES = "messages" -UPDATES = "updates" CUSTOM = "custom" SUPPORTED_MODES = (MESSAGES, UPDATES, CUSTOM) @@ -146,8 +146,11 @@ def __init__( static: Optional[StaticConfig] = None, sink_node: Optional[str] = None, path: Optional[Sequence[Any]] = None, + branch: Optional[str] = None, ) -> None: self._path = tuple(path) if path else None + # The conditional edge whose function this streamer serves, if any. + self._branch = branch # ``sink_node`` is the name chunks are keyed under in the sink when it # is not the node's own: a conditional edge's function streams as its # source node but must not share that node's attempts and ``updates``. @@ -197,6 +200,7 @@ def _emit(self, ns: Tuple[str, ...], mode: str, data: Any) -> None: data=data, display_node=self._node, path=self._path, + branch=self._branch, ) ) @@ -310,6 +314,9 @@ def updates(self, writes: List[Tuple[str, Any]]) -> None: channels = [ch for ch, _ in writes] if not writes: update = None + elif channels == ["__root__"]: + # a graph whose whole state is one value: LangGraph reports the value + update = writes[0][1] elif len(set(channels)) == len(channels): update = dict(writes) else: @@ -447,7 +454,10 @@ def run_error(final: Dict[str, Any]) -> GraphRunError: return GraphRunError(final) -def _failed(final: Dict[str, Any], message: str, error_type: str) -> Dict[str, Any]: +def workflow_failed( + final: Dict[str, Any], message: str, error_type: str +) -> Dict[str, Any]: + """``final`` turned into a ``workflow_failed`` event with this error.""" return { **final, "type": "workflow_failed", @@ -469,19 +479,19 @@ def normalize_final( kind = final.get("type") status = final.get("status") if not final: - out = _failed({}, NO_RESULT_MESSAGE, "NoResult") + out = workflow_failed({}, NO_RESULT_MESSAGE, "NoResult") elif kind == "workflow_completed" and status in FAILED_STATUSES: - out = _failed( + out = workflow_failed( final, str(final.get("error") or f"Workflow ended with status {status!r}"), "WorkflowStatus", ) elif kind == "workflow_error": - out = _failed( + out = workflow_failed( final, str(final.get("error") or "Workflow error"), "WorkflowError" ) elif kind == "workflow_terminated": - out = _failed(final, "Workflow was terminated", "WorkflowTerminated") + out = workflow_failed(final, "Workflow was terminated", "WorkflowTerminated") else: out = dict(final) if workflow_id: @@ -506,8 +516,8 @@ def stream_unavailable_event( ``seen`` holds the ``(step, node)`` pairs whose ``updates`` chunk arrived; every node that runs here sends one when it finishes, so an executed node without one had its activity (or its last attempt) elsewhere, even when - other nodes of its step streamed here. A final without ``executed`` (a run - started before the workflow reported it) is judged per step instead. A run + other nodes of its step streamed here. A final without ``executed`` is + judged per step instead. A run that failed is just a failure, and one with no step count has nothing to report. """ diff --git a/diagrid/agent/langgraph/values.py b/diagrid/agent/langgraph/values.py new file mode 100644 index 00000000..624cd7c8 --- /dev/null +++ b/diagrid/agent/langgraph/values.py @@ -0,0 +1,80 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""How a state value is stored in the workflow's channel state. + +The channel state crosses JSON (it is a workflow input and an activity result), +yet a node expects the types it wrote: a message object in a list, a ``set``, a +``datetime``. A value that is plain JSON is stored as it is. Anything else is +stored as the checkpoint serializer writes it (LangGraph's own +``JsonPlusSerializer``), wrapped as ``{"__typed__": [kind, base64]}``, and is +decoded when a node, a router or a reducer reads it. +""" + +import base64 +import math +from typing import Any + +TYPED = "__typed__" + + +def is_plain_json(value: Any) -> bool: + """Whether ``value`` is what JSON gives back unchanged (no tuple, set, object).""" + if value is None or isinstance(value, (str, bool, int)): + return True + if isinstance(value, float): + return math.isfinite(value) + if isinstance(value, list): + return all(is_plain_json(v) for v in value) + if isinstance(value, dict): + return all( + isinstance(k, str) and k != TYPED and is_plain_json(v) + for k, v in value.items() + ) + return False + + +def is_encoded(value: Any) -> bool: + """Whether ``value`` is a typed envelope made by :func:`encode_value`.""" + return isinstance(value, dict) and len(value) == 1 and TYPED in value + + +def encode_value(value: Any) -> Any: + """``value`` as JSON: itself when plain, else a typed envelope. + + A value the serializer cannot write is left to the caller's fallback: the + raw value comes back (and is made JSON by it). + """ + if is_plain_json(value): + return value + try: + from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer + + kind, data = JsonPlusSerializer().dumps_typed(value) + except Exception: + return value + return {TYPED: [kind, base64.b64encode(data).decode("ascii")]} + + +def decode_value(value: Any) -> Any: + """What :func:`encode_value` was given (anything else is returned as is).""" + if not is_encoded(value): + return value + from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer + + kind, data = value[TYPED] + return JsonPlusSerializer().loads_typed((kind, base64.b64decode(data))) + + +def coerce_to_default(value: Any, default: Any) -> Any: + """``value`` as the type of the channel's ``default`` when JSON blurred them. + + A tuple comes back from the serializer as a list, so a ``tuple`` channel is + given its tuple again (a ``set`` or ``frozenset`` survives, but a list that + was stored for one is turned back too). + """ + if type(default) in (tuple, set, frozenset) and isinstance( + value, (list, tuple, set, frozenset) + ): + return type(default)(value) + return value diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 17d992e3..aad60e93 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -5,6 +5,7 @@ import asyncio import base64 +import concurrent.futures import contextlib import copy import dataclasses @@ -42,6 +43,7 @@ from langgraph.graph.message import add_messages from pydantic import BaseModel, TypeAdapter, ValidationError from langgraph.runtime import Runtime +from langgraph.errors import ParentCommand from langgraph.types import Command, Overwrite, Send try: @@ -62,6 +64,13 @@ ) from .streaming import STREAM_RUN_KEY, NodeStreamer, StaticConfig +from .values import ( + coerce_to_default, + decode_value, + encode_value, + is_encoded, + is_plain_json, +) from .models import ( ChannelState, ExecuteNodeInput, @@ -86,7 +95,7 @@ # The value a reducer channel holds before its first write (``[]`` for a list). _channel_defaults: Dict[str, Any] = {} _NO_DEFAULT: Any = object() -# The graph's state channels: a node's other keys are not writes, as in LangGraph. +# The graph's state channels: a node's other keys are dropped, not written. # ``None`` until a runner registers them (then nothing is dropped). _state_channels: Optional[frozenset] = None # What a node and a conditional edge are handed: the channels of its input schema @@ -94,26 +103,46 @@ # dataclass state). Conditions are keyed by their name. _node_inputs: Dict[str, "_InputShape"] = {} _condition_inputs: Dict[str, "_InputShape"] = {} +# The managed values the graph's state asks for (name -> ``REMAINING_STEPS`` or +# ``IS_LAST_STEP``); they are given to nodes and routers, never stored. +_managed_channels: Dict[str, str] = {} _serializer: Optional[Any] = None _default_graph_config: Optional["GraphConfig"] = None _default_input_mapper: Optional[Callable] = None _default_max_steps: int = 100 -# Every trigger channel of each node, as LangGraph lists them in a task's metadata. +_default_strict_limit: bool = False +# The config a run started without one gets: the graph's own (``with_config``). +_default_run_config: Optional[Dict[str, Any]] = None +# Every trigger channel of each node, for ``langgraph_triggers`` in a task's metadata. _node_triggers: Dict[str, Tuple[str, ...]] = {} # The metadata and tags the graph and each node give their tasks (see StaticConfig). _node_static: Dict[str, StaticConfig] = {} +# The managed values of LangGraph's own that are supplied (``langgraph.managed``). +REMAINING_STEPS = "remaining_steps" +IS_LAST_STEP = "is_last_step" + # The key a write that replaces a reducer channel's value is stored under. OVERWRITE = "__overwrite__" +# The one channel of a graph whose whole state is a single value +# (``StateGraph(Annotated[list, operator.add])``). +ROOT = "__root__" + # Special node names START = "__start__" END = "__end__" # Each node runs as an activity named after the node, so the workflow UI shows -# the graph's own step names. Instances started before this change scheduled -# every node as ``execute_node_activity``; the patch keeps them replaying. +# the graph's own step names. A replay must schedule what the history holds, so +# an instance that scheduled every node as ``execute_node_activity`` keeps doing +# so: the patch is what tells the two apart. NODE_ACTIVITY_NAMES_PATCH = "langgraph-node-activity-names" +# A step's nodes run sorted by name (LangGraph's task order) and END does not +# end the run while other branches of the step are pending. An instance that +# scheduled its nodes in the order the edges were found, and ended at END, must +# replay that way: the patch is what tells the two apart. +STEP_ORDER_PATCH = "langgraph-step-order" GENERIC_NODE_ACTIVITY = "execute_node_activity" CONDITION_ACTIVITY = "evaluate_condition_activity" # What LangGraph names the trigger (and path) of a task started by a ``Send``. @@ -208,7 +237,7 @@ def register_channel_reducer( """Register a reducer function for a channel. ``default`` is what the channel holds before its first write; the first - write is reduced into it, as LangGraph does. Without one it is stored as is. + write is reduced into it. Without one it is stored as is. """ _channel_reducers[channel] = reducer if default is _NO_DEFAULT: @@ -223,9 +252,13 @@ class _InputShape: channels: Optional[Tuple[str, ...]] = None mapper: Optional[Callable[[Dict[str, Any]], Any]] = None + #: The state is one channel (``__root__``) and the node takes its value. + root: bool = False def apply(self, state: Dict[str, Any]) -> Any: """``state`` cut to the channels and coerced to the schema class.""" + if self.root: + return state.get(ROOT) channels = self.channels if channels is not None: state = {k: v for k, v in state.items() if k in channels} @@ -235,8 +268,8 @@ def apply(self, state: Dict[str, Any]) -> Any: def _input_shape(channels: Any, mapper: Optional[Callable]) -> _InputShape: """The shape for an input schema's ``channels`` (a single root channel is not cut).""" names = [channels] if isinstance(channels, str) else list(channels or ()) - keep = tuple(names) if names and "__root__" not in names else None - return _InputShape(channels=keep, mapper=mapper) + keep = tuple(names) if names and ROOT not in names else None + return _InputShape(channels=keep, mapper=mapper, root=ROOT in names) def register_node_input(name: str, channels: Any, mapper: Optional[Callable]) -> None: @@ -251,6 +284,30 @@ def register_condition_input( _condition_inputs[name] = _input_shape(channels, mapper) +def register_managed_channel(name: str, kind: str) -> None: + """Record that state key ``name`` is a managed value of ``kind``. + + ``kind`` is ``REMAINING_STEPS`` or ``IS_LAST_STEP``. + """ + _managed_channels[name] = kind + + +def _with_managed( + state: Dict[str, Any], recursion_limit: Optional[int], step: Optional[int] +) -> Dict[str, Any]: + """``state`` with the managed values of a task at workflow step ``step``. + + LangGraph counts ``RemainingSteps`` down from the limit: ``limit - 1 - step`` + for a task whose step is numbered from 0, and ``IsLastStep`` is true when one + remains. Nothing is added when the workflow did not say what the limit is. + """ + if not _managed_channels or recursion_limit is None or step is None: + return state + remaining = recursion_limit - 1 - step + values = {REMAINING_STEPS: remaining, IS_LAST_STEP: remaining == 1} + return {**state, **{n: values[k] for n, k in _managed_channels.items()}} + + def register_state_channels(channels: Iterable[str]) -> None: """Record the graph's state channels, the only keys a node can write.""" global _state_channels @@ -260,7 +317,12 @@ def register_state_channels(channels: Iterable[str]) -> None: def _keep_channel(channel: str) -> bool: """Whether a node's key is a state channel (everything is, before any is set).""" names = _state_channels - return names is None or "__root__" in names or channel in names + return names is None or ROOT in names or channel in names + + +def _is_root_state() -> bool: + """Whether the graph's whole state is the one ``__root__`` channel.""" + return _state_channels is not None and ROOT in _state_channels def get_channel_reducer(channel: str) -> Optional[Callable]: @@ -284,12 +346,21 @@ def set_default_graph_config( *, input_mapper: Optional[Callable] = None, max_steps: int = 100, + strict_limit: bool = False, + run_config: Optional[Dict[str, Any]] = None, ) -> None: - """Store the default graph config for orchestrator-initiated calls.""" + """Store the default graph config for orchestrator-initiated calls. + + ``run_config`` is the LangGraph config such a run starts with: what a runner + entry point makes of the config bound to the graph (``with_config``). + """ global _default_graph_config, _default_input_mapper, _default_max_steps + global _default_run_config, _default_strict_limit _default_graph_config = config _default_input_mapper = input_mapper _default_max_steps = max_steps + _default_strict_limit = strict_limit + _default_run_config = copy.deepcopy(run_config) if run_config else None def _close_langsmith_parent_trace_async(config: Optional[Dict[str, Any]]) -> None: @@ -361,9 +432,13 @@ def clear_registries() -> None: _state_channels = None _node_triggers.clear() _node_static.clear() + _managed_channels.clear() _node_inputs.clear() _condition_inputs.clear() global _serializer, _default_graph_config, _default_input_mapper, _default_max_steps + global _default_run_config, _default_strict_limit + _default_run_config = None + _default_strict_limit = False _serializer = None _default_graph_config = None _default_input_mapper = None @@ -375,16 +450,14 @@ def _workflow_input( ) -> GraphWorkflowInput: """The workflow's input: a full ``GraphWorkflowInput`` or a ``{"task": ...}``.""" if "graph_config" in input_data: - # Normal internal call with full GraphWorkflowInput return GraphWorkflowInput.from_dict(input_data) - # Orchestrator call with simple {"task": "..."} input + # An orchestrator starts the workflow with just {"task": "..."}. if _default_graph_config is None: raise ValueError( "Received simple task input but no default graph config is set. " "Ensure the runner has been started before the workflow is invoked." ) - # Build graph input from the task using the stored mapper if _default_input_mapper: graph_input = _default_input_mapper(input_data) elif "task" in input_data: @@ -404,10 +477,19 @@ def _workflow_input( channel_state=channel_state, step=0, max_steps=_default_max_steps, + strict_limit=_default_strict_limit, + config=_orchestrated_config(str(ctx.instance_id)), thread_id=str(ctx.instance_id), ) +def _orchestrated_config(thread_id: str) -> Optional[Dict[str, Any]]: + """The config of a run an orchestrator started: the graph's own, if it has one.""" + if _default_run_config is None: + return None + return {**copy.deepcopy(_default_run_config), "thread_id": thread_id} + + @dataclass class _Run: """What every step of one ``agent_workflow`` execution shares.""" @@ -419,9 +501,17 @@ class _Run: thread_id: Optional[str] retry_policy: RetryPolicy node_activities_by_name: bool + #: Whether a step's nodes run sorted by name (see :data:`STEP_ORDER_PATCH`). + step_order: bool + #: The run's bound as a LangGraph ``recursion_limit`` (what ``RemainingSteps`` + #: counts against): the runner's own ``max_steps`` lets a run of exactly that + #: many steps complete, which is a limit one above it. + recursion_limit: Optional[int] = None #: The nodes that ran in each step, reported on the output so a streaming #: consumer can tell which node's chunks never arrived. executed: List[List[str]] = field(default_factory=list) + #: Deferred nodes that were triggered and wait for nothing else to be pending. + held: List[str] = field(default_factory=list) def finish( self, step: int, status: str, error: Optional[str] = None @@ -441,31 +531,17 @@ def finish( ).to_dict() -def agent_workflow( - ctx: DaprWorkflowContext, input_data: Dict[str, Any] -) -> Generator[Any, Any, Dict[str, Any]]: - """Dapr Workflow that orchestrates LangGraph execution. - - This workflow implements the Pregel/BSP execution model: - 1. Determine which nodes should run based on updated channels - 2. Execute all triggered nodes in parallel (as activities) - 3. Apply writes to channels - 4. Repeat until no more nodes are triggered or END is reached +#: The nodes, the ``Send`` tasks and the error a search for the next step ends with. +_StartOrNext = Tuple[List[str], List[Dict[str, Any]], Optional[str]] - Args: - ctx: The Dapr workflow context - input_data: Dictionary containing GraphWorkflowInput data - - Returns: - GraphWorkflowOutput as a dictionary - """ - workflow_input = _workflow_input(ctx, input_data) +def _new_run(ctx: DaprWorkflowContext, workflow_input: GraphWorkflowInput) -> _Run: + """The shared state of one ``agent_workflow`` execution.""" # Ask before the first yield: a replay of an older instance must see the # patch as absent, and the answer is fixed for the rest of the execution. node_activities_by_name = ctx.is_patched(NODE_ACTIVITY_NAMES_PATCH) - - run = _Run( + step_order = ctx.is_patched(STEP_ORDER_PATCH) + return _Run( ctx=ctx, graph_config=workflow_input.graph_config, channel_state=workflow_input.channel_state, @@ -478,68 +554,137 @@ def agent_workflow( max_retry_interval=timedelta(seconds=30), ), node_activities_by_name=node_activities_by_name, + step_order=step_order, + recursion_limit=( + workflow_input.max_steps + if workflow_input.strict_limit + else workflow_input.max_steps + 1 + ), ) + + +def agent_workflow( + ctx: DaprWorkflowContext, input_data: Dict[str, Any] +) -> Generator[Any, Any, Dict[str, Any]]: + """Dapr Workflow that runs a LangGraph graph step by step (Pregel's BSP model). + + Each step runs the triggered nodes in parallel as activities, applies their + writes to the channels, and finds the next step's nodes from the edges. The + run ends when nothing is triggered, END is reached or a step bound is hit; + the result is a ``GraphWorkflowOutput`` as a dictionary. + """ + workflow_input = _workflow_input(ctx, input_data) + run = _new_run(ctx, workflow_input) max_steps = workflow_input.max_steps step = 0 pending_nodes, pending_sends, error = yield from _start_nodes(run) if error: return run.finish(step, "error", f"Condition evaluation failed: {error}") + pending_nodes = _hold_deferred(run, pending_nodes, pending_sends) # Joins: how many of each waiting edge's sources have run since it last fired. joined: List[Set[str]] = [set() for _ in run.graph_config.waiting_edges] - # Main execution loop while True: - # Log workflow step for debugging - if not ctx.is_replaying: - print( - f" [WORKFLOW] Step {step}, pending_nodes={pending_nodes}", flush=True - ) - - # END ends the run only when nothing else is pending: another branch of - # the step may still have nodes to run, as in LangGraph. - nodes_to_execute = [n for n in pending_nodes if n != END] - if not nodes_to_execute and not pending_sends: + _log_step(run, step, pending_nodes) + nodes_to_execute, run_ends = _step_nodes( + pending_nodes, pending_sends, run.step_order + ) + # A recursion_limit is checked before the end of the run: a run that + # has taken that many steps fails, whatever follows. + if workflow_input.strict_limit and step >= max_steps: + break + if run_ends: return run.finish(step, "completed") - # The bound is checked after the end of the run, so a graph that needs - # exactly ``max_steps`` steps completes instead of being cut at the end. + # The runner's own bound is checked after the end of the run, so a graph + # that needs exactly ``max_steps`` steps completes instead of being cut + # at the end. if step >= max_steps: break - run.executed.append( - [ - *nodes_to_execute, - *[send_key(t["node"], slot) for slot, t in enumerate(pending_sends)], - ] + pending_nodes, pending_sends, error = yield from _run_step( + run, nodes_to_execute, pending_sends, joined, step ) + if error: + return run.finish(step, "error", error) + pending_nodes = _hold_deferred(run, pending_nodes, pending_sends) + step += 1 - node_outputs = yield from _run_nodes(run, nodes_to_execute, pending_sends, step) - failed = next((o for o in node_outputs if o.error), None) - if failed: - return run.finish( - step, "error", f"Node '{failed.node_name}' failed: {failed.error}" - ) + return run.finish(step, "max_steps_reached", f"Max steps ({max_steps}) reached") - # Apply writes to channels - try: - updated_channels = _apply_outputs(run.channel_state, node_outputs) - except ReducerError as e: - return run.finish(step, "error", str(e)) - run.channel_state.updated_channels = updated_channels - ran = list( - dict.fromkeys([*nodes_to_execute, *[t["node"] for t in pending_sends]]) - ) - pending_nodes, pending_sends, error = yield from _next_nodes( - run, ran, node_outputs, joined, step +def _log_step(run: _Run, step: int, pending_nodes: List[str]) -> None: + """Print the step about to run, once: not again on a replay of it.""" + if not run.ctx.is_replaying: + print(f" [WORKFLOW] Step {step}, pending_nodes={pending_nodes}", flush=True) + + +def _run_step( + run: _Run, + nodes: List[str], + sends: List[Dict[str, Any]], + joined: List[Set[str]], + step: int, +) -> Generator[Any, Any, _StartOrNext]: + """Run a step's nodes and ``Send`` tasks, apply their writes, find the next step. + + Returns the next step's nodes and ``Send`` tasks, and the message the run + ends with if a node failed, a reducer raised or a condition failed. + """ + run.executed.append( + [*nodes, *[send_key(t["node"], slot) for slot, t in enumerate(sends)]] + ) + outputs = yield from _run_nodes(run, nodes, sends, step) + failed = next((o for o in outputs if o.error), None) + if failed: + return [], [], f"Node '{failed.node_name}' failed: {failed.error}" + + tasks = [ + _Task( + node=output.node_name, + output=output, + slot=i - len(nodes) if i >= len(nodes) else None, ) - if error: - return run.finish(step, "error", f"Condition evaluation failed: {error}") - step += 1 + for i, output in enumerate(outputs) + ] + # A conditional edge reads the state with only its own task's writes + # applied, so a step that runs several tasks keeps the state they start + # from. + before = _state_before_step(run, tasks) + try: + run.channel_state.updated_channels = _apply_outputs(run.channel_state, outputs) + except ReducerError as e: + return [], [], str(e) + next_nodes, next_sends, error = yield from _next_nodes( + run, tasks, before, joined, step + ) + return ( + next_nodes, + next_sends, + f"Condition evaluation failed: {error}" if error else None, + ) - # Max steps reached - return run.finish(step, "max_steps_reached", f"Max steps ({max_steps}) reached") + +def _step_nodes( + pending_nodes: List[str], pending_sends: List[Dict[str, Any]], step_order: bool +) -> Tuple[List[str], bool]: + """The nodes to run in a step, and whether the run ends instead. + + END ends the run only when nothing else is pending: another branch of the + step may still have nodes to run. The nodes run sorted by + name (LangGraph's task order), so the order their writes apply in does not + depend on the order the edges were found in. + + An instance started before :data:`STEP_ORDER_PATCH` (``step_order`` false) + ends at END and runs the nodes in the order they were found: its history + holds activities scheduled that way, and a replay must schedule the same. + """ + if step_order: + nodes = sorted(n for n in pending_nodes if n != END) + return nodes, not nodes and not pending_sends + nodes = [n for n in pending_nodes if n != END] + return nodes, (END in pending_nodes or not nodes) and not pending_sends def _apply_outputs( @@ -555,44 +700,103 @@ def _apply_outputs( return updated_channels -_StartOrNext = Tuple[List[str], List[Dict[str, Any]], Optional[str]] +@dataclass +class _Frontier: + """The nodes and ``Send`` tasks found to run next, in the order found.""" + + nodes: List[str] = field(default_factory=list) + sends: List[Dict[str, Any]] = field(default_factory=list) + + def add_nodes(self, names: Iterable[str]) -> None: + for name in names: + if name not in self.nodes: + self.nodes.append(name) + + def result(self, error: Optional[str] = None) -> _StartOrNext: + return self.nodes, self.sends, error def _start_nodes(run: _Run) -> Generator[Any, Any, _StartOrNext]: """The nodes (and ``Send`` tasks) the START edges lead to, and a condition error. - A conditional START edge is evaluated on the input, as LangGraph does. + A conditional START edge is evaluated on the input. """ graph_config = run.graph_config - if graph_config.entry_points is None: # a config from before entry_points + if graph_config.entry_points is None: # an input persisted without entry_points return [graph_config.entry_point], [], None - pending_nodes = list(graph_config.entry_points) - pending_sends: List[Dict[str, Any]] = [] + found = _Frontier(nodes=list(graph_config.entry_points)) for edge in graph_config.edges: if edge.source != START or not edge.condition: continue - cond_output = yield from _evaluate_edge( - run.ctx, - edge, - START, - run.channel_state, - run.config, - run.thread_id, - run.retry_policy, - -1, # before the first node, so the first node is step 1 + # step -1: before the first node, so the first node is step 1 + error = yield from _follow_edge( + run, found, edge, START, run.channel_state, -1, None ) - if cond_output.error: - return pending_nodes, pending_sends, cond_output.error - for n in cond_output.next_nodes: - if n not in pending_nodes: - pending_nodes.append(n) - pending_sends.extend(_indexed(cond_output.sends)) - return pending_nodes, pending_sends, None + if error: + return found.result(error) + return found.result() -def _indexed(sends: List[Dict[str, Any]]) -> List[Dict[str, Any]]: - """``sends`` numbered by their position in the list one source returned.""" - return [{**send, "index": i} for i, send in enumerate(sends)] +def _hold_deferred( + run: _Run, pending_nodes: List[str], pending_sends: List[Dict[str, Any]] +) -> List[str]: + """The nodes to run next, with deferred ones held back until nothing else is. + + A node added with ``defer=True`` runs once, when no other node or ``Send`` + task is pending (the end of the run, unless it starts more), however many + of its sources ran before. + """ + deferred = set(run.graph_config.deferred) + if not deferred: + return pending_nodes + ready = [] + for node in pending_nodes: + if node not in deferred: + ready.append(node) + elif node not in run.held: + run.held.append(node) + if not any(n != END for n in ready) and not pending_sends and run.held: + ready, run.held = [*ready, *run.held], [] + return ready + + +@dataclass +class _Task: + """One node (or ``Send``) execution of a step, with what it returned.""" + + node: str + output: ExecuteNodeOutput + #: Position among the step's ``Send`` tasks; ``None`` for a node's own run. + slot: Optional[int] = None + + +def _state_before_step(run: _Run, tasks: List["_Task"]) -> Optional[ChannelState]: + """A copy of the channel state to give each task's routers, if they need one. + + With one task, the state after its writes is what its routers read, so + nothing is kept. With several, a task's routers must not see its siblings' + writes, so the state before the step's writes is kept. + """ + if len(tasks) < 2: + return None + has_router = any( + e.condition and e.source == t.node + for t in tasks + for e in run.graph_config.edges + ) + return copy.deepcopy(run.channel_state) if has_router else None + + +def _state_for_task( + run: _Run, before: Optional[ChannelState], task: _Task +) -> ChannelState: + """The state a task's conditional edges read: the step's start plus its writes.""" + if before is None: + return run.channel_state + state = copy.deepcopy(before) + for write in task.output.writes: + _apply_write(state, write.channel, write.value) + return state def _run_nodes( @@ -605,10 +809,7 @@ def _run_nodes( node_tasks = [] invocations: List[Tuple[str, Optional[Dict[str, Any]]]] = [ *[(name, None) for name in nodes_to_execute], - *[ - (t["node"], {"arg": t["arg"], "index": t["index"], "slot": slot}) - for slot, t in enumerate(sends) - ], + *[(t["node"], {"arg": t["arg"], "slot": slot}) for slot, t in enumerate(sends)], ] for node_name, send in invocations: node_input = ExecuteNodeInput( @@ -618,6 +819,7 @@ def _run_nodes( thread_id=run.thread_id, step=step, send=send, + recursion_limit=run.recursion_limit, ) activity: Any = execute_node_activity if run.node_activities_by_name: @@ -630,97 +832,94 @@ def _run_nodes( ) ) - # Wait for all node executions to complete task_results = yield when_all(node_tasks) return [ExecuteNodeOutput.from_dict(result) for result in task_results] def _next_nodes( run: _Run, - nodes_to_execute: List[str], - node_outputs: List[ExecuteNodeOutput], + tasks: List[_Task], + before: Optional[ChannelState], joined: List[Set[str]], step: int, ) -> Generator[Any, Any, _StartOrNext]: """The nodes and ``Send`` tasks the next step runs, and a condition error. - They follow from the edges of the nodes that ran, the joins those nodes - complete, and the ``Command(goto=...)`` they returned. + They follow from the edges of the tasks that ran, the joins those tasks + complete, and the ``Command(goto=...)`` they returned. A conditional edge is + evaluated once per task, on the state with only that task's writes (see + :func:`_state_for_task`). Tasks are taken in the order LangGraph applies + them, and each one's ``goto`` before its conditional edges, so the ``Send`` + tasks come out numbered as LangGraph numbers them. """ - next_nodes: List[str] = [] - next_sends: List[Dict[str, Any]] = [] - for node_name in nodes_to_execute: + found = _Frontier() + for task in tasks: + found.add_nodes(task.output.goto) + found.sends.extend(task.output.sends) for edge in run.graph_config.edges: - if edge.source != node_name: + if edge.source != task.node: continue if not edge.condition: - # Direct edge - if edge.target not in next_nodes: - next_nodes.append(edge.target) + found.add_nodes([edge.target]) continue - # Evaluate conditional edge (as activity) - cond_output = yield from _evaluate_edge( - run.ctx, - edge, - node_name, - run.channel_state, - run.config, - run.thread_id, - run.retry_policy, - step, + try: + state = _state_for_task(run, before, task) + except ReducerError as e: + return found.result(str(e)) + error = yield from _follow_edge( + run, found, edge, task.node, state, step, task.slot ) - if cond_output.error: - return next_nodes, next_sends, cond_output.error - for n in cond_output.next_nodes: - if n not in next_nodes: - next_nodes.append(n) - next_sends.extend(_indexed(cond_output.sends)) + if error: + return found.result(error) # A join fires, once, in the step after the last of its sources ran. + ran = {task.node for task in tasks} for seen, join in zip(joined, run.graph_config.waiting_edges): - seen.update(n for n in nodes_to_execute if n in join.sources) + seen.update(n for n in ran if n in join.sources) if seen.issuperset(join.sources): seen.clear() - if join.target not in next_nodes: - next_nodes.append(join.target) - - # Nodes a Command(goto=...) asked for run next as well, as in LangGraph. - for output in node_outputs: - for target in output.goto: - if target not in next_nodes: - next_nodes.append(target) - next_sends.extend(_indexed(output.sends)) - return next_nodes, next_sends, None + found.add_nodes([join.target]) + return found.result() -def _evaluate_edge( - ctx: DaprWorkflowContext, +def _follow_edge( + run: _Run, + found: _Frontier, edge: Any, source_node: str, channel_state: ChannelState, - config: Optional[Dict[str, Any]], - thread_id: Optional[str], - retry_policy: RetryPolicy, step: int, -) -> Generator[Any, Any, EvaluateConditionOutput]: - """Evaluate a conditional edge as an activity; ``yield from`` it.""" + send_slot: Optional[int], +) -> Generator[Any, Any, Optional[str]]: + """Evaluate a conditional edge as an activity and add where it leads to ``found``. + + Returns the condition's error, if it failed. ``send_slot`` is the position + of the source task among the step's ``Send`` tasks, when it is one. + """ cond_input = EvaluateConditionInput( source_node=source_node, condition_name=edge.condition, channel_state=channel_state, - config=config, - thread_id=thread_id, + config=run.config, + thread_id=run.thread_id, path_map=edge.path_map, step=step, + send_slot=send_slot, + recursion_limit=run.recursion_limit, ) # By name, so the runner's own activity (the one that knows its stream # registry) runs, not the module-level function. - cond_result = yield ctx.call_activity( + cond_result = yield run.ctx.call_activity( CONDITION_ACTIVITY, input=cond_input.to_dict(), - retry_policy=retry_policy, + retry_policy=run.retry_policy, ) - return EvaluateConditionOutput.from_dict(cond_result) + output = EvaluateConditionOutput.from_dict(cond_result) + if output.error: + return output.error + found.add_nodes(output.next_nodes) + found.sends.extend(output.sends) + return None def _build_node_runtime( @@ -763,29 +962,22 @@ def _build_node_runtime( return Runtime(**extra) -def _is_async_only(runnable: Any) -> bool: - """Whether ``runnable`` wraps only an ``async def`` (no sync ``func``). - - ``RunnableCallable.invoke()`` raises for these, so they must be run through - ``ainvoke()`` instead. - """ - return ( - getattr(runnable, "func", None) is None - and getattr(runnable, "afunc", None) is not None - ) - - def _has_async_entry(runnable: Any) -> bool: """Whether ``runnable`` has a real async entry point, which a node should use. ``ToolNode`` has a sync ``func`` and an ``afunc``; its sync one cannot run an ``async def`` tool (MCP adapter tools are such), its async one runs both, - as native ``astream`` does. A plain sync node also gets an ``afunc``, but + A plain sync node also gets an ``afunc``, but only a ``run_in_executor`` wrapper around its function: that is not one. + + A composite (a compiled subgraph, a ``RunnableSequence``) has no function of + its own and no ``afunc``, but a step inside it may be an ``async def`` with + no sync entry, so it goes through ``ainvoke`` too: that runs a sync step in + an executor. """ afunc = getattr(runnable, "afunc", None) if afunc is None: - return False + return not hasattr(runnable, "func") and hasattr(runnable, "ainvoke") return not (isinstance(afunc, functools.partial) and afunc.func is run_in_executor) @@ -825,7 +1017,9 @@ def _make_activity_read( channel names when ``create_agent`` sends it a bare list of tool calls. """ return functools.partial( - _read_activity_channels, pending_sends, channel_state.values + _read_activity_channels, + pending_sends, + {name: decode_value(v) for name, v in channel_state.values.items()}, ) @@ -863,21 +1057,44 @@ class _BackgroundLoop: to the loop it was first used on. A loop made and closed for each activity would break that client for the next activity, so every coroutine runs on this one, which is never closed. + + ``asyncio`` re-raises ``SystemExit`` and ``KeyboardInterrupt`` out of + ``run_forever``, which would end the loop's thread and leave every waiting + and later async node hanging. A node's own coroutine is guarded so those + fail that node alone, and a loop whose thread has died anyway is replaced. """ + #: Seconds between looks at whether the loop's thread is still alive. + _CHECK_SECONDS = 1.0 + def __init__(self) -> None: self._lock = threading.Lock() self._loop: Optional[asyncio.AbstractEventLoop] = None + self._thread: Optional[threading.Thread] = None - def _running_loop(self) -> asyncio.AbstractEventLoop: + def _running_loop(self) -> Tuple[asyncio.AbstractEventLoop, threading.Thread]: with self._lock: - if self._loop is None or self._loop.is_closed(): + alive = self._thread is not None and self._thread.is_alive() + if self._loop is None or self._loop.is_closed() or not alive: loop = asyncio.new_event_loop() - threading.Thread( + thread = threading.Thread( target=loop.run_forever, name="langgraph-node-loop", daemon=True - ).start() - self._loop = loop - return self._loop + ) + thread.start() + self._loop, self._thread = loop, thread + assert self._loop is not None and self._thread is not None + return self._loop, self._thread + + @staticmethod + async def _guarded(coro: Any) -> Any: + """``coro``, with an exit request turned into an error of the node.""" + try: + return await coro + except (SystemExit, KeyboardInterrupt) as e: + raise RuntimeError( + f"The node raised {type(e).__name__}({', '.join(map(repr, e.args))}); " + "it fails the node, not the process" + ) from e def run(self, coro: Any) -> Any: """Run ``coro`` to completion on the loop and return its result. @@ -886,8 +1103,18 @@ def run(self, coro: Any) -> Any: thread's context, so the ambient config ``set_config_context`` set for the node is what the coroutine sees. """ - future = asyncio.run_coroutine_threadsafe(coro, self._running_loop()) - return future.result() + loop, thread = self._running_loop() + future = asyncio.run_coroutine_threadsafe(self._guarded(coro), loop) + while True: + concurrent.futures.wait([future], timeout=self._CHECK_SECONDS) + if future.done(): + return future.result() + if not thread.is_alive(): + future.cancel() + raise RuntimeError( + "The event loop async nodes run on stopped while this node " + "was running (something ended it, as SystemExit does)" + ) _background_loop = _BackgroundLoop() @@ -900,35 +1127,48 @@ def _await_if_coroutine(r: Any) -> Any: return r -def _runnable_config(call: _NodeCall) -> Dict[str, Any]: - """The config a Runnable node is invoked with. +def _is_runnable(obj: Any) -> bool: + """Whether ``obj`` is a LangChain Runnable, whose ``invoke`` injects config.""" + return hasattr(obj, "invoke") and callable(getattr(obj, "invoke")) - Copies before mutating so we never write back into the shared config dict - handed to this activity (immutability). - """ - _config = dict(call.config) if call.config else {} - _config[CONF] = dict(_config.get(CONF) or {}) - thread_id = ( - call.node_input.thread_id - or _config.get("thread_id") - or getattr(call.ctx, "workflow_id", None) - ) - # Expose thread_id in the conventional LangGraph location too, - # so middleware reading config["configurable"]["thread_id"] works. - _config[CONF].setdefault("thread_id", thread_id) - - # Ensure the config has a Runtime object for deep agent middleware nodes - # that require it (runtime injection via RunnableCallable). It also lets - # sandbox/state backends resolve which workflow owns a tool call via - # runtime.execution_info.thread_id. - if CONFIG_KEY_RUNTIME not in _config[CONF]: - _config[CONF][CONFIG_KEY_RUNTIME] = _build_node_runtime( - thread_id, call.ctx, call.node_name, call.stream_writer +def _node_config( + base: Optional[Dict[str, Any]], + *, + thread_id: Optional[str], + ctx: WorkflowActivityContext, + name: str, + streamer: Optional[NodeStreamer], +) -> Dict[str, Any]: + """The config a node or conditional edge runs under, built from ``base``. + + ``base`` is copied, never written back into, as it is the config handed to + the activity. The result carries the thread id where middleware reads it + (``configurable["thread_id"]``), a ``Runtime`` (deep agent middleware + requires one, and sandbox/state backends resolve the owning workflow from + ``runtime.execution_info.thread_id``) and, in a streamed run, the stream + handler. + """ + config = dict(base) if base else {} + config[CONF] = dict(config.get(CONF) or {}) + resolved = thread_id or config.get("thread_id") or getattr(ctx, "workflow_id", None) + config[CONF].setdefault("thread_id", resolved) + if CONFIG_KEY_RUNTIME not in config[CONF]: + config[CONF][CONFIG_KEY_RUNTIME] = _build_node_runtime( + resolved, ctx, name, streamer.writer if streamer else None ) - if call.streamer: - _config = call.streamer.patch_config(_config) + return streamer.patch_config(config) if streamer else config + +def _runnable_config(call: _NodeCall) -> Dict[str, Any]: + """The config a Runnable node is invoked with.""" + config = _node_config( + call.config, + thread_id=call.node_input.thread_id, + ctx=call.ctx, + name=call.node_name, + streamer=call.streamer, + ) # Inject CONFIG_KEY_READ / CONFIG_KEY_SEND so that deepagents # StateBackend (sandbox tools) can read/write the "files" # channel when running inside a Dapr workflow activity. @@ -938,20 +1178,20 @@ def _runnable_config(call: _NodeCall) -> Dict[str, Any]: CONFIG_KEY_SEND, ) - _config[CONF][CONFIG_KEY_READ] = _make_activity_read( + config[CONF][CONFIG_KEY_READ] = _make_activity_read( call.node_input.channel_state, call.pending_sends ) - _config[CONF][CONFIG_KEY_SEND] = call.pending_sends.extend + config[CONF][CONFIG_KEY_SEND] = call.pending_sends.extend except ImportError: pass - return _config + return config -def _invoke_runnable(call: _NodeCall, config: Dict[str, Any]) -> Any: - """Call a Runnable node; one with an async entry returns a coroutine to await.""" - if _has_async_entry(call.node_func): - return call.node_func.ainvoke(call.state, config=config) # type: ignore[attr-defined] - return call.node_func.invoke(call.state, config=config) # type: ignore[attr-defined] +def _invoke_runnable(runnable: Any, value: Any, config: Dict[str, Any]) -> Any: + """Call a Runnable; one with an async entry returns a coroutine to await.""" + if _has_async_entry(runnable): + return runnable.ainvoke(value, config=config) + return runnable.invoke(value, config=config) def _call_plain(call: _NodeCall) -> Any: @@ -971,27 +1211,29 @@ def _plain_node_config(call: _NodeCall) -> Dict[str, Any]: Plain callables get no config injected, so what a node reaches through the ambient config (``get_stream_writer()``, the stream handler and the task metadata of a streamed run) is supplied here. Without a streamer the - runtime carries LangGraph's no-op writer, as ``invoke`` does natively. + runtime carries LangGraph's no-op writer. """ - thread_id = call.node_input.thread_id or getattr(call.ctx, "workflow_id", None) - runtime = _build_node_runtime( - thread_id, call.ctx, call.node_name, call.stream_writer + return _node_config( + {CONF: call.config.get(CONF)}, + thread_id=call.node_input.thread_id, + ctx=call.ctx, + name=call.node_name, + streamer=call.streamer, ) - configurable = {**(call.config.get(CONF) or {}), CONFIG_KEY_RUNTIME: runtime} - config: Dict[str, Any] = {CONF: configurable} - return call.streamer.patch_config(config) if call.streamer else config def _run_node(call: _NodeCall) -> Any: """Run the node and return its raw result.""" node_func = call.node_func - if hasattr(node_func, "invoke") and callable(getattr(node_func, "invoke")): + if _is_runnable(node_func): # A LangChain Runnable (e.g. RunnableCallable): call .invoke() so that # argument injection (runtime, config, store) works. node_config = _runnable_config(call) def run() -> Any: - return _await_if_coroutine(_invoke_runnable(call, node_config)) + return _await_if_coroutine( + _invoke_runnable(node_func, call.state, node_config) + ) ambient = node_config else: @@ -1005,7 +1247,27 @@ def run() -> Any: # get_stream_writer() and the stream handler need it, and a node that calls # get_stream_writer() must find a (no-op) writer when the run is not streamed. with set_config_context(ambient) as ctx_: # type: ignore[arg-type] - return ctx_.run(run) + try: + return ctx_.run(run) + except ParentCommand as exc: + return _parent_command_result(exc, call.node_name) + + +def _parent_command_result(exc: ParentCommand, node_name: str) -> Command: + """The node's result when a subgraph it runs hands over to its parent graph. + + A node inside a subgraph returns ``Command(graph=Command.PARENT)`` to send an + update and a ``goto`` to the graph the subgraph is a node of (the swarm and + supervisor handoff). The subgraph runs here, inside its node's activity, and + LangGraph ends its run with the command addressed to the graph that called it + (``""``) or to the node by name; the command is then what the node returned. + Anything else is addressed above this graph, which has nowhere to send it, so + the error stands, as it does in LangGraph. + """ + cmd = exc.args[0] if exc.args else None + if isinstance(cmd, Command) and cmd.graph in ("", node_name): + return dataclasses.replace(cmd, graph=None) + raise exc def _warn_stream_sink_missing( @@ -1058,7 +1320,7 @@ def _make_streamer( sink_node=None if send is None else send_key(node_input.node_name, send["slot"]), - send_index=None if send is None else send["index"], + send_index=None if send is None else send["slot"], ) @@ -1071,6 +1333,7 @@ def _streamer_for( registry: Optional[StreamSinkRegistry], sink_node: Optional[str] = None, send_index: Optional[int] = None, + branch: Optional[str] = None, ) -> Optional[NodeStreamer]: """A streamer that emits as ``node_name`` at ``step``, or ``None``. @@ -1095,6 +1358,7 @@ def _streamer_for( static=get_node_static_config(node_name), sink_node=sink_node, path=None if send_index is None else (PUSH_TRIGGER, send_index, False), + branch=branch, ) @@ -1168,30 +1432,18 @@ def execute_node_activity( *, stream_registry: Optional[StreamSinkRegistry] = None, ) -> Dict[str, Any]: - """Activity that executes a single LangGraph node. - - This activity: - 1. Gets the node function from the registry - 2. Reconstructs the state from channel values - 3. Executes the node function - 4. Returns the writes produced - - Args: - ctx: The workflow activity context - input_data: Dictionary containing ExecuteNodeInput data - stream_registry: Where to look up the sink of a streamed run - (default: the module's registry). + """Run one node, or one ``Send`` task, and return the writes it produced. - Returns: - ExecuteNodeOutput as a dictionary + The node runs under a config that carries a ``Runtime`` and, when someone + streams the run, the handler that sends its chunks to the stream sink + (looked up in ``stream_registry``, default the module's). An exception + propagates, so Dapr retries the activity. """ node_input = ExecuteNodeInput.from_dict(input_data) node_name = node_input.node_name - # Log activity execution for debugging print(f" [ACTIVITY] Executing node '{node_name}' as Dapr activity", flush=True) - # Get the node function from registry node_func = get_registered_node(node_name) if node_func is None: return ExecuteNodeOutput( @@ -1199,11 +1451,7 @@ def execute_node_activity( error=f"Node '{node_name}' not found in registry", ).to_dict() - # Extract tracing config config = node_input.config or {} - - # Collect side-channel writes from CONFIG_KEY_SEND (used by StateBackend - # to write to the "files" channel from sandbox tools). call = _NodeCall( ctx=ctx, node_input=node_input, @@ -1214,8 +1462,7 @@ def execute_node_activity( pending_sends=[], ) - # Run under the LangSmith child trace so LLM calls nest under the parent - # "LangGraph" trace created by runner.invoke(). + # Under the LangSmith parent trace the runner opened, so LLM calls nest in it. result = _run_with_stream_hooks(call, _langsmith_parent(config)) return _node_output(call, result) @@ -1224,7 +1471,11 @@ def execute_node_activity( def _node_state(node_input: ExecuteNodeInput) -> Any: """What the node takes as input: the channel state, or a ``Send``'s argument.""" if node_input.send is None: - state = _reconstruct_state(node_input.channel_state) + state = _with_managed( + _reconstruct_state(node_input.channel_state), + node_input.recursion_limit, + node_input.step, + ) shape = _node_inputs.get(node_input.node_name) return shape.apply(state) if shape else state return _decode_arg(node_input.send["arg"]) @@ -1245,6 +1496,16 @@ def evaluate_condition( return evaluate_condition +def _branch_key(cond_input: EvaluateConditionInput) -> str: + """The sink key of a conditional edge's chunks, apart from its task's own.""" + task = ( + cond_input.source_node + if cond_input.send_slot is None + else send_key(cond_input.source_node, cond_input.send_slot) + ) + return f"{task}:branch:{cond_input.condition_name}" + + def _call_condition( ctx: WorkflowActivityContext, cond_input: EvaluateConditionInput, @@ -1255,17 +1516,10 @@ def _call_condition( """Call a conditional edge's function and return what it routed to. In a streamed run the function's LLM tokens and ``get_stream_writer()`` - events are sent as its source node's (that is what LangGraph does), keyed + events are sent as its source node's, keyed apart from the node's own chunks. """ - config = dict(cond_input.config or {}) - config[CONF] = dict(config.get(CONF) or {}) - thread_id = ( - cond_input.thread_id - or config.get("thread_id") - or getattr(ctx, "workflow_id", None) - ) - config[CONF].setdefault("thread_id", thread_id) + config = cond_input.config or {} streamer = None if cond_input.step is not None: streamer = _streamer_for( @@ -1275,33 +1529,27 @@ def _call_condition( cond_input.thread_id, config, registry, - # one key per edge: a node's several conditional edges are several - # tasks, and a key they share would read as one retrying - sink_node=f"{cond_input.source_node}:branch:{cond_input.condition_name}", - ) - if CONFIG_KEY_RUNTIME not in config[CONF]: - config[CONF][CONFIG_KEY_RUNTIME] = _build_node_runtime( - thread_id, - ctx, - cond_input.condition_name, - streamer.writer if streamer else None, + # one key per edge and task: a node's several conditional edges, and + # its several Send tasks, are several tasks, and a key they share + # would read as one retrying + sink_node=_branch_key(cond_input), + send_index=cond_input.send_slot, + branch=cond_input.condition_name, ) - if streamer: - config = streamer.patch_config(config) - - # If the condition is a LangChain Runnable (e.g. RunnableCallable from Deep - # Agents branches), call .invoke() so runtime injection works. - is_runnable = hasattr(cond_func, "invoke") and callable( - getattr(cond_func, "invoke") + config = _node_config( + config, + thread_id=cond_input.thread_id, + ctx=ctx, + name=cond_input.condition_name, + streamer=streamer, ) def run() -> Any: - if not is_runnable: + # A LangChain Runnable (e.g. RunnableCallable from Deep Agents + # branches) goes through invoke() so runtime injection works. + if not _is_runnable(cond_func): return _await_if_coroutine(cond_func(state)) - if _is_async_only(cond_func): - # A coroutine; run to completion - return _await_if_coroutine(cond_func.ainvoke(state, config=config)) # type: ignore[attr-defined] - return _await_if_coroutine(cond_func.invoke(state, config=config)) # type: ignore[attr-defined] + return _await_if_coroutine(_invoke_runnable(cond_func, state, config)) # Runnable.invoke only sets the ambient config when tracing, and a plain # function never does: get_stream_writer() and the stream handler need it. @@ -1315,50 +1563,53 @@ def evaluate_condition_activity( *, stream_registry: Optional[StreamSinkRegistry] = None, ) -> Dict[str, Any]: - """Activity that evaluates a conditional edge. + """Evaluate a conditional edge; the output names where it routes, or the error. - Args: - ctx: The workflow activity context - input_data: Dictionary containing EvaluateConditionInput data - stream_registry: The runner's registry, where the sink of a streamed - run is (default: the module's). - - Returns: - EvaluateConditionOutput as a dictionary + ``stream_registry`` is where the sink of a streamed run is (default: the + module's). """ cond_input = EvaluateConditionInput.from_dict(input_data) - # Get the condition function from registry cond_func = get_registered_condition(cond_input.condition_name) if cond_func is None: return EvaluateConditionOutput( error=f"Condition '{cond_input.condition_name}' not found in registry", ).to_dict() - # Reconstruct state from channel values - state: Any = _reconstruct_state(cond_input.channel_state) + state: Any = _with_managed( + _reconstruct_state(cond_input.channel_state), + cond_input.recursion_limit, + cond_input.step, + ) shape = _condition_inputs.get(cond_input.condition_name) if shape: state = shape.apply(state) - # Evaluate under the parent "LangGraph" trace. A Runnable condition (every + # Under the parent "LangGraph" trace. A Runnable condition (every # add_conditional_edges path is one) traces itself, so without a parent # each evaluation lands in LangSmith as a separate top-level trace. - parent = _langsmith_parent(cond_input.config) - if parent: - import langsmith as ls + with _under_parent_trace(cond_input.config): + result = _call_condition(ctx, cond_input, cond_func, state, stream_registry) + return _route(cond_input, result).to_dict() - trace_ctx: Any = ls.tracing_context(parent=parent) - else: - trace_ctx = contextlib.nullcontext() - with trace_ctx: - result = _call_condition(ctx, cond_input, cond_func, state, stream_registry) +def _under_parent_trace(config: Optional[Dict[str, Any]]) -> Any: + """A context that nests LangSmith runs under the run's parent trace, if it has one.""" + parent = _langsmith_parent(config) + if not parent: + return contextlib.nullcontext() + import langsmith as ls + + return ls.tracing_context(parent=parent) + + +def _route(cond_input: EvaluateConditionInput, result: Any) -> EvaluateConditionOutput: + """Where a conditional edge's return value sends the run. - # Result should be a node name, list of node names, or Send objects. - # LangGraph Send objects have a .node attribute with the target node name. - # Any other value goes through the edge's path_map when it has one, as in - # LangGraph: a router may return labels ("continue") rather than node names. + ``result`` is a node name, a list of them, or ``Send`` objects. Any other + value goes through the edge's ``path_map`` when it has one: a router may + return labels (``"continue"``) rather than node names. + """ path_map = cond_input.path_map items = list(result) if isinstance(result, (list, tuple)) else [result] @@ -1377,37 +1628,8 @@ def evaluate_condition_activity( f"Condition '{cond_input.condition_name}' returned {item!r}, " f"which is not in its path_map {sorted(path_map)}" ), - ).to_dict() - - return EvaluateConditionOutput(next_nodes=next_nodes, sends=sends).to_dict() - - -def _get_triggered_nodes( - graph_config: GraphConfig, - channel_state: ChannelState, - pending_nodes: List[str], - step: int, -) -> List[str]: - """Determine which nodes should execute in this step. - - Args: - graph_config: The graph configuration - channel_state: Current channel state - pending_nodes: Nodes explicitly pending execution - step: Current step number - - Returns: - List of node names to execute - """ - # On first step, start with entry point - if step == 0 and not pending_nodes: - return [graph_config.entry_point] - - # Return pending nodes if any - if pending_nodes: - return pending_nodes - - return [] + ) + return EvaluateConditionOutput(next_nodes=next_nodes, sends=sends) def _replay_safe_id(instance_id: Any, index: int, channel: str = "messages") -> str: @@ -1447,7 +1669,7 @@ def _serialize_input( channel: ( _serialize_messages(value, functools.partial(message_id, channel)) if channel == "messages" or _is_messages_channel(channel) - else _serialize_value(value) + else _store_value(value) ) for channel, value in input_data.items() } @@ -1465,24 +1687,48 @@ def _extract_output( Returns: Dictionary of channel name to value """ - values = {**channel_state.values, **_unwritten_defaults(channel_state.values)} + values = { + **{name: _output_value(v) for name, v in channel_state.values.items()}, + **{ + name: _output_json(default) + for name, default in _unwritten_defaults(channel_state.values).items() + }, + } return { channel: values[channel] for channel in output_channels if channel in values } +def _output_value(value: Any) -> Any: + """A stored value as the JSON a run's output carries.""" + return _output_json(decode_value(value)) if is_encoded(value) else value + + +def _output_json(value: Any) -> Any: + """``value`` as JSON for a run's output: a set becomes a (sorted) list. + + The output is JSON, so it cannot hold the set or the object a node wrote; + a nested message or model becomes its dump (see :func:`_serialize_value`). + """ + if isinstance(value, (set, frozenset)): + items = [_output_json(v) for v in value] + try: + return sorted(items) + except TypeError: + return items + if isinstance(value, (list, tuple)): + return [_output_json(v) for v in value] + if isinstance(value, dict): + return {k: _output_json(v) for k, v in value.items()} + return _serialize_value(value) + + class ReducerError(Exception): """A channel's reducer raised while a write was applied; the run fails.""" def _apply_write(channel_state: ChannelState, channel: str, value: Any) -> None: - """Apply a write to a channel, using reducer if available. - - Args: - channel_state: Channel state to update - channel: Channel name - value: Value to write - """ + """Apply a write to a channel, through its reducer if it has one.""" reducer = get_channel_reducer(channel) if reducer and isinstance(value, dict) and set(value) == {OVERWRITE}: # Overwrite replaces the channel's value without calling the reducer. @@ -1491,12 +1737,15 @@ def _apply_write(channel_state: ChannelState, channel: str, value: Any) -> None: return if reducer and channel not in channel_state.values: # The first write is reduced into the channel's default, so add_messages - # gives its messages ids and objects, as it does natively. + # gives its messages ids and objects. if channel in _channel_defaults: channel_state.values[channel] = copy.deepcopy(_channel_defaults[channel]) if reducer and channel in channel_state.values: - # Apply reducer to combine values - current = channel_state.values[channel] + default = _channel_defaults.get(channel) + current = coerce_to_default( + decode_value(channel_state.values[channel]), default + ) + value = coerce_to_default(decode_value(value), default) if _is_messages_channel(channel): # add_messages turns dicts into messages with convert_to_messages, # which files a dump's metadata under additional_kwargs; hand it @@ -1508,19 +1757,19 @@ def _apply_write(channel_state: ChannelState, channel: str, value: Any) -> None: # JSON-compatible (reducers like add_messages may return # BaseMessage objects from dict inputs). reduced = channel_state.values[channel] - if isinstance(reduced, list): + if _is_messages_channel(channel) and isinstance(reduced, list): channel_state.values[channel] = [ _serialize_value(item) for item in reduced ] + else: + channel_state.values[channel] = _store_value(reduced) except Exception as e: # LangGraph fails the run on a reducer that raises; overwriting the # channel would hide the error and differ between a run and a replay. raise ReducerError(f"Reducer failed for channel '{channel}': {e}") from e else: - # No reducer or first value, just set channel_state.values[channel] = value - # Increment version channel_state.versions[channel] = channel_state.versions.get(channel, 0) + 1 @@ -1546,7 +1795,11 @@ def _reconstruct_state(channel_state: ChannelState) -> Dict[str, Any]: state = {} for channel, value in channel_state.values.items(): - # Try to deserialize if needed + if is_encoded(value): + state[channel] = coerce_to_default( + decode_value(value), _channel_defaults.get(channel) + ) + continue if serializer and isinstance(value, (str, bytes)): try: if isinstance(value, str) and value.startswith(('{"', "[")): @@ -1560,8 +1813,7 @@ def _reconstruct_state(channel_state: ChannelState) -> Dict[str, Any]: else: state[channel] = value - # A reducer channel nobody has written yet holds its default, as it does in - # LangGraph: a node reads ``state["log"]`` as ``[]``, not as a missing key. + # A reducer channel nobody has written yet holds its default: a node reads ``state["log"]`` as ``[]``, not as a missing key. state.update(_unwritten_defaults(channel_state.values)) # Reconstruct LangChain message objects from serialized dicts. @@ -1585,9 +1837,15 @@ def _as_message(item: Any) -> Any: A dump (``type`` and the message's own fields) is validated as the message class, which keeps ``response_metadata``, ``usage_metadata`` and the like. ``convert_to_messages`` would take those fields for ``additional_kwargs``. - Anything else (a ``role`` dict, a ``RemoveMessage``) goes through it. + Anything else (a ``role`` dict, a ``RemoveMessage``) goes through it. A + ``ChatMessage`` dump has both a ``type`` (``"chat"``) and a ``role`` of its + own, so a ``role`` next to ``type="chat"`` does not make it the shorthand. """ - if isinstance(item, dict) and "type" in item and "role" not in item: + if ( + isinstance(item, dict) + and "type" in item + and (item["type"] == "chat" or "role" not in item) + ): try: return _MESSAGE_ADAPTER.validate_python(item) except ValidationError: @@ -1621,12 +1879,16 @@ def _result_to_raw_writes(result: Any) -> List[Tuple[str, Any]]: if result is None: return [] - # Handle LangGraph Command objects (used by Deep Agents and newer LangGraph) - # Single Command if isinstance(result, Command): return _command_to_raw_writes(result) - # List of Commands + # A root state has no keys: whatever else the node returns is the channel's + # write, a dict included. + if _is_root_state() and not ( + isinstance(result, list) and result and isinstance(result[0], Command) + ): + return [(ROOT, result)] + if isinstance(result, list) and result and isinstance(result[0], Command): writes: List[Tuple[str, Any]] = [] for cmd in result: @@ -1642,7 +1904,6 @@ def _result_to_raw_writes(result: Any) -> List[Tuple[str, Any]]: if fields is not None: return fields - # Non-dict results - write to a default channel return [("__result__", result)] @@ -1739,6 +2000,13 @@ def _command_to_raw_writes(cmd: Any) -> List[Tuple[str, Any]]: if update is None: return [] + if _is_root_state() and not isinstance(update, dict): + if not ( + isinstance(update, (list, tuple)) + and update + and all(isinstance(i, tuple) and len(i) == 2 for i in update) + ): + return [(ROOT, update)] if isinstance(update, dict): return [(k, v) for k, v in update.items() if _keep_channel(k)] if isinstance(update, (list, tuple)): @@ -1809,7 +2077,7 @@ def _serialize_channel_value( return {OVERWRITE: _serialize_channel_value(channel, inner, message_id)} if _is_messages_channel(channel): return _serialize_messages(value, message_id) - return _serialize_value(value) + return _store_value(value) def _serialize_writes(raw_writes: List[Tuple[str, Any]]) -> List[NodeWrite]: @@ -1831,16 +2099,19 @@ def _result_to_writes(result: Any) -> List[NodeWrite]: return _serialize_writes(_result_to_raw_writes(result)) -def _serialize_value(value: Any) -> Any: - """Serialize a value for storage. +def _store_value(value: Any) -> Any: + """``value`` as it is kept in the channel state: plain JSON, or typed (see values.py). - Args: - value: Value to serialize - - Returns: - Serialized value (JSON-compatible) + What the serializer cannot write falls back to :func:`_serialize_value`. """ - # Handle common types + stored = encode_value(value) + if is_encoded(stored) or is_plain_json(stored): + return stored + return _serialize_value(value) + + +def _serialize_value(value: Any) -> Any: + """``value`` as JSON-compatible data for storage.""" if value is None or isinstance(value, (str, int, float, bool)): return value @@ -1850,7 +2121,6 @@ def _serialize_value(value: Any) -> Any: if isinstance(value, dict): return {k: _serialize_value(v) for k, v in value.items()} - # Try common serialization methods if hasattr(value, "model_dump"): # Pydantic v2 return value.model_dump() @@ -1860,7 +2130,6 @@ def _serialize_value(value: Any) -> Any: if hasattr(value, "to_dict"): return value.to_dict() - # Handle LangChain messages try: from langchain_core.messages import BaseMessage @@ -1874,5 +2143,4 @@ def _serialize_value(value: Any) -> Any: except ImportError: pass - # Fall back to string representation return str(value) From 44cbe3a5e093acd4f61f6bba821b542ecee65f3c Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Wed, 25 Nov 2026 23:57:51 +0100 Subject: [PATCH 11/73] test(langgraph): cover streaming, the SSE endpoint, stream lifecycle and native parity Cover the sink and registry (ordering, backpressure, closed loops, attempt ownership), the control events and how astream() routes them, the node activity hooks, the public streaming names, and the run lifecycle: publishing, disconnects, overlapping streams, failure endings, poll retries and the request rules of the SSE route. The golden tests run the same graphs through LangGraph's own astream and through the runner and compare the "messages", "updates" and "custom" chunks. They cover linear and loop graphs, ReAct agents, subgraphs, joins, Command goto, Send, reducers and state-schema shapes. Shared helpers and the golden harness live in streaming_helpers.py and golden_harness.py. Signed-off-by: Casper Nielsen --- tests/agent/langgraph/golden_harness.py | 285 +++++++ tests/agent/langgraph/streaming_helpers.py | 323 ++++++++ tests/agent/langgraph/test_run_async_shape.py | 47 ++ .../langgraph/test_runner_graph_config.py | 83 ++ .../langgraph/test_runner_invoke_failures.py | 65 ++ tests/agent/langgraph/test_streaming.py | 399 ++++++++++ .../langgraph/test_streaming_activity.py | 281 +++++++ .../agent/langgraph/test_streaming_events.py | 668 ++++++++++++++++ .../agent/langgraph/test_streaming_golden.py | 660 ++++++++++++++++ .../langgraph/test_streaming_golden_state.py | 719 ++++++++++++++++++ .../langgraph/test_streaming_lifecycle.py | 610 +++++++++++++++ .../langgraph/test_streaming_poll_retry.py | 266 +++++++ .../langgraph/test_streaming_public_api.py | 102 +++ tests/agent/langgraph/test_streaming_sink.py | 576 ++++++++++++++ tests/agent/langgraph/test_streaming_sse.py | 588 ++++++++++++++ 15 files changed, 5672 insertions(+) create mode 100644 tests/agent/langgraph/golden_harness.py create mode 100644 tests/agent/langgraph/streaming_helpers.py create mode 100644 tests/agent/langgraph/test_run_async_shape.py create mode 100644 tests/agent/langgraph/test_runner_graph_config.py create mode 100644 tests/agent/langgraph/test_runner_invoke_failures.py create mode 100644 tests/agent/langgraph/test_streaming.py create mode 100644 tests/agent/langgraph/test_streaming_activity.py create mode 100644 tests/agent/langgraph/test_streaming_events.py create mode 100644 tests/agent/langgraph/test_streaming_golden.py create mode 100644 tests/agent/langgraph/test_streaming_golden_state.py create mode 100644 tests/agent/langgraph/test_streaming_lifecycle.py create mode 100644 tests/agent/langgraph/test_streaming_poll_retry.py create mode 100644 tests/agent/langgraph/test_streaming_public_api.py create mode 100644 tests/agent/langgraph/test_streaming_sink.py create mode 100644 tests/agent/langgraph/test_streaming_sse.py diff --git a/tests/agent/langgraph/golden_harness.py b/tests/agent/langgraph/golden_harness.py new file mode 100644 index 00000000..243ddf1f --- /dev/null +++ b/tests/agent/langgraph/golden_harness.py @@ -0,0 +1,285 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The native-vs-Dapr comparison harness the golden streaming tests share. + +Each graph runs through LangGraph's own ``astream`` and through the runner's +``astream`` (the real ``run_async``, ``_poll_workflow`` and ``agent_workflow`` +with a fake workflow client standing in for Dapr); the tests compare the two. +""" + +import json +import operator +import re +import threading +import unittest +from types import SimpleNamespace +from typing import Any, Dict, Iterator, List, Tuple +from unittest import mock + +from dapr.ext.workflow import WorkflowStatus +from langchain_core.language_models import BaseChatModel +from langchain_core.load import dumpd +from langchain_core.messages import ( + AIMessage, + AIMessageChunk, + BaseMessage, + ToolMessage, +) +from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult +from langchain_core.tools import tool +from langgraph.config import get_stream_writer +from langgraph.graph import END, START, StateGraph +from langgraph.graph.message import add_messages +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .streaming_helpers import _collect, _IdCtx, _StreamingModel +from .test_runner import _RunnerTestCase + +# LangGraph names a task by uuid; Dapr by an integer. Only the node matters. +_TASK_NS = re.compile(r"^(\w+):[0-9a-f-]+$") + + +def _normalize(items: List[Tuple[str, Any]]) -> List[Tuple[str, Any]]: + """Make two runs comparable: stable message ids, no task uuids.""" + ids: Dict[str, str] = {} + + def fix(value: Any) -> Any: + if isinstance(value, BaseMessage): + copy = value.model_copy() + if copy.id is not None: + copy.id = ids.setdefault(copy.id, f"msg-{len(ids)}") + return copy + if isinstance(value, str): + return _TASK_NS.sub(r"\1:", value) + if isinstance(value, dict): + return {k: fix(v) for k, v in value.items()} + if isinstance(value, tuple): + return tuple(fix(v) for v in value) + if isinstance(value, list): + return [fix(v) for v in value] + return value + + return [(mode, fix(payload)) for mode, payload in items] + + +MODES = ["messages", "updates", "custom"] + + +ADD_INPUT = {"messages": [{"role": "user", "content": "add 2 and 3"}]} + + +class _FakeWorkflowClient: + """Runs ``agent_workflow`` on a thread when scheduled; the poll sees its state.""" + + def __init__(self, runner: DaprWorkflowGraphRunner) -> None: + self._runner = runner + self._done: Dict[str, Any] = {} + + def schedule_new_workflow(self, *, workflow: Any, input: Any, instance_id: str): + def work() -> None: + from diagrid.agent.langgraph.models import ( + GraphWorkflowInput, + ) + + wf_input = GraphWorkflowInput.from_dict(json.loads(json.dumps(input))) + self._done[instance_id] = _run_input(self._runner, wf_input, instance_id) + + threading.Thread(target=work, daemon=True).start() + + def get_workflow_state(self, *, instance_id: str): + output = self._done.get(instance_id) + if output is None: + return SimpleNamespace( + runtime_status=WorkflowStatus.RUNNING, + serialized_output=None, + serialized_custom_status=None, + failure_details=None, + ) + return SimpleNamespace( + runtime_status=WorkflowStatus.COMPLETED, + serialized_output=json.dumps(output), + serialized_custom_status=None, + failure_details=None, + ) + + +def _run_input(runner: Any, wf_input: Any, instance_id: str) -> Dict[str, Any]: + from diagrid.agent.langgraph.workflow import agent_workflow + + ctx = _IdCtx(runner, instance_id) + workflow = agent_workflow(ctx, json.loads(json.dumps(wf_input.to_dict()))) + result = None + try: + while True: + result = workflow.send(result) + except StopIteration as stop: + return stop.value # type: ignore[no-any-return] + + +@tool +def add(a: int, b: int) -> int: + """Add two numbers.""" + get_stream_writer()({"adding": [a, b]}) + return a + b + + +class _ReactModel(BaseChatModel): + """Asks for ``add(2, 3)`` once, streaming the call, then streams its answer.""" + + @property + def _llm_type(self) -> str: + return "react" + + def bind_tools(self, tools: Any, **kwargs: Any) -> "_ReactModel": + return self + + def _generate(self, messages, stop=None, run_manager=None, **kw): + return ChatResult( + generations=[ChatGeneration(message=AIMessage(content="The sum is 5"))] + ) + + def _stream(self, messages, stop=None, run_manager=None, **kw) -> Iterator: + if any(isinstance(m, ToolMessage) for m in messages): + chunks = [AIMessageChunk(content=t) for t in ("The ", "sum ", "is 5")] + else: + chunks = [ + AIMessageChunk( + content="", + tool_call_chunks=[ + { + "name": "add", + "args": '{"a": 2, "b": 3}', + "id": "c1", + "index": 0, + } + ], + ) + ] + for chunk in chunks: + gen = ChatGenerationChunk(message=chunk) + if run_manager: + run_manager.on_llm_new_token(chunk.content or "", chunk=gen) + yield gen + + +async def _both(compiled: Any, name: str, graph_input: Any) -> Tuple[List, List]: + native = [ + item + async for item in compiled.astream( + graph_input, + { + "configurable": {"thread_id": "t1"}, + "tags": ["x"], + "metadata": {"foo": "bar"}, + }, + stream_mode=MODES, + ) + ] + runner = DaprWorkflowGraphRunner(graph=compiled, name=name) + runner._started = True + runner._workflow_client = _FakeWorkflowClient(runner) # type: ignore[assignment] + with mock.patch("diagrid.agent.langgraph.workflow.when_all", side_effect=list): + ours = await _collect( + runner.astream( + graph_input, + thread_id="t1", + config={"tags": ["x"], "metadata": {"foo": "bar"}}, + workflow_id=f"wf-{name}", + stream_mode=MODES, + poll_interval=0.01, + ) + ) + return native, ours + + +def _wire(items: List[Tuple[str, Any]]) -> List[Tuple[str, Any]]: + return [(mode, dumpd(payload)) for mode, payload in _normalize(items)] + + +class _Golden(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + maxDiff = None + + def _assert_same_sequence(self, native: List, ours: List) -> None: + want, got = _wire(native), _wire(ours) + self.assertEqual([m for m, _ in got], [m for m, _ in want]) + for index, (expected, actual) in enumerate(zip(want, got)): + with self.subTest(chunk=index, mode=expected[0]): + self.assertEqual(actual, expected) + + def _steps(self, items: List) -> List[int]: + return [i[1][1]["langgraph_step"] for i in items if i[0] == "messages"] + + +class _Log(TypedDict, total=False): + log: Annotated[list, operator.add] + + +class _Out(TypedDict, total=False): + out: Annotated[list, operator.add] + + +def _canonical(items: List) -> List[str]: + """The chunks as sorted JSON: nodes of one step run at once, so order is free.""" + return sorted(json.dumps(i, sort_keys=True, default=str) for i in _wire(items)) + + +class _State(TypedDict, total=False): + messages: Annotated[list, add_messages] + count: int + + +def _golden_graph() -> Any: + model = _StreamingModel() + + def chat(state: _State) -> dict: + get_stream_writer()({"progress": 1}) + return {"messages": [model.invoke(state["messages"])]} + + def counter(state: _State) -> dict: + get_stream_writer()("counting") + return {"count": 1} + + def quiet(state: _State) -> None: + return None + + graph = StateGraph(_State) + graph.add_node("chat", chat) + graph.add_node("counter", counter) + graph.add_node("quiet", quiet) + graph.add_edge(START, "chat") + graph.add_edge("chat", "counter") + graph.add_edge("counter", "quiet") + graph.add_edge("quiet", END) + return graph.compile() + + +def _chain(length: int) -> Any: + graph = StateGraph(_Log) + names = [f"n{i}" for i in range(length)] + for name in names: + graph.add_node(name, lambda state, name=name: {"log": [name]}) + graph.add_edge(START, names[0]) + for a, b in zip(names, names[1:]): + graph.add_edge(a, b) + graph.add_edge(names[-1], END) + return graph.compile() + + +def _runner(compiled: Any, name: str) -> DaprWorkflowGraphRunner: + runner = DaprWorkflowGraphRunner(graph=compiled, name=name) + runner._started = True + runner._workflow_client = _FakeWorkflowClient(runner) # type: ignore[assignment] + return runner + + +class _FakeDaprTest(_Golden): + def setUp(self): + super().setUp() + patch = mock.patch( + "diagrid.agent.langgraph.workflow.when_all", side_effect=list + ) + patch.start() + self.addCleanup(patch.stop) diff --git a/tests/agent/langgraph/streaming_helpers.py b/tests/agent/langgraph/streaming_helpers.py new file mode 100644 index 00000000..6073a4e0 --- /dev/null +++ b/tests/agent/langgraph/streaming_helpers.py @@ -0,0 +1,323 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Shared helpers for the streaming tests: fake model, fake run, SSE and serve.""" + +import asyncio +import json +import unittest +from types import SimpleNamespace +from typing import Any, Dict, Iterator, List, Tuple +from unittest import mock + +from dapr.ext.workflow import WorkflowStatus +from langchain_core.language_models import BaseChatModel +from langchain_core.messages import AIMessage, AIMessageChunk, BaseMessage +from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult +from langgraph.config import get_stream_writer +from langgraph.graph import END, START, MessagesState, StateGraph +from langgraph.runtime import Runtime + +from diagrid.agent.core.workflow import runner as core_runner +from diagrid.agent.core.workflow.stream import InProcessSink, StreamClosed, StreamEvent +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.models import ( + ChannelState, + ExecuteNodeInput, + GraphWorkflowOutput, +) +from diagrid.agent.langgraph.streaming import STREAM_RUN_KEY + +from .test_runner import _InlineWorkflowContext, _run, _RunnerTestCase + + +def parse_sse(text: str) -> List[Tuple[str, Any]]: + """``(event, data)`` for each frame of a ``text/event-stream`` body.""" + events = [] + for frame in text.strip().split("\n\n"): + fields = dict(line.split(": ", 1) for line in frame.split("\n")) + events.append((fields["event"], json.loads(fields["data"]))) + return events + + +def serve_app(runner: DaprWorkflowGraphRunner, **serve_kwargs: Any) -> Any: + """The FastAPI app ``runner.serve()`` builds, without starting a server.""" + captured: Dict[str, Any] = {} + with ( + mock.patch("uvicorn.run", lambda app, **kw: captured.update(app=app)), + mock.patch.object(runner, "_setup_telemetry"), + mock.patch.object(runner, "_setup_serve_defaults"), + ): + runner.serve(**serve_kwargs) + return captured["app"] + + +TOKENS = ["Hel", "lo ", "wor", "ld"] + + +class _StreamingModel(BaseChatModel): + """Chat model with a real ``_stream``; ``invoke`` streams when a handler asks.""" + + @property + def _llm_type(self) -> str: + return "fake-streaming" + + def _generate(self, messages: List[BaseMessage], stop=None, run_manager=None, **kw): + return ChatResult( + generations=[ChatGeneration(message=AIMessage("".join(TOKENS)))] + ) + + def _stream( + self, messages: List[BaseMessage], stop=None, run_manager=None, **kw + ) -> Iterator[ChatGenerationChunk]: + for tok in TOKENS: + chunk = ChatGenerationChunk(message=AIMessageChunk(content=tok)) + if run_manager: + run_manager.on_llm_new_token(tok, chunk=chunk) + yield chunk + + +class _Ctx: + def __init__(self, workflow_id: str, task_id: int = 1): + self.workflow_id = workflow_id + self.orchestration_id = workflow_id # what dapr's activity context reads + self.task_id = task_id + + +class _IdCtx(_InlineWorkflowContext): + """Inline context whose activities see a chosen workflow id.""" + + def __init__(self, runner, workflow_id: str): + super().__init__(runner) + self._workflow_id = workflow_id + + def call_activity(self, activity: Any, *, input: Any, retry_policy: Any = None): + activity_name = activity if isinstance(activity, str) else activity.__name__ + self.scheduled.append(activity_name) + fn = ( + self._registry.get_activity(activity) + if isinstance(activity, str) + else activity + ) + out = fn(_Ctx(self._workflow_id), json.loads(json.dumps(input))) + return json.loads(json.dumps(out)) + + +def _chat_graph( + *, + with_runtime: bool = False, + name: str = "stream", + writes: bool = True, + stream_registry: Any = None, +) -> Any: + model = _StreamingModel() + + def plain(state: MessagesState) -> dict: + if writes: + get_stream_writer()({"progress": 1}) + return {"messages": [model.invoke(state["messages"])]} + + def with_rt(state: MessagesState, runtime: Runtime) -> dict: + if writes: + get_stream_writer()({"progress": 1}) + return {"messages": [model.invoke(state["messages"])]} + + graph = StateGraph(MessagesState) + graph.add_node("chat", with_rt if with_runtime else plain) + graph.add_edge(START, "chat") + graph.add_edge("chat", END) + return DaprWorkflowGraphRunner( + graph=graph.compile(), name=name, stream_registry=stream_registry + ) + + +def _fake_run_async(runner: DaprWorkflowGraphRunner): + """Stand-in for ``run_async``: runs the workflow on a worker thread.""" + + async def run_async( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + yield {"type": "workflow_started", "workflow_id": workflow_id} + out = await asyncio.to_thread(_run, runner, input, _IdCtx(runner, workflow_id)) + yield { + "type": "workflow_completed", + "workflow_id": workflow_id, + "output": out.output, + } + + return run_async + + +INPUT = {"messages": [{"role": "user", "content": "hi"}]} + + +async def _collect(agen) -> list: + return [item async for item in agen] + + +_real_sleep = asyncio.sleep + + +async def _instant_sleep(delay: float, *args: Any) -> None: + await _real_sleep(0) + + +class _Unavailable(ConnectionError): + """Stands in for the gRPC UNAVAILABLE error of a restarting sidecar.""" + + +def _state(status: WorkflowStatus, output: Any = None) -> Any: + return SimpleNamespace( + runtime_status=status, + serialized_output=json.dumps(output) if output is not None else None, + serialized_custom_status=None, + failure_details=None, + ) + + +def _completed_state() -> Any: + out = GraphWorkflowOutput( + output={"x": 1}, channel_state=ChannelState(), steps=1, status="completed" + ) + return _state(WorkflowStatus.COMPLETED, out.to_dict()) + + +class _PollCase(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + """A runner whose workflow client answers each status poll from a script.""" + + def _runner(self, polls: List[Any], name: str): + runner = _chat_graph(name=name) + runner._started = True + client = mock.Mock() + client.get_workflow_state.side_effect = polls + runner._workflow_client = client + for patch in ( + mock.patch.object(core_runner, "POLL_RETRY_BASE_SECONDS", 0), + # the SSE path polls every 0.5 s whatever the test asks for + mock.patch.object(core_runner.asyncio, "sleep", _instant_sleep), + ): + patch.start() + self.addCleanup(patch.stop) + return runner, client + + +def _payload( + node: str = "n", step: int = 0, *, streamed: bool = True +) -> Dict[str, Any]: + """The input of an ``execute_node_activity`` call, for a streamed run or not.""" + return ExecuteNodeInput( + node_name=node, + channel_state=ChannelState(), + config={STREAM_RUN_KEY: True} if streamed else None, + step=step, + ).to_dict() + + +FAILED_ERROR = { + "message": "activity blew up", + "error_type": "RuntimeError", + "stack_trace": "Traceback ...", +} + + +def _scripted_run_async(*events: Dict[str, Any]): + """A ``run_async`` that yields ``events`` (``thread_id`` filled in).""" + + async def run_async( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + for event in events: + yield ( + {"thread_id": thread_id, **event} + if event["type"] == "workflow_started" + else dict(event) + ) + + return run_async + + +STARTED = {"type": "workflow_started", "workflow_id": "wf-fixed", "graph_name": "g"} + + +FAILED = {"type": "workflow_failed", "workflow_id": "wf-fixed", "error": FAILED_ERROR} + + +def _completed(status: str, error: Any = None) -> Dict[str, Any]: + return { + "type": "workflow_completed", + "workflow_id": "wf-fixed", + "output": {"x": 1}, + "steps": 2, + "status": status, + **({"error": error} if error else {}), + } + + +class _ScriptedCase(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + def _runner(self, events: List[Dict[str, Any]], name: str): + runner = _chat_graph(name=name) + runner._started = True + patch = mock.patch.object(runner, "run_async", _scripted_run_async(*events)) + patch.start() + self.addCleanup(patch.stop) + return runner + + def _client(self, runner, **serve_kwargs): + from fastapi.testclient import TestClient + + return TestClient(serve_app(runner, **serve_kwargs)) + + +ENDINGS: Dict[str, Dict[str, Any]] = { + "status-error": { + "events": [STARTED, _completed("error", "Node 'x' failed: nope")], + "message": "Node 'x' failed: nope", + }, + "max-steps": { + "events": [STARTED, _completed("max_steps_reached", "Max steps (3) reached")], + "message": "Max steps (3) reached", + }, + "workflow-failed": { + "events": [STARTED, FAILED], + "message": "activity blew up", + "error": FAILED_ERROR, + }, + "workflow-error": { + "events": [ + STARTED, + {"type": "workflow_error", "workflow_id": "wf-fixed", "error": "gone"}, + ], + "message": "gone", + "error_type": "WorkflowError", + }, + "terminated": { + "events": [STARTED, {"type": "workflow_terminated", "workflow_id": "wf-fixed"}], + "message": "Workflow was terminated", + "error_type": "WorkflowTerminated", + }, + "no-final-event": { + "events": [STARTED], + "message": "run ended without a result", + "error_type": "NoResult", + # the id is the one the run was started with, not the scripted one + "workflow_id": None, + }, +} + + +def _event( + attempt: str, seq: int, mode: str = "messages", node: str = "n", step: int = 0 +) -> StreamEvent: + """One chunk of a node's stream; its data names the attempt and sequence.""" + return StreamEvent("wf", step, node, attempt, seq, (), mode, f"{attempt}-{seq}") + + +async def _drain(sink: InProcessSink) -> List[Any]: + """Everything the sink delivers, up to and including its close marker.""" + await asyncio.sleep(0) + items: List[Any] = [] + while True: + item = await sink.get() + items.append(item) + if isinstance(item, StreamClosed): + return items diff --git a/tests/agent/langgraph/test_run_async_shape.py b/tests/agent/langgraph/test_run_async_shape.py new file mode 100644 index 00000000..f881ab1a --- /dev/null +++ b/tests/agent/langgraph/test_run_async_shape.py @@ -0,0 +1,47 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""What the public ``run_async`` yields does not change because streaming exists.""" + +from typing import Any + +from dapr.ext.workflow import WorkflowStatus + +from diagrid.agent.langgraph.models import ChannelState, GraphWorkflowOutput +from diagrid.agent.langgraph.streaming import STREAM_RUN_KEY + +from .streaming_helpers import INPUT, _collect, _PollCase, _state + + +def _done() -> Any: + out = GraphWorkflowOutput( + output={"a": 1}, + channel_state=ChannelState(), + steps=2, + status="completed", + executed=[["chat"], ["tool"]], + ) + return _state(WorkflowStatus.COMPLETED, out.to_dict()) + + +class TestRunAsyncShape(_PollCase): + async def test_a_direct_caller_gets_no_executed_key(self): + runner, _ = self._runner([_done()], "shape-plain") + events = await _collect(runner.run_async(INPUT, poll_interval=0)) + self.assertEqual( + events[-1], + { + "type": "workflow_completed", + "workflow_id": events[-1]["workflow_id"], + "output": {"a": 1}, + "steps": 2, + "status": "completed", + }, + ) + + async def test_the_stream_asks_for_it(self): + runner, _ = self._runner([_done()], "shape-stream") + events = await _collect( + runner.run_async(INPUT, config={STREAM_RUN_KEY: True}, poll_interval=0) + ) + self.assertEqual(events[-1]["executed"], [["chat"], ["tool"]]) diff --git a/tests/agent/langgraph/test_runner_graph_config.py b/tests/agent/langgraph/test_runner_graph_config.py new file mode 100644 index 00000000..93b8e639 --- /dev/null +++ b/tests/agent/langgraph/test_runner_graph_config.py @@ -0,0 +1,83 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The config bound to the graph, and the failures ``invoke`` raises.""" + +import asyncio +from typing import Any, Optional + +from langchain_core.runnables import RunnableConfig +from langgraph.errors import GraphRecursionError +from langgraph.graph import END, START, StateGraph +from typing_extensions import TypedDict + +from .golden_harness import _chain, _FakeDaprTest, _runner +from .streaming_helpers import _collect + + +class _Loop(TypedDict, total=False): + n: int + k: Optional[str] + + +def _loop(steps: int) -> Any: + """A graph that runs ``count`` ``steps`` times and reads ``configurable['k']``.""" + + def count(state: _Loop, config: RunnableConfig) -> dict: + return { + "n": state.get("n", 0) + 1, + "k": (config.get("configurable") or {}).get("k"), + } + + graph = StateGraph(_Loop) + graph.add_node("count", count) + graph.add_edge(START, "count") + graph.add_conditional_edges( + "count", lambda s: "count" if s["n"] < steps else END, ["count", END] + ) + return graph.compile() + + +class TestGraphBoundConfig(_FakeDaprTest): + def _invoke(self, runner: Any, config: Optional[dict] = None) -> Any: + return runner.invoke({}, config=config, poll_interval=0.01) + + async def test_a_bound_recursion_limit_and_configurable_apply(self): + compiled = _loop(150).with_config(recursion_limit=500, configurable={"k": "v"}) + native = compiled.invoke({}) + runner = _runner(compiled, "bound-loop") + out = await asyncio.to_thread(self._invoke, runner) + self.assertEqual((native["n"], native["k"]), (150, "v")) + self.assertEqual((out["n"], out["k"]), (150, "v")) + + async def test_a_bound_configurable_reaches_a_streamed_run(self): + compiled = _loop(2).with_config(configurable={"k": "v"}) + runner = _runner(compiled, "bound-stream") + seen = await _collect( + runner.astream({}, stream_mode=["updates"], poll_interval=0.01) + ) + self.assertEqual( + [c["count"]["k"] for m, c in seen if m == "updates"], ["v"] * 2 + ) + + async def test_a_bound_recursion_limit_below_the_default_is_enforced(self): + compiled = _chain(4).with_config(recursion_limit=3) + with self.assertRaises(GraphRecursionError): + compiled.invoke({"log": []}) + runner = _runner(compiled, "bound-low") + with self.assertRaises(GraphRecursionError): + await _collect(runner.astream({"log": []}, poll_interval=0.01)) + + async def test_the_caller_config_wins_over_the_bound_one(self): + compiled = _chain(4).with_config(recursion_limit=3, configurable={"k": "v"}) + runner = _runner(compiled, "bound-override") + out = await asyncio.to_thread( + self._invoke, runner, {"recursion_limit": 50, "configurable": {"j": "w"}} + ) + self.assertEqual(len(out["log"]), 4) + + async def test_the_callers_config_is_not_changed(self): + runner = _runner(_chain(1), "bound-copy") + config = {"tags": ["t"]} + await asyncio.to_thread(self._invoke, runner, config) + self.assertEqual(config, {"tags": ["t"]}) diff --git a/tests/agent/langgraph/test_runner_invoke_failures.py b/tests/agent/langgraph/test_runner_invoke_failures.py new file mode 100644 index 00000000..260d1a96 --- /dev/null +++ b/tests/agent/langgraph/test_runner_invoke_failures.py @@ -0,0 +1,65 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``invoke`` raises for a run that did not finish, as native ``invoke`` does.""" + +import asyncio +import operator +from typing import Any, Optional + +from langgraph.errors import GraphRecursionError +from langgraph.graph import END, START, StateGraph +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph.streaming import GraphRunError + +from .golden_harness import _chain, _FakeDaprTest, _runner + + +class TestInvokeFailures(_FakeDaprTest): + def _invoke(self, runner: Any, config: Optional[dict] = None) -> Any: + return runner.invoke({"log": []}, config=config, poll_interval=0.01) + + async def test_a_run_cut_by_the_recursion_limit_raises_like_native(self): + compiled = _chain(3) + runner = _runner(compiled, "invoke-limit") + for limit, ok in ((2, False), (3, False), (4, True), (5, True)): + with self.subTest(limit=limit): + config = {"recursion_limit": limit} + if ok: + out = await asyncio.to_thread(self._invoke, runner, config) + self.assertEqual(out["log"], ["n0", "n1", "n2"]) + else: + with self.assertRaises(GraphRecursionError): + compiled.invoke({"log": []}, config) + with self.assertRaises(GraphRecursionError) as ctx: + await asyncio.to_thread(self._invoke, runner, config) + self.assertIsInstance(ctx.exception, GraphRunError) + + async def test_a_limit_bound_to_the_graph_raises_too(self): + runner = _runner(_chain(4).with_config(recursion_limit=3), "invoke-bound") + with self.assertRaises(GraphRecursionError): + await asyncio.to_thread(self._invoke, runner) + + async def test_a_failed_run_raises_instead_of_returning_a_partial_output(self): + class State(TypedDict, total=False): + log: Annotated[list, operator.add] + + graph = StateGraph(State) + graph.add_node("a", lambda s: {"log": ["a"]}) + graph.add_node("b", lambda s: {"log": ["b"]}) + graph.add_edge(START, "a") + graph.add_conditional_edges("a", lambda s: "nowhere", {"go": "b"}) + graph.add_edge("b", END) + runner = _runner(graph.compile(), "invoke-fail") + with self.assertRaises(GraphRunError) as ctx: + await asyncio.to_thread(self._invoke, runner) + self.assertNotIsInstance(ctx.exception, GraphRecursionError) + self.assertIn("nowhere", str(ctx.exception)) + + async def test_a_config_that_cannot_travel_is_refused(self): + runner = _runner(_chain(1), "invoke-bad-config") + with self.assertRaisesRegex(ValueError, "callbacks"): + await asyncio.to_thread(self._invoke, runner, {"callbacks": [object()]}) + with self.assertRaisesRegex(ValueError, "recursion_limit"): + await asyncio.to_thread(self._invoke, runner, {"recursion_limit": 0}) diff --git a/tests/agent/langgraph/test_streaming.py b/tests/agent/langgraph/test_streaming.py new file mode 100644 index 00000000..d4977229 --- /dev/null +++ b/tests/agent/langgraph/test_streaming.py @@ -0,0 +1,399 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``astream`` and the streamed run it drives: which chunks arrive and in what +shape, the thread id of a run, and what is done with the LangGraph config the +caller hands in.""" + +import asyncio +import unittest +from typing import Any, Dict, List +from unittest import mock + +from langchain_core.messages import AIMessage +from langgraph.errors import GraphRecursionError +from langgraph.graph import END, START, MessagesState, StateGraph +from langgraph.types import Command + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.models import ChannelState, ExecuteNodeInput +from diagrid.agent.langgraph.streaming import GraphRunError, StreamControl +from diagrid.agent.langgraph.workflow import execute_node_activity + +from .golden_harness import _chain, _FakeDaprTest, _runner +from .streaming_helpers import ( + INPUT, + TOKENS, + _chat_graph, + _collect, + _Ctx, + _fake_run_async, + _StreamingModel, +) +from .test_runner import _run, _RunnerTestCase + + +class TestAstream(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + def _runner(self, **kw) -> DaprWorkflowGraphRunner: + runner = _chat_graph(**kw) + runner._started = True + self._patch = mock.patch.object(runner, "run_async", _fake_run_async(runner)) + self._patch.start() + self.addCleanup(self._patch.stop) + return runner + + async def test_messages_arrive_in_order_for_both_node_kinds(self): + for with_runtime in (False, True): + self.setUp() + runner = self._runner(with_runtime=with_runtime, name=f"s-{with_runtime}") + chunks = await _collect( + runner.astream(INPUT, workflow_id="wf-a", stream_mode="messages") + ) + # LangChain closes a stream with one empty chunk; only text counts. + texts = [c[0].content for c in chunks] + self.assertEqual([t for t in texts if t], TOKENS, with_runtime) + meta = chunks[0][1] + self.assertEqual(meta["langgraph_node"], "chat") + self.assertEqual(meta["langgraph_step"], 1) # as native Pregel + self.assertIn("langgraph_checkpoint_ns", meta) + + async def test_updates_and_custom_with_mode_list(self): + runner = self._runner() + items = await _collect( + runner.astream(INPUT, workflow_id="wf-b", stream_mode=["updates", "custom"]) + ) + self.assertEqual(items[0], ("custom", {"progress": 1})) + mode, update = items[-1] + self.assertEqual(mode, "updates") + self.assertEqual(list(update), ["chat"]) + self.assertEqual(len(items), 2) # no messages requested + + async def test_single_mode_yields_bare_chunks(self): + runner = self._runner() + items = await _collect( + runner.astream(INPUT, workflow_id="wf-c", stream_mode="custom") + ) + self.assertEqual(items, [{"progress": 1}]) + + async def test_unsupported_mode_and_subgraphs(self): + runner = self._runner() + with self.assertRaises(ValueError): + await _collect(runner.astream(INPUT, stream_mode="values")) + with self.assertRaises(NotImplementedError): + await _collect(runner.astream(INPUT, subgraphs=True)) + + async def test_no_events_leak_across_runs(self): + runner = self._runner() + + async def one(wf: str): + return await _collect( + runner.astream(INPUT, workflow_id=wf, stream_mode="messages") + ) + + # _run patches when_all per call; two threads doing it at once race, + # so hold one patch open for the whole overlap. + with mock.patch("diagrid.agent.langgraph.workflow.when_all", side_effect=list): + a, b = await asyncio.gather(one("wf-1"), one("wf-2")) + # Broadcasting every chunk to every open run would double these. + for run in (a, b): + texts = [c[0].content for c in run] + self.assertEqual([t for t in texts if t], TOKENS) + # The runner opens its sinks in its own registry, not the default one. + self.assertIsNone(runner.stream_registry.get("wf-1")) + self.assertIsNone(runner.stream_registry.get("wf-2")) + + async def test_node_returned_messages_stream_without_an_llm(self): + def tool(state: MessagesState) -> dict: + return {"messages": [AIMessage("from-node", id="m1")]} + + graph = StateGraph(MessagesState) + graph.add_node("tool", tool) + graph.add_edge(START, "tool") + graph.add_edge("tool", END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="node-msg") + runner._started = True + with mock.patch.object(runner, "run_async", _fake_run_async(runner)): + chunks = await _collect( + runner.astream(INPUT, workflow_id="wf-m", stream_mode="messages") + ) + self.assertEqual([c[0].content for c in chunks], ["from-node"]) + self.assertEqual(chunks[0][1]["langgraph_node"], "tool") + + async def test_repeated_channel_writes_are_all_in_updates(self): + def many(state: MessagesState) -> list: + return [ + Command(update={"messages": [AIMessage("a", id="a")]}), + Command(update={"messages": [AIMessage("b", id="b")]}), + ] + + graph = StateGraph(MessagesState) + graph.add_node("n", many) + graph.add_edge(START, "n") + graph.add_edge("n", END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="multi") + runner._started = True + with mock.patch.object(runner, "run_async", _fake_run_async(runner)): + items = await _collect( + runner.astream(INPUT, workflow_id="wf-u", stream_mode="updates") + ) + update = items[-1]["n"] + self.assertEqual(len(update), 2) + self.assertEqual([u["messages"][0].content for u in update], ["a", "b"]) + + async def test_post_agent_run_with_stream_returns_sse(self): + from fastapi.testclient import TestClient + + runner = self._runner() + captured: dict = {} + with mock.patch("uvicorn.run", lambda app, **kw: captured.update(app=app)): + with ( + mock.patch.object(runner, "_setup_telemetry"), + mock.patch.object(runner, "_setup_serve_defaults"), + ): + runner.serve() + # No context manager: the lifespan (runtime start) is not run. + client = TestClient(captured["app"]) + resp = client.post("/agent/run", json={"task": "hi", "stream": True}) + self.assertEqual(resp.status_code, 200) + self.assertTrue(resp.headers["content-type"].startswith("text/event-stream")) + self.assertIn("event: messages", resp.text) + self.assertIn("event: workflow_completed", resp.text) + + async def test_async_only_node_streams_tokens(self): + model = _StreamingModel() + + async def achat(state: MessagesState) -> dict: + return {"messages": [await model.ainvoke(state["messages"])]} + + graph = StateGraph(MessagesState) + graph.add_node("chat", achat) + graph.add_edge(START, "chat") + graph.add_edge("chat", END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="async-only") + runner._started = True + with mock.patch.object(runner, "run_async", _fake_run_async(runner)): + chunks = await _collect( + runner.astream(INPUT, workflow_id="wf-async", stream_mode="messages") + ) + texts = [c[0].content for c in chunks] + self.assertEqual([t for t in texts if t], TOKENS) + + async def test_serve_stream_yields_event_pairs(self): + runner = self._runner() + pairs = await _collect(runner._serve_stream({"task": "hi"}, "sess")) + names = [name for name, _ in pairs] + self.assertEqual(names[-1], "workflow_completed") + self.assertGreaterEqual(names.count("messages"), len(TOKENS)) + self.assertIn("updates", names) + self.assertIn("custom", names) + self.assertEqual(pairs[-1][1]["type"], "workflow_completed") + + async def test_sse_frames_are_numbered_and_terminated(self): + from fastapi.testclient import TestClient + + runner = self._runner() + captured: dict = {} + with ( + mock.patch("uvicorn.run", lambda app, **kw: captured.update(app=app)), + mock.patch.object(runner, "_setup_telemetry"), + mock.patch.object(runner, "_setup_serve_defaults"), + ): + runner.serve() + resp = TestClient(captured["app"]).post( + "/agent/run", json={"task": "hi", "stream": True} + ) + frames = resp.text.split("\n\n")[:-1] + self.assertEqual( + [f.split("\n")[0] for f in frames], + [f"id: {n}" for n in range(1, len(frames) + 1)], + ) + self.assertEqual(frames[-1].split("\n")[1], "event: workflow_completed") + self.assertTrue(resp.text.endswith("\n\n")) + + +class TestStreamingOff(_RunnerTestCase): + def test_no_sink_means_no_streaming_and_same_output(self): + # The node calls get_stream_writer(), as a graph that streams does. + runner = _chat_graph(name="off", writes=True) + self.assertIsNone(runner.stream_registry.get("wf-test")) + out = _run(runner, INPUT) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["messages"][-1]["content"], "".join(TOKENS)) + + +CFG = {"configurable": {"thread_id": "CFG-T"}} + + +class TestThreadId(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + def _runner(self, name: str): + """A runner whose run_async runs the node as the workflow would.""" + runner = _chat_graph(name=name) + runner._started = True + self.seen: Dict[str, Any] = {} + + async def run_async( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + self.seen.update(thread_id=thread_id, config=dict(config or {})) + yield {"type": "workflow_started", "workflow_id": workflow_id} + payload = ExecuteNodeInput( + node_name="chat", + channel_state=ChannelState( + values=runner._serialize_input(input), versions={} + ), + config=config, + thread_id=thread_id, + step=0, + ).to_dict() + await asyncio.to_thread( + execute_node_activity, + _Ctx(workflow_id), + payload, + stream_registry=runner.stream_registry, + ) + yield { + "type": "workflow_completed", + "workflow_id": workflow_id, + "steps": 1, + "status": "completed", + "executed": [["chat"]], + } + + patch = mock.patch.object(runner, "run_async", run_async) + patch.start() + self.addCleanup(patch.stop) + return runner + + async def test_config_is_positional_and_gives_the_thread_id(self): + runner = self._runner("tid-cfg") + controls: List[StreamControl] = [] + items = await _collect( + runner.astream( + INPUT, CFG, stream_mode=["messages"], on_control=controls.append + ) + ) + (started,) = [c for c in controls if c.kind == "workflow_started"] + self.assertEqual(started.data["thread_id"], "CFG-T") + self.assertEqual(self.seen["thread_id"], "CFG-T") + self.assertEqual( + {meta["thread_id"] for mode, (_, meta) in items if mode == "messages"}, + {"CFG-T"}, + ) + + async def test_an_explicit_thread_id_wins_and_the_run_has_just_one(self): + runner = self._runner("tid-arg") + items = await _collect( + runner.astream(INPUT, CFG, thread_id="ARG-T", stream_mode=["messages"]) + ) + self.assertEqual(self.seen["thread_id"], "ARG-T") + self.assertEqual(self.seen["config"]["configurable"]["thread_id"], "ARG-T") + self.assertEqual( + {meta["thread_id"] for mode, (_, meta) in items if mode == "messages"}, + {"ARG-T"}, + ) + + async def test_the_callers_config_is_not_modified(self): + runner = self._runner("tid-keep") + cfg = {"configurable": {"user": "u"}} + await _collect(runner.astream(INPUT, cfg, thread_id="T")) + self.assertEqual(cfg, {"configurable": {"user": "u"}}) + + async def test_without_either_a_thread_id_is_generated(self): + runner = self._runner("tid-gen") + await _collect(runner.astream(INPUT, {"tags": ["t"]})) + self.assertTrue(self.seen["thread_id"]) + self.assertEqual( + self.seen["config"]["configurable"]["thread_id"], self.seen["thread_id"] + ) + + +class _Handler: + """Stands in for a LangChain callback handler: not JSON.""" + + +class TestConfigThatCannotCrossToTheWorkflow(_FakeDaprTest): + def _astream(self, config: Any) -> Any: + runner = _runner(_chain(1), "config-json") + client = mock.Mock() + runner._workflow_client = client + return runner, client, runner.astream({"log": []}, config=config) + + async def test_callbacks_are_refused_before_a_run_starts(self): + runner, client, stream = self._astream({"callbacks": [_Handler()]}) + with self.assertRaisesRegex(ValueError, "callbacks"): + await asyncio.wait_for(_collect(stream), 5) + client.schedule_new_workflow.assert_not_called() + + async def test_a_configurable_value_that_is_not_json_names_its_key(self): + runner, client, stream = self._astream({"configurable": {"db": _Handler()}}) + with self.assertRaisesRegex(ValueError, "db"): + await asyncio.wait_for(_collect(stream), 5) + client.schedule_new_workflow.assert_not_called() + + async def test_json_config_is_fine(self): + runner = _runner(_chain(1), "config-ok") + items = await _collect( + runner.astream( + {"log": []}, + config={"tags": ["t"], "metadata": {"a": 1}}, + stream_mode=["updates"], + poll_interval=0.01, + ) + ) + self.assertEqual([m for m, _ in items], ["updates"]) + + +class TestRecursionLimit(_FakeDaprTest): + """``config["recursion_limit"]`` bounds the run as it bounds native LangGraph.""" + + async def test_matches_native_at_every_limit(self): + compiled = _chain(3) + runner = _runner(compiled, "config-recursion") + for limit in range(1, 6): + with self.subTest(limit=limit): + try: + compiled.invoke({"log": []}, {"recursion_limit": limit}) + native_ok = True + except GraphRecursionError: + native_ok = False + seen: List[Any] = [] + stream = runner.astream( + {"log": []}, + config={"recursion_limit": limit}, + workflow_id=f"wf-rl-{limit}", + stream_mode=["updates"], + poll_interval=0.01, + ) + try: + seen = await asyncio.wait_for(_collect(stream), 10) + ours_ok = True + except GraphRunError: + ours_ok = False + self.assertEqual(ours_ok, native_ok) + if ours_ok: + self.assertEqual(len(seen), 3) + + async def test_a_run_cut_by_the_limit_raises_langgraphs_recursion_error(self): + runner = _runner(_chain(4), "config-recursion-type") + stream = runner.astream( + {"log": []}, + config={"recursion_limit": 4}, + stream_mode=["updates"], + poll_interval=0.01, + ) + with self.assertRaises(GraphRecursionError) as ctx: + await asyncio.wait_for(_collect(stream), 10) + self.assertIsInstance(ctx.exception, GraphRunError) + self.assertEqual(ctx.exception.final["status"], "max_steps_reached") + + async def test_a_bad_limit_is_refused(self): + runner = _runner(_chain(1), "config-bad-limit") + for bad in (0, -1, "5", 2.5, True): + with self.subTest(limit=bad): + with self.assertRaisesRegex(ValueError, "recursion_limit"): + await asyncio.wait_for( + _collect( + runner.astream({"log": []}, config={"recursion_limit": bad}) + ), + 5, + ) diff --git a/tests/agent/langgraph/test_streaming_activity.py b/tests/agent/langgraph/test_streaming_activity.py new file mode 100644 index 00000000..097d7e2f --- /dev/null +++ b/tests/agent/langgraph/test_streaming_activity.py @@ -0,0 +1,281 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""What ``execute_node_activity`` streams, and what it must survive. + +The streaming side of a node activity: its failures, a writer with nothing +listening, the ``messages`` metadata native ``astream`` puts there, and a +langgraph release that moves its private message handler.""" + +import asyncio +import inspect +import sys +import unittest +from typing import Any, Dict, List +from unittest import mock + +from langgraph.graph import END, START, MessagesState, StateGraph + +from diagrid.agent.core.workflow.stream import ( + StreamClosed, + StreamEvent, + StreamSinkRegistry, + default_registry, +) +from diagrid.agent.langgraph.models import ChannelState, ExecuteNodeInput +from diagrid.agent.langgraph.streaming import ( + STREAM_RUN_KEY, + NodeStreamer, + _own_node_handler_class, +) +from diagrid.agent.langgraph.workflow import ( + clear_registries, + execute_node_activity, + register_node, +) + +from .streaming_helpers import INPUT, TOKENS, _chat_graph, _Ctx, _IdCtx, _payload +from .test_runner import _run, _RunnerTestCase + +# The two ways a node can be written: with and without a ``runtime`` argument. +NODE_KINDS = {"plain": False, "runtime": True} + + +class _RecordingStreamer(NodeStreamer): + created: List["_RecordingStreamer"] = [] + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.created.append(self) + + +class TestNodeThatRaises(unittest.IsolatedAsyncioTestCase): + def setUp(self): + clear_registries() + self.addCleanup(clear_registries) + _RecordingStreamer.created = [] + patch = mock.patch( + "diagrid.agent.langgraph.workflow.NodeStreamer", _RecordingStreamer + ) + patch.start() + self.addCleanup(patch.stop) + + async def _fail(self, node: Any, name: str = "boom") -> _RecordingStreamer: + register_node(name, node) + registry = StreamSinkRegistry() + registry.open("wf-err") + with self.assertRaises(RuntimeError): + await asyncio.to_thread( + execute_node_activity, + _Ctx("wf-err"), + _payload(name, streamed=False), + stream_registry=registry, + ) + (streamer,) = _RecordingStreamer.created + return streamer + + async def test_the_message_handler_is_told_the_node_failed(self): + def boom(state): + raise RuntimeError("nope") + + streamer = await self._fail(boom) + # StreamMessagesHandler keeps per-run state from on_chain_start until + # the matching on_chain_end / on_chain_error; none may be left behind. + self.assertEqual(streamer._handler.metadata, {}) + + async def test_same_for_a_runnable_node(self): + graph = StateGraph(MessagesState) + + def boom(state: MessagesState) -> dict: + raise RuntimeError("nope") + + graph.add_node("boom", boom) + graph.add_edge(START, "boom") + graph.add_edge("boom", END) + runnable = graph.compile().nodes["boom"].bound + streamer = await self._fail(runnable) + self.assertEqual(streamer._handler.metadata, {}) + + async def test_success_also_leaves_no_state(self): + register_node("fine", lambda state: {"x": 1}) + registry = StreamSinkRegistry() + registry.open("wf-ok") + await asyncio.to_thread( + execute_node_activity, + _Ctx("wf-ok"), + _payload("fine", streamed=False), + stream_registry=registry, + ) + (streamer,) = _RecordingStreamer.created + self.assertEqual(streamer._handler.metadata, {}) + + +class TestWriterWithoutAStreamer(_RunnerTestCase): + def _plain_run(self, with_runtime: bool) -> None: + runner = _chat_graph(with_runtime=with_runtime, writes=True) + out = _run(runner, INPUT, _IdCtx(runner, "wf-plain")) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["messages"][-1]["content"], "".join(TOKENS)) + + def _streamed_run_without_a_sink(self, with_runtime: bool) -> None: + registry = StreamSinkRegistry() + runner = _chat_graph( + with_runtime=with_runtime, writes=True, stream_registry=registry + ) + payload = ExecuteNodeInput( + node_name="chat", + channel_state=ChannelState( + values=runner._serialize_input(INPUT), versions={} + ), + config={STREAM_RUN_KEY: True}, + ).to_dict() + # the run's sink is in no registry this activity can see: a default one + # that does hold it must not be what answers + wf = f"wf-elsewhere-{with_runtime}" + loop = asyncio.new_event_loop() + self.addCleanup(loop.close) + + async def hold() -> None: + default_registry.open(wf) + + loop.run_until_complete(hold()) + self.addCleanup(default_registry.close, wf) + with self.assertLogs("diagrid.agent.langgraph.workflow", level="WARNING"): + out = execute_node_activity(_Ctx(wf), payload, stream_registry=registry) + self.assertIsNone(out.get("error")) + self.assertTrue(out["writes"]) + + def test_a_node_in_a_run_that_is_not_streamed(self): + for kind, with_runtime in NODE_KINDS.items(): + with self.subTest(node=kind): + self.setUp() + self._plain_run(with_runtime) + + def test_a_node_in_a_streamed_run_with_no_sink(self): + for kind, with_runtime in NODE_KINDS.items(): + with self.subTest(node=kind): + self.setUp() + self._streamed_run_without_a_sink(with_runtime) + + +CONFIG = { + STREAM_RUN_KEY: True, + "thread_id": "t1", + "metadata": {"foo": "bar"}, + "tags": ["x"], + "configurable": {"user": "u-7", "__private": "no", "obj": {"a": 1}}, +} + + +async def _messages_metadata(runner: Any, registry: StreamSinkRegistry) -> List[Dict]: + sink = registry.open("wf-meta") + payload = ExecuteNodeInput( + node_name="chat", + channel_state=ChannelState(values=runner._serialize_input(INPUT), versions={}), + config=CONFIG, + thread_id="t1", + step=0, + ).to_dict() + out = await asyncio.to_thread( + execute_node_activity, _Ctx("wf-meta"), payload, stream_registry=registry + ) + assert not out.get("error"), out + sink.close() + items = [] + while True: + item = await sink.get() + if isinstance(item, StreamClosed): + break + if isinstance(item, StreamEvent) and item.mode == "messages": + items.append(item.data[1]) + return items + + +class TestMessagesMetadata(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def _check(self, with_runtime: bool) -> None: + registry = StreamSinkRegistry() + runner = _chat_graph(with_runtime=with_runtime, stream_registry=registry) + metadata = await _messages_metadata(runner, registry) + self.assertTrue(metadata) + for meta in metadata: + self.assertEqual(meta["thread_id"], "t1") + self.assertEqual(meta["foo"], "bar") + # configurable values native copies into metadata: primitives only, + # never the private ones. + self.assertEqual(meta["user"], "u-7") + self.assertNotIn("__private", meta) + self.assertNotIn("obj", meta) + self.assertEqual(meta["langgraph_node"], "chat") + + async def test_the_metadata_native_puts_there(self): + for kind, with_runtime in NODE_KINDS.items(): + with self.subTest(node=kind): + self.setUp() + await self._check(with_runtime) + + +LOGGER = "diagrid.agent.langgraph.streaming" + + +class TestHandlerContract(unittest.TestCase): + """CI notices a langgraph that changes what the streamer relies on.""" + + def test_the_real_handler_is_built_the_way_the_streamer_builds_it(self): + from langgraph.pregel._messages import StreamMessagesHandler + + params = list(inspect.signature(StreamMessagesHandler).parameters) + self.assertEqual(params[:2], ["stream", "subgraphs"]) + streamer = NodeStreamer( + mock.Mock(), workflow_id="wf", step=0, node="n", task_id=1 + ) + self.assertIsNotNone(streamer._messages_handler()) + self.assertEqual(len(streamer.callbacks()), 1) + + +class TestHandlerDrift(unittest.IsolatedAsyncioTestCase): + def setUp(self): + clear_registries() + self.addCleanup(clear_registries) + register_node("n", lambda state: {"x": 1}) + NodeStreamer._handler_failure_logged = False + self.addCleanup(setattr, NodeStreamer, "_handler_failure_logged", False) + # the handler class is built once; build it again under each patch + _own_node_handler_class.cache_clear() + self.addCleanup(_own_node_handler_class.cache_clear) + + async def _run_streamed(self, wf: str) -> List[StreamEvent]: + registry = StreamSinkRegistry() + sink = registry.open(wf) + out = await asyncio.to_thread( + execute_node_activity, _Ctx(wf), _payload(), stream_registry=registry + ) + self.assertIsNone(out.get("error")) + self.assertEqual(out["writes"][0]["value"], 1) + sink.close() + items: List[Any] = [] + while True: + item = await sink.get() + if isinstance(item, StreamEvent): + items.append(item) + else: + return items + + async def _assert_run_survives(self) -> None: + with self.assertLogs(LOGGER, level="ERROR") as logs: + items = await self._run_streamed("wf-drift-1") + await self._run_streamed("wf-drift-2") + # the node ran, its update still streams, and the cause is logged once + self.assertEqual([i.mode for i in items], ["updates"]) + self.assertEqual(len(logs.records), 1) + self.assertIn("messages", logs.records[0].getMessage()) + + async def test_a_moved_module(self): + with mock.patch.dict(sys.modules, {"langgraph.pregel._messages": None}): + await self._assert_run_survives() + + async def test_a_changed_signature(self): + def renamed(stream: Any) -> Any: # takes one argument, as if it changed + raise AssertionError("not reached") + + with mock.patch("langgraph.pregel._messages.StreamMessagesHandler", renamed): + await self._assert_run_survives() diff --git a/tests/agent/langgraph/test_streaming_events.py b/tests/agent/langgraph/test_streaming_events.py new file mode 100644 index 00000000..aa62c28f --- /dev/null +++ b/tests/agent/langgraph/test_streaming_events.py @@ -0,0 +1,668 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""How a streamed run ends and what its control events say: failures, a stream +that did not reach this process, and how ``astream`` routes the control events.""" + +import asyncio +import json +import re +import unittest +from types import SimpleNamespace +from typing import Any, Dict, List, Sequence +from unittest import mock + +from dapr.ext.workflow import WorkflowStatus +from langchain_core.messages import AIMessageChunk +from langgraph.graph import END, START, StateGraph +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.core.workflow import stream +from diagrid.agent.core.workflow.stream import ( + CONTROL_MODES, + NODE_RESET, + STREAM_UNAVAILABLE, + UPDATES, + WORKFLOW_STARTED, + InProcessSink, + StreamClosed, + StreamEvent, +) +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.models import ChannelState, GraphWorkflowOutput +from diagrid.agent.langgraph.stream_events import route_astream_item +from diagrid.agent.langgraph.streaming import ( + STREAM_RUN_KEY, + GraphRunError, + NodeStreamer, + StreamControl, + stream_unavailable_event, +) +from diagrid.agent.langgraph.workflow import ( + clear_registries, + execute_node_activity, + register_node, +) + +from .streaming_helpers import ( + ENDINGS, + FAILED, + FAILED_ERROR, + INPUT, + STARTED, + _chat_graph, + _collect, + _completed, + _Ctx, + _payload, + _ScriptedCase, + parse_sse, + serve_app, +) +from .test_runner import _run, _RunnerTestCase + + +class TestEveryFailureEnding(_ScriptedCase): + """A run that does not end in a result is a failure, in both transports.""" + + async def test_astream_raises(self): + for name, row in ENDINGS.items(): + with self.subTest(ending=name): + self.setUp() + runner = self._runner(row["events"], f"end-raise-{name}") + with self.assertRaisesRegex(GraphRunError, re.escape(row["message"])): + await _collect(runner.astream(INPUT, stream_mode="updates")) + + async def test_sse_ends_with_workflow_failed(self): + for name, row in ENDINGS.items(): + with self.subTest(ending=name): + self.setUp() + runner = self._runner(row["events"], f"end-sse-{name}") + resp = self._client(runner).post( + "/agent/run", json={"task": "hi", "stream": True, "thread_id": "t9"} + ) + event, data = parse_sse(resp.text)[-1] + self.assertEqual(event, "workflow_failed") + self.assertEqual(data["thread_id"], "t9") + self.assertEqual(data["error"]["message"], row["message"]) + if "error_type" in row: + self.assertEqual(data["error"]["error_type"], row["error_type"]) + if "error" in row: + self.assertEqual(data["error"], row["error"]) + if row.get("workflow_id", "wf-fixed"): + self.assertEqual(data["workflow_id"], "wf-fixed") + else: + self.assertTrue(data["workflow_id"]) + + +class TestStatusErrorIsAFailure(_ScriptedCase): + async def test_completed_status_still_completes(self): + runner = self._runner([STARTED, _completed("completed")], "st-ok") + resp = self._client(runner).post( + "/agent/run", json={"task": "hi", "stream": True} + ) + self.assertEqual(parse_sse(resp.text)[-1][0], "workflow_completed") + + async def test_real_poll_path_keeps_the_workflow_error(self): + """``run_async`` itself must carry the output's error to the caller.""" + runner = _chat_graph(name="st-poll") + runner._started = True + output = GraphWorkflowOutput( + output={}, + channel_state=ChannelState(), + steps=0, + status="error", + error="Node 'chat' not found in registry", + ) + client = mock.Mock() + client.get_workflow_state.return_value = SimpleNamespace( + runtime_status=WorkflowStatus.COMPLETED, + serialized_output=json.dumps(output.to_dict()), + serialized_custom_status=None, + failure_details=None, + ) + runner._workflow_client = client + with self.assertRaisesRegex(RuntimeError, "not found in registry"): + await _collect( + runner.astream(INPUT, stream_mode="updates", poll_interval=0) + ) + + +class TestFailureDetailSurvives(_ScriptedCase): + async def test_astream_exception_carries_the_final(self): + runner = self._runner([STARTED, FAILED], "detail-b") + with self.assertRaises(RuntimeError) as caught: + await _collect( + runner.astream(INPUT, thread_id="t-2", stream_mode="updates") + ) + self.assertEqual(str(caught.exception), "activity blew up") + self.assertEqual(caught.exception.final["error"], FAILED_ERROR) + self.assertEqual(caught.exception.final["thread_id"], "t-2") + + async def test_unexpected_exception_becomes_a_failed_final(self): + runner = _chat_graph(name="detail-c") + runner._started = True + + async def broken(*a, **kw): + raise ConnectionError("sidecar gone") + yield # pragma: no cover + + with mock.patch.object(runner, "run_async", broken): + resp = self._client(runner).post( + "/agent/run", json={"task": "hi", "stream": True} + ) + name, data = parse_sse(resp.text)[-1] + self.assertEqual(name, "workflow_failed") + self.assertEqual(data["error"]["message"], "sidecar gone") + self.assertEqual(data["error"]["error_type"], "ConnectionError") + + +LOGGER = "diagrid.agent.langgraph.workflow" + + +class TestActivityWithoutASink(unittest.TestCase): + def setUp(self): + clear_registries() + self.addCleanup(clear_registries) + register_node("n", lambda state: {"x": 1}) + + def test_streamed_run_without_a_sink_warns_once_per_run(self): + with self.assertLogs(LOGGER, level="WARNING") as logs: + first = execute_node_activity(_Ctx("wf-lost"), _payload(streamed=True)) + execute_node_activity(_Ctx("wf-lost"), _payload(streamed=True, step=1)) + execute_node_activity(_Ctx("wf-other"), _payload(streamed=True)) + warnings = [r for r in logs.records if "no stream sink" in r.getMessage()] + self.assertEqual(len(warnings), 2) # one per run, not per node + self.assertIn("wf-lost", warnings[0].getMessage()) + self.assertIn("wf-other", warnings[1].getMessage()) + # The node itself is unaffected. + self.assertEqual(first["writes"][0]["value"], 1) + + def test_a_run_that_is_not_streamed_stays_quiet(self): + with self.assertNoLogs(LOGGER, level="WARNING"): + execute_node_activity(_Ctx("wf-plain"), _payload(streamed=False)) + + +class TestStreamedRunsAreMarked(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def test_the_workflow_config_says_the_run_is_streamed(self): + runner = _chat_graph(name="mark") + runner._started = True + seen: Dict[str, Any] = {} + + async def spy( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + seen.update(config or {}) + yield {"type": "workflow_completed", "workflow_id": workflow_id} + + with mock.patch.object(runner, "run_async", spy): + await _collect(runner.astream(INPUT, config={"tags": ["t"]})) + self.assertIs(seen[STREAM_RUN_KEY], True) + self.assertEqual(seen["tags"], ["t"]) # the caller's config is kept + + +def _chunk(step: int, node: str, mode: str, attempt: str = "a1") -> StreamEvent: + return StreamEvent("wf", step, node, attempt, 0, (), mode, {node: None}) + + +class _FakeRun(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + """A runner whose ``run_async`` puts ``chunks`` in its sink, then completes + with ``final`` (the keys of the ``workflow_completed`` event).""" + + def _runner(self, name: str, chunks: Sequence[StreamEvent] = (), **final: Any): + runner = _chat_graph(name=name) + runner._started = True + + async def run( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + sink = runner.stream_registry.get(workflow_id) + for chunk in chunks: + sink.put(chunk) + await asyncio.sleep(0) + yield { + "type": "workflow_completed", + "workflow_id": workflow_id, + "steps": len(final.get("executed", ())), + "status": "completed", + **final, + } + + patch = mock.patch.object(runner, "run_async", run) + patch.start() + self.addCleanup(patch.stop) + return runner + + +class TestStreamUnavailableEvent(_FakeRun): + async def test_nodes_ran_but_no_chunk_arrived(self): + runner = self._runner("un-none", steps=2) + items = await _collect( + runner.astream(INPUT, workflow_id="wf-u1", stream_mode=["updates"]) + ) + self.assertEqual(len(items), 1) + name, data = items[0] + self.assertEqual(name, "stream_unavailable") + self.assertEqual(data["workflow_id"], "wf-u1") + self.assertEqual(data["missing_steps"], [1, 2]) + self.assertIn("another process", data["reason"]) + + async def test_only_some_steps_arrived(self): + runner = self._runner("un-some", [_chunk(1, "n", "updates")], steps=2) + items = await _collect(runner.astream(INPUT, stream_mode=["updates"])) + self.assertEqual([m for m, _ in items], ["updates", "stream_unavailable"]) + self.assertEqual(items[-1][1]["missing_steps"], [1]) + + async def test_sse_sends_it_before_the_final_event(self): + from fastapi.testclient import TestClient + + runner = self._runner("un-sse", steps=1) + resp = TestClient(serve_app(runner)).post( + "/agent/run", json={"task": "hi", "stream": True} + ) + names = [n for n, _ in parse_sse(resp.text)] + self.assertEqual( + names, ["workflow_started", "stream_unavailable", "workflow_completed"] + ) + + async def test_nothing_is_reported_when_no_node_ran(self): + runner = self._runner("un-zero", steps=0) + self.assertEqual(await _collect(runner.astream(INPUT)), []) + + async def test_a_failed_run_is_just_a_failure(self): + # A node failure has steps and executed, and its node sent no chunk: it + # must not be blamed on another replica. Single-mode astream hides + # control events, so look at them through on_control and a list of modes. + runner = self._runner("un-fail", executed=[["n"]], status="error", error="boom") + controls: List[Any] = [] + with self.assertRaisesRegex(RuntimeError, "boom"): + await _collect( + runner.astream(INPUT, workflow_id="wf-f1", on_control=controls.append) + ) + self.assertEqual([c.kind for c in controls], ["workflow_started"]) + + seen: List[Any] = [] + with self.assertRaisesRegex(RuntimeError, "boom"): + async for item in runner.astream( + INPUT, workflow_id="wf-f2", stream_mode=["updates"] + ): + seen.append(item) + self.assertEqual(seen, []) + + async def test_sse_of_a_failed_run_has_no_stream_unavailable(self): + from fastapi.testclient import TestClient + + runner = self._runner( + "un-fail-sse", executed=[["n"]], status="error", error="boom" + ) + resp = TestClient(serve_app(runner)).post( + "/agent/run", json={"task": "hi", "stream": True} + ) + names = [n for n, _ in parse_sse(resp.text)] + self.assertEqual(names, ["workflow_started", "workflow_failed"]) + + +class TestDecision(unittest.TestCase): + FINAL = {"type": "workflow_completed", "steps": 2, "executed": [["a"], ["b", "c"]]} + + def test_every_executed_node_streamed(self): + seen = {(0, "a"), (1, "b"), (1, "c")} + self.assertIsNone(stream_unavailable_event(self.FINAL, seen, "wf")) + + def test_one_node_of_a_parallel_step_ran_elsewhere(self): + event = stream_unavailable_event(self.FINAL, {(0, "a"), (1, "b")}, "wf") + assert event is not None + self.assertEqual(event.data["missing_steps"], [2]) + self.assertEqual(event.data["missing_nodes"], [{"step": 2, "node": "c"}]) + + def test_a_whole_step_missing_lists_all_its_nodes(self): + event = stream_unavailable_event(self.FINAL, {(0, "a")}, "wf") + assert event is not None + self.assertEqual(event.data["missing_steps"], [2]) + self.assertEqual( + event.data["missing_nodes"], + [{"step": 2, "node": "b"}, {"step": 2, "node": "c"}], + ) + + def test_an_older_workflow_output_falls_back_to_steps(self): + final = {"type": "workflow_completed", "steps": 2} + event = stream_unavailable_event(final, {(0, "a")}, "wf") + assert event is not None + self.assertEqual(event.data["missing_steps"], [2]) + self.assertEqual(event.data["missing_nodes"], []) + self.assertIsNone(stream_unavailable_event(final, {(0, "a"), (1, "z")}, "wf")) + + +class TestThroughAstream(_FakeRun): + async def test_parallel_node_on_another_replica_is_reported(self): + runner = self._runner( + "un-par", [_chunk(0, "a", "updates")], executed=[["a", "b"]] + ) + items = await _collect(runner.astream(INPUT, stream_mode=["updates"])) + self.assertEqual([m for m, _ in items], ["updates", "stream_unavailable"]) + self.assertEqual(items[-1][1]["missing_nodes"], [{"step": 1, "node": "b"}]) + + async def test_a_retry_that_finished_on_another_replica_is_reported(self): + # Attempt 1 streamed some tokens here, then failed; attempt 2 ran + # elsewhere, so no updates chunk for the node ever arrived. + runner = self._runner( + "un-retry", [_chunk(0, "a", "messages")], executed=[["a"]] + ) + items = await _collect(runner.astream(INPUT, stream_mode=["messages"])) + # The partial text reached the client; so does the warning about it. + self.assertEqual([m for m, _ in items], ["messages", "stream_unavailable"]) + self.assertEqual(items[-1][1]["missing_nodes"], [{"step": 1, "node": "a"}]) + + async def test_complete_stream_reports_nothing(self): + runner = self._runner( + "un-full", + [_chunk(0, "a", "updates"), _chunk(0, "b", "updates")], + executed=[["a", "b"]], + ) + items = await _collect(runner.astream(INPUT, stream_mode=["updates"])) + self.assertEqual([m for m, _ in items], ["updates", "updates"]) + + async def test_executed_is_not_part_of_the_http_body_or_the_published_result(self): + from fastapi.testclient import TestClient + + runner = _chat_graph(name="un-http") + runner._started = True + + async def run( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + # like the real run_async, report it to a streamed run only + extra = ( + {"executed": [["chat"]]} if (config or {}).get(STREAM_RUN_KEY) else {} + ) + yield { + "type": "workflow_completed", + "workflow_id": workflow_id, + "steps": 1, + "status": "completed", + **extra, + } + + published: List[Any] = [] + fake = mock.Mock() + fake.publish.side_effect = lambda topic, data: published.append(data) + with ( + mock.patch.object(runner, "run_async", run), + mock.patch("diagrid.agent.core.pubsub.DaprPubSub", return_value=fake), + ): + client = TestClient(serve_app(runner, pubsub_name="ps", publish_topic="o")) + plain = client.post("/agent/run", json={"task": "hi"}).json() + sse = client.post("/agent/run", json={"task": "hi", "stream": True}) + self.assertNotIn("executed", parse_sse(sse.text)[-1][1]) + self.assertNotIn("executed", plain) + self.assertEqual(len(published), 2) + self.assertNotIn("executed", published[1]) + + +class TestWorkflowReportsWhatRan(_RunnerTestCase): + def test_output_lists_the_nodes_of_each_step(self): + from operator import add + + class State(TypedDict, total=False): + log: Annotated[list, add] + + graph = StateGraph(State) + for name in ("s", "a", "b", "c"): + graph.add_node(name, lambda state, n=name: {"log": [n]}) + graph.add_edge(START, "s") + graph.add_edge("s", "a") + graph.add_edge("s", "b") + graph.add_edge("a", "c") + graph.add_edge("b", "c") + graph.add_edge("c", END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="executed") + out = _run(runner, {"log": []}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.executed[0], ["s"]) + self.assertCountEqual(out.executed[1], ["a", "b"]) + self.assertEqual(out.executed[-1], ["c"]) + self.assertEqual(len(out.executed), out.steps) + + +class TestResetStepMatchesTheChunksItResets(unittest.IsolatedAsyncioTestCase): + async def test_node_reset_step_is_the_langgraph_step_of_the_chunks(self): + sink = InProcessSink("wf", asyncio.get_running_loop()) + # a loop graph: 'inc' runs in workflow steps 1, 2 and 3 (langgraph_step + # 2, 3, 4); its second invocation is retried + for step in (1, 2): + first = NodeStreamer( + sink, workflow_id="wf", step=step, node="inc", task_id=1 + ) + first._emit((), "custom", "partial") + retry = NodeStreamer(sink, workflow_id="wf", step=2, node="inc", task_id=1) + retry._emit((), "custom", "full") + await asyncio.sleep(0) + + items = [] + while not sink._queue.empty(): + items.append(sink._queue.get_nowait()) + (reset,) = [i for i in items if i.mode == NODE_RESET] + self.assertEqual(reset.data["node"], "inc") + self.assertEqual(reset.data["step"], retry.metadata["langgraph_step"]) + self.assertEqual(reset.data["step"], 3) + + +def _control_event(mode: str, node: str) -> StreamEvent: + return StreamEvent("wf", 0, node, "attempt", 0, (), mode, {}) + + +class TestControlModes(unittest.IsolatedAsyncioTestCase): + def test_control_modes_are_the_events_about_the_stream_itself(self): + self.assertEqual( + set(CONTROL_MODES), {WORKFLOW_STARTED, NODE_RESET, STREAM_UNAVAILABLE} + ) + + def test_updates_are_a_stream_mode_not_a_control_event(self): + # the runner delivers control events whatever modes were asked for + self.assertNotIn(UPDATES, CONTROL_MODES) + + async def test_a_full_buffer_keeps_control_events_and_updates_only(self): + modes = [ + "messages", + "custom", + UPDATES, + WORKFLOW_STARTED, + NODE_RESET, + STREAM_UNAVAILABLE, + ] + sink = InProcessSink("wf", asyncio.get_running_loop()) + with mock.patch.object(stream, "MAX_BUFFERED_EVENTS", 1): + sink.put(_control_event("messages", "filler")) + for mode in modes: + sink.put(_control_event(mode, mode)) + await asyncio.sleep(0) + sink.close() + kept = [] + while True: + item = await sink.get() + if isinstance(item, StreamClosed): + break + kept.append(item.mode) + self.assertEqual( + sorted(set(kept)), sorted({*CONTROL_MODES, UPDATES, "messages"}) + ) + # the filler is the only chunk of a droppable mode that got in + self.assertEqual(kept.count("messages"), 1) + self.assertNotIn("custom", kept) + + +RESET = StreamEvent("wf", 0, "chat", "a2", 0, (), NODE_RESET, {"node": "chat"}) + + +CHUNK = StreamEvent("wf", 0, "chat", "a2", 1, (), "messages", ("msg", {"k": 1})) + + +STARTED_EVENT = StreamEvent( + "wf", 0, "", "", 0, (), WORKFLOW_STARTED, {"workflow_id": "wf", "thread_id": "t"} +) + + +UNAVAILABLE = StreamEvent( + "wf", 0, "", "", 0, (), STREAM_UNAVAILABLE, {"workflow_id": "wf", "reason": "r"} +) + + +DROPPED = {"type": "workflow_completed", "dropped": 3} + + +def _control(item: StreamEvent) -> StreamControl: + return StreamControl(item.mode, item.data) + + +# How astream treats one item of the event stream. The columns are the way it +# was called: a single mode (the bare chunks of native astream) or a list of +# modes (``(mode, chunk)`` tuples), with or without ``on_control``. +SINGLE, SINGLE_CB, LIST, LIST_CB = ( + "single", + "single+on_control", + "list", + "list+on_control", +) + + +# item: {call: (yielded, handed to on_control, warns the reset went unseen)} +ROUTES = { + "chunk": ( + CHUNK, + { + SINGLE: ([("msg", {"k": 1})], [], False), + SINGLE_CB: ([("msg", {"k": 1})], [], False), + LIST: ([("messages", ("msg", {"k": 1}))], [], False), + LIST_CB: ([("messages", ("msg", {"k": 1}))], [], False), + }, + ), + "node_reset": ( + RESET, + { + SINGLE: ([], [], True), + SINGLE_CB: ([], [_control(RESET)], False), + LIST: ([(NODE_RESET, {"node": "chat"})], [], False), + LIST_CB: ([(NODE_RESET, {"node": "chat"})], [_control(RESET)], False), + }, + ), + "stream_unavailable": ( + UNAVAILABLE, + { + SINGLE: ([], [], False), + SINGLE_CB: ([], [_control(UNAVAILABLE)], False), + LIST: ([(STREAM_UNAVAILABLE, UNAVAILABLE.data)], [], False), + LIST_CB: ( + [(STREAM_UNAVAILABLE, UNAVAILABLE.data)], + [_control(UNAVAILABLE)], + False, + ), + }, + ), + # only informs on_control: native astream has no such mode + "workflow_started": ( + STARTED_EVENT, + { + SINGLE: ([], [], False), + SINGLE_CB: ([], [_control(STARTED_EVENT)], False), + LIST: ([], [], False), + LIST_CB: ([], [_control(STARTED_EVENT)], False), + }, + ), + "dropped": ( + DROPPED, + { + SINGLE: ([], [], False), + SINGLE_CB: ([], [StreamControl("stream_dropped", {"dropped": 3})], False), + LIST: ([("stream_dropped", {"dropped": 3})], [], False), + LIST_CB: ( + [("stream_dropped", {"dropped": 3})], + [StreamControl("stream_dropped", {"dropped": 3})], + False, + ), + }, + ), +} + + +class TestRouteAstreamItem(unittest.TestCase): + def test_every_item_in_every_call_style(self): + for name, (item, calls) in ROUTES.items(): + for call, (yielded, handed, warns) in calls.items(): + with self.subTest(item=name, call=call): + got: List[StreamControl] = [] + on_control = got.append if call.endswith("on_control") else None + is_list = call.startswith("list") + if warns: + with self.assertLogs(EVENTS_LOGGER, level="WARNING") as logs: + out, error = route_astream_item( + item, ["messages"], is_list, on_control + ) + # said once, with the node and the way to handle it + (warning,) = logs.records + self.assertIn("on_control", warning.getMessage()) + self.assertIn("'chat'", warning.getMessage()) + else: + with self.assertNoLogs(EVENTS_LOGGER, level="WARNING"): + out, error = route_astream_item( + item, ["messages"], is_list, on_control + ) + self.assertEqual(out, yielded) + self.assertEqual(got, handed) + self.assertIsNone(error) + + def test_a_chunk_of_a_mode_nobody_asked_for_is_dropped(self): + for is_list in (False, True): + with self.subTest(is_list=is_list): + out, _ = route_astream_item(CHUNK, ["custom"], is_list, None) + self.assertEqual(out, []) + + def test_a_failed_final_comes_back_as_the_error_after_what_came_with_it(self): + final = {"type": "workflow_failed", "dropped": 2, "error": {"message": "x"}} + out, error = route_astream_item(final, ["messages"], True, None) + self.assertEqual(out, [("stream_dropped", {"dropped": 2})]) + self.assertIsInstance(error, GraphRunError) + + +EVENTS_LOGGER = "diagrid.agent.langgraph.stream_events" + + +def _token(attempt: str, text: str, seq: int) -> StreamEvent: + return StreamEvent( + "wf", 0, "n", attempt, seq, (), "messages", (AIMessageChunk(content=text), {}) + ) + + +class TestRetryInSingleMode(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + def _runner(self, name: str): + runner = _chat_graph(name=name) + runner._started = True + + async def run( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + sink = runner.stream_registry.get(workflow_id) + for event in ( + _token("A", "Hel", 0), + _token("A", "lo ", 1), + _token("B", "Hello", 0), # Dapr retried the activity + _token("B", " world", 1), + ): + sink.put(event) + await asyncio.sleep(0) + yield {"type": "workflow_completed", "workflow_id": workflow_id} + + patch = mock.patch.object(runner, "run_async", run) + patch.start() + self.addCleanup(patch.stop) + return runner + + async def test_a_consumer_who_cannot_see_the_reset_is_warned(self): + runner = self._runner("retry-single") + with self.assertLogs(EVENTS_LOGGER, level="WARNING") as logs: + chunks = await _collect(runner.astream(INPUT, stream_mode="messages")) + # the attempt that was abandoned is still in what was yielded ... + self.assertEqual("".join(c[0].content for c in chunks), "Hello Hello world") + # ... and that is said, once per reset, with the way to handle it + (warning,) = [r for r in logs.records if "node_reset" in r.getMessage()] + self.assertIn("on_control", warning.getMessage()) + self.assertIn("'n'", warning.getMessage()) diff --git a/tests/agent/langgraph/test_streaming_golden.py b/tests/agent/langgraph/test_streaming_golden.py new file mode 100644 index 00000000..421d7f30 --- /dev/null +++ b/tests/agent/langgraph/test_streaming_golden.py @@ -0,0 +1,660 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Graph shapes: the stream matches what native ``astream`` yields.""" + +import asyncio +import operator +import unittest +from typing import Any, Callable, Dict, List, Literal +from unittest import mock + +from langchain_core.load import load +from langchain_core.messages import ( + AIMessage, + AIMessageChunk, + BaseMessage, + ToolMessage, +) +from langchain_core.tools import tool +from langgraph.config import get_stream_writer +from langgraph.graph import END, START, MessagesState, StateGraph +from langgraph.graph.message import add_messages +from langgraph.prebuilt import ToolNode, tools_condition +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.workflow import _has_async_entry + +from .golden_harness import ( + ADD_INPUT, + _both, + _canonical, + _Golden, + _golden_graph, + _Log, + _ReactModel, + _wire, + add, +) +from .streaming_helpers import ( + INPUT, + _fake_run_async, + _StreamingModel, + parse_sse, + serve_app, +) +from .test_runner import _run, _RunnerTestCase + + +class TestMatchesNativeLangGraph(_Golden): + async def test_same_sequence_of_mode_and_payload(self): + native, ours = await _both(_golden_graph(), "golden", INPUT) + self._assert_same_sequence(native, ours) + + async def test_step_numbers_follow_the_pregel_loop(self): + native, ours = await _both(_golden_graph(), "golden-steps", INPUT) + self.assertEqual(set(self._steps(ours)), set(self._steps(native))) + first = next(p for m, p in ours if m == "messages") + self.assertIsInstance(first[0], BaseMessage) + + +class TestSseCarriesLoadableObjects(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def test_messages_and_updates_load_back(self): + from fastapi.testclient import TestClient + + runner = DaprWorkflowGraphRunner(graph=_golden_graph(), name="golden-sse") + runner._started = True + with mock.patch.object(runner, "run_async", _fake_run_async(runner)): + client = TestClient(serve_app(runner)) + resp = client.post("/agent/run", json={"task": "hi", "stream": True}) + events = parse_sse(resp.text) + + messages = [ + load(d, allowed_objects="messages") for e, d in events if e == "messages" + ] + self.assertTrue(messages) + chunk, metadata = messages[0] + self.assertIsInstance(chunk, BaseMessage) + self.assertEqual(metadata["langgraph_node"], "chat") + + updates = [ + load(d, allowed_objects="messages") for e, d in events if e == "updates" + ] + self.assertEqual([list(u) for u in updates], [["chat"], ["counter"], ["quiet"]]) + self.assertIsInstance(updates[0]["chat"]["messages"][0], BaseMessage) + self.assertEqual(updates[1], {"counter": {"count": 1}}) + self.assertEqual(updates[2], {"quiet": None}) + + +def _react_graph() -> Any: + model = _ReactModel() + + def agent(state: MessagesState) -> dict: + return {"messages": [model.invoke(state["messages"])]} + + graph = StateGraph(MessagesState) + graph.add_node("agent", agent) + graph.add_node("tools", ToolNode([add])) + graph.add_edge(START, "agent") + graph.add_conditional_edges("agent", tools_condition) + graph.add_edge("tools", "agent") + return graph.compile() + + +class _Fan(TypedDict, total=False): + log: Annotated[list, operator.add] + messages: Annotated[list, add_messages] + + +def _fan_out_graph() -> Any: + model = _ReactModel() + + def start(state: _Fan) -> dict: + get_stream_writer()("start") + return {"log": ["start"]} + + def left(state: _Fan) -> dict: + get_stream_writer()("left") + return {"log": ["left"]} + + def right(state: _Fan) -> dict: + get_stream_writer()("right") + return {"log": ["right"], "messages": [model.invoke([("user", "hi")])]} + + def join(state: _Fan) -> dict: + get_stream_writer()("join") + return {"log": ["join"]} + + graph = StateGraph(_Fan) + for name, fn in ( + ("start", start), + ("left", left), + ("right", right), + ("join", join), + ): + graph.add_node(name, fn) + graph.add_edge(START, "start") + graph.add_edge("start", "left") + graph.add_edge("start", "right") + graph.add_edge("left", "join") + graph.add_edge("right", "join") + graph.add_edge("join", END) + return graph.compile() + + +class _Loop(TypedDict, total=False): + n: int + log: Annotated[list, operator.add] + + +def _router_loop_graph() -> Any: + def inc(state: _Loop) -> dict: + get_stream_writer()({"n": state.get("n", 0) + 1}) + return {"n": state.get("n", 0) + 1, "log": ["inc"]} + + def route(state: _Loop) -> Literal["inc", "__end__"]: + return "inc" if state["n"] < 3 else END + + graph = StateGraph(_Loop) + graph.add_node("inc", inc) + graph.add_edge(START, "inc") + graph.add_conditional_edges("inc", route) + return graph.compile() + + +class TestReactLoop(_Golden): + async def test_matches_native_with_thread_tags_and_metadata(self): + native, ours = await _both(_react_graph(), "golden-react", ADD_INPUT) + self._assert_same_sequence(native, ours) + + async def test_steps_and_the_tool_message_chunk(self): + native, ours = await _both(_react_graph(), "golden-react-steps", ADD_INPUT) + self.assertEqual(sorted(set(self._steps(ours))), [1, 2, 3]) + self.assertEqual(self._steps(ours), self._steps(native)) + tool_chunks = [ + i[1] + for i in ours + if i[0] == "messages" and isinstance(i[1][0], ToolMessage) + ] + self.assertEqual(len(tool_chunks), 1) + message, metadata = tool_chunks[0] + self.assertEqual(message.content, "5") + self.assertEqual(metadata["langgraph_node"], "tools") + self.assertEqual(metadata["langgraph_step"], 2) + self.assertEqual(metadata["thread_id"], "t1") + self.assertEqual(metadata["foo"], "bar") + + +class TestRouterLoop(_Golden): + async def test_matches_native_and_numbers_repeated_nodes(self): + native, ours = await _both(_router_loop_graph(), "golden-loop", {"log": []}) + self._assert_same_sequence(native, ours) + self.assertEqual( + [i[1] for i in ours if i[0] == "custom"], [{"n": 1}, {"n": 2}, {"n": 3}] + ) + + +class TestParallelStep(_Golden): + async def test_same_chunks_with_the_parallel_nodes_unordered(self): + native, ours = await _both(_fan_out_graph(), "golden-fan", {"log": []}) + + # The two nodes of a step run at once: their chunks may interleave + # differently from native, so compare them per node, not as a sequence. + def by_node(items: List) -> Dict[str, List]: + groups: Dict[str, List] = {} + for mode, payload in _wire(items): + node = ( + payload[1]["langgraph_node"] + if mode == "messages" + else next(iter(payload)) + if mode == "updates" + else None + ) + groups.setdefault(str(node), []).append((mode, payload)) + return groups + + self.assertEqual(_canonical(ours), _canonical(native)) + # One updates chunk per node, as native emits. + updates = [list(c) for m, c in ours if m == "updates"] + self.assertEqual( + sorted(u[0] for u in updates), ["join", "left", "right", "start"] + ) + self.assertEqual(sorted(len(u) for u in updates), [1, 1, 1, 1]) + self.assertEqual( + sorted(len(u) for m, u in native if m == "updates" for u in [list(u)]), + [1, 1, 1, 1], + ) + # Within a node the order is native's. + self.assertEqual(by_node(ours)["right"], by_node(native)["right"]) + + +def _router_graph(*, async_router: bool = False) -> Any: + model = _StreamingModel() + + def first(state: _Log) -> dict: + return {"log": ["first"]} + + def end_node(state: _Log) -> dict: + return {"log": ["end"]} + + graph = StateGraph(_Log) + graph.add_node("first", first) + graph.add_node("end_node", end_node) + graph.add_edge(START, "first") + if async_router: + + async def arouter(state: _Log) -> str: + get_stream_writer()("routing") + await model.ainvoke("which way?") + return "end_node" + + graph.add_conditional_edges("first", arouter, ["end_node"]) + else: + + def router(state: _Log) -> str: + get_stream_writer()("routing") + model.invoke("which way?") + return "end_node" + + graph.add_conditional_edges("first", router, ["end_node"]) + graph.add_edge("end_node", END) + return graph.compile() + + +class TestRouterThatStreams(_Golden): + async def test_its_tokens_and_custom_event_reach_the_stream(self): + native, ours = await _both(_router_graph(), "router-sync", {"log": []}) + router_tokens = [ + i + for i in ours + if i[0] == "messages" + and isinstance(i[1][0], AIMessageChunk) + and i[1][1]["langgraph_node"] == "first" + ] + self.assertTrue(router_tokens, "the router's tokens were lost") + self.assertIn(("custom", "routing"), ours) + # a router's chunks are the source node's in native LangGraph + self.assertEqual(_canonical(ours), _canonical(native)) + + async def test_an_async_router_streams_too(self): + native, ours = await _both( + _router_graph(async_router=True), "router-async", {"log": []} + ) + self.assertIn(("custom", "routing"), ours) + self.assertEqual(_canonical(ours), _canonical(native)) + + async def test_it_does_not_look_like_a_missing_stream(self): + # the router's chunks are not a node's updates: no stream_unavailable + _, ours = await _both(_router_graph(), "router-no-unavailable", {"log": []}) + self.assertNotIn("stream_unavailable", [m for m, _ in ours]) + + +def _start_router_graph() -> Any: + model = _StreamingModel() + + def router(state: _Log) -> str: + model.invoke("which way?") + return "end_node" + + graph = StateGraph(_Log) + graph.add_node("end_node", lambda state: {"log": ["end"]}) + graph.add_conditional_edges(START, router, ["end_node"]) + graph.add_edge("end_node", END) + return graph.compile() + + +class TestStartRouter(_Golden): + async def test_its_tokens_carry_the_start_trigger_like_native(self): + native, ours = await _both(_start_router_graph(), "start-router", {"log": []}) + + def metadata(items: List) -> List: + return [ + {k: i[1][1][k] for k in ("langgraph_node", "langgraph_triggers")} + for i in items + if i[0] == "messages" and isinstance(i[1][0], AIMessageChunk) + ] + + self.assertTrue(metadata(ours)) + self.assertEqual(metadata(ours), metadata(native)) + self.assertEqual(metadata(ours)[0]["langgraph_triggers"], ("__start__",)) + + +def _node(name: str) -> Callable[[_Log], dict]: + def run(state: _Log) -> dict: + get_stream_writer()(name) + return {"log": [name]} + + run.__name__ = name + return run + + +def _build(nodes: List[str], wire: Callable[[StateGraph], None]) -> Any: + graph = StateGraph(_Log) + for name in nodes: + graph.add_node(name, _node(name)) + wire(graph) + return graph.compile() + + +def _two_starts(graph: StateGraph) -> None: + graph.add_edge(START, "a") + graph.add_edge(START, "b") + graph.add_edge("a", END) + graph.add_edge("b", END) + + +def _conditional_start(graph: StateGraph) -> None: + graph.add_conditional_edges(START, lambda state: "b", ["a", "b"]) + graph.add_edge("a", END) + graph.add_edge("b", END) + + +def _conditional_start_and_edge(graph: StateGraph) -> None: + graph.add_edge(START, "a") + graph.add_conditional_edges(START, lambda state: ["b"], ["b"]) + graph.add_edge("a", END) + graph.add_edge("b", END) + + +def _waiting(graph: StateGraph) -> None: + graph.add_edge(START, "a") + graph.add_edge(START, "b") + graph.add_edge(["a", "b"], "j") + graph.add_edge("j", END) + + +def _waiting_uneven(graph: StateGraph) -> None: + # the join's sources finish in different steps: a -> c, and b at once + graph.add_edge(START, "a") + graph.add_edge(START, "b") + graph.add_edge("a", "c") + graph.add_edge(["c", "b"], "j") + graph.add_edge("j", END) + + +def _end_in_one_branch(graph: StateGraph) -> None: + # x reaches END in step 0 while y still has z to run + graph.add_edge(START, "x") + graph.add_edge(START, "y") + graph.add_edge("x", END) + graph.add_edge("y", "z") + graph.add_edge("z", END) + + +def _conditional_end_in_one_branch(graph: StateGraph) -> None: + graph.add_edge(START, "x") + graph.add_edge(START, "y") + graph.add_conditional_edges("x", lambda state: END, [END]) + graph.add_edge("y", "z") + graph.add_edge("z", END) + + +CASES = { + "two-starts": (["a", "b"], _two_starts), + "conditional-start": (["a", "b"], _conditional_start), + "conditional-and-direct-start": (["a", "b"], _conditional_start_and_edge), + "waiting-edge": (["a", "b", "j"], _waiting), + "waiting-uneven": (["a", "b", "c", "j"], _waiting_uneven), + "end-in-one-branch": (["x", "y", "z"], _end_in_one_branch), + "conditional-end-in-one-branch": (["x", "y", "z"], _conditional_end_in_one_branch), +} + + +class TestEntryShapes(_Golden): + async def test_the_stream_has_native_chunks(self): + for name, (nodes, wire) in CASES.items(): + with self.subTest(case=name): + self.setUp() + native, ours = await _both(_build(nodes, wire), f"entry-{name}", {}) + # nodes of one step run at once: compare the chunks, not their order + self.assertEqual(_canonical(ours), _canonical(native)) + + def test_the_final_state_is_native(self): + for name, (nodes, wire) in CASES.items(): + with self.subTest(case=name): + self.setUp() + compiled = _build(nodes, wire) + out = _run( + DaprWorkflowGraphRunner(graph=compiled, name=f"entry-out-{name}"), + {"log": []}, + ) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["log"], compiled.invoke({"log": []})["log"]) + + +class _Seen(TypedDict, total=False): + log: Annotated[list, operator.add] + seen: list + + +class TestUnevenJoinFiresAfterItsLastSource(_Golden): + """add_edge(["c", "b"], "j") with b in step 1 and c in step 2: j runs in step 3.""" + + def _graph(self) -> Any: + model = _StreamingModel() + + def j(state: _Seen) -> dict: + model.invoke("hi") + return {"seen": list(state["log"]), "log": ["j"]} + + graph = StateGraph(_Seen) + for name in ("a", "b", "c"): + graph.add_node(name, _node(name)) # type: ignore[arg-type] + graph.add_node("j", j) + graph.add_edge(START, "a") + graph.add_edge(START, "b") + graph.add_edge("a", "c") + graph.add_edge(["c", "b"], "j") + graph.add_edge("j", END) + return graph.compile() + + def test_j_runs_alone_in_the_step_after_c_and_sees_its_write(self): + compiled = self._graph() + out = _run( + DaprWorkflowGraphRunner(graph=compiled, name="uneven-join-state"), + {"log": []}, + ) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.executed, [["a", "b"], ["c"], ["j"]]) + self.assertEqual(out.output["seen"], ["a", "b", "c"]) + self.assertEqual(out.output["seen"], compiled.invoke({"log": []})["seen"]) + + async def test_j_s_messages_carry_the_step_native_gives_them(self): + native, ours = await _both(self._graph(), "uneven-join-steps", {"log": []}) + self.assertEqual(self._steps(ours), self._steps(native)) + self.assertEqual(set(self._steps(ours)), {3}) + + +class TestStartConditionError(_Golden): + def test_a_start_condition_that_cannot_route_is_an_error_not_a_silent_run(self): + graph = StateGraph(_Log) + graph.add_node("a", _node("a")) + graph.add_conditional_edges(START, lambda state: "nowhere", {"x": "a"}) + graph.add_edge("a", END) + out = _run( + DaprWorkflowGraphRunner(graph=graph.compile(), name="entry-bad-route"), + {"log": []}, + ) + self.assertEqual(out.status, "error") + self.assertIn("nowhere", out.error or "") + self.assertEqual(out.executed, []) + + +class TestTriggersMetadata(_Golden): + async def test_a_nodes_messages_carry_all_its_triggers(self): + model = _StreamingModel() + + def j(state: _Log) -> dict: + model.invoke("hi") + return {"log": ["j"]} + + graph = StateGraph(_Log) + graph.add_node("a", _node("a")) + graph.add_node("b", _node("b")) + graph.add_node("j", j) + graph.add_edge(START, "a") + graph.add_edge(START, "b") + graph.add_edge(["a", "b"], "j") + graph.add_edge("j", END) + compiled = graph.compile() + native, ours = await _both(compiled, "entry-triggers", {}) + + def triggers(items: List) -> List[Any]: + return [ + list(i[1][1]["langgraph_triggers"]) + for i in items + if i[0] == "messages" and isinstance(i[1][0], AIMessageChunk) + ] + + self.assertEqual(triggers(ours)[0], ["branch:to:j", "join:a+b:j"]) + self.assertEqual(triggers(ours), triggers(native)) + self.assertEqual(_canonical(ours), _canonical(native)) + + +class TestAnOlderGraphConfig(_Golden): + def test_a_config_without_entry_points_starts_at_its_entry_point(self): + compiled = _build(["a", "b"], _two_starts) + runner = DaprWorkflowGraphRunner(graph=compiled, name="entry-legacy") + config = runner.graph_config.to_dict() + config.pop("entry_points") + config.pop("waiting_edges") + from diagrid.agent.langgraph.models import GraphConfig + + runner._graph_config = GraphConfig.from_dict(config) + self.assertIsNone(runner._graph_config.entry_points) + out = _run(runner, {"log": []}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["log"], ["a"]) # as before the field existed + + +def _two_edges_graph(source: Any = "a") -> Any: + def r1(state: _Log) -> str: + get_stream_writer()("router1") + return "b" + + def r2(state: _Log) -> str: + get_stream_writer()("router2") + return "c" + + graph = StateGraph(_Log) + for name in ("a", "b", "c"): + graph.add_node(name, lambda s, n=name: {"log": [n]}) + graph.add_edge(START, "a") + graph.add_conditional_edges(source, r1, ["b"]) + graph.add_conditional_edges(source, r2, ["c"]) + graph.add_edge("b", END) + graph.add_edge("c", END) + return graph.compile() + + +def _two_start_edges_graph() -> Any: + def r1(state: _Log) -> str: + get_stream_writer()("router1") + return "b" + + def r2(state: _Log) -> str: + get_stream_writer()("router2") + return "c" + + graph = StateGraph(_Log) + for name in ("b", "c"): + graph.add_node(name, lambda s, n=name: {"log": [n]}) + graph.add_conditional_edges(START, r1, ["b"]) + graph.add_conditional_edges(START, r2, ["c"]) + graph.add_edge("b", END) + graph.add_edge("c", END) + return graph.compile() + + +class TestTwoConditionalEdges(_Golden): + async def test_two_edges_of_one_node_are_not_a_retry(self): + native, ours = await _both(_two_edges_graph(), "two-edges", {"log": []}) + self.assertNotIn("node_reset", [m for m, _ in ours]) + self.assertEqual( + sorted(p for m, p in ours if m == "custom"), + sorted(p for m, p in native if m == "custom"), + ) + + async def test_two_conditional_start_edges_are_not_a_retry(self): + native, ours = await _both( + _two_start_edges_graph(), "two-start-edges", {"log": []} + ) + self.assertNotIn("node_reset", [m for m, _ in ours]) + self.assertEqual( + sorted(p for m, p in ours if m == "custom"), + sorted(p for m, p in native if m == "custom"), + ) + + +@tool("add") +async def async_add(a: int, b: int) -> int: + """Add two numbers (async only).""" + get_stream_writer()({"adding": [a, b]}) + return a + b + + +def _async_tool_graph() -> Any: + model = _ReactModel() + + def agent(state: MessagesState) -> dict: + return {"messages": [model.invoke(state["messages"])]} + + graph = StateGraph(MessagesState) + graph.add_node("agent", agent) + graph.add_node("tools", ToolNode([async_add])) + graph.add_edge(START, "agent") + graph.add_conditional_edges("agent", tools_condition) + graph.add_edge("tools", "agent") + return graph.compile() + + +class TestAsyncOnlyTool(_Golden): + def test_the_run_completes_with_the_tools_result(self): + graph = StateGraph(MessagesState) + graph.add_node("tools", ToolNode([async_add])) + graph.add_edge(START, "tools") + compiled = graph.compile() + call = AIMessage( + content="", + tool_calls=[{"name": "add", "args": {"a": 2, "b": 3}, "id": "c1"}], + ) + runner = DaprWorkflowGraphRunner(graph=compiled, name="async-tool-run") + out = _run(runner, {"messages": [call]}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["messages"][-1]["content"], "5") + + async def test_matches_native_including_the_tools_custom_chunk(self): + # a failing activity never completes the fake run: bound the wait + native, ours = await asyncio.wait_for( + _both(_async_tool_graph(), "golden-async-tool", ADD_INPUT), 20 + ) + self._assert_same_sequence(native, ours) + self.assertIn(("custom", {"adding": [2, 3]}), [i for i in ours]) + + +class TestWhichNodesUseTheAsyncEntry(_Golden): + def test_a_sync_function_node_keeps_the_sync_entry(self): + # add_node gives every sync function an ``afunc`` that only wraps it in + # an executor: using it would run the node on a loop of its own. + def plain(state: MessagesState) -> dict: + return {} + + graph = StateGraph(MessagesState) + graph.add_node("plain", plain) + graph.add_node("tools", ToolNode([async_add])) + graph.add_edge(START, "plain") + compiled = graph.compile() + self.assertFalse(_has_async_entry(compiled.nodes["plain"].bound)) + + def test_a_tool_node_and_an_async_function_node_use_it(self): + async def aplain(state: MessagesState) -> dict: + return {} + + graph = StateGraph(MessagesState) + graph.add_node("aplain", aplain) + graph.add_node("tools", ToolNode([async_add])) + graph.add_edge(START, "aplain") + compiled = graph.compile() + self.assertTrue(_has_async_entry(compiled.nodes["aplain"].bound)) + self.assertTrue(_has_async_entry(compiled.nodes["tools"].bound)) diff --git a/tests/agent/langgraph/test_streaming_golden_state.py b/tests/agent/langgraph/test_streaming_golden_state.py new file mode 100644 index 00000000..56e848ad --- /dev/null +++ b/tests/agent/langgraph/test_streaming_golden_state.py @@ -0,0 +1,719 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""State, channels, ``Send``, config and ``Command(goto=...)``: the stream matches native ``astream``.""" + +import json +import operator +import unittest +from dataclasses import dataclass, field +from typing import Any, Dict, List, Literal, Optional +from unittest import mock + +from langchain_core.messages import AIMessage, AIMessageChunk, ToolMessage +from langgraph.config import get_stream_writer +from langgraph.graph import END, START, MessagesState, StateGraph +from langgraph.graph.message import add_messages +from langgraph.prebuilt import ToolNode, tools_condition +from langgraph.types import Command, Send +from pydantic import BaseModel, Field +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.workflow import _result_to_raw_writes + +from .golden_harness import ( + ADD_INPUT, + _both, + _canonical, + _Golden, + _Log, + _Out, + _ReactModel, + _wire, + add, +) +from .streaming_helpers import ( + INPUT, + _collect, + _fake_run_async, + _StreamingModel, +) +from .test_runner import _run, _RunnerTestCase + + +class _Writer(TypedDict, total=False): + log: Annotated[list, operator.add] + total: Annotated[int, operator.add] + messages: Annotated[list, add_messages] + + +def _writer_graph() -> Any: + def write(state: _Writer) -> dict: + return { + "messages": [ + {"role": "assistant", "content": "one"}, + ("assistant", "two"), + AIMessage(content="three"), + ], + "total": 5, + } + + def echo(state: _Writer) -> dict: + return {"messages": state["messages"]} + + graph = StateGraph(_Writer) + graph.add_node("write", write) + graph.add_node("echo", echo) + graph.add_edge(START, "write") + graph.add_edge("write", "echo") + graph.add_edge("echo", END) + return graph.compile() + + +def _messages(out: Dict[str, Any]) -> List[Dict[str, Any]]: + return out["messages"] + + +class TestFirstWriteToAReducerChannel(_Golden): + def test_it_goes_through_the_reducer_like_native(self): + compiled = _writer_graph() + native = compiled.invoke({"log": []}) + out = _run( + DaprWorkflowGraphRunner(graph=compiled, name="reducer-first"), + {"log": []}, + ) + self.assertEqual(out.status, "completed", out.error) + ours = _messages(out.output) + self.assertEqual([m["content"] for m in ours], ["one", "two", "three"]) + self.assertTrue(all(m.get("id") for m in ours), ours) + self.assertEqual(len(ours), len(native["messages"])) + self.assertEqual(out.output["total"], native["total"]) + + async def test_updates_match_native_in_channels_values_and_message_fields(self): + native, ours = await _both(_writer_graph(), "reducer-updates", {"log": []}) + want = [p for m, p in _wire(native) if m == "updates"] + got = [p for m, p in _wire(ours) if m == "updates"] + self.assertEqual(len(got), len(want)) + for index, (expected, actual) in enumerate(zip(want, got)): + with self.subTest(update=index): + self.assertEqual(actual, expected) + + +class TestTupleInputMessages(_Golden): + def _graph(self) -> Any: + def echo(state: _Writer) -> dict: + return {"messages": state["messages"]} + + graph = StateGraph(_Writer) + graph.add_node("echo", echo) + graph.add_edge(START, "echo") + graph.add_edge("echo", END) + return graph.compile() + + def test_a_tuple_is_a_message_with_an_id(self): + compiled = self._graph() + native = compiled.invoke({"messages": [("user", "hi")]}) + out = _run( + DaprWorkflowGraphRunner(graph=compiled, name="tuple-input"), + {"messages": [("user", "hi")]}, + ) + self.assertEqual(out.status, "completed", out.error) + ours = _messages(out.output) + self.assertEqual(len(ours), len(native["messages"])) + self.assertEqual(ours[0]["content"], "hi") + self.assertEqual(ours[0]["type"], "human") + self.assertTrue(ours[0].get("id")) + + async def test_what_a_node_echoes_is_not_streamed_again(self): + native, ours = await _both( + self._graph(), "tuple-echo", {"messages": [("user", "hi")]} + ) + got = [p for m, p in _wire(ours) if m == "updates"] + want = [p for m, p in _wire(native) if m == "updates"] + self.assertEqual(got, want) + + +def _stray_key_graph() -> Any: + def unk(state: _Log) -> dict: + return {"log": ["a"], "bogus": 1} + + def only(state: _Log) -> dict: + return {"bogus": 2} + + def command(state: _Log) -> Command: + return Command(update={"log": ["c"], "bogus": 3}) + + def seen(state: _Log) -> dict: + # what the node can read: a stray key must not have been stored + return {"log": sorted(state)} + + graph = StateGraph(_Log) + for name, fn in (("unk", unk), ("only", only), ("cmd", command), ("seen", seen)): + graph.add_node(name, fn) # type: ignore[arg-type] + graph.add_edge(START, "unk") + graph.add_edge("unk", "only") + graph.add_edge("only", "cmd") + graph.add_edge("cmd", "seen") + graph.add_edge("seen", END) + return graph.compile() + + +class TestKeysThatAreNotChannels(_Golden): + async def test_updates_match_native(self): + native, ours = await _both(_stray_key_graph(), "golden-channels", {"log": []}) + want = [p for m, p in _wire(native) if m == "updates"] + got = [p for m, p in _wire(ours) if m == "updates"] + self.assertEqual(got, want) + + def test_a_stray_key_is_not_stored_for_later_nodes(self): + compiled = _stray_key_graph() + out = _run( + DaprWorkflowGraphRunner(graph=compiled, name="chan-state"), {"log": []} + ) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["log"], compiled.invoke({"log": []})["log"]) + self.assertNotIn("bogus", out.channel_state.values) + + +class _Pydantic(BaseModel): + x: int = 0 + log: Annotated[list, operator.add] = Field(default_factory=list) + note: Optional[str] = None + + +@dataclass +class _Plain: + x: int = 0 + log: Annotated[list, operator.add] = field(default_factory=list) + + +def _object_graph(schema: Any, make: Any) -> Any: + def node(state: Any) -> Any: + return make() + + graph = StateGraph(schema) + graph.add_node("n", node) + graph.add_edge(START, "n") + graph.add_edge("n", END) + return graph.compile() + + +class TestStateObjectResults(_Golden): + async def _check(self, schema: Any, make: Any, name: str, start: Any) -> None: + compiled = _object_graph(schema, make) + native, ours = await _both(compiled, name, start) + self._assert_same_sequence(native, ours) + updates = [c for m, c in ours if m == "updates"] + self.assertEqual(list(updates[0]), ["n"]) + self.assertNotIn("__result__", updates[0]["n"]) + + async def test_pydantic_instance(self): + await self._check( + _Pydantic, lambda: _Pydantic(x=5, log=["a"]), "golden-pyd", {"x": 1} + ) + + async def test_pydantic_fields_left_at_their_default_are_not_written(self): + # LangGraph writes only what was set or differs from a None default + await self._check(_Pydantic, lambda: _Pydantic(x=2), "golden-pyd-def", {}) + + async def test_dataclass_instance(self): + await self._check(_Plain, lambda: _Plain(x=5, log=["a"]), "golden-dc", {"x": 1}) + + +class TestTheStateIsWritten(_Golden): + def test_the_workflow_output_has_the_nodes_fields(self): + compiled = _object_graph(_Pydantic, lambda: _Pydantic(x=5, log=["a"])) + runner = DaprWorkflowGraphRunner(graph=compiled, name="golden-pyd-out") + out = _run(runner, {"x": 1, "log": []}) + self.assertEqual(out.status, "completed", out.error) + want = compiled.invoke({"x": 1, "log": []}) + self.assertEqual(out.output["x"], want["x"]) + self.assertEqual(out.output["log"], want["log"]) + + +class TestWritesOfAnObject(_Golden): + def test_a_plain_object_is_still_one_result(self): + class Thing: + pass + + thing = Thing() + self.assertEqual(_result_to_raw_writes(thing), [("__result__", thing)]) + + +def _config_graph(*, graph_config: Any = None, node_metadata: Any = None) -> Any: + model = _ReactModel() + + def agent(state: MessagesState) -> dict: + return {"messages": [model.invoke(state["messages"])]} + + graph = StateGraph(MessagesState) + graph.add_node("agent", agent, metadata=node_metadata) + graph.add_node("tools", ToolNode([add])) + graph.add_edge(START, "agent") + graph.add_conditional_edges("agent", tools_condition) + graph.add_edge("tools", "agent") + compiled = graph.compile() + return compiled.with_config(graph_config) if graph_config else compiled + + +def _chunks(items: Any, node: str, kind: type) -> Any: + return [ + m + for mode, (m, md) in [i for i in items if i[0] == "messages"] + if md["langgraph_node"] == node and isinstance(m, kind) + ] + + +def _metadata(items: Any, node: str) -> Any: + return [ + md + for mode, (m, md) in [i for i in items if i[0] == "messages"] + if md["langgraph_node"] == node + ] + + +class TestGraphConfig(_Golden): + async def test_metadata_and_tags_of_with_config_reach_every_chunk(self): + compiled = _config_graph(graph_config={"metadata": {"gm": 1}, "tags": ["gt"]}) + native, ours = await _both(compiled, "meta-graph", ADD_INPUT) + for node in ("agent", "tools"): + with self.subTest(node=node): + self.assertTrue(_metadata(native, node)) + for md_native, md_ours in zip( + _metadata(native, node), _metadata(ours, node) + ): + self.assertEqual(md_ours["gm"], 1) + self.assertEqual( + md_ours.get("tags"), md_native.get("tags"), (md_native, md_ours) + ) + self._assert_same_sequence(native, ours) + + async def test_ls_integration_of_the_graph_wins(self): + compiled = _config_graph(graph_config={"metadata": {"ls_integration": "mine"}}) + native, ours = await _both(compiled, "meta-ls", ADD_INPUT) + tool = _metadata(ours, "tools")[0] + self.assertEqual(tool["ls_integration"], "mine") + self.assertEqual( + tool["ls_integration"], _metadata(native, "tools")[0]["ls_integration"] + ) + + async def test_the_caller_overrides_the_graph(self): + # the caller of _both sets foo=bar + compiled = _config_graph(graph_config={"metadata": {"foo": "graph"}}) + native, ours = await _both(compiled, "meta-caller", ADD_INPUT) + self.assertEqual(_metadata(native, "tools")[0]["foo"], "bar") + self.assertEqual(_metadata(ours, "tools")[0]["foo"], "bar") + + +class TestNodeMetadata(_Golden): + async def test_add_node_metadata_reaches_that_nodes_chunks_only(self): + compiled = _config_graph(node_metadata={"custom": "meta", "foo": "node"}) + native, ours = await _both(compiled, "meta-node", ADD_INPUT) + agent = _metadata(ours, "agent") + self.assertTrue(agent) + for md in agent: + self.assertEqual(md["custom"], "meta") + self.assertEqual(md["foo"], "node") # the node's own beats the caller's + for md in _metadata(ours, "tools"): + self.assertNotIn("custom", md) + self._assert_same_sequence(native, ours) + + async def test_the_tool_message_chunk_carries_the_graphs_metadata_too(self): + compiled = _config_graph(graph_config={"metadata": {"gm": 1}}) + native, ours = await _both(compiled, "meta-toolmsg", ADD_INPUT) + tool_chunks = [ + md + for mode, (m, md) in [i for i in ours if i[0] == "messages"] + if isinstance(m, ToolMessage) + ] + self.assertEqual(len(tool_chunks), 1) + self.assertEqual(tool_chunks[0]["gm"], 1) + + +def _subgraph_graph() -> Any: + model = _StreamingModel() + + def inner(state: MessagesState) -> dict: + return {"messages": [model.invoke(state["messages"])]} + + sub = StateGraph(MessagesState) + sub.add_node("inner", inner) + sub.add_edge(START, "inner") + sub.add_edge("inner", END) + + outer = StateGraph(MessagesState) + outer.add_node("outer", sub.compile()) + outer.add_edge(START, "outer") + outer.add_edge("outer", END) + return outer.compile() + + +class TestSubgraphNode(_Golden): + async def test_messages_are_the_outer_nodes_output_not_the_inner_tokens(self): + native, ours = await _both(_subgraph_graph(), "golden-sub", INPUT) + messages = [i[1] for i in ours if i[0] == "messages"] + self.assertEqual([m[1]["langgraph_node"] for m in messages], ["outer"]) + self.assertEqual(messages[0][0].content, "Hello world") + self.assertNotIn( + "inner", " ".join(m[1]["langgraph_checkpoint_ns"] for m in messages) + ) + self._assert_same_sequence(native, ours) + + def test_the_final_state_has_each_message_once_as_native_does(self): + compiled = _subgraph_graph() + runner = DaprWorkflowGraphRunner(graph=compiled, name="golden-sub-out") + out = _run(runner, INPUT) + self.assertEqual(out.status, "completed", out.error) + got = [(m["type"], m["content"]) for m in out.output["messages"]] + want = [(m.type, m.content) for m in compiled.invoke(INPUT)["messages"]] + self.assertEqual(got, want) + + +def _map_reduce(*, goto: bool = False) -> Any: + def work(arg: dict) -> dict: + return {"out": [arg["i"] * 10]} + + def fan(state: _Out) -> Any: + sends = [Send("work", {"i": i}) for i in (1, 2, 3)] + return Command(goto=sends) if goto else {"out": []} + + graph = StateGraph(_Out) + graph.add_node("fan", fan) + graph.add_node("work", work) + graph.add_edge(START, "fan") + if not goto: + graph.add_conditional_edges( + "fan", lambda state: [Send("work", {"i": i}) for i in (1, 2, 3)], ["work"] + ) + graph.add_edge("work", END) + return graph.compile() + + +def _updates(items: List) -> List[str]: + return sorted( + json.dumps(p, sort_keys=True, default=str) + for m, p in _wire(items) + if m == "updates" + ) + + +class TestMapReduce(_Golden): + def test_every_send_runs_the_node_on_its_argument(self): + for goto in (False, True): + with self.subTest(goto=goto): + self.setUp() + compiled = _map_reduce(goto=goto) + out = _run( + DaprWorkflowGraphRunner(graph=compiled, name=f"send-{goto}"), + {"out": []}, + ) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual( + sorted(out.output["out"]), + sorted(compiled.invoke({"out": []})["out"]), + ) + self.assertEqual(sorted(out.output["out"]), [10, 20, 30]) + + async def test_one_updates_chunk_per_send_like_native(self): + for goto in (False, True): + with self.subTest(goto=goto): + self.setUp() + native, ours = await _both( + _map_reduce(goto=goto), f"send-stream-{goto}", {"out": []} + ) + self.assertEqual(_updates(ours), _updates(native)) + works = [p for m, p in ours if m == "updates" and "work" in p] + self.assertEqual(len(works), 3) + + async def test_the_sends_are_push_tasks_in_the_metadata(self): + from langchain_core.messages import AIMessageChunk + + from .test_streaming import _StreamingModel + + model = _StreamingModel() + + def work(arg: dict) -> dict: + model.invoke("hi") + return {"out": [arg["i"]]} + + graph = StateGraph(_Out) + graph.add_node("work", work) + graph.add_conditional_edges( + START, lambda state: [Send("work", {"i": i}) for i in (1, 2)], ["work"] + ) + graph.add_edge("work", END) + native, ours = await _both(graph.compile(), "send-meta", {"out": []}) + + def push(items: List) -> List[Any]: + return sorted( + ( + md["langgraph_triggers"], + tuple(md["langgraph_path"][:1]), + md["langgraph_step"], + ) + for m, (c, md) in [i for i in items if i[0] == "messages"] + if isinstance(c, AIMessageChunk) + ) + + self.assertEqual(push(ours), push(native)) + self.assertTrue(all(t == ("__pregel_push",) for t, _, _ in push(ours))) + + def test_a_send_of_a_node_that_a_static_edge_also_reaches_runs_both(self): + def work(state: Any) -> dict: + return {"out": ["arg" if "i" in state else "state"]} + + graph = StateGraph(_Out) + graph.add_node("a", lambda state: {"out": ["a"]}) + graph.add_node("work", work) + graph.add_edge(START, "a") + graph.add_edge("a", "work") + graph.add_conditional_edges("a", lambda s: [Send("work", {"i": 1})], ["work"]) + graph.add_edge("work", END) + compiled = graph.compile() + out = _run( + DaprWorkflowGraphRunner(graph=compiled, name="send-both"), {"out": []} + ) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual( + sorted(out.output["out"]), sorted(compiled.invoke({"out": []})["out"]) + ) + + +class TestPrebuiltAgentToolCalls(_Golden): + """``create_agent`` sends each tool call to ``tools`` as a ``Send``.""" + + def _agent(self) -> Any: + from langchain.agents import create_agent + from langchain_core.language_models import BaseChatModel + from langchain_core.outputs import ChatGeneration, ChatResult + from langchain_core.tools import tool + + @tool + def add(a: int, b: int) -> int: + """Add.""" + return a + b + + class Model(BaseChatModel): + @property + def _llm_type(self) -> str: + return "two-calls" + + def bind_tools(self, tools: Any, **kw: Any) -> "Model": + return self + + def _generate(self, messages, stop=None, run_manager=None, **kw): + if any(m.type == "tool" for m in messages): + msg = AIMessage(content="done") + else: + msg = AIMessage( + content="", + tool_calls=[ + {"name": "add", "args": {"a": 1, "b": 2}, "id": "c1"}, + {"name": "add", "args": {"a": 3, "b": 4}, "id": "c2"}, + ], + ) + return ChatResult(generations=[ChatGeneration(message=msg)]) + + return create_agent(Model(), tools=[add]) + + async def test_two_tool_calls_are_two_tools_updates(self): + try: + compiled = self._agent() + except ImportError: + self.skipTest("langchain.agents is not installed") + native, ours = await _both( + compiled, + "send-create-agent", + {"messages": [{"role": "user", "content": "go"}]}, + ) + tools = [p for m, p in ours if m == "updates" and "tools" in p] + want = [p for m, p in native if m == "updates" and "tools" in p] + self.assertEqual(len(want), 2) + self.assertEqual(len(tools), 2) + + +def _send_router_graph(*, pull_too: bool = False) -> Any: + model = _StreamingModel() + + def work(arg: Any) -> dict: + get_stream_writer()({"work": arg.get("i") if isinstance(arg, dict) else None}) + return {"out": ["w"]} + + def route(state: _Out) -> str: + get_stream_writer()("route") + model.invoke("which way?") + return END + + def fan(state: _Out) -> Any: + return Command( + goto=[Send("work", {"i": i}) for i in (1, 2, 3)] + + (["work"] if pull_too else []) + ) + + graph = StateGraph(_Out) + graph.add_node("fan", fan) + graph.add_node("work", work) + graph.add_edge(START, "fan") + graph.add_conditional_edges("work", route, [END]) + return graph.compile() + + +def _tasks(items: List) -> List[str]: + """The (path, triggers) of every token chunk, whichever task's it is.""" + return sorted( + json.dumps([md["langgraph_path"], md["langgraph_triggers"]], default=str) + for m, (c, md) in [i for i in _wire(items) if i[0] == "messages"] + for _ in [0] + ) + + +class TestRouterOfSendTasks(_Golden): + async def test_each_router_streams_as_its_own_task_without_a_reset(self): + native, ours = await _both(_send_router_graph(), "send-router", {"out": []}) + self.assertNotIn("node_reset", [m for m, _ in ours]) + self.assertEqual(_canonical(ours), _canonical(native)) + + async def test_a_pull_task_and_send_tasks_of_one_node(self): + native, ours = await _both( + _send_router_graph(pull_too=True), "send-router-pull", {"out": []} + ) + self.assertNotIn("node_reset", [m for m, _ in ours]) + # which task a message id goes to depends on the order the tasks ran in + self.assertEqual(_tasks(ours), _tasks(native)) + self.assertEqual( + sorted(c for m, c in ours if m == "custom" and isinstance(c, str)), + ["route"] * 4, + ) + + async def test_the_routers_tokens_carry_the_push_path_and_trigger(self): + _, ours = await _both(_send_router_graph(), "send-router-meta", {"out": []}) + routed = [ + md + for m, (c, md) in [i for i in ours if i[0] == "messages"] + if isinstance(c, AIMessageChunk) + ] + self.assertEqual(sorted({md["langgraph_path"][1] for md in routed}), [0, 1, 2]) + self.assertTrue( + all(md["langgraph_triggers"] == ("__pregel_push",) for md in routed) + ) + + +class _GotoState(TypedDict, total=False): + count: int + log: Annotated[list, operator.add] + + +def _goto_runner(name: str, build: Any) -> DaprWorkflowGraphRunner: + graph = StateGraph(_GotoState) + build(graph) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name=name) + runner._started = True + return runner + + +def _goto_b(graph: Any) -> None: + def a(state: _GotoState) -> Command[Literal["b"]]: + return Command(update={"count": 5, "log": ["a"]}, goto="b") + + def b(state: _GotoState) -> dict: + return {"count": state["count"] + 1, "log": ["b"]} + + graph.add_node("a", a) + graph.add_node("b", b) + graph.add_edge(START, "a") + graph.add_edge("b", END) + + +class TestGoto(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def test_the_workflow_follows_goto(self): + runner = _goto_runner("goto-wf", _goto_b) + out = _run(runner, {"count": 0, "log": []}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.executed, [["a"], ["b"]]) + self.assertEqual(out.output["count"], 6) + + async def test_the_stream_shows_the_target_node_like_native_astream(self): + runner = _goto_runner("goto-stream", _goto_b) + native = [ + c + async for c in runner.graph.astream( + {"count": 0, "log": []}, stream_mode="updates" + ) + ] + with mock.patch.object(runner, "run_async", _fake_run_async(runner)): + ours = await _collect( + runner.astream( + {"count": 0, "log": []}, + workflow_id="wf-goto", + stream_mode="updates", + ) + ) + self.assertEqual([list(c) for c in ours], [list(c) for c in native]) + self.assertEqual(ours, native) + + async def test_goto_a_list_fans_out(self): + def build(graph: Any) -> None: + def a(state: _GotoState) -> Command[Literal["b", "c"]]: + return Command(update={"log": ["a"]}, goto=["b", "c"]) + + graph.add_node("a", a) + graph.add_node("b", lambda state: {"log": ["b"]}) + graph.add_node("c", lambda state: {"log": ["c"]}) + graph.add_edge(START, "a") + graph.add_edge("b", END) + graph.add_edge("c", END) + + out = _run(_goto_runner("goto-fan", build), {"log": []}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.executed[0], ["a"]) + self.assertCountEqual(out.executed[1], ["b", "c"]) + + async def test_goto_a_node_that_a_static_edge_also_reaches_runs_it_once(self): + def build(graph: Any) -> None: + def a(state: _GotoState) -> Command[Literal["b"]]: + return Command(update={"log": ["a"]}, goto="b") + + graph.add_node("a", a) + graph.add_node("b", lambda state: {"log": ["b"]}) + graph.add_edge(START, "a") + graph.add_edge("a", "b") + graph.add_edge("b", END) + + out = _run(_goto_runner("goto-dup", build), {"log": []}) + self.assertEqual(out.executed, [["a"], ["b"]]) + + async def test_goto_end_ends_the_run(self): + def build(graph: Any) -> None: + def a(state: _GotoState) -> Command: + return Command(update={"log": ["a"]}, goto=END) + + graph.add_node("a", a) + graph.add_edge(START, "a") + + out = _run(_goto_runner("goto-end", build), {"log": []}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.executed, [["a"]]) + + +class TestSendInGoto(_RunnerTestCase): + def test_a_send_in_command_goto_runs_its_node_on_the_argument(self): + class State(TypedDict, total=False): + x: int + + def a(state: State) -> Command[Literal["w"]]: + return Command(update={"x": 1}, goto=Send("w", {"x": 2})) + + graph = StateGraph(State) + graph.add_node("a", a) + graph.add_node("w", lambda state: {"x": state["x"] + 10}) + graph.add_edge(START, "a") + graph.add_edge("w", END) + compiled = graph.compile() + runner = DaprWorkflowGraphRunner(graph=compiled, name="send-goto") + out = _run(runner, {"x": 0}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.executed, [["a"], ["w#0"]]) + # the node read the Send argument (2), not the channel state (1) + self.assertEqual(out.output["x"], 12) + self.assertEqual(out.output["x"], compiled.invoke({"x": 0})["x"]) diff --git a/tests/agent/langgraph/test_streaming_lifecycle.py b/tests/agent/langgraph/test_streaming_lifecycle.py new file mode 100644 index 00000000..8fa97740 --- /dev/null +++ b/tests/agent/langgraph/test_streaming_lifecycle.py @@ -0,0 +1,610 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A streamed run alongside other things going on: a client that stays or leaves +and the result that is published either way, runs that overlap, and attempts +that overlap.""" + +import asyncio +import gc +import json +import threading +import unittest +import weakref +from contextlib import aclosing +from typing import Any, Dict, List +from unittest import mock + +from fastapi.testclient import TestClient +from langgraph.config import get_stream_writer +from langgraph.graph import END, START, MessagesState, StateGraph + +from diagrid.agent.core.workflow.stream import ( + InProcessSink, + StreamClosed, + StreamEvent, + StreamSinkRegistry, +) +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.workflow import ( + clear_registries, + execute_node_activity, + register_node, +) + +from .streaming_helpers import ( + ENDINGS, + INPUT, + STARTED, + _chat_graph, + _collect, + _completed, + _Ctx, + _fake_run_async, + _payload, + _ScriptedCase, + serve_app, +) +from .test_runner import _RunnerTestCase + +PUBLISH_WAIT = 5 + + +class _PublishCase(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + def _setup(self, name: str): + """A runner whose run waits on ``self.release`` before it completes.""" + self.release = asyncio.Event() + self.published: List[Dict[str, Any]] = [] + self.topics: List[str] = [] + runner = _chat_graph(name=name) + runner._started = True + + async def run_async( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + yield { + "type": "workflow_started", + "workflow_id": workflow_id, + "thread_id": thread_id, + } + runner.stream_registry.get(workflow_id).put( + StreamEvent(workflow_id, 0, "chat", "a", 0, (), "custom", "first") + ) + await self.release.wait() + yield { + "type": "workflow_completed", + "workflow_id": workflow_id, + "output": {"x": 1}, + "steps": 1, + "status": "completed", + } + + patch = mock.patch.object(runner, "run_async", run_async) + patch.start() + self.addCleanup(patch.stop) + + fake = mock.Mock() + fake.publish.side_effect = lambda topic, data: ( + self.topics.append(topic), + self.published.append(data), + ) + with mock.patch("diagrid.agent.core.pubsub.DaprPubSub", return_value=fake): + app = serve_app(runner, pubsub_name="ps", publish_topic="out") + self.route = next( + r + for r in app.routes + if getattr(r, "path", "") == "/agent/run" and "POST" in r.methods + ) + return runner, app + + async def _published(self, count: int = 1) -> None: + async def wait() -> None: + while len(self.published) < count: + await asyncio.sleep(0.01) + + await asyncio.wait_for(wait(), PUBLISH_WAIT) + await asyncio.sleep(0.05) # a second publish would show up now + + +class TestDisconnect(_PublishCase): + async def test_client_leaves_at_the_terminal_frame(self): + runner, _ = self._setup("pub-end") + self.release.set() + response = await self.route.endpoint({"task": "hi", "stream": True}) + body = response.body_iterator + async for frame in body: + if "event: workflow_completed" in frame: + break # the client goes away while the generator is suspended here + await body.aclose() + await self._published() + self.assertEqual(len(self.published), 1) + self.assertEqual(self.published[0]["type"], "workflow_completed") + + async def test_client_leaves_mid_run_and_the_run_still_publishes(self): + runner, _ = self._setup("pub-mid") + response = await self.route.endpoint({"task": "hi", "stream": True}) + body = response.body_iterator + self.assertIn("event: workflow_started", await body.__anext__()) + self.assertIn("event: custom", await body.__anext__()) + self.assertEqual(len(runner.stream_registry._sinks), 1) # the run's own + await body.aclose() # what the server does when the client hangs up + # The stream is closed at once, the run is still going. + self.assertEqual(self.published, []) + self.assertEqual(runner.stream_registry._sinks, {}) + self.release.set() + await self._published() + self.assertEqual(len(self.published), 1) + result = self.published[0] + self.assertEqual(result["type"], "workflow_completed") + self.assertEqual(result["output"], {"x": 1}) + self.assertTrue(result["instance_id"].startswith("graph-")) + + async def test_a_client_that_stays_causes_exactly_one_publish(self): + runner, _ = self._setup("pub-stay") + self.release.set() + response = await self.route.endpoint({"task": "hi", "stream": True}) + frames = [frame async for frame in response.body_iterator] + self.assertIn("event: workflow_completed", frames[-1]) + await self._published() + self.assertEqual(len(self.published), 1) + self.assertEqual(self.topics, ["out"]) + self.assertEqual(self.published[0]["type"], "workflow_completed") + + async def test_a_real_asgi_disconnect_mid_run_still_publishes(self): + runner, app = self._setup("pub-asgi") + body = json.dumps({"task": "hi", "stream": True}).encode() + first_frame = asyncio.Event() + sent: List[Dict[str, Any]] = [] + delivered = False + + async def receive() -> Dict[str, Any]: + nonlocal delivered + if not delivered: + delivered = True + return {"type": "http.request", "body": body, "more_body": False} + await first_frame.wait() + return {"type": "http.disconnect"} + + async def send(message: Dict[str, Any]) -> None: + sent.append(message) + if message["type"] == "http.response.body" and message.get("body"): + first_frame.set() + + scope = { + "type": "http", + "asgi": {"version": "3.0"}, + "http_version": "1.1", + "method": "POST", + "path": "/agent/run", + "raw_path": b"/agent/run", + "query_string": b"", + "headers": [(b"content-type", b"application/json")], + "client": ("t", 1), + "server": ("t", 80), + "scheme": "http", + } + await asyncio.wait_for(app(scope, receive, send), PUBLISH_WAIT) + self.assertEqual(self.published, []) + self.release.set() + await self._published() + self.assertEqual(len(self.published), 1) + self.assertEqual(self.published[0]["type"], "workflow_completed") + + +class TestDetachedPumpIsKeptAlive(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def test_a_pump_nobody_else_references_survives_garbage_collection(self): + runner = _chat_graph(name="gc-pump") + runner._started = True + gate: List["weakref.ref[asyncio.Event]"] = [] + + async def run_async( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + # Only the pump's own frames reference this event, and the test only + # a weak reference: whatever keeps the pump alive is what keeps it. + event = asyncio.Event() + gate.append(weakref.ref(event)) + yield {"type": "workflow_started", "workflow_id": workflow_id} + await event.wait() + yield {"type": "workflow_completed", "workflow_id": workflow_id} + + published: List[Any] = [] + fake = mock.Mock() + fake.publish.side_effect = lambda topic, data: published.append(data) + with ( + mock.patch.object(runner, "run_async", run_async), + mock.patch("diagrid.agent.core.pubsub.DaprPubSub", return_value=fake), + ): + app = serve_app(runner, pubsub_name="ps", publish_topic="out") + route = next( + r + for r in app.routes + if getattr(r, "path", "") == "/agent/run" and "POST" in r.methods + ) + with mock.patch.object(runner, "run_async", run_async): + response = await route.endpoint({"task": "hi", "stream": True}) + body = response.body_iterator + await body.__anext__() # workflow_started + await body.aclose() # the client leaves; the pump carries on alone + for _ in range(3): + gc.collect() + await asyncio.sleep(0) + event = gate[0]() + self.assertIsNotNone(event, "the detached pump was garbage collected") + event.set() + for _ in range(100): + if published: + break + await asyncio.sleep(0.01) + self.assertEqual([p["type"] for p in published], ["workflow_completed"]) + + +class TestPublishedPayloadsMatch(_ScriptedCase): + def _publish(self, runner, body: Dict[str, Any]) -> Dict[str, Any]: + published: List[Any] = [] + fake = mock.Mock() + fake.publish.side_effect = lambda topic, data: published.append(data) + with mock.patch("diagrid.agent.core.pubsub.DaprPubSub", return_value=fake): + client = self._client(runner, pubsub_name="ps", publish_topic="out") + client.post("/agent/run", json=body) + self.assertEqual(len(published), 1) + return published[0] + + async def test_every_failure_ending_publishes_the_same_result_streamed_or_not(self): + for name, row in ENDINGS.items(): + with self.subTest(ending=name): + self.setUp() + runner = self._runner(row["events"], f"pub-{name}") + body = {"task": "hi", "thread_id": "t-pub"} + plain = self._publish(runner, body) + streamed = self._publish(runner, {**body, "stream": True}) + self.assertEqual(streamed, plain) + if "error" in row: # a workflow_failed final carries its detail + self.assertEqual(plain["error"], row["error"]) + self.assertEqual(plain["workflow_id"], "wf-fixed") + self.assertEqual(plain["thread_id"], "t-pub") + + async def test_success_publishes_the_same_shape_streamed_or_not(self): + runner = self._runner([STARTED, _completed("completed")], "pub-ok") + body = {"task": "hi", "thread_id": "t-pub"} + plain = self._publish(runner, body) + streamed = self._publish(runner, {**body, "stream": True}) + self.assertEqual(streamed, plain) + + +class TestPublishLeavesTheLoop(_RunnerTestCase, unittest.TestCase): + def _post(self, body: Dict[str, Any]) -> Dict[str, List[int]]: + """Thread idents of the event loop and of each publish call.""" + runner = _chat_graph(name="offloop-pub") + runner._started = True + idents: Dict[str, List[int]] = {"loop": [], "publish": []} + + async def run_async( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + idents["loop"].append(threading.get_ident()) + yield {"type": "workflow_started", "workflow_id": workflow_id} + yield { + "type": "workflow_completed", + "workflow_id": workflow_id, + "output": {"x": 1}, + "steps": 0, + "status": "completed", + } + + fake = mock.Mock() + fake.publish.side_effect = lambda topic, data: idents["publish"].append( + threading.get_ident() + ) + with ( + mock.patch.object(runner, "run_async", run_async), + mock.patch("diagrid.agent.core.pubsub.DaprPubSub", return_value=fake), + ): + app = serve_app(runner, pubsub_name="ps", publish_topic="out") + TestClient(app).post("/agent/run", json=body) + return idents + + def _assert_off_the_loop(self, body: Dict[str, Any]) -> None: + idents = self._post(body) + self.assertEqual(len(idents["publish"]), 1) + self.assertNotIn(idents["publish"][0], idents["loop"]) + + def test_a_run_publishes_off_the_loop_streamed_or_not(self): + for name, body in ( + ("plain", {"task": "hi"}), + ("streamed", {"task": "hi", "stream": True}), + ): + with self.subTest(run=name): + self.setUp() + self._assert_off_the_loop(body) + + +WAIT = 10 + + +class TestTwoRunsAtOnce(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def test_concurrent_runs_each_get_only_their_own_chunks(self): + both_inside = threading.Barrier(2, timeout=WAIT) + reached_barrier: List[str] = [] + + def node(state: MessagesState) -> dict: + last = state["messages"][-1] + who = last["content"] if isinstance(last, dict) else last.content + writer = get_stream_writer() + writer(f"{who}-1") + # Hold both activities inside their node at the same moment; a + # sequential run would time out here. + both_inside.wait() + reached_barrier.append(who) + writer(f"{who}-2") + return {"messages": [{"role": "ai", "content": f"done {who}"}]} + + graph = StateGraph(MessagesState) + graph.add_node("n", node) + graph.add_edge(START, "n") + graph.add_edge("n", END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="concurrent") + runner._started = True + + async def one(who: str) -> List[Any]: + return await _collect( + runner.astream( + {"messages": [{"role": "user", "content": who}]}, + workflow_id=f"wf-{who}", + stream_mode="custom", + ) + ) + + with ( + mock.patch.object(runner, "run_async", _fake_run_async(runner)), + mock.patch("diagrid.agent.langgraph.workflow.when_all", side_effect=list), + ): + a, b = await asyncio.gather(one("A"), one("B")) + + self.assertCountEqual(reached_barrier, ["A", "B"]) + self.assertEqual(a, ["A-1", "A-2"]) + self.assertEqual(b, ["B-1", "B-2"]) + self.assertIsNone(runner.stream_registry.get("wf-A")) + self.assertIsNone(runner.stream_registry.get("wf-B")) + + +class TestRetryWhileTheOldAttemptIsStillRunning(unittest.IsolatedAsyncioTestCase): + def setUp(self): + clear_registries() + self.addCleanup(clear_registries) + + async def test_late_chunks_of_the_old_attempt_are_dropped(self): + a_streamed = threading.Event() + b_finished = threading.Event() + calls: List[str] = [] + lock = threading.Lock() + + def node(state) -> dict: + with lock: + attempt = "A" if not calls else "B" + calls.append(attempt) + writer = get_stream_writer() + if attempt == "A": + writer("A-early") + a_streamed.set() + self.assertTrue(b_finished.wait(WAIT)) + writer("A-late") # the engine already moved on to attempt B + return {"x": "from-A"} + self.assertTrue(a_streamed.wait(WAIT)) + writer("B-only") + return {"x": "from-B"} + + register_node("n", node) + registry = StreamSinkRegistry() + sink = registry.open("wf-retry") + + def run(ctx_id: int) -> Any: + return execute_node_activity( + _Ctx("wf-retry", ctx_id), + _payload("n", step=3, streamed=False), + stream_registry=registry, + ) + + async def attempt_b() -> Any: + out = await asyncio.to_thread(run, 2) + b_finished.set() + return out + + a_task = asyncio.create_task(asyncio.to_thread(run, 1)) + self.assertTrue(await asyncio.to_thread(a_streamed.wait, WAIT)) + out_b = await attempt_b() + out_a = await a_task # A finishes last, with its own (stale) result + + sink.close({"type": "workflow_completed"}) + items: List[Any] = [] + while True: + item = await sink.get() + if isinstance(item, StreamClosed): + break + items.append(item) + + shown = [(e.mode, e.data) for e in items] + self.assertEqual( + shown, + [ + ("custom", "A-early"), + ("node_reset", {"node": "n", "step": 4}), + ("custom", "B-only"), + ("updates", {"n": {"x": "from-B"}}), + ], + ) + # Dapr keeps only one attempt's result; the sink must never show a + # chunk the surviving attempt did not produce. + self.assertEqual(out_b["writes"][0]["value"], "from-B") + self.assertEqual(out_a["writes"][0]["value"], "from-A") + + async def test_late_chunks_are_dropped_while_the_new_attempt_is_running(self): + """A writes after B started but before B finished: B must not be mixed + with A's text.""" + b_streamed = threading.Event() + a_wrote_late = threading.Event() + a_streamed = threading.Event() + calls: List[str] = [] + lock = threading.Lock() + + def node(state) -> dict: + with lock: + attempt = "A" if not calls else "B" + calls.append(attempt) + writer = get_stream_writer() + if attempt == "A": + writer("A-early") + a_streamed.set() + self.assertTrue(b_streamed.wait(WAIT)) + writer("A-late") + a_wrote_late.set() + return {"x": "from-A"} + self.assertTrue(a_streamed.wait(WAIT)) + writer("B-1") + b_streamed.set() + self.assertTrue(a_wrote_late.wait(WAIT)) + writer("B-2") + return {"x": "from-B"} + + register_node("n", node) + registry = StreamSinkRegistry() + sink = registry.open("wf-retry2") + + def run(task_id: int) -> Any: + return execute_node_activity( + _Ctx("wf-retry2", task_id), + _payload("n", streamed=False), + stream_registry=registry, + ) + + a_task = asyncio.create_task(asyncio.to_thread(run, 1)) + self.assertTrue(await asyncio.to_thread(a_streamed.wait, WAIT)) + await asyncio.to_thread(run, 2) + await a_task + + sink.close({"type": "workflow_completed"}) + shown: List[Any] = [] + while True: + item = await sink.get() + if isinstance(item, StreamClosed): + break + shown.append((item.mode, item.data)) + self.assertEqual( + shown, + [ + ("custom", "A-early"), + ("node_reset", {"node": "n", "step": 1}), + ("custom", "B-1"), + ("custom", "B-2"), + ("updates", {"n": {"x": "from-B"}}), + ], + ) + + +class TestClientGoesAway(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + def _runner(self, name: str): + runner = DaprWorkflowGraphRunner(graph=_slow_graph(), name=name) + runner._started = True + return runner + + async def test_abandoned_astream_closes_the_sink_and_stops_the_run(self): + runner = self._runner("gone-astream") + run_cancelled = asyncio.Event() + + async def endless( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + sink = runner.stream_registry.get(workflow_id) + sink.put(StreamEvent(workflow_id, 0, "n", "a", 0, (), "custom", "first")) + try: + await asyncio.sleep(3600) + yield {} # pragma: no cover + except asyncio.CancelledError: + run_cancelled.set() + raise + + with mock.patch.object(runner, "run_async", endless): + stream = runner.astream(INPUT, workflow_id="wf-gone", stream_mode="custom") + self.assertEqual(await stream.__anext__(), "first") + self.assertIsNotNone(runner.stream_registry.get("wf-gone")) + await stream.aclose() + self.assertIsNone(runner.stream_registry.get("wf-gone")) + self.assertTrue(run_cancelled.is_set()) + + async def _endless_run(self, runner): + async def endless( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + sink = runner.stream_registry.get(workflow_id) + sink.put(StreamEvent(workflow_id, 0, "n", "a", 0, (), "custom", "first")) + await asyncio.sleep(3600) + yield {} # pragma: no cover + + return endless + + async def test_aclosing_releases_the_stream_on_break(self): + runner = self._runner("gone-aclosing") + with mock.patch.object(runner, "run_async", await self._endless_run(runner)): + async with aclosing( + runner.astream(INPUT, workflow_id="wf-ac", stream_mode="custom") + ) as stream: + async for _ in stream: + break + self.assertIsNone(runner.stream_registry.get("wf-ac")) + + async def test_bare_break_keeps_the_stream_open_until_it_is_closed(self): + # What the astream docstring says: break alone does not close the + # stream while the generator is still referenced. + runner = self._runner("gone-break") + with mock.patch.object(runner, "run_async", await self._endless_run(runner)): + stream = runner.astream(INPUT, workflow_id="wf-br", stream_mode="custom") + async for _ in stream: + break + await asyncio.sleep(0.05) + self.assertIsNotNone(runner.stream_registry.get("wf-br")) + await stream.aclose() + self.assertIsNone(runner.stream_registry.get("wf-br")) + + async def test_late_chunks_after_the_client_left_are_ignored(self): + runner = self._runner("gone-late") + registry = runner.stream_registry + captured: List[InProcessSink] = [] + original = registry.open + + def spy(workflow_id): + sink = original(workflow_id) + captured.append(sink) + return sink + + async def endless( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + registry.get(workflow_id).put( + StreamEvent(workflow_id, 0, "n", "a", 0, (), "custom", "first") + ) + await asyncio.sleep(3600) + yield {} # pragma: no cover + + with ( + mock.patch.object(registry, "open", spy), + mock.patch.object(runner, "run_async", endless), + ): + stream = runner.astream(INPUT, workflow_id="wf-late", stream_mode="custom") + await stream.__anext__() + await stream.aclose() + (sink,) = captured + # The activity is still running on its thread and keeps writing. + sink.put(StreamEvent("wf-late", 0, "n", "a", 1, (), "custom", "late")) + await asyncio.sleep(0) + # Only the close marker is delivered: the late chunk was refused. + self.assertIsInstance(await sink.get(), StreamClosed) + with self.assertRaises(asyncio.TimeoutError): + await asyncio.wait_for(sink.get(), 0.1) + + +def _slow_graph() -> Any: + graph = StateGraph(MessagesState) + graph.add_node("n", lambda state: {}) + graph.add_edge(START, "n") + graph.add_edge("n", END) + return graph.compile() diff --git a/tests/agent/langgraph/test_streaming_poll_retry.py b/tests/agent/langgraph/test_streaming_poll_retry.py new file mode 100644 index 00000000..89f97160 --- /dev/null +++ b/tests/agent/langgraph/test_streaming_poll_retry.py @@ -0,0 +1,266 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A failed status poll is not a failed workflow. + +Poll retries are for transient sidecar errors, opt-in, bounded, and count +consecutive failures only; and no blocking sidecar call runs on the event loop +that delivers tokens. +""" + +import ssl +import threading +import unittest +from typing import Any, Dict, List +from unittest import mock + +import grpc +from dapr.ext.workflow import WorkflowStatus +from fastapi.testclient import TestClient + +from diagrid.agent.core.workflow import runner as core_runner +from diagrid.agent.langgraph.streaming import GraphRunError + +from .streaming_helpers import ( + INPUT, + _collect, + _completed_state, + _PollCase, + _state, + _Unavailable, + parse_sse, + serve_app, +) + +MAX = core_runner.POLL_MAX_ERRORS + + +class _Rpc(grpc.RpcError): + """A gRPC error that carries no status, as a bare ``RpcError`` does.""" + + +def _rpc_error(code: grpc.StatusCode) -> grpc.RpcError: + class _Coded(grpc.RpcError): + def code(self) -> grpc.StatusCode: + return code + + return _Coded() + + +# What the poll loop retries (True) and what it lets through at once (False). +CLASSIFICATION = { + **{ + f"grpc-{code.name}": (_rpc_error(code), True) + for code in ( + grpc.StatusCode.UNAVAILABLE, + grpc.StatusCode.DEADLINE_EXCEEDED, + grpc.StatusCode.ABORTED, + grpc.StatusCode.RESOURCE_EXHAUSTED, + grpc.StatusCode.CANCELLED, + ) + }, + **{ + f"grpc-{code.name}": (_rpc_error(code), False) + for code in ( + grpc.StatusCode.PERMISSION_DENIED, + grpc.StatusCode.UNAUTHENTICATED, + grpc.StatusCode.UNIMPLEMENTED, + grpc.StatusCode.INVALID_ARGUMENT, + grpc.StatusCode.NOT_FOUND, + ) + }, + "grpc-without-a-status": (_Rpc(), False), + "connection-reset": (ConnectionResetError("x"), True), + "connection-refused": (ConnectionRefusedError("x"), True), + "timeout": (TimeoutError("x"), True), + "permission": (PermissionError("x"), False), + "bad-socket-path": (FileNotFoundError("x"), False), + "ssl": (ssl.SSLError("x"), False), + "plain-os-error": (OSError("x"), False), + "bug": (TypeError("x"), False), +} + + +class TestWhichPollErrorsAreRetried(_PollCase): + def test_classification(self): + for name, (error, transient) in CLASSIFICATION.items(): + with self.subTest(error=name): + self.assertIs(core_runner._is_transient_poll_error(error), transient) + + async def test_a_transient_error_is_ridden_out_and_any_other_surfaces_at_once(self): + for name, (error, transient) in CLASSIFICATION.items(): + with self.subTest(error=name): + self.setUp() + runner, client = self._runner([error, _completed_state()], name) + if transient: + events = await _collect(runner.run_async(INPUT, poll_interval=0)) + self.assertEqual(events[-1]["type"], "workflow_completed") + self.assertEqual(client.get_workflow_state.call_count, 2) + else: + with self.assertRaises(type(error)): + await _collect(runner.run_async(INPUT, poll_interval=0)) + self.assertEqual(client.get_workflow_state.call_count, 1) + + +class TestRetryIsOptIn(_PollCase): + async def test_the_shared_poll_loop_does_not_retry_by_default(self): + runner, client = self._runner( + [_Unavailable("blip"), _completed_state()], "scope-default" + ) + with self.assertRaises(_Unavailable): + async for _ in runner._poll_workflow("wf", "s", poll_interval=0): + pass + self.assertEqual(client.get_workflow_state.call_count, 1) + + async def test_it_retries_when_asked(self): + runner, client = self._runner( + [_Unavailable("blip"), _completed_state()], "scope-asked" + ) + events = [ + e + async for e in runner._poll_workflow( + "wf", "s", poll_interval=0, retry_failed_polls=True + ) + ] + self.assertEqual(events[-1]["type"], "workflow_completed") + + +class TestConsecutiveFailuresOnly(_PollCase): + async def test_scattered_errors_never_add_up(self): + running = _state(WorkflowStatus.RUNNING) + polls: List[Any] = [ + *[_Unavailable("a")] * (MAX - 1), + running, + *[_Unavailable("b")] * (MAX - 1), + _completed_state(), + ] + runner, client = self._runner(polls, "scope-scattered") + events = await _collect(runner.run_async(INPUT, poll_interval=0)) + self.assertEqual(events[-1]["type"], "workflow_completed") + self.assertEqual(client.get_workflow_state.call_count, len(polls)) + + +class TestRetryBound(_PollCase): + async def test_a_permanently_failing_poll_is_tried_exactly_max_plus_one_times(self): + runner, client = self._runner([_Unavailable("down")] * (MAX + 5), "scope-bound") + with self.assertRaises(_Unavailable): + async for _ in runner._poll_workflow( + "wf", "s", poll_interval=0, retry_failed_polls=True + ): + pass + # the first try and MAX retries, then the error is let through + self.assertEqual(client.get_workflow_state.call_count, MAX + 1) + + async def test_the_bound_is_per_stretch_of_failures(self): + running = _state(WorkflowStatus.RUNNING) + polls: List[Any] = [ + *[_Unavailable("a")] * MAX, + running, + *[_Unavailable("b")] * (MAX + 1), + _completed_state(), + ] + runner, client = self._runner(polls, "scope-bound-twice") + with self.assertRaises(_Unavailable): + async for _ in runner._poll_workflow( + "wf", "s", poll_interval=0, retry_failed_polls=True + ): + pass + self.assertEqual(client.get_workflow_state.call_count, 2 * MAX + 2) + + +class TestRetryDelay(unittest.IsolatedAsyncioTestCase): + async def test_the_delay_doubles_and_is_capped(self): + sleeps: List[float] = [] + + async def record(delay: float, *args: Any) -> None: + sleeps.append(delay) + + client = mock.Mock() + client.get_workflow_state.side_effect = [_Unavailable("x")] * (MAX - 1) + [ + _completed_state() + ] + runner = mock.Mock(spec=["_workflow_client"]) + runner._workflow_client = client + with mock.patch.object(core_runner.asyncio, "sleep", record): + async for _ in core_runner.BaseWorkflowRunner._poll_workflow( + runner, "wf", "s", poll_interval=0, retry_failed_polls=True + ): + pass + delays = [d for d in sleeps if d] + self.assertEqual( + delays[:6], [0.5, 1, 2, 4, 8, core_runner.POLL_RETRY_MAX_SECONDS] + ) + self.assertLessEqual(max(delays), core_runner.POLL_RETRY_MAX_SECONDS) + self.assertEqual(max(delays), core_runner.POLL_RETRY_MAX_SECONDS) + + +class TestTransientPollErrors(_PollCase): + async def test_astream_rides_out_a_dropped_poll(self): + runner, client = self._runner( + [ + _state(WorkflowStatus.RUNNING), + _Unavailable("sidecar restarting"), + _state(WorkflowStatus.RUNNING), + _completed_state(), + ], + "poll-ok", + ) + items = await _collect( + runner.astream(INPUT, stream_mode=["updates"], poll_interval=0) + ) + self.assertEqual(items[-1][0], "stream_unavailable") # no sink in this test + self.assertEqual(client.get_workflow_state.call_count, 4) + + +class TestPersistentPollErrors(_PollCase): + def _failing(self, name: str): + polls = [_Unavailable("sidecar gone")] * (core_runner.POLL_MAX_ERRORS + 1) + return self._runner(polls, name) + + async def test_astream_says_the_run_may_still_be_going(self): + runner, _ = self._failing("poll-dead") + with self.assertRaises(GraphRunError) as caught: + await _collect(runner.astream(INPUT, stream_mode=["updates"])) + final = caught.exception.final + self.assertEqual(final["error"]["error_type"], "PollError") + self.assertTrue(final["workflow_still_running"]) + self.assertTrue(final["workflow_id"]) + + async def test_it_is_not_published_as_a_workflow_failure(self): + runner, _ = self._failing("poll-pub") + published: List[Any] = [] + fake = mock.Mock() + fake.publish.side_effect = lambda topic, data: published.append(data) + with mock.patch("diagrid.agent.core.pubsub.DaprPubSub", return_value=fake): + app = serve_app(runner, pubsub_name="ps", publish_topic="out") + resp = TestClient(app).post("/agent/run", json={"task": "hi", "stream": True}) + name, data = parse_sse(resp.text)[-1] + self.assertEqual(name, "workflow_failed") + self.assertTrue(data["workflow_still_running"]) + self.assertEqual(published, []) + + +class TestSidecarCallsLeaveTheLoop(_PollCase): + async def test_polling_and_scheduling_run_in_worker_threads(self): + runner, client = self._runner( + [_state(WorkflowStatus.RUNNING), _completed_state()], "offloop" + ) + loop_thread = threading.get_ident() + threads: Dict[str, List[int]] = {"poll": [], "schedule": []} + polls = client.get_workflow_state.side_effect + + def poll(**kw: Any) -> Any: + threads["poll"].append(threading.get_ident()) + return next(polls_iter) + + polls_iter = iter(polls) + client.get_workflow_state.side_effect = poll + client.schedule_new_workflow.side_effect = lambda **kw: threads[ + "schedule" + ].append(threading.get_ident()) + + events = await _collect(runner.run_async(INPUT, poll_interval=0)) + self.assertEqual(events[-1]["type"], "workflow_completed") + self.assertTrue(threads["poll"] and threads["schedule"]) + for name, idents in threads.items(): + self.assertNotIn(loop_thread, idents, f"{name} ran on the event loop") diff --git a/tests/agent/langgraph/test_streaming_public_api.py b/tests/agent/langgraph/test_streaming_public_api.py new file mode 100644 index 00000000..5f4cd367 --- /dev/null +++ b/tests/agent/langgraph/test_streaming_public_api.py @@ -0,0 +1,102 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The names a streaming caller needs are importable, and every control event +is documented where a consumer looks.""" + +import unittest +from pathlib import Path + +from langgraph.graph import END, START, MessagesState, StateGraph + +from diagrid.agent.core.workflow.stream import ( + CONTROL_MODES, + STREAM_DROPPED, + StreamSinkRegistry, +) +from diagrid.agent.deepagents import DaprWorkflowDeepAgentRunner +from diagrid.agent.langgraph import DaprWorkflowGraphRunner, streaming + +from .test_runner import _RunnerTestCase + + +def _compiled(): + graph = StateGraph(MessagesState) + graph.add_node("n", lambda state: {}) + graph.add_edge(START, "n") + graph.add_edge("n", END) + return graph.compile() + + +class TestExports(unittest.TestCase): + def test_streaming_names_are_exported(self): + import diagrid.agent.langgraph as pkg + + for name in ("GraphRunError", "StreamControl", "StreamSinkRegistry"): + with self.subTest(name=name): + self.assertTrue(hasattr(pkg, name), name) + self.assertIn(name, pkg.__all__) + + def test_exported_registry_is_the_one_runners_take(self): + import diagrid.agent.langgraph as pkg + + self.assertIs(pkg.StreamSinkRegistry, StreamSinkRegistry) + + +class TestServeDocstring(unittest.TestCase): + def test_graph_runner_serve_documents_streaming_and_its_limit(self): + doc = DaprWorkflowGraphRunner.serve.__doc__ or "" + self.assertIn('"stream": true', doc) + self.assertIn("single replica", doc.lower()) + + +class TestDeepAgentRunner(_RunnerTestCase): + def test_stream_registry_is_forwarded(self): + registry = StreamSinkRegistry() + runner = DaprWorkflowDeepAgentRunner( + _compiled(), name="deep-reg", stream_registry=registry + ) + self.assertIs(runner.stream_registry, registry) + + +README = Path(streaming.__file__).with_name("README.md") + + +KINDS = (*CONTROL_MODES, STREAM_DROPPED) + + +class TestControlKindsAreDocumented(unittest.TestCase): + def test_the_stream_control_docstring_lists_every_kind(self): + for kind in KINDS: + self.assertIn(kind, streaming.StreamControl.__doc__ or "", kind) + + def test_the_readme_table_lists_every_kind(self): + table = [ + line for line in README.read_text().splitlines() if line.startswith("| `") + ] + for kind in KINDS: + self.assertTrue(any(line.startswith(f"| `{kind}`") for line in table), kind) + + def test_workflow_started_is_said_to_be_on_control_only(self): + doc = " ".join((streaming.StreamControl.__doc__ or "").split()) + self.assertIn("only ever given to ``on_control`` and never yielded", doc) + + +class TestSendTaskNameIsDocumentedWhereItIsSeen(unittest.TestCase): + """``executed`` never reaches a reader; ``missing_nodes`` is where ``node#k`` does.""" + + def _lines(self): + return README.read_text().splitlines() + + def test_the_stream_unavailable_row_names_a_send_task(self): + row = next( + line for line in self._lines() if line.startswith("| `stream_unavailable`") + ) + self.assertIn("node#k", row) + + def test_the_send_bullet_does_not_point_at_the_hidden_executed_key(self): + text = README.read_text() + start = text.index("- **`Send` tasks.**") + bullet = text[start : text.index("\n- ", start + 1)] + self.assertIn("missing_nodes", bullet) + self.assertNotIn("In `executed`", bullet) diff --git a/tests/agent/langgraph/test_streaming_sink.py b/tests/agent/langgraph/test_streaming_sink.py new file mode 100644 index 00000000..8ebce102 --- /dev/null +++ b/tests/agent/langgraph/test_streaming_sink.py @@ -0,0 +1,576 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The stream sink: its bounded buffer, many emitting threads, a retried node and +the registry that hands each run its sink.""" + +import asyncio +import threading +import unittest +from typing import Any, List +from unittest import mock + +from langgraph.config import get_stream_writer + +from diagrid.agent.core.workflow import stream as stream_module +from diagrid.agent.core.workflow.stream import ( + NODE_RESET, + InProcessSink, + StreamClosed, + StreamEvent, + StreamSinkRegistry, + default_registry, + get_stream_sink, +) +from diagrid.agent.langgraph.models import ChannelState, ExecuteNodeInput +from diagrid.agent.langgraph.streaming import GraphRunError, NodeStreamer +from diagrid.agent.langgraph.workflow import ( + clear_registries, + execute_node_activity, + register_node, +) + +from .streaming_helpers import ( + INPUT, + TOKENS, + _chat_graph, + _collect, + _Ctx, + _drain, + _event, + _fake_run_async, + _payload, + _StreamingModel, + parse_sse, + serve_app, +) +from .test_runner import _clear_dapr_registration, _RunnerTestCase + +CAP = 3 + + +class TestBufferCap(unittest.IsolatedAsyncioTestCase): + def setUp(self): + patch = mock.patch.object(stream_module, "MAX_BUFFERED_EVENTS", CAP) + patch.start() + self.addCleanup(patch.stop) + + async def test_chunks_past_the_cap_are_dropped_and_counted(self): + sink = InProcessSink("wf", asyncio.get_running_loop()) + for seq in range(10): + sink.put(_event("a1", seq)) + sink.close({"type": "workflow_completed"}) + items = await _drain(sink) + kept = [i for i in items if isinstance(i, StreamEvent)] + self.assertEqual([e.data for e in kept], ["a1-0", "a1-1", "a1-2"]) + self.assertEqual(items[-1].dropped, 7) + + async def test_updates_are_never_dropped(self): + sink = InProcessSink("wf", asyncio.get_running_loop()) + for seq in range(10): + sink.put(_event("a1", seq)) + sink.put(_event("a1", 10, "updates")) + sink.put(_event("a1", 11, "updates", node="other")) + sink.close() + items = await _drain(sink) + updates = [ + i for i in items if isinstance(i, StreamEvent) and i.mode == "updates" + ] + self.assertEqual(len(updates), 2) + self.assertEqual(items[-1].dropped, 7) + + async def test_node_reset_is_never_dropped(self): + sink = InProcessSink("wf", asyncio.get_running_loop()) + for seq in range(10): + sink.put(_event("a1", seq)) + sink.put(_event("a2", 0)) # a retry starts: reset must reach the client + sink.close() + items = await _drain(sink) + resets = [ + i for i in items if isinstance(i, StreamEvent) and i.mode == "node_reset" + ] + self.assertEqual(len(resets), 1) + + async def test_close_marker_survives_a_full_buffer(self): + sink = InProcessSink("wf", asyncio.get_running_loop()) + for seq in range(10): + sink.put(_event("a1", seq)) + sink.close({"type": "workflow_completed", "x": 1}) + items = await _drain(sink) + self.assertEqual(items[-1].final, {"type": "workflow_completed", "x": 1}) + + async def test_no_drops_reports_zero(self): + sink = InProcessSink("wf", asyncio.get_running_loop()) + sink.put(_event("a1", 0)) + sink.close() + self.assertEqual((await _drain(sink))[-1].dropped, 0) + + async def test_drops_from_activity_threads_are_counted(self): + sink = InProcessSink("wf", asyncio.get_running_loop()) + + def produce(attempt: str) -> None: + for seq in range(20): + sink.put(_event(attempt, seq, node=attempt)) + + threads = [threading.Thread(target=produce, args=(a,)) for a in ("x", "y")] + for t in threads: + t.start() + for t in threads: + await asyncio.to_thread(t.join) + sink.close() + items = await _drain(sink) + kept = [i for i in items if isinstance(i, StreamEvent)] + self.assertEqual(len(kept) + items[-1].dropped, 40) + self.assertEqual(len(kept), CAP) + + +class TestDroppedIsReported(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + def setUp(self): + super().setUp() + patch = mock.patch.object(stream_module, "MAX_BUFFERED_EVENTS", CAP) + patch.start() + self.addCleanup(patch.stop) + + def _runner(self, name: str, final_type: str = "workflow_completed"): + runner = _chat_graph(name=name) + runner._started = True + + async def flood( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + sink = runner.stream_registry.get(workflow_id) + for seq in range(10): + sink.put(_event("a1", seq)) + yield {"type": "workflow_started", "workflow_id": workflow_id} + yield {"type": final_type, "workflow_id": workflow_id, "error": "boom"} + + patch = mock.patch.object(runner, "run_async", flood) + patch.start() + self.addCleanup(patch.stop) + return runner + + async def test_sse_final_event_reports_dropped(self): + from fastapi.testclient import TestClient + + runner = self._runner("bp-sse") + resp = TestClient(serve_app(runner)).post( + "/agent/run", json={"task": "hi", "stream": True} + ) + name, data = parse_sse(resp.text)[-1] + self.assertEqual(name, "workflow_completed") + self.assertEqual(data["dropped"], 7) + + async def test_astream_yields_a_dropped_event(self): + runner = self._runner("bp-astream") + items = await _collect(runner.astream(INPUT, stream_mode=["messages"])) + self.assertEqual(items[-1], ("stream_dropped", {"dropped": 7})) + + async def test_a_failed_run_still_yields_the_dropped_event_before_it_raises(self): + runner = self._runner("bp-failed", final_type="workflow_failed") + items: List[Any] = [] + with self.assertRaises(GraphRunError): + async for item in runner.astream(INPUT, stream_mode=["messages"]): + items.append(item) + self.assertEqual(items[-1], ("stream_dropped", {"dropped": 7})) + + async def test_final_event_has_no_dropped_key_without_drops(self): + from fastapi.testclient import TestClient + + runner = _chat_graph(name="bp-none") + runner._started = True + + async def quiet( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + yield {"type": "workflow_completed", "workflow_id": workflow_id} + + with mock.patch.object(runner, "run_async", quiet): + resp = TestClient(serve_app(runner)).post( + "/agent/run", json={"task": "hi", "stream": True} + ) + self.assertNotIn("dropped", parse_sse(resp.text)[-1][1]) + + +THREADS = 8 + + +PER_THREAD = 500 + + +class TestConcurrentEmitters(unittest.IsolatedAsyncioTestCase): + async def test_every_chunk_of_a_multithreaded_node_is_delivered(self): + sink = InProcessSink("wf", asyncio.get_running_loop()) + streamer = NodeStreamer(sink, workflow_id="wf", step=0, node="n", task_id=1) + start = threading.Barrier(THREADS) + + def work(worker: int) -> None: + start.wait() + for i in range(PER_THREAD): + streamer.writer((worker, i)) + + threads = [threading.Thread(target=work, args=(w,)) for w in range(THREADS)] + for t in threads: + t.start() + await asyncio.to_thread(lambda: [t.join() for t in threads]) + sink.close({"type": "workflow_completed"}) + items = await _drain(sink) + + events = [i for i in items if isinstance(i, StreamEvent)] + self.assertEqual(len(events), THREADS * PER_THREAD) + self.assertEqual(items[-1].dropped, 0) + # Arrival order is the order seq was assigned, so a consumer sees + # each thread's chunks in the order that thread wrote them. + self.assertEqual([e.seq for e in events], sorted(e.seq for e in events)) + for worker in range(THREADS): + mine = [e.data[1] for e in events if e.data[0] == worker] + self.assertEqual(mine, list(range(PER_THREAD))) + + async def test_sink_keeps_chunks_that_arrive_out_of_seq_order(self): + sink = InProcessSink("wf", asyncio.get_running_loop()) + for seq in (6, 5, 7): + sink.put(StreamEvent("wf", 0, "n", "a1", seq, (), "custom", seq)) + sink.close() + items = await _drain(sink) + got = [i.data for i in items if isinstance(i, StreamEvent)] + self.assertEqual(got, [6, 5, 7]) + self.assertEqual(items[-1].dropped, 0) + + +async def _reset_after_retry(**streamer_args: Any) -> Any: + sink = InProcessSink("wf", asyncio.get_running_loop()) + first = NodeStreamer(sink, workflow_id="wf", step=1, task_id=1, **streamer_args) + first._emit((), "custom", "partial") + retry = NodeStreamer(sink, workflow_id="wf", step=1, task_id=1, **streamer_args) + retry._emit((), "custom", "full") + await asyncio.sleep(0) + items: List[Any] = [] + while not sink._queue.empty(): + items.append(sink._queue.get_nowait()) + (reset,) = [i for i in items if i.mode == NODE_RESET] + return reset, retry + + +class TestResetNode(unittest.IsolatedAsyncioTestCase): + async def test_a_send_task_is_reset_as_its_node_with_its_path(self): + path = ("__pregel_push", 1, False) + reset, retry = await _reset_after_retry( + node="work", sink_node="work#1", path=path + ) + self.assertEqual(reset.data["node"], retry.metadata["langgraph_node"]) + self.assertEqual(reset.data["node"], "work") + self.assertEqual(reset.data["step"], 2) + self.assertEqual(tuple(reset.data["path"]), retry.metadata["langgraph_path"]) + + async def test_a_conditional_edge_is_reset_as_its_source_node(self): + reset, retry = await _reset_after_retry( + node="a", sink_node="a:branch:a_cond_condition", branch="a_cond_condition" + ) + self.assertEqual(reset.data["node"], "a") + self.assertEqual(reset.data["step"], 2) + # the sink's key is internal; the edge's name is what tells the reset + # apart from a retry of the node itself + self.assertEqual(reset.data["branch"], "a_cond_condition") + self.assertNotIn(":branch:", str(reset.data)) + + async def test_a_send_tasks_conditional_edge_names_its_task_and_edge(self): + path = ("__pregel_push", 1, False) + reset, retry = await _reset_after_retry( + node="work", + sink_node="work#1:branch:route", + path=path, + branch="route", + ) + self.assertEqual(reset.data["node"], "work") + self.assertEqual(tuple(reset.data["path"]), path) + self.assertEqual(reset.data["branch"], "route") + + async def test_a_plain_node_reset_is_unchanged(self): + reset, _ = await _reset_after_retry(node="chat") + self.assertEqual(reset.data, {"node": "chat", "step": 2}) + + +class TestRetryDedupe(unittest.IsolatedAsyncioTestCase): + async def _drain(self, sink: InProcessSink) -> List[StreamEvent]: + sink.close() + return [i for i in await _drain(sink) if isinstance(i, StreamEvent)] + + async def test_new_attempt_resets_and_old_attempt_is_dropped(self): + sink = InProcessSink("wf", asyncio.get_running_loop()) + sink.put(_event("a1", 0)) + sink.put(_event("a2", 0)) # retry starts + sink.put(_event("a1", 1)) # late chunk from the dead attempt + sink.put(_event("a2", 1)) + got = await self._drain(sink) + self.assertEqual( + [(e.mode, e.data) for e in got], + [ + ("messages", "a1-0"), + ("node_reset", {"node": "n", "step": 1}), + ("messages", "a2-0"), + ("messages", "a2-1"), + ], + ) + + async def test_chunks_after_accepted_updates_are_dropped(self): + sink = InProcessSink("wf", asyncio.get_running_loop()) + sink.put(_event("a1", 0, "updates")) + sink.put(_event("a2", 0)) + got = await self._drain(sink) + self.assertEqual([e.attempt_id for e in got], ["a1"]) + + async def test_plain_callable_streams_messages(self): + model = _StreamingModel() + + def plain_node(state): + return {"messages": [model.invoke("hi")]} + + from diagrid.agent.langgraph.workflow import clear_registries, register_node + + clear_registries() + self.addCleanup(clear_registries) + register_node("plain", plain_node) + sink = default_registry.open("wf-plain") + self.addCleanup(default_registry.close, "wf-plain") + payload = ExecuteNodeInput( + node_name="plain", channel_state=ChannelState(), step=0 + ).to_dict() + await asyncio.to_thread(execute_node_activity, _Ctx("wf-plain"), payload) + got = await self._drain(sink) + texts = [e.data[0].content for e in got if e.mode == "messages"] + self.assertEqual([t for t in texts if t], TOKENS) + + async def test_retried_activity_emits_reset(self): + calls = {"n": 0} + + def flaky(state): + calls["n"] += 1 + get_stream_writer()(f"try-{calls['n']}") + if calls["n"] == 1: + raise RuntimeError("transient") + return {"x": 1} + + from diagrid.agent.langgraph.workflow import clear_registries, register_node + + clear_registries() + self.addCleanup(clear_registries) + register_node("flaky", flaky) + sink = default_registry.open("wf-retry") + self.addCleanup(default_registry.close, "wf-retry") + payload = ExecuteNodeInput( + node_name="flaky", channel_state=ChannelState(), step=2 + ).to_dict() + with self.assertRaises(RuntimeError): + await asyncio.to_thread(execute_node_activity, _Ctx("wf-retry"), payload) + await asyncio.to_thread(execute_node_activity, _Ctx("wf-retry"), payload) + got = await self._drain(sink) + self.assertEqual( + [(e.mode, e.data) for e in got if e.mode != "updates"], + [ + ("custom", "try-1"), + ("node_reset", {"node": "flaky", "step": 3}), + ("custom", "try-2"), + ], + ) + self.assertEqual(got[-1].mode, "updates") + + +class TestStreamSinkRegistry(unittest.IsolatedAsyncioTestCase): + async def test_registries_do_not_share_sinks(self): + first, second = StreamSinkRegistry(), StreamSinkRegistry() + sink = first.open("wf") + self.assertIs(first.get("wf"), sink) + self.assertIsNone(second.get("wf")) + second.open("wf") # the same id is fine in another registry + + async def test_get_stream_sink_uses_the_default_registry(self): + sink = default_registry.open("wf-default") + self.addCleanup(default_registry.close, "wf-default") + self.assertIs(default_registry.get("wf-default"), sink) + self.assertIs(get_stream_sink("wf-default"), sink) + + async def test_get_stream_sink_takes_an_explicit_registry(self): + registry = StreamSinkRegistry() + sink = registry.open("wf-x") + self.assertIs(get_stream_sink("wf-x", registry=registry), sink) + self.assertIsNone(get_stream_sink("wf-x")) + + async def test_close_marker_is_public(self): + registry = StreamSinkRegistry() + sink = registry.open("wf") + sink.close(final={"type": "workflow_failed"}) + await asyncio.sleep(0) + item = await sink.get() + self.assertIsInstance(item, StreamClosed) + self.assertEqual(item.final, {"type": "workflow_failed"}) + + +class TestSinkOnAClosedLoop(unittest.TestCase): + """An activity still writing after the serving loop is gone must not fail.""" + + def _sink(self) -> InProcessSink: + loop = asyncio.new_event_loop() + sink = InProcessSink("wf-gone", loop) + loop.close() + return sink + + def test_put_and_close_do_not_raise(self): + sink = self._sink() + sink.put(StreamEvent("wf-gone", 0, "n", "a1", 0, (), "custom", "x")) + sink.put(StreamEvent("wf-gone", 0, "n", "a1", 1, (), "updates", {"n": None})) + sink.close({"type": "workflow_completed"}) + + def test_later_puts_are_no_ops(self): + sink = self._sink() + sink.put(StreamEvent("wf-gone", 0, "n", "a1", 0, (), "custom", "x")) + with mock.patch.object(sink, "_enqueue") as enqueue: + sink.put(StreamEvent("wf-gone", 0, "n", "a1", 1, (), "custom", "y")) + sink.close() + enqueue.assert_not_called() + + +class TestRunnerOwnsRegistry(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + def test_each_runner_gets_its_own_registry_by_default(self): + first = _chat_graph(name="reg-a") + self._reset() + second = _chat_graph(name="reg-b") + self.assertIsInstance(first.stream_registry, StreamSinkRegistry) + self.assertIsNot(first.stream_registry, second.stream_registry) + self.assertIsNot(first.stream_registry, default_registry) + + def test_registry_can_be_injected(self): + registry = StreamSinkRegistry() + runner = _chat_graph(name="reg-inj", stream_registry=registry) + self.assertIs(runner.stream_registry, registry) + + def _reset(self): + # DaprWorkflowGraphRunner registers module-level functions with dapr. + _clear_dapr_registration() + + async def test_astream_streams_through_the_runners_registry(self): + registry = StreamSinkRegistry() + runner = _chat_graph(name="reg-run", stream_registry=registry) + runner._started = True + seen = [] + original = registry.open + + def spy(workflow_id): + seen.append(workflow_id) + return original(workflow_id) + + with ( + mock.patch.object(registry, "open", spy), + mock.patch.object(runner, "run_async", _fake_run_async(runner)), + ): + chunks = await _collect( + runner.astream(INPUT, workflow_id="wf-own", stream_mode="messages") + ) + self.assertEqual(seen, ["wf-own"]) + texts = [c[0].content for c in chunks] + self.assertEqual([t for t in texts if t], TOKENS) + self.assertIsNone(registry.get("wf-own")) + + async def test_a_runner_never_reads_another_runners_sinks(self): + mine = _chat_graph(name="reg-mine") + other_registry = StreamSinkRegistry() + other_sink = other_registry.open("wf-iso") + mine._started = True + with mock.patch.object(mine, "run_async", _fake_run_async(mine)): + await _collect(mine.astream(INPUT, workflow_id="wf-iso")) + other_sink.close() + await asyncio.sleep(0) + # Nothing from the run above was delivered to the other registry. + self.assertIsInstance(await other_sink.get(), StreamClosed) + + +LOGGER = "diagrid.agent.langgraph.workflow" + + +class TestRegistryRemembersClosedRuns(unittest.IsolatedAsyncioTestCase): + async def test_closed_ids_are_remembered_and_reopened_ones_forgotten(self): + registry = StreamSinkRegistry() + self.assertFalse(registry.was_closed("wf")) + sink = registry.open("wf") + self.assertFalse(registry.was_closed("wf")) + registry.close("wf", sink) + self.assertTrue(registry.was_closed("wf")) + registry.open("wf") + self.assertFalse(registry.was_closed("wf")) + + async def test_closing_an_unknown_id_remembers_nothing(self): + registry = StreamSinkRegistry() + registry.close("never-opened") + self.assertFalse(registry.was_closed("never-opened")) + + +# The registry's two bounded memories: (remember an id, is it still remembered?). +BOUNDED_MEMORIES = { + "closed-runs": ( + lambda registry, wf: registry.close(wf, registry.open(wf)), + lambda registry, wf: registry.was_closed(wf), + ), + "first-report": ( + lambda registry, wf: registry.first_report(wf), + lambda registry, wf: not registry.first_report(wf), + ), +} + + +class TestMemoriesAreBounded(unittest.IsolatedAsyncioTestCase): + async def test_only_the_most_recent_runs_are_remembered(self): + limit = stream_module._MAX_REPORTED_RUNS + for name, (remember, remembered) in BOUNDED_MEMORIES.items(): + with self.subTest(memory=name): + registry = StreamSinkRegistry() + for i in range(limit + 1): + remember(registry, f"wf-{i}") + # wf-0 is the oldest of limit + 1: forgotten, the newest is not + self.assertFalse(remembered(registry, "wf-0")) + self.assertTrue(remembered(registry, f"wf-{limit}")) + + async def test_a_run_is_reported_first_only_once(self): + registry = StreamSinkRegistry() + self.assertTrue(registry.first_report("wf-0")) + self.assertFalse(registry.first_report("wf-0")) + + +class TestLateActivityOfAClosedStream(unittest.IsolatedAsyncioTestCase): + def setUp(self): + clear_registries() + self.addCleanup(clear_registries) + register_node("n", lambda state: {"x": 1}) + + async def test_no_replica_warning_when_this_process_closed_the_stream(self): + registry = StreamSinkRegistry() + registry.close("wf-gone", registry.open("wf-gone")) + await asyncio.sleep(0) + with self.assertLogs(LOGGER, level="DEBUG") as logs: + out = execute_node_activity( + _Ctx("wf-gone"), _payload(), stream_registry=registry + ) + self.assertEqual(out["writes"][0]["value"], 1) + self.assertEqual([r.levelname for r in logs.records], ["DEBUG"]) + self.assertIn("closed", logs.records[0].getMessage()) + self.assertNotIn("replica", logs.records[0].getMessage()) + + async def test_a_run_this_process_never_opened_still_warns(self): + registry = StreamSinkRegistry() + with self.assertLogs(LOGGER, level="WARNING") as logs: + execute_node_activity(_Ctx("wf-else"), _payload(), stream_registry=registry) + self.assertIn("another process", logs.records[0].getMessage()) + + +class TestStreamRegistry(unittest.IsolatedAsyncioTestCase): + async def test_reused_workflow_id_is_rejected_and_first_sink_kept(self): + first = default_registry.open("same") + self.addCleanup(default_registry.close, "same") + with self.assertRaises(ValueError): + default_registry.open("same") + self.assertIs(get_stream_sink("same"), first) + + async def test_close_with_stale_sink_keeps_current(self): + first = default_registry.open("id1") + default_registry.close("id1", first) + second = default_registry.open("id1") + self.addCleanup(default_registry.close, "id1") + default_registry.close("id1", first) # stale handle + self.assertIs(get_stream_sink("id1"), second) diff --git a/tests/agent/langgraph/test_streaming_sse.py b/tests/agent/langgraph/test_streaming_sse.py new file mode 100644 index 00000000..6c1842a3 --- /dev/null +++ b/tests/agent/langgraph/test_streaming_sse.py @@ -0,0 +1,588 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The SSE side of ``POST /agent/run``: the request that switches it on, what a +client needs to survive a real network, how values are put on the wire, and +what happens when a chunk cannot be encoded or the run cannot be scheduled.""" + +import asyncio +import datetime +import decimal +import unittest +import uuid +from typing import Any, Dict, List, Tuple +from unittest import mock + +from dapr.ext.workflow import WorkflowStatus +from fastapi.testclient import TestClient +from langchain_core.load import load +from langchain_core.messages import AIMessage, BaseMessage +from langgraph.config import get_stream_writer +from langgraph.graph import END, START, StateGraph +from pydantic import BaseModel +from typing_extensions import TypedDict + +from diagrid.agent.core.workflow import stream as stream_module +from diagrid.agent.core.workflow.stream import ( + StreamEvent, + format_sse, +) +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.streaming import normalize_final, to_wire + +from .golden_harness import _golden_graph +from .streaming_helpers import ( + INPUT, + _chat_graph, + _collect, + _completed_state, + _fake_run_async, + _PollCase, + _state, + parse_sse, + serve_app, +) +from .test_runner import _RunnerTestCase + + +def _runner(name: str): + runner = _chat_graph(name=name) + runner._started = True + patch = mock.patch.object(runner, "run_async", _fake_run_async(runner)) + patch.start() + return runner, patch + + +class TestSseTransport(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def test_the_first_event_names_the_workflow(self): + runner, patch = _runner("sse-first") + self.addCleanup(patch.stop) + resp = TestClient(serve_app(runner)).post( + "/agent/run", json={"task": "hi", "stream": True, "thread_id": "t-9"} + ) + events = parse_sse(resp.text) + name, data = events[0] + self.assertEqual(name, "workflow_started") + self.assertEqual(data["thread_id"], "t-9") + self.assertEqual(data["workflow_id"], events[-1][1]["workflow_id"]) + self.assertEqual([n for n, _ in events].count("workflow_started"), 1) + + async def test_response_headers_stop_proxies_buffering(self): + runner, patch = _runner("sse-headers") + self.addCleanup(patch.stop) + resp = TestClient(serve_app(runner)).post( + "/agent/run", json={"task": "hi", "stream": True} + ) + self.assertEqual(resp.headers["cache-control"], "no-cache") + self.assertEqual(resp.headers["x-accel-buffering"], "no") + + async def test_idle_stream_sends_comment_keepalives(self): + runner = _chat_graph(name="sse-idle") + runner._started = True + release = asyncio.Event() + + async def silent( + input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 + ): + yield {"type": "workflow_started", "workflow_id": workflow_id} + await release.wait() # idle until the test has seen its keepalives + yield {"type": "workflow_completed", "workflow_id": workflow_id} + + app = serve_app(runner) + route = next( + r + for r in app.routes + if getattr(r, "path", "") == "/agent/run" and "POST" in r.methods + ) + frames: List[str] = [] + with ( + mock.patch.object(runner, "run_async", silent), + mock.patch.object(stream_module, "SSE_KEEPALIVE_SECONDS", 0.01), + ): + response = await route.endpoint({"task": "hi", "stream": True}) + + async def consume() -> None: + async for frame in response.body_iterator: + frames.append(frame) + # No timing assertion: the run waits for as many keepalives + # as the test asks for, however slow the machine is. + if len([f for f in frames if f.startswith(":")]) == 2: + release.set() + + # the bound only turns "no keepalive ever came" into a failure + await asyncio.wait_for(consume(), 30) + comments = [f for f in frames if f.startswith(":")] + self.assertGreaterEqual(len(comments), 2) + self.assertEqual({c.strip() for c in comments}, {": keepalive"}) + # Comments carry no event and do not use up an event id. + events = [f for f in frames if not f.startswith(":")] + self.assertEqual([f.split("\n")[0] for f in events], ["id: 1", "id: 2"]) + self.assertEqual(parse_sse("".join(events))[-1][0], "workflow_completed") + + async def test_astream_reports_the_workflow_through_on_control_only(self): + runner, patch = _runner("sse-astream") + self.addCleanup(patch.stop) + got: List[Any] = [] + items = await _collect( + runner.astream( + INPUT, + workflow_id="wf-known", + thread_id="t-3", + stream_mode=["custom"], + on_control=got.append, + ) + ) + self.assertEqual([m for m, _ in items], ["custom"]) + (started,) = [c for c in got if c.kind == "workflow_started"] + self.assertEqual(started.data["workflow_id"], "wf-known") + self.assertEqual(started.data["thread_id"], "t-3") + + +class Answer(BaseModel): + text: str + score: float + + +class _State(TypedDict, total=False): + result: Any + when: Any + + +WHEN = datetime.datetime(2026, 1, 1) + + +class TestToWire(unittest.TestCase): + def test_values_that_are_not_serializable_keep_their_data(self): + update = {"n": {"result": Answer(text="hi", score=0.5), "when": WHEN}} + wire = to_wire("updates", update) + self.assertEqual(wire["n"]["result"], {"text": "hi", "score": 0.5}) + self.assertEqual(wire["n"]["when"], str(WHEN)) + # and what comes out is load()-able + self.assertEqual(load(wire, allowed_objects="messages"), wire) + + def test_uuid_decimal_set_and_nested_models(self): + ident = uuid.UUID(int=7) + wire = to_wire( + "updates", + { + "n": { + "id": ident, + "price": decimal.Decimal("1.5"), + "tags": {"a"}, + "items": [Answer(text="x", score=1.0)], + } + }, + ) + self.assertEqual(wire["n"]["id"], str(ident)) + self.assertEqual(wire["n"]["price"], "1.5") + self.assertEqual(wire["n"]["tags"], str({"a"})) + self.assertEqual(wire["n"]["items"], [{"text": "x", "score": 1.0}]) + + def test_messages_stay_loadable_objects(self): + wire = to_wire("updates", {"n": {"messages": [AIMessage("hi")]}}) + back = load(wire, allowed_objects="messages") + self.assertIsInstance(back["n"]["messages"][0], BaseMessage) + + def test_custom_payloads_get_the_same_treatment(self): + wire = to_wire( + "custom", {"m": AIMessage("hi"), "answer": Answer(text="a", score=2)} + ) + self.assertEqual(wire["answer"], {"text": "a", "score": 2.0}) + self.assertIsInstance(load(wire["m"], allowed_objects="messages"), BaseMessage) + + def test_control_events_pass_through(self): + self.assertEqual(to_wire("node_reset", {"node": "n"}), {"node": "n"}) + + +class TestSseUpdates(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def test_update_matches_the_final_output(self): + def node(state: _State) -> dict: + get_stream_writer()({"answer": Answer(text="c", score=1.0)}) + return {"result": Answer(text="hi", score=0.5), "when": WHEN} + + graph = StateGraph(_State) + graph.add_node("n", node) + graph.add_edge(START, "n") + graph.add_edge("n", END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="wire") + runner._started = True + from fastapi.testclient import TestClient + + with mock.patch.object(runner, "run_async", _fake_run_async(runner)): + resp = TestClient(serve_app(runner)).post( + "/agent/run", json={"task": "hi", "stream": True} + ) + events = parse_sse(resp.text) + update = next(d for e, d in events if e == "updates") + final = events[-1][1] + + self.assertEqual(load(update, allowed_objects="messages"), update) + self.assertEqual(update["n"]["result"], final["output"]["result"]) + self.assertEqual(update["n"]["when"], final["output"]["when"]) + custom = next(d for e, d in events if e == "custom") + self.assertEqual(custom, {"answer": {"text": "c", "score": 1.0}}) + + +class _Bad: + def to_dict(self): + raise ValueError("cannot convert") + + +def _data_event(mode: str, data: Any, seq: int = 0) -> StreamEvent: + return StreamEvent("wf-1", 0, "n", "a", seq, (), mode, data) + + +def _events(*items: Any): + async def stream(graph_input, **kw): + for item in items: + if isinstance(item, BaseException): + raise item + yield item + + return stream + + +_STARTED = _data_event("workflow_started", {"workflow_id": "wf-1", "thread_id": "t"}) + + +_DONE = normalize_final( + {"type": "workflow_completed", "output": {"v": 1}}, + workflow_id="wf-1", + thread_id="t", +) + + +class TestUnencodableChunk(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def _serve(self, *items: Any) -> List[Tuple[str, Any]]: + runner = _chat_graph(name="enc") + with mock.patch.object(runner, "_stream_events", _events(*items)): + return await _collect(runner._serve_stream({"task": "hi"}, "sess")) + + async def test_the_stream_carries_on_and_the_loss_is_counted(self): + got = await self._serve( + _STARTED, + _data_event("custom", "first", 1), + _data_event("custom", _Bad(), 2), + _data_event("custom", "after", 3), + {**_DONE, "dropped": 1}, + ) + names = [n for n, _ in got] + self.assertEqual( + names, + ["workflow_started", "custom", "custom", "custom", "workflow_completed"], + ) + self.assertEqual(got[1][1], "first") + self.assertIn("unserializable", got[2][1]) + self.assertEqual(got[3][1], "after") + self.assertEqual(got[-1][1]["dropped"], 2) # the sink's drop and ours + + async def test_a_cyclic_chunk_is_not_a_failed_run(self): + loop: List[Any] = [] + loop.append(loop) + got = await self._serve(_STARTED, _data_event("custom", loop, 1), _DONE) + self.assertEqual(got[-1][0], "workflow_completed") + self.assertEqual(got[-1][1]["dropped"], 1) + + +class TestStreamFailureAfterStart(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def _serve(self, *items: Any): + runner = _chat_graph(name="enc-fail") + with mock.patch.object(runner, "_stream_events", _events(*items)): + return await _collect(runner._serve_stream({"task": "hi"}, "sess")) + + async def test_after_start_the_workflow_is_said_to_be_still_running(self): + got = await self._serve(_STARTED, RuntimeError("queue broke")) + name, data = got[-1] + self.assertEqual(name, "workflow_failed") + self.assertEqual(data["error"]["error_type"], "StreamError") + self.assertTrue(data["workflow_still_running"]) + self.assertEqual(data["workflow_id"], "wf-1") + + async def test_before_start_it_is_a_plain_failure(self): + got = await self._serve(RuntimeError("could not open")) + name, data = got[-1] + self.assertEqual(name, "workflow_failed") + self.assertEqual(data["error"]["error_type"], "RuntimeError") + self.assertNotIn("workflow_still_running", data) + + +class TestStartedIsFirst(_PollCase): + async def test_a_chunk_written_while_the_workflow_is_scheduled_comes_second(self): + runner, client = self._runner( + [_state(WorkflowStatus.RUNNING), _completed_state()], "first-ev" + ) + + def schedule(*, workflow, input, instance_id): + # a fast engine: the first node's activity has already run + sink = runner.stream_registry.get(instance_id) + sink.put(StreamEvent(instance_id, 0, "n", "a1", 0, (), "custom", "x")) + + client.schedule_new_workflow.side_effect = schedule + order: List[str] = [] + async for item in runner.astream( + INPUT, + workflow_id="wf-fast", + stream_mode=["custom"], + poll_interval=0, + on_control=lambda c: order.append(c.kind), + ): + order.append(item[0]) + self.assertEqual(order[:2], ["workflow_started", "custom"]) + + async def test_the_sink_order_puts_it_first(self): + runner, client = self._runner([_completed_state()], "first-ev-2") + order: List[str] = [] + + def schedule(*, workflow, input, instance_id): + sink = runner.stream_registry.get(instance_id) + sink.put(StreamEvent(instance_id, 0, "n", "a1", 0, (), "custom", "x")) + + client.schedule_new_workflow.side_effect = schedule + agen = runner._stream_events( + INPUT, + config=None, + thread_id="t", + workflow_id="wf-order", + poll_interval=0, + ) + async for item in agen: + order.append(item.mode if isinstance(item, StreamEvent) else item["type"]) + self.assertEqual(order[0], "workflow_started") + self.assertEqual(order.count("workflow_started"), 1) + self.assertEqual(order[1], "custom") + + +class TestSchedulingFailure(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def test_a_failed_schedule_is_a_failed_run_not_a_pump_crash(self): + runner = _chat_graph(name="first-ev-fail") + runner._started = True + client = mock.Mock() + client.schedule_new_workflow.side_effect = RuntimeError("no sidecar") + runner._workflow_client = client + items = [ + i + async for i in runner._stream_events( + INPUT, config=None, thread_id="t", workflow_id="w", poll_interval=0 + ) + ] + self.assertEqual(items[-1]["type"], "workflow_failed") + self.assertEqual(items[-1]["error"]["error_type"], "RuntimeError") + + +REQUEST = { + "messages": [{"role": "user", "content": "hi"}], + "stream": "a graph's own state key", + "stream_mode": "also a state key", +} + + +class TestReservedKeys(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + def test_a_plain_request_keeps_its_stream_keys(self): + runner = _chat_graph(name="rk-plain") + self.assertEqual(runner._request_to_input(REQUEST), REQUEST) + + def test_a_streaming_request_drops_them(self): + runner = _chat_graph(name="rk-stream") + self.assertEqual( + runner._request_to_input(REQUEST, streaming=True), + {"messages": REQUEST["messages"]}, + ) + + def test_same_rule_with_an_input_mapper(self): + runner = _chat_graph(name="rk-mapper") + runner._input_mapper = lambda request: dict(request) + self.assertEqual(runner._request_to_input(REQUEST), REQUEST) + self.assertEqual( + runner._request_to_input(REQUEST, streaming=True), + {"messages": REQUEST["messages"]}, + ) + + def test_task_shorthand_still_works_when_streaming(self): + runner = _chat_graph(name="rk-task") + got = runner._request_to_input({"task": "hi", "stream": True}, streaming=True) + self.assertEqual(got, {"messages": [{"role": "user", "content": "hi"}]}) + + async def test_non_streaming_serve_run_passes_the_keys_to_the_graph(self): + runner = _chat_graph(name="rk-run") + runner._started = True + seen: Dict[str, Any] = {} + + async def spy(input, **kw): + seen.update(input) + yield {"type": "workflow_completed"} + + with mock.patch.object(runner, "run_async", spy): + await _collect(runner._serve_run(dict(REQUEST), "sess")) + self.assertEqual(seen["stream"], REQUEST["stream"]) + + async def test_streaming_serve_drops_them_with_or_without_a_mapper(self): + for name, mapper in (("plain", None), ("mapper", lambda r: dict(r))): + with self.subTest(input=name): + self.setUp() + runner = _chat_graph(name=f"rk-serve-{name}") + runner._input_mapper = mapper + seen: Dict[str, Any] = {} + + async def events(graph_input, **kw): + seen.update(graph_input) + yield {"type": "workflow_completed"} + + request = {**REQUEST, "stream": True, "stream_mode": "updates"} + with mock.patch.object(runner, "_stream_events", events): + await _collect(runner._serve_stream(request, "sess")) + self.assertEqual(list(seen), ["messages"]) + + +MESSAGES = [{"role": "user", "content": "hi"}] + + +class _RouteCase(_RunnerTestCase, unittest.TestCase): + """``POST /agent/run`` against a runner whose ``run_async`` records its input.""" + + def _post(self, body: Dict[str, Any]): + runner = _chat_graph(name="route") + runner._started = True + seen: List[Dict[str, Any]] = [] + + async def spy(input, **kw): + seen.append(dict(input)) + yield {"type": "workflow_completed", "output": {"ok": 1}} + + with mock.patch.object(runner, "run_async", spy): + resp = TestClient(serve_app(runner)).post("/agent/run", json=body) + return resp, seen + + +class TestStreamRouteDecision(_RouteCase): + def test_a_stream_value_that_is_not_true_stays_a_plain_request(self): + for value in ("false", "no", "x", {"a": 1}, [1], 0, False, None): + with self.subTest(value=value): + self.setUp() # one runner (and workflow registration) per value + resp, seen = self._post({"messages": MESSAGES, "stream": value}) + self.assertTrue( + resp.headers["content-type"].startswith("application/json"), + resp.headers["content-type"], + ) + # a graph may have a state key of that name: it must arrive + self.assertEqual(seen[0]["stream"], value) + + def test_true_streams(self): + resp, _ = self._post({"messages": MESSAGES, "stream": True}) + self.assertTrue(resp.headers["content-type"].startswith("text/event-stream")) + + +class TestInvalidStreamRequest(_RouteCase): + def test_an_unsupported_stream_mode_is_rejected_before_the_stream_starts(self): + for mode in ("bogus", ["messages", "values"], 7): + with self.subTest(stream_mode=mode): + self.setUp() + resp, started = self._post( + {"task": "hi", "stream": True, "stream_mode": mode} + ) + self.assertEqual(resp.status_code, 422) + self.assertIn("Unsupported stream_mode", resp.json()["detail"]) + self.assertEqual(started, []) # no run was started + + def test_a_valid_stream_mode_streams(self): + resp, started = self._post( + {"task": "hi", "stream": True, "stream_mode": ["updates"]} + ) + self.assertEqual(resp.status_code, 200) + self.assertEqual(len(started), 1) + + def test_a_plain_request_ignores_stream_mode(self): + resp, started = self._post({"messages": MESSAGES, "stream_mode": "bogus"}) + self.assertEqual(resp.status_code, 200) + self.assertEqual(started[0]["stream_mode"], "bogus") + + +def _modes_sent(runner: Any, body: Dict[str, Any]) -> List[str]: + resp = TestClient(serve_app(runner)).post("/agent/run", json=body) + return [name for name, _ in parse_sse(resp.text)] + + +class TestStreamModeFiltersTheSse(_RunnerTestCase, unittest.TestCase): + """The request's ``stream_mode`` decides which chunks an SSE client receives.""" + + def _runner(self) -> Any: + from diagrid.agent.langgraph import DaprWorkflowGraphRunner + + runner = DaprWorkflowGraphRunner(graph=_golden_graph(), name="route-filter") + runner._started = True + patch = mock.patch.object(runner, "run_async", _fake_run_async(runner)) + patch.start() + self.addCleanup(patch.stop) + return runner + + def test_the_default_sends_every_mode(self): + names = set(_modes_sent(self._runner(), {"task": "hi", "stream": True})) + self.assertTrue({"messages", "updates", "custom"} <= names) + + def test_a_single_mode_string_sends_only_that_mode(self): + names = _modes_sent( + self._runner(), {"task": "hi", "stream": True, "stream_mode": "updates"} + ) + self.assertEqual( + set(names), {"workflow_started", "updates", "workflow_completed"} + ) + + def test_a_list_sends_only_the_listed_modes(self): + names = _modes_sent( + self._runner(), {"task": "hi", "stream": True, "stream_mode": ["custom"]} + ) + self.assertEqual( + set(names), {"workflow_started", "custom", "workflow_completed"} + ) + self.assertEqual(names[0], "workflow_started") + self.assertEqual(names[-1], "workflow_completed") + + +class TestControlEventsPassTheModeFilter(_RunnerTestCase, unittest.TestCase): + def test_node_reset_and_stream_unavailable_are_sent_whatever_the_modes(self): + from diagrid.agent.core.workflow.stream import ( + NODE_RESET, + STREAM_UNAVAILABLE, + StreamEvent, + ) + + def event(mode: str, data: Any) -> StreamEvent: + return StreamEvent( + workflow_id="wf", + step=0, + node="chat", + attempt_id="a", + seq=0, + ns=(), + mode=mode, + data=data, + ) + + runner = _chat_graph(name="route-control") + runner._started = True + + async def events(*args: Any, **kw: Any): + yield event("messages", ["x", {}]) # not asked for: filtered out + yield event(NODE_RESET, {"node": "chat", "step": 1}) + yield event("updates", {"chat": {}}) + yield event(STREAM_UNAVAILABLE, {"workflow_id": "wf", "reason": "r"}) + yield {"type": "workflow_completed", "workflow_id": "wf"} + + with mock.patch.object(runner, "_stream_events", events): + names = _modes_sent( + runner, {"task": "hi", "stream": True, "stream_mode": ["updates"]} + ) + self.assertEqual( + names, [NODE_RESET, "updates", STREAM_UNAVAILABLE, "workflow_completed"] + ) + + +class TestSseFormat(unittest.TestCase): + def test_frame(self): + self.assertEqual( + format_sse("messages", {"a": 1}, 3), + 'id: 3\nevent: messages\ndata: {"a": 1}\n\n', + ) + + def test_newlines_are_escaped_not_split(self): + frame = format_sse("custom", "a\nb") + self.assertEqual(frame, 'event: custom\ndata: "a\\nb"\n\n') From 78c2bfa657bed8a42e3d73b845b11188fece6c3c Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Wed, 25 Nov 2026 23:58:04 +0100 Subject: [PATCH 12/73] test(langgraph): cover LangGraph execution semantics in the workflow runner Pin the behaviour that makes a durable run match a native one: the order of a step's writes and Send numbering, goto order, a router evaluated per task, deferred nodes, the in-flight step-order patch, replay-safe message ids, message input shapes, channel defaults, Overwrite, state shapes, root-state graphs, value types through reducers and plain channels, managed values, Command(graph=PARENT), async composite nodes and the shared node loop, the step bound and the orchestrator's graph config. Signed-off-by: Casper Nielsen --- .../langgraph/test_async_composite_nodes.py | 69 ++++++++ tests/agent/langgraph/test_background_loop.py | 83 +++++++++ .../agent/langgraph/test_chat_message_role.py | 52 ++++++ .../agent/langgraph/test_last_value_types.py | 94 ++++++++++ tests/agent/langgraph/test_managed_values.py | 119 +++++++++++++ .../test_orchestrator_graph_config.py | 70 ++++++++ tests/agent/langgraph/test_parent_command.py | 86 +++++++++ .../langgraph/test_reducer_value_types.py | 132 ++++++++++++++ tests/agent/langgraph/test_root_state.py | 64 +++++++ tests/agent/langgraph/test_send_task_input.py | 57 ++++++ tests/agent/langgraph/test_step_bound.py | 166 ++++++++++++++++++ .../langgraph/test_workflow_async_loop.py | 91 ++++++++++ .../test_workflow_channel_defaults.py | 79 +++++++++ tests/agent/langgraph/test_workflow_defer.py | 93 ++++++++++ .../langgraph/test_workflow_goto_order.py | 46 +++++ .../langgraph/test_workflow_message_ids.py | 106 +++++++++++ .../langgraph/test_workflow_message_inputs.py | 79 +++++++++ .../langgraph/test_workflow_overwrite.py | 51 ++++++ tests/agent/langgraph/test_workflow_replay.py | 112 ++++++++++++ .../test_workflow_router_per_task.py | 86 +++++++++ .../langgraph/test_workflow_send_numbering.py | 67 +++++++ .../langgraph/test_workflow_state_shapes.py | 100 +++++++++++ .../test_workflow_step_order_patch.py | 95 ++++++++++ .../langgraph/test_workflow_write_order.py | 77 ++++++++ 24 files changed, 2074 insertions(+) create mode 100644 tests/agent/langgraph/test_async_composite_nodes.py create mode 100644 tests/agent/langgraph/test_background_loop.py create mode 100644 tests/agent/langgraph/test_chat_message_role.py create mode 100644 tests/agent/langgraph/test_last_value_types.py create mode 100644 tests/agent/langgraph/test_managed_values.py create mode 100644 tests/agent/langgraph/test_orchestrator_graph_config.py create mode 100644 tests/agent/langgraph/test_parent_command.py create mode 100644 tests/agent/langgraph/test_reducer_value_types.py create mode 100644 tests/agent/langgraph/test_root_state.py create mode 100644 tests/agent/langgraph/test_send_task_input.py create mode 100644 tests/agent/langgraph/test_step_bound.py create mode 100644 tests/agent/langgraph/test_workflow_async_loop.py create mode 100644 tests/agent/langgraph/test_workflow_channel_defaults.py create mode 100644 tests/agent/langgraph/test_workflow_defer.py create mode 100644 tests/agent/langgraph/test_workflow_goto_order.py create mode 100644 tests/agent/langgraph/test_workflow_message_ids.py create mode 100644 tests/agent/langgraph/test_workflow_message_inputs.py create mode 100644 tests/agent/langgraph/test_workflow_overwrite.py create mode 100644 tests/agent/langgraph/test_workflow_replay.py create mode 100644 tests/agent/langgraph/test_workflow_router_per_task.py create mode 100644 tests/agent/langgraph/test_workflow_send_numbering.py create mode 100644 tests/agent/langgraph/test_workflow_state_shapes.py create mode 100644 tests/agent/langgraph/test_workflow_step_order_patch.py create mode 100644 tests/agent/langgraph/test_workflow_write_order.py diff --git a/tests/agent/langgraph/test_async_composite_nodes.py b/tests/agent/langgraph/test_async_composite_nodes.py new file mode 100644 index 00000000..cd6c79d7 --- /dev/null +++ b/tests/agent/langgraph/test_async_composite_nodes.py @@ -0,0 +1,69 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A node that is a composite runnable with an async-only step inside it. + +A compiled subgraph (or a ``RunnableSequence``) has no ``afunc`` of its own, but +a step inside it may be an ``async def`` that has no sync entry. Native +``ainvoke`` and ``astream`` run it; the node must go through ``ainvoke`` too. +""" + +from typing import Any + +from langchain_core.runnables import RunnableLambda +from langgraph.graph import END, START, StateGraph +from typing_extensions import TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .test_runner import _RunnerTestCase, _run + + +class _S(TypedDict, total=False): + x: int + + +async def _inner(state: _S) -> dict: + return {"x": state["x"] + 1} + + +def _parent(sub: Any) -> Any: + graph = StateGraph(_S) + graph.add_node("sub", sub) + graph.add_edge(START, "sub") + graph.add_edge("sub", END) + return graph.compile() + + +def _async_subgraph() -> Any: + inner = StateGraph(_S) + inner.add_node("inner", _inner) + inner.add_edge(START, "inner") + inner.add_edge("inner", END) + return inner.compile() + + +def _sync_subgraph() -> Any: + inner = StateGraph(_S) + inner.add_node("inner", lambda s: {"x": s["x"] + 1}) + inner.add_edge(START, "inner") + inner.add_edge("inner", END) + return inner.compile() + + +class TestAsyncCompositeNodes(_RunnerTestCase): + def _check(self, sub: Any, name: str) -> None: + compiled = _parent(sub) + out = _run(DaprWorkflowGraphRunner(graph=compiled, name=name), {"x": 1}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output, {"x": 2}) + + def test_a_subgraph_with_an_async_only_node(self): + self._check(_async_subgraph(), "async-subgraph") + + def test_a_sequence_with_an_async_only_step(self): + sequence = RunnableLambda(lambda s: s) | RunnableLambda(_inner) + self._check(sequence, "async-sequence") + + def test_a_subgraph_of_sync_nodes_still_runs(self): + self._check(_sync_subgraph(), "sync-subgraph") diff --git a/tests/agent/langgraph/test_background_loop.py b/tests/agent/langgraph/test_background_loop.py new file mode 100644 index 00000000..dabc486e --- /dev/null +++ b/tests/agent/langgraph/test_background_loop.py @@ -0,0 +1,83 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The loop async nodes share survives what a node does to it. + +``asyncio`` re-raises ``SystemExit`` and ``KeyboardInterrupt`` out of the loop's +``run_forever``, which ends the loop's thread. Every async node and async +condition of the process runs on that one loop, so it must not stay dead: the +node that raised fails, and the next one runs. +""" + +import asyncio +import concurrent.futures +import threading +import unittest +from typing import Any + +from diagrid.agent.langgraph.workflow import _BackgroundLoop + +_WAIT = 10 + + +def _run_in_thread(loop: _BackgroundLoop, make_coro: Any) -> concurrent.futures.Future: + """``loop.run(...)`` on a worker, so a hang fails the test instead of freezing it.""" + future: concurrent.futures.Future = concurrent.futures.Future() + + def work() -> None: + try: + future.set_result(loop.run(make_coro())) + except BaseException as e: # reported through the future + future.set_exception(e) + + threading.Thread(target=work, daemon=True).start() + return future + + +async def _ok() -> int: + return 7 + + +async def _exits() -> None: + raise SystemExit(3) + + +async def _interrupts() -> None: + raise KeyboardInterrupt() + + +class TestBackgroundLoop(unittest.TestCase): + def test_a_coroutine_runs_and_returns(self): + loop = _BackgroundLoop() + self.assertEqual(_run_in_thread(loop, _ok).result(_WAIT), 7) + + def test_system_exit_fails_that_node_and_the_next_one_runs(self): + for raiser in (_exits, _interrupts): + with self.subTest(raiser=raiser.__name__): + loop = _BackgroundLoop() + with self.assertRaises(RuntimeError) as caught: + _run_in_thread(loop, raiser).result(_WAIT) + self.assertIn( + "SystemExit" if raiser is _exits else "KeyboardInterrupt", + str(caught.exception), + ) + self.assertEqual(_run_in_thread(loop, _ok).result(_WAIT), 7) + + def test_a_dead_loop_is_replaced_and_a_waiting_node_fails(self): + loop = _BackgroundLoop() + started = threading.Event() + + async def stuck() -> None: + started.set() + await asyncio.sleep(3600) + + waiting = _run_in_thread(loop, stuck) + self.assertTrue(started.wait(_WAIT)) + # a task of the node's own ends the loop's thread, as a stray one would + dead = loop._loop + assert dead is not None + + dead.call_soon_threadsafe(lambda: dead.create_task(_exits())) + with self.assertRaises(RuntimeError): + waiting.result(_WAIT) + self.assertEqual(_run_in_thread(loop, _ok).result(_WAIT), 7) diff --git a/tests/agent/langgraph/test_chat_message_role.py b/tests/agent/langgraph/test_chat_message_role.py new file mode 100644 index 00000000..63f9cfca --- /dev/null +++ b/tests/agent/langgraph/test_chat_message_role.py @@ -0,0 +1,52 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A ``ChatMessage`` has a ``role`` of its own, and is still a message dump. + +Its dump holds ``type: "chat"`` and ``role: "critic"``. A ``{"role", "content"}`` +dict (no ``type``) is the shorthand ``convert_to_messages`` reads, and must keep +working; a dump with a ``type`` is validated as the message class. +""" + +from typing import Any + +from langchain_core.messages import ChatMessage +from langgraph.graph import END, START, MessagesState, StateGraph + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.workflow import _as_message, _serialize_value + +from .test_runner import _RunnerTestCase, _run + + +def _graph() -> Any: + graph = StateGraph(MessagesState) + graph.add_node( + "critic", lambda s: {"messages": [ChatMessage(content="c", role="critic")]} + ) + graph.add_edge(START, "critic") + graph.add_edge("critic", END) + return graph.compile() + + +class TestChatMessageRole(_RunnerTestCase): + def test_a_chat_message_dump_is_a_chat_message_again(self): + back = _as_message(_serialize_value(ChatMessage(content="c", role="critic"))) + self.assertIsInstance(back, ChatMessage) + self.assertEqual((back.role, back.content), ("critic", "c")) + + def test_a_role_dict_is_still_the_shorthand(self): + back = _as_message({"role": "user", "content": "hi"}) + self.assertEqual((back.type, back.content), ("human", "hi")) + + def test_a_node_may_write_a_chat_message_to_an_add_messages_channel(self): + compiled = _graph() + native = compiled.invoke({"messages": [("user", "hi")]})["messages"] + out = _run( + DaprWorkflowGraphRunner(graph=compiled, name="chat-role"), + {"messages": [{"role": "user", "content": "hi"}]}, + ) + self.assertEqual(out.status, "completed", out.error) + got = [(m["type"], m["content"], m.get("role")) for m in out.output["messages"]] + want = [(m.type, m.content, getattr(m, "role", None)) for m in native] + self.assertEqual(got, want) diff --git a/tests/agent/langgraph/test_last_value_types.py b/tests/agent/langgraph/test_last_value_types.py new file mode 100644 index 00000000..6e36743c --- /dev/null +++ b/tests/agent/langgraph/test_last_value_types.py @@ -0,0 +1,94 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A plain (last value) channel holds the type its node wrote, not its JSON. + +A ``datetime`` reached the next node as a string, and a pydantic object as a +dict, so ``state["when"].year`` or ``state["profile"].name`` raised where +LangGraph hands the node what was written. +""" + +import datetime +import operator +from typing import Any, List + +from langchain_core.messages import AIMessage, AnyMessage +from langgraph.graph import END, START, StateGraph +from pydantic import BaseModel +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .test_runner import _RunnerTestCase, _run + + +class _Profile(BaseModel): + name: str + + +class _S(TypedDict, total=False): + history: Annotated[List[AnyMessage], operator.add] + when: datetime.datetime + profile: _Profile + seen: List[str] + + +def _graph() -> Any: + def write(state: _S) -> dict: + return { + "history": [AIMessage("x")], + "when": datetime.datetime(2020, 1, 2), + "profile": _Profile(name="n"), + } + + def read(state: _S) -> dict: + return { + "seen": [ + type(state["history"][0]).__name__, + type(state["when"]).__name__, + type(state["profile"]).__name__, + ] + } + + graph = StateGraph(_S) + graph.add_node("write", write) + graph.add_node("read", read) + graph.add_edge(START, "write") + graph.add_edge("write", "read") + graph.add_edge("read", END) + return graph.compile() + + +class TestLastValueTypes(_RunnerTestCase): + def test_the_next_node_reads_the_types_langgraph_gives_it(self): + compiled = _graph() + native = compiled.invoke({"history": []}) + self.assertEqual(native["seen"], ["AIMessage", "datetime", "_Profile"]) + out = _run( + DaprWorkflowGraphRunner(graph=compiled, name="lv-types"), {"history": []} + ) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["seen"], native["seen"]) + + def test_the_input_keeps_its_types_too(self): + def read(state: _S) -> dict: + return {"seen": [type(state["when"]).__name__]} + + graph = StateGraph(_S) + graph.add_node("read", read) + graph.add_edge(START, "read") + graph.add_edge("read", END) + out = _run( + DaprWorkflowGraphRunner(graph=graph.compile(), name="lv-input"), + {"when": datetime.datetime(2020, 1, 2)}, + ) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["seen"], ["datetime"]) + + def test_the_output_is_still_json(self): + import json + + out = _run( + DaprWorkflowGraphRunner(graph=_graph(), name="lv-output"), {"history": []} + ) + json.dumps(out.output) diff --git a/tests/agent/langgraph/test_managed_values.py b/tests/agent/langgraph/test_managed_values.py new file mode 100644 index 00000000..ff580618 --- /dev/null +++ b/tests/agent/langgraph/test_managed_values.py @@ -0,0 +1,119 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``RemainingSteps`` and ``IsLastStep`` are given to nodes and routers. + +``create_react_agent`` reads ``remaining_steps`` to answer "Sorry, need more +steps" before it runs into the limit; a node or router that reads them got +``None`` here. +""" + +import asyncio +import operator +from typing import Any + +from langchain_core.language_models import BaseChatModel +from langchain_core.messages import AIMessage +from langchain_core.outputs import ChatGeneration, ChatResult +from langchain_core.tools import tool +from langgraph.graph import END, START, StateGraph +from langgraph.managed import IsLastStep, RemainingSteps +from langgraph.prebuilt import create_react_agent +from typing_extensions import Annotated, TypedDict + +from .golden_harness import _FakeDaprTest, _runner + + +class _S(TypedDict, total=False): + log: Annotated[list, operator.add] + remaining_steps: RemainingSteps + last: IsLastStep + + +def _chain() -> Any: + def record(name: str) -> Any: + def node(state: _S) -> dict: + return {"log": [(name, state.get("remaining_steps"), state.get("last"))]} + + return node + + graph = StateGraph(_S) + for name in ("a", "b", "c"): + graph.add_node(name, record(name)) + graph.add_edge(START, "a") + graph.add_edge("a", "b") + + def route(state: _S) -> str: + # a router reads them too, at the step of the node it follows: b's + wanted = (state.get("remaining_steps"), state.get("last")) + return "c" if wanted[0] is not None and wanted[1] is False else END + + graph.add_conditional_edges("b", route, ["c", END]) + graph.add_edge("c", END) + return graph.compile() + + +class TestManagedValues(_FakeDaprTest): + def _invoke(self, runner: Any, config: Any) -> Any: + return runner.invoke({"log": []}, config=config, poll_interval=0.01) + + async def test_nodes_read_the_values_langgraph_gives_them(self): + compiled = _chain() + for limit in (4, 6, 25): + with self.subTest(limit=limit): + self.setUp() + config = {"recursion_limit": limit} + native = [list(e) for e in compiled.invoke({"log": []}, config)["log"]] + self.assertEqual(native[0][1], limit - 1) + self.assertEqual(len(native), 3) + runner = _runner(compiled, f"managed-{limit}") + out = await asyncio.to_thread(self._invoke, runner, config) + self.assertEqual(out["log"], native) + + async def test_the_last_step_is_flagged(self): + compiled = _chain() + native = compiled.invoke({"log": []}, {"recursion_limit": 4})["log"] + self.assertEqual([step[2] for step in native], [False, False, True]) + runner = _runner(compiled, "managed-last") + out = await asyncio.to_thread(self._invoke, runner, {"recursion_limit": 4}) + self.assertEqual([step[2] for step in out["log"]], [False, False, True]) + + +@tool +def ping() -> str: + """Ping.""" + return "pong" + + +class _AlwaysTools(BaseChatModel): + @property + def _llm_type(self) -> str: + return "always-tools" + + def bind_tools(self, tools: Any, **kwargs: Any) -> "_AlwaysTools": + return self + + def _generate(self, messages, stop=None, run_manager=None, **kw): + call = {"name": "ping", "args": {}, "id": f"c{len(messages)}"} + return ChatResult( + generations=[ + ChatGeneration(message=AIMessage(content="", tool_calls=[call])) + ] + ) + + +class TestReactAgentNearTheLimit(_FakeDaprTest): + async def test_it_answers_that_it_needs_more_steps_as_native_does(self): + agent = create_react_agent(_AlwaysTools(), [ping]) + config = {"recursion_limit": 6} + native = agent.invoke({"messages": [("user", "go")]}, config) + self.assertIn("need more steps", native["messages"][-1].content) + runner = _runner(agent, "managed-react") + out = await asyncio.to_thread( + lambda: runner.invoke( + {"messages": [{"role": "user", "content": "go"}]}, + config=config, + poll_interval=0.01, + ) + ) + self.assertIn("need more steps", out["messages"][-1]["content"]) diff --git a/tests/agent/langgraph/test_orchestrator_graph_config.py b/tests/agent/langgraph/test_orchestrator_graph_config.py new file mode 100644 index 00000000..0f499127 --- /dev/null +++ b/tests/agent/langgraph/test_orchestrator_graph_config.py @@ -0,0 +1,70 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A run an orchestrator starts with ``{"task": ...}`` gets the graph's own config. + +Every runner entry point merges the config bound with ``with_config`` into the +run's config; the workflow an orchestrator starts takes the same. +""" + +from typing import Any, Dict, Optional + +from langchain_core.runnables import RunnableConfig +from langgraph.graph import END, START, StateGraph +from typing_extensions import TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.models import GraphWorkflowOutput + +from .test_runner import _InlineWorkflowContext, _RunnerTestCase +from .test_workflow_replay import _drive + + +class _S(TypedDict, total=False): + n: int + tenant: Optional[str] + error: Optional[str] + + +def _loop(steps: int) -> Any: + def count(state: _S, config: RunnableConfig) -> dict: + configurable = config.get("configurable") or {} + return { + "n": state.get("n", 0) + 1, + "tenant": configurable.get("tenant"), + "error": None if "tenant" in configurable else "no tenant", + } + + graph = StateGraph(_S) + graph.add_node("count", count) + graph.add_edge(START, "count") + graph.add_conditional_edges( + "count", lambda s: "count" if s["n"] < steps else END, ["count", END] + ) + return graph.compile() + + +def _task_run(compiled: Any, name: str) -> Dict[str, Any]: + runner = DaprWorkflowGraphRunner(graph=compiled, name=name) + runner._setup_serve_defaults() + return _drive(_InlineWorkflowContext(runner), {"task": "hi"}) + + +class TestOrchestratorRun(_RunnerTestCase): + def test_the_bound_configurable_reaches_the_nodes(self): + compiled = _loop(2).with_config(configurable={"tenant": "x"}) + out = GraphWorkflowOutput.from_dict(_task_run(compiled, "orch-configurable")) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["tenant"], "x") + self.assertIsNone(out.output["error"]) + + def test_the_bound_recursion_limit_bounds_the_run(self): + compiled = _loop(50).with_config(recursion_limit=5) + out = GraphWorkflowOutput.from_dict(_task_run(compiled, "orch-limit")) + self.assertEqual(out.status, "max_steps_reached") + self.assertEqual(out.steps, 5) + + def test_a_graph_without_a_bound_config_runs_as_before(self): + out = GraphWorkflowOutput.from_dict(_task_run(_loop(3).with_config(), "plain")) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["n"], 3) diff --git a/tests/agent/langgraph/test_parent_command.py b/tests/agent/langgraph/test_parent_command.py new file mode 100644 index 00000000..727bdb77 --- /dev/null +++ b/tests/agent/langgraph/test_parent_command.py @@ -0,0 +1,86 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A subgraph node that hands over with ``Command(graph=Command.PARENT)``. + +The swarm and supervisor patterns do it: a node inside a subgraph sends the +update and the ``goto`` to the graph the subgraph is a node of. The subgraph +runs inside the activity of its node, so the command must become that node's +result instead of failing the activity. +""" + +import asyncio +from typing import Any + +from langgraph.errors import ParentCommand +from langgraph.graph import END, START, StateGraph +from langgraph.types import Command + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.workflow import _parent_command_result + +from .golden_harness import _both, _Golden, _Out +from .test_runner import _run + + +def _handoff(*, async_inner: bool = False, graph: Any = Command.PARENT) -> Any: + if async_inner: + + async def inner(state: _Out) -> Any: + return Command(goto="b", update={"out": ["handoff"]}, graph=graph) + + else: + + def inner(state: _Out) -> Any: # type: ignore[misc] + return Command(goto="b", update={"out": ["handoff"]}, graph=graph) + + sub = StateGraph(_Out) + sub.add_node("inner", inner) + sub.add_edge(START, "inner") + + parent = StateGraph(_Out) + parent.add_node("a", sub.compile()) + parent.add_node("b", lambda state: {"out": ["b"]}) + parent.add_edge(START, "a") + parent.add_edge("b", END) + return parent.compile() + + +class TestParentCommand(_Golden): + async def test_the_handoff_is_the_subgraph_nodes_update_and_goto(self): + for async_inner in (False, True): + with self.subTest(async_inner=async_inner): + self.setUp() + native, ours = await asyncio.wait_for( + _both( + _handoff(async_inner=async_inner), + f"parent-command-{async_inner}", + {"out": []}, + ), + 20, + ) + self.assertEqual( + [c for m, c in native if m == "updates"], + [{"a": {"out": ["handoff"]}}, {"b": {"out": ["b"]}}], + ) + self._assert_same_sequence(native, ours) + + def test_the_run_completes_with_the_handoffs_update(self): + compiled = _handoff() + runner = DaprWorkflowGraphRunner(graph=compiled, name="parent-command-run") + out = _run(runner, {"out": []}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["out"], compiled.invoke({"out": []})["out"]) + self.assertEqual(out.output["out"], ["handoff", "b"]) + + def test_a_command_addressed_above_this_graph_is_still_an_error(self): + lost = ParentCommand(Command(goto="b", graph=Command.PARENT)) + with self.assertRaises(ParentCommand): + _parent_command_result(lost, "a") + for graph in ("", "a"): + got = _parent_command_result( + ParentCommand(Command(goto="b", update={"out": [1]}, graph=graph)), "a" + ) + self.assertEqual( + (got.goto, got.update, got.graph), ("b", {"out": [1]}, None) + ) diff --git a/tests/agent/langgraph/test_reducer_value_types.py b/tests/agent/langgraph/test_reducer_value_types.py new file mode 100644 index 00000000..0c5262ea --- /dev/null +++ b/tests/agent/langgraph/test_reducer_value_types.py @@ -0,0 +1,132 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A reducer channel holds the types its nodes wrote, not their JSON. + +State such as ``Annotated[set, operator.or_]`` or ``Annotated[tuple, +operator.add]`` failed the run (the reducer was handed a string or a list where +it needs a set or a tuple), and a list of messages under ``operator.add`` came +back to the next node as dicts. +""" + +import operator +from typing import Any, List + +from langchain_core.messages import AIMessage, AnyMessage +from langgraph.graph import END, START, StateGraph +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .test_runner import _RunnerTestCase, _run + + +class _Sets(TypedDict, total=False): + tags: Annotated[set, operator.or_] + frozen: Annotated[frozenset, operator.or_] + seen: List[str] + + +class _Tuples(TypedDict, total=False): + pair: Annotated[tuple, operator.add] + seen: str + + +class _History(TypedDict, total=False): + history: Annotated[List[AnyMessage], operator.add] + seen: str + + +def _two_nodes(schema: Any, first: Any, second: Any, reader: Any) -> Any: + graph = StateGraph(schema) + graph.add_node("a", first) + graph.add_node("b", second) + graph.add_node("read", reader) + graph.add_edge(START, "a") + graph.add_edge("a", "b") + graph.add_edge("b", "read") + graph.add_edge("read", END) + return graph.compile() + + +class TestReducerValueTypes(_RunnerTestCase): + def test_a_set_channel_reduces_with_or(self): + compiled = _two_nodes( + _Sets, + lambda s: {"tags": {"a"}, "frozen": frozenset({1})}, + lambda s: {"tags": {"b"}, "frozen": frozenset({2})}, + lambda s: {"seen": [type(s["tags"]).__name__, type(s["frozen"]).__name__]}, + ) + native = compiled.invoke({}) + out = _run(DaprWorkflowGraphRunner(graph=compiled, name="rv-set"), {}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(sorted(out.output["tags"]), sorted(native["tags"])) + self.assertEqual(sorted(out.output["frozen"]), [1, 2]) + self.assertEqual(out.output["seen"], ["set", "frozenset"]) + + def test_a_tuple_channel_reduces_with_add(self): + compiled = _two_nodes( + _Tuples, + lambda s: {"pair": (1,)}, + lambda s: {"pair": (2,)}, + lambda s: {"seen": type(s["pair"]).__name__}, + ) + native = compiled.invoke({}) + out = _run(DaprWorkflowGraphRunner(graph=compiled, name="rv-tuple"), {}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(list(out.output["pair"]), list(native["pair"])) + self.assertEqual(out.output["seen"], "tuple") + + def test_messages_in_a_list_channel_stay_messages_for_the_next_node(self): + compiled = _two_nodes( + _History, + lambda s: {"history": [AIMessage("x")]}, + lambda s: {"history": [AIMessage("y")]}, + lambda s: { + "seen": "|".join( + f"{type(m).__name__}:{m.content}" for m in s["history"] + ) + }, + ) + native = compiled.invoke({"history": []}) + out = _run( + DaprWorkflowGraphRunner(graph=compiled, name="rv-history"), + {"history": []}, + ) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["seen"], native["seen"]) + self.assertEqual(out.output["seen"], "AIMessage:x|AIMessage:y") + self.assertEqual( + [m["content"] for m in out.output["history"]], + [m.content for m in native["history"]], + ) + + +class TestStoredValues(_RunnerTestCase): + def test_plain_json_is_stored_as_it_is_and_the_rest_round_trips(self): + import datetime + import json + + from diagrid.agent.langgraph.values import ( + coerce_to_default, + decode_value, + encode_value, + is_encoded, + ) + + for plain in (None, 1, 2.5, "s", [1, "a", None], {"k": [1, {"j": True}]}): + self.assertIs(encode_value(plain), plain) + for rich in ( + {"a"}, + frozenset({1}), + datetime.date(2020, 1, 1), + [AIMessage("x")], + ): + stored = encode_value(rich) + self.assertTrue(is_encoded(stored), rich) + json.dumps(stored) + self.assertEqual(decode_value(stored), rich) + # a tuple has no JSON of its own: it comes back as a list, then as the + # channel's own type + self.assertEqual(coerce_to_default(decode_value(encode_value((1,))), ()), (1,)) + self.assertEqual(coerce_to_default([1], []), [1]) diff --git a/tests/agent/langgraph/test_root_state.py b/tests/agent/langgraph/test_root_state.py new file mode 100644 index 00000000..e936726b --- /dev/null +++ b/tests/agent/langgraph/test_root_state.py @@ -0,0 +1,64 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A graph whose whole state is one channel: ``StateGraph(Annotated[list, add])``. + +LangGraph names that channel ``__root__``. The graph's input is the channel's +value, a node is handed that value and what it returns is the channel's write +(not a dict of channels), and the run's result is the value. +""" + +import asyncio +import operator +from typing import Any + +from langgraph.graph import END, START, StateGraph +from typing_extensions import Annotated + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .golden_harness import _both, _FakeDaprTest, _Golden, _runner + + +def _graph() -> Any: + seen = [] + + def a(state: Any) -> Any: + seen.append(("a", type(state).__name__, list(state))) + return ["a"] + + def b(state: Any) -> Any: + return ["b"] + + graph = StateGraph(Annotated[list, operator.add]) + graph.add_node("a", a) + graph.add_node("b", b) + graph.add_edge(START, "a") + graph.add_edge("a", "b") + graph.add_edge("b", END) + compiled = graph.compile() + compiled.seen = seen # type: ignore[attr-defined] + return compiled + + +class TestRootState(_Golden): + async def test_the_stream_matches_native(self): + compiled = _graph() + native, ours = await asyncio.wait_for(_both(compiled, "root", ["in"]), 20) + self.assertEqual( + [c for m, c in native if m == "updates"], [{"a": ["a"]}, {"b": ["b"]}] + ) + self._assert_same_sequence(native, ours) + # the node was handed the channel's value, as a list + self.assertEqual({entry[:2] for entry in compiled.seen}, {("a", "list")}) + self.assertEqual(compiled.seen[-1][2], ["in"]) + + +class TestRootStateInvoke(_FakeDaprTest): + async def test_invoke_takes_the_value_and_returns_it(self): + compiled = _graph() + native = compiled.invoke(["in"]) + runner: DaprWorkflowGraphRunner = _runner(compiled, "root-invoke") + out = await asyncio.to_thread(lambda: runner.invoke(["in"], poll_interval=0.01)) + self.assertEqual(native, ["in", "a", "b"]) + self.assertEqual(out, native) diff --git a/tests/agent/langgraph/test_send_task_input.py b/tests/agent/langgraph/test_send_task_input.py new file mode 100644 index 00000000..95a597d1 --- /dev/null +++ b/tests/agent/langgraph/test_send_task_input.py @@ -0,0 +1,57 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""What the workflow hands the activity of a ``Send`` task. + +A ``Send`` task is numbered once, over the whole step, and that number (its +slot) is all the activity needs: the path of its chunks and the key of its +attempts both follow from it. +""" + +import json +from typing import Any, Dict, List + +from langgraph.graph import END, START, StateGraph +from langgraph.types import Command, Send + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .golden_harness import _Out +from .streaming_helpers import _IdCtx +from .test_runner import _run, _RunnerTestCase + + +class _RecordingCtx(_IdCtx): + """Keeps what each node activity was scheduled with.""" + + def __init__(self, runner: Any, workflow_id: str) -> None: + super().__init__(runner, workflow_id) + self.node_inputs: List[Dict[str, Any]] = [] + + def call_activity(self, activity: Any, *, input: Any, retry_policy: Any = None): + self.node_inputs.append(input) + return super().call_activity(activity, input=input, retry_policy=retry_policy) + + +def _graph() -> Any: + def fan(state: _Out) -> Any: + return Command(goto=[Send("work", {"i": i}) for i in (1, 2)]) + + graph = StateGraph(_Out) + graph.add_node("fan", fan) + graph.add_node("work", lambda arg: {"out": [arg["i"]]}) + graph.add_edge(START, "fan") + graph.add_edge("work", END) + return graph.compile() + + +class TestSendTaskInput(_RunnerTestCase): + def test_a_send_task_carries_its_argument_and_one_slot(self): + runner = DaprWorkflowGraphRunner(graph=_graph(), name="send-input") + ctx = _RecordingCtx(runner, "wf-send-input") + out = _run(runner, {"out": []}, ctx) + self.assertEqual(out.status, "completed", out.error) + sends = [i["send"] for i in ctx.node_inputs if i.get("send")] + self.assertEqual([sorted(s) for s in sends], [["arg", "slot"]] * 2) + self.assertEqual([s["slot"] for s in sends], [0, 1]) + json.dumps(sends) diff --git a/tests/agent/langgraph/test_step_bound.py b/tests/agent/langgraph/test_step_bound.py new file mode 100644 index 00000000..b961bd51 --- /dev/null +++ b/tests/agent/langgraph/test_step_bound.py @@ -0,0 +1,166 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""How many steps a run may take: ``recursion_limit`` and the runner's ``max_steps``. + +A ``recursion_limit`` bounds the run as LangGraph counts it: that many node steps +run, and the run fails when it has taken them, whether or not more is pending. +The runner's ``max_steps`` is its own guard; a limit that only the graph's +``with_config`` supplies cannot raise it. +""" + +import asyncio +from typing import Any, List + +from langgraph.config import get_stream_writer +from langgraph.errors import GraphRecursionError +from langgraph.graph import END, START, StateGraph +from typing_extensions import TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .golden_harness import _FakeDaprTest, _FakeWorkflowClient, _runner + + +class _S(TypedDict, total=False): + n: int + + +def _forever() -> Any: + def step(state: _S) -> dict: + return {"n": state.get("n", 0) + 1} + + graph = StateGraph(_S) + graph.add_node("step", step) + graph.add_edge(START, "step") + graph.add_conditional_edges("step", lambda s: "step", ["step"]) + return graph.compile() + + +def _talking_chain(length: int) -> Any: + graph = StateGraph(_S) + names = [f"n{i}" for i in range(length)] + for name in names: + + def node(state: _S, name: str = name) -> dict: + get_stream_writer()(name) + return {"n": state.get("n", 0) + 1} + + graph.add_node(name, node) + graph.add_edge(START, names[0]) + for a, b in zip(names, names[1:]): + graph.add_edge(a, b) + graph.add_edge(names[-1], END) + return graph.compile() + + +def _talking_loop() -> Any: + def step(state: _S) -> dict: + get_stream_writer()(state.get("n", 0)) + return {"n": state.get("n", 0) + 1} + + graph = StateGraph(_S) + graph.add_node("step", step) + graph.add_edge(START, "step") + graph.add_conditional_edges("step", lambda s: "step", ["step"]) + return graph.compile() + + +def _runner_with(compiled: Any, name: str, **kwargs: Any) -> DaprWorkflowGraphRunner: + runner = DaprWorkflowGraphRunner(graph=compiled, name=name, **kwargs) + runner._started = True + runner._workflow_client = _FakeWorkflowClient(runner) # type: ignore[assignment] + return runner + + +async def _customs(runner: Any, config: Any, name: str) -> List[Any]: + """The custom chunks of a run, up to the recursion error it ends with.""" + seen: List[Any] = [] + try: + async for mode, chunk in runner.astream( + {}, + config=config, + workflow_id=f"wf-{name}", + stream_mode=["custom"], + poll_interval=0.01, + ): + if mode == "custom": + seen.append(chunk) + except GraphRecursionError: + seen.append("GraphRecursionError") + return seen + + +def _native_customs(compiled: Any, config: Any) -> List[Any]: + seen: List[Any] = [] + try: + for mode, chunk in compiled.stream({}, config, stream_mode=["custom"]): + seen.append(chunk) + except GraphRecursionError: + seen.append("GraphRecursionError") + return seen + + +class TestRecursionLimitCountsLikeLangGraph(_FakeDaprTest): + async def test_a_chain_cut_by_the_limit_runs_every_step_the_limit_allows(self): + compiled = _talking_chain(4) + config = {"recursion_limit": 4} + native = _native_customs(compiled, config) + self.assertEqual(native, ["n0", "n1", "n2", "n3", "GraphRecursionError"]) + runner = _runner(compiled, "limit-chain") + self.assertEqual(await _customs(runner, config, "limit-chain"), native) + + async def test_a_loop_runs_as_many_steps_as_the_limit(self): + compiled = _talking_loop() + config = {"recursion_limit": 10} + native = _native_customs(compiled, config) + self.assertEqual(len(native), 11) + runner = _runner(compiled, "limit-loop") + self.assertEqual(await _customs(runner, config, "limit-loop"), native) + + async def test_a_limit_one_above_the_steps_a_chain_needs_completes(self): + compiled = _talking_chain(4) + config = {"recursion_limit": 5} + native = _native_customs(compiled, config) + self.assertEqual(native, ["n0", "n1", "n2", "n3"]) + runner = _runner(compiled, "limit-enough") + self.assertEqual(await _customs(runner, config, "limit-enough"), native) + + +class TestRunnerMaxStepsAgainstTheGraphsBoundLimit(_FakeDaprTest): + def _invoke_error(self, runner: Any, config: Any = None) -> str: + try: + runner.invoke({}, config=config, poll_interval=0.01) + except GraphRecursionError as e: + return str(e) + return "" + + async def test_an_explicit_max_steps_caps_a_limit_only_the_graph_binds(self): + compiled = _forever().with_config(recursion_limit=60) + runner = _runner_with(compiled, "bound-capped", max_steps=5) + message = await asyncio.to_thread(self._invoke_error, runner) + self.assertIn("(5)", message) + + async def test_the_cap_holds_on_the_streaming_path_too(self): + compiled = _talking_loop().with_config(recursion_limit=60) + runner = _runner_with(compiled, "bound-capped-stream", max_steps=5) + seen = await _customs(runner, None, "bound-capped-stream") + self.assertEqual(seen, [0, 1, 2, 3, 4, "GraphRecursionError"]) + + async def test_without_an_explicit_max_steps_the_bound_limit_applies(self): + compiled = _talking_loop().with_config(recursion_limit=150) + runner = _runner_with(compiled, "bound-uncapped") + seen = await _customs(runner, None, "bound-uncapped") + self.assertEqual(len(seen), 151) + + async def test_a_limit_the_caller_passes_wins_over_max_steps(self): + compiled = _talking_loop().with_config(recursion_limit=60) + runner = _runner_with(compiled, "caller-limit", max_steps=5) + seen = await _customs(runner, {"recursion_limit": 20}, "caller-limit") + self.assertEqual(len(seen), 21) + + async def test_a_bound_limit_below_max_steps_is_the_graphs_own(self): + compiled = _talking_loop().with_config(recursion_limit=3) + runner = _runner_with(compiled, "bound-lower", max_steps=50) + seen = await _customs(runner, None, "bound-lower") + self.assertEqual(seen, [0, 1, 2, "GraphRecursionError"]) diff --git a/tests/agent/langgraph/test_workflow_async_loop.py b/tests/agent/langgraph/test_workflow_async_loop.py new file mode 100644 index 00000000..fdf65c81 --- /dev/null +++ b/tests/agent/langgraph/test_workflow_async_loop.py @@ -0,0 +1,91 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Async nodes run on one event loop that outlives the activity. + +A chat model keeps an async HTTP client (a connection pool bound to the loop it +was first used on). A loop made and closed for each activity would fail the +next activity that reuses the client with ``Event loop is closed``. +""" + +import asyncio +from typing import Any, List, TypedDict + +from langchain_core.runnables.config import var_child_runnable_config +from langgraph.graph import END, START, StateGraph +from langgraph.utils.runnable import RunnableCallable + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .test_runner import _run, _RunnerTestCase + + +class _State(TypedDict, total=False): + n: int + + +class TestAsyncNodeLoop(_RunnerTestCase): + def _graph(self, loops: List[Any], node_count: int = 3) -> DaprWorkflowGraphRunner: + graph = StateGraph(_State) + names = [] + for i in range(node_count): + + async def node(state: _State) -> dict: + loops.append(asyncio.get_running_loop()) + return {"n": i} + + graph.add_node(f"n{i}", node) + names.append(f"n{i}") + graph.add_edge(START, names[0]) + for a, b in zip(names, names[1:]): + graph.add_edge(a, b) + graph.add_edge(names[-1], END) + return DaprWorkflowGraphRunner(graph=graph.compile(), name="loop") + + def test_every_activity_runs_on_the_same_open_loop(self): + loops: List[Any] = [] + runner = self._graph(loops) + out = _run(runner, {"n": 0}) + self.assertEqual(out.status, "completed") + self.assertEqual(len(loops), 3) + self.assertEqual(len({id(loop) for loop in loops}), 1) + self.assertFalse(loops[0].is_closed()) + + def test_a_dual_entry_node_shares_the_loop_too(self): + loops: List[Any] = [] + + def sync_fn(state: _State) -> dict: + return {"n": 1} + + async def async_fn(state: _State) -> dict: + loops.append(asyncio.get_running_loop()) + return {"n": 1} + + graph = StateGraph(_State) + graph.add_node("a", RunnableCallable(sync_fn, async_fn)) + graph.add_node("b", RunnableCallable(sync_fn, async_fn)) + graph.add_edge(START, "a") + graph.add_edge("a", "b") + graph.add_edge("b", END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="loop-dual") + _run(runner, {"n": 0}) + self.assertEqual(len(loops), 2) + self.assertIs(loops[0], loops[1]) + + def test_the_activitys_ambient_config_reaches_the_coroutine(self): + seen: List[Any] = [] + + async def node(state: _State) -> dict: + seen.append(var_child_runnable_config.get()) + return {"n": 1} + + graph = StateGraph(_State) + graph.add_node("a", node) + graph.add_edge(START, "a") + graph.add_edge("a", END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="loop-ctx") + _run(runner, {"n": 0}) + self.assertEqual(len(seen), 1) + self.assertIsNotNone(seen[0]) + # the caller's context is untouched by what ran on the loop + self.assertIsNone(var_child_runnable_config.get()) diff --git a/tests/agent/langgraph/test_workflow_channel_defaults.py b/tests/agent/langgraph/test_workflow_channel_defaults.py new file mode 100644 index 00000000..3a003ee0 --- /dev/null +++ b/tests/agent/langgraph/test_workflow_channel_defaults.py @@ -0,0 +1,79 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A reducer channel nobody has written holds its default, as it does natively.""" + +import operator +from typing import Annotated, Any, Dict + +from langgraph.graph import END, START, MessagesState, StateGraph +from typing_extensions import TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .test_runner import _run, _RunnerTestCase + + +def _merge(old: dict, new: dict) -> dict: + return {**old, **new} + + +class _State(TypedDict, total=False): + docs: Annotated[list, operator.add] + n: Annotated[int, operator.add] + d: Annotated[dict, _merge] + q: str + + +class TestUnwrittenReducerChannels(_RunnerTestCase): + def _both(self, graph: StateGraph, graph_input: Dict[str, Any]): + compiled = graph.compile() + native = compiled.invoke(graph_input) + out = _run( + DaprWorkflowGraphRunner(graph=compiled, name="defaults"), graph_input + ) + return native, out + + def test_a_node_reads_a_channel_nobody_wrote(self): + graph = StateGraph(_State) + graph.add_node("a", lambda s: {"docs": s["docs"] + ["a"], "n": s["n"] + 1}) + graph.add_edge(START, "a") + graph.add_edge("a", END) + native, out = self._both(graph, {"q": "x"}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["docs"], native["docs"]) + self.assertEqual(out.output["n"], native["n"]) + + def test_a_router_reads_a_channel_nobody_wrote(self): + graph = StateGraph(_State) + graph.add_node("a", lambda s: {"q": "y"}) + graph.add_node("b", lambda s: {"docs": ["b"]}) + graph.add_edge(START, "a") + graph.add_conditional_edges("a", lambda s: "b" if not s["docs"] else END) + graph.add_edge("b", END) + native, out = self._both(graph, {"q": "x"}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["docs"], native["docs"]) + + def test_a_messages_graph_started_without_messages(self): + graph = StateGraph(MessagesState) + graph.add_node( + "a", lambda s: {"messages": [("assistant", str(len(s["messages"])))]} + ) + graph.add_edge(START, "a") + graph.add_edge("a", END) + native, out = self._both(graph, {}) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual( + [m["content"] for m in out.output["messages"]], + [m.content for m in native["messages"]], + ) + + def test_the_output_has_the_channels_nobody_wrote(self): + graph = StateGraph(_State) + graph.add_node("a", lambda s: {"q": "y"}) + graph.add_edge(START, "a") + graph.add_edge("a", END) + native, out = self._both(graph, {"q": "x"}) + self.assertEqual(native, {"docs": [], "n": 0, "d": {}, "q": "y"}) + self.assertEqual(out.output, native) diff --git a/tests/agent/langgraph/test_workflow_defer.py b/tests/agent/langgraph/test_workflow_defer.py new file mode 100644 index 00000000..673d9be2 --- /dev/null +++ b/tests/agent/langgraph/test_workflow_defer.py @@ -0,0 +1,93 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``add_node(..., defer=True)``: the node runs once, when nothing else is pending.""" + +import operator +from typing import Any + +from langgraph.graph import END, START, StateGraph +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.models import GraphConfig + +from .test_runner import _clear_dapr_registration, _run, _RunnerTestCase + + +class _Log(TypedDict, total=False): + log: Annotated[list, operator.add] + + +def _node(name: str) -> Any: + return lambda state: {"log": [name]} + + +class TestDeferredNode(_RunnerTestCase): + def _both(self, graph: StateGraph, name: str): + _clear_dapr_registration() + compiled = graph.compile() + native = compiled.invoke({"log": []}) + out = _run(DaprWorkflowGraphRunner(graph=compiled, name=name), {"log": []}) + self.assertEqual(out.status, "completed", out.error) + return native["log"], out.output["log"] + + def test_a_deferred_node_reached_from_branches_of_different_length_runs_once(self): + graph = StateGraph(_Log) + for name in ("a", "b", "b2"): + graph.add_node(name, _node(name)) + graph.add_node("fin", _node("fin"), defer=True) + graph.add_edge(START, "a") + graph.add_edge(START, "b") + graph.add_edge("b", "b2") + graph.add_edge("a", "fin") + graph.add_edge("b2", "fin") + graph.add_edge("fin", END) + native, ours = self._both(graph, "defer-uneven") + self.assertEqual(native, ["a", "b", "b2", "fin"]) + self.assertEqual(ours, native) + + def test_what_a_deferred_node_starts_goes_on(self): + graph = StateGraph(_Log) + for name in ("a", "b", "b2", "after"): + graph.add_node(name, _node(name)) + graph.add_node("fin", _node("fin"), defer=True) + graph.add_edge(START, "a") + graph.add_edge(START, "b") + graph.add_edge("b", "b2") + graph.add_edge("a", "fin") + graph.add_edge("b2", "fin") + graph.add_edge("fin", "after") + graph.add_edge("after", END) + native, ours = self._both(graph, "defer-after") + self.assertEqual(native, ["a", "b", "b2", "fin", "after"]) + self.assertEqual(ours, native) + + def test_a_deferred_join_waits_for_the_rest_too(self): + graph = StateGraph(_Log) + for name in ("a", "b", "c", "c2", "c3"): + graph.add_node(name, _node(name)) + graph.add_node("fin", _node("fin"), defer=True) + graph.add_edge(START, "a") + graph.add_edge(START, "b") + graph.add_edge(START, "c") + graph.add_edge("c", "c2") + graph.add_edge("c2", "c3") + graph.add_edge(["a", "b"], "fin") + graph.add_edge("c3", END) + graph.add_edge("fin", END) + native, ours = self._both(graph, "defer-join") + self.assertEqual(native, ["a", "b", "c", "c2", "c3", "fin"]) + self.assertEqual(ours, native) + + def test_a_graph_without_a_deferred_node_has_none_in_its_config(self): + _clear_dapr_registration() + graph = StateGraph(_Log) + graph.add_node("a", _node("a")) + graph.add_edge(START, "a") + graph.add_edge("a", END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="defer-none") + self.assertEqual(runner.graph_config.deferred, []) + self.assertEqual( + GraphConfig.from_dict(runner.graph_config.to_dict()).deferred, [] + ) diff --git a/tests/agent/langgraph/test_workflow_goto_order.py b/tests/agent/langgraph/test_workflow_goto_order.py new file mode 100644 index 00000000..14077d03 --- /dev/null +++ b/tests/agent/langgraph/test_workflow_goto_order.py @@ -0,0 +1,46 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A task's Command goto Sends come before the Sends of its conditional edges.""" + +import itertools +import operator +from typing import Any, List + +from langchain_core.messages import AIMessageChunk +from langgraph.graph import END, START, StateGraph +from langgraph.types import Command, Send +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .test_runner import _clear_dapr_registration, _run, _RunnerTestCase +from .golden_harness import _both, _Golden + + +class _Log(TypedDict, total=False): + log: Annotated[list, operator.add] + + +def _native_and_ours(graph: StateGraph, graph_input: dict, name: str): + _clear_dapr_registration() + compiled = graph.compile() + native = compiled.invoke(graph_input) + out = _run(DaprWorkflowGraphRunner(graph=compiled, name=name), graph_input) + return native, out + + +class TestGotoOrder(_Golden): + def test_goto_sends_come_before_a_branchs_sends(self): + def fan(state: _Log) -> Command: + return Command(goto=[Send("w", {"i": "goto"})]) + + graph = StateGraph(_Log) + graph.add_node("fan", fan) + graph.add_node("w", lambda arg: {"log": [str(arg["i"])]}) + graph.add_edge(START, "fan") + graph.add_conditional_edges("fan", lambda s: [Send("w", {"i": "cond"})], ["w"]) + graph.add_edge("w", END) + native, out = _native_and_ours(graph, {"log": ["fan"]}, "numbering-goto") + self.assertEqual(native["log"], ["fan", "goto", "cond"]) + self.assertEqual(out.output["log"], native["log"]) diff --git a/tests/agent/langgraph/test_workflow_message_ids.py b/tests/agent/langgraph/test_workflow_message_ids.py new file mode 100644 index 00000000..d0517075 --- /dev/null +++ b/tests/agent/langgraph/test_workflow_message_ids.py @@ -0,0 +1,106 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Ids of messages a node writes are made in the activity, so a replay keeps them. + +``add_messages`` gives an id-less message a random one. Run in the orchestrator it +would invent a new id on every replay, and a later ``RemoveMessage(id=...)`` (the +trim and summarise pattern) would name an id the replay never made. +""" + +from typing import Any, Dict, List + +from langchain_core.messages import AIMessage, RemoveMessage, ToolMessage +from langgraph.graph import END, START, MessagesState, StateGraph + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.workflow import set_default_graph_config + +from .test_runner import _RunnerTestCase +from .test_workflow_replay import _drive, _RecordingCtx, _ReplayCtx + + +def _runner(*nodes: Any) -> DaprWorkflowGraphRunner: + graph = StateGraph(MessagesState) + names = [] + for i, fn in enumerate(nodes): + graph.add_node(f"n{i}", fn) + names.append(f"n{i}") + graph.add_edge(START, names[0]) + for a, b in zip(names, names[1:]): + graph.add_edge(a, b) + graph.add_edge(names[-1], END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="ids") + set_default_graph_config(runner.graph_config, max_steps=10) + return runner + + +class TestWrittenMessageIds(_RunnerTestCase): + def _record_and_replay(self, runner: DaprWorkflowGraphRunner): + first = _RecordingCtx(runner) + out = _drive(first, {"task": "hello"}) + replay = _ReplayCtx(runner, first.recorded) + replayed = _drive(replay, {"task": "hello"}) + return out, replayed, replay + + def test_a_remove_message_of_an_id_less_message_survives_a_replay(self): + def write(state: MessagesState) -> dict: + return {"messages": [AIMessage(content="x")]} + + def trim(state: MessagesState) -> dict: + return {"messages": [RemoveMessage(id=state["messages"][-1].id)]} + + out, replayed, replay = self._record_and_replay(_runner(write, trim)) + self.assertEqual(out["status"], "completed") + self.assertEqual([m["content"] for m in out["output"]["messages"]], ["hello"]) + self.assertEqual(replay.mismatches, []) + self.assertEqual(replayed, out) + + def test_a_replay_gives_a_tool_message_the_id_the_node_saw(self): + def write(state: MessagesState) -> dict: + return {"messages": [ToolMessage(content="r", tool_call_id="c1")]} + + def trim(state: MessagesState) -> dict: + return {"messages": [RemoveMessage(id=state["messages"][-1].id)]} + + out, replayed, replay = self._record_and_replay(_runner(write, trim)) + self.assertEqual(replay.mismatches, []) + self.assertEqual(replayed, out) + + def test_every_written_message_has_an_id(self): + def write(state: MessagesState) -> dict: + return {"messages": [AIMessage(content="x"), ("assistant", "y")]} + + out, _, _ = self._record_and_replay(_runner(write)) + ids: List[Any] = [m.get("id") for m in out["output"]["messages"]] + self.assertTrue(all(isinstance(i, str) and i for i in ids), ids) + self.assertEqual(len(set(ids)), len(ids)) + + +class TestReducerFailure(_RunnerTestCase): + def test_a_reducer_that_raises_fails_the_run_instead_of_overwriting(self): + from typing import Annotated + + from typing_extensions import TypedDict + + def strict(old: list, new: list) -> list: + if "bad" in new: + raise ValueError("no bad values") + return old + new + + class State(TypedDict): + log: Annotated[list, strict] + + graph = StateGraph(State) + graph.add_node("a", lambda s: {"log": ["ok"]}) + graph.add_node("b", lambda s: {"log": ["bad"]}) + graph.add_edge(START, "a") + graph.add_edge("a", "b") + graph.add_edge("b", END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="strict") + set_default_graph_config(runner.graph_config, max_steps=10) + out = _drive(_RecordingCtx(runner), {"log": []}) + self.assertEqual(out["status"], "error") + self.assertIn("log", out["error"]) + self.assertIn("no bad values", out["error"]) + self.assertEqual(out["output"], {"log": ["ok"]}) diff --git a/tests/agent/langgraph/test_workflow_message_inputs.py b/tests/agent/langgraph/test_workflow_message_inputs.py new file mode 100644 index 00000000..572b9184 --- /dev/null +++ b/tests/agent/langgraph/test_workflow_message_inputs.py @@ -0,0 +1,79 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Messages reach a node as LangGraph hands them over, on any add_messages channel.""" + +from typing import Annotated, Any, List + +from langchain_core.messages import AnyMessage, BaseMessage, HumanMessage +from langgraph.graph import END, START, MessagesState, StateGraph +from langgraph.graph.message import add_messages +from typing_extensions import TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .test_runner import _clear_dapr_registration, _run, _RunnerTestCase + + +def _seen_graph(channel: str, schema: Any) -> StateGraph: + """A one-node graph whose output ``seen`` lists what the node got on ``channel``.""" + + def node(state: Any) -> dict: + got = state[channel] + return {"seen": [f"{type(m).__name__}:{m.content}" for m in got]} + + graph = StateGraph(schema) + graph.add_node("a", node) + graph.add_edge(START, "a") + graph.add_edge("a", END) + return graph + + +class _Seen(MessagesState): + seen: List[str] + + +class _History(TypedDict, total=False): + history: Annotated[List[AnyMessage], add_messages] + seen: List[str] + + +class TestMessageInputShapes(_RunnerTestCase): + def _both(self, graph: StateGraph, graph_input: dict): + _clear_dapr_registration() + compiled = graph.compile() + native = compiled.invoke(graph_input) + out = _run(DaprWorkflowGraphRunner(graph=compiled, name="shapes"), graph_input) + self.assertEqual(out.status, "completed", out.error) + return native, out + + def test_every_shape_add_messages_accepts_reaches_the_node_as_a_message(self): + shapes = { + "string": "hi", + "pair": ("user", "hi"), + "message": HumanMessage("hi"), + "list of string": ["hi"], + "dict": {"role": "user", "content": "hi"}, + "list of pair": [("user", "hi")], + } + for label, value in shapes.items(): + with self.subTest(label): + native, out = self._both( + _seen_graph("messages", _Seen), {"messages": value} + ) + self.assertEqual(out.output["seen"], native["seen"]) + self.assertEqual(out.output["seen"], ["HumanMessage:hi"]) + + def test_a_channel_not_named_messages_reaches_the_node_as_messages(self): + native, out = self._both( + _seen_graph("history", _History), {"history": HumanMessage("hi")} + ) + self.assertEqual(out.output["seen"], native["seen"]) + self.assertEqual(out.output["seen"], ["HumanMessage:hi"]) + + def test_the_output_messages_of_such_a_channel_have_an_id(self): + _, out = self._both( + _seen_graph("history", _History), {"history": [HumanMessage("hi")]} + ) + ids = [m.get("id") for m in out.output.get("history", [])] + self.assertTrue(ids and all(isinstance(i, str) and i for i in ids), ids) diff --git a/tests/agent/langgraph/test_workflow_overwrite.py b/tests/agent/langgraph/test_workflow_overwrite.py new file mode 100644 index 00000000..e69f55aa --- /dev/null +++ b/tests/agent/langgraph/test_workflow_overwrite.py @@ -0,0 +1,51 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A write of Overwrite replaces a reducer channel's value, as in LangGraph.""" + +from langchain_core.messages import AIMessage +from langgraph.graph import END, START, MessagesState, StateGraph +from langgraph.types import Overwrite + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .golden_harness import _Log +from .test_runner import _run, _RunnerTestCase + + +class TestOverwrite(_RunnerTestCase): + def _both(self, graph: StateGraph, graph_input: dict): + compiled = graph.compile() + native = compiled.invoke(graph_input) + out = _run(DaprWorkflowGraphRunner(graph=compiled, name="over"), graph_input) + self.assertEqual(out.status, "completed", out.error) + return native, out + + def test_overwrite_replaces_the_value_of_a_reducer_channel(self): + graph = StateGraph(_Log) + graph.add_node("a", lambda s: {"log": ["a"]}) + graph.add_node("b", lambda s: {"log": Overwrite(["reset"])}) + graph.add_node("c", lambda s: {"log": ["c"]}) + graph.add_edge(START, "a") + graph.add_edge("a", "b") + graph.add_edge("b", "c") + graph.add_edge("c", END) + native, out = self._both(graph, {}) + self.assertEqual(native["log"], ["reset", "c"]) + self.assertEqual(out.output["log"], native["log"]) + + def test_overwrite_of_messages_replaces_the_history(self): + graph = StateGraph(MessagesState) + graph.add_node("a", lambda s: {"messages": [AIMessage(content="a")]}) + graph.add_node( + "b", lambda s: {"messages": Overwrite([AIMessage(content="summary")])} + ) + graph.add_edge(START, "a") + graph.add_edge("a", "b") + graph.add_edge("b", END) + native, out = self._both(graph, {"messages": [("user", "hi")]}) + self.assertEqual( + [m["content"] for m in out.output["messages"]], + [m.content for m in native["messages"]], + ) + self.assertEqual([m["content"] for m in out.output["messages"]], ["summary"]) diff --git a/tests/agent/langgraph/test_workflow_replay.py b/tests/agent/langgraph/test_workflow_replay.py new file mode 100644 index 00000000..94e53367 --- /dev/null +++ b/tests/agent/langgraph/test_workflow_replay.py @@ -0,0 +1,112 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``agent_workflow`` is deterministic: a replay schedules what the first run did. + +Dapr replays the orchestrator from its first line for every decision, feeding the +recorded result of each activity. Anything the code invents (a random id) then +differs between the run that scheduled an activity and the replay that consumes +its result. +""" + +import json +from typing import Any, Dict, List, Tuple +from unittest import mock + +from langgraph.graph import END, START, MessagesState, StateGraph + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.workflow import ( + agent_workflow, + set_default_graph_config, +) + +from .test_runner import _InlineWorkflowContext, _RunnerTestCase + +Recorded = List[Tuple[Any, Any]] + + +class _RecordingCtx(_InlineWorkflowContext): + """The first execution: runs each activity and records its input and result.""" + + def __init__(self, runner: DaprWorkflowGraphRunner): + super().__init__(runner) + self.recorded: Recorded = [] + + def call_activity(self, activity: Any, *, input: Any, retry_policy: Any = None): + result = super().call_activity(activity, input=input, retry_policy=retry_policy) + self.recorded.append((json.loads(json.dumps(input)), result)) + return result + + +class _ReplayCtx(_InlineWorkflowContext): + """A replay: an activity must be scheduled with the recorded input.""" + + is_replaying = True + + def __init__(self, runner: DaprWorkflowGraphRunner, recorded: Recorded): + super().__init__(runner) + self._recorded = list(recorded) + self.mismatches: List[Tuple[Any, Any]] = [] + + def call_activity(self, activity: Any, *, input: Any, retry_policy: Any = None): + want_input, result = self._recorded.pop(0) + got = json.loads(json.dumps(input)) + if got != want_input: + self.mismatches.append((want_input, got)) + return result + + +def _drive(ctx: Any, input_data: Dict[str, Any]) -> Dict[str, Any]: + with mock.patch("diagrid.agent.langgraph.workflow.when_all", side_effect=list): + workflow = agent_workflow(ctx, dict(input_data)) + result = None + try: + while True: + result = workflow.send(result) + except StopIteration as stop: + return stop.value # type: ignore[no-any-return] + + +class TestReplay(_RunnerTestCase): + def _runner(self) -> DaprWorkflowGraphRunner: + def echo(state: MessagesState) -> dict: + # returns the messages it was handed: add_messages dedupes by id + return {"messages": state["messages"]} + + graph = StateGraph(MessagesState) + graph.add_node("echo", echo) + graph.add_edge(START, "echo") + graph.add_edge("echo", END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="replay") + set_default_graph_config(runner.graph_config, max_steps=10) + return runner + + def test_a_replay_schedules_the_same_activity_inputs(self): + runner = self._runner() + first = _RecordingCtx(runner) + out = _drive(first, {"task": "hello"}) + replay = _ReplayCtx(runner, first.recorded) + replayed = _drive(replay, {"task": "hello"}) + self.assertEqual(replay.mismatches, []) + self.assertEqual(replayed, out) + + def test_the_message_is_not_duplicated_by_a_replay(self): + runner = self._runner() + first = _RecordingCtx(runner) + _drive(first, {"task": "hello"}) + replayed = _drive(_ReplayCtx(runner, first.recorded), {"task": "hello"}) + contents = [m["content"] for m in replayed["output"]["messages"]] + self.assertEqual(contents, ["hello"]) + + def test_two_instances_of_one_input_get_ids_of_their_own(self): + runner = self._runner() + + def ids(instance_id: str) -> List[str]: + ctx = _RecordingCtx(runner) + ctx.instance_id = instance_id + out = _drive(ctx, {"task": "hello"}) + return [m["id"] for m in out["output"]["messages"]] + + self.assertNotEqual(ids("wf-one"), ids("wf-two")) + self.assertEqual(ids("wf-one"), ids("wf-one")) diff --git a/tests/agent/langgraph/test_workflow_router_per_task.py b/tests/agent/langgraph/test_workflow_router_per_task.py new file mode 100644 index 00000000..04d2185a --- /dev/null +++ b/tests/agent/langgraph/test_workflow_router_per_task.py @@ -0,0 +1,86 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A conditional edge runs once per task, on the state with only that task's writes.""" + +import itertools +import operator +from typing import Any, List + +from langchain_core.messages import AIMessageChunk +from langgraph.graph import END, START, StateGraph +from langgraph.types import Command, Send +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .test_runner import _clear_dapr_registration, _run, _RunnerTestCase +from .golden_harness import _both, _Golden + + +class _Log(TypedDict, total=False): + log: Annotated[list, operator.add] + + +def _native_and_ours(graph: StateGraph, graph_input: dict, name: str): + _clear_dapr_registration() + compiled = graph.compile() + native = compiled.invoke(graph_input) + out = _run(DaprWorkflowGraphRunner(graph=compiled, name=name), graph_input) + return native, out + + +_seen: List[Any] = [] + + +class TestRouterPerTask(_RunnerTestCase): + def setUp(self): + super().setUp() + _seen.clear() + + def _routers_saw(self, graph: StateGraph, name: str): + """What a router saw natively and in the runner, and the two outputs.""" + _clear_dapr_registration() + compiled = graph.compile() + _seen.clear() + native = compiled.invoke({"log": []}) + native_seen = sorted(_seen) + _seen.clear() + out = _run(DaprWorkflowGraphRunner(graph=compiled, name=name), {"log": []}) + self.assertEqual(out.status, "completed", out.error) + return native_seen, sorted(_seen), native, out.output + + def test_a_router_sees_only_its_own_tasks_writes(self): + def router(state: _Log) -> str: + _seen.append(list(state["log"])) + return "x" + + graph = StateGraph(_Log) + graph.add_node("a", lambda s: {"log": ["a"]}) + graph.add_node("b", lambda s: {"log": ["b", "b"]}) + graph.add_node("x", lambda s: {"log": ["x"]}) + graph.add_edge(START, "a") + graph.add_edge(START, "b") + graph.add_conditional_edges("a", router, ["x"]) + graph.add_edge("b", END) + graph.add_edge("x", END) + native_seen, seen, native, out = self._routers_saw(graph, "router-parallel") + self.assertEqual(native_seen, [["a"]]) + self.assertEqual(seen, native_seen) + self.assertEqual(out["log"], native["log"]) + + def test_a_router_runs_once_per_send_task(self): + def router(state: _Log) -> str: + _seen.append(list(state["log"])) + return END + + graph = StateGraph(_Log) + graph.add_node( + "fan", lambda s: Command(goto=[Send("w", {"i": i}) for i in (1, 2, 3)]) + ) + graph.add_node("w", lambda arg: {"log": [f"w{arg['i']}"]}) + graph.add_edge(START, "fan") + graph.add_conditional_edges("w", router, [END]) + native_seen, seen, _, _ = self._routers_saw(graph, "router-send") + self.assertEqual(native_seen, [["w1"], ["w2"], ["w3"]]) + self.assertEqual(seen, native_seen) diff --git a/tests/agent/langgraph/test_workflow_send_numbering.py b/tests/agent/langgraph/test_workflow_send_numbering.py new file mode 100644 index 00000000..46934244 --- /dev/null +++ b/tests/agent/langgraph/test_workflow_send_numbering.py @@ -0,0 +1,67 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``Send`` tasks are numbered over the whole step, in the order LangGraph uses.""" + +import itertools +import operator +from typing import Any, List + +from langchain_core.messages import AIMessageChunk +from langgraph.graph import END, START, StateGraph +from langgraph.types import Command, Send +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .test_runner import _clear_dapr_registration, _run, _RunnerTestCase +from .golden_harness import _both, _Golden + + +class _Log(TypedDict, total=False): + log: Annotated[list, operator.add] + + +def _native_and_ours(graph: StateGraph, graph_input: dict, name: str): + _clear_dapr_registration() + compiled = graph.compile() + native = compiled.invoke(graph_input) + out = _run(DaprWorkflowGraphRunner(graph=compiled, name=name), graph_input) + return native, out + + +class TestSendNumbering(_Golden): + async def test_two_sending_sources_number_their_tasks_over_the_step(self): + from .test_streaming import _StreamingModel + + model = _StreamingModel() + + def work(arg: dict) -> dict: + model.invoke("hi") + return {"log": [arg["i"]]} + + def sends(prefix: str) -> Any: + return lambda state: [Send("work", {"i": f"{prefix}{k}"}) for k in (1, 2)] + + graph = StateGraph(_Log) + graph.add_node("f1", lambda s: {}) + graph.add_node("f2", lambda s: {}) + graph.add_node("work", work) + graph.add_edge(START, "f1") + graph.add_edge(START, "f2") + graph.add_conditional_edges("f1", sends("a"), ["work"]) + graph.add_conditional_edges("f2", sends("b"), ["work"]) + graph.add_edge("work", END) + native, ours = await _both(graph.compile(), "numbering-paths", {"log": []}) + + def paths(items: List) -> List[Any]: + return sorted( + { + tuple(md["langgraph_path"]) + for m, (c, md) in [i for i in items if i[0] == "messages"] + if isinstance(c, AIMessageChunk) + } + ) + + self.assertEqual(paths(native), [("__pregel_push", i, False) for i in range(4)]) + self.assertEqual(paths(ours), paths(native)) diff --git a/tests/agent/langgraph/test_workflow_state_shapes.py b/tests/agent/langgraph/test_workflow_state_shapes.py new file mode 100644 index 00000000..29242c9f --- /dev/null +++ b/tests/agent/langgraph/test_workflow_state_shapes.py @@ -0,0 +1,100 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A node and a router get the state as LangGraph shapes it for them.""" + +from dataclasses import dataclass +from typing import Any, List + +from langgraph.graph import END, START, StateGraph +from pydantic import BaseModel +from typing_extensions import TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .test_runner import _clear_dapr_registration, _run, _RunnerTestCase + + +class _Pyd(BaseModel): + count: int = 0 + seen: str = "" + + +@dataclass +class _Plain: + count: int = 0 + seen: str = "" + + +class _Open(TypedDict, total=False): + log: List[str] + secret: int + seen: str + + +class _Priv(TypedDict): + secret: int + + +class TestStateShapes(_RunnerTestCase): + def _both(self, graph: StateGraph, graph_input: dict): + _clear_dapr_registration() + compiled = graph.compile() + native = compiled.invoke(graph_input) + out = _run(DaprWorkflowGraphRunner(graph=compiled, name="shapes"), graph_input) + self.assertEqual(out.status, "completed", out.error) + return native, out + + def _schema_graph(self, schema: Any) -> StateGraph: + def a(state: Any) -> dict: + return {"count": state.count + 1, "seen": type(state).__name__} + + def route(state: Any) -> str: + return "b" if state.count > 0 else END + + graph = StateGraph(schema) + graph.add_node("a", a) + graph.add_node("b", lambda state: {"seen": state.seen + f":{state.count}"}) + graph.add_edge(START, "a") + graph.add_conditional_edges("a", route, ["b", END]) + graph.add_edge("b", END) + return graph + + def test_a_pydantic_state_is_an_instance_for_a_node_and_a_router(self): + native, out = self._both(self._schema_graph(_Pyd), {"count": 4}) + self.assertEqual(out.output["count"], native["count"]) + self.assertEqual(out.output["seen"], native["seen"]) + self.assertEqual(out.output["seen"], "_Pyd:5") + + def test_a_dataclass_state_is_an_instance_for_a_node_and_a_router(self): + native, out = self._both(self._schema_graph(_Plain), {"count": 4}) + self.assertEqual(out.output["seen"], native["seen"]) + self.assertEqual(out.output["seen"], "_Plain:5") + + def test_a_node_with_an_input_schema_sees_only_its_channels(self): + def b(state: Any) -> dict: + return {"seen": ",".join(sorted(state))} + + graph = StateGraph(_Open) + graph.add_node("a", lambda s: {"log": ["a"], "secret": 1}) + graph.add_node("b", b, input_schema=_Priv) + graph.add_edge(START, "a") + graph.add_edge("a", "b") + graph.add_edge("b", END) + native, out = self._both(graph, {}) + self.assertEqual(native["seen"], "secret") + self.assertEqual(out.output["seen"], "secret") + + def test_a_router_sees_the_input_schema_of_its_source_node(self): + def route(state: _Priv) -> str: + return "b" if sorted(state) == ["secret"] else END + + graph = StateGraph(_Open) + graph.add_node("a", lambda s: {"log": ["a"], "secret": 1}, input_schema=_Priv) + graph.add_node("b", lambda s: {"seen": "routed"}) + graph.add_edge(START, "a") + graph.add_conditional_edges("a", route, ["b", END]) + graph.add_edge("b", END) + native, out = self._both(graph, {}) + self.assertEqual(native["seen"], "routed") + self.assertEqual(out.output.get("seen"), "routed") diff --git a/tests/agent/langgraph/test_workflow_step_order_patch.py b/tests/agent/langgraph/test_workflow_step_order_patch.py new file mode 100644 index 00000000..073985ff --- /dev/null +++ b/tests/agent/langgraph/test_workflow_step_order_patch.py @@ -0,0 +1,95 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""An instance started before the step-order change replays as it was scheduled. + +Dapr replays the orchestrator against the recorded history and fails a run whose +code schedules a different activity at a given point. The workflow used to run a +step's nodes in the order its edges were found and to end the run as soon as END +was pending; it now runs them sorted by name (LangGraph's task order) and lets +the other branches of a step finish. An instance that began under the old code +must keep the old order, so the change sits behind ``ctx.is_patched``. +""" + +from typing import Any, List + +from langgraph.graph import END, START, StateGraph + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.workflow import ( + NODE_ACTIVITY_NAMES_PATCH, + STEP_ORDER_PATCH, +) + +from .golden_harness import _Log +from .test_runner import _InlineWorkflowContext, _run, _RunnerTestCase + + +def _graph() -> Any: + graph = StateGraph(_Log) + for name in ("x", "a", "b"): + graph.add_node(name, lambda state, name=name: {"log": [name]}) + graph.add_edge(START, "x") + # a sorts before b; the test lists b's edge first (see _scheduled) + graph.add_edge("x", "b") + graph.add_edge("x", "a") + graph.add_edge("a", END) + graph.add_edge("b", END) + return graph.compile() + + +class _Ctx(_InlineWorkflowContext): + """Answers each patch by name, as an instance of a given age would.""" + + def __init__(self, runner: Any, patches: List[str]) -> None: + super().__init__(runner) + self._patches = patches + + def is_patched(self, patch_name: str) -> bool: + return patch_name in self._patches + + +class TestStepOrderPatch(_RunnerTestCase): + def _scheduled(self, graph: Any, name: str, patches: List[str]) -> List[str]: + runner = DaprWorkflowGraphRunner(graph=graph, name=name) + # The edges of an in-flight instance are in its recorded input, in the + # order its runner found them (a set's order); fix that order here. + runner.graph_config.edges.sort(key=lambda e: (e.source, e.target), reverse=True) + ctx = _Ctx(runner, patches) + out = _run(runner, {"log": []}, ctx) + self.assertEqual(out.status, "completed", out.error) + return ctx.scheduled + + def test_a_new_instance_runs_a_steps_nodes_sorted_by_name(self): + scheduled = self._scheduled( + _graph(), "order-new", [NODE_ACTIVITY_NAMES_PATCH, STEP_ORDER_PATCH] + ) + self.assertEqual(scheduled, ["x", "a", "b"]) + + def test_an_instance_from_before_the_change_keeps_the_order_it_found(self): + scheduled = self._scheduled(_graph(), "order-old", [NODE_ACTIVITY_NAMES_PATCH]) + self.assertEqual(scheduled, ["x", "b", "a"]) + + def _end_beside_a(self) -> Any: + graph = StateGraph(_Log) + for name in ("x", "a"): + graph.add_node(name, lambda state, name=name: {"log": [name]}) + graph.add_edge(START, "x") + graph.add_conditional_edges("x", lambda s: [END, "a"], ["a", END]) + graph.add_edge("a", END) + return graph.compile() + + def test_an_instance_from_before_the_change_still_ends_at_end(self): + # END and another node pending in one step: the old code ended the run + scheduled = self._scheduled( + self._end_beside_a(), "end-old", [NODE_ACTIVITY_NAMES_PATCH] + ) + self.assertEqual(scheduled, ["x", "evaluate_condition_activity"]) + + def test_a_new_instance_runs_the_other_branch_of_a_step_that_reaches_end(self): + scheduled = self._scheduled( + self._end_beside_a(), + "end-new", + [NODE_ACTIVITY_NAMES_PATCH, STEP_ORDER_PATCH], + ) + self.assertEqual(scheduled, ["x", "evaluate_condition_activity", "a"]) diff --git a/tests/agent/langgraph/test_workflow_write_order.py b/tests/agent/langgraph/test_workflow_write_order.py new file mode 100644 index 00000000..e31831af --- /dev/null +++ b/tests/agent/langgraph/test_workflow_write_order.py @@ -0,0 +1,77 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Parallel nodes apply their writes in LangGraph's task order, not edge order.""" + +import itertools +import operator +from typing import Any, List + +from langchain_core.messages import AIMessageChunk +from langgraph.graph import END, START, StateGraph +from langgraph.types import Command, Send +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from .test_runner import _clear_dapr_registration, _run, _RunnerTestCase +from .golden_harness import _both, _Golden + + +class _Log(TypedDict, total=False): + log: Annotated[list, operator.add] + + +def _native_and_ours(graph: StateGraph, graph_input: dict, name: str): + _clear_dapr_registration() + compiled = graph.compile() + native = compiled.invoke(graph_input) + out = _run(DaprWorkflowGraphRunner(graph=compiled, name=name), graph_input) + return native, out + + +class TestWriteOrder(_RunnerTestCase): + def _fan_out(self) -> StateGraph: + graph = StateGraph(_Log) + for name in ("start", "zeta", "alpha", "mid"): + graph.add_node(name, lambda s, name=name: {"log": [name]}) + graph.add_edge(START, "start") + for name in ("zeta", "alpha", "mid"): + graph.add_edge("start", name) + return graph + + def test_parallel_nodes_apply_in_name_order(self): + native, out = _native_and_ours(self._fan_out(), {"log": []}, "order") + self.assertEqual(native["log"], ["start", "alpha", "mid", "zeta"]) + self.assertEqual(out.output["log"], native["log"]) + + def test_the_order_of_the_edges_does_not_change_it(self): + # the edges come from a set: their order differs between processes + for permutation in itertools.permutations(range(3)): + with self.subTest(permutation=permutation): + _clear_dapr_registration() + compiled = self._fan_out().compile() + runner = DaprWorkflowGraphRunner(graph=compiled, name="order-perm") + direct = [e for e in runner.graph_config.edges if e.source == "start"] + others = [e for e in runner.graph_config.edges if e.source != "start"] + runner.graph_config.edges = [ + *others, + *(direct[i] for i in permutation), + ] + out = _run(runner, {"log": []}) + self.assertEqual(out.output["log"], ["start", "alpha", "mid", "zeta"]) + + def test_send_tasks_apply_after_the_pull_tasks_in_index_order(self): + def fan(state: _Log) -> Command: + return Command(goto=[Send("w", {"i": i}) for i in (3, 1, 2)]) + + graph = StateGraph(_Log) + graph.add_node("fan", fan) + graph.add_node("w", lambda arg: {"log": [f"w{arg['i']}"]}) + graph.add_node("z", lambda s: {"log": ["z"]}) + graph.add_edge(START, "fan") + graph.add_edge("fan", "z") + graph.add_edge("w", END) + native, out = _native_and_ours(graph, {"log": []}, "order-send") + self.assertEqual(native["log"], ["z", "w3", "w1", "w2"]) + self.assertEqual(out.output["log"], native["log"]) From bde4a7736568b5f3f15d01af64136cd6f486b59d Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 00:28:21 +0100 Subject: [PATCH 13/73] fix(langgraph): only turn input into messages on add_messages channels The workflow input stored every value of a channel named "messages" as message dicts, even when the channel has no add_messages reducer. A plain `messages: list[str]` state then came back with its input string as a HumanMessage dict, unlike native LangGraph, and the e2e test test_langgraph_pure_graph_execution failed. Decide by the channel's reducer alone, as node writes already do. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/workflow.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index aad60e93..5a8aaab8 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -1668,7 +1668,7 @@ def _serialize_input( return { channel: ( _serialize_messages(value, functools.partial(message_id, channel)) - if channel == "messages" or _is_messages_channel(channel) + if _is_messages_channel(channel) else _store_value(value) ) for channel, value in input_data.items() From e0a8807f7ade5d38f4385168184ae82c1dc952c7 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 00:37:40 +0100 Subject: [PATCH 14/73] test(langgraph): compare Send-router tokens per task, not by arrival order Native astream runs the three Send tasks concurrently, so which task's tokens get the first normalised message id depends on thread timing. Name each message id by its task's langgraph_path before comparing. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Casper Nielsen --- .../langgraph/test_streaming_golden_state.py | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/tests/agent/langgraph/test_streaming_golden_state.py b/tests/agent/langgraph/test_streaming_golden_state.py index 56e848ad..3fff6760 100644 --- a/tests/agent/langgraph/test_streaming_golden_state.py +++ b/tests/agent/langgraph/test_streaming_golden_state.py @@ -25,7 +25,6 @@ from .golden_harness import ( ADD_INPUT, _both, - _canonical, _Golden, _Log, _Out, @@ -568,11 +567,28 @@ def _tasks(items: List) -> List[str]: ) +def _canonical_by_task(items: List) -> List[str]: + """``_canonical`` with each token's message id named by its task's path. + + Native runs the Send tasks at once, so which task's tokens get the first + message id depends on the order they happened to run in. + """ + out = [] + for mode, payload in _wire(items): + if mode == "messages": + chunk, md = payload + chunk = {**chunk, "kwargs": dict(chunk["kwargs"])} + chunk["kwargs"]["id"] = json.dumps(md["langgraph_path"], default=str) + payload = [chunk, md] + out.append(json.dumps((mode, payload), sort_keys=True, default=str)) + return sorted(out) + + class TestRouterOfSendTasks(_Golden): async def test_each_router_streams_as_its_own_task_without_a_reset(self): native, ours = await _both(_send_router_graph(), "send-router", {"out": []}) self.assertNotIn("node_reset", [m for m, _ in ours]) - self.assertEqual(_canonical(ours), _canonical(native)) + self.assertEqual(_canonical_by_task(ours), _canonical_by_task(native)) async def test_a_pull_task_and_send_tasks_of_one_node(self): native, ours = await _both( From a3ead2a98b8591fa66678151a5c68381bad750cf Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 11:24:19 +0100 Subject: [PATCH 15/73] test(langgraph): expect a node's routers to run inside its activity The router golden test now compares the stream chunk by chunk with native astream: a router's tokens and custom events come before its node's updates chunk. New tests cover an instance from before the change (it replays the separate condition activity), a router that raises (it falls back to that activity, the node runs once and the consumer gets a branch node_reset), a parallel step with two routers, a Send task's router and a path_map miss. Signed-off-by: Casper Nielsen --- .../agent/langgraph/test_streaming_golden.py | 6 +- .../langgraph/test_workflow_route_in_node.py | 260 ++++++++++++++++++ 2 files changed, 263 insertions(+), 3 deletions(-) create mode 100644 tests/agent/langgraph/test_workflow_route_in_node.py diff --git a/tests/agent/langgraph/test_streaming_golden.py b/tests/agent/langgraph/test_streaming_golden.py index 421d7f30..27eacdcb 100644 --- a/tests/agent/langgraph/test_streaming_golden.py +++ b/tests/agent/langgraph/test_streaming_golden.py @@ -274,15 +274,15 @@ async def test_its_tokens_and_custom_event_reach_the_stream(self): ] self.assertTrue(router_tokens, "the router's tokens were lost") self.assertIn(("custom", "routing"), ours) - # a router's chunks are the source node's in native LangGraph - self.assertEqual(_canonical(ours), _canonical(native)) + # a router runs inside its node's task, before the node's updates chunk + self._assert_same_sequence(native, ours) async def test_an_async_router_streams_too(self): native, ours = await _both( _router_graph(async_router=True), "router-async", {"log": []} ) self.assertIn(("custom", "routing"), ours) - self.assertEqual(_canonical(ours), _canonical(native)) + self._assert_same_sequence(native, ours) async def test_it_does_not_look_like_a_missing_stream(self): # the router's chunks are not a node's updates: no stream_unavailable diff --git a/tests/agent/langgraph/test_workflow_route_in_node.py b/tests/agent/langgraph/test_workflow_route_in_node.py new file mode 100644 index 00000000..7870b707 --- /dev/null +++ b/tests/agent/langgraph/test_workflow_route_in_node.py @@ -0,0 +1,260 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A node's conditional edges run inside the node's activity. + +LangGraph runs a router as one of its node's writers, inside the node's task, +so the router's chunks come before the node's ``updates`` chunk. The node +activity now does the same, behind ``ROUTE_IN_NODE_PATCH``: an instance started +before it replays the separate condition activity it scheduled. A router that +raises inside the node activity falls back to that separate activity, so the +node itself never runs twice. +""" + +import operator +from typing import Any, Dict, List, Tuple + +from langchain_core.messages import AIMessageChunk +from langgraph.config import get_stream_writer +from langgraph.graph import END, START, StateGraph +from langgraph.types import Command, Send +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.workflow import ( + CONDITION_ACTIVITY, + NODE_ACTIVITY_NAMES_PATCH, + ROUTE_IN_NODE_PATCH, + STEP_ORDER_PATCH, +) + +from .golden_harness import _both, _canonical, _FakeDaprTest, _runner, _wire +from .streaming_helpers import _collect, _StreamingModel +from .test_runner import _InlineWorkflowContext, _run, _RunnerTestCase + +ALL_PATCHES = [NODE_ACTIVITY_NAMES_PATCH, STEP_ORDER_PATCH, ROUTE_IN_NODE_PATCH] +BEFORE_ROUTE_IN_NODE = [NODE_ACTIVITY_NAMES_PATCH, STEP_ORDER_PATCH] + + +class _Log(TypedDict, total=False): + log: Annotated[list, operator.add] + + +class _Ctx(_InlineWorkflowContext): + """Answers each patch by name, as an instance of a given age would.""" + + def __init__(self, runner: Any, patches: List[str]) -> None: + super().__init__(runner) + self._patches = patches + + def is_patched(self, patch_name: str) -> bool: + return patch_name in self._patches + + +def _routed_graph(calls: Dict[str, int], raise_once: bool = False) -> Any: + """START -> a -(router)-> b -> END, counting how often a and the router run.""" + + def a(state: _Log) -> dict: + calls["a"] = calls.get("a", 0) + 1 + return {"log": ["a"]} + + def router(state: _Log) -> str: + calls["router"] = calls.get("router", 0) + 1 + get_stream_writer()("routing") + if raise_once and calls["router"] == 1: + raise RuntimeError("router hiccup") + return "b" + + graph = StateGraph(_Log) + graph.add_node("a", a) + graph.add_node("b", lambda state: {"log": ["b"]}) + graph.add_edge(START, "a") + graph.add_conditional_edges("a", router, ["b"]) + graph.add_edge("b", END) + return graph.compile() + + +class TestTheSchedule(_RunnerTestCase): + def _scheduled(self, compiled: Any, name: str, patches: List[str]) -> List[str]: + runner = DaprWorkflowGraphRunner(graph=compiled, name=name) + ctx = _Ctx(runner, patches) + out = _run(runner, {"log": []}, ctx) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["log"], ["a", "b"]) + return ctx.scheduled + + def test_a_new_instance_schedules_no_condition_activity(self): + scheduled = self._scheduled(_routed_graph({}), "route-new", ALL_PATCHES) + self.assertEqual(scheduled, ["a", "b"]) + + def test_an_instance_from_before_the_patch_replays_the_condition_activity(self): + scheduled = self._scheduled( + _routed_graph({}), "route-old", BEFORE_ROUTE_IN_NODE + ) + self.assertEqual(scheduled, ["a", CONDITION_ACTIVITY, "b"]) + + +class TestARouterThatRaises(_RunnerTestCase): + def test_it_falls_back_to_the_condition_activity_and_the_node_runs_once(self): + calls: Dict[str, int] = {} + compiled = _routed_graph(calls, raise_once=True) + runner = DaprWorkflowGraphRunner(graph=compiled, name="route-raise") + ctx = _Ctx(runner, ALL_PATCHES) + out = _run(runner, {"log": []}, ctx) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(out.output["log"], ["a", "b"]) + self.assertEqual(ctx.scheduled, ["a", CONDITION_ACTIVITY, "b"]) + self.assertEqual(calls, {"a": 1, "router": 2}) + + +class TestARouterThatRaisesStreams(_FakeDaprTest): + async def test_the_consumer_gets_a_branch_reset_for_the_router_only(self): + calls: Dict[str, int] = {} + runner = _runner(_routed_graph(calls, raise_once=True), "route-raise-stream") + ours = await _collect( + runner.astream( + {"log": []}, + workflow_id="wf-route-raise-stream", + stream_mode=["custom", "updates"], + poll_interval=0.01, + ) + ) + resets = [data for kind, data in ours if kind == "node_reset"] + self.assertEqual(len(resets), 1) + self.assertEqual(resets[0]["node"], "a") + self.assertEqual(resets[0]["step"], 1) + self.assertIn("router", resets[0]["branch"]) + self.assertEqual( + [i for i in ours if i[0] != "node_reset"], + [ + ("custom", "routing"), + ("updates", {"a": {"log": ["a"]}}), + ("custom", "routing"), + ("updates", {"b": {"log": ["b"]}}), + ], + ) + self.assertEqual(calls, {"a": 1, "router": 2}) + + +def _parallel_routers_graph() -> Any: + def ra(state: _Log) -> str: + get_stream_writer()("ra") + return "x" + + def rb(state: _Log) -> str: + get_stream_writer()("rb") + return "y" + + graph = StateGraph(_Log) + for name in ("a", "b", "x", "y"): + graph.add_node(name, lambda state, name=name: {"log": [name]}) + graph.add_edge(START, "a") + graph.add_edge(START, "b") + graph.add_conditional_edges("a", ra, ["x"]) + graph.add_conditional_edges("b", rb, ["y"]) + graph.add_edge("x", END) + graph.add_edge("y", END) + return graph.compile() + + +def _before_its_update(items: List[Tuple[str, Any]], custom: str, node: str) -> bool: + """Whether the router's ``custom`` event comes before its node's ``updates``.""" + modes = [(m, p if m == "custom" else next(iter(p))) for m, p in items] + return modes.index(("custom", custom)) < modes.index(("updates", node)) + + +class TestParallelStepWithTwoRouters(_FakeDaprTest): + async def test_each_router_streams_before_its_nodes_update_like_native(self): + native, ours = await _both( + _parallel_routers_graph(), "two-routers", {"log": []} + ) + self.assertEqual(_canonical(ours), _canonical(native)) + self.assertNotIn("node_reset", [m for m, _ in ours]) + for custom, node in (("ra", "a"), ("rb", "b")): + with self.subTest(router=custom): + self.assertTrue(_before_its_update(native, custom, node)) + self.assertTrue(_before_its_update(ours, custom, node)) + + def test_neither_router_needs_an_activity_of_its_own(self): + compiled = _parallel_routers_graph() + runner = DaprWorkflowGraphRunner(graph=compiled, name="two-routers-run") + ctx = _Ctx(runner, ALL_PATCHES) + out = _run(runner, {"log": []}, ctx) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(sorted(out.output["log"]), sorted(compiled.invoke({})["log"])) + self.assertNotIn(CONDITION_ACTIVITY, ctx.scheduled) + + +def _send_router_graph() -> Any: + model = _StreamingModel() + + def router(state: _Log) -> str: + get_stream_writer()(f"route-{state['log'][-1]}") + model.invoke("which way?") + return END + + graph = StateGraph(_Log) + graph.add_node( + "fan", lambda state: Command(goto=[Send("w", {"i": i}) for i in (1, 2)]) + ) + graph.add_node("w", lambda arg: {"log": [f"w{arg['i']}"]}) + graph.add_edge(START, "fan") + graph.add_conditional_edges("w", router, [END]) + return graph.compile() + + +class TestASendTasksRouter(_FakeDaprTest): + async def test_it_streams_as_its_task_before_the_tasks_update(self): + native, ours = await _both(_send_router_graph(), "send-router", {"log": []}) + + def paths(items: List) -> List[Any]: + return sorted( + (tuple(md["langgraph_path"]), md["langgraph_node"]) + for m, (c, md) in [i for i in items if i[0] == "messages"] + if isinstance(c, AIMessageChunk) + ) + + self.assertEqual(paths(ours), paths(native)) + for index in (1, 2): + with self.subTest(task=index): + modes = [ + (m, p if m == "custom" else p.get("w")) for m, p in _wire(ours) + ] + self.assertLess( + modes.index(("custom", f"route-w{index}")), + modes.index(("updates", {"log": [f"w{index}"]})), + ) + self.assertNotIn("node_reset", [m for m, _ in ours]) + + def test_no_condition_activity_is_scheduled_for_the_send_tasks(self): + compiled = _send_router_graph() + runner = DaprWorkflowGraphRunner(graph=compiled, name="send-router-run") + ctx = _Ctx(runner, ALL_PATCHES) + out = _run(runner, {"log": []}, ctx) + self.assertEqual(out.status, "completed", out.error) + self.assertEqual(sorted(out.output["log"]), ["w1", "w2"]) + self.assertEqual(ctx.scheduled, ["fan", "w", "w"]) + + +class TestAPathMapMiss(_RunnerTestCase): + def test_it_fails_the_run_without_running_the_router_again(self): + calls: List[str] = [] + + def router(state: _Log) -> str: + calls.append("router") + return "nowhere" + + graph = StateGraph(_Log) + graph.add_node("a", lambda state: {"log": ["a"]}) + graph.add_node("b", lambda state: {"log": ["b"]}) + graph.add_edge(START, "a") + graph.add_conditional_edges("a", router, {"x": "b"}) + graph.add_edge("b", END) + runner = DaprWorkflowGraphRunner(graph=graph.compile(), name="route-miss") + ctx = _Ctx(runner, ALL_PATCHES) + out = _run(runner, {"log": []}, ctx) + self.assertEqual(out.status, "error") + self.assertIn("Condition evaluation failed", out.error or "") + self.assertIn("nowhere", out.error or "") + self.assertEqual(ctx.scheduled, ["a"]) + self.assertEqual(calls, ["router"]) From bcec2fc5d752b891dca10c5403d721c269c386b2 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 11:27:56 +0100 Subject: [PATCH 16/73] feat(langgraph): run a node's routers inside the node's activity LangGraph runs a conditional edge's function as a writer of its source node, inside the node's task, so its tokens and custom events come before the node's updates chunk. The runner ran it in a separate activity after every node of the step had finished, so they came after that chunk, and in a parallel step after the sibling nodes too. Behind a new workflow patch, the workflow now hands a node's activity the node's conditional edges. The activity evaluates them on the state the step started from plus the task's own writes, then publishes the updates chunk, and reports where they lead. A router that raises is not retried there: the activity says its routes are not done and the workflow evaluates them in the condition activity as before, so the node does not run again and the consumer gets the existing node_reset with branch. A path_map miss or a reducer that raises on the task's writes fails the run, as it did. Instances started before the patch replay their recorded schedule with the condition activity. A conditional hop also saves one activity and one stored copy of the state. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/models.py | 30 +++++ diagrid/agent/langgraph/node_routes.py | 124 ++++++++++++++++++ diagrid/agent/langgraph/workflow.py | 66 +++++++++- .../langgraph/test_workflow_route_in_node.py | 4 +- 4 files changed, 217 insertions(+), 7 deletions(-) create mode 100644 diagrid/agent/langgraph/node_routes.py diff --git a/diagrid/agent/langgraph/models.py b/diagrid/agent/langgraph/models.py index 67301c35..ed5d3de6 100644 --- a/diagrid/agent/langgraph/models.py +++ b/diagrid/agent/langgraph/models.py @@ -247,6 +247,10 @@ class ExecuteNodeInput: recursion_limit: The run's step limit as a LangGraph ``recursion_limit`` (what ``RemainingSteps`` and ``IsLastStep`` count against), or ``None`` for a workflow that did not send it. + routes: The node's conditional edges, each ``{"condition", "path_map"}``, + for the activity to evaluate once the node returns, as LangGraph + runs a router inside its node's task. ``None`` when the workflow + evaluates them itself (an instance from before routing moved here). """ node_name: str @@ -256,6 +260,7 @@ class ExecuteNodeInput: step: Optional[int] = None send: Optional[Dict[str, Any]] = None recursion_limit: Optional[int] = None + routes: Optional[List[Dict[str, Any]]] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -270,6 +275,8 @@ def to_dict(self) -> Dict[str, Any]: data["send"] = self.send if self.recursion_limit is not None: data["recursion_limit"] = self.recursion_limit + if self.routes is not None: + data["routes"] = self.routes return data @classmethod @@ -282,6 +289,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeInput": step=data.get("step"), send=data.get("send"), recursion_limit=data.get("recursion_limit"), + routes=data.get("routes"), ) @@ -297,6 +305,13 @@ class ExecuteNodeOutput: in addition to the nodes its edges lead to sends: The ``Send`` objects of that ``goto``, each ``{"node", "arg"}``: every one runs its node once, on its argument + routes_done: Whether the activity evaluated the node's conditional + edges (``ExecuteNodeInput.routes``). ``False`` when it was not asked + to or a router raised: the workflow then evaluates them itself. + next_nodes: Where those conditional edges lead, when they were evaluated + route_sends: The ``Send`` tasks those conditional edges returned + route_error: Why routing failed (a ``path_map`` miss, a reducer that + raised on this task's writes): the run fails with it """ node_name: str @@ -304,6 +319,10 @@ class ExecuteNodeOutput: error: Optional[str] = None goto: List[str] = field(default_factory=list) sends: List[Dict[str, Any]] = field(default_factory=list) + routes_done: bool = False + next_nodes: List[str] = field(default_factory=list) + route_sends: List[Dict[str, Any]] = field(default_factory=list) + route_error: Optional[str] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -315,6 +334,13 @@ def to_dict(self) -> Dict[str, Any]: data["goto"] = list(self.goto) if self.sends: data["sends"] = list(self.sends) + if self.routes_done: + data["routes_done"] = True + data["next_nodes"] = list(self.next_nodes) + if self.route_sends: + data["route_sends"] = list(self.route_sends) + if self.route_error: + data["route_error"] = self.route_error return data @classmethod @@ -325,6 +351,10 @@ def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeOutput": error=data.get("error"), goto=list(data.get("goto") or []), sends=list(data.get("sends") or []), + routes_done=bool(data.get("routes_done")), + next_nodes=list(data.get("next_nodes") or []), + route_sends=list(data.get("route_sends") or []), + route_error=data.get("route_error"), ) diff --git a/diagrid/agent/langgraph/node_routes.py b/diagrid/agent/langgraph/node_routes.py new file mode 100644 index 00000000..f1428bd7 --- /dev/null +++ b/diagrid/agent/langgraph/node_routes.py @@ -0,0 +1,124 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A node's conditional edges, evaluated inside the node's activity. + +LangGraph attaches a router to its source node as one of the node's writers, so +it runs inside the node's task, right after the node returns, and its chunks +come before the node's ``updates`` chunk. The node activity does the same when +the workflow hands it the node's routes (``ExecuteNodeInput.routes``). + +A router reads the state the step started from plus this task's own writes. A +router that raises is not retried here: the activity reports its routes as not +done and the workflow evaluates them in the separate condition activity, so the +node itself does not run again. +""" + +import copy +import logging +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional + +from diagrid.agent.core.workflow.stream import StreamSinkRegistry + +from .models import ( + ChannelState, + EvaluateConditionInput, + ExecuteNodeInput, + NodeWrite, +) + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class RouteOutcome: + """What a node's conditional edges decided, as the activity reports it. + + ``done`` is false when a router raised: the workflow then evaluates the + node's routes itself. ``error`` fails the run (a ``path_map`` miss, a + reducer that raised on this task's writes). + """ + + done: bool + next_nodes: List[str] = field(default_factory=list) + sends: List[Dict[str, Any]] = field(default_factory=list) + error: Optional[str] = None + + def output_fields(self) -> Dict[str, Any]: + """The ``ExecuteNodeOutput`` fields this outcome sets.""" + return { + "routes_done": self.done, + "next_nodes": list(self.next_nodes), + "route_sends": list(self.sends), + "route_error": self.error, + } + + +def _router_state(start: ChannelState, writes: List[NodeWrite]) -> ChannelState: + """The state the step started from with this task's ``writes`` applied.""" + from .workflow import _apply_write + + state = copy.deepcopy(start) + for write in writes: + _apply_write(state, write.channel, write.value) + return state + + +def _route_input( + node_input: ExecuteNodeInput, route: Dict[str, Any], state: ChannelState +) -> EvaluateConditionInput: + """What the condition activity would be given for ``route`` of this task.""" + send = node_input.send + return EvaluateConditionInput( + source_node=node_input.node_name, + condition_name=route["condition"], + channel_state=state, + config=node_input.config, + thread_id=node_input.thread_id, + path_map=route.get("path_map"), + step=node_input.step, + send_slot=None if send is None else send["slot"], + recursion_limit=node_input.recursion_limit, + ) + + +def route_in_node( + ctx: Any, + node_input: ExecuteNodeInput, + writes: List[NodeWrite], + registry: Optional[StreamSinkRegistry], +) -> RouteOutcome: + """Evaluate the node's conditional edges on the state with ``writes`` applied. + + The routers stream as they do in the condition activity: as the source + node, keyed by edge and task, so a later fallback attempt of one reads as + that router's retry, not the node's. + """ + from .workflow import ReducerError, evaluate_condition + + try: + state = _router_state(node_input.channel_state, writes) + except ReducerError as e: + # Raising would make Dapr retry the node; the run fails with it instead. + return RouteOutcome(done=True, error=str(e)) + next_nodes: List[str] = [] + sends: List[Dict[str, Any]] = [] + for route in node_input.routes or []: + cond_input = _route_input(node_input, route, state) + try: + output = evaluate_condition(ctx, cond_input, registry) + except Exception: + logger.warning( + "Router %r of node %r raised inside the node's activity; the " + "workflow evaluates the node's routes in their own activity", + cond_input.condition_name, + node_input.node_name, + exc_info=True, + ) + return RouteOutcome(done=False) + if output.error: + return RouteOutcome(done=True, error=output.error) + next_nodes.extend(output.next_nodes) + sends.extend(output.sends) + return RouteOutcome(done=True, next_nodes=next_nodes, sends=sends) diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 5a8aaab8..cfb32416 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -63,6 +63,7 @@ get_stream_sink, ) +from .node_routes import route_in_node from .streaming import STREAM_RUN_KEY, NodeStreamer, StaticConfig from .values import ( coerce_to_default, @@ -143,6 +144,10 @@ # scheduled its nodes in the order the edges were found, and ended at END, must # replay that way: the patch is what tells the two apart. STEP_ORDER_PATCH = "langgraph-step-order" +# A node's conditional edges run inside the node's activity, as LangGraph runs a +# router inside its node's task. An instance that scheduled a condition activity +# after each node must replay that way: the patch is what tells the two apart. +ROUTE_IN_NODE_PATCH = "langgraph-route-in-node" GENERIC_NODE_ACTIVITY = "execute_node_activity" CONDITION_ACTIVITY = "evaluate_condition_activity" # What LangGraph names the trigger (and path) of a task started by a ``Send``. @@ -507,6 +512,9 @@ class _Run: #: counts against): the runner's own ``max_steps`` lets a run of exactly that #: many steps complete, which is a limit one above it. recursion_limit: Optional[int] = None + #: Whether a node's activity evaluates its conditional edges + #: (see :data:`ROUTE_IN_NODE_PATCH`). + route_in_node: bool = False #: The nodes that ran in each step, reported on the output so a streaming #: consumer can tell which node's chunks never arrived. executed: List[List[str]] = field(default_factory=list) @@ -541,6 +549,7 @@ def _new_run(ctx: DaprWorkflowContext, workflow_input: GraphWorkflowInput) -> _R # patch as absent, and the answer is fixed for the rest of the execution. node_activities_by_name = ctx.is_patched(NODE_ACTIVITY_NAMES_PATCH) step_order = ctx.is_patched(STEP_ORDER_PATCH) + route_in_node = ctx.is_patched(ROUTE_IN_NODE_PATCH) return _Run( ctx=ctx, graph_config=workflow_input.graph_config, @@ -560,6 +569,7 @@ def _new_run(ctx: DaprWorkflowContext, workflow_input: GraphWorkflowInput) -> _R if workflow_input.strict_limit else workflow_input.max_steps + 1 ), + route_in_node=route_in_node, ) @@ -775,13 +785,15 @@ def _state_before_step(run: _Run, tasks: List["_Task"]) -> Optional[ChannelState With one task, the state after its writes is what its routers read, so nothing is kept. With several, a task's routers must not see its siblings' - writes, so the state before the step's writes is kept. + writes, so the state before the step's writes is kept. A task whose + activity evaluated its routers needs nothing. """ if len(tasks) < 2: return None has_router = any( e.condition and e.source == t.node for t in tasks + if not t.output.routes_done for e in run.graph_config.edges ) return copy.deepcopy(run.channel_state) if has_router else None @@ -820,6 +832,7 @@ def _run_nodes( step=step, send=send, recursion_limit=run.recursion_limit, + routes=_node_routes(run, node_name) if run.route_in_node else None, ) activity: Any = execute_node_activity if run.node_activities_by_name: @@ -836,6 +849,16 @@ def _run_nodes( return [ExecuteNodeOutput.from_dict(result) for result in task_results] +def _node_routes(run: _Run, node_name: str) -> Optional[List[Dict[str, Any]]]: + """The conditional edges of ``node_name``, for its activity to evaluate.""" + routes = [ + {"condition": edge.condition, "path_map": edge.path_map} + for edge in run.graph_config.edges + if edge.source == node_name and edge.condition + ] + return routes or None + + def _next_nodes( run: _Run, tasks: List[_Task], @@ -850,7 +873,8 @@ def _next_nodes( evaluated once per task, on the state with only that task's writes (see :func:`_state_for_task`). Tasks are taken in the order LangGraph applies them, and each one's ``goto`` before its conditional edges, so the ``Send`` - tasks come out numbered as LangGraph numbers them. + tasks come out numbered as LangGraph numbers them. A task whose activity + evaluated its conditional edges reports where they lead. """ found = _Frontier() for task in tasks: @@ -862,6 +886,8 @@ def _next_nodes( if not edge.condition: found.add_nodes([edge.target]) continue + if task.output.routes_done: + continue try: state = _state_for_task(run, before, task) except ReducerError as e: @@ -871,6 +897,11 @@ def _next_nodes( ) if error: return found.result(error) + if task.output.routes_done: + if task.output.route_error: + return found.result(task.output.route_error) + found.add_nodes(task.output.next_nodes) + found.sends.extend(task.output.route_sends) # A join fires, once, in the step after the last of its sources ran. ran = {task.node for task in tasks} @@ -993,6 +1024,8 @@ class _NodeCall: streamer: Optional[NodeStreamer] #: Side-channel writes queued via CONFIG_KEY_SEND while the node runs. pending_sends: list + #: Where the node's routers look for the run's stream sink. + registry: Optional[StreamSinkRegistry] = None @property def node_name(self) -> str: @@ -1412,17 +1445,25 @@ def _node_output(call: _NodeCall, result: Any) -> Dict[str, Any]: Converts the result to writes, appends any side-channel writes queued via CONFIG_KEY_SEND (e.g. StateBackend writing to the "files" channel from - sandbox tools), and streams the node's update. + sandbox tools), evaluates the node's conditional edges when the workflow + asked for that, and then streams the node's update, as LangGraph does. """ raw_writes = [*_result_to_raw_writes(result), *call.pending_sends] + writes = _serialize_writes(raw_writes) + routed: Dict[str, Any] = {} + if call.node_input.routes: + routed = route_in_node( + call.ctx, call.node_input, writes, call.registry + ).output_fields() if call.streamer: call.streamer.updates(raw_writes) goto, sends = _result_to_gotos(result) return ExecuteNodeOutput( node_name=call.node_name, - writes=_serialize_writes(raw_writes), + writes=writes, goto=goto, sends=sends, + **routed, ).to_dict() @@ -1460,6 +1501,7 @@ def execute_node_activity( config=config, streamer=_make_streamer(ctx, node_input, config, stream_registry), pending_sends=[], + registry=stream_registry, ) # Under the LangSmith parent trace the runner opened, so LLM calls nest in it. @@ -1569,12 +1611,24 @@ def evaluate_condition_activity( module's). """ cond_input = EvaluateConditionInput.from_dict(input_data) + return evaluate_condition(ctx, cond_input, stream_registry).to_dict() + +def evaluate_condition( + ctx: WorkflowActivityContext, + cond_input: EvaluateConditionInput, + stream_registry: Optional[StreamSinkRegistry], +) -> EvaluateConditionOutput: + """Call a conditional edge's function and say where it routes, or the error. + + What the condition activity does, and what a node activity does for each + of its node's conditional edges. An exception of the function propagates. + """ cond_func = get_registered_condition(cond_input.condition_name) if cond_func is None: return EvaluateConditionOutput( error=f"Condition '{cond_input.condition_name}' not found in registry", - ).to_dict() + ) state: Any = _with_managed( _reconstruct_state(cond_input.channel_state), @@ -1590,7 +1644,7 @@ def evaluate_condition_activity( # each evaluation lands in LangSmith as a separate top-level trace. with _under_parent_trace(cond_input.config): result = _call_condition(ctx, cond_input, cond_func, state, stream_registry) - return _route(cond_input, result).to_dict() + return _route(cond_input, result) def _under_parent_trace(config: Optional[Dict[str, Any]]) -> Any: diff --git a/tests/agent/langgraph/test_workflow_route_in_node.py b/tests/agent/langgraph/test_workflow_route_in_node.py index 7870b707..f43d614b 100644 --- a/tests/agent/langgraph/test_workflow_route_in_node.py +++ b/tests/agent/langgraph/test_workflow_route_in_node.py @@ -218,7 +218,9 @@ def paths(items: List) -> List[Any]: for index in (1, 2): with self.subTest(task=index): modes = [ - (m, p if m == "custom" else p.get("w")) for m, p in _wire(ours) + (m, p if m == "custom" else p.get("w")) + for m, p in _wire(ours) + if m in ("custom", "updates") ] self.assertLess( modes.index(("custom", f"route-w{index}")), From 45519957fe7648b35ad23c83783f9e561b9aa4a6 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 11:28:03 +0100 Subject: [PATCH 17/73] docs(langgraph): drop the router-order limit from the streaming README A conditional edge's function now runs inside its node's activity, so its chunks come before the node's updates chunk, as in LangGraph. The node_reset row says when a router's retry still happens: when it raised inside the node's activity and ran again in an activity of its own. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 8d7806eb..95412695 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -120,7 +120,7 @@ objects (`kind`, `data`): | `kind` | `data` | Meaning | |---|---|---| | `workflow_started` | `{"workflow_id", "thread_id"}` | Always the first event: the ids to use with `terminate_workflow` or `get_workflow_status`. Delivered only to `on_control`, never yielded. | -| `node_reset` | `{"node", "step"}`, plus `"path"` for a `Send` task | A node was retried; drop its partial output. `node` and `step` are the `langgraph_node` and `langgraph_step` of that node's `messages` metadata (`step` is numbered from 1). A task started by a `Send` also carries `path`, the `langgraph_path` of its chunks (`["__pregel_push", index, false]`), which tells apart the tasks of one node in a step. A retry of a conditional edge's function (the function runs in its own activity, after the node's) also carries `branch`, the edge's function name: only what that function sent since the node's `updates` chunk is stale, not the node's own output. | +| `node_reset` | `{"node", "step"}`, plus `"path"` for a `Send` task | A node was retried; drop its partial output. `node` and `step` are the `langgraph_node` and `langgraph_step` of that node's `messages` metadata (`step` is numbered from 1). A task started by a `Send` also carries `path`, the `langgraph_path` of its chunks (`["__pregel_push", index, false]`), which tells apart the tasks of one node in a step. A retry of a conditional edge's function also carries `branch`, the edge's function name. The function runs inside its node's activity, before the node's `updates` chunk, as in LangGraph; if it raises there, it runs again in an activity of its own, after that chunk, and only what the function sent is stale, not the node's own output. | | `stream_unavailable` | `{"workflow_id", "reason", "missing_steps", "missing_nodes"}` | The run finished but a node's chunks never arrived (see the limit below). `missing_nodes` is a list of `{"step", "node"}`, one per node of a step that streamed nothing, even when other nodes of that step did. Steps are numbered from 1, like `langgraph_step`. A `Send` task is named `node#k` there (`k` is its position among the step's `Send` tasks). | | `stream_dropped` | `{"dropped": n}` | The consumer fell behind and `n` token or custom chunks were dropped. `updates` are never dropped. | @@ -223,11 +223,6 @@ they are left alone. was written, as in LangGraph. It must be something that serializer handles. A run's output (the `invoke` result and the final event) is JSON: such a value appears there as its dump (a `set` as a sorted list, a `datetime` as a string). -- **Routers stream after their node's update.** The LLM tokens and - `get_stream_writer()` events of a conditional edge's function are sent as its - source node's (`langgraph_node` and step), as LangGraph does, but the router - runs after the node finished, so they follow that node's `updates` chunk - where LangGraph sends them before it. - **The `config` of `astream`, `invoke` and `run_async` travels as JSON.** `tags`, `metadata`, `configurable` and `recursion_limit` work; `recursion_limit` bounds the run's steps as LangGraph counts them: that many node steps run and From 17e319ed8caac479074ee23aa0ccbff51eabfc12 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 11:31:03 +0100 Subject: [PATCH 18/73] test(langgraph): expect the values, tasks and debug stream modes Golden tests against native astream for values (a sequential graph, values between a step's chunks, a parallel step, a router loop, the final value, a step that writes no output channel, an empty input, a run cut by its step limit), a retried step that does not send its value twice, and values over SSE loaded back with langchain_core.load. Tasks and debug are compared on graphs without a checkpointer, including a router, a parallel step and Send tasks; a failed attempt sends its start but no result. Checkpoints are refused with a ValueError and a 422 that say why. The golden harness takes the stream modes to compare, and the tests that used values as an example of an unsupported mode use a bogus one. Signed-off-by: Casper Nielsen --- tests/agent/langgraph/golden_harness.py | 8 +- tests/agent/langgraph/test_streaming.py | 2 +- .../langgraph/test_streaming_golden_tasks.py | 184 ++++++++++++++ .../langgraph/test_streaming_golden_values.py | 233 ++++++++++++++++++ tests/agent/langgraph/test_streaming_sse.py | 2 +- 5 files changed, 424 insertions(+), 5 deletions(-) create mode 100644 tests/agent/langgraph/test_streaming_golden_tasks.py create mode 100644 tests/agent/langgraph/test_streaming_golden_values.py diff --git a/tests/agent/langgraph/golden_harness.py b/tests/agent/langgraph/golden_harness.py index 243ddf1f..e9be5a0b 100644 --- a/tests/agent/langgraph/golden_harness.py +++ b/tests/agent/langgraph/golden_harness.py @@ -165,7 +165,9 @@ def _stream(self, messages, stop=None, run_manager=None, **kw) -> Iterator: yield gen -async def _both(compiled: Any, name: str, graph_input: Any) -> Tuple[List, List]: +async def _both( + compiled: Any, name: str, graph_input: Any, modes: List[str] = MODES +) -> Tuple[List, List]: native = [ item async for item in compiled.astream( @@ -175,7 +177,7 @@ async def _both(compiled: Any, name: str, graph_input: Any) -> Tuple[List, List] "tags": ["x"], "metadata": {"foo": "bar"}, }, - stream_mode=MODES, + stream_mode=modes, ) ] runner = DaprWorkflowGraphRunner(graph=compiled, name=name) @@ -188,7 +190,7 @@ async def _both(compiled: Any, name: str, graph_input: Any) -> Tuple[List, List] thread_id="t1", config={"tags": ["x"], "metadata": {"foo": "bar"}}, workflow_id=f"wf-{name}", - stream_mode=MODES, + stream_mode=modes, poll_interval=0.01, ) ) diff --git a/tests/agent/langgraph/test_streaming.py b/tests/agent/langgraph/test_streaming.py index d4977229..e74c1ebe 100644 --- a/tests/agent/langgraph/test_streaming.py +++ b/tests/agent/langgraph/test_streaming.py @@ -78,7 +78,7 @@ async def test_single_mode_yields_bare_chunks(self): async def test_unsupported_mode_and_subgraphs(self): runner = self._runner() with self.assertRaises(ValueError): - await _collect(runner.astream(INPUT, stream_mode="values")) + await _collect(runner.astream(INPUT, stream_mode="bogus")) with self.assertRaises(NotImplementedError): await _collect(runner.astream(INPUT, subgraphs=True)) diff --git a/tests/agent/langgraph/test_streaming_golden_tasks.py b/tests/agent/langgraph/test_streaming_golden_tasks.py new file mode 100644 index 00000000..4258b217 --- /dev/null +++ b/tests/agent/langgraph/test_streaming_golden_tasks.py @@ -0,0 +1,184 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``stream_mode="tasks"`` and ``"debug"``, and the refusal of ``"checkpoints"``. + +A node's activity sends a task's start event when it starts the node and its +result next to the node's ``updates`` chunk. ``debug`` wraps the same events +with the step, a timestamp and their type. Without a checkpointer that is all +native ``debug`` holds, which is the only case compared here. +""" + +import asyncio +import unittest +from collections import Counter +from typing import Any, Dict, List, Tuple + +from langgraph.graph import END, START, StateGraph +from langgraph.types import Send + +from diagrid.agent.core.workflow.stream import StreamSinkRegistry +from diagrid.agent.langgraph.workflow import ( + clear_registries, + execute_node_activity, + register_node, +) + +from .golden_harness import ( + _both, + _canonical, + _FakeDaprTest, + _golden_graph, + _Out, +) +from .streaming_helpers import ( + INPUT, + _chat_graph, + _collect, + _Ctx, + _drain, + _payload, + serve_app, +) +from .test_runner import _RunnerTestCase +from .test_streaming_golden import _fan_out_graph, _router_graph + + +def _stable(items: List[Tuple[str, Any]], keep_ids: bool = True) -> List: + """Task ids numbered by first appearance (or dropped), timestamps blanked.""" + ids: Dict[str, str] = {} + + def fix(payload: Dict[str, Any]) -> Dict[str, Any]: + task_id = ids.setdefault(payload["id"], f"task-{len(ids)}") + return {**payload, "id": task_id if keep_ids else ""} + + out: List[Tuple[str, Any]] = [] + for mode, payload in items: + if mode == "tasks": + out.append((mode, fix(payload))) + elif mode == "debug": + debug = {**payload, "timestamp": "", "payload": fix(payload["payload"])} + out.append((mode, debug)) + else: + out.append((mode, payload)) + return out + + +class TestTasksMatchNative(_FakeDaprTest): + async def test_a_sequential_graph(self): + native, ours = await _both(_golden_graph(), "tasks-seq", INPUT, ["tasks"]) + self.assertTrue(native) + self._assert_same_sequence(_stable(native), _stable(ours)) + + async def test_the_result_follows_the_nodes_update(self): + native, ours = await _both( + _golden_graph(), "tasks-updates", INPUT, ["updates", "tasks", "custom"] + ) + self._assert_same_sequence(_stable(native), _stable(ours)) + + async def test_a_node_with_a_router(self): + native, ours = await _both( + _router_graph(), "tasks-router", {"log": []}, ["updates", "tasks", "custom"] + ) + self._assert_same_sequence(_stable(native), _stable(ours)) + + async def test_a_parallel_step(self): + native, ours = await _both( + _fan_out_graph(), "tasks-fan", {"log": []}, ["tasks", "updates"] + ) + self.assertEqual( + _canonical(_stable(ours, keep_ids=False)), + _canonical(_stable(native, keep_ids=False)), + ) + + async def test_send_tasks(self): + graph = StateGraph(_Out) + graph.add_node("work", lambda arg: {"out": [arg["i"]]}) + graph.add_conditional_edges( + START, lambda state: [Send("work", {"i": i}) for i in (1, 2)], ["work"] + ) + graph.add_edge("work", END) + native, ours = await _both( + graph.compile(), "tasks-send", {"out": []}, ["tasks"] + ) + self.assertEqual( + _canonical(_stable(ours, keep_ids=False)), + _canonical(_stable(native, keep_ids=False)), + ) + + async def test_a_tasks_start_and_result_share_one_id(self): + _, ours = await _both(_fan_out_graph(), "tasks-ids", {"log": []}, ["tasks"]) + counts = Counter(payload["id"] for _, payload in ours) + self.assertEqual(len(counts), 4) + self.assertEqual(set(counts.values()), {2}) + + +class TestDebugMatchesNative(_FakeDaprTest): + async def test_without_a_checkpointer_it_is_the_task_events(self): + native, ours = await _both(_golden_graph(), "debug-seq", INPUT, ["debug"]) + self.assertEqual( + {p["type"] for _, p in native}, {"task", "task_result"} + ) # no checkpoint events without a checkpointer + self._assert_same_sequence(_stable(native), _stable(ours)) + + async def test_next_to_tasks_and_updates(self): + modes = ["updates", "tasks", "debug"] + native, ours = await _both(_router_graph(), "debug-all", {"log": []}, modes) + self._assert_same_sequence(_stable(native), _stable(ours)) + + +class TestAFailedAttempt(unittest.IsolatedAsyncioTestCase): + def setUp(self): + clear_registries() + self.addCleanup(clear_registries) + + async def test_it_sends_its_start_but_no_result(self): + def boom(state: Any) -> dict: + raise RuntimeError("nope") + + register_node("boom", boom) + registry = StreamSinkRegistry() + sink = registry.open("wf-boom") + with self.assertRaises(RuntimeError): + await asyncio.to_thread( + execute_node_activity, + _Ctx("wf-boom"), + _payload("boom"), + stream_registry=registry, + ) + sink.close() + events = [e for e in await _drain(sink) if hasattr(e, "mode")] + tasks = [e.data for e in events if e.mode == "tasks"] + self.assertEqual( + [sorted(t) for t in tasks], [["id", "input", "name", "triggers"]] + ) + debug = [e.data["type"] for e in events if e.mode == "debug"] + self.assertEqual(debug, ["task"]) + + +CHECKPOINTS_REASON = "workflow history" + + +class TestCheckpointsAreRefused(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def test_astream_says_why(self): + runner = _chat_graph(name="no-checkpoints") + runner._started = True + for mode in ("checkpoints", ["messages", "checkpoints"]): + with self.subTest(stream_mode=mode): + with self.assertRaises(ValueError) as caught: + await _collect(runner.astream(INPUT, stream_mode=mode)) + self.assertIn("checkpoints", str(caught.exception)) + self.assertIn(CHECKPOINTS_REASON, str(caught.exception)) + + def test_a_streaming_request_gets_a_422_that_says_why(self): + from fastapi.testclient import TestClient + + runner = _chat_graph(name="no-checkpoints-http") + runner._started = True + client = TestClient(serve_app(runner)) + resp = client.post( + "/agent/run", + json={"task": "hi", "stream": True, "stream_mode": ["checkpoints"]}, + ) + self.assertEqual(resp.status_code, 422) + self.assertIn(CHECKPOINTS_REASON, resp.json()["detail"]) diff --git a/tests/agent/langgraph/test_streaming_golden_values.py b/tests/agent/langgraph/test_streaming_golden_values.py new file mode 100644 index 00000000..7eface73 --- /dev/null +++ b/tests/agent/langgraph/test_streaming_golden_values.py @@ -0,0 +1,233 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``stream_mode="values"``: the graph's state after each step, as native yields it. + +The state after step s is what every activity of step s+1 is handed, so the +first of them to start sends it; the sink keeps the first and drops the rest. +The state after the last step comes from the run's final event. +""" + +import asyncio +import operator +from typing import Any, List +from unittest import mock + +from langchain_core.load import load +from langgraph.errors import GraphRecursionError +from langgraph.graph import END, START, StateGraph +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.core.workflow.stream import ( + NODE_RESET, + VALUES, + StreamSinkRegistry, +) +from diagrid.agent.langgraph.models import ChannelState, ExecuteNodeInput +from diagrid.agent.langgraph.streaming import STREAM_RUN_KEY +from diagrid.agent.langgraph.workflow import ( + clear_registries, + execute_node_activity, + register_node, +) + +from .golden_harness import ( + _both, + _canonical, + _chain, + _FakeDaprTest, + _golden_graph, + _runner, + _wire, +) +from .streaming_helpers import ( + INPUT, + _collect, + _Ctx, + _drain, + parse_sse, + serve_app, +) +from .test_streaming_golden import _fan_out_graph, _router_loop_graph + +VALUES_ONLY = ["values"] +WITH_CHUNKS = ["messages", "updates", "custom", "values"] + + +def _values(items: List) -> List[Any]: + return [p for m, p in _wire(items) if m == "values"] + + +class _Log(TypedDict, total=False): + log: Annotated[list, operator.add] + + +def _quiet_middle_graph() -> Any: + """a -> quiet (writes nothing) -> b: no values chunk after quiet's step.""" + graph = StateGraph(_Log) + graph.add_node("a", lambda state: {"log": ["a"]}) + graph.add_node("quiet", lambda state: None) + graph.add_node("b", lambda state: {"log": ["b"]}) + graph.add_edge(START, "a") + graph.add_edge("a", "quiet") + graph.add_edge("quiet", "b") + graph.add_edge("b", END) + return graph.compile() + + +class TestValuesMatchNative(_FakeDaprTest): + async def test_a_sequential_graph(self): + native, ours = await _both(_golden_graph(), "values-seq", INPUT, VALUES_ONLY) + self.assertTrue(_values(native)) + self._assert_same_sequence(native, ours) + + async def test_each_value_sits_between_its_steps_chunks(self): + native, ours = await _both(_golden_graph(), "values-mixed", INPUT, WITH_CHUNKS) + self._assert_same_sequence(native, ours) + + async def test_a_parallel_step(self): + native, ours = await _both( + _fan_out_graph(), "values-fan", {"log": []}, WITH_CHUNKS + ) + self.assertEqual(_canonical(ours), _canonical(native)) + self.assertEqual(_values(ours), _values(native)) + + async def test_a_router_loop(self): + native, ours = await _both( + _router_loop_graph(), "values-loop", {"log": []}, ["values", "updates"] + ) + self._assert_same_sequence(native, ours) + + async def test_the_last_value_is_the_final_state(self): + compiled = _chain(3) + native, ours = await _both(compiled, "values-final", {"log": []}, VALUES_ONLY) + self._assert_same_sequence(native, ours) + self.assertEqual(ours[-1], ("values", compiled.invoke({"log": []}))) + + async def test_a_step_that_writes_no_output_channel_sends_none(self): + for name, compiled, graph_input in ( + ("values-quiet-middle", _quiet_middle_graph(), {"log": []}), + # the golden graph's last node writes nothing: no final value + ("values-quiet-last", _golden_graph(), INPUT), + ): + with self.subTest(case=name): + native, ours = await _both( + compiled, name, graph_input, ["values", "updates"] + ) + self._assert_same_sequence(native, ours) + + async def test_an_empty_input_sends_no_first_value(self): + native, ours = await _both(_chain(2), "values-empty", {}, VALUES_ONLY) + self.assertEqual(len(_values(native)), 2) + self._assert_same_sequence(native, ours) + + +class _Count(TypedDict, total=False): + n: int + + +def _endless_graph() -> Any: + graph = StateGraph(_Count) + graph.add_node("inc", lambda state: {"n": state.get("n", 0) + 1}) + graph.add_edge(START, "inc") + graph.add_conditional_edges("inc", lambda s: "inc" if s["n"] < 99 else END) + return graph.compile() + + +async def _until_error(stream: Any) -> List[Any]: + items: List[Any] = [] + with mock.patch("diagrid.agent.langgraph.workflow.when_all", side_effect=list): + try: + async for item in stream: + items.append(item) + except GraphRecursionError: + return items + raise AssertionError("the run did not hit its step limit") + + +class TestValuesOfAFailedRun(_FakeDaprTest): + async def test_a_step_limit_ends_with_the_last_steps_value_like_native(self): + compiled = _endless_graph() + config = {"recursion_limit": 3} + native = await _until_error( + compiled.astream({"n": 0}, config, stream_mode=VALUES_ONLY) + ) + ours = await _until_error( + _runner(compiled, "values-limit").astream( + {"n": 0}, + config=config, + workflow_id="wf-values-limit", + stream_mode=VALUES_ONLY, + poll_interval=0.01, + ) + ) + self.assertEqual(native[-1], ("values", {"n": 3})) + self.assertEqual(ours, native) + + +class TestValuesOfARetriedStep(_FakeDaprTest): + def setUp(self): + super().setUp() + clear_registries() + self.addCleanup(clear_registries) + + async def test_a_retry_does_not_send_the_value_again(self): + attempts: List[int] = [] + + def flaky(state: Any) -> dict: + attempts.append(1) + if len(attempts) == 1: + raise RuntimeError("first attempt fails") + return {"log": ["b"]} + + register_node("b", flaky) + registry = StreamSinkRegistry() + sink = registry.open("wf-retry") + payload = ExecuteNodeInput( + node_name="b", + channel_state=ChannelState( + values={"log": ["a"]}, versions={"log": 2}, updated_channels=["log"] + ), + config={STREAM_RUN_KEY: True}, + step=1, + output_channels=["log"], + ).to_dict() + for _ in range(2): + try: + await asyncio.to_thread( + execute_node_activity, + _Ctx("wf-retry"), + payload, + stream_registry=registry, + ) + except RuntimeError: + pass + sink.close() + events = [e for e in await _drain(sink) if hasattr(e, "mode")] + values = [e for e in events if e.mode == VALUES] + self.assertEqual([e.data for e in values], [{"log": ["a"]}]) + self.assertEqual(events[0].mode, VALUES) + # the node's own retry is still reported, and only once + self.assertEqual([e.mode for e in events].count(NODE_RESET), 1) + + +class TestValuesOverSse(_FakeDaprTest): + def test_they_load_back_as_the_native_values(self): + from fastapi.testclient import TestClient + + compiled = _golden_graph() + native = list(compiled.stream(INPUT, stream_mode="values")) + runner = _runner(compiled, "values-sse") + client = TestClient(serve_app(runner)) + resp = client.post( + "/agent/run", + json={**INPUT, "stream": True, "stream_mode": ["values"]}, + ) + events = parse_sse(resp.text) + self.assertEqual(events[-1][0], "workflow_completed", events[-1]) + ours = [load(d, allowed_objects="messages") for e, d in events if e == "values"] + self.assertEqual( + _values([("values", v) for v in ours]), + _values([("values", v) for v in native]), + ) + self.assertNotIn("channel_state", events[-1][1]) diff --git a/tests/agent/langgraph/test_streaming_sse.py b/tests/agent/langgraph/test_streaming_sse.py index 6c1842a3..dc41c3f1 100644 --- a/tests/agent/langgraph/test_streaming_sse.py +++ b/tests/agent/langgraph/test_streaming_sse.py @@ -473,7 +473,7 @@ def test_true_streams(self): class TestInvalidStreamRequest(_RouteCase): def test_an_unsupported_stream_mode_is_rejected_before_the_stream_starts(self): - for mode in ("bogus", ["messages", "values"], 7): + for mode in ("bogus", ["messages", "bogus"], 7): with self.subTest(stream_mode=mode): self.setUp() resp, started = self._post( From 8caf4832281fcf2ab7f38217eab40311abe5811f Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 11:41:16 +0100 Subject: [PATCH 19/73] feat(langgraph): stream the values, tasks and debug modes values: the state after step s is the input of every activity of step s+1, so in a streamed run each of them offers it, when step s wrote an output channel, before it runs its node; the sink keeps the first offer of a step and drops the rest without a node_reset. The workflow hands the output channels to the activities of a streamed run, and a START edge's activity offers the input. The state after the last step travels on the final event of a streamed run (a stream-only key, stripped like executed) and is sent before the closing event when no activity sent it. A run that failed in a node or a router sends none; a run cut by its step limit sends it, as LangGraph does. tasks: a node's activity sends the task's start event (id, name, input, triggers and the user metadata and tags) when it starts the node, and its result next to its updates chunk. The id is derived from the run, step and task, so a retry keeps it. A failed attempt sends no result. debug wraps both with the step, a timestamp and the type, which is all native debug holds without a checkpointer. checkpoints is refused with a ValueError (a 422 over HTTP) that says why: the runner keeps no LangGraph checkpoints, the workflow history is the durable record. Tests that compared a node's exact event list now leave out the task events. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/stream.py | 12 +++ diagrid/agent/langgraph/models.py | 14 +++ diagrid/agent/langgraph/runner.py | 25 ++++- diagrid/agent/langgraph/stream_events.py | 32 +++++- diagrid/agent/langgraph/stream_values.py | 94 ++++++++++++++++ diagrid/agent/langgraph/streaming.py | 66 +++++++++++- diagrid/agent/langgraph/task_events.py | 101 ++++++++++++++++++ diagrid/agent/langgraph/workflow.py | 51 +++++++++ .../langgraph/test_streaming_activity.py | 7 +- .../langgraph/test_streaming_golden_tasks.py | 6 +- .../langgraph/test_streaming_golden_values.py | 1 + .../langgraph/test_streaming_lifecycle.py | 9 +- tests/agent/langgraph/test_streaming_sink.py | 5 +- 13 files changed, 404 insertions(+), 19 deletions(-) create mode 100644 diagrid/agent/langgraph/stream_values.py create mode 100644 diagrid/agent/langgraph/task_events.py diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index 28642157..99d9c5fc 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -28,6 +28,9 @@ MAX_BUFFERED_EVENTS = 10_000 UPDATES = "updates" +#: The graph's state after a step. Every activity of the next step is handed +#: that state and offers it; the sink keeps the first offer of each step. +VALUES = "values" NODE_RESET = "node_reset" STREAM_UNAVAILABLE = "stream_unavailable" STREAM_DROPPED = "stream_dropped" @@ -124,6 +127,9 @@ class InProcessSink: ownership and emits a ``node_reset`` event so consumers can drop the partial text; the old attempt's chunks are then ignored. After a node's ``updates`` chunk was accepted, chunks from any other attempt are dropped. + + A ``values`` chunk is the same whoever sends it, so the first one for a key + is kept and any later one dropped, with no ``node_reset``. """ def __init__(self, workflow_id: str, loop: asyncio.AbstractEventLoop) -> None: @@ -134,6 +140,7 @@ def __init__(self, workflow_id: str, loop: asyncio.AbstractEventLoop) -> None: self._owner: Dict[Tuple[int, str], str] = {} self._finished: Dict[Tuple[int, str], str] = {} self._retired: set = set() + self._values: set = set() self._closed = False self._dropped = 0 @@ -142,6 +149,11 @@ def put(self, event: StreamEvent) -> None: with self._lock: if self._closed: return + if event.mode == VALUES: + if key not in self._values: + self._values.add(key) + self._enqueue(event) + return if self._finished.get(key, event.attempt_id) != event.attempt_id: return if (key, event.attempt_id) in self._retired: diff --git a/diagrid/agent/langgraph/models.py b/diagrid/agent/langgraph/models.py index ed5d3de6..a2054fa4 100644 --- a/diagrid/agent/langgraph/models.py +++ b/diagrid/agent/langgraph/models.py @@ -251,6 +251,9 @@ class ExecuteNodeInput: for the activity to evaluate once the node returns, as LangGraph runs a router inside its node's task. ``None`` when the workflow evaluates them itself (an instance from before routing moved here). + output_channels: The graph's output channels, set only in a streamed + run: the activity sends the state it is handed (the state after the + previous step) as a ``values`` chunk when the step wrote one of them. """ node_name: str @@ -261,6 +264,7 @@ class ExecuteNodeInput: send: Optional[Dict[str, Any]] = None recursion_limit: Optional[int] = None routes: Optional[List[Dict[str, Any]]] = None + output_channels: Optional[List[str]] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -277,6 +281,8 @@ def to_dict(self) -> Dict[str, Any]: data["recursion_limit"] = self.recursion_limit if self.routes is not None: data["routes"] = self.routes + if self.output_channels is not None: + data["output_channels"] = self.output_channels return data @classmethod @@ -290,6 +296,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeInput": send=data.get("send"), recursion_limit=data.get("recursion_limit"), routes=data.get("routes"), + output_channels=data.get("output_channels"), ) @@ -380,6 +387,9 @@ class EvaluateConditionInput: task, apart from the node's other tasks of the step. recursion_limit: The run's step limit as a LangGraph ``recursion_limit`` (see ``ExecuteNodeInput``). + output_channels: Set only for a START edge of a streamed run: the + activity sends the input as the first ``values`` chunk (see + ``ExecuteNodeInput``). """ source_node: str @@ -391,6 +401,7 @@ class EvaluateConditionInput: step: Optional[int] = None send_slot: Optional[int] = None recursion_limit: Optional[int] = None + output_channels: Optional[List[str]] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -407,6 +418,8 @@ def to_dict(self) -> Dict[str, Any]: data["send_slot"] = self.send_slot if self.recursion_limit is not None: data["recursion_limit"] = self.recursion_limit + if self.output_channels is not None: + data["output_channels"] = self.output_channels return data @classmethod @@ -421,6 +434,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "EvaluateConditionInput": step=data.get("step"), send_slot=data.get("send_slot"), recursion_limit=data.get("recursion_limit"), + output_channels=data.get("output_channels"), ) diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 822fb791..0b8819d5 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -34,6 +34,7 @@ KEEPALIVE_EVENT, WORKFLOW_STARTED, UPDATES, + VALUES, InProcessSink, StreamClosed, StreamEvent, @@ -50,6 +51,7 @@ ) from .streaming import ( EXECUTED_KEY, + FINAL_STATE_KEY, STREAM_RUN_KEY, StaticConfig, FAILED_STATUSES, @@ -886,6 +888,12 @@ def _parse_output(wf_id: str, output_dict: dict) -> dict: # type: ignore[type-a "status": output.status, **({"error": output.error} if output.error else {}), **({EXECUTED_KEY: output.executed} if with_executed else {}), + # the state it ended with, for the stream's last values chunk + **( + {FINAL_STATE_KEY: output.channel_state.to_dict()} + if streamed and output.channel_state is not None + else {} + ), } async for event in self._poll_workflow( @@ -917,8 +925,10 @@ async def astream( ) -> AsyncIterator[Any]: """Stream a run like ``CompiledStateGraph.astream``. - ``messages``, ``updates`` and ``custom`` are supported; one mode yields - bare chunks, a list of modes yields ``(mode, chunk)``. The chunks have + ``messages``, ``updates``, ``custom``, ``values``, ``tasks`` and + ``debug`` are supported (``checkpoints`` is refused: there are no + LangGraph checkpoints); one mode yields bare chunks, a list of modes + yields ``(mode, chunk)``. The chunks have the shape native ``astream`` yields: ``messages`` are ``(message_chunk, metadata)``, ``updates`` are ``{node: update}`` with the values as the node returned them (``None`` for a node that wrote @@ -993,6 +1003,7 @@ async def _stream_events( sink = self._stream_registry.open(workflow_id) task: Optional["asyncio.Task[None]"] = None seen_nodes: Set[Tuple[int, str]] = set() + values_sent: Set[int] = set() try: # Before the pump schedules the workflow: an activity can write the # moment it is scheduled, and the event must come before its chunks. @@ -1014,11 +1025,19 @@ async def _stream_events( # Unregister before handing over the result: chunks a late # activity attempt writes from here on are dropped. self._stream_registry.close(workflow_id, sink) - for event in closing_events(item, seen_nodes, workflow_id): + for event in closing_events( + item, + seen_nodes, + workflow_id, + output_channels=self._graph_config.output_channels, + values_sent=values_sent, + ): yield event return if isinstance(item, StreamEvent) and item.mode == UPDATES: seen_nodes.add((item.step, item.node)) + if isinstance(item, StreamEvent) and item.mode == VALUES: + values_sent.add(item.step) yield item finally: # Also reached when the consumer goes away (client disconnect, diff --git a/diagrid/agent/langgraph/stream_events.py b/diagrid/agent/langgraph/stream_events.py index 3148b9b5..34a6c496 100644 --- a/diagrid/agent/langgraph/stream_events.py +++ b/diagrid/agent/langgraph/stream_events.py @@ -17,8 +17,10 @@ StreamEvent, ) +from .stream_values import final_values from .streaming import ( EXECUTED_KEY, + FINAL_STATE_KEY, GraphRunError, StreamControl, run_error, @@ -106,11 +108,15 @@ def started_event(workflow_id: str, thread_id: str) -> Any: ) +_STREAM_ONLY_KEYS = (EXECUTED_KEY, FINAL_STATE_KEY) + + def without_executed(event: Dict[str, Any]) -> Dict[str, Any]: - """``event`` minus the per-step node list, which is for the stream only.""" - if EXECUTED_KEY not in event: + """``event`` minus what is for the stream only: the per-step node list and + the state the run ended with.""" + if not any(key in event for key in _STREAM_ONLY_KEYS): return event - return {k: v for k, v in event.items() if k != EXECUTED_KEY} + return {k: v for k, v in event.items() if k not in _STREAM_ONLY_KEYS} async def next_item(sink: Any, keepalive: bool) -> Any: @@ -192,10 +198,26 @@ def route_astream_item( def closing_events( - closed: StreamClosed, seen_nodes: Set[Tuple[int, str]], workflow_id: str + closed: StreamClosed, + seen_nodes: Set[Tuple[int, str]], + workflow_id: str, + *, + output_channels: Optional[List[str]] = None, + values_sent: Optional[Set[int]] = None, ) -> List[Any]: - """The items a stream ends with: ``stream_unavailable`` if due, then the final.""" + """The items a stream ends with. + + The ``values`` chunk of the state the run ended with (when the run got to + the end of a step and no activity sent it), ``stream_unavailable`` if due, + then the final event. + """ out: List[Any] = [] + if output_channels: + last = final_values( + closed.final, output_channels, values_sent or set(), workflow_id + ) + if last is not None: + out.append(last) unavailable = stream_unavailable_event(closed.final, seen_nodes, workflow_id) if unavailable is not None: logger.warning( diff --git a/diagrid/agent/langgraph/stream_values.py b/diagrid/agent/langgraph/stream_values.py new file mode 100644 index 00000000..28fe3f2f --- /dev/null +++ b/diagrid/agent/langgraph/stream_values.py @@ -0,0 +1,94 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``stream_mode="values"``: the graph's output state after each step. + +LangGraph sends the output channels after a step that wrote one of them (and +after the input, when the input wrote one). Here the state after step s is the +input of every activity of step s+1, so the first of them to start sends it, +keyed by the step it opens; the sink keeps the first. The state after the last +step is in the run's final event. +""" + +import uuid +from typing import Any, Dict, Iterable, List, Optional, Set + +from diagrid.agent.core.workflow.stream import VALUES, StreamEvent + +from .models import ChannelState + +#: The sink key every ``values`` chunk of one step shares. +VALUES_KEY = "__values__" + +# The one channel of a graph whose whole state is a single value. +_ROOT = "__root__" + +# The statuses whose final state LangGraph still sends: a run that completed, +# and one cut by its step limit (native sends the last step's values, then +# raises). A run that failed in a node or a router never applied that step. +_FINAL_VALUE_STATUSES = ("completed", "max_steps_reached") + + +def wants_values(updated_channels: Iterable[str], output_channels: List[str]) -> bool: + """Whether a step that wrote ``updated_channels`` has a ``values`` chunk.""" + return not set(output_channels).isdisjoint(updated_channels) + + +def output_values(state: Dict[str, Any], output_channels: List[str]) -> Any: + """The chunk itself: the output channels that hold a value, as LangGraph reads them.""" + if output_channels == [_ROOT]: + return state.get(_ROOT) + return {name: state[name] for name in output_channels if name in state} + + +def values_event(workflow_id: str, step: int, chunk: Any) -> StreamEvent: + """The ``values`` chunk of the state step ``step`` starts from (0: the input).""" + return StreamEvent( + workflow_id=workflow_id, + step=step, + node=VALUES_KEY, + attempt_id=uuid.uuid4().hex, + seq=0, + ns=(), + mode=VALUES, + data=chunk, + ) + + +def state_values( + workflow_id: str, + step: int, + channel_state: ChannelState, + output_channels: List[str], +) -> Optional[StreamEvent]: + """The ``values`` chunk of ``channel_state``, or ``None`` if it has none.""" + if not wants_values(channel_state.updated_channels, output_channels): + return None + from .workflow import _reconstruct_state + + state = _reconstruct_state(channel_state) + return values_event(workflow_id, step, output_values(state, output_channels)) + + +def final_values( + final: Dict[str, Any], + output_channels: List[str], + sent_steps: Set[int], + workflow_id: str, +) -> Optional[StreamEvent]: + """The ``values`` chunk of the state a run ended with, if it is due. + + ``final`` is the run's terminal event, with its stream-only channel state; + ``sent_steps`` are the steps whose ``values`` chunk was already sent. + """ + from .streaming import FINAL_STATE_KEY + + steps = final.get("steps") + stored = final.get(FINAL_STATE_KEY) + if final.get("status") not in _FINAL_VALUE_STATUSES or not isinstance(steps, int): + return None + if not isinstance(stored, dict) or steps in sent_steps: + return None + return state_values( + workflow_id, steps, ChannelState.from_dict(stored), output_channels + ) diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index ab9fabef..9048585b 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -24,16 +24,37 @@ from diagrid.agent.core.workflow.stream import ( STREAM_UNAVAILABLE, UPDATES, + VALUES, StreamEvent, StreamSink, display_step, ) +from .task_events import ( + DEBUG, + TASKS, + debug_event, + task_id, + task_metadata, + task_result, + task_start, +) + logger = logging.getLogger(__name__) MESSAGES = "messages" CUSTOM = "custom" -SUPPORTED_MODES = (MESSAGES, UPDATES, CUSTOM) +SUPPORTED_MODES = (MESSAGES, UPDATES, CUSTOM, VALUES, TASKS, DEBUG) +# Modes LangGraph has and the runner refuses, with the reason it gives. +REFUSED_MODES = { + "checkpoints": ( + "stream_mode 'checkpoints' is not supported: the Dapr workflow runner " + "keeps no LangGraph checkpoints (the workflow history is the run's " + "durable record), so there are no checkpoint ids to stream or pass back. " + "Read the full state from the run's final event or from " + "GET /agent/run/{workflow_id}." + ), +} # Configurable keys LangChain never copies into metadata (they are secrets). _UNTRACED_CONFIGURABLE = frozenset(("api_key",)) @@ -41,6 +62,9 @@ # Key of the run_async terminal event that lists the nodes each step ran. It # serves the stream (see stream_unavailable_event) and is not part of a result. EXECUTED_KEY = "executed" +# Key of the run_async terminal event of a streamed run that holds the state it +# ended with, for the stream's last ``values`` chunk; also not part of a result. +FINAL_STATE_KEY = "channel_state" # Set in the workflow config of a run someone is streaming, so an activity that # finds no sink to write to knows that is a problem and not just a plain run. @@ -301,6 +325,34 @@ def writer(self, chunk: Any) -> None: """``Runtime.stream_writer``: what ``get_stream_writer()`` returns.""" self._emit((), CUSTOM, chunk) + @property + def _event_task_id(self) -> str: + """The id of this task in its ``tasks`` events.""" + return task_id(self._workflow_id, self._step, self._sink_node) + + def _emit_task(self, payload: Dict[str, Any]) -> None: + """A ``tasks`` event, and the same event as ``debug`` sends it.""" + self._emit((), TASKS, payload) + self._emit((), DEBUG, debug_event(display_step(self._step), payload)) + + def task_started( + self, node_input: Any, config: Optional[Dict[str, Any]] = None + ) -> None: + """Send the task's start event, as LangGraph does when a step starts it.""" + config = config or {} + metadata = task_metadata( + self._static.metadata(config.get("metadata")), + self._static.tags(config.get("tags")), + ) + triggers = self.metadata["langgraph_triggers"] + self._emit_task( + task_start(self._event_task_id, self._node, node_input, triggers, metadata) + ) + + def task_finished(self, writes: List[Tuple[str, Any]]) -> None: + """Send the task's result event: its writes, after its ``updates`` chunk.""" + self._emit_task(task_result(self._event_task_id, self._node, writes)) + def updates(self, writes: List[Tuple[str, Any]]) -> None: """Emit the node's ``(channel, value)`` writes as ``{node: update}``. @@ -369,6 +421,11 @@ def normalize_stream_mode(stream_mode: Any) -> Tuple[List[str], bool]: """Return ``(modes, is_list)``; reject modes the runner cannot provide.""" is_list = isinstance(stream_mode, (list, tuple)) modes = list(stream_mode) if is_list else [stream_mode] + refused = [ + REFUSED_MODES[m] for m in modes if isinstance(m, str) and m in REFUSED_MODES + ] + if refused: + raise ValueError(refused[0]) unsupported = [m for m in modes if m not in SUPPORTED_MODES] if unsupported: raise ValueError( @@ -406,14 +463,15 @@ def _plain_data(value: Any) -> Any: def to_wire(mode: str, data: Any) -> Any: """JSON-ready form of a chunk for a transport. - ``messages``, ``updates`` and ``custom`` chunks can carry LangChain objects - next to arbitrary values a node chose to return or write. ``dumpd`` turns + Every chunk of a stream mode can carry LangChain objects (messages in a + ``values`` state, a task's input) next to arbitrary values a node chose to + return or write. ``dumpd`` turns the objects into the form ``langchain_core.load.load`` restores, so a client sees the same objects an in-process ``astream`` consumer does; everything else becomes plain data first (see :func:`_plain_data`). Control events go as they are. """ - if mode in (MESSAGES, UPDATES, CUSTOM): + if mode in SUPPORTED_MODES: return dumpd(_plain_data(data)) return data diff --git a/diagrid/agent/langgraph/task_events.py b/diagrid/agent/langgraph/task_events.py new file mode 100644 index 00000000..4b76df03 --- /dev/null +++ b/diagrid/agent/langgraph/task_events.py @@ -0,0 +1,101 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The ``tasks`` and ``debug`` stream modes, shaped as LangGraph shapes them. + +A task's start event is sent when its node starts, and its result next to its +``updates`` chunk. ``debug`` wraps both with the step, a timestamp and the +event's type. Without a checkpointer that is everything native ``debug`` sends; +there are no LangGraph checkpoints here, so no ``checkpoint`` events. + +A failed attempt sends no result: Dapr retries it, ``node_reset`` covers its +partial output, and only the workflow knows which failure is the last. +""" + +import uuid +from datetime import datetime, timezone +from typing import Any, Dict, List, Optional, Sequence, Tuple + +from langgraph.checkpoint.base import EXCLUDED_METADATA_KEYS + +TASKS = "tasks" +DEBUG = "debug" +#: ``debug`` event types. +TASK = "task" +TASK_RESULT = "task_result" + +# How LangGraph marks a channel written more than once by one task. +_MULTIPLE_WRITES = "$writes" + + +def task_id(workflow_id: str, step: int, task_key: str) -> str: + """A task's id: the same for its start, its result and every attempt.""" + return str(uuid.uuid5(uuid.NAMESPACE_OID, f"{workflow_id}:{step}:{task_key}")) + + +def task_metadata( + metadata: Dict[str, Any], tags: Sequence[str] +) -> Optional[Dict[str, Any]]: + """What a start event carries as ``metadata``: the user's keys and tags.""" + kept = {k: v for k, v in metadata.items() if k not in EXCLUDED_METADATA_KEYS} + user_tags = [t for t in tags if not t.startswith("seq:step")] + if user_tags: + kept["tags"] = user_tags + return kept or None + + +def task_start( + task: str, + name: str, + task_input: Any, + triggers: Sequence[str], + metadata: Optional[Dict[str, Any]], +) -> Dict[str, Any]: + """A ``tasks`` start event: ``{id, name, input, triggers[, metadata]}``.""" + payload: Dict[str, Any] = { + "id": task, + "name": name, + "input": task_input, + "triggers": tuple(triggers), + } + if metadata: + payload["metadata"] = metadata + return payload + + +def task_result(task: str, name: str, writes: List[Tuple[str, Any]]) -> Dict[str, Any]: + """A ``tasks`` result event of a task that finished with ``writes``.""" + return { + "id": task, + "name": name, + "error": None, + "result": _result_writes(writes), + "interrupts": [], + } + + +def _result_writes(writes: List[Tuple[str, Any]]) -> Dict[str, Any]: + """``{channel: value}``; a channel written more than once lists its writes.""" + result: Dict[str, Any] = {} + for channel, value in writes: + if channel not in result: + result[channel] = value + continue + existing = result[channel] + earlier = ( + existing[_MULTIPLE_WRITES] + if isinstance(existing, dict) and _MULTIPLE_WRITES in existing + else [existing] + ) + result[channel] = {_MULTIPLE_WRITES: [*earlier, value]} + return result + + +def debug_event(step: int, payload: Dict[str, Any]) -> Dict[str, Any]: + """A ``tasks`` event as ``debug`` sends it; ``step`` as ``langgraph_step``.""" + return { + "step": step, + "timestamp": datetime.now(timezone.utc).isoformat(), + "type": TASK_RESULT if "result" in payload else TASK, + "payload": payload, + } diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index cfb32416..6dc0b9e7 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -64,6 +64,7 @@ ) from .node_routes import route_in_node +from .stream_values import state_values from .streaming import STREAM_RUN_KEY, NodeStreamer, StaticConfig from .values import ( coerce_to_default, @@ -521,6 +522,13 @@ class _Run: #: Deferred nodes that were triggered and wait for nothing else to be pending. held: List[str] = field(default_factory=list) + @property + def output_channels(self) -> Optional[List[str]]: + """What an activity of a streamed run sends ``values`` chunks of.""" + if not (self.config or {}).get(STREAM_RUN_KEY): + return None + return list(self.graph_config.output_channels) + def finish( self, step: int, status: str, error: Optional[str] = None ) -> Dict[str, Any]: @@ -833,6 +841,7 @@ def _run_nodes( send=send, recursion_limit=run.recursion_limit, routes=_node_routes(run, node_name) if run.route_in_node else None, + output_channels=run.output_channels, ) activity: Any = execute_node_activity if run.node_activities_by_name: @@ -937,6 +946,8 @@ def _follow_edge( step=step, send_slot=send_slot, recursion_limit=run.recursion_limit, + # a START edge reads the input: the state of the run's first values chunk + output_channels=run.output_channels if source_node == START else None, ) # By name, so the runner's own activity (the one that knows its stream # registry) runs, not the module-level function. @@ -1417,6 +1428,7 @@ def _run_with_stream_hooks(call: _NodeCall, parent: Optional[str]) -> Any: """ streamer = call.streamer if streamer: + streamer.task_started(call.state, call.config) streamer.node_started(call.state, call.config) try: if parent: @@ -1457,6 +1469,7 @@ def _node_output(call: _NodeCall, result: Any) -> Dict[str, Any]: ).output_fields() if call.streamer: call.streamer.updates(raw_writes) + call.streamer.task_finished(raw_writes) goto, sends = _result_to_gotos(result) return ExecuteNodeOutput( node_name=call.node_name, @@ -1504,12 +1517,43 @@ def execute_node_activity( registry=stream_registry, ) + _send_values( + ctx, + node_input.channel_state, + node_input.output_channels, + node_input.step or 0, + stream_registry, + ) # Under the LangSmith parent trace the runner opened, so LLM calls nest in it. result = _run_with_stream_hooks(call, _langsmith_parent(config)) return _node_output(call, result) +def _send_values( + ctx: WorkflowActivityContext, + channel_state: ChannelState, + output_channels: Optional[List[str]], + step: int, + registry: Optional[StreamSinkRegistry], +) -> None: + """Offer the state this activity was handed as the ``values`` chunk of ``step``. + + It is the state after the previous step (the input for step 0), which + every activity of ``step`` is handed: the sink keeps the first offer, which + comes before any of the step's own chunks. + """ + if not output_channels: + return + workflow_id = getattr(ctx, "workflow_id", None) + sink = get_stream_sink(workflow_id, registry=registry) + if sink is None: + return + event = state_values(str(workflow_id), step, channel_state, output_channels) + if event is not None: + sink.put(event) + + def _node_state(node_input: ExecuteNodeInput) -> Any: """What the node takes as input: the channel state, or a ``Send``'s argument.""" if node_input.send is None: @@ -1611,6 +1655,13 @@ def evaluate_condition_activity( module's). """ cond_input = EvaluateConditionInput.from_dict(input_data) + _send_values( + ctx, + cond_input.channel_state, + cond_input.output_channels, + 0, + stream_registry, + ) return evaluate_condition(ctx, cond_input, stream_registry).to_dict() diff --git a/tests/agent/langgraph/test_streaming_activity.py b/tests/agent/langgraph/test_streaming_activity.py index 097d7e2f..8880e429 100644 --- a/tests/agent/langgraph/test_streaming_activity.py +++ b/tests/agent/langgraph/test_streaming_activity.py @@ -264,8 +264,11 @@ async def _assert_run_survives(self) -> None: with self.assertLogs(LOGGER, level="ERROR") as logs: items = await self._run_streamed("wf-drift-1") await self._run_streamed("wf-drift-2") - # the node ran, its update still streams, and the cause is logged once - self.assertEqual([i.mode for i in items], ["updates"]) + # the node ran, its update and task events still stream, and the cause + # is logged once + self.assertEqual( + [i.mode for i in items], ["tasks", "debug", "updates", "tasks", "debug"] + ) self.assertEqual(len(logs.records), 1) self.assertIn("messages", logs.records[0].getMessage()) diff --git a/tests/agent/langgraph/test_streaming_golden_tasks.py b/tests/agent/langgraph/test_streaming_golden_tasks.py index 4258b217..0c475054 100644 --- a/tests/agent/langgraph/test_streaming_golden_tasks.py +++ b/tests/agent/langgraph/test_streaming_golden_tasks.py @@ -84,7 +84,11 @@ async def test_a_node_with_a_router(self): async def test_a_parallel_step(self): native, ours = await _both( - _fan_out_graph(), "tasks-fan", {"log": []}, ["tasks", "updates"] + # with messages: the fan-out's model answers differently when it streams + _fan_out_graph(), + "tasks-fan", + {"log": []}, + ["tasks", "updates", "messages"], ) self.assertEqual( _canonical(_stable(ours, keep_ids=False)), diff --git a/tests/agent/langgraph/test_streaming_golden_values.py b/tests/agent/langgraph/test_streaming_golden_values.py index 7eface73..91b3247a 100644 --- a/tests/agent/langgraph/test_streaming_golden_values.py +++ b/tests/agent/langgraph/test_streaming_golden_values.py @@ -111,6 +111,7 @@ async def test_a_step_that_writes_no_output_channel_sends_none(self): ("values-quiet-last", _golden_graph(), INPUT), ): with self.subTest(case=name): + self.setUp() native, ours = await _both( compiled, name, graph_input, ["values", "updates"] ) diff --git a/tests/agent/langgraph/test_streaming_lifecycle.py b/tests/agent/langgraph/test_streaming_lifecycle.py index 8fa97740..0e6d25b2 100644 --- a/tests/agent/langgraph/test_streaming_lifecycle.py +++ b/tests/agent/langgraph/test_streaming_lifecycle.py @@ -368,6 +368,9 @@ async def one(who: str) -> List[Any]: self.assertIsNone(runner.stream_registry.get("wf-B")) +TASK_MODES = ("tasks", "debug") + + class TestRetryWhileTheOldAttemptIsStillRunning(unittest.IsolatedAsyncioTestCase): def setUp(self): clear_registries() @@ -423,7 +426,8 @@ async def attempt_b() -> Any: break items.append(item) - shown = [(e.mode, e.data) for e in items] + # a task's start and result events are not what this is about + shown = [(e.mode, e.data) for e in items if e.mode not in TASK_MODES] self.assertEqual( shown, [ @@ -488,7 +492,8 @@ def run(task_id: int) -> Any: item = await sink.get() if isinstance(item, StreamClosed): break - shown.append((item.mode, item.data)) + if item.mode not in TASK_MODES: + shown.append((item.mode, item.data)) self.assertEqual( shown, [ diff --git a/tests/agent/langgraph/test_streaming_sink.py b/tests/agent/langgraph/test_streaming_sink.py index 8ebce102..e5e6b8e0 100644 --- a/tests/agent/langgraph/test_streaming_sink.py +++ b/tests/agent/langgraph/test_streaming_sink.py @@ -364,14 +364,15 @@ def flaky(state): await asyncio.to_thread(execute_node_activity, _Ctx("wf-retry"), payload) got = await self._drain(sink) self.assertEqual( - [(e.mode, e.data) for e in got if e.mode != "updates"], + [(e.mode, e.data) for e in got if e.mode in ("custom", "node_reset")], [ ("custom", "try-1"), ("node_reset", {"node": "flaky", "step": 3}), ("custom", "try-2"), ], ) - self.assertEqual(got[-1].mode, "updates") + # the retry's update closes the node; only its task result follows it + self.assertEqual([e.mode for e in got][-3:], ["updates", "tasks", "debug"]) class TestStreamSinkRegistry(unittest.IsolatedAsyncioTestCase): From 4cb0a248f5ae332d0d519e85956b8cdf08eb6c62 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 11:41:29 +0100 Subject: [PATCH 20/73] docs(langgraph): list the stream modes and why checkpoints is refused The Streaming section lists every mode with its chunk, says that checkpoints is refused because the workflow history, not a LangGraph checkpoint, is the run's durable record, and that the full state is in values, the final event or GET /agent/run/{workflow_id}. It also says when a values chunk arrives and what a failed run sends. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 37 ++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 95412695..2c0f46a3 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -100,8 +100,32 @@ from diagrid.agent.langgraph import ( ``` `astream` yields what `CompiledStateGraph.astream` yields, while each node runs -as a Dapr activity: LLM tokens (`messages`), node updates (`updates`) and -whatever a node writes with `get_stream_writer()` (`custom`). +as a Dapr activity. The stream modes are: + +| Mode | Chunk | +|---|---| +| `messages` | LLM tokens and the messages a node returns, as `(message_chunk, metadata)` | +| `updates` | `{node: update}`, one per node, with the values as the node returned them | +| `custom` | whatever a node writes with `get_stream_writer()` | +| `values` | the graph's output state after each step that wrote an output channel (and after the input, when it wrote one) | +| `tasks` | a task's start (`id`, `name`, `input`, `triggers`) when its node starts, and its result (`result`, `error`, `interrupts`) after its `updates` chunk | +| `debug` | the `tasks` events wrapped as `{step, timestamp, type, payload}` | + +`checkpoints` is refused (`ValueError` from `astream`, a `422` over HTTP): the +runner keeps no LangGraph checkpoints, because the Dapr workflow history is the +run's durable record, so there are no checkpoint ids a client could pass back. +For the same reason `debug` holds only the task events, which is what native +`debug` holds for a graph compiled without a checkpointer. A client that wants +the full state reads it from `values`, from the run's final event, or from `GET +/agent/run/{workflow_id}`. + +The `values` chunk of step s is sent by the first activity of step s+1 to +start, which is handed that state, so it comes one scheduling hop later than in +LangGraph but in the same place in the stream. The state after the last step is +sent before the final event; a run that failed in a node or a router sends no +value for that step, and a run cut by its step limit sends it, as LangGraph +does. A task that fails sends no result: Dapr retries it and `node_reset` +covers its partial output. ```python async for mode, chunk in runner.astream( @@ -162,14 +186,15 @@ Closing the stream does not cancel the Dapr workflow, which runs to completion. `serve()` answers `POST /agent/run` with `"stream": true` (the JSON boolean; any other value is a plain request and the key reaches the graph) as server-sent events. -`stream_mode` (a mode or a list; default all three) picks the chunks; an -unsupported one is refused with a `422` before the stream starts. The first +`stream_mode` (a mode or a list; default `messages`, `updates` and `custom`) +picks the chunks; an unsupported one, `checkpoints` included, is refused with a +`422` before the stream starts. The first event is `workflow_started`. An idle stream sends a `: keepalive` comment every 15 seconds so a proxy does not cut it, and the response sets `Cache-Control: no-cache` and `X-Accel-Buffering: no` so an nginx or ingress in front does not buffer the tokens. The -messages and updates are serialized with `langchain_core.load.dumpd`, so -`langchain_core.load.load` restores them. The stream ends with +chunks are serialized with `langchain_core.load.dumpd`, so +`langchain_core.load.load` restores the messages in them. The stream ends with `workflow_completed` or `workflow_failed`; both carry `workflow_id` and `thread_id`, a failure carries the error, and `dropped` is set when chunks were dropped. The run's result is also published to `publish_topic`; it is exactly what From 6320f3dcd44e63eaea37711f7241ad7decdd8aa3 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 11:59:49 +0100 Subject: [PATCH 21/73] test(langgraph): expect workflow_started only after the workflow is scheduled Signed-off-by: Casper Nielsen --- .../agent/langgraph/test_streaming_events.py | 4 + .../langgraph/test_streaming_lifecycle.py | 3 + tests/agent/langgraph/test_streaming_sink.py | 1 + .../test_streaming_started_after_schedule.py | 106 ++++++++++++++++++ 4 files changed, 114 insertions(+) create mode 100644 tests/agent/langgraph/test_streaming_started_after_schedule.py diff --git a/tests/agent/langgraph/test_streaming_events.py b/tests/agent/langgraph/test_streaming_events.py index aa62c28f..4f36e981 100644 --- a/tests/agent/langgraph/test_streaming_events.py +++ b/tests/agent/langgraph/test_streaming_events.py @@ -193,6 +193,7 @@ async def spy( input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 ): seen.update(config or {}) + yield {"type": "workflow_started", "workflow_id": workflow_id} yield {"type": "workflow_completed", "workflow_id": workflow_id} with mock.patch.object(runner, "run_async", spy): @@ -217,6 +218,7 @@ async def run( input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 ): sink = runner.stream_registry.get(workflow_id) + yield {"type": "workflow_started", "workflow_id": workflow_id} for chunk in chunks: sink.put(chunk) await asyncio.sleep(0) @@ -375,6 +377,7 @@ async def run( extra = ( {"executed": [["chat"]]} if (config or {}).get(STREAM_RUN_KEY) else {} ) + yield {"type": "workflow_started", "workflow_id": workflow_id} yield { "type": "workflow_completed", "workflow_id": workflow_id, @@ -648,6 +651,7 @@ async def run( _token("B", " world", 1), ): sink.put(event) + yield {"type": "workflow_started", "workflow_id": workflow_id} await asyncio.sleep(0) yield {"type": "workflow_completed", "workflow_id": workflow_id} diff --git a/tests/agent/langgraph/test_streaming_lifecycle.py b/tests/agent/langgraph/test_streaming_lifecycle.py index 0e6d25b2..639ce815 100644 --- a/tests/agent/langgraph/test_streaming_lifecycle.py +++ b/tests/agent/langgraph/test_streaming_lifecycle.py @@ -521,6 +521,7 @@ async def endless( ): sink = runner.stream_registry.get(workflow_id) sink.put(StreamEvent(workflow_id, 0, "n", "a", 0, (), "custom", "first")) + yield {"type": "workflow_started", "workflow_id": workflow_id} try: await asyncio.sleep(3600) yield {} # pragma: no cover @@ -542,6 +543,7 @@ async def endless( ): sink = runner.stream_registry.get(workflow_id) sink.put(StreamEvent(workflow_id, 0, "n", "a", 0, (), "custom", "first")) + yield {"type": "workflow_started", "workflow_id": workflow_id} await asyncio.sleep(3600) yield {} # pragma: no cover @@ -587,6 +589,7 @@ async def endless( registry.get(workflow_id).put( StreamEvent(workflow_id, 0, "n", "a", 0, (), "custom", "first") ) + yield {"type": "workflow_started", "workflow_id": workflow_id} await asyncio.sleep(3600) yield {} # pragma: no cover diff --git a/tests/agent/langgraph/test_streaming_sink.py b/tests/agent/langgraph/test_streaming_sink.py index e5e6b8e0..9bd616af 100644 --- a/tests/agent/langgraph/test_streaming_sink.py +++ b/tests/agent/langgraph/test_streaming_sink.py @@ -182,6 +182,7 @@ async def test_final_event_has_no_dropped_key_without_drops(self): async def quiet( input, *, thread_id=None, config=None, workflow_id=None, poll_interval=0.5 ): + yield {"type": "workflow_started", "workflow_id": workflow_id} yield {"type": "workflow_completed", "workflow_id": workflow_id} with mock.patch.object(runner, "run_async", quiet): diff --git a/tests/agent/langgraph/test_streaming_started_after_schedule.py b/tests/agent/langgraph/test_streaming_started_after_schedule.py new file mode 100644 index 00000000..e508f3f5 --- /dev/null +++ b/tests/agent/langgraph/test_streaming_started_after_schedule.py @@ -0,0 +1,106 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``workflow_started`` reaches the client only once the workflow exists. + +A client (or a second replica) that looks the run up the moment it sees +``workflow_started`` must find it: the event is yielded after +``schedule_new_workflow`` has returned, never before. +""" + +import asyncio +import threading +import unittest +from typing import Any, List +from unittest import mock + +from diagrid.agent.core.workflow.stream import WORKFLOW_STARTED, StreamEvent + +from .golden_harness import _FakeWorkflowClient +from .streaming_helpers import INPUT, _chat_graph +from .test_runner import _RunnerTestCase + + +class _GatedClient(_FakeWorkflowClient): + """A workflow client whose scheduling waits until the test lets it return.""" + + def __init__(self, runner: Any) -> None: + super().__init__(runner) + self.release = threading.Event() + self.returned = threading.Event() + + def schedule_new_workflow(self, *, workflow: Any, input: Any, instance_id: str): + self.release.wait(5) + super().schedule_new_workflow( + workflow=workflow, input=input, instance_id=instance_id + ) + self.returned.set() + + +class TestStartedAfterSchedule(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + def setUp(self) -> None: + super().setUp() + patch = mock.patch( + "diagrid.agent.langgraph.workflow.when_all", side_effect=list + ) + patch.start() + self.addCleanup(patch.stop) + + def _runner(self, name: str) -> Any: + runner = _chat_graph(name=name) + runner._started = True + client = _GatedClient(runner) + runner._workflow_client = client + return runner, client + + async def test_nothing_is_yielded_while_the_workflow_is_being_scheduled(self): + runner, client = self._runner("started-gated") + events = runner._stream_events( + INPUT, config=None, thread_id="t", workflow_id="wf-gated", poll_interval=0 + ) + first = asyncio.ensure_future(events.__anext__()) + await asyncio.sleep(0.2) + self.assertFalse(first.done(), "workflow_started came before scheduling") + client.release.set() + item = await first + self.assertTrue(client.returned.is_set()) + self.assertIsInstance(item, StreamEvent) + self.assertEqual(item.mode, WORKFLOW_STARTED) + self.assertEqual(item.data["workflow_id"], "wf-gated") + rest = [i async for i in events] + self.assertEqual(rest[-1]["type"], "workflow_completed") + + async def test_on_control_hears_of_it_after_scheduling_returned(self): + runner, client = self._runner("started-control") + seen: List[bool] = [] + client.release.set() + async for _ in runner.astream( + INPUT, + workflow_id="wf-control", + stream_mode="updates", + poll_interval=0, + on_control=lambda c: ( + seen.append(client.returned.is_set()) + if c.kind == WORKFLOW_STARTED + else None + ), + ): + pass + self.assertEqual(seen, [True]) + + async def test_a_run_that_never_scheduled_has_no_started_event(self): + runner, client = self._runner("started-never") + + def fail(**kw: Any) -> None: + raise RuntimeError("no sidecar") + + client.schedule_new_workflow = fail # type: ignore[method-assign] + items = [ + i + async for i in runner._stream_events( + INPUT, config=None, thread_id="t", workflow_id="wf-x", poll_interval=0 + ) + ] + modes = [i.mode for i in items if isinstance(i, StreamEvent)] + self.assertNotIn(WORKFLOW_STARTED, modes) + self.assertEqual(items[-1]["type"], "workflow_failed") From 77d60e3bec013b1be23e9db803726f603146937f Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 11:59:49 +0100 Subject: [PATCH 22/73] fix(langgraph): send workflow_started after scheduling returns Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 2 +- diagrid/agent/langgraph/runner.py | 29 +++++++++++++++++++++++++---- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 2c0f46a3..16696b4e 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -143,7 +143,7 @@ objects (`kind`, `data`): | `kind` | `data` | Meaning | |---|---|---| -| `workflow_started` | `{"workflow_id", "thread_id"}` | Always the first event: the ids to use with `terminate_workflow` or `get_workflow_status`. Delivered only to `on_control`, never yielded. | +| `workflow_started` | `{"workflow_id", "thread_id"}` | The first event, sent once the workflow has been scheduled, so `GET /agent/run/{workflow_id}` finds the run as soon as the event arrives (a run that could not be scheduled ends with `workflow_failed` and has none): the ids to use with `terminate_workflow` or `get_workflow_status`. Delivered only to `on_control`, never yielded. | | `node_reset` | `{"node", "step"}`, plus `"path"` for a `Send` task | A node was retried; drop its partial output. `node` and `step` are the `langgraph_node` and `langgraph_step` of that node's `messages` metadata (`step` is numbered from 1). A task started by a `Send` also carries `path`, the `langgraph_path` of its chunks (`["__pregel_push", index, false]`), which tells apart the tasks of one node in a step. A retry of a conditional edge's function also carries `branch`, the edge's function name. The function runs inside its node's activity, before the node's `updates` chunk, as in LangGraph; if it raises there, it runs again in an activity of its own, after that chunk, and only what the function sent is stale, not the node's own output. | | `stream_unavailable` | `{"workflow_id", "reason", "missing_steps", "missing_nodes"}` | The run finished but a node's chunks never arrived (see the limit below). `missing_nodes` is a list of `{"step", "node"}`, one per node of a step that streamed nothing, even when other nodes of that step did. Steps are numbered from 1, like `langgraph_step`. A `Send` task is named `node#k` there (`k` is its position among the step's `Send` tasks). | | `stream_dropped` | `{"dropped": n}` | The consumer fell behind and `n` token or custom chunks were dropped. `updates` are never dropped. | diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 0b8819d5..b934af58 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -239,6 +239,16 @@ def _run_identity( return thread, workflow_id or f"graph-{thread}-{uuid.uuid4().hex[:8]}", run_config +async def _wait_scheduled(scheduled: asyncio.Event, pump: "asyncio.Task[None]") -> bool: + """Wait until the workflow is scheduled or the pump ends; whether it was.""" + waiter = asyncio.ensure_future(scheduled.wait()) + try: + await asyncio.wait({waiter, pump}, return_when=asyncio.FIRST_COMPLETED) + finally: + waiter.cancel() + return scheduled.is_set() + + @dataclass(frozen=True) class _RunSetup: """What a run needs once its identity, config and input are settled.""" @@ -1004,10 +1014,8 @@ async def _stream_events( task: Optional["asyncio.Task[None]"] = None seen_nodes: Set[Tuple[int, str]] = set() values_sent: Set[int] = set() + scheduled = asyncio.Event() try: - # Before the pump schedules the workflow: an activity can write the - # moment it is scheduled, and the event must come before its chunks. - sink.put(started_event(workflow_id, thread_id)) task = asyncio.create_task( self._pump_run( sink, @@ -1017,8 +1025,14 @@ async def _stream_events( run_config, poll_interval, on_result, + scheduled, ) ) + # Only once the workflow exists: a client (or another replica) that + # looks the run up on this event must find it. Chunks an activity + # writes meanwhile wait in the sink, so they still come after it. + if await _wait_scheduled(scheduled, task): + yield started_event(workflow_id, thread_id) while True: item = await next_item(sink, keepalive) if isinstance(item, StreamClosed): @@ -1055,8 +1069,13 @@ async def _pump_run( run_config: Dict[str, Any], poll_interval: float, on_result: Optional[Callable[[Dict[str, Any]], None]], + scheduled: Optional[asyncio.Event] = None, ) -> None: - """Follow the run, publish its result, and close ``sink`` with the final.""" + """Follow the run, publish its result, and close ``sink`` with the final. + + ``scheduled`` is set once ``run_async`` reports the workflow started, + which it does after ``schedule_new_workflow`` returned. + """ final: Dict[str, Any] = {} result: Dict[str, Any] = {} try: @@ -1067,6 +1086,8 @@ async def _pump_run( workflow_id=workflow_id, poll_interval=poll_interval, ): + if event["type"] == "workflow_started" and scheduled is not None: + scheduled.set() fold_run_event(result, without_executed(event)) if event["type"] in FINAL_EVENTS: final = event From ab194217da3c8f8683f7b1c593fafcdd0e4105ee Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:02:03 +0100 Subject: [PATCH 23/73] test(langgraph): expect GET /agent/run/{id} to return a finished run's result Signed-off-by: Casper Nielsen --- .../agent/langgraph/test_run_status_result.py | 110 ++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 tests/agent/langgraph/test_run_status_result.py diff --git a/tests/agent/langgraph/test_run_status_result.py b/tests/agent/langgraph/test_run_status_result.py new file mode 100644 index 00000000..992cd2f8 --- /dev/null +++ b/tests/agent/langgraph/test_run_status_result.py @@ -0,0 +1,110 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``GET /agent/run/{workflow_id}`` tells how a run ended, with its result. + +A client that lost its stream polls this endpoint for the run's result, so a +finished run's body carries what a plain ``POST /agent/run`` returns for it. +The state lookup is a blocking gRPC call and runs off the event loop. +""" + +import asyncio +import json +import unittest +from types import SimpleNamespace +from typing import Any, List, Optional +from unittest import mock + +from dapr.ext.workflow import WorkflowStatus + +from diagrid.agent.langgraph.models import ChannelState, GraphWorkflowOutput + +from .streaming_helpers import _chat_graph, serve_app +from .test_runner import _RunnerTestCase + + +def _wf_state( + status: WorkflowStatus, output: Optional[GraphWorkflowOutput] = None, **kw: Any +) -> Any: + return SimpleNamespace( + runtime_status=status, + serialized_output=json.dumps(output.to_dict()) if output else None, + serialized_custom_status=None, + created_at=None, + last_updated_at=None, + failure_details=kw.get("failure_details"), + ) + + +class TestRunStatusResult(_RunnerTestCase): + def _get(self, state: Any, loops: Optional[List[bool]] = None) -> Any: + from fastapi.testclient import TestClient + + runner = _chat_graph(name="status-result") + runner._started = True + + def lookup(*, instance_id: str) -> Any: + if loops is not None: + try: + asyncio.get_running_loop() + loops.append(True) + except RuntimeError: + loops.append(False) + return state + + runner._workflow_client = mock.Mock() + runner._workflow_client.get_workflow_state.side_effect = lookup + return TestClient(serve_app(runner)).get("/agent/run/wf-1") + + def test_a_completed_run_carries_its_output(self): + out = GraphWorkflowOutput( + output={"x": 1}, + channel_state=ChannelState(values={"x": 1}), + steps=2, + status="completed", + executed=[["a"], ["b"]], + ) + resp = self._get(_wf_state(WorkflowStatus.COMPLETED, out)) + self.assertEqual(resp.status_code, 200) + body = resp.json() + self.assertEqual(body["workflow_id"], "wf-1") + self.assertEqual(body["output"], {"x": 1}) + self.assertEqual(body["steps"], 2) + self.assertEqual(body["run_status"], "completed") + # what is for the stream only stays out of it + self.assertNotIn("executed", body) + self.assertNotIn("channel_state", body) + + def test_a_run_that_ended_in_error_says_why(self): + out = GraphWorkflowOutput( + output={}, steps=1, status="error", error="Node 'a' failed: boom" + ) + body = self._get(_wf_state(WorkflowStatus.COMPLETED, out)).json() + self.assertEqual(body["run_status"], "error") + self.assertEqual(body["error"], "Node 'a' failed: boom") + + def test_a_failed_workflow_carries_its_failure(self): + state = _wf_state( + WorkflowStatus.FAILED, + failure_details=SimpleNamespace(message="activity blew up"), + ) + body = self._get(state).json() + self.assertEqual(body["error"], "activity blew up") + self.assertNotIn("output", body) + + def test_a_running_run_has_no_output_yet(self): + body = self._get(_wf_state(WorkflowStatus.RUNNING)).json() + self.assertNotIn("output", body) + self.assertIn("RUNNING", body["status"]) + + def test_an_unknown_run_is_404(self): + self.assertEqual(self._get(None).status_code, 404) + + def test_the_lookup_runs_off_the_event_loop(self): + loops: List[bool] = [] + self._get(_wf_state(WorkflowStatus.RUNNING), loops) + self.assertEqual(loops, [False]) + + +if __name__ == "__main__": + unittest.main() From 0e554d01049c5236a5cd1780dd6c5dc3d53e8135 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:02:03 +0100 Subject: [PATCH 24/73] feat(langgraph): return the run's result from GET /agent/run/{id}, off the event loop Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 17 ++++++++++++- diagrid/agent/langgraph/run_status.py | 35 +++++++++++++++++++++++++++ diagrid/agent/langgraph/runner.py | 5 ++++ 3 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 diagrid/agent/langgraph/run_status.py diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index a9e85015..6e01cb94 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -393,8 +393,22 @@ def get_workflow_status(self, workflow_id: str) -> Optional[dict[str, Any]]: "last_updated_at": ( str(state.last_updated_at) if state.last_updated_at else None ), + **self._status_result(state), } + def _status_result(self, state: Any) -> dict[str, Any]: + """What :meth:`get_workflow_status` adds about how the run ended. + + A runner whose workflow output it can read overrides this; by default a + failed workflow carries its failure message and nothing else is added. + """ + if state.runtime_status != WorkflowStatus.FAILED: + return {} + details = state.failure_details + if details is None: + return {"error": "Workflow failed"} + return {"error": str(getattr(details, "message", details))} + def terminate_workflow(self, workflow_id: str) -> None: """Terminate a running workflow. @@ -666,7 +680,8 @@ async def run_agent(request: dict) -> Any: # type: ignore[type-arg] @app.get("/agent/run/{workflow_id}") async def get_status(workflow_id: str) -> dict: # type: ignore[type-arg] - status = self.get_workflow_status(workflow_id) + # Off the loop: the state lookup is a blocking gRPC call. + status = await asyncio.to_thread(self.get_workflow_status, workflow_id) if status is None: raise HTTPException(status_code=404, detail="Workflow not found") return status diff --git a/diagrid/agent/langgraph/run_status.py b/diagrid/agent/langgraph/run_status.py new file mode 100644 index 00000000..4bf8caac --- /dev/null +++ b/diagrid/agent/langgraph/run_status.py @@ -0,0 +1,35 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""How a LangGraph run ended, as ``GET /agent/run/{workflow_id}`` reports it.""" + +import json +from typing import Any, Dict + +from dapr.ext.workflow import WorkflowStatus + +from .models import GraphWorkflowOutput + + +def completed_result(state: Any) -> Dict[str, Any]: + """The result of a completed workflow: what a plain ``POST`` returns for it. + + ``output`` and ``steps`` as the run reported them, ``run_status`` (the + graph's own ``completed``, ``error`` or ``max_steps_reached``; ``status`` + stays the workflow's runtime status) and ``error`` when there is one. What + the workflow output holds for the stream only (``executed``, the channel + state) is left out. Empty for a workflow that has not completed. + """ + if state.runtime_status != WorkflowStatus.COMPLETED: + return {} + raw = state.serialized_output + if not raw: + return {} + data = json.loads(raw) if isinstance(raw, str) else raw + output = GraphWorkflowOutput.from_dict(data) + return { + "output": output.output, + "steps": output.steps, + "run_status": output.status, + **({"error": output.error} if output.error else {}), + } diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index b934af58..ca97c334 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -73,6 +73,7 @@ without_executed, ) from .langsmith_trace import ParentTrace, start_parent_trace +from .run_status import completed_result from .limits import StepBound, step_bound from .workflow import ( IS_LAST_STEP, @@ -1115,6 +1116,10 @@ async def _release_pump( task.cancel() await asyncio.gather(task, return_exceptions=True) + def _status_result(self, state: Any) -> Dict[str, Any]: + """A completed run's result, or a failed workflow's error.""" + return completed_result(state) or super()._status_result(state) + def _is_root_state(self) -> bool: """Whether the graph's whole state is one ``__root__`` channel.""" channels = getattr(getattr(self._graph, "builder", None), "channels", None) From 8020d0359723db0b213cdce42ea5a4726fe7609c Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:04:32 +0100 Subject: [PATCH 25/73] test(langgraph): expect routers that streamed nothing in missing_nodes Signed-off-by: Casper Nielsen --- .../test_streaming_missing_routers.py | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 tests/agent/langgraph/test_streaming_missing_routers.py diff --git a/tests/agent/langgraph/test_streaming_missing_routers.py b/tests/agent/langgraph/test_streaming_missing_routers.py new file mode 100644 index 00000000..8c4dd261 --- /dev/null +++ b/tests/agent/langgraph/test_streaming_missing_routers.py @@ -0,0 +1,121 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A router that ran in its own activity is listed in ``missing_nodes`` when +none of its chunks arrived. + +A conditional edge's function runs in the condition activity when it is a +START edge, when it raised inside its node's activity, or for an instance +older than routing inside the node. The workflow reports each such call on +its output (``branches``); the router's streamer marks it done in the sink +(an internal ``branch_done`` that never reaches a client), so a router that +ran in another process is reported like a node that did. +""" + +import unittest +from typing import Any, List + +from langgraph.graph import END, START, StateGraph +from typing_extensions import TypedDict + +from diagrid.agent.core.workflow.stream import BRANCH_DONE, StreamEvent +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.streaming import stream_unavailable_event + +from .golden_harness import _FakeDaprTest, _runner +from .streaming_helpers import INPUT, _collect +from .test_runner import _RunnerTestCase, _run +from .test_streaming_events import _chunk, _FakeRun + +ROUTER = "a:branch:route" + + +def _final(**extra: Any) -> dict: + return {"type": "workflow_completed", "steps": 1, "executed": [["a"]], **extra} + + +class TestStreamUnavailableWithRouters(unittest.TestCase): + def test_a_router_whose_chunks_never_arrived_is_missing(self): + event = stream_unavailable_event( + _final(branches=[[0, ROUTER]]), {(0, "a")}, "wf" + ) + assert event is not None + self.assertEqual(event.data["missing_nodes"], [{"step": 1, "node": ROUTER}]) + self.assertEqual(event.data["missing_steps"], [1]) + + def test_a_router_marked_done_is_not_missing(self): + seen = {(0, "a"), (0, ROUTER)} + self.assertIsNone( + stream_unavailable_event(_final(branches=[[0, ROUTER]]), seen, "wf") + ) + + def test_a_start_router_is_numbered_as_the_input_step(self): + event = stream_unavailable_event( + _final(branches=[[-1, "__start__:branch:pick"]]), {(0, "a")}, "wf" + ) + assert event is not None + self.assertEqual( + event.data["missing_nodes"], [{"step": 0, "node": "__start__:branch:pick"}] + ) + + +class TestBranchDoneInTheStream(_FakeRun): + async def test_branch_done_marks_the_router_seen_and_is_not_yielded(self): + done = StreamEvent("wf", 0, ROUTER, "r1", 0, (), BRANCH_DONE, None) + runner = self._runner( + "router-done", + [_chunk(0, "a", "updates"), done], + executed=[["a"]], + branches=[[0, ROUTER]], + ) + items = await _collect( + runner.astream(INPUT, stream_mode=["updates", "custom", "messages"]) + ) + self.assertEqual([m for m, _ in items], ["updates"]) + + async def test_a_router_without_branch_done_is_reported(self): + runner = self._runner( + "router-gone", + [_chunk(0, "a", "updates")], + executed=[["a"]], + branches=[[0, ROUTER]], + ) + items = await _collect(runner.astream(INPUT, stream_mode=["updates"])) + self.assertEqual(items[-1][0], "stream_unavailable") + self.assertEqual(items[-1][1]["missing_nodes"], [{"step": 1, "node": ROUTER}]) + + +class _S(TypedDict, total=False): + log: List[str] + + +def _start_router_graph() -> Any: + def pick(state: _S) -> str: + return "a" + + graph = StateGraph(_S) + graph.add_node("a", lambda s: {"log": ["a"]}) + graph.add_conditional_edges(START, pick, ["a"]) + graph.add_edge("a", END) + return graph.compile() + + +class TestWorkflowReportsBranches(_RunnerTestCase): + def test_a_start_router_is_on_the_output(self): + runner = DaprWorkflowGraphRunner(graph=_start_router_graph(), name="br-out") + out = _run(runner, {"log": []}) + self.assertEqual( + out.branches, [[-1, "__start__:branch:__start___pick_condition"]] + ) + + +class TestRouterStreamedHere(_FakeDaprTest): + async def test_a_router_that_ran_here_is_not_reported(self): + runner = _runner(_start_router_graph(), "br-here") + items = await _collect( + runner.astream( + {"log": []}, workflow_id="wf-br-here", stream_mode=["updates"] + ) + ) + self.assertNotIn("stream_unavailable", [m for m, _ in items]) + self.assertIn("updates", [m for m, _ in items]) From 6e082e50ae0e02552309c198b2d02dd4d304b90b Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:04:32 +0100 Subject: [PATCH 26/73] feat(langgraph): report routers that ran elsewhere in stream_unavailable Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/stream.py | 9 ++++--- diagrid/agent/langgraph/README.md | 2 +- diagrid/agent/langgraph/models.py | 7 +++++ diagrid/agent/langgraph/runner.py | 11 ++++++++ diagrid/agent/langgraph/stream_events.py | 3 ++- diagrid/agent/langgraph/streaming.py | 34 +++++++++++++++++++----- diagrid/agent/langgraph/workflow.py | 11 +++++++- 7 files changed, 64 insertions(+), 13 deletions(-) diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index 99d9c5fc..759174a8 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -38,9 +38,12 @@ WORKFLOW_STARTED = "workflow_started" # Events about the stream itself, delivered whatever stream modes were asked for. CONTROL_MODES = (WORKFLOW_STARTED, NODE_RESET, STREAM_UNAVAILABLE) -# What a full buffer never drops: the control events and node updates, which are -# a stream mode of their own but cannot be re-sent either. -_KEPT_WHEN_FULL = (*CONTROL_MODES, UPDATES) +#: Internal marker: a conditional edge's function finished streaming here. It +#: tells the stream which routers ran in this process and never reaches a client. +BRANCH_DONE = "branch_done" +# What a full buffer never drops: the control events, node updates and router +# markers, which cannot be re-sent either. +_KEPT_WHEN_FULL = (*CONTROL_MODES, UPDATES, BRANCH_DONE) #: Seconds an idle SSE stream waits before it sends a keepalive comment, so a #: proxy or load balancer does not cut it during a long tool call or LLM gap. diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 16696b4e..16b4913d 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -145,7 +145,7 @@ objects (`kind`, `data`): |---|---|---| | `workflow_started` | `{"workflow_id", "thread_id"}` | The first event, sent once the workflow has been scheduled, so `GET /agent/run/{workflow_id}` finds the run as soon as the event arrives (a run that could not be scheduled ends with `workflow_failed` and has none): the ids to use with `terminate_workflow` or `get_workflow_status`. Delivered only to `on_control`, never yielded. | | `node_reset` | `{"node", "step"}`, plus `"path"` for a `Send` task | A node was retried; drop its partial output. `node` and `step` are the `langgraph_node` and `langgraph_step` of that node's `messages` metadata (`step` is numbered from 1). A task started by a `Send` also carries `path`, the `langgraph_path` of its chunks (`["__pregel_push", index, false]`), which tells apart the tasks of one node in a step. A retry of a conditional edge's function also carries `branch`, the edge's function name. The function runs inside its node's activity, before the node's `updates` chunk, as in LangGraph; if it raises there, it runs again in an activity of its own, after that chunk, and only what the function sent is stale, not the node's own output. | -| `stream_unavailable` | `{"workflow_id", "reason", "missing_steps", "missing_nodes"}` | The run finished but a node's chunks never arrived (see the limit below). `missing_nodes` is a list of `{"step", "node"}`, one per node of a step that streamed nothing, even when other nodes of that step did. Steps are numbered from 1, like `langgraph_step`. A `Send` task is named `node#k` there (`k` is its position among the step's `Send` tasks). | +| `stream_unavailable` | `{"workflow_id", "reason", "missing_steps", "missing_nodes"}` | The run finished but a node's chunks never arrived (see the limit below). `missing_nodes` is a list of `{"step", "node"}`, one per node of a step that streamed nothing, even when other nodes of that step did. Steps are numbered from 1, like `langgraph_step`. A `Send` task is named `node#k` there (`k` is its position among the step's `Send` tasks). A conditional edge's function that ran in an activity of its own (a START edge's, or one that raised inside its node's activity and ran again) is listed as `node:branch:` (`node#k:branch:` after a `Send` task, `__start__:branch:` at step 0 for a START edge), where `` is the name the runner registered the edge under. | | `stream_dropped` | `{"dropped": n}` | The consumer fell behind and `n` token or custom chunks were dropped. `updates` are never dropped. | Pass `on_control=callback` to `astream` to receive them. A list of modes also diff --git a/diagrid/agent/langgraph/models.py b/diagrid/agent/langgraph/models.py index a2054fa4..df61e17b 100644 --- a/diagrid/agent/langgraph/models.py +++ b/diagrid/agent/langgraph/models.py @@ -539,6 +539,9 @@ class GraphWorkflowOutput: executed: The nodes that ran in each step, in order. Lets a streaming consumer tell which node's chunks never arrived. ``None`` for an output written before the field existed. + branches: The conditional edges evaluated in their own activity, as + ``[step, sink key]`` (step ``-1`` for a START edge), for the same + purpose. ``None`` when there were none. """ output: Dict[str, Any] = field(default_factory=dict) @@ -547,6 +550,7 @@ class GraphWorkflowOutput: status: str = "completed" error: Optional[str] = None executed: Optional[List[List[str]]] = None + branches: Optional[List[List[Any]]] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -560,6 +564,8 @@ def to_dict(self) -> Dict[str, Any]: } if self.executed is not None: data["executed"] = self.executed + if self.branches: + data["branches"] = self.branches return data @classmethod @@ -574,4 +580,5 @@ def from_dict(cls, data: Dict[str, Any]) -> "GraphWorkflowOutput": status=data.get("status", "completed"), error=data.get("error"), executed=data.get("executed"), + branches=data.get("branches"), ) diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index ca97c334..dbdfdcbb 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -30,6 +30,7 @@ from diagrid.agent.core.workflow import BaseWorkflowRunner from diagrid.agent.core.workflow.runner import fold_run_event from diagrid.agent.core.workflow.stream import ( + BRANCH_DONE, CONTROL_MODES, KEEPALIVE_EVENT, WORKFLOW_STARTED, @@ -50,6 +51,7 @@ WaitingEdgeConfig, ) from .streaming import ( + BRANCHES_KEY, EXECUTED_KEY, FINAL_STATE_KEY, STREAM_RUN_KEY, @@ -899,6 +901,11 @@ def _parse_output(wf_id: str, output_dict: dict) -> dict: # type: ignore[type-a "status": output.status, **({"error": output.error} if output.error else {}), **({EXECUTED_KEY: output.executed} if with_executed else {}), + **( + {BRANCHES_KEY: output.branches} + if streamed and output.branches + else {} + ), # the state it ended with, for the stream's last values chunk **( {FINAL_STATE_KEY: output.channel_state.to_dict()} @@ -1049,6 +1056,10 @@ async def _stream_events( ): yield event return + if isinstance(item, StreamEvent) and item.mode == BRANCH_DONE: + # a router that ran here: internal, never sent on + seen_nodes.add((item.step, item.node)) + continue if isinstance(item, StreamEvent) and item.mode == UPDATES: seen_nodes.add((item.step, item.node)) if isinstance(item, StreamEvent) and item.mode == VALUES: diff --git a/diagrid/agent/langgraph/stream_events.py b/diagrid/agent/langgraph/stream_events.py index 34a6c496..68270e46 100644 --- a/diagrid/agent/langgraph/stream_events.py +++ b/diagrid/agent/langgraph/stream_events.py @@ -19,6 +19,7 @@ from .stream_values import final_values from .streaming import ( + BRANCHES_KEY, EXECUTED_KEY, FINAL_STATE_KEY, GraphRunError, @@ -108,7 +109,7 @@ def started_event(workflow_id: str, thread_id: str) -> Any: ) -_STREAM_ONLY_KEYS = (EXECUTED_KEY, FINAL_STATE_KEY) +_STREAM_ONLY_KEYS = (EXECUTED_KEY, BRANCHES_KEY, FINAL_STATE_KEY) def without_executed(event: Dict[str, Any]) -> Dict[str, Any]: diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index 9048585b..ef46aad0 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -22,6 +22,7 @@ from langgraph.errors import GraphRecursionError from diagrid.agent.core.workflow.stream import ( + BRANCH_DONE, STREAM_UNAVAILABLE, UPDATES, VALUES, @@ -62,6 +63,9 @@ # Key of the run_async terminal event that lists the nodes each step ran. It # serves the stream (see stream_unavailable_event) and is not part of a result. EXECUTED_KEY = "executed" +# Key of the run_async terminal event that lists the conditional edges evaluated +# in their own activity, as ``[step, sink key]``; for the stream only, too. +BRANCHES_KEY = "branches" # Key of the run_async terminal event of a streamed run that holds the state it # ended with, for the stream's last ``values`` chunk; also not part of a result. FINAL_STATE_KEY = "channel_state" @@ -353,6 +357,11 @@ def task_finished(self, writes: List[Tuple[str, Any]]) -> None: """Send the task's result event: its writes, after its ``updates`` chunk.""" self._emit_task(task_result(self._event_task_id, self._node, writes)) + def branch_finished(self) -> None: + """Mark this conditional edge's function as done streaming here.""" + if self._branch: + self._emit((), BRANCH_DONE, None) + def updates(self, writes: List[Tuple[str, Any]]) -> None: """Emit the node's ``(channel, value)`` writes as ``{node: update}``. @@ -566,16 +575,26 @@ def normalize_final( ) +def _branches(final: Dict[str, Any]) -> List[Tuple[int, str]]: + """The ``(step, sink key)`` of each conditional edge run in its own activity.""" + branches = final.get(BRANCHES_KEY) + if not isinstance(branches, list): + return [] + return [(int(step), str(key)) for step, key in branches] + + def stream_unavailable_event( final: Dict[str, Any], seen: Set[Tuple[int, str]], workflow_id: str ) -> Optional[StreamEvent]: """The ``stream_unavailable`` event for a finished run, if it applies. - ``seen`` holds the ``(step, node)`` pairs whose ``updates`` chunk arrived; - every node that runs here sends one when it finishes, so an executed node - without one had its activity (or its last attempt) elsewhere, even when - other nodes of its step streamed here. A final without ``executed`` is - judged per step instead. A run + ``seen`` holds the ``(step, node)`` pairs whose ``updates`` chunk (or, for + a conditional edge, ``branch_done`` marker) arrived; every node that runs + here sends one when it finishes, so an executed node without one had its + activity (or its last attempt) elsewhere, even when other nodes of its step + streamed here. The conditional edges the workflow evaluated in their own + activity (``branches``) are judged the same way. A final without + ``executed`` is judged per step instead. A run that failed is just a failure, and one with no step count has nothing to report. """ @@ -585,10 +604,11 @@ def stream_unavailable_event( executed = final.get("executed") missing_nodes: List[Dict[str, Any]] = [] if isinstance(executed, list): + ran = [(step, node) for step, nodes in enumerate(executed) for node in nodes] + ran.extend(_branches(final)) missing_nodes = [ {"step": display_step(step), "node": node} - for step, nodes in enumerate(executed) - for node in nodes + for step, node in sorted(ran, key=lambda pair: pair[0]) if (step, node) not in seen ] missing = sorted({m["step"] for m in missing_nodes}) diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 6dc0b9e7..eb3e70c1 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -521,6 +521,10 @@ class _Run: executed: List[List[str]] = field(default_factory=list) #: Deferred nodes that were triggered and wait for nothing else to be pending. held: List[str] = field(default_factory=list) + #: The conditional edges evaluated in their own activity, ``[step, sink + #: key]``, so a streaming consumer can tell which router's chunks never + #: arrived. + branches: List[List[Any]] = field(default_factory=list) @property def output_channels(self) -> Optional[List[str]]: @@ -542,6 +546,7 @@ def finish( channel_state=self.channel_state, steps=step, executed=self.executed, + branches=self.branches or None, status=status, **({"error": error} if error else {}), ).to_dict() @@ -949,6 +954,7 @@ def _follow_edge( # a START edge reads the input: the state of the run's first values chunk output_channels=run.output_channels if source_node == START else None, ) + run.branches.append([step, _branch_key(cond_input)]) # By name, so the runner's own activity (the one that knows its stream # registry) runs, not the module-level function. cond_result = yield run.ctx.call_activity( @@ -1640,7 +1646,10 @@ def run() -> Any: # Runnable.invoke only sets the ambient config when tracing, and a plain # function never does: get_stream_writer() and the stream handler need it. with set_config_context(config) as ctx_: # type: ignore[arg-type] - return ctx_.run(run) + result = ctx_.run(run) + if streamer: + streamer.branch_finished() + return result def evaluate_condition_activity( From 199b73ed9a3a41ecad3109717c630ec4c02da469 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:07:02 +0100 Subject: [PATCH 27/73] test(langgraph): expect native langgraph_* task metadata without a stream Signed-off-by: Casper Nielsen --- tests/agent/langgraph/test_task_metadata.py | 105 ++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 tests/agent/langgraph/test_task_metadata.py diff --git a/tests/agent/langgraph/test_task_metadata.py b/tests/agent/langgraph/test_task_metadata.py new file mode 100644 index 00000000..b3114c34 --- /dev/null +++ b/tests/agent/langgraph/test_task_metadata.py @@ -0,0 +1,105 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A node sees the ``langgraph_*`` metadata native LangGraph gives its task. + +Whether the run is streamed or not: the keys come from the config every node +and router runs under, not only from the stream handler. +""" + +import re +from typing import Any, Dict, List + +from langchain_core.runnables import RunnableConfig +from langgraph.config import get_config +from langgraph.graph import END, START, StateGraph +from typing_extensions import TypedDict + +from .golden_harness import _FakeDaprTest, _runner +from .streaming_helpers import _collect + +_NS = re.compile(r"^(\w+):.+$") + + +class _S(TypedDict, total=False): + log: List[str] + + +def _graph(seen: Dict[str, Dict[str, Any]]) -> Any: + def a(state: _S, config: RunnableConfig) -> dict: + seen["a"] = dict(config["metadata"]) + return {"log": ["a"]} + + def b(state: _S) -> dict: + seen["b"] = dict(get_config()["metadata"]) + return {"log": ["b"]} + + def route(state: _S) -> str: + seen["route"] = dict(get_config()["metadata"]) + return "b" + + graph = StateGraph(_S) + graph.add_node("a", a) + graph.add_node("b", b) + graph.add_edge(START, "a") + graph.add_conditional_edges("a", route, ["b"]) + graph.add_edge("b", END) + return graph.compile() + + +def _comparable(metadata: Dict[str, Any]) -> Dict[str, Any]: + """The metadata with task ids (uuids natively, integers here) left out.""" + out = dict(metadata) + out.pop("checkpoint_ns", None) + ns = out.get("langgraph_checkpoint_ns") + if isinstance(ns, str): + out["langgraph_checkpoint_ns"] = _NS.sub(r"\1:", ns) + return out + + +CONFIG = {"configurable": {"thread_id": "t1"}, "metadata": {"foo": "bar"}} + + +class TestTaskMetadata(_FakeDaprTest): + def _native(self) -> Dict[str, Dict[str, Any]]: + seen: Dict[str, Dict[str, Any]] = {} + _graph(seen).invoke({"log": []}, CONFIG) + return seen + + def test_an_invoked_run_matches_native(self): + want = self._native() + seen: Dict[str, Dict[str, Any]] = {} + runner = _runner(_graph(seen), "meta-invoke") + runner.invoke( + {"log": []}, + thread_id="t1", + config={"metadata": {"foo": "bar"}}, + poll_interval=0.01, + timeout=10, + ) + self.assertEqual(set(seen), {"a", "b", "route"}) + for name in seen: + with self.subTest(task=name): + self.assertEqual(_comparable(seen[name]), _comparable(want[name])) + + async def test_a_streamed_run_sets_the_same_keys(self): + want = self._native() + seen: Dict[str, Dict[str, Any]] = {} + runner = _runner(_graph(seen), "meta-stream") + await _collect( + runner.astream( + {"log": []}, + thread_id="t1", + config={"metadata": {"foo": "bar"}}, + stream_mode="updates", + poll_interval=0.01, + ) + ) + keys = [k for k in want["a"] if k.startswith("langgraph_")] + for name in ("a", "b", "route"): + with self.subTest(task=name): + got = _comparable(seen[name]) + self.assertEqual( + {k: got.get(k) for k in keys}, + {k: _comparable(want[name])[k] for k in keys}, + ) From 988d118e2a7ae8e66b0ef3d10afe629e748809a6 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:07:03 +0100 Subject: [PATCH 28/73] feat(langgraph): set langgraph_* metadata on every task's config, streamed or not Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/streaming.py | 39 ++++------- diagrid/agent/langgraph/task_identity.py | 86 ++++++++++++++++++++++++ diagrid/agent/langgraph/workflow.py | 37 +++++++++- 3 files changed, 134 insertions(+), 28 deletions(-) create mode 100644 diagrid/agent/langgraph/task_identity.py diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index ef46aad0..7a6a31d6 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -31,6 +31,7 @@ display_step, ) +from .task_identity import TaskIdentity, configurable_metadata from .task_events import ( DEBUG, TASKS, @@ -57,9 +58,6 @@ ), } -# Configurable keys LangChain never copies into metadata (they are secrets). -_UNTRACED_CONFIGURABLE = frozenset(("api_key",)) - # Key of the run_async terminal event that lists the nodes each step ran. It # serves the stream (see stream_unavailable_event) and is not part of a result. EXECUTED_KEY = "executed" @@ -191,6 +189,13 @@ def __init__( self._node = node self._task_id = task_id self._triggers = tuple(triggers) if triggers else None + self._identity = TaskIdentity( + step=step, + node=node, + task_id=task_id, + triggers=self._triggers, + path=self._path, + ) self._attempt_id = uuid.uuid4().hex self._seq = itertools.count() # A node may emit from several threads (parallel tool calls); seq is @@ -204,14 +209,8 @@ def __init__( def metadata(self) -> Dict[str, Any]: """The ``langgraph_*`` keys the Pregel loop sets on a task's config.""" return { - # Pregel numbers the first node after START as step 1. - "langgraph_step": display_step(self._step), - "langgraph_node": self._node, - # Every trigger channel of the node, sorted, as Pregel lists them. - "langgraph_triggers": self._triggers or (f"branch:to:{self._node}",), - "langgraph_path": self._path or ("__pregel_pull", self._node), - "langgraph_checkpoint_ns": f"{self._node}:{self._task_id}", - "checkpoint_ns": f"{self._node}:{self._task_id}", + **self._identity.metadata(), + "checkpoint_ns": self._identity.checkpoint_ns, } def _emit(self, ns: Tuple[str, ...], mode: str, data: Any) -> None: @@ -408,22 +407,8 @@ def patch_config(self, config: Dict[str, Any]) -> Dict[str, Any]: return patched def _configurable_metadata(self, config: Dict[str, Any]) -> Dict[str, Any]: - """What native LangGraph copies from ``configurable`` into metadata. - - ``thread_id`` and the other primitive, non-private configurable values, - so a client keying on ``metadata["thread_id"]`` sees what it would - from ``CompiledStateGraph.astream``. - """ - derived = { - key: value - for key, value in (config.get("configurable") or {}).items() - if not key.startswith("__") - and isinstance(value, (str, int, float, bool)) - and key not in _UNTRACED_CONFIGURABLE - } - if self._thread_id: - derived.setdefault("thread_id", self._thread_id) - return derived + """What native LangGraph copies from ``configurable`` into metadata.""" + return configurable_metadata(config, self._thread_id) def normalize_stream_mode(stream_mode: Any) -> Tuple[List[str], bool]: diff --git a/diagrid/agent/langgraph/task_identity.py b/diagrid/agent/langgraph/task_identity.py new file mode 100644 index 00000000..6884861d --- /dev/null +++ b/diagrid/agent/langgraph/task_identity.py @@ -0,0 +1,86 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The ``langgraph_*`` metadata the Pregel loop gives every task. + +A node and its routers run under a config built from these keys whether the +run is streamed or not, as they do in native LangGraph; the stream handler +reads the same keys for its chunks. +""" + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple + +from diagrid.agent.core.workflow.stream import display_step + +if TYPE_CHECKING: + from .streaming import StaticConfig + +# Configurable keys LangChain never copies into metadata (they are secrets). +_UNTRACED_CONFIGURABLE = frozenset(("api_key",)) + + +@dataclass(frozen=True) +class TaskIdentity: + """Which task of the run a node (or a router of it) executes as.""" + + step: int + node: str + task_id: Any + #: Every trigger channel of the node, sorted, as Pregel lists them. + triggers: Optional[Tuple[str, ...]] = None + #: The task's ``langgraph_path`` when it is not the node's own (a ``Send``). + path: Optional[Tuple[Any, ...]] = None + + @property + def checkpoint_ns(self) -> str: + return f"{self.node}:{self.task_id}" + + def metadata(self) -> Dict[str, Any]: + """The ``langgraph_*`` keys Pregel sets on the task's config metadata.""" + return { + # Pregel numbers the first node after START as step 1. + "langgraph_step": display_step(self.step), + "langgraph_node": self.node, + "langgraph_triggers": self.triggers or (f"branch:to:{self.node}",), + "langgraph_path": self.path or ("__pregel_pull", self.node), + "langgraph_checkpoint_ns": self.checkpoint_ns, + } + + def config_metadata( + self, + config: Dict[str, Any], + static: "StaticConfig", + thread_id: Optional[str], + ) -> Dict[str, Any]: + """The metadata a task's config carries, as native LangGraph builds it. + + The primitive configurable values, then the graph's, the caller's and + the node's own metadata, then the task's ``langgraph_*`` keys. + """ + return { + **configurable_metadata(config, thread_id), + **static.metadata(config.get("metadata")), + **self.metadata(), + } + + +def configurable_metadata( + config: Dict[str, Any], thread_id: Optional[str] +) -> Dict[str, Any]: + """What native LangGraph copies from ``configurable`` into metadata. + + ``thread_id`` and the other primitive, non-private configurable values, + so a client keying on ``metadata["thread_id"]`` sees what it would from + ``CompiledStateGraph.astream``. + """ + derived = { + key: value + for key, value in (config.get("configurable") or {}).items() + if not key.startswith("__") + and isinstance(value, (str, int, float, bool)) + and key not in _UNTRACED_CONFIGURABLE + } + if thread_id: + derived.setdefault("thread_id", thread_id) + return derived diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index eb3e70c1..b2778ae8 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -66,6 +66,7 @@ from .node_routes import route_in_node from .stream_values import state_values from .streaming import STREAM_RUN_KEY, NodeStreamer, StaticConfig +from .task_identity import TaskIdentity from .values import ( coerce_to_default, decode_value, @@ -1189,6 +1190,7 @@ def _node_config( ctx: WorkflowActivityContext, name: str, streamer: Optional[NodeStreamer], + identity: Optional[TaskIdentity] = None, ) -> Dict[str, Any]: """The config a node or conditional edge runs under, built from ``base``. @@ -1197,12 +1199,16 @@ def _node_config( (``configurable["thread_id"]``), a ``Runtime`` (deep agent middleware requires one, and sandbox/state backends resolve the owning workflow from ``runtime.execution_info.thread_id``) and, in a streamed run, the stream - handler. + handler. ``identity`` sets the task's ``langgraph_*`` metadata, streamed + run or not, as the Pregel loop sets it on every task. """ config = dict(base) if base else {} config[CONF] = dict(config.get(CONF) or {}) resolved = thread_id or config.get("thread_id") or getattr(ctx, "workflow_id", None) config[CONF].setdefault("thread_id", resolved) + if identity is not None: + static = get_node_static_config(identity.node) or StaticConfig() + config["metadata"] = identity.config_metadata(config, static, resolved) if CONFIG_KEY_RUNTIME not in config[CONF]: config[CONF][CONFIG_KEY_RUNTIME] = _build_node_runtime( resolved, ctx, name, streamer.writer if streamer else None @@ -1210,6 +1216,30 @@ def _node_config( return streamer.patch_config(config) if streamer else config +def _task_identity( + ctx: WorkflowActivityContext, node_name: str, step: int, send_index: Optional[int] +) -> TaskIdentity: + """The task a node (or one of its routers) runs as, as Pregel names it.""" + return TaskIdentity( + step=step, + node=node_name, + task_id=getattr(ctx, "task_id", ""), + triggers=_task_triggers(node_name, send_index), + path=None if send_index is None else (PUSH_TRIGGER, send_index, False), + ) + + +def _call_identity(call: _NodeCall) -> TaskIdentity: + """The task this node execution runs as.""" + send = call.node_input.send + return _task_identity( + call.ctx, + call.node_name, + call.node_input.step or 0, + None if send is None else send["slot"], + ) + + def _runnable_config(call: _NodeCall) -> Dict[str, Any]: """The config a Runnable node is invoked with.""" config = _node_config( @@ -1218,6 +1248,7 @@ def _runnable_config(call: _NodeCall) -> Dict[str, Any]: ctx=call.ctx, name=call.node_name, streamer=call.streamer, + identity=_call_identity(call), ) # Inject CONFIG_KEY_READ / CONFIG_KEY_SEND so that deepagents # StateBackend (sandbox tools) can read/write the "files" @@ -1269,6 +1300,7 @@ def _plain_node_config(call: _NodeCall) -> Dict[str, Any]: ctx=call.ctx, name=call.node_name, streamer=call.streamer, + identity=_call_identity(call), ) @@ -1634,6 +1666,9 @@ def _call_condition( ctx=ctx, name=cond_input.condition_name, streamer=streamer, + identity=_task_identity( + ctx, cond_input.source_node, cond_input.step or 0, cond_input.send_slot + ), ) def run() -> Any: From cb15f1d8cee95aa276858d9940750f7b276b4766 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:07:18 +0100 Subject: [PATCH 29/73] docs(langgraph): describe running behind a proxy and what to do when a stream drops Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 16b4913d..67078b9e 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -219,6 +219,26 @@ sent as `{"unserializable": ""}`, counted in the final event's removed before the graph (or your `input_mapper`) sees it. On a plain request they are left alone. +`GET /agent/run/{workflow_id}` reports a run by the id in `workflow_started`: +`status` is the workflow's runtime status, and once the run has completed the +body also has the `output` and `steps` a plain `POST /agent/run` returns for +it, `run_status` (`completed`, `error` or `max_steps_reached`) and `error` +when there is one. A workflow that failed carries its `error`. An unknown id is +a `404`. + +#### Behind a proxy + +Anything between the client and the app (nginx, an ingress, a load balancer) +must pass the response through as it is written, not buffer it. The response +already sends `X-Accel-Buffering: no` and `Cache-Control: no-cache`, which +nginx and the nginx ingress honour; for any other proxy, turn response +buffering off for `POST /agent/run`, and keep its idle timeout above 15 +seconds so the keepalive comments hold the connection open. A client should +expect events to arrive one by one as the nodes produce them, comment lines +(`: keepalive`) to ignore while a node is quiet, and the stream to end right +after `workflow_completed` or `workflow_failed`. If tokens arrive all at once +at the end of the run, something in front of the app is buffering. + ### Limits - **Single replica.** Chunks travel from the activity to the HTTP connection @@ -227,6 +247,16 @@ they are left alone. activity logs a warning once per run and the stream sends `stream_unavailable` before it ends. The run and its result are not affected. Delivery across replicas is not implemented yet. +- **A dropped connection cannot be resumed.** If the connection drops (a + network failure, a proxy timeout, the app's process restarting), the events + sent while the client was away are lost and the stream cannot be reopened. + The run is not affected: Dapr keeps running it, on this process or after a + restart. The client polls `GET /agent/run/{workflow_id}`, with the id from + `workflow_started`, until the run is finished, and reads the result from + that response. +- **Node code must not count attempts in process memory.** A retried node may + run in another process, so a counter kept in a module or a closure does not + see the earlier attempt. Keep such state in the graph's state or a store. - **A disconnect does not cancel the run.** The stream closes but the Dapr workflow runs to completion; `terminate_workflow` stops it, and the ids in `workflow_started` let a client that lost its connection `GET From b1e64abd3504a1be45f21bca49567c17c8b7bc06 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:09:46 +0100 Subject: [PATCH 30/73] test(langgraph): expect thread_id to carry state between runs with a checkpointer Signed-off-by: Casper Nielsen --- tests/agent/langgraph/test_state.py | 10 +- .../langgraph/test_thread_continuation.py | 118 ++++++++++++++++++ tests/agent/langgraph/test_thread_replay.py | 81 ++++++++++++ tests/agent/langgraph/thread_helpers.py | 73 +++++++++++ 4 files changed, 277 insertions(+), 5 deletions(-) create mode 100644 tests/agent/langgraph/test_thread_continuation.py create mode 100644 tests/agent/langgraph/test_thread_replay.py create mode 100644 tests/agent/langgraph/thread_helpers.py diff --git a/tests/agent/langgraph/test_state.py b/tests/agent/langgraph/test_state.py index 7a0adb8b..abdd46cb 100644 --- a/tests/agent/langgraph/test_state.py +++ b/tests/agent/langgraph/test_state.py @@ -26,7 +26,7 @@ def test_save_checkpoint(self): # Should save the checkpoint store.save.assert_any_call( - "langgraph-t1-checkpoint-cp1", + "langgraph:t1:checkpoint:cp1", { "thread_id": "t1", "checkpoint_id": "cp1", @@ -37,7 +37,7 @@ def test_save_checkpoint(self): ) # Should save the index store.save.assert_any_call( - "langgraph-t1-index", + "langgraph:t1:index", {"checkpoints": ["cp1"], "latest": "cp1"}, ) @@ -47,7 +47,7 @@ def test_load_checkpoint_by_id(self): result = cp.load_checkpoint("t1", "cp1") - store.get.assert_called_with("langgraph-t1-checkpoint-cp1") + store.get.assert_called_with("langgraph:t1:checkpoint:cp1") self.assertEqual(result, {"channel_values": {"messages": ["hi"]}}) def test_load_latest_checkpoint(self): @@ -94,10 +94,10 @@ def test_delete_checkpoint(self): cp.delete_checkpoint("t1", "cp2") - store.delete.assert_called_once_with("langgraph-t1-checkpoint-cp2") + store.delete.assert_called_once_with("langgraph:t1:checkpoint:cp2") # Should update index store.save.assert_called_with( - "langgraph-t1-index", + "langgraph:t1:index", {"checkpoints": ["cp1"], "latest": "cp1"}, ) diff --git a/tests/agent/langgraph/test_thread_continuation.py b/tests/agent/langgraph/test_thread_continuation.py new file mode 100644 index 00000000..0c9ef9e0 --- /dev/null +++ b/tests/agent/langgraph/test_thread_continuation.py @@ -0,0 +1,118 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A ``thread_id`` carries the graph's state from one run to the next. + +With a checkpointer (the runner's, the graph's own, or by default the Dapr +state store the app has), the second run on a thread starts from the state +the first one ended with, as native LangGraph does with a checkpointer. The +thread's state is read and written by activities, never by workflow code. +""" + +from typing import Any, List +from unittest import mock + +from langgraph.checkpoint.memory import MemorySaver + +from diagrid.agent.core.discovery import DiscoveredComponents +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.state import DaprMemoryCheckpointer + +from .golden_harness import _FakeDaprTest, _FakeWorkflowClient +from .streaming_helpers import _collect +from .thread_helpers import MemoryStateStore, chat_graph, shape, turn + +HI = ("human", "hi") +AGAIN = ("human", "again") +ANSWER = ("ai", "Hello world") + + +def _runner(graph: Any, name: str, **kwargs: Any) -> DaprWorkflowGraphRunner: + runner = DaprWorkflowGraphRunner(graph=graph, name=name, **kwargs) + runner._started = True + runner._workflow_client = _FakeWorkflowClient(runner) # type: ignore[assignment] + return runner + + +def _invoke(runner: DaprWorkflowGraphRunner, text: str, thread: str) -> Any: + return runner.invoke(turn(text), thread_id=thread, poll_interval=0.01, timeout=10) + + +class TestThreadContinuation(_FakeDaprTest): + def _dapr_runner(self, name: str) -> Any: + store = MemoryStateStore() + checkpointer = DaprMemoryCheckpointer(state_store=store) # type: ignore[arg-type] + return _runner(chat_graph(), name, checkpointer=checkpointer), store + + def test_two_invokes_on_a_thread_accumulate_messages(self): + runner, _ = self._dapr_runner("thread-invoke") + _invoke(runner, "hi", "t1") + out = _invoke(runner, "again", "t1") + self.assertEqual(shape(out["messages"]), [HI, ANSWER, AGAIN, ANSWER]) + + async def test_two_streams_on_a_thread_accumulate_messages(self): + runner, _ = self._dapr_runner("thread-astream") + for text in ("hi", "again"): + values = await _collect( + runner.astream( + turn(text), thread_id="t1", stream_mode="values", poll_interval=0.01 + ) + ) + self.assertEqual(shape(values[-1]["messages"]), [HI, ANSWER, AGAIN, ANSWER]) + # the first values chunk is the thread's state with the new input, as native + self.assertEqual(shape(values[0]["messages"]), [HI, ANSWER, AGAIN]) + + def test_threads_do_not_share_state(self): + runner, _ = self._dapr_runner("thread-apart") + _invoke(runner, "hi", "t1") + out = _invoke(runner, "again", "t2") + self.assertEqual(shape(out["messages"]), [AGAIN, ANSWER]) + + def test_the_store_keys_use_colons_and_escape_the_thread_id(self): + runner, store = self._dapr_runner("thread-keys") + _invoke(runner, "hi", "a:b|c#d") + self.assertTrue(store.data) + for key in store.data: + self.assertTrue(key.startswith("langgraph:a%3Ab%7Cc%23d:"), key) + self.assertNotIn("||", key) + + def test_without_a_checkpointer_or_store_a_thread_is_a_label(self): + runner = _runner(chat_graph(), "thread-none") + _invoke(runner, "hi", "t1") + out = _invoke(runner, "again", "t1") + self.assertEqual(shape(out["messages"]), [AGAIN, ANSWER]) + + def test_a_graph_compiled_with_a_checkpointer_continues_its_threads(self): + runner = _runner(chat_graph(MemorySaver()), "thread-saver") + _invoke(runner, "hi", "t1") + out = _invoke(runner, "again", "t1") + self.assertEqual(shape(out["messages"]), [HI, ANSWER, AGAIN, ANSWER]) + + def test_the_apps_state_store_is_used_by_default(self): + found = DiscoveredComponents(memory_store_name="agent-memory") + with ( + mock.patch( + "diagrid.agent.core.workflow.runner.discover_components", + return_value=found, + ), + mock.patch("diagrid.agent.core.state.DaprStateStore", MemoryStateStore), + ): + runner = _runner(chat_graph(), "thread-default") + _invoke(runner, "hi", "t1") + out = _invoke(runner, "again", "t1") + self.assertEqual(shape(out["messages"]), [HI, ANSWER, AGAIN, ANSWER]) + + def test_matches_native_memory_saver_over_two_turns(self): + native_graph = chat_graph(MemorySaver()) + config = {"configurable": {"thread_id": "t1"}} + native_graph.invoke(turn("hi"), config) + native = native_graph.invoke(turn("again"), config) + + runner, _ = self._dapr_runner("thread-golden") + _invoke(runner, "hi", "t1") + ours = _invoke(runner, "again", "t1") + self.assertEqual(set(ours), set(native)) + self.assertEqual(shape(ours["messages"]), shape(native["messages"])) + # every message kept its own id across the turns, and no id repeats + ids: List[str] = [m["id"] for m in ours["messages"]] + self.assertEqual(len(set(ids)), 4) diff --git a/tests/agent/langgraph/test_thread_replay.py b/tests/agent/langgraph/test_thread_replay.py new file mode 100644 index 00000000..5dae203f --- /dev/null +++ b/tests/agent/langgraph/test_thread_replay.py @@ -0,0 +1,81 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The thread's state is read and written by activities, never by workflow code. + +Workflow code runs again on every replay; an activity's result comes from the +history. An instance started before thread continuation replays without the +two activities. +""" + +import json +import threading +from typing import Any + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.models import GraphWorkflowOutput +from diagrid.agent.langgraph.state import DaprMemoryCheckpointer +from diagrid.agent.langgraph.workflow import agent_workflow + +from .golden_harness import _FakeDaprTest +from .test_runner import _InlineWorkflowContext +from .thread_helpers import MemoryStateStore, chat_graph, shape, turn + +_in_activity = threading.local() + + +class _GuardedCtx(_InlineWorkflowContext): + """Marks when an activity runs, so the store can tell who calls it.""" + + instance_id = "wf-replay" + + def call_activity(self, activity: Any, *, input: Any, retry_policy: Any = None): + _in_activity.on = True + try: + return super().call_activity(activity, input=input) + finally: + _in_activity.on = False + + +def _only_in_activities() -> None: + if not getattr(_in_activity, "on", False): + raise AssertionError("the thread store was touched from workflow code") + + +class TestThreadStateInActivities(_FakeDaprTest): + def _setup(self) -> Any: + store = MemoryStateStore() + store.guard = _only_in_activities + runner = DaprWorkflowGraphRunner( + graph=chat_graph(), + name="thread-replay", + checkpointer=DaprMemoryCheckpointer(state_store=store), # type: ignore[arg-type] + ) + runner._started = True + return runner, store + + def _drive(self, runner: Any, text: str, patched: bool = True) -> Any: + ctx = _GuardedCtx(runner, patched=patched) + wf_input = runner._prepare_run(turn(text), "t1", None, "wf-replay") + workflow = agent_workflow(ctx, json.loads(json.dumps(wf_input.workflow_input))) + result = None + try: + while True: + result = workflow.send(result) + except StopIteration as stop: + return ctx, GraphWorkflowOutput.from_dict(stop.value) + + def test_load_comes_first_and_save_last_both_as_activities(self): + runner, store = self._setup() + self._drive(runner, "hi") + ctx, out = self._drive(runner, "again") + self.assertEqual(ctx.scheduled[0], "load_thread_state") + self.assertEqual(ctx.scheduled[-1], "save_thread_state") + self.assertEqual(len(shape(out.output["messages"])), 4) + + def test_an_instance_from_before_the_patch_replays_without_them(self): + runner, store = self._setup() + ctx, out = self._drive(runner, "hi", patched=False) + self.assertNotIn("load_thread_state", ctx.scheduled) + self.assertNotIn("save_thread_state", ctx.scheduled) + self.assertEqual(store.data, {}) diff --git a/tests/agent/langgraph/thread_helpers.py b/tests/agent/langgraph/thread_helpers.py new file mode 100644 index 00000000..845f2734 --- /dev/null +++ b/tests/agent/langgraph/thread_helpers.py @@ -0,0 +1,73 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Helpers for the thread continuation tests: an in-memory state store and graphs.""" + +import copy +import json +from typing import Any, Callable, Dict, Optional + +from langgraph.graph import END, START, MessagesState, StateGraph + +from .streaming_helpers import _StreamingModel + + +class MemoryStateStore: + """A ``DaprStateStore`` stand-in: values cross JSON as they do over gRPC. + + ``guard`` is called on every access, so a test can check where the store + is touched from. + """ + + def __init__(self, store_name: str = "agent-memory", **_: Any) -> None: + self.store_name = store_name + self.data: Dict[str, Any] = {} + self.guard: Optional[Callable[[], None]] = None + + def _check(self) -> None: + if self.guard is not None: + self.guard() + + def save(self, key: str, value: Any, metadata: Any = None) -> None: + self._check() + self.data[key] = json.loads(json.dumps(value)) + + def get(self, key: str) -> Any: + self._check() + return copy.deepcopy(self.data.get(key)) + + def delete(self, key: str) -> None: + self._check() + self.data.pop(key, None) + + def close(self) -> None: + pass + + +def chat_graph(checkpointer: Any = None) -> Any: + """One chat node that answers every turn: the messages accumulate per thread.""" + model = _StreamingModel() + + def chat(state: MessagesState) -> dict: + return {"messages": [model.invoke(state["messages"])]} + + graph = StateGraph(MessagesState) + graph.add_node("chat", chat) + graph.add_edge(START, "chat") + graph.add_edge("chat", END) + return graph.compile(checkpointer=checkpointer) + + +def turn(text: str) -> Dict[str, Any]: + return {"messages": [{"role": "user", "content": text}]} + + +def shape(messages: Any) -> list: + """``(type, content)`` of each message, dict or object: ids differ by design.""" + out = [] + for m in messages: + if isinstance(m, dict): + out.append((m.get("type"), m.get("content"))) + else: + out.append((m.type, m.content)) + return out From 952e7353489dc0aa4ce53ddb9e2afb03ed3dba69 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:13:23 +0100 Subject: [PATCH 31/73] feat(langgraph): carry a thread's state between runs through a checkpointer Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 30 +++- diagrid/agent/langgraph/models.py | 7 + diagrid/agent/langgraph/runner.py | 28 ++++ diagrid/agent/langgraph/saver_store.py | 79 +++++++++ diagrid/agent/langgraph/state.py | 19 ++- diagrid/agent/langgraph/thread_state.py | 209 ++++++++++++++++++++++++ diagrid/agent/langgraph/workflow.py | 25 +++ 7 files changed, 392 insertions(+), 5 deletions(-) create mode 100644 diagrid/agent/langgraph/saver_store.py create mode 100644 diagrid/agent/langgraph/thread_state.py diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 67078b9e..70857239 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -65,6 +65,30 @@ finally: runner.shutdown() ``` +## Conversations + +Pass the same `thread_id` to each run of a conversation, and send only the new +message: + +```python +runner.invoke({"messages": [{"role": "user", "content": "hi"}]}, thread_id="chat-1") +result = runner.invoke( + {"messages": [{"role": "user", "content": "and again"}]}, thread_id="chat-1" +) +# result["messages"] holds both turns, as with a LangGraph checkpointer +``` + +That is all. `thread_id` may also come as `config["configurable"]["thread_id"]` +or, over HTTP, as `thread_id` in the request body. Each run starts from the +state the thread's last run ended with and applies its input to it through the +channels' reducers, as LangGraph does with a checkpointer. The state is kept in +the app's Dapr state store (`agent-memory`, which a Catalyst app has), keyed by +thread. To keep it elsewhere, compile the graph with a LangGraph checkpointer +(`graph.compile(checkpointer=MemorySaver())`) or pass `checkpointer=` to the +runner (a `DaprMemoryCheckpointer` on another store, or a LangGraph saver with +the synchronous `get_tuple` and `put`). With none of these, `thread_id` only +names the run and each run starts from its input alone. + ## Async Usage ```python @@ -112,8 +136,10 @@ as a Dapr activity. The stream modes are: | `debug` | the `tasks` events wrapped as `{step, timestamp, type, payload}` | `checkpoints` is refused (`ValueError` from `astream`, a `422` over HTTP): the -runner keeps no LangGraph checkpoints, because the Dapr workflow history is the -run's durable record, so there are no checkpoint ids a client could pass back. +runner keeps no per-step LangGraph checkpoints, because the Dapr workflow +history is the run's durable record, so there are no checkpoint ids a client +could pass back (a thread keeps only the state its last run ended with, see +[Conversations](#conversations)). For the same reason `debug` holds only the task events, which is what native `debug` holds for a graph compiled without a checkpointer. A client that wants the full state reads it from `values`, from the run's final event, or from `GET diff --git a/diagrid/agent/langgraph/models.py b/diagrid/agent/langgraph/models.py index df61e17b..46699fe9 100644 --- a/diagrid/agent/langgraph/models.py +++ b/diagrid/agent/langgraph/models.py @@ -487,6 +487,9 @@ class GraphWorkflowInput: pending_nodes: Nodes pending execution config: Optional LangGraph config dict thread_id: Thread identifier for the execution + thread_state: The run starts from its thread's last state and keeps + the state it ends with as the thread's (the runner has a + checkpointer). """ graph_config: GraphConfig @@ -497,6 +500,7 @@ class GraphWorkflowInput: pending_nodes: List[str] = field(default_factory=list) config: Optional[Dict[str, Any]] = None thread_id: Optional[str] = None + thread_state: bool = False def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -510,6 +514,8 @@ def to_dict(self) -> Dict[str, Any]: } if self.strict_limit: data["strict_limit"] = True + if self.thread_state: + data["thread_state"] = True return data @classmethod @@ -523,6 +529,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "GraphWorkflowInput": pending_nodes=data.get("pending_nodes", []), config=data.get("config"), thread_id=data.get("thread_id"), + thread_state=bool(data.get("thread_state", False)), ) diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index dbdfdcbb..6029f71f 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -76,6 +76,13 @@ ) from .langsmith_trace import ParentTrace, start_parent_trace from .run_status import completed_result +from .thread_state import ( + LOAD_THREAD_ACTIVITY, + SAVE_THREAD_ACTIVITY, + make_load_activity, + make_save_activity, + resolve_thread_store, +) from .limits import StepBound, step_bound from .workflow import ( IS_LAST_STEP, @@ -332,6 +339,7 @@ def __init__( instructions: Optional[str] = None, registry_config: Optional[Any] = None, stream_registry: Optional[StreamSinkRegistry] = None, + checkpointer: Optional[Any] = None, ): """Initialize the runner. @@ -352,6 +360,13 @@ def __init__( stream_registry: Where streamed runs register their sinks. The activities this runner registers write into it. Defaults to a new registry owned by this runner. + checkpointer: Where a thread's state is kept between runs, so a run + with the same ``thread_id`` continues the conversation: a + ``DaprMemoryCheckpointer`` or a LangGraph checkpoint saver with + the synchronous API. Defaults to the checkpointer the graph was + compiled with, else the app's Dapr state store + (``agent-memory``) when it has one; with none, ``thread_id`` is + only a label. """ self._graph = graph self._max_steps = DEFAULT_MAX_STEPS if max_steps is None else max_steps @@ -383,6 +398,10 @@ def __init__( # max_iterations instead of a hardcoded default (read by DeepAgentsMapper). self._graph._diagrid_max_steps = self._max_steps # type: ignore[attr-defined] + self._thread_store = resolve_thread_store( + checkpointer, self._graph, self._state_store + ) + self._register_agent_metadata( agent=self._graph, framework=self._REGISTRY_FRAMEWORK, @@ -413,6 +432,14 @@ def _register_workflow_components(self) -> None: make_condition_activity(self._stream_registry), name="evaluate_condition_activity", ) + # Registered even without a store, so an instance that scheduled them + # still replays on a runner that has none. + self._workflow_runtime.register_activity( + make_load_activity(self._thread_store), name=LOAD_THREAD_ACTIVITY + ) + self._workflow_runtime.register_activity( + make_save_activity(self._thread_store), name=SAVE_THREAD_ACTIVITY + ) def _register_node_activities(self) -> None: """Register one activity per graph node, named after the node.""" @@ -617,6 +644,7 @@ def _prepare_run( pending_nodes=[], config=run_config, thread_id=thread_id, + thread_state=self._thread_store is not None, ).to_dict() json.dumps(workflow_input) return _RunSetup(workflow_id, thread_id, run_config, trace, workflow_input) diff --git a/diagrid/agent/langgraph/saver_store.py b/diagrid/agent/langgraph/saver_store.py new file mode 100644 index 00000000..da90791d --- /dev/null +++ b/diagrid/agent/langgraph/saver_store.py @@ -0,0 +1,79 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A thread's state in a LangGraph checkpoint saver (``MemorySaver`` and the like). + +The saver keeps the thread's latest checkpoint as LangGraph writes one: the +channel values as Python objects. They are converted to and from the +workflow's channel state at the edges. The saver must have the synchronous +API (``get_tuple`` and ``put``), as the activities that use it are +synchronous. +""" + +from typing import Any, Dict, List, Optional + +from .models import ChannelState + +#: The checkpoint namespace of a graph's own (not a subgraph's) checkpoints. +_ROOT_NS = "" + + +def is_saver(obj: Any) -> bool: + """Whether ``obj`` is a LangGraph checkpoint saver.""" + try: + from langgraph.checkpoint.base import BaseCheckpointSaver + except ImportError: # pragma: no cover - langgraph without checkpoints + return False + return isinstance(obj, BaseCheckpointSaver) + + +def _config(thread_id: str) -> Dict[str, Any]: + return {"configurable": {"thread_id": thread_id, "checkpoint_ns": _ROOT_NS}} + + +class SaverThreadStore: + """A thread's last state in a LangGraph ``BaseCheckpointSaver``.""" + + def __init__(self, saver: Any, channels: List[str]) -> None: + self._saver = saver + # Only the graph's state channels: a native checkpoint also holds the + # loop's own trigger channels, which the workflow does not keep. + self._channels = frozenset(channels) + + def load(self, thread_id: str) -> Optional[Dict[str, Any]]: + from .workflow import _serialize_input + + found = self._saver.get_tuple(_config(thread_id)) + if found is None: + return None + values = { + name: value + for name, value in (found.checkpoint.get("channel_values") or {}).items() + if not self._channels or name in self._channels + } + stored = _serialize_input(values) + return ChannelState( + values=stored, versions={name: 1 for name in stored} + ).to_dict() + + def save(self, checkpoint: Any) -> None: + from langgraph.checkpoint.base import empty_checkpoint + + from .workflow import _reconstruct_state + + state = ChannelState.from_dict(checkpoint.channel_state) + values = { + name: value + for name, value in _reconstruct_state(state).items() + if name in state.values + } + versions = {name: self._saver.get_next_version(None, None) for name in values} + native = empty_checkpoint() + native["channel_values"] = values + native["channel_versions"] = versions + self._saver.put( + _config(checkpoint.thread_id), + native, + {"source": "loop", "step": checkpoint.steps, "parents": {}}, + versions, + ) diff --git a/diagrid/agent/langgraph/state.py b/diagrid/agent/langgraph/state.py index eda6e242..7abe2b6a 100644 --- a/diagrid/agent/langgraph/state.py +++ b/diagrid/agent/langgraph/state.py @@ -5,6 +5,7 @@ import logging from typing import Any, Optional +from urllib.parse import quote from diagrid.agent.core.state import DaprStateStore @@ -17,7 +18,14 @@ class DaprMemoryCheckpointer: Persists LangGraph checkpoints (channel state and version metadata) to a Dapr state store, enabling conversation memory across invocations. - Key format: ``langgraph-{thread_id}-checkpoint-{checkpoint_id}`` + Key format: ``langgraph:{thread_id}:checkpoint:{checkpoint_id}``, and + ``langgraph:{thread_id}:index`` for the thread's list of checkpoints. Each + id is path-escaped, so a ``:``, ``|`` or ``#`` in it cannot run into the + separators (and no key ever holds ``||``, which Dapr reserves). + + :class:`~diagrid.agent.langgraph.DaprWorkflowGraphRunner` uses one on the + app's state store by default, so ``thread_id`` carries a conversation from + one run to the next. Example: ```python @@ -52,10 +60,10 @@ def __init__( ) def _checkpoint_key(self, thread_id: str, checkpoint_id: str) -> str: - return f"langgraph-{thread_id}-checkpoint-{checkpoint_id}" + return f"langgraph:{_segment(thread_id)}:checkpoint:{_segment(checkpoint_id)}" def _thread_index_key(self, thread_id: str) -> str: - return f"langgraph-{thread_id}-index" + return f"langgraph:{_segment(thread_id)}:index" def save_checkpoint( self, @@ -162,3 +170,8 @@ def delete_checkpoint(self, thread_id: str, checkpoint_id: str) -> None: def close(self) -> None: """Close the underlying state store.""" self._store.close() + + +def _segment(value: str) -> str: + """``value`` escaped so it is one segment of a ``:``-separated key.""" + return quote(str(value), safe="") diff --git a/diagrid/agent/langgraph/thread_state.py b/diagrid/agent/langgraph/thread_state.py new file mode 100644 index 00000000..7b6f072f --- /dev/null +++ b/diagrid/agent/langgraph/thread_state.py @@ -0,0 +1,209 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A thread's state, carried from one run to the next. + +With a checkpointer, LangGraph starts a run on a thread from the state the +thread's last run ended with and applies the new input to it through the +channels' reducers. The workflow does the same: an activity loads the thread's +last state before the first step, the workflow applies the input to it, and an +activity saves the state the run ended with. Workflow code never touches the +store, so a replay reads both from the history. +""" + +import copy +import logging +from dataclasses import dataclass +from typing import Any, Callable, Dict, Generator, List, Optional, Protocol + +from .models import ChannelState +from .state import DaprMemoryCheckpointer + +logger = logging.getLogger(__name__) + +#: An instance started before threads carried state replays without the load and +#: save activities: the patch is what tells the two apart. +THREAD_STATE_PATCH = "langgraph-thread-state" +LOAD_THREAD_ACTIVITY = "load_thread_state" +SAVE_THREAD_ACTIVITY = "save_thread_state" + + +class ThreadStore(Protocol): + """Where a thread's last channel state is kept (``ChannelState`` dicts).""" + + def load(self, thread_id: str) -> Optional[Dict[str, Any]]: ... + + def save(self, checkpoint: "ThreadCheckpoint") -> None: ... + + +@dataclass(frozen=True) +class ThreadCheckpoint: + """The state a run on a thread ended with, as the save activity gets it.""" + + thread_id: str + #: The workflow instance that produced it. + checkpoint_id: str + channel_state: Dict[str, Any] + steps: int = 0 + status: str = "completed" + + def to_dict(self) -> Dict[str, Any]: + return { + "thread_id": self.thread_id, + "checkpoint_id": self.checkpoint_id, + "channel_state": self.channel_state, + "steps": self.steps, + "status": self.status, + } + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ThreadCheckpoint": + return cls( + thread_id=str(data["thread_id"]), + checkpoint_id=str(data["checkpoint_id"]), + channel_state=dict(data.get("channel_state") or {}), + steps=int(data.get("steps") or 0), + status=str(data.get("status") or "completed"), + ) + + +class DaprThreadStore: + """A thread's state in a Dapr state store, through ``DaprMemoryCheckpointer``.""" + + def __init__(self, checkpointer: DaprMemoryCheckpointer) -> None: + self._checkpointer = checkpointer + + def load(self, thread_id: str) -> Optional[Dict[str, Any]]: + data = self._checkpointer.load_checkpoint(thread_id) + if not data: + return None + return ChannelState( + values=dict(data.get("channel_values") or {}), + versions=dict(data.get("channel_versions") or {}), + ).to_dict() + + def save(self, checkpoint: ThreadCheckpoint) -> None: + state = ChannelState.from_dict(checkpoint.channel_state) + self._checkpointer.save_checkpoint( + thread_id=checkpoint.thread_id, + checkpoint_id=checkpoint.checkpoint_id, + channel_values=state.values, + channel_versions=state.versions, + metadata={"steps": checkpoint.steps, "status": checkpoint.status}, + ) + + +def resolve_thread_store( + checkpointer: Any, graph: Any, state_store: Any +) -> Optional[ThreadStore]: + """The store a runner keeps its threads' state in, or ``None`` for none. + + The runner's own ``checkpointer`` first, then the one the graph was + compiled with, then the app's Dapr state store (``agent-memory``, which a + Catalyst app has). Without any of them a thread id is only a label. + """ + from .saver_store import SaverThreadStore, is_saver + + if checkpointer is not None: + if isinstance(checkpointer, DaprMemoryCheckpointer): + return DaprThreadStore(checkpointer) + if is_saver(checkpointer): + return SaverThreadStore(checkpointer, _state_channels(graph)) + raise TypeError( + "checkpointer must be a DaprMemoryCheckpointer or a LangGraph " + f"checkpoint saver, not {type(checkpointer).__name__}" + ) + own = getattr(graph, "checkpointer", None) + if is_saver(own): + return SaverThreadStore(own, _state_channels(graph)) + if state_store is not None: + return DaprThreadStore(DaprMemoryCheckpointer(state_store=state_store)) + return None + + +def _state_channels(graph: Any) -> List[str]: + channels = getattr(getattr(graph, "builder", None), "channels", None) or {} + return list(channels) + + +def make_load_activity( + store: Optional[ThreadStore], +) -> Callable[[Any, Dict[str, Any]], Optional[Dict[str, Any]]]: + """The activity that reads a thread's last state (``None`` for a new thread).""" + + def load_thread_state( + ctx: Any, input_data: Dict[str, Any] + ) -> Optional[Dict[str, Any]]: + if store is None: + logger.warning("A run asked for its thread's state but no store is set") + return None + return store.load(str(input_data["thread_id"])) + + return load_thread_state + + +def make_save_activity( + store: Optional[ThreadStore], +) -> Callable[[Any, Dict[str, Any]], None]: + """The activity that keeps the state a run ended with as its thread's.""" + + def save_thread_state(ctx: Any, input_data: Dict[str, Any]) -> None: + if store is None: + logger.warning("A run asked to save its thread's state but no store is set") + return + store.save(ThreadCheckpoint.from_dict(input_data)) + + return save_thread_state + + +def continue_thread(loaded: ChannelState, incoming: ChannelState) -> ChannelState: + """The thread's state with the run's input applied to it. + + Each input channel is written through its reducer, as LangGraph applies a + run's input to a thread's state: ``add_messages`` appends, a plain channel + is replaced. Deterministic, so it may run in workflow code. + """ + from .workflow import _apply_write + + state = ChannelState( + values=copy.deepcopy(loaded.values), versions=dict(loaded.versions) + ) + for channel in incoming.updated_channels: + if channel in incoming.values: + _apply_write(state, channel, incoming.values[channel]) + state.updated_channels = list(incoming.updated_channels) + return state + + +def load_thread( + ctx: Any, thread_id: str, incoming: ChannelState, retry_policy: Any +) -> Generator[Any, Any, ChannelState]: + """Workflow step: the run's starting state, from its thread's and its input.""" + loaded = yield ctx.call_activity( + LOAD_THREAD_ACTIVITY, + input={"thread_id": thread_id}, + retry_policy=retry_policy, + ) + if not loaded: + return incoming + return continue_thread(ChannelState.from_dict(loaded), incoming) + + +def save_thread( + ctx: Any, thread_id: str, output: Dict[str, Any], retry_policy: Any +) -> Generator[Any, Any, None]: + """Workflow step: keep the state the run ended with as its thread's.""" + if not output.get("channel_state"): + return + checkpoint = ThreadCheckpoint( + thread_id=thread_id, + checkpoint_id=str(ctx.instance_id), + channel_state=output["channel_state"], + steps=int(output.get("steps") or 0), + status=str(output.get("status") or "completed"), + ) + yield ctx.call_activity( + SAVE_THREAD_ACTIVITY, + input=checkpoint.to_dict(), + retry_policy=retry_policy, + ) diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index b2778ae8..4cab4727 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -67,6 +67,7 @@ from .stream_values import state_values from .streaming import STREAM_RUN_KEY, NodeStreamer, StaticConfig from .task_identity import TaskIdentity +from .thread_state import THREAD_STATE_PATCH, load_thread, save_thread from .values import ( coerce_to_default, decode_value, @@ -517,6 +518,9 @@ class _Run: #: Whether a node's activity evaluates its conditional edges #: (see :data:`ROUTE_IN_NODE_PATCH`). route_in_node: bool = False + #: Whether the run starts from its thread's state and saves its own as the + #: thread's (see :data:`THREAD_STATE_PATCH`). + thread_state: bool = False #: The nodes that ran in each step, reported on the output so a streaming #: consumer can tell which node's chunks never arrived. executed: List[List[str]] = field(default_factory=list) @@ -564,6 +568,7 @@ def _new_run(ctx: DaprWorkflowContext, workflow_input: GraphWorkflowInput) -> _R node_activities_by_name = ctx.is_patched(NODE_ACTIVITY_NAMES_PATCH) step_order = ctx.is_patched(STEP_ORDER_PATCH) route_in_node = ctx.is_patched(ROUTE_IN_NODE_PATCH) + thread_state = workflow_input.thread_state and ctx.is_patched(THREAD_STATE_PATCH) return _Run( ctx=ctx, graph_config=workflow_input.graph_config, @@ -584,6 +589,7 @@ def _new_run(ctx: DaprWorkflowContext, workflow_input: GraphWorkflowInput) -> _R else workflow_input.max_steps + 1 ), route_in_node=route_in_node, + thread_state=thread_state, ) @@ -596,9 +602,28 @@ def agent_workflow( writes to the channels, and finds the next step's nodes from the edges. The run ends when nothing is triggered, END is reached or a step bound is hit; the result is a ``GraphWorkflowOutput`` as a dictionary. + + A run on a thread with a checkpointer starts from the thread's last state + with the input applied to it, and keeps the state it ends with as the + thread's: both through activities (see ``thread_state``). """ workflow_input = _workflow_input(ctx, input_data) run = _new_run(ctx, workflow_input) + thread_id = str(run.thread_id or ctx.instance_id) + if run.thread_state: + run.channel_state = yield from load_thread( + ctx, thread_id, run.channel_state, run.retry_policy + ) + output = yield from _run_graph(run, workflow_input) + if run.thread_state: + yield from save_thread(ctx, thread_id, output, run.retry_policy) + return output + + +def _run_graph( + run: _Run, workflow_input: GraphWorkflowInput +) -> Generator[Any, Any, Dict[str, Any]]: + """Run the graph's steps until it ends; the workflow output as a dict.""" max_steps = workflow_input.max_steps step = 0 From 1f7e639802b15f0a2cf26719fd9b2ed92e42e208 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:18:08 +0100 Subject: [PATCH 32/73] test(langgraph): drop an unused helper import from the golden values test Signed-off-by: Casper Nielsen --- tests/agent/langgraph/test_streaming_golden_values.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/agent/langgraph/test_streaming_golden_values.py b/tests/agent/langgraph/test_streaming_golden_values.py index 91b3247a..d1b506b9 100644 --- a/tests/agent/langgraph/test_streaming_golden_values.py +++ b/tests/agent/langgraph/test_streaming_golden_values.py @@ -42,7 +42,6 @@ ) from .streaming_helpers import ( INPUT, - _collect, _Ctx, _drain, parse_sse, From 58f64fb2d2e1233e2e382236210da90eb79b6ba5 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:29:47 +0100 Subject: [PATCH 33/73] test(stream): expect a state-store event log any replica can resume from Signed-off-by: Casper Nielsen --- tests/agent/core/log_store_fake.py | 53 +++++ tests/agent/core/test_stream_cursor.py | 55 ++++++ tests/agent/core/test_stream_log.py | 260 +++++++++++++++++++++++++ 3 files changed, 368 insertions(+) create mode 100644 tests/agent/core/log_store_fake.py create mode 100644 tests/agent/core/test_stream_cursor.py create mode 100644 tests/agent/core/test_stream_log.py diff --git a/tests/agent/core/log_store_fake.py b/tests/agent/core/log_store_fake.py new file mode 100644 index 00000000..784afd61 --- /dev/null +++ b/tests/agent/core/log_store_fake.py @@ -0,0 +1,53 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""An in-memory state store with the bulk API the stream event log uses.""" + +import copy +import json +import threading +from typing import Any, Dict, List, Optional, Sequence, Tuple + + +class FakeLogStore: + """Keys to JSON values, with the metadata each save carried. + + ``fail_saves`` / ``fail_gets`` make the next calls raise, as a store that + is down would. + """ + + def __init__(self) -> None: + self.data: Dict[str, Any] = {} + self.metadata: Dict[str, Dict[str, str]] = {} + self.saves: List[List[str]] = [] + self.fail_saves = 0 + self.fail_gets = 0 + self._lock = threading.Lock() + + def save_bulk(self, items: Sequence[Tuple[str, Any, Dict[str, str]]]) -> None: + with self._lock: + if self.fail_saves: + self.fail_saves -= 1 + raise ConnectionError("store down") + self.saves.append([key for key, _, _ in items]) + for key, value, metadata in items: + # crosses JSON, as a real store does + self.data[key] = json.loads(json.dumps(value)) + self.metadata[key] = dict(metadata) + + def get_bulk(self, keys: Sequence[str]) -> Dict[str, Any]: + with self._lock: + if self.fail_gets: + self.fail_gets -= 1 + raise ConnectionError("store down") + return {k: copy.deepcopy(self.data[k]) for k in keys if k in self.data} + + def delete(self, key: str) -> None: + with self._lock: + self.data.pop(key, None) + + def keys_like(self, part: str) -> List[str]: + return sorted(k for k in self.data if part in k) + + def get(self, key: str) -> Optional[Any]: + return self.data.get(key) diff --git a/tests/agent/core/test_stream_cursor.py b/tests/agent/core/test_stream_cursor.py new file mode 100644 index 00000000..39a4d275 --- /dev/null +++ b/tests/agent/core/test_stream_cursor.py @@ -0,0 +1,55 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The SSE id of a stream read from the event log: a cursor any replica can resume.""" + +import unittest + +from diagrid.agent.core.workflow.stream_cursor import ( + END_ID, + START_ID, + StreamCursor, + encode_cursor, + parse_cursor, +) + + +class TestStreamCursor(unittest.TestCase): + def test_round_trip(self): + cursor = StreamCursor( + base=3, + positions=((3, "research#0", "a1b2c3d4", 7), (3, "review:branch:route", "ffff0000", 2)), + ) + text = encode_cursor(cursor) + self.assertTrue(text.startswith("v1.3.")) + self.assertEqual(parse_cursor(text), cursor) + self.assertEqual(cursor.position(3, "research#0"), ("a1b2c3d4", 7)) + self.assertIsNone(cursor.position(3, "other")) + + def test_negative_base_round_trips(self): + cursor = StreamCursor(base=-1, positions=((-1, "__start__:branch:c", "abcd1234", 1),)) + self.assertEqual(parse_cursor(encode_cursor(cursor)), cursor) + + def test_fixed_ids(self): + self.assertEqual(parse_cursor(START_ID), StreamCursor()) + self.assertTrue(parse_cursor(END_ID).at_end) + self.assertEqual(encode_cursor(StreamCursor()), START_ID) + self.assertEqual(encode_cursor(StreamCursor(at_end=True)), END_ID) + + def test_missing_or_junk_replays_from_the_start(self): + for junk in (None, "", "17", "v1", "v1.x.y", "v2.1.abc", "v1.1.!!!", "v1.1.e30"): + with self.subTest(junk=junk): + self.assertEqual(parse_cursor(junk), StreamCursor()) + + def test_the_start_skips_nothing(self): + start = StreamCursor() + self.assertFalse(start.skips_step(-1)) + self.assertFalse(start.skips_step(0)) + later = StreamCursor(base=2) + self.assertTrue(later.skips_step(1)) + self.assertFalse(later.skips_step(2)) + + def test_the_id_holds_only_open_steps(self): + cursor = StreamCursor(base=5, positions=((5, "a", "12345678", 1),)) + # small: grows with one step's parallelism, not with the run + self.assertLess(len(encode_cursor(cursor)), 80) diff --git a/tests/agent/core/test_stream_log.py b/tests/agent/core/test_stream_log.py new file mode 100644 index 00000000..97b22a77 --- /dev/null +++ b/tests/agent/core/test_stream_log.py @@ -0,0 +1,260 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The state-store event log: what an activity writes and what any replica reads back.""" + +import time +import unittest +from typing import Any, List + +from diagrid.agent.core.workflow.stream import ( + BRANCH_DONE, + UPDATES, + StreamEvent, +) +from diagrid.agent.core.workflow.stream_log import ( + LogReader, + LogWriter, + StateLogStreamConfig, + UnitWant, + batch_key, + escape_key_part, + head_key, + wire_event, +) + +from .log_store_fake import FakeLogStore + + +def _config(**kw: Any) -> StateLogStreamConfig: + base = dict(flush_interval_s=30.0, flush_max_chunks=1000) + base.update(kw) + return StateLogStreamConfig(**base) + + +def _event(node: str, seq: int, mode: str = "messages", attempt: str = "att") -> StreamEvent: + return StreamEvent("wf:1", 0, node, attempt, seq, (), mode, f"{node}-{seq}") + + +def _writer(store: FakeLogStore, unit: str = "research#0", **kw: Any) -> LogWriter: + return LogWriter(store, _config(**kw), "wf:1", 0, unit, encode=lambda e: e.data) + + +def _datas(chunk: Any) -> List[Any]: + return [e["data"] for e in chunk.events] + + +class TestKeys(unittest.TestCase): + def test_parts_are_escaped_and_never_use_the_actor_separator(self): + for part in ("research#0", "review:branch:route", "a/b", "x||y", "a b"): + escaped = escape_key_part(part) + for bad in (":", "#", "/", "|"): + self.assertNotIn(bad, escaped) + key = batch_key("lgstream", "wf:1", 3, "review:branch:route", "abc", 2) + self.assertNotIn("||", key) + self.assertEqual(key.count(":"), 5) + self.assertTrue(head_key("lgstream", "wf:1", 3, "n").endswith(":head")) + + def test_distinct_units_never_share_a_key(self): + self.assertNotEqual( + head_key("p", "w", 1, "a:b"), head_key("p", "w:1", 1, "b") + ) + + +class TestWriter(unittest.TestCase): + def test_flushes_on_the_chunk_count(self): + store = FakeLogStore() + writer = _writer(store, flush_max_chunks=3) + for seq in range(3): + writer.put(_event("research#0", seq)) + self.assertEqual(len(store.saves), 1) + writer.finish(done=True) + + def test_flushes_on_the_interval(self): + store = FakeLogStore() + writer = _writer(store, flush_interval_s=0.02) + writer.put(_event("research#0", 0)) + deadline = time.monotonic() + 5 + while not store.saves and time.monotonic() < deadline: + time.sleep(0.01) + self.assertEqual(len(store.saves), 1) + writer.finish(done=True) + + def test_the_last_flush_runs_before_finish_returns(self): + store = FakeLogStore() + writer = _writer(store) + writer.put(_event("research#0", 0)) + self.assertEqual(store.saves, []) + writer.finish(done=True) + head = store.get(head_key("lgstream", "wf:1", 0, "research#0")) + self.assertEqual( + head, {"attempt": writer.attempt, "batches": 1, "events": 1, "done": True} + ) + + def test_every_save_carries_a_ttl_and_heads_outlive_batches(self): + store = FakeLogStore() + writer = _writer(store, event_ttl_s=100, record_ttl_factor=24) + writer.put(_event("research#0", 0)) + writer.finish(done=True) + batch = batch_key("lgstream", "wf:1", 0, "research#0", writer.attempt, 0) + head = head_key("lgstream", "wf:1", 0, "research#0") + self.assertEqual(store.metadata[batch], {"ttlInSeconds": "100"}) + self.assertEqual(store.metadata[head], {"ttlInSeconds": "2400"}) + self.assertEqual(store.saves, [[batch, head]]) + + def test_a_write_error_never_raises_and_is_retried(self): + store = FakeLogStore() + writer = _writer(store, flush_max_chunks=1) + store.fail_saves = 1 + writer.put(_event("research#0", 0)) # the save fails: logged, counted + self.assertEqual(writer.write_failures, 1) + writer.put(_event("research#0", 1)) + writer.finish(done=True) + chunk = LogReader(store, _config(), "wf:1").read( + [UnitWant(0, "research#0")] + )[0] + self.assertEqual(_datas(chunk), ["research#0-0", "research#0-1"]) + + def test_a_failed_last_flush_leaves_the_unit_not_done(self): + store = FakeLogStore() + writer = _writer(store) + writer.put(_event("research#0", 0)) + store.fail_saves = 5 + writer.finish(done=True) + self.assertIsNone(store.get(head_key("lgstream", "wf:1", 0, "research#0"))) + self.assertGreaterEqual(writer.write_failures, 1) + + def test_a_full_buffer_never_drops_internal_markers(self): + store = FakeLogStore() + writer = _writer(store, max_buffered=5, flush_max_chunks=1) + store.fail_saves = 10_000 # the store is down for the whole node + for seq in range(20): + writer.put(_event("research#0", seq)) + writer.put(_event("research#0", 20, UPDATES)) + writer.put(_event("review:branch:route", 0, BRANCH_DONE)) + store.fail_saves = 0 + writer.finish(done=True) + chunk = LogReader(store, _config(), "wf:1").read( + [UnitWant(0, "research#0")] + )[0] + modes = [e["mode"] for e in chunk.events] + self.assertIn(UPDATES, modes) + self.assertIn(BRANCH_DONE, modes) + self.assertLessEqual(modes.count("messages"), 5) + self.assertGreater(writer.dropped, 0) + + def test_a_new_attempt_takes_over_the_unit(self): + store = FakeLogStore() + first = _writer(store) + first.put(_event("research#0", 0, attempt="a1")) + first.finish(done=False) # the node raised: Dapr retries it + second = _writer(store) + second.put(_event("research#0", 0, attempt="a2")) + second.finish(done=True) + head = store.get(head_key("lgstream", "wf:1", 0, "research#0")) + self.assertEqual(head["attempt"], second.attempt) + + def test_a_done_unit_blocks_a_late_attempt(self): + store = FakeLogStore() + first = _writer(store) + first.put(_event("research#0", 0)) + first.finish(done=True) + late = _writer(store) + late.put(_event("research#0", 0)) + late.finish(done=True) + head = store.get(head_key("lgstream", "wf:1", 0, "research#0")) + self.assertEqual(head["attempt"], first.attempt) + + def test_events_keep_their_identity_on_the_wire(self): + event = StreamEvent( + "wf", 2, "research#1", "att", 4, ("x",), "messages", "d", + display_node="research", path=("__pregel_push", 1, False), branch=None, + ) + wire = wire_event(event, lambda e: e.data) + self.assertEqual(wire["node"], "research#1") + self.assertEqual(wire["display_node"], "research") + self.assertEqual(wire["path"], ["__pregel_push", 1, False]) + self.assertEqual(wire["step"], 2) + + +class TestReader(unittest.TestCase): + def _written(self, store: FakeLogStore, n: int, flush: int = 2) -> LogWriter: + writer = _writer(store, flush_max_chunks=flush) + for seq in range(n): + writer.put(_event("research#0", seq)) + writer.finish(done=True) + return writer + + def test_reads_a_unit_in_order(self): + store = FakeLogStore() + writer = self._written(store, 5) + chunk = LogReader(store, _config(), "wf:1").read([UnitWant(0, "research#0")])[0] + self.assertEqual(_datas(chunk), [f"research#0-{i}" for i in range(5)]) + self.assertEqual(chunk.attempt, writer.attempt) + self.assertTrue(chunk.done) + self.assertFalse(chunk.reset) + self.assertFalse(chunk.purged) + self.assertEqual(chunk.batches, 3) + + def test_reads_only_what_is_new(self): + store = FakeLogStore() + writer = self._written(store, 5) + reader = LogReader(store, _config(), "wf:1") + chunk = reader.read( + [UnitWant(0, "research#0", attempt=writer.attempt, from_batch=2)] + )[0] + self.assertEqual(_datas(chunk), ["research#0-4"]) + + def test_resumes_inside_a_batch(self): + store = FakeLogStore() + writer = self._written(store, 5) + reader = LogReader(store, _config(), "wf:1") + chunk = reader.read( + [UnitWant(0, "research#0", attempt=writer.attempt[:8], skip_events=3)] + )[0] + self.assertEqual(_datas(chunk), ["research#0-3", "research#0-4"]) + self.assertEqual(chunk.start, 3) + + def test_an_attempt_that_changed_is_read_from_its_start(self): + store = FakeLogStore() + self._written(store, 3) + reader = LogReader(store, _config(), "wf:1") + chunk = reader.read( + [UnitWant(0, "research#0", attempt="oldattem", skip_events=2)] + )[0] + self.assertTrue(chunk.reset) + self.assertEqual(len(chunk.events), 3) + self.assertEqual(chunk.start, 0) + + def test_a_unit_with_no_head_has_nothing(self): + chunk = LogReader(FakeLogStore(), _config(), "wf:1").read( + [UnitWant(0, "nobody")] + )[0] + self.assertIsNone(chunk.attempt) + self.assertEqual(chunk.events, []) + + def test_a_missing_batch_inside_the_count_is_purged(self): + store = FakeLogStore() + writer = self._written(store, 5) + store.delete(batch_key("lgstream", "wf:1", 0, "research#0", writer.attempt, 1)) + chunk = LogReader(store, _config(), "wf:1").read([UnitWant(0, "research#0")])[0] + self.assertTrue(chunk.purged) + self.assertEqual(chunk.events, []) + + def test_a_store_that_fails_raises(self): + store = FakeLogStore() + self._written(store, 1) + store.fail_gets = 1 + with self.assertRaises(ConnectionError): + LogReader(store, _config(), "wf:1").read([UnitWant(0, "research#0")]) + + def test_one_round_trip_for_heads_and_one_for_batches(self): + store = FakeLogStore() + self._written(store, 5) + calls: List[Any] = [] + real = store.get_bulk + store.get_bulk = lambda keys: calls.append(list(keys)) or real(keys) # type: ignore[method-assign] + LogReader(store, _config(), "wf:1").read( + [UnitWant(0, "research#0"), UnitWant(0, "other")] + ) + self.assertEqual(len(calls), 2) From 1f1742343bc270d93b988ff700010b7a3542f1ac Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:31:24 +0100 Subject: [PATCH 34/73] feat(stream): add a state-store event log and a resumable stream cursor Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/stream.py | 8 +- diagrid/agent/core/workflow/stream_cursor.py | 99 ++++ diagrid/agent/core/workflow/stream_log.py | 459 +++++++++++++++++++ tests/agent/core/test_stream_cursor.py | 20 +- tests/agent/core/test_stream_log.py | 29 +- 5 files changed, 598 insertions(+), 17 deletions(-) create mode 100644 diagrid/agent/core/workflow/stream_cursor.py create mode 100644 diagrid/agent/core/workflow/stream_log.py diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index 759174a8..3bccfcc4 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -222,9 +222,13 @@ def _put() -> None: self._closed = True +def is_kept_when_full(mode: str) -> bool: + """Whether chunks of ``mode`` must survive a full buffer: they cannot be re-sent.""" + return mode in _KEPT_WHEN_FULL + + def _is_kept_when_full(item: Any) -> bool: - """Chunks that must not be dropped: they cannot be re-sent.""" - return isinstance(item, StreamEvent) and item.mode in _KEPT_WHEN_FULL + return isinstance(item, StreamEvent) and is_kept_when_full(item.mode) def _remember(runs: "OrderedDict[str, None]", workflow_id: str) -> None: diff --git a/diagrid/agent/core/workflow/stream_cursor.py b/diagrid/agent/core/workflow/stream_cursor.py new file mode 100644 index 00000000..0a299a00 --- /dev/null +++ b/diagrid/agent/core/workflow/stream_cursor.py @@ -0,0 +1,99 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The SSE id of a stream read from the state-store event log. + +The id is where the client is in the run's log, in a form any replica (or a +restarted process) can resume from: ``v1..``. Steps are +barriers, so every unit of a step below ``base`` was read in full; for the +units of ``base`` and later that were read in part, ``positions`` holds the +attempt (its first 8 characters) and how many of its events were read, as +base64url JSON. The id grows with one step's parallelism, not with the run. + +``v1.start`` replays from the beginning and ``v1.end`` means the final event +was received. An id that does not parse replays from the start too. +""" + +import base64 +import binascii +import json +from dataclasses import dataclass +from typing import Optional, Tuple + +VERSION = "v1" +START_ID = f"{VERSION}.start" +END_ID = f"{VERSION}.end" +#: How much of an attempt id a cursor keeps: enough to tell attempts apart. +ATTEMPT_PREFIX = 8 + +#: ``(step, unit, attempt prefix, events read)`` +Position = Tuple[int, str, str, int] + + +@dataclass(frozen=True) +class StreamCursor: + """How far a client got in a run's event log.""" + + #: Units of steps below this were read in full; ``None``: nothing was. + base: Optional[int] = None + positions: Tuple[Position, ...] = () + #: The client has the final event. + at_end: bool = False + + def skips_step(self, step: int) -> bool: + """Whether every unit of ``step`` was already read.""" + return self.base is not None and step < self.base + + def position(self, step: int, unit: str) -> Optional[Tuple[str, int]]: + """``(attempt prefix, events read)`` of a unit read in part, else ``None``.""" + for p_step, p_unit, attempt, events in self.positions: + if p_step == step and p_unit == unit: + return attempt, events + return None + + +def encode_cursor(cursor: StreamCursor) -> str: + """The SSE id for ``cursor``.""" + if cursor.at_end: + return END_ID + if cursor.base is None and not cursor.positions: + return START_ID + payload = json.dumps( + [list(p) for p in cursor.positions], separators=(",", ":") + ).encode() + packed = base64.urlsafe_b64encode(payload).decode().rstrip("=") + return f"{VERSION}.{cursor.base if cursor.base is not None else -2}.{packed}" + + +def parse_cursor(text: Optional[str]) -> StreamCursor: + """The cursor an SSE id names; anything that does not parse is the start.""" + if text == END_ID: + return StreamCursor(at_end=True) + try: + return _parse(text or "") + except (ValueError, TypeError, binascii.Error): + return StreamCursor() + + +def _parse(text: str) -> StreamCursor: + version, base, packed = text.split(".", 2) + if version != VERSION: + raise ValueError(text) + padded = packed + "=" * (-len(packed) % 4) + raw = json.loads(base64.urlsafe_b64decode(padded.encode())) + if not isinstance(raw, list): + raise ValueError(text) + positions = tuple(_position(p) for p in raw) + step = int(base) + return StreamCursor(base=None if step == -2 else step, positions=positions) + + +def _position(item: object) -> Position: + if not isinstance(item, list) or len(item) != 4: + raise ValueError(item) + step, unit, attempt, events = item + if not isinstance(unit, str) or not isinstance(attempt, str): + raise ValueError(item) + if int(events) < 0: + raise ValueError(item) + return int(step), unit, attempt, int(events) diff --git a/diagrid/agent/core/workflow/stream_log.py b/diagrid/agent/core/workflow/stream_log.py new file mode 100644 index 00000000..a4e06ec0 --- /dev/null +++ b/diagrid/agent/core/workflow/stream_log.py @@ -0,0 +1,459 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A run's stream as an event log in a Dapr state store. + +Every activity execution (a *unit*: one node, ``Send`` task or router at one +step) appends its chunks in batches, and any replica reads them back from any +point. Keys use ``:`` between parts, each part path-escaped; ``||`` is never +used (Dapr reserves it for actor keys): + +- ``::::head``: ``{"attempt", "batches", "events", + "done"}``, rewritten after each batch, kept ``record_ttl_factor`` times + longer than the batches. +- ``:::::``: batch ``n`` of an attempt, a + list of events. + +A retried activity is a new attempt: it takes the head over, and a reader that +sees the attempt change starts that unit again (the consumer turns that into +``node_reset``). An attempt that finished (``done``) keeps the unit: a late +attempt is not written. A head whose count names a batch that is gone means +the log outlived its TTL: the reader reports it purged. +""" + +import itertools +import logging +import threading +import uuid +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, List, Optional, Protocol, Sequence, Tuple +from urllib.parse import quote + +from .stream import MAX_BUFFERED_EVENTS, StreamEvent, is_kept_when_full + +logger = logging.getLogger(__name__) + +#: ``(key, JSON value, Dapr state metadata)`` +LogItem = Tuple[str, Any, Dict[str, str]] + + +@dataclass(frozen=True) +class StateLogStreamConfig: + """How the state-store event log is written and read.""" + + #: The Dapr state store; the runner fills in its own when this is ``None``. + store_name: Optional[str] = None + key_prefix: str = "lgstream" + #: Seconds a batch is kept. + event_ttl_s: int = 3600 + #: Heads outlive batches by this factor, so a purge is told from a gap. + record_ttl_factor: int = 24 + flush_interval_s: float = 0.1 + flush_max_chunks: int = 64 + #: How often a reader looks for new batches. + read_poll_s: float = 0.2 + #: Events an activity holds while the store refuses writes; past it, + #: tokens and custom chunks are dropped, markers and updates never. + max_buffered: int = MAX_BUFFERED_EVENTS + + +class LogStore(Protocol): + """The two state calls the log needs.""" + + def save_bulk(self, items: Sequence[LogItem]) -> None: ... + + def get_bulk(self, keys: Sequence[str]) -> Dict[str, Any]: ... + + +class DaprLogStore: + """:class:`LogStore` on a Dapr state store, through the sidecar.""" + + def __init__(self, store_name: str) -> None: + self.store_name = store_name + self._client: Any = None + self._lock = threading.Lock() + + def _get_client(self) -> Any: + with self._lock: + if self._client is None: + from dapr.clients import DaprClient + + self._client = DaprClient() + return self._client + + def save_bulk(self, items: Sequence[LogItem]) -> None: + import json + + from dapr.clients.grpc._state import StateItem + + states = [ + StateItem(key=key, value=json.dumps(value), metadata=metadata) + for key, value, metadata in items + ] + self._get_client().save_bulk_state(store_name=self.store_name, states=states) + + def get_bulk(self, keys: Sequence[str]) -> Dict[str, Any]: + import json + + if not keys: + return {} + response = self._get_client().get_bulk_state( + store_name=self.store_name, keys=list(keys) + ) + found: Dict[str, Any] = {} + for item in response.items: + if getattr(item, "error", ""): + raise RuntimeError(f"state store read of {item.key!r}: {item.error}") + if item.data: + found[item.key] = json.loads(item.data) + return found + + +def escape_key_part(part: Any) -> str: + """One key part, path-escaped: no ``:``, ``#``, ``/`` or ``|`` is left.""" + return quote(str(part), safe="") + + +def _unit_prefix(prefix: str, workflow_id: str, step: int, unit: str) -> str: + return ":".join(escape_key_part(p) for p in (prefix, workflow_id, step, unit)) + + +def head_key(prefix: str, workflow_id: str, step: int, unit: str) -> str: + return f"{_unit_prefix(prefix, workflow_id, step, unit)}:head" + + +def batch_key( + prefix: str, workflow_id: str, step: int, unit: str, attempt: str, n: int +) -> str: + base = _unit_prefix(prefix, workflow_id, step, unit) + return f"{base}:{escape_key_part(attempt)}:{n}" + + +def wire_event( + event: StreamEvent, encode: Callable[[StreamEvent], Any] +) -> Dict[str, Any]: + """``event`` as the log stores it; ``encode`` makes its data JSON.""" + return { + "step": event.step, + "node": event.node, + "attempt": event.attempt_id, + "seq": event.seq, + "ns": list(event.ns), + "mode": event.mode, + "data": encode(event), + "display_node": event.display_node, + "path": list(event.path) if event.path else None, + "branch": event.branch, + } + + +def event_from_wire( + wire: Dict[str, Any], workflow_id: str, decode: Callable[[str, Any], Any] +) -> StreamEvent: + """The :class:`StreamEvent` a stored event stands for.""" + path = wire.get("path") + return StreamEvent( + workflow_id=workflow_id, + step=int(wire["step"]), + node=str(wire["node"]), + attempt_id=str(wire["attempt"]), + seq=int(wire["seq"]), + ns=tuple(wire.get("ns") or ()), + mode=str(wire["mode"]), + data=decode(str(wire["mode"]), wire.get("data")), + display_node=wire.get("display_node"), + path=tuple(path) if path else None, + branch=wire.get("branch"), + ) + + +def _ttl(seconds: int) -> Dict[str, str]: + return {"ttlInSeconds": str(int(seconds))} + + +class LogWriter: + """Appends one activity execution's chunks to its unit of the log. + + Flushes every ``flush_interval_s``, every ``flush_max_chunks`` chunks and + on :meth:`finish`, which writes synchronously, so the unit is complete + before the activity returns. A failed write is logged and counted, and + the chunks are tried again with the next flush; it never fails the node. + """ + + def __init__( + self, + store: LogStore, + config: StateLogStreamConfig, + workflow_id: str, + step: int, + unit: str, + *, + encode: Callable[[StreamEvent], Any], + ) -> None: + self._store = store + self._config = config + self._workflow_id = workflow_id + self._step = step + self._unit = unit + self._encode = encode + self.attempt = uuid.uuid4().hex + self._pending: List[Dict[str, Any]] = [] + self._buffer_lock = threading.Lock() + self._flush_lock = threading.Lock() + self._timer: Optional[threading.Timer] = None + self._batches = 0 + self._events = 0 + self._blocked: Optional[bool] = None + self._finished = False + self.write_failures = 0 + self.dropped = 0 + + def put(self, event: StreamEvent) -> None: + wire = wire_event(event, self._encode) + with self._buffer_lock: + if self._finished: + return + if len( + self._pending + ) >= self._config.max_buffered and not is_kept_when_full(event.mode): + self._note_dropped() + return + self._pending.append(wire) + full = len(self._pending) >= self._config.flush_max_chunks + if not full and self._timer is None: + self._timer = threading.Timer( + self._config.flush_interval_s, self._timed_flush + ) + self._timer.daemon = True + self._timer.start() + if full: + self._flush(done=False) + + def finish(self, *, done: bool) -> None: + """Write what is left; ``done`` marks the attempt as the unit's last.""" + with self._buffer_lock: + self._finished = True + timer, self._timer = self._timer, None + if timer is not None: + timer.cancel() + self._flush(done=done, final=True) + + def _note_dropped(self) -> None: + if not self.dropped: + logger.warning( + "Stream log of %s (%s) is full while the store refuses writes; " + "dropping token and custom chunks", + self._workflow_id, + self._unit, + ) + self.dropped += 1 + + def _timed_flush(self) -> None: + with self._buffer_lock: + self._timer = None + self._flush(done=False) + + def _flush(self, *, done: bool, final: bool = False) -> None: + with self._flush_lock: + with self._buffer_lock: + batch = list(self._pending) + if not batch and not final: + return + if self._is_blocked(): + with self._buffer_lock: + del self._pending[: len(batch)] + return + items: List[LogItem] = [] + if batch: + items.append( + ( + batch_key( + self._config.key_prefix, + self._workflow_id, + self._step, + self._unit, + self.attempt, + self._batches, + ), + batch, + _ttl(self._config.event_ttl_s), + ) + ) + if not items and not done: + return + batches = self._batches + (1 if batch else 0) + head = { + "attempt": self.attempt, + "batches": batches, + "events": self._events + len(batch), + "done": done, + } + items.append( + ( + head_key( + self._config.key_prefix, + self._workflow_id, + self._step, + self._unit, + ), + head, + _ttl(self._config.event_ttl_s * self._config.record_ttl_factor), + ) + ) + try: + self._store.save_bulk(items) + except Exception as e: # never fail the node over its stream + self.write_failures += 1 + logger.warning( + "Stream log write for %s (%s) failed (%s: %s); retrying with " + "the next batch", + self._workflow_id, + self._unit, + type(e).__name__, + e, + ) + return + self._batches = batches + self._events += len(batch) + with self._buffer_lock: + del self._pending[: len(batch)] + + def _is_blocked(self) -> bool: + """Whether an attempt that already finished owns the unit (read once).""" + if self._blocked is None: + key = head_key( + self._config.key_prefix, self._workflow_id, self._step, self._unit + ) + try: + head = self._store.get_bulk([key]).get(key) + except Exception as e: + logger.warning( + "Stream log head of %s (%s) could not be read (%s); writing anyway", + self._workflow_id, + self._unit, + e, + ) + head = None + self._blocked = bool( + isinstance(head, dict) + and head.get("done") + and head.get("attempt") != self.attempt + ) + return self._blocked + + +@dataclass(frozen=True) +class UnitWant: + """What a reader asks of one unit: what it has of it already.""" + + step: int + unit: str + #: The attempt it read so far (a prefix is enough); ``None``: none. + attempt: Optional[str] = None + #: The first batch it has not read, of ``attempt``. + from_batch: int = 0 + #: Events of the batches from ``from_batch`` on that it already has. + skip_events: int = 0 + + +@dataclass(frozen=True) +class UnitChunk: + """What a read found in one unit.""" + + step: int + unit: str + #: The unit's attempt now; ``None`` when it has no head yet. + attempt: Optional[str] = None + events: List[Dict[str, Any]] = field(default_factory=list) + #: Index, within the attempt, of the first event in ``events``. + start: int = 0 + #: Batches of the attempt there are (all read once these are). + batches: int = 0 + #: Events of the attempt there are. + total: int = 0 + done: bool = False + #: The attempt is not the one the reader asked about: start again. + reset: bool = False + #: A batch the head counts is gone (TTL): the log cannot be replayed. + purged: bool = False + + +class LogReader: + """Reads units of one run's log: heads in one round trip, batches in another. + + A store that fails raises: a reader must say so, never return an empty + stream as if nothing had happened. + """ + + def __init__( + self, store: LogStore, config: StateLogStreamConfig, workflow_id: str + ) -> None: + self._store = store + self._config = config + self._workflow_id = workflow_id + + def read(self, wants: Sequence[UnitWant]) -> List[UnitChunk]: + prefix = self._config.key_prefix + head_keys = [head_key(prefix, self._workflow_id, w.step, w.unit) for w in wants] + heads = self._store.get_bulk(head_keys) if head_keys else {} + plans: List[Tuple[UnitWant, Dict[str, Any], bool, List[str]]] = [] + for want, key in zip(wants, head_keys): + head = heads.get(key) + if not isinstance(head, dict): + plans.append((want, {}, False, [])) + continue + attempt = str(head.get("attempt")) + reset = bool(want.attempt) and not attempt.startswith(str(want.attempt)) + first = 0 if reset else want.from_batch + keys = [ + batch_key(prefix, self._workflow_id, want.step, want.unit, attempt, n) + for n in range(first, int(head.get("batches") or 0)) + ] + plans.append((want, head, reset, keys)) + wanted = list(itertools.chain.from_iterable(p[3] for p in plans)) + batches = self._store.get_bulk(wanted) if wanted else {} + return [ + self._chunk(want, head, reset, keys, batches) + for want, head, reset, keys in plans + ] + + def _chunk( + self, + want: UnitWant, + head: Dict[str, Any], + reset: bool, + keys: List[str], + batches: Dict[str, Any], + ) -> UnitChunk: + if not head: + return UnitChunk(want.step, want.unit) + attempt = str(head["attempt"]) + total = int(head.get("events") or 0) + count = int(head.get("batches") or 0) + done = bool(head.get("done")) + if any(key not in batches for key in keys): + return UnitChunk( + want.step, + want.unit, + attempt, + batches=count, + total=total, + done=done, + reset=reset, + purged=True, + ) + events = [e for key in keys for e in batches[key]] + skip = 0 if reset else min(want.skip_events, len(events)) + # the events of batches before the first one read are not in ``events`` + before = 0 if reset else max(0, total - len(events)) + return UnitChunk( + want.step, + want.unit, + attempt, + events=events[skip:], + start=before + skip, + batches=count, + total=total, + done=done, + reset=reset, + ) diff --git a/tests/agent/core/test_stream_cursor.py b/tests/agent/core/test_stream_cursor.py index 39a4d275..30b3fee5 100644 --- a/tests/agent/core/test_stream_cursor.py +++ b/tests/agent/core/test_stream_cursor.py @@ -18,7 +18,10 @@ class TestStreamCursor(unittest.TestCase): def test_round_trip(self): cursor = StreamCursor( base=3, - positions=((3, "research#0", "a1b2c3d4", 7), (3, "review:branch:route", "ffff0000", 2)), + positions=( + (3, "research#0", "a1b2c3d4", 7), + (3, "review:branch:route", "ffff0000", 2), + ), ) text = encode_cursor(cursor) self.assertTrue(text.startswith("v1.3.")) @@ -27,7 +30,9 @@ def test_round_trip(self): self.assertIsNone(cursor.position(3, "other")) def test_negative_base_round_trips(self): - cursor = StreamCursor(base=-1, positions=((-1, "__start__:branch:c", "abcd1234", 1),)) + cursor = StreamCursor( + base=-1, positions=((-1, "__start__:branch:c", "abcd1234", 1),) + ) self.assertEqual(parse_cursor(encode_cursor(cursor)), cursor) def test_fixed_ids(self): @@ -37,7 +42,16 @@ def test_fixed_ids(self): self.assertEqual(encode_cursor(StreamCursor(at_end=True)), END_ID) def test_missing_or_junk_replays_from_the_start(self): - for junk in (None, "", "17", "v1", "v1.x.y", "v2.1.abc", "v1.1.!!!", "v1.1.e30"): + for junk in ( + None, + "", + "17", + "v1", + "v1.x.y", + "v2.1.abc", + "v1.1.!!!", + "v1.1.e30", + ): with self.subTest(junk=junk): self.assertEqual(parse_cursor(junk), StreamCursor()) diff --git a/tests/agent/core/test_stream_log.py b/tests/agent/core/test_stream_log.py index 97b22a77..34b392e7 100644 --- a/tests/agent/core/test_stream_log.py +++ b/tests/agent/core/test_stream_log.py @@ -32,7 +32,9 @@ def _config(**kw: Any) -> StateLogStreamConfig: return StateLogStreamConfig(**base) -def _event(node: str, seq: int, mode: str = "messages", attempt: str = "att") -> StreamEvent: +def _event( + node: str, seq: int, mode: str = "messages", attempt: str = "att" +) -> StreamEvent: return StreamEvent("wf:1", 0, node, attempt, seq, (), mode, f"{node}-{seq}") @@ -56,9 +58,7 @@ def test_parts_are_escaped_and_never_use_the_actor_separator(self): self.assertTrue(head_key("lgstream", "wf:1", 3, "n").endswith(":head")) def test_distinct_units_never_share_a_key(self): - self.assertNotEqual( - head_key("p", "w", 1, "a:b"), head_key("p", "w:1", 1, "b") - ) + self.assertNotEqual(head_key("p", "w", 1, "a:b"), head_key("p", "w:1", 1, "b")) class TestWriter(unittest.TestCase): @@ -110,9 +110,7 @@ def test_a_write_error_never_raises_and_is_retried(self): self.assertEqual(writer.write_failures, 1) writer.put(_event("research#0", 1)) writer.finish(done=True) - chunk = LogReader(store, _config(), "wf:1").read( - [UnitWant(0, "research#0")] - )[0] + chunk = LogReader(store, _config(), "wf:1").read([UnitWant(0, "research#0")])[0] self.assertEqual(_datas(chunk), ["research#0-0", "research#0-1"]) def test_a_failed_last_flush_leaves_the_unit_not_done(self): @@ -134,9 +132,7 @@ def test_a_full_buffer_never_drops_internal_markers(self): writer.put(_event("review:branch:route", 0, BRANCH_DONE)) store.fail_saves = 0 writer.finish(done=True) - chunk = LogReader(store, _config(), "wf:1").read( - [UnitWant(0, "research#0")] - )[0] + chunk = LogReader(store, _config(), "wf:1").read([UnitWant(0, "research#0")])[0] modes = [e["mode"] for e in chunk.events] self.assertIn(UPDATES, modes) self.assertIn(BRANCH_DONE, modes) @@ -167,8 +163,17 @@ def test_a_done_unit_blocks_a_late_attempt(self): def test_events_keep_their_identity_on_the_wire(self): event = StreamEvent( - "wf", 2, "research#1", "att", 4, ("x",), "messages", "d", - display_node="research", path=("__pregel_push", 1, False), branch=None, + "wf", + 2, + "research#1", + "att", + 4, + ("x",), + "messages", + "d", + display_node="research", + path=("__pregel_push", 1, False), + branch=None, ) wire = wire_event(event, lambda e: e.data) self.assertEqual(wire["node"], "research#1") From e9a0956fce0fc78e50f62103a349af7db17092e4 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 12:33:12 +0100 Subject: [PATCH 35/73] test(langgraph): expect streams to go through the state-store log whenever the runner has a store Signed-off-by: Casper Nielsen --- tests/agent/langgraph/log_helpers.py | 159 +++++++++++++++ .../agent/langgraph/test_stream_transport.py | 181 ++++++++++++++++++ 2 files changed, 340 insertions(+) create mode 100644 tests/agent/langgraph/log_helpers.py create mode 100644 tests/agent/langgraph/test_stream_transport.py diff --git a/tests/agent/langgraph/log_helpers.py b/tests/agent/langgraph/log_helpers.py new file mode 100644 index 00000000..7f741626 --- /dev/null +++ b/tests/agent/langgraph/log_helpers.py @@ -0,0 +1,159 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Runs streamed through the state-store event log, with a fake store and client. + +The workflow runs inline on a thread (as in the golden harness) and records the +custom status it sets, which is how a reader on any replica finds the run's +units. ``activity_runner`` lets another runner's activities (another replica +of the app) run the nodes while the first one serves the stream. +""" + +import json +import threading +from types import SimpleNamespace +from typing import Any, Dict, Optional +from unittest import mock + +from dapr.ext.workflow import WorkflowStatus + +from diagrid.agent.core.workflow.stream_log import ( + StateLogStreamConfig, + StateLogTransport, +) +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.models import GraphWorkflowInput + +from ..core.log_store_fake import FakeLogStore +from .streaming_helpers import _IdCtx + +FAST = StateLogStreamConfig(flush_interval_s=0.01, flush_max_chunks=4, read_poll_s=0.01) + + +class StatusCtx(_IdCtx): + """An inline workflow context that keeps the custom status the run sets.""" + + def __init__(self, runner: Any, workflow_id: str, client: "LogClient") -> None: + super().__init__(runner, workflow_id) + self.instance_id = workflow_id + self._client = client + + def set_custom_status(self, status: str) -> None: + self._client.custom[self._workflow_id] = status + + def wait_for_external_event(self, name: str) -> Any: + return self._client.wait_event(self._workflow_id, name) + + +class LogClient: + """A workflow client: schedules ``agent_workflow`` on a thread, answers polls.""" + + def __init__( + self, runner: DaprWorkflowGraphRunner, activity_runner: Any = None + ) -> None: + self._runner = runner + self._activity_runner = activity_runner or runner + self.done: Dict[str, Any] = {} + self.failed: Dict[str, str] = {} + self.custom: Dict[str, str] = {} + self.inputs: Dict[str, Any] = {} + self._events: Dict[str, Any] = {} + self._cond = threading.Condition() + + def schedule_new_workflow(self, *, workflow: Any, input: Any, instance_id: str): + self.inputs[instance_id] = json.loads(json.dumps(input)) + threading.Thread( + target=self._work, args=(input, instance_id), daemon=True + ).start() + + def _work(self, input: Any, instance_id: str) -> None: + from diagrid.agent.langgraph.workflow import agent_workflow + + wf_input = GraphWorkflowInput.from_dict(json.loads(json.dumps(input))) + ctx = StatusCtx(self._activity_runner, instance_id, self) + try: + with mock.patch( + "diagrid.agent.langgraph.workflow.when_all", side_effect=list + ): + workflow = agent_workflow( + ctx, json.loads(json.dumps(wf_input.to_dict())) + ) + result = None + try: + while True: + result = workflow.send(result) + except StopIteration as stop: + self.done[instance_id] = stop.value + except Exception as e: # the workflow failed + self.failed[instance_id] = str(e) + + def raise_workflow_event(self, instance_id: str, event_name: str, data: Any = None): + with self._cond: + self._events[f"{instance_id}/{event_name}"] = json.loads(json.dumps(data)) + self._cond.notify_all() + + def wait_event(self, instance_id: str, name: str) -> Any: + key = f"{instance_id}/{name}" + with self._cond: + self._cond.wait_for(lambda: key in self._events, timeout=30) + return self._events.pop(key, None) + + def get_workflow_state(self, *, instance_id: str, fetch_payloads: bool = True): + if instance_id not in self.inputs: + return None + common = dict( + serialized_custom_status=self.custom.get(instance_id), + serialized_input=json.dumps(self.inputs[instance_id]), + created_at=None, + last_updated_at=None, + ) + if instance_id in self.failed: + return SimpleNamespace( + runtime_status=WorkflowStatus.FAILED, + serialized_output=None, + failure_details=SimpleNamespace(message=self.failed[instance_id]), + **common, + ) + output = self.done.get(instance_id) + if output is None: + return SimpleNamespace( + runtime_status=WorkflowStatus.RUNNING, + serialized_output=None, + failure_details=None, + **common, + ) + return SimpleNamespace( + runtime_status=WorkflowStatus.COMPLETED, + serialized_output=json.dumps(output), + failure_details=None, + **common, + ) + + +def log_runner( + compiled: Any, + name: str, + *, + store: Optional[FakeLogStore] = None, + config: StateLogStreamConfig = FAST, + activity_runner: Any = None, +) -> DaprWorkflowGraphRunner: + """A started runner whose streams go through ``store``'s event log.""" + store = store if store is not None else FakeLogStore() + runner = DaprWorkflowGraphRunner( + graph=compiled, + name=name, + stream_transport=StateLogTransport(config, store=store), + ) + runner._started = True + runner._workflow_client = LogClient(runner, activity_runner) # type: ignore[assignment] + return runner + + +def replica(compiled: Any, name: str, store: FakeLogStore) -> DaprWorkflowGraphRunner: + """Another process of the same app: same graph, same store, its own activities.""" + return DaprWorkflowGraphRunner( + graph=compiled, + name=name, + stream_transport=StateLogTransport(FAST, store=store), + ) diff --git a/tests/agent/langgraph/test_stream_transport.py b/tests/agent/langgraph/test_stream_transport.py new file mode 100644 index 00000000..192572d0 --- /dev/null +++ b/tests/agent/langgraph/test_stream_transport.py @@ -0,0 +1,181 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Which transport a runner streams through, and what the state-store log delivers.""" + +import json +import unittest +from typing import Any, List +from unittest import mock + +from fastapi.testclient import TestClient + +from diagrid.agent.core.discovery import DiscoveredComponents +from diagrid.agent.core.workflow import stream as stream_module +from diagrid.agent.core.workflow.stream import ( + InProcessTransport, + StreamSinkRegistry, +) +from diagrid.agent.core.workflow.stream_cursor import ( + END_ID, + START_ID, + parse_cursor, +) +from diagrid.agent.core.workflow.stream_log import ( + StateLogStreamConfig, + StateLogTransport, +) +from diagrid.agent.langgraph import DaprWorkflowGraphRunner + +from ..core.log_store_fake import FakeLogStore +from .golden_harness import MODES, _both, _golden_graph, _Golden, _wire +from .log_helpers import FAST, log_runner, replica +from .streaming_helpers import INPUT, _collect, serve_app +from .test_runner import _RunnerTestCase + + +def _discovered(**kw: Any) -> Any: + return mock.patch( + "diagrid.agent.core.workflow.runner.discover_components", + return_value=DiscoveredComponents(**kw), + ) + + +class TestTransportChoice(_RunnerTestCase): + def test_no_state_store_streams_in_process(self): + runner = DaprWorkflowGraphRunner(graph=_golden_graph(), name="t-none") + self.assertIsInstance(runner.stream_transport, InProcessTransport) + self.assertFalse(runner.stream_transport.replayable) + + def test_the_app_memory_store_turns_the_event_log_on(self): + with _discovered(memory_store_name="agent-memory"): + runner = DaprWorkflowGraphRunner(graph=_golden_graph(), name="t-mem") + transport = runner.stream_transport + self.assertIsInstance(transport, StateLogTransport) + self.assertTrue(transport.replayable) + self.assertEqual(transport.store_name, "agent-memory") + + def test_the_workflow_state_store_is_enough(self): + # every workflow app has one: no component, variable or argument to add + with _discovered(workflow_store_name="agent-workflow"): + runner = DaprWorkflowGraphRunner(graph=_golden_graph(), name="t-wf") + self.assertIsInstance(runner.stream_transport, StateLogTransport) + self.assertEqual(runner.stream_transport.store_name, "agent-workflow") + + def test_a_given_transport_wins(self): + mine = StateLogTransport(StateLogStreamConfig(store_name="mine")) + with _discovered(memory_store_name="agent-memory"): + runner = DaprWorkflowGraphRunner( + graph=_golden_graph(), name="t-own", stream_transport=mine + ) + self.assertEqual(runner.stream_transport.store_name, "mine") + + def test_a_given_registry_keeps_the_in_process_transport(self): + registry = StreamSinkRegistry() + with _discovered(memory_store_name="agent-memory"): + runner = DaprWorkflowGraphRunner( + graph=_golden_graph(), name="t-reg", stream_registry=registry + ) + self.assertIsInstance(runner.stream_transport, InProcessTransport) + self.assertIs(runner.stream_registry, registry) + + +class TestStateLogStream(_Golden): + async def _astream(self, runner: Any, wf: str, **kw: Any) -> List[Any]: + return await _collect( + runner.astream( + INPUT, + thread_id="t1", + config={"tags": ["x"], "metadata": {"foo": "bar"}}, + workflow_id=wf, + stream_mode=kw.pop("modes", MODES), + poll_interval=0.01, + **kw, + ) + ) + + async def test_the_same_chunks_as_the_in_process_transport(self): + _, in_process = await _both(_golden_graph(), "golden-ip", INPUT) + runner = log_runner(_golden_graph(), "golden-log") + ours = await self._astream(runner, "wf-golden-log") + self.assertEqual(_wire(ours), _wire(in_process)) + + async def test_chunks_of_nodes_on_another_replica_arrive(self): + store = FakeLogStore() + other = replica(_golden_graph(), "two", store) + runner = log_runner(_golden_graph(), "two", store=store, activity_runner=other) + controls: List[Any] = [] + ours = await self._astream(runner, "wf-two", on_control=controls.append) + self.assertEqual({m for m, _ in ours}, {"messages", "updates", "custom"}) + updates = [p for m, p in ours if m == "updates"] + self.assertEqual([list(u) for u in updates], [["chat"], ["counter"], ["quiet"]]) + self.assertNotIn("stream_unavailable", [c.kind for c in controls]) + + async def test_a_slow_consumer_loses_nothing(self): + runner = log_runner(_golden_graph(), "slow") + with mock.patch.object(stream_module, "MAX_BUFFERED_EVENTS", 2): + controls: List[Any] = [] + ours = await self._astream(runner, "wf-slow", on_control=controls.append) + self.assertNotIn("stream_dropped", [c.kind for c in controls]) + self.assertEqual(len([m for m, _ in ours if m == "messages"]), 5) + + async def test_writes_that_fail_are_reported_as_write_failed(self): + store = FakeLogStore() + store.fail_saves = 10_000 + runner = log_runner(_golden_graph(), "wfail", store=store) + controls: List[Any] = [] + await self._astream(runner, "wf-wfail", on_control=controls.append) + unavailable = [c.data for c in controls if c.kind == "stream_unavailable"] + self.assertEqual(len(unavailable), 1) + self.assertEqual(unavailable[0]["reason"], "write_failed") + self.assertEqual( + [m["node"] for m in unavailable[0]["missing_nodes"]], + ["chat", "counter", "quiet"], + ) + + async def test_a_store_that_cannot_be_read_is_an_error_not_an_empty_stream(self): + store = FakeLogStore() + runner = log_runner(_golden_graph(), "rfail", store=store) + store.fail_gets = 10_000 + with self.assertRaises(Exception) as caught: + await self._astream(runner, "wf-rfail") + self.assertIn("StreamReadError", repr(getattr(caught.exception, "final", ""))) + + async def test_a_run_nobody_streams_writes_no_log(self): + store = FakeLogStore() + runner = log_runner(_golden_graph(), "plain", store=store) + result = [ + e + async for e in runner.run_async( + INPUT, workflow_id="wf-plain", poll_interval=0.01 + ) + ] + self.assertEqual(result[-1]["type"], "workflow_completed") + self.assertEqual(store.data, {}) + + +class TestStateLogSse(_RunnerTestCase): + def test_every_event_has_an_id_any_replica_can_resume_from(self): + runner = log_runner(_golden_graph(), "sse-ids") + resp = TestClient(serve_app(runner)).post( + "/agent/run", json={"messages": INPUT["messages"], "stream": True} + ) + frames = [f for f in resp.text.strip().split("\n\n") if not f.startswith(":")] + ids = [f.split("\n")[0] for f in frames] + self.assertTrue(all(i.startswith("id: ") for i in ids), ids) + ids = [i[4:] for i in ids] + self.assertEqual(ids[0], START_ID) + self.assertEqual(ids[-1], END_ID) + for event_id in ids[1:-1]: + self.assertNotEqual( + parse_cursor(event_id), parse_cursor(START_ID), event_id + ) + names = [f.split("\n")[1] for f in frames] + self.assertEqual(names[-1], "event: workflow_completed") + self.assertEqual( + json.loads(frames[-1].split("data: ", 1)[1])["status"], "completed" + ) + + +if __name__ == "__main__": + unittest.main() From 83ebfd523fd463f166f61ea6e6d20f90092776eb Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 14:10:18 +0100 Subject: [PATCH 36/73] feat(langgraph): stream through the state-store event log whenever the runner has a store Activities ask the runner's stream transport for a writer once per execution. With a state store (the app's agent-memory store, else the workflow's own actor state store, which every workflow app has) chunks go to the event log and the serving replica reads them back, so a stream carries every node whichever replica ran it. Without one the in-process transport stays. SSE ids are resumable cursors on the log transport. Signed-off-by: Casper Nielsen --- diagrid/agent/core/discovery.py | 9 + diagrid/agent/core/workflow/runner.py | 5 + diagrid/agent/core/workflow/stream.py | 153 ++++++++- diagrid/agent/core/workflow/stream_log.py | 62 ++++ diagrid/agent/deepagents/runner.py | 5 + diagrid/agent/langgraph/README.md | 1 + diagrid/agent/langgraph/activity_stream.py | 81 +++++ diagrid/agent/langgraph/node_routes.py | 6 +- diagrid/agent/langgraph/runner.py | 98 +++++- diagrid/agent/langgraph/stream_events.py | 15 +- diagrid/agent/langgraph/stream_follow.py | 294 ++++++++++++++++++ diagrid/agent/langgraph/stream_source.py | 136 ++++++++ diagrid/agent/langgraph/streaming.py | 13 +- diagrid/agent/langgraph/workflow.py | 183 +++++------ tests/agent/langgraph/log_helpers.py | 7 +- .../agent/langgraph/test_stream_transport.py | 5 +- .../langgraph/test_streaming_activity.py | 2 +- .../agent/langgraph/test_streaming_events.py | 7 +- tests/agent/langgraph/test_streaming_sink.py | 2 +- 19 files changed, 945 insertions(+), 139 deletions(-) create mode 100644 diagrid/agent/langgraph/activity_stream.py create mode 100644 diagrid/agent/langgraph/stream_follow.py create mode 100644 diagrid/agent/langgraph/stream_source.py diff --git a/diagrid/agent/core/discovery.py b/diagrid/agent/core/discovery.py index 6cde2a5d..34a57266 100644 --- a/diagrid/agent/core/discovery.py +++ b/diagrid/agent/core/discovery.py @@ -41,6 +41,10 @@ class DiscoveredComponents: registry_store_name: Optional[str] = None """``state`` type component named ``agent-registry``.""" + workflow_store_name: Optional[str] = None + """The ``state`` type component workflows keep their state in (the actor + state store): every workflow app has one.""" + runtime_conf: dict[str, str] = field(default_factory=dict) """Config loaded from ``agent-runtime`` statestore key ``agent_runtime``.""" @@ -53,6 +57,7 @@ def discover_components() -> DiscoveredComponents: - ``state`` type + name ``agent-memory`` -> ``memory_store_name`` - ``pubsub`` type + name ``agent-pubsub`` -> ``pubsub_name`` - ``state`` type + name ``agent-registry`` -> ``registry_store_name`` + - ``state`` type with the ``ACTOR`` capability -> ``workflow_store_name`` - ``state`` type + name ``agent-runtime`` -> loads ``agent_runtime`` key into ``runtime_conf`` Returns ``DiscoveredComponents()`` with empty defaults on sidecar error. @@ -81,6 +86,10 @@ def discover_components() -> DiscoveredComponents: if "pubsub" in ctype and cname == "agent-pubsub": result.pubsub_name = cname + capabilities = getattr(component, "capabilities", None) or () + if "state" in ctype and "ACTOR" in capabilities: + result.workflow_store_name = cname + if "state" in ctype and cname == "agent-registry": result.registry_store_name = cname diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 6e01cb94..0f64dbb0 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -297,6 +297,11 @@ def __init__( runtime_conf=discovered.runtime_conf or None, ) + #: The state store workflows keep their state in, if discovery saw one. + self._workflow_store_name: Optional[str] = getattr( + discovered, "workflow_store_name", None + ) + # Auto-configure state store from discovery if not explicitly provided if self._state_store is None and discovered.memory_store_name: from diagrid.agent.core.state import DaprStateStore diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index 3bccfcc4..59e94485 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -4,10 +4,11 @@ """Transport for streaming chunks out of workflow activities. Activities run in worker threads; the HTTP connection that wants the chunks -lives on the asyncio loop of the API. A :class:`StreamSink` sits between them. -Only the in-process sink exists today (single replica: activity and API share -a process). :func:`get_stream_sink` is the seam for a later cross-replica sink: -it is the only place an activity looks a sink up. +lives on the asyncio loop of the API. A :class:`StreamTransport` hands each +activity execution a writer, and the serving side reads what it wrote. Two +exist: :class:`InProcessTransport` (activity and API share a process, a single +replica) and the state-store event log (``stream_log.StateLogTransport``), +which any replica can read and resume from. """ import asyncio @@ -34,10 +35,12 @@ NODE_RESET = "node_reset" STREAM_UNAVAILABLE = "stream_unavailable" STREAM_DROPPED = "stream_dropped" +#: The run's event log outlived its TTL: what is left cannot be replayed. +STREAM_PURGED = "stream_purged" #: First event of a stream: the ids a client needs to find or stop its run. WORKFLOW_STARTED = "workflow_started" # Events about the stream itself, delivered whatever stream modes were asked for. -CONTROL_MODES = (WORKFLOW_STARTED, NODE_RESET, STREAM_UNAVAILABLE) +CONTROL_MODES = (WORKFLOW_STARTED, NODE_RESET, STREAM_UNAVAILABLE, STREAM_PURGED) #: Internal marker: a conditional edge's function finished streaming here. It #: tells the stream which routers ran in this process and never reaches a client. BRANCH_DONE = "branch_done" @@ -85,6 +88,9 @@ class StreamEvent: #: The conditional edge whose function sent the chunk, so a retry of that #: function is not taken for a retry of the node itself. branch: Optional[str] = None + #: The SSE id of the stream after this event, when the transport can + #: resume from it (the state-store log); ``None`` otherwise. + event_id: Optional[str] = None def reset_data(self) -> Dict[str, Any]: """The ``node_reset`` payload for a retry of this event's task. @@ -135,8 +141,17 @@ class InProcessSink: is kept and any later one dropped, with no ``node_reset``. """ - def __init__(self, workflow_id: str, loop: asyncio.AbstractEventLoop) -> None: + def __init__( + self, + workflow_id: str, + loop: asyncio.AbstractEventLoop, + *, + bounded: bool = True, + ) -> None: self.workflow_id = workflow_id + #: ``False`` when the writer waits for room itself (a log reader), so + #: nothing is ever dropped here. + self._bounded = bounded self._loop = loop self._queue: "asyncio.Queue[Any]" = asyncio.Queue() self._lock = threading.Lock() @@ -192,6 +207,19 @@ def close(self, final: Optional[Dict[str, Any]] = None) -> None: async def get(self) -> Any: return await self._queue.get() + def backlog(self) -> int: + """Items waiting for the consumer.""" + return self._queue.qsize() + + def prime(self, step: int, node: str, attempt_id: str) -> None: + """Take ``attempt_id`` as the owner of ``(step, node)`` without a chunk. + + A stream resumed from a cursor uses it for an attempt the client saw + part of: the next attempt's first chunk then sends ``node_reset``. + """ + with self._lock: + self._owner.setdefault((step, node), attempt_id) + def _enqueue(self, item: Any) -> None: def _put() -> None: # Runs on the loop thread in the order chunks were handed over, so @@ -204,8 +232,10 @@ def _put() -> None: self.workflow_id, self._dropped, ) - elif self._queue.qsize() >= MAX_BUFFERED_EVENTS and not _is_kept_when_full( - item + elif ( + self._bounded + and self._queue.qsize() >= MAX_BUFFERED_EVENTS + and not _is_kept_when_full(item) ): if not self._dropped: logger.warning( @@ -316,6 +346,93 @@ def get(self, workflow_id: Optional[str]) -> Optional[InProcessSink]: default_registry = StreamSinkRegistry() +class ActivityStreamWriter(Protocol): + """What one activity execution writes its chunks to.""" + + def put(self, event: StreamEvent) -> None: ... + + def finish(self, *, done: bool) -> None: + """The execution ended; ``done`` when it is the task's last attempt.""" + ... + + +class StreamTransport(Protocol): + """How a streamed run's chunks get from its activities to its stream.""" + + #: Whether a stream can be read again from a cursor (reconnect, replay). + replayable: bool + + def writer( + self, workflow_id: str, step: int, unit: str, *, streamed: bool + ) -> Optional[ActivityStreamWriter]: + """The writer for one execution of ``unit`` at ``step``, or ``None``.""" + ... + + +class _SinkWriter: + """An in-process sink as an activity's writer: nothing to flush.""" + + def __init__(self, sink: InProcessSink) -> None: + self._sink = sink + + def put(self, event: StreamEvent) -> None: + self._sink.put(event) + + def finish(self, *, done: bool) -> None: + return None + + +class InProcessTransport: + """Chunks go to the sink a stream opened in this process, if there is one. + + Works while the activities run in the process that serves the stream (a + single replica); a chunk written anywhere else is lost, and the stream + says so with ``stream_unavailable``. Nothing can be replayed. + """ + + replayable = False + + def __init__(self, registry: Optional[StreamSinkRegistry] = None) -> None: + self.registry = registry if registry is not None else default_registry + + def writer( + self, workflow_id: str, step: int, unit: str, *, streamed: bool + ) -> Optional[ActivityStreamWriter]: + sink = self.registry.get(workflow_id) + if sink is None: + if streamed: + _warn_sink_missing(self.registry, workflow_id, unit) + return None + return _SinkWriter(sink) + + +def _warn_sink_missing( + registry: StreamSinkRegistry, workflow_id: str, unit: str +) -> None: + """Say, once per run, that a streamed run's chunks are going nowhere.""" + if not registry.first_report(workflow_id): + return + if registry.was_closed(workflow_id): + # This process had the stream and it ended (the client left, or the + # run's stream was closed): not a second replica, nothing to act on. + logger.debug( + "Run %s: its stream was closed in this process (its consumer left " + "or the stream ended); chunks of %r are not delivered", + workflow_id, + unit, + ) + return + logger.warning( + "Run %s is streamed but this process has no stream sink for it, so the " + "chunks of %r (and of any node that runs here) are not delivered. " + "The activity is running in another process (several replicas) or the " + "run outlived the process that streams it. Give the app a state store " + "to stream across replicas; the run itself is unaffected.", + workflow_id, + unit, + ) + + def get_stream_sink( workflow_id: Optional[str], *, registry: Optional[StreamSinkRegistry] = None ) -> Optional[StreamSink]: @@ -327,7 +444,7 @@ def get_stream_sink( return (registry or default_registry).get(workflow_id) -def format_sse(event: str, data: Any, event_id: Optional[int] = None) -> str: +def format_sse(event: str, data: Any, event_id: Optional[Any] = None) -> str: """Frame one Server-Sent Event (a keepalive is a comment, not an event).""" if event == KEEPALIVE_EVENT: return ": keepalive\n\n" @@ -341,18 +458,22 @@ def format_sse(event: str, data: Any, event_id: Optional[int] = None) -> str: return "\n".join(lines) + "\n\n" -async def frame_sse(events: AsyncIterator[Tuple[str, Any]]) -> AsyncIterator[str]: - """Frame ``(event, data)`` pairs as SSE. +async def frame_sse(events: AsyncIterator[Tuple[Any, ...]]) -> AsyncIterator[str]: + """Frame ``(event, data)`` or ``(event, data, id)`` items as SSE. The only place a streamed run is turned into SSE frames, so a runner just - yields pairs. Publishing is the runner's job (``on_result``). + yields pairs. An item that brings its own id (a cursor a client can resume + from) is sent with it; otherwise events are numbered on this connection. + Publishing is the runner's job (``on_result``). """ - event_id = 0 + counter = 0 try: - async for name, data in events: + async for item in events: + name, data = item[0], item[1] + given = item[2] if len(item) > 2 else None if name != KEEPALIVE_EVENT: - event_id += 1 - yield format_sse(name, data, event_id) + counter += 1 + yield format_sse(name, data, given if given is not None else counter) finally: # A client that disconnects ends the generator at a yield; close the # runner's stream now rather than when it is collected. diff --git a/diagrid/agent/core/workflow/stream_log.py b/diagrid/agent/core/workflow/stream_log.py index a4e06ec0..4d5224e5 100644 --- a/diagrid/agent/core/workflow/stream_log.py +++ b/diagrid/agent/core/workflow/stream_log.py @@ -457,3 +457,65 @@ def _chunk( done=done, reset=reset, ) + + +def _json_data(event: StreamEvent) -> Any: + return event.data + + +def _as_is(mode: str, data: Any) -> Any: + return data + + +class StateLogTransport: + """Streams through the state-store event log: any replica reads, any time. + + ``store`` defaults to the Dapr state store ``config.store_name``. ``encode`` + turns a chunk's data into JSON for the log and ``decode`` turns it back; a + runner binds its own with :meth:`with_codec`. + """ + + replayable = True + + def __init__( + self, + config: Optional[StateLogStreamConfig] = None, + *, + store: Optional[LogStore] = None, + encode: Callable[[StreamEvent], Any] = _json_data, + decode: Callable[[str, Any], Any] = _as_is, + ) -> None: + self.config = config or StateLogStreamConfig() + if store is None: + if not self.config.store_name: + raise ValueError("StateLogTransport needs a store or a store_name") + store = DaprLogStore(self.config.store_name) + self.store = store + self.encode = encode + self.decode = decode + + @property + def store_name(self) -> Optional[str]: + return self.config.store_name or getattr(self.store, "store_name", None) + + def with_codec( + self, + encode: Callable[[StreamEvent], Any], + decode: Callable[[str, Any], Any], + ) -> "StateLogTransport": + """A transport on the same store that encodes and decodes this way.""" + return StateLogTransport( + self.config, store=self.store, encode=encode, decode=decode + ) + + def writer( + self, workflow_id: str, step: int, unit: str, *, streamed: bool + ) -> Optional[LogWriter]: + if not streamed: + return None + return LogWriter( + self.store, self.config, workflow_id, step, unit, encode=self.encode + ) + + def reader(self, workflow_id: str) -> LogReader: + return LogReader(self.store, self.config, workflow_id) diff --git a/diagrid/agent/deepagents/runner.py b/diagrid/agent/deepagents/runner.py index 257495e3..aa332e20 100644 --- a/diagrid/agent/deepagents/runner.py +++ b/diagrid/agent/deepagents/runner.py @@ -67,6 +67,7 @@ def __init__( goal: Optional[str] = None, registry_config: Optional[Any] = None, stream_registry: Optional["StreamSinkRegistry"] = None, + stream_transport: Optional[Any] = None, ): """Initialize the runner. @@ -82,6 +83,9 @@ def __init__( stream_registry: Where streamed runs register their sinks (see :class:`DaprWorkflowGraphRunner`); each runner owns one by default. + stream_transport: How streamed runs get their chunks (see + :class:`DaprWorkflowGraphRunner`); by default the state-store + event log when the app has a state store. """ super().__init__( graph=agent, @@ -93,6 +97,7 @@ def __init__( goal=goal, registry_config=registry_config, stream_registry=stream_registry, + stream_transport=stream_transport, ) @property diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 70857239..b0f1a0a1 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -172,6 +172,7 @@ objects (`kind`, `data`): | `workflow_started` | `{"workflow_id", "thread_id"}` | The first event, sent once the workflow has been scheduled, so `GET /agent/run/{workflow_id}` finds the run as soon as the event arrives (a run that could not be scheduled ends with `workflow_failed` and has none): the ids to use with `terminate_workflow` or `get_workflow_status`. Delivered only to `on_control`, never yielded. | | `node_reset` | `{"node", "step"}`, plus `"path"` for a `Send` task | A node was retried; drop its partial output. `node` and `step` are the `langgraph_node` and `langgraph_step` of that node's `messages` metadata (`step` is numbered from 1). A task started by a `Send` also carries `path`, the `langgraph_path` of its chunks (`["__pregel_push", index, false]`), which tells apart the tasks of one node in a step. A retry of a conditional edge's function also carries `branch`, the edge's function name. The function runs inside its node's activity, before the node's `updates` chunk, as in LangGraph; if it raises there, it runs again in an activity of its own, after that chunk, and only what the function sent is stale, not the node's own output. | | `stream_unavailable` | `{"workflow_id", "reason", "missing_steps", "missing_nodes"}` | The run finished but a node's chunks never arrived (see the limit below). `missing_nodes` is a list of `{"step", "node"}`, one per node of a step that streamed nothing, even when other nodes of that step did. Steps are numbered from 1, like `langgraph_step`. A `Send` task is named `node#k` there (`k` is its position among the step's `Send` tasks). A conditional edge's function that ran in an activity of its own (a START edge's, or one that raised inside its node's activity and ran again) is listed as `node:branch:` (`node#k:branch:` after a `Send` task, `__start__:branch:` at step 0 for a START edge), where `` is the name the runner registered the edge under. | +| `stream_purged` | `{"workflow_id", "step"}` | A reconnect or a late reader found that the run's event log outlived its TTL (state-store transport only): what is left cannot be replayed. The final event follows. | | `stream_dropped` | `{"dropped": n}` | The consumer fell behind and `n` token or custom chunks were dropped. `updates` are never dropped. | Pass `on_control=callback` to `astream` to receive them. A list of modes also diff --git a/diagrid/agent/langgraph/activity_stream.py b/diagrid/agent/langgraph/activity_stream.py new file mode 100644 index 00000000..f4ed0440 --- /dev/null +++ b/diagrid/agent/langgraph/activity_stream.py @@ -0,0 +1,81 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Where an activity of a streamed run writes, and what the workflow publishes. + +An activity asks the runner's transport for a writer once per execution; the +node, its routers and its ``values`` chunk all write to it. The workflow +publishes the units each step runs in its custom status (no I/O, so it is safe +in workflow code), which is how a reader on any replica finds them. +""" + +import json +from typing import Any, Dict, Optional, Union + +from diagrid.agent.core.workflow.stream import ( + ActivityStreamWriter, + InProcessTransport, + StreamSinkRegistry, + StreamTransport, +) + +from .streaming import STREAM_RUN_KEY + +#: Custom status keys: the units of each step, and the routers run apart. +STATUS_EXECUTED = "executed" +STATUS_BRANCHES = "branches" + + +def transport_of( + stream: Union[StreamTransport, StreamSinkRegistry, None], +) -> StreamTransport: + """``stream`` as a transport: a registry is the in-process transport over it.""" + if stream is None: + return InProcessTransport() + if isinstance(stream, StreamSinkRegistry): + return InProcessTransport(stream) + return stream + + +def activity_writer( + ctx: Any, + transport: StreamTransport, + step: int, + unit: str, + config: Dict[str, Any], +) -> Optional[ActivityStreamWriter]: + """The writer of this execution of ``unit``, or ``None`` when not streaming.""" + workflow_id = getattr(ctx, "workflow_id", None) + if not workflow_id: + return None + return transport.writer( + str(workflow_id), step, unit, streamed=bool(config.get(STREAM_RUN_KEY)) + ) + + +def run_status(run: Any) -> Dict[str, Any]: + """The custom status of a run: what a stream reader needs to find its units.""" + status: Dict[str, Any] = {} + if (run.config or {}).get(STREAM_RUN_KEY): + status[STATUS_EXECUTED] = run.executed + status[STATUS_BRANCHES] = run.branches + return status + + +def publish_run_status(run: Any) -> None: + """Set the run's custom status, if it has one to publish (workflow code).""" + status = run_status(run) + setter = getattr(run.ctx, "set_custom_status", None) + if status and setter is not None: + setter(json.dumps(status)) + + +def parse_status(raw: Any) -> Dict[str, Any]: + """A run's custom status as a dict (empty when it has none or it is not ours).""" + if not raw: + return {} + try: + data = json.loads(raw) if isinstance(raw, str) else raw + except (TypeError, ValueError): + return {} + return data if isinstance(data, dict) else {} diff --git a/diagrid/agent/langgraph/node_routes.py b/diagrid/agent/langgraph/node_routes.py index f1428bd7..d5467fb8 100644 --- a/diagrid/agent/langgraph/node_routes.py +++ b/diagrid/agent/langgraph/node_routes.py @@ -19,7 +19,7 @@ from dataclasses import dataclass, field from typing import Any, Dict, List, Optional -from diagrid.agent.core.workflow.stream import StreamSinkRegistry +from diagrid.agent.core.workflow.stream import StreamSink from .models import ( ChannelState, @@ -87,7 +87,7 @@ def route_in_node( ctx: Any, node_input: ExecuteNodeInput, writes: List[NodeWrite], - registry: Optional[StreamSinkRegistry], + sink: Optional[StreamSink], ) -> RouteOutcome: """Evaluate the node's conditional edges on the state with ``writes`` applied. @@ -107,7 +107,7 @@ def route_in_node( for route in node_input.routes or []: cond_input = _route_input(node_input, route, state) try: - output = evaluate_condition(ctx, cond_input, registry) + output = evaluate_condition(ctx, cond_input, sink) except Exception: logger.warning( "Router %r of node %r raised inside the node's activity; the " diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 6029f71f..040fe1e3 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -36,11 +36,13 @@ WORKFLOW_STARTED, UPDATES, VALUES, - InProcessSink, + InProcessTransport, StreamClosed, StreamEvent, StreamSinkRegistry, + StreamTransport, ) +from diagrid.agent.core.workflow.stream_cursor import END_ID, START_ID from .models import ( ChannelState, EdgeConfig, @@ -76,6 +78,11 @@ ) from .langsmith_trace import ParentTrace, start_parent_trace from .run_status import completed_result +from .stream_source import ( + custom_status, + open_source, + resolve_transport, +) from .thread_state import ( LOAD_THREAD_ACTIVITY, SAVE_THREAD_ACTIVITY, @@ -259,6 +266,31 @@ async def _wait_scheduled(scheduled: asyncio.Event, pump: "asyncio.Task[None]") return scheduled.is_set() +class _SseIds: + """The SSE id of each event of a stream read from the log: its cursor. + + A stream on the in-process transport has no cursor: its events are + numbered per connection (``()`` leaves that to the framer). + """ + + def __init__(self, replayable: bool) -> None: + self._replayable = replayable + self._last = START_ID + + def of(self, item: StreamEvent) -> Tuple[str, ...]: + if not self._replayable: + return () + if item.mode == WORKFLOW_STARTED: + return (START_ID,) + if item.event_id: + self._last = item.event_id + # a control event reuses the cursor of the chunk it follows + return (self._last,) + + def final(self) -> Tuple[str, ...]: + return (END_ID,) if self._replayable else () + + @dataclass(frozen=True) class _RunSetup: """What a run needs once its identity, config and input are settled.""" @@ -340,6 +372,7 @@ def __init__( registry_config: Optional[Any] = None, stream_registry: Optional[StreamSinkRegistry] = None, checkpointer: Optional[Any] = None, + stream_transport: Optional[StreamTransport] = None, ): """Initialize the runner. @@ -357,9 +390,9 @@ def __init__( goal when ``goal`` is not given. Without it, the registry looks for a module-level ``SystemMessage`` in node globals. registry_config: Optional registry configuration for metadata extraction - stream_registry: Where streamed runs register their sinks. The - activities this runner registers write into it. Defaults to a - new registry owned by this runner. + stream_registry: Where streamed runs register their sinks when + they stream in process. Giving one picks the in-process + transport. Defaults to a new registry owned by this runner. checkpointer: Where a thread's state is kept between runs, so a run with the same ``thread_id`` continues the conversation: a ``DaprMemoryCheckpointer`` or a LangGraph checkpoint saver with @@ -367,6 +400,11 @@ def __init__( compiled with, else the app's Dapr state store (``agent-memory``) when it has one; with none, ``thread_id`` is only a label. + stream_transport: How a streamed run's chunks get from its + activities to its stream. By default the state-store event + log (``StateLogTransport``) when the app has a state store, + which any replica reads and a client can reconnect to, and + the in-process transport otherwise. """ self._graph = graph self._max_steps = DEFAULT_MAX_STEPS if max_steps is None else max_steps @@ -374,6 +412,8 @@ def __init__( self._stream_registry = ( stream_registry if stream_registry is not None else StreamSinkRegistry() ) + self._given_transport = stream_transport + self._given_registry = stream_registry # Pumps of streams whose consumer left while a result is still to be # published; held here so they are not collected before they finish. self._detached_pumps: Set["asyncio.Task[None]"] = set() @@ -401,6 +441,14 @@ def __init__( self._thread_store = resolve_thread_store( checkpointer, self._graph, self._state_store ) + self._stream_transport = resolve_transport( + self._given_transport, + self._given_registry, + getattr(self._state_store, "store_name", None) or self._workflow_store_name, + self._stream_registry, + ) + if isinstance(self._stream_transport, InProcessTransport): + self._stream_registry = self._stream_transport.registry self._register_agent_metadata( agent=self._graph, @@ -425,11 +473,11 @@ def _register_workflow_components(self) -> None: agent_workflow, name=self.workflow_name ) self._workflow_runtime.register_activity( - make_node_activity(GENERIC_NODE_ACTIVITY, self._stream_registry), + make_node_activity(GENERIC_NODE_ACTIVITY, self._stream_transport), name=GENERIC_NODE_ACTIVITY, ) self._workflow_runtime.register_activity( - make_condition_activity(self._stream_registry), + make_condition_activity(self._stream_transport), name="evaluate_condition_activity", ) # Registered even without a store, so an instance that scheduled them @@ -448,7 +496,7 @@ def _register_node_activities(self) -> None: if name == GENERIC_NODE_ACTIVITY: continue self._workflow_runtime.register_activity( - make_node_activity(node.name, self._stream_registry), name=name + make_node_activity(node.name, self._stream_transport), name=name ) def _extract_graph_config(self) -> GraphConfig: @@ -1046,15 +1094,21 @@ async def _stream_events( config, self._run_config(config), thread_id, workflow_id ) run_config = {**run_config, STREAM_RUN_KEY: True} - sink = self._stream_registry.open(workflow_id) - task: Optional["asyncio.Task[None]"] = None seen_nodes: Set[Tuple[int, str]] = set() + source = open_source( + self._stream_transport, + workflow_id, + status=lambda: custom_status(self._workflow_client, workflow_id), + seen=seen_nodes, + ) + sink = source.sink + task: Optional["asyncio.Task[None]"] = None values_sent: Set[int] = set() scheduled = asyncio.Event() try: task = asyncio.create_task( self._pump_run( - sink, + source.on_final, input, thread_id, workflow_id, @@ -1074,13 +1128,15 @@ async def _stream_events( if isinstance(item, StreamClosed): # Unregister before handing over the result: chunks a late # activity attempt writes from here on are dropped. - self._stream_registry.close(workflow_id, sink) + await source.close() for event in closing_events( item, seen_nodes, workflow_id, output_channels=self._graph_config.output_channels, values_sent=values_sent, + unavailable_reason=source.unavailable_reason, + purged=source.purged, ): yield event return @@ -1097,12 +1153,12 @@ async def _stream_events( # Also reached when the consumer goes away (client disconnect, # abandoned generator). That stops this stream only: the Dapr # workflow itself keeps running to completion. - self._stream_registry.close(workflow_id, sink) + await source.close() await self._release_pump(task, detach=on_result is not None) async def _pump_run( self, - sink: InProcessSink, + on_final: Callable[[Dict[str, Any]], None], input: Any, thread_id: str, workflow_id: str, @@ -1111,7 +1167,7 @@ async def _pump_run( on_result: Optional[Callable[[Dict[str, Any]], None]], scheduled: Optional[asyncio.Event] = None, ) -> None: - """Follow the run, publish its result, and close ``sink`` with the final. + """Follow the run, publish its result, and hand ``on_final`` the final. ``scheduled`` is set once ``run_async`` reports the workflow started, which it does after ``schedule_new_workflow`` returned. @@ -1138,7 +1194,7 @@ async def _pump_run( final = stream_failure_event( e, "PollError", bool(result.get("instance_id")) ) - sink.close(normalize_final(final, workflow_id=workflow_id, thread_id=thread_id)) + on_final(normalize_final(final, workflow_id=workflow_id, thread_id=thread_id)) async def _release_pump( self, task: Optional["asyncio.Task[None]"], *, detach: bool @@ -1272,6 +1328,7 @@ async def _serve_stream( # type: ignore[override] thread_id = request.get("thread_id") or request.get("session_id") or session_id workflow_id: Optional[str] = None unencodable = 0 + ids = _SseIds(self._stream_transport.replayable) try: modes, _ = normalize_stream_mode( request.get("stream_mode") or self._DEFAULT_STREAM_MODES @@ -1292,15 +1349,17 @@ async def _serve_stream( # type: ignore[override] if item is KEEPALIVE: yield KEEPALIVE_EVENT, None elif isinstance(item, StreamEvent): + event_id = ids.of(item) if item.mode not in CONTROL_MODES and item.mode not in modes: continue if item.mode == WORKFLOW_STARTED: workflow_id = item.data["workflow_id"] wire, ok = encode_chunk(item) unencodable += 0 if ok else 1 - yield item.mode, wire + yield (item.mode, wire, *event_id) else: - yield item["type"], count_unencodable(item, unencodable) + final = count_unencodable(item, unencodable) + yield (item["type"], final, *ids.final()) except Exception as e: logger.exception("Streaming run failed") failed = stream_failure_event(e, "StreamError", bool(workflow_id)) @@ -1337,6 +1396,11 @@ def _request_to_input( # Properties # ------------------------------------------------------------------ + @property + def stream_transport(self) -> StreamTransport: + """How this runner's streamed runs get their chunks (see ``__init__``).""" + return self._stream_transport + @property def stream_registry(self) -> StreamSinkRegistry: """Where this runner's streamed runs register their sinks.""" diff --git a/diagrid/agent/langgraph/stream_events.py b/diagrid/agent/langgraph/stream_events.py index 68270e46..9e68721a 100644 --- a/diagrid/agent/langgraph/stream_events.py +++ b/diagrid/agent/langgraph/stream_events.py @@ -205,12 +205,15 @@ def closing_events( *, output_channels: Optional[List[str]] = None, values_sent: Optional[Set[int]] = None, + unavailable_reason: Optional[str] = None, + purged: bool = False, ) -> List[Any]: """The items a stream ends with. The ``values`` chunk of the state the run ended with (when the run got to - the end of a step and no activity sent it), ``stream_unavailable`` if due, - then the final event. + the end of a step and no activity sent it), ``stream_unavailable`` if due + (with ``unavailable_reason``; never after ``stream_purged``, which already + said the rest is gone), then the final event. """ out: List[Any] = [] if output_channels: @@ -219,7 +222,13 @@ def closing_events( ) if last is not None: out.append(last) - unavailable = stream_unavailable_event(closed.final, seen_nodes, workflow_id) + unavailable = ( + None + if purged + else stream_unavailable_event( + closed.final, seen_nodes, workflow_id, unavailable_reason + ) + ) if unavailable is not None: logger.warning( "Streamed run %s: no chunks for steps %s (nodes %s)", diff --git a/diagrid/agent/langgraph/stream_follow.py b/diagrid/agent/langgraph/stream_follow.py new file mode 100644 index 00000000..3567af46 --- /dev/null +++ b/diagrid/agent/langgraph/stream_follow.py @@ -0,0 +1,294 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Reading a run's stream back from the state-store event log. + +The follower finds the run's units in its custom status (the final event once +the run ended), reads what is new in each of them, and puts the chunks into +an in-process sink the stream is drained from, so a stream read from the log +is consumed exactly like one fed by activities in this process. It reads at +the consumer's pace: a slow client lags, it does not lose chunks. + +Each chunk carries the cursor after it as its SSE id (see ``stream_cursor``). +""" + +import asyncio +import logging +from dataclasses import dataclass, replace +from typing import Any, Callable, Dict, List, Optional, Set, Tuple + +from diagrid.agent.core.workflow.stream import ( + STREAM_PURGED, + VALUES, + InProcessSink, + StreamEvent, +) +from diagrid.agent.core.workflow.stream_cursor import ( + ATTEMPT_PREFIX, + StreamCursor, + encode_cursor, +) +from diagrid.agent.core.workflow.stream_log import ( + LogReader, + UnitChunk, + UnitWant, + event_from_wire, +) + +from .activity_stream import STATUS_BRANCHES, STATUS_EXECUTED +from .stream_events import encode_chunk, stream_failure_event +from .streaming import BRANCHES_KEY, EXECUTED_KEY, SUPPORTED_MODES + +logger = logging.getLogger(__name__) + +#: The follower stops reading while this many chunks wait for the consumer. +BACKLOG_HIGH = 256 +#: Reads that fail in a row before the stream reports the store unreadable. +READ_ATTEMPTS = 5 + +Unit = Tuple[int, str] + + +def encode_wire(event: StreamEvent) -> Any: + """A chunk's data as the log keeps it: its wire form (see ``to_wire``).""" + return encode_chunk(event)[0] + + +def decode_wire(mode: str, data: Any) -> Any: + """A chunk's data as an in-process consumer gets it, from its wire form.""" + if mode not in SUPPORTED_MODES: + return data + from langchain_core._api.beta_decorator import suppress_langchain_beta_warning + from langchain_core.load import load + + try: + with suppress_langchain_beta_warning(): + value = load(data) + except Exception: # not something load() knows: keep it as sent + return data + if mode == "messages" and isinstance(value, list) and len(value) == 2: + return tuple(value) + return value + + +def units_of(status: Dict[str, Any]) -> List[Unit]: + """The run's units in replay order: by step, nodes first, then routers. + + ``status`` is the custom status or the final event (same keys). + """ + executed = status.get(STATUS_EXECUTED) or status.get(EXECUTED_KEY) or [] + branches = status.get(STATUS_BRANCHES) or status.get(BRANCHES_KEY) or [] + units: List[Tuple[int, int, int, str]] = [] + for step, keys in enumerate(executed): + for order, key in enumerate(keys): + units.append((step, 0, order, str(key))) + for order, (step, key) in enumerate(branches): + units.append((int(step), 1, order, str(key))) + seen: Set[Unit] = set() + ordered: List[Unit] = [] + for step, _, _, key in sorted(units): + if (step, key) not in seen: + seen.add((step, key)) + ordered.append((step, key)) + return ordered + + +@dataclass +class _UnitState: + """How far the stream got in one unit.""" + + attempt: Optional[str] = None + from_batch: int = 0 + #: Events of the attempt handed to the sink (or read by an earlier client). + consumed: int = 0 + #: Events to skip on the first read: the client got them before. + skip: int = 0 + done: bool = False + total: int = 0 + #: The attempt an earlier client saw part of, when it was replaced. + replaced: Optional[str] = None + + @property + def complete(self) -> bool: + return self.done and self.consumed >= self.total + + +class LogFollower: + """Feeds ``sink`` from the run's log until the run ends, then closes it.""" + + def __init__( + self, + reader: LogReader, + sink: InProcessSink, + *, + workflow_id: str, + status: Callable[[], Dict[str, Any]], + poll_s: float, + cursor: Optional[StreamCursor] = None, + decode: Callable[[str, Any], Any] = decode_wire, + seen: Optional[Set[Unit]] = None, + ) -> None: + self._reader = reader + self._sink = sink + self._workflow_id = workflow_id + self._status = status + self._poll_s = poll_s + self._cursor = cursor or StreamCursor() + self._decode = decode + self._units: Dict[Unit, _UnitState] = {} + self._order: List[Unit] = [] + #: Units the client had in full or in part before this stream: the + #: stream does not report them missing. + self._seen = seen if seen is not None else set() + self.purged = False + self._final: "asyncio.Future[Dict[str, Any]]" = ( + asyncio.get_running_loop().create_future() + ) + + def finish(self, final: Dict[str, Any]) -> None: + """The run ended with ``final``: read what is left, then close the sink.""" + if not self._final.done(): + self._final.set_result(final) + + async def run(self) -> None: + failures = 0 + while True: + final = self._final.result() if self._final.done() else None + try: + await self._read_once(final) + failures = 0 + except asyncio.CancelledError: + raise + except Exception as e: + failures += 1 + logger.warning( + "Reading the stream log of %s failed (%d/%d): %s", + self._workflow_id, + failures, + READ_ATTEMPTS, + e, + ) + if failures >= READ_ATTEMPTS: + self._sink.close(stream_failure_event(e, "StreamReadError", True)) + return + await asyncio.sleep(self._poll_s) + continue + if final is not None: + self._sink.close(final) + return + try: + await asyncio.wait_for(asyncio.shield(self._final), self._poll_s) + except asyncio.TimeoutError: + pass + + async def _read_once(self, final: Optional[Dict[str, Any]]) -> None: + if self.purged or self._cursor.at_end: + return + status = final if final is not None else await asyncio.to_thread(self._status) + self._learn(units_of(status or {})) + wants = [ + UnitWant( + unit[0], + unit[1], + attempt=state.attempt, + from_batch=state.from_batch, + skip_events=state.skip, + ) + for unit in self._order + if not (state := self._units[unit]).complete + ] + if not wants: + return + chunks = await asyncio.to_thread(self._reader.read, wants) + for chunk in chunks: + if chunk.purged: + self._purge(chunk) + return + await self._deliver(chunk) + + def _learn(self, units: List[Unit]) -> None: + for unit in units: + if unit in self._units: + continue + state = _UnitState() + if self._cursor.skips_step(unit[0]): + state = _UnitState(done=True) + self._seen.add(unit) + else: + position = self._cursor.position(*unit) + if position is not None: + state = _UnitState(attempt=position[0], skip=position[1]) + state.consumed = position[1] + self._seen.add(unit) + self._units[unit] = state + self._order.append(unit) + self._order.sort(key=lambda u: u[0]) + + def _purge(self, chunk: UnitChunk) -> None: + self.purged = True + logger.warning( + "The stream log of %s is purged (unit %s of step %s): it outlived its TTL", + self._workflow_id, + chunk.unit, + chunk.step, + ) + self._sink.put( + StreamEvent( + workflow_id=self._workflow_id, + step=chunk.step, + node="", + attempt_id="", + seq=0, + ns=(), + mode=STREAM_PURGED, + data={"workflow_id": self._workflow_id, "step": chunk.step + 1}, + event_id=self.event_id(), + ) + ) + + async def _deliver(self, chunk: UnitChunk) -> None: + state = self._units[(chunk.step, chunk.unit)] + if chunk.attempt is None: + return + if chunk.reset: + # an attempt the client saw part of was replaced: its first chunk + # in this stream must tell the client to drop that part + had = state.consumed > 0 + state.replaced = state.attempt if had else None + primed: Set[Tuple[int, str]] = set() + state.attempt = chunk.attempt + state.from_batch = chunk.batches + state.skip = 0 + state.done = chunk.done + state.total = chunk.total + state.consumed = chunk.start + for wire in chunk.events: + event = event_from_wire(wire, self._workflow_id, self._decode) + await self._wait_for_room() + key = (event.step, event.node) + if state.replaced and event.mode != VALUES and key not in primed: + self._sink.prime(event.step, event.node, state.replaced) + primed.add(key) + state.consumed += 1 + self._sink.put(replace(event, event_id=self.event_id())) + state.replaced = None + + async def _wait_for_room(self) -> None: + while self._sink.backlog() >= BACKLOG_HIGH: + await asyncio.sleep(0.01) + + def event_id(self) -> str: + """The SSE id of the stream as it stands: a cursor any replica resumes.""" + open_steps = [u[0] for u in self._order if not self._units[u].complete] + if open_steps: + base = min(open_steps) + elif self._order: + base = max(u[0] for u in self._order) + else: + return encode_cursor(self._cursor) + positions = tuple( + (step, unit, (state.attempt or "")[:ATTEMPT_PREFIX], state.consumed) + for (step, unit) in self._order + if step >= base and (state := self._units[(step, unit)]).consumed > 0 + ) + return encode_cursor(StreamCursor(base=base, positions=positions)) diff --git a/diagrid/agent/langgraph/stream_source.py b/diagrid/agent/langgraph/stream_source.py new file mode 100644 index 00000000..24437cec --- /dev/null +++ b/diagrid/agent/langgraph/stream_source.py @@ -0,0 +1,136 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Where a stream's chunks come from: this process's activities, or the log. + +Either way the stream drains one :class:`InProcessSink`. With the in-process +transport the sink is registered and activities in this process write to it; +with the state-store log a :class:`LogFollower` fills it from the log, which +activities on any replica wrote. +""" + +import asyncio +import logging +from dataclasses import dataclass +from typing import Any, Callable, Dict, Optional, Set, Tuple + +from diagrid.agent.core.workflow.stream import ( + InProcessSink, + InProcessTransport, + StreamTransport, +) +from diagrid.agent.core.workflow.stream_cursor import StreamCursor +from diagrid.agent.core.workflow.stream_log import StateLogTransport + +from .activity_stream import parse_status +from .stream_follow import LogFollower + +logger = logging.getLogger(__name__) + +#: ``stream_unavailable`` reason when the log lacks a unit that ran: its +#: writes failed (or the log was cut short). +WRITE_FAILED = "write_failed" +#: ``stream_unavailable`` reason on a reconnect to a run streamed in process. +NOT_REPLAYABLE = "transport_not_replayable" + + +@dataclass +class StreamSource: + """The sink a stream drains and how the run's end reaches it.""" + + sink: InProcessSink + #: Called once with the run's terminal event. + on_final: Callable[[Dict[str, Any]], None] + follower: Optional[LogFollower] = None + task: Optional["asyncio.Task[None]"] = None + #: Unregisters the sink (in-process transport only). + release: Optional[Callable[[], None]] = None + + @property + def unavailable_reason(self) -> Optional[str]: + return WRITE_FAILED if self.follower is not None else None + + @property + def purged(self) -> bool: + return self.follower is not None and self.follower.purged + + async def close(self) -> None: + if self.release is not None: + self.release() + if self.task is not None and not self.task.done(): + self.task.cancel() + await asyncio.gather(self.task, return_exceptions=True) + + +def custom_status(client: Any, workflow_id: str) -> Dict[str, Any]: + """The run's custom status (blocking: call it off the event loop).""" + state = client.get_workflow_state(instance_id=workflow_id) + return parse_status(getattr(state, "serialized_custom_status", None)) + + +def open_source( + transport: StreamTransport, + workflow_id: str, + *, + status: Callable[[], Dict[str, Any]], + seen: Set[Tuple[int, str]], + cursor: Optional[StreamCursor] = None, +) -> StreamSource: + """The source of a stream of ``workflow_id`` on ``transport``. + + Raises ``ValueError`` if an in-process stream of this run is already open. + """ + if isinstance(transport, StateLogTransport): + sink = InProcessSink(workflow_id, asyncio.get_running_loop(), bounded=False) + follower = LogFollower( + transport.reader(workflow_id), + sink, + workflow_id=workflow_id, + status=status, + poll_s=transport.config.read_poll_s, + cursor=cursor, + decode=transport.decode, + seen=seen, + ) + task = asyncio.create_task(follower.run()) + return StreamSource(sink, follower.finish, follower=follower, task=task) + registry = ( + transport.registry + if isinstance(transport, InProcessTransport) + else InProcessTransport().registry + ) + sink = registry.open(workflow_id) + return StreamSource( + sink, sink.close, release=lambda: registry.close(workflow_id, sink) + ) + + +def resolve_transport( + given: Optional[StreamTransport], + registry: Optional[Any], + store_name: Optional[str], + own_registry: Any, +) -> StreamTransport: + """The transport a runner streams through. + + The one given; else the in-process transport over a given registry; else + the state-store log on the runner's store (any app on Catalyst has one, + since workflows need it); else in-process. A log transport is bound to + the LangGraph codec, so chunks keep their message objects. + """ + from diagrid.agent.core.workflow.stream_log import StateLogStreamConfig + + from .stream_follow import decode_wire, encode_wire + + transport: StreamTransport + if given is not None: + transport = given + elif registry is not None: + transport = InProcessTransport(registry) + elif store_name: + transport = StateLogTransport(StateLogStreamConfig(store_name=store_name)) + else: + transport = InProcessTransport(own_registry) + if isinstance(transport, StateLogTransport): + transport = transport.with_codec(encode_wire, decode_wire) + return transport diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index 7a6a31d6..d220dd6d 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -78,7 +78,8 @@ class StreamControl: """An event about the stream itself rather than a chunk of the run. ``kind`` is ``workflow_started`` (``{"workflow_id", "thread_id"}``, always - first), ``node_reset``, ``stream_unavailable`` or ``stream_dropped``; + first), ``node_reset``, ``stream_unavailable``, ``stream_purged`` or + ``stream_dropped``; ``data`` is its payload. ``astream`` hands these to its ``on_control`` callback, and in list mode also yields them as ``(kind, data)``, except ``workflow_started``, which is only ever given to ``on_control`` and never @@ -569,7 +570,10 @@ def _branches(final: Dict[str, Any]) -> List[Tuple[int, str]]: def stream_unavailable_event( - final: Dict[str, Any], seen: Set[Tuple[int, str]], workflow_id: str + final: Dict[str, Any], + seen: Set[Tuple[int, str]], + workflow_id: str, + reason: Optional[str] = None, ) -> Optional[StreamEvent]: """The ``stream_unavailable`` event for a finished run, if it applies. @@ -581,7 +585,8 @@ def stream_unavailable_event( activity (``branches``) are judged the same way. A final without ``executed`` is judged per step instead. A run that failed is just a failure, and one with no step count has nothing to - report. + report. ``reason`` replaces the default explanation (the state-store log + says ``write_failed``). """ steps = final.get("steps") if final.get("type") != "workflow_completed" or not isinstance(steps, int): @@ -614,7 +619,7 @@ def stream_unavailable_event( mode=STREAM_UNAVAILABLE, data={ "workflow_id": workflow_id, - "reason": UNAVAILABLE_REASON, + "reason": reason or UNAVAILABLE_REASON, "missing_steps": missing, "missing_nodes": missing_nodes, }, diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 4cab4727..7248199c 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -25,6 +25,7 @@ Optional, Set, Tuple, + Union, ) from dapr.ext.workflow import ( @@ -58,11 +59,16 @@ CONF = "configurable" from diagrid.agent.core.workflow.stream import ( + StreamSink, StreamSinkRegistry, - default_registry, - get_stream_sink, + StreamTransport, ) +from .activity_stream import ( + activity_writer, + publish_run_status, + transport_of, +) from .node_routes import route_in_node from .stream_values import state_values from .streaming import STREAM_RUN_KEY, NodeStreamer, StaticConfig @@ -182,19 +188,21 @@ def node_activity_name(node_name: str) -> str: def make_node_activity( node_name: str, - stream_registry: Optional[StreamSinkRegistry] = None, + stream: Union[StreamTransport, StreamSinkRegistry, None] = None, ) -> Callable[[WorkflowActivityContext, Dict[str, Any]], Dict[str, Any]]: """Build the activity registered for one node. Dapr registers each function object once, so every node gets its own - wrapper around ``execute_node_activity``. ``stream_registry`` is where the - wrapper looks for the sink of a streamed run (default: the module's). + wrapper around ``execute_node_activity``. ``stream`` is the runner's + stream transport (a registry stands for the in-process one over it; + default: the module's registry). """ + transport = transport_of(stream) def node_activity( ctx: WorkflowActivityContext, input_data: Dict[str, Any] ) -> Dict[str, Any]: - return execute_node_activity(ctx, input_data, stream_registry=stream_registry) + return execute_node_activity(ctx, input_data, stream_transport=transport) return node_activity @@ -684,6 +692,7 @@ def _run_step( run.executed.append( [*nodes, *[send_key(t["node"], slot) for slot, t in enumerate(sends)]] ) + publish_run_status(run) outputs = yield from _run_nodes(run, nodes, sends, step) failed = next((o for o in outputs if o.error), None) if failed: @@ -981,6 +990,7 @@ def _follow_edge( output_channels=run.output_channels if source_node == START else None, ) run.branches.append([step, _branch_key(cond_input)]) + publish_run_status(run) # By name, so the runner's own activity (the one that knows its stream # registry) runs, not the module-level function. cond_result = yield run.ctx.call_activity( @@ -1067,8 +1077,8 @@ class _NodeCall: streamer: Optional[NodeStreamer] #: Side-channel writes queued via CONFIG_KEY_SEND while the node runs. pending_sends: list - #: Where the node's routers look for the run's stream sink. - registry: Optional[StreamSinkRegistry] = None + #: Where the node's routers write their chunks, in a streamed run. + sink: Optional[StreamSink] = None @property def node_name(self) -> str: @@ -1377,42 +1387,15 @@ def _parent_command_result(exc: ParentCommand, node_name: str) -> Command: raise exc -def _warn_stream_sink_missing( - registry: StreamSinkRegistry, workflow_id: str, node_name: str -) -> None: - """Say, once per run, that a streamed run's chunks are going nowhere.""" - if not registry.first_report(workflow_id): - return - if registry.was_closed(workflow_id): - # This process had the stream and it ended (the client left, or the - # run's stream was closed): not a second replica, nothing to act on. - logger.debug( - "Run %s: its stream was closed in this process (its consumer left " - "or the stream ended); chunks of node %r are not delivered", - workflow_id, - node_name, - ) - return - logger.warning( - "Run %s is streamed but this process has no stream sink for it, so the " - "chunks of node %r (and of any node that runs here) are not delivered. " - "The activity is running in another process (several replicas) or the " - "run outlived the process that streams it. Cross-replica streaming is " - "not supported yet; the run itself is unaffected.", - workflow_id, - node_name, - ) - - def _make_streamer( ctx: WorkflowActivityContext, node_input: ExecuteNodeInput, config: Dict[str, Any], - registry: Optional[StreamSinkRegistry], + sink: Optional[StreamSink], ) -> Optional[NodeStreamer]: """The streamer for this attempt of the node, or ``None`` when not streaming. - Chunks are streamed only when a consumer registered a sink for this run; + Chunks are streamed only when the transport gave this activity a writer; otherwise nothing about the node's execution changes. """ send = node_input.send @@ -1422,7 +1405,7 @@ def _make_streamer( node_input.step or 0, node_input.thread_id, config, - registry, + sink, # a Send is a task of its own, keyed apart from the node's other runs sink_node=None if send is None @@ -1437,22 +1420,17 @@ def _streamer_for( step: int, thread_id: Optional[str], config: Dict[str, Any], - registry: Optional[StreamSinkRegistry], + sink: Optional[StreamSink], sink_node: Optional[str] = None, send_index: Optional[int] = None, branch: Optional[str] = None, ) -> Optional[NodeStreamer]: - """A streamer that emits as ``node_name`` at ``step``, or ``None``. + """A streamer that emits as ``node_name`` at ``step`` into ``sink``, or ``None``. ``send_index`` is set for a node that runs for a ``Send``: LangGraph tags such a task with the ``__pregel_push`` trigger and path. """ - sink = get_stream_sink(getattr(ctx, "workflow_id", None), registry=registry) if sink is None: - if config.get(STREAM_RUN_KEY): - _warn_stream_sink_missing( - registry or default_registry, str(ctx.workflow_id), node_name - ) return None return NodeStreamer( sink, @@ -1528,7 +1506,7 @@ def _node_output(call: _NodeCall, result: Any) -> Dict[str, Any]: routed: Dict[str, Any] = {} if call.node_input.routes: routed = route_in_node( - call.ctx, call.node_input, writes, call.registry + call.ctx, call.node_input, writes, call.sink ).output_fields() if call.streamer: call.streamer.updates(raw_writes) @@ -1548,13 +1526,15 @@ def execute_node_activity( input_data: Dict[str, Any], *, stream_registry: Optional[StreamSinkRegistry] = None, + stream_transport: Optional[StreamTransport] = None, ) -> Dict[str, Any]: """Run one node, or one ``Send`` task, and return the writes it produced. The node runs under a config that carries a ``Runtime`` and, when someone - streams the run, the handler that sends its chunks to the stream sink - (looked up in ``stream_registry``, default the module's). An exception - propagates, so Dapr retries the activity. + streams the run, the handler that sends its chunks to the writer + ``stream_transport`` gives this execution (``stream_registry`` stands for + the in-process transport over it; default the module's registry). An + exception propagates, so Dapr retries the activity. """ node_input = ExecuteNodeInput.from_dict(input_data) node_name = node_input.node_name @@ -1569,28 +1549,42 @@ def execute_node_activity( ).to_dict() config = node_input.config or {} - call = _NodeCall( - ctx=ctx, - node_input=node_input, - node_func=node_func, - state=_node_state(node_input), - config=config, - streamer=_make_streamer(ctx, node_input, config, stream_registry), - pending_sends=[], - registry=stream_registry, - ) - - _send_values( + send = node_input.send + writer = activity_writer( ctx, - node_input.channel_state, - node_input.output_channels, + transport_of(stream_transport or stream_registry), node_input.step or 0, - stream_registry, + node_name if send is None else send_key(node_name, send["slot"]), + config, ) - # Under the LangSmith parent trace the runner opened, so LLM calls nest in it. - result = _run_with_stream_hooks(call, _langsmith_parent(config)) - - return _node_output(call, result) + done = False + try: + call = _NodeCall( + ctx=ctx, + node_input=node_input, + node_func=node_func, + state=_node_state(node_input), + config=config, + streamer=_make_streamer(ctx, node_input, config, writer), + pending_sends=[], + sink=writer, + ) + _send_values( + ctx, + node_input.channel_state, + node_input.output_channels, + node_input.step or 0, + writer, + ) + # Under the LangSmith parent trace the runner opened, so LLM calls nest in it. + result = _run_with_stream_hooks(call, _langsmith_parent(config)) + output = _node_output(call, result) + done = True + return output + finally: + if writer is not None: + # synchronous: the unit's log is complete before the activity returns + writer.finish(done=done) def _send_values( @@ -1598,7 +1592,7 @@ def _send_values( channel_state: ChannelState, output_channels: Optional[List[str]], step: int, - registry: Optional[StreamSinkRegistry], + sink: Optional[StreamSink], ) -> None: """Offer the state this activity was handed as the ``values`` chunk of ``step``. @@ -1606,12 +1600,9 @@ def _send_values( every activity of ``step`` is handed: the sink keeps the first offer, which comes before any of the step's own chunks. """ - if not output_channels: + if not output_channels or sink is None: return workflow_id = getattr(ctx, "workflow_id", None) - sink = get_stream_sink(workflow_id, registry=registry) - if sink is None: - return event = state_values(str(workflow_id), step, channel_state, output_channels) if event is not None: sink.put(event) @@ -1631,16 +1622,15 @@ def _node_state(node_input: ExecuteNodeInput) -> Any: def make_condition_activity( - stream_registry: Optional[StreamSinkRegistry] = None, + stream: Union[StreamTransport, StreamSinkRegistry, None] = None, ) -> Callable[[WorkflowActivityContext, Dict[str, Any]], Dict[str, Any]]: """Build the conditional-edge activity of a runner (see ``make_node_activity``).""" + transport = transport_of(stream) def evaluate_condition( ctx: WorkflowActivityContext, input_data: Dict[str, Any] ) -> Dict[str, Any]: - return evaluate_condition_activity( - ctx, input_data, stream_registry=stream_registry - ) + return evaluate_condition_activity(ctx, input_data, stream_transport=transport) return evaluate_condition @@ -1660,7 +1650,7 @@ def _call_condition( cond_input: EvaluateConditionInput, cond_func: Callable, state: Any, - registry: Optional[StreamSinkRegistry], + sink: Optional[StreamSink], ) -> Any: """Call a conditional edge's function and return what it routed to. @@ -1677,7 +1667,7 @@ def _call_condition( cond_input.step, cond_input.thread_id, config, - registry, + sink, # one key per edge and task: a node's several conditional edges, and # its several Send tasks, are several tasks, and a key they share # would read as one retrying @@ -1717,27 +1707,42 @@ def evaluate_condition_activity( input_data: Dict[str, Any], *, stream_registry: Optional[StreamSinkRegistry] = None, + stream_transport: Optional[StreamTransport] = None, ) -> Dict[str, Any]: """Evaluate a conditional edge; the output names where it routes, or the error. - ``stream_registry`` is where the sink of a streamed run is (default: the - module's). + A streamed run's chunks go to the writer ``stream_transport`` gives this + execution (see :func:`execute_node_activity`). """ cond_input = EvaluateConditionInput.from_dict(input_data) - _send_values( + writer = activity_writer( ctx, - cond_input.channel_state, - cond_input.output_channels, - 0, - stream_registry, + transport_of(stream_transport or stream_registry), + cond_input.step if cond_input.step is not None else 0, + _branch_key(cond_input), + cond_input.config or {}, ) - return evaluate_condition(ctx, cond_input, stream_registry).to_dict() + done = False + try: + _send_values( + ctx, + cond_input.channel_state, + cond_input.output_channels, + 0, + writer, + ) + output = evaluate_condition(ctx, cond_input, writer).to_dict() + done = True + return output + finally: + if writer is not None: + writer.finish(done=done) def evaluate_condition( ctx: WorkflowActivityContext, cond_input: EvaluateConditionInput, - stream_registry: Optional[StreamSinkRegistry], + sink: Optional[StreamSink], ) -> EvaluateConditionOutput: """Call a conditional edge's function and say where it routes, or the error. @@ -1763,7 +1768,7 @@ def evaluate_condition( # add_conditional_edges path is one) traces itself, so without a parent # each evaluation lands in LangSmith as a separate top-level trace. with _under_parent_trace(cond_input.config): - result = _call_condition(ctx, cond_input, cond_func, state, stream_registry) + result = _call_condition(ctx, cond_input, cond_func, state, sink) return _route(cond_input, result) diff --git a/tests/agent/langgraph/log_helpers.py b/tests/agent/langgraph/log_helpers.py index 7f741626..13a07dbb 100644 --- a/tests/agent/langgraph/log_helpers.py +++ b/tests/agent/langgraph/log_helpers.py @@ -26,6 +26,7 @@ from ..core.log_store_fake import FakeLogStore from .streaming_helpers import _IdCtx +from .test_runner import _clear_dapr_registration FAST = StateLogStreamConfig(flush_interval_s=0.01, flush_max_chunks=4, read_poll_s=0.01) @@ -152,8 +153,12 @@ def log_runner( def replica(compiled: Any, name: str, store: FakeLogStore) -> DaprWorkflowGraphRunner: """Another process of the same app: same graph, same store, its own activities.""" - return DaprWorkflowGraphRunner( + other = DaprWorkflowGraphRunner( graph=compiled, name=name, stream_transport=StateLogTransport(FAST, store=store), ) + # one process registers a workflow function once; the next runner (this + # replica's server) registers it again + _clear_dapr_registration() + return other diff --git a/tests/agent/langgraph/test_stream_transport.py b/tests/agent/langgraph/test_stream_transport.py index 192572d0..d93f3f70 100644 --- a/tests/agent/langgraph/test_stream_transport.py +++ b/tests/agent/langgraph/test_stream_transport.py @@ -29,9 +29,9 @@ from ..core.log_store_fake import FakeLogStore from .golden_harness import MODES, _both, _golden_graph, _Golden, _wire -from .log_helpers import FAST, log_runner, replica +from .log_helpers import log_runner, replica from .streaming_helpers import INPUT, _collect, serve_app -from .test_runner import _RunnerTestCase +from .test_runner import _clear_dapr_registration, _RunnerTestCase def _discovered(**kw: Any) -> Any: @@ -96,6 +96,7 @@ async def _astream(self, runner: Any, wf: str, **kw: Any) -> List[Any]: async def test_the_same_chunks_as_the_in_process_transport(self): _, in_process = await _both(_golden_graph(), "golden-ip", INPUT) + _clear_dapr_registration() runner = log_runner(_golden_graph(), "golden-log") ours = await self._astream(runner, "wf-golden-log") self.assertEqual(_wire(ours), _wire(in_process)) diff --git a/tests/agent/langgraph/test_streaming_activity.py b/tests/agent/langgraph/test_streaming_activity.py index 8880e429..10411e78 100644 --- a/tests/agent/langgraph/test_streaming_activity.py +++ b/tests/agent/langgraph/test_streaming_activity.py @@ -140,7 +140,7 @@ async def hold() -> None: loop.run_until_complete(hold()) self.addCleanup(default_registry.close, wf) - with self.assertLogs("diagrid.agent.langgraph.workflow", level="WARNING"): + with self.assertLogs("diagrid.agent.core.workflow.stream", level="WARNING"): out = execute_node_activity(_Ctx(wf), payload, stream_registry=registry) self.assertIsNone(out.get("error")) self.assertTrue(out["writes"]) diff --git a/tests/agent/langgraph/test_streaming_events.py b/tests/agent/langgraph/test_streaming_events.py index 4f36e981..67f45ce4 100644 --- a/tests/agent/langgraph/test_streaming_events.py +++ b/tests/agent/langgraph/test_streaming_events.py @@ -21,6 +21,7 @@ from diagrid.agent.core.workflow.stream import ( CONTROL_MODES, NODE_RESET, + STREAM_PURGED, STREAM_UNAVAILABLE, UPDATES, WORKFLOW_STARTED, @@ -157,7 +158,7 @@ async def broken(*a, **kw): self.assertEqual(data["error"]["error_type"], "ConnectionError") -LOGGER = "diagrid.agent.langgraph.workflow" +LOGGER = "diagrid.agent.core.workflow.stream" class TestActivityWithoutASink(unittest.TestCase): @@ -457,7 +458,8 @@ def _control_event(mode: str, node: str) -> StreamEvent: class TestControlModes(unittest.IsolatedAsyncioTestCase): def test_control_modes_are_the_events_about_the_stream_itself(self): self.assertEqual( - set(CONTROL_MODES), {WORKFLOW_STARTED, NODE_RESET, STREAM_UNAVAILABLE} + set(CONTROL_MODES), + {WORKFLOW_STARTED, NODE_RESET, STREAM_UNAVAILABLE, STREAM_PURGED}, ) def test_updates_are_a_stream_mode_not_a_control_event(self): @@ -472,6 +474,7 @@ async def test_a_full_buffer_keeps_control_events_and_updates_only(self): WORKFLOW_STARTED, NODE_RESET, STREAM_UNAVAILABLE, + STREAM_PURGED, ] sink = InProcessSink("wf", asyncio.get_running_loop()) with mock.patch.object(stream, "MAX_BUFFERED_EVENTS", 1): diff --git a/tests/agent/langgraph/test_streaming_sink.py b/tests/agent/langgraph/test_streaming_sink.py index 9bd616af..b21e14b2 100644 --- a/tests/agent/langgraph/test_streaming_sink.py +++ b/tests/agent/langgraph/test_streaming_sink.py @@ -484,7 +484,7 @@ async def test_a_runner_never_reads_another_runners_sinks(self): self.assertIsInstance(await other_sink.get(), StreamClosed) -LOGGER = "diagrid.agent.langgraph.workflow" +LOGGER = "diagrid.agent.core.workflow.stream" class TestRegistryRemembersClosedRuns(unittest.IsolatedAsyncioTestCase): From 9cbfc52fa48dc38421c28aa82d784065bf7d977d Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 14:26:26 +0100 Subject: [PATCH 37/73] test(langgraph): expect GET /agent/run/{id}/stream to resume a stream from Last-Event-ID Signed-off-by: Casper Nielsen --- .../agent/langgraph/test_stream_reconnect.py | 226 ++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 tests/agent/langgraph/test_stream_reconnect.py diff --git a/tests/agent/langgraph/test_stream_reconnect.py b/tests/agent/langgraph/test_stream_reconnect.py new file mode 100644 index 00000000..687ec0da --- /dev/null +++ b/tests/agent/langgraph/test_stream_reconnect.py @@ -0,0 +1,226 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Reconnecting to a run's stream: ``GET /agent/run/{id}/stream`` and ``astream_resume``.""" + +import json +import time +import unittest +from typing import Any, List, Tuple + +from fastapi.testclient import TestClient + +from diagrid.agent.core.workflow.stream_cursor import ( + END_ID, + START_ID, + StreamCursor, + encode_cursor, +) + +from .golden_harness import MODES, _golden_graph, _wire +from .log_helpers import LogClient, log_runner +from .streaming_helpers import INPUT, _chat_graph, _collect, serve_app +from .test_runner import _clear_dapr_registration, _RunnerTestCase + + +def _frames(text: str) -> List[Tuple[str, str, Any]]: + """``(id, event, data)`` of each SSE frame (comments left out).""" + out = [] + for frame in text.strip().split("\n\n"): + if frame.startswith(":"): + continue + fields = dict(line.split(": ", 1) for line in frame.split("\n")) + out.append((fields.get("id"), fields["event"], json.loads(fields["data"]))) + return out + + +def _wait_done(runner: Any, workflow_id: str) -> None: + client = runner._workflow_client + deadline = time.monotonic() + 10 + while workflow_id not in client.done and time.monotonic() < deadline: + time.sleep(0.01) + + +class _Case(_RunnerTestCase): + def _post(self, runner: Any) -> List[Tuple[str, str, Any]]: + resp = TestClient(serve_app(runner)).post( + "/agent/run", json={"messages": INPUT["messages"], "stream": True} + ) + self.assertEqual(resp.status_code, 200) + return _frames(resp.text) + + +class TestReconnectEndpoint(_Case): + def test_resuming_after_any_event_gives_exactly_the_rest(self): + runner = log_runner(_golden_graph(), "re-mid") + frames = self._post(runner) + wf = frames[0][2]["workflow_id"] + _wait_done(runner, wf) + http = TestClient(serve_app(runner)) + for cut in (1, len(frames) // 2, len(frames) - 2): + with self.subTest(cut=cut): + resp = http.get( + f"/agent/run/{wf}/stream", + headers={"Last-Event-ID": frames[cut][0]}, + ) + self.assertEqual(resp.status_code, 200) + self.assertTrue( + resp.headers["content-type"].startswith("text/event-stream") + ) + got = _frames(resp.text) + self.assertEqual(got[0][1], "workflow_started") + self.assertEqual(got[0][0], START_ID) + # no duplicates, no gaps: the events after the cut, same ids + self.assertEqual([(i, e, d) for i, e, d in got[1:]], frames[cut + 1 :]) + + def test_the_query_parameter_works_like_the_header(self): + runner = log_runner(_golden_graph(), "re-query") + frames = self._post(runner) + wf = frames[0][2]["workflow_id"] + _wait_done(runner, wf) + resp = TestClient(serve_app(runner)).get( + f"/agent/run/{wf}/stream", params={"last_event_id": frames[3][0]} + ) + self.assertEqual(_frames(resp.text)[1:], frames[4:]) + + def test_no_id_replays_the_whole_run_with_its_result(self): + runner = log_runner(_golden_graph(), "re-all") + frames = self._post(runner) + wf = frames[0][2]["workflow_id"] + _wait_done(runner, wf) + got = _frames(TestClient(serve_app(runner)).get(f"/agent/run/{wf}/stream").text) + self.assertEqual(got[1:], frames[1:]) + self.assertEqual(got[-1][1], "workflow_completed") + self.assertIn("output", got[-1][2]) + + def test_the_end_id_gives_only_the_final_event(self): + runner = log_runner(_golden_graph(), "re-end") + frames = self._post(runner) + wf = frames[0][2]["workflow_id"] + _wait_done(runner, wf) + got = _frames( + TestClient(serve_app(runner)) + .get(f"/agent/run/{wf}/stream", headers={"Last-Event-ID": END_ID}) + .text + ) + self.assertEqual([e for _, e, _ in got], ["workflow_completed"]) + self.assertEqual(got[0][0], END_ID) + + def test_a_junk_id_replays_from_the_start(self): + runner = log_runner(_golden_graph(), "re-junk") + frames = self._post(runner) + wf = frames[0][2]["workflow_id"] + _wait_done(runner, wf) + got = _frames( + TestClient(serve_app(runner)) + .get(f"/agent/run/{wf}/stream", headers={"Last-Event-ID": "nonsense"}) + .text + ) + self.assertEqual(got[1:], frames[1:]) + + def test_another_replica_serves_the_reconnect(self): + runner = log_runner(_golden_graph(), "re-two") + frames = self._post(runner) + wf = frames[0][2]["workflow_id"] + _wait_done(runner, wf) + store = runner.stream_transport.store + client = runner._workflow_client + _clear_dapr_registration() + other = log_runner(_golden_graph(), "re-two", store=store) + other._workflow_client = client + got = _frames( + TestClient(serve_app(other)) + .get(f"/agent/run/{wf}/stream", headers={"Last-Event-ID": frames[2][0]}) + .text + ) + self.assertEqual(got[1:], frames[3:]) + + def test_an_unknown_run_is_404(self): + runner = log_runner(_golden_graph(), "re-404") + resp = TestClient(serve_app(runner)).get("/agent/run/nope/stream") + self.assertEqual(resp.status_code, 404) + + def test_an_unsupported_mode_is_422_before_the_stream(self): + runner = log_runner(_golden_graph(), "re-422") + frames = self._post(runner) + wf = frames[0][2]["workflow_id"] + resp = TestClient(serve_app(runner)).get( + f"/agent/run/{wf}/stream", params={"stream_mode": "checkpoints"} + ) + self.assertEqual(resp.status_code, 422) + + def test_stream_mode_picks_what_is_replayed(self): + runner = log_runner(_golden_graph(), "re-mode") + frames = self._post(runner) + wf = frames[0][2]["workflow_id"] + _wait_done(runner, wf) + got = _frames( + TestClient(serve_app(runner)) + .get(f"/agent/run/{wf}/stream", params={"stream_mode": "updates"}) + .text + ) + self.assertEqual( + {e for _, e, _ in got}, + {"workflow_started", "updates", "workflow_completed"}, + ) + + +class TestReconnectInProcess(_Case): + def test_says_reconnect_needs_a_state_store_and_still_gives_the_result(self): + runner = _chat_graph(name="re-ip") + runner._started = True + runner._workflow_client = LogClient(runner) # type: ignore[assignment] + frames = self._post(runner) + wf = frames[0][2]["workflow_id"] + _wait_done(runner, wf) + got = _frames(TestClient(serve_app(runner)).get(f"/agent/run/{wf}/stream").text) + names = [e for _, e, _ in got] + self.assertEqual( + names, ["workflow_started", "stream_unavailable", "workflow_completed"] + ) + self.assertEqual(got[1][2]["reason"], "transport_not_replayable") + self.assertIn("state store", got[1][2]["message"]) + self.assertIn("output", got[2][2]) + + +class TestAstreamResume(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def test_replays_a_finished_run_like_astream(self): + runner = log_runner(_golden_graph(), "ar-all") + first = await _collect( + runner.astream( + INPUT, workflow_id="wf-ar", stream_mode=MODES, poll_interval=0.01 + ) + ) + again = await _collect( + runner.astream_resume("wf-ar", stream_mode=MODES, poll_interval=0.01) + ) + self.assertEqual(_wire(again), _wire(first)) + + async def test_an_attempt_the_client_saw_part_of_is_reset(self): + runner = log_runner(_golden_graph(), "ar-reset") + await _collect( + runner.astream( + INPUT, workflow_id="wf-arr", stream_mode=MODES, poll_interval=0.01 + ) + ) + # the client saw 2 events of an attempt of "chat" that the log no longer has + cursor = encode_cursor( + StreamCursor(base=0, positions=((0, "chat", "deadbeef", 2),)) + ) + controls: List[Any] = [] + await _collect( + runner.astream_resume( + "wf-arr", + last_event_id=cursor, + stream_mode=MODES, + poll_interval=0.01, + on_control=controls.append, + ) + ) + resets = [c.data for c in controls if c.kind == "node_reset"] + self.assertEqual(resets, [{"node": "chat", "step": 1}]) + + async def test_an_unknown_run_raises(self): + runner = log_runner(_golden_graph(), "ar-404") + with self.assertRaises(LookupError): + await _collect(runner.astream_resume("nope")) From c1ffe68bb242512c959bfb54742a5e83dcec28cc Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 14:29:27 +0100 Subject: [PATCH 38/73] feat(langgraph): reconnect to a run's stream with GET /agent/run/{id}/stream The endpoint (and runner.astream_resume) takes Last-Event-ID, as a header or the last_event_id query parameter, and replays the run's event log after that cursor, then follows the run live and ends with the final event and its result. Any replica serves it. A run on the in-process transport gets stream_unavailable with reason transport_not_replayable, then its result; an unknown run is 404. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 5 + diagrid/agent/langgraph/reconnect.py | 228 ++++++++++++++++++++++++ diagrid/agent/langgraph/runner.py | 196 ++++++++------------ diagrid/agent/langgraph/stream_drain.py | 153 ++++++++++++++++ 4 files changed, 465 insertions(+), 117 deletions(-) create mode 100644 diagrid/agent/langgraph/reconnect.py create mode 100644 diagrid/agent/langgraph/stream_drain.py diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 0f64dbb0..aa67a514 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -696,6 +696,7 @@ async def get_status(workflow_id: str) -> dict: # type: ignore[type-arg] app, pubsub_name, subscribe_topic, _run_and_collect ) + self._add_routes(app) uvicorn.run(app, host=host, port=port) # ------------------------------------------------------------------ @@ -741,6 +742,10 @@ async def _serve_run( # ``"stream": true``). _supports_serve_stream = False + def _add_routes(self, app: Any) -> None: + """Register a runner's own routes on the ``serve()`` app. Default: none.""" + return None + def _validate_stream_request(self, request: dict) -> None: # type: ignore[type-arg] """Raise ``ValueError`` if a streaming request is invalid. diff --git a/diagrid/agent/langgraph/reconnect.py b/diagrid/agent/langgraph/reconnect.py new file mode 100644 index 00000000..6f97649f --- /dev/null +++ b/diagrid/agent/langgraph/reconnect.py @@ -0,0 +1,228 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Reconnecting to a run's stream from wherever the client got to. + +``GET /agent/run/{workflow_id}/stream`` (with ``Last-Event-ID``, or the +``last_event_id`` query parameter for a client that cannot set the header) +and ``runner.astream_resume`` share :func:`resume_events`. On the state-store +transport any replica replays the run's log after the cursor, then follows +the run live and ends with the final event and its result. On the in-process +transport nothing can be replayed: the stream says so, then still ends with +the result. +""" + +import asyncio +import json +import logging +from typing import Any, AsyncGenerator, AsyncIterator, Dict, Optional, Set, Tuple + +from diagrid.agent.core.workflow import stream as stream_module +from diagrid.agent.core.workflow.stream import ( + STREAM_UNAVAILABLE, + StreamEvent, + frame_sse, +) +from diagrid.agent.core.workflow.stream_cursor import parse_cursor + +from .stream_drain import SseEncoder, drain +from .stream_events import ( + FINAL_EVENTS, + KEEPALIVE, + started_event, + stream_failure_event, + without_executed, +) +from .stream_source import NOT_REPLAYABLE, custom_status, open_source +from .streaming import normalize_final, normalize_stream_mode + +logger = logging.getLogger(__name__) + +NOT_REPLAYABLE_MESSAGE = ( + "This runner streams in process, so a stream cannot be resumed or read on " + "another replica: reconnecting needs a state store (any Dapr state store " + "the app has; on Catalyst the workflow store is enough). The run's result " + "follows when it ends." +) + + +def _thread_of(state: Any, workflow_id: str) -> str: + """The thread a run belongs to, from its workflow input.""" + raw = getattr(state, "serialized_input", None) + try: + data = json.loads(raw) if isinstance(raw, str) else raw + except (TypeError, ValueError): + data = None + thread = data.get("thread_id") if isinstance(data, dict) else None + return str(thread or workflow_id) + + +def not_replayable_event(workflow_id: str) -> StreamEvent: + return StreamEvent( + workflow_id=workflow_id, + step=-1, + node="", + attempt_id="", + seq=0, + ns=(), + mode=STREAM_UNAVAILABLE, + data={ + "workflow_id": workflow_id, + "reason": NOT_REPLAYABLE, + "message": NOT_REPLAYABLE_MESSAGE, + "missing_steps": [], + "missing_nodes": [], + }, + ) + + +async def follow_final( + runner: Any, workflow_id: str, thread_id: str, poll_interval: float +) -> Dict[str, Any]: + """Wait for the run to end; its normalized terminal event (stream-only keys kept).""" + final: Dict[str, Any] = {} + try: + async for event in runner._follow_run( + workflow_id, thread_id, poll_interval=poll_interval, streamed=True + ): + if event["type"] in FINAL_EVENTS: + final = event + except Exception as e: + logger.exception("Following run %s failed", workflow_id) + final = stream_failure_event(e, "PollError", True) + return normalize_final(final, workflow_id=workflow_id, thread_id=thread_id) + + +async def _with_keepalive( + task: "asyncio.Task[Dict[str, Any]]", keepalive: bool +) -> AsyncGenerator[Any, None]: + """Keepalives while ``task`` runs (when asked), then its result.""" + while True: + if not keepalive: + yield await task + return + done, _ = await asyncio.wait( + {task}, timeout=stream_module.SSE_KEEPALIVE_SECONDS + ) + if done: + yield task.result() + return + yield KEEPALIVE + + +async def resume_events( + runner: Any, + workflow_id: str, + last_event_id: Optional[str], + *, + poll_interval: float, + keepalive: bool, +) -> AsyncGenerator[Any, None]: + """The items of a reconnected stream, as ``_stream_events`` yields them. + + Raises ``LookupError`` for a run the workflow engine does not know. + """ + client = runner._workflow_client + state = await asyncio.to_thread(client.get_workflow_state, instance_id=workflow_id) + if state is None: + raise LookupError(f"Workflow {workflow_id!r} not found") + thread_id = _thread_of(state, workflow_id) + cursor = parse_cursor(last_event_id) + transport = runner.stream_transport + if not transport.replayable or cursor.at_end: + task = asyncio.create_task( + follow_final(runner, workflow_id, thread_id, poll_interval) + ) + try: + if not cursor.at_end: + yield started_event(workflow_id, thread_id) + yield not_replayable_event(workflow_id) + async for item in _with_keepalive(task, keepalive): + yield without_executed(item) if isinstance(item, dict) else item + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + return + seen: Set[Tuple[int, str]] = set() + source = open_source( + transport, + workflow_id, + status=lambda: custom_status(client, workflow_id), + seen=seen, + cursor=cursor, + ) + + async def pump() -> None: + source.on_final( + await follow_final(runner, workflow_id, thread_id, poll_interval) + ) + + pump_task = asyncio.create_task(pump()) + try: + yield started_event(workflow_id, thread_id) + async for item in drain( + source, + workflow_id=workflow_id, + seen=seen, + keepalive=keepalive, + output_channels=runner.graph_config.output_channels, + ): + yield item + finally: + await source.close() + pump_task.cancel() + await asyncio.gather(pump_task, return_exceptions=True) + + +async def resume_sse( + runner: Any, workflow_id: str, last_event_id: Optional[str], modes: Any +) -> AsyncIterator[Tuple[Any, ...]]: + """The SSE items of a reconnect; a failure of the stream ends it in-band.""" + encoder = SseEncoder(modes, runner.stream_transport.replayable) + try: + async for item in resume_events( + runner, workflow_id, last_event_id, poll_interval=0.5, keepalive=True + ): + out = encoder.encode(item) + if out is not None: + yield out + except Exception as e: + logger.exception("Reconnected stream of %s failed", workflow_id) + failed = stream_failure_event(e, "StreamError", True) + yield ( + "workflow_failed", + normalize_final(failed, workflow_id=workflow_id, thread_id=workflow_id), + ) + + +def _stream_modes(query: Any, default: Any) -> Any: + raw = [m for value in query.getlist("stream_mode") for m in value.split(",") if m] + modes, _ = normalize_stream_mode(raw or default) + return modes + + +def add_reconnect_route(app: Any, runner: Any) -> None: + """Register ``GET /agent/run/{workflow_id}/stream`` on ``app``.""" + from fastapi import HTTPException, Request + from fastapi.responses import StreamingResponse + + @app.get("/agent/run/{workflow_id}/stream") + async def stream_run(workflow_id: str, request: Request) -> Any: + try: + modes = _stream_modes(request.query_params, runner._DEFAULT_STREAM_MODES) + except ValueError as e: + raise HTTPException(status_code=422, detail=str(e)) + # Off the loop: the state lookup is a blocking gRPC call. + state = await asyncio.to_thread( + runner._workflow_client.get_workflow_state, instance_id=workflow_id + ) + if state is None: + raise HTTPException(status_code=404, detail="Workflow not found") + last_event_id = request.headers.get( + "last-event-id" + ) or request.query_params.get("last_event_id") + return StreamingResponse( + frame_sse(resume_sse(runner, workflow_id, last_event_id, modes)), + media_type="text/event-stream", + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, + ) diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 040fe1e3..01acf24b 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -30,19 +30,10 @@ from diagrid.agent.core.workflow import BaseWorkflowRunner from diagrid.agent.core.workflow.runner import fold_run_event from diagrid.agent.core.workflow.stream import ( - BRANCH_DONE, - CONTROL_MODES, - KEEPALIVE_EVENT, - WORKFLOW_STARTED, - UPDATES, - VALUES, InProcessTransport, - StreamClosed, - StreamEvent, StreamSinkRegistry, StreamTransport, ) -from diagrid.agent.core.workflow.stream_cursor import END_ID, START_ID from .models import ( ChannelState, EdgeConfig, @@ -53,9 +44,6 @@ WaitingEdgeConfig, ) from .streaming import ( - BRANCHES_KEY, - EXECUTED_KEY, - FINAL_STATE_KEY, STREAM_RUN_KEY, StaticConfig, FAILED_STATUSES, @@ -66,18 +54,15 @@ ) from .stream_events import ( FINAL_EVENTS, - KEEPALIVE, - closing_events, - count_unencodable, - encode_chunk, stream_failure_event, - next_item, route_astream_item, started_event, without_executed, ) from .langsmith_trace import ParentTrace, start_parent_trace from .run_status import completed_result +from .reconnect import add_reconnect_route, resume_events +from .stream_drain import SseEncoder, drain, parse_output from .stream_source import ( custom_status, open_source, @@ -266,31 +251,6 @@ async def _wait_scheduled(scheduled: asyncio.Event, pump: "asyncio.Task[None]") return scheduled.is_set() -class _SseIds: - """The SSE id of each event of a stream read from the log: its cursor. - - A stream on the in-process transport has no cursor: its events are - numbered per connection (``()`` leaves that to the framer). - """ - - def __init__(self, replayable: bool) -> None: - self._replayable = replayable - self._last = START_ID - - def of(self, item: StreamEvent) -> Tuple[str, ...]: - if not self._replayable: - return () - if item.mode == WORKFLOW_STARTED: - return (START_ID,) - if item.event_id: - self._last = item.event_id - # a control event reuses the cursor of the chunk it follows - return (self._last,) - - def final(self) -> Tuple[str, ...]: - return (END_ID,) if self._replayable else () - - @dataclass(frozen=True) class _RunSetup: """What a run needs once its identity, config and input are settled.""" @@ -964,40 +924,11 @@ async def run_async( # Which nodes ran in each step is for the stream (stream_unavailable), # not for a caller of run_async: only a streamed run asks for it. - streamed = bool(run.config.get(STREAM_RUN_KEY)) - - def _parse_output(wf_id: str, output_dict: dict) -> dict: # type: ignore[type-arg] - output = GraphWorkflowOutput.from_dict(output_dict) - with_executed = streamed and bool(output.executed) - return { - "type": "workflow_completed", - "workflow_id": wf_id, - "output": output.output, - "steps": output.steps, - "status": output.status, - **({"error": output.error} if output.error else {}), - **({EXECUTED_KEY: output.executed} if with_executed else {}), - **( - {BRANCHES_KEY: output.branches} - if streamed and output.branches - else {} - ), - # the state it ended with, for the stream's last values chunk - **( - {FINAL_STATE_KEY: output.channel_state.to_dict()} - if streamed and output.channel_state is not None - else {} - ), - } - - async for event in self._poll_workflow( + async for event in self._follow_run( workflow_id, thread_id, poll_interval=poll_interval, - parse_output=_parse_output, - # A poll that fails is reported as such (PollError) while the - # run may still finish: ride out a restarting sidecar first. - retry_failed_polls=True, + streamed=bool(run.config.get(STREAM_RUN_KEY)), ): yield event @@ -1005,6 +936,64 @@ def _parse_output(wf_id: str, output_dict: dict) -> dict: # type: ignore[type-a if trace: trace.end() + async def _follow_run( + self, + workflow_id: str, + thread_id: str, + *, + poll_interval: float, + streamed: bool, + ) -> AsyncIterator[Dict[str, Any]]: + """Poll a scheduled run; its status changes, then its terminal event.""" + async for event in self._poll_workflow( + workflow_id, + thread_id, + poll_interval=poll_interval, + parse_output=lambda wf_id, out: parse_output(wf_id, out, streamed), + # A poll that fails is reported as such (PollError) while the + # run may still finish: ride out a restarting sidecar first. + retry_failed_polls=True, + ): + yield event + + async def astream_resume( + self, + workflow_id: str, + last_event_id: Optional[str] = None, + *, + stream_mode: Any = "updates", + poll_interval: float = 0.5, + on_control: Optional[Callable[[StreamControl], None]] = None, + ) -> AsyncIterator[Any]: + """Stream a run that was already started, from ``last_event_id`` on. + + ``last_event_id`` is the SSE id of the last event the client got (a + cursor of the state-store transport); ``None`` replays from the start, + and the end id gives the final event only. Chunks are yielded as + :meth:`astream` yields them, from any replica, for a run still going + or one that ended (within the log's TTL). On the in-process transport + nothing is replayed: ``stream_unavailable`` with reason + ``transport_not_replayable``, then the run's end. Raises + ``LookupError`` for an unknown run and :class:`GraphRunError` for a + run that failed. + """ + modes, is_list = normalize_stream_mode(stream_mode) + async with aclosing( + resume_events( + self, + workflow_id, + last_event_id, + poll_interval=poll_interval, + keepalive=False, + ) + ) as events: + async for item in events: + outs, error = route_astream_item(item, modes, is_list, on_control) + for out in outs: + yield out + if error is not None: + raise error + async def astream( self, input: Any, @@ -1101,9 +1090,7 @@ async def _stream_events( status=lambda: custom_status(self._workflow_client, workflow_id), seen=seen_nodes, ) - sink = source.sink task: Optional["asyncio.Task[None]"] = None - values_sent: Set[int] = set() scheduled = asyncio.Event() try: task = asyncio.create_task( @@ -1123,31 +1110,13 @@ async def _stream_events( # writes meanwhile wait in the sink, so they still come after it. if await _wait_scheduled(scheduled, task): yield started_event(workflow_id, thread_id) - while True: - item = await next_item(sink, keepalive) - if isinstance(item, StreamClosed): - # Unregister before handing over the result: chunks a late - # activity attempt writes from here on are dropped. - await source.close() - for event in closing_events( - item, - seen_nodes, - workflow_id, - output_channels=self._graph_config.output_channels, - values_sent=values_sent, - unavailable_reason=source.unavailable_reason, - purged=source.purged, - ): - yield event - return - if isinstance(item, StreamEvent) and item.mode == BRANCH_DONE: - # a router that ran here: internal, never sent on - seen_nodes.add((item.step, item.node)) - continue - if isinstance(item, StreamEvent) and item.mode == UPDATES: - seen_nodes.add((item.step, item.node)) - if isinstance(item, StreamEvent) and item.mode == VALUES: - values_sent.add(item.step) + async for item in drain( + source, + workflow_id=workflow_id, + seen=seen_nodes, + keepalive=keepalive, + output_channels=self._graph_config.output_channels, + ): yield item finally: # Also reached when the consumer goes away (client disconnect, @@ -1326,13 +1295,12 @@ async def _serve_stream( # type: ignore[override] the run's full terminal event. The base runner frames the pairs. """ thread_id = request.get("thread_id") or request.get("session_id") or session_id - workflow_id: Optional[str] = None - unencodable = 0 - ids = _SseIds(self._stream_transport.replayable) + encoder: Optional[SseEncoder] = None try: modes, _ = normalize_stream_mode( request.get("stream_mode") or self._DEFAULT_STREAM_MODES ) + encoder = SseEncoder(modes, self._stream_transport.replayable) graph_input = self._request_to_input(request, streaming=True) async with aclosing( self._stream_events( @@ -1346,28 +1314,22 @@ async def _serve_stream( # type: ignore[override] ) ) as events: async for item in events: - if item is KEEPALIVE: - yield KEEPALIVE_EVENT, None - elif isinstance(item, StreamEvent): - event_id = ids.of(item) - if item.mode not in CONTROL_MODES and item.mode not in modes: - continue - if item.mode == WORKFLOW_STARTED: - workflow_id = item.data["workflow_id"] - wire, ok = encode_chunk(item) - unencodable += 0 if ok else 1 - yield (item.mode, wire, *event_id) - else: - final = count_unencodable(item, unencodable) - yield (item["type"], final, *ids.final()) + out = encoder.encode(item) + if out is not None: + yield out except Exception as e: logger.exception("Streaming run failed") + workflow_id = encoder.workflow_id if encoder else None failed = stream_failure_event(e, "StreamError", bool(workflow_id)) yield ( "workflow_failed", normalize_final(failed, workflow_id=workflow_id, thread_id=thread_id), ) + def _add_routes(self, app: Any) -> None: + """``GET /agent/run/{workflow_id}/stream``: reconnect to a run's stream.""" + add_reconnect_route(app, self) + def _request_to_input( self, request: dict, # type: ignore[type-arg] diff --git a/diagrid/agent/langgraph/stream_drain.py b/diagrid/agent/langgraph/stream_drain.py new file mode 100644 index 00000000..39d59935 --- /dev/null +++ b/diagrid/agent/langgraph/stream_drain.py @@ -0,0 +1,153 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Draining a stream's sink, and turning what it yields into SSE items. + +Shared by a new run's stream (``POST /agent/run``, ``astream``) and a +reconnect (``GET /agent/run/{id}/stream``, ``astream_resume``). +""" + +from typing import Any, AsyncGenerator, Dict, List, Optional, Set, Tuple + +from diagrid.agent.core.workflow.stream import ( + BRANCH_DONE, + CONTROL_MODES, + KEEPALIVE_EVENT, + UPDATES, + VALUES, + WORKFLOW_STARTED, + StreamClosed, + StreamEvent, +) +from diagrid.agent.core.workflow.stream_cursor import END_ID, START_ID + +from .models import GraphWorkflowOutput +from .stream_events import ( + KEEPALIVE, + closing_events, + count_unencodable, + encode_chunk, + next_item, +) +from .stream_source import StreamSource +from .streaming import BRANCHES_KEY, EXECUTED_KEY, FINAL_STATE_KEY + + +def parse_output( + workflow_id: str, output_dict: Dict[str, Any], streamed: bool +) -> Dict[str, Any]: + """The ``workflow_completed`` event of a finished workflow's output. + + Which nodes ran in each step, the routers and the state it ended with are + for the stream (``stream_unavailable``, the last ``values``), not for a + caller of ``run_async``: only a streamed run gets them. + """ + output = GraphWorkflowOutput.from_dict(output_dict) + return { + "type": "workflow_completed", + "workflow_id": workflow_id, + "output": output.output, + "steps": output.steps, + "status": output.status, + **({"error": output.error} if output.error else {}), + **({EXECUTED_KEY: output.executed} if streamed and output.executed else {}), + **({BRANCHES_KEY: output.branches} if streamed and output.branches else {}), + **( + {FINAL_STATE_KEY: output.channel_state.to_dict()} + if streamed and output.channel_state is not None + else {} + ), + } + + +async def drain( + source: StreamSource, + *, + workflow_id: str, + seen: Set[Tuple[int, str]], + keepalive: bool, + output_channels: Optional[List[str]], +) -> AsyncGenerator[Any, None]: + """Yield the sink's chunks, then the items the stream ends with. + + ``seen`` collects the ``(step, node)`` pairs whose ``updates`` (or router + ``branch_done`` marker) arrived, for ``stream_unavailable``. + """ + values_sent: Set[int] = set() + while True: + item = await next_item(source.sink, keepalive) + if isinstance(item, StreamClosed): + # Unregister before handing over the result: chunks a late + # activity attempt writes from here on are dropped. + await source.close() + for event in closing_events( + item, + seen, + workflow_id, + output_channels=output_channels, + values_sent=values_sent, + unavailable_reason=source.unavailable_reason, + purged=source.purged, + ): + yield event + return + if isinstance(item, StreamEvent) and item.mode == BRANCH_DONE: + # a router that ran here: internal, never sent on + seen.add((item.step, item.node)) + continue + if isinstance(item, StreamEvent) and item.mode == UPDATES: + seen.add((item.step, item.node)) + if isinstance(item, StreamEvent) and item.mode == VALUES: + values_sent.add(item.step) + yield item + + +class SseIds: + """The SSE id of each event of a stream read from the log: its cursor. + + A stream on the in-process transport has no cursor: its events are + numbered per connection (``()`` leaves that to the framer). + """ + + def __init__(self, replayable: bool) -> None: + self._replayable = replayable + self._last = START_ID + + def of(self, item: StreamEvent) -> Tuple[str, ...]: + if not self._replayable: + return () + if item.mode == WORKFLOW_STARTED: + return (START_ID,) + if item.event_id: + self._last = item.event_id + # a control event reuses the cursor of the chunk it follows + return (self._last,) + + def final(self) -> Tuple[str, ...]: + return (END_ID,) if self._replayable else () + + +class SseEncoder: + """``(event, data[, id])`` for each item of a stream, as ``frame_sse`` takes it.""" + + def __init__(self, modes: List[str], replayable: bool) -> None: + self._modes = modes + self._ids = SseIds(replayable) + self.unencodable = 0 + self.workflow_id: Optional[str] = None + + def encode(self, item: Any) -> Optional[Tuple[Any, ...]]: + """The SSE item for ``item``, or ``None`` for one the client did not ask for.""" + if item is KEEPALIVE: + return (KEEPALIVE_EVENT, None) + if isinstance(item, StreamEvent): + event_id = self._ids.of(item) + if item.mode not in CONTROL_MODES and item.mode not in self._modes: + return None + if item.mode == WORKFLOW_STARTED: + self.workflow_id = item.data["workflow_id"] + wire, ok = encode_chunk(item) + self.unencodable += 0 if ok else 1 + return (item.mode, wire, *event_id) + final = count_unencodable(item, self.unencodable) + return (item["type"], final, *self._ids.final()) From 68b6b9dc3f3c67bbe37991619e3c34611fe5d88a Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 14:39:46 +0100 Subject: [PATCH 39/73] test(langgraph): expect interrupt() to pause the run durably and Command(resume=...) to continue it Signed-off-by: Casper Nielsen --- tests/agent/langgraph/test_interrupt.py | 227 ++++++++++++++++++ .../agent/langgraph/test_reconnect_helpers.py | 18 ++ 2 files changed, 245 insertions(+) create mode 100644 tests/agent/langgraph/test_interrupt.py create mode 100644 tests/agent/langgraph/test_reconnect_helpers.py diff --git a/tests/agent/langgraph/test_interrupt.py b/tests/agent/langgraph/test_interrupt.py new file mode 100644 index 00000000..581f4ccb --- /dev/null +++ b/tests/agent/langgraph/test_interrupt.py @@ -0,0 +1,227 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``interrupt()`` in a node: the run pauses durably and resumes with ``Command(resume=...)``.""" + +import json +import operator +import time +import unittest +from typing import Any + +from fastapi.testclient import TestClient +from langgraph.graph import END, START, StateGraph +from langgraph.types import Command, Interrupt, interrupt +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.models import ChannelState, ExecuteNodeInput +from diagrid.agent.langgraph.streaming import STREAM_RUN_KEY +from diagrid.agent.langgraph.workflow import execute_node_activity + +from .log_helpers import LogClient, log_runner +from .streaming_helpers import _collect, _Ctx, serve_app +from .test_reconnect_helpers import frames +from .test_runner import _RunnerTestCase + + +class _State(TypedDict, total=False): + answer: str + log: Annotated[list, operator.add] + + +def _approval_graph(asks: int = 1) -> Any: + def ask(state: _State) -> dict: + answers = [interrupt({"question": f"approve #{i}?"}) for i in range(asks)] + return {"answer": "+".join(str(a) for a in answers), "log": ["ask"]} + + def after(state: _State) -> dict: + return {"log": [f"after:{state['answer']}"]} + + graph = StateGraph(_State) + graph.add_node("ask", ask) + graph.add_node("after", after) + graph.add_edge(START, "ask") + graph.add_edge("ask", "after") + graph.add_edge("after", END) + return graph.compile() + + +def _wait(predicate: Any, timeout: float = 10.0) -> None: + deadline = time.monotonic() + timeout + while not predicate() and time.monotonic() < deadline: + time.sleep(0.01) + + +def _custom(runner: Any, wf: str) -> dict: + raw = runner._workflow_client.custom.get(wf) + return json.loads(raw) if raw else {} + + +INPUT = {"log": ["start"]} + + +class TestActivity(_RunnerTestCase): + def _payload(self, resume: Any = None) -> dict: + return ExecuteNodeInput( + node_name="ask", + channel_state=ChannelState(values={"log": []}, versions={"log": 1}), + config={STREAM_RUN_KEY: True}, + step=0, + resume=resume, + ).to_dict() + + def test_a_node_that_interrupts_returns_its_interrupt_not_an_error(self): + log_runner(_approval_graph(), "act-int") # registers the graph's nodes + out = execute_node_activity(_Ctx("wf-act"), self._payload()) + self.assertIsNone(out["error"]) + self.assertEqual(out["writes"], []) + self.assertEqual(len(out["interrupts"]), 1) + self.assertEqual(out["interrupts"][0]["value"], {"question": "approve #0?"}) + self.assertTrue(out["interrupts"][0]["id"]) + + def test_the_resume_value_is_what_interrupt_returns(self): + log_runner(_approval_graph(), "act-res") + out = execute_node_activity(_Ctx("wf-act2"), self._payload(resume=["yes"])) + self.assertNotIn("interrupts", out) + writes = {w["channel"]: w["value"] for w in out["writes"]} + self.assertEqual(writes["answer"], "yes") + self.assertNotIn("__resume__", writes) + + +class TestInterruptOverHttp(_RunnerTestCase): + def _start(self, name: str, asks: int = 1) -> Any: + runner = log_runner(_approval_graph(asks), name) + http = TestClient(serve_app(runner)) + resp = http.post( + "/agent/run", json={**INPUT, "stream": True, "thread_id": "t-1"} + ) + return runner, http, frames(resp.text) + + def test_the_stream_shows_the_interrupt_and_ends_while_the_run_waits(self): + runner, http, got = self._start("h-int") + names = [e for _, e, _ in got] + self.assertEqual(names[-1], "workflow_interrupted") + final = got[-1][2] + wf = final["workflow_id"] + self.assertEqual(final["interrupts"][0]["value"], {"question": "approve #0?"}) + updates = [d for _, e, d in got if e == "updates"] + self.assertIn("__interrupt__", updates[-1]) + # durably waiting: the workflow is still running, not done + self.assertNotIn(wf, runner._workflow_client.done) + status = http.get(f"/agent/run/{wf}").json() + self.assertIn("RUNNING", status["status"]) + self.assertTrue(status["interrupted"]) + self.assertEqual(status["interrupts"][0]["value"], {"question": "approve #0?"}) + + def test_resuming_continues_the_same_run_and_streams_the_rest(self): + runner, http, got = self._start("h-res") + wf = got[-1][2]["workflow_id"] + resp = http.post( + f"/agent/run/{wf}/resume", json={"resume": "yes", "stream": True} + ) + self.assertEqual(resp.status_code, 200) + rest = frames(resp.text) + self.assertEqual(rest[0][1], "workflow_started") + self.assertEqual(rest[0][2]["workflow_id"], wf) + self.assertEqual(rest[0][2]["thread_id"], "t-1") + updates = [d for _, e, d in rest if e == "updates"] + self.assertEqual([list(u) for u in updates], [["ask"], ["after"]]) + self.assertEqual(rest[-1][1], "workflow_completed") + self.assertEqual(rest[-1][2]["output"]["answer"], "yes") + self.assertEqual(rest[-1][2]["output"]["log"], ["start", "ask", "after:yes"]) + + def test_a_plain_resume_returns_the_result(self): + runner, http, got = self._start("h-plain") + wf = got[-1][2]["workflow_id"] + body = http.post(f"/agent/run/{wf}/resume", json={"resume": "ok"}).json() + self.assertEqual(body["status"], "completed") + self.assertEqual(body["output"]["answer"], "ok") + + def test_each_interrupt_waits_for_its_own_resume(self): + runner, http, got = self._start("h-two", asks=2) + wf = got[-1][2]["workflow_id"] + first = frames( + http.post( + f"/agent/run/{wf}/resume", json={"resume": "a", "stream": True} + ).text + ) + self.assertEqual(first[-1][1], "workflow_interrupted") + self.assertEqual( + first[-1][2]["interrupts"][0]["value"], {"question": "approve #1?"} + ) + second = frames( + http.post( + f"/agent/run/{wf}/resume", json={"resume": "b", "stream": True} + ).text + ) + self.assertEqual(second[-1][2]["output"]["answer"], "a+b") + + def test_resume_is_refused_when_it_cannot_apply(self): + runner, http, got = self._start("h-bad") + wf = got[-1][2]["workflow_id"] + self.assertEqual( + http.post(f"/agent/run/{wf}/resume", json={"value": 1}).status_code, 422 + ) + self.assertEqual( + http.post("/agent/run/nope/resume", json={"resume": 1}).status_code, 404 + ) + http.post(f"/agent/run/{wf}/resume", json={"resume": "x"}) + _wait(lambda: wf in runner._workflow_client.done) + self.assertEqual( + http.post(f"/agent/run/{wf}/resume", json={"resume": 1}).status_code, 409 + ) + + +class TestInterruptInPython(_RunnerTestCase, unittest.IsolatedAsyncioTestCase): + async def test_astream_with_a_command_resumes_the_run(self): + runner = log_runner(_approval_graph(), "py-res") + first = await _collect( + runner.astream( + INPUT, workflow_id="wf-py", stream_mode="updates", poll_interval=0.01 + ) + ) + (interrupted,) = first[-1]["__interrupt__"] + self.assertIsInstance(interrupted, Interrupt) + self.assertEqual(interrupted.value, {"question": "approve #0?"}) + rest = await _collect( + runner.astream( + Command(resume="go"), + workflow_id="wf-py", + stream_mode="updates", + poll_interval=0.01, + ) + ) + self.assertEqual(rest[-1], {"after": {"log": ["after:go"]}}) + + async def test_a_command_without_a_run_to_resume_is_refused(self): + runner = log_runner(_approval_graph(), "py-bad") + with self.assertRaises(ValueError): + await _collect(runner.astream(Command(resume="go"))) + + +class TestInvoke(_RunnerTestCase): + def test_invoke_returns_the_interrupt_instead_of_waiting_forever(self): + runner = log_runner(_approval_graph(), "inv") + out = runner.invoke(INPUT, workflow_id="wf-inv", poll_interval=0.01, timeout=10) + (interrupted,) = out["__interrupt__"] + self.assertEqual(interrupted.value, {"question": "approve #0?"}) + + +class TestInProcessResume(_RunnerTestCase): + def test_resume_streams_in_process_too(self): + # no store: the in-process transport + runner = DaprWorkflowGraphRunner(graph=_approval_graph(), name="ip-int") + runner._started = True + runner._workflow_client = LogClient(runner) # type: ignore[assignment] + http = TestClient(serve_app(runner)) + got = frames(http.post("/agent/run", json={**INPUT, "stream": True}).text) + self.assertEqual(got[-1][1], "workflow_interrupted") + wf = got[-1][2]["workflow_id"] + rest = frames( + http.post( + f"/agent/run/{wf}/resume", json={"resume": "y", "stream": True} + ).text + ) + self.assertEqual(rest[-1][1], "workflow_completed") + self.assertIn("after", [list(d)[0] for _, e, d in rest if e == "updates"]) diff --git a/tests/agent/langgraph/test_reconnect_helpers.py b/tests/agent/langgraph/test_reconnect_helpers.py new file mode 100644 index 00000000..bf47e509 --- /dev/null +++ b/tests/agent/langgraph/test_reconnect_helpers.py @@ -0,0 +1,18 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Reading SSE bodies in the reconnect and interrupt tests.""" + +import json +from typing import Any, List, Tuple + + +def frames(text: str) -> List[Tuple[str, str, Any]]: + """``(id, event, data)`` of each SSE frame (comments left out).""" + out = [] + for frame in text.strip().split("\n\n"): + if frame.startswith(":") or not frame: + continue + fields = dict(line.split(": ", 1) for line in frame.split("\n")) + out.append((fields.get("id"), fields["event"], json.loads(fields["data"]))) + return out From 2ace7d7b1f13621b06749f868ed6946921a7c870 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 14:48:24 +0100 Subject: [PATCH 40/73] feat(langgraph): pause a run on interrupt() and resume it with Command(resume=...) A node that calls interrupt() returns its interrupts from the activity (no writes, no retry) and streams LangGraph's __interrupt__ updates chunk. The workflow keeps the step's other results, publishes the interrupt in its custom status and waits durably for a resume event; the stream ends with workflow_interrupted and GET /agent/run/{id} shows the interrupts. A resume (POST /agent/run/{id}/resume, or astream(Command(resume=...), workflow_id=...)) raises that event and re-runs the interrupted tasks of the same step with the resume values, then streams the rest of the same run on the same thread. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 9 +- diagrid/agent/langgraph/activity_stream.py | 9 +- diagrid/agent/langgraph/interrupts.py | 212 +++++++++++++++++++++ diagrid/agent/langgraph/models.py | 12 ++ diagrid/agent/langgraph/reconnect.py | 15 +- diagrid/agent/langgraph/resume_run.py | 185 ++++++++++++++++++ diagrid/agent/langgraph/run_status.py | 23 +++ diagrid/agent/langgraph/runner.py | 57 +++++- diagrid/agent/langgraph/stream_events.py | 1 + diagrid/agent/langgraph/stream_follow.py | 35 ++++ diagrid/agent/langgraph/stream_source.py | 2 + diagrid/agent/langgraph/streaming.py | 29 +++ diagrid/agent/langgraph/workflow.py | 145 +++++++++++--- 13 files changed, 687 insertions(+), 47 deletions(-) create mode 100644 diagrid/agent/langgraph/interrupts.py create mode 100644 diagrid/agent/langgraph/resume_run.py diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index aa67a514..57e1210e 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -197,7 +197,7 @@ def fold_run_event(result: dict, event: dict) -> bool: # type: ignore[type-arg] result["instance_id"] = event["workflow_id"] if event.get("thread_id"): result["thread_id"] = event["thread_id"] - elif kind in ("workflow_completed", "workflow_failed"): + elif kind in ("workflow_completed", "workflow_failed", "workflow_interrupted"): result.update(event) return True return False @@ -452,6 +452,7 @@ async def _poll_workflow( poll_interval: float = 0.5, parse_output: Any = None, retry_failed_polls: bool = False, + running_event: Optional[Callable[[Any], Optional[dict[str, Any]]]] = None, ) -> AsyncIterator[dict[str, Any]]: """Poll a running workflow and yield status/completion events. @@ -459,7 +460,9 @@ async def _poll_workflow( dict (the raw output is returned without one). ``retry_failed_polls`` rides out a failed poll that looks transient (see ``POLL_MAX_ERRORS``) instead of raising at once; a runner opts in when it can tell its - caller that the run's fate is unknown. + caller that the run's fate is unknown. ``running_event`` may end the + poll of a run that is still running (one paused for input): the event + it returns for a state is yielded last. """ assert self._workflow_client is not None previous_status = None @@ -485,6 +488,8 @@ async def _poll_workflow( previous_status = state.runtime_status terminal = _terminal_event(state, workflow_id, parse_output) + if terminal is None and running_event is not None: + terminal = running_event(state) if terminal is not None: yield terminal break diff --git a/diagrid/agent/langgraph/activity_stream.py b/diagrid/agent/langgraph/activity_stream.py index f4ed0440..adcc212d 100644 --- a/diagrid/agent/langgraph/activity_stream.py +++ b/diagrid/agent/langgraph/activity_stream.py @@ -54,11 +54,18 @@ def activity_writer( def run_status(run: Any) -> Dict[str, Any]: - """The custom status of a run: what a stream reader needs to find its units.""" + """The custom status of a run: what a stream reader needs to find its + units, and the interrupt the run waits on.""" + from .interrupts import STATUS_INTERRUPT, STATUS_INTERRUPT_SEQ + status: Dict[str, Any] = {} if (run.config or {}).get(STREAM_RUN_KEY): status[STATUS_EXECUTED] = run.executed status[STATUS_BRANCHES] = run.branches + if run.interrupt_seq: + status[STATUS_INTERRUPT_SEQ] = run.interrupt_seq + if run.interrupt: + status[STATUS_INTERRUPT] = run.interrupt return status diff --git a/diagrid/agent/langgraph/interrupts.py b/diagrid/agent/langgraph/interrupts.py new file mode 100644 index 00000000..e0934a60 --- /dev/null +++ b/diagrid/agent/langgraph/interrupts.py @@ -0,0 +1,212 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``interrupt()`` and ``Command(resume=...)`` on the Dapr workflow runner. + +LangGraph pauses a task that calls ``interrupt(value)``: the run ends with the +interrupt, the checkpointer keeps the thread, and a later run on the same +thread with ``Command(resume=...)`` re-runs the task, where ``interrupt`` +now returns the resume value. Here the workflow is the checkpoint: + +- The node activity runs the node with LangGraph's interrupt scratchpad. When + it raises ``GraphInterrupt`` the activity returns the interrupts (no writes, + not an error, so Dapr does not retry it) and streams them as LangGraph's + ``{"__interrupt__": ...}`` updates chunk. +- The workflow keeps the step's other results, publishes the interrupts in its + custom status, and waits for the ``resume`` external event: durably, in the + workflow history, on whatever replica, for as long as it takes. +- A resume raises that event. The workflow re-runs the interrupted tasks of + the same step with the resume values (``interrupt`` returns them in order), + then goes on as if the step had just finished. A task that interrupts again + waits for the next resume. +""" + +import itertools +import json +from typing import Any, Callable, Dict, Generator, List, Optional, Sequence, Tuple + +from .models import ExecuteNodeOutput + +#: The external event a resume raises on the workflow. +RESUME_EVENT = "resume" +#: Custom status: the pending interrupt, and the number of the last one. +STATUS_INTERRUPT = "interrupt" +STATUS_INTERRUPT_SEQ = "interrupt_seq" +#: The updates-chunk key LangGraph streams interrupts under. +INTERRUPT_KEY = "__interrupt__" +#: The final event of a stream whose run is waiting for a resume. +WORKFLOW_INTERRUPTED = "workflow_interrupted" + + +def _plain(value: Any) -> Any: + """``value`` as JSON (an interrupt's payload crosses the workflow and HTTP).""" + return json.loads(json.dumps(value, default=str)) + + +def _no_null_resume(consume: bool = False) -> Any: + """No resume value without a task: every resume here names its tasks.""" + return None + + +def interrupt_config( + *, + namespace: str, + step: int, + stop: Optional[int], + resume: Optional[List[Any]], + send: Callable[[Sequence[Tuple[str, Any]]], None], +) -> Dict[str, Any]: + """The ``configurable`` keys ``langgraph.types.interrupt`` reads. + + ``namespace`` names the task, so an interrupt's id is the same on every + run of it; ``resume`` holds the values the task's interrupts get, in order. + """ + from langgraph._internal._constants import ( + CONFIG_KEY_CHECKPOINT_NS, + CONFIG_KEY_SCRATCHPAD, + CONFIG_KEY_SEND, + ) + from langgraph._internal._scratchpad import PregelScratchpad + + calls, interrupts, subgraphs = ( + itertools.count(), + itertools.count(), + itertools.count(), + ) + scratchpad = PregelScratchpad( + step=step, + stop=stop or 0, + call_counter=lambda: next(calls), + interrupt_counter=lambda: next(interrupts), + get_null_resume=_no_null_resume, + resume=list(resume or []), + subgraph_counter=lambda: next(subgraphs), + ) + return { + CONFIG_KEY_SCRATCHPAD: scratchpad, + CONFIG_KEY_CHECKPOINT_NS: namespace, + CONFIG_KEY_SEND: send, + } + + +def without_resume_writes(writes: List[Tuple[str, Any]]) -> List[Tuple[str, Any]]: + """``writes`` minus the bookkeeping ``interrupt()`` records for Pregel.""" + from langgraph._internal._constants import RESUME + + return [w for w in writes if w[0] != RESUME] + + +def interrupt_payloads(error: BaseException) -> List[Dict[str, Any]]: + """The interrupts a ``GraphInterrupt`` carries, as JSON.""" + found = error.args[0] if error.args else () + out = [] + for item in found or (): + payload: Dict[str, Any] = { + "id": str(getattr(item, "id", "")), + "value": _plain(getattr(item, "value", None)), + } + schema = getattr(item, "response_schema", None) + if schema is not None: + payload["response_schema"] = _plain(schema) + out.append(payload) + return out + + +def as_interrupts(payloads: Sequence[Dict[str, Any]]) -> Tuple[Any, ...]: + """LangGraph ``Interrupt`` objects for ``payloads`` (what native astream yields).""" + from langgraph.types import Interrupt + + out = [] + for p in payloads: + if isinstance(p, Interrupt): + out.append(p) + elif isinstance(p, dict): + out.append(Interrupt(value=p.get("value"), id=str(p.get("id", "")))) + return tuple(out) + + +def resume_values(pending: Sequence[Dict[str, Any]], resume: Any) -> Dict[str, Any]: + """The resume value of each pending interrupt id. + + A dict whose keys are all pending interrupt ids maps them one by one (as + LangGraph's ``Command(resume={id: value})``); anything else resumes every + pending interrupt with the same value. + """ + ids = [str(p["id"]) for p in pending] + if isinstance(resume, dict) and resume and set(resume) <= set(ids): + return {i: resume[i] for i in ids if i in resume} + return {i: resume for i in ids} + + +def settle_interrupts( + run: Any, + outputs: List[ExecuteNodeOutput], + step: int, + rerun: Callable[ + [Dict[int, List[Any]]], Generator[Any, Any, Dict[int, ExecuteNodeOutput]] + ], + publish: Callable[[Any], None], +) -> Generator[Any, Any, List[ExecuteNodeOutput]]: + """Workflow step: wait out every interrupt of a step's tasks (deterministic). + + ``rerun`` runs the tasks at the given positions again with their resume + values and returns their new outputs; ``publish`` sets the custom status. + """ + resumes: Dict[int, List[Any]] = {} + while True: + pending = [ + {**p, "node": o.node_name, "task": i} + for i, o in enumerate(outputs) + for p in (o.interrupts or []) + ] + if not pending: + return outputs + run.interrupt_seq += 1 + run.interrupt = {"seq": run.interrupt_seq, "step": step, "interrupts": pending} + publish(run) + values = yield from _wait_resume(run.ctx, run.interrupt_seq, pending) + run.interrupt = None + publish(run) + for item in pending: + if item["id"] in values: + resumes.setdefault(item["task"], []).append(values[item["id"]]) + again = yield from rerun( + {task: resumes.get(task, []) for task in {p["task"] for p in pending}} + ) + outputs = [again.get(i, output) for i, output in enumerate(outputs)] + + +def _wait_resume( + ctx: Any, seq: int, pending: List[Dict[str, Any]] +) -> Generator[Any, Any, Dict[str, Any]]: + """Wait for the resume of interrupt ``seq``; others (stale) are ignored.""" + while True: + event = yield ctx.wait_for_external_event(RESUME_EVENT) + data = event if isinstance(event, dict) else {"resume": event} + if data.get("seq") in (None, seq): + return resume_values(pending, data.get("resume")) + + +def pending_interrupt(status: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """The interrupt a run waits on, from its custom status, or ``None``.""" + pending = status.get(STATUS_INTERRUPT) + return pending if isinstance(pending, dict) and pending.get("interrupts") else None + + +def interrupted_event( + status: Dict[str, Any], workflow_id: str, after_seq: int = 0 +) -> Optional[Dict[str, Any]]: + """The ``workflow_interrupted`` event for a run waiting on a newer interrupt.""" + pending = pending_interrupt(status) + if pending is None or int(pending.get("seq") or 0) <= after_seq: + return None + return { + "type": WORKFLOW_INTERRUPTED, + "workflow_id": workflow_id, + "status": "interrupted", + "interrupt_seq": int(pending.get("seq") or 0), + "interrupts": [ + {k: v for k, v in item.items() if k != "task"} + for item in pending["interrupts"] + ], + } diff --git a/diagrid/agent/langgraph/models.py b/diagrid/agent/langgraph/models.py index 46699fe9..9ccf00b6 100644 --- a/diagrid/agent/langgraph/models.py +++ b/diagrid/agent/langgraph/models.py @@ -254,6 +254,8 @@ class ExecuteNodeInput: output_channels: The graph's output channels, set only in a streamed run: the activity sends the state it is handed (the state after the previous step) as a ``values`` chunk when the step wrote one of them. + resume: The values this task's ``interrupt()`` calls return, in order, + when it runs again after the run was resumed; ``None`` otherwise. """ node_name: str @@ -265,6 +267,7 @@ class ExecuteNodeInput: recursion_limit: Optional[int] = None routes: Optional[List[Dict[str, Any]]] = None output_channels: Optional[List[str]] = None + resume: Optional[List[Any]] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -283,6 +286,8 @@ def to_dict(self) -> Dict[str, Any]: data["routes"] = self.routes if self.output_channels is not None: data["output_channels"] = self.output_channels + if self.resume is not None: + data["resume"] = self.resume return data @classmethod @@ -297,6 +302,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeInput": recursion_limit=data.get("recursion_limit"), routes=data.get("routes"), output_channels=data.get("output_channels"), + resume=data.get("resume"), ) @@ -330,6 +336,9 @@ class ExecuteNodeOutput: next_nodes: List[str] = field(default_factory=list) route_sends: List[Dict[str, Any]] = field(default_factory=list) route_error: Optional[str] = None + #: The task called ``interrupt()``: ``[{"id", "value"}]``; it wrote nothing + #: and runs again when the run is resumed. + interrupts: Optional[List[Dict[str, Any]]] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -348,6 +357,8 @@ def to_dict(self) -> Dict[str, Any]: data["route_sends"] = list(self.route_sends) if self.route_error: data["route_error"] = self.route_error + if self.interrupts: + data["interrupts"] = list(self.interrupts) return data @classmethod @@ -362,6 +373,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeOutput": next_nodes=list(data.get("next_nodes") or []), route_sends=list(data.get("route_sends") or []), route_error=data.get("route_error"), + interrupts=data.get("interrupts"), ) diff --git a/diagrid/agent/langgraph/reconnect.py b/diagrid/agent/langgraph/reconnect.py index 6f97649f..74311afb 100644 --- a/diagrid/agent/langgraph/reconnect.py +++ b/diagrid/agent/langgraph/reconnect.py @@ -77,13 +77,22 @@ def not_replayable_event(workflow_id: str) -> StreamEvent: async def follow_final( - runner: Any, workflow_id: str, thread_id: str, poll_interval: float + runner: Any, + workflow_id: str, + thread_id: str, + poll_interval: float, + after_seq: int = 0, ) -> Dict[str, Any]: - """Wait for the run to end; its normalized terminal event (stream-only keys kept).""" + """Wait for the run to end (or to pause on an interrupt newer than + ``after_seq``); its normalized terminal event (stream-only keys kept).""" final: Dict[str, Any] = {} try: async for event in runner._follow_run( - workflow_id, thread_id, poll_interval=poll_interval, streamed=True + workflow_id, + thread_id, + poll_interval=poll_interval, + streamed=True, + after_seq=after_seq, ): if event["type"] in FINAL_EVENTS: final = event diff --git a/diagrid/agent/langgraph/resume_run.py b/diagrid/agent/langgraph/resume_run.py new file mode 100644 index 00000000..a15ca10f --- /dev/null +++ b/diagrid/agent/langgraph/resume_run.py @@ -0,0 +1,185 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Resuming a run paused by ``interrupt()``: ``Command(resume=...)``. + +``POST /agent/run/{workflow_id}/resume`` (``{"resume": value}``, with +``"stream": true`` for SSE) and ``astream(Command(resume=...), +workflow_id=...)`` raise the workflow's ``resume`` event and follow the same +run to its end, or to its next interrupt. A stream of a resumed run carries +what happens after the resume only. +""" + +import asyncio +import logging +from typing import Any, AsyncGenerator, AsyncIterator, Dict, Set, Tuple + +from diagrid.agent.core.workflow.stream import frame_sse + +from .activity_stream import parse_status +from .interrupts import RESUME_EVENT, pending_interrupt +from .reconnect import _thread_of, follow_final +from .stream_drain import SseEncoder, drain +from .stream_events import started_event, stream_failure_event, without_executed +from .stream_source import custom_status, open_source +from .streaming import normalize_final, normalize_stream_mode + +logger = logging.getLogger(__name__) + + +class NotInterrupted(ValueError): + """The run is not waiting for a resume (it ended, or never paused).""" + + +async def _pending(runner: Any, workflow_id: str) -> Tuple[int, str]: + """``(interrupt seq, thread id)`` of a run waiting for a resume. + + Raises ``LookupError`` for an unknown run, :class:`NotInterrupted` for a + run that is not waiting. + """ + client = runner._workflow_client + state = await asyncio.to_thread(client.get_workflow_state, instance_id=workflow_id) + if state is None: + raise LookupError(f"Workflow {workflow_id!r} not found") + pending = pending_interrupt( + parse_status(getattr(state, "serialized_custom_status", None)) + ) + if pending is None: + raise NotInterrupted(f"Workflow {workflow_id!r} is not waiting for a resume") + return int(pending.get("seq") or 0), _thread_of(state, workflow_id) + + +async def _send_resume(runner: Any, workflow_id: str, seq: int, value: Any) -> None: + await asyncio.to_thread( + runner._workflow_client.raise_workflow_event, + instance_id=workflow_id, + event_name=RESUME_EVENT, + data={"seq": seq, "resume": value}, + ) + + +async def resume_run_events( + runner: Any, + workflow_id: str, + value: Any, + *, + poll_interval: float, + keepalive: bool, +) -> AsyncGenerator[Any, None]: + """Resume the run and yield its stream from there, as ``_stream_events`` does.""" + seq, thread_id = await _pending(runner, workflow_id) + client = runner._workflow_client + seen: Set[Tuple[int, str]] = set() + source = open_source( + runner.stream_transport, + workflow_id, + status=lambda: custom_status(client, workflow_id), + seen=seen, + # what the log holds now was streamed before the interrupt + from_end=True, + ) + pump_task = None + try: + if source.follower is not None: + await source.follower.ready.wait() + await _send_resume(runner, workflow_id, seq, value) + + async def pump() -> None: + source.on_final( + await follow_final( + runner, workflow_id, thread_id, poll_interval, after_seq=seq + ) + ) + + pump_task = asyncio.create_task(pump()) + yield started_event(workflow_id, thread_id) + async for item in drain( + source, + workflow_id=workflow_id, + seen=seen, + keepalive=keepalive, + output_channels=runner.graph_config.output_channels, + ): + yield item + finally: + await source.close() + if pump_task is not None: + pump_task.cancel() + await asyncio.gather(pump_task, return_exceptions=True) + + +async def resume_run_result( + runner: Any, workflow_id: str, value: Any, *, poll_interval: float +) -> Dict[str, Any]: + """Resume the run and wait for it: the body a plain ``POST /agent/run`` returns.""" + seq, thread_id = await _pending(runner, workflow_id) + await _send_resume(runner, workflow_id, seq, value) + final = await follow_final( + runner, workflow_id, thread_id, poll_interval, after_seq=seq + ) + return { + "instance_id": workflow_id, + "thread_id": thread_id, + **without_executed(final), + } + + +async def _resume_sse( + runner: Any, workflow_id: str, value: Any, modes: Any +) -> AsyncIterator[Tuple[Any, ...]]: + encoder = SseEncoder(modes, runner.stream_transport.replayable) + try: + async for item in resume_run_events( + runner, workflow_id, value, poll_interval=0.5, keepalive=True + ): + out = encoder.encode(item) + if out is not None: + yield out + except Exception as e: + logger.exception("Resumed run %s failed to stream", workflow_id) + failed = stream_failure_event(e, "StreamError", True) + yield ( + "workflow_failed", + normalize_final(failed, workflow_id=workflow_id, thread_id=workflow_id), + ) + + +def add_resume_route(app: Any, runner: Any) -> None: + """Register ``POST /agent/run/{workflow_id}/resume`` on ``app``.""" + from fastapi import HTTPException, Request + from fastapi.responses import StreamingResponse + + @app.post("/agent/run/{workflow_id}/resume") + async def resume_run(workflow_id: str, request: Request) -> Any: + try: + body = await request.json() + except ValueError: + raise HTTPException(status_code=422, detail="the body must be JSON") + if not isinstance(body, dict) or "resume" not in body: + raise HTTPException( + status_code=422, detail='the body must be {"resume": }' + ) + try: + modes, _ = normalize_stream_mode( + body.get("stream_mode") or runner._DEFAULT_STREAM_MODES + ) + except ValueError as e: + raise HTTPException(status_code=422, detail=str(e)) + try: + await _pending(runner, workflow_id) + except LookupError: + raise HTTPException(status_code=404, detail="Workflow not found") + except NotInterrupted as e: + raise HTTPException(status_code=409, detail=str(e)) + if body.get("stream") is True: + return StreamingResponse( + frame_sse(_resume_sse(runner, workflow_id, body["resume"], modes)), + media_type="text/event-stream", + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, + ) + try: + return await resume_run_result( + runner, workflow_id, body["resume"], poll_interval=0.5 + ) + except NotInterrupted as e: + raise HTTPException(status_code=409, detail=str(e)) diff --git a/diagrid/agent/langgraph/run_status.py b/diagrid/agent/langgraph/run_status.py index 4bf8caac..91d521ed 100644 --- a/diagrid/agent/langgraph/run_status.py +++ b/diagrid/agent/langgraph/run_status.py @@ -33,3 +33,26 @@ def completed_result(state: Any) -> Dict[str, Any]: "run_status": output.status, **({"error": output.error} if output.error else {}), } + + +def interrupted_result(state: Any) -> Dict[str, Any]: + """A run paused by ``interrupt()``: ``interrupted`` and its interrupts. + + ``status`` stays the workflow's (running: it waits durably for a resume). + Empty for a run that is not paused. + """ + from .activity_stream import parse_status + from .interrupts import interrupted_event + + if state.runtime_status != WorkflowStatus.RUNNING: + return {} + paused = interrupted_event( + parse_status(getattr(state, "serialized_custom_status", None)), "" + ) + if paused is None: + return {} + return { + "interrupted": True, + "interrupt_seq": paused["interrupt_seq"], + "interrupts": paused["interrupts"], + } diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 01acf24b..03e69c0e 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -25,6 +25,7 @@ from dapr.ext.workflow import WorkflowStatus from langchain_core.runnables.config import DEFAULT_RECURSION_LIMIT +from langgraph.types import Command from diagrid.agent.core.types.type import SupportedFrameworks from diagrid.agent.core.workflow import BaseWorkflowRunner @@ -60,8 +61,11 @@ without_executed, ) from .langsmith_trace import ParentTrace, start_parent_trace -from .run_status import completed_result +from .run_status import completed_result, interrupted_result +from .activity_stream import parse_status +from .interrupts import INTERRUPT_KEY, as_interrupts, interrupted_event from .reconnect import add_reconnect_route, resume_events +from .resume_run import add_resume_route, resume_run_events from .stream_drain import SseEncoder, drain, parse_output from .stream_source import ( custom_status, @@ -834,6 +838,13 @@ def invoke( if state is None: raise RuntimeError(f"Workflow {workflow_id} state not found") + paused = interrupted_event( + parse_status(state.serialized_custom_status), workflow_id + ) + if state.runtime_status == WorkflowStatus.RUNNING and paused: + # As LangGraph's invoke: the interrupts, under __interrupt__. + return {INTERRUPT_KEY: list(as_interrupts(paused["interrupts"]))} + if state.runtime_status == WorkflowStatus.COMPLETED: # Workflow completed normally; workflow.py already closes the trace. trace = None @@ -943,8 +954,13 @@ async def _follow_run( *, poll_interval: float, streamed: bool, + after_seq: int = 0, ) -> AsyncIterator[Dict[str, Any]]: - """Poll a scheduled run; its status changes, then its terminal event.""" + """Poll a scheduled run; its status changes, then its terminal event. + + A run paused by ``interrupt()`` (on an interrupt newer than + ``after_seq``) ends the poll with ``workflow_interrupted``. + """ async for event in self._poll_workflow( workflow_id, thread_id, @@ -953,6 +969,9 @@ async def _follow_run( # A poll that fails is reported as such (PollError) while the # run may still finish: ride out a restarting sidecar first. retry_failed_polls=True, + running_event=lambda state: interrupted_event( + parse_status(state.serialized_custom_status), workflow_id, after_seq + ), ): yield event @@ -1036,18 +1055,31 @@ async def astream( if subgraphs: raise NotImplementedError("subgraphs=True is not supported yet") modes, is_list = normalize_stream_mode(stream_mode) - # aclosing: if the caller stops early, close the inner stream now (it - # unregisters the sink) instead of whenever the garbage collector runs. - async with aclosing( - self._stream_events( + if isinstance(input, Command): + if input.resume is None or not workflow_id: + raise ValueError( + "astream(Command(resume=...)) resumes a run paused by " + "interrupt(): pass the run's workflow_id" + ) + events: Any = resume_run_events( + self, + workflow_id, + input.resume, + poll_interval=poll_interval, + keepalive=False, + ) + else: + events = self._stream_events( input, config=config, thread_id=thread_id, workflow_id=workflow_id, poll_interval=poll_interval, ) - ) as events: - async for item in events: + # aclosing: if the caller stops early, close the inner stream now (it + # unregisters the sink) instead of whenever the garbage collector runs. + async with aclosing(events) as stream: + async for item in stream: outs, error = route_astream_item(item, modes, is_list, on_control) for out in outs: yield out @@ -1182,7 +1214,11 @@ async def _release_pump( def _status_result(self, state: Any) -> Dict[str, Any]: """A completed run's result, or a failed workflow's error.""" - return completed_result(state) or super()._status_result(state) + return ( + completed_result(state) + or interrupted_result(state) + or super()._status_result(state) + ) def _is_root_state(self) -> bool: """Whether the graph's whole state is one ``__root__`` channel.""" @@ -1327,8 +1363,9 @@ async def _serve_stream( # type: ignore[override] ) def _add_routes(self, app: Any) -> None: - """``GET /agent/run/{workflow_id}/stream``: reconnect to a run's stream.""" + """Reconnect to a run's stream; resume a run paused by ``interrupt()``.""" add_reconnect_route(app, self) + add_resume_route(app, self) def _request_to_input( self, diff --git a/diagrid/agent/langgraph/stream_events.py b/diagrid/agent/langgraph/stream_events.py index 9e68721a..c5aaae2e 100644 --- a/diagrid/agent/langgraph/stream_events.py +++ b/diagrid/agent/langgraph/stream_events.py @@ -33,6 +33,7 @@ logger = logging.getLogger(__name__) FINAL_EVENTS = ( + "workflow_interrupted", "workflow_completed", "workflow_failed", "workflow_terminated", diff --git a/diagrid/agent/langgraph/stream_follow.py b/diagrid/agent/langgraph/stream_follow.py index 3567af46..b97878c1 100644 --- a/diagrid/agent/langgraph/stream_follow.py +++ b/diagrid/agent/langgraph/stream_follow.py @@ -36,6 +36,7 @@ ) from .activity_stream import STATUS_BRANCHES, STATUS_EXECUTED +from .interrupts import INTERRUPT_KEY, as_interrupts from .stream_events import encode_chunk, stream_failure_event from .streaming import BRANCHES_KEY, EXECUTED_KEY, SUPPORTED_MODES @@ -68,6 +69,8 @@ def decode_wire(mode: str, data: Any) -> Any: return data if mode == "messages" and isinstance(value, list) and len(value) == 2: return tuple(value) + if mode == "updates" and isinstance(value, dict) and INTERRUPT_KEY in value: + return {INTERRUPT_KEY: as_interrupts(value[INTERRUPT_KEY] or ())} return value @@ -127,6 +130,7 @@ def __init__( cursor: Optional[StreamCursor] = None, decode: Callable[[str, Any], Any] = decode_wire, seen: Optional[Set[Unit]] = None, + from_end: bool = False, ) -> None: self._reader = reader self._sink = sink @@ -141,6 +145,10 @@ def __init__( #: stream does not report them missing. self._seen = seen if seen is not None else set() self.purged = False + #: Start after what the log holds when the follower starts (a resumed run). + self._from_end = from_end + #: Set once the follower knows where it starts reading. + self.ready = asyncio.Event() self._final: "asyncio.Future[Dict[str, Any]]" = ( asyncio.get_running_loop().create_future() ) @@ -152,6 +160,14 @@ def finish(self, final: Dict[str, Any]) -> None: async def run(self) -> None: failures = 0 + if self._from_end: + try: + await self.skip_to_end() + except Exception as e: + self.ready.set() + self._sink.close(stream_failure_event(e, "StreamReadError", True)) + return + self.ready.set() while True: final = self._final.result() if self._final.done() else None try: @@ -181,6 +197,25 @@ async def run(self) -> None: except asyncio.TimeoutError: pass + async def skip_to_end(self) -> None: + """Take everything the log holds now as read: a stream of what comes next. + + A resumed run streams the rest of the run from here, so this is read + before the resume is sent. + """ + status = await asyncio.to_thread(self._status) + self._learn(units_of(status or {})) + wants = [UnitWant(step, unit, from_batch=1 << 30) for step, unit in self._order] + if not wants: + return + for chunk in await asyncio.to_thread(self._reader.read, wants): + state = self._units[(chunk.step, chunk.unit)] + state.attempt = chunk.attempt + state.from_batch = chunk.batches + state.consumed = state.total = chunk.total + state.done = chunk.done + self._seen.add((chunk.step, chunk.unit)) + async def _read_once(self, final: Optional[Dict[str, Any]]) -> None: if self.purged or self._cursor.at_end: return diff --git a/diagrid/agent/langgraph/stream_source.py b/diagrid/agent/langgraph/stream_source.py index 24437cec..a191b230 100644 --- a/diagrid/agent/langgraph/stream_source.py +++ b/diagrid/agent/langgraph/stream_source.py @@ -75,6 +75,7 @@ def open_source( status: Callable[[], Dict[str, Any]], seen: Set[Tuple[int, str]], cursor: Optional[StreamCursor] = None, + from_end: bool = False, ) -> StreamSource: """The source of a stream of ``workflow_id`` on ``transport``. @@ -91,6 +92,7 @@ def open_source( cursor=cursor, decode=transport.decode, seen=seen, + from_end=from_end, ) task = asyncio.create_task(follower.run()) return StreamSource(sink, follower.finish, follower=follower, task=task) diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index d220dd6d..05b682e0 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -362,6 +362,30 @@ def branch_finished(self) -> None: if self._branch: self._emit((), BRANCH_DONE, None) + def interrupted(self, interrupts: List[Dict[str, Any]]) -> None: + """Send LangGraph's ``{"__interrupt__": (Interrupt, ...)}`` updates chunk. + + Keyed apart from the node's own updates, so the task's run after the + resume is not taken for a late attempt of a finished one. + """ + from .interrupts import INTERRUPT_KEY, as_interrupts + + with self._emit_lock: + self._sink.put( + StreamEvent( + workflow_id=self._workflow_id, + step=self._step, + node=f"{self._sink_node}:{INTERRUPT_KEY}", + attempt_id=self._attempt_id, + seq=next(self._seq), + ns=(), + mode=UPDATES, + data={INTERRUPT_KEY: as_interrupts(interrupts)}, + display_node=self._node, + path=self._path, + ) + ) + def updates(self, writes: List[Tuple[str, Any]]) -> None: """Emit the node's ``(channel, value)`` writes as ``{node: update}``. @@ -444,6 +468,11 @@ def _plain_data(value: Any) -> Any: return value if isinstance(value, Serializable): return value + from langgraph.types import Interrupt + + if isinstance(value, Interrupt): + # what a client needs to answer it: the payload and the id to resume by + return {"value": _plain_data(value.value), "id": value.id} if isinstance(value, (list, tuple)): return [_plain_data(v) for v in value] if isinstance(value, dict): diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 7248199c..568f32b7 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -44,7 +44,7 @@ from langgraph.graph.message import add_messages from pydantic import BaseModel, TypeAdapter, ValidationError from langgraph.runtime import Runtime -from langgraph.errors import ParentCommand +from langgraph.errors import GraphInterrupt, ParentCommand from langgraph.types import Command, Overwrite, Send try: @@ -69,6 +69,12 @@ publish_run_status, transport_of, ) +from .interrupts import ( + interrupt_config, + interrupt_payloads, + settle_interrupts, + without_resume_writes, +) from .node_routes import route_in_node from .stream_values import state_values from .streaming import STREAM_RUN_KEY, NodeStreamer, StaticConfig @@ -538,6 +544,10 @@ class _Run: #: key]``, so a streaming consumer can tell which router's chunks never #: arrived. branches: List[List[Any]] = field(default_factory=list) + #: The interrupt the run waits on (``{"seq", "step", "interrupts"}``). + interrupt: Optional[Dict[str, Any]] = None + #: How many times the run was interrupted so far. + interrupt_seq: int = 0 @property def output_channels(self) -> Optional[List[str]]: @@ -694,6 +704,13 @@ def _run_step( ) publish_run_status(run) outputs = yield from _run_nodes(run, nodes, sends, step) + outputs = yield from settle_interrupts( + run, + outputs, + step, + lambda resumes: _rerun_nodes(run, nodes, sends, step, resumes), + publish_run_status, + ) failed = next((o for o in outputs if o.error), None) if failed: return [], [], f"Node '{failed.node_name}' failed: {failed.error}" @@ -859,6 +876,44 @@ def _state_for_task( return state +def _invocations( + nodes: List[str], sends: List[Dict[str, Any]] +) -> List[Tuple[str, Optional[Dict[str, Any]]]]: + """A step's tasks in order: its nodes, then its ``Send`` tasks.""" + return [ + *[(name, None) for name in nodes], + *[(t["node"], {"arg": t["arg"], "slot": slot}) for slot, t in enumerate(sends)], + ] + + +def _call_node( + run: _Run, + node_name: str, + send: Optional[Dict[str, Any]], + step: int, + resume: Optional[List[Any]] = None, +) -> Any: + """Schedule one task of ``step`` as its activity.""" + node_input = ExecuteNodeInput( + node_name=node_name, + channel_state=run.channel_state, + config=run.config, + thread_id=run.thread_id, + step=step, + send=send, + recursion_limit=run.recursion_limit, + routes=_node_routes(run, node_name) if run.route_in_node else None, + output_channels=run.output_channels, + resume=resume, + ) + activity: Any = execute_node_activity + if run.node_activities_by_name: + activity = node_activity_name(node_name) + return run.ctx.call_activity( + activity, input=node_input.to_dict(), retry_policy=run.retry_policy + ) + + def _run_nodes( run: _Run, nodes_to_execute: List[str], @@ -866,38 +921,34 @@ def _run_nodes( step: int, ) -> Generator[Any, Any, List[ExecuteNodeOutput]]: """Run the nodes and ``Send`` tasks of one step in parallel, each as an activity.""" - node_tasks = [] - invocations: List[Tuple[str, Optional[Dict[str, Any]]]] = [ - *[(name, None) for name in nodes_to_execute], - *[(t["node"], {"arg": t["arg"], "slot": slot}) for slot, t in enumerate(sends)], + node_tasks = [ + _call_node(run, name, send, step) + for name, send in _invocations(nodes_to_execute, sends) ] - for node_name, send in invocations: - node_input = ExecuteNodeInput( - node_name=node_name, - channel_state=run.channel_state, - config=run.config, - thread_id=run.thread_id, - step=step, - send=send, - recursion_limit=run.recursion_limit, - routes=_node_routes(run, node_name) if run.route_in_node else None, - output_channels=run.output_channels, - ) - activity: Any = execute_node_activity - if run.node_activities_by_name: - activity = node_activity_name(node_name) - node_tasks.append( - run.ctx.call_activity( - activity, - input=node_input.to_dict(), - retry_policy=run.retry_policy, - ) - ) - task_results = yield when_all(node_tasks) return [ExecuteNodeOutput.from_dict(result) for result in task_results] +def _rerun_nodes( + run: _Run, + nodes: List[str], + sends: List[Dict[str, Any]], + step: int, + resumes: Dict[int, List[Any]], +) -> Generator[Any, Any, Dict[int, ExecuteNodeOutput]]: + """Run the step's tasks at ``resumes``' positions again, with their resume values.""" + invocations = _invocations(nodes, sends) + positions = sorted(resumes) + node_tasks = [ + _call_node(run, *invocations[i], step, resume=resumes[i]) for i in positions + ] + task_results = yield when_all(node_tasks) + return { + i: ExecuteNodeOutput.from_dict(result) + for i, result in zip(positions, task_results) + } + + def _node_routes(run: _Run, node_name: str) -> Optional[List[Dict[str, Any]]]: """The conditional edges of ``node_name``, for its activity to evaluate.""" routes = [ @@ -1300,9 +1351,27 @@ def _runnable_config(call: _NodeCall) -> Dict[str, Any]: config[CONF][CONFIG_KEY_SEND] = call.pending_sends.extend except ImportError: pass + config[CONF].update(_interrupt_conf(call)) return config +def _interrupt_conf(call: _NodeCall) -> Dict[str, Any]: + """What ``interrupt()`` reads from the config: the task's scratchpad and name.""" + node_input = call.node_input + send = node_input.send + workflow_id = getattr(call.ctx, "workflow_id", "") + return interrupt_config( + namespace=( + f"{call.node_name}:{workflow_id}:{node_input.step or 0}:" + f"{'' if send is None else send['slot']}" + ), + step=node_input.step or 0, + stop=node_input.recursion_limit, + resume=node_input.resume, + send=call.pending_sends.extend, + ) + + def _invoke_runnable(runnable: Any, value: Any, config: Dict[str, Any]) -> Any: """Call a Runnable; one with an async entry returns a coroutine to await.""" if _has_async_entry(runnable): @@ -1329,7 +1398,7 @@ def _plain_node_config(call: _NodeCall) -> Dict[str, Any]: metadata of a streamed run) is supplied here. Without a streamer the runtime carries LangGraph's no-op writer. """ - return _node_config( + config = _node_config( {CONF: call.config.get(CONF)}, thread_id=call.node_input.thread_id, ctx=call.ctx, @@ -1337,6 +1406,8 @@ def _plain_node_config(call: _NodeCall) -> Dict[str, Any]: streamer=call.streamer, identity=_call_identity(call), ) + config[CONF].update(_interrupt_conf(call)) + return config def _run_node(call: _NodeCall) -> Any: @@ -1501,7 +1572,10 @@ def _node_output(call: _NodeCall, result: Any) -> Dict[str, Any]: sandbox tools), evaluates the node's conditional edges when the workflow asked for that, and then streams the node's update, as LangGraph does. """ - raw_writes = [*_result_to_raw_writes(result), *call.pending_sends] + raw_writes = [ + *_result_to_raw_writes(result), + *without_resume_writes(call.pending_sends), + ] writes = _serialize_writes(raw_writes) routed: Dict[str, Any] = {} if call.node_input.routes: @@ -1577,7 +1651,16 @@ def execute_node_activity( writer, ) # Under the LangSmith parent trace the runner opened, so LLM calls nest in it. - result = _run_with_stream_hooks(call, _langsmith_parent(config)) + try: + result = _run_with_stream_hooks(call, _langsmith_parent(config)) + except GraphInterrupt as paused: + # Not a failure: the task waits for a resume and runs again then. + interrupts = interrupt_payloads(paused) + if call.streamer: + call.streamer.interrupted(interrupts) + return ExecuteNodeOutput( + node_name=node_name, interrupts=interrupts + ).to_dict() output = _node_output(call, result) done = True return output From 2d277a04e2b8b6e369bcf1b5d79a49f9124ec326 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 14:48:52 +0100 Subject: [PATCH 41/73] test(langgraph): expect the README to document reconnecting, the stream transport and interrupts Signed-off-by: Casper Nielsen --- .../agent/langgraph/test_readme_streaming.py | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 tests/agent/langgraph/test_readme_streaming.py diff --git a/tests/agent/langgraph/test_readme_streaming.py b/tests/agent/langgraph/test_readme_streaming.py new file mode 100644 index 00000000..774ad4de --- /dev/null +++ b/tests/agent/langgraph/test_readme_streaming.py @@ -0,0 +1,67 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The streaming README says how to reconnect, which transport is used, and how to resume.""" + +import unittest +from pathlib import Path + +from diagrid.agent.langgraph import streaming + +README = Path(streaming.__file__).with_name("README.md") + + +class TestStreamingReadme(unittest.TestCase): + def setUp(self) -> None: + self.text = README.read_text() + self.flat = " ".join(self.text.split()) + + def _section(self, heading: str) -> str: + start = self.text.index(heading) + end = self.text.find("\n#", start + len(heading)) + return self.text[start : end if end != -1 else None] + + def test_reconnect_replaces_the_poll_limit(self): + self.assertNotIn("A dropped connection cannot be resumed", self.text) + section = " ".join(self._section("#### Reconnecting").split()) + for needed in ( + "GET /agent/run/{workflow_id}/stream", + "Last-Event-ID", + "last_event_id", + "astream_resume", + "404", + "transport_not_replayable", + ): + self.assertIn(needed, section, needed) + + def test_the_transport_choice_is_documented(self): + section = " ".join(self._section("#### Streaming across replicas").split()) + for needed in ( + "StateLogTransport", + "InProcessTransport", + "state store", + "stream_transport", + "write_failed", + ): + self.assertIn(needed, section, needed) + self.assertNotIn("Delivery across replicas is not implemented yet", self.text) + + def test_sse_ids_are_documented(self): + for needed in ("v1.start", "v1.end", "cursor"): + self.assertIn(needed, self.flat, needed) + + def test_interrupt_and_resume_are_documented(self): + section = " ".join(self._section("### Interrupts").split()) + for needed in ( + "interrupt(", + "Command(resume=", + "POST /agent/run/{workflow_id}/resume", + "workflow_interrupted", + "__interrupt__", + "409", + ): + self.assertIn(needed, section, needed) + + def test_the_proxy_wording_is_kept(self): + self.assertIn("#### Behind a proxy", self.text) + self.assertNotIn("behind a load balancer", self.text.lower()) From 6fde78e7eb73693de1ea1727c9ec298b20eb5737 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 14:50:54 +0100 Subject: [PATCH 42/73] docs(langgraph): document reconnecting, the stream transport, SSE ids and interrupts Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 6 +- diagrid/agent/langgraph/README.md | 144 ++++++++++++++++++++++---- diagrid/agent/langgraph/runner.py | 10 +- 3 files changed, 136 insertions(+), 24 deletions(-) diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 57e1210e..c5a0e57c 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -624,9 +624,9 @@ def serve( else) as server-sent events. The keys ``stream`` and ``stream_mode`` are reserved on such a request. The last event is ``workflow_completed`` or ``workflow_failed``; its data is - also what gets published to ``publish_topic``. Streaming works while the - node activities run in the serving process (single replica; see the - runner's README). A client that disconnects ends the stream but not the + also what gets published to ``publish_topic``. Which replicas a stream + reaches depends on the runner's stream transport (see the runner's + README). A client that disconnects ends the stream but not the workflow, which keeps running; with ``publish_topic`` set its result is still published when the run ends. diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index b0f1a0a1..50fd4a53 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -121,6 +121,7 @@ from diagrid.agent.langgraph import ( StreamControl, # what `on_control` receives StreamSinkRegistry, # the type of the `stream_registry` argument ) +from langgraph.types import Command # resumes a run paused by interrupt() ``` `astream` yields what `CompiledStateGraph.astream` yields, while each node runs @@ -222,7 +223,8 @@ no-cache` and `X-Accel-Buffering: no` so an nginx or ingress in front does not buffer the tokens. The chunks are serialized with `langchain_core.load.dumpd`, so `langchain_core.load.load` restores the messages in them. The stream ends with -`workflow_completed` or `workflow_failed`; both carry `workflow_id` and +`workflow_completed` or `workflow_failed` (or `workflow_interrupted`, see +[Interrupts](#interrupts)); both carry `workflow_id` and `thread_id`, a failure carries the error, and `dropped` is set when chunks were dropped. The run's result is also published to `publish_topic`; it is exactly what a non-streaming call returns and publishes for the same run, so a run that ends @@ -250,8 +252,89 @@ they are left alone. `status` is the workflow's runtime status, and once the run has completed the body also has the `output` and `steps` a plain `POST /agent/run` returns for it, `run_status` (`completed`, `error` or `max_steps_reached`) and `error` -when there is one. A workflow that failed carries its `error`. An unknown id is -a `404`. +when there is one. A workflow that failed carries its `error`; a run paused by +`interrupt()` has `interrupted: true` and its `interrupts` (see +[Interrupts](#interrupts)). An unknown id is a `404`. + +Every event carries an SSE `id`. With the state-store transport (see +[Streaming across replicas](#streaming-across-replicas)) the id is a cursor +into the run's event log that any replica can resume from: `v1.start` on +`workflow_started`, `v1.end` on the final event, and in between the position +after that chunk (a control event repeats the id of the chunk before it). With +the in-process transport the events are numbered from 1 on each connection. + +#### Reconnecting + +A client that lost its stream (a network drop, a proxy timeout, the serving +process restarting) reconnects with `GET /agent/run/{workflow_id}/stream`, +sending the last id it received as the `Last-Event-ID` header (a browser +`EventSource` does this by itself) or, when it cannot set headers, as the +`last_event_id` query parameter. Any replica answers it. The response is the +same SSE stream from that point on: `workflow_started`, then the chunks the +client has not seen, then the live ones, then the final event with the run's +result. Nothing is repeated and nothing is skipped. Without an id, or with one +that does not parse, the whole run is replayed; with `v1.end` only the final +event is sent. A run that already ended is replayed the same way, for as long +as its log is kept (an hour by default). `stream_mode` (repeat the parameter, +or separate modes with commas) picks the chunks as on `POST`; an unsupported +one is a `422`, and an unknown run a `404`. If a node was retried after the +client saw part of its output, the stream sends `node_reset` for it before the +new attempt's chunks. If the log has expired, the stream sends +`stream_purged` and then the final event. + +On the in-process transport nothing can be replayed: the endpoint answers with +`workflow_started`, then `stream_unavailable` with reason +`transport_not_replayable` (reconnecting needs a state store), then waits for +the run and sends the final event with its result. + +In Python, `runner.astream_resume(workflow_id, last_event_id=None, +stream_mode=...)` does the same and yields what `astream` yields. + +#### Streaming across replicas + +How chunks get from a node's activity to the stream is the runner's stream +transport (`DaprWorkflowGraphRunner(stream_transport=...)`). You normally do +not pick one: + +- **`StateLogTransport` (the default whenever the app has a state store).** + Every activity writes its chunks to an event log in a Dapr state store, in + small batches (every 100 ms, every 64 chunks, and when the node ends), and + the replica that serves a stream reads them back. So a stream carries every + node's chunks whichever replica ran it, a client can reconnect to any + replica, and a slow client lags instead of losing chunks. The runner uses + the app's `agent-memory` state store if it has one, else the state store the + workflows themselves use; every workflow app has that one, so on Catalyst + there is nothing to add: no component, no variable, no argument. Keys look + like `lgstream::::...` with `:` between path-escaped + parts, batches expire after an hour and their index after a day. Chunks + arrive about 150 to 250 ms later than in process, in small bursts. A failed + write is retried with the next batch and never fails a node; if a node's + chunks still never reach the log, the stream ends with `stream_unavailable` + whose `reason` is `write_failed`. A store that cannot be read ends the + stream with `workflow_failed` (`error_type` `StreamReadError`), never with an + empty stream. `StateLogStreamConfig` sets the store, key prefix, TTLs, batch + sizes and read interval: + + ```python + from diagrid.agent.core.workflow.stream_log import ( + StateLogStreamConfig, + StateLogTransport, + ) + + runner = DaprWorkflowGraphRunner( + graph=compiled, + name="my-graph", + stream_transport=StateLogTransport( + StateLogStreamConfig(store_name="statestore", event_ttl_s=600) + ), + ) + ``` + +- **`InProcessTransport` (no state store, or a `stream_registry` given).** + Chunks go straight from the activity to the stream through a queue in the + process. Only the nodes that run in the process serving the stream are + streamed (a single replica), nothing can be replayed, and a stream cannot be + resumed after a drop or a restart. #### Behind a proxy @@ -266,28 +349,53 @@ expect events to arrive one by one as the nodes produce them, comment lines after `workflow_completed` or `workflow_failed`. If tokens arrive all at once at the end of the run, something in front of the app is buffering. +### Interrupts + +A node can pause the run with LangGraph's `interrupt(value)`, as in a graph +with a checkpointer: the workflow is the checkpoint, so no checkpointer is +needed for this. + +- The stream sends LangGraph's `updates` chunk `{"__interrupt__": [...]}` (each + interrupt's `value` and `id`; `Interrupt` objects in `astream`) and ends with + the event `workflow_interrupted` (`workflow_id`, `thread_id`, `interrupts`). + `invoke` returns `{"__interrupt__": [Interrupt(...)]}`. +- The workflow waits durably for the answer: in its history, not in process + memory, so the app may restart or scale meanwhile. The other nodes of the + step keep their results. `GET /agent/run/{workflow_id}` shows + `interrupted: true` and the `interrupts` while it waits. +- Resume it with `POST /agent/run/{workflow_id}/resume` and the body + `{"resume": }` (add `"stream": true`, and `stream_mode` if you like, + for SSE; without it the response is the run's result, as a plain `POST` + returns it). In Python: `runner.astream(Command(resume=value), + workflow_id=...)`. The interrupted node runs again in the same run, on the + same thread, and `interrupt()` returns the value; a dict keyed by interrupt + ids answers several interrupts one by one. The stream of a resume carries + what happens after it (starting with `node_reset` for the node that runs + again) and ends with the final event, or with `workflow_interrupted` when a + node asks again. A body without `resume` is a `422`, an unknown run a `404`, + and a run that is not waiting a `409`. + ### Limits -- **Single replica.** Chunks travel from the activity to the HTTP connection - through an in-process queue. If an activity runs in another process (several - replicas of the app, or after a restart) its chunks are not delivered: the - activity logs a warning once per run and the stream sends `stream_unavailable` - before it ends. The run and its result are not affected. Delivery across - replicas is not implemented yet. -- **A dropped connection cannot be resumed.** If the connection drops (a - network failure, a proxy timeout, the app's process restarting), the events - sent while the client was away are lost and the stream cannot be reopened. - The run is not affected: Dapr keeps running it, on this process or after a - restart. The client polls `GET /agent/run/{workflow_id}`, with the id from - `workflow_started`, until the run is finished, and reads the result from - that response. +- **Single replica without a state store.** On the in-process transport chunks + travel from the activity to the HTTP connection through a queue in the + process. If an activity runs in another process (several replicas of the + app, or after a restart) its chunks are not delivered: the activity logs a + warning once per run and the stream sends `stream_unavailable` before it + ends. The run and its result are not affected. Give the app a state store to + stream across replicas and to reconnect (see + [Streaming across replicas](#streaming-across-replicas)). +- **A replay shows a node's last attempt.** When a node was retried, a client + that was connected saw the first attempt's chunks and then `node_reset`; a + replay from the start (or a reconnect from before the retry) has the attempt + that finished only. - **Node code must not count attempts in process memory.** A retried node may run in another process, so a counter kept in a module or a closure does not see the earlier attempt. Keep such state in the graph's state or a store. - **A disconnect does not cancel the run.** The stream closes but the Dapr workflow runs to completion; `terminate_workflow` stops it, and the ids in - `workflow_started` let a client that lost its connection `GET - /agent/run/{workflow_id}` or terminate the run. When `publish_topic` is set, + `workflow_started` let a client that lost its connection reconnect to its + stream, `GET /agent/run/{workflow_id}` or terminate the run. When `publish_topic` is set, the server keeps following the run after the client left and publishes its result when it ends. diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 03e69c0e..860a948b 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -1262,9 +1262,13 @@ def serve( ``POST /agent/run`` with ``"stream": true`` answers as server-sent events (``workflow_started``, the chunks ``stream_mode`` picks, then ``workflow_completed`` or ``workflow_failed``); the streaming README - has the details. Streaming works only on a single replica. A client that - disconnects ends the stream, not the workflow, and with ``publish_topic`` - set the result is still published when the run ends. + has the details. With a state store the stream carries every node + whichever replica ran it, and ``GET /agent/run/{workflow_id}/stream`` + reconnects to it (``Last-Event-ID``); without one, streaming works on a + single replica only. ``POST /agent/run/{workflow_id}/resume`` resumes a + run paused by ``interrupt()``. A client that disconnects ends the + stream, not the workflow, and with ``publish_topic`` set the result is + still published when the run ends. ``input_mapper`` maps the request dict to the graph's input. """ From 34697ee7e38077a55081119089c222bc43e41386 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 15:23:20 +0100 Subject: [PATCH 43/73] refactor(langgraph): move the node loop and Runnable call helpers out of workflow.py Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/runnable_call.py | 119 +++++++++++++++++++++++ diagrid/agent/langgraph/workflow.py | 116 ++-------------------- 2 files changed, 127 insertions(+), 108 deletions(-) create mode 100644 diagrid/agent/langgraph/runnable_call.py diff --git a/diagrid/agent/langgraph/runnable_call.py b/diagrid/agent/langgraph/runnable_call.py new file mode 100644 index 00000000..b0238edb --- /dev/null +++ b/diagrid/agent/langgraph/runnable_call.py @@ -0,0 +1,119 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Calling a node's Runnable or coroutine from a (synchronous) activity. + +Async nodes run on one process-wide event loop (see :class:`_BackgroundLoop`); +a Runnable with a real async entry point is called through ``ainvoke``. +""" + +import asyncio +import concurrent.futures +import functools +import threading +from typing import Any, Dict, Optional, Tuple + +from langchain_core.runnables.config import run_in_executor + + +def _has_async_entry(runnable: Any) -> bool: + """Whether ``runnable`` has a real async entry point, which a node should use. + + ``ToolNode`` has a sync ``func`` and an ``afunc``; its sync one cannot run + an ``async def`` tool (MCP adapter tools are such), its async one runs both, + A plain sync node also gets an ``afunc``, but + only a ``run_in_executor`` wrapper around its function: that is not one. + + A composite (a compiled subgraph, a ``RunnableSequence``) has no function of + its own and no ``afunc``, but a step inside it may be an ``async def`` with + no sync entry, so it goes through ``ainvoke`` too: that runs a sync step in + an executor. + """ + afunc = getattr(runnable, "afunc", None) + if afunc is None: + return not hasattr(runnable, "func") and hasattr(runnable, "ainvoke") + return not (isinstance(afunc, functools.partial) and afunc.func is run_in_executor) + + +class _BackgroundLoop: + """One event loop per process, in a daemon thread, that async nodes run on. + + An async client a node keeps (a chat model's HTTP connection pool) is bound + to the loop it was first used on. A loop made and closed for each activity + would break that client for the next activity, so every coroutine runs on + this one, which is never closed. + + ``asyncio`` re-raises ``SystemExit`` and ``KeyboardInterrupt`` out of + ``run_forever``, which would end the loop's thread and leave every waiting + and later async node hanging. A node's own coroutine is guarded so those + fail that node alone, and a loop whose thread has died anyway is replaced. + """ + + #: Seconds between looks at whether the loop's thread is still alive. + _CHECK_SECONDS = 1.0 + + def __init__(self) -> None: + self._lock = threading.Lock() + self._loop: Optional[asyncio.AbstractEventLoop] = None + self._thread: Optional[threading.Thread] = None + + def _running_loop(self) -> Tuple[asyncio.AbstractEventLoop, threading.Thread]: + with self._lock: + alive = self._thread is not None and self._thread.is_alive() + if self._loop is None or self._loop.is_closed() or not alive: + loop = asyncio.new_event_loop() + thread = threading.Thread( + target=loop.run_forever, name="langgraph-node-loop", daemon=True + ) + thread.start() + self._loop, self._thread = loop, thread + assert self._loop is not None and self._thread is not None + return self._loop, self._thread + + @staticmethod + async def _guarded(coro: Any) -> Any: + """``coro``, with an exit request turned into an error of the node.""" + try: + return await coro + except (SystemExit, KeyboardInterrupt) as e: + raise RuntimeError( + f"The node raised {type(e).__name__}({', '.join(map(repr, e.args))}); " + "it fails the node, not the process" + ) from e + + def run(self, coro: Any) -> Any: + """Run ``coro`` to completion on the loop and return its result. + + ``run_coroutine_threadsafe`` starts the task in a copy of the calling + thread's context, so the ambient config ``set_config_context`` set for + the node is what the coroutine sees. + """ + loop, thread = self._running_loop() + future = asyncio.run_coroutine_threadsafe(self._guarded(coro), loop) + while True: + concurrent.futures.wait([future], timeout=self._CHECK_SECONDS) + if future.done(): + return future.result() + if not thread.is_alive(): + future.cancel() + raise RuntimeError( + "The event loop async nodes run on stopped while this node " + "was running (something ended it, as SystemExit does)" + ) + + +_background_loop = _BackgroundLoop() + + +def _await_if_coroutine(r: Any) -> Any: + """Run ``r`` to completion on the process's node loop if it is a coroutine.""" + if asyncio.iscoroutine(r): + return _background_loop.run(r) + return r + + +def _invoke_runnable(runnable: Any, value: Any, config: Dict[str, Any]) -> Any: + """Call a Runnable; one with an async entry returns a coroutine to await.""" + if _has_async_entry(runnable): + return runnable.ainvoke(value, config=config) + return runnable.invoke(value, config=config) diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 568f32b7..8dd794fb 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -3,9 +3,7 @@ """Dapr Workflow definitions for durable LangGraph execution.""" -import asyncio import base64 -import concurrent.futures import contextlib import copy import dataclasses @@ -40,7 +38,7 @@ convert_to_messages, message_chunk_to_message, ) -from langchain_core.runnables.config import run_in_executor, set_config_context +from langchain_core.runnables.config import set_config_context from langgraph.graph.message import add_messages from pydantic import BaseModel, TypeAdapter, ValidationError from langgraph.runtime import Runtime @@ -76,6 +74,13 @@ without_resume_writes, ) from .node_routes import route_in_node +from .runnable_call import ( # noqa: F401 (re-exported) + _BackgroundLoop, + _await_if_coroutine, + _background_loop, + _has_async_entry, + _invoke_runnable, +) from .stream_values import state_values from .streaming import STREAM_RUN_KEY, NodeStreamer, StaticConfig from .task_identity import TaskIdentity @@ -393,8 +398,6 @@ def _close_langsmith_parent_trace_async(config: Optional[Dict[str, Any]]) -> Non if not run_id: return - import threading - def _do_close() -> None: try: import os @@ -1097,25 +1100,6 @@ def _build_node_runtime( return Runtime(**extra) -def _has_async_entry(runnable: Any) -> bool: - """Whether ``runnable`` has a real async entry point, which a node should use. - - ``ToolNode`` has a sync ``func`` and an ``afunc``; its sync one cannot run - an ``async def`` tool (MCP adapter tools are such), its async one runs both, - A plain sync node also gets an ``afunc``, but - only a ``run_in_executor`` wrapper around its function: that is not one. - - A composite (a compiled subgraph, a ``RunnableSequence``) has no function of - its own and no ``afunc``, but a step inside it may be an ``async def`` with - no sync entry, so it goes through ``ainvoke`` too: that runs a sync step in - an executor. - """ - afunc = getattr(runnable, "afunc", None) - if afunc is None: - return not hasattr(runnable, "func") and hasattr(runnable, "ainvoke") - return not (isinstance(afunc, functools.partial) and afunc.func is run_in_executor) - - @dataclass class _NodeCall: """Everything one execution of a node needs, gathered by the activity.""" @@ -1187,83 +1171,6 @@ def _read_activity_channels( return {k: source.get(k) for k in select if k in source} -class _BackgroundLoop: - """One event loop per process, in a daemon thread, that async nodes run on. - - An async client a node keeps (a chat model's HTTP connection pool) is bound - to the loop it was first used on. A loop made and closed for each activity - would break that client for the next activity, so every coroutine runs on - this one, which is never closed. - - ``asyncio`` re-raises ``SystemExit`` and ``KeyboardInterrupt`` out of - ``run_forever``, which would end the loop's thread and leave every waiting - and later async node hanging. A node's own coroutine is guarded so those - fail that node alone, and a loop whose thread has died anyway is replaced. - """ - - #: Seconds between looks at whether the loop's thread is still alive. - _CHECK_SECONDS = 1.0 - - def __init__(self) -> None: - self._lock = threading.Lock() - self._loop: Optional[asyncio.AbstractEventLoop] = None - self._thread: Optional[threading.Thread] = None - - def _running_loop(self) -> Tuple[asyncio.AbstractEventLoop, threading.Thread]: - with self._lock: - alive = self._thread is not None and self._thread.is_alive() - if self._loop is None or self._loop.is_closed() or not alive: - loop = asyncio.new_event_loop() - thread = threading.Thread( - target=loop.run_forever, name="langgraph-node-loop", daemon=True - ) - thread.start() - self._loop, self._thread = loop, thread - assert self._loop is not None and self._thread is not None - return self._loop, self._thread - - @staticmethod - async def _guarded(coro: Any) -> Any: - """``coro``, with an exit request turned into an error of the node.""" - try: - return await coro - except (SystemExit, KeyboardInterrupt) as e: - raise RuntimeError( - f"The node raised {type(e).__name__}({', '.join(map(repr, e.args))}); " - "it fails the node, not the process" - ) from e - - def run(self, coro: Any) -> Any: - """Run ``coro`` to completion on the loop and return its result. - - ``run_coroutine_threadsafe`` starts the task in a copy of the calling - thread's context, so the ambient config ``set_config_context`` set for - the node is what the coroutine sees. - """ - loop, thread = self._running_loop() - future = asyncio.run_coroutine_threadsafe(self._guarded(coro), loop) - while True: - concurrent.futures.wait([future], timeout=self._CHECK_SECONDS) - if future.done(): - return future.result() - if not thread.is_alive(): - future.cancel() - raise RuntimeError( - "The event loop async nodes run on stopped while this node " - "was running (something ended it, as SystemExit does)" - ) - - -_background_loop = _BackgroundLoop() - - -def _await_if_coroutine(r: Any) -> Any: - """Run ``r`` to completion on the process's node loop if it is a coroutine.""" - if asyncio.iscoroutine(r): - return _background_loop.run(r) - return r - - def _is_runnable(obj: Any) -> bool: """Whether ``obj`` is a LangChain Runnable, whose ``invoke`` injects config.""" return hasattr(obj, "invoke") and callable(getattr(obj, "invoke")) @@ -1372,13 +1279,6 @@ def _interrupt_conf(call: _NodeCall) -> Dict[str, Any]: ) -def _invoke_runnable(runnable: Any, value: Any, config: Dict[str, Any]) -> Any: - """Call a Runnable; one with an async entry returns a coroutine to await.""" - if _has_async_entry(runnable): - return runnable.ainvoke(value, config=config) - return runnable.invoke(value, config=config) - - def _call_plain(call: _NodeCall) -> Any: """Call a plain function node (sync or async) and return its result.""" sig = inspect.signature(call.node_func) From 58eb55704595563eaff7aa3b5ff4bd0f28273309 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 15:27:20 +0100 Subject: [PATCH 44/73] fix(langgraph): pause on interrupt() in a subgraph or a router instead of completing A compiled subgraph run as a node (or whose result a node returns) ends with __interrupt__ instead of raising; that is now the task's interrupt, and on the re-run the subgraph gets its resume value through the task's scratchpad. A node that drops a paused subgraph's result fails with a clear error. A router that calls interrupt() inside its node's activity pauses the task as LangGraph does; one run in its own activity reports that it cannot. The LangGraph internals the scratchpad needs are imported behind an error naming the supported langgraph range. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/interrupts.py | 163 +++++++++++++++--- diagrid/agent/langgraph/node_routes.py | 10 +- diagrid/agent/langgraph/workflow.py | 30 +++- .../agent/langgraph/test_interrupt_imports.py | 29 ++++ .../agent/langgraph/test_interrupt_nested.py | 137 +++++++++++++++ 5 files changed, 337 insertions(+), 32 deletions(-) create mode 100644 tests/agent/langgraph/test_interrupt_imports.py create mode 100644 tests/agent/langgraph/test_interrupt_nested.py diff --git a/diagrid/agent/langgraph/interrupts.py b/diagrid/agent/langgraph/interrupts.py index e0934a60..28f77c58 100644 --- a/diagrid/agent/langgraph/interrupts.py +++ b/diagrid/agent/langgraph/interrupts.py @@ -19,14 +19,27 @@ the same step with the resume values (``interrupt`` returns them in order), then goes on as if the step had just finished. A task that interrupts again waits for the next resume. + +An ``interrupt()`` below the node pauses the task too: in a subgraph the node +runs (its ``__interrupt__`` result is the task's interrupt, and on the re-run +the subgraph gets its resume value through the task's scratchpad) and in the +node's router (it shares the task's scratchpad). + +The scratchpad is a LangGraph internal, supported for langgraph +:data:`SUPPORTED_LANGGRAPH`. """ import itertools import json +import threading +from types import SimpleNamespace from typing import Any, Callable, Dict, Generator, List, Optional, Sequence, Tuple from .models import ExecuteNodeOutput +#: The langgraph versions whose internals ``interrupt()`` support is built on. +SUPPORTED_LANGGRAPH = ">=1.2.14,<2" + #: The external event a resume raises on the workflow. RESUME_EVENT = "resume" #: Custom status: the pending interrupt, and the number of the last one. @@ -43,9 +56,69 @@ def _plain(value: Any) -> Any: return json.loads(json.dumps(value, default=str)) -def _no_null_resume(consume: bool = False) -> Any: - """No resume value without a task: every resume here names its tasks.""" - return None +def _internals() -> Any: + """The LangGraph internals ``interrupt()`` support reads, or a clear error.""" + try: + from langgraph._internal._constants import ( + CONFIG_KEY_CHECKPOINT_NS, + CONFIG_KEY_SCRATCHPAD, + CONFIG_KEY_SEND, + RESUME, + ) + from langgraph._internal._scratchpad import PregelScratchpad + except ImportError as e: + raise ImportError( + "interrupt() on the Dapr workflow runner needs langgraph " + f"{SUPPORTED_LANGGRAPH}: this langgraph does not have the internals " + f"it uses ({e})" + ) from e + return SimpleNamespace( + CHECKPOINT_NS=CONFIG_KEY_CHECKPOINT_NS, + SCRATCHPAD=CONFIG_KEY_SCRATCHPAD, + SEND=CONFIG_KEY_SEND, + RESUME=RESUME, + PregelScratchpad=PregelScratchpad, + ) + + +class TaskResumes: + """The resume values of one task's interrupts, handed out in the order asked. + + The task's own ``interrupt()`` calls and those of a subgraph it runs (which + ask the task's scratchpad for a resume value when they have none) share + one order: the order the interrupts happened in on the run that paused. + ``nested_missed`` is set when a subgraph asked and none was left: it + paused, and its interrupt must not be lost. + """ + + def __init__(self, values: Optional[Sequence[Any]] = None) -> None: + self._values = tuple(values or ()) + self._next = 0 + self._lock = threading.Lock() + self.nested_missed = False + + @property + def values(self) -> List[Any]: + return list(self._values) + + def next_index(self) -> int: + """The position of the task's next own ``interrupt()`` call.""" + with self._lock: + index = self._next + self._next += 1 + return index + + def null_resume(self, consume: bool = False) -> Any: + """The next resume value, for an interrupt that has none of its own.""" + with self._lock: + if self._next < len(self._values): + value = self._values[self._next] + if consume: + self._next += 1 + return value + if consume: + self.nested_missed = True + return None def interrupt_config( @@ -55,45 +128,85 @@ def interrupt_config( stop: Optional[int], resume: Optional[List[Any]], send: Callable[[Sequence[Tuple[str, Any]]], None], + resumes: Optional[TaskResumes] = None, ) -> Dict[str, Any]: """The ``configurable`` keys ``langgraph.types.interrupt`` reads. ``namespace`` names the task, so an interrupt's id is the same on every - run of it; ``resume`` holds the values the task's interrupts get, in order. + run of it; ``resume`` holds the values the task's interrupts get, in order + (``resumes`` instead shares them with another scratchpad of the task). """ - from langgraph._internal._constants import ( - CONFIG_KEY_CHECKPOINT_NS, - CONFIG_KEY_SCRATCHPAD, - CONFIG_KEY_SEND, - ) - from langgraph._internal._scratchpad import PregelScratchpad - - calls, interrupts, subgraphs = ( - itertools.count(), - itertools.count(), - itertools.count(), - ) - scratchpad = PregelScratchpad( + lg = _internals() + task = resumes if resumes is not None else TaskResumes(resume) + calls, subgraphs = itertools.count(), itertools.count() + scratchpad = lg.PregelScratchpad( step=step, stop=stop or 0, call_counter=lambda: next(calls), - interrupt_counter=lambda: next(interrupts), - get_null_resume=_no_null_resume, - resume=list(resume or []), + interrupt_counter=task.next_index, + get_null_resume=task.null_resume, + resume=task.values, subgraph_counter=lambda: next(subgraphs), ) return { - CONFIG_KEY_SCRATCHPAD: scratchpad, - CONFIG_KEY_CHECKPOINT_NS: namespace, - CONFIG_KEY_SEND: send, + lg.SCRATCHPAD: scratchpad, + lg.CHECKPOINT_NS: namespace, + lg.SEND: send, } def without_resume_writes(writes: List[Tuple[str, Any]]) -> List[Tuple[str, Any]]: """``writes`` minus the bookkeeping ``interrupt()`` records for Pregel.""" - from langgraph._internal._constants import RESUME + resume = _internals().RESUME + return [w for w in writes if w[0] != resume] + + +#: A router run in its own activity (not its node's) cannot pause the run. +ROUTER_INTERRUPT_ERROR = ( + "interrupt() in a router pauses the run only when the router runs in its " + "node's activity, as it does in runs started on this version; this one ran " + "on its own (a run started on an older version, or a router that raised " + "in its node's activity)" +) + + +def router_interrupt_conf(cond_input: Any) -> Dict[str, Any]: + """The scratchpad of a router run in its own activity: it can only report.""" + return interrupt_config( + namespace=f"{cond_input.source_node}:router:{cond_input.condition_name}", + step=cond_input.step or 0, + stop=cond_input.recursion_limit, + resume=None, + send=lambda writes: None, + ) + - return [w for w in writes if w[0] != RESUME] +class DroppedInterrupt(RuntimeError): + """A subgraph the node ran paused, and the node returned without its interrupt.""" + + +def nested_interrupts(result: Any, resumes: TaskResumes, node_name: str) -> Any: + """``result`` of a node that returned, unless a subgraph in it paused. + + A compiled subgraph run as the node (or called by it, its result returned) + ends with ``{"__interrupt__": [...]}`` instead of raising: that is the + task's interrupt, raised here as LangGraph's parent task would. A subgraph + that paused while the node dropped its result raises + :class:`DroppedInterrupt`: the run must not go on as if it had not. + """ + from langgraph.errors import GraphInterrupt + + found = result.get(INTERRUPT_KEY) if isinstance(result, dict) else None + if found: + raise GraphInterrupt(tuple(found)) + if resumes.nested_missed: + raise DroppedInterrupt( + f"A subgraph called by node '{node_name}' paused on interrupt(), " + "but the node did not return the subgraph's result, so the pause " + "would be lost. Return the subgraph's result from the node (or add " + "the compiled subgraph as the node itself)." + ) + return result def interrupt_payloads(error: BaseException) -> List[Dict[str, Any]]: diff --git a/diagrid/agent/langgraph/node_routes.py b/diagrid/agent/langgraph/node_routes.py index d5467fb8..9c1dfe2a 100644 --- a/diagrid/agent/langgraph/node_routes.py +++ b/diagrid/agent/langgraph/node_routes.py @@ -88,13 +88,17 @@ def route_in_node( node_input: ExecuteNodeInput, writes: List[NodeWrite], sink: Optional[StreamSink], + interrupt_conf: Optional[Dict[str, Any]] = None, ) -> RouteOutcome: """Evaluate the node's conditional edges on the state with ``writes`` applied. The routers stream as they do in the condition activity: as the source node, keyed by edge and task, so a later fallback attempt of one reads as - that router's retry, not the node's. + that router's retry, not the node's. ``interrupt_conf`` is the task's + ``interrupt()`` scratchpad: a router that interrupts pauses the task. """ + from langgraph.errors import GraphInterrupt + from .workflow import ReducerError, evaluate_condition try: @@ -107,7 +111,9 @@ def route_in_node( for route in node_input.routes or []: cond_input = _route_input(node_input, route, state) try: - output = evaluate_condition(ctx, cond_input, sink) + output = evaluate_condition(ctx, cond_input, sink, interrupt_conf) + except GraphInterrupt: + raise except Exception: logger.warning( "Router %r of node %r raised inside the node's activity; the " diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 8dd794fb..44d6c2c1 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -68,8 +68,13 @@ transport_of, ) from .interrupts import ( + ROUTER_INTERRUPT_ERROR, + DroppedInterrupt, + TaskResumes, interrupt_config, interrupt_payloads, + nested_interrupts, + router_interrupt_conf, settle_interrupts, without_resume_writes, ) @@ -1114,6 +1119,8 @@ class _NodeCall: pending_sends: list #: Where the node's routers write their chunks, in a streamed run. sink: Optional[StreamSink] = None + #: The task's resume values, shared by the node, its subgraphs and routers. + resumes: TaskResumes = field(default_factory=TaskResumes) @property def node_name(self) -> str: @@ -1276,6 +1283,7 @@ def _interrupt_conf(call: _NodeCall) -> Dict[str, Any]: stop=node_input.recursion_limit, resume=node_input.resume, send=call.pending_sends.extend, + resumes=call.resumes, ) @@ -1336,9 +1344,10 @@ def run() -> Any: # get_stream_writer() must find a (no-op) writer when the run is not streamed. with set_config_context(ambient) as ctx_: # type: ignore[arg-type] try: - return ctx_.run(run) + result = ctx_.run(run) except ParentCommand as exc: return _parent_command_result(exc, call.node_name) + return nested_interrupts(result, call.resumes, call.node_name) def _parent_command_result(exc: ParentCommand, node_name: str) -> Command: @@ -1480,7 +1489,7 @@ def _node_output(call: _NodeCall, result: Any) -> Dict[str, Any]: routed: Dict[str, Any] = {} if call.node_input.routes: routed = route_in_node( - call.ctx, call.node_input, writes, call.sink + call.ctx, call.node_input, writes, call.sink, _interrupt_conf(call) ).output_fields() if call.streamer: call.streamer.updates(raw_writes) @@ -1542,6 +1551,7 @@ def execute_node_activity( streamer=_make_streamer(ctx, node_input, config, writer), pending_sends=[], sink=writer, + resumes=TaskResumes(node_input.resume), ) _send_values( ctx, @@ -1553,6 +1563,7 @@ def execute_node_activity( # Under the LangSmith parent trace the runner opened, so LLM calls nest in it. try: result = _run_with_stream_hooks(call, _langsmith_parent(config)) + output = _node_output(call, result) except GraphInterrupt as paused: # Not a failure: the task waits for a resume and runs again then. interrupts = interrupt_payloads(paused) @@ -1561,7 +1572,8 @@ def execute_node_activity( return ExecuteNodeOutput( node_name=node_name, interrupts=interrupts ).to_dict() - output = _node_output(call, result) + except DroppedInterrupt as e: # retrying would drop it again + return ExecuteNodeOutput(node_name=node_name, error=str(e)).to_dict() done = True return output finally: @@ -1634,6 +1646,7 @@ def _call_condition( cond_func: Callable, state: Any, sink: Optional[StreamSink], + interrupt_conf: Optional[Dict[str, Any]] = None, ) -> Any: """Call a conditional edge's function and return what it routed to. @@ -1668,6 +1681,7 @@ def _call_condition( ctx, cond_input.source_node, cond_input.step or 0, cond_input.send_slot ), ) + config[CONF].update(interrupt_conf or router_interrupt_conf(cond_input)) def run() -> Any: # A LangChain Runnable (e.g. RunnableCallable from Deep Agents @@ -1714,7 +1728,10 @@ def evaluate_condition_activity( 0, writer, ) - output = evaluate_condition(ctx, cond_input, writer).to_dict() + try: + output = evaluate_condition(ctx, cond_input, writer).to_dict() + except GraphInterrupt: + output = EvaluateConditionOutput(error=ROUTER_INTERRUPT_ERROR).to_dict() done = True return output finally: @@ -1726,6 +1743,7 @@ def evaluate_condition( ctx: WorkflowActivityContext, cond_input: EvaluateConditionInput, sink: Optional[StreamSink], + interrupt_conf: Optional[Dict[str, Any]] = None, ) -> EvaluateConditionOutput: """Call a conditional edge's function and say where it routes, or the error. @@ -1751,7 +1769,9 @@ def evaluate_condition( # add_conditional_edges path is one) traces itself, so without a parent # each evaluation lands in LangSmith as a separate top-level trace. with _under_parent_trace(cond_input.config): - result = _call_condition(ctx, cond_input, cond_func, state, sink) + result = _call_condition( + ctx, cond_input, cond_func, state, sink, interrupt_conf + ) return _route(cond_input, result) diff --git a/tests/agent/langgraph/test_interrupt_imports.py b/tests/agent/langgraph/test_interrupt_imports.py new file mode 100644 index 00000000..3029b567 --- /dev/null +++ b/tests/agent/langgraph/test_interrupt_imports.py @@ -0,0 +1,29 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``interrupt()`` support reads LangGraph internals: a langgraph without them is named.""" + +import builtins +import unittest +from typing import Any +from unittest import mock + +from diagrid.agent.langgraph.interrupts import interrupt_config + + +class TestInternalImports(unittest.TestCase): + def test_a_langgraph_without_the_internals_gets_a_clear_error(self): + real = builtins.__import__ + + def fake(name: str, *args: Any, **kwargs: Any) -> Any: + if name.startswith("langgraph._internal"): + raise ImportError(f"No module named {name!r}") + return real(name, *args, **kwargs) + + with mock.patch("builtins.__import__", side_effect=fake): + with self.assertRaises(ImportError) as caught: + interrupt_config( + namespace="n", step=0, stop=None, resume=None, send=lambda w: None + ) + self.assertIn("langgraph", str(caught.exception)) + self.assertIn("1.2", str(caught.exception)) diff --git a/tests/agent/langgraph/test_interrupt_nested.py b/tests/agent/langgraph/test_interrupt_nested.py new file mode 100644 index 00000000..b7672d79 --- /dev/null +++ b/tests/agent/langgraph/test_interrupt_nested.py @@ -0,0 +1,137 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``interrupt()`` below a node: in a subgraph the node runs, and in its router. + +LangGraph pauses the node's task for both, and a resume runs the task again. +The workflow must pause and resume the same way, never complete as if the +interrupt had not happened. +""" + +import operator +from typing import Any + +from fastapi.testclient import TestClient +from langgraph.graph import END, START, StateGraph +from langgraph.types import interrupt +from typing_extensions import Annotated, TypedDict + +from .log_helpers import log_runner +from .streaming_helpers import serve_app +from .test_reconnect_helpers import frames +from .test_runner import _RunnerTestCase + + +class _S(TypedDict, total=False): + log: Annotated[list, operator.add] + choice: str + + +def _inner() -> Any: + def inner(s: _S) -> dict: + return {"log": [f"inner:{interrupt('inner?')}"]} + + sub = StateGraph(_S) + sub.add_node("inner", inner) + sub.add_edge(START, "inner") + sub.add_edge("inner", END) + return sub.compile() + + +def _subgraph_node_graph() -> Any: + g = StateGraph(_S) + g.add_node("sub", _inner()) + g.add_edge(START, "sub") + g.add_edge("sub", END) + return g.compile() + + +def _calls_subgraph_graph(keep_result: bool) -> Any: + sub = _inner() + + def call(s: _S) -> dict: + out = sub.invoke({"log": []}) + if keep_result: + return out + return {"log": ["ignored the subgraph"]} + + g = StateGraph(_S) + g.add_node("call", call) + g.add_edge(START, "call") + g.add_edge("call", END) + return g.compile() + + +def _router_graph() -> Any: + def pick(s: _S) -> dict: + return {"log": ["pick"]} + + def route(s: _S) -> str: + return "yes" if interrupt("which way?") == "yes" else "no" + + def yes(s: _S) -> dict: + return {"log": ["yes"]} + + def no(s: _S) -> dict: + return {"log": ["no"]} + + g = StateGraph(_S) + g.add_node("pick", pick) + g.add_node("yes", yes) + g.add_node("no", no) + g.add_edge(START, "pick") + g.add_conditional_edges("pick", route, ["yes", "no"]) + g.add_edge("yes", END) + g.add_edge("no", END) + return g.compile() + + +def _run(graph: Any, name: str) -> Any: + runner = log_runner(graph, name) + http = TestClient(serve_app(runner)) + got = frames(http.post("/agent/run", json={"log": ["s"], "stream": True}).text) + return runner, http, got + + +def _resume(http: Any, wf: str, value: Any) -> Any: + return frames( + http.post( + f"/agent/run/{wf}/resume", json={"resume": value, "stream": True} + ).text + ) + + +class TestSubgraphInterrupt(_RunnerTestCase): + def test_a_subgraph_node_pauses_the_run_and_resumes(self): + _, http, got = _run(_subgraph_node_graph(), "nest-sub") + self.assertEqual(got[-1][1], "workflow_interrupted") + self.assertEqual(got[-1][2]["interrupts"][0]["value"], "inner?") + self.assertEqual(got[-1][2]["interrupts"][0]["node"], "sub") + rest = _resume(http, got[-1][2]["workflow_id"], "ok") + self.assertEqual(rest[-1][1], "workflow_completed") + # as native: the subgraph's whole state is the node's update + self.assertEqual(rest[-1][2]["output"]["log"], ["s", "s", "inner:ok"]) + + def test_a_node_that_returns_a_subgraph_result_pauses_too(self): + _, http, got = _run(_calls_subgraph_graph(keep_result=True), "nest-call") + self.assertEqual(got[-1][1], "workflow_interrupted") + rest = _resume(http, got[-1][2]["workflow_id"], "ok") + self.assertEqual(rest[-1][1], "workflow_completed") + self.assertEqual(rest[-1][2]["output"]["log"], ["s", "inner:ok"]) + + def test_a_node_that_drops_a_subgraph_interrupt_fails_loudly(self): + _, _, got = _run(_calls_subgraph_graph(keep_result=False), "nest-drop") + self.assertEqual(got[-1][1], "workflow_failed") + message = got[-1][2]["error"]["message"] + self.assertIn("paused on interrupt()", message) + self.assertIn("'call'", message) + + +class TestRouterInterrupt(_RunnerTestCase): + def test_a_router_that_interrupts_pauses_and_resumes(self): + _, http, got = _run(_router_graph(), "nest-route") + self.assertEqual(got[-1][1], "workflow_interrupted") + self.assertEqual(got[-1][2]["interrupts"][0]["value"], "which way?") + rest = _resume(http, got[-1][2]["workflow_id"], "yes") + self.assertEqual(rest[-1][1], "workflow_completed") + self.assertEqual(rest[-1][2]["output"]["log"], ["s", "pick", "yes"]) From fcd391851e07406059c6e03e49d7849368619417 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 15:27:20 +0100 Subject: [PATCH 45/73] fix(langgraph): resume a paused run with invoke(Command(resume=...)) invoke() raised AttributeError for a Command. It now resumes the run named by workflow_id and waits for it, and refuses any other Command, or one without a paused run, with a ValueError. The polling loop moves out of runner.py. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/invoke_result.py | 141 ++++++++++++++++++++ diagrid/agent/langgraph/runner.py | 88 +++--------- tests/agent/langgraph/test_invoke_resume.py | 35 +++++ 3 files changed, 193 insertions(+), 71 deletions(-) create mode 100644 diagrid/agent/langgraph/invoke_result.py create mode 100644 tests/agent/langgraph/test_invoke_resume.py diff --git a/diagrid/agent/langgraph/invoke_result.py b/diagrid/agent/langgraph/invoke_result.py new file mode 100644 index 00000000..cd2c3997 --- /dev/null +++ b/diagrid/agent/langgraph/invoke_result.py @@ -0,0 +1,141 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""What ``runner.invoke`` returns: the run's output, its interrupts, or an error. + +``invoke(input)`` schedules a run and waits for it here; ``invoke( +Command(resume=...), workflow_id=...)`` resumes a run paused by +``interrupt()`` and waits for it the same way, as LangGraph's ``invoke`` with +a ``Command`` continues the thread. +""" + +import json +import time +from typing import Any, Callable, Optional + +from dapr.ext.workflow import WorkflowStatus + +from .activity_stream import parse_status +from .interrupts import INTERRUPT_KEY, RESUME_EVENT, as_interrupts +from .interrupts import interrupted_event, pending_interrupt +from .models import GraphWorkflowOutput +from .streaming import FAILED_STATUSES, normalize_final, run_error + +#: The workflow output key of a graph whose whole state is one value. +_ROOT = "__root__" + + +def _completed_output(state: Any, runner: Any, workflow_id: str, thread_id: str) -> Any: + """The output of a completed run; a run that failed in the graph raises.""" + if not state.serialized_output: + return {} + raw = state.serialized_output + output = GraphWorkflowOutput.from_dict( + json.loads(raw) if isinstance(raw, str) else raw + ) + if output.status in FAILED_STATUSES: + # Not a result: a run that hit its step limit or failed in a node raises. + raise run_error( + normalize_final( + { + "type": "workflow_completed", + "status": output.status, + "error": output.error, + "output": output.output, + }, + workflow_id=workflow_id, + thread_id=thread_id, + ) + ) + if runner._is_root_state() and _ROOT in output.output: + return output.output[_ROOT] + return output.output + + +def wait_invoke_result( + runner: Any, + workflow_id: str, + thread_id: str, + *, + poll_interval: float, + timeout: Optional[float], + after_seq: int = 0, + on_completed: Optional[Callable[[], None]] = None, +) -> Any: + """Poll the run until it ends or pauses on an interrupt newer than ``after_seq``. + + A pause returns ``{"__interrupt__": [Interrupt, ...]}`` as LangGraph's + ``invoke`` does; a run that failed raises. ``on_completed`` is called once + the workflow completed (in the graph's error or not). + """ + client = runner._workflow_client + start = time.time() + while True: + time.sleep(poll_interval) + if timeout and (time.time() - start) > timeout: + raise TimeoutError(f"Workflow {workflow_id} timed out after {timeout}s") + state = client.get_workflow_state(instance_id=workflow_id) + if state is None: + raise RuntimeError(f"Workflow {workflow_id} state not found") + paused = interrupted_event( + parse_status(state.serialized_custom_status), workflow_id, after_seq + ) + if state.runtime_status == WorkflowStatus.RUNNING and paused: + return {INTERRUPT_KEY: list(as_interrupts(paused["interrupts"]))} + if state.runtime_status == WorkflowStatus.COMPLETED: + if on_completed is not None: + on_completed() + return _completed_output(state, runner, workflow_id, thread_id) + if state.runtime_status == WorkflowStatus.FAILED: + details = state.failure_details + raise RuntimeError( + getattr(details, "message", str(details)) + if details + else "Workflow failed" + ) + if state.runtime_status == WorkflowStatus.TERMINATED: + raise RuntimeError(f"Workflow {workflow_id} was terminated") + + +def invoke_resume( + runner: Any, + command: Any, + workflow_id: Optional[str], + *, + poll_interval: float, + timeout: Optional[float], +) -> Any: + """Resume the run ``workflow_id`` with ``command.resume`` and wait for it. + + Raises ``ValueError`` for a ``Command`` that is not a resume, without the + run's ``workflow_id``, or for a run that is not waiting for a resume, and + ``LookupError`` for an unknown run. + """ + from .reconnect import _thread_of + + if getattr(command, "resume", None) is None or not workflow_id: + raise ValueError( + "invoke(Command(resume=...)) resumes a run paused by interrupt(): " + "pass the run's workflow_id (other Commands are not supported as input)" + ) + client = runner._workflow_client + state = client.get_workflow_state(instance_id=workflow_id) + if state is None: + raise LookupError(f"Workflow {workflow_id!r} not found") + pending = pending_interrupt(parse_status(state.serialized_custom_status)) + if state.runtime_status != WorkflowStatus.RUNNING or pending is None: + raise ValueError(f"Workflow {workflow_id!r} is not waiting for a resume") + seq = int(pending.get("seq") or 0) + client.raise_workflow_event( + instance_id=workflow_id, + event_name=RESUME_EVENT, + data={"seq": seq, "resume": command.resume}, + ) + return wait_invoke_result( + runner, + workflow_id, + _thread_of(state, workflow_id), + poll_interval=poll_interval, + timeout=timeout, + after_seq=seq, + ) diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 860a948b..9cf6082d 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -6,7 +6,6 @@ import asyncio import json import logging -import time import uuid from contextlib import aclosing from dataclasses import dataclass @@ -23,7 +22,6 @@ TYPE_CHECKING, ) -from dapr.ext.workflow import WorkflowStatus from langchain_core.runnables.config import DEFAULT_RECURSION_LIMIT from langgraph.types import Command @@ -40,18 +38,15 @@ EdgeConfig, GraphConfig, GraphWorkflowInput, - GraphWorkflowOutput, NodeConfig, WaitingEdgeConfig, ) from .streaming import ( STREAM_RUN_KEY, StaticConfig, - FAILED_STATUSES, StreamControl, normalize_final, normalize_stream_mode, - run_error, ) from .stream_events import ( FINAL_EVENTS, @@ -63,7 +58,8 @@ from .langsmith_trace import ParentTrace, start_parent_trace from .run_status import completed_result, interrupted_result from .activity_stream import parse_status -from .interrupts import INTERRUPT_KEY, as_interrupts, interrupted_event +from .interrupts import interrupted_event +from .invoke_result import invoke_resume, wait_invoke_result from .reconnect import add_reconnect_route, resume_events from .resume_run import add_resume_route, resume_run_events from .stream_drain import SseEncoder, drain, parse_output @@ -810,6 +806,10 @@ def invoke( GraphRunError: The run failed (a node or a condition raised). RuntimeError: The workflow failed or was terminated. """ + if isinstance(input, Command): + return invoke_resume( + self, input, workflow_id, poll_interval=poll_interval, timeout=timeout + ) run = self._prepare_run(input, thread_id, config, workflow_id) workflow_id, thread_id, trace = run.workflow_id, run.thread_id, run.trace @@ -820,73 +820,19 @@ def invoke( input=run.workflow_input, instance_id=workflow_id, ) - - start_time = time.time() + # a run that completed had its trace closed by workflow.py + completed: List[bool] = [] try: - while True: - time.sleep(poll_interval) - - if timeout and (time.time() - start_time) > timeout: - raise TimeoutError( - f"Workflow {workflow_id} timed out after {timeout}s" - ) - - state = self._workflow_client.get_workflow_state( - instance_id=workflow_id - ) - - if state is None: - raise RuntimeError(f"Workflow {workflow_id} state not found") - - paused = interrupted_event( - parse_status(state.serialized_custom_status), workflow_id - ) - if state.runtime_status == WorkflowStatus.RUNNING and paused: - # As LangGraph's invoke: the interrupts, under __interrupt__. - return {INTERRUPT_KEY: list(as_interrupts(paused["interrupts"]))} - - if state.runtime_status == WorkflowStatus.COMPLETED: - # Workflow completed normally; workflow.py already closes the trace. - trace = None - if state.serialized_output: - output_dict = ( - json.loads(state.serialized_output) - if isinstance(state.serialized_output, str) - else state.serialized_output - ) - output = GraphWorkflowOutput.from_dict(output_dict) - if output.status in FAILED_STATUSES: - # Not a result: a run that hit its step limit or - # failed in a node raises. - raise run_error( - normalize_final( - { - "type": "workflow_completed", - "status": output.status, - "error": output.error, - "output": output.output, - }, - workflow_id=workflow_id, - thread_id=thread_id, - ) - ) - if self._is_root_state() and ROOT in output.output: - return output.output[ROOT] - return output.output - return {} - - elif state.runtime_status == WorkflowStatus.FAILED: - error_msg = "Workflow failed" - if state.failure_details: - error_msg = getattr( - state.failure_details, "message", str(state.failure_details) - ) - raise RuntimeError(error_msg) - - elif state.runtime_status == WorkflowStatus.TERMINATED: - raise RuntimeError(f"Workflow {workflow_id} was terminated") + return wait_invoke_result( + self, + workflow_id, + thread_id, + poll_interval=poll_interval, + timeout=timeout, + on_completed=lambda: completed.append(True), + ) finally: - if trace: + if trace and not completed: trace.end() async def run_async( diff --git a/tests/agent/langgraph/test_invoke_resume.py b/tests/agent/langgraph/test_invoke_resume.py new file mode 100644 index 00000000..415ba747 --- /dev/null +++ b/tests/agent/langgraph/test_invoke_resume.py @@ -0,0 +1,35 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""``invoke(Command(resume=...), workflow_id=...)`` resumes a paused run, as native.""" + +from langgraph.types import Command + +from .log_helpers import log_runner +from .test_interrupt_nested import _subgraph_node_graph +from .test_runner import _RunnerTestCase + + +class TestInvokeCommand(_RunnerTestCase): + def test_invoke_with_a_command_resumes_the_run(self): + runner = log_runner(_subgraph_node_graph(), "nest-inv") + first = runner.invoke( + {"log": []}, workflow_id="wf-nest-inv", poll_interval=0.01, timeout=10 + ) + self.assertIn("__interrupt__", first) + out = runner.invoke( + Command(resume="go"), + workflow_id="wf-nest-inv", + poll_interval=0.01, + timeout=10, + ) + self.assertEqual(out["log"], ["inner:go"]) + + def test_invoke_with_a_command_needs_a_paused_run(self): + runner = log_runner(_subgraph_node_graph(), "nest-inv-bad") + with self.assertRaises(ValueError): + runner.invoke(Command(resume="go"), poll_interval=0.01, timeout=1) + with self.assertRaises(ValueError): + runner.invoke( + Command(goto="sub"), workflow_id="wf-x", poll_interval=0.01, timeout=1 + ) From 243ecddf31508d1a4e4d9f6daf5ad15e1d87dfdb Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 15:34:33 +0100 Subject: [PATCH 46/73] fix(langgraph): carry thread state only for a thread the caller names A run without a thread_id or session_id got a generated 8-hex thread id and still loaded and saved thread state, so stateless traffic grew the store. Now only a thread the caller names (thread_id, session_id or configurable thread_id) carries state; continue_threads=False turns it off. Generated thread ids and workflow id suffixes are full UUIDs. A graph compiled with MemorySaver no longer wins over the app's Dapr state store: the runner keeps threads in the store and warns, and warns too when an in-memory saver is all there is. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 4 +- diagrid/agent/langgraph/runner.py | 50 ++++++- diagrid/agent/langgraph/saver_store.py | 9 ++ diagrid/agent/langgraph/thread_state.py | 27 +++- tests/agent/langgraph/test_thread_scope.py | 150 +++++++++++++++++++++ 5 files changed, 230 insertions(+), 10 deletions(-) create mode 100644 tests/agent/langgraph/test_thread_scope.py diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index c5a0e57c..3adcae7f 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -595,7 +595,7 @@ def _stream_response( except ValueError as e: raise HTTPException(status_code=422, detail=str(e)) session_id = request.get( - "session_id", request.get("thread_id", uuid.uuid4().hex[:8]) + "session_id", request.get("thread_id", uuid.uuid4().hex) ) return StreamingResponse( frame_sse(self._serve_stream(request, session_id, on_result=on_result)), @@ -664,7 +664,7 @@ async def _run_and_collect(request: dict) -> dict: # type: ignore[type-arg] """Run the agent and collect the result.""" session_id = request.get( "session_id", - request.get("thread_id", uuid.uuid4().hex[:8]), + request.get("thread_id", uuid.uuid4().hex), ) result: dict[str, Any] = {} async for event in runner_ref._serve_run( diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 9cf6082d..51e85b2a 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -238,7 +238,24 @@ def _run_identity( "thread_id": thread, }, } - return thread, workflow_id or f"graph-{thread}-{uuid.uuid4().hex[:8]}", run_config + return thread, workflow_id or f"graph-{thread}-{uuid.uuid4().hex}", run_config + + +#: Run config key a stream sets for a run whose thread id it generated. +_STATELESS_KEY = "__diagrid_stateless_run__" + + +def _names_thread(thread_id: Optional[str], merged: Dict[str, Any]) -> bool: + """Whether the caller named the run's thread (else the run is stateless).""" + if merged.get(_STATELESS_KEY): + return False + return bool(thread_id or (merged.get("configurable") or {}).get("thread_id")) + + +def _without_stateless_key(config: Optional[Dict[str, Any]]) -> Any: + if not config or _STATELESS_KEY not in config: + return config + return {k: v for k, v in config.items() if k != _STATELESS_KEY} async def _wait_scheduled(scheduled: asyncio.Event, pump: "asyncio.Task[None]") -> bool: @@ -333,6 +350,7 @@ def __init__( stream_registry: Optional[StreamSinkRegistry] = None, checkpointer: Optional[Any] = None, stream_transport: Optional[StreamTransport] = None, + continue_threads: bool = True, ): """Initialize the runner. @@ -359,7 +377,13 @@ def __init__( the synchronous API. Defaults to the checkpointer the graph was compiled with, else the app's Dapr state store (``agent-memory``) when it has one; with none, ``thread_id`` is - only a label. + only a label. A graph compiled with an in-memory saver + (``MemorySaver``) gets the app's Dapr state store instead, when + it has one: memory is per process, so it breaks across replicas. + continue_threads: Whether a run on a thread the caller names + (``thread_id``, ``session_id`` or ``configurable["thread_id"]``) + starts from that thread's state (default on). A run without a + thread id is always stateless. stream_transport: How a streamed run's chunks get from its activities to its stream. By default the state-store event log (``StateLogTransport``) when the app has a state store, @@ -398,6 +422,7 @@ def __init__( # max_iterations instead of a hardcoded default (read by DeepAgentsMapper). self._graph._diagrid_max_steps = self._max_steps # type: ignore[attr-defined] + self._continue_threads = continue_threads self._thread_store = resolve_thread_store( checkpointer, self._graph, self._state_store ) @@ -624,8 +649,11 @@ def _prepare_run( """Everything ``invoke`` and ``run_async`` settle before scheduling the run.""" if not self._started: raise RuntimeError("Runner not started. Call start() first.") + named = _names_thread(thread_id, {**self._run_config(config), **(config or {})}) + config = _without_stateless_key(config) + merged = self._run_config(config) thread_id, workflow_id, caller_config = _run_identity( - config, self._run_config(config), thread_id, workflow_id + config, merged, thread_id, workflow_id ) bound = self._step_bound(config) run_config = self._run_config(caller_config) @@ -652,7 +680,9 @@ def _prepare_run( pending_nodes=[], config=run_config, thread_id=thread_id, - thread_state=self._thread_store is not None, + thread_state=named + and self._continue_threads + and self._thread_store is not None, ).to_dict() json.dumps(workflow_input) return _RunSetup(workflow_id, thread_id, run_config, trace, workflow_input) @@ -1057,10 +1087,14 @@ async def _stream_events( ``thread_id``). With ``keepalive`` set, :data:`KEEPALIVE` is yielded whenever nothing arrived for ``SSE_KEEPALIVE_SECONDS``. """ + merged = self._run_config(config) + named = _names_thread(thread_id, merged) thread_id, workflow_id, run_config = _run_identity( - config, self._run_config(config), thread_id, workflow_id + config, merged, thread_id, workflow_id ) run_config = {**run_config, STREAM_RUN_KEY: True} + if not named: + run_config[_STATELESS_KEY] = True seen_nodes: Set[Tuple[int, str]] = set() source = open_source( self._stream_transport, @@ -1252,7 +1286,8 @@ async def _serve_run( request: dict, session_id: str, # type: ignore[type-arg] ) -> AsyncIterator[dict[str, Any]]: - thread_id = request.get("thread_id") or request.get("session_id") or session_id + # only a thread the caller names carries state: no id, a stateless run + thread_id = request.get("thread_id") or request.get("session_id") graph_input = self._request_to_input(request) @@ -1280,7 +1315,8 @@ async def _serve_stream( # type: ignore[override] Ends with ``workflow_completed`` or ``workflow_failed``, whose data is the run's full terminal event. The base runner frames the pairs. """ - thread_id = request.get("thread_id") or request.get("session_id") or session_id + # only a thread the caller names carries state: no id, a stateless run + thread_id = request.get("thread_id") or request.get("session_id") encoder: Optional[SseEncoder] = None try: modes, _ = normalize_stream_mode( diff --git a/diagrid/agent/langgraph/saver_store.py b/diagrid/agent/langgraph/saver_store.py index da90791d..1cfe3de1 100644 --- a/diagrid/agent/langgraph/saver_store.py +++ b/diagrid/agent/langgraph/saver_store.py @@ -27,6 +27,15 @@ def is_saver(obj: Any) -> bool: return isinstance(obj, BaseCheckpointSaver) +def is_in_memory_saver(obj: Any) -> bool: + """Whether ``obj`` is LangGraph's in-process saver (``MemorySaver``).""" + try: + from langgraph.checkpoint.memory import InMemorySaver + except ImportError: # pragma: no cover - langgraph without checkpoints + return False + return isinstance(obj, InMemorySaver) + + def _config(thread_id: str) -> Dict[str, Any]: return {"configurable": {"thread_id": thread_id, "checkpoint_ns": _ROOT_NS}} diff --git a/diagrid/agent/langgraph/thread_state.py b/diagrid/agent/langgraph/thread_state.py index 7b6f072f..7b12a1c8 100644 --- a/diagrid/agent/langgraph/thread_state.py +++ b/diagrid/agent/langgraph/thread_state.py @@ -101,26 +101,51 @@ def resolve_thread_store( The runner's own ``checkpointer`` first, then the one the graph was compiled with, then the app's Dapr state store (``agent-memory``, which a Catalyst app has). Without any of them a thread id is only a label. + + A graph compiled with an in-memory saver (``MemorySaver``, as LangGraph's + examples do) keeps threads in one process, which breaks across replicas + and restarts: the app's Dapr state store is used instead when there is + one, and either way a warning says so. """ - from .saver_store import SaverThreadStore, is_saver + from .saver_store import SaverThreadStore, is_in_memory_saver, is_saver if checkpointer is not None: if isinstance(checkpointer, DaprMemoryCheckpointer): return DaprThreadStore(checkpointer) if is_saver(checkpointer): + if is_in_memory_saver(checkpointer): + logger.warning(_IN_MEMORY_WARNING, type(checkpointer).__name__) return SaverThreadStore(checkpointer, _state_channels(graph)) raise TypeError( "checkpointer must be a DaprMemoryCheckpointer or a LangGraph " f"checkpoint saver, not {type(checkpointer).__name__}" ) own = getattr(graph, "checkpointer", None) + if is_in_memory_saver(own) and state_store is not None: + logger.warning( + "The graph was compiled with %s, which keeps threads in this process " + "only; the runner keeps them in the app's Dapr state store %r " + "instead, so they survive restarts and work across replicas", + type(own).__name__, + getattr(state_store, "store_name", None), + ) + return DaprThreadStore(DaprMemoryCheckpointer(state_store=state_store)) if is_saver(own): + if is_in_memory_saver(own): + logger.warning(_IN_MEMORY_WARNING, type(own).__name__) return SaverThreadStore(own, _state_channels(graph)) if state_store is not None: return DaprThreadStore(DaprMemoryCheckpointer(state_store=state_store)) return None +_IN_MEMORY_WARNING = ( + "Threads are kept in %s, in this process only: a thread's state is lost on " + "a restart and not seen by another replica. Give the app a Dapr state " + "store (Catalyst apps have one) or a durable checkpointer" +) + + def _state_channels(graph: Any) -> List[str]: channels = getattr(getattr(graph, "builder", None), "channels", None) or {} return list(channels) diff --git a/tests/agent/langgraph/test_thread_scope.py b/tests/agent/langgraph/test_thread_scope.py new file mode 100644 index 00000000..680d1e4c --- /dev/null +++ b/tests/agent/langgraph/test_thread_scope.py @@ -0,0 +1,150 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Which runs carry a thread's state, and the ids a run gets when it has none. + +A run continues a thread only when the caller named one (``thread_id``, +``session_id`` or ``configurable["thread_id"]``): a run without one is +stateless and touches no thread state. Generated ids are full UUIDs. Thread +continuation is on by default and can be turned off on the runner. +""" + +import logging +import re +from typing import Any +from unittest import mock + +from fastapi.testclient import TestClient +from langgraph.checkpoint.memory import MemorySaver + +from diagrid.agent.core.discovery import DiscoveredComponents +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.state import DaprMemoryCheckpointer +from diagrid.agent.langgraph.thread_state import DaprThreadStore + +from .golden_harness import _FakeDaprTest, _FakeWorkflowClient +from .log_helpers import log_runner +from .streaming_helpers import serve_app +from .test_reconnect_helpers import frames +from .thread_helpers import MemoryStateStore, chat_graph, shape, turn + +FULL_UUID = re.compile( + r"^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$" +) + + +def _runner(name: str, **kwargs: Any) -> DaprWorkflowGraphRunner: + store = MemoryStateStore() + runner = DaprWorkflowGraphRunner( + graph=chat_graph(), + name=name, + checkpointer=DaprMemoryCheckpointer(state_store=store), # type: ignore[arg-type] + **kwargs, + ) + runner._started = True + runner._workflow_client = _FakeWorkflowClient(runner) # type: ignore[assignment] + return runner + + +def _thread_state(runner: Any, thread_id: Any = None, config: Any = None) -> bool: + setup = runner._prepare_run(turn("hi"), thread_id, config, None) + return bool(setup.workflow_input.get("thread_state")) + + +class TestWhichRunsCarryState(_FakeDaprTest): + def test_a_run_without_a_thread_id_is_stateless(self): + self.assertFalse(_thread_state(_runner("scope-none"))) + + def test_a_named_thread_carries_state(self): + runner = _runner("scope-named") + self.assertTrue(_thread_state(runner, "t1")) + self.assertTrue( + _thread_state(runner, config={"configurable": {"thread_id": "t1"}}) + ) + + def test_continuation_can_be_turned_off(self): + runner = _runner("scope-off", continue_threads=False) + self.assertFalse(_thread_state(runner, "t1")) + + def test_stateless_runs_leave_nothing_in_the_store(self): + runner = _runner("scope-store") + store = runner._thread_store._checkpointer._store # type: ignore[union-attr] + for _ in range(3): + runner.invoke(turn("hi"), poll_interval=0.01, timeout=10) + self.assertEqual(store.data, {}) + + +class TestGeneratedIds(_FakeDaprTest): + def test_a_generated_thread_and_workflow_id_are_full_uuids(self): + runner = _runner("scope-ids") + setup = runner._prepare_run(turn("hi"), None, None, None) + self.assertRegex(setup.thread_id, FULL_UUID) + suffix = setup.workflow_id.rsplit("-", 1)[1] + self.assertRegex(suffix, r"^[0-9a-f]{32}$") + + def test_an_http_run_without_ids_is_stateless_with_a_full_uuid(self): + runner = log_runner(chat_graph(), "scope-http") + runner._thread_store = DaprThreadStore( # a runner with a store + DaprMemoryCheckpointer(state_store=MemoryStateStore()) # type: ignore[arg-type] + ) + http = TestClient(serve_app(runner)) + got = frames(http.post("/agent/run", json={**turn("hi"), "stream": True}).text) + started = got[0][2] + self.assertRegex(started["thread_id"], FULL_UUID) + inputs = runner._workflow_client.inputs[started["workflow_id"]] + self.assertFalse(inputs.get("thread_state")) + named = frames( + http.post( + "/agent/run", json={**turn("hi"), "stream": True, "session_id": "s1"} + ).text + ) + self.assertTrue( + runner._workflow_client.inputs[named[0][2]["workflow_id"]]["thread_state"] + ) + + +class TestResentHistory(_FakeDaprTest): + def test_messages_resent_with_their_ids_are_not_duplicated(self): + runner = _runner("scope-resend") + first = runner.invoke( + turn("hi"), thread_id="t1", poll_interval=0.01, timeout=10 + ) + history = [*first["messages"], {"role": "user", "content": "again"}] + out = runner.invoke( + {"messages": history}, thread_id="t1", poll_interval=0.01, timeout=10 + ) + self.assertEqual( + shape(out["messages"]), + [ + ("human", "hi"), + ("ai", "Hello world"), + ("human", "again"), + ("ai", "Hello world"), + ], + ) + + +class TestInMemoryCheckpointer(_FakeDaprTest): + def test_a_graph_compiled_with_memory_saver_uses_the_apps_store(self): + found = DiscoveredComponents(memory_store_name="agent-memory") + with ( + mock.patch( + "diagrid.agent.core.workflow.runner.discover_components", + return_value=found, + ), + mock.patch("diagrid.agent.core.state.DaprStateStore", MemoryStateStore), + self.assertLogs("diagrid.agent.langgraph", level=logging.WARNING) as logs, + ): + runner = DaprWorkflowGraphRunner( + graph=chat_graph(MemorySaver()), name="scope-mem" + ) + self.assertIsInstance(runner._thread_store, DaprThreadStore) + self.assertTrue(any("MemorySaver" in line for line in logs.output)) + + def test_memory_saver_without_a_store_still_works_with_a_warning(self): + with self.assertLogs("diagrid.agent.langgraph", level=logging.WARNING) as logs: + runner = DaprWorkflowGraphRunner( + graph=chat_graph(MemorySaver()), name="scope-mem-only" + ) + self.assertIsNotNone(runner._thread_store) + self.assertTrue(any("replica" in line for line in logs.output)) From 7fbf82f3f2e24f11937326c412ea64fd812c9d86 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 15:34:33 +0100 Subject: [PATCH 47/73] fix(langgraph): expire, prune and etag-write a thread's checkpoints DaprMemoryCheckpointer kept every run's checkpoint forever, lost index entries when runs on one thread saved at once, and no longer read checkpoints saved under the old langgraph--... keys. Checkpoints and the index now carry a TTL (30 days by default), a thread keeps its last two checkpoints, the index is written with an etag (first-write) and retried with backoff, and the old keys are read when a thread has no index under the new ones. DaprStateStore gains get_with_etag and save_with_etag. Signed-off-by: Casper Nielsen --- diagrid/agent/core/state/store.py | 51 ++++++ diagrid/agent/langgraph/state.py | 157 +++++++++++++----- tests/agent/core/test_state_store.py | 46 +++++ .../langgraph/test_checkpointer_store.py | 124 ++++++++++++++ tests/agent/langgraph/test_state.py | 11 +- tests/agent/langgraph/thread_helpers.py | 33 +++- 6 files changed, 380 insertions(+), 42 deletions(-) create mode 100644 tests/agent/langgraph/test_checkpointer_store.py diff --git a/diagrid/agent/core/state/store.py b/diagrid/agent/core/state/store.py index 611532e0..40877bf0 100644 --- a/diagrid/agent/core/state/store.py +++ b/diagrid/agent/core/state/store.py @@ -97,6 +97,44 @@ def get(self, key: str) -> Any | None: return None return json.loads(response.data.decode()) + def get_with_etag(self, key: str) -> tuple[Any | None, Optional[str]]: + """A value and its etag (``(None, None)`` when the key does not exist).""" + response = self._get_client().get_state(store_name=self._store_name, key=key) + if not response.data: + return None, None + return json.loads(response.data.decode()), (response.etag or None) + + def save_with_etag( + self, + key: str, + value: Any, + etag: Optional[str], + metadata: Optional[dict[str, str]] = None, + ) -> bool: + """Save ``value`` only if the key still has ``etag`` (first-write wins). + + ``etag`` ``None`` saves only a key that does not exist yet. Returns + ``False`` when another write got there first (the sidecar answers + ``ABORTED``); any other error propagates. + """ + from dapr.clients.grpc._state import Concurrency, StateOptions + + try: + self._get_client().save_state( + store_name=self._store_name, + key=key, + value=json.dumps(value), + etag=etag, + options=StateOptions(concurrency=Concurrency.first_write), + state_metadata=metadata, + ) + except Exception as e: + if _is_etag_conflict(e): + logger.debug("Etag conflict on key=%s store=%s", key, self._store_name) + return False + raise + return True + def delete(self, key: str) -> None: """Delete a key from the state store. @@ -141,3 +179,16 @@ def close(self) -> None: if self._client is not None: self._client.close() self._client = None + + +def _is_etag_conflict(error: Exception) -> bool: + """Whether a save failed because the key's etag changed (gRPC ``ABORTED``).""" + code = getattr(error, "code", None) + if not callable(code): + return False + try: + import grpc + + return bool(code() == grpc.StatusCode.ABORTED) + except Exception: # not a gRPC error after all + return False diff --git a/diagrid/agent/langgraph/state.py b/diagrid/agent/langgraph/state.py index 7abe2b6a..8a338cbd 100644 --- a/diagrid/agent/langgraph/state.py +++ b/diagrid/agent/langgraph/state.py @@ -4,13 +4,25 @@ """Dapr-backed checkpoint saver for LangGraph.""" import logging -from typing import Any, Optional +import random +import time +from typing import Any, Callable, List, Optional, Tuple from urllib.parse import quote from diagrid.agent.core.state import DaprStateStore logger = logging.getLogger(__name__) +#: How long a thread's checkpoints and index are kept after its last save. +DEFAULT_THREAD_TTL_S = 30 * 24 * 3600 +#: How many checkpoints a thread keeps: the latest, and the one before it. +DEFAULT_KEEP_CHECKPOINTS = 2 +#: Tries at writing a thread's index when other runs write it at the same time. +INDEX_WRITE_ATTEMPTS = 8 + +#: ``(index after the change, checkpoint ids it no longer lists)`` +IndexChange = Callable[[dict[str, Any]], Tuple[dict[str, Any], List[str]]] + class DaprMemoryCheckpointer: """LangGraph checkpoint saver backed by Dapr state store. @@ -21,7 +33,15 @@ class DaprMemoryCheckpointer: Key format: ``langgraph:{thread_id}:checkpoint:{checkpoint_id}``, and ``langgraph:{thread_id}:index`` for the thread's list of checkpoints. Each id is path-escaped, so a ``:``, ``|`` or ``#`` in it cannot run into the - separators (and no key ever holds ``||``, which Dapr reserves). + separators (and no key ever holds ``||``, which Dapr reserves). Checkpoints + saved under the earlier ``langgraph-{thread_id}-checkpoint-{id}`` keys are + still read. + + A thread keeps its last ``keep_checkpoints`` checkpoints (older ones are + deleted), and its checkpoints and index expire ``ttl_s`` seconds after the + thread's last save (``None``: never; the state store must support TTLs). + The index is written with an etag (first-write concurrency) where the store + supports it, so concurrent runs on one thread lose none of its entries. :class:`~diagrid.agent.langgraph.DaprWorkflowGraphRunner` uses one on the app's state store by default, so ``thread_id`` carries a conversation from @@ -54,10 +74,19 @@ def __init__( store_name: str = "agent-memory", consistency: str = "strong", state_store: Optional[DaprStateStore] = None, + *, + ttl_s: Optional[int] = DEFAULT_THREAD_TTL_S, + keep_checkpoints: int = DEFAULT_KEEP_CHECKPOINTS, ) -> None: + if keep_checkpoints < 1: + raise ValueError("keep_checkpoints must be at least 1") + if ttl_s is not None and ttl_s < 1: + raise ValueError("ttl_s must be a positive number of seconds, or None") self._store = state_store or DaprStateStore( store_name=store_name, consistency=consistency ) + self._ttl_s = ttl_s + self._keep = keep_checkpoints def _checkpoint_key(self, thread_id: str, checkpoint_id: str) -> str: return f"langgraph:{_segment(thread_id)}:checkpoint:{_segment(checkpoint_id)}" @@ -65,6 +94,9 @@ def _checkpoint_key(self, thread_id: str, checkpoint_id: str) -> str: def _thread_index_key(self, thread_id: str) -> str: return f"langgraph:{_segment(thread_id)}:index" + def _metadata(self) -> Optional[dict[str, str]]: + return None if self._ttl_s is None else {"ttlInSeconds": str(self._ttl_s)} + def save_checkpoint( self, thread_id: str, @@ -90,20 +122,41 @@ def save_checkpoint( "channel_versions": channel_versions, "metadata": metadata or {}, } - self._store.save(key, data) - - # Update thread index with latest checkpoint - index_key = self._thread_index_key(thread_id) - index = self._store.get(index_key) or {"checkpoints": []} - if checkpoint_id not in index["checkpoints"]: - index["checkpoints"].append(checkpoint_id) - index["latest"] = checkpoint_id - self._store.save(index_key, index) - + self._store.save(key, data, self._metadata()) + dropped = self._update_index( + thread_id, lambda index: _with_latest(index, checkpoint_id, self._keep) + ) + for old in dropped: + self._store.delete(self._checkpoint_key(thread_id, old)) logger.debug( - "Saved checkpoint thread=%s checkpoint=%s", + "Saved checkpoint thread=%s checkpoint=%s (pruned %d)", thread_id, checkpoint_id, + len(dropped), + ) + + def _update_index(self, thread_id: str, change: IndexChange) -> List[str]: + """Apply ``change`` to the thread's index; the checkpoint ids it dropped. + + With etags, a write that lost to a concurrent one reads the index again + and re-applies the change (with jittered backoff). + """ + key = self._thread_index_key(thread_id) + get_with_etag = getattr(self._store, "get_with_etag", None) + save_with_etag = getattr(self._store, "save_with_etag", None) + if not (callable(get_with_etag) and callable(save_with_etag)): + index, dropped = change(_index_copy(self._store.get(key))) + self._store.save(key, index, self._metadata()) + return dropped + for attempt in range(INDEX_WRITE_ATTEMPTS): + current, etag = get_with_etag(key) + index, dropped = change(_index_copy(current)) + if save_with_etag(key, index, etag, self._metadata()): + return dropped + time.sleep(random.uniform(0, 0.01 * (2**attempt))) + raise RuntimeError( + f"The index of thread {thread_id!r} could not be written: " + f"{INDEX_WRITE_ATTEMPTS} concurrent writes in a row won over this one" ) def load_checkpoint( @@ -121,15 +174,18 @@ def load_checkpoint( Returns: Checkpoint data dict or None if not found. """ - if checkpoint_id is None: - index_key = self._thread_index_key(thread_id) - index = self._store.get(index_key) - if not index or "latest" not in index: - return None - checkpoint_id = index["latest"] - - key = self._checkpoint_key(thread_id, checkpoint_id) - return self._store.get(key) + if checkpoint_id is not None: + found = self._store.get(self._checkpoint_key(thread_id, checkpoint_id)) + return found or self._store.get( + _legacy_checkpoint_key(thread_id, checkpoint_id) + ) + index = self._store.get(self._thread_index_key(thread_id)) + if index and index.get("latest"): + return self._store.get(self._checkpoint_key(thread_id, index["latest"])) + legacy = self._store.get(_legacy_index_key(thread_id)) + if not legacy or not legacy.get("latest"): + return None + return self._store.get(_legacy_checkpoint_key(thread_id, legacy["latest"])) def list_checkpoints(self, thread_id: str) -> list[str]: """List all checkpoint IDs for a thread. @@ -140,11 +196,12 @@ def list_checkpoints(self, thread_id: str) -> list[str]: Returns: List of checkpoint IDs. """ - index_key = self._thread_index_key(thread_id) - index = self._store.get(index_key) + index = self._store.get(self._thread_index_key(thread_id)) + if not index: + index = self._store.get(_legacy_index_key(thread_id)) if not index: return [] - return index.get("checkpoints", []) + return list(index.get("checkpoints", [])) def delete_checkpoint(self, thread_id: str, checkpoint_id: str) -> None: """Delete a specific checkpoint. @@ -153,19 +210,8 @@ def delete_checkpoint(self, thread_id: str, checkpoint_id: str) -> None: thread_id: The thread identifier. checkpoint_id: The checkpoint to delete. """ - key = self._checkpoint_key(thread_id, checkpoint_id) - self._store.delete(key) - - # Update index - index_key = self._thread_index_key(thread_id) - index = self._store.get(index_key) - if index and checkpoint_id in index.get("checkpoints", []): - index["checkpoints"].remove(checkpoint_id) - if index.get("latest") == checkpoint_id: - index["latest"] = ( - index["checkpoints"][-1] if index["checkpoints"] else None - ) - self._store.save(index_key, index) + self._store.delete(self._checkpoint_key(thread_id, checkpoint_id)) + self._update_index(thread_id, lambda index: _without(index, checkpoint_id)) def close(self) -> None: """Close the underlying state store.""" @@ -175,3 +221,38 @@ def close(self) -> None: def _segment(value: str) -> str: """``value`` escaped so it is one segment of a ``:``-separated key.""" return quote(str(value), safe="") + + +def _legacy_index_key(thread_id: str) -> str: + """The index key checkpoints were saved under before ``:`` keys (read only).""" + return f"langgraph-{thread_id}-index" + + +def _legacy_checkpoint_key(thread_id: str, checkpoint_id: str) -> str: + return f"langgraph-{thread_id}-checkpoint-{checkpoint_id}" + + +def _index_copy(index: Any) -> dict[str, Any]: + """A thread index to change (the stored one is never changed in place).""" + if not isinstance(index, dict): + return {"checkpoints": []} + return {**index, "checkpoints": list(index.get("checkpoints") or [])} + + +def _with_latest( + index: dict[str, Any], checkpoint_id: str, keep: int +) -> Tuple[dict[str, Any], List[str]]: + """``index`` with ``checkpoint_id`` as its latest, trimmed to ``keep`` entries.""" + ids = [c for c in index["checkpoints"] if c != checkpoint_id] + [checkpoint_id] + return {**index, "checkpoints": ids[-keep:], "latest": checkpoint_id}, ids[:-keep] + + +def _without( + index: dict[str, Any], checkpoint_id: str +) -> Tuple[dict[str, Any], List[str]]: + """``index`` without ``checkpoint_id``; the latest moves to the one before.""" + ids = [c for c in index["checkpoints"] if c != checkpoint_id] + latest = index.get("latest") + if latest == checkpoint_id: + latest = ids[-1] if ids else None + return {**index, "checkpoints": ids, "latest": latest}, [] diff --git a/tests/agent/core/test_state_store.py b/tests/agent/core/test_state_store.py index 405e469c..d6a4bdf2 100644 --- a/tests/agent/core/test_state_store.py +++ b/tests/agent/core/test_state_store.py @@ -119,3 +119,49 @@ def test_store_name_property(self): def test_default_store_name(self): store = DaprStateStore() self.assertEqual(store.store_name, "agent-memory") + + +class _Aborted(Exception): + """What the sidecar raises for an etag that no longer matches.""" + + def code(self): + import grpc + + return grpc.StatusCode.ABORTED + + +class TestDaprStateStoreEtags(TestCase): + @mock.patch("dapr.clients.DaprClient") + def test_get_with_etag_returns_the_value_and_its_etag(self, mock_dapr_cls): + response = mock.MagicMock(data=json.dumps({"a": 1}).encode(), etag="7") + mock_dapr_cls.return_value.get_state.return_value = response + self.assertEqual(DaprStateStore().get_with_etag("k"), ({"a": 1}, "7")) + + @mock.patch("dapr.clients.DaprClient") + def test_a_missing_key_has_no_etag(self, mock_dapr_cls): + response = mock.MagicMock(data=b"", etag="") + mock_dapr_cls.return_value.get_state.return_value = response + self.assertEqual(DaprStateStore().get_with_etag("k"), (None, None)) + + @mock.patch("dapr.clients.DaprClient") + def test_save_with_etag_writes_first_write_wins(self, mock_dapr_cls): + from dapr.clients.grpc._state import Concurrency + + ok = DaprStateStore(store_name="s").save_with_etag("k", [1], "7", {"t": "1"}) + self.assertTrue(ok) + kwargs = mock_dapr_cls.return_value.save_state.call_args.kwargs + self.assertEqual(kwargs["etag"], "7") + self.assertEqual(kwargs["options"].concurrency, Concurrency.first_write) + self.assertEqual(kwargs["state_metadata"], {"t": "1"}) + self.assertEqual(kwargs["value"], json.dumps([1])) + + @mock.patch("dapr.clients.DaprClient") + def test_an_etag_mismatch_is_false_not_an_error(self, mock_dapr_cls): + mock_dapr_cls.return_value.save_state.side_effect = _Aborted("etag mismatch") + self.assertFalse(DaprStateStore().save_with_etag("k", 1, "7")) + + @mock.patch("dapr.clients.DaprClient") + def test_other_errors_propagate(self, mock_dapr_cls): + mock_dapr_cls.return_value.save_state.side_effect = ConnectionError("down") + with self.assertRaises(ConnectionError): + DaprStateStore().save_with_etag("k", 1, None) diff --git a/tests/agent/langgraph/test_checkpointer_store.py b/tests/agent/langgraph/test_checkpointer_store.py new file mode 100644 index 00000000..92006eb5 --- /dev/null +++ b/tests/agent/langgraph/test_checkpointer_store.py @@ -0,0 +1,124 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""How ``DaprMemoryCheckpointer`` keeps a thread's checkpoints in the store. + +Checkpoints and the thread's index expire (TTL), a thread keeps only its last +few checkpoints, the index is written with an etag so concurrent runs on one +thread lose no entry, and checkpoints written under the old key format are +still read. +""" + +import threading +import unittest +from typing import Any + +from diagrid.agent.langgraph.state import DaprMemoryCheckpointer +from diagrid.agent.langgraph.thread_state import DaprThreadStore + +from .thread_helpers import MemoryStateStore + + +def _save(cp: DaprMemoryCheckpointer, thread: str, checkpoint: str) -> None: + cp.save_checkpoint( + thread_id=thread, + checkpoint_id=checkpoint, + channel_values={"messages": [checkpoint]}, + channel_versions={"messages": 1}, + ) + + +class TestExpiryAndPruning(unittest.TestCase): + def test_checkpoints_and_the_index_expire(self): + store = MemoryStateStore() + cp = DaprMemoryCheckpointer(state_store=store, ttl_s=600) # type: ignore[arg-type] + _save(cp, "t1", "cp1") + for key in ("langgraph:t1:checkpoint:cp1", "langgraph:t1:index"): + self.assertEqual(store.metadata[key], {"ttlInSeconds": "600"}, key) + + def test_the_default_ttl_is_set(self): + store = MemoryStateStore() + _save(DaprMemoryCheckpointer(state_store=store), "t1", "cp1") # type: ignore[arg-type] + self.assertIn("ttlInSeconds", store.metadata["langgraph:t1:index"]) + + def test_a_thread_keeps_only_its_last_checkpoints(self): + store = MemoryStateStore() + cp = DaprMemoryCheckpointer(state_store=store, keep_checkpoints=2) # type: ignore[arg-type] + for n in range(5): + _save(cp, "t1", f"cp{n}") + self.assertEqual(cp.list_checkpoints("t1"), ["cp3", "cp4"]) + kept = sorted(k for k in store.data if ":checkpoint:" in k) + self.assertEqual( + kept, ["langgraph:t1:checkpoint:cp3", "langgraph:t1:checkpoint:cp4"] + ) + self.assertEqual( + cp.load_checkpoint("t1")["channel_values"], {"messages": ["cp4"]} + ) + + def test_keep_checkpoints_must_be_positive(self): + with self.assertRaises(ValueError): + DaprMemoryCheckpointer(state_store=MemoryStateStore(), keep_checkpoints=0) # type: ignore[arg-type] + + +class TestConcurrentRuns(unittest.TestCase): + def test_a_concurrent_index_write_is_not_lost(self): + store = MemoryStateStore() + cp = DaprMemoryCheckpointer(state_store=store, keep_checkpoints=10) # type: ignore[arg-type] + other = DaprMemoryCheckpointer(state_store=store, keep_checkpoints=10) # type: ignore[arg-type] + fired = [] + + def race(key: str) -> None: + if key.endswith(":index") and not fired: + fired.append(key) + _save(other, "t1", "other") + + store.between = race + _save(cp, "t1", "mine") + self.assertEqual(sorted(cp.list_checkpoints("t1")), ["mine", "other"]) + + def test_many_threads_saving_at_once_keep_every_entry(self): + store = MemoryStateStore() + cp = DaprMemoryCheckpointer(state_store=store, keep_checkpoints=50) # type: ignore[arg-type] + workers = [ + threading.Thread(target=_save, args=(cp, "t1", f"cp{n}")) for n in range(20) + ] + for w in workers: + w.start() + for w in workers: + w.join() + self.assertEqual(len(cp.list_checkpoints("t1")), 20) + + +class TestOldKeyFormat(unittest.TestCase): + def _old_store(self) -> Any: + store = MemoryStateStore() + store.data["langgraph-t1-index"] = {"checkpoints": ["cp1"], "latest": "cp1"} + store.data["langgraph-t1-checkpoint-cp1"] = { + "thread_id": "t1", + "checkpoint_id": "cp1", + "channel_values": {"messages": ["old"]}, + "channel_versions": {"messages": 1}, + "metadata": {}, + } + return store + + def test_a_checkpoint_saved_under_the_old_keys_is_read(self): + cp = DaprMemoryCheckpointer(state_store=self._old_store()) + self.assertEqual( + cp.load_checkpoint("t1")["channel_values"], {"messages": ["old"]} + ) + self.assertEqual(cp.load_checkpoint("t1", "cp1")["checkpoint_id"], "cp1") + self.assertEqual(cp.list_checkpoints("t1"), ["cp1"]) + + def test_a_thread_continues_from_its_old_checkpoint(self): + store = self._old_store() + threads = DaprThreadStore(DaprMemoryCheckpointer(state_store=store)) + loaded = threads.load("t1") + self.assertEqual(loaded["values"], {"messages": ["old"]}) + + def test_a_new_save_takes_over_from_the_old_keys(self): + cp = DaprMemoryCheckpointer(state_store=self._old_store()) + _save(cp, "t1", "cp2") + self.assertEqual( + cp.load_checkpoint("t1")["channel_values"], {"messages": ["cp2"]} + ) diff --git a/tests/agent/langgraph/test_state.py b/tests/agent/langgraph/test_state.py index abdd46cb..ca3c890c 100644 --- a/tests/agent/langgraph/test_state.py +++ b/tests/agent/langgraph/test_state.py @@ -5,12 +5,16 @@ from unittest import TestCase, mock -from diagrid.agent.langgraph.state import DaprMemoryCheckpointer +from diagrid.agent.langgraph.state import DEFAULT_THREAD_TTL_S, DaprMemoryCheckpointer + + +TTL = {"ttlInSeconds": str(DEFAULT_THREAD_TTL_S)} class TestDaprMemoryCheckpointer(TestCase): def _make_checkpointer(self): - store = mock.MagicMock() + # a store without the etag calls: the index is written plainly + store = mock.MagicMock(spec=["get", "save", "delete", "close"]) return DaprMemoryCheckpointer(state_store=store), store def test_save_checkpoint(self): @@ -34,11 +38,13 @@ def test_save_checkpoint(self): "channel_versions": {"messages": 1}, "metadata": {}, }, + TTL, ) # Should save the index store.save.assert_any_call( "langgraph:t1:index", {"checkpoints": ["cp1"], "latest": "cp1"}, + TTL, ) def test_load_checkpoint_by_id(self): @@ -99,6 +105,7 @@ def test_delete_checkpoint(self): store.save.assert_called_with( "langgraph:t1:index", {"checkpoints": ["cp1"], "latest": "cp1"}, + TTL, ) def test_close(self): diff --git a/tests/agent/langgraph/thread_helpers.py b/tests/agent/langgraph/thread_helpers.py index 845f2734..b096c6e5 100644 --- a/tests/agent/langgraph/thread_helpers.py +++ b/tests/agent/langgraph/thread_helpers.py @@ -5,7 +5,8 @@ import copy import json -from typing import Any, Callable, Dict, Optional +import threading +from typing import Any, Callable, Dict, Optional, Tuple from langgraph.graph import END, START, MessagesState, StateGraph @@ -22,7 +23,12 @@ class MemoryStateStore: def __init__(self, store_name: str = "agent-memory", **_: Any) -> None: self.store_name = store_name self.data: Dict[str, Any] = {} + self.metadata: Dict[str, Any] = {} + self.etags: Dict[str, int] = {} self.guard: Optional[Callable[[], None]] = None + #: Called between an etag read and its write: a concurrent writer. + self.between: Optional[Callable[[str], None]] = None + self._lock = threading.RLock() def _check(self) -> None: if self.guard is not None: @@ -30,7 +36,30 @@ def _check(self) -> None: def save(self, key: str, value: Any, metadata: Any = None) -> None: self._check() - self.data[key] = json.loads(json.dumps(value)) + with self._lock: + self.data[key] = json.loads(json.dumps(value)) + self.metadata[key] = metadata + self.etags[key] = self.etags.get(key, 0) + 1 + + def get_with_etag(self, key: str) -> Tuple[Any, Optional[str]]: + self._check() + with self._lock: + etag = self.etags.get(key) if key in self.data else None + value = copy.deepcopy(self.data.get(key)) + if self.between is not None: + self.between(key) + return value, None if etag is None else str(etag) + + def save_with_etag( + self, key: str, value: Any, etag: Optional[str], metadata: Any = None + ) -> bool: + self._check() + with self._lock: + current = self.etags.get(key) if key in self.data else None + if (None if current is None else str(current)) != etag: + return False + self.save(key, value, metadata) + return True def get(self, key: str) -> Any: self._check() From 2e0c5884b6dffdb70a1a3deacd85c520e0f3e5db Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 15:39:55 +0100 Subject: [PATCH 48/73] fix(langgraph): return a run's output when its thread state cannot be saved A save activity that failed after every node had run failed the whole run and lost its output. The workflow now catches the failure (after the activity's retries), returns the output with thread_saved false and thread_error, and a stream sends a thread_not_saved control event before its final event. GET /agent/run/{id} reports it as well. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/stream.py | 10 ++- diagrid/agent/langgraph/README.md | 1 + diagrid/agent/langgraph/invoke_result.py | 10 +++ diagrid/agent/langgraph/models.py | 10 +++ diagrid/agent/langgraph/run_status.py | 5 ++ diagrid/agent/langgraph/stream_drain.py | 5 ++ diagrid/agent/langgraph/stream_events.py | 21 ++++++ diagrid/agent/langgraph/streaming.py | 3 +- diagrid/agent/langgraph/thread_state.py | 32 ++++++-- diagrid/agent/langgraph/workflow.py | 2 +- .../agent/langgraph/test_streaming_events.py | 10 ++- .../langgraph/test_thread_save_failure.py | 74 +++++++++++++++++++ 12 files changed, 171 insertions(+), 12 deletions(-) create mode 100644 tests/agent/langgraph/test_thread_save_failure.py diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index 59e94485..ca93e7f4 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -39,8 +39,16 @@ STREAM_PURGED = "stream_purged" #: First event of a stream: the ids a client needs to find or stop its run. WORKFLOW_STARTED = "workflow_started" +#: The run ended but its thread's state could not be saved (the output stands). +THREAD_NOT_SAVED = "thread_not_saved" # Events about the stream itself, delivered whatever stream modes were asked for. -CONTROL_MODES = (WORKFLOW_STARTED, NODE_RESET, STREAM_UNAVAILABLE, STREAM_PURGED) +CONTROL_MODES = ( + WORKFLOW_STARTED, + NODE_RESET, + STREAM_UNAVAILABLE, + STREAM_PURGED, + THREAD_NOT_SAVED, +) #: Internal marker: a conditional edge's function finished streaming here. It #: tells the stream which routers ran in this process and never reaches a client. BRANCH_DONE = "branch_done" diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 50fd4a53..8172d9ae 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -174,6 +174,7 @@ objects (`kind`, `data`): | `node_reset` | `{"node", "step"}`, plus `"path"` for a `Send` task | A node was retried; drop its partial output. `node` and `step` are the `langgraph_node` and `langgraph_step` of that node's `messages` metadata (`step` is numbered from 1). A task started by a `Send` also carries `path`, the `langgraph_path` of its chunks (`["__pregel_push", index, false]`), which tells apart the tasks of one node in a step. A retry of a conditional edge's function also carries `branch`, the edge's function name. The function runs inside its node's activity, before the node's `updates` chunk, as in LangGraph; if it raises there, it runs again in an activity of its own, after that chunk, and only what the function sent is stale, not the node's own output. | | `stream_unavailable` | `{"workflow_id", "reason", "missing_steps", "missing_nodes"}` | The run finished but a node's chunks never arrived (see the limit below). `missing_nodes` is a list of `{"step", "node"}`, one per node of a step that streamed nothing, even when other nodes of that step did. Steps are numbered from 1, like `langgraph_step`. A `Send` task is named `node#k` there (`k` is its position among the step's `Send` tasks). A conditional edge's function that ran in an activity of its own (a START edge's, or one that raised inside its node's activity and ran again) is listed as `node:branch:` (`node#k:branch:` after a `Send` task, `__start__:branch:` at step 0 for a START edge), where `` is the name the runner registered the edge under. | | `stream_purged` | `{"workflow_id", "step"}` | A reconnect or a late reader found that the run's event log outlived its TTL (state-store transport only): what is left cannot be replayed. The final event follows. | +| `thread_not_saved` | `{"workflow_id", "thread_id", "error"}` | The run ended, but its thread's state could not be saved (after retries), so the next run on the thread starts from the state before this one. The run's output stands: the final event follows, with `thread_saved: false` and `thread_error`, which a plain `POST /agent/run` and `GET /agent/run/{workflow_id}` return too. | | `stream_dropped` | `{"dropped": n}` | The consumer fell behind and `n` token or custom chunks were dropped. `updates` are never dropped. | Pass `on_control=callback` to `astream` to receive them. A list of modes also diff --git a/diagrid/agent/langgraph/invoke_result.py b/diagrid/agent/langgraph/invoke_result.py index cd2c3997..b1014f7b 100644 --- a/diagrid/agent/langgraph/invoke_result.py +++ b/diagrid/agent/langgraph/invoke_result.py @@ -10,6 +10,7 @@ """ import json +import logging import time from typing import Any, Callable, Optional @@ -21,6 +22,8 @@ from .models import GraphWorkflowOutput from .streaming import FAILED_STATUSES, normalize_final, run_error +logger = logging.getLogger(__name__) + #: The workflow output key of a graph whose whole state is one value. _ROOT = "__root__" @@ -47,6 +50,13 @@ def _completed_output(state: Any, runner: Any, workflow_id: str, thread_id: str) thread_id=thread_id, ) ) + if output.thread_saved is False: + logger.warning( + "Run %s completed, but the state of thread %r was not saved: %s", + workflow_id, + thread_id, + output.thread_error, + ) if runner._is_root_state() and _ROOT in output.output: return output.output[_ROOT] return output.output diff --git a/diagrid/agent/langgraph/models.py b/diagrid/agent/langgraph/models.py index 9ccf00b6..c00bacab 100644 --- a/diagrid/agent/langgraph/models.py +++ b/diagrid/agent/langgraph/models.py @@ -561,6 +561,9 @@ class GraphWorkflowOutput: branches: The conditional edges evaluated in their own activity, as ``[step, sink key]`` (step ``-1`` for a START edge), for the same purpose. ``None`` when there were none. + thread_saved: ``False`` when the run's thread state could not be + saved (its output stands); ``None`` otherwise. + thread_error: Why the thread state was not saved. """ output: Dict[str, Any] = field(default_factory=dict) @@ -570,6 +573,8 @@ class GraphWorkflowOutput: error: Optional[str] = None executed: Optional[List[List[str]]] = None branches: Optional[List[List[Any]]] = None + thread_saved: Optional[bool] = None + thread_error: Optional[str] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -585,6 +590,9 @@ def to_dict(self) -> Dict[str, Any]: data["executed"] = self.executed if self.branches: data["branches"] = self.branches + if self.thread_saved is not None: + data["thread_saved"] = self.thread_saved + data["thread_error"] = self.thread_error return data @classmethod @@ -600,4 +608,6 @@ def from_dict(cls, data: Dict[str, Any]) -> "GraphWorkflowOutput": error=data.get("error"), executed=data.get("executed"), branches=data.get("branches"), + thread_saved=data.get("thread_saved"), + thread_error=data.get("thread_error"), ) diff --git a/diagrid/agent/langgraph/run_status.py b/diagrid/agent/langgraph/run_status.py index 91d521ed..cea6b26b 100644 --- a/diagrid/agent/langgraph/run_status.py +++ b/diagrid/agent/langgraph/run_status.py @@ -32,6 +32,11 @@ def completed_result(state: Any) -> Dict[str, Any]: "steps": output.steps, "run_status": output.status, **({"error": output.error} if output.error else {}), + **( + {"thread_saved": False, "thread_error": output.thread_error} + if output.thread_saved is False + else {} + ), } diff --git a/diagrid/agent/langgraph/stream_drain.py b/diagrid/agent/langgraph/stream_drain.py index 39d59935..6cc75e48 100644 --- a/diagrid/agent/langgraph/stream_drain.py +++ b/diagrid/agent/langgraph/stream_drain.py @@ -50,6 +50,11 @@ def parse_output( "steps": output.steps, "status": output.status, **({"error": output.error} if output.error else {}), + **( + {"thread_saved": False, "thread_error": output.thread_error} + if output.thread_saved is False + else {} + ), **({EXECUTED_KEY: output.executed} if streamed and output.executed else {}), **({BRANCHES_KEY: output.branches} if streamed and output.branches else {}), **( diff --git a/diagrid/agent/langgraph/stream_events.py b/diagrid/agent/langgraph/stream_events.py index c5aaae2e..aff8c3a4 100644 --- a/diagrid/agent/langgraph/stream_events.py +++ b/diagrid/agent/langgraph/stream_events.py @@ -12,6 +12,7 @@ CONTROL_MODES, NODE_RESET, STREAM_DROPPED, + THREAD_NOT_SAVED, WORKFLOW_STARTED, StreamClosed, StreamEvent, @@ -199,6 +200,24 @@ def route_astream_item( return out, None +def thread_not_saved_event(final: Dict[str, Any], workflow_id: str) -> StreamEvent: + """The warning that the run's thread state was not saved (its output stands).""" + return StreamEvent( + workflow_id=workflow_id, + step=-1, + node="", + attempt_id="", + seq=0, + ns=(), + mode=THREAD_NOT_SAVED, + data={ + "workflow_id": workflow_id, + "thread_id": final.get("thread_id"), + "error": final.get("thread_error"), + }, + ) + + def closing_events( closed: StreamClosed, seen_nodes: Set[Tuple[int, str]], @@ -238,6 +257,8 @@ def closing_events( [m["node"] for m in unavailable.data["missing_nodes"]], ) out.append(unavailable) + if closed.final.get("thread_saved") is False: + out.append(thread_not_saved_event(closed.final, workflow_id)) final = without_executed(closed.final) out.append({**final, "dropped": closed.dropped} if closed.dropped else final) return out diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index 05b682e0..f58fad5c 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -78,7 +78,8 @@ class StreamControl: """An event about the stream itself rather than a chunk of the run. ``kind`` is ``workflow_started`` (``{"workflow_id", "thread_id"}``, always - first), ``node_reset``, ``stream_unavailable``, ``stream_purged`` or + first), ``node_reset``, ``stream_unavailable``, ``stream_purged``, + ``thread_not_saved`` (``{"workflow_id", "thread_id", "error"}``) or ``stream_dropped``; ``data`` is its payload. ``astream`` hands these to its ``on_control`` callback, and in list mode also yields them as ``(kind, data)``, except diff --git a/diagrid/agent/langgraph/thread_state.py b/diagrid/agent/langgraph/thread_state.py index 7b12a1c8..26dbb1ce 100644 --- a/diagrid/agent/langgraph/thread_state.py +++ b/diagrid/agent/langgraph/thread_state.py @@ -216,10 +216,15 @@ def load_thread( def save_thread( ctx: Any, thread_id: str, output: Dict[str, Any], retry_policy: Any -) -> Generator[Any, Any, None]: - """Workflow step: keep the state the run ended with as its thread's.""" +) -> Generator[Any, Any, Dict[str, Any]]: + """Workflow step: keep the state the run ended with as its thread's. + + Returns ``output``, or when the save failed (after its retries) ``output`` + with ``thread_saved`` false and the reason: every node ran, so the run's + output stands. The failure is in the history, so a replay decides the same. + """ if not output.get("channel_state"): - return + return output checkpoint = ThreadCheckpoint( thread_id=thread_id, checkpoint_id=str(ctx.instance_id), @@ -227,8 +232,19 @@ def save_thread( steps=int(output.get("steps") or 0), status=str(output.get("status") or "completed"), ) - yield ctx.call_activity( - SAVE_THREAD_ACTIVITY, - input=checkpoint.to_dict(), - retry_policy=retry_policy, - ) + try: + yield ctx.call_activity( + SAVE_THREAD_ACTIVITY, + input=checkpoint.to_dict(), + retry_policy=retry_policy, + ) + except Exception as e: # the activity failed after its retries + if not ctx.is_replaying: + logger.warning( + "Run %s: the state of thread %r was not saved: %s", + ctx.instance_id, + thread_id, + e, + ) + return {**output, "thread_saved": False, "thread_error": str(e)} + return output diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 44d6c2c1..bc9a4dda 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -642,7 +642,7 @@ def agent_workflow( ) output = yield from _run_graph(run, workflow_input) if run.thread_state: - yield from save_thread(ctx, thread_id, output, run.retry_policy) + output = yield from save_thread(ctx, thread_id, output, run.retry_policy) return output diff --git a/tests/agent/langgraph/test_streaming_events.py b/tests/agent/langgraph/test_streaming_events.py index 67f45ce4..b77595f1 100644 --- a/tests/agent/langgraph/test_streaming_events.py +++ b/tests/agent/langgraph/test_streaming_events.py @@ -23,6 +23,7 @@ NODE_RESET, STREAM_PURGED, STREAM_UNAVAILABLE, + THREAD_NOT_SAVED, UPDATES, WORKFLOW_STARTED, InProcessSink, @@ -459,7 +460,13 @@ class TestControlModes(unittest.IsolatedAsyncioTestCase): def test_control_modes_are_the_events_about_the_stream_itself(self): self.assertEqual( set(CONTROL_MODES), - {WORKFLOW_STARTED, NODE_RESET, STREAM_UNAVAILABLE, STREAM_PURGED}, + { + WORKFLOW_STARTED, + NODE_RESET, + STREAM_UNAVAILABLE, + STREAM_PURGED, + THREAD_NOT_SAVED, + }, ) def test_updates_are_a_stream_mode_not_a_control_event(self): @@ -475,6 +482,7 @@ async def test_a_full_buffer_keeps_control_events_and_updates_only(self): NODE_RESET, STREAM_UNAVAILABLE, STREAM_PURGED, + THREAD_NOT_SAVED, ] sink = InProcessSink("wf", asyncio.get_running_loop()) with mock.patch.object(stream, "MAX_BUFFERED_EVENTS", 1): diff --git a/tests/agent/langgraph/test_thread_save_failure.py b/tests/agent/langgraph/test_thread_save_failure.py new file mode 100644 index 00000000..0cdc153e --- /dev/null +++ b/tests/agent/langgraph/test_thread_save_failure.py @@ -0,0 +1,74 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A run whose thread state cannot be saved still returns its output. + +The nodes all ran: failing the run would lose their work. The result says the +thread was not saved and why, and a stream says so before its final event. +""" + +from typing import Any + +from fastapi.testclient import TestClient + +from diagrid.agent.core.workflow.stream_log import StateLogTransport +from diagrid.agent.langgraph import DaprWorkflowGraphRunner +from diagrid.agent.langgraph.state import DaprMemoryCheckpointer + +from ..core.log_store_fake import FakeLogStore +from .log_helpers import FAST, LogClient +from .streaming_helpers import serve_app +from .test_reconnect_helpers import frames +from .test_runner import _RunnerTestCase +from .thread_helpers import MemoryStateStore, chat_graph, turn + + +class _SaveFails(MemoryStateStore): + def save(self, key: str, value: Any, metadata: Any = None) -> None: + raise ConnectionError("state store unreachable") + + def save_with_etag(self, *args: Any, **kwargs: Any) -> bool: + raise ConnectionError("state store unreachable") + + +def _runner(name: str) -> DaprWorkflowGraphRunner: + runner = DaprWorkflowGraphRunner( + graph=chat_graph(), + name=name, + checkpointer=DaprMemoryCheckpointer(state_store=_SaveFails()), # type: ignore[arg-type] + stream_transport=StateLogTransport(FAST, store=FakeLogStore()), + ) + runner._started = True + runner._workflow_client = LogClient(runner) # type: ignore[assignment] + return runner + + +class TestThreadSaveFailure(_RunnerTestCase): + def test_a_plain_run_returns_its_output_and_says_the_thread_was_not_saved(self): + http = TestClient(serve_app(_runner("save-fail-plain"))) + body = http.post("/agent/run", json={**turn("hi"), "thread_id": "t1"}).json() + self.assertEqual(body["status"], "completed") + self.assertEqual(body["output"]["messages"][-1]["content"], "Hello world") + self.assertIs(body["thread_saved"], False) + self.assertIn("state store unreachable", body["thread_error"]) + + def test_a_stream_warns_before_its_final_event(self): + http = TestClient(serve_app(_runner("save-fail-stream"))) + got = frames( + http.post( + "/agent/run", json={**turn("hi"), "thread_id": "t1", "stream": True} + ).text + ) + names = [e for _, e, _ in got] + self.assertEqual(names[-2:], ["thread_not_saved", "workflow_completed"]) + self.assertIn("state store unreachable", got[-2][2]["error"]) + self.assertEqual(got[-2][2]["thread_id"], "t1") + self.assertIs(got[-1][2]["thread_saved"], False) + + def test_the_status_endpoint_reports_it_too(self): + runner = _runner("save-fail-status") + http = TestClient(serve_app(runner)) + body = http.post("/agent/run", json={**turn("hi"), "thread_id": "t1"}).json() + status = http.get(f"/agent/run/{body['instance_id']}").json() + self.assertIs(status["thread_saved"], False) + self.assertIn("state store unreachable", status["thread_error"]) From aa12be9bbe02ee93da6c5ad66c73e624983a6004 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 15:42:03 +0100 Subject: [PATCH 49/73] fix(stream): retry an activity's last stream-log write with backoff The final flush of a unit (its updates chunk and done head) was tried once, so a single store error lost the node's updates. It is now tried up to final_flush_attempts times (default 4) with a doubling backoff before the unit is left not written. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/stream_log.py | 36 ++++++++++++++++++----- diagrid/agent/langgraph/README.md | 4 ++- tests/agent/core/test_stream_log.py | 20 ++++++++++--- 3 files changed, 48 insertions(+), 12 deletions(-) diff --git a/diagrid/agent/core/workflow/stream_log.py b/diagrid/agent/core/workflow/stream_log.py index 4d5224e5..582213ed 100644 --- a/diagrid/agent/core/workflow/stream_log.py +++ b/diagrid/agent/core/workflow/stream_log.py @@ -24,6 +24,7 @@ import itertools import logging import threading +import time import uuid from dataclasses import dataclass, field from typing import Any, Callable, Dict, List, Optional, Protocol, Sequence, Tuple @@ -55,6 +56,10 @@ class StateLogStreamConfig: #: Events an activity holds while the store refuses writes; past it, #: tokens and custom chunks are dropped, markers and updates never. max_buffered: int = MAX_BUFFERED_EVENTS + #: Tries at the last write of an activity (its ``updates`` and done head), + #: with a backoff that doubles from ``final_flush_backoff_s``. + final_flush_attempts: int = 4 + final_flush_backoff_s: float = 0.05 class LogStore(Protocol): @@ -177,7 +182,9 @@ class LogWriter: Flushes every ``flush_interval_s``, every ``flush_max_chunks`` chunks and on :meth:`finish`, which writes synchronously, so the unit is complete before the activity returns. A failed write is logged and counted, and - the chunks are tried again with the next flush; it never fails the node. + the chunks are tried again with the next flush; the last flush, which + nothing follows, is tried again with backoff (``final_flush_attempts``). + A write never fails the node. """ def __init__( @@ -236,7 +243,20 @@ def finish(self, *, done: bool) -> None: timer, self._timer = self._timer, None if timer is not None: timer.cancel() - self._flush(done=done, final=True) + delay = self._config.final_flush_backoff_s + for attempt in range(max(1, self._config.final_flush_attempts)): + if attempt: + time.sleep(delay) + delay *= 2 + if self._flush(done=done, final=True): + return + logger.warning( + "Stream log of %s (%s): the last write failed %d times; the unit's " + "last chunks are lost and readers report it as not written", + self._workflow_id, + self._unit, + self._config.final_flush_attempts, + ) def _note_dropped(self) -> None: if not self.dropped: @@ -253,16 +273,17 @@ def _timed_flush(self) -> None: self._timer = None self._flush(done=False) - def _flush(self, *, done: bool, final: bool = False) -> None: + def _flush(self, *, done: bool, final: bool = False) -> bool: + """Write what is pending; whether nothing is left to write.""" with self._flush_lock: with self._buffer_lock: batch = list(self._pending) if not batch and not final: - return + return True if self._is_blocked(): with self._buffer_lock: del self._pending[: len(batch)] - return + return True items: List[LogItem] = [] if batch: items.append( @@ -280,7 +301,7 @@ def _flush(self, *, done: bool, final: bool = False) -> None: ) ) if not items and not done: - return + return True batches = self._batches + (1 if batch else 0) head = { "attempt": self.attempt, @@ -312,11 +333,12 @@ def _flush(self, *, done: bool, final: bool = False) -> None: type(e).__name__, e, ) - return + return False self._batches = batches self._events += len(batch) with self._buffer_lock: del self._pending[: len(batch)] + return True def _is_blocked(self) -> bool: """Whether an attempt that already finished owns the unit (read once).""" diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 8172d9ae..ae0b278d 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -309,7 +309,9 @@ not pick one: like `lgstream::::...` with `:` between path-escaped parts, batches expire after an hour and their index after a day. Chunks arrive about 150 to 250 ms later than in process, in small bursts. A failed - write is retried with the next batch and never fails a node; if a node's + write is retried with the next batch, and a node's last write (its `updates` + chunk), which no batch follows, is retried up to four times with backoff; a + write never fails a node. If a node's chunks still never reach the log, the stream ends with `stream_unavailable` whose `reason` is `write_failed`. A store that cannot be read ends the stream with `workflow_failed` (`error_type` `StreamReadError`), never with an diff --git a/tests/agent/core/test_stream_log.py b/tests/agent/core/test_stream_log.py index 34b392e7..fe9be2fc 100644 --- a/tests/agent/core/test_stream_log.py +++ b/tests/agent/core/test_stream_log.py @@ -113,14 +113,26 @@ def test_a_write_error_never_raises_and_is_retried(self): chunk = LogReader(store, _config(), "wf:1").read([UnitWant(0, "research#0")])[0] self.assertEqual(_datas(chunk), ["research#0-0", "research#0-1"]) - def test_a_failed_last_flush_leaves_the_unit_not_done(self): + def test_a_transient_error_at_the_last_flush_is_retried(self): store = FakeLogStore() - writer = _writer(store) + writer = _writer(store, final_flush_backoff_s=0.001) + writer.put(_event("research#0", 0, UPDATES)) + store.fail_saves = 2 # two errors in a row at the final flush + writer.finish(done=True) + head = store.get(head_key("lgstream", "wf:1", 0, "research#0")) + self.assertTrue(head["done"]) + chunk = LogReader(store, _config(), "wf:1").read([UnitWant(0, "research#0")])[0] + self.assertEqual(_datas(chunk), ["research#0-0"]) + self.assertEqual(writer.write_failures, 2) + + def test_a_last_flush_that_keeps_failing_leaves_the_unit_not_done(self): + store = FakeLogStore() + writer = _writer(store, final_flush_attempts=3, final_flush_backoff_s=0.001) writer.put(_event("research#0", 0)) - store.fail_saves = 5 + store.fail_saves = 100 writer.finish(done=True) self.assertIsNone(store.get(head_key("lgstream", "wf:1", 0, "research#0"))) - self.assertGreaterEqual(writer.write_failures, 1) + self.assertEqual(writer.write_failures, 3) def test_a_full_buffer_never_drops_internal_markers(self): store = FakeLogStore() From ebb7749cafc113d8d6d1ed8ae750342d72f0c68a Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 15:44:57 +0100 Subject: [PATCH 50/73] fix(langgraph): send each values chunk once on a reconnect Every unit of a step logs that step's values chunk, and a reconnect replayed the copies of the units it had not read, so values repeated; the final values chunk reused the id before it, so a reconnect from it sent it again. The SSE cursor now carries the last step whose values the client has (a fourth, optional part), the follower skips earlier copies, and the final values chunk gets its own id. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/stream_cursor.py | 25 ++++- diagrid/agent/langgraph/stream_drain.py | 11 +++ diagrid/agent/langgraph/stream_follow.py | 28 +++++- tests/agent/core/test_stream_cursor.py | 18 ++++ .../agent/langgraph/test_reconnect_values.py | 94 +++++++++++++++++++ 5 files changed, 167 insertions(+), 9 deletions(-) create mode 100644 tests/agent/langgraph/test_reconnect_values.py diff --git a/diagrid/agent/core/workflow/stream_cursor.py b/diagrid/agent/core/workflow/stream_cursor.py index 0a299a00..77fef3fd 100644 --- a/diagrid/agent/core/workflow/stream_cursor.py +++ b/diagrid/agent/core/workflow/stream_cursor.py @@ -9,6 +9,8 @@ units of ``base`` and later that were read in part, ``positions`` holds the attempt (its first 8 characters) and how many of its events were read, as base64url JSON. The id grows with one step's parallelism, not with the run. +A fourth part, ``.``, is the last step whose ``values`` chunk the +client has: every unit of a step logs that chunk, and it is sent once. ``v1.start`` replays from the beginning and ``v1.end`` means the final event was received. An id that does not parse replays from the start too. @@ -39,6 +41,8 @@ class StreamCursor: positions: Tuple[Position, ...] = () #: The client has the final event. at_end: bool = False + #: The last step whose ``values`` chunk the client has; ``None``: none. + values_through: Optional[int] = None def skips_step(self, step: int) -> bool: """Whether every unit of ``step`` was already read.""" @@ -56,13 +60,16 @@ def encode_cursor(cursor: StreamCursor) -> str: """The SSE id for ``cursor``.""" if cursor.at_end: return END_ID - if cursor.base is None and not cursor.positions: + if cursor.base is None and not cursor.positions and cursor.values_through is None: return START_ID payload = json.dumps( [list(p) for p in cursor.positions], separators=(",", ":") ).encode() packed = base64.urlsafe_b64encode(payload).decode().rstrip("=") - return f"{VERSION}.{cursor.base if cursor.base is not None else -2}.{packed}" + text = f"{VERSION}.{cursor.base if cursor.base is not None else -2}.{packed}" + if cursor.values_through is not None: + text += f".{cursor.values_through}" + return text def parse_cursor(text: Optional[str]) -> StreamCursor: @@ -76,8 +83,12 @@ def parse_cursor(text: Optional[str]) -> StreamCursor: def _parse(text: str) -> StreamCursor: - version, base, packed = text.split(".", 2) - if version != VERSION: + parts = text.split(".") + if len(parts) not in (3, 4): + raise ValueError(text) + version, base, packed = parts[:3] + values_through = int(parts[3]) if len(parts) == 4 else None + if version != VERSION or (values_through is not None and values_through < 0): raise ValueError(text) padded = packed + "=" * (-len(packed) % 4) raw = json.loads(base64.urlsafe_b64decode(padded.encode())) @@ -85,7 +96,11 @@ def _parse(text: str) -> StreamCursor: raise ValueError(text) positions = tuple(_position(p) for p in raw) step = int(base) - return StreamCursor(base=None if step == -2 else step, positions=positions) + return StreamCursor( + base=None if step == -2 else step, + positions=positions, + values_through=values_through, + ) def _position(item: object) -> Position: diff --git a/diagrid/agent/langgraph/stream_drain.py b/diagrid/agent/langgraph/stream_drain.py index 6cc75e48..a15c0f17 100644 --- a/diagrid/agent/langgraph/stream_drain.py +++ b/diagrid/agent/langgraph/stream_drain.py @@ -7,6 +7,7 @@ reconnect (``GET /agent/run/{id}/stream``, ``astream_resume``). """ +from dataclasses import replace from typing import Any, AsyncGenerator, Dict, List, Optional, Set, Tuple from diagrid.agent.core.workflow.stream import ( @@ -79,12 +80,15 @@ async def drain( ``branch_done`` marker) arrived, for ``stream_unavailable``. """ values_sent: Set[int] = set() + follower = source.follower while True: item = await next_item(source.sink, keepalive) if isinstance(item, StreamClosed): # Unregister before handing over the result: chunks a late # activity attempt writes from here on are dropped. await source.close() + if follower is not None: # the client had these before a reconnect + values_sent.update(range(follower.values_through + 1)) for event in closing_events( item, seen, @@ -94,6 +98,13 @@ async def drain( unavailable_reason=source.unavailable_reason, purged=source.purged, ): + if ( + follower is not None + and isinstance(event, StreamEvent) + and event.mode == VALUES + ): + # its own id: a reconnect from it does not send it again + event = replace(event, event_id=follower.event_id(event.step)) yield event return if isinstance(item, StreamEvent) and item.mode == BRANCH_DONE: diff --git a/diagrid/agent/langgraph/stream_follow.py b/diagrid/agent/langgraph/stream_follow.py index b97878c1..3dc3da17 100644 --- a/diagrid/agent/langgraph/stream_follow.py +++ b/diagrid/agent/langgraph/stream_follow.py @@ -144,6 +144,11 @@ def __init__( #: Units the client had in full or in part before this stream: the #: stream does not report them missing. self._seen = seen if seen is not None else set() + #: The last step whose ``values`` chunk went out (here or before a + #: reconnect): every unit of a step logs it, and it is sent once. + self.values_through = ( + -1 if self._cursor.values_through is None else self._cursor.values_through + ) self.purged = False #: Start after what the log holds when the follower starts (a resumed run). self._from_end = from_end @@ -299,6 +304,11 @@ async def _deliver(self, chunk: UnitChunk) -> None: state.consumed = chunk.start for wire in chunk.events: event = event_from_wire(wire, self._workflow_id, self._decode) + if event.mode == VALUES: + if event.step <= self.values_through: + state.consumed += 1 # another unit's copy already went out + continue + self.values_through = event.step await self._wait_for_room() key = (event.step, event.node) if state.replaced and event.mode != VALUES and key not in primed: @@ -312,18 +322,28 @@ async def _wait_for_room(self) -> None: while self._sink.backlog() >= BACKLOG_HIGH: await asyncio.sleep(0.01) - def event_id(self) -> str: - """The SSE id of the stream as it stands: a cursor any replica resumes.""" + def event_id(self, values_through: Optional[int] = None) -> str: + """The SSE id of the stream as it stands: a cursor any replica resumes. + + ``values_through`` is the step of a ``values`` chunk sent outside the + log (the run's final state), which the id then covers. + """ + values = max( + self.values_through, -1 if values_through is None else values_through + ) + through = None if values < 0 else values open_steps = [u[0] for u in self._order if not self._units[u].complete] if open_steps: base = min(open_steps) elif self._order: base = max(u[0] for u in self._order) else: - return encode_cursor(self._cursor) + return encode_cursor(replace(self._cursor, values_through=through)) positions = tuple( (step, unit, (state.attempt or "")[:ATTEMPT_PREFIX], state.consumed) for (step, unit) in self._order if step >= base and (state := self._units[(step, unit)]).consumed > 0 ) - return encode_cursor(StreamCursor(base=base, positions=positions)) + return encode_cursor( + StreamCursor(base=base, positions=positions, values_through=through) + ) diff --git a/tests/agent/core/test_stream_cursor.py b/tests/agent/core/test_stream_cursor.py index 30b3fee5..de0d46a9 100644 --- a/tests/agent/core/test_stream_cursor.py +++ b/tests/agent/core/test_stream_cursor.py @@ -67,3 +67,21 @@ def test_the_id_holds_only_open_steps(self): cursor = StreamCursor(base=5, positions=((5, "a", "12345678", 1),)) # small: grows with one step's parallelism, not with the run self.assertLess(len(encode_cursor(cursor)), 80) + + +class TestValuesThrough(unittest.TestCase): + def test_the_last_values_step_round_trips(self): + cursor = StreamCursor( + base=1, positions=((1, "a", "abcd1234", 2),), values_through=1 + ) + self.assertEqual(parse_cursor(encode_cursor(cursor)), cursor) + + def test_values_alone_is_not_the_start(self): + cursor = StreamCursor(values_through=0) + text = encode_cursor(cursor) + self.assertNotEqual(text, START_ID) + self.assertEqual(parse_cursor(text), cursor) + + def test_an_id_without_it_still_parses(self): + cursor = StreamCursor(base=2, positions=()) + self.assertIsNone(parse_cursor(encode_cursor(cursor)).values_through) diff --git a/tests/agent/langgraph/test_reconnect_values.py b/tests/agent/langgraph/test_reconnect_values.py new file mode 100644 index 00000000..631697db --- /dev/null +++ b/tests/agent/langgraph/test_reconnect_values.py @@ -0,0 +1,94 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A reconnect sends each ``values`` chunk once, whatever SSE id it resumes from. + +Every activity of a step offers the step's ``values`` chunk and the log keeps +each unit's copy, so the cursor carries the last step whose ``values`` the +client has; the final ``values`` chunk has its own id. +""" + +import operator +import time +from typing import Any + +from fastapi.testclient import TestClient +from langgraph.graph import END, START, StateGraph +from typing_extensions import Annotated, TypedDict + +from .log_helpers import log_runner +from .streaming_helpers import serve_app +from .test_reconnect_helpers import frames +from .test_runner import _RunnerTestCase + + +class _S(TypedDict, total=False): + log: Annotated[list, operator.add] + + +def _fan_out() -> Any: + def a(s: _S) -> dict: + return {"log": ["a"]} + + def b(s: _S) -> dict: + return {"log": ["b"]} + + def c(s: _S) -> dict: + return {"log": ["c"]} + + g = StateGraph(_S) + g.add_node("a", a) + g.add_node("b", b) + g.add_node("c", c) + g.add_edge(START, "a") + g.add_edge(START, "b") + g.add_edge("a", "c") + g.add_edge("b", "c") + g.add_edge("c", END) + return g.compile() + + +def _wait_done(runner: Any, wf: str) -> None: + deadline = time.monotonic() + 10 + while wf not in runner._workflow_client.done and time.monotonic() < deadline: + time.sleep(0.01) + + +class TestReconnectValues(_RunnerTestCase): + def test_reconnect_every_cut_values_parallel(self): + runner = log_runner(_fan_out(), "rv-fan") + http = TestClient(serve_app(runner)) + resp = http.post( + "/agent/run", + json={"log": ["x"], "stream": True, "stream_mode": ["values", "updates"]}, + ) + full = frames(resp.text) + self.assertEqual([e for _, e, _ in full].count("values"), 3) + wf = full[0][2]["workflow_id"] + _wait_done(runner, wf) + bad = [] + for cut in range(1, len(full) - 1): + got = frames( + http.get( + f"/agent/run/{wf}/stream", + params={"stream_mode": "values,updates"}, + headers={"Last-Event-ID": full[cut][0]}, + ).text + ) + rest = [(e, d) for _, e, d in got[1:]] + want = [(e, d) for _, e, d in full[cut + 1 :]] + if rest != want: + bad.append((cut, full[cut][1], [e for e, _ in rest])) + self.assertEqual(bad, []) + + def test_every_values_chunk_has_its_own_id(self): + runner = log_runner(_fan_out(), "rv-ids") + http = TestClient(serve_app(runner)) + full = frames( + http.post( + "/agent/run", + json={"log": ["x"], "stream": True, "stream_mode": ["values"]}, + ).text + ) + ids = [i for i, e, _ in full if e == "values"] + self.assertEqual(len(ids), len(set(ids))) From 0f32deaae3dc149842922d94de72653461b2a406 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 15:47:21 +0100 Subject: [PATCH 51/73] fix(langgraph): keep streaming after a purged part of the log A run that waited on interrupt() longer than the batch TTL lost its first steps' chunks, and a reconnect stopped at stream_purged with nothing live after the resume. The follower now skips a purged unit (keeping it open for a later attempt), says stream_purged once, and streams what is still in the log and what comes live. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 8 +- diagrid/agent/langgraph/stream_follow.py | 23 +++++- tests/agent/langgraph/test_reconnect_purge.py | 78 +++++++++++++++++++ 3 files changed, 103 insertions(+), 6 deletions(-) create mode 100644 tests/agent/langgraph/test_reconnect_purge.py diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index ae0b278d..748a0d9f 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -173,7 +173,7 @@ objects (`kind`, `data`): | `workflow_started` | `{"workflow_id", "thread_id"}` | The first event, sent once the workflow has been scheduled, so `GET /agent/run/{workflow_id}` finds the run as soon as the event arrives (a run that could not be scheduled ends with `workflow_failed` and has none): the ids to use with `terminate_workflow` or `get_workflow_status`. Delivered only to `on_control`, never yielded. | | `node_reset` | `{"node", "step"}`, plus `"path"` for a `Send` task | A node was retried; drop its partial output. `node` and `step` are the `langgraph_node` and `langgraph_step` of that node's `messages` metadata (`step` is numbered from 1). A task started by a `Send` also carries `path`, the `langgraph_path` of its chunks (`["__pregel_push", index, false]`), which tells apart the tasks of one node in a step. A retry of a conditional edge's function also carries `branch`, the edge's function name. The function runs inside its node's activity, before the node's `updates` chunk, as in LangGraph; if it raises there, it runs again in an activity of its own, after that chunk, and only what the function sent is stale, not the node's own output. | | `stream_unavailable` | `{"workflow_id", "reason", "missing_steps", "missing_nodes"}` | The run finished but a node's chunks never arrived (see the limit below). `missing_nodes` is a list of `{"step", "node"}`, one per node of a step that streamed nothing, even when other nodes of that step did. Steps are numbered from 1, like `langgraph_step`. A `Send` task is named `node#k` there (`k` is its position among the step's `Send` tasks). A conditional edge's function that ran in an activity of its own (a START edge's, or one that raised inside its node's activity and ran again) is listed as `node:branch:` (`node#k:branch:` after a `Send` task, `__start__:branch:` at step 0 for a START edge), where `` is the name the runner registered the edge under. | -| `stream_purged` | `{"workflow_id", "step"}` | A reconnect or a late reader found that the run's event log outlived its TTL (state-store transport only): what is left cannot be replayed. The final event follows. | +| `stream_purged` | `{"workflow_id", "step"}` | A reconnect or a late reader found that part of the run's event log outlived its TTL (state-store transport only), from `step` on: those chunks cannot be replayed. Sent once; the chunks still in the log, the live ones and the final event follow. | | `thread_not_saved` | `{"workflow_id", "thread_id", "error"}` | The run ended, but its thread's state could not be saved (after retries), so the next run on the thread starts from the state before this one. The run's output stands: the final event follows, with `thread_saved: false` and `thread_error`, which a plain `POST /agent/run` and `GET /agent/run/{workflow_id}` return too. | | `stream_dropped` | `{"dropped": n}` | The consumer fell behind and `n` token or custom chunks were dropped. `updates` are never dropped. | @@ -280,8 +280,10 @@ as its log is kept (an hour by default). `stream_mode` (repeat the parameter, or separate modes with commas) picks the chunks as on `POST`; an unsupported one is a `422`, and an unknown run a `404`. If a node was retried after the client saw part of its output, the stream sends `node_reset` for it before the -new attempt's chunks. If the log has expired, the stream sends -`stream_purged` and then the final event. +new attempt's chunks. If part of the log has expired, the stream sends +`stream_purged` once and goes on with what is still there and what comes +live (a run resumed after waiting on `interrupt()` for longer than the batch +TTL streams everything after the resume), then the final event. On the in-process transport nothing can be replayed: the endpoint answers with `workflow_started`, then `stream_unavailable` with reason diff --git a/diagrid/agent/langgraph/stream_follow.py b/diagrid/agent/langgraph/stream_follow.py index 3dc3da17..722a6227 100644 --- a/diagrid/agent/langgraph/stream_follow.py +++ b/diagrid/agent/langgraph/stream_follow.py @@ -222,7 +222,7 @@ async def skip_to_end(self) -> None: self._seen.add((chunk.step, chunk.unit)) async def _read_once(self, final: Optional[Dict[str, Any]]) -> None: - if self.purged or self._cursor.at_end: + if self._cursor.at_end: return status = final if final is not None else await asyncio.to_thread(self._status) self._learn(units_of(status or {})) @@ -243,7 +243,7 @@ async def _read_once(self, final: Optional[Dict[str, Any]]) -> None: for chunk in chunks: if chunk.purged: self._purge(chunk) - return + continue await self._deliver(chunk) def _learn(self, units: List[Unit]) -> None: @@ -265,9 +265,26 @@ def _learn(self, units: List[Unit]) -> None: self._order.sort(key=lambda u: u[0]) def _purge(self, chunk: UnitChunk) -> None: + """A unit whose batches expired: skip what is gone, read on from there. + + A run that waited on ``interrupt()`` past the batch TTL lost its first + steps' chunks, but what came after the resume is in the log: the + stream says ``stream_purged`` once and goes on. The unit stays open, so + a later attempt of it (the resumed task) is read from its start. + """ + state = self._units[(chunk.step, chunk.unit)] + state.attempt = chunk.attempt + state.from_batch = chunk.batches + state.consumed = state.total = chunk.total + state.skip = 0 + state.done = chunk.done + self._seen.add((chunk.step, chunk.unit)) + if self.purged: + return self.purged = True logger.warning( - "The stream log of %s is purged (unit %s of step %s): it outlived its TTL", + "The stream log of %s is purged (unit %s of step %s): it outlived its " + "TTL; streaming what is left", self._workflow_id, chunk.unit, chunk.step, diff --git a/tests/agent/langgraph/test_reconnect_purge.py b/tests/agent/langgraph/test_reconnect_purge.py new file mode 100644 index 00000000..fd6d4ae8 --- /dev/null +++ b/tests/agent/langgraph/test_reconnect_purge.py @@ -0,0 +1,78 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A stream whose oldest log batches expired goes on with what is still there. + +A run that waited on ``interrupt()`` longer than the log's batch TTL has lost +the chunks of its first steps, but everything after the resume is fresh: a +reconnect says ``stream_purged`` and then streams the rest, live. +""" + +import operator +import time +from typing import Any + +from fastapi.testclient import TestClient +from langgraph.graph import END, START, StateGraph +from langgraph.types import interrupt +from typing_extensions import Annotated, TypedDict + +from ..core.log_store_fake import FakeLogStore +from .log_helpers import log_runner +from .streaming_helpers import serve_app +from .test_reconnect_helpers import frames +from .test_runner import _RunnerTestCase + + +class _S(TypedDict, total=False): + log: Annotated[list, operator.add] + + +def _graph() -> Any: + def first(s: _S) -> dict: + return {"log": ["first"]} + + def ask(s: _S) -> dict: + return {"log": [f"ask:{interrupt('go?')}"]} + + def after(s: _S) -> dict: + return {"log": ["after"]} + + g = StateGraph(_S) + g.add_node("first", first) + g.add_node("ask", ask) + g.add_node("after", after) + g.add_edge(START, "first") + g.add_edge("first", "ask") + g.add_edge("ask", "after") + g.add_edge("after", END) + return g.compile() + + +def _expire_batches(store: FakeLogStore, step: int, unit: str) -> None: + """What the batch TTL does: the batches go, the (longer-lived) head stays.""" + for key in store.keys_like(f":{step}:{unit}:"): + if not key.endswith(":head"): + store.delete(key) + + +class TestPurgedThenLive(_RunnerTestCase): + def test_a_reconnect_after_a_long_interrupt_streams_the_rest(self): + store = FakeLogStore() + runner = log_runner(_graph(), "purge-live", store=store) + http = TestClient(serve_app(runner)) + got = frames(http.post("/agent/run", json={"log": [], "stream": True}).text) + self.assertEqual(got[-1][1], "workflow_interrupted") + wf = got[-1][2]["workflow_id"] + _expire_batches(store, 0, "first") + http.post(f"/agent/run/{wf}/resume", json={"resume": "yes"}) + deadline = time.monotonic() + 10 + while wf not in runner._workflow_client.done and time.monotonic() < deadline: + time.sleep(0.01) + again = frames(http.get(f"/agent/run/{wf}/stream").text) + names = [e for _, e, _ in again] + self.assertIn("stream_purged", names) + updates = [list(d)[0] for _, e, d in again if e == "updates"] + self.assertEqual(updates, ["ask", "after"]) + self.assertEqual(names[-1], "workflow_completed") + self.assertEqual(names.count("stream_purged"), 1) From e7ace69bf0282784013090eaffb03f0e843eac66 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 15:59:49 +0100 Subject: [PATCH 52/73] fix(langgraph): stream the attempt of a node whose output the run used When Dapr ran a node's activity twice (a lost completion, or two at once), the stream log kept the first attempt that finished while the workflow could use the other one's output, so stream and state disagreed. Now every attempt logs its batches and an end record (a late one leaves the head alone), the activity output names its attempt, the workflow publishes the attempt it used per unit in its custom status and output, and the reader follows that attempt, resetting a unit it streamed from another one. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/stream.py | 13 +++ diagrid/agent/core/workflow/stream_log.py | 64 +++++++---- diagrid/agent/langgraph/README.md | 9 ++ diagrid/agent/langgraph/activity_stream.py | 3 + diagrid/agent/langgraph/models.py | 16 +++ diagrid/agent/langgraph/stream_attempts.py | 47 ++++++++ diagrid/agent/langgraph/stream_drain.py | 2 + diagrid/agent/langgraph/stream_events.py | 2 +- diagrid/agent/langgraph/stream_follow.py | 24 ++++ diagrid/agent/langgraph/workflow.py | 17 ++- tests/agent/core/test_stream_log.py | 35 +++++- tests/agent/langgraph/test_stream_winner.py | 115 ++++++++++++++++++++ 12 files changed, 317 insertions(+), 30 deletions(-) create mode 100644 diagrid/agent/langgraph/stream_attempts.py create mode 100644 tests/agent/langgraph/test_stream_winner.py diff --git a/diagrid/agent/core/workflow/stream.py b/diagrid/agent/core/workflow/stream.py index ca93e7f4..4af0ff08 100644 --- a/diagrid/agent/core/workflow/stream.py +++ b/diagrid/agent/core/workflow/stream.py @@ -219,6 +219,19 @@ def backlog(self) -> int: """Items waiting for the consumer.""" return self._queue.qsize() + def reopen(self, step: int, node: str, attempt_id: str) -> None: + """Let another attempt of ``(step, node)`` in, after ``attempt_id``'s. + + A log reader learns late which attempt's output the run used; when it + is not the one already streamed (even in full), the next attempt's + first chunk sends ``node_reset`` and its chunks are kept. + """ + key = (step, node) + with self._lock: + self._finished.pop(key, None) + self._owner[key] = attempt_id + self._retired.discard((key, attempt_id)) + def prime(self, step: int, node: str, attempt_id: str) -> None: """Take ``attempt_id`` as the owner of ``(step, node)`` without a chunk. diff --git a/diagrid/agent/core/workflow/stream_log.py b/diagrid/agent/core/workflow/stream_log.py index 582213ed..91be763a 100644 --- a/diagrid/agent/core/workflow/stream_log.py +++ b/diagrid/agent/core/workflow/stream_log.py @@ -13,12 +13,17 @@ longer than the batches. - ``:::::``: batch ``n`` of an attempt, a list of events. +- ``:::::end``: the head of an attempt that + finished, as it was when it did (kept as long as the head). A retried activity is a new attempt: it takes the head over, and a reader that sees the attempt change starts that unit again (the consumer turns that into -``node_reset``). An attempt that finished (``done``) keeps the unit: a late -attempt is not written. A head whose count names a batch that is gone means -the log outlived its TTL: the reader reports it purged. +``node_reset``). An attempt that finished (``done``) keeps the head: a late +attempt (Dapr ran the activity again) logs its batches and its end record but +leaves the head alone. The workflow says which attempt's output it used (the +*winner*); a reader told the winner reads it through its end record. A head +whose count names a batch that is gone means the log outlived its TTL: the +reader reports it purged. """ import itertools @@ -127,6 +132,11 @@ def head_key(prefix: str, workflow_id: str, step: int, unit: str) -> str: return f"{_unit_prefix(prefix, workflow_id, step, unit)}:head" +def end_key(prefix: str, workflow_id: str, step: int, unit: str, attempt: str) -> str: + base = _unit_prefix(prefix, workflow_id, step, unit) + return f"{base}:{escape_key_part(attempt)}:end" + + def batch_key( prefix: str, workflow_id: str, step: int, unit: str, attempt: str, n: int ) -> str: @@ -280,10 +290,6 @@ def _flush(self, *, done: bool, final: bool = False) -> bool: batch = list(self._pending) if not batch and not final: return True - if self._is_blocked(): - with self._buffer_lock: - del self._pending[: len(batch)] - return True items: List[LogItem] = [] if batch: items.append( @@ -309,18 +315,17 @@ def _flush(self, *, done: bool, final: bool = False) -> bool: "events": self._events + len(batch), "done": done, } - items.append( - ( - head_key( - self._config.key_prefix, - self._workflow_id, - self._step, - self._unit, - ), - head, - _ttl(self._config.event_ttl_s * self._config.record_ttl_factor), - ) + record_ttl = _ttl(self._config.event_ttl_s * self._config.record_ttl_factor) + prefix = ( + self._config.key_prefix, + self._workflow_id, + self._step, + self._unit, ) + if not self._is_blocked(): + items.append((head_key(*prefix), head, record_ttl)) + if done: + items.append((end_key(*prefix, self.attempt), head, record_ttl)) try: self._store.save_bulk(items) except Exception as e: # never fail the node over its stream @@ -376,6 +381,9 @@ class UnitWant: from_batch: int = 0 #: Events of the batches from ``from_batch`` on that it already has. skip_events: int = 0 + #: The attempt whose output the workflow used, once it is known: it is + #: read (through its end record) whatever attempt holds the head. + winner: Optional[str] = None @dataclass(frozen=True) @@ -417,10 +425,21 @@ def __init__( def read(self, wants: Sequence[UnitWant]) -> List[UnitChunk]: prefix = self._config.key_prefix head_keys = [head_key(prefix, self._workflow_id, w.step, w.unit) for w in wants] - heads = self._store.get_bulk(head_keys) if head_keys else {} + end_keys = { + i: end_key(prefix, self._workflow_id, w.step, w.unit, w.winner) + for i, w in enumerate(wants) + if w.winner + } + wanted_heads = [*head_keys, *end_keys.values()] + heads = self._store.get_bulk(wanted_heads) if wanted_heads else {} plans: List[Tuple[UnitWant, Dict[str, Any], bool, List[str]]] = [] - for want, key in zip(wants, head_keys): + for i, (want, key) in enumerate(zip(wants, head_keys)): head = heads.get(key) + won = heads.get(end_keys[i]) if i in end_keys else None + if isinstance(won, dict) and not _same_attempt( + str((head or {}).get("attempt")), str(want.winner) + ): + head = won # the head is another attempt's: read the winner if not isinstance(head, dict): plans.append((want, {}, False, [])) continue @@ -541,3 +560,8 @@ def writer( def reader(self, workflow_id: str) -> LogReader: return LogReader(self.store, self.config, workflow_id) + + +def _same_attempt(a: str, b: str) -> bool: + """Whether two attempt ids (or a cursor's prefix of one) name one attempt.""" + return bool(a) and bool(b) and (a.startswith(b) or b.startswith(a)) diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 748a0d9f..ad8e29be 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -394,6 +394,15 @@ needed for this. that was connected saw the first attempt's chunks and then `node_reset`; a replay from the start (or a reconnect from before the retry) has the attempt that finished only. +- **The stream follows the attempt the run used.** Dapr may run a node's + activity twice even when the first run succeeded (its completion got lost), + or run two attempts at once. Each attempt logs its own chunks, and the run + records which attempt's output it used. On the state-store transport the + stream ends on that attempt: a connected client that saw the other one gets + `node_reset` for the node (possibly after the next step's first chunks, as + the run says which attempt it used when that step starts) and then the used + attempt's chunks; a replay has the used attempt only. The in-process + transport keeps the first attempt that finished. - **Node code must not count attempts in process memory.** A retried node may run in another process, so a counter kept in a module or a closure does not see the earlier attempt. Keep such state in the graph's state or a store. diff --git a/diagrid/agent/langgraph/activity_stream.py b/diagrid/agent/langgraph/activity_stream.py index adcc212d..3dbd3c2b 100644 --- a/diagrid/agent/langgraph/activity_stream.py +++ b/diagrid/agent/langgraph/activity_stream.py @@ -57,11 +57,14 @@ def run_status(run: Any) -> Dict[str, Any]: """The custom status of a run: what a stream reader needs to find its units, and the interrupt the run waits on.""" from .interrupts import STATUS_INTERRUPT, STATUS_INTERRUPT_SEQ + from .stream_attempts import STATUS_ATTEMPTS status: Dict[str, Any] = {} if (run.config or {}).get(STREAM_RUN_KEY): status[STATUS_EXECUTED] = run.executed status[STATUS_BRANCHES] = run.branches + if run.attempts: + status[STATUS_ATTEMPTS] = run.attempts if run.interrupt_seq: status[STATUS_INTERRUPT_SEQ] = run.interrupt_seq if run.interrupt: diff --git a/diagrid/agent/langgraph/models.py b/diagrid/agent/langgraph/models.py index c00bacab..2dd0e25f 100644 --- a/diagrid/agent/langgraph/models.py +++ b/diagrid/agent/langgraph/models.py @@ -339,6 +339,8 @@ class ExecuteNodeOutput: #: The task called ``interrupt()``: ``[{"id", "value"}]``; it wrote nothing #: and runs again when the run is resumed. interrupts: Optional[List[Dict[str, Any]]] = None + #: The attempt this execution logged its stream chunks under, if any. + stream_attempt: Optional[str] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -359,6 +361,8 @@ def to_dict(self) -> Dict[str, Any]: data["route_error"] = self.route_error if self.interrupts: data["interrupts"] = list(self.interrupts) + if self.stream_attempt: + data["stream_attempt"] = self.stream_attempt return data @classmethod @@ -374,6 +378,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "ExecuteNodeOutput": route_sends=list(data.get("route_sends") or []), route_error=data.get("route_error"), interrupts=data.get("interrupts"), + stream_attempt=data.get("stream_attempt"), ) @@ -464,6 +469,8 @@ class EvaluateConditionOutput: next_nodes: List[str] = field(default_factory=list) error: Optional[str] = None sends: List[Dict[str, Any]] = field(default_factory=list) + #: The attempt this execution logged its stream chunks under, if any. + stream_attempt: Optional[str] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -472,6 +479,8 @@ def to_dict(self) -> Dict[str, Any]: } if self.sends: data["sends"] = list(self.sends) + if self.stream_attempt: + data["stream_attempt"] = self.stream_attempt return data @classmethod @@ -480,6 +489,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "EvaluateConditionOutput": next_nodes=data.get("next_nodes", []), error=data.get("error"), sends=list(data.get("sends") or []), + stream_attempt=data.get("stream_attempt"), ) @@ -575,6 +585,9 @@ class GraphWorkflowOutput: branches: Optional[List[List[Any]]] = None thread_saved: Optional[bool] = None thread_error: Optional[str] = None + #: The attempt of each unit's output the run used (``":"``), + #: for the stream only. + attempts: Optional[Dict[str, str]] = None def to_dict(self) -> Dict[str, Any]: data: Dict[str, Any] = { @@ -593,6 +606,8 @@ def to_dict(self) -> Dict[str, Any]: if self.thread_saved is not None: data["thread_saved"] = self.thread_saved data["thread_error"] = self.thread_error + if self.attempts: + data["attempts"] = dict(self.attempts) return data @classmethod @@ -610,4 +625,5 @@ def from_dict(cls, data: Dict[str, Any]) -> "GraphWorkflowOutput": branches=data.get("branches"), thread_saved=data.get("thread_saved"), thread_error=data.get("thread_error"), + attempts=data.get("attempts"), ) diff --git a/diagrid/agent/langgraph/stream_attempts.py b/diagrid/agent/langgraph/stream_attempts.py new file mode 100644 index 00000000..65e48a2a --- /dev/null +++ b/diagrid/agent/langgraph/stream_attempts.py @@ -0,0 +1,47 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Which attempt of each unit the run used, so its stream shows that one. + +Dapr runs an activity at least once: a completion that got lost is run again, +and two attempts may even run at once. Each attempt logs its own chunks; the +activity's output names its attempt, the workflow keeps the attempt of the +output it used per unit (``":"``), and publishes them with the +units in its custom status and its output. A stream reader follows that +attempt (``UnitWant.winner``), whatever attempt holds the unit's head. +""" + +from typing import Any, Dict, Iterable, Optional + +#: Custom status (and stream-only output) key: the attempt each unit used. +STATUS_ATTEMPTS = "attempts" + + +def unit_key(step: int, unit: str) -> str: + return f"{step}:{unit}" + + +def with_attempt(output: Dict[str, Any], writer: Any) -> Dict[str, Any]: + """An activity's output naming the attempt its chunks were logged under.""" + attempt = getattr(writer, "attempt", None) + if not isinstance(attempt, str) or not attempt: + return output + return {**output, "stream_attempt": attempt} + + +def record_attempts( + attempts: Dict[str, str], step: int, units: Iterable[str], outputs: Iterable[Any] +) -> None: + """Keep the attempt of each unit's output (workflow code: no I/O).""" + for unit, output in zip(units, outputs): + attempt = getattr(output, "stream_attempt", None) + if attempt: + attempts[unit_key(step, unit)] = attempt + + +def attempts_of(status: Optional[Dict[str, Any]]) -> Dict[str, str]: + """The attempts a custom status or a final event names, by unit key.""" + found = (status or {}).get(STATUS_ATTEMPTS) + if not isinstance(found, dict): + return {} + return {str(k): str(v) for k, v in found.items() if v} diff --git a/diagrid/agent/langgraph/stream_drain.py b/diagrid/agent/langgraph/stream_drain.py index a15c0f17..ac27c04f 100644 --- a/diagrid/agent/langgraph/stream_drain.py +++ b/diagrid/agent/langgraph/stream_drain.py @@ -30,6 +30,7 @@ encode_chunk, next_item, ) +from .stream_attempts import STATUS_ATTEMPTS from .stream_source import StreamSource from .streaming import BRANCHES_KEY, EXECUTED_KEY, FINAL_STATE_KEY @@ -58,6 +59,7 @@ def parse_output( ), **({EXECUTED_KEY: output.executed} if streamed and output.executed else {}), **({BRANCHES_KEY: output.branches} if streamed and output.branches else {}), + **({STATUS_ATTEMPTS: output.attempts} if streamed and output.attempts else {}), **( {FINAL_STATE_KEY: output.channel_state.to_dict()} if streamed and output.channel_state is not None diff --git a/diagrid/agent/langgraph/stream_events.py b/diagrid/agent/langgraph/stream_events.py index aff8c3a4..b77a7fb4 100644 --- a/diagrid/agent/langgraph/stream_events.py +++ b/diagrid/agent/langgraph/stream_events.py @@ -111,7 +111,7 @@ def started_event(workflow_id: str, thread_id: str) -> Any: ) -_STREAM_ONLY_KEYS = (EXECUTED_KEY, BRANCHES_KEY, FINAL_STATE_KEY) +_STREAM_ONLY_KEYS = (EXECUTED_KEY, BRANCHES_KEY, FINAL_STATE_KEY, "attempts") def without_executed(event: Dict[str, Any]) -> Dict[str, Any]: diff --git a/diagrid/agent/langgraph/stream_follow.py b/diagrid/agent/langgraph/stream_follow.py index 722a6227..e9103ba0 100644 --- a/diagrid/agent/langgraph/stream_follow.py +++ b/diagrid/agent/langgraph/stream_follow.py @@ -37,6 +37,7 @@ from .activity_stream import STATUS_BRANCHES, STATUS_EXECUTED from .interrupts import INTERRUPT_KEY, as_interrupts +from .stream_attempts import attempts_of, unit_key from .stream_events import encode_chunk, stream_failure_event from .streaming import BRANCHES_KEY, EXECUTED_KEY, SUPPORTED_MODES @@ -96,6 +97,11 @@ def units_of(status: Dict[str, Any]) -> List[Unit]: return ordered +def _same_attempt(a: str, b: str) -> bool: + """Whether two attempt ids (or a cursor's prefix of one) name one attempt.""" + return bool(a) and bool(b) and (a.startswith(b) or b.startswith(a)) + + @dataclass class _UnitState: """How far the stream got in one unit.""" @@ -110,9 +116,19 @@ class _UnitState: total: int = 0 #: The attempt an earlier client saw part of, when it was replaced. replaced: Optional[str] = None + #: The attempt whose output the run used, once the workflow said so. + winner: Optional[str] = None @property def complete(self) -> bool: + # read another attempt, but the run used the winner: read that one + # (a step a cursor skips whole has no attempt here: it was read) + if ( + self.winner + and self.attempt + and not _same_attempt(self.attempt, self.winner) + ): + return False return self.done and self.consumed >= self.total @@ -226,6 +242,9 @@ async def _read_once(self, final: Optional[Dict[str, Any]]) -> None: return status = final if final is not None else await asyncio.to_thread(self._status) self._learn(units_of(status or {})) + winners = attempts_of(status) + for key, state in self._units.items(): + state.winner = winners.get(unit_key(*key), state.winner) wants = [ UnitWant( unit[0], @@ -233,6 +252,7 @@ async def _read_once(self, final: Optional[Dict[str, Any]]) -> None: attempt=state.attempt, from_batch=state.from_batch, skip_events=state.skip, + winner=state.winner, ) for unit in self._order if not (state := self._units[unit]).complete @@ -312,6 +332,10 @@ async def _deliver(self, chunk: UnitChunk) -> None: # in this stream must tell the client to drop that part had = state.consumed > 0 state.replaced = state.attempt if had else None + if had and state.attempt: + # the sink may have closed the unit on the old attempt's updates + for node in {str(w.get("node")) for w in chunk.events}: + self._sink.reopen(chunk.step, node, state.attempt) primed: Set[Tuple[int, str]] = set() state.attempt = chunk.attempt state.from_batch = chunk.batches diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index bc9a4dda..52a4a710 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -86,6 +86,7 @@ _has_async_entry, _invoke_runnable, ) +from .stream_attempts import record_attempts, with_attempt from .stream_values import state_values from .streaming import STREAM_RUN_KEY, NodeStreamer, StaticConfig from .task_identity import TaskIdentity @@ -556,6 +557,8 @@ class _Run: interrupt: Optional[Dict[str, Any]] = None #: How many times the run was interrupted so far. interrupt_seq: int = 0 + #: The attempt of each unit's output the run used (see ``stream_attempts``). + attempts: Dict[str, str] = field(default_factory=dict) @property def output_channels(self) -> Optional[List[str]]: @@ -578,6 +581,7 @@ def finish( steps=step, executed=self.executed, branches=self.branches or None, + attempts=self.attempts or None, status=status, **({"error": error} if error else {}), ).to_dict() @@ -719,6 +723,7 @@ def _run_step( lambda resumes: _rerun_nodes(run, nodes, sends, step, resumes), publish_run_status, ) + record_attempts(run.attempts, step, run.executed[-1], outputs) failed = next((o for o in outputs if o.error), None) if failed: return [], [], f"Node '{failed.node_name}' failed: {failed.error}" @@ -1058,6 +1063,7 @@ def _follow_edge( retry_policy=run.retry_policy, ) output = EvaluateConditionOutput.from_dict(cond_result) + record_attempts(run.attempts, step, [_branch_key(cond_input)], [output]) if output.error: return output.error found.add_nodes(output.next_nodes) @@ -1569,13 +1575,14 @@ def execute_node_activity( interrupts = interrupt_payloads(paused) if call.streamer: call.streamer.interrupted(interrupts) - return ExecuteNodeOutput( - node_name=node_name, interrupts=interrupts - ).to_dict() + return with_attempt( + ExecuteNodeOutput(node_name=node_name, interrupts=interrupts).to_dict(), + writer, + ) except DroppedInterrupt as e: # retrying would drop it again return ExecuteNodeOutput(node_name=node_name, error=str(e)).to_dict() done = True - return output + return with_attempt(output, writer) finally: if writer is not None: # synchronous: the unit's log is complete before the activity returns @@ -1733,7 +1740,7 @@ def evaluate_condition_activity( except GraphInterrupt: output = EvaluateConditionOutput(error=ROUTER_INTERRUPT_ERROR).to_dict() done = True - return output + return with_attempt(output, writer) finally: if writer is not None: writer.finish(done=done) diff --git a/tests/agent/core/test_stream_log.py b/tests/agent/core/test_stream_log.py index fe9be2fc..3ed547e5 100644 --- a/tests/agent/core/test_stream_log.py +++ b/tests/agent/core/test_stream_log.py @@ -18,6 +18,7 @@ StateLogStreamConfig, UnitWant, batch_key, + end_key, escape_key_part, head_key, wire_event, @@ -99,8 +100,10 @@ def test_every_save_carries_a_ttl_and_heads_outlive_batches(self): batch = batch_key("lgstream", "wf:1", 0, "research#0", writer.attempt, 0) head = head_key("lgstream", "wf:1", 0, "research#0") self.assertEqual(store.metadata[batch], {"ttlInSeconds": "100"}) + end = end_key("lgstream", "wf:1", 0, "research#0", writer.attempt) self.assertEqual(store.metadata[head], {"ttlInSeconds": "2400"}) - self.assertEqual(store.saves, [[batch, head]]) + self.assertEqual(store.metadata[end], {"ttlInSeconds": "2400"}) + self.assertEqual(store.saves, [[batch, head, end]]) def test_a_write_error_never_raises_and_is_retried(self): store = FakeLogStore() @@ -162,16 +165,40 @@ def test_a_new_attempt_takes_over_the_unit(self): head = store.get(head_key("lgstream", "wf:1", 0, "research#0")) self.assertEqual(head["attempt"], second.attempt) - def test_a_done_unit_blocks_a_late_attempt(self): + def test_a_late_attempt_keeps_the_head_but_logs_its_own_chunks(self): store = FakeLogStore() first = _writer(store) - first.put(_event("research#0", 0)) + first.put(_event("research#0", 0, attempt="a1")) first.finish(done=True) late = _writer(store) - late.put(_event("research#0", 0)) + late.put(_event("research#0", 0, attempt="a2")) + late.put(_event("research#0", 1, attempt="a2")) late.finish(done=True) head = store.get(head_key("lgstream", "wf:1", 0, "research#0")) self.assertEqual(head["attempt"], first.attempt) + # the workflow used the late attempt: a reader told so reads it + reader = LogReader(store, _config(), "wf:1") + chunk = reader.read( + [UnitWant(0, "research#0", attempt=first.attempt[:8], winner=late.attempt)] + )[0] + self.assertTrue(chunk.reset) + self.assertTrue(chunk.done) + self.assertEqual(chunk.attempt, late.attempt) + self.assertEqual(_datas(chunk), ["research#0-0", "research#0-1"]) + + def test_a_reader_follows_the_winner_of_concurrent_attempts(self): + store = FakeLogStore() + a = _writer(store) + b = _writer(store) + a.put(_event("research#0", 0, attempt="a")) + b.put(_event("research#0", 5, attempt="b")) + b.finish(done=True) + a.finish(done=True) + reader = LogReader(store, _config(), "wf:1") + for winner, want in ((a, ["research#0-0"]), (b, ["research#0-5"])): + chunk = reader.read([UnitWant(0, "research#0", winner=winner.attempt)])[0] + self.assertEqual(chunk.attempt, winner.attempt) + self.assertEqual(_datas(chunk), want) def test_events_keep_their_identity_on_the_wire(self): event = StreamEvent( diff --git a/tests/agent/langgraph/test_stream_winner.py b/tests/agent/langgraph/test_stream_winner.py new file mode 100644 index 00000000..783b54e0 --- /dev/null +++ b/tests/agent/langgraph/test_stream_winner.py @@ -0,0 +1,115 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The stream follows the attempt of a node whose output the workflow used. + +Dapr may run an activity twice (a completion that got lost, a redelivery) and +the workflow uses one of the results. The stream must show that attempt's +chunks, so what a client saw and the run's state agree. +""" + +import json +import operator +import threading +from typing import Any +from unittest import mock + +from fastapi.testclient import TestClient +from langgraph.graph import END, START, StateGraph +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph.models import GraphWorkflowInput + +from .log_helpers import LogClient, StatusCtx, log_runner +from .streaming_helpers import serve_app +from .test_reconnect_helpers import frames +from .test_runner import _RunnerTestCase + + +class _S(TypedDict, total=False): + log: Annotated[list, operator.add] + + +def _graph() -> Any: + runs = {"n": 0} + lock = threading.Lock() + + def flaky(s: _S) -> dict: + with lock: + runs["n"] += 1 + n = runs["n"] + return {"log": [f"attempt-{n}"]} + + def after(s: _S) -> dict: + return {"log": ["after"]} + + g = StateGraph(_S) + g.add_node("flaky", flaky) + g.add_node("after", after) + g.add_edge(START, "flaky") + g.add_edge("flaky", "after") + g.add_edge("after", END) + return g.compile() + + +class _RedeliverCtx(StatusCtx): + """Runs ``flaky``'s activity twice and hands the workflow the second result.""" + + def call_activity(self, activity: Any, *, input: Any, retry_policy: Any = None): + out = super().call_activity(activity, input=input, retry_policy=retry_policy) + if isinstance(input, dict) and input.get("node_name") == "flaky": + out = super().call_activity( + activity, input=input, retry_policy=retry_policy + ) + return out + + +class _RedeliverClient(LogClient): + def _work(self, input: Any, instance_id: str) -> None: + from diagrid.agent.langgraph.workflow import agent_workflow + + wf_input = GraphWorkflowInput.from_dict(json.loads(json.dumps(input))) + ctx = _RedeliverCtx(self._activity_runner, instance_id, self) + with mock.patch("diagrid.agent.langgraph.workflow.when_all", side_effect=list): + workflow = agent_workflow(ctx, json.loads(json.dumps(wf_input.to_dict()))) + result = None + try: + while True: + result = workflow.send(result) + except StopIteration as stop: + self.done[instance_id] = stop.value + + +def _flaky_updates(got: Any) -> list: + return [d["flaky"]["log"] for _, e, d in got if e == "updates" and "flaky" in d] + + +class TestWinningAttempt(_RunnerTestCase): + def _run(self, name: str) -> Any: + runner = log_runner(_graph(), name) + runner._workflow_client = _RedeliverClient(runner) # type: ignore[assignment] + http = TestClient(serve_app(runner)) + got = frames( + http.post( + "/agent/run", + json={"log": [], "stream": True, "stream_mode": ["updates"]}, + ).text + ) + return http, got + + def test_a_live_stream_ends_on_the_attempt_the_run_used(self): + _, got = self._run("winner-live") + output = got[-1][2]["output"]["log"] + self.assertEqual(output, ["attempt-2", "after"]) + self.assertEqual(_flaky_updates(got)[-1], ["attempt-2"]) + if len(_flaky_updates(got)) > 1: # the first attempt was seen: reset it + self.assertIn("node_reset", [e for _, e, _ in got]) + + def test_a_replay_shows_only_the_attempt_the_run_used(self): + http, got = self._run("winner-replay") + wf = got[0][2]["workflow_id"] + again = frames( + http.get(f"/agent/run/{wf}/stream", params={"stream_mode": "updates"}).text + ) + self.assertEqual(_flaky_updates(again), [["attempt-2"]]) + self.assertNotIn("node_reset", [e for _, e, _ in again]) From 08bade751dcab9c82e36332444600234033d7894 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 16:03:39 +0100 Subject: [PATCH 53/73] fix(langgraph): answer 409 to a resume another request beat to the run Two concurrent POST /resume calls for one interrupt both passed the pending check; the workflow took the first and ignored the second, yet its caller got the run's result. Each resume now carries an id, the workflow publishes the id it took in its custom status, and a caller whose resume was ignored gets ResumeConflict: a 409, before any event of a streamed resume. invoke(Command(resume=...)) checks the same. The test client queues raised events per key instead of keeping the last. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 10 +- diagrid/agent/langgraph/activity_stream.py | 4 +- diagrid/agent/langgraph/interrupts.py | 36 ++++++- diagrid/agent/langgraph/invoke_result.py | 28 +++++- diagrid/agent/langgraph/resume_run.py | 63 +++++++++++- diagrid/agent/langgraph/workflow.py | 2 + tests/agent/langgraph/log_helpers.py | 15 ++- tests/agent/langgraph/test_resume_conflict.py | 97 +++++++++++++++++++ 8 files changed, 239 insertions(+), 16 deletions(-) create mode 100644 tests/agent/langgraph/test_resume_conflict.py diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index ad8e29be..68b9dd6f 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -372,13 +372,21 @@ needed for this. `{"resume": }` (add `"stream": true`, and `stream_mode` if you like, for SSE; without it the response is the run's result, as a plain `POST` returns it). In Python: `runner.astream(Command(resume=value), + workflow_id=...)` or `runner.invoke(Command(resume=value), workflow_id=...)`. The interrupted node runs again in the same run, on the same thread, and `interrupt()` returns the value; a dict keyed by interrupt ids answers several interrupts one by one. The stream of a resume carries what happens after it (starting with `node_reset` for the node that runs again) and ends with the final event, or with `workflow_interrupted` when a node asks again. A body without `resume` is a `422`, an unknown run a `404`, - and a run that is not waiting a `409`. + and a run that is not waiting a `409`. When two requests resume the same + interrupt at once, the run takes one and the other gets a `409` (before any + event, when it asked for a stream). +- `interrupt()` pauses the run also when it is called in a subgraph the node + runs (a compiled subgraph added as the node, or one whose result the node + returns) and in the node's router (its conditional edge). A node that calls + a subgraph that pauses and drops its result fails with an error that says + so, rather than going on as if it had not paused. ### Limits diff --git a/diagrid/agent/langgraph/activity_stream.py b/diagrid/agent/langgraph/activity_stream.py index 3dbd3c2b..f0d0f04b 100644 --- a/diagrid/agent/langgraph/activity_stream.py +++ b/diagrid/agent/langgraph/activity_stream.py @@ -56,7 +56,7 @@ def activity_writer( def run_status(run: Any) -> Dict[str, Any]: """The custom status of a run: what a stream reader needs to find its units, and the interrupt the run waits on.""" - from .interrupts import STATUS_INTERRUPT, STATUS_INTERRUPT_SEQ + from .interrupts import STATUS_INTERRUPT, STATUS_INTERRUPT_SEQ, STATUS_RESUMED from .stream_attempts import STATUS_ATTEMPTS status: Dict[str, Any] = {} @@ -69,6 +69,8 @@ def run_status(run: Any) -> Dict[str, Any]: status[STATUS_INTERRUPT_SEQ] = run.interrupt_seq if run.interrupt: status[STATUS_INTERRUPT] = run.interrupt + if getattr(run, "resumed", None): + status[STATUS_RESUMED] = run.resumed return status diff --git a/diagrid/agent/langgraph/interrupts.py b/diagrid/agent/langgraph/interrupts.py index 28f77c58..c6684fec 100644 --- a/diagrid/agent/langgraph/interrupts.py +++ b/diagrid/agent/langgraph/interrupts.py @@ -45,6 +45,8 @@ #: Custom status: the pending interrupt, and the number of the last one. STATUS_INTERRUPT = "interrupt" STATUS_INTERRUPT_SEQ = "interrupt_seq" +#: Custom status: the resume the run took last, ``{"seq", "id"}``. +STATUS_RESUMED = "resumed" #: The updates-chunk key LangGraph streams interrupts under. INTERRUPT_KEY = "__interrupt__" #: The final event of a stream whose run is waiting for a resume. @@ -277,8 +279,10 @@ def settle_interrupts( run.interrupt_seq += 1 run.interrupt = {"seq": run.interrupt_seq, "step": step, "interrupts": pending} publish(run) - values = yield from _wait_resume(run.ctx, run.interrupt_seq, pending) + values, resume_id = yield from _wait_resume(run.ctx, run.interrupt_seq, pending) run.interrupt = None + # which resume the run took: a caller whose resume it ignored is told + run.resumed = {"seq": run.interrupt_seq, "id": resume_id} publish(run) for item in pending: if item["id"] in values: @@ -291,13 +295,37 @@ def settle_interrupts( def _wait_resume( ctx: Any, seq: int, pending: List[Dict[str, Any]] -) -> Generator[Any, Any, Dict[str, Any]]: - """Wait for the resume of interrupt ``seq``; others (stale) are ignored.""" +) -> Generator[Any, Any, Tuple[Dict[str, Any], Optional[str]]]: + """Wait for the resume of interrupt ``seq``; others (stale) are ignored. + + Returns the resume values and the id the resume was raised with. + """ while True: event = yield ctx.wait_for_external_event(RESUME_EVENT) data = event if isinstance(event, dict) else {"resume": event} if data.get("seq") in (None, seq): - return resume_values(pending, data.get("resume")) + raised = data.get("id") + return ( + resume_values(pending, data.get("resume")), + None if raised is None else str(raised), + ) + + +def resume_taken(status: Dict[str, Any], seq: int, resume_id: str) -> Optional[bool]: + """Whether the run took the resume ``resume_id`` of interrupt ``seq``. + + ``None`` while it is still waiting for one. A run started on a version + that does not say which resume it took is taken to have taken this one. + """ + resumed = status.get(STATUS_RESUMED) + if isinstance(resumed, dict) and int(resumed.get("seq") or 0) >= seq: + if int(resumed.get("seq") or 0) > seq: + return True # the run is past it: nothing to tell + return resumed.get("id") in (None, resume_id) + waiting = pending_interrupt(status) + if waiting is not None and int(waiting.get("seq") or 0) == seq: + return None + return True def pending_interrupt(status: Dict[str, Any]) -> Optional[Dict[str, Any]]: diff --git a/diagrid/agent/langgraph/invoke_result.py b/diagrid/agent/langgraph/invoke_result.py index b1014f7b..cf83cab6 100644 --- a/diagrid/agent/langgraph/invoke_result.py +++ b/diagrid/agent/langgraph/invoke_result.py @@ -12,13 +12,14 @@ import json import logging import time +import uuid from typing import Any, Callable, Optional from dapr.ext.workflow import WorkflowStatus from .activity_stream import parse_status from .interrupts import INTERRUPT_KEY, RESUME_EVENT, as_interrupts -from .interrupts import interrupted_event, pending_interrupt +from .interrupts import interrupted_event, pending_interrupt, resume_taken from .models import GraphWorkflowOutput from .streaming import FAILED_STATUSES, normalize_final, run_error @@ -107,6 +108,27 @@ def wait_invoke_result( raise RuntimeError(f"Workflow {workflow_id} was terminated") +def _wait_taken( + client: Any, workflow_id: str, seq: int, resume_id: str, poll_interval: float +) -> None: + """Wait until the run took this resume; another one taken raises.""" + from .resume_run import TAKE_TIMEOUT_S, ResumeConflict + + deadline = time.monotonic() + TAKE_TIMEOUT_S + while time.monotonic() < deadline: + state = client.get_workflow_state(instance_id=workflow_id) + status = parse_status(getattr(state, "serialized_custom_status", None)) + taken = resume_taken(status, seq, resume_id) + if taken is False: + raise ResumeConflict( + f"Interrupt {seq} of workflow {workflow_id!r} was already resumed " + "by another request" + ) + if taken: + return + time.sleep(min(poll_interval, 0.05)) + + def invoke_resume( runner: Any, command: Any, @@ -136,11 +158,13 @@ def invoke_resume( if state.runtime_status != WorkflowStatus.RUNNING or pending is None: raise ValueError(f"Workflow {workflow_id!r} is not waiting for a resume") seq = int(pending.get("seq") or 0) + resume_id = uuid.uuid4().hex client.raise_workflow_event( instance_id=workflow_id, event_name=RESUME_EVENT, - data={"seq": seq, "resume": command.resume}, + data={"seq": seq, "resume": command.resume, "id": resume_id}, ) + _wait_taken(client, workflow_id, seq, resume_id, poll_interval) return wait_invoke_result( runner, workflow_id, diff --git a/diagrid/agent/langgraph/resume_run.py b/diagrid/agent/langgraph/resume_run.py index a15ca10f..22177b7d 100644 --- a/diagrid/agent/langgraph/resume_run.py +++ b/diagrid/agent/langgraph/resume_run.py @@ -8,16 +8,23 @@ workflow_id=...)`` raise the workflow's ``resume`` event and follow the same run to its end, or to its next interrupt. A stream of a resumed run carries what happens after the resume only. + +Two callers may resume the same interrupt at once: both raise the event, the +run takes the first and ignores the other. Each resume carries an id, the run +publishes the id it took, and the caller whose resume it ignored gets +:class:`ResumeConflict` (``409``) instead of a result its value had no part in. """ import asyncio import logging +import time +import uuid from typing import Any, AsyncGenerator, AsyncIterator, Dict, Set, Tuple from diagrid.agent.core.workflow.stream import frame_sse from .activity_stream import parse_status -from .interrupts import RESUME_EVENT, pending_interrupt +from .interrupts import RESUME_EVENT, pending_interrupt, resume_taken from .reconnect import _thread_of, follow_final from .stream_drain import SseEncoder, drain from .stream_events import started_event, stream_failure_event, without_executed @@ -31,6 +38,15 @@ class NotInterrupted(ValueError): """The run is not waiting for a resume (it ended, or never paused).""" +class ResumeConflict(NotInterrupted): + """Another resume of the same interrupt got to the run first.""" + + +#: Seconds a caller waits for the run to take its resume before following it +#: anyway (a sidecar that is slow to deliver the event). +TAKE_TIMEOUT_S = 30.0 + + async def _pending(runner: Any, workflow_id: str) -> Tuple[int, str]: """``(interrupt seq, thread id)`` of a run waiting for a resume. @@ -50,11 +66,36 @@ async def _pending(runner: Any, workflow_id: str) -> Tuple[int, str]: async def _send_resume(runner: Any, workflow_id: str, seq: int, value: Any) -> None: + """Raise the resume and wait until the run took it (or another one).""" + resume_id = uuid.uuid4().hex await asyncio.to_thread( runner._workflow_client.raise_workflow_event, instance_id=workflow_id, event_name=RESUME_EVENT, - data={"seq": seq, "resume": value}, + data={"seq": seq, "resume": value, "id": resume_id}, + ) + deadline = time.monotonic() + TAKE_TIMEOUT_S + while time.monotonic() < deadline: + taken = resume_taken( + await asyncio.to_thread( + custom_status, runner._workflow_client, workflow_id + ), + seq, + resume_id, + ) + if taken is False: + raise ResumeConflict( + f"Interrupt {seq} of workflow {workflow_id!r} was already resumed " + "by another request" + ) + if taken: + return + await asyncio.sleep(0.05) + logger.warning( + "Run %s did not take resume %s within %.0fs; following it anyway", + workflow_id, + resume_id, + TAKE_TIMEOUT_S, ) @@ -135,6 +176,8 @@ async def _resume_sse( out = encoder.encode(item) if out is not None: yield out + except ResumeConflict: + raise # before the first event: the route answers 409 except Exception as e: logger.exception("Resumed run %s failed to stream", workflow_id) failed = stream_failure_event(e, "StreamError", True) @@ -144,6 +187,12 @@ async def _resume_sse( ) +async def _after(first: Any, rest: AsyncIterator[Any]) -> AsyncIterator[Any]: + yield first + async for item in rest: + yield item + + def add_resume_route(app: Any, runner: Any) -> None: """Register ``POST /agent/run/{workflow_id}/resume`` on ``app``.""" from fastapi import HTTPException, Request @@ -172,8 +221,16 @@ async def resume_run(workflow_id: str, request: Request) -> Any: except NotInterrupted as e: raise HTTPException(status_code=409, detail=str(e)) if body.get("stream") is True: + events = _resume_sse(runner, workflow_id, body["resume"], modes) + try: + # the first event comes once the run took this resume + first = await events.__anext__() + except (NotInterrupted, LookupError) as e: + await events.aclose() + code = 404 if isinstance(e, LookupError) else 409 + raise HTTPException(status_code=code, detail=str(e)) return StreamingResponse( - frame_sse(_resume_sse(runner, workflow_id, body["resume"], modes)), + frame_sse(_after(first, events)), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, ) diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 52a4a710..b4e2ae78 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -557,6 +557,8 @@ class _Run: interrupt: Optional[Dict[str, Any]] = None #: How many times the run was interrupted so far. interrupt_seq: int = 0 + #: The resume the run took last, ``{"seq", "id"}``. + resumed: Optional[Dict[str, Any]] = None #: The attempt of each unit's output the run used (see ``stream_attempts``). attempts: Dict[str, str] = field(default_factory=dict) diff --git a/tests/agent/langgraph/log_helpers.py b/tests/agent/langgraph/log_helpers.py index 13a07dbb..79267fca 100644 --- a/tests/agent/langgraph/log_helpers.py +++ b/tests/agent/langgraph/log_helpers.py @@ -12,7 +12,7 @@ import json import threading from types import SimpleNamespace -from typing import Any, Dict, Optional +from typing import Any, Dict, List, Optional from unittest import mock from dapr.ext.workflow import WorkflowStatus @@ -58,7 +58,9 @@ def __init__( self.failed: Dict[str, str] = {} self.custom: Dict[str, str] = {} self.inputs: Dict[str, Any] = {} - self._events: Dict[str, Any] = {} + #: Raised events per ``/``, in order, as the engine + #: queues them: a second event is not lost while the first waits. + self._events: Dict[str, List[Any]] = {} self._cond = threading.Condition() def schedule_new_workflow(self, *, workflow: Any, input: Any, instance_id: str): @@ -90,14 +92,17 @@ def _work(self, input: Any, instance_id: str) -> None: def raise_workflow_event(self, instance_id: str, event_name: str, data: Any = None): with self._cond: - self._events[f"{instance_id}/{event_name}"] = json.loads(json.dumps(data)) + self._events.setdefault(f"{instance_id}/{event_name}", []).append( + json.loads(json.dumps(data)) + ) self._cond.notify_all() def wait_event(self, instance_id: str, name: str) -> Any: key = f"{instance_id}/{name}" with self._cond: - self._cond.wait_for(lambda: key in self._events, timeout=30) - return self._events.pop(key, None) + self._cond.wait_for(lambda: bool(self._events.get(key)), timeout=30) + queued = self._events.get(key) or [] + return queued.pop(0) if queued else None def get_workflow_state(self, *, instance_id: str, fetch_payloads: bool = True): if instance_id not in self.inputs: diff --git a/tests/agent/langgraph/test_resume_conflict.py b/tests/agent/langgraph/test_resume_conflict.py new file mode 100644 index 00000000..0c36b45b --- /dev/null +++ b/tests/agent/langgraph/test_resume_conflict.py @@ -0,0 +1,97 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Two resumes of one interrupt: the run takes one, the other caller gets 409. + +Both callers see the run waiting and both raise the ``resume`` event; the +workflow takes the first and ignores the other. The caller whose value was +ignored must be told, not handed a result its value had no part in. +""" + +import threading +import time +from typing import Any, List + +from fastapi.testclient import TestClient + +from .log_helpers import LogClient, log_runner +from .streaming_helpers import serve_app +from .test_interrupt import INPUT, _approval_graph +from .test_reconnect_helpers import frames +from .test_runner import _RunnerTestCase + + +class _GatedClient(LogClient): + """Holds the workflow back from taking a resume until ``release`` is set.""" + + def __init__(self, runner: Any) -> None: + super().__init__(runner) + self.release = threading.Event() + + def wait_event(self, instance_id: str, name: str) -> Any: + self.release.wait(timeout=30) + return super().wait_event(instance_id, name) + + def buffered(self) -> int: + with self._cond: + return sum(len(v) for v in self._events.values()) + + +def _start(name: str) -> Any: + runner = log_runner(_approval_graph(), name) + client = _GatedClient(runner) + runner._workflow_client = client # type: ignore[assignment] + http = TestClient(serve_app(runner)) + got = frames(http.post("/agent/run", json={**INPUT, "stream": True}).text) + assert got[-1][1] == "workflow_interrupted", got[-1] + return client, http, got[-1][2]["workflow_id"] + + +def _race(client: Any, posts: List[Any]) -> List[Any]: + results: List[Any] = [None] * len(posts) + + def run(i: int) -> None: + results[i] = posts[i]() + + threads = [threading.Thread(target=run, args=(i,)) for i in range(len(posts))] + for t in threads: + t.start() + deadline = time.monotonic() + 10 + while client.buffered() < len(posts) and time.monotonic() < deadline: + time.sleep(0.01) + client.release.set() + for t in threads: + t.join(timeout=30) + return results + + +class TestConcurrentResumes(_RunnerTestCase): + def test_the_second_resume_of_one_interrupt_gets_409(self): + client, http, wf = _start("race-plain") + url = f"/agent/run/{wf}/resume" + a, b = _race( + client, + [ + lambda: http.post(url, json={"resume": "A"}), + lambda: http.post(url, json={"resume": "B"}), + ], + ) + codes = sorted([a.status_code, b.status_code]) + self.assertEqual(codes, [200, 409]) + won = a if a.status_code == 200 else b + value = "A" if won is a else "B" + self.assertEqual(won.json()["output"]["answer"], value) + + def test_a_streamed_resume_that_lost_gets_409_before_streaming(self): + client, http, wf = _start("race-stream") + url = f"/agent/run/{wf}/resume" + a, b = _race( + client, + [ + lambda: http.post(url, json={"resume": "A", "stream": True}), + lambda: http.post(url, json={"resume": "B", "stream": True}), + ], + ) + self.assertEqual(sorted([a.status_code, b.status_code]), [200, 409]) + won = a if a.status_code == 200 else b + self.assertEqual(frames(won.text)[-1][1], "workflow_completed") From f354e66a2035b7463277cf69c78b86e6e7a6c2bd Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 16:07:04 +0100 Subject: [PATCH 54/73] perf(langgraph): bound a streamed run's custom status and read it less The custom status listed every step's units and was rewritten each step, and every stream read it every 200 ms. Dapr returns the custom status only with fetch_payloads (durabletask-go's GetInstance copies it inside the GetInputsAndOutputs branch), so the input travels with every read and fetch_payloads=False is not an option. The status now lists the last 128 steps (executed_from says where they start); a reader behind that window waits for the final event, which lists every step, so its chunks stay in order. A follower reads the status when no known unit is still being written, and otherwise every tenth poll. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 6 +- diagrid/agent/langgraph/activity_stream.py | 23 ++- diagrid/agent/langgraph/stream_follow.py | 50 ++++++- tests/agent/langgraph/test_status_size.py | 162 +++++++++++++++++++++ 4 files changed, 229 insertions(+), 12 deletions(-) create mode 100644 tests/agent/langgraph/test_status_size.py diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 68b9dd6f..c488b3c1 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -317,7 +317,11 @@ not pick one: chunks still never reach the log, the stream ends with `stream_unavailable` whose `reason` is `write_failed`. A store that cannot be read ends the stream with `workflow_failed` (`error_type` `StreamReadError`), never with an - empty stream. `StateLogStreamConfig` sets the store, key prefix, TTLs, batch + empty stream. A stream finds a run's tasks in the run's custom status, which + lists its last 128 steps (a reader further behind catches up on the older + steps when the run ends) and which it reads about every 2 seconds while a + node is streaming, as Dapr returns the status only together with the run's + input. `StateLogStreamConfig` sets the store, key prefix, TTLs, batch sizes and read interval: ```python diff --git a/diagrid/agent/langgraph/activity_stream.py b/diagrid/agent/langgraph/activity_stream.py index f0d0f04b..b71014ed 100644 --- a/diagrid/agent/langgraph/activity_stream.py +++ b/diagrid/agent/langgraph/activity_stream.py @@ -24,6 +24,13 @@ #: Custom status keys: the units of each step, and the routers run apart. STATUS_EXECUTED = "executed" STATUS_BRANCHES = "branches" +#: Custom status key: the step the first entry of ``executed`` is. +STATUS_EXECUTED_FROM = "executed_from" +#: The steps whose units the custom status holds: the status is rewritten +#: every step and read by every stream (with the run's input: Dapr returns it +#: only with the payloads), so it must not grow with the run. A reader that +#: needs older steps gets them from the run's output when it ends. +STATUS_STEP_WINDOW = 128 def transport_of( @@ -61,10 +68,18 @@ def run_status(run: Any) -> Dict[str, Any]: status: Dict[str, Any] = {} if (run.config or {}).get(STREAM_RUN_KEY): - status[STATUS_EXECUTED] = run.executed - status[STATUS_BRANCHES] = run.branches - if run.attempts: - status[STATUS_ATTEMPTS] = run.attempts + first = max(0, len(run.executed) - STATUS_STEP_WINDOW) + status[STATUS_EXECUTED] = run.executed[first:] + status[STATUS_BRANCHES] = [b for b in run.branches if int(b[0]) >= first] + if first: + status[STATUS_EXECUTED_FROM] = first + attempts = { + key: attempt + for key, attempt in run.attempts.items() + if int(key.split(":", 1)[0]) >= first + } + if attempts: + status[STATUS_ATTEMPTS] = attempts if run.interrupt_seq: status[STATUS_INTERRUPT_SEQ] = run.interrupt_seq if run.interrupt: diff --git a/diagrid/agent/langgraph/stream_follow.py b/diagrid/agent/langgraph/stream_follow.py index e9103ba0..52fa7757 100644 --- a/diagrid/agent/langgraph/stream_follow.py +++ b/diagrid/agent/langgraph/stream_follow.py @@ -35,7 +35,7 @@ event_from_wire, ) -from .activity_stream import STATUS_BRANCHES, STATUS_EXECUTED +from .activity_stream import STATUS_BRANCHES, STATUS_EXECUTED, STATUS_EXECUTED_FROM from .interrupts import INTERRUPT_KEY, as_interrupts from .stream_attempts import attempts_of, unit_key from .stream_events import encode_chunk, stream_failure_event @@ -47,6 +47,8 @@ BACKLOG_HIGH = 256 #: Reads that fail in a row before the stream reports the store unreadable. READ_ATTEMPTS = 5 +#: Polls between reads of the run's status while a unit is still being written. +STATUS_EVERY = 10 Unit = Tuple[int, str] @@ -82,8 +84,9 @@ def units_of(status: Dict[str, Any]) -> List[Unit]: """ executed = status.get(STATUS_EXECUTED) or status.get(EXECUTED_KEY) or [] branches = status.get(STATUS_BRANCHES) or status.get(BRANCHES_KEY) or [] + first = int(status.get(STATUS_EXECUTED_FROM) or 0) units: List[Tuple[int, int, int, str]] = [] - for step, keys in enumerate(executed): + for step, keys in enumerate(executed, start=first): for order, key in enumerate(keys): units.append((step, 0, order, str(key))) for order, (step, key) in enumerate(branches): @@ -160,6 +163,8 @@ def __init__( #: Units the client had in full or in part before this stream: the #: stream does not report them missing. self._seen = seen if seen is not None else set() + #: Polls since the run's status was last read (see ``_run_status``). + self._polls_since_status = STATUS_EVERY #: The last step whose ``values`` chunk went out (here or before a #: reconnect): every unit of a step logs it, and it is sent once. self.values_through = ( @@ -240,11 +245,14 @@ async def skip_to_end(self) -> None: async def _read_once(self, final: Optional[Dict[str, Any]]) -> None: if self._cursor.at_end: return - status = final if final is not None else await asyncio.to_thread(self._status) - self._learn(units_of(status or {})) - winners = attempts_of(status) - for key, state in self._units.items(): - state.winner = winners.get(unit_key(*key), state.winner) + status = await self._run_status(final) + if status is not None: + if final is None and self._behind_window(status): + return # the final event lists every step: read in order then + self._learn(units_of(status)) + winners = attempts_of(status) + for key, state in self._units.items(): + state.winner = winners.get(unit_key(*key), state.winner) wants = [ UnitWant( unit[0], @@ -266,6 +274,34 @@ async def _read_once(self, final: Optional[Dict[str, Any]]) -> None: continue await self._deliver(chunk) + async def _run_status( + self, final: Optional[Dict[str, Any]] + ) -> Optional[Dict[str, Any]]: + """The run's status, when there may be something new in it. + + New units appear when a step starts, and the run says which attempt + it used when the next one does; while a known unit is still being + written the status is read only every :data:`STATUS_EVERY` polls (a + unit whose writes failed must not hold the stream back for good). + Dapr returns the status only with the run's input and output, so this + is the expensive read of a poll. + """ + if final is not None: + return final + self._polls_since_status += 1 + writing = any(not state.complete for state in self._units.values()) + if writing and self._polls_since_status < STATUS_EVERY: + return None + self._polls_since_status = 0 + return await asyncio.to_thread(self._status) or {} + + def _behind_window(self, status: Dict[str, Any]) -> bool: + """Whether the status no longer lists steps this reader still needs.""" + first = int(status.get(STATUS_EXECUTED_FROM) or 0) + if not first or self._cursor.skips_step(first - 1): + return False + return not any(step < first for step, _ in self._units) + def _learn(self, units: List[Unit]) -> None: for unit in units: if unit in self._units: diff --git a/tests/agent/langgraph/test_status_size.py b/tests/agent/langgraph/test_status_size.py new file mode 100644 index 00000000..b327c0a5 --- /dev/null +++ b/tests/agent/langgraph/test_status_size.py @@ -0,0 +1,162 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""What a streamed run's custom status costs: its size, and how often it is read. + +The status is rewritten every step and read by every stream, and Dapr returns +it only with the run's input and output (``fetch_payloads``), so it holds the +last steps' units only, and a stream reads it when it needs to find new units, +not on every poll. +""" + +import operator +import threading +import time +from types import SimpleNamespace +from typing import Any, List +from unittest import mock + +from fastapi.testclient import TestClient +from langgraph.config import get_stream_writer +from langgraph.graph import END, START, StateGraph +from langgraph.types import interrupt +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.langgraph import activity_stream +from diagrid.agent.langgraph.activity_stream import STATUS_EXECUTED_FROM, run_status +from diagrid.agent.langgraph.stream_follow import units_of +from diagrid.agent.langgraph.streaming import STREAM_RUN_KEY + +from .log_helpers import log_runner +from .streaming_helpers import serve_app +from .test_reconnect_helpers import frames +from .test_runner import _RunnerTestCase + + +class _S(TypedDict, total=False): + log: Annotated[list, operator.add] + n: int + + +def _run(steps: int) -> Any: + return SimpleNamespace( + config={STREAM_RUN_KEY: True}, + executed=[[f"node{i}"] for i in range(steps)], + branches=[[i, f"node{i}:branch:r"] for i in range(steps)], + attempts={f"{i}:node{i}": f"att{i}" for i in range(steps)}, + interrupt=None, + interrupt_seq=0, + resumed=None, + ) + + +class TestStatusSize(_RunnerTestCase): + def test_the_status_holds_the_last_steps_only(self): + with mock.patch.object(activity_stream, "STATUS_STEP_WINDOW", 10): + status = run_status(_run(500)) + self.assertEqual(status[STATUS_EXECUTED_FROM], 490) + self.assertEqual(len(status["executed"]), 10) + self.assertEqual(len(status["branches"]), 10) + self.assertEqual(len(status["attempts"]), 10) + units = units_of(status) + self.assertEqual(units[0], (490, "node490")) + self.assertEqual(units[-1], (499, "node499:branch:r")) + + def test_a_short_run_keeps_every_step(self): + status = run_status(_run(5)) + self.assertEqual(status.get(STATUS_EXECUTED_FROM, 0), 0) + self.assertEqual(units_of(status)[0], (0, "node0")) + + +def _long_node_graph() -> Any: + def talk(s: _S) -> dict: + write = get_stream_writer() + for i in range(40): + write({"tick": i}) + time.sleep(0.02) + return {"log": ["talk"]} + + g = StateGraph(_S) + g.add_node("talk", talk) + g.add_edge(START, "talk") + g.add_edge("talk", END) + return g.compile() + + +class TestStatusReads(_RunnerTestCase): + def test_a_stream_does_not_read_the_status_on_every_poll(self): + from diagrid.agent.langgraph import runner as runner_module + + calls: List[float] = [] + real = runner_module.custom_status + + def counting(client: Any, wf: str) -> Any: + calls.append(time.monotonic()) + return real(client, wf) + + runner = log_runner(_long_node_graph(), "status-reads") + http = TestClient(serve_app(runner)) + with mock.patch.object(runner_module, "custom_status", counting): + got = frames( + http.post( + "/agent/run", + json={"log": [], "stream": True, "stream_mode": ["custom"]}, + ).text + ) + self.assertEqual(len([e for _, e, _ in got if e == "custom"]), 40) + # ~0.8 s of streaming at a 10 ms read interval: about 80 polls + self.assertLess(len(calls), 30, len(calls)) + + +def _loop_then_ask() -> Any: + def step(s: _S) -> dict: + return {"log": [f"s{s.get('n', 0)}"], "n": s.get("n", 0) + 1} + + def ask(s: _S) -> dict: + return {"log": [f"ask:{interrupt('go?')}"]} + + def route(s: _S) -> str: + return "step" if s.get("n", 0) < 6 else "ask" + + g = StateGraph(_S) + g.add_node("step", step) + g.add_node("ask", ask) + g.add_edge(START, "step") + g.add_conditional_edges("step", route, ["step", "ask"]) + g.add_edge("ask", END) + return g.compile() + + +class TestReconnectBehindTheWindow(_RunnerTestCase): + def test_a_reader_behind_the_window_still_gets_every_step_in_order(self): + with mock.patch.object(activity_stream, "STATUS_STEP_WINDOW", 3): + runner = log_runner(_loop_then_ask(), "status-window") + http = TestClient(serve_app(runner)) + got = frames( + http.post( + "/agent/run", + json={"log": [], "stream": True, "stream_mode": ["updates"]}, + ).text + ) + self.assertEqual(got[-1][1], "workflow_interrupted") + wf = got[-1][2]["workflow_id"] + out: List[Any] = [] + + def reconnect() -> None: + out.extend( + frames( + http.get( + f"/agent/run/{wf}/stream", params={"stream_mode": "updates"} + ).text + ) + ) + + reader = threading.Thread(target=reconnect) + reader.start() + time.sleep(0.3) # the reader is following the paused run + http.post(f"/agent/run/{wf}/resume", json={"resume": "yes"}) + reader.join(timeout=30) + updates = [list(d)[0] for _, e, d in out if e == "updates"] + self.assertEqual(updates[:6], ["step"] * 6) + self.assertEqual(updates[-1], "ask") + self.assertEqual(out[-1][1], "workflow_completed") From cf0a9a2fd60fdb7bcbf5feae08a0d8a54730f3ac Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 16:07:38 +0100 Subject: [PATCH 55/73] docs(langgraph): say which runs keep thread state and how to secure the run endpoints The Conversations section recommended MemorySaver and did not say that a run without a thread id is stateless, how resent history is handled, how to opt out, or what happens when the state cannot be saved. The proxy section now says the per-run endpoints answer anyone who knows a run's id and belong behind the app's own authentication. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 49 +++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index c488b3c1..c3919b44 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -79,15 +79,37 @@ result = runner.invoke( ``` That is all. `thread_id` may also come as `config["configurable"]["thread_id"]` -or, over HTTP, as `thread_id` in the request body. Each run starts from the -state the thread's last run ended with and applies its input to it through the -channels' reducers, as LangGraph does with a checkpointer. The state is kept in -the app's Dapr state store (`agent-memory`, which a Catalyst app has), keyed by -thread. To keep it elsewhere, compile the graph with a LangGraph checkpointer -(`graph.compile(checkpointer=MemorySaver())`) or pass `checkpointer=` to the -runner (a `DaprMemoryCheckpointer` on another store, or a LangGraph saver with -the synchronous `get_tuple` and `put`). With none of these, `thread_id` only -names the run and each run starts from its input alone. +or, over HTTP, as `thread_id` (or `session_id`) in the request body. Each run +starts from the state the thread's last run ended with and applies its input +to it through the channels' reducers, as LangGraph does with a checkpointer. +The state is kept in the app's Dapr state store (`agent-memory`, which a +Catalyst app has, else the store the workflows use), keyed by thread; a +thread keeps its last two checkpoints, which expire 30 days after its last +run (`DaprMemoryCheckpointer(ttl_s=..., keep_checkpoints=...)`). Runs on one +thread at the same time each start from the state before them, and the last +one to end sets the thread's state. + +- **No thread id, no state.** A run without one is stateless: it starts from + its input alone and leaves nothing in the store. Its generated thread id + (a UUID) is only a label. +- **Send only the new messages.** As with a LangGraph checkpointer, the input + is applied to the thread's state: a client that sends the whole history + every turn duplicates it, unless every message it resends carries the `id` + the run returned for it (`add_messages` then replaces it in place). Such a + client can also send no thread id and keep the history itself. +- **Opting out.** `DaprWorkflowGraphRunner(..., continue_threads=False)` makes + every run stateless. +- **Another store.** Pass `checkpointer=` to the runner: a + `DaprMemoryCheckpointer` on another Dapr store, or a LangGraph saver with + the synchronous `get_tuple` and `put` (a database saver). A graph compiled + with LangGraph's `MemorySaver` keeps threads in one process, which breaks + across replicas and restarts: the runner keeps them in the Dapr state store + instead (and logs a warning); without any store it uses the `MemorySaver` + and warns. With no store at all, `thread_id` only names the run. +- **If the state cannot be saved** (the store is down past the retries), the + run still returns its output, with `thread_saved: false` and + `thread_error`, and a stream sends `thread_not_saved` before its final + event; the thread keeps the state it had before the run. ## Async Usage @@ -358,6 +380,15 @@ expect events to arrive one by one as the nodes produce them, comment lines after `workflow_completed` or `workflow_failed`. If tokens arrive all at once at the end of the run, something in front of the app is buffering. +**Put the endpoints behind the app's own authentication.** `GET +/agent/run/{workflow_id}`, `GET /agent/run/{workflow_id}/stream` and `POST +/agent/run/{workflow_id}/resume` answer anyone who knows a run's id, with the +run's output, its stream and the power to resume it; the runner does not check +who started a run. Workflow ids end in a random UUID, so they cannot be +guessed, but they travel in responses and logs: deploy the app behind the +authentication (and, where runs belong to users, the per-user checks) your +API gateway or app already applies, as you would for `POST /agent/run`. + ### Interrupts A node can pause the run with LangGraph's `interrupt(value)`, as in a graph From dbdf33956cc8ab507bc7f2289cc2ed85cf92e7b1 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 16:12:50 +0100 Subject: [PATCH 56/73] fix(langgraph): run a node through its sync entry when its middleware is sync-only The runner calls a node with an async entry point through ainvoke, where an AgentMiddleware with only wrap_model_call or wrap_tool_call raises NotImplementedError before the wrapped call runs. A node with its own sync function now falls back to invoke (in an executor, with the ambient config) for that error; a composite is not retried, as its earlier steps ran, and the README says to add the async variant there. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 8 ++ diagrid/agent/langgraph/runnable_call.py | 47 +++++++++++- tests/agent/langgraph/test_sync_middleware.py | 75 +++++++++++++++++++ 3 files changed, 127 insertions(+), 3 deletions(-) create mode 100644 tests/agent/langgraph/test_sync_middleware.py diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index c3919b44..07d35dfe 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -446,6 +446,14 @@ needed for this. the run says which attempt it used when that step starts) and then the used attempt's chunks; a replay has the used attempt only. The in-process transport keeps the first attempt that finished. +- **Middleware with only a sync wrap hook.** The runner calls a node that has + an async entry point (an agent's model and tool nodes do) through + `ainvoke`, where an `AgentMiddleware` that defines only `wrap_model_call` or + `wrap_tool_call` raises. The runner then runs that node through its sync + entry, so such an agent works when it is the graph the runner runs. An + agent added as a subgraph node of another graph runs as one call, which is + not repeated: give its middleware the async variant too + (`awrap_model_call`, `awrap_tool_call`). - **Node code must not count attempts in process memory.** A retried node may run in another process, so a counter kept in a module or a closure does not see the earlier attempt. Keep such state in the graph's state or a store. diff --git a/diagrid/agent/langgraph/runnable_call.py b/diagrid/agent/langgraph/runnable_call.py index b0238edb..c5b75d46 100644 --- a/diagrid/agent/langgraph/runnable_call.py +++ b/diagrid/agent/langgraph/runnable_call.py @@ -10,11 +10,14 @@ import asyncio import concurrent.futures import functools +import logging import threading from typing import Any, Dict, Optional, Tuple from langchain_core.runnables.config import run_in_executor +logger = logging.getLogger(__name__) + def _has_async_entry(runnable: Any) -> bool: """Whether ``runnable`` has a real async entry point, which a node should use. @@ -114,6 +117,44 @@ def _await_if_coroutine(r: Any) -> Any: def _invoke_runnable(runnable: Any, value: Any, config: Dict[str, Any]) -> Any: """Call a Runnable; one with an async entry returns a coroutine to await.""" - if _has_async_entry(runnable): - return runnable.ainvoke(value, config=config) - return runnable.invoke(value, config=config) + if not _has_async_entry(runnable): + return runnable.invoke(value, config=config) + if getattr(runnable, "func", None) is not None: + return _ainvoke_or_sync(runnable, value, config) + return runnable.ainvoke(value, config=config) + + +def _is_sync_only_middleware(error: BaseException) -> bool: + """Whether ``error`` is a middleware that has only a sync wrap hook. + + LangChain's ``AgentMiddleware`` raises it from ``awrap_model_call`` / + ``awrap_tool_call`` when only ``wrap_model_call`` / ``wrap_tool_call`` is + defined, before the wrapped call runs. + """ + text = str(error) + return ( + isinstance(error, NotImplementedError) + and "Asynchronous implementation of awrap_" in text + and "is not available" in text + ) + + +async def _ainvoke_or_sync(runnable: Any, value: Any, config: Dict[str, Any]) -> Any: + """``ainvoke``, or ``invoke`` for a node whose middleware is sync-only. + + Only a node with its own sync function falls back: the error comes before + the model or tool call it wraps, so nothing ran twice. A composite (a + subgraph) is not retried, as its earlier steps did run. + """ + try: + return await runnable.ainvoke(value, config=config) + except NotImplementedError as e: + if not _is_sync_only_middleware(e): + raise + logger.info( + "A middleware of node %r has only a sync wrap hook; running the node " + "through its sync entry", + getattr(runnable, "name", None), + ) + # in an executor, with this context: the ambient config goes with it + return await run_in_executor(config, runnable.invoke, value, config=config) diff --git a/tests/agent/langgraph/test_sync_middleware.py b/tests/agent/langgraph/test_sync_middleware.py new file mode 100644 index 00000000..e53210d0 --- /dev/null +++ b/tests/agent/langgraph/test_sync_middleware.py @@ -0,0 +1,75 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""An agent whose middleware has only a sync ``wrap_model_call`` / ``wrap_tool_call``. + +The runner calls a node with an async entry point through ``ainvoke``, where +such a middleware raises ``NotImplementedError``. ``invoke`` works natively, +so the runner falls back to the node's sync entry for that error. +""" + +from typing import Any + +from langchain.agents import create_agent +from langchain.agents.middleware import AgentMiddleware +from langchain_core.language_models.fake_chat_models import GenericFakeChatModel +from langchain_core.messages import AIMessage +from langchain_core.tools import tool + +from .log_helpers import log_runner +from .test_runner import _RunnerTestCase + + +@tool +def double(x: int) -> int: + """Double a number.""" + return x * 2 + + +class _SyncOnly(AgentMiddleware): + def __init__(self) -> None: + super().__init__() + self.model_calls = 0 + self.tool_calls = 0 + + def wrap_model_call(self, request: Any, handler: Any) -> Any: + self.model_calls += 1 + return handler(request) + + def wrap_tool_call(self, request: Any, handler: Any) -> Any: + self.tool_calls += 1 + return handler(request) + + +class _ToolModel(GenericFakeChatModel): + def bind_tools(self, tools: Any, **kwargs: Any) -> Any: + return self + + +def _model() -> Any: + return _ToolModel( + messages=iter( + [ + AIMessage( + content="", + tool_calls=[{"name": "double", "args": {"x": 21}, "id": "c1"}], + ), + AIMessage(content="42"), + ] + ) + ) + + +class TestSyncOnlyMiddleware(_RunnerTestCase): + def test_an_agent_with_sync_only_wraps_runs_under_the_runner(self): + middleware = _SyncOnly() + agent = create_agent(_model(), tools=[double], middleware=[middleware]) + runner = log_runner(agent, "sync-mw") + out = runner.invoke( + {"messages": [{"role": "user", "content": "double 21"}]}, + poll_interval=0.01, + timeout=20, + ) + self.assertEqual(out["messages"][-1]["content"], "42") + self.assertEqual(middleware.model_calls, 2) + self.assertEqual(middleware.tool_calls, 1) From cd494308620244436dc60ac8296a45e730632e80 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 16:15:47 +0100 Subject: [PATCH 57/73] fix(langgraph): type the fix pass for mypy A failed stream with no caller thread id reports the workflow id as its thread, the sync fallback passes a RunnableConfig, and the resume route's generator is typed as one. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/resume_run.py | 2 +- diagrid/agent/langgraph/runnable_call.py | 7 +++++-- diagrid/agent/langgraph/runner.py | 6 +++++- diagrid/agent/langgraph/workflow.py | 2 +- 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/diagrid/agent/langgraph/resume_run.py b/diagrid/agent/langgraph/resume_run.py index 22177b7d..535d728b 100644 --- a/diagrid/agent/langgraph/resume_run.py +++ b/diagrid/agent/langgraph/resume_run.py @@ -167,7 +167,7 @@ async def resume_run_result( async def _resume_sse( runner: Any, workflow_id: str, value: Any, modes: Any -) -> AsyncIterator[Tuple[Any, ...]]: +) -> AsyncGenerator[Tuple[Any, ...], None]: encoder = SseEncoder(modes, runner.stream_transport.replayable) try: async for item in resume_run_events( diff --git a/diagrid/agent/langgraph/runnable_call.py b/diagrid/agent/langgraph/runnable_call.py index c5b75d46..c1585926 100644 --- a/diagrid/agent/langgraph/runnable_call.py +++ b/diagrid/agent/langgraph/runnable_call.py @@ -12,8 +12,9 @@ import functools import logging import threading -from typing import Any, Dict, Optional, Tuple +from typing import Any, Dict, Optional, Tuple, cast +from langchain_core.runnables import RunnableConfig from langchain_core.runnables.config import run_in_executor logger = logging.getLogger(__name__) @@ -157,4 +158,6 @@ async def _ainvoke_or_sync(runnable: Any, value: Any, config: Dict[str, Any]) -> getattr(runnable, "name", None), ) # in an executor, with this context: the ambient config goes with it - return await run_in_executor(config, runnable.invoke, value, config=config) + return await run_in_executor( + cast(RunnableConfig, config), runnable.invoke, value, config=config + ) diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 51e85b2a..f32c59fb 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -1345,7 +1345,11 @@ async def _serve_stream( # type: ignore[override] failed = stream_failure_event(e, "StreamError", bool(workflow_id)) yield ( "workflow_failed", - normalize_final(failed, workflow_id=workflow_id, thread_id=thread_id), + normalize_final( + failed, + workflow_id=workflow_id, + thread_id=thread_id or workflow_id or "", + ), ) def _add_routes(self, app: Any) -> None: diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index b4e2ae78..283977b2 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -585,7 +585,7 @@ def finish( branches=self.branches or None, attempts=self.attempts or None, status=status, - **({"error": error} if error else {}), + error=error or None, ).to_dict() From 1500c9da54224c54d49a42c097970da924fd98db Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 16:36:15 +0100 Subject: [PATCH 58/73] fix(stream-log): write a batch before the head that counts it A Dapr bulk save is neither atomic nor ordered, so writing a batch and its head in one save let a reader see the head first, or the head alone after a failed batch write, and report a live run as purged. A flush now writes the batch, then the head, and a reader looks a missing batch up once more after a short wait before it calls the unit purged. The fake log store can land a bulk save out of order or in part. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/stream_log.py | 44 +++++++----- tests/agent/core/log_store_fake.py | 28 ++++++-- tests/agent/core/test_stream_log.py | 88 +++++++++++++++++++++-- 3 files changed, 133 insertions(+), 27 deletions(-) diff --git a/diagrid/agent/core/workflow/stream_log.py b/diagrid/agent/core/workflow/stream_log.py index 91be763a..0393217a 100644 --- a/diagrid/agent/core/workflow/stream_log.py +++ b/diagrid/agent/core/workflow/stream_log.py @@ -16,6 +16,12 @@ - ``:::::end``: the head of an attempt that finished, as it was when it did (kept as long as the head). +A Dapr bulk save is neither atomic nor ordered, so a flush writes its batch +first and the head that counts it in a second save: a head never names a +batch that was not written. A reader that still misses a counted batch (a +replica that lags) looks again after ``purge_recheck_s`` before it calls the +unit purged. + A retried activity is a new attempt: it takes the head over, and a reader that sees the attempt change starts that unit again (the consumer turns that into ``node_reset``). An attempt that finished (``done``) keeps the head: a late @@ -58,6 +64,9 @@ class StateLogStreamConfig: flush_max_chunks: int = 64 #: How often a reader looks for new batches. read_poll_s: float = 0.2 + #: A batch the head counts but the store does not return is looked for + #: again after this long before the unit is called purged. + purge_recheck_s: float = 0.5 #: Events an activity holds while the store refuses writes; past it, #: tokens and custom chunks are dropped, markers and updates never. max_buffered: int = MAX_BUFFERED_EVENTS @@ -290,23 +299,7 @@ def _flush(self, *, done: bool, final: bool = False) -> bool: batch = list(self._pending) if not batch and not final: return True - items: List[LogItem] = [] - if batch: - items.append( - ( - batch_key( - self._config.key_prefix, - self._workflow_id, - self._step, - self._unit, - self.attempt, - self._batches, - ), - batch, - _ttl(self._config.event_ttl_s), - ) - ) - if not items and not done: + if not batch and not done: return True batches = self._batches + (1 if batch else 0) head = { @@ -322,12 +315,21 @@ def _flush(self, *, done: bool, final: bool = False) -> bool: self._step, self._unit, ) + items: List[LogItem] = [] if not self._is_blocked(): items.append((head_key(*prefix), head, record_ttl)) if done: items.append((end_key(*prefix, self.attempt), head, record_ttl)) try: - self._store.save_bulk(items) + # the batch lands before any head counts it; a batch written + # again (its head failed) is the same batch with more events + if batch: + key = batch_key(*prefix, self.attempt, self._batches) + self._store.save_bulk( + [(key, batch, _ttl(self._config.event_ttl_s))] + ) + if items: + self._store.save_bulk(items) except Exception as e: # never fail the node over its stream self.write_failures += 1 logger.warning( @@ -453,6 +455,12 @@ def read(self, wants: Sequence[UnitWant]) -> List[UnitChunk]: plans.append((want, head, reset, keys)) wanted = list(itertools.chain.from_iterable(p[3] for p in plans)) batches = self._store.get_bulk(wanted) if wanted else {} + missing = [key for key in wanted if key not in batches] + if missing: + # a head is written after its batches, so a counted batch that is + # not there is purged, or on a replica that has not caught up yet + time.sleep(self._config.purge_recheck_s) + batches = {**batches, **self._store.get_bulk(missing)} return [ self._chunk(want, head, reset, keys, batches) for want, head, reset, keys in plans diff --git a/tests/agent/core/log_store_fake.py b/tests/agent/core/log_store_fake.py index 784afd61..00de69c8 100644 --- a/tests/agent/core/log_store_fake.py +++ b/tests/agent/core/log_store_fake.py @@ -6,7 +6,9 @@ import copy import json import threading -from typing import Any, Dict, List, Optional, Sequence, Tuple +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple + +Item = Tuple[str, Any, Dict[str, str]] class FakeLogStore: @@ -14,6 +16,12 @@ class FakeLogStore: ``fail_saves`` / ``fail_gets`` make the next calls raise, as a store that is down would. + + A Dapr bulk save is neither atomic nor ordered (components-contrib runs + the sets in parallel), and these simulate that: ``bulk_order`` lands a + save's items one by one in the order it returns, ``after_item`` runs after + each item landed (a reader racing the save), and ``partial_saves`` makes + the next save land only that many of its items, then raise. """ def __init__(self) -> None: @@ -22,18 +30,30 @@ def __init__(self) -> None: self.saves: List[List[str]] = [] self.fail_saves = 0 self.fail_gets = 0 - self._lock = threading.Lock() + self.bulk_order: Optional[Callable[[List[Item]], List[Item]]] = None + self.after_item: Optional[Callable[[str], None]] = None + self.partial_saves: Optional[int] = None + self._lock = threading.RLock() - def save_bulk(self, items: Sequence[Tuple[str, Any, Dict[str, str]]]) -> None: + def save_bulk(self, items: Sequence[Item]) -> None: with self._lock: if self.fail_saves: self.fail_saves -= 1 raise ConnectionError("store down") self.saves.append([key for key, _, _ in items]) - for key, value, metadata in items: + ordered = list(items) + if self.bulk_order is not None: + ordered = self.bulk_order(ordered) + landing, self.partial_saves = self.partial_saves, None + for n, (key, value, metadata) in enumerate(ordered): + if landing is not None and n >= landing: + raise ConnectionError(f"bulk save: {key!r} failed") + with self._lock: # crosses JSON, as a real store does self.data[key] = json.loads(json.dumps(value)) self.metadata[key] = dict(metadata) + if self.after_item is not None: + self.after_item(key) def get_bulk(self, keys: Sequence[str]) -> Dict[str, Any]: with self._lock: diff --git a/tests/agent/core/test_stream_log.py b/tests/agent/core/test_stream_log.py index 3ed547e5..ebac7265 100644 --- a/tests/agent/core/test_stream_log.py +++ b/tests/agent/core/test_stream_log.py @@ -28,7 +28,7 @@ def _config(**kw: Any) -> StateLogStreamConfig: - base = dict(flush_interval_s=30.0, flush_max_chunks=1000) + base = dict(flush_interval_s=30.0, flush_max_chunks=1000, purge_recheck_s=0.01) base.update(kw) return StateLogStreamConfig(**base) @@ -68,7 +68,7 @@ def test_flushes_on_the_chunk_count(self): writer = _writer(store, flush_max_chunks=3) for seq in range(3): writer.put(_event("research#0", seq)) - self.assertEqual(len(store.saves), 1) + self.assertEqual(len(store.saves), 2) # the batch, then its head writer.finish(done=True) def test_flushes_on_the_interval(self): @@ -76,9 +76,9 @@ def test_flushes_on_the_interval(self): writer = _writer(store, flush_interval_s=0.02) writer.put(_event("research#0", 0)) deadline = time.monotonic() + 5 - while not store.saves and time.monotonic() < deadline: + while len(store.saves) < 2 and time.monotonic() < deadline: time.sleep(0.01) - self.assertEqual(len(store.saves), 1) + self.assertEqual(len(store.saves), 2) # the batch, then its head writer.finish(done=True) def test_the_last_flush_runs_before_finish_returns(self): @@ -103,7 +103,7 @@ def test_every_save_carries_a_ttl_and_heads_outlive_batches(self): end = end_key("lgstream", "wf:1", 0, "research#0", writer.attempt) self.assertEqual(store.metadata[head], {"ttlInSeconds": "2400"}) self.assertEqual(store.metadata[end], {"ttlInSeconds": "2400"}) - self.assertEqual(store.saves, [[batch, head, end]]) + self.assertEqual(store.saves, [[batch], [head, end]]) def test_a_write_error_never_raises_and_is_retried(self): store = FakeLogStore() @@ -302,3 +302,81 @@ def test_one_round_trip_for_heads_and_one_for_batches(self): [UnitWant(0, "research#0"), UnitWant(0, "other")] ) self.assertEqual(len(calls), 2) + + +def _heads_first(items: List[Any]) -> List[Any]: + """The worst order a parallel bulk save can land in: heads before batches.""" + return sorted(items, key=lambda item: 0 if item[0].endswith(":head") else 1) + + +class TestNonAtomicBulkSave(unittest.TestCase): + """A Dapr bulk save lands its items in any order, and may land some only.""" + + def test_a_read_racing_the_save_never_calls_a_live_unit_purged(self): + store = FakeLogStore() + writer = _writer(store) + reader = LogReader(store, _config(), "wf:1") + seen: List[Any] = [] + store.bulk_order = _heads_first + store.after_item = lambda key: seen.extend( + reader.read([UnitWant(0, "research#0")]) + ) + for seq in range(3): + writer.put(_event("research#0", seq)) + writer.finish(done=True) + self.assertTrue(seen) + for chunk in seen: + self.assertFalse(chunk.purged, chunk) + self.assertEqual(seen[-1].total, 3) + self.assertEqual(len(seen[-1].events), 3) + + def test_a_save_that_lands_in_part_never_calls_a_live_unit_purged(self): + for landed in range(3): + with self.subTest(landed=landed): + store = FakeLogStore() + writer = _writer(store) + for seq in range(2): + writer.put(_event("research#0", seq)) + store.bulk_order = _heads_first + store.partial_saves = landed + writer._flush(done=False) + reader = LogReader(store, _config(), "wf:1") + (chunk,) = reader.read([UnitWant(0, "research#0")]) + self.assertFalse(chunk.purged, chunk) + writer.finish(done=True) # the retry writes what failed + (chunk,) = reader.read([UnitWant(0, "research#0")]) + self.assertFalse(chunk.purged, chunk) + self.assertEqual(_datas(chunk), ["research#0-0", "research#0-1"]) + + def test_batches_land_before_the_head_that_counts_them(self): + store = FakeLogStore() + writer = _writer(store) + writer.put(_event("research#0", 0)) + writer.finish(done=True) + batch = batch_key("lgstream", "wf:1", 0, "research#0", writer.attempt, 0) + head = head_key("lgstream", "wf:1", 0, "research#0") + end = end_key("lgstream", "wf:1", 0, "research#0", writer.attempt) + self.assertEqual(store.saves, [[batch], [head, end]]) + + def test_a_batch_that_shows_up_on_a_second_look_is_read(self): + """A replica that lags the head by a moment: the reader looks again.""" + store = FakeLogStore() + writer = _writer(store, flush_max_chunks=1) + for seq in range(2): + writer.put(_event("research#0", seq)) + writer.finish(done=True) + lagging = batch_key("lgstream", "wf:1", 0, "research#0", writer.attempt, 1) + real = store.get_bulk + hidden = {"left": 1} + + def lagging_get(keys: Any) -> Any: + found = real(keys) + if lagging in found and hidden["left"]: + hidden["left"] -= 1 + found.pop(lagging) + return found + + store.get_bulk = lagging_get # type: ignore[method-assign] + (chunk,) = LogReader(store, _config(), "wf:1").read([UnitWant(0, "research#0")]) + self.assertFalse(chunk.purged, chunk) + self.assertEqual(_datas(chunk), ["research#0-0", "research#0-1"]) From 7fe311055a79a414191ae4163cc1f7aeee6fa1e0 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 16:37:15 +0100 Subject: [PATCH 59/73] fix(stream-log): look at the head again before an attempt's last write Two attempts of one unit running at once both took the head at their first flush, so the one that finished last overwrote the other's done head. The last flush now reads the head again and leaves a done head of another attempt alone. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/stream_log.py | 8 +++++++- tests/agent/core/test_stream_log.py | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/diagrid/agent/core/workflow/stream_log.py b/diagrid/agent/core/workflow/stream_log.py index 0393217a..722ef5af 100644 --- a/diagrid/agent/core/workflow/stream_log.py +++ b/diagrid/agent/core/workflow/stream_log.py @@ -262,6 +262,9 @@ def finish(self, *, done: bool) -> None: timer, self._timer = self._timer, None if timer is not None: timer.cancel() + # another attempt may have finished since the first flush: a done + # head is never overwritten, so look at the head again + self._blocked = None delay = self._config.final_flush_backoff_s for attempt in range(max(1, self._config.final_flush_attempts)): if attempt: @@ -348,7 +351,10 @@ def _flush(self, *, done: bool, final: bool = False) -> bool: return True def _is_blocked(self) -> bool: - """Whether an attempt that already finished owns the unit (read once).""" + """Whether an attempt that already finished owns the unit. + + Read at the first flush and again at the last one. + """ if self._blocked is None: key = head_key( self._config.key_prefix, self._workflow_id, self._step, self._unit diff --git a/tests/agent/core/test_stream_log.py b/tests/agent/core/test_stream_log.py index ebac7265..f0e76077 100644 --- a/tests/agent/core/test_stream_log.py +++ b/tests/agent/core/test_stream_log.py @@ -186,6 +186,26 @@ def test_a_late_attempt_keeps_the_head_but_logs_its_own_chunks(self): self.assertEqual(chunk.attempt, late.attempt) self.assertEqual(_datas(chunk), ["research#0-0", "research#0-1"]) + def test_a_concurrent_attempt_never_overwrites_a_done_head(self): + """Both attempts owned the head at their first flush; one finished first.""" + store = FakeLogStore() + a = _writer(store) + b = _writer(store) + a.put(_event("research#0", 0, attempt="a")) + a._flush(done=False) + b.put(_event("research#0", 0, attempt="b")) + b._flush(done=False) + a.finish(done=True) + b.finish(done=True) + head = store.get(head_key("lgstream", "wf:1", 0, "research#0")) + self.assertEqual(head["attempt"], a.attempt) + self.assertTrue(head["done"]) + # b's output is still in the log, through its end record + reader = LogReader(store, _config(), "wf:1") + chunk = reader.read([UnitWant(0, "research#0", winner=b.attempt)])[0] + self.assertEqual(_datas(chunk), ["research#0-0"]) + self.assertEqual(chunk.attempt, b.attempt) + def test_a_reader_follows_the_winner_of_concurrent_attempts(self): store = FakeLogStore() a = _writer(store) From bf2c69f965f03cb373ef79c2203274a1bddff54f Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 16:38:09 +0100 Subject: [PATCH 60/73] fix(langgraph): wait for the final event when a reader is behind the step window A reader that knew any step below the status's window took it as caught up, so one that knew step 0 but not steps 1..199 learned the later steps first, and a reconnect with the id it handed out skipped the gap. The reader now reads on only when it knows the step just below the window. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/stream_follow.py | 9 ++- tests/agent/langgraph/test_stream_window.py | 70 +++++++++++++++++++++ 2 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 tests/agent/langgraph/test_stream_window.py diff --git a/diagrid/agent/langgraph/stream_follow.py b/diagrid/agent/langgraph/stream_follow.py index 52fa7757..886b978e 100644 --- a/diagrid/agent/langgraph/stream_follow.py +++ b/diagrid/agent/langgraph/stream_follow.py @@ -296,11 +296,16 @@ async def _run_status( return await asyncio.to_thread(self._status) or {} def _behind_window(self, status: Dict[str, Any]) -> bool: - """Whether the status no longer lists steps this reader still needs.""" + """Whether the status no longer lists steps this reader still needs. + + The reader must know the step just below the window: one that knows + only older steps would learn the later ones first, and a cursor it + hands out then would skip the gap. + """ first = int(status.get(STATUS_EXECUTED_FROM) or 0) if not first or self._cursor.skips_step(first - 1): return False - return not any(step < first for step, _ in self._units) + return max((step for step, _ in self._units), default=-1) < first - 1 def _learn(self, units: List[Unit]) -> None: for unit in units: diff --git a/tests/agent/langgraph/test_stream_window.py b/tests/agent/langgraph/test_stream_window.py new file mode 100644 index 00000000..b3e777c6 --- /dev/null +++ b/tests/agent/langgraph/test_stream_window.py @@ -0,0 +1,70 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A reader that fell behind the status's window of steps waits for the final. + +The custom status lists the run's last steps only. A reader that knows some +early steps but not the ones just below the window must not learn the later +steps first: a cursor it then hands out would skip the gap for good. +""" + +import asyncio +import unittest +from typing import Any, Dict, Optional + +from diagrid.agent.core.workflow.stream import InProcessSink +from diagrid.agent.core.workflow.stream_cursor import StreamCursor +from diagrid.agent.core.workflow.stream_log import ( + StateLogStreamConfig, + StateLogTransport, +) +from diagrid.agent.langgraph.stream_follow import LogFollower, units_of + +from tests.agent.core.log_store_fake import FakeLogStore + + +def _behind( + known: Dict[str, Any], later: Dict[str, Any], cursor: Optional[StreamCursor] = None +) -> bool: + async def go() -> bool: + transport = StateLogTransport(StateLogStreamConfig(), store=FakeLogStore()) + sink = InProcessSink("wf", asyncio.get_running_loop(), bounded=False) + follower = LogFollower( + transport.reader("wf"), + sink, + workflow_id="wf", + status=lambda: {}, + poll_s=0.01, + cursor=cursor, + ) + follower._learn(units_of(known)) + return follower._behind_window(later) + + return asyncio.run(go()) + + +class TestBehindTheWindow(unittest.TestCase): + def test_a_gap_between_known_steps_and_the_window_waits(self): + known = {"executed": [["a"]]} # step 0 + later = {"executed_from": 200, "executed": [["z"]]} # 1..199 are gone + self.assertTrue(_behind(known, later)) + + def test_a_reader_that_knows_nothing_waits(self): + self.assertTrue(_behind({}, {"executed_from": 5, "executed": [["z"]]})) + + def test_a_reader_that_knows_the_step_before_the_window_reads_on(self): + known = {"executed_from": 70, "executed": [["a"]] * 130} # steps 70..199 + later = {"executed_from": 200, "executed": [["z"]]} + self.assertFalse(_behind(known, later)) + + def test_a_reader_that_knows_steps_inside_the_window_reads_on(self): + known = {"executed_from": 100, "executed": [["a"]] * 150} # 100..249 + later = {"executed_from": 200, "executed": [["z"]] * 60} + self.assertFalse(_behind(known, later)) + + def test_a_cursor_past_the_gap_reads_on(self): + later = {"executed_from": 200, "executed": [["z"]]} + self.assertFalse(_behind({}, later, StreamCursor(base=200))) + + def test_a_status_with_every_step_never_waits(self): + self.assertFalse(_behind({}, {"executed": [["a"], ["b"]]})) From a3ea81bbdd83283f671f88565d8ee81f9efcaa66 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 16:39:11 +0100 Subject: [PATCH 61/73] fix(langgraph): keep threads in the workflow state store when there is no other The README said a thread's state falls back to the store the workflows use, but the runner passed only the app's agent-memory store, so an app with just the workflow store (the default on Catalyst) ran every named thread from scratch. The thread store now falls back to the workflow store, as the stream log already does. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/runner.py | 2 +- diagrid/agent/langgraph/thread_state.py | 14 ++++++++++--- .../agent/langgraph/test_stream_transport.py | 21 +++++++++++++++++++ 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index f32c59fb..78e2ef9d 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -424,7 +424,7 @@ def __init__( self._continue_threads = continue_threads self._thread_store = resolve_thread_store( - checkpointer, self._graph, self._state_store + checkpointer, self._graph, self._state_store, self._workflow_store_name ) self._stream_transport = resolve_transport( self._given_transport, diff --git a/diagrid/agent/langgraph/thread_state.py b/diagrid/agent/langgraph/thread_state.py index 26dbb1ce..29dddcd8 100644 --- a/diagrid/agent/langgraph/thread_state.py +++ b/diagrid/agent/langgraph/thread_state.py @@ -94,13 +94,17 @@ def save(self, checkpoint: ThreadCheckpoint) -> None: def resolve_thread_store( - checkpointer: Any, graph: Any, state_store: Any + checkpointer: Any, + graph: Any, + state_store: Any, + workflow_store_name: Optional[str] = None, ) -> Optional[ThreadStore]: """The store a runner keeps its threads' state in, or ``None`` for none. The runner's own ``checkpointer`` first, then the one the graph was - compiled with, then the app's Dapr state store (``agent-memory``, which a - Catalyst app has). Without any of them a thread id is only a label. + compiled with, then the app's Dapr state store (``agent-memory``), else + the store the workflows use (``workflow_store_name``, which every + workflow app has). Without any of them a thread id is only a label. A graph compiled with an in-memory saver (``MemorySaver``, as LangGraph's examples do) keeps threads in one process, which breaks across replicas @@ -109,6 +113,10 @@ def resolve_thread_store( """ from .saver_store import SaverThreadStore, is_in_memory_saver, is_saver + if state_store is None and workflow_store_name: + from diagrid.agent.core.state import DaprStateStore + + state_store = DaprStateStore(store_name=workflow_store_name) if checkpointer is not None: if isinstance(checkpointer, DaprMemoryCheckpointer): return DaprThreadStore(checkpointer) diff --git a/tests/agent/langgraph/test_stream_transport.py b/tests/agent/langgraph/test_stream_transport.py index d93f3f70..d033a808 100644 --- a/tests/agent/langgraph/test_stream_transport.py +++ b/tests/agent/langgraph/test_stream_transport.py @@ -62,6 +62,27 @@ def test_the_workflow_state_store_is_enough(self): self.assertIsInstance(runner.stream_transport, StateLogTransport) self.assertEqual(runner.stream_transport.store_name, "agent-workflow") + def test_the_workflow_state_store_keeps_threads_too(self): + # the default Catalyst app: continuation needs no setup either + with _discovered(workflow_store_name="agent-workflow"): + runner = DaprWorkflowGraphRunner(graph=_golden_graph(), name="t-wf-th") + store = runner._thread_store + self.assertIsNotNone(store) + self.assertEqual( + store._checkpointer._store.store_name, # type: ignore[union-attr] + "agent-workflow", + ) + + def test_the_app_memory_store_keeps_threads_before_the_workflow_store(self): + with _discovered( + memory_store_name="agent-memory", workflow_store_name="agent-workflow" + ): + runner = DaprWorkflowGraphRunner(graph=_golden_graph(), name="t-mem-th") + self.assertEqual( + runner._thread_store._checkpointer._store.store_name, # type: ignore[union-attr] + "agent-memory", + ) + def test_a_given_transport_wins(self): mine = StateLogTransport(StateLogStreamConfig(store_name="mine")) with _discovered(memory_store_name="agent-memory"): From 1786d58fc4ae124029d5b25782a756aae796fe88 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 16:41:53 +0100 Subject: [PATCH 62/73] fix(langgraph): load a thread's state whatever its id and concurrent saves do - A thread id holding '||' made every run fail on the old-format index key, which Dapr refuses. Such ids are now a 422 over HTTP (they also end up in the workflow id), the old keys are never read for them, and an old key the store cannot read is skipped with a warning. - With keep_checkpoints=1 a concurrent save could delete the checkpoint the index named before the load read it, and the thread started over. A load that misses its checkpoint now reads the index once more, and keep_checkpoints must be at least 2. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/runner.py | 11 +++ diagrid/agent/langgraph/README.md | 7 +- diagrid/agent/langgraph/runner.py | 11 ++- diagrid/agent/langgraph/state.py | 67 +++++++++++++++---- diagrid/agent/langgraph/thread_state.py | 27 ++++++++ .../langgraph/test_checkpointer_store.py | 61 ++++++++++++++++- tests/agent/langgraph/test_thread_scope.py | 16 +++++ 7 files changed, 177 insertions(+), 23 deletions(-) diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 3adcae7f..0afef020 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -682,6 +682,10 @@ async def _run_and_collect(request: dict) -> dict: # type: ignore[type-arg] @app.post("/agent/run") async def run_agent(request: dict) -> Any: # type: ignore[type-arg] + try: + self._validate_run_request(request) + except ValueError as e: + raise HTTPException(status_code=422, detail=str(e)) # Only the JSON value true streams. Anything else ("false", an # object) is a plain request whose "stream" key may be the graph's own. if request.get("stream") is True and self._supports_serve_stream: @@ -751,6 +755,13 @@ def _add_routes(self, app: Any) -> None: """Register a runner's own routes on the ``serve()`` app. Default: none.""" return None + def _validate_run_request(self, request: dict) -> None: # type: ignore[type-arg] + """Raise ``ValueError`` if a ``POST /agent/run`` (any kind) is invalid. + + The client gets a 422 and no run starts. Default: accept all. + """ + return None + def _validate_stream_request(self, request: dict) -> None: # type: ignore[type-arg] """Raise ``ValueError`` if a streaming request is invalid. diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 07d35dfe..4ecce0a1 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -79,13 +79,16 @@ result = runner.invoke( ``` That is all. `thread_id` may also come as `config["configurable"]["thread_id"]` -or, over HTTP, as `thread_id` (or `session_id`) in the request body. Each run +or, over HTTP, as `thread_id` (or `session_id`) in the request body (one that +holds `||`, which Dapr reserves in keys, is a `422`). Each run starts from the state the thread's last run ended with and applies its input to it through the channels' reducers, as LangGraph does with a checkpointer. The state is kept in the app's Dapr state store (`agent-memory`, which a Catalyst app has, else the store the workflows use), keyed by thread; a thread keeps its last two checkpoints, which expire 30 days after its last -run (`DaprMemoryCheckpointer(ttl_s=..., keep_checkpoints=...)`). Runs on one +run (`DaprMemoryCheckpointer(ttl_s=..., keep_checkpoints=...)`; it keeps at +least two, so a run never loses the one it is loading to a concurrent save). +Runs on one thread at the same time each start from the state before them, and the last one to end sets the thread's state. diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 78e2ef9d..53c6e881 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -73,7 +73,9 @@ SAVE_THREAD_ACTIVITY, make_load_activity, make_save_activity, + request_thread_id, resolve_thread_store, + validate_run_request, ) from .limits import StepBound, step_bound from .workflow import ( @@ -1286,15 +1288,13 @@ async def _serve_run( request: dict, session_id: str, # type: ignore[type-arg] ) -> AsyncIterator[dict[str, Any]]: - # only a thread the caller names carries state: no id, a stateless run - thread_id = request.get("thread_id") or request.get("session_id") - graph_input = self._request_to_input(request) - + thread_id = request_thread_id(request) async for event in self.run_async(input=graph_input, thread_id=thread_id): yield event _supports_serve_stream = True + _validate_run_request = staticmethod(validate_run_request) _DEFAULT_STREAM_MODES = ["messages", "updates", "custom"] @@ -1315,8 +1315,7 @@ async def _serve_stream( # type: ignore[override] Ends with ``workflow_completed`` or ``workflow_failed``, whose data is the run's full terminal event. The base runner frames the pairs. """ - # only a thread the caller names carries state: no id, a stateless run - thread_id = request.get("thread_id") or request.get("session_id") + thread_id = request_thread_id(request) encoder: Optional[SseEncoder] = None try: modes, _ = normalize_stream_mode( diff --git a/diagrid/agent/langgraph/state.py b/diagrid/agent/langgraph/state.py index 8a338cbd..a8872f0a 100644 --- a/diagrid/agent/langgraph/state.py +++ b/diagrid/agent/langgraph/state.py @@ -17,6 +17,8 @@ DEFAULT_THREAD_TTL_S = 30 * 24 * 3600 #: How many checkpoints a thread keeps: the latest, and the one before it. DEFAULT_KEEP_CHECKPOINTS = 2 +#: Fewer, and a concurrent save could delete the checkpoint a load is reading. +MIN_KEEP_CHECKPOINTS = 2 #: Tries at writing a thread's index when other runs write it at the same time. INDEX_WRITE_ATTEMPTS = 8 @@ -37,8 +39,10 @@ class DaprMemoryCheckpointer: saved under the earlier ``langgraph-{thread_id}-checkpoint-{id}`` keys are still read. - A thread keeps its last ``keep_checkpoints`` checkpoints (older ones are - deleted), and its checkpoints and index expire ``ttl_s`` seconds after the + A thread keeps its last ``keep_checkpoints`` checkpoints (at least two: + older ones are deleted, and a load whose checkpoint a concurrent save just + deleted reads the index again), and its checkpoints and index expire + ``ttl_s`` seconds after the thread's last save (``None``: never; the state store must support TTLs). The index is written with an etag (first-write concurrency) where the store supports it, so concurrent runs on one thread lose none of its entries. @@ -78,8 +82,11 @@ def __init__( ttl_s: Optional[int] = DEFAULT_THREAD_TTL_S, keep_checkpoints: int = DEFAULT_KEEP_CHECKPOINTS, ) -> None: - if keep_checkpoints < 1: - raise ValueError("keep_checkpoints must be at least 1") + if keep_checkpoints < MIN_KEEP_CHECKPOINTS: + raise ValueError( + f"keep_checkpoints must be at least {MIN_KEEP_CHECKPOINTS}: a " + "concurrent save must not delete the checkpoint a run is loading" + ) if ttl_s is not None and ttl_s < 1: raise ValueError("ttl_s must be a positive number of seconds, or None") self._store = state_store or DaprStateStore( @@ -176,16 +183,48 @@ def load_checkpoint( """ if checkpoint_id is not None: found = self._store.get(self._checkpoint_key(thread_id, checkpoint_id)) - return found or self._store.get( - _legacy_checkpoint_key(thread_id, checkpoint_id) + return found or self._legacy_get( + thread_id, _legacy_checkpoint_key, checkpoint_id ) - index = self._store.get(self._thread_index_key(thread_id)) - if index and index.get("latest"): - return self._store.get(self._checkpoint_key(thread_id, index["latest"])) - legacy = self._store.get(_legacy_index_key(thread_id)) + # a save may prune the checkpoint the index named between the two + # reads: the index read again names the one that replaced it + for _ in range(2): + index = self._store.get(self._thread_index_key(thread_id)) + if not index or not index.get("latest"): + break + found = self._store.get(self._checkpoint_key(thread_id, index["latest"])) + if found: + return found + else: + return None + legacy = self._legacy_get(thread_id, _legacy_index_key) if not legacy or not legacy.get("latest"): return None - return self._store.get(_legacy_checkpoint_key(thread_id, legacy["latest"])) + return self._legacy_get(thread_id, _legacy_checkpoint_key, legacy["latest"]) + + def _legacy_get( + self, thread_id: str, key_of: Callable[..., str], *rest: str + ) -> Any: + """A value under the old ``-`` keys, or ``None`` when it cannot be read. + + A thread id that holds ``||`` cannot be in an old key (Dapr reserves + it), and an old key the store refuses holds no state worth a failed run. + """ + if _ACTOR_SEPARATOR in thread_id: + return None + key = key_of(thread_id, *rest) + try: + return self._store.get(key) + except Exception as e: + logger.warning( + "The old-format key %r of thread %r could not be read (%s: %s); " + "going on without it", + key, + thread_id, + type(e).__name__, + e, + ) + return None def list_checkpoints(self, thread_id: str) -> list[str]: """List all checkpoint IDs for a thread. @@ -198,7 +237,7 @@ def list_checkpoints(self, thread_id: str) -> list[str]: """ index = self._store.get(self._thread_index_key(thread_id)) if not index: - index = self._store.get(_legacy_index_key(thread_id)) + index = self._legacy_get(thread_id, _legacy_index_key) if not index: return [] return list(index.get("checkpoints", [])) @@ -218,6 +257,10 @@ def close(self) -> None: self._store.close() +#: Dapr's actor key separator: never in a key, so never in an old-format one. +_ACTOR_SEPARATOR = "||" + + def _segment(value: str) -> str: """``value`` escaped so it is one segment of a ``:``-separated key.""" return quote(str(value), safe="") diff --git a/diagrid/agent/langgraph/thread_state.py b/diagrid/agent/langgraph/thread_state.py index 29dddcd8..49f45ecb 100644 --- a/diagrid/agent/langgraph/thread_state.py +++ b/diagrid/agent/langgraph/thread_state.py @@ -93,6 +93,33 @@ def save(self, checkpoint: ThreadCheckpoint) -> None: ) +#: Dapr's actor key separator: no key or workflow id may hold it. +ACTOR_SEPARATOR = "||" + + +def request_thread_id(request: Dict[str, Any]) -> Optional[str]: + """The thread an HTTP request names (``thread_id`` or ``session_id``). + + Only a thread the caller names carries state: no id, a stateless run. + """ + return request.get("thread_id") or request.get("session_id") + + +def validate_run_request(request: Dict[str, Any]) -> None: + """Refuse a request whose thread id cannot be part of a Dapr key. + + The thread id goes into the run's workflow id and its state keys; Dapr + reserves ``||`` in both. + """ + for name in ("thread_id", "session_id"): + value = request.get(name) + if value is not None and ACTOR_SEPARATOR in str(value): + raise ValueError( + f"{name} must not contain {ACTOR_SEPARATOR!r}: Dapr reserves it " + "in state keys and workflow ids" + ) + + def resolve_thread_store( checkpointer: Any, graph: Any, diff --git a/tests/agent/langgraph/test_checkpointer_store.py b/tests/agent/langgraph/test_checkpointer_store.py index 92006eb5..3b100879 100644 --- a/tests/agent/langgraph/test_checkpointer_store.py +++ b/tests/agent/langgraph/test_checkpointer_store.py @@ -55,9 +55,34 @@ def test_a_thread_keeps_only_its_last_checkpoints(self): cp.load_checkpoint("t1")["channel_values"], {"messages": ["cp4"]} ) - def test_keep_checkpoints_must_be_positive(self): - with self.assertRaises(ValueError): - DaprMemoryCheckpointer(state_store=MemoryStateStore(), keep_checkpoints=0) # type: ignore[arg-type] + def test_keep_checkpoints_must_be_at_least_two(self): + # with one, a concurrent save deletes the checkpoint a load was reading + for keep in (0, 1): + with self.assertRaises(ValueError): + DaprMemoryCheckpointer( + state_store=MemoryStateStore(), keep_checkpoints=keep + ) # type: ignore[arg-type] + + def test_a_checkpoint_pruned_under_a_load_is_read_from_a_fresh_index(self): + store = MemoryStateStore() + cp = DaprMemoryCheckpointer(state_store=store) # type: ignore[arg-type] + other = DaprMemoryCheckpointer(state_store=store) # type: ignore[arg-type] + _save(cp, "t1", "cp1") + real_get = store.get + raced = [] + + def racing_get(key: str) -> Any: + found = real_get(key) + if key.endswith(":index") and not raced: + # two saves land between the index read and the checkpoint read + raced.append(key) + _save(other, "t1", "cp2") + _save(other, "t1", "cp3") + return found + + store.get = racing_get # type: ignore[method-assign] + loaded = cp.load_checkpoint("t1") + self.assertEqual(loaded["channel_values"], {"messages": ["cp3"]}) class TestConcurrentRuns(unittest.TestCase): @@ -122,3 +147,33 @@ def test_a_new_save_takes_over_from_the_old_keys(self): self.assertEqual( cp.load_checkpoint("t1")["channel_values"], {"messages": ["cp2"]} ) + + +class _RefusingStore(MemoryStateStore): + """Refuses keys as Dapr does: ``||`` is the actor separator; ``broken`` fails.""" + + def __init__(self, broken: str = "") -> None: + super().__init__() + self.broken = broken + + def get(self, key: str) -> Any: + if "||" in key or (self.broken and key == self.broken): + raise RuntimeError(f"state store refused key {key!r}") + return super().get(key) + + +class TestThreadIdsTheOldKeysCannotHold(unittest.TestCase): + def test_a_thread_id_with_the_actor_separator_never_reads_the_old_keys(self): + cp = DaprMemoryCheckpointer(state_store=_RefusingStore()) # type: ignore[arg-type] + self.assertIsNone(cp.load_checkpoint("a||b")) + self.assertEqual(cp.list_checkpoints("a||b"), []) + _save(cp, "a||b", "cp1") + self.assertEqual( + cp.load_checkpoint("a||b")["channel_values"], {"messages": ["cp1"]} + ) + + def test_an_old_index_that_cannot_be_read_is_skipped(self): + store = _RefusingStore(broken="langgraph-t1-index") + cp = DaprMemoryCheckpointer(state_store=store) # type: ignore[arg-type] + with self.assertLogs("diagrid.agent.langgraph.state", "WARNING"): + self.assertIsNone(cp.load_checkpoint("t1")) diff --git a/tests/agent/langgraph/test_thread_scope.py b/tests/agent/langgraph/test_thread_scope.py index 680d1e4c..6985cec8 100644 --- a/tests/agent/langgraph/test_thread_scope.py +++ b/tests/agent/langgraph/test_thread_scope.py @@ -103,6 +103,22 @@ def test_an_http_run_without_ids_is_stateless_with_a_full_uuid(self): ) +class TestThreadIdsOverHttp(_FakeDaprTest): + def test_a_thread_id_with_the_actor_separator_is_refused(self): + runner = log_runner(chat_graph(), "scope-sep") + http = TestClient(serve_app(runner)) + for key in ("thread_id", "session_id"): + for stream in (True, False): + with self.subTest(key=key, stream=stream): + response = http.post( + "/agent/run", + json={**turn("hi"), key: "a||b", "stream": stream}, + ) + self.assertEqual(response.status_code, 422, response.text) + self.assertIn("||", response.text) + self.assertEqual(runner._workflow_client.inputs, {}) + + class TestResentHistory(_FakeDaprTest): def test_messages_resent_with_their_ids_are_not_duplicated(self): runner = _runner("scope-resend") From 58c6f0cb54069b1a7567f7f827c98af25c26914a Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 16:53:20 +0100 Subject: [PATCH 63/73] fix(langgraph): a replay of a run whose whole log expired says stream_purged Past the heads' TTL (a day by default) nothing of a finished run is left in the log, and a replay reported every unit as stream_unavailable with reason write_failed. A reconnect that finds no head for any unit it reads now sends stream_purged; a unit missing among others that are there, and a live stream's, is still a failed write. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 4 +- diagrid/agent/langgraph/reconnect.py | 1 + diagrid/agent/langgraph/stream_follow.py | 44 ++++++++++++++++--- diagrid/agent/langgraph/stream_source.py | 2 + tests/agent/langgraph/test_reconnect_purge.py | 39 ++++++++++++++++ 5 files changed, 83 insertions(+), 7 deletions(-) diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 4ecce0a1..8c0f1ec5 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -308,7 +308,9 @@ client saw part of its output, the stream sends `node_reset` for it before the new attempt's chunks. If part of the log has expired, the stream sends `stream_purged` once and goes on with what is still there and what comes live (a run resumed after waiting on `interrupt()` for longer than the batch -TTL streams everything after the resume), then the final event. +TTL streams everything after the resume), then the final event. A run that +ended more than a day ago has no log left at all: its replay is +`stream_purged` and the final event. On the in-process transport nothing can be replayed: the endpoint answers with `workflow_started`, then `stream_unavailable` with reason diff --git a/diagrid/agent/langgraph/reconnect.py b/diagrid/agent/langgraph/reconnect.py index 74311afb..91dce641 100644 --- a/diagrid/agent/langgraph/reconnect.py +++ b/diagrid/agent/langgraph/reconnect.py @@ -159,6 +159,7 @@ async def resume_events( status=lambda: custom_status(client, workflow_id), seen=seen, cursor=cursor, + replay=True, ) async def pump() -> None: diff --git a/diagrid/agent/langgraph/stream_follow.py b/diagrid/agent/langgraph/stream_follow.py index 886b978e..056fdf60 100644 --- a/diagrid/agent/langgraph/stream_follow.py +++ b/diagrid/agent/langgraph/stream_follow.py @@ -150,6 +150,7 @@ def __init__( decode: Callable[[str, Any], Any] = decode_wire, seen: Optional[Set[Unit]] = None, from_end: bool = False, + replay: bool = False, ) -> None: self._reader = reader self._sink = sink @@ -173,6 +174,9 @@ def __init__( self.purged = False #: Start after what the log holds when the follower starts (a resumed run). self._from_end = from_end + #: A reconnect: the run may have ended long enough ago that its whole + #: log expired (see ``_expired``). + self._replay = replay #: Set once the follower knows where it starts reading. self.ready = asyncio.Event() self._final: "asyncio.Future[Dict[str, Any]]" = ( @@ -273,6 +277,31 @@ async def _read_once(self, final: Optional[Dict[str, Any]]) -> None: self._purge(chunk) continue await self._deliver(chunk) + if final is not None and self._expired(): + self._say_purged(min(step for step, _ in self._wanted())) + + def _expired(self) -> bool: + """Whether a replayed run's whole log is gone: its heads expired too. + + Heads outlive batches (a day by default), and a run that ended that + long ago has none left. A unit missing among others that are there + is still a write that failed, and so is a live stream's. + """ + wanted = self._wanted() + return ( + self._replay + and not self.purged + and bool(wanted) + and all(state.attempt is None for state in wanted.values()) + ) + + def _wanted(self) -> Dict[Unit, _UnitState]: + """The units this stream reads: those its cursor did not skip whole.""" + return { + unit: state + for unit, state in self._units.items() + if not self._cursor.skips_step(unit[0]) + } async def _run_status( self, final: Optional[Dict[str, Any]] @@ -340,26 +369,29 @@ def _purge(self, chunk: UnitChunk) -> None: state.skip = 0 state.done = chunk.done self._seen.add((chunk.step, chunk.unit)) + self._say_purged(chunk.step) + + def _say_purged(self, step: int) -> None: + """Send ``stream_purged`` (once): the log is gone from ``step`` on.""" if self.purged: return self.purged = True logger.warning( - "The stream log of %s is purged (unit %s of step %s): it outlived its " - "TTL; streaming what is left", + "The stream log of %s is purged from step %s: it outlived its TTL; " + "streaming what is left", self._workflow_id, - chunk.unit, - chunk.step, + step, ) self._sink.put( StreamEvent( workflow_id=self._workflow_id, - step=chunk.step, + step=step, node="", attempt_id="", seq=0, ns=(), mode=STREAM_PURGED, - data={"workflow_id": self._workflow_id, "step": chunk.step + 1}, + data={"workflow_id": self._workflow_id, "step": step + 1}, event_id=self.event_id(), ) ) diff --git a/diagrid/agent/langgraph/stream_source.py b/diagrid/agent/langgraph/stream_source.py index a191b230..53b2befe 100644 --- a/diagrid/agent/langgraph/stream_source.py +++ b/diagrid/agent/langgraph/stream_source.py @@ -76,6 +76,7 @@ def open_source( seen: Set[Tuple[int, str]], cursor: Optional[StreamCursor] = None, from_end: bool = False, + replay: bool = False, ) -> StreamSource: """The source of a stream of ``workflow_id`` on ``transport``. @@ -93,6 +94,7 @@ def open_source( decode=transport.decode, seen=seen, from_end=from_end, + replay=replay, ) task = asyncio.create_task(follower.run()) return StreamSource(sink, follower.finish, follower=follower, task=task) diff --git a/tests/agent/langgraph/test_reconnect_purge.py b/tests/agent/langgraph/test_reconnect_purge.py index fd6d4ae8..5f72bb29 100644 --- a/tests/agent/langgraph/test_reconnect_purge.py +++ b/tests/agent/langgraph/test_reconnect_purge.py @@ -76,3 +76,42 @@ def test_a_reconnect_after_a_long_interrupt_streams_the_rest(self): self.assertEqual(updates, ["ask", "after"]) self.assertEqual(names[-1], "workflow_completed") self.assertEqual(names.count("stream_purged"), 1) + + +class TestWholeLogExpired(_RunnerTestCase): + """Past the heads' TTL (a day by default) nothing of the run is left.""" + + def _ended_and_expired(self, name: str) -> Any: + store = FakeLogStore() + runner = log_runner(_graph(), name, store=store) + http = TestClient(serve_app(runner)) + got = frames(http.post("/agent/run", json={"log": [], "stream": True}).text) + wf = got[-1][2]["workflow_id"] + rest = frames( + http.post( + f"/agent/run/{wf}/resume", json={"resume": "yes", "stream": True} + ).text + ) + self.assertEqual(rest[-1][1], "workflow_completed") + for key in list(store.data): # heads and end records expired too + store.delete(key) + return http, wf, rest + + def test_a_replay_says_the_log_expired_not_that_writes_failed(self): + http, wf, _ = self._ended_and_expired("expired-all") + again = frames(http.get(f"/agent/run/{wf}/stream").text) + names = [e for _, e, _ in again] + self.assertEqual(names.count("stream_purged"), 1, names) + self.assertNotIn("stream_unavailable", names) + self.assertEqual(names[-1], "workflow_completed") + + def test_a_client_that_had_every_chunk_is_told_nothing_expired(self): + http, wf, rest = self._ended_and_expired("expired-had-all") + last = [i for i, e, _ in rest if e not in ("workflow_completed",)][-1] + again = frames( + http.get(f"/agent/run/{wf}/stream", headers={"Last-Event-ID": last}).text + ) + names = [e for _, e, _ in again] + self.assertNotIn("stream_purged", names) + self.assertNotIn("stream_unavailable", names) + self.assertEqual(names[-1], "workflow_completed") From 2584fea027d6affa517e1b398dff131e385b78e6 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 17:01:04 +0100 Subject: [PATCH 64/73] fix(langgraph): resume each of a subgraph's parallel interrupts by its own id A subgraph a node runs starts afresh on every run of the node, so LangGraph's ids for its interrupts change from run to run, and its parallel nodes take the task's resume values in whatever order they ask. An id map answering one of two such interrupts gave its value to the wrong one and re-issued the other under a new id. A subgraph's interrupt is now reported under an id made of the task and the path of node names down to it, the workflow tags each answer with that id, and the interrupt that asks gets its own value; one left unanswered keeps its id. Activity outputs of runs started earlier carry no path, so their replay is unchanged. Tasks a subgraph sends to one node cannot be told apart across runs: an id map naming only some of their interrupts is refused (422 over HTTP, ValueError in Python), as the README says. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 9 + diagrid/agent/langgraph/interrupt_ids.py | 99 ++++++++++ diagrid/agent/langgraph/interrupts.py | 77 +++++++- diagrid/agent/langgraph/invoke_result.py | 4 + diagrid/agent/langgraph/resume_run.py | 25 ++- diagrid/agent/langgraph/workflow.py | 2 +- .../agent/langgraph/test_interrupt_nested.py | 174 +++++++++++++++++- 7 files changed, 369 insertions(+), 21 deletions(-) create mode 100644 diagrid/agent/langgraph/interrupt_ids.py diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 8c0f1ec5..95257e08 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -427,6 +427,15 @@ needed for this. returns) and in the node's router (its conditional edge). A node that calls a subgraph that pauses and drops its result fails with an error that says so, rather than going on as if it had not paused. +- Interrupts that pause together in one subgraph (its parallel nodes) each + keep their id until answered, and a dict keyed by their ids answers some + of them and leaves the others waiting. Their ids are not LangGraph's own + (a subgraph run here keeps no checkpoint of its own, so LangGraph's would + change on every run). The one exception: tasks a subgraph sends to one + node (`Send`) cannot be told apart from one run to the next, so their + interrupts must be answered all in one resume, with one value or a dict + naming every one of them; a dict that names only some is a `422` + (`ValueError` in Python). ### Limits diff --git a/diagrid/agent/langgraph/interrupt_ids.py b/diagrid/agent/langgraph/interrupt_ids.py new file mode 100644 index 00000000..eaf635db --- /dev/null +++ b/diagrid/agent/langgraph/interrupt_ids.py @@ -0,0 +1,99 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Stable ids for the interrupts of a subgraph a task runs, and resumes by id. + +LangGraph names an interrupt by its task's checkpoint namespace. A subgraph +the node runs starts afresh on every run of the task (its checkpoint is not +kept), so the namespaces of its tasks, and the ids of their interrupts, change +from one run to the next. Two of its nodes that pause in parallel ask the +task's scratchpad for their resume values in whatever order they get there. + +So a nested interrupt is reported under an id made of the task's namespace and +the path of node names down to it (stable on every run), and the workflow +hands its resume value to the task tagged with that id: each interrupt gets +its own value, and one left unanswered keeps its id. Interrupts whose paths +collide (a subgraph that sends two tasks to one node) keep LangGraph's ids and +take their values in order; an id map that answers only some of them is +refused. +""" + +import hashlib +from typing import Any, Dict, List, Optional, Sequence, Tuple + +#: The key of a resume value the workflow tags with the interrupt it is for. +RESUME_FOR = "__diagrid_resume_for__" +#: An interrupt payload's key holding the path of a nested interrupt. +PATH_KEY = "path" +#: LangGraph's separators in a checkpoint namespace: between levels, and +#: between a node's name and its task id (neither is allowed in a node name). +_NS_SEP = "|" +_NS_END = ":" + + +def nested_ids(namespace: str) -> Optional[Tuple[str, str, str]]: + """``(LangGraph's id, stable id, path)`` of the interrupt asking now. + + ``None`` when the one asking is the task's own (its namespace is the + task's), or when it cannot be told (no runnable config). + """ + from langgraph._internal._constants import CONFIG_KEY_CHECKPOINT_NS + from langgraph.config import get_config + from langgraph.types import Interrupt + + try: + ns = get_config().get("configurable", {}).get(CONFIG_KEY_CHECKPOINT_NS) + except RuntimeError: # not inside a runnable + return None + if not ns or ns == namespace: + return None + path = _NS_SEP.join(part.rsplit(_NS_END, 1)[0] for part in ns.split(_NS_SEP)) + stable = hashlib.sha256(f"{namespace}{_NS_SEP}{path}".encode()).hexdigest()[:32] + return Interrupt.from_ns(value=None, ns=ns).id, stable, path + + +def tagged(interrupt_id: str, value: Any) -> Dict[str, Any]: + """``value`` tagged with the nested interrupt it answers (see :func:`split`).""" + return {RESUME_FOR: interrupt_id, "value": value} + + +def split(values: Sequence[Any]) -> Tuple[List[Any], Dict[str, List[Any]]]: + """A task's resume values: ``(in order, by nested interrupt id)``. + + A nested node that asks again keeps its id (as LangGraph's interrupts of + one task share theirs), so each id has its answers in the order given. + """ + ordered: List[Any] = [] + by_id: Dict[str, List[Any]] = {} + for value in values: + if isinstance(value, dict) and set(value) == {RESUME_FOR, "value"}: + by_id.setdefault(str(value[RESUME_FOR]), []).append(value["value"]) + else: + ordered.append(value) + return ordered, by_id + + +def partial_map_error(pending: Sequence[Dict[str, Any]], resume: Any) -> Optional[str]: + """Why ``resume`` cannot resume ``pending``, or ``None`` when it can. + + An id map that leaves out an interrupt of a task with several pending, + where one of them has no stable id, cannot say which value is whose. + """ + ids = {str(p.get("id")) for p in pending} + if not (isinstance(resume, dict) and resume and set(resume) <= ids): + return None + by_task: Dict[Any, List[Dict[str, Any]]] = {} + for item in pending: + by_task.setdefault(item.get("task"), []).append(item) + for items in by_task.values(): + answered = [str(i.get("id")) in resume for i in items] + unstable = any(not i.get(PATH_KEY) for i in items) + if len(items) > 1 and unstable and not all(answered): + node = items[0].get("node") + return ( + f"node {node!r} waits on {len(items)} interrupts of tasks a " + "subgraph sent to one node, which keep no id across runs: " + "answer every interrupt of the node in one resume (an id map " + "naming them all, or one value for all)" + ) + return None diff --git a/diagrid/agent/langgraph/interrupts.py b/diagrid/agent/langgraph/interrupts.py index c6684fec..9c3cde1a 100644 --- a/diagrid/agent/langgraph/interrupts.py +++ b/diagrid/agent/langgraph/interrupts.py @@ -35,6 +35,7 @@ from types import SimpleNamespace from typing import Any, Callable, Dict, Generator, List, Optional, Sequence, Tuple +from . import interrupt_ids from .models import ExecuteNodeOutput #: The langgraph versions whose internals ``interrupt()`` support is built on. @@ -90,14 +91,23 @@ class TaskResumes: ask the task's scratchpad for a resume value when they have none) share one order: the order the interrupts happened in on the run that paused. ``nested_missed`` is set when a subgraph asked and none was left: it - paused, and its interrupt must not be lost. + paused, and its interrupt must not be lost. A value the workflow tagged + with a nested interrupt's stable id goes to that interrupt only (see + :mod:`.interrupt_ids`), and an interrupt that paused here is reported + under its stable id. """ def __init__(self, values: Optional[Sequence[Any]] = None) -> None: - self._values = tuple(values or ()) + ordered, by_id = interrupt_ids.split(values or ()) + self._values = tuple(ordered) + self._by_id = by_id + #: Answers of each nested interrupt id handed out so far. + self._by_id_used: Dict[str, int] = {} self._next = 0 self._lock = threading.Lock() self.nested_missed = False + #: LangGraph's id of each nested interrupt that paused -> (stable id, path) + self._paused: Dict[str, Tuple[str, str]] = {} @property def values(self) -> List[Any]: @@ -110,9 +120,21 @@ def next_index(self) -> int: self._next += 1 return index - def null_resume(self, consume: bool = False) -> Any: - """The next resume value, for an interrupt that has none of its own.""" + def null_resume(self, consume: bool = False, namespace: str = "") -> Any: + """The resume value of an interrupt that has none of its own. + + A nested interrupt the workflow answered by id gets its own value; + any other takes the next one in order. + """ + nested = interrupt_ids.nested_ids(namespace) if namespace else None with self._lock: + if nested is not None: + answers = self._by_id.get(nested[1], []) + used = self._by_id_used.get(nested[1], 0) + if used < len(answers): + if consume: + self._by_id_used[nested[1]] = used + 1 + return answers[used] if self._next < len(self._values): value = self._values[self._next] if consume: @@ -120,8 +142,23 @@ def null_resume(self, consume: bool = False) -> Any: return value if consume: self.nested_missed = True + if nested is not None: + self._paused[nested[0]] = (nested[1], nested[2]) return None + def reported(self, interrupt_id: str) -> Tuple[str, Optional[str]]: + """``(id, path)`` an interrupt that paused here is reported under. + + A nested one gets its stable id and path, unless another one that + paused has the same path: those keep LangGraph's ids (and no path). + """ + with self._lock: + found = self._paused.get(interrupt_id) + if found is None: + return interrupt_id, None + twins = [p for p in self._paused.values() if p[0] == found[0]] + return (found[0], found[1]) if len(twins) == 1 else (interrupt_id, None) + def interrupt_config( *, @@ -146,7 +183,7 @@ def interrupt_config( stop=stop or 0, call_counter=lambda: next(calls), interrupt_counter=task.next_index, - get_null_resume=task.null_resume, + get_null_resume=lambda consume=False: task.null_resume(consume, namespace), resume=task.values, subgraph_counter=lambda: next(subgraphs), ) @@ -211,15 +248,27 @@ def nested_interrupts(result: Any, resumes: TaskResumes, node_name: str) -> Any: return result -def interrupt_payloads(error: BaseException) -> List[Dict[str, Any]]: - """The interrupts a ``GraphInterrupt`` carries, as JSON.""" +def interrupt_payloads( + error: BaseException, resumes: Optional[TaskResumes] = None +) -> List[Dict[str, Any]]: + """The interrupts a ``GraphInterrupt`` carries, as JSON. + + With the task's ``resumes``, a subgraph's interrupt gets its stable id + and its path (see :mod:`.interrupt_ids`). + """ found = error.args[0] if error.args else () out = [] for item in found or (): + interrupt_id = str(getattr(item, "id", "")) + path = None + if resumes is not None: + interrupt_id, path = resumes.reported(interrupt_id) payload: Dict[str, Any] = { - "id": str(getattr(item, "id", "")), + "id": interrupt_id, "value": _plain(getattr(item, "value", None)), } + if path: + payload[interrupt_ids.PATH_KEY] = path schema = getattr(item, "response_schema", None) if schema is not None: payload["response_schema"] = _plain(schema) @@ -286,7 +335,11 @@ def settle_interrupts( publish(run) for item in pending: if item["id"] in values: - resumes.setdefault(item["task"], []).append(values[item["id"]]) + value = values[item["id"]] + if item.get(interrupt_ids.PATH_KEY): + # a subgraph's: its own value, whatever order they ask in + value = interrupt_ids.tagged(item["id"], value) + resumes.setdefault(item["task"], []).append(value) again = yield from rerun( {task: resumes.get(task, []) for task in {p["task"] for p in pending}} ) @@ -334,6 +387,10 @@ def pending_interrupt(status: Dict[str, Any]) -> Optional[Dict[str, Any]]: return pending if isinstance(pending, dict) and pending.get("interrupts") else None +#: Keys of a pending interrupt the workflow keeps for itself. +_INTERNAL_KEYS = ("task", interrupt_ids.PATH_KEY) + + def interrupted_event( status: Dict[str, Any], workflow_id: str, after_seq: int = 0 ) -> Optional[Dict[str, Any]]: @@ -347,7 +404,7 @@ def interrupted_event( "status": "interrupted", "interrupt_seq": int(pending.get("seq") or 0), "interrupts": [ - {k: v for k, v in item.items() if k != "task"} + {k: v for k, v in item.items() if k not in _INTERNAL_KEYS} for item in pending["interrupts"] ], } diff --git a/diagrid/agent/langgraph/invoke_result.py b/diagrid/agent/langgraph/invoke_result.py index cf83cab6..ff46f12f 100644 --- a/diagrid/agent/langgraph/invoke_result.py +++ b/diagrid/agent/langgraph/invoke_result.py @@ -18,6 +18,7 @@ from dapr.ext.workflow import WorkflowStatus from .activity_stream import parse_status +from .interrupt_ids import partial_map_error from .interrupts import INTERRUPT_KEY, RESUME_EVENT, as_interrupts from .interrupts import interrupted_event, pending_interrupt, resume_taken from .models import GraphWorkflowOutput @@ -157,6 +158,9 @@ def invoke_resume( pending = pending_interrupt(parse_status(state.serialized_custom_status)) if state.runtime_status != WorkflowStatus.RUNNING or pending is None: raise ValueError(f"Workflow {workflow_id!r} is not waiting for a resume") + error = partial_map_error(pending["interrupts"], command.resume) + if error is not None: + raise ValueError(error) seq = int(pending.get("seq") or 0) resume_id = uuid.uuid4().hex client.raise_workflow_event( diff --git a/diagrid/agent/langgraph/resume_run.py b/diagrid/agent/langgraph/resume_run.py index 535d728b..aa08a991 100644 --- a/diagrid/agent/langgraph/resume_run.py +++ b/diagrid/agent/langgraph/resume_run.py @@ -24,6 +24,7 @@ from diagrid.agent.core.workflow.stream import frame_sse from .activity_stream import parse_status +from .interrupt_ids import partial_map_error from .interrupts import RESUME_EVENT, pending_interrupt, resume_taken from .reconnect import _thread_of, follow_final from .stream_drain import SseEncoder, drain @@ -42,16 +43,21 @@ class ResumeConflict(NotInterrupted): """Another resume of the same interrupt got to the run first.""" +class InvalidResume(ValueError): + """A resume value the run's pending interrupts cannot take (``422``).""" + + #: Seconds a caller waits for the run to take its resume before following it #: anyway (a sidecar that is slow to deliver the event). TAKE_TIMEOUT_S = 30.0 -async def _pending(runner: Any, workflow_id: str) -> Tuple[int, str]: +async def _pending(runner: Any, workflow_id: str, value: Any) -> Tuple[int, str]: """``(interrupt seq, thread id)`` of a run waiting for a resume. Raises ``LookupError`` for an unknown run, :class:`NotInterrupted` for a - run that is not waiting. + run that is not waiting, :class:`InvalidResume` for a ``value`` its + interrupts cannot take. """ client = runner._workflow_client state = await asyncio.to_thread(client.get_workflow_state, instance_id=workflow_id) @@ -62,6 +68,9 @@ async def _pending(runner: Any, workflow_id: str) -> Tuple[int, str]: ) if pending is None: raise NotInterrupted(f"Workflow {workflow_id!r} is not waiting for a resume") + error = partial_map_error(pending["interrupts"], value) + if error is not None: + raise InvalidResume(error) return int(pending.get("seq") or 0), _thread_of(state, workflow_id) @@ -108,7 +117,7 @@ async def resume_run_events( keepalive: bool, ) -> AsyncGenerator[Any, None]: """Resume the run and yield its stream from there, as ``_stream_events`` does.""" - seq, thread_id = await _pending(runner, workflow_id) + seq, thread_id = await _pending(runner, workflow_id, value) client = runner._workflow_client seen: Set[Tuple[int, str]] = set() source = open_source( @@ -153,7 +162,7 @@ async def resume_run_result( runner: Any, workflow_id: str, value: Any, *, poll_interval: float ) -> Dict[str, Any]: """Resume the run and wait for it: the body a plain ``POST /agent/run`` returns.""" - seq, thread_id = await _pending(runner, workflow_id) + seq, thread_id = await _pending(runner, workflow_id, value) await _send_resume(runner, workflow_id, seq, value) final = await follow_final( runner, workflow_id, thread_id, poll_interval, after_seq=seq @@ -176,8 +185,8 @@ async def _resume_sse( out = encoder.encode(item) if out is not None: yield out - except ResumeConflict: - raise # before the first event: the route answers 409 + except (ResumeConflict, InvalidResume): + raise # before the first event: the route answers 409 / 422 except Exception as e: logger.exception("Resumed run %s failed to stream", workflow_id) failed = stream_failure_event(e, "StreamError", True) @@ -215,9 +224,11 @@ async def resume_run(workflow_id: str, request: Request) -> Any: except ValueError as e: raise HTTPException(status_code=422, detail=str(e)) try: - await _pending(runner, workflow_id) + await _pending(runner, workflow_id, body["resume"]) except LookupError: raise HTTPException(status_code=404, detail="Workflow not found") + except InvalidResume as e: + raise HTTPException(status_code=422, detail=str(e)) except NotInterrupted as e: raise HTTPException(status_code=409, detail=str(e)) if body.get("stream") is True: diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index 283977b2..c8bd7326 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -1574,7 +1574,7 @@ def execute_node_activity( output = _node_output(call, result) except GraphInterrupt as paused: # Not a failure: the task waits for a resume and runs again then. - interrupts = interrupt_payloads(paused) + interrupts = interrupt_payloads(paused, call.resumes) if call.streamer: call.streamer.interrupted(interrupts) return with_attempt( diff --git a/tests/agent/langgraph/test_interrupt_nested.py b/tests/agent/langgraph/test_interrupt_nested.py index b7672d79..51ee819b 100644 --- a/tests/agent/langgraph/test_interrupt_nested.py +++ b/tests/agent/langgraph/test_interrupt_nested.py @@ -8,18 +8,23 @@ interrupt had not happened. """ +import json import operator -from typing import Any +import time +import unittest +from typing import Any, Dict, List from fastapi.testclient import TestClient from langgraph.graph import END, START, StateGraph -from langgraph.types import interrupt +from langgraph.types import Send, interrupt from typing_extensions import Annotated, TypedDict +from diagrid.agent.langgraph.interrupt_ids import partial_map_error + from .log_helpers import log_runner from .streaming_helpers import serve_app from .test_reconnect_helpers import frames -from .test_runner import _RunnerTestCase +from .test_runner import _clear_dapr_registration, _RunnerTestCase class _S(TypedDict, total=False): @@ -135,3 +140,166 @@ def test_a_router_that_interrupts_pauses_and_resumes(self): rest = _resume(http, got[-1][2]["workflow_id"], "yes") self.assertEqual(rest[-1][1], "workflow_completed") self.assertEqual(rest[-1][2]["output"]["log"], ["s", "pick", "yes"]) + + +def _parallel_inner(slow_on: Any) -> Any: + """A subgraph whose nodes ``a`` and ``b`` both pause, in parallel. + + ``slow_on(name, call)`` says whether a node's ``call``-th run waits a + moment before it asks: the order the two ask in can change between runs. + """ + calls = {"a": 0, "b": 0} + + def asking(name: str) -> Any: + def node(s: _S) -> dict: + calls[name] += 1 + if slow_on(name, calls[name]): + time.sleep(0.05) + return {"log": [f"{name}={interrupt('q' + name)}"]} + + return node + + sub = StateGraph(_S) + for name in ("a", "b"): + sub.add_node(name, asking(name)) + sub.add_edge(START, name) + sub.add_edge(name, END) + g = StateGraph(_S) + g.add_node("sub", sub.compile()) + g.add_edge(START, "sub") + g.add_edge("sub", END) + return g.compile() + + +def _fanout_inner() -> Any: + """A subgraph that sends two tasks to one node, which both pause.""" + + def fan(s: _S) -> dict: + return {} + + def work(s: Any) -> dict: + return {"log": [f"w{s['i']}={interrupt({'q': s['i']})}"]} + + sub = StateGraph(_S) + sub.add_node("fan", fan) + sub.add_node("work", work) + sub.add_edge(START, "fan") + sub.add_conditional_edges( + "fan", lambda s: [Send("work", {"i": i}) for i in range(2)], ["work"] + ) + sub.add_edge("work", END) + g = StateGraph(_S) + g.add_node("sub", sub.compile()) + g.add_edge(START, "sub") + g.add_edge("sub", END) + return g.compile() + + +def _ids(event: Any) -> Dict[Any, str]: + return { + json.dumps(i["value"], sort_keys=True): i["id"] for i in event["interrupts"] + } + + +class TestParallelInterruptsInOneTask(_RunnerTestCase): + """Two interrupts of one task (a subgraph's parallel nodes), resumed by id.""" + + def test_a_partial_map_answers_only_the_interrupt_it_names(self): + for slow in ("a", "b"): + with self.subTest(slow=slow): + _clear_dapr_registration() + graph = _parallel_inner(lambda name, call: name == slow) + _, http, got = _run(graph, f"par-{slow}") + self.assertEqual(got[-1][1], "workflow_interrupted") + ids = _ids(got[-1][2]) + wf = got[-1][2]["workflow_id"] + rest = _resume(http, wf, {ids['"qb"']: "B"}) + self.assertEqual(rest[-1][1], "workflow_interrupted", rest[-1]) + left = rest[-1][2]["interrupts"] + # the other one still waits, under the id the client has + self.assertEqual( + [(i["value"], i["id"]) for i in left], [("qa", ids['"qa"'])] + ) + done = _resume(http, wf, {ids['"qa"']: "A"}) + self.assertEqual(done[-1][1], "workflow_completed", done[-1]) + self.assertEqual( + sorted(done[-1][2]["output"]["log"]), ["a=A", "b=B", "s", "s"] + ) + + def test_a_full_map_reaches_each_interrupt_whatever_order_they_ask_in(self): + # ``a`` asks first on the run that pauses, last on the one resumed + graph = _parallel_inner(lambda name, call: (name == "a") == (call > 1)) + _, http, got = _run(graph, "par-flip") + ids = _ids(got[-1][2]) + wf = got[-1][2]["workflow_id"] + done = _resume(http, wf, {ids['"qa"']: "A", ids['"qb"']: "B"}) + self.assertEqual(done[-1][1], "workflow_completed", done[-1]) + self.assertEqual(sorted(done[-1][2]["output"]["log"]), ["a=A", "b=B", "s", "s"]) + + def test_a_subgraph_node_that_asks_twice_gets_each_answer_once(self): + def twice(s: _S) -> dict: + first = interrupt("first?") + return {"log": [f"{first}+{interrupt('second?')}"]} + + sub = StateGraph(_S) + sub.add_node("twice", twice) + sub.add_edge(START, "twice") + sub.add_edge("twice", END) + g = StateGraph(_S) + g.add_node("sub", sub.compile()) + g.add_edge(START, "sub") + g.add_edge("sub", END) + _, http, got = _run(g.compile(), "par-twice") + (asked,) = got[-1][2]["interrupts"] + wf = got[-1][2]["workflow_id"] + again = _resume(http, wf, {asked["id"]: "A"}) + self.assertEqual(again[-1][1], "workflow_interrupted", again[-1]) + (second,) = again[-1][2]["interrupts"] + self.assertEqual(second["value"], "second?") + done = _resume(http, wf, {second["id"]: "B"}) + self.assertEqual(done[-1][1], "workflow_completed", done[-1]) + self.assertEqual(done[-1][2]["output"]["log"], ["s", "s", "A+B"]) + + def test_one_value_still_answers_them_all(self): + _, http, got = _run(_parallel_inner(lambda name, call: False), "par-one") + done = _resume(http, got[-1][2]["workflow_id"], "X") + self.assertEqual(sorted(done[-1][2]["output"]["log"]), ["a=X", "b=X", "s", "s"]) + + +class TestInterruptsWithoutStableIds(_RunnerTestCase): + """Tasks a subgraph sends to one node cannot be told apart across runs.""" + + def test_a_partial_map_is_refused(self): + _, http, got = _run(_fanout_inner(), "fan-part") + self.assertEqual(got[-1][1], "workflow_interrupted", got[-1]) + ids = _ids(got[-1][2]) + wf = got[-1][2]["workflow_id"] + response = http.post( + f"/agent/run/{wf}/resume", json={"resume": {ids['{"q": 1}']: "one"}} + ) + self.assertEqual(response.status_code, 422, response.text) + self.assertIn("every interrupt", response.text) + done = _resume(http, wf, "both") + self.assertEqual(done[-1][1], "workflow_completed", done[-1]) + self.assertEqual( + sorted(done[-1][2]["output"]["log"]), ["s", "s", "w0=both", "w1=both"] + ) + + +class TestPartialMapRule(unittest.TestCase): + def _pending(self, *items: Any) -> List[Dict[str, Any]]: + return [dict(item) for item in items] + + def test_only_a_partial_map_of_a_task_without_stable_ids_is_refused(self): + twins = self._pending( + {"id": "x", "task": 0, "node": "sub"}, {"id": "y", "task": 0, "node": "sub"} + ) + self.assertIsNotNone(partial_map_error(twins, {"x": 1})) + self.assertIsNone(partial_map_error(twins, {"x": 1, "y": 2})) + self.assertIsNone(partial_map_error(twins, "same for all")) + stable = self._pending( + {"id": "x", "task": 0, "path": "a"}, {"id": "y", "task": 0, "path": "b"} + ) + self.assertIsNone(partial_map_error(stable, {"x": 1})) + tasks = self._pending({"id": "x", "task": 0}, {"id": "y", "task": 1}) + self.assertIsNone(partial_map_error(tasks, {"x": 1})) From 0543be247ed352fe84321e0a43d975e21a0f476a Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 17:02:11 +0100 Subject: [PATCH 65/73] fix(langgraph): a resume that lost gets 409 even after the run moved on The status said only which resume the run took last, so a caller that polled after the run took another resume and paused again was told its resume was taken. The status now keeps the winner of the last 16 interrupts, and a loser among them always gets 409. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/interrupts.py | 27 +++++++++--- tests/agent/langgraph/test_resume_conflict.py | 44 ++++++++++++++++++- 2 files changed, 64 insertions(+), 7 deletions(-) diff --git a/diagrid/agent/langgraph/interrupts.py b/diagrid/agent/langgraph/interrupts.py index 9c3cde1a..d15d5acd 100644 --- a/diagrid/agent/langgraph/interrupts.py +++ b/diagrid/agent/langgraph/interrupts.py @@ -46,8 +46,12 @@ #: Custom status: the pending interrupt, and the number of the last one. STATUS_INTERRUPT = "interrupt" STATUS_INTERRUPT_SEQ = "interrupt_seq" -#: Custom status: the resume the run took last, ``{"seq", "id"}``. +#: Custom status: the resume the run took last, ``{"seq", "id", "taken"}``; +#: ``taken`` lists ``[seq, id]`` of the last :data:`RESUMES_KEPT` it took. STATUS_RESUMED = "resumed" +#: Resumes the status keeps the winner of: a caller that lost one is told so +#: even after the run took it and paused again. +RESUMES_KEPT = 16 #: The updates-chunk key LangGraph streams interrupts under. INTERRUPT_KEY = "__interrupt__" #: The final event of a stream whose run is waiting for a resume. @@ -331,7 +335,7 @@ def settle_interrupts( values, resume_id = yield from _wait_resume(run.ctx, run.interrupt_seq, pending) run.interrupt = None # which resume the run took: a caller whose resume it ignored is told - run.resumed = {"seq": run.interrupt_seq, "id": resume_id} + run.resumed = _took(run.resumed, run.interrupt_seq, resume_id) publish(run) for item in pending: if item["id"] in values: @@ -364,17 +368,28 @@ def _wait_resume( ) +def _took( + resumed: Optional[Dict[str, Any]], seq: int, resume_id: Optional[str] +) -> Dict[str, Any]: + """The status's ``resumed`` once the run took ``resume_id`` for ``seq``.""" + taken = list((resumed or {}).get("taken") or []) + taken = [*taken, [seq, resume_id]][-RESUMES_KEPT:] + return {"seq": seq, "id": resume_id, "taken": taken} + + def resume_taken(status: Dict[str, Any], seq: int, resume_id: str) -> Optional[bool]: """Whether the run took the resume ``resume_id`` of interrupt ``seq``. ``None`` while it is still waiting for one. A run started on a version - that does not say which resume it took is taken to have taken this one. + that does not say which resume it took (or past :data:`RESUMES_KEPT` + more interrupts since) is taken to have taken this one. """ resumed = status.get(STATUS_RESUMED) if isinstance(resumed, dict) and int(resumed.get("seq") or 0) >= seq: - if int(resumed.get("seq") or 0) > seq: - return True # the run is past it: nothing to tell - return resumed.get("id") in (None, resume_id) + winners = {int(s): w for s, w in resumed.get("taken") or []} + if int(resumed.get("seq") or 0) == seq: + winners.setdefault(seq, resumed.get("id")) + return winners.get(seq) in (None, resume_id) waiting = pending_interrupt(status) if waiting is not None and int(waiting.get("seq") or 0) == seq: return None diff --git a/tests/agent/langgraph/test_resume_conflict.py b/tests/agent/langgraph/test_resume_conflict.py index 0c36b45b..7a8e0a87 100644 --- a/tests/agent/langgraph/test_resume_conflict.py +++ b/tests/agent/langgraph/test_resume_conflict.py @@ -8,12 +8,16 @@ ignored must be told, not handed a result its value had no part in. """ +import json import threading import time -from typing import Any, List +import unittest +from typing import Any, Dict, List from fastapi.testclient import TestClient +from diagrid.agent.langgraph.interrupts import resume_taken + from .log_helpers import LogClient, log_runner from .streaming_helpers import serve_app from .test_interrupt import INPUT, _approval_graph @@ -95,3 +99,41 @@ def test_a_streamed_resume_that_lost_gets_409_before_streaming(self): self.assertEqual(sorted([a.status_code, b.status_code]), [200, 409]) won = a if a.status_code == 200 else b self.assertEqual(frames(won.text)[-1][1], "workflow_completed") + + +class TestALoserAfterTheRunMovedOn(unittest.TestCase): + """The run took another resume and paused again before the loser looked.""" + + def _status(self) -> Dict[str, Any]: + return { + "resumed": {"seq": 3, "id": "won-3", "taken": [[2, "won-2"], [3, "won-3"]]}, + "interrupt": {"seq": 4, "interrupts": [{"id": "x", "value": 1}]}, + } + + def test_the_loser_is_still_told(self): + self.assertIs(resume_taken(self._status(), 2, "lost-2"), False) + + def test_the_winner_is_still_told_it_won(self): + self.assertIs(resume_taken(self._status(), 2, "won-2"), True) + self.assertIs(resume_taken(self._status(), 3, "won-3"), True) + + def test_a_run_that_says_nothing_of_older_resumes_takes_it(self): + old = {"resumed": {"seq": 3, "id": "won-3"}} # a run started earlier + self.assertIs(resume_taken(old, 2, "lost-2"), True) + + +class TestTheRunKeepsWhichResumesItTook(_RunnerTestCase): + def test_each_interrupt_s_winner_stays_in_the_status(self): + runner = log_runner(_approval_graph(asks=2), "taken-list") + http = TestClient(serve_app(runner)) + got = frames(http.post("/agent/run", json={**INPUT, "stream": True}).text) + wf = got[-1][2]["workflow_id"] + for value in ("A", "B"): + self.assertEqual( + http.post( + f"/agent/run/{wf}/resume", json={"resume": value} + ).status_code, + 200, + ) + status = json.loads(runner._workflow_client.custom[wf]) + self.assertEqual([seq for seq, _ in status["resumed"]["taken"]], [1, 2]) From c5546222cd6580301391de507d456db34a3afbc9 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 17:05:54 +0100 Subject: [PATCH 66/73] fix(langgraph): refuse a null resume over HTTP and a resume that also updates - {"resume": null} raised a resume over HTTP while Command(resume=None) is refused in Python: both are now refused (422 over HTTP). - Command(update=..., resume=...) resumed the run and dropped the update without a word: a Command that sets update or goto besides resume is now a ValueError. - The README said a node's last write is retried up to four times; it is tried four times in all. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 11 ++++--- diagrid/agent/langgraph/invoke_result.py | 40 ++++++++++++++++++------ diagrid/agent/langgraph/resume_run.py | 6 ++-- diagrid/agent/langgraph/runner.py | 11 ++----- tests/agent/langgraph/test_interrupt.py | 26 +++++++++++++++ 5 files changed, 71 insertions(+), 23 deletions(-) diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 95257e08..23533ad0 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -339,8 +339,8 @@ not pick one: parts, batches expire after an hour and their index after a day. Chunks arrive about 150 to 250 ms later than in process, in small bursts. A failed write is retried with the next batch, and a node's last write (its `updates` - chunk), which no batch follows, is retried up to four times with backoff; a - write never fails a node. If a node's + chunk), which no batch follows, is tried up to four times in all, with + backoff; a write never fails a node. If a node's chunks still never reach the log, the stream ends with `stream_unavailable` whose `reason` is `write_failed`. A store that cannot be read ends the stream with `workflow_failed` (`error_type` `StreamReadError`), never with an @@ -418,8 +418,11 @@ needed for this. ids answers several interrupts one by one. The stream of a resume carries what happens after it (starting with `node_reset` for the node that runs again) and ends with the final event, or with `workflow_interrupted` when a - node asks again. A body without `resume` is a `422`, an unknown run a `404`, - and a run that is not waiting a `409`. When two requests resume the same + node asks again. A body without `resume`, or with `"resume": null` (as + `Command(resume=None)` is no resume in Python), is a `422`, an unknown run + a `404`, and a run that is not waiting a `409`. In Python a `Command` that + sets `update` or `goto` besides `resume` is a `ValueError`: the run would + not apply them. When two requests resume the same interrupt at once, the run takes one and the other gets a `409` (before any event, when it asked for a stream). - `interrupt()` pauses the run also when it is called in a subgraph the node diff --git a/diagrid/agent/langgraph/invoke_result.py b/diagrid/agent/langgraph/invoke_result.py index ff46f12f..a1a389c0 100644 --- a/diagrid/agent/langgraph/invoke_result.py +++ b/diagrid/agent/langgraph/invoke_result.py @@ -130,15 +130,40 @@ def _wait_taken( time.sleep(min(poll_interval, 0.05)) +def command_resume(command: Any, workflow_id: Optional[str], call: str) -> Any: + """The resume value of a ``Command`` given as ``call``'s input. + + Raises ``ValueError`` for a ``Command`` that is not a resume (or sets more + than ``resume``, which would be lost) or comes without the run's + ``workflow_id``. + """ + if getattr(command, "resume", None) is None or not workflow_id: + raise ValueError( + f"{call}(Command(resume=...)) resumes a run paused by interrupt(): " + "pass the run's workflow_id (other Commands are not supported as input)" + ) + extra = [ + name + for name in ("update", "goto", "graph") + if getattr(command, name, None) not in (None, ()) + ] + if extra: + raise ValueError( + f"{call}(Command(resume=..., {extra[0]}=...)): a resume cannot also " + f"set {' or '.join(extra)}; send Command(resume=...) only" + ) + return command.resume + + def invoke_resume( runner: Any, command: Any, - workflow_id: Optional[str], + run_id: Optional[str], *, poll_interval: float, timeout: Optional[float], ) -> Any: - """Resume the run ``workflow_id`` with ``command.resume`` and wait for it. + """Resume the run ``run_id`` with ``command.resume`` and wait for it. Raises ``ValueError`` for a ``Command`` that is not a resume, without the run's ``workflow_id``, or for a run that is not waiting for a resume, and @@ -146,11 +171,8 @@ def invoke_resume( """ from .reconnect import _thread_of - if getattr(command, "resume", None) is None or not workflow_id: - raise ValueError( - "invoke(Command(resume=...)) resumes a run paused by interrupt(): " - "pass the run's workflow_id (other Commands are not supported as input)" - ) + resume = command_resume(command, run_id, "invoke") + workflow_id = str(run_id) client = runner._workflow_client state = client.get_workflow_state(instance_id=workflow_id) if state is None: @@ -158,7 +180,7 @@ def invoke_resume( pending = pending_interrupt(parse_status(state.serialized_custom_status)) if state.runtime_status != WorkflowStatus.RUNNING or pending is None: raise ValueError(f"Workflow {workflow_id!r} is not waiting for a resume") - error = partial_map_error(pending["interrupts"], command.resume) + error = partial_map_error(pending["interrupts"], resume) if error is not None: raise ValueError(error) seq = int(pending.get("seq") or 0) @@ -166,7 +188,7 @@ def invoke_resume( client.raise_workflow_event( instance_id=workflow_id, event_name=RESUME_EVENT, - data={"seq": seq, "resume": command.resume, "id": resume_id}, + data={"seq": seq, "resume": resume, "id": resume_id}, ) _wait_taken(client, workflow_id, seq, resume_id, poll_interval) return wait_invoke_result( diff --git a/diagrid/agent/langgraph/resume_run.py b/diagrid/agent/langgraph/resume_run.py index aa08a991..a5ed0d29 100644 --- a/diagrid/agent/langgraph/resume_run.py +++ b/diagrid/agent/langgraph/resume_run.py @@ -213,9 +213,11 @@ async def resume_run(workflow_id: str, request: Request) -> Any: body = await request.json() except ValueError: raise HTTPException(status_code=422, detail="the body must be JSON") - if not isinstance(body, dict) or "resume" not in body: + if not isinstance(body, dict) or body.get("resume") is None: + # null is no resume, as Command(resume=None) is none in Python raise HTTPException( - status_code=422, detail='the body must be {"resume": }' + status_code=422, + detail='the body must be {"resume": }, the value not null', ) try: modes, _ = normalize_stream_mode( diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 53c6e881..9735b367 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -59,7 +59,7 @@ from .run_status import completed_result, interrupted_result from .activity_stream import parse_status from .interrupts import interrupted_event -from .invoke_result import invoke_resume, wait_invoke_result +from .invoke_result import command_resume, invoke_resume, wait_invoke_result from .reconnect import add_reconnect_route, resume_events from .resume_run import add_resume_route, resume_run_events from .stream_drain import SseEncoder, drain, parse_output @@ -1034,15 +1034,10 @@ async def astream( raise NotImplementedError("subgraphs=True is not supported yet") modes, is_list = normalize_stream_mode(stream_mode) if isinstance(input, Command): - if input.resume is None or not workflow_id: - raise ValueError( - "astream(Command(resume=...)) resumes a run paused by " - "interrupt(): pass the run's workflow_id" - ) events: Any = resume_run_events( self, - workflow_id, - input.resume, + str(workflow_id), + command_resume(input, workflow_id, "astream"), poll_interval=poll_interval, keepalive=False, ) diff --git a/tests/agent/langgraph/test_interrupt.py b/tests/agent/langgraph/test_interrupt.py index 581f4ccb..b93f9f5b 100644 --- a/tests/agent/langgraph/test_interrupt.py +++ b/tests/agent/langgraph/test_interrupt.py @@ -163,6 +163,10 @@ def test_resume_is_refused_when_it_cannot_apply(self): self.assertEqual( http.post(f"/agent/run/{wf}/resume", json={"value": 1}).status_code, 422 ) + # as in Python, where Command(resume=None) is no resume + refused = http.post(f"/agent/run/{wf}/resume", json={"resume": None}) + self.assertEqual(refused.status_code, 422) + self.assertNotIn(wf, runner._workflow_client.done) self.assertEqual( http.post("/agent/run/nope/resume", json={"resume": 1}).status_code, 404 ) @@ -199,6 +203,28 @@ async def test_a_command_without_a_run_to_resume_is_refused(self): with self.assertRaises(ValueError): await _collect(runner.astream(Command(resume="go"))) + async def test_a_command_that_also_updates_the_state_is_refused(self): + runner = log_runner(_approval_graph(), "py-upd") + await _collect(runner.astream(INPUT, workflow_id="wf-upd", poll_interval=0.01)) + with self.assertRaises(ValueError) as caught: + await _collect( + runner.astream( + Command(resume="go", update={"answer": "x"}), + workflow_id="wf-upd", + poll_interval=0.01, + ) + ) + self.assertIn("update", str(caught.exception)) + with self.assertRaises(ValueError): + runner.invoke( + Command(resume="go", update={"answer": "x"}), + workflow_id="wf-upd", + poll_interval=0.01, + timeout=1, + ) + # still waiting: the refused commands raised no resume + self.assertNotIn("wf-upd", runner._workflow_client.done) + class TestInvoke(_RunnerTestCase): def test_invoke_returns_the_interrupt_instead_of_waiting_forever(self): From b48af665bf2c27623cb6b62a0f0e53f7809780ff Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 22:06:53 +0100 Subject: [PATCH 67/73] fix(langgraph): a stream that fails while the run goes on resumes from its last chunk When the serving replica's sidecar went away mid-run, the stream ended with workflow_failed (workflow_still_running: true) and the SSE id v1.end. A client that reconnected with that id, as EventSource does, got only the final event and lost the rest of the run. A final event of a run that is still going now repeats the last chunk's cursor (on a reconnect, before any chunk, the cursor the client sent), and the failures raised out of a stream (StreamError) go through the same encoder instead of being numbered per connection. The README says to treat such an event as a lost stream and reconnect with its id. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 19 ++- diagrid/agent/langgraph/reconnect.py | 10 +- diagrid/agent/langgraph/resume_run.py | 6 +- diagrid/agent/langgraph/runner.py | 6 +- diagrid/agent/langgraph/stream_drain.py | 60 ++++++-- diagrid/agent/langgraph/stream_events.py | 6 +- tests/agent/langgraph/follow_helpers.py | 114 +++++++++++++++ .../langgraph/test_stream_read_failure.py | 130 ++++++++++++++++++ 8 files changed, 325 insertions(+), 26 deletions(-) create mode 100644 tests/agent/langgraph/follow_helpers.py create mode 100644 tests/agent/langgraph/test_stream_read_failure.py diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 23533ad0..2b98cbf9 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -286,8 +286,11 @@ Every event carries an SSE `id`. With the state-store transport (see [Streaming across replicas](#streaming-across-replicas)) the id is a cursor into the run's event log that any replica can resume from: `v1.start` on `workflow_started`, `v1.end` on the final event, and in between the position -after that chunk (a control event repeats the id of the chunk before it). With -the in-process transport the events are numbered from 1 on each connection. +after that chunk (a control event repeats the id of the chunk before it). A +`workflow_failed` with `workflow_still_running: true` is not the run's end: it +repeats the id of the last chunk too (on a reconnect, before any chunk, the id +the client sent). With the in-process transport the events are numbered from 1 +on each connection. #### Reconnecting @@ -295,7 +298,12 @@ A client that lost its stream (a network drop, a proxy timeout, the serving process restarting) reconnects with `GET /agent/run/{workflow_id}/stream`, sending the last id it received as the `Last-Event-ID` header (a browser `EventSource` does this by itself) or, when it cannot set headers, as the -`last_event_id` query parameter. Any replica answers it. The response is the +`last_event_id` query parameter. A stream can also end in-band while the run +goes on: when the serving replica's sidecar goes away (the pod is deleted, +say) the stream ends with `workflow_failed` whose `workflow_still_running` is +`true` (`error_type` `StreamReadError`, `PollError` or `StreamError`). Treat +that as a lost stream, not a failed run: reconnect with its id, which is the +last chunk's, and the stream goes on from there. Any replica answers it. The response is the same SSE stream from that point on: `workflow_started`, then the chunks the client has not seen, then the live ones, then the final event with the run's result. Nothing is repeated and nothing is skipped. Without an id, or with one @@ -343,8 +351,9 @@ not pick one: backoff; a write never fails a node. If a node's chunks still never reach the log, the stream ends with `stream_unavailable` whose `reason` is `write_failed`. A store that cannot be read ends the - stream with `workflow_failed` (`error_type` `StreamReadError`), never with an - empty stream. A stream finds a run's tasks in the run's custom status, which + stream with `workflow_failed` (`error_type` `StreamReadError`, + `workflow_still_running: true`, the last chunk's id: see + [Reconnecting](#reconnecting)), never with an empty stream. A stream finds a run's tasks in the run's custom status, which lists its last 128 steps (a reader further behind catches up on the older steps when the run ends) and which it reads about every 2 seconds while a node is streaming, as Dapr returns the status only together with the run's diff --git a/diagrid/agent/langgraph/reconnect.py b/diagrid/agent/langgraph/reconnect.py index 91dce641..b49d7a16 100644 --- a/diagrid/agent/langgraph/reconnect.py +++ b/diagrid/agent/langgraph/reconnect.py @@ -25,7 +25,7 @@ ) from diagrid.agent.core.workflow.stream_cursor import parse_cursor -from .stream_drain import SseEncoder, drain +from .stream_drain import SseEncoder, drain, encode_final from .stream_events import ( FINAL_EVENTS, KEEPALIVE, @@ -188,7 +188,9 @@ async def resume_sse( runner: Any, workflow_id: str, last_event_id: Optional[str], modes: Any ) -> AsyncIterator[Tuple[Any, ...]]: """The SSE items of a reconnect; a failure of the stream ends it in-band.""" - encoder = SseEncoder(modes, runner.stream_transport.replayable) + encoder = SseEncoder( + modes, runner.stream_transport.replayable, resume_from=last_event_id + ) try: async for item in resume_events( runner, workflow_id, last_event_id, poll_interval=0.5, keepalive=True @@ -199,8 +201,8 @@ async def resume_sse( except Exception as e: logger.exception("Reconnected stream of %s failed", workflow_id) failed = stream_failure_event(e, "StreamError", True) - yield ( - "workflow_failed", + yield encode_final( + encoder, normalize_final(failed, workflow_id=workflow_id, thread_id=workflow_id), ) diff --git a/diagrid/agent/langgraph/resume_run.py b/diagrid/agent/langgraph/resume_run.py index a5ed0d29..e4106d71 100644 --- a/diagrid/agent/langgraph/resume_run.py +++ b/diagrid/agent/langgraph/resume_run.py @@ -27,7 +27,7 @@ from .interrupt_ids import partial_map_error from .interrupts import RESUME_EVENT, pending_interrupt, resume_taken from .reconnect import _thread_of, follow_final -from .stream_drain import SseEncoder, drain +from .stream_drain import SseEncoder, drain, encode_final from .stream_events import started_event, stream_failure_event, without_executed from .stream_source import custom_status, open_source from .streaming import normalize_final, normalize_stream_mode @@ -190,8 +190,8 @@ async def _resume_sse( except Exception as e: logger.exception("Resumed run %s failed to stream", workflow_id) failed = stream_failure_event(e, "StreamError", True) - yield ( - "workflow_failed", + yield encode_final( + encoder, normalize_final(failed, workflow_id=workflow_id, thread_id=workflow_id), ) diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 9735b367..394a3f41 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -62,7 +62,7 @@ from .invoke_result import command_resume, invoke_resume, wait_invoke_result from .reconnect import add_reconnect_route, resume_events from .resume_run import add_resume_route, resume_run_events -from .stream_drain import SseEncoder, drain, parse_output +from .stream_drain import SseEncoder, drain, encode_final, parse_output from .stream_source import ( custom_status, open_source, @@ -1337,8 +1337,8 @@ async def _serve_stream( # type: ignore[override] logger.exception("Streaming run failed") workflow_id = encoder.workflow_id if encoder else None failed = stream_failure_event(e, "StreamError", bool(workflow_id)) - yield ( - "workflow_failed", + yield encode_final( + encoder, normalize_final( failed, workflow_id=workflow_id, diff --git a/diagrid/agent/langgraph/stream_drain.py b/diagrid/agent/langgraph/stream_drain.py index ac27c04f..cee3d242 100644 --- a/diagrid/agent/langgraph/stream_drain.py +++ b/diagrid/agent/langgraph/stream_drain.py @@ -20,11 +20,17 @@ StreamClosed, StreamEvent, ) -from diagrid.agent.core.workflow.stream_cursor import END_ID, START_ID +from diagrid.agent.core.workflow.stream_cursor import ( + END_ID, + START_ID, + encode_cursor, + parse_cursor, +) from .models import GraphWorkflowOutput from .stream_events import ( KEEPALIVE, + STILL_RUNNING_KEY, closing_events, count_unencodable, encode_chunk, @@ -127,9 +133,12 @@ class SseIds: numbered per connection (``()`` leaves that to the framer). """ - def __init__(self, replayable: bool) -> None: + def __init__(self, replayable: bool, resume_from: Optional[str] = None) -> None: self._replayable = replayable - self._last = START_ID + #: Where the client is: the cursor it reconnected with, until a chunk. + self._last = ( + encode_cursor(parse_cursor(resume_from)) if resume_from else START_ID + ) def of(self, item: StreamEvent) -> Tuple[str, ...]: if not self._replayable: @@ -141,16 +150,30 @@ def of(self, item: StreamEvent) -> Tuple[str, ...]: # a control event reuses the cursor of the chunk it follows return (self._last,) - def final(self) -> Tuple[str, ...]: - return (END_ID,) if self._replayable else () + def final(self, event: Dict[str, Any]) -> Tuple[str, ...]: + """The id of the event a stream ends with. + + ``v1.end`` says the client has the run's end. A stream that failed + while the run goes on has not: its failure repeats the last chunk's + cursor, so a reconnect with it (what an ``EventSource`` does) gets the + rest of the run. + """ + if not self._replayable: + return () + return (self._last,) if event.get(STILL_RUNNING_KEY) else (END_ID,) class SseEncoder: - """``(event, data[, id])`` for each item of a stream, as ``frame_sse`` takes it.""" + """``(event, data[, id])`` for each item of a stream, as ``frame_sse`` takes it. + + ``resume_from`` is the id a reconnecting client sent. + """ - def __init__(self, modes: List[str], replayable: bool) -> None: + def __init__( + self, modes: List[str], replayable: bool, resume_from: Optional[str] = None + ) -> None: self._modes = modes - self._ids = SseIds(replayable) + self._ids = SseIds(replayable, resume_from) self.unencodable = 0 self.workflow_id: Optional[str] = None @@ -167,5 +190,22 @@ def encode(self, item: Any) -> Optional[Tuple[Any, ...]]: wire, ok = encode_chunk(item) self.unencodable += 0 if ok else 1 return (item.mode, wire, *event_id) - final = count_unencodable(item, self.unencodable) - return (item["type"], final, *self._ids.final()) + return self.encode_final(item) + + def encode_final(self, event: Dict[str, Any]) -> Tuple[Any, ...]: + """The SSE item of the event a stream ends with.""" + final = count_unencodable(event, self.unencodable) + return (event["type"], final, *self._ids.final(event)) + + +def encode_final( + encoder: Optional[SseEncoder], event: Dict[str, Any] +) -> Tuple[Any, ...]: + """The SSE item of a final event sent when the stream itself raised. + + With an encoder it carries the id the stream got to (see + :meth:`SseIds.final`); a stream refused before it had one numbers it. + """ + if encoder is None: + return (event["type"], event) + return encoder.encode_final(event) diff --git a/diagrid/agent/langgraph/stream_events.py b/diagrid/agent/langgraph/stream_events.py index b77a7fb4..de04f752 100644 --- a/diagrid/agent/langgraph/stream_events.py +++ b/diagrid/agent/langgraph/stream_events.py @@ -143,6 +143,10 @@ def failure_event( return workflow_failed({}, str(error), error_type or type(error).__name__) +#: Key of a ``workflow_failed`` event for a failure of the stream, not the run. +STILL_RUNNING_KEY = "workflow_still_running" + + def stream_failure_event( error: BaseException, stream_error_type: str, started: bool ) -> Dict[str, Any]: @@ -157,7 +161,7 @@ def stream_failure_event( return failure_event(error) return { **failure_event(error, stream_error_type), - "workflow_still_running": True, + STILL_RUNNING_KEY: True, } diff --git a/tests/agent/langgraph/follow_helpers.py b/tests/agent/langgraph/follow_helpers.py new file mode 100644 index 00000000..b6da4dc5 --- /dev/null +++ b/tests/agent/langgraph/follow_helpers.py @@ -0,0 +1,114 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A log follower fed by hand: units written with real writers, read as SSE.""" + +import asyncio +from typing import Any, AsyncIterator, Callable, Dict, List, Optional, Tuple + +from diagrid.agent.core.workflow.stream import InProcessSink, StreamEvent +from diagrid.agent.core.workflow.stream_cursor import StreamCursor +from diagrid.agent.core.workflow.stream_log import ( + LogWriter, + StateLogStreamConfig, + StateLogTransport, +) +from diagrid.agent.langgraph.stream_drain import SseEncoder, drain +from diagrid.agent.langgraph.stream_follow import ( + LogFollower, + decode_wire, + encode_wire, +) +from diagrid.agent.langgraph.stream_source import StreamSource + +from ..core.log_store_fake import FakeLogStore + +WF = "wf" +MODES = ["custom", "updates"] +#: Two chunks per batch: a unit's first chunks are in the log before it ends. +CONFIG = StateLogStreamConfig(flush_interval_s=60, flush_max_chunks=2, read_poll_s=0.01) + +Frame = Tuple[Any, ...] + + +def transport(store: FakeLogStore) -> StateLogTransport: + return StateLogTransport(CONFIG, store=store).with_codec(encode_wire, decode_wire) + + +def chunk(step: int, node: str, mode: str, data: Any, seq: int) -> StreamEvent: + return StreamEvent( + workflow_id=WF, + step=step, + node=node, + attempt_id="", + seq=seq, + ns=(), + mode=mode, + data=data, + ) + + +def write( + log: StateLogTransport, step: int, node: str, items: List[Tuple[str, Any]] +) -> LogWriter: + """A writer of ``(step, node)`` that put ``items``; finish it to end the unit.""" + writer = log.writer(WF, step, node, streamed=True) + assert writer is not None + for seq, (mode, data) in enumerate(items): + writer.put(chunk(step, node, mode, data, seq)) + return writer + + +class FollowedStream: + """A stream read from the log, as SSE ``(event, data, id)`` items.""" + + def __init__( + self, + log: StateLogTransport, + status: Callable[[], Dict[str, Any]], + *, + cursor: Optional[StreamCursor] = None, + poll_s: float = 0.01, + ) -> None: + sink = InProcessSink(WF, asyncio.get_running_loop(), bounded=False) + self.follower = LogFollower( + log.reader(WF), + sink, + workflow_id=WF, + status=status, + poll_s=poll_s, + cursor=cursor, + replay=cursor is not None, + ) + task = asyncio.create_task(self.follower.run()) + self._source = StreamSource( + sink, self.follower.finish, follower=self.follower, task=task + ) + self._encoder = SseEncoder(MODES, True) + self._items = drain( + self._source, + workflow_id=WF, + seen=set(), + keepalive=False, + output_channels=None, + ) + self._frames = self._encoded() + + async def _encoded(self) -> AsyncIterator[Frame]: + async for item in self._items: + out = self._encoder.encode(item) + if out is not None: + yield out + + async def take(self, n: int) -> List[Frame]: + """The next ``n`` frames.""" + return [await self._frames.__anext__() for _ in range(n)] + + async def rest(self) -> List[Frame]: + """Every frame up to and including the final event.""" + return [frame async for frame in self._frames] + + async def close(self) -> None: + await self._frames.aclose() + await self._items.aclose() + await self._source.close() diff --git a/tests/agent/langgraph/test_stream_read_failure.py b/tests/agent/langgraph/test_stream_read_failure.py new file mode 100644 index 00000000..29f5ee56 --- /dev/null +++ b/tests/agent/langgraph/test_stream_read_failure.py @@ -0,0 +1,130 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A stream that cannot read the log mid-run ends with an id the client resumes from. + +When the serving process's sidecar goes away (the pod is deleted), the reader +fails and the stream ends with ``workflow_failed`` and +``workflow_still_running``. The run goes on elsewhere, so that event must not +carry ``v1.end`` (the client has the end): it repeats the last chunk's id, and +a reconnect with it gets exactly the rest of the run. +""" + +import asyncio +import unittest +from typing import Any, Dict + +from diagrid.agent.core.workflow.stream import StreamEvent +from diagrid.agent.core.workflow.stream_cursor import END_ID, START_ID, parse_cursor +from diagrid.agent.langgraph.stream_drain import SseEncoder, encode_final +from diagrid.agent.langgraph.stream_events import stream_failure_event + +from ..core.log_store_fake import FakeLogStore +from .follow_helpers import FollowedStream, chunk, transport, write + +A = [("custom", {"a": i}) for i in range(3)] + [("updates", {"a": {"x": 1}})] +B_FIRST = [("custom", {"b": i}) for i in range(2)] +B_REST = [("custom", {"b": i}) for i in range(2, 5)] + [("updates", {"b": {"y": 2}})] +STATUS = {"executed": [["a"], ["b"]]} +COMPLETED = {"type": "workflow_completed", "workflow_id": "wf", **STATUS} + + +def _data(frames: Any) -> list: + return [data for _, data, *_ in frames] + + +class TestReadFailureMidRun(unittest.IsolatedAsyncioTestCase): + async def test_the_failure_carries_the_last_chunk_id_and_resumes_exactly(self): + store = FakeLogStore() + log = transport(store) + write(log, 0, "a", A).finish(done=True) + b = write(log, 1, "b", B_FIRST) # still running: two chunks are in the log + + status: Dict[str, Any] = dict(STATUS) + live = FollowedStream(log, lambda: status) + before = await live.take(len(A) + len(B_FIRST)) + self.assertEqual(_data(before), [d for _, d in A + B_FIRST]) + store.fail_gets = 10**6 # the sidecar is gone + rest = await asyncio.wait_for(live.rest(), 10) + await live.close() + + name, final, event_id = rest[-1] + self.assertEqual(name, "workflow_failed") + self.assertEqual(final["error"]["error_type"], "StreamReadError") + self.assertTrue(final["workflow_still_running"]) + self.assertNotEqual(event_id, END_ID) + self.assertEqual(event_id, before[-1][2]) + + # the run goes on elsewhere and ends + store.fail_gets = 0 + for seq, (mode, data) in enumerate(B_REST, start=len(B_FIRST)): + b.put(chunk(1, "b", mode, data, seq)) + b.finish(done=True) + + resumed = FollowedStream(log, lambda: status, cursor=parse_cursor(event_id)) + resumed.follower.finish(COMPLETED) + after = await asyncio.wait_for(resumed.rest(), 10) + await resumed.close() + self.assertEqual(after[-1][0], "workflow_completed") + self.assertEqual(_data(after[:-1]), [d for _, d in B_REST]) + + whole = FollowedStream(log, lambda: status, cursor=parse_cursor(START_ID)) + whole.follower.finish(COMPLETED) + replay = await asyncio.wait_for(whole.rest(), 10) + await whole.close() + # no gaps, no duplicates + self.assertEqual(_data(before) + _data(after[:-1]), _data(replay[:-1])) + + +def _chunk_event(event_id: str) -> StreamEvent: + return StreamEvent( + workflow_id="wf", + step=0, + node="a", + attempt_id="", + seq=0, + ns=(), + mode="custom", + data={}, + event_id=event_id, + ) + + +class TestFinalIds(unittest.TestCase): + def _failure(self) -> Dict[str, Any]: + return stream_failure_event(ConnectionError("gone"), "StreamError", True) + + def test_a_finished_run_ends_on_the_end_id(self): + encoder = SseEncoder(["custom"], True) + encoder.encode(_chunk_event("v1.0.x")) + self.assertEqual(encoder.encode(COMPLETED)[2], END_ID) + + def test_a_failure_while_the_run_goes_on_repeats_the_last_chunk_id(self): + encoder = SseEncoder(["custom"], True) + encoder.encode(_chunk_event("v1.0.x")) + self.assertEqual(encoder.encode(self._failure())[2], "v1.0.x") + + def test_before_any_chunk_it_is_where_the_client_resumed_from(self): + cursor = "v1.3.W10" + self.assertEqual( + SseEncoder(["custom"], True, resume_from=cursor).encode(self._failure())[2], + cursor, + ) + self.assertEqual( + SseEncoder(["custom"], True).encode(self._failure())[2], START_ID + ) + + def test_a_failure_raised_out_of_the_stream_gets_the_same_id(self): + encoder = SseEncoder(["custom"], True) + encoder.encode(_chunk_event("v1.0.x")) + self.assertEqual( + encode_final(encoder, self._failure()), + ("workflow_failed", self._failure(), "v1.0.x"), + ) + # no encoder yet (the request was refused before the stream): no id + self.assertEqual( + encode_final(None, self._failure()), ("workflow_failed", self._failure()) + ) + + def test_the_in_process_transport_numbers_events_itself(self): + self.assertEqual(len(SseEncoder(["custom"], False).encode(self._failure())), 2) From 92167a33e7a3d0f400bd894b9e2589e0ae26a008 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 22:09:56 +0100 Subject: [PATCH 68/73] fix(langgraph): a live stream drains the step a run paused or failed in The log reader learns a run's units from its custom status, which it reads only every few polls while a unit is being written, and once the run ended it took the final event as the status. A completed run's final lists every step; workflow_interrupted and a failed run's final list none. So when the run paused on interrupt() before the reader had read the status since that step started, the stream closed without reading the step: the __interrupt__ updates chunk was missing from the live stream, though a replay had it. When the final event does not list the run's units (and the run is not still going), the reader now reads the custom status once more and drains every unit it names before it closes. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 11 ++- diagrid/agent/langgraph/stream_follow.py | 31 ++++--- .../langgraph/test_stream_final_units.py | 84 +++++++++++++++++++ 3 files changed, 112 insertions(+), 14 deletions(-) create mode 100644 tests/agent/langgraph/test_stream_final_units.py diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 2b98cbf9..8efb0c53 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -357,7 +357,9 @@ not pick one: lists its last 128 steps (a reader further behind catches up on the older steps when the run ends) and which it reads about every 2 seconds while a node is streaming, as Dapr returns the status only together with the run's - input. `StateLogStreamConfig` sets the store, key prefix, TTLs, batch + input, and once more when a run pauses or fails, so the chunks of the step + it ended in (an `__interrupt__` chunk, say) always come before the final + event. `StateLogStreamConfig` sets the store, key prefix, TTLs, batch sizes and read interval: ```python @@ -410,8 +412,11 @@ with a checkpointer: the workflow is the checkpoint, so no checkpointer is needed for this. - The stream sends LangGraph's `updates` chunk `{"__interrupt__": [...]}` (each - interrupt's `value` and `id`; `Interrupt` objects in `astream`) and ends with - the event `workflow_interrupted` (`workflow_id`, `thread_id`, `interrupts`). + interrupt's `value` and `id`; `Interrupt` objects in `astream`), on any + replica, and ends with the event `workflow_interrupted` (`workflow_id`, + `thread_id`, `interrupts`), whose SSE id is `v1.end`: a reconnect with it + gets only the run's next final event (`workflow_interrupted` again while it + waits). The stream of the resume (below) carries the rest of the run. `invoke` returns `{"__interrupt__": [Interrupt(...)]}`. - The workflow waits durably for the answer: in its history, not in process memory, so the app may restart or scale meanwhile. The other nodes of the diff --git a/diagrid/agent/langgraph/stream_follow.py b/diagrid/agent/langgraph/stream_follow.py index 056fdf60..d0eb8095 100644 --- a/diagrid/agent/langgraph/stream_follow.py +++ b/diagrid/agent/langgraph/stream_follow.py @@ -38,7 +38,7 @@ from .activity_stream import STATUS_BRANCHES, STATUS_EXECUTED, STATUS_EXECUTED_FROM from .interrupts import INTERRUPT_KEY, as_interrupts from .stream_attempts import attempts_of, unit_key -from .stream_events import encode_chunk, stream_failure_event +from .stream_events import STILL_RUNNING_KEY, encode_chunk, stream_failure_event from .streaming import BRANCHES_KEY, EXECUTED_KEY, SUPPORTED_MODES logger = logging.getLogger(__name__) @@ -164,7 +164,7 @@ def __init__( #: Units the client had in full or in part before this stream: the #: stream does not report them missing. self._seen = seen if seen is not None else set() - #: Polls since the run's status was last read (see ``_run_status``). + #: Polls since the run's status was last read (see ``_run_statuses``). self._polls_since_status = STATUS_EVERY #: The last step whose ``values`` chunk went out (here or before a #: reconnect): every unit of a step logs it, and it is sent once. @@ -249,10 +249,11 @@ async def skip_to_end(self) -> None: async def _read_once(self, final: Optional[Dict[str, Any]]) -> None: if self._cursor.at_end: return - status = await self._run_status(final) - if status is not None: - if final is None and self._behind_window(status): - return # the final event lists every step: read in order then + for status in await self._run_statuses(final): + if status is not final and self._behind_window(status): + if final is None: + return # the final event lists every step: read in order then + continue # learning these steps first would leave a gap self._learn(units_of(status)) winners = attempts_of(status) for key, state in self._units.items(): @@ -303,9 +304,9 @@ def _wanted(self) -> Dict[Unit, _UnitState]: if not self._cursor.skips_step(unit[0]) } - async def _run_status( + async def _run_statuses( self, final: Optional[Dict[str, Any]] - ) -> Optional[Dict[str, Any]]: + ) -> List[Dict[str, Any]]: """The run's status, when there may be something new in it. New units appear when a step starts, and the run says which attempt @@ -314,15 +315,23 @@ async def _run_status( unit whose writes failed must not hold the stream back for good). Dapr returns the status only with the run's input and output, so this is the expensive read of a poll. + + Once the run ended, the final event lists its units when it completed. + An interrupted or failed run's final does not, and the step it ended + in may have started after the last read: the status is read once more, + so the stream drains every unit before it closes. A stream that failed + while the run goes on has nothing more to read. """ if final is not None: - return final + if EXECUTED_KEY in final or final.get(STILL_RUNNING_KEY): + return [final] + return [final, await asyncio.to_thread(self._status) or {}] self._polls_since_status += 1 writing = any(not state.complete for state in self._units.values()) if writing and self._polls_since_status < STATUS_EVERY: - return None + return [] self._polls_since_status = 0 - return await asyncio.to_thread(self._status) or {} + return [await asyncio.to_thread(self._status) or {}] def _behind_window(self, status: Dict[str, Any]) -> bool: """Whether the status no longer lists steps this reader still needs. diff --git a/tests/agent/langgraph/test_stream_final_units.py b/tests/agent/langgraph/test_stream_final_units.py new file mode 100644 index 00000000..45013ced --- /dev/null +++ b/tests/agent/langgraph/test_stream_final_units.py @@ -0,0 +1,84 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A live stream reads every unit of the run before it closes on the final event. + +The reader learns a run's units from its custom status, which it reads only +now and then while a unit is being written. A run that pauses on +``interrupt()`` (or fails) right after the last read has a final event that +does not list its units, so the reader must read the status once more: the +``__interrupt__`` chunk comes before ``workflow_interrupted``. +""" + +import asyncio +import unittest +from typing import Any, Dict, List + +from langgraph.types import Interrupt + +from ..core.log_store_fake import FakeLogStore +from .follow_helpers import FollowedStream, transport, write + +DRAFT = [("custom", {"token": i}) for i in range(3)] + [ + ("updates", {"draft": {"draft": "text"}}) +] +ASKED = {"__interrupt__": (Interrupt(value={"question": "ship?"}, id="i-1"),)} +INTERRUPTED = { + "type": "workflow_interrupted", + "workflow_id": "wf", + "status": "interrupted", + "interrupt_seq": 1, + "interrupts": [{"value": {"question": "ship?"}, "id": "i-1"}], +} +FAILED = { + "type": "workflow_failed", + "workflow_id": "wf", + "error": {"message": "boom", "error_type": "WorkflowError"}, +} + + +class TestFinalAfterTheLastStatusRead(unittest.IsolatedAsyncioTestCase): + async def _stream_ending_with(self, final: Dict[str, Any]) -> List[Any]: + log = transport(FakeLogStore()) + write(log, 0, "draft", DRAFT).finish(done=True) + status: Dict[str, Any] = {"executed": [["draft"]]} + # a long poll: the reader reads the status once, then only on the final + live = FollowedStream(log, lambda: status, poll_s=30) + before = await live.take(len(DRAFT)) + # the next step starts and pauses before the reader looks again + status = {"executed": [["draft"], ["ask"]]} + write(log, 1, "ask", [("updates", ASKED)]).finish(done=True) + live.follower.finish(final) + rest = await asyncio.wait_for(live.rest(), 10) + await live.close() + return before + rest + + async def test_an_interrupt_streams_its_chunk_before_the_final_event(self): + frames = await self._stream_ending_with(INTERRUPTED) + names = [name for name, *_ in frames] + self.assertEqual(names[-1], "workflow_interrupted") + self.assertEqual(names[-2], "updates") + self.assertIn("__interrupt__", frames[-2][1]) + self.assertEqual( + frames[-2][1]["__interrupt__"][0]["value"], + INTERRUPTED["interrupts"][0]["value"], + ) + + async def test_a_failed_run_streams_what_its_last_step_wrote(self): + frames = await self._stream_ending_with(FAILED) + self.assertEqual([n for n, *_ in frames][-2:], ["updates", "workflow_failed"]) + self.assertIn("__interrupt__", frames[-2][1]) + + +class TestFinalBehindTheWindow(unittest.IsolatedAsyncioTestCase): + async def test_a_reader_behind_the_window_does_not_learn_later_steps_first(self): + # the status lists only steps 5 on: steps 0..4 are in no status and no + # final event, so step 5 now would leave a gap a cursor then skips + log = transport(FakeLogStore()) + write(log, 5, "z", [("updates", {"z": {"n": 5}})]).finish(done=True) + status = {"executed_from": 5, "executed": [["z"]]} + live = FollowedStream(log, lambda: status, poll_s=30) + live.follower.finish(INTERRUPTED) + frames = await asyncio.wait_for(live.rest(), 10) + await live.close() + self.assertEqual([n for n, *_ in frames], ["workflow_interrupted"]) From 90008656954020af2a9094c50a363f154f103f00 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 22:16:15 +0100 Subject: [PATCH 69/73] fix(langgraph): a reconnected stream starts at the client's id, not v1.start workflow_started always carried v1.start, also on GET /agent/run/{id}/stream with a Last-Event-ID. A connection that dropped right after it made the client reconnect with v1.start and receive the whole run again. It now carries the id the client resumed from (normalized as a cursor); a new run still starts at v1.start. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 6 ++++-- diagrid/agent/langgraph/stream_drain.py | 5 +++-- .../agent/langgraph/test_stream_reconnect.py | 20 ++++++++++++++++++- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 8efb0c53..0624f384 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -284,8 +284,10 @@ when there is one. A workflow that failed carries its `error`; a run paused by Every event carries an SSE `id`. With the state-store transport (see [Streaming across replicas](#streaming-across-replicas)) the id is a cursor -into the run's event log that any replica can resume from: `v1.start` on -`workflow_started`, `v1.end` on the final event, and in between the position +into the run's event log that any replica can resume from: on +`workflow_started` where the stream starts (`v1.start` for a new run, the id +the client sent on a reconnect, so a drop right after it replays nothing), +`v1.end` on the final event, and in between the position after that chunk (a control event repeats the id of the chunk before it). A `workflow_failed` with `workflow_still_running: true` is not the run's end: it repeats the id of the last chunk too (on a reconnect, before any chunk, the id diff --git a/diagrid/agent/langgraph/stream_drain.py b/diagrid/agent/langgraph/stream_drain.py index cee3d242..d45db01e 100644 --- a/diagrid/agent/langgraph/stream_drain.py +++ b/diagrid/agent/langgraph/stream_drain.py @@ -143,8 +143,9 @@ def __init__(self, replayable: bool, resume_from: Optional[str] = None) -> None: def of(self, item: StreamEvent) -> Tuple[str, ...]: if not self._replayable: return () - if item.mode == WORKFLOW_STARTED: - return (START_ID,) + # workflow_started says where the stream starts: v1.start for a new + # run, the client's cursor on a reconnect (a drop right after it must + # not replay the run), or the one it carries if item.event_id: self._last = item.event_id # a control event reuses the cursor of the chunk it follows diff --git a/tests/agent/langgraph/test_stream_reconnect.py b/tests/agent/langgraph/test_stream_reconnect.py index 687ec0da..17a0517a 100644 --- a/tests/agent/langgraph/test_stream_reconnect.py +++ b/tests/agent/langgraph/test_stream_reconnect.py @@ -69,9 +69,27 @@ def test_resuming_after_any_event_gives_exactly_the_rest(self): ) got = _frames(resp.text) self.assertEqual(got[0][1], "workflow_started") - self.assertEqual(got[0][0], START_ID) + # where the client resumed from, not v1.start: a drop right + # after it must not replay the whole run + self.assertEqual(got[0][0], frames[cut][0]) # no duplicates, no gaps: the events after the cut, same ids self.assertEqual([(i, e, d) for i, e, d in got[1:]], frames[cut + 1 :]) + again = _frames( + http.get( + f"/agent/run/{wf}/stream", + headers={"Last-Event-ID": got[0][0]}, + ).text + ) + self.assertEqual(again[1:], frames[cut + 1 :]) + + def test_a_new_stream_and_a_replay_from_the_start_begin_at_the_start(self): + runner = log_runner(_golden_graph(), "re-start-id") + frames = self._post(runner) + self.assertEqual(frames[0][0], START_ID) + wf = frames[0][2]["workflow_id"] + _wait_done(runner, wf) + got = _frames(TestClient(serve_app(runner)).get(f"/agent/run/{wf}/stream").text) + self.assertEqual(got[0][0], START_ID) def test_the_query_parameter_works_like_the_header(self): runner = log_runner(_golden_graph(), "re-query") From aec4d6b4917d9428bd7e0c371d5e99c367413503 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 22:31:20 +0100 Subject: [PATCH 70/73] fix(langgraph): a resume's stream starts after the run's last chunk, not v1.start The stream of POST /agent/run/{id}/resume carries what happens after the resume only, but its workflow_started carried v1.start, and so did a failure before its first chunk. A client that reconnected with either got the part of the run streamed before the interrupt again. workflow_started now carries the cursor of what the log held when the stream started, and a failure before the first chunk repeats it. Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/README.md | 8 +- diagrid/agent/langgraph/resume_run.py | 8 +- .../agent/langgraph/test_resume_stream_ids.py | 87 +++++++++++++++++++ 3 files changed, 99 insertions(+), 4 deletions(-) create mode 100644 tests/agent/langgraph/test_resume_stream_ids.py diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 0624f384..75350e3c 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -286,12 +286,14 @@ Every event carries an SSE `id`. With the state-store transport (see [Streaming across replicas](#streaming-across-replicas)) the id is a cursor into the run's event log that any replica can resume from: on `workflow_started` where the stream starts (`v1.start` for a new run, the id -the client sent on a reconnect, so a drop right after it replays nothing), +the client sent on a reconnect, and on the stream of a resume the position +after the run's last chunk before it, so a drop right after it replays +nothing), `v1.end` on the final event, and in between the position after that chunk (a control event repeats the id of the chunk before it). A `workflow_failed` with `workflow_still_running: true` is not the run's end: it -repeats the id of the last chunk too (on a reconnect, before any chunk, the id -the client sent). With the in-process transport the events are numbered from 1 +repeats the id of the last chunk too (before any chunk, the id of +`workflow_started`). With the in-process transport the events are numbered from 1 on each connection. #### Reconnecting diff --git a/diagrid/agent/langgraph/resume_run.py b/diagrid/agent/langgraph/resume_run.py index e4106d71..67e8333a 100644 --- a/diagrid/agent/langgraph/resume_run.py +++ b/diagrid/agent/langgraph/resume_run.py @@ -19,6 +19,7 @@ import logging import time import uuid +from dataclasses import replace from typing import Any, AsyncGenerator, AsyncIterator, Dict, Set, Tuple from diagrid.agent.core.workflow.stream import frame_sse @@ -142,7 +143,12 @@ async def pump() -> None: ) pump_task = asyncio.create_task(pump()) - yield started_event(workflow_id, thread_id) + started = started_event(workflow_id, thread_id) + if source.follower is not None: + # the stream starts after what the log held: a reconnect from + # here gets the rest of the run, not what came before the resume + started = replace(started, event_id=source.follower.event_id()) + yield started async for item in drain( source, workflow_id=workflow_id, diff --git a/tests/agent/langgraph/test_resume_stream_ids.py b/tests/agent/langgraph/test_resume_stream_ids.py new file mode 100644 index 00000000..edff811c --- /dev/null +++ b/tests/agent/langgraph/test_resume_stream_ids.py @@ -0,0 +1,87 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The stream of a resume starts at the run's last chunk, not at ``v1.start``. + +It carries what happens after the resume only, so its ``workflow_started`` +(and a failure before its first chunk) carries the cursor of what the log held +when it started: a reconnect with that id gets the rest of the run, not the +part streamed before the interrupt again. +""" + +from typing import Any, List, Tuple +from unittest import mock + +from fastapi.testclient import TestClient + +from diagrid.agent.core.workflow.stream_cursor import START_ID + +from .log_helpers import log_runner +from .streaming_helpers import serve_app +from .test_interrupt import INPUT, _approval_graph, _wait +from .test_reconnect_helpers import frames +from .test_runner import _RunnerTestCase + +Frames = List[Tuple[Any, str, Any]] + + +async def _broken_drain(*args: Any, **kwargs: Any) -> Any: + raise ConnectionError("sidecar gone") + yield # an async generator + + +class TestResumeStreamIds(_RunnerTestCase): + def _interrupted(self, name: str) -> Tuple[Any, TestClient, Frames]: + runner = log_runner(_approval_graph(), name) + http = TestClient(serve_app(runner)) + got = frames(http.post("/agent/run", json={**INPUT, "stream": True}).text) + self.assertEqual(got[-1][1], "workflow_interrupted") + return runner, http, got + + def _reconnect(self, http: TestClient, wf: str, event_id: str) -> Frames: + return frames( + http.get( + f"/agent/run/{wf}/stream", headers={"Last-Event-ID": event_id} + ).text + ) + + def test_a_drop_right_after_workflow_started_resumes_the_rest(self): + runner, http, got = self._interrupted("ids-started") + wf = got[-1][2]["workflow_id"] + rest = frames( + http.post( + f"/agent/run/{wf}/resume", json={"resume": "yes", "stream": True} + ).text + ) + started_id = rest[0][0] + self.assertEqual(rest[0][1], "workflow_started") + self.assertNotEqual(started_id, START_ID) + _wait(lambda: wf in runner._workflow_client.done) + again = self._reconnect(http, wf, started_id) + # exactly what the resume's stream carried: nothing from before it + self.assertEqual(again[1:], rest[1:]) + + def test_a_failure_before_the_first_chunk_carries_the_same_id(self): + runner, http, got = self._interrupted("ids-broken") + wf = got[-1][2]["workflow_id"] + with mock.patch("diagrid.agent.langgraph.resume_run.drain", _broken_drain): + broken = frames( + http.post( + f"/agent/run/{wf}/resume", json={"resume": "yes", "stream": True} + ).text + ) + self.assertEqual( + [e for _, e, _ in broken], ["workflow_started", "workflow_failed"] + ) + self.assertTrue(broken[-1][2]["workflow_still_running"]) + self.assertNotEqual(broken[-1][0], START_ID) + self.assertEqual(broken[-1][0], broken[0][0]) + _wait(lambda: wf in runner._workflow_client.done) + after = self._reconnect(http, wf, broken[-1][0]) + # the same events as a client that kept the last chunk before the + # interrupt gets (the ids differ: each repeats the cursor it was sent) + kept = self._reconnect(http, wf, got[-2][0]) + self.assertEqual( + [(e, d) for _, e, d in after[1:]], [(e, d) for _, e, d in kept[1:]] + ) + self.assertEqual(after[-1][1], "workflow_completed") From 2cb5131b50c692e158f4247da4b0af857f805bd6 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Thu, 26 Nov 2026 22:41:31 +0100 Subject: [PATCH 71/73] test(langgraph): keep the inline when_all in place for the whole session Tests that drive agent_workflow inline patch the workflow's when_all per run, and a patch restores whatever it found when it ends. A patch that ended while another thread's run was still going (a paused run of an earlier test whose wait timed out) put the real when_all back under it, and that run failed with "'dict' object has no attribute '_parent'". Which test hit it depended on timing: adding tests made a reconnect test in test_status_size fail in the full suite only. A session fixture now sets the inline when_all once, so every restore restores it. Signed-off-by: Casper Nielsen --- tests/agent/langgraph/conftest.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 tests/agent/langgraph/conftest.py diff --git a/tests/agent/langgraph/conftest.py b/tests/agent/langgraph/conftest.py new file mode 100644 index 00000000..b4c7338f --- /dev/null +++ b/tests/agent/langgraph/conftest.py @@ -0,0 +1,28 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +from typing import Iterator + +import pytest + +from diagrid.agent.langgraph import workflow + + +@pytest.fixture(autouse=True, scope="session") +def _inline_when_all() -> Iterator[None]: + """Run ``when_all`` inline for the whole session, not per test or per thread. + + These tests drive ``agent_workflow`` inline, where ``when_all`` must + return the activities' results as a list, and many patch it per run. A + patch saves and restores the module attribute, so one that ends while + another thread's run is still going (a paused run of an earlier test + whose wait timed out, say) put the real ``when_all`` back under it, and + that run failed with ``'dict' object has no attribute '_parent'``. With + the inline one in place for the session, every restore restores it. + """ + real = workflow.when_all + workflow.when_all = list # type: ignore[assignment] + try: + yield + finally: + workflow.when_all = real # type: ignore[assignment] From d5f13081c23cc1db3ceb5afe1332089141d5bb23 Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Fri, 27 Nov 2026 08:29:03 +0100 Subject: [PATCH 72/73] fix(langgraph): take a resume stream's start id before the resume is sent The workflow_started of a resume's stream took its id from the follower after the run had taken the resume. The follower reads the log on its own while the run goes on, so by then it could already have read the run's first chunks after the resume, which the stream had not yet yielded. The id then pointed past them, and a reconnect with it missed them (test_a_drop_right_after_workflow_started_resumes_the_rest failed in CI on 3.12). The id is now read once the follower has skipped to the end of the log and before the resume is sent, while the paused run cannot add to it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Casper Nielsen --- diagrid/agent/langgraph/resume_run.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/diagrid/agent/langgraph/resume_run.py b/diagrid/agent/langgraph/resume_run.py index 67e8333a..933839b9 100644 --- a/diagrid/agent/langgraph/resume_run.py +++ b/diagrid/agent/langgraph/resume_run.py @@ -131,8 +131,14 @@ async def resume_run_events( ) pump_task = None try: + started = started_event(workflow_id, thread_id) if source.follower is not None: await source.follower.ready.wait() + # the stream starts after what the log held: a reconnect from + # here gets the rest of the run, not what came before the resume. + # Read before the resume is sent: the follower reads on while the + # run goes on, ahead of what this stream has yielded. + started = replace(started, event_id=source.follower.event_id()) await _send_resume(runner, workflow_id, seq, value) async def pump() -> None: @@ -143,11 +149,6 @@ async def pump() -> None: ) pump_task = asyncio.create_task(pump()) - started = started_event(workflow_id, thread_id) - if source.follower is not None: - # the stream starts after what the log held: a reconnect from - # here gets the rest of the run, not what came before the resume - started = replace(started, event_id=source.follower.event_id()) yield started async for item in drain( source, From 290cf4e04a75be48ecb762d0fc8d08f5b697b54c Mon Sep 17 00:00:00 2001 From: Casper Nielsen Date: Fri, 27 Nov 2026 10:51:20 +0100 Subject: [PATCH 73/73] fix(langgraph): record only the stream modes a run was started with Every node activity of a streamed run wrote a values chunk (the whole output state) and tasks/debug start events (the node's whole input) to the stream log, whatever modes the client asked for. With the default modes (messages, updates, custom) those three copies of the state per activity were never read. The run now carries its requested modes in its config. Activities write values chunks only when the run asked for values, and task events (sent as both tasks and debug) when it asked for either. messages, updates and custom are always written. A run without recorded modes (started before this change) records every mode. A reconnect (GET /agent/run/{id}/stream, astream_resume) or a streamed resume that asks for a mode the run did not record is refused with a 422 (ValueError in Python) naming the modes the run recorded. A resumed run keeps the modes it was started with. The README's Streaming section says so. With no task event, a node that fails before its first chunk logged nothing and wrote no head, and a replay of the run reported its log as expired (stream_purged). A failed attempt that logged nothing now writes its head, and a replay reports the log expired only when a unit whose output the run used has no head either. Signed-off-by: Casper Nielsen --- diagrid/agent/core/workflow/stream_log.py | 6 +- diagrid/agent/langgraph/README.md | 41 +- diagrid/agent/langgraph/reconnect.py | 22 +- diagrid/agent/langgraph/resume_run.py | 25 +- diagrid/agent/langgraph/runner.py | 14 +- diagrid/agent/langgraph/stream_follow.py | 6 +- diagrid/agent/langgraph/stream_modes.py | 123 ++++++ diagrid/agent/langgraph/streaming.py | 8 + diagrid/agent/langgraph/workflow.py | 12 +- .../agent/langgraph/test_readme_streaming.py | 8 + .../agent/langgraph/test_resume_stream_ids.py | 18 +- .../langgraph/test_stream_modes_recorded.py | 406 ++++++++++++++++++ 12 files changed, 660 insertions(+), 29 deletions(-) create mode 100644 diagrid/agent/langgraph/stream_modes.py create mode 100644 tests/agent/langgraph/test_stream_modes_recorded.py diff --git a/diagrid/agent/core/workflow/stream_log.py b/diagrid/agent/core/workflow/stream_log.py index 722ef5af..000aec17 100644 --- a/diagrid/agent/core/workflow/stream_log.py +++ b/diagrid/agent/core/workflow/stream_log.py @@ -302,8 +302,10 @@ def _flush(self, *, done: bool, final: bool = False) -> bool: batch = list(self._pending) if not batch and not final: return True - if not batch and not done: - return True + if not batch and not done and self._batches: + return True # the head written with the last batch says it all + # A failed attempt that logged nothing still writes its head: a + # reader then knows the unit was written, not that its log expired. batches = self._batches + (1 if batch else 0) head = { "attempt": self.attempt, diff --git a/diagrid/agent/langgraph/README.md b/diagrid/agent/langgraph/README.md index 75350e3c..21229cf3 100644 --- a/diagrid/agent/langgraph/README.md +++ b/diagrid/agent/langgraph/README.md @@ -274,6 +274,16 @@ sent as `{"unserializable": ""}`, counted in the final event's removed before the graph (or your `input_mapper`) sees it. On a plain request they are left alone. +A streamed run records only what it was asked for. The chunks of `messages`, +`updates` and `custom` are always written to the run's event log. A `values` +chunk holds the whole state, so it is written only when the run was started +with `values`. A `tasks` or `debug` start event holds the node's whole input; +`tasks` and `debug` carry the same events, so both are written when the run +was started with either. A run streamed with the default modes therefore +writes no copy of its state per node. A run that needs the state at the end +has it in the final event and in `GET /agent/run/{workflow_id}` whatever +modes it was started with. + `GET /agent/run/{workflow_id}` reports a run by the id in `workflow_started`: `status` is the workflow's runtime status, and once the run has completed the body also has the `output` and `steps` a plain `POST /agent/run` returns for @@ -315,12 +325,15 @@ that does not parse, the whole run is replayed; with `v1.end` only the final event is sent. A run that already ended is replayed the same way, for as long as its log is kept (an hour by default). `stream_mode` (repeat the parameter, or separate modes with commas) picks the chunks as on `POST`; an unsupported -one is a `422`, and an unknown run a `404`. If a node was retried after the -client saw part of its output, the stream sends `node_reset` for it before the -new attempt's chunks. If part of the log has expired, the stream sends -`stream_purged` once and goes on with what is still there and what comes -live (a run resumed after waiting on `interrupt()` for longer than the batch -TTL streams everything after the resume), then the final event. A run that +one is a `422`, and an unknown run a `404`. A mode the run did not record +(`values`, `tasks` or `debug` when the run was not started with it) is a `422` +too, whose message names the modes the run recorded: reconnect with those. If +a node was retried after the client saw part of its output, the stream sends +`node_reset` for it before the new attempt's chunks. If part of the log has +expired, the stream sends `stream_purged` once and goes on with what is still +there and what comes live (a run resumed after waiting on `interrupt()` for +longer than the batch TTL streams everything after the resume), then the +final event. A run that ended more than a day ago has no log left at all: its replay is `stream_purged` and the final event. @@ -330,7 +343,8 @@ On the in-process transport nothing can be replayed: the endpoint answers with the run and sends the final event with its result. In Python, `runner.astream_resume(workflow_id, last_event_id=None, -stream_mode=...)` does the same and yields what `astream` yields. +stream_mode=...)` does the same and yields what `astream` yields; a mode the +run did not record raises `ValueError` before anything is yielded. #### Streaming across replicas @@ -429,11 +443,14 @@ needed for this. - Resume it with `POST /agent/run/{workflow_id}/resume` and the body `{"resume": }` (add `"stream": true`, and `stream_mode` if you like, for SSE; without it the response is the run's result, as a plain `POST` - returns it). In Python: `runner.astream(Command(resume=value), - workflow_id=...)` or `runner.invoke(Command(resume=value), - workflow_id=...)`. The interrupted node runs again in the same run, on the - same thread, and `interrupt()` returns the value; a dict keyed by interrupt - ids answers several interrupts one by one. The stream of a resume carries + returns it). A resumed run keeps the stream modes it was started with: a + streamed resume that asks for `values`, `tasks` or `debug` the run did not + record is a `422` (a `ValueError` from `astream`), and the run still waits. + In Python: `runner.astream(Command(resume=value), workflow_id=...)` or + `runner.invoke(Command(resume=value), workflow_id=...)`. The interrupted + node runs again in the same run, on the same thread, and `interrupt()` + returns the value; a dict keyed by interrupt ids answers several + interrupts one by one. The stream of a resume carries what happens after it (starting with `node_reset` for the node that runs again) and ends with the final event, or with `workflow_interrupted` when a node asks again. A body without `resume`, or with `"resume": null` (as diff --git a/diagrid/agent/langgraph/reconnect.py b/diagrid/agent/langgraph/reconnect.py index b49d7a16..d19aa73d 100644 --- a/diagrid/agent/langgraph/reconnect.py +++ b/diagrid/agent/langgraph/reconnect.py @@ -15,7 +15,16 @@ import asyncio import json import logging -from typing import Any, AsyncGenerator, AsyncIterator, Dict, Optional, Set, Tuple +from typing import ( + Any, + AsyncGenerator, + AsyncIterator, + Dict, + List, + Optional, + Set, + Tuple, +) from diagrid.agent.core.workflow import stream as stream_module from diagrid.agent.core.workflow.stream import ( @@ -26,6 +35,7 @@ from diagrid.agent.core.workflow.stream_cursor import parse_cursor from .stream_drain import SseEncoder, drain, encode_final +from .stream_modes import UnrecordedStreamMode, check_recorded from .stream_events import ( FINAL_EVENTS, KEEPALIVE, @@ -126,15 +136,19 @@ async def resume_events( *, poll_interval: float, keepalive: bool, + modes: Optional[List[str]] = None, ) -> AsyncGenerator[Any, None]: """The items of a reconnected stream, as ``_stream_events`` yields them. - Raises ``LookupError`` for a run the workflow engine does not know. + Raises ``LookupError`` for a run the workflow engine does not know, and + :class:`UnrecordedStreamMode` for one of ``modes`` the run did not record. """ client = runner._workflow_client state = await asyncio.to_thread(client.get_workflow_state, instance_id=workflow_id) if state is None: raise LookupError(f"Workflow {workflow_id!r} not found") + if modes is not None: + check_recorded(modes, state, workflow_id) thread_id = _thread_of(state, workflow_id) cursor = parse_cursor(last_event_id) transport = runner.stream_transport @@ -230,6 +244,10 @@ async def stream_run(workflow_id: str, request: Request) -> Any: ) if state is None: raise HTTPException(status_code=404, detail="Workflow not found") + try: + check_recorded(modes, state, workflow_id) + except UnrecordedStreamMode as e: + raise HTTPException(status_code=422, detail=str(e)) last_event_id = request.headers.get( "last-event-id" ) or request.query_params.get("last_event_id") diff --git a/diagrid/agent/langgraph/resume_run.py b/diagrid/agent/langgraph/resume_run.py index 933839b9..22e9fe3c 100644 --- a/diagrid/agent/langgraph/resume_run.py +++ b/diagrid/agent/langgraph/resume_run.py @@ -20,7 +20,7 @@ import time import uuid from dataclasses import replace -from typing import Any, AsyncGenerator, AsyncIterator, Dict, Set, Tuple +from typing import Any, AsyncGenerator, AsyncIterator, Dict, List, Optional, Set, Tuple from diagrid.agent.core.workflow.stream import frame_sse @@ -29,6 +29,7 @@ from .interrupts import RESUME_EVENT, pending_interrupt, resume_taken from .reconnect import _thread_of, follow_final from .stream_drain import SseEncoder, drain, encode_final +from .stream_modes import UnrecordedStreamMode, check_recorded from .stream_events import started_event, stream_failure_event, without_executed from .stream_source import custom_status, open_source from .streaming import normalize_final, normalize_stream_mode @@ -53,17 +54,23 @@ class InvalidResume(ValueError): TAKE_TIMEOUT_S = 30.0 -async def _pending(runner: Any, workflow_id: str, value: Any) -> Tuple[int, str]: +async def _pending( + runner: Any, workflow_id: str, value: Any, modes: Optional[List[str]] = None +) -> Tuple[int, str]: """``(interrupt seq, thread id)`` of a run waiting for a resume. Raises ``LookupError`` for an unknown run, :class:`NotInterrupted` for a run that is not waiting, :class:`InvalidResume` for a ``value`` its - interrupts cannot take. + interrupts cannot take, :class:`UnrecordedStreamMode` for one of the + stream ``modes`` the run does not record (a resumed run keeps the modes + it was started with). """ client = runner._workflow_client state = await asyncio.to_thread(client.get_workflow_state, instance_id=workflow_id) if state is None: raise LookupError(f"Workflow {workflow_id!r} not found") + if modes is not None: + check_recorded(modes, state, workflow_id) pending = pending_interrupt( parse_status(getattr(state, "serialized_custom_status", None)) ) @@ -116,9 +123,10 @@ async def resume_run_events( *, poll_interval: float, keepalive: bool, + modes: Optional[List[str]] = None, ) -> AsyncGenerator[Any, None]: """Resume the run and yield its stream from there, as ``_stream_events`` does.""" - seq, thread_id = await _pending(runner, workflow_id, value) + seq, thread_id = await _pending(runner, workflow_id, value, modes) client = runner._workflow_client seen: Set[Tuple[int, str]] = set() source = open_source( @@ -232,15 +240,18 @@ async def resume_run(workflow_id: str, request: Request) -> Any: ) except ValueError as e: raise HTTPException(status_code=422, detail=str(e)) + streamed = body.get("stream") is True try: - await _pending(runner, workflow_id, body["resume"]) + await _pending( + runner, workflow_id, body["resume"], modes if streamed else None + ) except LookupError: raise HTTPException(status_code=404, detail="Workflow not found") - except InvalidResume as e: + except (InvalidResume, UnrecordedStreamMode) as e: raise HTTPException(status_code=422, detail=str(e)) except NotInterrupted as e: raise HTTPException(status_code=409, detail=str(e)) - if body.get("stream") is True: + if streamed: events = _resume_sse(runner, workflow_id, body["resume"], modes) try: # the first event comes once the run took this resume diff --git a/diagrid/agent/langgraph/runner.py b/diagrid/agent/langgraph/runner.py index 394a3f41..eb79e047 100644 --- a/diagrid/agent/langgraph/runner.py +++ b/diagrid/agent/langgraph/runner.py @@ -63,6 +63,7 @@ from .reconnect import add_reconnect_route, resume_events from .resume_run import add_resume_route, resume_run_events from .stream_drain import SseEncoder, drain, encode_final, parse_output +from .stream_modes import with_stream_modes from .stream_source import ( custom_status, open_source, @@ -972,7 +973,8 @@ async def astream_resume( nothing is replayed: ``stream_unavailable`` with reason ``transport_not_replayable``, then the run's end. Raises ``LookupError`` for an unknown run and :class:`GraphRunError` for a - run that failed. + run that failed, and ``ValueError`` for a mode the run did not record + (``values``, ``tasks`` or ``debug`` when it was not started with it). """ modes, is_list = normalize_stream_mode(stream_mode) async with aclosing( @@ -982,6 +984,7 @@ async def astream_resume( last_event_id, poll_interval=poll_interval, keepalive=False, + modes=modes, ) ) as events: async for item in events: @@ -1040,6 +1043,7 @@ async def astream( command_resume(input, workflow_id, "astream"), poll_interval=poll_interval, keepalive=False, + modes=modes, ) else: events = self._stream_events( @@ -1048,6 +1052,7 @@ async def astream( thread_id=thread_id, workflow_id=workflow_id, poll_interval=poll_interval, + modes=modes, ) # aclosing: if the caller stops early, close the inner stream now (it # unregisters the sink) instead of whenever the garbage collector runs. @@ -1069,9 +1074,13 @@ async def _stream_events( poll_interval: float, on_result: Optional[Callable[[Dict[str, Any]], None]] = None, keepalive: bool = False, + modes: Optional[List[str]] = None, ) -> AsyncGenerator[Any, None]: """Yield ``StreamEvent`` chunks, then the terminal event dict. + ``modes`` are the stream modes asked for: the run records those (see + ``stream_modes``); ``None`` records every mode. + The terminal event is always the last item: ``workflow_completed`` or ``workflow_failed`` (see :func:`normalize_final`), carrying the run's ``workflow_id`` and ``thread_id``. @@ -1090,6 +1099,8 @@ async def _stream_events( config, merged, thread_id, workflow_id ) run_config = {**run_config, STREAM_RUN_KEY: True} + if modes is not None: + run_config = with_stream_modes(run_config, modes) if not named: run_config[_STATELESS_KEY] = True seen_nodes: Set[Tuple[int, str]] = set() @@ -1327,6 +1338,7 @@ async def _serve_stream( # type: ignore[override] poll_interval=0.5, on_result=on_result, keepalive=True, + modes=modes, ) ) as events: async for item in events: diff --git a/diagrid/agent/langgraph/stream_follow.py b/diagrid/agent/langgraph/stream_follow.py index d0eb8095..00a008be 100644 --- a/diagrid/agent/langgraph/stream_follow.py +++ b/diagrid/agent/langgraph/stream_follow.py @@ -286,7 +286,10 @@ def _expired(self) -> bool: Heads outlive batches (a day by default), and a run that ended that long ago has none left. A unit missing among others that are there - is still a write that failed, and so is a live stream's. + is still a write that failed, and so is a live stream's. Only a unit + whose output the run used (it has a winner) surely wrote a head, so + one of those must be among the missing: a node that failed before + its first chunk is not taken for an expired log. """ wanted = self._wanted() return ( @@ -294,6 +297,7 @@ def _expired(self) -> bool: and not self.purged and bool(wanted) and all(state.attempt is None for state in wanted.values()) + and any(state.winner for state in wanted.values()) ) def _wanted(self) -> Dict[Unit, _UnitState]: diff --git a/diagrid/agent/langgraph/stream_modes.py b/diagrid/agent/langgraph/stream_modes.py new file mode 100644 index 00000000..abd2d0f5 --- /dev/null +++ b/diagrid/agent/langgraph/stream_modes.py @@ -0,0 +1,123 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""Which stream modes a streamed run records. + +A streamed run carries the modes it was started with in its config +(:data:`STREAM_MODES_KEY`), which every activity is handed. The chunks of +``messages``, ``updates`` and ``custom`` are always written; a ``values`` +chunk (the whole output state) and the ``tasks``/``debug`` events (a task's +start event carries the node's whole input) only when the run asked for that +mode. Without them a run streamed with the default modes writes no copy of +the state per activity to the stream log. + +A run whose config has no modes (started before the runner recorded them, +or not streamed) records every mode, as before. +""" + +import json +from typing import Any, Dict, FrozenSet, Iterable, List, Optional + +from diagrid.agent.core.workflow.stream import UPDATES, VALUES + +from .task_events import DEBUG, TASKS + +#: Workflow config key: the stream modes the run was started with. +STREAM_MODES_KEY = "diagrid_stream_modes" + +#: Modes whose chunks a streamed run always writes. +ALWAYS_RECORDED = ("messages", UPDATES, "custom") +#: Modes whose chunks are written only when the run asked for them. +ON_REQUEST = (VALUES, TASKS, DEBUG) + + +#: The modes of a task's start and result events, which are written together. +_TASK_MODES = frozenset((TASKS, DEBUG)) + + +class UnrecordedStreamMode(ValueError): + """A stream asked for a mode its run did not record (``422``).""" + + +def recorded_modes(config: Optional[Dict[str, Any]]) -> Optional[FrozenSet[str]]: + """The modes a run with ``config`` records, or ``None`` for all of them. + + ``tasks`` and ``debug`` are the same events, written together: a run + started with either records both. + """ + requested = (config or {}).get(STREAM_MODES_KEY) + if not isinstance(requested, list): + return None + recorded = frozenset(ALWAYS_RECORDED) | frozenset(requested) + if recorded & _TASK_MODES: + recorded |= _TASK_MODES + return recorded + + +def records(config: Optional[Dict[str, Any]], mode: str) -> bool: + """Whether a run with ``config`` writes chunks of ``mode``.""" + modes = recorded_modes(config) + return modes is None or mode in modes + + +def records_values(config: Optional[Dict[str, Any]]) -> bool: + """Whether a run with ``config`` writes ``values`` chunks.""" + return records(config, VALUES) + + +def records_task_events(config: Optional[Dict[str, Any]]) -> bool: + """Whether a run with ``config`` writes ``tasks`` and ``debug`` events.""" + return records(config, TASKS) + + +def with_stream_modes(config: Dict[str, Any], modes: Iterable[str]) -> Dict[str, Any]: + """A copy of ``config`` that records ``modes`` (in a canonical order).""" + wanted = set(modes) + order = [*ALWAYS_RECORDED, *ON_REQUEST] + return {**config, STREAM_MODES_KEY: [m for m in order if m in wanted]} + + +def recorded_in_state(state: Any) -> Optional[FrozenSet[str]]: + """The modes the run of a workflow ``state`` records (from its input).""" + raw = getattr(state, "serialized_input", None) + try: + data = json.loads(raw) if isinstance(raw, str) else raw + except (TypeError, ValueError): + return None + config = data.get("config") if isinstance(data, dict) else None + return recorded_modes(config if isinstance(config, dict) else None) + + +def check_recorded(requested: Iterable[str], state: Any, workflow_id: str) -> List[str]: + """``requested`` if the run of ``state`` recorded all of them. + + Raises :class:`UnrecordedStreamMode`, naming the modes the run recorded, + for a mode whose chunks were never written. + """ + wanted = list(requested) + recorded = recorded_in_state(state) + if recorded is None: + return wanted + missing = [m for m in wanted if m not in recorded] + if missing: + order = [*ALWAYS_RECORDED, *ON_REQUEST] + raise UnrecordedStreamMode( + f"Run {workflow_id!r} did not record stream_mode {missing!r}: it " + f"records {[m for m in order if m in recorded]!r}, the modes it was " + "started with plus messages, updates and custom. " + + _refusal_hint(missing, workflow_id) + ) + return wanted + + +def _refusal_hint(missing: List[str], workflow_id: str) -> str: + """Where a client finds what the refused modes would have carried.""" + if VALUES in missing: + return ( + "Its final state is in the final event and in " + f"GET /agent/run/{workflow_id}." + ) + return ( + "Its task events are written only when it is started with tasks or " + "debug; the updates mode carries each task's writes." + ) diff --git a/diagrid/agent/langgraph/streaming.py b/diagrid/agent/langgraph/streaming.py index f58fad5c..beefe69d 100644 --- a/diagrid/agent/langgraph/streaming.py +++ b/diagrid/agent/langgraph/streaming.py @@ -175,8 +175,12 @@ def __init__( sink_node: Optional[str] = None, path: Optional[Sequence[Any]] = None, branch: Optional[str] = None, + task_events: bool = True, ) -> None: self._path = tuple(path) if path else None + # False when the run did not ask for ``tasks`` or ``debug``: a task's + # start event carries the node's whole input, not worth writing unread. + self._task_events = task_events # The conditional edge whose function this streamer serves, if any. self._branch = branch # ``sink_node`` is the name chunks are keyed under in the sink when it @@ -344,6 +348,8 @@ def task_started( self, node_input: Any, config: Optional[Dict[str, Any]] = None ) -> None: """Send the task's start event, as LangGraph does when a step starts it.""" + if not self._task_events: + return config = config or {} metadata = task_metadata( self._static.metadata(config.get("metadata")), @@ -356,6 +362,8 @@ def task_started( def task_finished(self, writes: List[Tuple[str, Any]]) -> None: """Send the task's result event: its writes, after its ``updates`` chunk.""" + if not self._task_events: + return self._emit_task(task_result(self._event_task_id, self._node, writes)) def branch_finished(self) -> None: diff --git a/diagrid/agent/langgraph/workflow.py b/diagrid/agent/langgraph/workflow.py index c8bd7326..40b98813 100644 --- a/diagrid/agent/langgraph/workflow.py +++ b/diagrid/agent/langgraph/workflow.py @@ -88,6 +88,7 @@ ) from .stream_attempts import record_attempts, with_attempt from .stream_values import state_values +from .stream_modes import records_task_events, records_values from .streaming import STREAM_RUN_KEY, NodeStreamer, StaticConfig from .task_identity import TaskIdentity from .thread_state import THREAD_STATE_PATCH, load_thread, save_thread @@ -564,8 +565,14 @@ class _Run: @property def output_channels(self) -> Optional[List[str]]: - """What an activity of a streamed run sends ``values`` chunks of.""" - if not (self.config or {}).get(STREAM_RUN_KEY): + """What an activity of a streamed run sends ``values`` chunks of. + + ``None`` (no chunks) when the run was not streamed, or was streamed + without ``values`` (see ``stream_modes``). + """ + if not (self.config or {}).get(STREAM_RUN_KEY) or not records_values( + self.config + ): return None return list(self.graph_config.output_channels) @@ -1432,6 +1439,7 @@ def _streamer_for( sink_node=sink_node, path=None if send_index is None else (PUSH_TRIGGER, send_index, False), branch=branch, + task_events=records_task_events(config), ) diff --git a/tests/agent/langgraph/test_readme_streaming.py b/tests/agent/langgraph/test_readme_streaming.py index 774ad4de..c8184c83 100644 --- a/tests/agent/langgraph/test_readme_streaming.py +++ b/tests/agent/langgraph/test_readme_streaming.py @@ -65,3 +65,11 @@ def test_interrupt_and_resume_are_documented(self): def test_the_proxy_wording_is_kept(self): self.assertIn("#### Behind a proxy", self.text) self.assertNotIn("behind a load balancer", self.text.lower()) + + def test_the_recorded_modes_are_documented(self): + for needed in ( + "A streamed run records only what it was asked for.", + "A mode the run did not record", + "A resumed run keeps the stream modes it was started with", + ): + self.assertIn(needed, self.flat, needed) diff --git a/tests/agent/langgraph/test_resume_stream_ids.py b/tests/agent/langgraph/test_resume_stream_ids.py index edff811c..8a691af1 100644 --- a/tests/agent/langgraph/test_resume_stream_ids.py +++ b/tests/agent/langgraph/test_resume_stream_ids.py @@ -58,8 +58,22 @@ def test_a_drop_right_after_workflow_started_resumes_the_rest(self): self.assertNotEqual(started_id, START_ID) _wait(lambda: wf in runner._workflow_client.done) again = self._reconnect(http, wf, started_id) - # exactly what the resume's stream carried: nothing from before it - self.assertEqual(again[1:], rest[1:]) + # exactly what the resume's stream carried: nothing from before it. + # The ids may differ: a live reader may not yet know a unit whose last + # event it sent is done, a replay does, and both cursors resume alike. + self.assertEqual( + [(e, d) for _, e, d in again[1:]], [(e, d) for _, e, d in rest[1:]] + ) + pairs = zip(rest[1:-1], again[1:-1]) + for i, ((live_id, event, _), (replay_id, _, _)) in enumerate(pairs, start=1): + if event == "node_reset": + continue # a control event repeats the id of the chunk before it + want = [(e, d) for _, e, d in rest[i + 1 :]] + for cursor in (live_id, replay_id): + with self.subTest(event=i, cursor=cursor): + got = self._reconnect(http, wf, cursor) + # the rest of the stream after event i: no repeat, no gap + self.assertEqual([(e, d) for _, e, d in got[1:]], want) def test_a_failure_before_the_first_chunk_carries_the_same_id(self): runner, http, got = self._interrupted("ids-broken") diff --git a/tests/agent/langgraph/test_stream_modes_recorded.py b/tests/agent/langgraph/test_stream_modes_recorded.py new file mode 100644 index 00000000..9344ba91 --- /dev/null +++ b/tests/agent/langgraph/test_stream_modes_recorded.py @@ -0,0 +1,406 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""A streamed run records only the modes it was started with. + +``messages``, ``updates`` and ``custom`` chunks are always written. A +``values`` chunk (the whole state) and the ``tasks``/``debug`` events (a task's +start carries the node's whole input) are written only when the run asked for +them; a reconnect or a streamed resume that asks for one the run did not +record is refused, naming what the run recorded. +""" + +import asyncio +import json +import operator +import unittest +from typing import Any, List, Set + +from fastapi.testclient import TestClient +from langgraph.graph import END, START, StateGraph +from typing_extensions import Annotated, TypedDict + +from diagrid.agent.core.workflow.stream import StreamSinkRegistry +from diagrid.agent.langgraph.models import ChannelState, ExecuteNodeInput +from diagrid.agent.langgraph.stream_modes import ( + STREAM_MODES_KEY, + UnrecordedStreamMode, + check_recorded, + recorded_modes, + with_stream_modes, +) +from diagrid.agent.langgraph.streaming import STREAM_RUN_KEY +from diagrid.agent.langgraph.workflow import ( + clear_registries, + execute_node_activity, + register_node, +) + +from ..core.log_store_fake import FakeLogStore +from .golden_harness import MODES, _both, _FakeDaprTest, _golden_graph, _wire +from .log_helpers import log_runner +from .streaming_helpers import INPUT, _collect, _Ctx, _drain, serve_app +from .test_interrupt import INPUT as ASK_INPUT +from .test_interrupt import _approval_graph +from .test_reconnect_helpers import frames +from .test_runner import _RunnerTestCase +from .test_streaming_golden_tasks import _stable + +ALL_MODES = ["messages", "updates", "custom", "values", "tasks", "debug"] +STATE_MODES = {"values", "tasks", "debug"} + + +def _logged_modes(store: FakeLogStore) -> Set[str]: + """The modes of every event the run's log holds (batches are event lists).""" + return { + wire["mode"] + for value in store.data.values() + if isinstance(value, list) + for wire in value + if isinstance(wire, dict) and "mode" in wire + } + + +class TestRecordedModes(unittest.TestCase): + def test_a_config_without_modes_records_every_mode(self): + self.assertIsNone(recorded_modes({STREAM_RUN_KEY: True})) + self.assertIsNone(recorded_modes(None)) + + def test_the_always_recorded_modes_are_added(self): + config = with_stream_modes({}, ["values"]) + self.assertEqual( + with_stream_modes({}, ["values", "updates"])[STREAM_MODES_KEY], + ["updates", "values"], + ) + self.assertEqual( + recorded_modes(config), {"messages", "updates", "custom", "values"} + ) + + +class TestTheLogHoldsOnlyRequestedModes( + _RunnerTestCase, unittest.IsolatedAsyncioTestCase +): + async def _run(self, name: str, modes: List[str]) -> FakeLogStore: + store = FakeLogStore() + runner = log_runner(_golden_graph(), name, store=store) + await _collect( + runner.astream( + INPUT, workflow_id=f"wf-{name}", stream_mode=modes, poll_interval=0.01 + ) + ) + return store + + async def test_default_modes_write_no_values_or_task_events(self): + logged = _logged_modes(await self._run("lean-default", MODES)) + self.assertTrue(logged) + self.assertFalse(logged & STATE_MODES, logged) + + async def test_values_alone_writes_no_task_events(self): + logged = _logged_modes(await self._run("lean-values", ["values"])) + self.assertIn("values", logged) + self.assertFalse(logged & {"tasks", "debug"}, logged) + + async def test_tasks_alone_writes_task_and_debug_events_but_no_values(self): + logged = _logged_modes(await self._run("lean-tasks", ["tasks"])) + self.assertTrue({"tasks", "debug"} <= logged, logged) + self.assertNotIn("values", logged) + + async def test_every_mode_is_written_when_requested(self): + logged = _logged_modes(await self._run("lean-all", ALL_MODES)) + self.assertTrue(STATE_MODES <= logged, logged) + + async def test_a_replay_of_every_mode_is_what_the_live_stream_gave(self): + runner = log_runner(_golden_graph(), "lean-replay") + live = await _collect( + runner.astream( + INPUT, workflow_id="wf-lr", stream_mode=ALL_MODES, poll_interval=0.01 + ) + ) + again = await _collect( + runner.astream_resume("wf-lr", stream_mode=ALL_MODES, poll_interval=0.01) + ) + self.assertEqual(_wire(again), _wire(live)) + + +class TestEveryModeMatchesNative(_FakeDaprTest): + async def test_all_six_modes_requested_match_native(self): + native, ours = await _both(_golden_graph(), "lean-golden", INPUT, ALL_MODES) + self.assertTrue({m for m, _ in native} >= STATE_MODES) + self._assert_same_sequence(_stable(native), _stable(ours)) + + +class TestUnrecordedModeOnReconnect(_RunnerTestCase): + def _default_run(self, name: str) -> Any: + runner = log_runner(_golden_graph(), name) + http = TestClient(serve_app(runner)) + got = frames( + http.post( + "/agent/run", json={"messages": INPUT["messages"], "stream": True} + ).text + ) + return runner, http, got[0][2]["workflow_id"] + + def test_values_on_a_run_without_it_is_422_naming_the_recorded_modes(self): + _, http, wf = self._default_run("lean-422") + resp = http.get(f"/agent/run/{wf}/stream", params={"stream_mode": "values"}) + self.assertEqual(resp.status_code, 422) + detail = resp.json()["detail"] + self.assertIn("['values']", detail) + self.assertIn("['messages', 'updates', 'custom']", detail) + self.assertIn(f"GET /agent/run/{wf}", detail) + + def test_task_modes_are_refused_too(self): + _, http, wf = self._default_run("lean-422-tasks") + for mode in ("tasks", "debug"): + with self.subTest(mode=mode): + resp = http.get( + f"/agent/run/{wf}/stream", + params={"stream_mode": ["updates", mode]}, + ) + self.assertEqual(resp.status_code, 422) + + def test_a_recorded_mode_is_still_served(self): + _, http, wf = self._default_run("lean-ok") + resp = http.get(f"/agent/run/{wf}/stream", params={"stream_mode": "updates"}) + self.assertEqual(resp.status_code, 200) + + +class TestUnrecordedModeOnAstreamResume( + _RunnerTestCase, unittest.IsolatedAsyncioTestCase +): + async def test_values_on_a_run_without_it_raises_value_error(self): + runner = log_runner(_golden_graph(), "lean-ar") + await _collect( + runner.astream( + INPUT, workflow_id="wf-lean-ar", stream_mode=MODES, poll_interval=0.01 + ) + ) + with self.assertRaises(ValueError) as caught: + await _collect( + runner.astream_resume( + "wf-lean-ar", stream_mode="values", poll_interval=0.01 + ) + ) + self.assertIsInstance(caught.exception, UnrecordedStreamMode) + self.assertIn("'messages', 'updates', 'custom'", str(caught.exception)) + + async def test_a_run_that_asked_for_values_replays_them(self): + runner = log_runner(_golden_graph(), "lean-ar-ok") + await _collect( + runner.astream( + INPUT, + workflow_id="wf-lean-ok", + stream_mode=["updates", "values"], + poll_interval=0.01, + ) + ) + got = await _collect( + runner.astream_resume( + "wf-lean-ok", stream_mode=["values"], poll_interval=0.01 + ) + ) + self.assertTrue([p for m, p in _wire(got) if m == "values"]) + + +class TestUnrecordedModeOnResume(_RunnerTestCase): + def test_a_streamed_resume_keeps_the_runs_modes(self): + runner = log_runner(_approval_graph(), "lean-resume") + http = TestClient(serve_app(runner)) + got = frames(http.post("/agent/run", json={**ASK_INPUT, "stream": True}).text) + self.assertEqual(got[-1][1], "workflow_interrupted") + wf = got[-1][2]["workflow_id"] + refused = http.post( + f"/agent/run/{wf}/resume", + json={"resume": "yes", "stream": True, "stream_mode": ["values"]}, + ) + self.assertEqual(refused.status_code, 422) + self.assertIn("'messages', 'updates', 'custom'", refused.json()["detail"]) + # the refusal raised nothing: the run still waits, and a resume with + # its own modes goes through + ok = frames( + http.post( + f"/agent/run/{wf}/resume", + json={"resume": "yes", "stream": True, "stream_mode": ["updates"]}, + ).text + ) + self.assertEqual(ok[-1][1], "workflow_completed") + + +class TestInProcessActivity(unittest.IsolatedAsyncioTestCase): + def setUp(self): + clear_registries() + self.addCleanup(clear_registries) + + async def _modes_sent(self, config: dict) -> Set[str]: + register_node("b", lambda state: {"log": ["b"]}) + registry = StreamSinkRegistry() + sink = registry.open("wf-ip") + payload = ExecuteNodeInput( + node_name="b", + channel_state=ChannelState( + values={"log": ["a"]}, versions={"log": 2}, updated_channels=["log"] + ), + config=config, + step=1, + ).to_dict() + await asyncio.to_thread( + execute_node_activity, _Ctx("wf-ip"), payload, stream_registry=registry + ) + sink.close() + return {e.mode for e in await _drain(sink) if hasattr(e, "mode")} + + async def test_no_task_events_are_built_for_a_run_without_them(self): + modes = await self._modes_sent(with_stream_modes({STREAM_RUN_KEY: True}, MODES)) + self.assertIn("updates", modes) + self.assertFalse(modes & {"tasks", "debug"}, modes) + + async def test_a_run_without_recorded_modes_sends_task_events(self): + modes = await self._modes_sent({STREAM_RUN_KEY: True}) + self.assertTrue({"tasks", "debug"} <= modes, modes) + + +class TestCheckRecorded(unittest.TestCase): + def test_a_run_from_before_modes_were_recorded_allows_every_mode(self): + from types import SimpleNamespace + + state = SimpleNamespace( + serialized_input='{"config": {"diagrid_streamed": true}}' + ) + self.assertEqual(check_recorded(["values"], state, "wf"), ["values"]) + + +class TestUnrecordedModeOnAstreamCommand( + _RunnerTestCase, unittest.IsolatedAsyncioTestCase +): + async def test_a_resume_asking_for_values_raises_and_the_run_still_waits(self): + from langgraph.types import Command + + runner = log_runner(_approval_graph(), "lean-cmd") + await _collect( + runner.astream( + ASK_INPUT, + workflow_id="wf-cmd", + stream_mode="updates", + poll_interval=0.01, + ) + ) + with self.assertRaises(ValueError): + await _collect( + runner.astream( + Command(resume="go"), + workflow_id="wf-cmd", + stream_mode=["values"], + poll_interval=0.01, + ) + ) + rest = await _collect( + runner.astream( + Command(resume="go"), + workflow_id="wf-cmd", + stream_mode="updates", + poll_interval=0.01, + ) + ) + self.assertEqual(rest[-1], {"after": {"log": ["after:go"]}}) + + +class _Failing(TypedDict, total=False): + log: Annotated[list, operator.add] + + +def _failing_graph(first_ok: bool = True) -> Any: + """[ok ->] boom, where boom raises before it streams anything.""" + + def boom(state: _Failing) -> dict: + raise RuntimeError("boom") + + graph = StateGraph(_Failing) + graph.add_node("boom", boom) + if first_ok: + graph.add_node("ok", lambda state: {"log": ["ok"]}) + graph.add_edge(START, "ok") + graph.add_edge("ok", "boom") + else: + graph.add_edge(START, "boom") + graph.add_edge("boom", END) + return graph.compile() + + +class TestFailedNodeReplay(_RunnerTestCase): + """A node that failed before its first chunk is not an expired log.""" + + def _failed_run(self, name: str, first_ok: bool = True) -> Any: + runner = log_runner(_failing_graph(first_ok), name) + http = TestClient(serve_app(runner)) + live = frames( + http.post( + "/agent/run", + json={"log": [], "stream": True, "stream_mode": ["updates"]}, + ).text + ) + self.assertEqual(live[-1][1], "workflow_failed") + return http, live + + def test_a_replay_from_the_start_sends_no_stream_purged(self): + # only the failing node: no unit of the run logged anything + http, live = self._failed_run("lean-fail-start", first_ok=False) + wf = live[0][2]["workflow_id"] + again = frames( + http.get(f"/agent/run/{wf}/stream", params={"stream_mode": "updates"}).text + ) + self.assertNotIn("stream_purged", [e for _, e, _ in again]) + self.assertEqual( + [(e, d) for _, e, d in again[1:-1]], [(e, d) for _, e, d in live[1:-1]] + ) + self.assertEqual(again[-1][1], "workflow_failed") + + def test_a_reconnect_at_the_failed_step_sends_no_stream_purged(self): + http, live = self._failed_run("lean-fail-base") + wf = live[0][2]["workflow_id"] + # the id after ok's update: the cursor's base is the failed step + after_ok = [i for i, e, d in live if e == "updates"][-1] + again = frames( + http.get( + f"/agent/run/{wf}/stream", + params={"stream_mode": "updates"}, + headers={"Last-Event-ID": after_ok}, + ).text + ) + self.assertEqual( + [e for _, e, _ in again], ["workflow_started", "workflow_failed"] + ) + + def test_the_failed_attempt_writes_a_head(self): + store = FakeLogStore() + runner = log_runner(_failing_graph(), "lean-fail-head", store=store) + frames( + TestClient(serve_app(runner)) + .post("/agent/run", json={"log": [], "stream": True}) + .text + ) + heads = [k for k in store.data if ":boom:" in k and k.endswith(":head")] + self.assertTrue(heads, sorted(store.data)) + + +class TestTaskModesGoTogether(unittest.TestCase): + def test_either_task_mode_records_both(self): + for mode in ("tasks", "debug"): + with self.subTest(mode=mode): + recorded = recorded_modes(with_stream_modes({}, ["updates", mode])) + self.assertTrue({"tasks", "debug"} <= set(recorded or ())) + + def test_the_refusal_of_a_task_mode_does_not_point_at_the_state(self): + from types import SimpleNamespace + + state = SimpleNamespace( + serialized_input=json.dumps( + {"config": with_stream_modes({STREAM_RUN_KEY: True}, ["updates"])} + ) + ) + with self.assertRaises(UnrecordedStreamMode) as caught: + check_recorded(["tasks"], state, "wf") + self.assertIn("started with tasks or debug", str(caught.exception)) + self.assertNotIn("final state", str(caught.exception)) + with self.assertRaises(UnrecordedStreamMode) as caught: + check_recorded(["values"], state, "wf") + self.assertIn("final state", str(caught.exception))