"""Parallel-wave LangGraph executor node.
When a plan contains a sequence of actions whose preconditions /
effects do not interact, they form a *parallel wave* that can be
executed concurrently in the async path or sequentially-in-one-tick
in the sync path.
"""
from __future__ import annotations
import asyncio
import random
from typing import Any, Iterable
from langgraph.errors import GraphBubbleUp
from langgoap.actions import ActionSpec, ensure_unique_action_names
from langgoap.graph.nodes._execution import (
HistoryState,
Observation,
StillWaiting,
_build_failure,
_build_guard_block,
_build_success,
_check_human_approval,
_compact_history,
_is_prepared,
_planning_keys_for,
_prepare_execution,
_settle_wait,
_still_waiting,
_validate_history_state,
)
from langgoap.graph.nodes._helpers import logger
from langgoap.graph.nodes.executor import (
_execute_with_retries_async,
_execute_with_retries_sync,
)
from langgoap.graph.state import (
ActionResult,
GoapState,
rehydrate_state,
serialize_updates,
)
from langgoap.guards import (
ActionGuard,
AsyncActionGuard,
has_blocking_failure,
run_guards_async,
run_guards_sync,
)
from langgoap.planner.transitions import TransitionModel
from langgoap.planner.types import Plan
from langgoap.sensors import AsyncSensor, Sensor
from langgoap.tracing import NullTracer, PlanningTracer, SafeTracerProxy
def _pauses(action: ActionSpec) -> bool:
"""True for an action that interrupts the graph: an approval gate or a wait."""
return bool(action.require_human_approval) or action.is_wait
def _find_parallel_group(
plan_actions: tuple[ActionSpec, ...],
current_step: int,
deps: dict[int, list[int]] | None = None,
) -> list[int]:
"""Return the maximal set of plan indices that can run in parallel from *current_step*.
Uses the CSP dependency graph: action j is added to the group as long as it
does not depend (transitively or directly) on any action already in the
group. The group always contains *current_step* as its first element.
Args:
plan_actions: All actions in the plan (full tuple, not a slice).
current_step: Index of the first action to include.
deps: Pre-computed dependency graph (output of
:func:`~langgoap.planner.csp.build_dependency_graph`). When
``None``, computed on-the-fly. Pass this to avoid redundant
graph construction across waves of the same plan.
Returns:
A list of action indices (all >= current_step) that can execute in
parallel. A single-element list means no parallelism is available at
this step.
"""
if current_step >= len(plan_actions):
return []
if deps is None:
from langgoap.planner.csp import build_dependency_graph
deps = build_dependency_graph(plan_actions)
# A human-approval gate pauses the graph with ``interrupt()``, and so
# does a wait. Neither may share a wave: siblings launched alongside
# would run their side effects before the interrupt and run them again
# after resume.
if _pauses(plan_actions[current_step]):
return [current_step]
group: list[int] = [current_step]
group_set: set[int] = {current_step}
for j in range(current_step + 1, len(plan_actions)):
# Stop if j depends on any action already in the group.
if any(d in group_set for d in deps[j]):
break
if _pauses(plan_actions[j]):
break
group.append(j)
group_set.add(j)
return group
def _abort_wave(
failure: dict[str, Any],
*,
world_state: dict[str, Any],
completed: list[ActionResult],
) -> dict[str, Any]:
"""Return a wave-level failure that keeps what the completed siblings did.
``failure`` is the per-action failure dict (``action_failed`` status,
possibly with ``action_failure_counts`` from a guard block or HITL
denial). The returned dict carries the merged ``world_state`` with
every completed sibling's effects applied and an ``execution_history``
that lists the completed siblings before the failure record, so the
planner sees them as executed (and auto-blacklists ``can_rerun=False``
ones) instead of running them again on the next plan (issue #16).
"""
out = dict(failure)
out["world_state"] = world_state
out["execution_history"] = list(completed) + list(
failure.get("execution_history", [])
)
return out
def _delta(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:
"""Keys ``after`` added or changed relative to ``before``."""
return {k: v for k, v in after.items() if k not in before or before[k] != v}
[docs]
class ParallelGoapExecutor:
"""LangGraph node that executes independent plan actions in parallel.
See :class:`~langgoap.graph.nodes.executor.GoapExecutor` for
sequential semantics; this class differs only in detecting the
maximal *parallel wave* starting at ``current_step`` and running
its members concurrently in the async path.
Args:
tracer: Optional :class:`~langgoap.tracing.PlanningTracer` invoked for
each action in the wave.
guards: Optional list of :class:`~langgoap.guards.ActionGuard` /
:class:`~langgoap.guards.AsyncActionGuard` evaluated before each
action. A ``BLOCK`` failure aborts that action and the whole wave.
transition_model: Optional
:class:`~langgoap.planner.transitions.TransitionModel` consumed
when a wave action's ``execute`` callable returns ``None`` (or
is absent). Mirrors :class:`GoapExecutor` so direct users of
this class get identical stochastic runtime semantics.
rng: Optional ``random.Random`` forwarded to
``transition_model.sample``. When omitted, a single
``random.Random()`` is created at construction time and
reused across waves. Back-off jitter uses a separate stream.
history_state: See :class:`GoapExecutor`; applied to every record of
a wave.
sensors: See :class:`GoapExecutor`.
effects: See :class:`GoapExecutor`.
always_observe: See :class:`GoapExecutor`.
"""
[docs]
def __init__(
self,
*,
tracer: PlanningTracer | None = None,
guards: list[ActionGuard | AsyncActionGuard] | None = None,
transition_model: TransitionModel | None = None,
rng: random.Random | None = None,
actions: list[ActionSpec] | None = None,
history_state: HistoryState = "full",
sensors: list[Sensor | AsyncSensor] | None = None,
effects: str = "declared",
always_observe: Iterable[str] = (),
) -> None:
self._history_state = _validate_history_state(history_state)
# See ``GoapExecutor.__init__`` for the SafeTracerProxy rationale.
self._tracer: PlanningTracer = SafeTracerProxy(tracer or NullTracer())
self._observation = Observation(
sensors,
effects=effects,
always_observe=always_observe,
tracer=self._tracer,
)
self._guards: list[ActionGuard | AsyncActionGuard] = guards or []
self._transition_model: TransitionModel | None = transition_model
self._rng: random.Random = rng if rng is not None else random.Random()
# See ``GoapExecutor``: jitter must not consume the sampling stream.
self._backoff_rng = random.Random()
# Source-of-truth action map for rebinding fields the serializer
# cannot round-trip (callable execute, qos, Pydantic
# require_human_approval class refs, human_input_key strings).
# See :class:`GoapExecutor._rebind` for the full rationale —
# same pattern, applied per-action inside each parallel wave.
if actions:
ensure_unique_action_names(actions)
self._actions: dict[str, ActionSpec] = (
{a.name: a for a in actions} if actions else {}
)
# Cache the dependency graph by the plan's action-name signature
# so it is computed once per plan rather than once per wave. A
# name tuple is used (not ``id(plan_actions)``) because Python
# may reuse object addresses after garbage collection, which
# would let a stale cache leak across distinct plans.
self._dep_cache: tuple[tuple[str, ...], dict[int, list[int]]] | None = None
def _rebind(self, action: ActionSpec) -> ActionSpec:
"""Restore the live ``ActionSpec`` for ``action.name`` if known."""
return self._actions.get(action.name, action)
def _get_deps(self, plan_actions: tuple[ActionSpec, ...]) -> dict[int, list[int]]:
"""Return the dependency graph, caching by action-name signature."""
key = tuple(a.name for a in plan_actions)
if self._dep_cache is not None and self._dep_cache[0] == key:
return self._dep_cache[1]
from langgoap.planner.csp import build_dependency_graph
deps = build_dependency_graph(plan_actions)
self._dep_cache = (key, deps)
return deps
# ------------------------------------------------------------------
# Sync path
# ------------------------------------------------------------------
def __call__(self, state: GoapState) -> dict[str, Any]:
return serialize_updates(
self._call_typed(rehydrate_state(state, self._actions))
)
def _compact(self, result: dict[str, Any], state: GoapState) -> dict[str, Any]:
"""Apply ``history_state`` to the history entries of an update."""
if self._history_state == "full":
return result
keys = (
_planning_keys_for(state, state.get("plan"), self._actions.values())
if self._history_state == "planning"
else None
)
return _compact_history(result, self._history_state, keys)
def _call_typed(self, state: GoapState) -> dict[str, Any]:
return self._compact(self._run_wave_sync(state), state)
def _run_wave_sync(self, state: GoapState) -> dict[str, Any]:
prep = _prepare_execution(state)
if isinstance(prep, dict):
return prep
world_state, plan_obj, current_step, first_action = prep
try:
result = self._act_wave_sync(state, world_state, plan_obj, current_step)
except StillWaiting as still:
# A wait runs alone in its wave. Nothing it watches has changed:
# no step, no record; the observer routes back and it pauses again.
return _still_waiting(still)
return _settle_wait(first_action, result)
def _act_wave_sync(
self,
state: GoapState,
world_state: dict[str, Any],
plan_obj: Plan,
current_step: int,
) -> dict[str, Any]:
deps = self._get_deps(plan_obj.actions)
group = _find_parallel_group(plan_obj.actions, current_step, deps)
merged_world: dict[str, Any] = dict(world_state)
all_results: list[ActionResult] = []
for idx in group:
action = self._rebind(plan_obj.actions[idx])
logger.debug(
"ParallelExecutor: running action %r (wave idx %d/%d)",
action.name,
group.index(idx) + 1,
len(group),
)
self._tracer.on_action_start(action, merged_world)
state_before = dict(merged_world)
if self._guards:
guard_results = run_guards_sync(self._guards, action, merged_world)
if has_blocking_failure(guard_results):
result = _build_guard_block(
action,
guard_results,
state_before,
merged_world,
failure_counts=state.get("action_failure_counts", {}),
)
self._tracer.on_action_complete(result)
return _abort_wave(
result, world_state=state_before, completed=all_results
)
denial = _check_human_approval(
action,
merged_world,
state_before,
failure_counts=state.get("action_failure_counts", {}),
)
if denial is not None:
self._tracer.on_action_complete(denial)
return _abort_wave(
denial, world_state=state_before, completed=all_results
)
# The state the action runs in includes the operator's answer (#75).
state_before = dict(merged_world)
try:
raw = (
None # a prepared wait, back at its step after a resume
if _is_prepared(state, action)
else _execute_with_retries_sync(
action,
merged_world,
tracer=self._tracer,
rng=self._backoff_rng,
)
)
returned_dict = self._observation.settle_sync(
raw,
action,
merged_world,
transition_model=self._transition_model,
rng=self._rng,
)
action_result = _build_success(
action, idx, state_before, merged_world, check_effects=returned_dict
)
except (
GraphBubbleUp
): # interrupt() inside an action: let LangGraph pause the graph
raise
except StillWaiting:
raise # handled by _run_wave_sync
except Exception as exc:
action_result = _build_failure(action, exc, state_before, merged_world)
self._tracer.on_action_complete(action_result)
return _abort_wave(
action_result, world_state=state_before, completed=all_results
)
self._tracer.on_action_complete(action_result)
if action_result.get("status") == "action_failed":
# Effect validation rejected the action; ``_build_success``
# already rolled its world state back to ``state_before``.
return _abort_wave(
action_result, world_state=state_before, completed=all_results
)
all_results.extend(action_result["execution_history"])
return {
"world_state": merged_world,
"current_step": max(group) + 1,
"execution_history": all_results,
}
# ------------------------------------------------------------------
# Async path
# ------------------------------------------------------------------
async def acall(self, state: GoapState) -> dict[str, Any]:
return serialize_updates(
await self._acall_typed(rehydrate_state(state, self._actions))
)
async def _acall_typed(self, state: GoapState) -> dict[str, Any]:
return self._compact(await self._run_wave_async(state), state)
async def _run_wave_async(self, state: GoapState) -> dict[str, Any]:
"""Async variant \u2014 executes the wave actions concurrently via asyncio.gather."""
prep = _prepare_execution(state)
if isinstance(prep, dict):
return prep
world_state, plan_obj, current_step, first_action = prep
try:
result = await self._act_wave_async(
state, world_state, plan_obj, current_step
)
except StillWaiting as still:
return _still_waiting(still) # see _run_wave_sync
return _settle_wait(first_action, result)
async def _act_wave_async(
self,
state: GoapState,
world_state: dict[str, Any],
plan_obj: Plan,
current_step: int,
) -> dict[str, Any]:
deps = self._get_deps(plan_obj.actions)
group = _find_parallel_group(plan_obj.actions, current_step, deps)
async def _run_one(idx: int) -> dict[str, Any]:
action = self._rebind(plan_obj.actions[idx])
# Each parallel action gets a snapshot of the world-state as it
# was at the start of this wave (independent actions don't see
# each other's in-progress effects).
ws_snapshot = dict(world_state)
await self._tracer.aon_action_start(action, ws_snapshot)
state_before = dict(ws_snapshot)
if self._guards:
guard_results = await run_guards_async(
self._guards, action, ws_snapshot
)
if has_blocking_failure(guard_results):
result = _build_guard_block(
action,
guard_results,
state_before,
ws_snapshot,
failure_counts=state.get("action_failure_counts", {}),
)
await self._tracer.aon_action_complete(result)
return result
denial = _check_human_approval(
action,
ws_snapshot,
state_before,
failure_counts=state.get("action_failure_counts", {}),
)
if denial is not None:
await self._tracer.aon_action_complete(denial)
return denial
state_before = dict(ws_snapshot) # includes the operator's answer (#75)
try:
raw = (
None
if _is_prepared(state, action)
else await _execute_with_retries_async(
action,
ws_snapshot,
tracer=self._tracer,
rng=self._backoff_rng,
)
)
returned_dict = await self._observation.settle_async(
raw,
action,
ws_snapshot,
transition_model=self._transition_model,
rng=self._rng,
)
result = _build_success(
action, idx, state_before, ws_snapshot, check_effects=returned_dict
)
except (
GraphBubbleUp
): # interrupt() inside an action: let LangGraph pause the graph
raise
except StillWaiting:
raise # handled by _run_wave_async
except Exception as exc:
result = _build_failure(action, exc, state_before, ws_snapshot)
await self._tracer.aon_action_complete(result)
return result
raw_results: list[Any] = list(
await asyncio.gather(
*(_run_one(idx) for idx in group), return_exceptions=False
)
)
# Merge each *successful* member's delta (not its full snapshot:
# a sibling's stale copy of a key must never overwrite another
# sibling's change) and collect their history records.
merged_world = dict(world_state)
completed: list[ActionResult] = []
failure: dict[str, Any] | None = None
for r in raw_results:
if r.get("status") == "action_failed":
if failure is None:
failure = r # first failure in wave order wins
if "world_state" in r:
# A failure's world_state is its pre-execution snapshot,
# which carries a typed-form answer the HITL gate merged;
# keep it so the operator is not asked again (#75).
merged_world.update(_delta(world_state, r["world_state"]))
continue
if "world_state" in r:
merged_world.update(_delta(world_state, r["world_state"]))
if "execution_history" in r:
completed.extend(r["execution_history"])
if failure is not None:
# Abort the wave but keep what the other members did, so the
# planner does not run them again (issue #16).
return _abort_wave(failure, world_state=merged_world, completed=completed)
return {
"world_state": merged_world,
"current_step": max(group) + 1,
"execution_history": completed,
}
__all__ = ["ParallelGoapExecutor", "_find_parallel_group"]