← Back to Guides

Companion to the book Building Real-World Agentic AI Systems with LangGraph · this part maps to Book Part II · Chapters 4–6

GuideFor: AI Engineers, ML Engineers, Platform Engineers, AI Systems Architects

LangGraph Reducers Are a Concurrency Policy

Rename a node and the answer changes. The code that decides how concurrent writes merge lives inside a type annotation, appears on no diagram, and the docs decline to guarantee its order.

Updated
#langgraph#agent-state#reducers#concurrency#state-management#production-ai

16 November 2026: re-verified on langgraph 1.2.22 / langchain 1.5.0 / langchain-core 1.8.1 (Python 3.13.9). Corrected the status of issues #4026 and #6005, which were closed before this was published; updated the quoted apply_writes sort line, which langgraph-checkpoint now makes a replay contract; re-pointed the docs quote to its current page; added Overwrite and error_handler= as write-relation traps; diagrams redrawn in D2.

Adding a second retriever to a LangGraph agent is a ten-line change. It crashes the graph on the first run, and the two-line fix everyone reaches for trades a loud failure for a quiet one whose cost depends on something nobody checks.

Atlas is the customer-support agent from Part 1. It answered questions from one knowledge base. Someone asked for a second source, so we added a search_tickets node next to search_kb, let both run in parallel, and let both append what they found to evidence: NotRequired[list[Evidence]].

text
langgraph.errors.InvalidUpdateError: At key 'evidence': Can receive only onevalue 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

That error is LangGraph behaving well. Two nodes finished in the same step, both wrote evidence, and the runtime refused to guess which one you meant. It failed loudly, before anything reached a customer. LangChain's own agent framework has the shape that produces it. In deepagents 0.7.38, files carries a reducer and todos does not. todos now exists only if you opt into langchain's TodoListMiddleware, whose PlanningState declares it with no reducer, and a user hit this exact error on todos with parallel subagents writing it. A maintainer could not reproduce it, and the report was closed in January 2026 without a reducer being added, so treat it as a schema asymmetry you can go and read rather than as a confirmed incident - which is the point either way, since nothing in the type or the graph surfaces the difference between those two keys.

The InvalidUpdateError fix, and why it is a trap

Then you follow the link. The official troubleshooting page explains that concurrent updates create "uncertainty around how to update the internal state," and it prescribes a reducer:

python
from typing import Annotatedimport operatorevidence: Annotated[NotRequired[list[Evidence]], operator.add]

The crash stops. Both writes survive. That line is what the framework's own error page tells you to write, which is reason enough to expect it in most graphs that fan out.

The crash was the easy failure. It named the key, named the step, and linked the page that explains it. What replaces it is a graph that can answer the same billing question two different ways depending on which retriever somebody renamed last, with nothing in the logs connecting the rename to the answer.

Here are the same two writes before and after the one-line fix:

d2
grid-rows: 1
grid-gap: 40
classes: {
  writer: {style: {fill: "#98D8C8"; stroke: "#5FA898"; font-color: "#2C2C2A"}}
  box: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"}; label.near: top-center}
}
before: "Before: no reducer" {
  class: box
  kb: "search_kb\nwrites evidence" {class: writer}
  tk: "search_tickets\nwrites evidence" {class: writer}
  ch: "evidence: LastValue" {style: {fill: "#4A90E2"; stroke: "#2C6FB0"; font-color: "#FFFFFF"}}
  err: "InvalidUpdateError\nat key 'evidence'\nloud, names the key" {style: {fill: "#FFD93D"; stroke: "#C9A800"; font-color: "#2C2C2A"}}
  kb -> ch
  tk -> ch
  ch -> err
}
after: "After: operator.add" {
  class: box
  kb: "search_kb\nwrites evidence" {class: writer}
  tk: "search_tickets\nwrites evidence" {class: writer}
  ch: "evidence: operator.add\nfold order = node names" {style: {fill: "#7B68EE"; stroke: "#5A4BC4"; font-color: "#FFFFFF"}}
  out: "['search_kb', 'search_tickets']\nno error, order from names" {style: {fill: "#E74C3C"; stroke: "#B03A2E"; font-color: "#FFFFFF"}}
  kb -> ch
  tk -> ch
  ch -> out
}

You have just replaced a loud failure with a silent one. The state is no longer wrong in a way that raises. It is wrong in a way that depends on what you named your nodes.

The write relation: why LangGraph reducers are a concurrency policy

Part 1 made a specific claim about what a graph buys you. The edge set turns control flow into data. graph.get_graph().draw_mermaid() hands back a sound over-approximation of the transition relation: an upper bound on which node can run after which, reviewable on a Tuesday before anything runs. That artifact is the reason to prefer a specified runtime over an Accidental Runtime.

Here is the other half, and nobody ships an artifact for it.

A graph has a second relation. Call it the write relation: which node writes which state key, and by what policy concurrent writes to that key are merged. It is not a coinage, it is the obvious counterpart to the transition relation. What matters is that it has no draw_mermaid(). It appears on no diagram, in no edge list, and in no type checker's output.

Part 1's central guarantee shows the gap precisely. issue_refund has a guarded mandatory predecessor: one inbound edge, guarded by state, so every path to a refund passes the entitlement check. That property is real and it is visible in the edge set. It says nothing whatsoever about refund_cents. Two nodes can write that key, the merge policy decides which value survives, and no part of the guarantee Part 1 spent its length establishing extends to the number the refund is for.

The merge half of it lives in one place: the reducer. And a reducer is executable code that you pass as metadata inside a type annotation. Annotated[list, operator.add] is a function argument dressed as a type. It is skipped by every review surface that reads your graph, because none of them read annotations as behaviour.

So the thesis:

The reducer is not a merge helper. It is the concurrency-control policy for that state key. A reviewer, a diagram, and a type checker all miss it, and it is the only thing they miss that decides what the state value is when two nodes write at once. The ecosystem's default choice - operator.add, prescribed by LangGraph's own error page - has no order-independence property. So the value of your state becomes a function of the order writes are folded in when two writers land in the same superstep, and that order is derived from your node names.

The consensus this argues with is not subtle. Reducers are taught as plumbing. They are described as "how you accumulate results from parallel branches," which makes them sound like a detail of list handling. They are the thing standing between two concurrent writers and a correct answer, which is a different job with a different name in every other part of computing.

There is a second asymmetry underneath the first, and it is the reason this cannot be fixed by drawing a better diagram. Part 1's edge set gives you a sound over-approximation: it may show a transition that never happens, and it never misses one that can. That is the direction of error you want from a safety artifact, because an upper bound can justify a claim about what the system will never do. The write relation cannot be recovered that way. The declared merge policy is static, but the node-to-key mapping is not, as I show at the end. So the best available artifact is a coverage-bounded under-approximation. Everything it reports is real, and it misses any write on a path you never exercised. Those are opposite kinds of wrong. Control flow got the useful kind. State did not.

Row by row, the two relations compare like this:

d2
grid-rows: 5
grid-columns: 3
grid-gap: 8
classes: {
  head: {style: {fill: "#95A5A6"; stroke: "#6F7F80"; font-color: "#2C2C2A"; bold: true}}
  label: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"; bold: true}}
  good: {style: {fill: "#4A90E2"; stroke: "#2C6FB0"; font-color: "#FFFFFF"}}
  bad: {style: {fill: "#E74C3C"; stroke: "#B03A2E"; font-color: "#FFFFFF"}}
}
h0: "" {class: head}
h1: "Transition relation" {class: head}
h2: "Write relation" {class: head}
r1: "Says" {class: label}
t1: "which node can run\nafter which" {class: good}
w1: "which node writes which key,\nand how concurrent writes merge" {class: bad}
r2: "Lives in" {class: label}
t2: "the edge set" {class: good}
w2: "reducers in Annotated metadata,\nplus node return dicts" {class: bad}
r3: "Artifact" {class: label}
t3: "draw_mermaid()" {class: good}
w3: "none" {class: bad}
r4: "Best bound" {class: label}
t4: "sound over-approximation:\nnever misses a transition" {class: good}
w4: "coverage-bounded under-approximation:\nmisses unexercised writes" {class: bad}

Read the bottom row across. Only the left cell can justify a claim that something never happens. Its neighbour can only report what a run has already seen.

LangGraph reducer order: rename a node, change the answer

Here is Atlas with the parallel retrieval that caused the crash, now with the prescribed reducer. This builds directly on Part 1's state, which I have extended by a single key.

