Subgraph persistence and testing subgraphs

Topic 3 of 4 in Subgraphs & modular design23 min readAdvancedFree course

Overview

In the previous lesson, you learned how parent graphs communicate with subgraphs through shared state channels and explicit state transformations. Those techniques establish the interfaces between reusable graph components.

However, a production application must answer another important question: what happens to a subgraph’s internal state after it finishes executing?

Consider an enterprise customer support system containing several specialized components:

  • A billing assistant that remembers previous billing questions.
  • A technical support workflow that pauses for diagnostic information.
  • A classification component that categorizes incoming requests.
  • A refund workflow that requires human approval.
  • A knowledge retrieval component that searches documentation.

These components have different persistence requirements. Some need conversational memory, some require recoverable execution, and others should discard their working state immediately.

Giving every component permanent memory increases storage costs, complicates debugging, and creates unnecessary opportunities for stale information. Disabling persistence everywhere, on the other hand, makes long-running workflows difficult to recover.

LangGraph allows each subgraph to declare its own persistence behavior while participating in a larger checkpoint-enabled application.

In this lesson, you will learn to choose the appropriate persistence mode, inspect nested execution state, and test individual components without executing an entire agentic application.

Environment setup

Install the required packages in your Python environment.

Terminal
pip install -U "langgraph>=1.1,<2" "langchain>=1,<2" pytest

The examples deliberately use deterministic Python functions rather than live language models. This makes persistence behavior observable without API keys, network latency, model costs, or nondeterministic responses.

The APIs follow the LangGraph subgraph documentation and the LangGraph 1.x interface. Expected outputs are provided for local verification; the examples have not been runtime-tested in the authoring environment.

Three persistence modes

Understanding nested persistence

A checkpoint records graph execution state at a particular execution boundary. Depending on the checkpoint, it can contain state channel values, pending tasks, scheduling information, and metadata needed to continue execution.

When a compiled graph is embedded inside another graph, the child participates in nested execution. Although the parent sees the child as a node, the child can execute multiple internal steps.

Checkpointing makes it possible to preserve those internal steps independently of the parent’s execution progress.

Three concepts determine how this works:

  • Thread ID: Identifies a continuing execution history.
  • Checkpoint namespace: Distinguishes execution histories belonging to different nested graph components.
  • Checkpoint ID: Identifies a particular saved checkpoint within a history.

The namespace is especially important because multiple subgraphs may execute under the same thread ID without sharing their private state.

Conceptually, nested checkpoints belong to an execution hierarchy rather than a single flat dictionary.

The following diagram illustrates the relationship between a parent graph, its children, and checkpoint storage.

Three persistence modes diagram: START to Parent graph; Parent graph to Billing subgraph; Parent graph to Technical subgraph; Parent graph to Classification subgraph; Parent graph to Checkpoint store; Billing subgraph to Checkpoint store; Technical subgraph to Checkpoint store; Billing subgraph to END; Technical subgraph to END; Classification subgraph to END.

The classification component does not checkpoint its internal execution, whereas the billing and technical support components can use the parent’s checkpointing infrastructure.

Persistence mode comparison

The checkpointer argument supplied to the child graph’s compile() method controls its persistence behavior.

Feature Per-invocation Per-thread Stateless
Compilation setting None True False
Internal checkpointing Yes, inherited Yes, inherited No
Private state retained across calls No Yes No
Dynamic interrupts Supported Supported Not supported
Internal execution recovery Supported Supported Not supported
Nested state inspection Current invocation Accumulated state when accessible Unavailable
Repeated parallel child calls Supported Requires serialization or isolation Supported
Typical use Independent specialist tasks Stateful conversational agents Simple transformations

For the two checkpoint-enabled modes, the parent must supply a functioning checkpointer.

Mode 1: Per-invocation persistence

Per-invocation persistence is the default when compiling a subgraph.

Python
subgraph = builder.compile(checkpointer=None)

Omitting the argument has the same effect.

This mode creates an execution scope for each child invocation. Internal state can survive an interruption or recoverable failure during that invocation, but the next independent invocation does not automatically inherit the previous invocation’s private state.

