AlgoViz

Typed state, routing and graph execution

medium 8 min

A graph makes control explicit through nodes, edges and a state schema.

Video lesson · Chapter 1 of 4

A billing request reaches shipping

0:00 / 3:22

Theory

Read or listen first. About 3 min.

What it is

A graph makes control explicit through nodes, edges and a state schema. Nodes produce updates, routes choose permitted transitions and reducers define how concurrent updates combine. A cycle is meaningful only when the controller can terminate it.

Why it exists

A diagram helps inspect possible paths; a trace helps explain one actual run. Preserve the state entering a router and the decision it returned. This makes control errors distinguishable from failures of the tool invoked downstream.

Why a refund query entered the shipping branch

Typed state → Conditional router (update graph state). Conditional router → Billing search (take declared edge)
Typed state → Conditional router (update graph state). Conditional router → Billing search (take declared edge)

Inside this chapter

Chapter sources
LangChain Basics
LangChain offers model, tool and retrieval interfaces that can be composed into applications. Make I/O boundaries explicit: a retriever returns documents, a formatter creates context, and a model creates a response. Test each boundary with a fixture so an empty result can be traced to its source.

The value of composing components is that each boundary has a type you can assert on. When an answer is wrong, a fixture at each boundary tells you whether the retriever found nothing, the formatter dropped what it found or the model ignored good context. Without those seams, every failure looks like a prompt problem.

Example. Stub a retriever to return an empty list. Confirm the chain’s formatter and generator take the specified missing-evidence path.

Typed boundaries in a retrieval chain
  1. 1Retrieverreturns a list of documents
  2. 2Formatterbuilds context, or flags empty
  3. 3Modeldrafts the answer
  4. 4Responseanswer or missing-evidence reply

Stub the retriever to return [] and each later box must follow its declared empty path.

LangGraph Agents
LangGraph represents a workflow as state updates, nodes and routes. A conditional edge chooses the next node from the current state. Keep state serializable and specify how simultaneous updates combine. A review or approval step can then suspend and resume a run at a defined boundary.

Nodes return partial updates to a shared state object and a conditional edge is a function of that state that names the next node. Keeping state serialisable is what allows the runtime to checkpoint between steps, so an approval node can pause a run and a different worker can resume it later. Keep routing inputs as explicit fields so a trace shows exactly what the edge saw.

Example. A node returns a billing intent and two source IDs. Verify a conditional edge chooses billing while the state still retains the original question.

A conditional edge reads state, not prose

The classify node returns intent and source_ids; the original question stays in state untouched.
DAGs vs. Cycles
A DAG expresses a bounded flow with no cycles. A retrieval workflow that can revise a query needs a cycle or an explicitly unrolled sequence. Cycles require a termination condition. Track remaining attempts and stop when evidence is sufficient or the next pass cannot add useful information.

A DAG terminates by construction because there is no way back. A cycle is useful when a later step can improve an earlier one, such as rewriting a query after weak results, but it needs a quantity that strictly decreases plus an exit when the next pass cannot help. Many graph runtimes also enforce an overall step limit as a backstop; treat hitting it as a bug signal, not a normal exit.

Example. Draw a branch that can revisit retrieval. Add a decreasing attempt counter and an explicit exit when no usable evidence remains.

A retrieval cycle with a guaranteed exit

The counter only decreases, so the cycle must end.
The State Schema
A graph state schema specifies which fields survive transitions and how updates combine. Separate the original question, current query, retrieved IDs, retry count and terminal status. Overwriting the original question during a rewrite makes it difficult to evaluate whether the final answer still satisfies the request.

The schema is a contract about which facts survive each step and how two updates to the same field combine. Splitting the original question from the current query looks pedantic until you try to grade a final answer: if the rewrite overwrote the question, you can no longer tell whether the answer addressed what the user asked. Reducers matter most for parallel branches, where replace semantics silently drop one branch's results.

Example. After a rewrite, preserve both the original question and the derived query. Grade the final answer against the original question.

Another example. A contract-review graph keeps document_id and user_question fixed, appends clauses_found from three parallel extractors, and replaces risk_summary only from the final node.

Python
from typing import Annotated, TypedDictimport operatorclass RetrievalState(TypedDict):    original_question: str          # written once, never overwritten    current_query: str              # rewrites replace this field    retrieved_ids: Annotated[list[str], operator.add]  # updates append    retries_left: int    status: str                     # running | answered | no_evidence
Annotating a field with a reducer tells the runtime to combine updates (here, append) instead of replacing them.
Anatomy of a Graph
A node performs a transformation and returns a state update. Edges determine which node runs next. Keep side effects visible at node boundaries and log state versions. An execution trace can then show whether an empty answer originated at retrieval, filtering or a later routing decision.

Treat every node as a function from state to a small update and keep side effects at node edges where the trace can see them. Logging state versions means a bad outcome can be walked backwards: find the first version where the state is wrong, and the node that produced it is your suspect.

Example. Replace the retriever node with a fixture returning no IDs. Check how the reducer and downstream router handle the empty update.

