Back to all articlesAI & Agents

Task Decomposition: Building a Planner That Replans (Part 6)

A plan you can execute

Task graphvalidated DAG, not prose
Ready schedulingdeps done -> task runs
Bounded parallelism504 ms -> 130 ms at 4 workers
Bounded replanappend remediation, max 2

Plan, execute, replan

The graph refuses anything unrunnable before a single model call runs.

Plan, execute, replan — flow diagramPlan, execute, replan. Flow diagram with 6 steps. Shapes: pill = input, rounded rect = process, diamond = decision, double border = output, dashed = loop. Steps in order: Step 1, goal + tool names (input), one plan call; Step 2, parse + validate (decision), ids, deps, cycles, limit 8; Step 3, run ready tasks (process), fresh AgentLoop per task; Step 4, task failed? (decision), dependants skipped, branches run; Step 5, repair plan (process), patch merged with r1_ prefix; Step 6, synthesis (output), one call over done results. Then loops back to step 2: ↺ replan until max_replans or no failures.goal + tool namesone plan callparse + validateids, deps, cycles, limit 8run ready tasksfresh AgentLoop per tasktask failed?dependants skipped, branches runrepair planpatch merged with r1_ prefixsynthesisone call over done results
  • input
  • process
  • decision
  • output

Ask the Part 5 agent to compare two findings and it does the right thing by luck: one search, then another, then an answer. Each step appends about 420 tokens of search results to one shared history, and by step six the context is mostly transcript. Part 3’s budget starts compressing exactly the evidence the agent paid to retrieve, and the model re-reads its own history to remember what it already learned.

The structural fix is a plan: separate tasks, each with its own small context, each executed as an independent loop, joined by explicit dependencies. This is also the precondition for the two capabilities the series needs next — parallel execution, and verification of a step before it contaminates the answer.

The failure mode of planning is equally structural. A model that emits a plan is emitting a claim about work: it will invent task ids it never defines, build a cycle, hand you nine tasks when you asked for five, or produce JSON with a trailing comma. Every one of those becomes a crash or a hang if the executor trusts it. So this part is really two components: a graph that refuses to represent anything unrunnable, and a planner that gets one repair attempt before it is overruled.

What you’ll build

A planner.py module with four pieces:

  • Task + TaskGraph — an immutable task, and a DAG that validates ids, dependencies and cycles at build time, exposes ready() for scheduling, and merge() for adding remediation tasks.
  • Planner — turns a goal into a graph via one model call, with a schema validator and exactly one repair round.
  • PlanExecutor — runs ready tasks sequentially or with bounded parallelism, passes each task the results of its dependencies only, and marks dependants skipped on failure.
  • PlannedAgent — plan, execute, replan (bounded), synthesise. The same LLMClient interface from Parts 1–5, so AgentLoop runs inside a task.

The current state of research-agent: loop, contracts, budget, memory, retriever. The planner composes the retriever — a task is just a goal with max_steps=4, and the loop inside it calls the same search tool with the same citations.

Prerequisites

  • Parts 1–5. planner.py imports AgentLoop, LLMClient, Message, Tool from contracts.py.
  • Python 3.10+, standard library only (concurrent.futures, re, json).
  • The Part 5 rag.py and corpus.py if you want tasks to do real retrieval; the demo and tests use scripted models and do not need them.

One honest scope note: parallel execution here means threads. Python’s GIL makes this correct for I/O-bound tasks (search calls, HTTP), which is what tasks are. If a task runs CPU-bound work, use a process pool and accept that task results must be picklable. The code below does not pretend otherwise.

Where the flat loop runs out of road

The flat loop has three costs that grow with question complexity.

Context cost grows quadratically with steps. Every step’s model call re-sends the full history. Six searches at 420 tokens of results each is 2,520 tokens of history re-sent up to six times — about 15,000 tokens billed for 2,520 useful ones. The compression strategy from Part 3 reduces the re-sent size but costs fidelity on exactly the evidence that matters.

Nothing is verified before it is used. A bad search result enters the history once and influences every later decision. There is no place to say: this step’s output must pass a check before the next step consumes it.

