flowchart LR
START(["START"]) --> split{"split"}
split -.->|fan_out| r1("retrieve")
split -.->|fan_out| r2("retrieve")
split -.->|fan_out| r3("retrieve")
r1 --> synth("synthesize")
r2 --> synth
r3 --> synth
synth --> END(["END"])
10 Parallel & Reducers

Back in Chapter 5 we warned you off a trap: two plain edges out of one node don’t make a choice, they make a fan-out — both branches run at once. That was the wrong tool for picking one path. It is the right tool here: real work, done in parallel.
But parallelism has a sharp edge of its own. The moment two branches run at the same time and both try to write the same state key, they collide. So we’ll meet the bug first, fix it with one annotation, and only then scale up.
To run work in parallel you fan out — several edges, a routing function that returns a list, or a list of
Sends — so several nodes execute in one superstep. The moment two of them write the same key they collide; a reducer is what turns that collision into a merge.
10.1 What we’re building
The chapter climbs in four steps: the parallel-write bug, the reducer that fixes it, a router that fans out to a chosen subset of tools, and finally a Send fan-out that splits a compound question into sub-questions and retrieves each one in its own worker. That last graph is the shape to hold in your head:
split fans out to as many retrieve workers as there are sub-questions, and all of them feed one synthesize node. A reducer on findings stitches their results together.
Those four steps — plus the join Gotcha between them — are the main line, and enough to build parallel work. Two more routers follow and read fine as a second pass: Command (Section 10.6), a node that returns its own next stop, and the Overwrite deep dive, which skips a reducer on purpose.
10.2 The bug: two writers race for one key
Start with the simplest parallel graph: an agent node fans out to two tools — search_docs and web_search — and both write what they found into sources.
class BuggyState(TypedDict):
question: str
sources: NotRequired[list[str]] # no reducer → writes collide
answer: NotRequired[str]The fan-out is two plain edges out of agent — the shape Chapter 5 told you not to use for a choice. Here it is what we want, and both branches rejoin at generate:
builder.add_edge(START, "agent")
builder.add_edge("agent", "search_docs")
builder.add_edge("agent", "web_search")
builder.add_edge("search_docs", "generate")
builder.add_edge("web_search", "generate")
builder.add_edge("generate", END)flowchart TD
START(["START"]) --> agent("agent")
agent --> search_docs("search_docs")
agent --> web_search("web_search")
search_docs --> generate("generate")
web_search --> generate
generate --> END(["END"])
Each worker returns only its own contribution — it doesn’t read the other branch, doesn’t merge, just reports:
def search_docs_node(state: dict) -> dict:
return {"sources": ["doc 1", "doc 2"]}
def web_search_node(state: dict) -> dict:
return {"sources": ["web A", "web B"]}Run it and it doesn’t quietly lose data — it refuses outright:
langgraph.errors.InvalidUpdateError: At key 'sources': Can receive only one
value per step. Use an Annotated key to handle multiple values.Both branches wrote sources in the same superstep. A plain state key is a “last value” channel. It accepts exactly one write per step, so when two arrive it can’t pick a winner and raises InvalidUpdateError. The error message even tells you the fix — an Annotated key.