python
import operatorfrom typing import Annotated, Literal, NotRequired, TypedDictfrom langchain.messages import AnyMessagefrom langgraph.graph import StateGraph, START, ENDfrom langgraph.graph.message import add_messagesclass Evidence(TypedDict):    source: str    text: strclass AtlasState(TypedDict):    # Supplied by the caller at invoke() time. The model never writes this.    customer_id: str    messages: Annotated[list[AnyMessage], add_messages]    # Model-written or derived from a model-written field.    intent: NotRequired[Literal["refund", "question"]]    ticket_id: NotRequired[str | None]    refund_cents: NotRequired[int]    refund_allowed: NotRequired[bool]    receipt_id: NotRequired[str | None]    # New in Part 2. Two retrievers opened this article; a third is added below.    evidence: Annotated[NotRequired[list[Evidence]], operator.add]def make_retriever(source: str):    def node(state: AtlasState) -> dict:        hits = corpus.search(source, state["customer_id"], state["messages"][-1])        return {"evidence": [{"source": source, "text": h} for h in hits]}    return nodebuilder = StateGraph(AtlasState)builder.add_node("triage", triage)builder.add_node("search_kb", make_retriever("search_kb"))builder.add_node("search_tickets", make_retriever("search_tickets"))builder.add_node("search_docs", make_retriever("search_docs"))builder.add_node("answer", answer)builder.add_edge(START, "triage")for name in ("search_kb", "search_tickets", "search_docs"):    builder.add_edge("triage", name)    builder.add_edge(name, "answer")builder.add_edge("answer", END)

triage, answer, corpus, render_context, model, and SystemMessage carry over from Part 1 unchanged, as do the companion-repo stubs behind them. Three retrievers, one accumulator, one answer node that renders evidence into the prompt: fan-out, fan-in, one shared accumulator.

Run it and look at the order the evidence arrives in:

text
('search_kb', 'search_tickets', 'search_docs')  -> ['search_docs', 'search_kb', 'search_tickets']

Not the order I added the nodes. Not the order they finished. It is the node names, sorted.

Now do the most ordinary refactor there is. Someone points out that search_docs retrieves internal design papers rather than product documentation, so it should be called search_papers. One rename. No change to the function, the edges, the fan-out, or anything else:

text
('search_kb', 'search_tickets', 'search_papers')  -> ['search_kb', 'search_papers', 'search_tickets']

That evidence moved from first position to the middle. It is the same evidence, retrieved by the same code, from the same source. Here is that move as prompt positions:

d2
grid-rows: 1
grid-gap: 40
classes: {
  box: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"}; label.near: top-center}
  pos: {style: {fill: "#98D8C8"; stroke: "#5FA898"; font-color: "#2C2C2A"}}
  top: {style: {fill: "#6BCF7F"; stroke: "#3F9E52"; font-color: "#2C2C2A"}}
  dip: {style: {fill: "#E74C3C"; stroke: "#B03A2E"; font-color: "#FFFFFF"}}
}
before: "Before" {
  class: box
  grid-rows: 3
  grid-gap: 10
  p1: "1. search_docs\ntop of the prompt" {class: top}
  p2: "2. search_kb" {class: pos}
  p3: "3. search_tickets" {class: pos}
}
after: "After the rename" {
  class: box
  grid-rows: 3
  grid-gap: 10
  p1: "1. search_kb" {class: pos}
  p2: "2. search_papers\nmiddle, where the U-curve dips" {class: dip}
  p3: "3. search_tickets" {class: pos}
}

Lost in the Middle is what makes that particular move the expensive one. Model attention to retrieved context is U-shaped: strongest at the start, second-strongest at the end, weakest in between. The rename took the design-paper hit off the top of the prompt and put it in the position the curve punishes hardest. Nobody who reviewed that commit was thinking about prompt position, because the commit was about a name.

One precondition, because it is load-bearing and belongs here rather than buried in a checklist. The sort applies within a single superstep. It reorders writers that are co-active - a fan-out from a shared predecessor, or a Send batch. Writers at different depths fold in control-flow order across supersteps, and renaming those changes nothing:

text
zzz_first -> aaa_second -> zzz_first -> aaa_second ...

So the defect needs two things at once: two writers to the same non-commutative key in one step, and something downstream that reads the order. That is narrower than "your agent is nondeterministic." It is also true of every parallel-retrieval graph I have seen, and it has a sharper cousin one layer out, where a call's argument depends on a sibling call's result that has not arrived yet.

Add order does not save you, and neither does the order you wrote the edges:

text
nodes ("alpha", "zulu")              -> ['alpha', 'zulu']nodes ("zulu", "alpha")              -> ['alpha', 'zulu']   # add order is irrelevantnodes ("verify_a", "analyze_b")      -> ['analyze_b', 'verify_a']nodes ("KBSearch", "search_docs")    -> ['KBSearch', 'search_docs']nodes ("2_retriever", "a_retriever") -> ['2_retriever', 'a_retriever']

The third line is the one that matters. verify_a runs the same function it ran before. Its edges are unchanged. It moved because a sorts before v.

The last two lines are why I will stop saying "alphabetical." The sort is codepoint-wise on the node name, so uppercase precedes lowercase and digits precede letters. KBSearch wins on a capital K. I will keep writing "by name" as shorthand, but if you are predicting the order for a real schema, sort it the way Python does rather than the way a dictionary does.

Every one of these graphs draws the identical Mermaid. Same node count, same edge count, same shape, same dotted and solid edges. The artifact Part 1 taught you to review shows nothing, because nothing it models changed.

That is the whole argument in one experiment. The rest of this is mechanism.

Order-Coupled State: naming the defect

The pattern deserves a name, because "the list came out in a different order" does not sound like a defect until it has a handle.

Order-Coupled State: state whose value is a function of the order its writes are folded in, where that order comes from the runtime's task-ordering rule rather than from anything semantic in the data.

In LangGraph 1.x that rule is the node name for edge-triggered tasks and the Send list index for pushed ones. The definition deliberately does not say so, because the sort key is an implementation detail and the defect would outlive a change to it.

The definition has two halves and both are load-bearing. The first says the value depends on fold order. The second says that order comes from the runtime rather than from your data. A node name is documentation. A Send list index is an artifact of however the list got built. Neither is a decision anyone made about correctness, and both are exactly the kind of thing a refactor changes without a second thought.

A non-commutative reducer makes a key an order-coupled hazard. Two more conditions promote a hazard to a defect: two writers have to be co-active in one superstep, and something downstream has to read the order. Keep those separate. Most schemas have several hazards and one or two real defects, and the audit at the end of this article is built to tell them apart. The three conditions stack like this:

d2
grid-rows: 3
grid-columns: 2
grid-gap: 26
classes: {
  q: {style: {fill: "#7B68EE"; stroke: "#5A4BC4"; font-color: "#FFFFFF"}}
  hz: {style: {fill: "#FFD93D"; stroke: "#C9A800"; font-color: "#2C2C2A"}}
  ok: {style: {fill: "#6BCF7F"; stroke: "#3F9E52"; font-color: "#2C2C2A"}}
  bad: {style: {fill: "#E74C3C"; stroke: "#B03A2E"; font-color: "#FFFFFF"}}
}
q1: "1. Is the key's reducer non-commutative?" {class: q}
a1: "Yes: order-coupled HAZARD\n(evidence, messages)" {class: hz}
q2: "2. Can two writers be co-active\nin one superstep?" {class: q}
a2: "No: the hazard stays latent" {class: ok}
q3: "3. Does anything downstream\nread the order?" {class: q}
a3: "Yes to all three: DEFECT" {class: bad}
q1 -> q2
q2 -> q3

Order-Coupled State is a property a key has, not a bug you can point at, which is why it survives code review. evidence has it. messages has it. customer_id does not, because it has no reducer and therefore cannot take a concurrent write at all - it raises instead. It can still be silently overwritten one superstep later, which is the trap near the end of this article. That order comes from control flow, which is at least something somebody decided.

Naming it is most of the work, and there is precedent for that claim. In 1995, Berenson and colleagues wrote A Critique of ANSI SQL Isolation Levels, whose contribution was largely to name the anomalies the standard had failed to describe. Write skew was happening in databases before that paper. What the paper changed was that engineers could now say "this is write skew" in a review, instead of describing a confusing symptom and moving on. Agent state is at the pre-1995 stage. The anomalies are shipping, and the vocabulary to reject them in a pull request does not exist yet. "The evidence list came out in a weird order" gets waved through. "This key is Order-Coupled State and three nodes write it" does not.

Why evidence order changes the model's answer

The reasonable objection at this point is that a list is a list. If all three retrievers contributed, the model sees all three, and order is cosmetic.

It is not, though I want to be careful about how far the evidence reaches.

