openJiuwen agent-core 会话检查点(Checkpointer)机制详解:状态持久化、中断恢复与工作流续跑实战指南

原创2026-10-09 13:18:422,227 阅读
文章标签:人工智能大模型AI AgentAgent 框架Agent 编排多智能体工作流自动化RAGEmbeddingRerank向量数据库MCP 服务提示工程可观测性后端

openJiuwen agent-core 会话检查点(Checkpointer)机制详解:状态持久化、中断恢复与工作流续跑实战指南

openJiuwen agent-core 的 openjiuwen.core.session.checkpointer 模块为 Agent、Agent 团队与工作流(Workflow)提供了统一的检查点(Checkpoint)抽象,用于在关键执行节点保存与恢复会话状态,是实现中断恢复、异常恢复、人机交互续跑能力的核心基础设施。本文以官方 API 文档为主体,结合仓库源码与单元测试,系统讲解 Checkpointer 的抽象接口、内置实现(内存版与持久化版)、工厂与配置体系、Key 命名规范,并给出可直接落地的配置示例与使用建议。读完本文,你将掌握如何为 Agent 与工作流接入检查点能力、如何按需选择 in_memory / persistence / redis 等存储后端,以及理解工作流"续跑"背后恢复-保存-清理的完整生命周期。

一、模块定位与核心职责

Checkpointer 是会话状态持久化与恢复的抽象基类(位于 openjiuwen/core/session/checkpointer/base.py),它的职责贯穿 Agent 与工作流执行的关键阶段:

  • 保存状态:在 Agent 执行完成、工作流被中断(等待用户输入)、工作流异常抛出等节点持久化会话状态;
  • 恢复状态:在 Agent / 工作流再次执行前,把上次保存的状态重新载入会话,实现"从断点继续";
  • 清理状态:在任务正常完成或显式释放时删除检查点数据,避免脏状态污染下一次运行。

从源码结构看,检查点体系由四层构成,其关系如下:

层级 类 说明
抽象契约 Checkpointer、Storage 定义检查点与底层存储的统一接口
状态存储 AgentStorage、AgentTeamStorage、WorkflowStorage、GraphStore 分别管理 Agent 状态、团队全局状态、工作流自身状态、图状态
具体实现 InMemoryCheckpointer、PersistenceCheckpointer 面向不同存储后端
工厂与配置 CheckpointerFactory、CheckpointerProvider、CheckpointerConfig 根据配置创建对应实例

其中 Checkpointer 的 get_thread_id 静态方法返回格式为 session_id:workflow_id 的线程 ID(见 base.py),该 ID 用于在流式消息、日志中关联同一线程的多次执行。

二、Checkpointer 抽象基类:接口全景

2.1 静态方法 get_thread_id

staticmethod get_thread_id(session: BaseSession) -> str

获取会话的线程 ID,格式为 session_id:workflow_id。

参数:

  • session(BaseSession):会话对象。

返回:str,线程 ID 字符串。实现上直接拼接 session.session_id() 与 session.workflow_id():

return ":".join([session.session_id(), session.workflow_id()])

2.2 pre_workflow_execute:工作流执行前恢复或清理状态

abstractmethod async pre_workflow_execute(session: BaseSession, inputs: InteractiveInput)

参数:

  • session(BaseSession):工作流会话对象;
  • inputs(InteractiveInput):工作流输入。核心规则:若输入类型为 InteractiveInput,则恢复工作流状态(续跑模式);否则先检查是否存在已保存的状态——若存在且未开启强制清理,则抛出异常。

这一规则在 inmemory.py 与 persistence.py 中均有完整实现:非交互式输入意味着"重新开始",残留的检查点可能来自一次未完成的中断,因此必须显式处理。强制清理由环境配置项 FORCE_DEL_WORKFLOW_STATE(内部 Key 为 _force_del_workflow_state,定义于 openjiuwen/core/session/constants.py)控制,通过 session.config().get_env(FORCE_DEL_WORKFLOW_STATE_KEY, False) 读取。

2.3 post_workflow_execute:工作流执行后保存或清理状态

abstractmethod async post_workflow_execute(session: BaseSession, result, exception)

参数:

  • session(BaseSession):工作流会话对象;
  • result:工作流执行结果;
  • exception:若执行中出现异常则传入异常对象,否则为 None。