10.3 The fix: a reducer
A reducer is a two-argument function bound to a state key that says how to combine the existing value with an incoming one. Bind it with Annotated, and operator.add — plain list concatenation — is all we need:
import operator
from typing import Annotated
class MergedState(TypedDict):
question: str
# operator.add is the function itself, not a call: LangGraph invokes it
1 sources: Annotated[list[str], operator.add] # reducer → writes accumulate
answer: NotRequired[str]- 1
-
Annotated[T, x]is a type with a label stapled to it. Ask Python for this class’s hints andsourcesis a plainlist[str]; the label is extra baggage that nothing sees unless it goes looking. LangGraph goes looking, findsoperator.add, and calls it with the stored list and each incoming one instead of rejecting the second write.
That is the entire change. Same four nodes, same six edges — only the type of sources differs. Where the plain key rejected the second write, the reducer folds both writes together: ["doc 1", "doc 2"] + ["web A", "web B"]. The run completes with all four sources intact.
One requirement rides along with that freedom: keep a reducer associative,1 so that f(f(a, b), c) and f(a, f(b, c)) agree. Concatenation does, which is why operator.add is safe here. A combiner that subtracts does not: a reducer that drops from the accumulator whatever the incoming batch already holds gives one answer for (a − b) − c and another for a − (b − c), and both look right on a graph with one branch.
Do not expect the runtime to show you the difference. On the pinned version a superstep’s writes are folded one at a time in a fixed order: make one branch of this graph slow and the other fast, then swap them, and the stored list and the reducer’s call sequence come back identical either way. Associativity is what the contract asks of you, not what this build exercises — which is how a combiner that lacks it can still work well without a symptom.
Associative is also not the same as order-independent, and concatenation is the case that separates them: a + b and b + a are different lists.
Overwrite
A reducer binds to the key, so every write folds — even the rare one that shouldn’t. For a deliberate reset (wiping sources before a fresh retrieval pass, say), wrap that single write in Overwrite from langgraph.types: return {"sources": Overwrite([])} replaces the value outright, skipping the reducer for that one update.
It hands back the merge protection this section just added, so keep it in the serial parts of the graph. Two Overwrites in one superstep raise InvalidUpdateError, and an Overwrite racing a plain write silently wins — the other write is lost.
And it only means anything on a key that has a reducer. Put it on a plain key and nothing unwraps it: the Overwrite object itself is written into the state, with no error, and the next node to read that key gets a wrapper instead of a value.
10.4 Fanning out to a chosen few
So far the fan-out was hard-wired: both tools, always. Often you want to fan out to a runtime-chosen subset — some questions need the docs, some need the web, some need both. This is the routing function from Chapter 5 with one twist: instead of returning a single string (take one edge), it returns a list of node names (take all of them, in parallel).
class RouterState(TypedDict):
question: str
plan: NotRequired[list[str]]
1 sources: Annotated[list[str], operator.add]
def decide_node(state: RouterState) -> dict:
q = state["question"].lower()
plan: list[str] = []
if any(k in q for k in ("configure", "error", "how")):
plan.append("doc_search")
if any(k in q for k in ("latest", "news", "2026")):
plan.append("web_search")
if not plan:
2 plan = ["doc_search", "web_search"]
return {"plan": plan}
def route_parallel(state: RouterState) -> list[str]:
3 return state["plan"]
def doc_search_node(state: RouterState) -> dict:
return {"sources": [f"[doc] about '{state['question']}'"]}
4def web_search_node2(state: RouterState) -> dict:
return {"sources": [f"[web] about '{state['question']}'"]}- 1
-
The reducer. Both branches write
sourcesin the same superstep; withoutoperator.addthe second write raisesInvalidUpdateError. - 2
- The plan is data in the state, so the decision is visible in every checkpoint and the router stays a one-liner. No match: run both.
- 3
-
A list, not a string: every name in it runs in the next superstep. The same function returning
"doc_search"would be Chapter 5’s single-edge router. - 4
-
The
2is only to keep the name free: the fan-out earlier in this chapter already has aweb_search_node, and the companion file holds both.
Wiring it is the Chapter 5 call, but the path_map now lists every node the router might fan out to:
builder.add_conditional_edges(
"decide", route_parallel, ["doc_search", "web_search"]
)
builder.add_edge("doc_search", "merge")
builder.add_edge("web_search", "merge")flowchart TD
decide{"decide"} -.->|route_parallel| doc_search("doc_search")
decide -.->|route_parallel| web_search("web_search")
doc_search --> merge("merge")
web_search --> merge
The merge node is the join — it runs once, after the branches finish:
def merge_node(state: RouterState) -> dict:
# Sort to choose the display order.
sources = sorted(state["sources"])
noun = "source" if len(sources) == 1 else "sources"
print(f"[merge] joined {len(sources)} {noun}: {sources}")
return {}sources carries the same operator.add reducer, so merge sees a single accumulated list however many branches ran. A one-string return picks one path; a list return fans out to many.
Nothing in the runtime waits for both branches.
A node with several plain in-edges is triggered once per predecessor. merge runs once here only because doc_search and web_search both finish in the same superstep, so their two triggers collapse into one run.
Wire merge with the two plain edges shown above, then put a rerank step after web_search, and merge does not wait for it. It runs twice: once in the superstep after doc_search finishes — already holding both branches’ sources, because web_search wrote in that same superstep, but not rerank’s — and again after rerank, with everything. The output does not say so. What the early run misses is not a branch; it is a branch that has not finished. Read the run left to right, one superstep per column:
%%{init: {"flowchart": {"nodeSpacing": 14, "rankSpacing": 18, "padding": 4, "subGraphTitleMargin": {"top": 0, "bottom": 2}}}}%%
flowchart LR
subgraph s1["superstep 1"]
decide{"decide"}
end
subgraph s2["superstep 2"]
doc("doc_search")
web("web_search")
end
subgraph s3["superstep 3"]
rerank("rerank")
m1("⚠ merge · 1st run<br/>no rerank yet")
end
subgraph s4["superstep 4"]
m2("⚠ merge · 2nd run<br/>all sources")
end
decide --> doc
decide --> web
doc --> m1
web --> rerank
rerank --> m2
classDef step fill:none,stroke:#999,stroke-dasharray:4 4;
class s1,s2,s3,s4 step;
classDef bad fill:#fde2e2,stroke:#c0392b;
class m1,m2 bad;
doc_search finishes in superstep 2 and that alone is enough to trigger merge in superstep 3; rerank finishes in superstep 3 and triggers it again in 4.
Two declarations fix that, and they are not interchangeable:
# wait for these two — the last node of each branch:
builder.add_edge(["doc_search", "rerank"], "merge")
# wait for the run to drain:
builder.add_node("merge", merge_node, defer=True)| the join you wire | merge runs |
how it goes wrong |
|---|---|---|
| plain edges | once per superstep in which any predecessor finishes | branches of different lengths finish in different supersteps, so it runs again for each — early runs carrying partial data |
add_edge([…], "merge") |
once, when every node named has run | one named node doesn’t run, and merge never runs at all: no error, no output, nothing |
defer=True |
once, when the run has no pending work left | it can’t miss a branch or fire twice — but it waits for unrelated branches too |
10.5 Fanning out over a dynamic list
The router still chooses from a fixed menu of two nodes. The real map-reduce case is different. You don’t know how many workers you need until runtime: a compound question — “How do I configure retries and enable TLS and rotate credentials?” — should split into three sub-questions and retrieve each in parallel. That’s what the Send API is for.