Liu et al., Lost in the Middle (TACL 2024), measured how language models use long contexts. They found a U-shaped curve. Accuracy is highest when the relevant document sits at the beginning or the end of the input, and it degrades in between. The control is the part that matters here: the positional bias held whether the documents kept their original ranking or were randomly shuffled, so the bias is positional rather than content-driven. The same positional degradation shows up on the retrieval side, where an assembler concatenates in reranker order and nobody checks what that does to the prompt.

State its setting honestly, because it is not quite yours. That paper measures single-relevant-document question answering among ten to thirty distractors, on 2023-era models. Atlas is synthesising an answer from three partially relevant evidence lists. The U-shape transfers; the effect size does not, and nobody has published one for that case.

For "reordering changes outputs at small n," which is closer to what a three-item evidence list does, the better citations are newer. The Order Effect (arXiv:2502.04134) measures prompt sensitivity to input order directly. Set-LLM (arXiv:2505.15433) exists because "[the model's] response changes simply due to a reordering of the answer options" was worth building a permutation-invariant architecture to solve.

So: your parallel retrieval accumulates evidence into a list, the fold order decides the list order, and the list order decides the prompt order. Prompt order is a documented lever on model output. Only the first of the chain's three links was measured here:

d2
direction: down
classes: {
  m: {style: {fill: "#4A90E2"; stroke: "#2C6FB0"; font-color: "#FFFFFF"}}
  lit: {style: {fill: "#FFA07A"; stroke: "#D9785A"; font-color: "#2C2C2A"}}
}
fold: "fold order\n(sorted node names)" {class: m}
list: "evidence list order" {class: m}
prompt: "prompt order\n(render_context)" {class: m}
answer: "model answer" {class: lit}
fold -> list: "1. measured here, exact"
list -> prompt: "2. answer renders the list in order"
prompt -> answer: "3. from the literature:\nLost in the Middle, The Order Effect"

Be precise about which half of that I demonstrated. I measured the order change - that is the console output above, and it is exact. I did not measure an answer change on Atlas. That step is imported from the literature, and for a three-item reorder in a synthesis task the honest statement is that the mechanism is well attested and the magnitude is unpublished. What a rename gives you is a silent, uncontrolled change to a variable the research says matters. No test catches it, because the evidence set is identical and every retriever ran.

This is the series thesis made concrete, and it is one of the failure modes that get misread as reasoning problems. It looks like a reasoning failure. The model gave a different answer to an unchanged question, so the model is the suspect. It is a state-management failure wearing a reasoning failure's clothes, and the actual cause is in a git mv.

Where LangGraph's merge order actually comes from

I dispatched research for this article believing the order depended on which branch finished first. That is wrong, and it is worth showing why, because the truth is more useful.

Writes are not applied when a node returns. LangGraph runs on supersteps, inherited from Pregel and Bulk Synchronous Parallel. Every node that is ready runs, all of them finish, and only then are the collected writes applied to channels. Inside apply_writes, before anything is folded:

python
# sort tasks on path, to ensure deterministic order for update applicationtasks = sorted(tasks, key=lambda t: writes_sort_key(task_path_str(t.path)))

Edge-triggered tasks carry a path of (PULL, node_name). Send-created tasks carry (PUSH, idx), with the index zero-padded to ten digits so numeric order survives string sorting. The whole path is the key, with task id and write index as tiebreakers (writes_sort_key). Sorting those paths gives you: node name, codepoint-sorted, for parallel nodes; Send list position for fan-out; and because __pregel_pull sorts before __pregel_push, edge-triggered writes fold before pushed ones in a mixed step. One scoping note for anyone using the functional API: that (PUSH, idx) shape is Graph-API-Send-specific, and @task calls carry a longer path that sorts by parent first, then by call order, not by task name.

Here is one superstep with Atlas's three retrievers, plus one Send task to show where pushed work lands:

d2
grid-rows: 1
grid-gap: 40
classes: {
  box: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"}; label.near: top-center}
  step: {style: {fill: "#4A90E2"; stroke: "#2C6FB0"; font-color: "#FFFFFF"}}
  sort: {style: {fill: "#7B68EE"; stroke: "#5A4BC4"; font-color: "#FFFFFF"}}
  pull: {style: {fill: "#98D8C8"; stroke: "#5FA898"; font-color: "#2C2C2A"}}
  push: {style: {fill: "#FFA07A"; stroke: "#D9785A"; font-color: "#2C2C2A"}}
}
superstep: "One superstep" {
  class: box
  s1: "1. every ready task runs" {class: step}
  s2: "2. writes are collected,\nnone applied yet" {class: step}
  s3: "3. apply_writes sorts tasks by\nwrites_sort_key(task_path_str(t.path))" {class: sort}
  s4: "4. each key folds its writes\nleft to right through its reducer" {class: step}
  s5: "a saver replaying these writes\nmust use the same order" {style: {fill: "#FFD93D"; stroke: "#C9A800"; font-color: "#2C2C2A"}}
  s1 -> s2
  s2 -> s3
  s3 -> s4
  s4 -> s5
}
queue: "Sorted fold order" {
  class: box
  grid-rows: 4
  grid-gap: 10
  k1: "1. ~__pregel_pull, search_docs" {class: pull}
  k2: "2. ~__pregel_pull, search_kb" {class: pull}
  k3: "3. ~__pregel_pull, search_tickets" {class: pull}
  k4: "4. ~__pregel_push, 0000000000, ..." {class: push}
}

So the fold order is completely deterministic. Timing does not enter into it. A slow retriever and a fast one produce the same list. This series grew into a book: Building Real-World Agentic AI Systems with LangGraph. Chapter 4, "StateGraph, Nodes, and Edges," walks the superstep loop this sort runs inside - active nodes run, their deltas merge through the reducers, and the boundary is where a checkpoint can be saved - while it builds Atlas's first runnable graph.

There is a behaviour here, a design claim about it, and no specification of it. Those are three different things, and it is worth not confusing them, because I did at first.

The implementation sorts, with a comment saying why.

The framework's author defends that publicly. Nuno Campos, writing on the design of the LangGraph runtime, says updates are applied "in a deterministic order (this is what guarantees no data races)," and that the design "ensures that the execution order and latency of each node never influences the final output of the agent."

Read that carefully, because it is narrower than it first sounds and it is entirely true. It is a claim about timing. Node execution order and latency cannot change your output, and the sort is exactly what buys that. A slow retriever and a fast one give you the same list.

The Graph API control-flow page then declines to name which order you get:

"updates from a parallel superstep may not be ordered consistently. If you need a consistent, predetermined ordering of updates from a parallel superstep, you should write the outputs to a separate field in the state together with a value with which to order them."

These do not contradict each other. Timing-independence and "we are not telling you the order" are both true at once. That is not a disagreement, and calling it one would be the easy version of this argument.

It is worse than a disagreement. It is a behaviour with no specification: stable enough that you will build on it without noticing, and unsupported enough that nothing stops it changing. A contradiction gets noticed and filed. This does not.

I could not find the sort key stated on any documentation page. It is source-only. Treat it as an undocumented implementation detail: real, reliable in practice, and not something to depend on in writing.

Since the delta-channel work, the source does say why the order matters. writes_sort_key in langgraph-checkpoint is the key apply_writes now uses, and its docstring makes the order a saver obligation: a checkpointer that replays stored writes "must sort them by it too, or an order-sensitive reducer rebuilds a different value than the run produced." That is the framework naming the hazard this article is about. It fixes it for replay by pinning the order, and it is written for whoever implements a checkpointer, not for whoever writes a reducer.

The engineering position that falls out is not "LangGraph is nondeterministic." It is narrower and harder to argue with:

Your state value depends on an ordering that is real, load-bearing, derived from node names, invisible on every artifact, and documented nowhere a user reads - it is a contract only between the runtime and the checkpointer.

LangGraph Send order: the case that genuinely varies run to run

There is one case where this stops being about refactors and becomes ordinary nondeterminism, and it is the one to worry about in production.

Send fan-out folds in list-index order. When the list is built by your code, that order is yours. When the list comes out of a model, it is not.

python
from langgraph.types import Senddef fan_out_subquestions(state: AtlasState) -> list[Send]:    # The model decides how many workers, and in what order.    plan = planner.with_structured_output(SubQuestions).invoke(state["messages"])    return [Send("research", {"question": q}) for q in plan.questions]

Same customer, same question, same retrievers, same evidence found. The planner returns its sub-questions in a different order this time, because that is what samplers do. The fold order follows the list, so the evidence is permuted and the prompt with it. Per the order-sensitivity work above - The Order Effect is the closer fit at this n - the answer can change:

text
plan ['refund window', 'shipping delay']  -> evidence ['refund window', 'shipping delay']plan ['shipping delay', 'refund window']  -> evidence ['shipping delay', 'refund window']

