openJiuwen agent-core RedisCheckpointer 检查点机制:独立 Redis 与集群模式下的状态持久化与中断恢复实战
openJiuwen agent-core RedisCheckpointer 检查点机制:独立 Redis 与集群模式下的状态持久化与中断恢复实战
导读
本文聚焦 openJiuwen agent-core 中基于 Redis 的检查点组件 openjiuwen.extensions.checkpointer.redis.RedisCheckpointer,完整讲解其配置模型、生命周期钩子与底层存储实现。你将掌握如何在独立 Redis 与 Redis 集群两种部署形态下为 Agent 与工作流配置检查点,理解 pre_agent_execute、interrupt_agent_execute、post_workflow_execute 等钩子如何协同完成状态保存、中断恢复与状态清理,并学会通过 TTL 管理 Redis 中的数据生命周期。
一、RedisCheckpointer 是什么
RedisCheckpointer 是 openJiuwen 框架提供的基于 Redis 的检查点(Checkpoint)实现,用于在 Agent 与工作流执行的关键节点持久化状态,并在重新执行时恢复状态,从而支撑中断恢复与异常恢复能力。它的核心特点如下:
- 双模式支持:同时支持独立 Redis 与 Redis Cluster 集群模式,适用于分布式生产部署;
- 接口隔离:所有 Redis 操作均通过
RedisStore接口完成,不直接调用 Redis 客户端 API,便于替换与测试; - TTL 管理:支持默认 TTL 与读取时刷新(
refresh_on_read),可自动清理过期状态,避免数据无限增长; - 命名空间隔离:通过
session:namespace:entity_id:suffix的键结构,将 Agent 状态、Agent 团队状态、工作流自身状态与图状态相互分离。
类的构造签名如下(实现见 redis/checkpointer.py):
class RedisCheckpointer(redis_store: RedisStore, ttl: Optional[dict[str, Any]] = None)
redis_store(RedisStore):Redis 存储对象,承载全部 Redis 读写操作;ttl(可选字典):TTL 配置字典,包含default_ttl(分钟)与refresh_on_read两个键,默认None。
最简使用方式
直接构造 RedisStore 并传给 RedisCheckpointer:
from openjiuwen.extensions.checkpointer.redis import RedisCheckpointer
from openjiuwen.extensions.store.kv import RedisStore
from redis.asyncio import Redis
redis_client = Redis.from_url("redis://localhost:6379")
redis_store = RedisStore(redis_client)
checkpointer = RedisCheckpointer(redis_store)
# 使用 checkpointer 进行状态管理
二、通过 Provider 与工厂创建实例(推荐)
在生产代码中更推荐通过 CheckpointerProvider + CheckpointerFactory 的工厂模式创建。RedisCheckpointerProvider 在源码中以装饰器 @CheckpointerFactory.register("redis") 注册(见 checkpointer.py),其 create(conf: dict) 方法接收结构化的配置字典,自动完成参数校验、Redis 客户端创建与实例组装。
from openjiuwen.core.session.checkpointer import CheckpointerFactory, CheckpointerConfig
# 独立 Redis
conf = {
"connection": {"url": "redis://localhost:6379"}
}
config = CheckpointerConfig(type="redis", conf=conf)
checkpointer = await CheckpointerFactory.create(config)
# 集群模式
conf = {
"connection": {
"url": "redis://localhost:7000",
"cluster_mode": True
}
}
config = CheckpointerConfig(type="redis", conf=conf)
checkpointer = await CheckpointerFactory.create(config)
# 带 TTL
conf = {
"connection": {"url": "redis://localhost:6379"},
"ttl": {"default_ttl": 5, "refresh_on_read": True}
}
config = CheckpointerConfig(type="redis", conf=conf)
checkpointer = await CheckpointerFactory.create(config)
create 方法的完整配置格式为:
{
"connection": {
"redis_client": Redis(...), # 可选:预配置的客户端,提供后其余连接参数被忽略
"url": "redis://...", # 如果未提供 redis_client 则必需
"cluster_mode": True, # 可选:从 URL 自动检测(如果为 None)
"connection_args": {...} # 可选:额外的连接参数
},
"ttl": { # 可选
"default_ttl": 5, # 可选:TTL(分钟)
"refresh_on_read": True # 可选:读取时刷新 TTL
}
}
工厂创建的关键行为
从 checkpointer.py 的实现可以看到 CheckpointerFactory 是一个带注册表的工厂:register(name) 将 provider 实例写入 _registry,create 根据 CheckpointerConfig.type 取出对应 provider 并调用其 create(conf)。内置的 in_memory provider 在导入 openjiuwen.core.session.checkpointer 时即注册。
重要:redis 属于扩展 provider,需要显式导入模块以触发装饰器注册。单独使用(脱离 Runner)时请先执行:
from openjiuwen.extensions.checkpointer.redis import checkpointer # noqa: F401
如果通过 Runner 运行,Runner 启动时会自动处理 provider 的注册(懒加载导入),无需手动操作。
Provider 内部的客户端创建逻辑
在 RedisCheckpointerProvider.create 中,配置先经 RedisCheckpointerConfig.model_validate(conf) 校验;随后按以下优先级决定连接方式:
- 若提供
redis_client,直接包装为RedisStore并跳过 URL 解析; - 否则通过
get_connection_url()取得规范化 URL; - 通过
is_cluster_mode()判定集群模式,分别调用RedisCluster.from_url()或Redis.from_url(),并将connection_args透传给客户端; - 最终统一包装为
RedisStore并构造RedisCheckpointer。
这一过程对应的单元测试见 test_redis_checkpointer_provider.py,其中验证了 redis_client 直传、URL 创建、TTL 转换(default_ttl=5 分钟被转换为 5 * 60 = 300 秒)以及缺省连接配置时报 ValueError 等行为。
三、结构化配置类:类型安全的连接与 TTL 配置
除字典形式外,openjiuwen.extensions.checkpointer.redis 还提供三个基于 Pydantic 的配置类,支持自动验证与合理默认值。
3.1 RedisCheckpointerConfig
检查点的完整配置,包含 connection(必填)与 ttl(可选):
from openjiuwen.extensions.checkpointer.redis import (
RedisCheckpointerConfig,
RedisConnectionConfig,
RedisTTLConfig
)
# 最小配置(独立 Redis)
config = RedisCheckpointerConfig(
connection=RedisConnectionConfig(url="redis://localhost:6379")
)
# 带 TTL 配置
config = RedisCheckpointerConfig(
connection=RedisConnectionConfig(url="redis://localhost:6379"),
ttl=RedisTTLConfig(default_ttl=5, refresh_on_read=True)
)
# 集群模式
config = RedisCheckpointerConfig(
connection=RedisConnectionConfig(
url="redis://localhost:7000",
cluster_mode=True
)
)
# 使用预配置客户端
from redis.asyncio import Redis
redis_client = Redis.from_url("redis://localhost:6379")
config = RedisCheckpointerConfig(
connection=RedisConnectionConfig(redis_client=redis_client),
ttl=RedisTTLConfig(default_ttl=10)
)
3.2 RedisConnectionConfig 连接配置
class RedisConnectionConfig(
redis_client: Optional[Union[Redis, RedisCluster]] = None,
url: Optional[str] = None,
cluster_mode: Optional[bool] = None,
connection_args: dict[str, Any] = {}
)
参数语义(与源码 checkpointer.py 对应):
redis_client:预配置的 Redis 或 RedisCluster 客户端实例;一旦提供,其他连接参数被忽略;url:连接 URL,可为独立地址redis:///rediss://,或集群地址redis+cluster:///rediss+cluster://;cluster_mode:显式开启/关闭集群模式;为None时从 URL 方案自动检测;connection_args:透传给 Redis 客户端的额外连接参数(如decode_responses、连接池大小、超时等)。
该配置类内置两层校验:
validate_url字段校验:URL 必须以redis://、rediss://、redis+cluster://、rediss+cluster://之一开头,否则抛出ValueError;validate_config模型校验:redis_client与url至少提供一个,否则报错 "Either 'redis_client' or 'url' must be provided..."。
集群模式判定逻辑(is_cluster_mode()):优先看 redis_client 是否为 RedisCluster 实例;否则看显式的 cluster_mode;再否则看 URL 是否以 redis+cluster:// / rediss+cluster:// 开头。判定顺序保证了预配置客户端场景下不会被误判。
URL 规范化(get_connection_url()):由于 RedisCluster.from_url() 不识别 +cluster 后缀,该方法会把 redis+cluster:// 替换为 redis://、rediss+cluster:// 替换为 rediss://,再交给客户端创建。
典型用法:
from openjiuwen.extensions.checkpointer.redis import RedisConnectionConfig
# 独立 Redis
config = RedisConnectionConfig(url="redis://localhost:6379")
# 带显式标志的集群模式
config = RedisConnectionConfig(
url="redis://localhost:7000",
cluster_mode=True
)
# 使用 URL 方案的集群模式
config = RedisConnectionConfig(url="redis+cluster://localhost:7000")
# 使用预配置客户端
redis_client = Redis.from_url("redis://localhost:6379")
config = RedisConnectionConfig(redis_client=redis_client)
3.3 RedisTTLConfig TTL 配置
class RedisTTLConfig(default_ttl: Optional[float] = None, refresh_on_read: bool = False)
default_ttl:存储数据的默认 TTL(分钟)。设置后所有写入的数据都会带上该过期时间。底层实现(见 storage.py)会将其乘以 60 转换为秒,即_ttl_seconds = int(default_ttl * 60);refresh_on_read:为True时,每次读取数据都会重新设置 TTL,从而延长高频访问数据的存活时间,适合活跃会话场景。
TTL 生效范围覆盖 Agent 状态、Agent 团队状态、工作流状态(含更新数据)与图状态四类存储,由各存储统一从 ttl 字典读取 default_ttl 与 refresh_on_read 两个键。
四、生命周期钩子:状态何时被保存与恢复
RedisCheckpointer 继承自 openjiuwen.core.session.checkpointer 的抽象基类 Checkpointer(见 base.py),实现了全部生命周期方法。Runner 与 Workflow 引擎会在执行的关键节点自动调用这些钩子,开发者一般无需手动调用。
4.1 Agent 生命周期
pre_agent_execute(session, inputs) — Agent 执行前调用,用于恢复 Agent 状态:
- 通过
self._agent_storage.recover(session)从 Redis 恢复状态; - 若
inputs非空,则将其写入会话状态:session.state().update({INTERACTIVE_INPUT: [inputs]})。
interrupt_agent_execute(session) — Agent 需要中断等待用户交互时调用,保存 Agent 状态(self._agent_storage.save(session))。
post_agent_execute(session) — Agent 执行完成后调用,保存最终 Agent 状态。
Agent 执行流程可概括为:
开始执行 Agent
↓
pre_agent_execute (恢复状态)
↓
执行 Agent 逻辑
↓
如果需要中断 → interrupt_agent_execute (保存状态)
↓
执行完成 → post_agent_execute (保存状态)
Agent 团队(Agent Team):源码中还有 pre_agent_team_execute 与 post_agent_team_execute 两个钩子,分别通过 AgentGroupStorage.recover/save 管理团队全局状态(session.state().update_global(...)),说明 Redis 检查点同样覆盖多智能体团队场景。
4.2 工作流生命周期
pre_workflow_execute(session, inputs: InteractiveInput) — 工作流执行前调用,负责恢复或清理工作流状态(完整逻辑见 checkpointer.py):
- 若
inputs是InteractiveInput类型,则调用_workflow_storage.recover(session, inputs)恢复工作流状态(中断后恢复执行场景); - 若
inputs不是交互输入且工作流状态已存在,则分两种情况:- 会话环境变量
FORCE_DEL_WORKFLOW_STATE_KEY(openjiuwen.core.session.constants中定义)为True:先删除图状态(_graph_state.delete)再清理工作流状态(_workflow_storage.clear),并记录 "Force deleted workflow state" 日志; - 否则抛出
StatusCode.CHECKPOINTER_PRE_WORKFLOW_EXECUTION_ERROR异常,提示"workflow state exists but non-interactive input and cleanup is disabled"。
- 会话环境变量
post_workflow_execute(session, result, exception) — 工作流执行后调用:
- 若
exception非空:保存工作流状态并重新抛出异常(便于后续恢复); - 若
result中不含TASK_STATUS_INTERRUPT(图执行中断状态标记,来自openjiuwen.core.graph.pregel):工作流正常完成,删除图状态并清理工作流状态; - 若包含中断标记:工作流等待交互,保存工作流状态。
开始执行工作流
↓
pre_workflow_execute
├─ 如果是 InteractiveInput → 恢复工作流状态
└─ 如果不是 InteractiveInput → 检查状态
├─ 状态存在且未启用强制删除 → 抛出异常
└─ 状态存在且启用强制删除 → 清理状态
↓
执行工作流逻辑
↓
post_workflow_execute
├─ 发生异常 → 保存状态并抛出异常
├─ 正常完成 → 清理状态
└─ 需要中断 → 保存状态
4.3 会话管理与资源释放
session_exists(session_id: str) -> bool:检查指定会话是否存在。实现上使用前缀 f"{session_id}:" 通过 RedisStore.get_by_prefix() 扫描 Redis,只要存在任意以该前缀开头的键即返回 True(见 checkpointer.py)。
release(session_id: str, agent_id: Optional[str] = None):释放会话资源:
- 提供
agent_id时,仅调用_agent_storage.clear(agent_id, session_id)清理该 Agent 的状态; - 未提供时,通过
_redis_store.delete_by_prefix(prefix, batch_size=500)分批删除整个会话前缀下的全部键(每次 500 个键,兼顾内存与网络往返)。
graph_store() -> Store:返回图状态存储对象 GraphStore,可用于直接读取/删除工作流图执行状态。
五、底层存储设计:命名空间、序列化与键结构
RedisCheckpointer 内部组合了四类存储(见 storage.py):
| 存储类 | 命名空间 | 管理对象 | Redis 键后缀 |
|---|---|---|---|
AgentStorage |
SESSION_NAMESPACE_AGENT("agent") |
Agent 状态 | agent_state_blobs、agent_state_blobs_dump_type |
AgentGroupStorage |
SESSION_NAMESPACE_AGENT_TEAM("agent-team") |
Agent 团队全局状态 | agent_group_state_blobs、agent_group_state_blobs_dump_type |
WorkflowStorage |
SESSION_NAMESPACE_WORKFLOW("workflow") |
工作流状态与更新 | workflow_state_blobs、workflow_state_blobs_dump_type、workflow_update_blobs、workflow_update_blobs_dump_type |
GraphStore |
WORKFLOW_NAMESPACE_GRAPH("workflow-graph") |
图执行状态 | checkpoint_data_type、checkpoint_data_value |
键由 build_key_with_namespace(session_id, namespace, entity_id, *suffixes) 构建,最终形如:
session_id:namespace:entity_id:suffix
例如 Agent 状态键为 {session_id}:agent:{agent_id}:agent_state_blobs。图状态键采用 {session_id}:workflow-graph:{workflow_id}:checkpoint_data_value 的结构,将图状态与工作流自身状态分离(见 storage.py 的类注释)。
序列化与 TTL 的实现细节
- 所有存储统一使用
create_serializer("pickle")生成的序列化器,将状态编码为(dump_type, blob)元组后写入 Redis; - 读取时若
dump_type为 bytes 会自动解码为 UTF-8 字符串,反序列化失败仅记录日志并返回None,不中断执行流程; _refresh_ttl()仅在refresh_on_read=True且设置了_ttl_seconds时生效,通过RedisStore.refresh_ttl(keys, ttl_seconds)批量刷新;WorkflowStorage的recover还会把InteractiveInput中的原始输入(raw_inputs)或按节点 ID 的用户输入(user_inputs)合并进工作流状态,这是中断恢复的核心环节(见 storage.py)。
RedisStore 的支撑能力
RedisStore(见 extensions/store/kv/redis_store.py)是基于 redis.asyncio 的异步 KV 存储,为检查点提供了:
set/get/delete/exists等 O(1) 单键操作;- 基于
SCAN(非阻塞)的get_by_prefix/delete_by_prefix前缀扫描与批量删除(默认 500 键一批); pipeline()批量执行:状态保存、恢复与exists判断均通过 pipeline 一次性完成多个命令,减少网络往返;refresh_ttl:通过 pipeline 批量执行EXPIRE;- 集群模式支持:客户端按哈希槽自动路由,
SCAN自动遍历所有节点,跨槽 MGET 失败时自动回退为逐个 GET。
六、与 Runner 集成及中断恢复实战
6.1 在 Runner 中配置 Redis 检查点
Runner 启动时自动完成 provider 懒加载、实例创建与默认检查点设置,因此只需在 RunnerConfig 中声明配置:
from openjiuwen.core.runner import Runner
from openjiuwen.core.runner.runner_config import RunnerConfig
from openjiuwen.core.session.checkpointer import CheckpointerConfig
runner_config = RunnerConfig()
# 独立 Redis
runner_config.checkpointer_config = CheckpointerConfig(
type="redis",
conf={"connection": {"url": "redis://localhost:6379"}}
)
Runner.set_config(runner_config)
await Runner.start()
# 集群模式
runner_config.checkpointer_config = CheckpointerConfig(
type="redis",
conf={
"connection": {
"url": "redis://localhost:7000",
"cluster_mode": True
}
}
)
Runner.set_config(runner_config)
await Runner.start()
# 带 TTL 的 Redis(60 分钟过期,读取时刷新)
runner_config.checkpointer_config = CheckpointerConfig(
type="redis",
conf={
"connection": {"url": "redis://localhost:6379"},
"ttl": {"default_ttl": 60, "refresh_on_read": True}
}
)
Runner.set_config(runner_config)
await Runner.start()
注意事项:
- 若配置了
redis类型但未安装 Redis 依赖,Runner 启动会失败并提示安装依赖; - 检查点初始化失败会导致 Runner 启动失败;
- 启动成功后,所有通过 Runner 执行的 Agent、Agent 团队与工作流都会自动使用该检查点;
- 在 Runner 中无需手动导入扩展模块,Runner 会自动处理 provider 注册。
6.2 手动管理检查点实例
脱离 Runner 时,可手动创建并管理检查点:
from openjiuwen.core.session.checkpointer import CheckpointerFactory
# 获取当前默认检查点
checkpointer = CheckpointerFactory.get_checkpointer()
# 检查会话是否存在
exists = await checkpointer.session_exists("session_id")
# 释放会话资源(整会话)
await checkpointer.release("session_id")
# 释放特定 Agent 的资源
await checkpointer.release("session_id", agent_id="agent_id")
6.3 工作流中断-恢复闭环(测试佐证)
仓库中的集成测试完整验证了"中断 → 保存 → 恢复 → 完成 → 清理"的生命周期:
- test_integration_workflow.py 中的
test_simple_interactive_workflow_checkpointer:首次invoke触发交互中断后,通过checkpointer.graph_store().get(session_id, workflow_id)可读取到图状态检查点,_workflow_storage.exists(session)返回True;继续提供用户输入恢复执行,最终工作流COMPLETED后,图状态返回None、工作流存储被清理,证明"正常完成即清理"的行为; - test_integration_runner.py 中的
test_workflow_agent_invoke_with_interrupt_recovery:在 Runner 配置 Redis 检查点后,第一次调用返回__interaction__类型输出,第二次携带用户输入调用后从检查点恢复并正常完成,同时验证了CheckpointerFactory.get_checkpointer()返回的实例类名为RedisCheckpointer。
这两组测试是理解 Redis 检查点真实行为的权威参考,可作为自行复现的最小用例。
七、最佳实践与故障排查
7.1 选型建议
- 开发/测试环境:使用
in_memory检查点,无需额外配置; - 单机生产环境:可使用
persistence(SQLite/Shelve)检查点; - 分布式生产环境:使用
redis检查点,配合 Redis 集群获得高可用与横向扩展能力。
7.2 TTL 配置建议
为避免 Redis 数据无限增长,生产环境建议始终配置 TTL:
config = CheckpointerConfig(
type="redis",
conf={
"connection": {"url": "redis://localhost:6379"},
"ttl": {
"default_ttl": 60, # 60 分钟过期
"refresh_on_read": True # 读取时刷新,保持活跃会话
}
}
)
refresh_on_read=True 适合长会话场景——只要会话持续被读取,其状态就不会过期;闲置会话则会自然淘汰。
7.3 状态清理
定期释放不再需要的会话资源,避免遗留键堆积:
# 释放整个会话
await checkpointer.release("session_id")
# 仅释放会话内某个 Agent
await checkpointer.release("session_id", agent_id="agent_id")
release 通过 SCAN 前缀匹配批量删除(每批 500 键),全程不阻塞 Redis 服务端。
7.4 常见问题
-
Provider 未注册错误:
CheckpointerFactory.create()报 provider 不存在。原因是redis为扩展 provider,需先导入注册:from openjiuwen.extensions.checkpointer.redis import checkpointer # noqa: F401在 Runner 中无需手动处理。
-
状态恢复失败:检查检查点配置是否正确、Redis 是否可访问、会话 ID 是否一致、provider 是否已注册。
-
状态未保存/未清理:确认执行路径是否命中对应钩子——例如工作流正常完成时会清理状态,若期望保留状态则应关注中断场景(
TASK_STATUS_INTERRUPT)而非已完成场景。 -
非交互输入重入冲突:同一会话已存在工作流状态时,若以非
InteractiveInput输入重新执行且未开启FORCE_DEL_WORKFLOW_STATE_KEY,会抛出CHECKPOINTER_PRE_WORKFLOW_EXECUTION_ERROR。此时应使用InteractiveInput恢复执行,或在会话配置中显式开启强制删除。 -
会话并发冲突:确保同一会话 ID 不会被并发执行,避免多个检查点实例同时读写同一组键。
八、参考资源
- 本组件 API 文档:docs/zh/2.开发指南/API文档/openjiuwen.extensions/checkpointer/checkpointer.md
- 检查点机制总览:docs/zh/2.开发指南/高阶用法/Checkpointer检查点机制.md
- 核心实现:openjiuwen/extensions/checkpointer/redis/checkpointer.py、openjiuwen/extensions/checkpointer/redis/storage.py
- 抽象基类与工厂:openjiuwen/core/session/checkpointer/base.py、openjiuwen/core/session/checkpointer/checkpointer.py
- KV 存储后端:openjiuwen/extensions/store/kv/redis_store.py
- 单元与集成测试:tests/unit_tests/extensions/checkpointer/test_redis_checkpointer_provider.py、tests/unit_tests/extensions/checkpointer/test_integration_workflow.py、tests/unit_tests/extensions/checkpointer/test_integration_runner.py