[Feature]: 为 QueueFS 增加 Redis 后端支持/Add Redis Backend Support to QueueFS
本 issue 为双语版本(英文 + 中文)。中文版在前,英文版在后。 This issue is bilingual (English + Chinese). Chinese version first, English version below.
中文版 / Chinese Version
Problem Statement
当前 QueueFS 有两个后端:
memory:轻量、非持久化、dequeue语义较弱sqlite:持久化,具备pending -> processing -> ack -> recover_stale语义
从 Python 业务层视角看,Redis 后端必须对齐 sqlite 语义,而不是对齐 memory 语义。
当前缺口主要有:
- 目前还没有一个 Redis backend 能同时保留 QueueFS 的持久化能力和状态化投递语义。
- 当前 Python worker 流程依赖
dequeue -> process -> ack,因此 Redis backend 不能像memorybackend 一样过早删除消息。 - Redis 场景下,多实例失败后的
processingstale 消息恢复语义尚未定义清楚。 - 队列注册、payload 存储、processing 归属以及 stale 恢复需要一套 Redis 原生的数据模型,并保证状态迁移原子性。
- 当前 QueueFS 配置链路还没有把 Redis 配置按嵌套对象、按 backend 语义正确透传下去。
- Redis backend 还没有明确
singleton、cluster和sentinel三种连接模式下的一致行为和配置约束。
相关实现入口:
crates/ragfs/src/plugins/queuefs/backend.rscrates/ragfs/src/plugins/queuefs/mod.rsopenviking/utils/agfs_utils.pyopenviking/storage/queuefs/named_queue.py
Proposed Solution
1. 引入一个与 SQLite 语义对齐的 Redis backend
为 QueueFS 增加 redis backend,并显式要求它的行为与当前 sqlite backend 对齐。
目标行为:
- 队列状态持久化
dequeue只把消息从pending迁移到processingack是唯一真正删除处理中消息的操作recover_stale能把 staleprocessing消息放回pending- Python 层继续沿用当前的
dequeue -> process -> ack流程,不产生行为偏差 - Redis 连接模式支持
singleton、cluster和sentinel
本次变更不追求 exactly-once,投递语义仍然是 at-least-once。
2. 为队列元信息、待处理状态、处理中状态和 payload 定义 Redis key 模型
用 Redis key 来承载 SQLite 当前在 queue_metadata 和 queue_messages 里表达的语义。
建议的 key 结构:
{key_prefix}:ov:queue:namesSET- 记录队列注册表
{key_prefix}:ov:queue:{queue}:metaHASH- 存储
created_at、last_updated、last_enqueue_ts
{key_prefix}:ov:queue:{queue}:pendingLIST- 按 FIFO 顺序存放待处理
message_id
{key_prefix}:ov:queue:{queue}:processingZSET- member 为
{message_id}|{instance_id},score 为processing_started_at
{key_prefix}:ov:queue:{queue}:msg:{message_id}STRING- 存储序列化后的
StoredMessageJSON payload
{key_prefix}:ov:queue:instance:{instance_id}:alive- 带 TTL 的
STRING - 表示实例存活状态,用于 stale 恢复
- 带 TTL 的
key_prefix 默认值为 default。所有 Redis key 都以 {key_prefix}:ov: 开头,其中 { 和 } 是 Redis key 中实际存在的 Cluster hash tag 字符,不是文档占位符。key_prefix=default 时,实际前缀为 {default}:ov:。三种连接模式都使用相同的 key 结构;在 cluster 模式下,同一 key_prefix 的全部 QueueFS key 通过 {key_prefix} 固定到同一个 slot,以满足 Lua 脚本的同 slot 要求。key_prefix 必须非空,且不能包含 { 或 }。
3. 用 Lua 脚本保证关键状态迁移的原子性
核心队列操作都应使用 Lua 脚本,以保持与 SQLite 相近的原子语义。
需要脚本化的原子操作包括:
create_queue- 原子注册队列并初始化元信息
enqueue- 原子写入 payload、把
message_id追加到 pending,并更新 meta
- 原子写入 payload、把
dequeue- 原子弹出最早 pending、校验 payload、标记 processing,并返回 payload
ack- 原子删除匹配的 processing 记录和 payload
clear- 原子删除单个队列的 pending、processing 和 payload
remove_queue- 原子删除目标队列及其所有子队列的元信息、pending、processing 和 payload
recover_stale- 原子回收死实例占用的 processing 消息
Redis backend 不能把这些状态迁移实现成多次“尽力而为”的网络往返。
4. 引入实例心跳与“仅启动时执行一次”的 stale 恢复
backend 启动时生成唯一 instance_id,并维护实例心跳 key:
- TTL:
30s - 续约间隔:
10s
recover_stale 的逻辑应当是:
- 扫描每个队列的
processingzset - 解析
{message_id}|{instance_id} - 检查
{key_prefix}:ov:queue:instance:{instance_id}:alive是否仍存在 - 将死实例占用的消息重新放回
pending
这套恢复逻辑只在 backend 启动时执行一次。
在运行期间:
- QueueFS 不执行后台周期恢复
- 对于心跳尚未过期的实例,其占用的 processing 消息不会被回收
- 如果新 backend 在旧实例心跳失效前启动,这部分消息不会被立即恢复
5. 在 storage.agfs.queuefs.redis 下增加嵌套 Redis 配置
在 storage.agfs.queuefs.backend 中增加 redis 选项,并通过 storage.agfs.queuefs.redis 嵌套对象承载 Redis 专属配置。
配置示例:
{
"storage": {
"agfs": {
"queuefs": {
"backend": "redis",
"redis": {
"mode": "singleton",
"key_prefix": "default",
"endpoints": ["redis://127.0.0.1:6379"],
"master_name": null,
"username": null,
"password": null,
"sentinel_username": null,
"sentinel_password": null,
"db": 0,
"connect_timeout_ms": 3000,
"command_timeout_ms": 3000,
"tls_enabled": false,
"tls_insecure_skip_verify": false
}
}
}
}
}
queuefs.redis.mode 表示 Redis 拓扑模式,与 queuefs.mode 的 shared / worker QueueFS 路径命名空间模式相互独立。
Cluster 配置示例:
{
"mode": "cluster",
"key_prefix": "default",
"endpoints": [
"redis://redis-cluster-0:6379",
"redis://redis-cluster-1:6379"
],
"db": 0
}
Sentinel 配置示例:
{
"mode": "sentinel",
"key_prefix": "default",
"endpoints": [
"redis://redis-sentinel-0:26379",
"redis://redis-sentinel-1:26379"
],
"master_name": "mymaster",
"username": "queue-user",
"password": "queue-password",
"sentinel_username": "sentinel-user",
"sentinel_password": "sentinel-password",
"db": 0
}
规则如下:
- Python
openviking/utils/agfs_utils.py::_build_queuefs_plugin_config()在backend=redis时原样透传queuefs.redis - Rust
QueueFSPlugin::parse_backend_config()解析嵌套redis对象并构造RedisQueueOptions db_path和busy_timeout_ms仍然只对 SQLite 生效recover_stale_sec不进入 Redis backend;Redis 恢复逻辑固定按实例心跳失活判断mode必须为singleton、cluster或sentinelkey_prefix必须非空且不能包含{或},Python 和 Rust 两层都要校验singleton模式的endpoints长度必须等于 1cluster和sentinel模式的endpoints至少包含一个地址sentinel模式必须配置非空master_namecluster模式只允许db=0master_name、sentinel_username和sentinel_password在非sentinel模式下不生效- Redis backend 内部使用固定容量为 2 的
r2d2同步连接池,分别满足一路串行业务命令和一路心跳续约同时 checkout 的需求;pool checkout timeout 固定为 5 秒,池大小和 checkout timeout 均不对外开放配置
Alternatives Considered
- 直接沿用当前
memorybackend 的 Redis 语义
- 这样实现会更小
- 但会破坏当前 Python
dequeue -> process -> ack契约,也无法对齐 SQLite 的恢复语义
- 连同 Redis backend 一起重写 Python worker 流程
- 这样后端设计自由度更高
- 但会显著扩大范围,不适合这次仅增加 backend 的目标
- 增加运行期周期 stale 恢复
- 这样崩溃后的人工介入会更少
- 但会引入比首版 Redis backend 更高的运行时复杂度和协调成本
Feature Area
Core (Storage/Engine)
Use Case
QueueFS 需要一个 Redis backend,用于在保留当前 Python 业务层行为契约的前提下,把队列状态存到 Redis。
典型场景包括:
- 用 Redis 替代 SQLite 作为持久化队列状态存储
- 在多实例环境下保留可恢复的
processing归属语义 - 在
singleton、cluster或sentinel部署中提供相同的 QueueFS 行为 - 不改动当前 Python worker 生命周期
- 通过不同
key_prefix隔离多个 QueueFS 租户或业务域
Additional Context
本 issue 来源于 QueueFS Redis backend 的内部设计稿。
相关文件:
crates/ragfs/src/plugins/queuefs/backend.rscrates/ragfs/src/plugins/queuefs/mod.rscrates/ragfs/src/plugins/queuefs/redis_backend.rsopenviking/utils/agfs_utils.pyopenviking/storage/queuefs/named_queue.py
本次设计基线是:
- 以 SQLite 语义为准
- 用 Redis key 模型承载队列状态
- 用 Lua 脚本保证状态迁移原子性
- 在
singleton、cluster和sentinel三种模式下保持一致的 QueueFS 契约 - 不以当前
memorybackend 作为语义参考
为避免 issue 化过程中丢失原设计信息,下面保留原设计中的完整细节展开。保持 issue 模板层级不变,但补回所有关键设计点。
-
当前 SQLite 表结构与 Redis 对应设计
SQLite表 SQLite表结构 SQLite数据示例 对应Redis key结构设计 Redis数据实例 queue_metadataqueue_name TEXT PRIMARY KEY, created_at INTEGER DEFAULT strftime('%s','now'), last_updated INTEGER DEFAULT strftime('%s','now')queue_name='Semantic', created_at=1753890000, last_updated=1753890123{key_prefix}:ov:queue:names(SET) +{key_prefix}:ov:queue:{queue_name}:meta(HASH)SADD {default}:ov:queue:names Semantic;HSET {default}:ov:queue:Semantic:meta created_at 1753890000 last_updated 1753890123queue_messagesid INTEGER PRIMARY KEY AUTOINCREMENT, queue_name TEXT NOT NULL, message_id TEXT NOT NULL, data TEXT NOT NULL, timestamp INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', processing_started_at INTEGER, created_at INTEGER DEFAULT strftime('%s','now')id=42, queue_name='Semantic', message_id='9d5d2f2e-7e9d-4f3f-9b73-1c0f5b7b0abc', data='{"id":"9d5d2f2e-7e9d-4f3f-9b73-1c0f5b7b0abc","data":[104,101,108,108,111],"timestamp":1753890000}', timestamp=1753890000, status='processing', processing_started_at=1753890055, created_at=1753890000{key_prefix}:ov:queue:{queue_name}:pending(LIST) +{key_prefix}:ov:queue:{queue_name}:processing(ZSET) +{key_prefix}:ov:queue:{queue_name}:msg:{message_id}(STRING)RPUSH {default}:ov:queue:Semantic:pending 9d5d2f2e-7e9d-4f3f-9b73-1c0f5b7b0abc;`ZADD {default}:ov:queue:Semantic:processing 1753890055 '9d5d2f2e-7e9d-4f3f-9b73-1c0f5b7b0abc -
为什么
queue_messages在 Redis 中必须拆开SQLite 用一张
queue_messages表同时表达了三类信息:- 队列顺序
- 消息内容
- 消息状态:
pending/processing
Redis 没有表抽象,所以这三类语义必须拆到不同 key 类型里:
- 用
LIST表达 FIFO 的 pending 顺序 - 用
ZSET表达 processing 状态和恢复时间 - 用
STRING表达消息 payload
如果要保持当前 QueueFS 的语义一致性,这个拆分是必须的。
-
Key 结构设计
key_prefix用于隔离不同业务的 QueueFS 数据,默认值为default。所有 Redis key 都以{key_prefix}:ov:开头,其中{和}是 Redis key 中实际存在的 Cluster hash tag 字符,不是文档占位符。key_prefix=default时,实际前缀为{default}:ov:。不同业务配置不同的key_prefix,彼此的队列注册表、消息和实例心跳完全隔离。三种连接模式使用完全相同的 key 格式。
cluster模式下,同一key_prefix的全部 QueueFS key 通过{key_prefix}hash tag 固定到同一个 slot,确保 Lua 脚本涉及的 names、meta、pending、processing 和 payload key 满足 Redis Cluster 的同 slot 要求。key_prefix不能为空,且不能包含{或}。假设
key_prefix为default,队列名为Semantic,消息 ID 为9d5d...。- 实例存活状态
{key_prefix}:ov:queue:instance:{instance_id}:alive- 类型:
STRING - 值:固定占位值,例如
1 - TTL:30 秒
- 作用:表示某个实例当前存活,并通过周期性续约维持有效期
- 队列注册表
{key_prefix}:ov:queue:names- 类型:
SET - 作用:记录有哪些队列
- 队列元信息
{key_prefix}:ov:queue:{queue}:meta- 类型:
HASH - 字段:
created_atlast_updatedlast_enqueue_ts
- 待处理队列
{key_prefix}:ov:queue:{queue}:pending- 类型:
LIST - 值:按顺序排列的
message_id - 作用:作为 FIFO 出队源
- 处理中队列
{key_prefix}:ov:queue:{queue}:processing- 类型:
ZSET - member:
{message_id}|{instance_id} - score:
processing_started_at - 作用:记录正在处理的消息、处理开始时间,以及对应实例归属;
processing_started_at用于可观测性和调试,不参与实例失活回收判定 - 格式约束:
message_id和instance_id使用 UUID/ULID,不包含|,Lua 和 Rust 统一按首个|分割
- 消息内容
{key_prefix}:ov:queue:{queue}:msg:{message_id}- 类型:
STRING - 值:序列化后的
StoredMessageJSON
- 实例存活状态
-
操作映射
QueueFS操作 SQLite语义 Redis设计 create_queue向 queue_metadata插入一行使用 Lua 脚本原子执行 SADD {key_prefix}:ov:queue:names {queue}并初始化{key_prefix}:ov:queue:{queue}:metaqueue_exists查 queue_metadata或已有消息SISMEMBER {key_prefix}:ov:queue:names {queue}list_queues查 metadata 表,兼容历史回填 SMEMBERS {key_prefix}:ov:queue:names,再在代码里做队列名前缀过滤enqueue向 queue_messages插入一条pending记录使用 Lua 脚本原子检查队列注册状态,再执行 SET msg payload、RPUSH pending msg_id并更新 metapeek读取最前面的 pending,但不改状态LINDEX pending 0,再GET msg payloaddequeue最早的 pending变成processing使用 Lua 脚本原子地移除第一个 pending id,并把 `{message_id} size统计 status='pending'的行数LLEN pendingack按 message_id删除一条processing记录使用 Lua 脚本扫描 processing,按 member 中的message_id匹配并删除对应记录,再DEL msg payloadclear删除该队列所有消息行 使用 Lua 脚本原子删除 pending、processing以及该队列下所有 payload keyremove_queue删除目标队列及其全部子队列 使用 Lua 脚本从队列注册表筛选名称等于 {queue}或以{queue}/开头的队列,并原子删除全部匹配队列recover_stale在启动时,把异常实例占用的 processing改回pending使用 Lua 脚本扫描 processing,按 `{message_id} -
dequeue语义要求Redis 实现必须对齐 SQLite 语义,不能对齐
memory语义。目标行为:
- 取出最早的一条
pending消息 - 暂时不删除 payload
- 先把这条消息标记成
processing - 把 payload 返回给调用方
- 只有调用
ack后才真正删除
这样才能和当前 Python worker 流程保持一致:
dequeue- 业务处理
ack
- 取出最早的一条
-
原子流程
- Create Queue
- 使用 Lua 脚本实现
- 原子步骤:
SADD {key_prefix}:ov:queue:names {queue}- 初始化
{key_prefix}:ov:queue:{queue}:meta - 返回是否创建成功
- 原因:
- 保证队列注册和元信息初始化一次完成
- 避免只注册队列名、但缺少元信息的半成功状态
- Enqueue
- 使用 Lua 脚本实现
- 脚本落地方式:
- 把 Lua 脚本写成 Rust 字符串常量,和 QueueFS Redis backend 代码一起管理
- 由 Rust 在运行时通过
EVAL/EVALSHA下发到 Redis 执行
- 原子步骤:
- 序列化
StoredMessage SISMEMBER {key_prefix}:ov:queue:names {queue}- 队列未注册时,在写入任何 key 前返回
NotFound SET {key_prefix}:ov:queue:{queue}:msg:{msg_id} {payload}RPUSH {key_prefix}:ov:queue:{queue}:pending {msg_id}- 按需更新
{key_prefix}:ov:queue:{queue}:meta - 返回 enqueue 结果
- 序列化
- 原因:
- 让
Enqueue/Dequeue/Ack三个核心操作统一采用 Lua 原子执行,设计更整齐 - 减少网络抖动或客户端异常导致的中间态
- 避免出现 payload 已写但队列未入列,或队列已入列但附加元信息未更新完成的半成功状态
- 避免多实例下
remove_queue与enqueue并发时,出现 enqueue 返回成功但消息不在队列注册表中的孤儿状态
- 让
- Dequeue
- 使用 Lua 脚本实现,不拆成多次网络往返
- 脚本落地方式:
- 把 Lua 脚本写成 Rust 字符串常量,和 QueueFS Redis backend 代码一起管理
- 由 Rust 在运行时通过
EVAL/EVALSHA下发到 Redis 执行
- 原子步骤:
LPOP {key_prefix}:ov:queue:{queue}:pending- 若为空,返回
nil GET {key_prefix}:ov:queue:{queue}:msg:{msg_id}- payload 不存在时使用
LPUSH把message_id放回 pending,并返回存储损坏错误 - 生成
{message_id}|{instance_id}的 processing member ZADD {key_prefix}:ov:queue:{queue}:processing {now} {processing_member}- 返回 payload
- 原因:
- 避免拿走 pending id 之后,却没来得及标记为 processing
- 保持
pending -> processing切换与 SQLite 事务语义一致
- Ack
- 使用 Lua 脚本实现
- 脚本落地方式:
- 把 Lua 脚本写成 Rust 字符串常量,和 QueueFS Redis backend 代码一起管理
- 由 Rust 在运行时通过
EVAL/EVALSHA下发到 Redis 执行
- 原子步骤:
- 在
processing中扫描 member,并按分隔串中的message_id查找对应 member ZREM {key_prefix}:ov:queue:{queue}:processing {processing_member}DEL {key_prefix}:ov:queue:{queue}:msg:{msg_id}- 返回是否真的删除成功
- 在
- Instance Heartbeat
- 服务启动时生成唯一
instance_id,使用UUID或ULID即可 - 实例启动后执行以下动作:
- 初始化
instance_id - 写入
{key_prefix}:ov:queue:instance:{instance_id}:alive - 设置 TTL 为 30 秒
- 每 10 秒续约一次该 key
- backend 正常关闭时停止心跳并删除该 key,使下一实例启动时立即恢复未完成任务
- 初始化
- 原因:
- 让 Redis 后端具备多实例下的实例存活判断能力
- 为
recover_stale提供“实例是否失活”的判断依据
- 服务启动时生成唯一
- Recover Stale
- 使用 Lua 脚本实现,在 backend 启动时执行一次
- 原子步骤:
- 扫描
{key_prefix}:ov:queue:{queue}:processing中的 member - 按
{message_id}|{instance_id}解析每个 member 中的message_id和instance_id - 检查
{key_prefix}:ov:queue:instance:{instance_id}:alive是否仍然存在 - 对于实例心跳已经失效的
message_id:ZREM processing {processing_member}RPUSH pending {message_id}
- 扫描
- 原因:
- 保证实例失活判断、状态移除和重新入队在一次脚本执行中完成
- 避免恢复到一半中断,留下部分消息已移除但未重新入队的中间态
- 只回收异常实例占用的 processing 消息,避免多实例并存时误回收正常处理中的任务
- 运行期间不执行后台周期恢复。异常退出实例的心跳最多在 30 秒后失效;
recover_stale只处理 backend 启动时已经失效的实例。backend 在旧实例心跳失效前启动时不会回收对应消息,运行期间需要通过 Redis 运维操作手动处理,QueueFS 不提供运行期恢复接口。
- Create Queue
-
消息内容格式
Redis 中的 payload 直接沿用当前 SQLite 的
StoredMessageJSON:{ "id": "9d5d2f2e-7e9d-4f3f-9b73-1c0f5b7b0abc", "data": [104, 101, 108, 108, 111], "timestamp": 1753890000 }原因:
- Python 层行为不用改
- 不引入新的序列化迁移成本
- 保留现有的非 UTF-8 字节兼容性
-
失败语义
目标投递语义仍然是 at-least-once。
场景 结果 enqueue 成功,worker 尚未消费 消息仍留在 pendingdequeue 成功,业务处理中崩溃,尚未 ack 消息停留在 processing;旧实例心跳失效后启动的 backend 通过recover_stale将其放回pendingdequeue 成功,ack 成功后崩溃 消息已经完成,不再重试 dequeue 成功,但 payload key 丢失 视为存储损坏,应返回错误并记录日志 -
实现边界与细节
- 配置透传
-
QueueFS 配置入口包含这些字段:
backenddb_pathrecover_stale_secbusy_timeout_msredis
-
Redis backend 的配置面按下面的方式实现:
storage.agfs.queuefs.backend增加redisstorage.agfs.queuefs下新增redis子对象- Python 配置组装阶段把
queuefs.redis原样透传到 QueueFS plugin config - Rust
QueueFSPlugin::parse_backend_config()在backend=redis时解析redis子对象并构造RedisQueueOptions
-
配置结构使用嵌套对象,不把 Redis 参数平铺到
queuefs顶层 -
queuefs.redis.mode表示 Redis 拓扑模式,与queuefs.mode的shared/workerQueueFS 路径命名空间模式相互独立 -
redis子对象字段定义:字段 类型 说明 modestringRedis 连接模式,允许值为 singleton、cluster、sentinel,默认值为singletonkey_prefixstringQueueFS Redis key 业务前缀,默认值为 default,不能为空;所有 key 使用{key_prefix}:ov:*endpointsstring[]Redis endpoint 列表; singleton必须且只能配置一个,cluster至少配置一个初始节点,sentinel至少配置一个 Sentinel 节点master_namestring | nullSentinel 服务名,仅 sentinel模式使用且必须配置usernamestring | nullRedis 数据节点 ACL 用户名 passwordstring | nullRedis 数据节点 ACL 密码 sentinel_usernamestring | nullSentinel ACL 用户名,仅 sentinel模式使用sentinel_passwordstring | nullSentinel ACL 密码,仅 sentinel模式使用dbintRedis database 编号 connect_timeout_msint物理建连超时,单位毫秒;Singleton 用于目标实例,Cluster 用于数据节点,Sentinel 用于发现 Master 后的数据节点连接 command_timeout_msint命令执行超时,单位毫秒 tls_enabledbool是否启用 TLS tls_insecure_skip_verifybool是否跳过 TLS 证书校验 -
透传和解析规则如下:
- Python
openviking/utils/agfs_utils.py::_build_queuefs_plugin_config()在backend=redis时写入:backend = "redis"redis = queuefs.redis
- Rust
crates/ragfs/src/plugins/queuefs/mod.rs在 plugin 元数据中新增:backend允许值包含redisredis对象参数
db_path和busy_timeout_ms只在 SQLite backend 生效recover_stale_sec不进入 Redis backend;Redis 启动恢复固定按实例心跳失活判断执行mode必须为singleton、cluster或sentinelkey_prefix不能为空且不能包含{或},Python 和 Rust 两层执行相同校验singleton模式的endpoints长度必须等于 1cluster和sentinel模式的endpoints至少包含一个地址sentinel模式必须配置非空master_namecluster模式只允许db=0master_name、sentinel_username和sentinel_password在非sentinel模式下不生效
- Python
-
Redis 连接参数和
key_prefix只存在于queuefs.redis子对象内,不改动顶层配置结构。Redis backend 内部使用固定容量为 2 的r2d2同步连接池,分别满足一路串行业务命令和一路心跳续约同时 checkout 的需求。pool checkout timeout 固定为 5 秒。连接池大小和 checkout timeout 均为内部参数,不对外提供配置。 -
池容量统计逻辑连接,不统计 endpoint 或 Redis 节点数量。Singleton 和 Sentinel 的一个 pooled item 对应一条数据节点连接;Cluster 的一个 pooled item 对应一个
ClusterConnection,由它在内部根据 Cluster 拓扑维护多个节点连接。Cluster 初始 endpoints 或运行期发现的节点数量不会直接增加r2d2pool 容量。
-
- Redis 连接模式
- 三种模式分别为
singleton、cluster和sentinel singleton使用redis::Client+r2d2::Poolcluster使用redis::cluster::ClusterClient+r2d2::Poolsentinel使用redis::sentinel::SentinelClient+ 最小r2d2manager- 关键边界:
crates/ragfs/Cargo.toml需要为redis依赖启用cluster、sentinel和r2d2featurer2d2的职责是同步连接复用、容量限制、健康检查和被动淘汰,不把连接池表述为主动自动重连- Cluster 直接使用 redis-rs 原生
r2d2manager。Singleton 使用最小自定义 manager,把connect_timeout_ms传给Client::get_connection_with_timeout();Sentinel 使用最小自定义 manager,在 redis-rs 完成 Master discovery 后把connect_timeout_ms传给目标 Master 的Client::get_connection_with_timeout(),并补充READONLY、MASTERDOWN后的 topology generation 失效 - 业务命令和实例心跳分别 checkout 独占连接;两者同时执行时使用不同 pooled connection
- 连接池固定
max_size=2、checkout timeout 固定为 5 秒,均不增加用户配置;cluster连接内部管理的节点连接不计入该容量 cluster的 slot 路由、MOVED/ASK处理、节点重连和异常节点切换由ClusterConnection自身能力负责,QueueFS 不维护 endpoint 轮转sentinel建立连接时使用SentinelClient查询可用 Sentinel、发现并校验当前 master,再以connect_timeout_ms限制目标 Master 的物理建连。redis-rs 1.5.0 的同步 Sentinel discovery 不暴露物理建连 timeout,因此 discovery 阶段由内部 5 秒 pool checkout timeout 限制调用方等待。旧 master 返回READONLY或MASTERDOWN等拓扑失效错误时,QueueFS 使同一 pool 内当前 topology generation 的连接全部失效,后续 checkout 重新执行 master discovery- QueueFS 不在结果未知的写命令失败后自动重试 Lua 脚本,避免对
enqueue、dequeue和ack产生二次执行风险 - backend 正常关闭时删除当前实例心跳;若连接已不可用,不主动为删除心跳创建新连接,而是依赖 30 秒 TTL 自然清理
- 三种模式分别为
- Backend trait
- 当前
QueueBackendtrait 是同步接口 - 实施方案如下:
- 在
crates/ragfs/ QueueFS 自身范围内独立实现 Redis backend - Redis backend 直接面向 QueueFS 的队列语义实现:
enqueue、dequeue、ack、recover_stale - Python 绑定和默认构建路径继续以
crates/ragfs-python为主,不改变现有主工作流 - Redis backend 实现在
crates/ragfs/src/plugins/queuefs/redis_backend.rs
- 在
- 这样实现的好处是:
- QueueFS Redis backend 的职责边界清晰
- 现有
ragfs-python主路径不受影响
- 当前
- Queue clear
clear使用 Lua 脚本实现- 原子步骤:
- 读出
pending里的所有 id - 读出
processing里的所有 member,并按{message_id}|{instance_id}解析出其中的message_id - 删除对应的 payload key
- 删除
pending - 删除
processing
- 读出
- 原因:
- 和
enqueue、dequeue、ack的实现风格保持一致 - 避免执行到一半中断,留下半清理状态
- 对当前预期队列规模,Lua 脚本可以直接满足需求
- 和
- Queue remove
remove_queue使用 Lua 脚本实现- 原子步骤:
- 从
{key_prefix}:ov:queue:names读取全部注册队列 - 筛选名称等于目标队列或以
{queue}/开头的全部队列 - 对每个匹配队列删除
pending中消息的 payload - 对每个匹配队列删除
processing中消息的 payload - 删除每个匹配队列的
pending、processing和meta - 从
{key_prefix}:ov:queue:names移除全部匹配队列 - 没有匹配队列时返回
NotFound
- 从
- 原因:
- 保证目标队列及其全部子队列的消息、元信息、注册信息一次性删除完成
- 避免删掉队列注册后仍残留 payload 或 processing 状态
- 对齐 SQLite
remove_queue的递归删除语义,并支持删除只包含子队列的虚拟父目录
- 配置透传
Contribution
- [x] I am willing to contribute to implementing this feature
English Version / 英文版
Problem Statement
QueueFS currently has two backends:
memory: lightweight, non-persistent, and with weakerdequeuesemanticssqlite: persistent, withpending -> processing -> ack -> recover_stalesemantics
From the Python business-layer perspective, a Redis backend must align with the sqlite backend semantics rather than the memory backend semantics.
The main gaps are:
- There is no Redis backend today that preserves QueueFS persistence and stateful delivery semantics.
- The current Python worker flow depends on
dequeue -> process -> ack, so a Redis backend cannot behave like the in-memory backend and remove messages too early. - Multi-instance recovery semantics are not defined for Redis yet, especially around stale
processingmessages after instance failure. - Queue registration, payload storage, processing ownership, and stale recovery need a Redis-native data model with atomic state transitions.
- Redis configuration is not yet plumbed through the existing QueueFS config path in a nested and backend-specific way.
- The Redis backend does not yet define a consistent contract and configuration rules across
singleton,cluster, andsentinelconnection modes.
Relevant implementation entry points:
crates/ragfs/src/plugins/queuefs/backend.rscrates/ragfs/src/plugins/queuefs/mod.rsopenviking/utils/agfs_utils.pyopenviking/storage/queuefs/named_queue.py
Proposed Solution
1. Introduce a Redis backend with SQLite-aligned QueueFS semantics
Add redis as a new QueueFS backend and explicitly align its behavior with the current sqlite backend.
The target behavior is:
- queue state is persistent
dequeueonly moves a message frompendingtoprocessingackis the only operation that permanently deletes a processing messagerecover_stalemoves staleprocessingmessages back topending- Python continues to use the existing
dequeue -> process -> ackflow without behavioral changes - Redis connection modes support
singleton,cluster, andsentinel
This change does not target exactly-once delivery. The delivery model remains at-least-once.
2. Define a Redis-native key layout for queue metadata, pending state, processing state, and payloads
Use Redis keys to represent the same semantic pieces that SQLite currently stores in queue_metadata and queue_messages.
Suggested layout:
{key_prefix}:ov:queue:namesSET- stores queue registry
{key_prefix}:ov:queue:{queue}:metaHASH- stores
created_at,last_updated,last_enqueue_ts
{key_prefix}:ov:queue:{queue}:pendingLIST- stores FIFO pending
message_ids
{key_prefix}:ov:queue:{queue}:processingZSET- stores
{message_id}|{instance_id}as member andprocessing_started_atas score
{key_prefix}:ov:queue:{queue}:msg:{message_id}STRING- stores serialized
StoredMessageJSON payload
{key_prefix}:ov:queue:instance:{instance_id}:aliveSTRINGwith TTL- stores instance liveness for stale recovery
key_prefix defaults to default. All Redis keys start with {key_prefix}:ov:, where { and } are literal Redis Cluster hash tag characters rather than placeholder syntax. When key_prefix=default, the actual prefix is {default}:ov:. The same key layout is used in all three connection modes; in cluster mode, {key_prefix} pins all QueueFS keys for the same prefix into one slot so Lua scripts satisfy Redis Cluster's same-slot requirement. key_prefix must be non-empty and must not contain { or }.
3. Use Lua scripts to guarantee atomic queue state transitions
Core queue operations should use Lua scripts so QueueFS can preserve SQLite-like atomicity.
Required atomic operations:
create_queue- atomically register queue name and initialize queue metadata
enqueue- atomically write payload, push
message_idinto pending, and update metadata
- atomically write payload, push
dequeue- atomically pop the oldest pending item, validate payload presence, mark it as processing, and return the payload
ack- atomically remove the matching processing record and delete payload
clear- atomically delete pending entries, processing entries, and payloads for one queue
remove_queue- atomically delete the target queue and all sub-queues, including metadata, pending entries, processing entries, and payloads
recover_stale- atomically requeue messages held by dead instances
The Redis backend must not implement these state transitions as multiple best-effort round trips.
4. Introduce instance heartbeat and startup-only stale recovery
Generate a unique instance_id when the backend starts and maintain a liveness key:
- heartbeat key TTL:
30s - heartbeat refresh interval:
10s
recover_stale should:
- scan each queue's
processingzset - parse
{message_id}|{instance_id} - check whether
{key_prefix}:ov:queue:instance:{instance_id}:alivestill exists - move messages owned by dead instances back to
pending
This recovery only runs once during backend startup.
During steady-state runtime:
- QueueFS does not run a background recovery loop
- messages still owned by an instance whose heartbeat has not expired are not reclaimed
- if a new backend starts before the dead instance heartbeat expires, those messages are not recovered immediately
5. Add nested Redis configuration under storage.agfs.queuefs.redis
Add redis as a backend option in storage.agfs.queuefs.backend and use a nested storage.agfs.queuefs.redis object for Redis-specific configuration.
Configuration example:
{
"storage": {
"agfs": {
"queuefs": {
"backend": "redis",
"redis": {
"mode": "singleton",
"key_prefix": "default",
"endpoints": ["redis://127.0.0.1:6379"],
"master_name": null,
"username": null,
"password": null,
"sentinel_username": null,
"sentinel_password": null,
"db": 0,
"connect_timeout_ms": 3000,
"command_timeout_ms": 3000,
"tls_enabled": false,
"tls_insecure_skip_verify": false
}
}
}
}
}
queuefs.redis.mode describes the Redis topology mode and is independent from QueueFS path namespace modes such as shared or worker.
Cluster example:
{
"mode": "cluster",
"key_prefix": "default",
"endpoints": [
"redis://redis-cluster-0:6379",
"redis://redis-cluster-1:6379"
],
"db": 0
}
Sentinel example:
{
"mode": "sentinel",
"key_prefix": "default",
"endpoints": [
"redis://redis-sentinel-0:26379",
"redis://redis-sentinel-1:26379"
],
"master_name": "mymaster",
"username": "queue-user",
"password": "queue-password",
"sentinel_username": "sentinel-user",
"sentinel_password": "sentinel-password",
"db": 0
}
Rules:
- Python
openviking/utils/agfs_utils.py::_build_queuefs_plugin_config()passesqueuefs.redisthrough unchanged whenbackend=redis - Rust
QueueFSPlugin::parse_backend_config()parses the nestedredisobject and buildsRedisQueueOptions db_pathandbusy_timeout_msremain SQLite-onlyrecover_stale_secdoes not apply to Redis; Redis recovery is based on dead-instance heartbeatmodemust be one ofsingleton,cluster, orsentinelkey_prefixmust be non-empty and must not contain{or}, and must be validated in both Python and Rustsingletonrequires exactly one endpointclusterandsentinelrequire at least one endpointsentinelrequires a non-emptymaster_nameclusteronly allowsdb=0master_name,sentinel_username, andsentinel_passwordhave no effect outsidesentinelmode- the Redis backend internally uses a fixed-size
r2d2pool of 2 synchronous connections so one business command and one heartbeat renewal can check out connections at the same time; pool checkout timeout is fixed at 5 seconds, and neither setting is exposed for configuration
Alternatives Considered
- Reuse the current
memorybackend semantics for Redis
- this would be smaller to implement
- but it would break the current Python
dequeue -> process -> ackcontract and lose SQLite-aligned recovery semantics
- Redesign the Python worker flow together with the Redis backend
- this would give more freedom in backend behavior
- but it would expand scope significantly and is not needed for this backend addition
- Add periodic runtime stale recovery
- this could reduce operator intervention after crashes
- but it adds more runtime behavior and coordination complexity than required for the first Redis backend version
Feature Area
Core (Storage/Engine)
Use Case
QueueFS needs a Redis backend for deployments that want Redis-based queue state while preserving the same behavioral contract already relied on by the Python business layer.
Typical scenarios include:
- using Redis instead of SQLite as the persistent queue state store
- running QueueFS across multiple instances with recoverable
processingownership - preserving the same QueueFS behavior in
singleton,cluster, andsentineldeployments - keeping the current Python worker lifecycle unchanged
- isolating multiple QueueFS tenants or business domains with different
key_prefixvalues
Additional Context
This issue is derived from the internal Redis backend design draft for QueueFS.
Relevant files:
crates/ragfs/src/plugins/queuefs/backend.rscrates/ragfs/src/plugins/queuefs/mod.rscrates/ragfs/src/plugins/queuefs/redis_backend.rsopenviking/utils/agfs_utils.pyopenviking/storage/queuefs/named_queue.py
The design baseline is:
- align with SQLite semantics
- use Redis key structures to encode queue state
- use Lua scripts for atomic transitions
- keep one QueueFS contract across
singleton,cluster, andsentinel - do not use the current
memorybackend as the semantic reference
To keep the English and Chinese sections semantically aligned, the full design details are preserved below as well.
-
Current SQLite structure and Redis mapping
SQLite table SQLite schema SQLite example Redis key design Redis example queue_metadataqueue_name TEXT PRIMARY KEY, created_at INTEGER DEFAULT strftime('%s','now'), last_updated INTEGER DEFAULT strftime('%s','now')queue_name='Semantic', created_at=1753890000, last_updated=1753890123{key_prefix}:ov:queue:names(SET) +{key_prefix}:ov:queue:{queue_name}:meta(HASH)SADD {default}:ov:queue:names Semantic;HSET {default}:ov:queue:Semantic:meta created_at 1753890000 last_updated 1753890123queue_messagesid INTEGER PRIMARY KEY AUTOINCREMENT, queue_name TEXT NOT NULL, message_id TEXT NOT NULL, data TEXT NOT NULL, timestamp INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', processing_started_at INTEGER, created_at INTEGER DEFAULT strftime('%s','now')id=42, queue_name='Semantic', message_id='9d5d2f2e-7e9d-4f3f-9b73-1c0f5b7b0abc', data='{"id":"9d5d2f2e-7e9d-4f3f-9b73-1c0f5b7b0abc","data":[104,101,108,108,111],"timestamp":1753890000}', timestamp=1753890000, status='processing', processing_started_at=1753890055, created_at=1753890000{key_prefix}:ov:queue:{queue_name}:pending(LIST) +{key_prefix}:ov:queue:{queue_name}:processing(ZSET) +{key_prefix}:ov:queue:{queue_name}:msg:{message_id}(STRING)RPUSH {default}:ov:queue:Semantic:pending 9d5d2f2e-7e9d-4f3f-9b73-1c0f5b7b0abc; `ZADD {default}:ov:queue:Semantic:processing 1753890055 '9d5d2f2e-7e9d-4f3f-9b73-1c0f5b7b0abc -
Why
queue_messagesmust be split in RedisIn SQLite, one
queue_messagestable expresses three different concerns at once:- queue order
- message payload
- message state:
pending/processing
Redis has no table abstraction, so these semantics must be split across different key types:
- use
LISTfor FIFO pending order - use
ZSETfor processing state and recovery timing - use
STRINGfor message payload
This split is required if QueueFS is expected to preserve its current semantics.
-
Key structure
key_prefixisolates QueueFS data for different business domains. Its default value isdefault. All Redis keys start with{key_prefix}:ov:, where{and}are literal Redis Cluster hash tag characters rather than placeholder syntax. Whenkey_prefix=default, the real prefix is{default}:ov:. Different business domains use differentkey_prefixvalues so queue registry, messages, and instance heartbeats remain fully isolated.All three connection modes use the same key format. In
clustermode, all QueueFS keys for the samekey_prefixare pinned to one slot through the{key_prefix}hash tag so Lua scripts operate on same-slot keys.key_prefixmust be non-empty and must not contain{or}.Assume
key_prefix=default, queue nameSemantic, and message ID9d5d....- instance liveness
{key_prefix}:ov:queue:instance:{instance_id}:alive- type:
STRING - value: fixed placeholder such as
1 - TTL: 30 seconds
- purpose: indicates that one instance is alive and keeps renewing this key
- queue registry
{key_prefix}:ov:queue:names- type:
SET - purpose: stores all queue names
- queue metadata
{key_prefix}:ov:queue:{queue}:meta- type:
HASH - fields:
created_atlast_updatedlast_enqueue_ts
- pending queue
{key_prefix}:ov:queue:{queue}:pending- type:
LIST - value: ordered
message_ids - purpose: FIFO dequeue source
- processing queue
{key_prefix}:ov:queue:{queue}:processing- type:
ZSET - member:
{message_id}|{instance_id} - score:
processing_started_at - purpose: stores in-flight messages, processing start time, and instance ownership;
processing_started_atis for observability and debugging only, not for dead-instance reclaim decisions - format constraint:
message_idandinstance_iduse UUID/ULID and must not contain|; both Lua and Rust split on the first|
- message payload
{key_prefix}:ov:queue:{queue}:msg:{message_id}- type:
STRING - value: serialized
StoredMessageJSON
- instance liveness
-
Operation mapping
QueueFS operation SQLite semantics Redis design create_queueinsert one row into queue_metadataatomically SADD {key_prefix}:ov:queue:names {queue}and initialize{key_prefix}:ov:queue:{queue}:metathrough Luaqueue_existsquery queue_metadataor existing messagesSISMEMBER {key_prefix}:ov:queue:names {queue}list_queuesquery metadata table and support legacy backfill SMEMBERS {key_prefix}:ov:queue:names, then filter by queue name prefix in codeenqueueinsert one pendingrow intoqueue_messagesatomically check queue registration, then SETpayload,RPUSHpendingmessage_id, and update metadata through Luapeekread the earliest pendingrow without changing stateLINDEX pending 0, thenGETpayloaddequeuemove the earliest pendingrow intoprocessingatomically remove the first pending ID and add `{message_id} sizecount rows with status='pending'LLEN pendingackdelete one processingrow bymessage_idscan processing, match bymessage_id, remove the matching member, thenDELpayload through Luacleardelete all message rows for one queue atomically delete pending,processing, and all payload keys for that queue through Luaremove_queuedelete the target queue and all sub-queues atomically find queue names equal to {queue}or prefixed with{queue}/, then delete all matching queues through Luarecover_staleduring startup, move abandoned processingrows back topendingscan processing, parse `{message_id} -
Required
dequeuesemanticsThe Redis implementation must align with SQLite semantics, not memory semantics.
Target behavior:
- take the earliest
pendingmessage - do not delete its payload yet
- mark it as
processing - return the payload to the caller
- permanently delete it only after
ack
This is required to stay compatible with the current Python worker flow:
dequeue- business processing
ack
- take the earliest
-
Atomic flows
- Create Queue
- implemented with Lua
- atomic steps:
SADD {key_prefix}:ov:queue:names {queue}- initialize
{key_prefix}:ov:queue:{queue}:meta - return whether creation succeeded
- reason:
- queue registration and metadata initialization complete together
- avoids a half-success state where the queue name exists but metadata does not
- Enqueue
- implemented with Lua
- script delivery:
- store the Lua script as a Rust string constant next to the QueueFS Redis backend code
- let Rust execute it with
EVAL/EVALSHA
- atomic steps:
- serialize
StoredMessage SISMEMBER {key_prefix}:ov:queue:names {queue}- if the queue is not registered, return
NotFoundbefore writing any key SET {key_prefix}:ov:queue:{queue}:msg:{msg_id} {payload}RPUSH {key_prefix}:ov:queue:{queue}:pending {msg_id}- update
{key_prefix}:ov:queue:{queue}:metawhen needed - return enqueue result
- serialize
- reason:
- keeps
enqueue,dequeue, andackconsistently atomic - reduces intermediate states caused by network jitter or client failure
- avoids half-success cases where payload exists but queue entry does not, or queue entry exists but metadata is not fully updated
- avoids orphan states where
remove_queueraces withenqueueand the message write succeeds even though the queue is no longer in the registry
- keeps
- Dequeue
- implemented with Lua, not multiple round trips
- script delivery:
- store the Lua script as a Rust string constant next to the QueueFS Redis backend code
- let Rust execute it with
EVAL/EVALSHA
- atomic steps:
LPOP {key_prefix}:ov:queue:{queue}:pending- if empty, return
nil GET {key_prefix}:ov:queue:{queue}:msg:{msg_id}- if payload is missing, use
LPUSHto returnmessage_idback to pending and return a corruption error - build the processing member
{message_id}|{instance_id} ZADD {key_prefix}:ov:queue:{queue}:processing {now} {processing_member}- return payload
- reason:
- avoids taking a pending ID without marking it as processing
- preserves SQLite-like
pending -> processingtransition semantics
- Ack
- implemented with Lua
- script delivery:
- store the Lua script as a Rust string constant next to the QueueFS Redis backend code
- let Rust execute it with
EVAL/EVALSHA
- atomic steps:
- scan members in
processingand find the one matching the requestedmessage_id ZREM {key_prefix}:ov:queue:{queue}:processing {processing_member}DEL {key_prefix}:ov:queue:{queue}:msg:{msg_id}- return whether deletion actually happened
- scan members in
- Instance Heartbeat
- create a unique
instance_idwhen the service starts, usingUUIDorULID - after startup:
- initialize
instance_id - write
{key_prefix}:ov:queue:instance:{instance_id}:alive - set TTL to 30 seconds
- renew it every 10 seconds
- on normal shutdown, stop heartbeat and delete the key so the next instance can recover unfinished work immediately
- initialize
- reason:
- gives the Redis backend multi-instance liveness awareness
- provides the liveness signal used by
recover_stale
- create a unique
- Recover Stale
- implemented with Lua and executed once during backend startup
- atomic steps:
- scan members in
{key_prefix}:ov:queue:{queue}:processing - parse
message_idandinstance_idfrom each{message_id}|{instance_id}member - check whether
{key_prefix}:ov:queue:instance:{instance_id}:alivestill exists - for each
message_idwhose instance heartbeat has expired:ZREM processing {processing_member}RPUSH pending {message_id}
- scan members in
- reason:
- keeps dead-instance detection, state removal, and requeue in one script execution
- avoids mid-recovery interruption that would leave partially restored messages
- only reclaims processing messages owned by dead instances, avoiding false reclaim while multiple instances are alive
- no periodic recovery runs during normal runtime. After abnormal exit, heartbeat expiration takes at most 30 seconds.
recover_stalehandles only instances already expired when the backend starts. If the backend starts before the old heartbeat expires, those messages are not reclaimed immediately. Runtime remediation then requires Redis-side operational handling; QueueFS does not expose a runtime recovery API.
- Create Queue
-
Payload format
Redis payloads reuse the current SQLite
StoredMessageJSON format:{ "id": "9d5d2f2e-7e9d-4f3f-9b73-1c0f5b7b0abc", "data": [104, 101, 108, 108, 111], "timestamp": 1753890000 }Reason:
- no Python behavior change
- no new serialization migration cost
- preserves non-UTF-8 byte compatibility
-
Failure semantics
The delivery target remains at-least-once.
Scenario Result enqueue succeeds, worker has not consumed yet message remains in pendingdequeue succeeds, processing crashes before ack message remains in processing; after old-instance heartbeat expiry, a newly started backend can move it back topendingthroughrecover_staledequeue succeeds, ack succeeds, then process crashes message is already completed and will not be retried dequeue succeeds, but payload key is missing treated as storage corruption; should return an error and be logged -
Implementation Boundaries and Details
- config passthrough
-
QueueFS configuration currently includes:
backenddb_pathrecover_stale_secbusy_timeout_msredis
-
Redis backend configuration should work as follows:
- add
redistostorage.agfs.queuefs.backend - add nested
redisobject understorage.agfs.queuefs - Python config assembly passes
queuefs.redisthrough unchanged into QueueFS plugin config - Rust
QueueFSPlugin::parse_backend_config()parses the nestedredisobject and buildsRedisQueueOptions
- add
-
use a nested config object rather than flattening Redis fields into the QueueFS top level
-
redisobject fields:Field Type Description modestringRedis connection mode, one of singleton,cluster, orsentinel, defaultsingletonkey_prefixstringQueueFS Redis business prefix, default default, must be non-empty; all keys use{key_prefix}:ov:*endpointsstring[]Redis endpoints; singletonrequires exactly one,clusterrequires at least one seed node,sentinelrequires at least one Sentinel nodemaster_namestring | nullSentinel service name; required only in sentinelmodeusernamestring | nullRedis data-node ACL username passwordstring | nullRedis data-node ACL password sentinel_usernamestring | nullSentinel ACL username, only for sentinelmodesentinel_passwordstring | nullSentinel ACL password, only for sentinelmodedbintRedis database number connect_timeout_msintphysical connection timeout in milliseconds; applies to the target instance in Singleton, data nodes in Cluster, and the data node after Master discovery in Sentinel command_timeout_msintcommand timeout in milliseconds tls_enabledboolwhether TLS is enabled tls_insecure_skip_verifyboolwhether to skip TLS certificate verification -
passthrough and parsing rules:
- Python
openviking/utils/agfs_utils.py::_build_queuefs_plugin_config()writes:backend = "redis"redis = queuefs.redis
- Rust
crates/ragfs/src/plugins/queuefs/mod.rsextends plugin metadata with:backendallowingredis- the
redisobject parameter
db_pathandbusy_timeout_msremain SQLite-onlyrecover_stale_secdoes not apply to Redis; Redis startup recovery is fixed to dead-instance heartbeat checksmodemust besingleton,cluster, orsentinelkey_prefixmust be non-empty, must not contain{or}, and is validated in both Python and Rustsingletonrequires exactly one endpointclusterandsentinelrequire at least one endpointsentinelrequires a non-emptymaster_nameclusteronly allowsdb=0master_name,sentinel_username, andsentinel_passwordare ignored outsidesentinelmode
- Python
-
Redis connection parameters and
key_prefixexist only insidequeuefs.redis. The top-level config shape stays unchanged. The Redis backend internally uses a fixed-sizer2d2pool of 2 synchronous connections so one business command and one heartbeat renewal can run concurrently. Pool checkout timeout is fixed at 5 seconds. Pool size and checkout timeout remain internal and are not user-configurable. -
Pool capacity counts logical connections, not endpoints or Redis nodes. One pooled item in Singleton or Sentinel represents one data-node connection. One pooled item in Cluster represents one
ClusterConnection, which internally maintains node connections from the Cluster topology. Seed endpoints and runtime-discovered nodes do not directly increaser2d2pool capacity.
-
- Redis connection modes
- the three supported modes are
singleton,cluster, andsentinel singletonusesredis::Client+r2d2::Poolclusterusesredis::cluster::ClusterClient+r2d2::Poolsentinelusesredis::sentinel::SentinelClient+ a minimalr2d2manager- key boundaries:
crates/ragfs/Cargo.tomlneedscluster,sentinel, andr2d2features enabled on theredisdependencyr2d2is responsible for synchronous connection reuse, capacity limiting, health checks, and passive eviction; it should not be described as active auto-retry- Cluster uses the native redis-rs
r2d2manager. Singleton uses a minimal custom manager that passesconnect_timeout_mstoClient::get_connection_with_timeout(). Sentinel uses a minimal custom manager that, after redis-rs completes Master discovery, passesconnect_timeout_msto the target Master'sClient::get_connection_with_timeout()and invalidates the topology generation afterREADONLYorMASTERDOWN - business commands and heartbeat renewals check out separate pooled connections so long business commands do not block heartbeat refresh
- the pool stays at
max_size=2with a fixed 5-second checkout timeout; neither is user-configurable, and node connections maintained inside a cluster connection do not count toward that capacity - slot routing,
MOVED/ASKhandling, node reconnect, and unhealthy-node switching inclusterare delegated toClusterConnection; QueueFS does not maintain endpoint rotation itself - in Sentinel mode,
SentinelClientqueries available Sentinel nodes, discovers and validates the current master, then usesconnect_timeout_msfor the target Master's physical connection. Since synchronous Sentinel discovery in redis-rs 1.5.0 does not expose a physical connection timeout, the internal 5-second pool checkout timeout bounds caller wait during discovery. When an old master returnsREADONLYorMASTERDOWN, QueueFS invalidates the current topology generation so the next checkout rediscovers the master - QueueFS does not automatically retry failed Lua write commands whose results are unknown, to avoid double execution of
enqueue,dequeue, orack - on graceful shutdown, the backend deletes the current instance heartbeat; if the connection is already unavailable, it does not create a new connection just to delete the heartbeat and instead relies on the 30-second TTL
- the three supported modes are
- Backend trait
- the current
QueueBackendtrait is synchronous - implementation plan:
- implement the Redis backend independently inside
crates/ragfs/ QueueFS - keep the Redis backend directly focused on QueueFS queue semantics:
enqueue,dequeue,ack,recover_stale - keep Python bindings and the default build path centered on
crates/ragfs-python - place the Redis backend implementation in
crates/ragfs/src/plugins/queuefs/redis_backend.rs
- implement the Redis backend independently inside
- benefit:
- clear responsibility boundary for the QueueFS Redis backend
- no disruption to the current
ragfs-pythonmain path
- the current
- Queue clear
- implement
clearwith Lua - atomic steps:
- read all IDs from
pending - read all members from
processingand parsemessage_idfrom{message_id}|{instance_id} - delete corresponding payload keys
- delete
pending - delete
processing
- read all IDs from
- reason:
- keeps implementation style aligned with
enqueue,dequeue, andack - avoids half-cleared states if interruption happens mid-operation
- Lua is sufficient for the expected queue size
- keeps implementation style aligned with
- implement
- Queue remove
- implement
remove_queuewith Lua - atomic steps:
- read all registered queues from
{key_prefix}:ov:queue:names - select queues equal to the target name or prefixed by
{queue}/ - delete payloads referenced by
pendingfor every matched queue - delete payloads referenced by
processingfor every matched queue - delete
pending,processing, andmetafor every matched queue - remove all matched names from
{key_prefix}:ov:queue:names - return
NotFoundif there are no matches
- read all registered queues from
- reason:
- ensures target queue and all child queues are removed together with messages, metadata, and registration state
- avoids leaving payload or processing residue after registry deletion
- aligns with SQLite
remove_queuerecursive deletion semantics, including virtual parent directories that only contain child queues
- implement
- config passthrough
Contribution
- [x] I am willing to contribute to implementing this feature