Side by side, the two runs differ only in the list the planner emitted:

d2
grid-rows: 1
grid-gap: 40
classes: {
  box: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"}; label.near: top-center}
  plan: {style: {fill: "#FFA07A"; stroke: "#D9785A"; font-color: "#2C2C2A"}}
  send: {style: {fill: "#98D8C8"; stroke: "#5FA898"; font-color: "#2C2C2A"}}
  out: {style: {fill: "#7B68EE"; stroke: "#5A4BC4"; font-color: "#FFFFFF"}}
}
run1: "Run 1" {
  class: box
  plan: "planner: ['refund window',\n'shipping delay']" {class: plan}
  s0: "Send idx 0\nrefund window" {class: send}
  s1: "Send idx 1\nshipping delay" {class: send}
  ev: "evidence:\n['refund window', 'shipping delay']" {class: out}
  plan -> s0
  plan -> s1
  s0 -> ev
  s1 -> ev
}
run2: "Run 2" {
  class: box
  plan: "planner: ['shipping delay',\n'refund window']" {class: plan}
  s0: "Send idx 0\nshipping delay" {class: send}
  s1: "Send idx 1\nrefund window" {class: send}
  ev: "evidence:\n['shipping delay', 'refund window']" {class: out}
  plan -> s0
  plan -> s1
  s0 -> ev
  s1 -> ev
}

Identical set of writes. Different state value. Nothing changed in the input except the order a sampler emitted two strings in.

This is the honest version of "your agent is nondeterministic." Not the whole runtime - one narrow, specific, reproducible path, where model output order propagates into state value through a reducer nobody reviewed.

A reducer is a merge function without any of the laws

The vocabulary for this problem was settled fifteen years ago, in a different field, and LangGraph borrowed half of it.

Shapiro, Preguiça, Baquero and Zawirski defined Conflict-free Replicated Data Types (CRDTs) in 2011. The core result is about what a merge function must guarantee for replicas to converge no matter what order updates arrive in or how often they are duplicated. The merge must be commutative, associative, and idempotent. Those three properties are the price of not caring about order.

LangGraph asks you to supply that merge function and imposes none of those laws. Before leaning on the analogy, though, it is worth saying where it does not hold, because the disanalogy narrows the argument to the part that survives.

CRDT laws exist for replica convergence under unordered, duplicated, out-of-band delivery. A LangGraph superstep is none of that. It is a single process, one authoritative channel, and a deterministic left fold that applies each write exactly once. In that setting only commutativity is load-bearing. Associativity is structurally satisfied, because BinaryOperatorAggregate.update() folds left with fixed parenthesisation, so you cannot construct a case where non-associativity changes the result on that path. That is precisely why DeltaChannel, which does batch variably, has to state batching-invariance as an explicit obligation. Idempotence only starts to matter because node execution is at-least-once rather than exactly-once, which is a durability property and a Part 4 problem.

Here is what each law is worth inside one superstep:

d2
grid-rows: 4
grid-columns: 3
grid-gap: 8
classes: {
  head: {style: {fill: "#95A5A6"; stroke: "#6F7F80"; font-color: "#2C2C2A"; bold: true}}
  label: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"; bold: true}}
  note: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"}}
}
h0: "CRDT law" {class: head}
h1: "In a superstep" {class: head}
h2: "Why" {class: head}
l1: "Commutative" {class: label}
v1: "load-bearing" {style: {fill: "#E74C3C"; stroke: "#B03A2E"; font-color: "#FFFFFF"}}
n1: "fold order comes from node names\nand Send indexes" {class: note}
l2: "Associative" {class: label}
v2: "structurally satisfied" {style: {fill: "#6BCF7F"; stroke: "#3F9E52"; font-color: "#2C2C2A"}}
n2: "BinaryOperatorAggregate folds left\nwith fixed grouping; DeltaChannel\nbatches, so it must state it" {class: note}
l3: "Idempotent" {class: label}
v3: "matters on re-execution" {style: {fill: "#FFD93D"; stroke: "#C9A800"; font-color: "#2C2C2A"}}
n3: "nodes run at least once,\nnot exactly once (Part 4)" {class: note}

So the borrowed vocabulary earns one thing rather than three: it names commutativity as a merge obligation, and LangGraph never states it. The one place the codebase acknowledges order sensitivity at all is the checkpointer's writes_sort_key docstring, and it handles the problem by fixing the order rather than by asking reducers to commute.

I am not the first person to point at operator.add here. Abdeali Azguards, writing on checkpoint collisions and write skew in LangGraph in May 2026, argues that the default operator.add duplicates state entries on retry loops and that reducers need CRDT semantics. That piece is about cross-thread checkpoint collisions and idempotence under retry, and it resolves them by pushing serialisation into Postgres. It does not address commutativity, the merge order among concurrent branch writes inside one superstep, or whether any of it is reviewable. Sajjad Khan's 2026 formalisation of concurrency anomalies in multi-agent language-model systems is the standing prior art on the general problem, and it models shared external stores rather than graph state channels. Both got to the neighbourhood first. What is left, and what this article is about, is narrower: the merge policy for a state key is itself an unreviewed concurrency-control decision, it is written as metadata inside a type annotation, and no artifact shows it.

I searched for it before writing this. The word "commutative" does not appear in the graph API documentation, the runtime documentation, binop.py, last_value.py, or message.py. BinaryOperatorAggregate, the channel behind every Annotated[T, fn] key you have ever written, has a docstring whose one sentence, above a usage example, describes what it does and requires nothing:

text
Stores the result of applying a binary operator to the current value and each new value.

LangGraph does state an obligation in two places, and both are about batch reducers. DeltaChannel requires reducers to be "deterministic and batching-invariant," and the Pregel runtime page says bulk reducers must be associative. Scope that correctly before you lean on it. DeltaChannel is beta and needs langgraph 1.2 or later. Batching-invariance is associativity across folds, which is a different property from commutativity rather than a weaker one - neither implies the other. It does not give you order independence. It gives you the freedom to batch.

Now check the reducers you actually use against the CRDT bar:

ReducerCommutativeAssociativeIdempotentOrder-independent
operator.add on listNoYesNoNo
add_messagesNoPartialWith caller-set idsNo
operator.or_ on setYesYesYesYes
operator.or_ on dictNoYesYesNo
max / min as a named wrapperYesYesYesYes

Two cells need their footnotes, because both are places I would have got this wrong.

add_messages is only partially associative. On the append and id-replace paths it holds. RemoveMessage breaks it, and REMOVE_ALL_MESSAGES breaks it hard. With A=[m1], B=[m2], C=[RemoveMessage(REMOVE_ALL_MESSAGES), m3], I get ['m3'] grouping left and ['m1', 'm3'] grouping right. Removing an id that is not present raises ValueError outright, so one grouping can raise where the other returns. Idempotence needs caller-assigned stable ids, because add_messages mints a fresh UUID for any message that arrives without one.

operator.or_ is the trap in this table. It is commutative on set and not commutative on dict, where | is right-wins. Commutativity is a property of the function and its operand type, never of the function alone. That distinction comes back to bite the audit tool at the end of this article.

operator.add is where the reasoning goes wrong, and it goes wrong for an understandable reason. Addition is the textbook example of a commutative operation. operator.add is named after it. But the operation applied to your state is not addition, it is list concatenation, and concatenation is associative without being commutative. [1] + [2] and [2] + [1] are different lists. The name carries an intuition that the behaviour does not honour, and nothing in the type, the annotation, or the error page that recommended it will correct you.

Test it rather than trusting either of us:

python
def commutes(fn, a, b) -> bool:    return fn(a, b) == fn(b, a)def test_evidence_reducer_is_order_coupled():    a, b = [{"source": "kb"}], [{"source": "tickets"}]    assert not commutes(operator.add, a, b)

Note the shape. The assertion documents the hazard and passes, so it belongs in a suite. A test named ..._is_commutative that asserts the opposite is a permanently red build and somebody will delete it.

The move worth making is to run commutes over every reducer in your schema and assert that the resulting hazard set matches an explicit allowlist. That test goes red the day somebody adds an order-coupled key, which is the day you want to hear about it.

Why add_messages order decides which message wins

add_messages is worse than it looks, because its dedupe path is order-sensitive too. When two parallel branches emit messages carrying the same id, the message from the later-sorting node wins the content. I ran this to be sure:

text
id collision across parallel branches (both write id='dup'):  survivors: [('dup', 'from verify')]

Because the dedupe path replaces by id in fold order, whichever writer sorts later keeps the content:

d2
direction: down
classes: {
  w: {style: {fill: "#98D8C8"; stroke: "#5FA898"; font-color: "#2C2C2A"}}
}
analyze: "analyze\nAIMessage(id='dup', 'from analyze')" {class: w}
verify: "verify\nAIMessage(id='dup', 'from verify')" {class: w}
fold: "add_messages folds analyze, then verify\n(a sorts before v)" {style: {fill: "#7B68EE"; stroke: "#5A4BC4"; font-color: "#FFFFFF"}}
out: "survivor: ('dup', 'from verify')\nanalyze's content is replaced" {style: {fill: "#E74C3C"; stroke: "#B03A2E"; font-color: "#FFFFFF"}}
analyze -> fold: "1st"
verify -> fold: "2nd"
fold -> out

analyze and verify both wrote a message with id='dup'. verify won. Rename it to alpha and analyze wins instead. That id-keyed path is also the one RemoveMessage travels, and what it deletes from state stays in every checkpoint on disk.

What LangGraph's Mermaid diagram shows, and what it hides

On the left is what draw_mermaid() gives you for Atlas. On the right is the same program's write relation, which nothing draws:

d2
grid-rows: 1
grid-gap: 40
classes: {
  box: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"}; label.near: top-center}
  main: {style: {fill: "#4A90E2"; stroke: "#2C6FB0"; font-color: "#FFFFFF"}}
  ret: {style: {fill: "#98D8C8"; stroke: "#5FA898"; font-color: "#2C2C2A"}}
}
shown: "draw_mermaid(): transitions" {
  class: box
  triage: "triage" {class: main}
  kb: "search_kb" {class: ret}
  tk: "search_tickets" {class: ret}
  docs: "search_docs" {class: ret}
  answer: "answer" {class: main}
  triage -> kb
  triage -> tk
  triage -> docs
  kb -> answer
  tk -> answer
  docs -> answer
}
hidden: "Not drawn: writes" {
  class: box
  kb: "search_kb" {class: ret}
  tk: "search_tickets" {class: ret}
  docs: "search_docs" {class: ret}
  m: "evidence\noperator.add\nfold by node name" {style: {fill: "#7B68EE"; stroke: "#5A4BC4"; font-color: "#FFFFFF"}}
  v1: "search_docs:\ntop of prompt" {style: {fill: "#6BCF7F"; stroke: "#3F9E52"; font-color: "#2C2C2A"}}
  v2: "search_papers:\nmiddle, U-curve dip" {style: {fill: "#E74C3C"; stroke: "#B03A2E"; font-color: "#FFFFFF"}}
  kb -> m
  tk -> m
  docs -> m
  m -> v1
  m -> v2
}

The right graph is the same program. Nothing in the toolchain draws it. The purple node is a policy decision - which merge semantics this key gets - written as annotation metadata and never surfaced. The two nodes below it are the same graph, before and after a one-word rename, and the left panel cannot tell them apart.

How to fix order-coupled state in LangGraph

1. Use a commutative reducer

If the merge genuinely does not care about order, say so in code and the problem disappears:

python
def keep_max(a: float, b: float) -> float:    return max(a, b)# A set union does not care who wrote first.seen_sources: Annotated[NotRequired[set[str]], operator.or_]# Neither does a max - but wrap it, do not pass the builtin.highest_confidence: Annotated[NotRequired[float], keep_max]

Fold the same two writes in both orders and the difference between these reducers and operator.add is plain:

d2
grid-rows: 4
grid-columns: 3
grid-gap: 8
classes: {
  head: {style: {fill: "#95A5A6"; stroke: "#6F7F80"; font-color: "#2C2C2A"; bold: true}}
  label: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"; bold: true}}
  same: {style: {fill: "#6BCF7F"; stroke: "#3F9E52"; font-color: "#2C2C2A"}}
  diff: {style: {fill: "#E74C3C"; stroke: "#B03A2E"; font-color: "#FFFFFF"}}
}
h0: "Reducer" {class: head}
h1: "kb first, then tickets" {class: head}
h2: "tickets first, then kb" {class: head}
l1: "operator.add on list" {class: label}
a1: "['kb', 'tickets']" {class: diff}
b1: "['tickets', 'kb']" {class: diff}
l2: "operator.or_ on set" {class: label}
a2: "{'kb', 'tickets'}" {class: same}
b2: "{'kb', 'tickets'}" {class: same}
l3: "keep_max on 0.4 and 0.9" {class: label}
a3: "0.9" {class: same}
b3: "0.9" {class: same}

The wrapper is not stylistic. Annotated[NotRequired[float], max] raises ValueError: no signature found for builtin <built-in function max> when you construct the graph, because _is_field_binop calls inspect.signature to check the reducer takes two positional arguments and the builtins do not expose one. min fails the same way. A named function also gives print_merge_policy something readable to report, and it survives pickling for a checkpointer.

One caveat on the set: a set survives LangGraph's default serialisation but not a JSON one, and it will not stream to a browser client as-is.

This is the only fix that removes Order-Coupled State rather than managing it. Reach for it first, and notice how often the accumulator you reached for a list to build did not actually need a sequence.

2. Carry the ordering key in the data

When order matters, make it depend on something meaningful and sort at the point of use. This is what the documentation recommends, and it is right:

python
class Evidence(TypedDict):    source: str    text: str    rank: float          # the ordering that matters; make_retriever must emit itdef answer(state: AtlasState) -> dict:    # Part 1's render_context, now handed evidence in a defined order    # instead of reading it off state in whatever order it merged.    evidence = sorted(state.get("evidence", []), key=lambda e: -e["rank"])    context = SystemMessage(content=render_context(state, evidence))    return {"messages": [model.invoke([context, *state["messages"]])]}

Fold order is still name order. What changes is that answer re-sorts before anything reaches the prompt:

d2
direction: down
classes: {
  ret: {style: {fill: "#98D8C8"; stroke: "#5FA898"; font-color: "#2C2C2A"}}
}
kb: "search_kb\nemits rank" {class: ret}
tk: "search_tickets\nemits rank" {class: ret}
docs: "search_docs\nemits rank" {class: ret}
ev: "evidence via operator.add\nstill in node-name order" {style: {fill: "#7B68EE"; stroke: "#5A4BC4"; font-color: "#FFFFFF"}}
srt: "answer: sorted(key=-rank)" {style: {fill: "#4A90E2"; stroke: "#2C6FB0"; font-color: "#FFFFFF"}}
prompt: "prompt order = relevance" {style: {fill: "#6BCF7F"; stroke: "#3F9E52"; font-color: "#2C2C2A"}}
kb -> ev
tk -> ev
docs -> ev
ev -> srt: "fold order ignored"
srt -> prompt

The reducer stays non-commutative. It no longer matters, because nothing downstream reads the fold order. The prompt order is now a function of relevance, which is a decision someone made, rather than of a node name, which is not.

It also gives you something to assert on. You can write ranks = [e["rank"] for e in evidence] and then assert ranks == sorted(ranks, reverse=True). There is no test you can write against "whatever order it merged in".

3. Give each writer its own key

When two nodes write the same key for no better reason than that they both produce output, stop sharing:

python
kb_hits: NotRequired[list[Evidence]]ticket_hits: NotRequired[list[Evidence]]doc_hits: NotRequired[list[Evidence]]

Each retriever gets a key of its own, and answer is the one place they meet:

d2
direction: down
classes: {
  ret: {style: {fill: "#98D8C8"; stroke: "#5FA898"; font-color: "#2C2C2A"}}
  key: {style: {fill: "#4A90E2"; stroke: "#2C6FB0"; font-color: "#FFFFFF"}}
}
kb: "search_kb" {class: ret}
tk: "search_tickets" {class: ret}
docs: "search_docs" {class: ret}
k1: "kb_hits\n(LastValue)" {class: key}
k2: "ticket_hits\n(LastValue)" {class: key}
k3: "doc_hits\n(LastValue)" {class: key}
answer: "answer\nassembles in readable code" {style: {fill: "#6BCF7F"; stroke: "#3F9E52"; font-color: "#2C2C2A"}}
kb -> k1
tk -> k2
docs -> k3
k1 -> answer
k2 -> answer
k3 -> answer

No reducer, no merge, no order. Each key has one writer node, which removes the fan-out and Command shapes by construction rather than by policy. It holds only if nodes return just the keys they own. In langgraph issue #2336, a retry loop on one branch kept a node running into the superstep where a sibling branch's fan-in node ran, and that fan-in node returned its whole input state, so it became a second writer of the retrying node's key. A node that returns state writes every key, so it is worth checking for separately. The assembly happens in answer, in ordinary readable code, where a reviewer can see it.

This is the least fashionable option and often the correct one. Nobody enjoys a state schema with three near-identical keys in it, and I would still take it over a shared accumulator, because a write relation you can state in a sentence is a write relation somebody will read.