Imagine a document analysis specialist that extracts information, checks its completeness, and requests human clarification when necessary.

The specialist needs durable execution while processing a particular document. It does not need to remember every document processed during previous requests.

Per-invocation persistence satisfies both requirements.

An important distinction is that resuming an interrupted invocation is not the same as starting another invocation. Resumption continues the logical execution already in progress.

Mode 2: Per-thread persistence

Per-thread persistence is enabled explicitly:

Python
subgraph = builder.compile(checkpointer=True)

The boolean value does not instantiate a checkpoint database. Instead, it requests persistent child execution state using the surrounding checkpoint infrastructure.

When the same named child runs again on the same parent thread, it can recover previously saved private state.

This is useful for assistants that progressively accumulate context, including billing assistants, research agents, troubleshooting specialists, and long-running case management workflows.

Persistence does not automatically turn every state field into a history. A normal state channel uses replacement semantics. To accumulate information, the node must explicitly preserve previous values or use an appropriate reducer.

For example, MessagesState uses message-aware merging, while an ordinary string field generally receives the latest value.

Per-thread persistence also introduces concurrency constraints. Multiple executions of the same persistent child within one thread and namespace can conflict. Serialize calls to that child or assign deliberately isolated graph identities.

Mode 3: Stateless persistence

Disable internal checkpointing explicitly with:

Python
subgraph = builder.compile(checkpointer=False)

The child still has working state while executing its nodes. The word stateless refers to persistence between executions, not the absence of graph state.

This mode is suitable for inexpensive calculations, normalization, deterministic validation, and other operations that can safely execute again.

The parent may still checkpoint its own state, including the completed child’s output. However, it cannot recover the child’s intermediate progress.

Note: A subgraph with checkpointer=False must not depend on interrupt() for human approval or input. Use per-invocation persistence when a temporary workflow must pause and resume.

Practical example: Comparing all three modes

The following complete program runs the same billing component under each persistence mode. The child maintains a private list of processed questions, while the parent receives only the question count.

Python
from typing import TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver

class ParentState(TypedDict):
    question: str
    count: int

class BillingState(ParentState):
    history: list[str]

def record_question(state: BillingState) -> dict:
    history = state.get("history", []) + [state["question"]]

    return {
        "history": history,
        "count": len(history),
    }

def build_billing(mode=None):
    builder = StateGraph(BillingState)
    builder.add_node("record", record_question)
    builder.add_edge(START, "record")
    builder.add_edge("record", END)

    return builder.compile(checkpointer=mode)

def build_parent(mode=None):
    builder = StateGraph(ParentState)
    builder.add_node("billing", build_billing(mode))
    builder.add_edge(START, "billing")
    builder.add_edge("billing", END)

    return builder.compile(checkpointer=InMemorySaver())

modes = [
    ("Per-invocation", None),
    ("Per-thread", True),
    ("Stateless", False),
]

for name, mode in modes:
    graph = build_parent(mode)

    config = {
        "configurable": {"thread_id": "customer-101"}
    }

    print(name)

    for question in [
        "Where is my invoice?",
        "When is payment due?",
        "Can I request a refund?",
    ]:
        result = graph.invoke(
            {"question": question},
            config,
        )

        print("Questions remembered:", result["count"])

    print()

Expected output:

Text
Per-invocation
Questions remembered: 1
Questions remembered: 1
Questions remembered: 1

Per-thread
Questions remembered: 1
Questions remembered: 2
Questions remembered: 3

Stateless
Questions remembered: 1
Questions remembered: 1
Questions remembered: 1

The private history field does not belong to ParentState. Therefore, the parent does not automatically pass that history into subsequent child invocations.

This distinction makes the experiment meaningful. If the parent stored and repeatedly supplied the history, even a stateless child could appear to remember previous interactions.

Although per-invocation and stateless modes produce identical counts, their recovery capabilities are fundamentally different.

Inspecting subgraph state

Why parent state alone is insufficient

Suppose a customer requests a refund, but the support application stops producing responses.

The parent checkpoint might indicate that execution is waiting at the refund subgraph. That information does not reveal whether the child is waiting for approval, calculating eligibility, or encountering an internal error.