An orchestrator splits the question and records the pieces:
class MapState(TypedDict):
question: str
sub_questions: NotRequired[list[str]]
findings: Annotated[list[str], operator.add]
answer: NotRequired[str]
def split_node(state: MapState) -> dict:
raw = state["question"].rstrip("?")
parts = [p.strip() for p in raw.split(" and ") if p.strip()]
print(f"[split] {len(parts)} sub-questions:")
for i, p in enumerate(parts, 1):
print(f" {i}. {p}")
return {"sub_questions": parts}Then a conditional edge returns a list of Send objects — one per sub-question. Each Send names a target node and hands it its own payload, which need not be the whole graph state:
from langgraph.types import Send
def fan_out(state: MapState) -> list[Send]:
return [
Send("retrieve", {"index": i, "sub_question": sq})
for i, sq in enumerate(state["sub_questions"], 1)
]The retrieve worker reads only the small payload it was sent, and writes one finding into a reducer-backed key. Its input schema is just the payload, not MapState:
class RetrieveState(TypedDict):
index: int
sub_question: str
def retrieve_node(state: RetrieveState) -> dict:
sq = state["sub_question"]
return {"findings": [f"{state['index']}. [doc] setup notes for '{sq}'"]}Every worker points at one synthesize node, and findings carries Annotated[list[str], operator.add]. Every Send worker is spawned in the same superstep, so they all finish together and synthesize runs once, reducing the pieces into an answer:
def synthesize_node(state: MapState) -> dict:
# Sort to choose the display order.
findings = sorted(state["findings"])
print(f"[synthesize] merged {len(findings)} findings")
body = "\n".join(f" - {f}" for f in findings)
return {"answer": f"Here is what I found:\n{body}"}builder.add_edge(START, "split")
builder.add_conditional_edges("split", fan_out, ["retrieve"])
1builder.add_edge("retrieve", "synthesize")
builder.add_edge("synthesize", END)- 1
-
One edge, however many workers there are — and it is triggered once by the whole batch, not once per worker. Anything you want done per sub-question belongs inside
retrieveitself. The flip side of “once per batch”: ifsplitreturns zero sub-questions, no worker fans out, so this edge never fires,synthesizenever runs, and the graph ends with noanswer. If an empty question is possible, givesplita fallback (or the router a no-work branch) rather than assuming every batch synthesizes.
flowchart TD
split{"split"} -.->|fan_out| r1("retrieve")
split -.->|fan_out| dots["..."]
split -.->|fan_out| r3("retrieve")
r1 --> synthesize("synthesize")
dots --> synthesize
r3 --> synthesize
classDef dots fill:none,stroke:none;
class dots dots
Declare every Send target in the path_map list — ["retrieve"] here. The engine does not need it. Omit it and the workers still fan out and still finish; what you lose is draw_mermaid(), which no longer knows where split can go and draws a straight arrow to END — a picture that is now wrong, which is worse than no picture at all.
The join needs no declaration here. Every worker is the same node, so however long the worker’s chain gets they advance in lockstep and land together.
10.6 Command, the other dynamic router
Send is not the only way to pick a destination at runtime. A node can skip the routing function entirely and return a Command — one object carrying both a state update and the next stop. State here is the small schema in ch08_command_router.py — question, route, and the reducer-backed sources:
from typing import Literal
from langgraph.types import Command
def command_agent_node(state: State) -> Command[Literal["search_docs", "web_search"]]:
target = "search_docs" if "deploy" in state["question"] else "web_search"
return Command(
update={"route": target},
goto=target,
)flowchart TD
agent("agent") -.->|goto| search_docs("search_docs")
agent -.->|goto| web_search("web_search")
No add_conditional_edges, no separate routing function: the node that just computed the decision acts on it. That’s the appeal — when the route depends on something the node just worked out, Command saves you from stashing an intermediate result in state just so an edge function can read it back out.
The return annotation does real work. The goto is a string buried in the function body, where the compiler can’t see it — the same disease as the missing path_map in the Gotcha above, and you have seen the fix: declare the possible targets, Command[Literal["search_docs", "web_search"]]. LangGraph reads it when you add_node and registers the edges. Prefer not to annotate? Declare them on the node instead:
builder.add_node("agent", command_agent_node, destinations=("search_docs", "web_search"))Either way, the declaration is for people and tools. Three cases are worth keeping apart:
At compile() |
At run time | In the picture | |
|---|---|---|---|
| declaration omitted, target is a real node | builds | goto jumps there |
wrong: a straight arrow to END |
declared target that was never add_noded |
refused: ValueError: Found edge ending at unknown node |
never runs | — |
goto to a name that matches no node (a typo) |
the declaration cannot catch it | a warning, the goto ignored, the run ends there |
— |
So the declared targets are checked against the nodes you registered; the runtime goto string never is. A typo in it never raises — the node’s update still lands in State, and only the jump is dropped.
What breaks when you omit the declaration is everything that reads the structure. draw_mermaid() no longer knows where agent can go, so it wrongly draws the only thing it can infer — a straight arrow to END. And the next person to touch the code has to excavate function bodies to learn where control can go.
Two dynamic routers, then. Keep them straight:
Send |
Command |
|
|---|---|---|
| returned by | a conditional-edge function | the node itself |
| data it carries | the worker’s private input — never touches shared state | an update, merged through the reducers like any node return |
| shape of the jump | a list of Sends spawns N copies of a node, each with its own payload |
one node, or a list of named nodes run in parallel (goto=["a", "b"]) |
| edge declaration | the path_map list |
the Literal annotation, or destinations |
| other jobs | — | resume=... for interrupt (Section 9.5) |
And they compose: Command(update={...}, goto=[Send(...), Send(...)]) updates state and fans out in one return — something neither can do alone.
Rule of thumb: reach for Command when the route depends on what the node just computed; keep the plain routing function when the logic is a small pure function you’d rather test on its own; when you need a fixed set of named nodes to run together, Command(goto=[...]) does it without a routing function; and when you need N copies of one worker, each with its own input, only Send will do.
Command route, fan out, and mis-draw
Everything this section claims is in one small file, code/ch08_command_router.py. Run it and compare the two draw_mermaid() edge lists — with the Literal annotation and without — then look at the superstep trace for goto=["search_docs", "web_search"] and for goto=[Send(...), ...]. Then break it: change a goto target to a name that doesn’t exist and watch the run end with a warning instead of an error.
10.7 Running it
The driver walks all four steps in order. Two habits carry through it: parallel workers stay silent, so prints cannot interleave, and every list we print is sorted first — choosing a display order explicitly rather than inheriting whatever the merge produced.
Each graph’s assembly lives in a small builder function that wires up the nodes and edges we walked through above and returns a compiled graph. build_router and build_mapreduce take no arguments; build_fanout takes the state class, because steps (a) and (b) are the very same wiring compiled over two different states — BuggyState without the reducer, MergedState with it.
The two workers are the ones from the top of the chapter. The other two nodes have not appeared yet, and they are this small — agent exists only to give the fan-out somewhere to start, and writes nothing:
def agent_node(state: dict) -> dict:
# Kicks off the fan-out to both tools; writes nothing itself.
return {}
def generate_node(state: dict) -> dict:
return {"answer": f"answer from {len(state['sources'])} sources"}def build_fanout(state_cls: type):
builder = StateGraph(state_cls)
builder.add_node("agent", agent_node)
builder.add_node("search_docs", search_docs_node)
builder.add_node("web_search", web_search_node)
builder.add_node("generate", generate_node)
builder.add_edge(START, "agent")
builder.add_edge("agent", "search_docs")
builder.add_edge("agent", "web_search")
builder.add_edge("search_docs", "generate")
builder.add_edge("web_search", "generate")
builder.add_edge("generate", END)
return builder.compile()flowchart TD
agent --> search_docs
agent --> web_search
search_docs --> generate
web_search --> generate
The router and the Send fan-out assemble the same way:
def build_router():
builder = StateGraph(RouterState)
builder.add_node("decide", decide_node)
builder.add_node("doc_search", doc_search_node)
builder.add_node("web_search", web_search_node2)
builder.add_node("merge", merge_node, defer=True) # the join
builder.add_edge(START, "decide")
builder.add_conditional_edges(
"decide", route_parallel, ["doc_search", "web_search"]
)
builder.add_edge("doc_search", "merge")
builder.add_edge("web_search", "merge")
builder.add_edge("merge", END)
return builder.compile()flowchart TD
decide{"decide"} -.->|route_parallel| doc_search("doc_search")
decide -.->|route_parallel| web_search("web_search")
doc_search --> merge("merge")
web_search --> merge
def build_mapreduce():
builder = StateGraph(MapState)
builder.add_node("split", split_node)
builder.add_node("retrieve", retrieve_node)
builder.add_node("synthesize", synthesize_node)
builder.add_edge(START, "split")
builder.add_conditional_edges("split", fan_out, ["retrieve"])
builder.add_edge("retrieve", "synthesize")
builder.add_edge("synthesize", END)
return builder.compile()flowchart TD
split{"split"} -.->|fan_out| r1("retrieve")
split -.->|fan_out| dots["..."]
split -.->|fan_out| r3("retrieve")
r1 --> synthesize("synthesize")
dots --> synthesize
r3 --> synthesize
classDef dots fill:none,stroke:none;
class dots dots
if __name__ == "__main__":
# (a) the bug — caught so the program still exits cleanly
buggy = build_fanout(BuggyState)
try:
buggy.invoke({"question": "How do I set retries?"})
print("no error (unexpected)")
except InvalidUpdateError as e:
print("caught InvalidUpdateError:")
for line in str(e).splitlines():
print(f" {line}")
# (b) the reducer fix
merged = build_fanout(MergedState)
result = merged.invoke({"question": "How do I set retries?"})
sources = sorted(result["sources"]) # an explicit display order
print(f"merged {len(sources)} sources: {sources}")
# (c) the parallel router
router = build_router()
for q in ("How do I configure the latest release?", # plan: both branches
"How do I configure retries?"): # plan: one branch
router.invoke({"question": q})
# (d) the Send fan-out
mapreduce = build_mapreduce()
q = "How do I configure retries and enable TLS and rotate credentials?"
print(f"question: {q}")
result = mapreduce.invoke({"question": q})
print(result["answer"])(The full driver adds a banner line before each step; those banners are what you see between the blocks below.)
==============================================================
(a) two parallel branches write 'sources', no reducer
==============================================================
caught InvalidUpdateError:
At key 'sources': Can receive only one value per step. Use an Annotated key to handle multiple values.
For troubleshooting, visit: https://docs.langchain.com/oss/python/langgraph/errors/INVALID_CONCURRENT_GRAPH_UPDATE
==============================================================
(b) same graph + Annotated[list, operator.add] reducer
==============================================================
merged 4 sources: ['doc 1', 'doc 2', 'web A', 'web B']
==============================================================
1(c) parallel router: conditional edge returns a LIST of names
==============================================================
[decide] plan: ['doc_search', 'web_search']
[merge] joined 2 sources: ["[doc] about 'How do I configure the latest release?'", "[web] about 'How do I configure the latest release?'"]
[decide] plan: ['doc_search']
[merge] joined 1 source: ["[doc] about 'How do I configure retries?'"]
==============================================================
(d) Send fan-out: split -> retrieve x N -> synthesize
==============================================================
question: How do I configure retries and enable TLS and rotate credentials?
[split] 3 sub-questions:
1. How do I configure retries
2. enable TLS
3. rotate credentials
[synthesize] merged 3 findings
Here is what I found:
- 1. [doc] setup notes for 'How do I configure retries'
- 2. [doc] setup notes for 'enable TLS'
- 3. [doc] setup notes for 'rotate credentials'- 1
-
Look at the router’s two runs: the first question fans out to both branches, the second to one, and
mergejoins either way.
10.8 What we learned
- Fan-out runs branches in parallel. Several plain edges out of a node, or a
Sendlist, put multiple nodes in one superstep. (Chapter 5’s “wrong for a choice” is this chapter’s right answer.) - Concurrent writes to one key collide. A plain state key accepts one write per step; two writers in the same superstep raise
InvalidUpdateError. - A reducer makes parallel writes accumulate.
Annotated[list[str], operator.add]folds every write together instead of overwriting: one annotation, no node changes. - A routing function that returns a list fans out. One string takes one edge; a list of names fans out to each; a list of
Sendfans out to a runtime-sized set of workers, each with its own payload. - A join is a trigger, not a barrier. A node with several plain in-edges runs once per predecessor that finishes in a different superstep. With branches of unequal length it runs early, with everything except the branch still working. Declare the join deliberately:
add_edge([...], "merge")waits for the nodes you name — right for a fixed fan-out, silently never firing for a runtime-chosen subset — whiledefer=Truewaits for the run to drain and covers both.
The workers here were bare nodes. In the next chapter we let a whole graph play the part of a single node — a subgraph — so a self-contained RAG pipeline can be dropped into a parent graph with its own isolated state, and we watch how the parent and child state schemas map across the boundary.
New pieces in this chapter
| Piece | Usage |
|---|---|
| Type | |
InvalidUpdateError |
The error a plain state key raises when two nodes write it in one superstep. except InvalidUpdateError:; the message itself names the fix — an Annotated key |
Annotated |
Attaches a reducer to a state key alongside its type. sources: Annotated[list[str], operator.add]; a plain key accepts only one write per step |
Overwrite |
Wraps a single write so it replaces the value, skipping the key’s reducer. return {"sources": Overwrite([])}; for deliberate serial resets, not for concurrent writers |
Send |
A runtime fan-out ticket: a target node plus that worker’s own payload. Send("retrieve", {"sub_question": sq, …}); return a list of them from a conditional edge |
Literal |
A closed set of legal values, here a node’s possible destinations. Command[Literal["search_docs", "web_search"]]; read at add_node time to register the edges |
| Value | |
operator.add |
A stdlib function (list concatenation) used here as the reducer value. Annotated[list[str], operator.add]; accumulates every write — and keeps duplicates |
| API | |
add_edge([…], node) |
List form of add_edge: the node waits for every source named. add_edge(["doc_search", "rerank"], "merge"); a fan-out that fires only some of them never triggers it |
add_node(defer=…) |
Keyword arg: hold a node until nothing else in the run is pending. add_node("merge", merge_node, defer=True); the join that survives a runtime-chosen fan-out, at the price of waiting on unrelated branches |
Command(goto=…) |
Keyword arg on Command (Chapter 7’s resume=): the next node, or a list of nodes to run in parallel. Command(update={…}, goto=target); jumps even to undeclared targets — draw_mermaid() then draws a wrong edge |
add_node(destinations=…) |
Keyword arg: declare a node’s possible goto targets without a return annotation. add_node("agent", command_agent_node, destinations=("search_docs", …)); a declared target must be a real node (checked at compile()), but the runtime goto string is not |
Code in this chapter
| File | What it runs |
|---|---|
code/ch08_parallel_reducers.py |
The whole arc in order: two writers colliding on one key, the reducer that fixes it, the join, and a Send fan-out. |
code/ch08_command_router.py |
Runnable ground truth for Command: what the annotation registers, what the drawing loses without it, and how a typo’d goto dies. |
Challenge
Two challenges: first make a double-firing join fire exactly once, then replace the reducer under it with one of your own.
🥉 Bronze — make the join fire exactly once
Build a fan-out whose two branches finish in different supersteps, join them at a merge node with a plain edge from each branch, and count how often merge runs. Then fix it twice over — once with each declaration from the table in the Gotcha. Finally, swap the fixed fan-out for a router that picks its branches at runtime, and count again under each fix.
You’ve got it when the plain wiring fires merge twice, both declarations bring it back to once, and the runtime-chosen plan separates them: one of the two stops firing merge at all, with nothing raised and nothing in the output to say so.
Hints: a join names who triggers the node, not a barrier that waits, so make one branch take an extra superstep — without the uneven timing the bug never shows. Both fixes are one line: a list of sources on add_edge, or one keyword on add_node. Count the firings from inside merge, with a reducer-backed counter in the state.
Worked solution with tests: code/answers/ch08_defer_join.py.
🥈 Silver — write your own reducer
Write a union reducer that merges while dropping repeats (order-preserving), bind it with Annotated[list[str], union], and fan out two branches that both surface a shared item.
Confirm the result is deduplicated — and, for contrast, that the same graph with operator.add keeps the duplicate.
Hints: a reducer is any function (existing, incoming) -> merged; operator.add just happens to be list concatenation. The limit worth feeling for yourself is the one two parallel retrievers hit in production — they often return overlapping sources, and operator.add keeps every duplicate.
Worked solution with tests: code/answers/ch08_custom_reducer.py.
A two-argument function that combines two values of one type is what Scala’s Cats calls a
Semigroup, and the combiner half of a JavaCollector;operator.addon a list is the textbook instance.↩︎