Two independent questions cannot run at the same time. The loop is strictly sequential because there is exactly one history. If two searches share no dependency, half the wall time is waste — and the demo at the end of the execution section measures that waste at 504 ms versus 130 ms on a four-task workload.

A plan fixes all three by giving each task its own AgentLoop and its own context, and by making the dependencies — not the transcript — the only channel between tasks.

The task graph: dependencies you can execute

The data model is deliberately dull: an immutable task, a status record, and a graph that is validated once, at build time.

from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Callable
import json
import re
from contracts import AgentLoop, LLMClient, Message, Tool
TASK_ID = re.compile(r"^[a-z][a-z0-9_]{0,30}$")
MAX_TASKS = 8
class PlanError(Exception):
"""A plan the executor cannot run: duplicate ids, unknown deps, cycles, oversize."""
@dataclass(frozen=True)
class Task:
id: str
goal: str
depends_on: tuple[str, ...] = ()
tool_hint: str | None = None
@dataclass
class TaskState:
task: Task
status: str = "pending" # pending | done | failed | skipped
attempts: int = 0
result: str = ""
error: str = ""
@dataclass
class TaskGraph:
tasks: dict[str, Task]
order: list[str]
@classmethod
def build(cls, tasks: list[Task], limit: int | None = MAX_TASKS) -> "TaskGraph":
if not tasks:
raise PlanError("plan is empty")
if limit is not None and len(tasks) > limit:
raise PlanError("plan has %d tasks, limit is %d" % (len(tasks), limit))
by_id: dict[str, Task] = {}
for task in tasks:
if not TASK_ID.match(task.id):
raise PlanError("bad task id: %r" % task.id)
if task.id in by_id:
raise PlanError("duplicate task id: " + task.id)
by_id[task.id] = task
for task in by_id.values():
for dep in task.depends_on:
if dep == task.id:
raise PlanError("task %s depends on itself" % task.id)
if dep not in by_id:
raise PlanError("task %s depends on unknown %s" % (task.id, dep))
return cls(by_id, cls._toposort(by_id))
@staticmethod
def _toposort(by_id: dict[str, Task]) -> list[str]:
state: dict[str, int] = {}
order: list[str] = []
def visit(task_id: str, path: list[str]) -> None:
mark = state.get(task_id, 0)
if mark == 2:
return
if mark == 1:
raise PlanError("cycle: " + " -> ".join(path + [task_id]))
state[task_id] = 1
for dep in by_id[task_id].depends_on:
visit(dep, path + [task_id])
state[task_id] = 2
order.append(task_id)
for task_id in by_id:
visit(task_id, [])
return order
def ready(self, states: dict[str, TaskState]) -> list[Task]:
return [
self.tasks[tid] for tid in self.order
if states[tid].status == "pending"
and all(states[dep].status == "done" for dep in self.tasks[tid].depends_on)
]
def context_for(self, task: Task, states: dict[str, TaskState], max_chars: int = 1200) -> str:
chunks = []
for dep in task.depends_on:
state = states[dep]
chunks.append("RESULT[%s]: %s" % (dep, state.result[:400]))
return "\n".join(chunks)[:max_chars]
def merge(self, extra: list[Task], prefix: str) -> "TaskGraph":
"""Add tasks under a prefix, remapping their internal dependencies."""
remapped: dict[str, Task] = {}
for task in extra:
new_id = prefix + task.id
deps = tuple(prefix + d if d not in self.tasks else d for d in task.depends_on)
remapped[new_id] = Task(new_id, task.goal, deps, task.tool_hint)
combined = list(self.tasks.values()) + list(remapped.values())
return TaskGraph.build(combined, limit=None)

Five guards, each answering a specific crash that happens in practice:

The id regex. [a-z][a-z0-9_]{0,30} rejects "Fetch" (capitalised), "3rd-step" (leading digit) and a 400-character id that would blow up a log line. More importantly it makes ids safe to embed in a RESULT[...] marker and to prefix for replans without ambiguity.