Nested state inspection allows you to examine the child’s execution state without modifying its public interface.

The main API is:

Python
snapshot = graph.get_state(config, subgraphs=True)

A state snapshot exposes several useful attributes:

Attribute Purpose
values Saved state channel values
next Nodes scheduled to execute next
tasks Task information associated with execution
config Configuration identifying the checkpoint
metadata Additional execution information
created_at Checkpoint creation timestamp
parent_config Configuration of the preceding checkpoint

When nested state is discoverable, entries in tasks can contain child state snapshots.

Practical example: Inspecting an interrupted refund subgraph

This example calculates a refund amount, pauses inside the child graph for approval, inspects the saved internal state, and resumes execution.

Python
from typing import TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt

class SupportState(TypedDict):
    order_id: str
    status: str

class RefundState(SupportState):
    refund_amount: int

def calculate_refund(state: RefundState) -> dict:
    return {"refund_amount": 1200}

def request_approval(state: RefundState) -> dict:
    approved = interrupt({
        "order_id": state["order_id"],
        "amount": state["refund_amount"],
        "currency": "INR",
        "action": "approve_refund",
    })

    return {
        "status": "approved" if approved is True else "rejected"
    }

refund_builder = StateGraph(RefundState)
refund_builder.add_node("calculate", calculate_refund)
refund_builder.add_node("approval", request_approval)
refund_builder.add_edge(START, "calculate")
refund_builder.add_edge("calculate", "approval")
refund_builder.add_edge("approval", END)

refund_graph = refund_builder.compile()

parent_builder = StateGraph(SupportState)
parent_builder.add_node("refund", refund_graph)
parent_builder.add_edge(START, "refund")
parent_builder.add_edge("refund", END)

graph = parent_builder.compile(
    checkpointer=InMemorySaver()
)

config = {
    "configurable": {"thread_id": "refund-case-101"}
}

result = graph.invoke(
    {"order_id": "ORD-101", "status": "pending"},
    config,
)

print("Interrupt:", result["__interrupt__"][0].value)

snapshot = graph.get_state(config, subgraphs=True)

print("Parent next:", snapshot.next)

for task in snapshot.tasks:
    if task.name == "refund" and hasattr(task.state, "values"):
        child = task.state

        print("Child amount:", child.values["refund_amount"])
        print("Child next:", child.next)

final = graph.invoke(
    Command(resume=True),
    config,
)

print("Final status:", final["status"])
print("Parent finished:", not graph.get_state(config).next)

Expected output:

Text
Interrupt: {'order_id': 'ORD-101', 'amount': 1200, 'currency': 'INR', 'action': 'approve_refund'}
Parent next: ('refund',)
Child amount: 1200
Child next: ('approval',)
Final status: approved
Parent finished: True

The refund amount is available inside the child checkpoint even though it is not part of the parent’s public state.

The parent resumes using its original thread configuration. LangGraph routes the resume value to the interrupted nested execution.

Understanding inspection limitations

Inspect child state while the child has pending execution, such as during an interrupt or debugging breakpoint.

After a child completes, the latest parent snapshot may contain no corresponding pending task. Consequently, accessing snapshot.tasks[0].state unconditionally can raise an indexing error.

Per-thread persistence retains child state across calls, but it does not guarantee that completed children will always appear in the latest parent task list.

For historical investigation, examine saved parent snapshots:

Python
for snapshot in graph.get_state_history(config):
    print(snapshot.created_at, snapshot.next)

If you capture a nested snapshot’s configuration while inspecting it, that configuration identifies the relevant child checkpoint and can support subsequent targeted investigation.

Nested inspection also depends on LangGraph discovering the child graph. A registered subgraph node is straightforward to discover. A subagent hidden behind a tool or dynamic indirection may propagate interrupts correctly without exposing the same nested inspection interface.

When investigating execution activity, nested streaming can complement checkpoint inspection:

Python
for chunk in graph.stream(
    inputs,
    config,
    subgraphs=True,
    stream_mode="updates",
    version="v2",
):
    print(chunk["ns"], chunk["type"], chunk["data"])

Here, inputs represents a new request for the graph. The ns field identifies the execution scope responsible for each update.

