Practical technical guides / Architecture / evergreen

Reject Incomplete Agent Plan Graphs Before Any Tool Runs

Compile a proposed graph against a closed operation registry; reject dangling dependencies and disconnected cycles before any effect.

By Sandeep Belgavi · Published 2026-11-25 · Prepared 2026-11-17

Admit the complete proposed graph: Declared task registry, then Resolve every dependency, then Reject before dispatch
Original explanatory diagram by Sandeep Belgavi. Conceptual sequence; no measured performance is represented.

Compile a proposed graph against a closed operation registry; reject dangling dependencies and disconnected cycles before any effect.

A runnable node does not prove a runnable plan

An agent proposes three operations: read a synthetic fixture, calculate a checksum, and compare the result with an expected value. A conventional workflow usually gets this graph from reviewed application code. An agent introduces a different boundary: the graph itself is now input. A scheduler that starts whatever looks ready can perform work before discovering that another component contains an impossible dependency. The architectural change is to admit the whole proposal before releasing its first operation.

This guide treats admission as compilation into a restricted workflow. The planner supplies task identifiers, operation names and predecessor identifiers. Deterministic code checks those fields against the operations actually implemented by the host. Only an admitted graph becomes an execution object. Natural-language confidence, a plausible ordering and an acyclic fragment do not satisfy this contract. A rejected proposal produces diagnostics and zero dispatched tasks, including tasks that would otherwise have been individually executable.

The example uses no model and makes no performance claim. It teaches one question: can every declared dependency be resolved inside this exact proposed work set? A dependency sorter answers a related mathematical question, but it does not know whether an identifier names a real handler. The host must provide that missing application meaning before it asks the sorter to establish an order.

Define a closed registry before sorting

The synthetic registry contains read_fixture, checksum and compare. A task named digest can use the checksum operation; its identifier need not equal the operation name. That separation makes plans readable while preventing the planner from inventing executable functions. The registry is owned by application code. Its keys are capabilities the application deliberately exposes, not import paths or arbitrary shell fragments supplied in the plan.

The plan is a list so duplicate identifiers remain observable. Converting it immediately into a dictionary would overwrite one duplicate and destroy evidence of an invalid proposal. Validate uniqueness first. Then require every predecessor to appear among the declared identifiers. A misspelled predecessor such as read-fixtur must be an error rather than an implicit source node. Reject unknown operations even when their nodes sit behind dependencies that have not become ready.

Python 3.13's graphlib accepts a mapping from nodes to predecessors. Its documented behavior automatically includes predecessor nodes that were not explicitly added. That convenience is appropriate for general graph algorithms. It is unsuitable as proof that every task has an application implementation. The documentation also permits retrieving some ready nodes after a cycle error; this guide deliberately chooses a stricter admission policy for plans with effects.

Compile a proposal without dispatching it

The following original function keeps graph validation separate from execution. It uses standard-library graphlib and returns an immutable order. Its input is intentionally small; a network-facing decoder should additionally enforce byte, nesting and field-length limits before constructing these objects. The returned order is useful for the example's sequential executor. A concurrent executor can retain the admitted graph and release independent nodes in groups.

# Author: Sandeep Belgavi. Original synthetic plan admission example.
from graphlib import TopologicalSorter, CycleError

OPERATIONS = frozenset({"read_fixture", "checksum", "compare"})

def compile_plan(tasks):
    if not isinstance(tasks, list) or not 1 <= len(tasks) <= 32:
        raise ValueError("plan must contain 1..32 tasks")
    registry = {}
    for task in tasks:
        if not isinstance(task, dict) or set(task) != {"id", "op", "after"}:
            raise ValueError("invalid task fields")
        name = task["id"]
        if not isinstance(name, str) or not name or name in registry:
            raise ValueError("missing or duplicate task identifier")
        if not isinstance(task["op"], str) or task["op"] not in OPERATIONS:
            raise ValueError("operation is not registered")
        deps = task["after"]
        if not isinstance(deps, list) or any(not isinstance(d, str) for d in deps):
            raise ValueError("predecessors must be strings")
        registry[name] = tuple(deps)
    missing = {d for deps in registry.values() for d in deps} - registry.keys()
    if missing:
        raise ValueError("undeclared predecessors: " + ", ".join(sorted(missing)))
    try:
        return tuple(TopologicalSorter(registry).static_order())
    except CycleError as exc:
        raise ValueError("cyclic proposal") from exc