Duplicate rejection, not last-write-wins. A plan with two tasks named search is a model error, not a dict-update opportunity. Silently keeping the second hides the error and produces a graph the model did not describe.

Cycle detection with a path, not a boolean. The error message names the cycle — cycle: a -> b -> a — because that string goes straight back to the model in the repair round. A bare ValueError: cycle detected wastes the one repair attempt.

limit=8 at build time, not at prompt time. Telling the model “at most 8 tasks” in the system prompt reduces violations; it does not prevent them. The executor must also refuse, or a verbose plan becomes 24 model calls before anyone notices.

ready() iterates topological order. With 8 tasks the difference between scanning by order and scanning by id is invisible; with 200 tasks, order-based scheduling lets you stop at the first not-ready task in a future optimisation. Order also makes execution deterministic, which is what makes the trace reproducible in Part 9.

context_for is the dependency channel, and its cap of 400 characters per dependency is a budget decision: two dependencies cost at most 800 characters of context, so a fan-in task cannot quietly accumulate the whole plan’s output. If a dependency’s result is longer than 400 characters, the task should have been split, not the context — a rule Part 7’s verifier will lean on.

Getting a plan out of a model, and rejecting most of it

The planner’s job is one model call plus a strict parse. The system prompt carries the schema; the parse carries the enforcement.

PLAN_SYSTEM = (
"You are a planner. Decompose the goal into at most %d tasks. "
"Reply with JSON: {\"type\": \"plan\", \"tasks\": [{\"id\": \"snake_case\", "
"\"goal\": \"one imperative sentence\", \"depends_on\": [], \"tool\": \"search\"}]}. "
"Only reference tools that exist. Ids are lowercase snake_case."
) % MAX_TASKS
class Planner:
"""Turns a goal into a validated DAG. One repair attempt, then it gives up."""
def __init__(self, llm: LLMClient, max_tasks: int = MAX_TASKS, repairs: int = 1) -> None:
self.llm = llm
self.max_tasks = max_tasks
self.repairs = repairs
def plan(self, goal: str, tool_names: list[str]) -> TaskGraph:
messages = [
Message("system", PLAN_SYSTEM),
Message("user", "Goal: %s\nTools: %s" % (goal, ", ".join(tool_names))),
]
decision = self.llm.complete(messages, [])
for attempt in range(self.repairs + 1):
try:
return TaskGraph.build(self.parse(decision))
except PlanError as exc:
if attempt == self.repairs:
raise
messages.append(Message("user",
"Your plan was rejected: %s. Return corrected JSON only." % exc))
decision = self.llm.complete(messages, [])
raise PlanError("unreachable")
def repair_plan(self, goal: str, graph: TaskGraph, states: dict[str, TaskState],
failed_id: str, error: str) -> list[Task]:
done = [tid for tid, s in states.items() if s.status == "done"]
prompt = (
"Goal: %s\nCompleted tasks: %s\nTask %s failed with: %s\n"
"Return {\"type\": \"plan\", \"tasks\": [...]} with only the new tasks needed to "
"recover. You may depend on any completed id."
) % (goal, ", ".join(done) or "none", failed_id, error[:300])
decision = self.llm.complete([Message("system", PLAN_SYSTEM), Message("user", prompt)], [])
try:
return self.parse(decision)
except PlanError:
return []
@staticmethod
def parse(decision: dict) -> list[Task]:
if decision.get("type") != "plan":
raise PlanError("expected a plan decision, got %r" % decision.get("type"))
raw = decision.get("tasks")
if not isinstance(raw, list):
raise PlanError("tasks must be a list")
tasks: list[Task] = []
for item in raw:
if not isinstance(item, dict):
raise PlanError("task must be an object")
deps = item.get("depends_on", [])
if not isinstance(deps, list) or not all(isinstance(d, str) for d in deps):
raise PlanError("depends_on must be a list of ids")
goal = item.get("goal")
if not isinstance(goal, str) or len(goal.strip()) < 8:
raise PlanError("task goal is too short")
tool = item.get("tool")
tasks.append(Task(str(item.get("id", "")), goal.strip(), tuple(deps),
tool if isinstance(tool, str) else None))
return tasks