Modular application architecture

Designing around business capabilities

A modular graph application should organize subgraphs around cohesive business responsibilities rather than arbitrary groups of nodes.

For enterprise customer support, a useful decomposition might be:

Component Responsibility Persistence
Request classifier Categorize incoming questions Stateless
Billing assistant Maintain billing conversation context Per-thread
Technical support Execute recoverable diagnostics Per-invocation
Refund workflow Request approval and process decisions Per-invocation
Knowledge retrieval Search reference material Stateless
Parent orchestrator Coordinate customer interaction Checkpoint-enabled

This design minimizes unnecessary persistence while maintaining recoverability where required.

The following architecture separates specialist workflows from coordination and infrastructure.

Modular application architecture diagram: START to Request router; Request router to Billing assistant; Request router to Technical support; Request router to Refund workflow; Request router to Knowledge retrieval; Billing assistant to Response composer; Technical support to Response composer; Refund workflow to Response composer; Knowledge retrieval to Response composer; Billing assistant to Checkpoint database.

Organizing the Python project

A maintainable application might use the following directory structure:

Text
customer_support/
├── app/
│   ├── __init__.py
│   ├── graph.py
│   ├── schemas.py
│   ├── context.py
│   ├── persistence.py
│   ├── subgraphs/
│   │   ├── __init__.py
│   │   ├── billing.py
│   │   ├── technical.py
│   │   ├── refunds.py
│   │   └── classification.py
│   └── services/
│       ├── billing_api.py
│       └── ticket_repository.py
├── tests/
│   ├── test_billing.py
│   ├── test_refunds.py
│   ├── test_classification.py
│   └── test_integration.py
├── requirements.txt
└── langgraph.json

Each subgraph module should expose a graph factory. Factories allow tests to substitute checkpoint backends and external dependencies without changing business logic.

Avoid compiling every graph into a global object with a permanently attached in-memory saver. Such objects can unintentionally share execution history across tests.

Stable namespaces and explicit contracts

Treat persistent subgraph names as part of your application’s durable execution architecture.

Registering children under distinct, stable node names helps separate their checkpoint histories. Renaming nodes or reordering nested calls can affect the relationship between previously saved state and the current graph structure.

For persistent child graphs, deployment changes should therefore include compatibility checks against existing threads.

Keep public state contracts small. A billing component might return a billing decision, confidence score, and escalation requirement rather than exposing every internal intermediate value.

Remember that a private schema is an architectural boundary, not a security boundary. Internal checkpoint contents still require appropriate access controls and retention policies.

Production persistence infrastructure

InMemorySaver is appropriate for local development and automated tests, but its contents do not survive process termination.

A self-hosted production application can use a database-backed checkpointer such as PostgresSaver.

Install the PostgreSQL checkpoint integration:

Terminal
pip install -U langgraph-checkpoint-postgres "psycopg[binary,pool]"

A typical lifecycle uses the following pattern:

Python
from langgraph.checkpoint.postgres import PostgresSaver

DB_URI = "postgresql://user:password@localhost:5432/support"

with PostgresSaver.from_conn_string(DB_URI) as saver:
    saver.setup()

    graph = parent_builder.compile(checkpointer=saver)

    result = graph.invoke(
        {"question": "Show my invoice"},
        {"configurable": {"thread_id": "support-case-101"}},
        durability="sync",
    )

In a real deployment, load database credentials from secure configuration and keep the checkpointer available throughout the application’s execution lifecycle.

Synchronous durability persists execution progress before advancing to subsequent steps. Asynchronous durability trades some crash-recovery guarantees for performance, while exit durability is suitable only when intermediate recovery is unnecessary.

Checkpointing also does not guarantee exactly-once external side effects. Payment operations, ticket creation, and outbound notifications require idempotency keys or transactional safeguards.

Store cross-thread customer preferences and durable business records in an appropriate store or application database rather than treating thread checkpoints as the authoritative customer database.

Testing individual subgraphs

Building a layered testing strategy

Testing an entire multi-agent application for every code change is expensive and makes failures difficult to isolate.

A better approach separates verification into four layers:

