Module 5 · Streaming & production

Testing and versioning your graphs

7 min read

A graph in production evolves: you tweak a prompt, add a tool, change a threshold, rename a node. Each change can break a behavior that worked, and some can break ongoing conversations — those whose state is saved, sometimes waiting for approval for days. This lesson presents Relay's testing strategy and the rules for evolving a graph without breakage.

The test pyramid of a graph

LevelWhat is testedModelSpeedFrequency
UnitRouters, business rules, tools, isolated nodesNoneMillisecondsOn every change
GraphTrajectories, branches, interrupts, persistenceFakeSecondsOn every change
ServerAPI, streaming, concurrencyFakeSecondsOn every change
EvaluationQuality of answers and decisions on real casesRealMinutesBefore each release, after each prompt or model change

The key to the pyramid is the fake model: as long as the test is about the graph's mechanics (the right path, the right interrupt, the right resume), the model's behavior must be deterministic. Relay switches to FakeSupportModel with RELAY_FAKE_LLM=1, thanks to the single chat_model() access point: no node creates its own model.

Unit tests: pure code first

Routers and business rules are pure functions, tested without a graph or a model:

@pytest.mark.parametrize(
    ("intent", "expected"),
    [("question", "agent"), ("order_status", "agent"), ("refund", "refund"), ("other", "handoff")],
)
def test_route_intent(intent, expected):
    assert route_intent({"intent": intent}) == expected


@pytest.mark.parametrize(
    ("amounts", "approvals", "route"),
    [
        ((), [], "explain"),
        ((24.0, 18.0), [], "execute"),
        ((349.0,), ["supervisor"], "supervisor_review"),
        ((349.0, 499.0), ["supervisor", "finance"], "supervisor_review"),
    ],
)
def test_refund_policy(amounts, approvals, route):
    update = decide(_state(*amounts))
    assert update["refund"]["approvals_needed"] == approvals
    assert route_decision(update) == route

These tests (file tests/test_units.py) cover every branch of the routers and every tier of the policy. It is the most cost-effective level: the refund policy — which costs money if it's wrong — is tested exhaustively in a few milliseconds.

Graph tests: trajectories and scenarios

The tests in tests/test_graph.py run the complete graph, with a fresh InMemorySaver and InMemoryStore for each test (pytest fixtures):

@pytest.fixture
def graph(store):
    return build_graph(checkpointer=InMemorySaver(), store=store)


async def test_order_status_goes_through_tool(graph):
    out = await say(graph, "t1", "cus_lea", "Bonjour, où en est ma commande ORD-1002 ?")
    assert out.value["status"] == "resolved"
    expected = ["__start__", "load_profile", "triage", "agent", "tools", "agent", "finish"]
    assert await nodes_visited(graph, "t1") == expected

Three families of assertions complement each other:

  • The result: status, answer, refunded amount.
  • The trajectory: the sequence of visited nodes, rebuilt from the checkpoint history. It catches an agent that answers correctly without consulting the tool, or a refund that skipped an approval.
  • Side effects: the refund ledger (data.REFUNDS), reset before each test. We check that no refund is issued before approval, and that only one is after a replay.

Human scenarios are tested naturally, since Command(resume=...) is a simple call: test_two_level_approval, test_invalid_answer_is_asked_again, test_edit_amount_skips_finance, test_rejection. Failures are simulated (data.fail_next_payments(n)) to test retries and the error handler.

Server tests

tests/test_server.py uses httpx.ASGITransport to call the FastAPI application in memory, without starting a network server, and parses the SSE events. It checks the event sequence, the complete approval circuit through the API, the refusal of a message during an approval, and double-texting.

Evaluations with the real model

Fake tests guarantee mechanics, not quality. For quality, build a set of real (anonymized) cases with the expected result: correct intent, correct tool, correct amount, appropriate tone. Run it with the real model on each prompt or model change, and track scores over time — LangSmith provides datasets and evaluators for this, but a script and a spreadsheet are enough to start. Evaluate first the decisions that have a cost: triage (a refund request classified as a question will never be processed) and the per-item reason (which determines the amount).

Versioning a graph

The companion code records the graph version in the metadata of every run:

return builder.compile(checkpointer=checkpointer, store=store, name="relay").with_config(
    {"metadata": {"graph_version": config.GRAPH_VERSION}}
)

Each trace and each checkpoint thus says which graph version produced it: essential to analyze an incident that happened during a deployment, or to compare the quality of two versions.

The test_graph_structure_is_versioned test freezes the graph's structure (the set of nodes). The goal isn't to prevent change, but to make it deliberate: renaming or removing a node makes this test fail, and forces you to ask the questions of the next section.

Evolving a graph without breaking ongoing conversations

Saved checkpoints reference node names (nodes to run next, interrupted tasks) and state keys. A new version of the code must be able to resume threads created by the old one.

ChangeRisk for ongoing threadsPrecaution
Change a prompt, threshold, modelNone for the mechanicsEvaluate quality before deploying
Add a node or branchLowNone, if existing paths remain valid
Add a state keyLowMake it optional (total=False, state.get(...))
Remove or rename a keyMedium: old states have the old keyRead both names during a transition period
Rename or remove a nodeHigh: a thread interrupted on that node can no longer resumeKeep the old name, or drain the affected threads first
Change the meaning of a value (an amount's unit…)High, and silentA new key rather than a new meaning

For risky changes, two strategies:

  • Drain: stop sending new conversations to the old version, wait for ongoing threads to finish (or handle them), then switch.
  • Run side by side: deploy the new version under another graph name, route new threads to it, and let the old version finish its own. The managed platform offers this mechanism with its versioned assistants; on a homemade server, just store the graph version with each thread.

Course conclusion

You built Relay brick by brick: a typed state with its reducers, a bounded agent loop, reliable routing, a parallel map-reduce, a subgraph with an explicit interface, persistence and long-term memory, time-travel, a two-level human approval circuit, a server with streaming and concurrency management, and a suite of 34 tests that runs offline in a few seconds.

These bricks are found in any serious agentic system. The most important thing to remember isn't an API, but a method: a deterministic, tested skeleton, bounded zones of autonomy, humans at the points of risk, and an explicit state that makes all of it observable, resumable and correctable.

Key takeaways

  • Test pyramid: unit (pure code), graph and server (fake model), evaluations (real model).
  • A single model access point makes the fake model possible; a resettable ledger makes side effects checkable.
  • Test the result, the trajectory and the side effects.
  • Record the graph version in metadata; freeze the structure in a test to make every change deliberate.
  • Checkpoints reference node names and state keys: don't rename them without draining or running versions side by side.

Practice

  1. Add the edge cases to test_refund_policy: exactly €50 and exactly €500. Is the result what you expected from the policy?
  2. Rename the supervisor_review node to manager_review, then try to resume a thread interrupted by the old version (with a SQLite checkpointer). What happens?
  3. Build a set of 20 varied customer messages with the expected intent, and measure triage accuracy with the real model.

Resources