实际处理逻辑(三种分支):

  1. 发生异常:先保存当前工作流检查点,再重新抛出异常,保证失败现场可恢复;
  2. 正常完成(结果中无 TASK_STATUS_INTERRUPT 标记):清理图状态与工作流状态(执行完成不再需要断点);
  3. 被中断(结果包含 TASK_STATUS_INTERRUPT):保存工作流检查点,供下次携带 InteractiveInput 续跑。

2.4 Agent 相关钩子

abstractmethod async pre_agent_execute(session: BaseSession, inputs)
abstractmethod async interrupt_agent_execute(session: BaseSession)
abstractmethod async post_agent_execute(session: BaseSession)
  • pre_agent_execute:Agent 执行前恢复 Agent 状态;若 inputs 非空,会写入会话状态(Key 为 INTERACTIVE_INPUT,见 inmemory.py);
  • interrupt_agent_execute:Agent 需要中断等待用户交互时保存状态;
  • post_agent_execute:Agent 执行完成后保存状态。

2.5 会话生命周期与图存储

abstractmethod async session_exists(session_id: str) -> bool
abstractmethod async release(session_id: str, agent_id: str = None)
abstractmethod graph_store() -> Store
  • session_exists:判断指定会话 ID 是否存在检查点;
  • release:释放会话资源;传入 agent_id 时仅释放该 Agent 的检查点,否则释放整个会话(含工作流、图状态、团队状态);
  • graph_store:返回图状态存储对象(Store),工作流的 Pregel 图状态与工作流自身状态分开存放。

注:抽象基类中还定义了 pre_agent_team_execute / post_agent_team_execute 两个团队级钩子(见 base.py),用于 Agent 团队全局状态的恢复与保存,属于 Agent 团队(Swarm)场景的扩展接口。

三、Storage 抽象基类:底层存储契约

abstractmethod async save(session: BaseSession)          # 保存会话状态
abstractmethod async recover(session: BaseSession, inputs: InteractiveInput = None)  # 恢复会话状态
abstractmethod async clear(session_id: str)              # 清除指定会话状态
abstractmethod async exists(session: BaseSession) -> bool  # 判断状态是否存在

Storage 与 Checkpointer 的职责分离是理解本模块的关键:Checkpointer 负责"何时保存/恢复/清理"(生命周期编排),Storage 负责"具体怎么读写"(序列化与后端交互)。以 WorkflowStorage 为例,它不仅要保存工作流的完整状态(state_blobs),还会单独保存状态更新(state_updates_blobs),恢复时按"状态 → 交互输入 → 更新"的顺序逐层还原(见 inmemory.py)。交互输入按节点(NodeSession)分发到 INTERACTIVE_INPUT,从而精确定位到工作流中等待用户输入的节点。

四、两种内置实现

4.1 InMemoryCheckpointer:开发调试首选

class openjiuwen.core.session.checkpointer.InMemoryCheckpointer()

内存检查点实现:所有状态保存在内存字典中,进程重启后丢失,适用于开发与测试场景。

使用示例:

>>> from openjiuwen.core.session.checkpointer import InMemoryCheckpointer
>>>
>>> checkpointer = InMemoryCheckpointer()
>>> # Use checkpointer for state management

内部结构(见 inmemory.py):分别维护 _agent_stores、_agent_team_stores、_workflow_stores 三个字典,以及一个 InMemoryStore 图状态存储和 _session_to_workflow_ids 会话-工作流 ID 映射表。状态序列化使用 pickle 型 Serializer,单实体存储(BaseSingleStateStorage)以 entity_id(如 agent_id)为键保存 (dump_type, bytes) 二元组。从 test_inmemory_storage.py 可见其完整测试路径:save → recover → exists → clear 全链路均有覆盖。

4.2 PersistenceCheckpointer:进程重启后依然可恢复

class openjiuwen.core.session.checkpointer.PersistenceCheckpointer(kv_store: BaseKVStore)

基于 BaseKVStore 接口的持久化实现,支持任意实现 BaseKVStore 的存储后端(如 SQLite、Shelve 等),状态在进程重启后依然存在,是生产环境的推荐选择。

参数:

  • kv_store(BaseKVStore):用于持久化状态的键值存储对象。

使用示例(Shelve 后端):