repairs=1 is the whole policy, and it is worth defending. The first rejection is usually a format slip — a trailing comma, a missing id — and the error message makes it a trivial fix. A second rejection means the model does not understand the schema, and another round produces a third wrong plan while burning latency. One repair, then PlanError propagates to the caller, which fails the run visibly instead of executing a plan nobody validated. In the trace, a run that needed its repair round is a run to watch.

The goal length floor of 8 characters looks like a typo check and is actually a decomposition check. Real decompositions produce imperatives like Find the reranker latency cost. Degenerate plans produce "search" or "step1" — and those degenerate goals are what the model will send to the worker loop, producing equally degenerate work. Rejecting them at the parse is cheaper than discovering them in the trace.

repair_plan returns an empty list rather than raising. A replan is an optional recovery: if the model cannot express one, the run ends with the failure recorded, which is a truthful outcome. Raising here would turn a recoverable run into a crash, and crashing a five-task run because the recovery prompt failed is the wrong severity.

Executing ready tasks, and what a failure should block

The executor is a scheduling loop over ready(). Its semantics are the design:

@dataclass
class PlanExecutor:
"""Runs ready tasks; a failure blocks dependants but not independent branches."""
graph: TaskGraph
run_task: Callable[[Task, str], str]
max_workers: int = 1
def run(self) -> dict[str, TaskState]:
states = {tid: TaskState(self.graph.tasks[tid]) for tid in self.graph.order}
while True:
ready = self.graph.ready(states)
if not ready:
break
if self.max_workers > 1 and len(ready) > 1:
with ThreadPoolExecutor(max_workers=self.max_workers) as pool:
futures = [
pool.submit(self._run_one, task, states) for task in ready
]
for future in futures:
future.result()
else:
for task in ready:
self._run_one(task, states)
for state in states.values():
if state.status == "pending":
state.status = "skipped"
return states
def _run_one(self, task: Task, states: dict[str, TaskState]) -> None:
state = states[task.id]
context = self.graph.context_for(task, states)
state.attempts += 1
try:
state.result = self.run_task(task, context)
state.status = "done"
except Exception as exc:
state.status = "failed"
state.error = "%s: %s" % (type(exc).__name__, exc)

The failure policy is: a failed task marks itself failed; its dependants never become ready and end as skipped; independent branches run to completion. That is the only policy that respects what the DAG actually promises. A blanket stop-on-first-failure wastes work the plan already proved independent; a run-everything policy feeds None into dependants and produces garbage answers attributed to real evidence.

A note on thread safety, because it is the kind of thing that fails only on Fridays. Two workers share states and mutate different keys; CPython’s GIL makes each dict write atomic, and no worker reads a key another worker writes (a ready task’s dependencies are all done, so no concurrent writer touches them). The futures are collected after all submit, so a worker exception is re-raised in the main thread — but _run_one already converts exceptions into status, so future.result() raising is a bug in the executor itself, which is what you want.

Now the agent that ties plan, execution and synthesis together:

