tests/test_composition.py
Tests for planning, multi-agent, durability and rollout. 527 lines, standard-library Python.
Taught in
"""Tests for the composition patterns in lessons 17, 18, 19 and 22.
These four lessons are deliberately different from the rest of the course. They
ship no new classes — `planning.md` says so outright ("the library ships no
`Planner` class"), `multi-agent.md` says there is no `Supervisor` "and there is
not going to be one", and `durable-execution.md` says there is no `Checkpoint`.
Each one is a pattern assembled from parts that already exist: `Agent`,
`Registry.scoped`, `Budget`, `Stop`, `FakeModel`, `Suite`.
That is the right call. A `Planner` class would hide the thing the lesson is
teaching, which is that a planner is two `Agent.run` calls and a judge you
write. But it left the four exercises with nothing to run. Each one states a
precise success criterion and then points at `tests/test_loop.py` or
`tests/test_memory_evals_guard.py`, neither of which contains a single
assertion about planning, delegation, checkpointing or regression gating — so
the suggested command passed whether or not the reader had done the exercise.
This module is that missing verification. Every test below asserts the exercise
success criterion from its lesson verbatim, so a reader who has worked the
exercise can check their answer, and a reader who has not can read the test to
see what "done" means. Where a lesson makes a point about an assertion that
would quietly lie, the weak version is tested too, and named.
"""
import json
import unittest
from agentic import (
Agent,
Budget,
FakeModel,
Message,
Registry,
Stop,
ToolCall,
echo_json,
tool,
tool_call,
)
from agentic.evals import Case, Suite, answered, contains, max_steps, used_tools
# -- lesson 17 fixtures: planner-executor -------------------------------
@tool(description="Look up an order by its id.", order_id="The order id.")
def get_order(order_id: str) -> str:
return json.dumps({"id": order_id, "courier": "BlueDart", "status": "shipped"})
@tool(description="Fetch a courier tracking summary.", courier="The courier name.")
def track(courier: str) -> str:
return f"{courier}: out for delivery, ETA today"
PLAN = {
"steps": [
{"goal": "Find the courier carrying order 4471", "tools": ["get_order"]},
{"goal": "Fetch the tracking summary for that courier", "tools": ["track"]},
]
}
def plan_tools() -> Registry:
return Registry([get_order, track])
def execute(tools: Registry, step: dict, carried: str | None):
"""One executing agent per step: a scoped registry and its own ceiling."""
def reply(msgs):
if not any(m.role == "tool" for m in msgs):
name = step["tools"][0]
args = {"order_id": "4471"} if name == "get_order" else {"courier": carried}
return tool_call(name, args)
return msgs[-1].content
executor = Agent(
FakeModel([reply, reply]),
tools.scoped(set(step["tools"])),
system=f"Do exactly one step: {step['goal']}",
budget=Budget(max_steps=3),
)
return executor.run(step["goal"])
def judge(run) -> Stop:
"""The planner-level progress judge. This is where NO_PROGRESS is emitted.
Reads two signals, not one. `run.ok` is `stop is Stop.ANSWERED`;
`run.trajectory()` is what actually executed. A run can be a clean
ANSWERED and have achieved nothing.
"""
if run.ok and run.trajectory():
return Stop.ANSWERED
return Stop.NO_PROGRESS
class TestPlannerExecutor(unittest.TestCase):
"""Lesson 17. Criterion: trajectories == [[get_order], [track]], every
verdict ANSWERED, and summed executor steps at most 6."""
def test_two_step_plan_executes_in_order_within_budget(self) -> None:
tools = plan_tools()
planner = Agent(
FakeModel([echo_json(PLAN)]),
system="Return a JSON plan. You have no tools.",
budget=Budget(max_steps=2),
)
plan_run = planner.run("Where is order 4471?")
self.assertIs(plan_run.stop, Stop.ANSWERED)
self.assertEqual(planner.registry.schemas(), [])
plan = json.loads(plan_run.output)
carried, trajectories, verdicts, steps_used = None, [], [], 0
for step in plan["steps"]:
run = execute(tools, step, carried)
trajectories.append(run.trajectory())
verdicts.append(judge(run))
steps_used += run.step_count
carried = (
json.loads(run.output)["courier"]
if "courier" in run.output
else run.output
)
self.assertEqual(trajectories, [["get_order"], ["track"]])
self.assertTrue(all(v is Stop.ANSWERED for v in verdicts))
self.assertLessEqual(steps_used, 6)
self.assertEqual(carried, "BlueDart: out for delivery, ETA today")
def test_scoping_is_what_makes_the_trajectory_equality_hold(self) -> None:
"""Step one could not have called `track` even if the model asked."""
tools = plan_tools()
scoped = tools.scoped({"get_order"})
self.assertEqual(
[s["function"]["name"] for s in scoped.schemas()], ["get_order"]
)
def test_an_answered_run_with_an_empty_trajectory_is_no_progress(self) -> None:
"""The failure the lesson's "what broke" section records.
A judge reading `run.ok` alone marks this step done and carries
"I could not do that." forward as the dependency for step two.
"""
tools = plan_tools()
stalled = Agent(
FakeModel(["I could not do that."]),
tools.scoped({"track"}),
budget=Budget(max_steps=2),
).run("Fetch tracking")
self.assertIs(stalled.stop, Stop.ANSWERED)
self.assertTrue(stalled.ok)
self.assertEqual(stalled.trajectory(), [])
self.assertIs(judge(stalled), Stop.NO_PROGRESS)
def test_replanning_is_bounded_by_a_counter_you_write(self) -> None:
"""`Budget` is per `Agent.run`, so the outer plan-fail-replan cycle is
invisible to it. Only an explicit cap stops it."""
max_replans, replans, attempts = 1, 0, 0
while True:
attempts += 1
stalled = Agent(
FakeModel(["I could not do that."]), budget=Budget(max_steps=2)
).run("Do the thing")
if judge(stalled) is Stop.NO_PROGRESS:
if replans >= max_replans:
break
replans += 1
continue
break
self.assertEqual(replans, 1)
self.assertEqual(attempts, 2)
# -- lesson 18 fixtures: supervisor and specialists ---------------------
@tool(description="Search the internal knowledge base.", q="A short search phrase.")
def search_kb(q: str) -> str:
return "Refunds are allowed within 30 days of delivery."
@tool(
description="Append a note to a support ticket.",
ticket="The ticket id.",
body="The note text.",
mutating=True,
)
def write_note(ticket: str, body: str) -> str:
return f"note added to {ticket}"
def researcher_reply(msgs):
"""Scripted to over-reach: it finds the policy, then tries to write."""
seen = sum(1 for m in msgs if m.role == "tool")
if seen == 0:
return tool_call("search_kb", {"q": "refund window"})
if seen == 1:
return tool_call("write_note", {"ticket": "T-1", "body": "auto-resolved"})
return "Refunds are allowed within 30 days of delivery."
class TestSupervisorSpecialists(unittest.TestCase):
"""Lesson 18. Criterion: `write_note` is in the researcher's
requested_tools() and blocked_tools() but absent from its trajectory();
and present in the writer's trajectory()."""
def setUp(self) -> None:
self.shared = Registry([search_kb, write_note])
self.research_only = self.shared.scoped({"search_kb"})
self.write_only = self.shared.scoped({"write_note"})
def _researcher(self):
return Agent(
FakeModel([researcher_reply] * 3),
self.research_only,
system="You research policy. You cannot change anything.",
budget=Budget(max_steps=4),
).run("What is the refund window?")
def test_the_researchers_mutation_attempt_is_contained(self) -> None:
r = self._researcher()
self.assertIn("write_note", r.requested_tools())
self.assertIn("write_note", r.blocked_tools())
self.assertNotIn("write_note", r.trajectory())
self.assertEqual(r.trajectory(), ["search_kb"])
def test_the_writer_holds_the_capability_the_researcher_lacks(self) -> None:
r = self._researcher()
def writer_reply(msgs):
if not any(m.role == "tool" for m in msgs):
return tool_call("write_note", {"ticket": "T-1", "body": r.output})
return "Noted on T-1."
w = Agent(
FakeModel([writer_reply, writer_reply]),
self.write_only,
system="You write findings onto the ticket. You cannot search.",
budget=Budget(max_steps=3),
).run(f"Record on T-1: {r.output}")
self.assertEqual(w.trajectory(), ["write_note"])
self.assertNotIn("search_kb", w.requested_tools())
def test_absence_from_the_trajectory_alone_proves_nothing(self) -> None:
"""The assertion the lesson's "what broke" section calls out.
`write_note not in trajectory()` passes on a model that never tried,
which is a different situation from a contained attempt. Only pairing
it with requested_tools() distinguishes the two.
"""
polite = Agent(
FakeModel(["I will not change anything."]),
self.research_only,
budget=Budget(max_steps=2),
).run("What is the refund window?")
self.assertNotIn("write_note", polite.trajectory())
self.assertNotIn("write_note", polite.requested_tools())
self.assertEqual(polite.blocked_tools(), [])
def test_the_supervisor_routes_without_tools(self) -> None:
supervisor = Agent(
FakeModel([echo_json({"route": ["researcher", "writer"]})]),
system="Route the task. Reply with JSON only. You have no tools.",
budget=Budget(max_steps=2),
)
routed = supervisor.run("Answer the refund question and log it.")
self.assertEqual(
json.loads(routed.output), {"route": ["researcher", "writer"]}
)
self.assertEqual(supervisor.registry.schemas(), [])
def test_the_architecture_costs_six_model_calls_for_three_calls_of_work(
self,
) -> None:
"""The arithmetic the lesson says to read before adopting the pattern."""
r = self._researcher()
def writer_reply(msgs):
if not any(m.role == "tool" for m in msgs):
return tool_call("write_note", {"ticket": "T-1", "body": r.output})
return "Noted on T-1."
w = Agent(
FakeModel([writer_reply, writer_reply]),
self.write_only,
budget=Budget(max_steps=3),
).run(f"Record on T-1: {r.output}")
self.assertEqual(1 + r.step_count + w.step_count, 6)
# -- lesson 19 fixtures: checkpoint and resume --------------------------
LEDGER: dict[str, str] = {}
EFFECTS: list[str] = []
@tool(
description="Charge an invoice. Idempotent on the key.",
invoice="The invoice id.",
key="A caller-supplied idempotency key.",
mutating=True,
)
def charge(invoice: str, key: str) -> str:
if key in LEDGER:
return f"already charged {invoice}, ref {LEDGER[key]}"
LEDGER[key] = f"ref-{len(LEDGER) + 1}"
EFFECTS.append(key)
return f"charged {invoice}, ref {LEDGER[key]}"
def rehydrate(rows: list[dict]) -> list[Message]:
"""`Message.to_dict` ships; `from_dict` does not. This is the half you write,
and it has to restore tool_calls and tool_call_id or the transcript is
malformed in a way that reads fine and behaves wrong."""
return [
Message(
role=row["role"],
content=row.get("content", ""),
tool_calls=tuple(
ToolCall(id=c["id"], name=c["name"], arguments=c["arguments"])
for c in row.get("tool_calls", ())
),
tool_call_id=row.get("tool_call_id"),
)
for row in rows
]
def billing_reply(msgs):
if not any(m.role == "tool" for m in msgs):
return tool_call("charge", {"invoice": "inv-9", "key": "inv-9:attempt-1"})
return "Invoice inv-9 is settled."
class TestCheckpointResume(unittest.TestCase):
"""Lesson 19. Criterion: len(EFFECTS) == 1 and len(LEDGER) == 1 after all
three runs, while retry.trajectory() == ["charge"] proves the tool did
execute on the resume."""
def setUp(self) -> None:
LEDGER.clear()
EFFECTS.clear()
self.billing = Registry([charge])
def _crash(self):
"""A one-step budget: the charge lands, the answer never arrives."""
return Agent(
FakeModel([billing_reply]),
self.billing,
system="Settle invoices.",
budget=Budget(max_steps=1),
).run("Settle invoice inv-9")
def test_the_side_effect_happens_exactly_once_across_three_runs(self) -> None:
first = self._crash()
self.assertIs(first.stop, Stop.STEP_BUDGET)
self.assertEqual(EFFECTS, ["inv-9:attempt-1"])
checkpoint = {
"task": "Settle invoice inv-9",
"messages": [m.to_dict() for m in first.messages],
"step_index": first.step_count,
"cost": first.cost,
}
saved = json.loads(json.dumps(checkpoint))
history = [m for m in rehydrate(saved["messages"]) if m.role != "system"]
# The round trip is where a checkpoint usually breaks.
self.assertEqual(history[1].tool_calls[0].name, "charge")
self.assertIsNotNone(history[2].tool_call_id)
warm = Agent(
FakeModel(["Invoice inv-9 is settled."]),
self.billing,
system="Settle invoices.",
budget=Budget(max_steps=4),
).run("Continue. Do not repeat completed work.", history=history)
self.assertIs(warm.stop, Stop.ANSWERED)
self.assertEqual(len(EFFECTS), 1)
# The hostile case: a resumed model that re-issues the charge.
same_call = tool_call(
"charge", {"invoice": "inv-9", "key": "inv-9:attempt-1"}
)
retry = Agent(
FakeModel([same_call, "Already settled."]),
self.billing,
budget=Budget(max_steps=3),
).run("Settle invoice inv-9", history=history)
self.assertEqual(retry.trajectory(), ["charge"])
self.assertEqual(len(EFFECTS), 1)
self.assertEqual(len(LEDGER), 1)
def test_the_gap_between_ran_and_had_an_effect_is_what_idempotency_buys(
self,
) -> None:
self._crash()
self.assertEqual(len(EFFECTS), 1)
again = Agent(
FakeModel([billing_reply]),
self.billing,
budget=Budget(max_steps=1),
).run("Settle invoice inv-9")
# The repeat guard is per-run, so run two does not see run one's call.
self.assertEqual(again.trajectory(), ["charge"])
self.assertEqual(len(EFFECTS), 1)
def test_a_checkpoint_resumed_with_its_system_message_duplicates_it(
self,
) -> None:
"""`Agent.run` prepends its own system message, so history must be
passed without one."""
first = self._crash()
rows = [m.to_dict() for m in first.messages]
kept = rehydrate(rows)
resumed = Agent(
FakeModel(["Invoice inv-9 is settled."]),
self.billing,
system="Settle invoices.",
budget=Budget(max_steps=4),
).run("Continue.", history=kept)
self.assertEqual(
sum(1 for m in resumed.messages if m.role == "system"),
2,
"passing history with its system message in place duplicates it",
)
# -- lesson 22 fixtures: the regression gate ----------------------------
PRICES = dict(price_per_1k_input=0.5, price_per_1k_output=1.5) # assumed unit prices
@tool(description="Fetch the refund policy section.", topic="A policy topic.")
def fetch_policy(topic: str) -> str:
return "Refunds: within 30 days."
SUITE = Suite(
name="support-agent",
version=1,
cases=[
Case(
id="refund-in-window",
task="Can I refund order 4471?",
tags=("policy",),
why="the core question the agent exists to answer",
checks=[answered(), used_tools("fetch_policy"), contains("30"), max_steps(4)],
),
],
)
def reply_good(msgs):
if not any(m.role == "tool" for m in msgs):
return tool_call("fetch_policy", {"topic": "refunds"})
return "Yes - order 4471 is inside the 30 day refund window."
def reply_regressed(msgs):
# A description edit made the model keep searching instead of answering.
return tool_call("fetch_policy", {"topic": f"refunds {len(msgs)}"})
def factory(reply):
def build():
return Agent(
FakeModel([reply] * 12),
Registry([fetch_policy]),
system="You are a support agent.",
budget=Budget(max_steps=4, **PRICES),
)
return build
class TestRegressionGate(unittest.TestCase):
"""Lesson 22. Criterion: an identical release produces [], and the
regressed release is named and stopped with Stop.STEP_BUDGET.
The lesson asks the reader to save this as tests/test_exercise_gate.py.
It is kept here too so the shipped suite covers the pattern.
"""
def test_gate_is_green_on_an_identical_release(self) -> None:
baseline = SUITE.run(factory(reply_good))
self.assertEqual(baseline.pass_rate, 1.0)
self.assertEqual(
SUITE.run(factory(reply_good)).regressed_against(baseline), []
)
def test_gate_catches_a_deliberate_regression(self) -> None:
baseline = SUITE.run(factory(reply_good))
candidate = SUITE.run(factory(reply_regressed))
self.assertEqual(candidate.regressed_against(baseline), ["refund-in-window"])
self.assertIs(candidate.results[0].run.stop, Stop.STEP_BUDGET)
def test_the_stop_reason_is_what_tells_you_which_investigation_to_open(
self,
) -> None:
"""Two candidates with identical pass-rate drops need completely
different investigations: a quality problem versus a control-flow one."""
candidate = SUITE.run(factory(reply_regressed))
self.assertEqual(candidate.pass_rate, 0.0)
self.assertIsNot(candidate.results[0].run.stop, Stop.ANSWERED)
def test_a_fresh_agent_per_case_is_why_build_agent_is_a_callable(self) -> None:
"""A shared agent between cases is how an eval suite starts lying about
which case caused what."""
build = factory(reply_good)
self.assertIsNot(build(), build())
if __name__ == "__main__":
unittest.main()