>>> from openjiuwen.core.session.checkpointer import PersistenceCheckpointer
>>> from openjiuwen.core.foundation.store.kv import ShelveStore
>>>
>>> kv_store = ShelveStore("checkpoint.db")
>>> checkpointer = PersistenceCheckpointer(kv_store)
>>> # Use checkpointer for state management

实现要点(见 persistence.py):

  • 构造函数内部创建 AgentStorage、AgentTeamStorage、WorkflowStorage、GraphStore 四类存储,统一基于同一个 kv_store;
  • 持久化存储的 Key 结构严格遵循"会话 → 命名空间 → 实体 → 后缀"的命名规范(见下文第六节);
  • GraphStore 负责 session:workflow-graph:workflow_id:suffix 前缀的图状态读写,与工作流自身状态(workflow 命名空间)物理隔离;
  • session_exists 通过 get_by_prefix(f"{session_id}:") 判断是否存在关联 Key,release 在未指定 agent_id 时通过 delete_by_prefix 一键清理整个会话前缀下的全部 Key;
  • 所有读写操作通过 kv_store.pipeline() 批量提交,recover/exists 均一次管线获取全部所需 Key,减少往返开销。

对应的单元测试 test_persistence_storage.py 覆盖了 agent / agent_group 存储的 save-recover-exists-clear 全链路,以及"恢复不存在状态为空操作"的边界行为。

五、CheckpointerFactory:统一的创建与管理入口

class openjiuwen.core.session.checkpointer.CheckpointerFactory

检查点工厂类,负责不同类型检查点实例的注册与创建。

5.1 register:注册 Provider

classmethod register(name: str)

注册一个检查点 Provider。name 为检查点类型名(如 "in_memory"、"persistence"、"redis")。返回装饰器函数,用于装饰 CheckpointerProvider 子类。

示例(注册自定义 Provider):

>>> from openjiuwen.core.session.checkpointer import CheckpointerFactory, CheckpointerProvider
>>>
>>> @CheckpointerFactory.register("custom")
>>> class CustomCheckpointerProvider(CheckpointerProvider):
...     async def create(self, conf: dict) -> Checkpointer:
...         # Create custom checkpoint instance
...         return CustomCheckpointer()

实现上,注册把 provider_class() 实例存入 _registry 字典(见 checkpointer.py)。仓库内置注册了两个 Provider:

  • InMemoryCheckpointerProvider:create() 直接返回单例 default_inmemory_checkpointer;
  • PersistenceCheckpointerProvider:依据 conf 中的 db_type 构建 SQLite(DbBasedKVStore)或 Shelve(ShelveStore)后端。

5.2 create:按配置创建实例

classmethod async create(checkpointer_conf: CheckpointerConfig) -> Checkpointer

根据配置对象创建检查点实例。checkpointer_conf 为 CheckpointerConfig,包含 type 与 conf 两个字段。

示例:

>>> from openjiuwen.core.session.checkpointer import CheckpointerFactory, CheckpointerConfig
>>>
>>> config = CheckpointerConfig(type="in_memory", conf={})
>>> checkpointer = await CheckpointerFactory.create(config)

create 内部先从 _registry 查找对应 Provider,未找到则抛出异常;找到后调用 provider.create(conf)(见 checkpointer.py)。

5.3 实例管理三件套

方法 作用
set_default_checkpointer(checkpointer) 设置全局默认检查点实例
set_checkpointer(store_type, checkpointer) 为特定存储类型设置检查点实例(如 "in_memory"、"redis")
get_checkpointer(store_type=None) 获取检查点实例

get_checkpointer 的取值优先级(见 checkpointer.py):

  1. 指定了 store_type 且已通过 set_checkpointer 设置过该类型 → 返回该实例;
  2. 指定了 store_type == "in_memory" 但未设置 → 返回默认内存检查点单例;
  3. 未指定类型或类型未设置 → 返回 set_default_checkpointer 设置的实例;若未设置则回退到默认内存检查点单例。

六、CheckpointerProvider 与 CheckpointerConfig

6.1 CheckpointerProvider:Provider 抽象

class openjiuwen.core.session.checkpointer.CheckpointerProvider

检查点 Provider 的抽象基类,用于创建特定类型的检查点实例。

abstractmethod async create(conf: dict) -> Checkpointer

参数:conf(dict):配置字典。返回:Checkpointer 实例。

6.2 CheckpointerConfig:配置模型