Nine more LangGraph write-relation traps

Nine more things sit in this blind spot. Each is small on its own, and most have produced real issues.

Metadata order silently deletes your reducer. _is_field_binop inspects only the last item in Annotated[...]. Put anything non-callable after the reducer and the key silently becomes a plain last-value channel:

python
# The reducer is gone. No error at build time.evidence: Annotated[list[Evidence], operator.add, FieldDoc("retrieved hits")]

I confirmed this on langgraph 1.2.22: the channel comes back as LastValue, StateGraph() constructs without complaint, and the failure surfaces later as InvalidUpdateError, only under concurrency, only on the branch that happens to fan out. A wrong-arity reducer, by contrast, raises ValueError: Invalid reducer signature. Expected (a, b) -> c. Got (a, b, c=None) at construction. I checked both on 1.2.22. One of these two mistakes is caught at construction and the other is not.

Command does not suppress a static edge. The Graph API overview states it plainly - "Command adds dynamic edges. Static edges from the same node still run." - and the consequence is a concurrent write you did not plan:

python
def router(state) -> Command[Literal["target"]]:    return Command(goto="target", update={"log": ["router"]})builder.add_edge(START, "router")builder.add_edge("router", "static_dest")   # still live
text
{'log': ['router', 'static_dest', 'target']}

router routed to target and static_dest ran anyway. If both destinations write the same key, you get an InvalidUpdateError from a branch you thought you had routed away from.

Send hides cardinality, not destination. Part 1 argued that Send preserves which nodes run and destroys how many. That holds. Here is the actual rendering of a map-reduce fan-out:

text
---config:  flowchart:    curve: linear---graph TD;	__start__([<p>__start__</p>]):::first	plan(plan)	research(research)	__end__([<p>__end__</p>]):::last	__start__ --> plan;	plan -.-> research;	research --> __end__;	classDef default fill:#f2f0ff,line-height:1.2	classDef first fill-opacity:0	classDef last fill:#bfb6fc

One dotted edge. I ran that graph with three workers and with three hundred, and the picture is byte-identical - only the number of results changes. Since every worker's writes fold through the same reducer, in Send-list order, the drawn graph tells you neither how many values that key is about to receive nor in what order. Part 6 measures how wide that fan-out can get, and what happens when nothing in the runtime bounds it.

A shared-schema subgraph writes straight into the parent's channels. Pass a compiled subgraph to add_node() with overlapping keys and it reads and writes the parent's channels directly, so its writes go through the parent's reducers. The whole subgraph contributes as one task, sorted under the parent node's name rather than its internal node names, which means the sort rule composes across levels but does not see inside. When the schemas do not overlap you wrap it in a function that translates in and out, and only what that wrapper returns merges. The docs are explicit about the wrapper case and silent on the merge mechanics of the shared case, so I am reporting that one from the channel behaviour rather than from a documented contract.

A key with no reducer is not automatically safe. The hard error only fires for two writes in one superstep. Across supersteps a bare LastValue key takes silent last-write-wins, so two nodes at different depths both writing ticket_id will never raise and the second one simply wins. The loud failure that opens this article is the best case: the same mistake one superstep apart is silent. That is the same class of hazard as resuming into state that no longer holds - wrong quietly, and only visible if you went looking. Part 8 measures the same shape with no reducer at all: two threads writing one key in a shared BaseStore leave one survivor, with no error and no version on the item to show that a write was lost. Chapter 5 of my book, "State Design and Reducers," works through the cyclic form of this: a loop back to retrieval where each pass lands in its own superstep, so a key with no reducer overwrites the documents the previous pass found and the answer degrades without an error.

Overwrite lets one writer erase its siblings. Overwrite(value) bypasses the reducer for that write, and in a parallel step it wins outright. Three nodes, a_first, b_mid and c_last, append to a log key seeded with ["seed"], and one of them returns an Overwrite instead:

text
overwrite by a_first -> ['a_first']overwrite by b_mid   -> ['b_mid']overwrite by c_last  -> ['c_last']

Wherever the overwriting node sorts, the seed and every sibling write are gone: writes folded before it are replaced, and writes after it are skipped. A second Overwrite on the same key in the same step raises InvalidUpdateError. So the annotation is the key's default policy, and any node's return value can override it for one step. Nothing in the schema shows which nodes do. Chapter 6, "Conditional Edges and Dynamic Control Flow," uses Overwrite([]) deliberately, to empty an accumulating key at the start of each question from a node that runs alone in its superstep, which is the condition that keeps it from erasing a sibling.

An error_handler= node is a writer you did not wire. Since langgraph 1.2, add_node(..., error_handler=fn) runs fn when the node raises, and whatever fn returns is a state update. On 1.2.22 the handler's writes land in the same superstep as the failed node's siblings and fold in the failed node's sort position, so a retriever that fails can still contribute to evidence, through a function that appears on no edge.

Deferred nodes are a mitigation, not a fix. add_node(..., defer=True) delays a fan-in node until no tasks are pending anywhere in the graph, which helps with uneven branch lengths. It does not make your reducer commutative, and it is a scheduling hint, not a barrier: in langgraph issue #6005, closed 2025-09-10 as working as designed, a maintainer explained that a deferred node can be postponed across many supersteps in a graph that keeps producing work, and agreed the deferred-node docs needed work.

Separate edges into a fan-in node run it once per arriving branch. Issue #4026 (closed 2025-03-26, the day it was opened) is the wiring trap. With a branch a -> b_1 -> b_2 beside a -> c, two separate edges add_edge("b_2", "d") and add_edge("c", "d") make d run in every superstep where a branch arrives. A list edge waits for both:

text
separate edges: ['a', 'b_1', 'c', 'b_2', 'd', 'd']list join     : ['a', 'b_1', 'c', 'b_2', 'd']

Laid out by superstep, the extra run is the d that fires as soon as c arrives:

d2
grid-rows: 3
grid-columns: 5
grid-gap: 8
classes: {
  head: {style: {fill: "#95A5A6"; stroke: "#6F7F80"; font-color: "#2C2C2A"; bold: true}}
  label: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"; bold: true}}
  run: {style: {fill: "#98D8C8"; stroke: "#5FA898"; font-color: "#2C2C2A"}}
  dup: {style: {fill: "#E74C3C"; stroke: "#B03A2E"; font-color: "#FFFFFF"}}
  once: {style: {fill: "#6BCF7F"; stroke: "#3F9E52"; font-color: "#2C2C2A"}}
}
h0: "superstep" {class: head}
h1: "1" {class: head}
h2: "2" {class: head}
h3: "3" {class: head}
h4: "4" {class: head}
l1: "separate edges" {class: label}
s1: "a" {class: run}
s2: "b_1, c" {class: run}
s3: "b_2 + d\n(c arrived)" {class: dup}
s4: "d again\n(b_2 arrived)" {class: dup}
l2: "list join or defer=True" {class: label}
j1: "a" {class: run}
j2: "b_1, c" {class: run}
j3: "b_2" {class: run}
j4: "d, once" {class: once}

add_edge(["b_2", "c"], "d") runs d once, and so does keeping the separate edges with defer=True on d. A maintainer called the double run expected, and the current docs now spell out the difference. log recorded d twice because d ran twice.

That last one is worth stating as a general property. A reducer records what happened. If a node runs twice, an accumulating reducer produces two entries, and the state is a truthful record of a wiring mistake (or a retry). operator.add is not idempotent, so it cannot absorb a duplicate execution the way a set union or a keyed map would.

How to audit which node writes which state key

Part 1 ended with a printed upper bound on the transition relation. Part 2 cannot end with the equivalent for writes. Half of it is recoverable statically and half of it is not, and the split is where you have to put your testing effort.

The declared merge policy is fully recoverable statically. Reducers live in Annotated metadata, and both the standard library and LangGraph itself will hand them to you. This runs against a compiled graph and needs no execution:

python
from langgraph.channels.delta import DeltaChannel      # langgraph >= 1.2from langgraph.channels.last_value import LastValuedef print_merge_policy(compiled, samples) -> None:    """Static audit of every state key's concurrency policy.    samples maps a key to two example values of its declared type, used to    test commutativity directly instead of guessing from the reducer's name.    commutes() is the helper defined with the reducer test above.    """    for key, channel in compiled.builder.channels.items():        # DeltaChannel exposes .reducer; BinaryOperatorAggregate exposes .operator.        fn = getattr(channel, "operator", None) or getattr(channel, "reducer", None)        pair = samples.get(key)        if fn is None:            if isinstance(channel, LastValue):                policy, verdict = "none (last value)", "concurrent write is a hard error"            else:                # Topic, EphemeralValue, AnyValue, UntrackedValue, managed values.                policy, verdict = "-", "unknown channel type - inspect manually"        else:            policy = f"{fn.__module__.rsplit('.', 1)[-1]}.{fn.__name__}"            if isinstance(channel, DeltaChannel):                verdict = "batch reducer - check commutativity by hand"            elif pair is None:                verdict = "reducer present - NO SAMPLE, commutativity unchecked"            elif commutes(fn, *pair):                verdict = "commutative on sampled values - order independent"            else:                verdict = "ORDER-COUPLED - value depends on fold order"        print(f"{key:<18} {type(channel).__name__:<23} {policy}")        print(f"{'':<18} -> {verdict}")