Test layer What it verifies
Node unit tests Individual business functions
Subgraph tests Internal workflow behavior
Persistence tests Recovery, memory, and isolation
Integration tests Parent-child communication

A subgraph should be invocable independently of its parent. When testing persistence in isolation, compile it with a concrete checkpointer rather than relying on inherited persistence.

Practical example: Testing a refund subgraph with pytest

Save the following complete example as test_refund.py. It verifies business logic, interruption behavior, approval decisions, and thread isolation without contacting any external services.

Python
from typing import TypedDict
from uuid import uuid4

import pytest

from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt

class RefundState(TypedDict):
    amount: int
    status: str

def validate(state: RefundState) -> dict:
    if state["amount"] <= 0:
        return {"status": "invalid"}

    return {"status": "eligible"}

def route(state: RefundState) -> str:
    if state["status"] == "invalid":
        return "finish"

    return "approval"

def approval(state: RefundState) -> dict:
    approved = interrupt({
        "amount": state["amount"],
        "action": "approve_refund",
    })

    return {
        "status": "approved" if approved is True else "rejected"
    }

def build_refund_graph(checkpointer=None):
    builder = StateGraph(RefundState)

    builder.add_node("validate", validate)
    builder.add_node("approval", approval)

    builder.add_edge(START, "validate")

    builder.add_conditional_edges(
        "validate",
        route,
        {
            "approval": "approval",
            "finish": END,
        },
    )

    builder.add_edge("approval", END)

    return builder.compile(checkpointer=checkpointer)

@pytest.fixture
def graph():
    return build_refund_graph(InMemorySaver())

@pytest.fixture
def config():
    return {
        "configurable": {"thread_id": str(uuid4())}
    }

def test_validation_node():
    assert validate({"amount": -100}) == {
        "status": "invalid"
    }

def test_invalid_refund(graph, config):
    result = graph.invoke({"amount": 0}, config)

    assert result["status"] == "invalid"
    assert not result.get("__interrupt__")

def test_approval_interrupt(graph, config):
    result = graph.invoke({"amount": 500}, config)

    assert len(result["__interrupt__"]) == 1

    payload = result["__interrupt__"][0].value

    assert payload["amount"] == 500
    assert payload["action"] == "approve_refund"

    snapshot = graph.get_state(config)

    assert snapshot.next == ("approval",)
    assert snapshot.values["status"] == "eligible"

@pytest.mark.parametrize(
    "decision,expected",
    [
        (True, "approved"),
        (False, "rejected"),
    ],
)
def test_resume(graph, config, decision, expected):
    graph.invoke({"amount": 500}, config)

    result = graph.invoke(
        Command(resume=decision),
        config,
    )

    assert result["status"] == expected
    assert not graph.get_state(config).next

def test_thread_isolation(graph):
    config_a = {
        "configurable": {"thread_id": "customer-a"}
    }

    config_b = {
        "configurable": {"thread_id": "customer-b"}
    }

    graph.invoke({"amount": 500}, config_a)
    graph.invoke({"amount": 900}, config_b)

    result_a = graph.invoke(
        Command(resume=True),
        config_a,
    )

    snapshot_b = graph.get_state(config_b)

    assert result_a["status"] == "approved"
    assert snapshot_b.values["amount"] == 900
    assert snapshot_b.values["status"] == "eligible"
    assert snapshot_b.next == ("approval",)

Run the tests:

Terminal
pytest -v test_refund.py

Expected result:

Text
6 passed

The parameterized resume test contributes two test cases, giving six cases in total.

These tests verify actual checkpoint behavior instead of merely checking whether Python functions return correctly formatted dictionaries.

Tip: Create a fresh graph, checkpointer, and thread ID for each independent test. Reuse them deliberately only when verifying persistence across calls.

Testing language-model-powered subgraphs

Real specialist agents often depend on language models, retrieval systems, and external tools.

Avoid making live model calls mandatory for ordinary unit tests. Inject deterministic fake responses through graph factories or service interfaces.

Verify structured decisions, tool arguments, routing outcomes, and state transitions rather than exact natural-language wording.