State versions through one run with an empty retriever

VersionNodeUpdate returnedState after
v1inputquestion setquery = question, ids = []
v2retrieve (fixture)ids += []ids = [] (unchanged)
v3routerroute = no_evidencestatus = no_evidence
v4replyanswer = cannot find a sourcestatus = answered_empty
Logging a version per node shows the empty answer began at retrieval, not at routing.
The Router Pattern
A router maps evidence about the request to a finite set of permitted destinations. Validate a model-produced route against this set and define a fallback. For a support bot, a billing question may require a different knowledge source from a product setup question.

A router turns open-ended input into one of a few named destinations, so the set of destinations must be closed and checked in code. Parse the model's output against the allowed labels and send anything else to a fallback rather than crashing or guessing. Cheap signals in the input, like an invoice code pattern, can also be used as a deterministic pre-check before the model is asked at all.

Example. A request with a billing code is routed to product help. Inspect the router’s allowed labels and the state immediately before its decision.

Validate the label before following it

If this request lands in product help, look first at the router's input state and the label it returned.
Graph Compilation
Compiling a graph connects the declared state, nodes, reducers and routes into an executable workflow. Check unreachable nodes, invalid destinations and missing stop paths. Successful compilation verifies structure; exercising failure branches with fixtures tests behavior that static wiring alone cannot establish.

Compiling is a structural check, like a type checker: it proves the wiring is consistent, not that the behaviour is right. Failure branches are the ones most likely to be wired but never exercised, so write a fixture per failure edge (timeout, empty result, denied) and assert the run ends in the expected terminal state.

Example. Compile a graph with a declared failure path, then exercise the path with a timeout fixture. A successful compile alone does not exercise it.

What compilation checks

  • Every edge points to a declared node
  • No node is unreachable from the start
  • Reducers exist for declared fields
  • Some path reaches the end

What only a fixture run shows

  • The timeout branch actually handles a timeout
  • The router picks the right label on new inputs
  • Retries stop when they should
  • Fallback replies make sense to a user
Visualization & Debugging
A graph drawing shows possible routes, while a run trace records the route actually taken. Compare the two for a query that should trigger a fallback. Capture input versions, selected edges and observable results so an unexpected route can be reproduced.

A rendered graph is the map of what may happen; a trace is the record of what did. Lay the actual node sequence over the map and find the first point they part ways. Record input versions and the chosen edge at that point so you can replay the exact decision locally rather than trying to reproduce the whole conversation.

Example. Overlay the actual node order on a diagram of permitted transitions. Mark the first place the observed route differs from the expected route.

Expected route against the trace

StepExpected nodeActual nodeMatch
1classifyclassifyyes
2retrieveretrieveyes
3fallback (no evidence)answerno: first divergence
4endendn/a
The first mismatch is where to start: capture the state version that entered step 3 and replay it.
Resuming across schema changes
Store the workflow version alongside durable state. Resume on a compatible worker or perform an explicit, tested migration of both state and pending effects. Merely decoding the old JSON does not prove its meaning survived the deployment.

Store the workflow version with every checkpoint so the runtime knows which code wrote it. Then either keep compatible workers running until old runs drain, or write a migration that is tested on real suspended states, including any pending side effects. Fields whose meaning changed, such as an approval that now needs an expiry, should force a fresh decision rather than being guessed.

Example. Revision two replaces an approved flag with an approval ID and expiry. A suspended revision-one run needs fresh authorization before taking the new execution path.

A suspended run meets a new deployment

Decoding the old JSON is not enough: a bare approved: true cannot become an approval ID with an expiry.

How it works

Step through the idea, or press Play.

Step 1 of 3

Typed state. intent unknown · query preserved

Understand it

Worked example

Why a refund query entered the shipping branch

  1. 1

    intent unknown · query preserved

    Record the original request independently from derived fields. This allows later inspection even when a rewrite changes the query.

  2. 2

    intent = billing

    A node returns a state update and a validated edge chooses a declared destination. A compiled graph may still route incorrectly on an unseen input.

  3. 3

    Source IDs B7 and B9

    Compare the expected edge with the run trace and inspect state before routing. This separates classification errors from retrieval errors in the selected branch.

Follow the handoffs

A diagram helps inspect possible paths; a trace helps explain one actual run. Preserve the state entering a router and the decision it returned. This makes control errors distinguishable from failures of the tool invoked downstream.

State before the router in the failed run

FieldExpectedObserved in trace
original_questionWhy was I charged twice?Why was I charged twice?
intent (router output)billingshipping
selected edgeto billing_searchto shipping_search
source_idsB7, B9S3
The input was intact and the edge followed the label, so the classification is the fault, not retrieval.

Locate the fault from the trace

Summary

The whole topic in one minute.

The graph describes allowed transitions. The trace records which transition occurred and the state used to choose it.

A diagram helps inspect possible paths; a trace helps explain one actual run. Preserve the state entering a router and the decision it returned. This makes control errors distinguishable from failures of the tool invoked downstream.

Sources