mechaharness.graph_executor

Injectable graph walk, budgets, failure policy, and opt-in EffectfulGraphNodeRunner orchestration.

Injectable execution-graph runner (schedule, authorize, retry, escalate).

Hosts define node behavior as GraphNodeRunner injectables and bind a GraphNodeRunnerRegistry via Config. The executor walks ExecutionGraph ready nodes, enforces grants, emits lifecycle events, checkpoints through CheckpointStore, and applies a GraphFailurePolicy / GraphEscalation on failure.

Effectful runners opt into EffectfulGraphNodeRunner so external side effects get durable intent/acceptance and resume reconciliation (DR-03..11). A host coding-job adapter + SQLite store looks like:

>>> import asyncio, tempfile
>>> from pathlib import Path
>>> from pyiv.time import PythonDateTimeService
>>> from mechaharness.budget import BudgetPolicy
>>> from mechaharness.checkpoint_store import CheckpointStore
>>> from mechaharness.core.access import GraphExecute
>>> from mechaharness.di import MechaHarnessConfig, get_injector
>>> from mechaharness.external_effect import (
...     EffectDispatchResult, EffectRecord, EffectReconciliation,
...     EffectReconciliationAction, EffectState,
... )
>>> from mechaharness.graph import ExecutionGraph, GraphNode
>>> from mechaharness.graph_executor import (
...     EffectfulGraphNodeRunner, GraphExecutor, GraphNodeRunnerRegistry,
...     GraphRunContext,
... )
>>> from mechaharness.harness.pass_through import PassThroughHarness
>>> from mechaharness.inference.mock import MockInferenceStrategy
>>> from mechaharness.sqlite_checkpoint_store import SqliteCheckpointStore
>>> class CodingJob(EffectfulGraphNodeRunner):
...     def __init__(self):
...         self.dispatches = 0
...     def kinds(self):
...         return ["coding_job"]
...     def backend_id(self):
...         return "host.coding_job"
...     async def reconcile(self, node, *, effect, context):
...         if effect.state is EffectState.INTENDED:
...             return EffectReconciliation(
...                 action=EffectReconciliationAction.DISPATCH,
...             )
...         return EffectReconciliation(
...             action=EffectReconciliationAction.COMPLETE,
...             external_handle=effect.external_handle or "job-1",
...             outcome_payload={"diff": "ok"},
...         )
...     async def dispatch(self, node, *, effect, context):
...         self.dispatches += 1
...         return EffectDispatchResult(external_handle="job-1")
...     async def observe(self, node, *, effect, context):
...         return EffectReconciliation(
...             action=EffectReconciliationAction.COMPLETE,
...             external_handle=effect.external_handle or "job-1",
...             outcome_payload={"diff": "ok"},
...         )
>>> path = Path(tempfile.mkdtemp()) / "ckpt.sqlite"
>>> runner = CodingJob()
>>> class Cfg(MechaHarnessConfig):
...     def get_inference_class(self):
...         return MockInferenceStrategy
...     def get_harness_class(self):
...         return PassThroughHarness
...     def get_grants(self):
...         return [GraphExecute]
...     def get_node_runner_registry(self):
...         return GraphNodeRunnerRegistry([runner])
...     def get_checkpoint_store(self):
...         return SqliteCheckpointStore(
...             path, datetime_service=PythonDateTimeService()
...         )
>>> executor = get_injector(Cfg()).inject(GraphExecutor)
>>> graph = ExecutionGraph(goal="ship feature")
>>> _ = graph.add_node(GraphNode(id="job", kind="coding_job"))
>>> result = asyncio.run(executor.run(
...     graph, budget_policy=BudgetPolicy.unlimited(), run_id="demo",
...     skip_linkage=True,
... ))
>>> result.status, runner.dispatches
('ok', 1)
>>> executor.store.durability
'durable'
class mechaharness.graph_executor.CallableGraphNodeRunner(kinds: Sequence[str], handler: Callable[[GraphNode, GraphRunContext], Awaitable[NodeOutcome] | NodeOutcome], *, grants: Sequence[object] | None = None)[source]

Bases: GraphNodeRunner

Adapter: bind a callable (sync or async) to one or more kinds.

__init__(kinds: Sequence[str], handler: Callable[[GraphNode, GraphRunContext], Awaitable[NodeOutcome] | NodeOutcome], *, grants: Sequence[object] | None = None) → None[source]
kinds() → Sequence[str][source]

Node kinds this runner accepts (open string identity).

required_grants() → Sequence[object][source]

Extra grants checked before each node this runner handles.

async run(node: GraphNode, *, context: GraphRunContext) → NodeOutcome[source]

Execute node once; return success or failure outcome.