class openjiuwen.core.session.checkpointer.CheckpointerConfig(type: str = "in_memory", conf: dict = {})

参数:

  • type(str,可选):检查点类型,默认 "in_memory";
  • conf(dict,可选):检查点配置字典,默认 {}。

该类基于 Pydantic BaseModel 实现(见 checkpointer.py),并有一个值得注意的安全特性:__repr__ 与 __str__ 会递归脱敏 conf 中 URL 型字符串的密码(通过 redact_url_password),避免打印配置时泄露连接凭据。单元测试 test_checkpointer_config_repr.py 专门验证了 Redis / Pulsar 等分布式配置中 URL 密码被脱敏的行为。

6.3 PersistenceCheckpointer 的生产配置模板

PersistenceCheckpointerProvider 支持的 conf 字段(见 persistence.py):

{
    "db_type": "sqlite",      # 可选:存储后端类型,sqlite 或 shelve,默认 "sqlite"
    "db_path": "checkpointer",# 可选:数据库文件路径,默认 "checkpointer"(sqlite 会自动补全 .db 后缀)
    "db_client": None,        # 可选:预配置的 AsyncEngine 实例(提供后忽略 db_path 创建逻辑)
    "db_timeout": 30,         # 可选:SQLite 锁等待秒数,默认 30,降低 OperationalError 概率
    "db_enable_wal": True,    # 可选:启用 SQLite WAL 模式,默认 True,提升并发读写能力
}

要点说明:

  • db_type="sqlite" 时使用 sqlite+aiosqlite:/// 创建异步引擎,并通过 connect_args={"timeout": db_timeout} 配置锁等待;启用 WAL 模式时会在每个新连接上执行 PRAGMA journal_mode=WAL(见 persistence.py),允许一个写者与多个并发读者共存,显著缓解高并发下的 "database is locked" 问题;
  • db_type="shelve" 时会移除 .db 后缀后交给 ShelveStore;
  • 不支持的 db_type 会抛出 CHECKPOINTER_CONFIG_ERROR 异常。

6.4 扩展:Redis 检查点后端

