openJiuwen agent-core 的 Redis 检查点(Checkpointer)扩展:基于 Redis 的会话状态持久化与中断恢复实践
openJiuwen agent-core 的 Redis 检查点(Checkpointer)扩展:基于 Redis 的会话状态持久化与中断恢复实践
openjiuwen.extensions.checkpointer 是 openJiuwen agent-core 提供的可选检查点扩展包,其核心子模块 redis 基于 Redis 实现了 Agent 与工作流(Workflow)运行状态的持久化、恢复与清理,并同时支持独立 Redis 与 Redis 集群两种部署模式。本文以 checkpointer.README.md 及其指向的 redis 模块 API 文档 为骨架,结合仓库源码深入讲解:读完本文你将掌握 RedisCheckpointer 的生命周期钩子语义、通过 CheckpointerFactory 与结构化配置接入检查点的完整姿势、TTL 过期策略,以及底层 RedisStore 的存储与键空间设计。
一、模块定位:检查点在 agent-core 会话体系中的角色
在 openJiuwen agent-core 中,会话(Session)承载了 Agent、Agent 团队(Agent Team)与工作流(Workflow)三类的运行上下文。Checkpointer(检查点)抽象基类定义在 openjiuwen/core/session/checkpointer/base.py,它规定了统一的生命周期接口:在执行前恢复状态、在中断/结束时保存状态、按会话释放资源。openjiuwen.extensions.checkpointer.redis 正是该接口的一个可选实现——基于 Redis 的持久化版本,与核心内置的 in_memory(内存)检查点、persistence(基于 SQLite/Shelve 的持久化检查点,见 persistence.py)并列存在。
扩展包在仓库中的物理结构如下:
openjiuwen/extensions/checkpointer/
├── redis/
│ ├── __init__.py
│ ├── checkpointer.py # RedisCheckpointer、Provider 与三类配置类
│ └── storage.py # AgentStorage、AgentGroupStorage、WorkflowStorage、GraphStore
需要特别强调的设计约束是:该实现不直接使用 Redis 客户端 API,所有 Redis 操作都经由 RedisStore 接口完成(见 redis/checkpointer.py 与 redis/storage.py 的类注释)。这意味着换存储后端时,检查点逻辑无需改动,只需要替换实现了 BaseKVStore 接口的存储对象。
二、核心 API 一览
openjiuwen.extensions.checkpointer.redis 模块公开了五个核心类,其中两个是运行时对象,三个是 Pydantic 配置模型:
| 类 | 类型 | 职责 |
|---|---|---|
RedisCheckpointer |
运行时 | 检查点实现本体,承载 Agent / Agent 团队 / 工作流的生命周期钩子 |
RedisCheckpointerProvider |
工厂 | 依据配置字典创建 RedisCheckpointer,支持独立与集群模式 |
RedisCheckpointerConfig |
配置 | 结构化、类型安全的完整检查点配置(connection + ttl) |
RedisConnectionConfig |
配置 | Redis 连接配置(客户端 / URL / 集群模式 / 额外参数) |
RedisTTLConfig |
配置 | 存储数据的 TTL(生存时间)配置 |
其中配置类均基于 Pydantic BaseModel 实现,具备字段校验、默认值与模型级验证能力。
三、RedisCheckpointer:生命周期钩子详解
RedisCheckpointer 的构造函数签名如下:
class openjiuwen.extensions.checkpointer.redis.RedisCheckpointer(redis_store: RedisStore, ttl: Optional[dict[str, Any]] = None)
- redis_store(必填):
RedisStore实例,承担所有 Redis 读写操作; - ttl(可选):TTL 配置字典,例如
{"default_ttl": 10, "refresh_on_read": True},默认None(永不过期)。
构造时(见 checkpointer.py 第 340-363 行),RedisCheckpointer 内部会创建四个存储组件,分别管理不同粒度的状态:
self._agent_storage = AgentStorage(redis_store, ttl) # 单个 Agent 状态
self._agent_group_storage = AgentGroupStorage(redis_store, ttl) # Agent 团队全局状态
self._workflow_storage = WorkflowStorage(redis_store, ttl) # 工作流自身状态
self._graph_state = GraphStore(redis_store, ttl) # 工作流图执行状态
四个存储类定义在 redis/storage.py,它们与核心模块 Checkpointer 基类中的命名空间常量一一对应(base.py 第 78-86 行):
SESSION_NAMESPACE_AGENT = "agent" # Agent 状态命名空间
SESSION_NAMESPACE_AGENT_TEAM = "agent-team" # Agent 团队状态命名空间
SESSION_NAMESPACE_WORKFLOW = "workflow" # 工作流自身状态命名空间
WORKFLOW_NAMESPACE_GRAPH = "workflow-graph" # 工作流图执行状态命名空间(与工作流自身状态分离)
3.1 Agent 生命周期钩子
pre_agent_execute(session: BaseSession, inputs)
在 Agent 执行前调用,用于恢复 Agent 状态:
async pre_agent_execute(session: BaseSession, inputs)
实现逻辑(checkpointer.py 第 365-371 行):首先通过 self._agent_storage.recover(session) 从 Redis 恢复此前保存的 Agent 状态;若 inputs 非空,则将其写入会话状态的 INTERACTIVE_INPUT 键(包装为列表),供后续执行读取。对应测试见 test_redis_checkpointer.py 中的 test_checkpointer_pre_agent_execute 与 test_checkpointer_pre_agent_execute_with_inputs。
interrupt_agent_execute(session: BaseSession)
当 Agent 需要中断等待用户交互时调用,用于保存 Agent 当前状态:
async interrupt_agent_execute(session: BaseSession)
实现(第 381-384 行)直接调用 self._agent_storage.save(session),将此刻的状态落盘,确保后续恢复能接续执行。该钩子的触发点在 openjiuwen/core/session/interaction/interaction.py,当交互流程需要用户输入时被调用。
post_agent_execute(session: BaseSession)
在 Agent 执行完成后调用,同样保存状态(第 386-389 行)。Agent 会话的 commit() 方法会触发该钩子(见 openjiuwen/core/session/agent.py 第 287-289 行)。
团队级钩子(补充说明)
除文档列出的钩子外,源码还实现了 pre_agent_team_execute 与 post_agent_team_execute(第 373-396 行),用于 Agent 团队(多智能体协作)场景:pre_agent_team_execute 通过 AgentGroupStorage.recover 恢复团队的全局状态,并将 inputs 写入全局 INTERACTIVE_INPUT;post_agent_team_execute 在团队执行结束后保存全局状态。这也解释了 AgentGroupStorage 的存在意义。
3.2 工作流生命周期钩子
pre_workflow_execute(session: BaseSession, inputs: InteractiveInput)
在工作流执行前调用,用于恢复或清理工作流状态:
async pre_workflow_execute(session: BaseSession, inputs: InteractiveInput)
实现逻辑(第 398-440 行)是分支判断:
- 若
inputs是InteractiveInput类型,调用self._workflow_storage.recover(session, inputs)恢复状态,并将交互输入写回对应节点(见WorkflowStorage._process_interactive_inputs,它支持raw_inputs全局输入与按节点 ID 的user_inputs逐节点分发,见 storage.py 第 267-284 行); - 若
inputs不是InteractiveInput(即全新发起的一次执行)且 Redis 中已存在该工作流状态:- 若会话配置项
FORCE_DEL_WORKFLOW_STATE_KEY(环境变量FORCE_DEL_WORKFLOW_STATE,常量定义见 openjiuwen/core/session/constants.py)为True,则删除图状态与工作流状态,强制执行全新流程; - 否则抛出
CHECKPOINTER_PRE_WORKFLOW_EXECUTION_ERROR异常,阻止在未显式清理的情况下重复执行。
- 若会话配置项
这个设计避免了"上一轮未完成的工作流残留状态被新执行错误继承"的隐患。
post_workflow_execute(session: BaseSession, result, exception)
在工作流执行后调用,用于保存或清理工作流状态:
async post_workflow_execute(session: BaseSession, result, exception)
实现逻辑(第 442-459 行)依据执行结果三分支:
exception非空:保存工作流检查点(保留现场)后重新抛出异常;result中不包含TASK_STATUS_INTERRUPT(即正常完成):删除图状态与工作流状态(self._graph_state.delete+self._workflow_storage.clear);result包含TASK_STATUS_INTERRUPT(执行中途因交互中断):保存工作流检查点,供下一次以InteractiveInput恢复续跑。
三个分支均有对应测试:test_checkpointer_post_workflow_execute_success、test_checkpointer_post_workflow_execute_with_exception、test_checkpointer_post_workflow_execute_with_interrupt(见 tests/unit_tests/extensions/checkpointer/test_redis_checkpointer.py)。
3.3 会话查询与资源释放
session_exists(session_id: str) -> bool
检查指定会话 ID 在 Redis 中是否存在。实现(第 461-481 行)以 f"{session_id}:" 为前缀,调用 RedisStore.get_by_prefix 做前缀匹配查询(底层使用 SCAN,非阻塞),只要存在任一前缀匹配的键即返回 True。
release(session_id: str, agent_id: Optional[str] = None)
释放指定会话的资源:
async release(session_id: str, agent_id: Optional[str] = None)
- 提供了
agent_id:仅通过AgentStorage.clear(agent_id, session_id)清理该 Agent 的检查点; - 未提供
agent_id:以f"{session_id}:"为前缀,通过RedisStore.delete_by_prefix(prefix, batch_size=500)按批(每批 500 个键)删除整个会话的所有键。
test_checkpointer_release_with_agent_id 与 test_checkpointer_release_without_agent_id 分别覆盖两种场景(后者还验证了不会误删其他会话的键)。
graph_store() -> Store
返回图状态存储对象(GraphStore),供工作流图执行引擎读写图检查点数据。
四、RedisCheckpointerProvider:工厂接入方式
RedisCheckpointerProvider 通过 @CheckpointerFactory.register("redis") 装饰器注册到核心的 CheckpointerFactory(见 checkpointer.py 第 229-230 行,工厂实现见 openjiuwen/core/session/checkpointer/checkpointer.py),因此可以通过工厂按类型字符串 "redis" 一键创建:
async create(conf: dict) -> Checkpointer
4.1 配置格式
create 方法接收一个配置字典,包含 connection(必填)与可选的 ttl 键:
{
"connection": {
"redis_client": Redis(...), # 可选:预配置的客户端实例
"url": "redis://...", # 可选:连接 URL(未提供 redis_client 时必填)
"cluster_mode": True, # 可选:显式开启集群模式(为 None 时从 URL 自动检测)
"connection_args": {...} # 可选:传递给 Redis 客户端的额外连接参数
},
"ttl": { # 可选
"default_ttl": 5, # 可选:默认 TTL(单位:分钟)
"refresh_on_read": True # 可选:读取时是否刷新 TTL
}
}
create 的内部流程(第 286-337 行):先通过 RedisCheckpointerConfig.model_validate(conf) 解析并自动校验配置;若提供了 redis_client 则直接包装为 RedisStore;否则依据 url 与集群判定结果分别创建 RedisCluster.from_url 或 Redis.from_url 客户端,再包装为 RedisStore;最后构造 RedisCheckpointer(redis_store, ttl_dict) 返回。
4.2 三种典型接入样例
独立 Redis(最小配置)
from openjiuwen.core.session.checkpointer import CheckpointerFactory, CheckpointerConfig
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)
4.3 工厂的全局注册与默认实例
核心工厂 CheckpointerFactory 采用注册表模式:register(name) 装饰器将 Provider 实例化后存入 _registry;create(checkpointer_conf) 根据 CheckpointerConfig.type 找到对应 Provider 并调用其 create(conf)。工厂还提供 set_default_checkpointer / set_checkpointer(store_type, checkpointer) / get_checkpointer(store_type=None) 三个方法用于全局管理实例:业务侧可以在应用启动时创建好 Redis 检查点并通过 set_default_checkpointer 设置为默认实例,之后 CheckpointerFactory.get_checkpointer() 会返回它;未设置任何默认值时,系统回退到内置的 default_inmemory_checkpointer(内存实现)。集成测试 test_integration_workflow.py 展示了完整用法:启动时创建 Redis 检查点并 set_default_checkpointer,测试结束后恢复内存默认实例并关闭 Redis 连接。
五、配置类深解:校验规则与集群检测
5.1 RedisConnectionConfig
class openjiuwen.extensions.checkpointer.redis.RedisConnectionConfig(
redis_client: Optional[Union[Redis, RedisCluster]] = None,
url: Optional[str] = None,
cluster_mode: Optional[bool] = None,
connection_args: dict[str, Any] = {}
)
字段语义与校验规则(源码 checkpointer.py 第 64-178 行):
| 字段 | 默认值 | 说明 |
|---|---|---|
redis_client |
None |
预配置的 Redis / RedisCluster 异步客户端实例;若提供,其余连接参数全部被忽略 |
url |
None |
连接 URL。合法前缀仅四种:redis://、rediss://(TLS)、redis+cluster://、rediss+cluster://;否则字段校验器 validate_url 抛出 ValueError |
cluster_mode |
None |
显式开启/关闭集群模式;为 None 时从 URL 方案自动检测 |
connection_args |
{} |
透传给 Redis 客户端的额外连接参数(如连接池、超时等) |
模型级校验器 validate_config 确保 redis_client 与 url 至少提供其一,否则抛错。
is_cluster_mode() -> bool:集群判定优先级为——先看是否传入了 RedisCluster 实例;其次看显式 cluster_mode 标志;最后回退到 URL 前缀(redis+cluster:// 或 rediss+cluster:// 视为集群)。
get_connection_url() -> Optional[str]:获取连接 URL,并做规范化——把 redis+cluster:// 替换为 redis://、rediss+cluster:// 替换为 rediss://(因为 RedisCluster.from_url 需要标准前缀)。
5.2 RedisTTLConfig
class openjiuwen.extensions.checkpointer.redis.RedisTTLConfig(
default_ttl: Optional[float] = None,
refresh_on_read: bool = False
)
| 字段 | 默认值 | 说明 |
|---|---|---|
default_ttl |
None |
存储数据的默认 TTL,单位是分钟;设置后所有写入的数据都会携带该过期时间 |
refresh_on_read |
False |
为 True 时,每次读取命中数据都会刷新 TTL,延长高频访问数据的存活时间 |
TTL 的底层换算与生效位置在 storage.py 第 48-63 行:_ttl_seconds = int(default_ttl * 60)(分钟转秒),随后所有 set / EXPIRE 均以秒为单位;refresh_on_read=True 时,_refresh_ttl 会在 recover 读取后通过 RedisStore.refresh_ttl(底层为 pipeline 批量 EXPIRE,见 redis_store.py 第 466-505 行)刷新键的过期时间,并且即使反序列化失败也会尝试刷新(保证热数据不因偶发解析错误而过期丢失)。测试 test_provider_create_with_ttl 验证了 default_ttl=5 时 _ttl_seconds == 5 * 60 且 refresh_on_read 生效。
5.3 RedisCheckpointerConfig
class openjiuwen.extensions.checkpointer.redis.RedisCheckpointerConfig(
connection: RedisConnectionConfig,
ttl: Optional[RedisTTLConfig] = None
)
完整配置的容器类:connection 必填,ttl 可选。除了经由 create(conf) 传 dict 的方式,也可以直接以类型安全方式构造:
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)
)
六、底层存储设计:RedisStore 与键空间
6.1 RedisStore:异步 KV 存储抽象
RedisStore 定义在 openjiuwen/extensions/store/kv/redis_store.py,基于 redis.asyncio 实现,实现类注释明确声明了以下关键特性:
- 值编码:默认以 UTF-8 字符串存储/读取,Redis 返回的 bytes 自动解码;
- 前缀操作非阻塞:
get_by_prefix/delete_by_prefix使用SCAN迭代(而非阻塞的KEYS),集群模式下自动跨节点扫描;批量删除以 500 个键为一批 控制内存与网络往返; - 批量与原子操作:提供
mget、batch_delete、exclusive_set(SET NX原子写,可配合EX过期时间)、pipeline()(独立模式下单服务器批量执行、集群模式下按哈希槽自动路由,跨槽操作由客户端处理); - TTL 批量刷新:
refresh_ttl(keys, ttl_seconds)用 pipeline 批量EXPIRE,ttl_seconds <= 0时跳过,刷新失败仅记 warning 不阻断主流程。
6.2 序列化与键结构
所有状态在写入前都通过 create_serializer("pickle") 序列化为 (dump_type, blob) 二元组,拆分为类型键 + 值键两个键存储(见 BaseSingleStateStorage._build_state_keys,storage.py 第 138-145 行),键由 build_key_with_namespace 以冒号拼接生成,整体模式为:
{session_id}:{namespace}:{entity_id}:{suffix}
具体到各类存储:
| 存储类 | 键前缀模式 | 键后缀 | 说明 |
|---|---|---|---|
AgentStorage |
{session_id}:agent:{agent_id}: |
agent_state_blobs 与 agent_state_blobs_dump_type |
单 Agent 状态,2 个键 |
AgentGroupStorage |
{session_id}:agent-team:{group_id}: |
agent_group_state_blobs 与 agent_group_state_blobs_dump_type |
Agent 团队全局状态,2 个键 |
WorkflowStorage |
{session_id}:workflow:{workflow_id}: |
workflow_state_blobs(+dump_type) 与 workflow_update_blobs(+dump_type) |
工作流自身状态与增量更新,最多 4 个键 |
GraphStore |
{session_id}:workflow-graph:{ns}: |
checkpoint_data_type 与 checkpoint_data_value |
工作流图执行状态,与工作流自身状态分离 |
读写均通过 pipeline 批量执行(如 AgentStorage.recover 一次 pipeline 取 2 个键、WorkflowStorage.recover 一次取 4 个键)。exists 判断要求"类型键与值键同时存在"才算状态存在;工作流的 updates 键是可选的,仅要求 state 两个键存在。
6.3 钩子接线点:检查点何时被调用
检查点钩子并非孤立 API,它们被核心执行引擎在关键时机调用(均有源码佐证):
- 工作流:
CompiledGraph._invoke在执行前调用pre_workflow_execute(session, inputs),执行完毕后调用post_workflow_execute(session, result, exception),取消(CancelledError)时也会兜底调用post_workflow_execute(session, {}, None)(见 openjiuwen/core/graph/graph.py 第 315-352 行); - Agent 会话:
AgentSession.pre_run调用pre_agent_execute,commit()调用post_agent_execute(见 openjiuwen/core/session/agent.py 第 253-289 行); - 交互中断:需要用户输入时,交互模块调用
interrupt_agent_execute保存现场(见 openjiuwen/core/session/interaction/interaction.py)。
由此形成完整的"中断 → 保存 → 恢复续跑"闭环:工作流因交互中断时,TASK_STATUS_INTERRUPT 触发状态保存;用户回传输入时以 InteractiveInput 再次进入 pre_workflow_execute,从 Redis 恢复状态并注入 INTERACTIVE_INPUT,从而无缝接续执行。
七、测试与验证
该扩展配有完整的单元测试与集成测试,位于 tests/unit_tests/extensions/checkpointer/:
| 测试文件 | 覆盖内容 |
|---|---|
conftest.py |
共享 fixture:Redis 客户端、RedisStore、RedisCheckpointer、带 TTL 实例、mock 的 Agent/Workflow 会话(需要本地 Redis 环境,模块级 skip) |
test_redis_checkpointer.py |
Agent 与工作流各生命周期钩子的保存/恢复/清理行为、release 两种粒度、graph_store 返回类型 |
test_redis_checkpointer_provider.py |
Provider 以 redis_client / url / 带 TTL 三种方式创建实例,以及缺失连接配置时抛出 ValueError |
test_integration_runner.py / test_integration_workflow.py |
端到端验证:真实 Workflow 在 Redis 检查点下执行交互式工作流(InteractiveNode4Cp 等 mock 节点),并演示工厂全局注册与清理流程 |
需要说明的是:上述测试依赖本地 Redis 服务(conftest.py 中默认连接 redis://127.0.0.1:6379),仓库中以 pytest.skip(..., allow_module_level=True) 标记,在无 Redis 环境下默认跳过。
八、实践建议与注意事项
- 集群模式接入:生产环境若使用 Redis Cluster,建议显式设置
cluster_mode: True,或直接使用redis+cluster:///rediss+cluster://前缀的 URL(is_cluster_mode会从 URL 自动判定,get_connection_url会自动规范化前缀)。集群模式下 SCAN、pipeline 与批量删除会自动按哈希槽路由,但跨槽批量操作(如mget、batch_delete涉及多个槽位)性能可能略降,客户端会自动拆分处理。 - TTL 与热数据:
default_ttl单位为分钟(内部换算为秒),配合refresh_on_read: True可让高频访问的会话"越活跃越长寿",适合长会话场景;对不设 TTL 的场景保持默认None即可。 - 工作流重复执行的防护:非交互输入下若 Redis 残留工作流状态,默认会抛
CHECKPOINTER_PRE_WORKFLOW_EXECUTION_ERROR。需要强制重跑时,通过会话配置(对应环境变量FORCE_DEL_WORKFLOW_STATE,键常量_force_del_workflow_state,见 constants.py)开启强制清理,或先调用release(session_id)显式释放会话资源。 - 资源释放:会话结束时务必调用
release(session_id)或release(session_id, agent_id)清理 Redis 键,避免残留键占用空间;未指定agent_id时按前缀分批删除(每批 500),不会误伤其他会话。 - 应用启动接线:推荐在应用启动阶段通过
CheckpointerFactory.create(CheckpointerConfig(type="redis", conf={...}))创建实例并调用CheckpointerFactory.set_default_checkpointer(checkpointer)全局生效,与 test_integration_workflow.py 中的示范保持一致。 - 连接生命周期:由 URL 创建的 Redis 客户端由 Provider 负责创建,使用完毕后应关闭(测试中通过
checkpointer._redis_store.redis.aclose()清理);建议在生产中为redis_client配置连接池与超时参数(通过connection_args传入),并可复用预配置客户端避免重复建连。
综上,openjiuwen.extensions.checkpointer.redis 为 openJiuwen agent-core 提供了生产可用的分布式会话检查点能力:既可以通过 CheckpointerFactory 一行接入,也保留了配置类级别的精细控制;既有完整的中断恢复语义,又有 TTL 过期与按前缀清理的运维手段,是构建长时任务、多轮交互与可恢复 Agent/工作流的基础设施之一。