class mechaharness.graph_executor.DefaultGraphFailurePolicy[source]

Bases: GraphFailurePolicy

Retry while attempts remain; then escalate; callers may still FAIL.

decide(node: GraphNode, *, error: str | None) → GraphFailureAction[source]

Return the next action for node after a failed attempt.

class mechaharness.graph_executor.EffectfulGraphNodeRunner[source]

Bases: GraphNodeRunner

Opt-in runner for non-idempotent external side effects (DR-11).

GraphExecutor() orchestrates durable intent → uncertain → dispatch → accept → reduce. Hosts implement reconcile/dispatch/observe; pure run() is unused for this path.

abstractmethod backend_id() → str[source]

Stable provider identity (generic; not a Cursor type).

abstractmethod async dispatch(node: GraphNode, *, effect: EffectRecord, context: GraphRunContext) → EffectDispatchResult[source]

Perform the non-idempotent external call (only when allowed).

effect_id_for(node: GraphNode, *, run_id: str) → str[source]

Stable effect identity for this node attempt context.

abstractmethod async observe(node: GraphNode, *, effect: EffectRecord, context: GraphRunContext) → EffectReconciliation[source]

Poll/complete an accepted effect into a terminal reconciliation.

abstractmethod async reconcile(node: GraphNode, *, effect: EffectRecord, context: GraphRunContext) → EffectReconciliation[source]

Decide what to do with an intended/uncertain/accepted effect on resume.

async run(node: GraphNode, *, context: GraphRunContext) → NodeOutcome[source]

Execute node once; return success or failure outcome.

class mechaharness.graph_executor.GraphEscalation[source]

Bases: ABC

Host hook when failure policy chooses escalate.

abstractmethod async handle(node: GraphNode, *, context: GraphRunContext) → NodeOutcome[source]

Attempt recovery or mark the node terminal.

class mechaharness.graph_executor.GraphExecutor(event_log: mechaharness.core.events.EventLog, access: mechaharness.core.access.AccessControl, runners: GraphNodeRunnerRegistry, failure_policy: GraphFailurePolicy, escalation: GraphEscalation, linkage_resolver: LinkageResolver, checkpoint_store: CheckpointStore, crash_probe: CrashProbe, lifecycle_extensions: LifecycleExtensionRegistry | None = None, *, agent_id: str | None = None, parent_agent_id: str | None = None)[source]

Bases: object

Authorize and walk an ExecutionGraph.

Constructor dependencies are pyiv-injectable. Hosts subclass Config and override get_node_runner_registry / get_graph_failure_policy / get_graph_escalation / get_linkage_resolver / get_checkpoint_store rather than hand-building the executor.

__init__(event_log: mechaharness.core.events.EventLog, access: mechaharness.core.access.AccessControl, runners: GraphNodeRunnerRegistry, failure_policy: GraphFailurePolicy, escalation: GraphEscalation, linkage_resolver: LinkageResolver, checkpoint_store: CheckpointStore, crash_probe: CrashProbe, lifecycle_extensions: LifecycleExtensionRegistry | None = None, *, agent_id: str | None = None, parent_agent_id: str | None = None) → None[source]
async run(graph: ExecutionGraph, *, budget_policy: BudgetPolicy, budget: Budget | None = None, run_id: str | None = None, resume: bool = False, envelope: CapabilityEnvelope | None = None, skip_linkage: bool = False, parent_run_id: str | None = None, control: RunControl | None = None) → GraphResult[source]

Execute graph until completion, denial, stall, budget failure, or pause.

Every event emitted for the run carries graph_id, graph_goal, recipe stamp, authorization_epoch, and (for nested runs) parent_run_id / nest_depth — see mechaharness.event_correlators.graph_trace_context().

budget_policy is required. Pass a shared budget for nested subgraphs so spend aggregates; otherwise a fresh Budget is created from the policy.

Soft limit: cancel remaining open work and return soft_exhausted. Hard limit: fail open nodes and return failed with prejudice. BudgetPolicy.hard_limit=None means unlimited hard ceiling.

control (SG-01): default to_completion. one_step / until return status=paused without a terminal GraphEnd.

class mechaharness.graph_executor.GraphFailureAction(*values)[source]

Bases: str, Enum

What to do after a node attempt fails verification or raises.

ESCALATE = 'escalate'
FAIL = 'fail'
RETRY = 'retry'
class mechaharness.graph_executor.GraphFailurePolicy[source]

Bases: ABC

Decide retry / escalate / fail after a failed node attempt.

abstractmethod decide(node: GraphNode, *, error: str | None) → GraphFailureAction[source]

Return the next action for node after a failed attempt.

class mechaharness.graph_executor.GraphNodeRunner[source]

Bases: ABC