除内置实现外,仓库在 openjiuwen/extensions/checkpointer/redis/checkpointer.py 提供 Redis 扩展,其配置模型包含:

  • RedisTTLConfig:default_ttl(数据默认过期时间,分钟)与 refresh_on_read(读取时是否刷新 TTL),适合会话状态需要自动过期的场景;
  • RedisConnectionConfig:支持预配置客户端(redis_client)、URL(redis:// 独立模式 / redis+cluster:// 集群模式)、cluster_mode 显式开关及附加连接参数。

这印证了 CheckpointerFactory.register 的可扩展设计:任何存储后端只要实现 CheckpointerProvider.create 并完成注册,即可无缝接入现有生命周期管理。

七、Key 命名规范:把状态精确落到 KV 存储

检查点模块提供两个 Key 构造函数与三个命名空间常量(均定义于 openjiuwen/core/session/checkpointer/base.py)。

7.1 build_key

func build_key(*parts: str) -> str

用冒号连接多个字符串片段构造 Key。

>>> from openjiuwen.core.session.checkpointer import build_key
>>>
>>> key = build_key("session1", "agent", "agent1")
>>> print(key)
session1:agent:agent1

7.2 build_key_with_namespace

func build_key_with_namespace(session_id: str, namespace: str, entity_id: str, *suffixes: str) -> str

构造带命名空间结构的 Key,格式为 session:namespace:entity_id:suffixes。

>>> from openjiuwen.core.session.checkpointer import build_key_with_namespace
>>>
>>> key = build_key_with_namespace("session1", "agent", "agent1", "state")
>>> print(key)
session1:agent:agent1:state

7.3 命名空间常量

常量 值 含义
SESSION_NAMESPACE_AGENT "agent" 会话下的 Agent 状态命名空间
SESSION_NAMESPACE_WORKFLOW "workflow" 会话下的工作流状态命名空间(工作流自身状态)
WORKFLOW_NAMESPACE_GRAPH "workflow-graph" 工作流下的图状态命名空间(与工作流自身状态分离)

补充:源码中还存在 SESSION_NAMESPACE_AGENT_TEAM = "agent-team"(Agent 团队状态命名空间),用于团队全局状态的多级隔离。

以持久化实现为例,各存储使用的实际 Key 形如:

  • Agent 状态:{session_id}:agent:{agent_id}:agent_state_blobs(及 agent_state_blobs_dump_type);
  • Agent 团队状态:{session_id}:agent-team:{team_id}:agent_team_state_blobs;
  • 工作流状态:{session_id}:workflow:{workflow_id}:workflow_state_blobs、workflow_state_blobs_dump_type、workflow_update_blobs、workflow_update_blobs_dump_type(共 4 个 Key,见 persistence.py);
  • 图状态:{session_id}:workflow-graph:{workflow_id}:checkpoint_data_type、checkpoint_data_value。

这套前缀规范使得 delete_by_prefix、get_by_prefix 等范围操作可以精确瞄准"某个会话的全部状态""某个会话的某个实体状态"等粒度,是 release 与 session_exists 高效工作的基础。

八、状态存储的序列化与一致性设计

从源码可以归纳出存储层几个关键设计:

  1. typed 序列化:所有状态经 create_serializer("pickle") 序列化为 (dump_type, blob) 二元组,dump_type 标记数据形态(如 "empty" 表示空状态),反序列化时据此还原,避免类型信息丢失;
  2. 字符串兼容:持久化存储的反序列化对字符串形态的 blob 先做 base64 解码再还原(见 persistence.py),兼容不同 KV 后端对二进制值的存储差异;
  3. 管线批量操作:save / recover / exists 均使用 pipeline() 组合多个命令一次性提交,减少存储往返;
  4. 日志可观测:每个关键阶段(CHECKPOINT_SAVE、CHECKPOINT_RESTORE、CHECKPOINT_CLEAR、CHECKPOINTER_STORE_ADD、CHECKPOINTER_STORE_REMOVE)都通过 session_logger 输出结构化日志,便于排查恢复链路问题;
  5. 失败不静默:Agent 中断保存、执行后保存、工作流异常保存等路径在存储不存在时会抛出明确的 StatusCode(如 CHECKPOINTER_INTERRUPT_AGENT_ERROR、CHECKPOINTER_POST_WORKFLOW_EXECUTION_ERROR),防止静默丢失状态。

九、生命周期串联:一次完整的中断续跑

将上述机制串联起来,一次典型的中断续跑流程如下:

  1. 工作流执行到需要用户输入的节点,Pregel 图产生 TASK_STATUS_INTERRUPT 标记;
  2. post_workflow_execute 检测到中断标记 → 保存工作流状态、状态更新与图状态(同时 interrupt_agent_execute 保存 Agent 状态);
  3. 用户输入到达后,以 InteractiveInput 重新发起执行;
  4. pre_workflow_execute 识别到 InteractiveInput → 恢复工作流状态,并把用户输入按节点分发到 NodeSession 的 INTERACTIVE_INPUT;
  5. pre_agent_execute 恢复 Agent 状态(含历史交互输入);
  6. 工作流从上次中断的节点继续执行,正常完成后 post_workflow_execute 清理全部检查点。

若步骤 4 中传入的不是 InteractiveInput 而会话存在残留状态,框架会抛出 CHECKPOINTER_PRE_WORKFLOW_EXECUTION_ERROR——除非显式开启 FORCE_DEL_WORKFLOW_STATE 环境变量强制清理,这正是"续跑"与"重跑"语义边界的保护机制。

十、小结与选型建议

openjiuwen.core.session.checkpointer 以"生命周期编排(Checkpointer)+ 底层读写(Storage)+ 工厂注册(Factory)"的三层架构,为 Agent 与工作流提供了一致、可扩展的检查点能力:

  • 开发调试:使用 InMemoryCheckpointer,零配置、重启即清;
  • 单机生产:使用 PersistenceCheckpointer + SQLite(默认开 WAL 提升并发),或 Shelve 后端;
  • 分布式 / 需要 TTL:扩展模块提供 Redis 后端,支持集群模式与数据自动过期;
  • 自定义后端:实现 CheckpointerProvider 并 @CheckpointerFactory.register(name) 即可接入。

核心源码与测试可进一步查阅:

结合官方 API 文档(docs/en/2.Development Guide/API Docs/openjiuwen.core/session/checkpointer.md)与上述源码,即可在自己的 Agent / 工作流应用中快速接入稳定可靠的检查点能力。

登录后查看全文
agent-core