AI Agent / 系统课时
处理部分失败与安全重放
处理部分失败与安全重放
并行智能体最危险的不是某个节点报错,而是恢复时把已经成功的工作和外部副作用一起重复执行。本节用一个可运行的并行图拆清检查点、待提交写入和幂等键的边界,并建立只重做失败分支的恢复流程。
学习目标
- 从检查点中区分已经成功、仍待完成和失败的并行任务。
- 使用相同
thread_id恢复执行,让已成功分支不被重复计算。 - 为外部副作用设计稳定幂等键,避免重放造成重复写入或重复通知。
先识别已成功与未完成的任务
LangGraph 的并行节点按 superstep 推进。同一轮里如果一个节点成功、另一个节点抛错,整个运行会失败,但检查点会保留成功节点的 pending writes;恢复时可以复用这些写入,而不是把成功节点重新执行一遍。([LangChain AI][1])
判断恢复范围时不要只看“本次调用抛了异常”。应同时查看当前 StateSnapshot.tasks:result 已存在且 error 为空的任务已经完成;带 error 的任务才是需要处理的失败点。外部系统是否已经收到副作用,则必须另外核对,因为图内检查点无法替代数据库、支付网关或消息系统的业务幂等记录。

用检查点只恢复失败分支
下面的示例让两个节点并行执行:load_profile 正常完成,send_notification 在“外部写入已经发生”之后模拟确认丢失。第一次运行失败后读取任务快照,再用同一个 thread_id 和 None 输入恢复。InMemorySaver 适合演示与测试;生产环境应换成持久化 checkpointer。([GitHub][2])
from typing import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
order_id: str
profile_status: str
notification_status: str
# 计数器用于证明恢复时只有失败分支被再次调用。
attempts = {"load_profile": 0, "send_notification": 0}
# set 仅用于演示唯一约束;生产环境应使用持久化幂等账本。
effect_ledger: set[str] = set()
def load_profile(state: State) -> dict:
attempts["load_profile"] += 1
return {"profile_status": "profile-ok"}
def send_notification(state: State) -> dict:
attempts["send_notification"] += 1
key = f"notify:{state['order_id']}"
# set 模拟带唯一约束的幂等账本;重复写入不会产生第二个副作用。
effect_ledger.add(key)
if attempts["send_notification"] == 1:
raise RuntimeError("ack lost after external write")
return {"notification_status": "sent"}
# 两个 START 边让节点处于同一个并行 superstep。
builder = StateGraph(State)
builder.add_node("load_profile", load_profile)
builder.add_node("send_notification", send_notification)
builder.add_edge(START, "load_profile")
builder.add_edge(START, "send_notification")
builder.add_edge("load_profile", END)
builder.add_edge("send_notification", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "order-42"}}
try:
graph.invoke({"order_id": "42"}, config)
except RuntimeError as exc:
print("first run:", exc)
# 失败后先读取快照,区分已完成任务和失败任务。
snapshot = graph.get_state(config)
completed = sorted(
task.name
for task in snapshot.tasks
if task.error is None and task.result is not None
)
failed = sorted(task.name for task in snapshot.tasks if task.error is not None)
print("completed:", completed)
print("failed:", failed)
print(
"before replay:",
attempts["load_profile"],
attempts["send_notification"],
len(effect_ledger),
)
# None + 相同 thread_id 表示从已有检查点继续执行。
result = graph.invoke(None, config)
print(
"after replay:",
attempts["load_profile"],
attempts["send_notification"],
len(effect_ledger),
)
print("result:", result["profile_status"], result["notification_status"])预期输出
first run: ack lost after external write
completed: ['load_profile']
failed: ['send_notification']
before replay: 1 1 1
after replay: 1 2 1
result: profile-ok sentload_profile 的调用次数保持为 1,说明成功分支没有重跑;失败分支调用次数从 1 变为 2。副作用账本的条目数始终为 1,说明即使失败发生在外部写入之后,重放也没有制造第二次通知。
把幂等放在副作用边界
安全重放需要两层保障。图层负责“哪些节点需要重新执行”,业务层负责“节点重新执行时会不会重复扣款、发券、创建工单或发送消息”。检查点只能解决前者,不能自动把任意外部 API 变成 exactly-once。
幂等键应由稳定业务身份和动作组成,例如 ticket:<ID>:close、order:<ID>:refund。生产实现可以依赖数据库唯一约束与 UPSERT、支付接口原生 idempotency key,或独立的操作账本。不要在每次重试时生成新的随机键,否则每次重放都会被外部系统视为一笔新操作。
按失败类型决定恢复动作
瞬时网络错误、限流或服务暂时不可用,适合有限次数重试;参数错误、权限拒绝和业务校验失败通常不应自动重试。最棘手的是“请求可能已经成功,但客户端没有收到确认”,这类未知结果必须依赖幂等查询或操作账本消歧。
| 失败类型 | 恢复策略 | 关键保护 |
|---|---|---|
| 瞬时故障 | 重试失败节点 | 最大次数、退避、超时 |
| 确定性业务失败 | 记录失败并转人工或补偿 | 明确失败码与原因 |
| 副作用结果未知 | 使用原幂等键查询或重放 | 唯一约束、外部幂等接口 |
| 成功并行分支 | 复用 checkpoint 中的结果 | 不主动清空线程或换 thread_id |
恢复的核心判断不是“能不能重新跑”,而是“重新跑哪一部分、重复执行是否安全”。只要这两个问题分别由检查点和幂等边界回答,部分失败就能从一次全局重做变成可控的局部恢复。