Host-supplied handler for one or more GraphNode.kind values.

abstractmethod kinds() → Sequence[str][source]

Node kinds this runner accepts (open string identity).

required_grants() → Sequence[object][source]

Extra grants checked before each node this runner handles.

abstractmethod async run(node: GraphNode, *, context: GraphRunContext) → NodeOutcome[source]

Execute node once; return success or failure outcome.

class mechaharness.graph_executor.GraphNodeRunnerRegistry(runners: Sequence[GraphNodeRunner] | None = None)[source]

Bases: object

Map of node kind → runner. Hosts populate via Config hooks.

__init__(runners: Sequence[GraphNodeRunner] | None = None) → None[source]
get(kind: str) → GraphNodeRunner | None[source]
kinds() → list[str][source]
register(runner: GraphNodeRunner) → None[source]
class mechaharness.graph_executor.GraphResult(*, status: ~typing.Literal['ok', 'failed', 'denied', 'stalled', 'soft_exhausted', 'paused'], graph: ~mechaharness.graph.ExecutionGraph, run_id: str, events: list[~mechaharness.core.events.Event] = <factory>, error: str | None = None, budget_spent: float = 0.0, budget_level: str = 'ok', diagnostics: dict[str, ~typing.Any] = <factory>, stopped_before: str | None = None, entered_node_id: str | None = None, active_run_id: str | None = None, frame_path: list[str] = <factory>, **extra_data: ~typing.Any)[source]

Bases: BaseModel

Outcome of GraphExecutor.run().

active_run_id: str | None
budget_level: str
budget_spent: float
diagnostics: dict[str, Any]
entered_node_id: str | None
error: str | None
events: list[Event]
frame_path: list[str]
graph: ExecutionGraph
model_config = {'extra': 'allow'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

run_id: str
status: Literal['ok', 'failed', 'denied', 'stalled', 'soft_exhausted', 'paused']
stopped_before: str | None
class mechaharness.graph_executor.GraphRunContext(graph: ExecutionGraph, run_id: str, agent_id: str, budget: Budget, parent_agent_id: str | None = None, envelope: CapabilityEnvelope | None = None, config_fingerprint: str | None = None, bag: WalkBag = <factory>, pause: _PauseMarkers = <factory>)[source]

Bases: object

Per-run identity passed to node runners and escalation.

bag is a mutable WalkBag held by the frozen context (register ABI for node→node data; see walk_bag).

__init__(graph: ExecutionGraph, run_id: str, agent_id: str, budget: Budget, parent_agent_id: str | None = None, envelope: CapabilityEnvelope | None = None, config_fingerprint: str | None = None, bag: WalkBag = <factory>, pause: _PauseMarkers = <factory>) → None
agent_id: str
bag: WalkBag
budget: Budget
config_fingerprint: str | None = None
envelope: CapabilityEnvelope | None = None
graph: ExecutionGraph
parent_agent_id: str | None = None
pause: _PauseMarkers
run_id: str
class mechaharness.graph_executor.NodeOutcome(*, status: NodeStatus = NodeStatus.SUCCEEDED, payload: dict[str, ~typing.Any]=<factory>, evidence: dict[str, ~typing.Any]=<factory>, error: str | None = None, cost_units: float | None = None, **extra_data: Any)[source]

Bases: BaseModel

Result of one runner attempt against a node.

cost_units: float | None
error: str | None
evidence: dict[str, Any]
model_config = {'extra': 'allow'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

payload: dict[str, Any]
status: NodeStatus
class mechaharness.graph_executor.RejectGraphEscalation[source]

Bases: GraphEscalation

Default: escalation is unavailable; leave the node failed.

async handle(node: GraphNode, *, context: GraphRunContext) → NodeOutcome[source]

Attempt recovery or mark the node terminal.

class mechaharness.graph_executor.RunControl(*, mode: Literal['to_completion', 'one_step', 'until'] = 'to_completion', until: str | None = None, stop: Literal['before', 'after'] = 'before')[source]

Bases: BaseModel

Stepped / until control for GraphExecutor.run() (SG-01..07).

Default to_completion preserves historical behavior. one_step and until return GraphResult.status=paused with a checkpoint so the host can mutate live authority (or answer soft points) before continuing.

mode: Literal['to_completion', 'one_step', 'until']
model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

stop: Literal['before', 'after']
until: str | None
mechaharness.graph_executor.registry_from_mapping(handlers: Mapping[str, Callable[[GraphNode, GraphRunContext], Awaitable[NodeOutcome] | NodeOutcome]], *, grants: Mapping[str, Sequence[object]] | None = None) → GraphNodeRunnerRegistry[source]

Build a registry from kind → callable (convenience for hosts/tests).