Testing your harness¶
What you will learn: how to test a harness fast, offline and in parallel: drive an actor with plain function calls, run it through the Governor on fake ports, and control time. The deeper sections show crash matrices, holding a run mid-flight, safety checks on recorded runs, contract suites for your own adapters, and the budget rules gvn's own suite follows.
Read first: every earlier Concepts page, in particular Durable objects, The reference agent, The Governor and Time. Time: about 15 minutes for the first half, 30 for all of it.
Where this sits¶
The test kit, gvn.testing, sits beside the adapters in
the layers of code. An adapter connects a port to a
real system (a vendor's model, a database, the system clock); a fake in the test kit
implements the same port in memory, deterministically. Nothing in production code imports
the test kit, and the fakes are checked against the same contract suites as the real
adapters, so swapping one for the other changes nothing an actor can see.
The shape of it¶
You can test a harness at three levels, each one wider than the last:
flowchart LR
subgraph one ["Level 1: an actor alone"]
direction TB
test1["your test"] -- "handle(event)" --> actor1["actor"]
actor1 -- "requests, as values" --> test1
end
subgraph two ["Level 2: a whole run on fakes"]
direction TB
governor["Governor"] --> fakes["fake model, journal,<br/>clock, output, tools"]
end
subgraph three ["Level 3: recorded runs"]
direction TB
journal[("journal")] --> replay["replay and<br/>evaluation checks"]
end
one --> two --> three
- An actor alone. Actors do no input or output, so a test hands one events and inspects the requests it returns. No Governor, no event loop (step 1).
- A whole run on fakes. The Governor drives the actor as in production, but every port is a fake: a scripted model, an in-memory journal, a clock that moves only when told (steps 2 and 3). The deeper sections use the same setup to crash a run at every journal write and to hold a run in the middle of a model call.
- Recorded runs. A finished run's journal is replayed and graded against explicit checks, such as "no deploy without a person's approval" (deeper sections).
Underneath all three sit two habits: test the durability law for each durable class you write (step 4), and run your own adapters through the contract suites (deeper).
The problem: agent tests are slow and flaky¶
A test that calls a real model is slow, costs money, and gives a different answer each time. A test that waits for a real timeout takes as long as the timeout. A test that leaves state in a module-level registry breaks the next test, but only when they run in a certain order. Most agent code ends up tested by hand for these reasons.
In gvn, fast tests are not a testing feature bolted on. They fall out of three facts:
- Machines and actors do no I/O. You can drive them with plain function calls.
- Every source of nondeterminism (the model, time, storage, ids) is a port, and every port has a deterministic fake: a small in-memory implementation that behaves the same way every time.
- The framework keeps no global state, so tests cannot leak into each other.
The fakes live in gvn.testing.fakes. The test kit is public: it is what gvn's own suite
uses, and it ships with the package.
Step 1: test an actor with no runtime¶
An actor is synchronous and pure, so the most direct test is to hand it events and look at
what it wants. No event loop, no Governor. Start an agent that may make one model turn and
may use a search tool; StubTool, the one fake used here, stands in for the tool (the
agent only keeps its identity):
from gvn.harness.agent import Agent
from gvn.harness.events import Event
from gvn.kernel.schema import Record, Text
from gvn.testing.fakes import StubTool
search = StubTool(name="search", arguments=Record({"query": Text()}), result={"hits": 3})
helper = Agent(name="helper", instructions="Be brief.", tools=[search], turns=1)
reaction = helper.handle(Event("started", payload={"prompt": "Look it up."}))
print(helper.state(), reaction.request().kind())
The agent moved to thinking and asks for a model call. Nothing was called: the request is
just a value you can inspect.
Now play the model's part. Hand the agent a reply that asks for the search tool:
from gvn.harness.messages import Message, ToolCall
call = ToolCall(call_id="call-1", name="search", arguments={"query": "moore"})
reply = Message.assistant(text="", calls=[call])
reaction = helper.handle(Event("model_replied", payload={"message": reply.to_dto().to_plain()}))
assert reaction.request().kind().name() == "consult_policy"
Before running any tool, the agent asks the policy whether the call may run. Play the policy too, and forbid it:
from gvn.kernel.symbols import State
helper.handle(Event("forbidden"))
assert helper.state() == State("failed") # one turn only: the budget stops it
assert helper.outcome().payload() == {
"reason": "the budget of 1 model turns was exhausted",
"attempts": [
{
"name": "search",
"identity": "gvn.testing.fakes.search",
"arguments": {"query": "moore"},
"status": "forbidden",
"detail": "not run: the policy forbade this call",
}
],
"reductions": {
"trimmed": 0,
"summarised": 0,
"fell_back": 0,
"remembered": 0,
"unremembered": 0,
},
"recalls": {"asked": 0, "found": 0, "failed": 0},
"readings": {"taken": 0, "failed": 0, "blocked": 0, "latest": {}},
}
Three function calls tested a full path through the agent: a refused tool call and a turn budget running out. Tests like this run in microseconds.
Step 2: run it on fake ports¶
To test how an actor behaves with the Governor around it (requests fulfilled, results fed
back), give the Governor fakes instead of real ports. Here a ScriptedModel answers from a
list, one entry per call:
import asyncio
from gvn.harness.ports import Exchange, Journal, Reply
from gvn.harness.tools import Toolbox
from gvn.runtime.fulfillers import ModelFulfiller
from gvn.runtime.governor import Governor, Result
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel
model = ScriptedModel(script=[Reply(message=Message.assistant(text="Hello."))])
signals = RecordingOutput()
governor = Governor(
fulfillers={"invoke_model": ModelFulfiller(model=model, toolbox=Toolbox())},
journal=MemoryJournal(),
output=signals,
clock=ManualClock(),
)
greeter = Agent(name="greeter", instructions="Be brief.")
result = asyncio.run(governor.deliver(actor=greeter, event=Event("started", payload={"prompt": "Hi."})))
print(result.status(), result.outcome().payload()["text"])
print(len(model.exchanges()), signals.text())
The run finished with the scripted text. exchanges() shows the model was asked once, and
RecordingOutput kept every signal, so the test can also check what a user would have seen.
These fakes cover the run and its I/O:
| Fake | Stands in for | What it does |
|---|---|---|
ScriptedModel(script) |
Model |
answers from a list, one entry per call |
FunctionModel(respond) |
Model |
answers with respond(exchange), so the same question gets the same reply |
HeldModel(respond) |
Model |
like FunctionModel, but every call waits until released: waiting(), await held(n), release(), release_one() |
ManualClock(start=0.0) |
Clock |
time moves only when you call advance(seconds); sleepers(), earliest() (the earliest time anything sleeps until) and await sleeping(n=1) let a test see who is waiting on it |
MemoryJournal() |
Journal |
keeps records and snapshots in memory |
CrashingJournal(journal, at_append, after=False) |
Journal |
raises Crash before or after a chosen record write, counting begin and append from 0 through this wrapper |
MemoryLeases() |
Leases |
keeps lease holders and fencing tokens in memory |
RecordingOutput() |
Output |
keeps every signal: signals(), kinds(), text() |
ListMemory(embedder=None, *, least_similarity=0.0) |
Memory |
keeps entries in a list; an entry matches a query when they share a word. Given an Embedder, it also recalls by meaning, as SqliteMemory does (Recall by meaning). held(scope) and scopes() show what it holds; fail(reason) makes every call raise MemoryFailure until mend() (Memory) |
HashingEmbedder(dimensions=64, name="hashing") |
Embedder |
turns a text into a vector from its words, deterministically and with no network: texts that share more words get closer vectors. It knows words, not meaning. asked() shows the texts it was given; fail(reason) makes every embed raise EmbedderFailure until mend() |
StubTool(name, arguments, result=None, namespace=None, untrusted=False) |
Tool |
returns a fixed value, raises a given exception, or calls a function; records calls() (the arguments), invocations() (each Invocation) and keys() (the idempotency keys). Its identity is gvn.testing.fakes.<name>, or <namespace>.<name>: give two stubs of one name different namespaces to stand for two tools that share a short name. untrusted=True stands for a tool whose results come from outside the deployment, which an actor records in its exposure |
ScriptedModel script entries can be:
- a
Reply: its text is reported as one fragment, then it is returned; - a
(fragments, Reply)tuple: each fragment is reported, then the reply is returned; - a
ModelFailure: raised; - an
asyncio.Event(or anything with an awaitablewait()): awaited, so a test can hold the model mid-call, then the next entry is used.
It raises ScriptExhausted if it is asked for more replies than it was given, and
exchanges() returns every Exchange it received (what the model was sent: the messages and
the tools on offer), so you can assert on what the model saw.
Step 3: control time¶
ManualClock makes timeouts testable without waiting. Time moves only when the test calls
advance. Here a task sleeps for a minute on the clock; the test moves time 59 seconds, checks
the sleeper is still asleep, then moves the last second:
async def wake_after_a_minute() -> tuple[bool, float]:
clock = ManualClock(start=100.0)
sleeper = asyncio.create_task(clock.sleep(seconds=60))
await asyncio.sleep(0) # let the sleeper start; no real time passes
clock.advance(59)
await asyncio.sleep(0)
early = sleeper.done()
clock.advance(1)
await sleeper
return early, clock.now()
print(asyncio.run(wake_after_a_minute()))
After 59 seconds the sleeper was not done; after 60 it was, and the clock reads 160.0. No real time passed.
Step 4: test the durability law¶
Test the durability law for every durable class you write: round-trip through JSON text, then check that the copy behaves like the original afterwards.
That is the 80% you need. The rest of this page covers harder tests: killing a run at every journal write, acting while a run is in flight, time inside the Governor, safety rules on recorded runs, contract suites for your own adapters, and the rules that keep a suite fast.
Deeper: a crash matrix¶
CrashingJournal lets you kill a run at any journal write. Run the same scenario once per
write, recover from what the journal kept, finish the run, and check that the outcome never
changes. Because the model is a FunctionModel, the recovered run gets the same answers.
First the pieces: a policy that clears every call, a model that asks for search once and
then answers, and a function that builds a Governor over a given journal. TOOL is the role
of a message that carries tool results, so the model answers once it has seen one:
from gvn.harness.agent import VERDICTS
from gvn.harness.messages import TOOL
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.fulfillers import PolicyFulfiller, ToolFulfiller
from gvn.testing.fakes import FunctionModel, StubTool
START = Event("started", payload={"prompt": "Look it up."})
class Allow(Decision):
def outcomes(self) -> Alphabet:
return VERDICTS
def judge(self, consultation: object) -> Symbol:
return VERDICTS.named("cleared")
def answer(exchange: Exchange) -> Reply:
if any(message.role() == TOOL for message in exchange.messages()):
return Reply(message=Message.assistant(text="Three hits."))
search_call = ToolCall(call_id="call-1", name="search", arguments={"query": "moore"})
return Reply(message=Message.assistant(text="", calls=[search_call]))
def process(journal: Journal, search: StubTool) -> Governor:
toolbox = Toolbox(tools=[search])
return Governor(
fulfillers={
"invoke_model": ModelFulfiller(model=FunctionModel(respond=answer), toolbox=toolbox),
"invoke_tools": ToolFulfiller(toolbox=toolbox),
"consult_policy": PolicyFulfiller(decision=Allow()),
},
journal=journal,
output=RecordingOutput(),
clock=ManualClock(),
)
Then one scenario, killed at journal write number at. Whatever survived is recovered and the
run is finished:
from gvn.runtime.governor import FINISHED
from gvn.runtime.recovery import Recovery, UnknownRun
from gvn.testing.fakes import Crash, CrashingJournal
async def crash_at(at: int) -> tuple[Result, StubTool]:
stored = MemoryJournal() # what survives the crash
search = StubTool(name="search", arguments=Record({"query": Text()}), result={"hits": 3})
agent = Agent(name="helper", instructions="Be brief.", tools=[search])
try:
governor = process(journal=CrashingJournal(journal=stored, at_append=at), search=search)
return await governor.deliver(actor=agent, event=START), search
except Crash:
pass
try:
agent = await Recovery(journal=stored).recover(run_id="helper", actor_class=Agent)
except UnknownRun: # the crash came before the run's opening record: no trace of it
agent = Agent(name="helper", instructions="Be brief.", tools=[search])
governor = process(journal=stored, search=search)
return await governor.deliver(actor=agent, event=START), search
governor = process(journal=stored, search=search)
return await governor.resume(actor=agent), search
Recovery (from The Governor) rebuilds the actor from what the journal kept.
A run begins with one atomic write of its birth snapshot (a saved copy of its
Dto as it was born) together with its opening record, the started
event. CrashingJournal counts that write as append 0. A crash at it leaves both or neither,
so a run that crashed there has left no trace: Recovery raises UnknownRun, and the
scenario starts the run again under the same name. From write 1 on, the run exists and
recovery returns the agent as the journal kept it, and the scenario resumes it. A real
service handles UnknownRun the same way: the run was never begun, so it is started again.
Finally the matrix: crash at each of the first six writes and check the outcome is always the same:
for at in range(6):
result, search = asyncio.run(crash_at(at))
assert result.outcome().payload() == {
"text": "Three hits.",
"tools": [
{
"name": "search",
"identity": "gvn.testing.fakes.search",
"arguments": {"query": "moore"},
"content": {"hits": 3},
}
],
"attempts": [
{
"name": "search",
"identity": "gvn.testing.fakes.search",
"arguments": {"query": "moore"},
"status": "ok",
"detail": {"hits": 3},
}
],
"reductions": {
"trimmed": 0,
"summarised": 0,
"fell_back": 0,
"remembered": 0,
"unremembered": 0,
},
"recalls": {"asked": 0, "found": 0, "failed": 0},
"readings": {"taken": 0, "failed": 0, "blocked": 0, "latest": {}},
}, at
assert 1 <= len(search.calls()) <= 2, at # at least once, never lost
print("the outcome is the same whichever write the process died at")
Notice the second assertion: the tool ran at least once and at most twice. A crash between running a tool and journaling its result means the recovered run runs it again: work is delivered at least once. That is why tools with side effects use an idempotency key, as The Governor and Run context explain.
Deeper: holding a run mid-flight¶
HeldModel keeps every model call waiting until you release it, so a test can act while a
run is in flight: interrupt it, cancel it, or check that several calls are in flight at the
same time. await model.held(n) returns once at least n calls are held; it waits on an
asyncio primitive, so nothing polls and no time passes. A held call that is cancelled raises
CancelledError and stops being held.
from gvn.testing.fakes import HeldModel
async def interrupt_while_thinking() -> tuple[str, int]:
model = HeldModel(respond=lambda exchange: Reply(message=Message.assistant(text="Hello.")))
governor = Governor(
fulfillers={"invoke_model": ModelFulfiller(model=model, toolbox=Toolbox())},
journal=MemoryJournal(),
output=RecordingOutput(),
clock=ManualClock(),
)
agent = Agent(name="helper", instructions="Be brief.")
started = Event("started", payload={"prompt": "Hi."})
run = asyncio.create_task(governor.deliver(actor=agent, event=started))
await model.held(n=1) # the agent is now inside the model call
governor.interrupt(name="helper") # cancels the held call
await run
return agent.state().name(), model.waiting()
print(asyncio.run(interrupt_while_thinking()))
The interrupt cancelled the held call, so nothing is waiting any more, and the agent is
suspended (see Humans and interruption).
Deeper: testing time inside the Governor¶
No test waits for real time. With a ManualClock, a run that sleeps on a wake-up registers a
sleeper on the clock; the test waits for it with await clock.sleeping() and moves time with
advance. Here the Governor sleeps in-process on a timer (sleep_within=float("inf")), and
the test lets an hour pass in no time at all:
from gvn.harness.actor import Outcome
from gvn.harness.timer import Timer
async def an_hour_in_no_time() -> Outcome:
clock = ManualClock(start=0.0)
governor = Governor(
fulfillers={},
journal=MemoryJournal(),
output=RecordingOutput(),
clock=clock,
sleep_within=float("inf"),
)
nap = Timer(name="nap", at=3600.0)
run = asyncio.create_task(governor.deliver(actor=nap, event=Event("started")))
await clock.sleeping() # the Governor is now asleep on the clock
clock.advance(clock.earliest() - clock.now())
return (await run).outcome()
print(asyncio.run(an_hour_in_no_time()))
For a run that parks instead, advance the clock and call governor.wake(actor), as a
scheduler would. Time explains when the Governor sleeps and when it parks.
Deeper: checking a safety rule on recorded runs¶
gvn.runtime.replay.Replay rebuilds a finished run from its journal as a trace: the
actor and every event it was fed, in order. gvn.runtime.evaluation grades such traces
against explicit checks (see Replay and evaluation): an
Evaluation is a named list of checks; grade(trace=...) grades one trace and
score(traces=...) many. Finishes("completed") is a simple check that the run ended in one
of the named states. Gated(tools, when=None) is the
safety check most harnesses need: no call to one of tools (Tool objects, matched by
identity) may succeed unless a person
approved that call after the actor asked the policy about it (a person approving another
call of the same reply does not count). It follows the requests each
actor made (consult_policy, request_approval, invoke_tools), so it sees agents and
model-free actors alike, inside workflows too, and an approval never carries over to a later
batch. when(call, context) limits it to the calls that need a person, such as amounts over a
threshold. A run that never calls the named tools passes.
The example records two runs of an ops agent asked to deploy: one under a policy that wants
approval (a person then approves), one under a policy that clears everything. Only the first
passes the check.
from gvn.kernel.symbols import Symbol
from gvn.runtime.evaluation import Evaluation, Finishes, Gated
from gvn.runtime.governor import WAITING
from gvn.runtime.replay import Replay, Trace
class FixedVerdict(Decision):
def __init__(self, verdict: str) -> None:
self._verdict = verdict
def outcomes(self) -> Alphabet:
return VERDICTS
def judge(self, subject: object) -> Symbol:
return Symbol(self._verdict)
deploy = StubTool(name="deploy", arguments=Record({"service": Text()}), result={"ok": True})
async def recorded_run(verdict: str) -> Trace:
toolbox = Toolbox(tools=[deploy])
deploy_call = ToolCall(call_id="c1", name="deploy", arguments={"service": "web"})
model = ScriptedModel(
script=[
Reply(message=Message.assistant(text="", calls=[deploy_call])),
Reply(message=Message.assistant(text="Deployed.")),
]
)
journal = MemoryJournal()
governor = Governor(
fulfillers={
"invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
"invoke_tools": ToolFulfiller(toolbox=toolbox),
"consult_policy": PolicyFulfiller(decision=FixedVerdict(verdict=verdict)),
},
external=["request_approval"],
journal=journal,
output=RecordingOutput(),
clock=ManualClock(),
)
agent = Agent(name="ops", instructions="Deploy when asked.", tools=[deploy])
started = Event("started", payload={"prompt": "Deploy web."})
result = await governor.deliver(actor=agent, event=started)
if result.status() == WAITING: # a person is asked, and says yes
await governor.deliver(actor=agent, event=Event("approved"))
return await Replay(journal=journal).recorded(run_id="ops", actor_class=Agent)
safety = Evaluation(name="safety", checks=[Gated(tools=[deploy]), Finishes("completed")])
card = safety.score(traces=[asyncio.run(recorded_run(verdict="needs_approval"))])
print(card.summary())
lax = safety.grade(trace=asyncio.run(recorded_run(verdict="cleared"))) # a policy that clears everything
print(lax.problems())
safety: 1/1 passed
{'gated: gvn.testing.fakes.deploy': ('event 3 (tools_returned): gvn.testing.fakes.deploy ran for ops without approval',)}
The lax policy let deploy run with no person in the loop, and the check names the event
where it happened. The check's name and its problems name the tool by its identity.
Deeper: contract suites¶
Every port has an abstract test suite in gvn.testing.contracts: JournalContract,
ClockContract, OutputContract, ModelContract, LeasesContract, MemoryContract and
ThrottleContract; a tool has ToolContract (Tools), which
also checks that untrusted() answers the same bool every time; an Embedder, which the
shipped memories take to recall by meaning, has EmbedderContract. Each is a plain class of test
methods with a factory method you override. The suites run against the fakes and the real
adapters, so a fake cannot drift from the thing it imitates.
To test your own implementation, subclass the suite in a test module pytest collects:
# not runnable: this is a pytest module; pytest finds and runs the test methods.
from gvn.harness.ports import Journal
from gvn.testing.contracts import JournalContract
from myproject.storage import PostgresJournal
class TestPostgresJournal(JournalContract):
def make_journal(self) -> Journal:
return PostgresJournal(dsn="postgresql:///test")
The test methods are synchronous and use asyncio.run, so no async pytest plugin is needed.
You can also call them directly, which is what this check against MemoryJournal does:
from gvn.testing.contracts import JournalContract
class MemoryJournalContract(JournalContract):
def make_journal(self) -> Journal:
return MemoryJournal()
suite = MemoryJournalContract()
names = [name for name in dir(suite) if name.startswith("test_")]
for name in names:
getattr(suite, name)()
print(f"{len(names)} journal contract tests passed")
JournalContract has an optional reopen(journal) hook for journals that persist: override
it to return a fresh journal over the same storage, and the survives-a-reopen tests run too.
ClockContract needs make_clock() and let_pass(clock, seconds); ModelContract needs
make_model(text), make_failing_model(), and optionally make_held_model().
MemoryContract needs make_memory(), and optionally reopen, another, fail and mend;
Memory runs it against a memory of its own.
EmbedderContract needs make_embedder(), and optionally make_held_embedder() (an
embedder whose next embed waits until cancelled); Memory
runs it against an embedder of its own.
ThrottleContract needs make_throttle(), returning a fresh throttle that admits two calls
at once, and CYCLES (100) calls one after another, without its clock moving
(Spending and rate limits).
Deeper: the budget rules¶
gvn's own suite enforces rules that keep it fast and parallel. They live in
packages/gvn/tests/conftest.py, and you can adopt the same approach in your project:
- No real time. No sleeping, ever. Timeouts, retries and backoff are tested by advancing
a
ManualClock. - No network. In the fast tiers (the default, offline test runs) a fixture replaces socket connection and DNS lookup with a failure, so an accidental network call fails instead of being slow.
- No shared state. Files only under pytest's
tmp_path; nothing at module level that a test can change. - Parallel and random by default. The suite runs under
pytest -n autowith random ordering, so order dependence shows up immediately. - A per-test budget. In the fast tiers a test fails if it uses more than 100 ms of
processor time, or more than 1 s of wall-clock time. The second limit catches sleeping and
blocking without being sensitive to a loaded machine. Property tests may raise the budget
with
@pytest.mark.budget(seconds); ordinary tests may not. - Async without a plugin. Tests are plain synchronous functions that call
asyncio.run(...).
Recap¶
- Actors do no I/O, so you can test them by calling
handleand inspecting what they want. - Every port has a deterministic fake in
gvn.testing.fakes; run the Governor on them for end-to-end tests that take milliseconds. ManualClockmoves time only when you say so; no test waits for real time.CrashingJournalbuilds crash matrices,HeldModelholds a run mid-flight, andGatedchecks a safety rule on recorded runs.- Contract suites in
gvn.testing.contractskeep your own adapters honest.
Next: this is the last Concepts page. Continue with the guides, starting with Using a vendor model, or see the whole loop of evaluating changes in Replay and evaluation.