The DeltaChannel branch is not defensive padding. A batch reducer has the signature reducer(state, writes: list) -> state, not (a, b) -> c, so a binary commutativity probe does not typecheck against it. Hand deepagents' _file_data_delta_reducer two plain dicts and it iterates one of them as if it were a list of write batches and calls .items() on a string. That is an AttributeError in the middle of your audit, on the exact key this branch exists to catch.

Two things in that function are the whole point of writing it carefully.

It tests commutativity rather than looking the reducer up in an allowlist of trusted names. My first version carried COMMUTATIVE = {"builtins.max", ..., "_operator.or_"} and it was wrong, for the reason the table above already gave: operator.or_ is commutative on set and right-wins on dict. A name-keyed allowlist would have stamped Annotated[dict[str, X], operator.or_] as order independent, which is the exact defect this article exists to find. Commutativity belongs to the function and its operand type, so the only honest check runs the function.

And it branches on channel class rather than on whether .operator happens to exist. DeltaChannel exposes .reducer, so an attribute probe returns None and the key gets reported as a hard-error channel - the safest-sounding verdict, on a key that has a reducer and does not raise. deepagents 0.7.38 ships files as DeltaChannel(_file_data_delta_reducer, snapshot_frequency=50), whose reducer is last-write-wins per filename, which makes it the most order-coupled key in that schema. A tool that silently defaults the channels it does not recognise to "safe" is the failure mode this article is about, and I wrote it that way on the first pass.

On Atlas, with two commutative keys added from the fixes above:

text
customer_id        LastValue               none (last value)                   -> concurrent write is a hard errormessages           BinaryOperatorAggregate message._add_messages                   -> ORDER-COUPLED - value depends on fold orderintent             LastValue               none (last value)                   -> concurrent write is a hard errorticket_id          LastValue               none (last value)                   -> concurrent write is a hard errorrefund_cents       LastValue               none (last value)                   -> concurrent write is a hard errorrefund_allowed     LastValue               none (last value)                   -> concurrent write is a hard errorreceipt_id         LastValue               none (last value)                   -> concurrent write is a hard errorevidence           BinaryOperatorAggregate _operator.add                   -> ORDER-COUPLED - value depends on fold orderseen_sources       BinaryOperatorAggregate _operator.or_                   -> commutative on sampled values - order independenthighest_confidence BinaryOperatorAggregate __main__.keep_max                   -> commutative on sampled values - order independent

Each key prints on two lines: its channel class and reducer, then the verdict. The reducer is reported as the last segment of its module plus its name, which keeps every line readable.

builder.channels is not a documented surface either. I am using it for the same reason everyone ends up relying on the sort order - it is real and it is convenient - which is this article's own argument turned back on itself. get_type_hints(AtlasState, include_extras=True) is the standard-library route, it is what _get_channels uses internally, and it is the one to reach for if you want this artifact to outlive a minor version.

"Commutative on sampled values" is doing honest work in that phrasing, and the first time I ran this it caught me. I passed ([], []) as the sample for messages, two empty lists commute trivially, and the tool cheerfully reported messages as order independent. A sampled property test is only as good as its sample. Use values that actually collide - two non-empty lists, two messages with ids - and treat a key with no sample as unchecked rather than as safe, which is why the function reports it that way.

That table is a review artifact. It needs no run, and the channel and reducer columns are complete and deterministic - which is enough to catch the silent metadata trap, where a key you believe has a reducer shows up as LastValue. The commutativity column is only as complete as your samples, which is exactly why an unsampled key reports as unchecked rather than as safe. And the table reports the declared policy, not every write: a node that returns Overwrite bypasses the reducer for that step, so grep for Overwrite alongside it. Put it in a test and assert on it.

Which node writes which key is not statically recoverable, and I will not pretend otherwise. StateNodeSpec carries input_schema, retry_policy, cache_policy, ends, defer, timeout, trace_policy and error-handler wiring. There is still no output schema. Node functions return arbitrary dictionaries, return annotations are optional and read only for the Command[Literal[...]] control-flow case, and static analysis of return {...} breaks on conditional returns, dict spreads and helper functions. Anyone promising you a static write-relation printer is promising something the API does not support.

What you can do is observe it. stream_mode="updates" emits one chunk per node per step, and the documentation confirms that "multiple updates in the same step are streamed separately," so parallel nodes stay attributable:

python
from collections import defaultdictdef record_write_relation(compiled, inputs, config=None) -> dict[str, set[str]]:    """Runtime observation. Coverage-bounded: only sees paths this run took."""    writes: dict[str, set[str]] = defaultdict(set)    for ns, chunk in compiled.stream(inputs, config=config,                                     stream_mode="updates", subgraphs=True):        prefix = "/".join(part.split(":")[0] for part in ns)        for node, update in chunk.items():            if isinstance(update, dict):                writes[f"{prefix}/{node}" if prefix else node].update(update.keys())    return dict(writes)

This relies on the default v1 output shape, a (namespace, chunk) tuple per update. Under version="v2" each item is a StreamPart dict instead, so read part["ns"] and part["data"].

subgraphs=True is not optional. Without it, a subgraph's internal nodes never appear and its writes surface under the parent wrapper node's name, so the tool reports attribution that is wrong rather than merely incomplete. Since create_agent embeds as a subgraph, leaving it off degrades exactly the shape you are most likely to have. Two smaller things: pass a config with a thread_id if the graph was compiled with a checkpointer, and know that an interrupt() ends the stream and hands back a partial relation.

Run it against a build with your side-effecting clients stubbed. This executes the graph, and Part 1's Atlas has a node that calls billing.refund(). The write relation is a property of what nodes return, so stubs do not distort it as long as they still exercise the same branches.

Union the results across your evaluation corpus and you have node to keys. Then cross it with the static table. For every key whose reducer is not commutative, list the nodes observed writing it. Then check whether two of them can be co-active in one superstep. That intersection is the review surface that does not currently exist anywhere.

Each half feeds it from a different direction, with a different guarantee:

d2
direction: down
classes: {
  box: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"}; label.near: top-center}
  tool: {style: {fill: "#4A90E2"; stroke: "#2C6FB0"; font-color: "#FFFFFF"}}
  stat: {style: {fill: "#6BCF7F"; stroke: "#3F9E52"; font-color: "#2C2C2A"}}
  run: {style: {fill: "#FFD93D"; stroke: "#C9A800"; font-color: "#2C2C2A"}}
}
static: "Static: no run" {
  class: box
  p: "print_merge_policy\ncompiled.builder.channels" {class: tool}
  t: "key -> reducer -> verdict\ncomplete for the declared policy" {class: stat}
  p -> t
}
runtime: "Runtime: needs a corpus" {
  class: box
  r: "record_write_relation\nstream_mode='updates', subgraphs=True" {class: tool}
  w: "node -> keys written\nonly the paths your corpus took" {class: run}
  r -> w
}
review: "Review surface:\norder-coupled keys x writers that can be\nco-active in one superstep" {style: {fill: "#7B68EE"; stroke: "#5A4BC4"; font-color: "#FFFFFF"}}
static.t -> review
runtime.w -> review

This is the under-approximation I promised at the start, and its limit is not a detail to skip past. An upper bound on control flow can justify a safety claim: the diagram says a transition cannot happen, so it cannot. A lower bound on writes can never justify one. It reports hazards it has already seen, and stays silent about the branch your corpus never took. Do not let a clean write-relation report be read as a clean bill of health. It is a coverage statement about your tests, printed in the shape of a fact about your graph.

That is the honest summary of where LangGraph is today. Control flow became data and got an artifact. State merging is still code in an annotation, and getting a picture of it costs you a test corpus.

A five-question LangGraph state audit