For a valid chain, read precedes digest, which precedes verify. Now change the last task's dependency to missing. The compiler rejects the entire proposal. It does not run read and then discover the error. Add a second component in which x depends on y and y depends on x: the otherwise valid chain still stays undispatched. This is the difference between global admission and opportunistic progress.

Preserve the admitted object through execution

Validation is useful only if execution consumes what was validated. Copy the normalized proposal into an immutable representation and give it a revision identity. Do not validate a mutable list and later reread that list after another component has changed its operation names. Store the admitted revision with task outcomes so a restart cannot silently substitute a new graph under old completion records.

Operation argument validation remains a separate gate. A graph can be structurally valid while a checksum task asks for an unsupported algorithm. Validate the operation-specific argument shape during admission where possible, and enforce authorization again at the adapter that performs the effect. Graph correctness does not establish permission, resource availability or successful execution. It establishes only that the proposed structure belongs to the host's supported execution language.

Output dependencies need explicit contracts too. If compare requires a hexadecimal digest, record that requirement rather than treating any completed predecessor as sufficient. A worker failure is not a successful value. The scheduler should propagate failure or invoke an approved recovery policy without satisfying the dependent node's success precondition. These rules belong to execution state, downstream of the initial structural gate.

Migrate an autonomous loop incrementally

Start by recording the loop's proposed operations without executing them. Translate a few existing deterministic paths into the restricted plan format and compare their outputs with the current implementation. The first migration milestone is a traceable proposal and a reproducible admission decision. It is not a more ambitious planner. Keep the operation registry small enough that a reviewer can understand every possible effect.

Next move dispatch behind an admission receipt containing the plan revision, registry version and validation result. A rejected graph may be returned to the planner with a bounded diagnostic, but repairing it creates a new proposal. Do not append missing operations automatically or break a cycle by deleting an arbitrary edge. Those changes alter the requested computation and need an explicit planning decision followed by another complete validation pass.

For dynamic discovery, use separate admitted stages. A discovery task can return candidate work for a later stage, whose graph is then validated. This introduces a deliberate barrier and may reduce parallelism, but it avoids mutating the meaning of an already admitted stage. If the workflow must support online graph extension, define a different protocol with versioned edges and admission ownership; the simple compiler here does not provide that protocol.

Test refusals as well as successful orders

A meaningful expected-outcome test puts a dispatch spy behind compilation and supplies an unknown predecessor. Assert that compilation fails and the spy receives no calls. Repeat with a disconnected cycle and with a duplicate identifier whose later occurrence would otherwise overwrite an earlier one. These tests distinguish the safety property from a test that merely checks one topological order on a well-formed graph.

For successful graphs, assert precedence relationships rather than one arbitrary order among independent nodes. Multiple orders can be valid. Also test a self-cycle, an empty plan, the node-count boundary and an unsupported operation on a disconnected node. The interactive lab exposes these fixtures and compares strict admission with a deliberately unsafe ready-node shortcut. Its trace shows what was rejected before any simulated effect.

Know when a planner adds no value

If every input always requires the same three operations, an ordinary function or declared workflow is simpler. Adding a planner would create a new input-validation surface without adding useful flexibility. A planner becomes useful when it chooses among legitimate operation combinations that depend on ambiguous input; the host still owns the executable vocabulary, dependency rules, effect permissions and recovery behavior.

Whole-graph admission also has limits. It can reject a plan whose independent read-only component would have been useful, and large graphs make diagnostics harder to interpret. Those are policy tradeoffs, not reasons to silently weaken the gate. If partial execution is desirable, expose it as a separate mode with explicitly read-only operations and a partial-result contract. Keep the effectful mode's promise simple: an invalid proposal dispatches nothing.

Interactive experiment

Agent plan graph: reject missing tasks and cycles before execution. Change the synthetic plan, compare strict admission with a ready-node shortcut, and inspect every decision.

Run the example yourself

The synthetic fixtures, expected output and tests behind this guide are in the companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.

Primary references and authorship

Sources read 17 November 2026. Original explanation and synthetic examples by Sandeep Belgavi. Views are my own and do not represent any employer, past or present.