AI Agent / 系统课时
从检查点恢复失败执行
从检查点恢复失败执行
当工作流在中途节点抛出异常时,目标不是把整条链路从头跑一遍,而是保留已经完成的状态,只重试尚未成功的部分。本节用一个“首次必失败、第二次成功”的节点验证检查点恢复,并检查恢复点是否准确。
学习目标
- 为图配置检查点并用稳定的
thread_id标识一次可恢复执行 - 模拟节点异常后从保存状态继续,而不是重新执行已完成节点
- 通过状态快照和控制台输出验证实际恢复位置
恢复机制保存了什么
LangGraph 的 checkpointer 会按线程保存图状态;顺序图中,每个成功的 super-step 都会形成可恢复的状态边界。节点失败后,继续同一个线程时可以从最近可用的执行位置恢复,而不是丢弃此前已持久化的结果。([Docs by LangChain][1])

检查点保存的是图状态与执行位置,不是 Python 进程本身。恢复时必须复用原来的 thread_id;换一个线程标识,相当于开始一条新的状态历史。
模拟失败并从原线程继续
下面的示例要求当前 Python 环境已安装 langgraph。prepare 只应执行一次,unstable 第一次故意抛错,随后用同一配置再次调用图。
python
from typing_extensions import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
history: list[str]
attempts = {"unstable": 0}
def prepare(state: State) -> dict:
print("prepare runs")
return {"history": state["history"] + ["prepare"]}
def unstable(state: State) -> dict:
attempts["unstable"] += 1
print(f"unstable attempt {attempts['unstable']}")
if attempts["unstable"] == 1:
raise RuntimeError("simulated timeout")
return {"history": state["history"] + ["unstable"]}
def finalize(state: State) -> dict:
print("finalize runs")
return {"history": state["history"] + ["finalize"]}
builder = StateGraph(State)
builder.add_node("prepare", prepare)
builder.add_node("unstable", unstable)
builder.add_node("finalize", finalize)
builder.add_edge(START, "prepare")
builder.add_edge("prepare", "unstable")
builder.add_edge("unstable", "finalize")
builder.add_edge("finalize", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "recover-demo"}}
try:
graph.invoke({"history": []}, config=config)
except RuntimeError as exc:
print("failed:", exc)
snapshot = graph.get_state(config)
print("next:", snapshot.next)
print("saved:", snapshot.values)
result = graph.invoke(None, config=config)
print("result:", result)预期输出
text
prepare runs
unstable attempt 1
failed: simulated timeout
next: ('unstable',)
saved: {'history': ['prepare']}
unstable attempt 2
finalize runs
result: {'history': ['prepare', 'unstable', 'finalize']}prepare runs 只出现一次,说明它的成功结果已经留在检查点中;恢复时重新进入的是失败的 unstable 节点。snapshot.next 也明确指出下一步仍是 unstable。
恢复并不等于任意副作用都自动去重
检查点能避免无意义地重跑已完成图步骤,但失败节点会从节点入口重新执行。如果节点在抛错前已经调用支付、发邮件或写外部数据库,第二次执行可能再次产生副作用,因此这类操作仍要使用幂等键、事务或“先查后写”等机制。
判断恢复是否正确
验证时不要只看最终结果,而要同时检查三件事:同一个 thread_id 是否被复用、失败前的状态是否仍在 graph.get_state(config) 中、已完成节点是否没有再次产生日志或外部副作用。只要这三点成立,才能确认工作流确实从检查点继续,而不是悄悄从头执行。
按自己的节奏,确认真正理解。