@dataclass
class PlanRun:
goal: str
answer: str
graph: TaskGraph
states: dict[str, TaskState]
replans: int = 0
@property
def failed(self) -> list[str]:
return [tid for tid, s in self.states.items() if s.status in ("failed", "skipped")]
class PlannedAgent:
"""Plan, execute, replan on failure, synthesise. Three model calls minimum, nine maximum."""
def __init__(self, llm: LLMClient, tools: list[Tool], planner: Planner | None = None,
max_steps_per_task: int = 4, max_replans: int = 2,
max_workers: int = 1) -> None:
self.llm = llm
self.tools = tools
self.planner = planner or Planner(llm)
self.max_steps_per_task = max_steps_per_task
self.max_replans = max_replans
self.max_workers = max_workers
def _run_task(self, task: Task, context: str) -> str:
goal = task.goal if not context else task.goal + "\n\n" + context
loop = AgentLoop(self.llm, self.tools, max_steps=self.max_steps_per_task)
answer = loop.run(goal)
if answer.startswith("aborted:"):
raise RuntimeError(answer)
return answer
def run(self, goal: str) -> PlanRun:
graph = self.planner.plan(goal, [tool.name for tool in self.tools])
states = PlanExecutor(graph, self._run_task, self.max_workers).run()
replans = 0
while replans < self.max_replans:
failed = [tid for tid, s in states.items() if s.status == "failed"]
if not failed:
break
first = graph.tasks[failed[0]]
patch = self.planner.repair_plan(goal, graph, states, first.id, states[first.id].error)
if not patch:
break
replans += 1
graph = graph.merge(patch, "r%d_" % replans)
states = self._resume(graph, states)
answer = self.synthesise(goal, states)
return PlanRun(goal, answer, graph, states, replans)
def _resume(self, graph: TaskGraph, done: dict[str, TaskState]) -> dict[str, TaskState]:
carried = {tid: TaskState(graph.tasks[tid]) for tid in graph.order}
for tid, state in done.items():
carried[tid] = state
executor = PlanExecutor(graph, self._run_task, self.max_workers)
states = carried
while True:
ready = graph.ready(states)
if not ready:
break
for task in ready:
executor._run_one(task, states)
for state in states.values():
if state.status == "pending":
state.status = "skipped"
return states
def synthesise(self, goal: str, states: dict[str, TaskState]) -> str:
lines = []
for tid, state in states.items():
if state.status == "done":
lines.append("- %s: %s" % (tid, state.result[:300]))
body = "\n".join(lines) or "- no task produced a result"
decision = self.llm.complete(
[Message("system", "Answer the goal using only these task results. Keep citations."),
Message("user", "Goal: %s\nResults:\n%s" % (goal, body))],
[],
)
return str(decision.get("content", ""))

Four decisions in that class, each with a reason.

A fresh AgentLoop per task. The same rule as Part 4’s MemoryAgent: a task’s working memory is exactly that task. Reusing one loop across tasks would leak one task’s search results into another’s context — and the whole point of the graph is that the dependency edges, not an accident of scheduling, decide what is shared.

max_steps=4 per task, not the run’s budget. Eight tasks at eight steps each is 64 model calls; the planner is supposed to bound fan-out, and it does: 1 plan + 8 × 4 + 2 replans + 1 synthesis = 36 calls worst case, versus a minimum of 3. The per-task budget is what makes that bound real.

aborted: becomes an exception. The loop signals a step-limit or malformed-decision failure with that string; inside a task, treating it as a successful result would let a downstream task build on an answer the model never actually produced. Converting it to a failure routes the run into replanning.

Synthesis sees only done results, each capped at 300 characters. That is at most 2,400 characters for eight tasks — one bounded call, with citations intact so Part 7 can check the final answer against the evidence the tasks actually retrieved.

Replanning without starting over

The demo runs the four-task plan from the previous section end to end:

import time
import planner as pl
from contracts import ScriptedLLM, build_tools
GOAL = "Compare chunking trade-offs with reranker latency, then write a short brief."
PLAN = {"type": "plan", "tasks": [
{"id": "search_chunking", "goal": "Find the chunk size and overlap trade-offs.", "depends_on": []},
{"id": "search_latency", "goal": "Find the reranker latency cost per query.", "depends_on": []},
{"id": "compare", "goal": "Compare the two findings on cost and quality.",
"depends_on": ["search_chunking", "search_latency"]},
{"id": "write_brief", "goal": "Write a three-sentence brief with citations.",
"depends_on": ["compare"]},
]}
WORKER = [
{"type": "final", "content": "Chunks of 420 chars with 90 overlap [chunking#0]."},
{"type": "final", "content": "Reranking 20 candidates costs ~200 ms per query [latency-budget#0]."},
{"type": "final", "content": "Chunking is a one-off cost; reranking is per query."},
{"type": "final", "content": "Brief: pay once for chunking, meter reranking."},
]
def demo_plan() -> None:
planner_llm = ScriptedLLM([PLAN])
worker_llm = ScriptedLLM(WORKER + [{"type": "final", "content": "Final brief: pay once, meter per query."}])
agent = pl.PlannedAgent(worker_llm, build_tools(), pl.Planner(planner_llm), max_steps_per_task=2)
run = agent.run(GOAL)
print("order:", " -> ".join(run.graph.order))
for tid, state in run.states.items():
print(" %-16s %-7s %s" % (tid, state.status, state.result[:60]))
print("replans:", run.replans)
print("answer:", run.answer)
print("model calls:", len(planner_llm.calls) + len(worker_llm.calls))
def demo_parallel() -> None:
graph = pl.TaskGraph.build([pl.Task("t%d" % i, "independent lookup %d" % i) for i in range(4)])
def slow(task, ctx):
time.sleep(0.12)
return task.id
for workers in (1, 2, 4):
started = time.perf_counter()
pl.PlanExecutor(graph, slow, max_workers=workers).run()
elapsed = (time.perf_counter() - started) * 1000
print("workers=%d wall=%.0f ms" % (workers, elapsed))
if __name__ == "__main__":
demo_plan()
print()
demo_parallel()
order: search_chunking -> search_latency -> compare -> write_brief
search_chunking done Chunks of 420 chars with 90 overlap [chunking#0].
search_latency done Reranking 20 candidates costs ~200 ms per query [latency-bud
compare done Chunking is a one-off cost; reranking is per query.
write_brief done Brief: pay once for chunking, meter reranking.
replans: 0
answer: Final brief: pay once, meter per query.
model calls: 6

Six model calls for four tasks: one plan, four task runs (one call each, because the scripted workers answer immediately), one synthesis. The two searches are independent, so with max_workers=2 they run concurrently.

The parallel measurement is the reason to bother with a graph at all — four independent 120 ms tasks:

workers=1 wall=504 ms
workers=2 wall=260 ms
workers=4 wall=130 ms

Near-perfect scaling to four workers, because the tasks share nothing. That is what max_workers is buying, and it is also why the dependency edges must be honest: if the model marks two tasks independent when the second actually needs the first’s result, parallel execution converts a logic error into a nondeterministic wrong answer. The tool hint and the task goals are the only information the model has for that judgement, which is why task goals must be self-contained imperatives and why depends_on errors matter more than any other plan defect.

Replanning is the path for the run that is not clean. When numbers fails with RuntimeError: tool exploded, the agent does not restart the plan: repair_plan receives the completed ids and the error, the patch comes back as a retry task depending on search, merge prefixes it to r1_retry so it cannot collide with anything, and _resume re-runs only what is pending. Completed work is never recomputed — which is also the property Part 8’s checkpointing will make durable across process restarts, not just within one run.

Failure modes and how to handle them

Failure What actually happens Handling here Still broken
Model invents a dependency id Build raises unknown Rejected at build; one repair round Repair may produce a different wrong plan
Plan contains a cycle Toposort raises with the path Error string feeds the repair prompt Two-cycle plans burn the repair budget
20-task plan for a 3-task goal 20 × 4 = 80 model calls MAX_TASKS=8 enforced at build No per-task cost estimate yet
Two “independent” tasks race on one tool Concurrent duplicate searches Idempotency store from Part 2 dedupes Non-idempotent side effects still race
Task hangs Worker thread never returns AgentLoop has max_steps; tool has timeout_s A stuck HTTP client can still pin a worker
Replan loops forever Same patch, same failure max_replans=2, then run ends truthfully No memory of previous patch content
Synthesis ignores task results Answer contradicts evidence Prompt restricts to results; citations kept No verification — that is Part 7

The racing row deserves a second look, because it is where planning and the earlier parts meet. Two parallel tasks calling search with the same query hit the same idempotency key; the second gets the cached result with from_cache=True and costs nothing. That composition was free: the store already existed, and the graph just made concurrent calls possible. This is the pattern to keep — new capabilities should create new consumers of old guarantees, not new guarantees.

Trade-offs

Decision Alternative Why we chose it Cost
Plan as a DAG, not a list Numbered steps in prose Dependencies are executable; a list hides ordering Model must emit valid JSON
One repair round Repair until valid Second failure means the schema is not understood A run dies on two bad plans
Fail: block dependants only Stop whole run / run everything Respects what the graph proved independent Partial answers need labelling
Fresh loop per task One shared loop No cross-task context leakage Tool specs rebuilt per task
Threads, not processes Process pool Tasks are I/O-bound; no pickling GIL-bound if a task computes
Append-and-resume replan Rebuild the full plan Completed work is never recomputed Patch ids need a prefix namespace
Synthesis as a separate call Last task answers One bounded call over capped results One extra model call per run

The last row is the one to watch in cost reviews. Synthesis adds a call, but it also removes the largest prompt in the system: instead of re-sending a 2,500-token transcript, it sends at most 2,400 characters of distilled results. On the Part 3 arithmetic, that is cheaper for any plan with more than three tasks.

Testing it

Fourteen tests, no network, 2 ms. The invariants:

import unittest
import planner as pl
from contracts import ScriptedLLM, build_tools
def task(id_, deps=(), goal="do something useful here"):
return pl.Task(id_, goal, tuple(deps))
def plan_decision(*tasks):
return {"type": "plan", "tasks": [
{"id": t.id, "goal": t.goal, "depends_on": list(t.depends_on)} for t in tasks
]}
class TestGraph(unittest.TestCase):
def test_cycle_is_rejected_before_execution(self):
with self.assertRaises(pl.PlanError):
pl.TaskGraph.build([task("a", ("b",)), task("b", ("a",))])
def test_unknown_dependency_is_rejected(self):
with self.assertRaises(pl.PlanError):
pl.TaskGraph.build([task("a", ("ghost",))])
def test_topological_order_respects_dependencies(self):
graph = pl.TaskGraph.build([
task("write", ("compare",)),
task("compare", ("search_a", "search_b")),
task("search_a"),
task("search_b"),
])
self.assertLess(graph.order.index("search_a"), graph.order.index("compare"))
self.assertEqual(graph.order[-1], "write")
def test_merge_prefixes_new_ids_and_remaps_internal_deps(self):
graph = pl.TaskGraph.build([task("a")])
merged = graph.merge([task("probe"), task("retry", ("probe", "a"))], "r1_")
self.assertEqual(merged.tasks["r1_retry"].depends_on, ("r1_probe", "a"))
class TestPlanner(unittest.TestCase):
def test_repairs_a_rejected_plan_once(self):
bad = {"type": "plan", "tasks": [{"id": "a", "goal": "short", "depends_on": ["ghost"]}]}
llm = ScriptedLLM([bad, plan_decision(task("a"), task("b", ("a",)))])
graph = pl.Planner(llm).plan("compare two things", ["search"])
self.assertEqual(graph.order, ["a", "b"])
self.assertIn("rejected", llm.calls[1][-1].content)
def test_gives_up_after_the_repair_budget(self):
bad = {"type": "plan", "tasks": []}
llm = ScriptedLLM([bad, bad])
with self.assertRaises(pl.PlanError):
pl.Planner(llm, repairs=1).plan("goal", ["search"])
class TestExecutor(unittest.TestCase):
def test_failed_task_blocks_dependants_but_not_independent_branches(self):
graph = pl.TaskGraph.build([task("a"), task("b", ("a",)), task("c")])
seen = []
def run(t, ctx):
seen.append(t.id)
if t.id == "a":
raise RuntimeError("boom")
return "ok " + t.id
states = pl.PlanExecutor(graph, run).run()
self.assertEqual(states["a"].status, "failed")
self.assertEqual(states["b"].status, "skipped")
self.assertEqual(states["c"].status, "done")
self.assertEqual(seen, ["a", "c"])
def test_parallel_and_sequential_agree(self):
graph = pl.TaskGraph.build([task("a"), task("b"), task("c", ("a", "b"))])
seq = pl.PlanExecutor(graph, lambda t, ctx: "out " + t.id, max_workers=1).run()
par = pl.PlanExecutor(graph, lambda t, ctx: "out " + t.id, max_workers=2).run()
self.assertEqual({k: v.result for k, v in seq.items()},
{k: v.result for k, v in par.items()})
class FlakyAgent(pl.PlannedAgent):
def __init__(self, *args, failing=("numbers",), **kwargs):
super().__init__(*args, **kwargs)
self.failing = set(failing)
self.calls: list[str] = []
def _run_task(self, t, ctx):
self.calls.append(t.id)
if t.id in self.failing:
raise RuntimeError("tool exploded")
return "result of " + t.id
class TestReplan(unittest.TestCase):
def test_replan_adds_a_remediation_task_and_finishes(self):
plan = plan_decision(task("search"), task("numbers", ("search",)), task("write", ("numbers",)))
patch = {"type": "plan", "tasks": [
{"id": "retry", "goal": "retry the numbers step with a cheaper expression",
"depends_on": ["search"]},
]}
llm = ScriptedLLM([plan, patch, {"type": "final", "content": "final brief"}])
agent = FlakyAgent(llm, build_tools(), max_replans=1)
run = agent.run("compare two numbers")
self.assertEqual(run.replans, 1)
self.assertEqual(run.states["r1_retry"].status, "done")
self.assertEqual(run.answer, "final brief")
self.assertIn("r1_retry", agent.calls)
def test_no_patch_ends_the_run_without_looping(self):
plan = plan_decision(task("numbers"))
llm = ScriptedLLM([plan, {"type": "plan", "tasks": []}, {"type": "final", "content": "done"}])
agent = FlakyAgent(llm, build_tools(), max_replans=3)
run = agent.run("do it")
self.assertEqual(run.replans, 0)
self.assertEqual(run.failed, ["numbers"])
if __name__ == "__main__":
unittest.main()

test_failed_task_blocks_dependants_but_not_independent_branches is the contract the whole design rests on: a fails, b is skipped without being run (seen proves it), and c still completes. Get the scheduling wrong and this test fails in one of two instructive ways — b runs and produces garbage, or c never runs and the failure blocks more than the graph allows.

test_replan_adds_a_remediation_task_and_finishes encodes the prefix discipline: the patched graph contains r1_retry, its dependency on search survived the remap, and the run terminates with a synthesis rather than looping. If someone raises max_replans above 2 without adding patch-content memory, test_no_patch_ends_the_run_without_looping is the test that will start failing first.

Exercises

  1. Cost accounting. Instrument PlannedAgent to count model calls and estimate tokens (chars ÷ 4) per plan. Run five goals of increasing fan-out and plot calls versus tasks. Where does the 1 + 4n + 2 + 1 formula break down?
  2. Critical path. Add a critical_path(graph, estimates) method that computes the longest dependency chain from task duration estimates, and make PlanExecutor schedule critical-path tasks first. Measure the wall-time change on the four-task demo with 120 ms tasks of unequal length.
  3. Patch memory. repair_plan currently has no memory of previous patches. Add the last patch and its outcome to the prompt, and write a test where two consecutive identical patches must trigger a stop. Does max_replans=2 still make sense?

Exercise 2 is the one worth doing before Part 12. Scheduling order is free latency, and the critical path is also the number you quote when someone asks why the run takes two seconds.

What’s next

The plan is executed, but nothing checks it. A task can return a result that contradicts its own citations, the synthesis can restate a number the evidence does not contain, and every downstream consumer — including the user — inherits the error.

Part 7, Reflection and verification, adds a Critic with a rubric, programmatic checks that run before the model judges anything (does the citation exist, does the quoted number appear in the evidence), and a reflection loop whose three stop conditions — round limit, minimum improvement, oscillation detection — are the difference between self-correction and an expensive way to rewrite a correct answer.

Connect your agents without writing code

Everything above, running in Ball — no code, no install. Try it in your browser.

Try Ball free
Get the free AI agent kit

Only used to send Ball resources. No spam.

Try Ball in your browser — no install, no signup needed.

Try Ball in your browser — no install, no signup needed.

Reading in English? Switch language in the menu.