11. Testing your harness¶
At the end you can: write pytest tests for a policy, an actor and a whole run that need no network and no API key, and prove that a run ends the same way whichever journal write its process dies at.
A harness here means everything you built around the model for one job: the actor, its tools, your policy, and the Governor wiring that joins them.
What you will learn: how to test a gvn harness quickly and offline, from the smallest piece to the whole run: a policy on its own, an agent with no runtime, a full run with a stub tool, and a crash matrix that kills the run at every journal write and checks that the outcome never changes.
Before this: 10. A conversation. The refund agent of tutorials 5 and 6 is what you test.
Time: about 15 minutes.
Where this sits in the big picture¶
Every box of the quickstart's big picture that touches the outside world (the model, the tools, the journal, the output, the clock) is a port with a fake. That is what makes a gvn harness easy to test: replace the outside boxes with fakes, and what is left (the actors, your policy, your wiring) runs in milliseconds and gives the same answer every time. This page tests from the smallest piece to the whole run: first one policy, then one actor, then a full run, then a run killed at every journal write.
Where you are¶
You have built the pieces of a help desk: a policy, tools, an agent, a workflow. Before any of
it meets a customer, you want tests that run in milliseconds, need no network and give the
same answer every time. gvn is built for that: actors do no I/O, and everything that could
vary (the model, time, storage) is a port with a fake in gvn.testing.fakes. You have used
most of the fakes already.
The tests below are plain functions named test_..., as pytest expects; at the end of each
step the page calls them so you can see them pass.
Start a new file for this page, and begin it with the block below. The block holds
everything from the earlier pages that this page uses, imports included: the code under
test, which is the refund policy and the Governor wiring of tutorial 6. Every step uses
names from it (RefundPolicy, build_governor, new_refund_agent, BROKEN, APPROVED),
so the steps do not run without it. Then add each block of the page below it, in order.
If you want the same idea as one self-contained file first, the recipe Test an agent offline is a single script you can run as it is.
The refund harness from tutorials 5 and 6
import asyncio
import typing
from gvn.harness.agent import VERDICTS, Agent
from gvn.harness.events import Event
from gvn.harness.messages import TOOL, Message, ToolCall
from gvn.harness.ports import Exchange, Journal, Reply
from gvn.harness.tools import Tool, Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor, Result
from gvn.testing.fakes import FunctionModel, ManualClock, RecordingOutput
REFUND_LIMIT = 100.0
class RefundPolicy(Decision):
"""Look-ups are cleared, refunds need a person, large refunds are forbidden."""
def __init__(self, refund_tool: Tool) -> None:
self._refund_tool = refund_tool
def outcomes(self) -> Alphabet:
return VERDICTS
def judge(self, consultation: object) -> Symbol:
refunds = consultation.calls_to(self._refund_tool)
if not refunds:
return VERDICTS.named("cleared")
(call,) = refunds # the one call being judged
amount = call.arguments().get("amount")
if not isinstance(amount, (int, float)) or amount > REFUND_LIMIT:
return VERDICTS.named("forbidden")
return VERDICTS.named("needs_approval")
def refund_model(exchange: Exchange) -> Reply:
"""Asks to refund A-17; once a tool result is in the conversation, reports."""
if any(message.role() == TOOL for message in exchange.messages()):
return Reply(message=Message.assistant(text="I refunded 40.00 on order A-17."))
refund = ToolCall(
call_id="call-1", name="issue_refund", arguments={"order_id": "A-17", "amount": 40.0}
)
return Reply(message=Message.assistant(calls=[refund]))
def build_governor(journal: Journal, refund_tool: Tool) -> Governor:
toolbox = Toolbox([refund_tool])
return Governor(
fulfillers={
"invoke_model": ModelFulfiller(model=FunctionModel(respond=refund_model), toolbox=toolbox),
"invoke_tools": ToolFulfiller(toolbox=toolbox),
"consult_policy": PolicyFulfiller(decision=RefundPolicy(refund_tool=refund_tool)),
},
external=["request_approval"],
journal=journal,
output=RecordingOutput(),
clock=ManualClock(),
)
def new_refund_agent(run_name: str, refund_tool: Tool) -> Agent:
return Agent(name=run_name, instructions="Help customers.", tools=[refund_tool])
BROKEN = Event(name="started", payload={"prompt": "Order A-17 arrived broken. Refund me."})
APPROVED = Event(name="approved")
build_governor and new_refund_agent now take the refund tool as a parameter, so a test
can pass in a stand-in for it. The agent and the policy only need the tool's
identity; the toolbox runs
it.
Step 1: test the policy on its own¶
The smallest test needs no agent and no runtime. A policy is a Decision, so you build a
Consultation and call decide. Test the edges: the limit itself, just above it, and
arguments a model got wrong.
The policy is given the refund tool, and a test needs no real one. StubTool, from
gvn.testing.fakes, is a fake tool built from a short name and an argument schema, so the
model sees the same tool as in production; step 3 runs it. A consultation holds the calls and
the identity of each call's tool:
from gvn.harness.tools import Consultation
from gvn.kernel.schema import Number, Record, Text
from gvn.kernel.symbols import Symbol
from gvn.testing.fakes import StubTool
def refund_stub() -> StubTool:
return StubTool(
name="issue_refund",
arguments=Record({"order_id": Text(), "amount": Number()}),
result={"refund": 1},
)
def verdict_for(arguments: dict[str, typing.Any]) -> Symbol:
stub = refund_stub()
call = ToolCall(call_id="call-1", name="issue_refund", arguments=arguments)
consultation = Consultation(calls=[call], identities=[stub.identity()], origin="refunds")
return RefundPolicy(refund_tool=stub).decide(consultation)
def test_refunds_up_to_the_limit_need_a_person() -> None:
assert verdict_for({"order_id": "A-17", "amount": 100.0}) == Symbol("needs_approval")
def test_refunds_above_the_limit_are_forbidden() -> None:
assert verdict_for({"order_id": "A-17", "amount": 100.01}) == Symbol("forbidden")
def test_an_unreadable_amount_is_forbidden() -> None:
assert verdict_for({"order_id": "A-17", "amount": "lots"}) == Symbol("forbidden")
assert verdict_for({"order_id": "A-17"}) == Symbol("forbidden")
test_refunds_up_to_the_limit_need_a_person()
test_refunds_above_the_limit_are_forbidden()
test_an_unreadable_amount_is_forbidden()
print("policy tests pass") # policy tests pass
Step 2: test an actor with no runtime¶
An actor is synchronous and pure (it does no I/O and depends only on the events it is given), so you can hand it events yourself and look at what it wants, as you did in tutorial 3. No event loop, no Governor. Here the test plays the model and the policy, and checks that the agent asks a person:
from gvn.kernel.symbols import State
def test_the_agent_asks_for_approval_after_a_needs_approval_verdict() -> None:
agent = new_refund_agent("refunds", refund_tool=refund_stub())
agent.handle(BROKEN)
refund = ToolCall(
call_id="call-1", name="issue_refund", arguments={"order_id": "A-17", "amount": 40.0}
)
reply = Message.assistant(calls=[refund])
agent.handle(Event(name="model_replied", payload={"message": reply.to_dto().to_plain()}))
assert agent.pending()[0].kind().name() == "consult_policy"
agent.handle(Event(name="needs_approval"))
assert agent.state() == State("awaiting_approval")
assert agent.pending()[0].kind().name() == "request_approval"
test_the_agent_asks_for_approval_after_a_needs_approval_verdict()
print("actor test passes") # actor test passes
The model_replied event carries the reply as plain JSON (to_dto().to_plain()), exactly
as the Governor would build it.
Step 3: test a whole run with a stub tool¶
The StubTool of step 1 returns a fixed result and records every call it receives:
calls() (the arguments) and keys() (the idempotency keys of tutorial 6). Its namespace is
gvn.testing.fakes unless you pass namespace=; the agent, the policy and the toolbox are
all given the same stub, so they agree on its identity:
from gvn.runtime.governor import WAITING
from gvn.testing.fakes import MemoryJournal
def test_an_approved_refund_runs_once_and_is_reported() -> None:
stub = refund_stub()
governor = build_governor(journal=MemoryJournal(), refund_tool=stub)
agent = new_refund_agent("refunds", refund_tool=stub)
async def scenario() -> Result:
waiting = await governor.deliver(actor=agent, event=BROKEN)
assert waiting.status() == WAITING
assert stub.calls() == () # nothing runs before the person answers
return await governor.answer(actor=agent, request=waiting.pending()[0], event=APPROVED)
result = asyncio.run(scenario())
assert result.outcome().payload()["text"] == "I refunded 40.00 on order A-17."
assert stub.calls() == ({"order_id": "A-17", "amount": 40.0},)
test_an_approved_refund_runs_once_and_is_reported()
print("run test passes") # run test passes
The test checks what the run did (one refund, and none before approval), not only what the model said.
Step 4: a crash matrix¶
Tutorial 6 killed the process at one chosen write. A crash matrix kills it at every
write, one run per position, then recovers from what the journal kept, finishes the run and
checks that the outcome is always the same. CrashingJournal makes the crash, MemoryJournal
plays the file that survives, and FunctionModel makes the recovered run get the same
answers.
First, a helper that finishes a run from wherever it stands, answering approvals as they come up:
from gvn.runtime.recovery import Recovery, UnknownRun
from gvn.testing.fakes import Crash, CrashingJournal
async def finish(governor: Governor, agent: Agent) -> Result:
result = await governor.resume(actor=agent)
while result.status() == WAITING:
result = await governor.answer(actor=agent, request=result.pending()[0], event=APPROVED)
return result
Then one scenario per crash position. A run begins with one write that saves the agent as it
was born together with the started event, so a crash at that first write leaves no trace of
the run: recovery raises UnknownRun, and the scenario starts the run again under the same
name. A crash at any later write leaves a run to recover:
async def crash_at(position: int) -> tuple[Result, StubTool]:
survived = MemoryJournal() # what is on disk when the process dies
stub = refund_stub()
agent = new_refund_agent("refunds", refund_tool=stub)
try:
dying = build_governor(journal=CrashingJournal(journal=survived, at_append=position), refund_tool=stub)
waiting = await dying.deliver(actor=agent, event=BROKEN)
result = await dying.answer(actor=agent, request=waiting.pending()[0], event=APPROVED)
return result, stub # the crash position was past the last write
except Crash:
pass
governor = build_governor(journal=survived, refund_tool=stub)
try:
agent = await Recovery(journal=survived).recover(run_id="refunds", actor_class=Agent)
except UnknownRun: # the crash came before the run's opening record: no trace of it
agent = new_refund_agent("refunds", refund_tool=stub)
await governor.deliver(actor=agent, event=BROKEN)
return await finish(governor, agent), stub
def test_the_outcome_is_the_same_whichever_write_the_process_dies_at() -> None:
for position in range(7):
result, stub = asyncio.run(crash_at(position))
assert result.outcome().payload()["text"] == "I refunded 40.00 on order A-17.", position
assert 1 <= len(stub.calls()) <= 2, position # at least once, never lost
assert len(set(stub.keys())) == 1, position # a repeat always has the same key
test_the_outcome_is_the_same_whichever_write_the_process_dies_at()
print("crash matrix passes") # crash matrix passes
The run journals six events (started, model_replied, needs_approval, approved,
tools_returned, model_replied), so positions 0 to 5 each kill it before a different one,
and position 6 lets it finish untouched. Three things hold at every position: the outcome is the
same, the refund ran at least once and at most twice, and a repeated refund came with the
same key, which is what lets a tool such as tutorial 6's IssueRefundOnce make the repeat
harmless.
Change it and run again¶
Predict the answer first, then run the code and open the block.
1. Lower the limit. Set REFUND_LIMIT to 50.0, as a change to the shop's rules would.
Which of the three policy tests fail? Does the whole-run test still pass?
REFUND_LIMIT = 50.0
for test in (
test_refunds_up_to_the_limit_need_a_person,
test_refunds_above_the_limit_are_forbidden,
test_an_unreadable_amount_is_forbidden,
test_an_approved_refund_runs_once_and_is_reported,
):
try:
test()
print("passes:", test.__name__)
except AssertionError:
print("fails: ", test.__name__)
REFUND_LIMIT = 100.0
What happens
fails: test_refunds_up_to_the_limit_need_a_person
passes: test_refunds_above_the_limit_are_forbidden
passes: test_an_unreadable_amount_is_forbidden
passes: test_an_approved_refund_runs_once_and_is_reported
Only the test at the edge fails: a refund of 100.00 is now forbidden, where the test expects a person to be asked. The run test refunds 40.00, which is still under the limit, so it cannot notice. That is why step 1 tests the limit itself and the value just above it.
2. Count the refunds at each crash position. The matrix allows one or two calls to the tool. At which positions does the refund run twice?
for position in range(7):
result, stub = asyncio.run(crash_at(position))
print(position, len(stub.calls()), len(set(stub.keys())))
What happens
Only position 4, the write of tools_returned: the refund had run, and the process
died before its result reached the journal. The recovered run cannot know the refund
happened, so it asks again, with the same key (the last column is always 1). At every
other position the tool had either not started or its result was already recorded.
Where the tests go¶
Put the functions in a file such as tests/test_refunds.py and run pytest; drop the calls
and prints, which are only here so this page shows them passing. Nothing in them sleeps or
reaches the network, so they run in parallel and in any order.
Testing your harness lists every fake (including HeldModel, which
holds a model call in flight so a test can interrupt it) and the
contract suites (the tests every implementation of
a port must pass) that check an adapter of your own.
Recap¶
- A policy is tested by calling
decideon aConsultation; aStubToolstands in for the tool it is given. - An actor is tested by handing it events and checking its state and
pending(). - A run is tested with
ScriptedModelorFunctionModel,StubTool,MemoryJournal,RecordingOutputandManualClock, checking what the tools received. - A crash matrix kills the run at every journal write and checks the outcome never changes and work in flight runs at least once.
Next: 12. A real model and ready-made tools swaps the scripted model for a vendor's, and the hand-written tools for gvn's ready-made ones.