Maintain a separate evaluation suite for real-model behavior, including answer quality, tool selection, grounding, and robustness. LangSmith evaluations and trajectory evaluators complement deterministic tests; they do not replace them.

For production readiness, include integration tests using the actual checkpoint backend. In-memory tests cannot establish PostgreSQL recovery behavior, transaction handling, or concurrency reliability.

See the official LangGraph testing guide for additional graph-level and partial-execution testing patterns.

Common mistakes and production best practices

Mistake Correct approach
Compiling every child with True Enable persistent child memory only when required
Omitting the parent checkpointer Supply checkpoint infrastructure for nested persistence
Reusing test threads unintentionally Create isolated test fixtures
Expecting False to remove parent state Understand that it disables child checkpointing only
Passing parent history into a child during persistence tests Use private state to verify actual retention
Assuming completed children appear in pending tasks Inspect during interruption or investigate checkpoint history
Calling the same persistent child concurrently Serialize access or isolate execution namespaces
Performing irreversible actions before an interrupt Place approval first and make external actions idempotent
Treating checkpoints as permanent business records Maintain authoritative records in a dedicated database

One particularly important issue is interruption replay. When a node resumes after interrupt(), the node executes again from its beginning. If the child was invoked inside a parent wrapper node, that wrapper can also restart.

Any operation preceding the interrupt may therefore execute more than once. Keep such operations deterministic, read-only, or idempotent.

Production tests should simulate interrupted execution, process restarts, repeated requests, rejected approvals, backend failures, and concurrent activity. Also verify that one tenant cannot access another tenant’s thread merely by supplying its identifier.

A thread ID identifies execution history; it is not an authorization credential.

Preparing for the next lesson

In the next lesson, Project: a modular enterprise customer support system, you will combine the techniques developed throughout this chapter into a complete application.

The project will use explicit parent-child state contracts, specialist subgraphs, differentiated persistence policies, recoverable approval workflows, and independently testable business components.

The parent graph will coordinate the overall customer journey, while each specialist owns its internal workflow and declares its persistence requirements. This separation enables teams to develop, test, maintain, and deploy sophisticated agentic systems without turning the application into a single tightly coupled graph.

Exercise

Build a Persistent Billing Support Subgraph

Build a billing support subgraph that records customer questions and returns the number of questions it has processed. Support per-invocation, per-thread, and stateless persistence through a configurable graph factory. Integrate the subgraph into a parent support graph and write tests verifying memory retention, state isolation, and correct behavior across different threads.

Python
from typing import TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver


class SupportState(TypedDict):
    question: str
    question_count: int


class BillingState(SupportState):
    history: list[str]


def process_billing_question(state: BillingState) -> dict:
    # TODO: Append the current question to the private history.
    # TODO: Return the updated history and question count.
    raise NotImplementedError


def build_billing_subgraph(checkpointer=None):
    # TODO: Create and compile the billing graph.
    raise NotImplementedError


def build_support_graph(mode=None):
    # TODO: Register the billing subgraph as a parent node.
    # TODO: Compile the parent with InMemorySaver.
    raise NotImplementedError


def test_per_invocation():
    # TODO: Verify that history resets between invocations.
    pass


def test_per_thread():
    # TODO: Verify that history accumulates on the same thread.
    pass


def test_stateless():
    # TODO: Verify that the subgraph retains no history.
    pass


def test_thread_isolation():
    # TODO: Verify that different threads have independent history.
    pass

Summary

  • Per-invocation persistence preserves recoverable execution within a child invocation without retaining its private state across independent calls.
  • Per-thread persistence retains subgraph state across invocations associated with the same thread and checkpoint namespace.
  • Stateless subgraphs disable internal checkpointing and are appropriate for inexpensive operations that do not require interruption or recovery.
  • Parent checkpointers provide the persistence infrastructure inherited by checkpoint-enabled nested graphs.
  • Nested state snapshots expose discoverable subgraph execution details through get_state with subgraphs=True.
  • Stable checkpoint namespaces, explicit state contracts, and controlled concurrency are essential for reliable modular applications.
  • Independent subgraph tests should verify business behavior, persistence, interruption recovery, thread isolation, and parent-child integration.