Run this against any graph with more than one edge into a node.

  1. Which keys have a reducer? Print the merge policy table. Any key you believed had one and does not is a latent InvalidUpdateError.
  2. For each reducer, is it commutative? Run commutes(fn, a, b) from above, on values that actually collide. Every key that fails is an order-coupled hazard. Questions 3 and 4 are what decide whether the hazard is a defect.
  3. For each order-coupled key, does anything downstream read the order? A list rendered into a prompt does. A list you take len() of does not. If the order reaches the model, position bias makes it a correctness question.
  4. Can two nodes write that key in the same superstep? Five shapes qualify: fan-out from a shared predecessor, Send fan-out, a static edge surviving a Command(goto=...), a retry loop on one branch that overlaps a sibling branch's downstream node (langgraph issue #2336), and an error_handler= node standing in for a failed parallel node.
  5. Is any fold order derived from model output? A Send list built from a structured model response makes the order vary run to run. This is the case that will not reproduce on your machine.

Read the questions as a funnel. Where a key leaves it decides what you do with it:

d2
grid-rows: 5
grid-columns: 2
grid-gap: 26
classes: {
  q: {style: {fill: "#7B68EE"; stroke: "#5A4BC4"; font-color: "#FFFFFF"}}
  ok: {style: {fill: "#6BCF7F"; stroke: "#3F9E52"; font-color: "#2C2C2A"}}
  hz: {style: {fill: "#FFD93D"; stroke: "#C9A800"; font-color: "#2C2C2A"}}
  bad: {style: {fill: "#E74C3C"; stroke: "#B03A2E"; font-color: "#FFFFFF"}}
}
q1: "1. Does every key you think\nhas a reducer have one?" {class: q}
a1: "If not: latent InvalidUpdateError" {class: hz}
q2: "2. Does the reducer fail\ncommutes() on colliding values?" {class: q}
a2: "If not: order independent, stop" {class: ok}
q3: "3. Does anything downstream\nread the order?" {class: q}
a3: "If not: hazard, add it to the allowlist" {class: hz}
q4: "4. Can two writers be co-active\nin one superstep?" {class: q}
a4: "If yes: live defect,\nwrite the rename test" {class: bad}
q5: "5. Is the fold order derived\nfrom model output?" {class: q}
a5: "If yes: it varies run to run" {class: bad}
q1 -> q2
q2 -> q3
q3 -> q4
q4 -> q5

If questions 2, 3 and 4 are all "yes" for the same key, you have a live defect and no test currently covers it, so write one that renames the writer nodes. If only 2 is yes, you have a hazard worth an allowlist entry so that somebody notices the day 3 or 4 becomes true.

What these fixes cost

The fixes are not free and pretending otherwise would be the same mistake as pretending the reducer is plumbing.

A commutative reducer costs you sequence: a set loses duplicates and ordering, and max collapses everything to one value.

Splitting into per-writer keys costs you a bigger schema and moves assembly into a node body. That is survivable, because assembly is a pure function over state rather than control flow, and it unit-tests the way a routing decision buried in a loop never did.

The ordering key is the expensive one, and I glossed it above. A rank field assumes your retrievers emit comparable scores. They do not. A vector index gives you cosine similarity in roughly 0 to 1, clustered high and hard to separate at the top. A keyword index gives you BM25, which is unbounded and scaled by corpus statistics that shift as the corpus does. A ticket API sorts by recency and gives you no score at all, so you invent one. Normalising those onto a single axis is a modelling decision, and picking it badly reintroduces the exact defect you were fixing - a prompt order that has nothing to do with relevance. You will get the normalisation wrong at least once. The difference is that a bad normalisation shows up in a diff and somebody can argue with it, which is more than a sorting before v ever gave you.

And the audit itself costs a corpus. The runtime half of the artifact is only as good as the paths you exercise, which means the write relation is one more thing your evaluation suite is now responsible for covering.

Put the four costs in one place and the choice is visible:

d2
grid-rows: 5
grid-columns: 3
grid-gap: 8
classes: {
  head: {style: {fill: "#95A5A6"; stroke: "#6F7F80"; font-color: "#2C2C2A"; bold: true}}
  label: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"; bold: true}}
  gain: {style: {fill: "#6BCF7F"; stroke: "#3F9E52"; font-color: "#2C2C2A"}}
  cost: {style: {fill: "#FFA07A"; stroke: "#D9785A"; font-color: "#2C2C2A"}}
}
h0: "Choice" {class: head}
h1: "What it buys" {class: head}
h2: "What it costs" {class: head}
l1: "Commutative reducer" {class: label}
g1: "removes the hazard" {class: gain}
c1: "sequence: a set drops order and\nduplicates, max keeps one value" {class: cost}
l2: "Per-writer keys" {class: label}
g2: "no shared writers" {class: gain}
c2: "a bigger schema, assembly\nin a node body" {class: cost}
l3: "Ordering key (rank)" {class: label}
g3: "order from relevance,\nnot names" {class: gain}
c3: "normalising cosine, BM25\nand recency onto one axis" {class: cost}
l4: "Write-relation audit" {class: label}
g4: "the review surface" {class: gain}
c4: "an evaluation corpus\nthat covers the paths" {class: cost}

None of that changes the recommendation. It does mean you are choosing which cost to pay, and a reviewer should get to see which one you chose.

Specified or inherited, again

Part 1 asked one question about control flow: is the constraint a property of your system, or a hope about the model's behaviour. The demarcation was whether the constraint holds regardless of whether the model complies.

The same question applies to state, and most graphs currently fail it. The merge policy for a key holds regardless of the model, which is good. But it is not a decision anyone reviewed, it is not visible on any artifact, and its ordering is derived from identifiers chosen for readability. That is not a specified merge. It is an inherited one, arrived at by copying the line the error page suggested.

Apply that test to both halves of the graph:

d2
grid-rows: 1
grid-gap: 40
classes: {
  box: {style: {fill: "#FFFFFF"; stroke: "#95A5A6"; font-color: "#2C2C2A"}; label.near: top-center}
  src: {style: {fill: "#4A90E2"; stroke: "#2C6FB0"; font-color: "#FFFFFF"}}
}
flow: "Control flow" {
  class: box
  a: "edges you wrote" {class: src}
  b: "draw_mermaid()" {style: {fill: "#98D8C8"; stroke: "#5FA898"; font-color: "#2C2C2A"}}
  c: "reviewed: specified" {style: {fill: "#6BCF7F"; stroke: "#3F9E52"; font-color: "#2C2C2A"}}
  a -> b
  b -> c
}
merge: "State merging" {
  class: box
  a: "reducer copied from\nthe error page" {class: src}
  b: "no artifact" {style: {fill: "#95A5A6"; stroke: "#6F7F80"; font-color: "#2C2C2A"}}
  c: "unreviewed: inherited" {style: {fill: "#E74C3C"; stroke: "#B03A2E"; font-color: "#FFFFFF"}}
  a -> b
  b -> c
}

operator.add is a fine reducer. It is a terrible default, because it is the one the framework recommends at the exact moment you are least equipped to evaluate it - mid-crash, following a link, looking for the line that makes the red text stop.

Part 3 puts tools and middleware inside the agent loop, and both write state. Carry one question into it: for every key in your schema, who can write it, and what happens when two of them do? Right now you cannot answer that from any artifact. You can answer it from a table you print yourself, and that is enough to start.

Going deeper

  • Supersteps, and the merge step where node deltas become state: Chapter 4, "StateGraph, Nodes, and Edges"
  • Choosing a reducer per key, and writing a custom one: Chapter 5, "State Design and Reducers"
  • InvalidUpdateError versus the silent overwrite across supersteps: Chapter 5, "State Design and Reducers"
  • Command, conditional edges, and resetting a key with Overwrite: Chapter 6, "Conditional Edges and Dynamic Control Flow"
  • Bounding a retry loop with a counter in state: Chapter 6, "Conditional Edges and Dynamic Control Flow"

References

Verified against langgraph 1.2.22, langchain 1.5.0, langchain-core 1.8.1 and langgraph-checkpoint 4.3.2 on Python 3.13.9 (langchain 1.5 needs Python 3.11 or later) on 2026-11-16; every console output was re-run on those versions. Source references are to main at that date, and the deepagents references are to deepagents 0.7.38. DeltaChannel requires langgraph 1.2 or later and is beta.


Agentic AI

Follow for more technical deep dives on AI/ML systems, production engineering, and building real-world applications:


Books by Ranjan Kumar

Federated AI Agents cover

Federated AI Agents

Right-Sized AI cover

Right-Sized AI

Harness Engineering for Production AI Systems cover

Harness Engineering

The 7 GenAI Architectures cover

The 7 GenAI Architectures

Building Real-World Agentic AI Systems with LangGraph cover

Building Real-World Agentic AI Systems

The ChatML Handbook cover

The ChatML Handbook

The Chat Templates Handbook cover

The Chat Templates Handbook

Comments