OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Feature]: 为 QueueFS 增加 Redis 后端支持/Add Redis Backend Support to QueueFS

Open baojun-zhang opened this issue 3 months ago • 0 comments

本 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 语义。

当前缺口主要有:

  1. 目前还没有一个 Redis backend 能同时保留 QueueFS 的持久化能力和状态化投递语义。
  2. 当前 Python worker 流程依赖 dequeue -> process -> ack,因此 Redis backend 不能像 memory backend 一样过早删除消息。
  3. Redis 场景下,多实例失败后的 processing stale 消息恢复语义尚未定义清楚。
  4. 队列注册、payload 存储、processing 归属以及 stale 恢复需要一套 Redis 原生的数据模型,并保证状态迁移原子性。
  5. 当前 QueueFS 配置链路还没有把 Redis 配置按嵌套对象、按 backend 语义正确透传下去。
  6. Redis backend 还没有明确 singleton、cluster 和 sentinel 三种连接模式下的一致行为和配置约束。

相关实现入口:

  • crates/ragfs/src/plugins/queuefs/backend.rs
  • crates/ragfs/src/plugins/queuefs/mod.rs
  • openviking/utils/agfs_utils.py
  • openviking/storage/queuefs/named_queue.py

Proposed Solution

1. 引入一个与 SQLite 语义对齐的 Redis backend

为 QueueFS 增加 redis backend,并显式要求它的行为与当前 sqlite backend 对齐。

目标行为:

  • 队列状态持久化
  • dequeue 只把消息从 pending 迁移到 processing
  • ack 是唯一真正删除处理中消息的操作
  • recover_stale 能把 stale processing 消息放回 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:names
    • SET
    • 记录队列注册表
  • {key_prefix}:ov:queue:{queue}:meta
    • HASH
    • 存储 created_at、last_updated、last_enqueue_ts
  • {key_prefix}:ov:queue:{queue}:pending
    • LIST
    • 按 FIFO 顺序存放待处理 message_id
  • {key_prefix}:ov:queue:{queue}:processing
    • ZSET
    • member 为 {message_id}|{instance_id},score 为 processing_started_at
  • {key_prefix}:ov:queue:{queue}:msg:{message_id}
    • STRING
    • 存储序列化后的 StoredMessage JSON payload
  • {key_prefix}:ov:queue:instance:{instance_id}:alive
    • 带 TTL 的 STRING
    • 表示实例存活状态,用于 stale 恢复

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
  • 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 的逻辑应当是:

  1. 扫描每个队列的 processing zset
  2. 解析 {message_id}|{instance_id}
  3. 检查 {key_prefix}:ov:queue:instance:{instance_id}:alive 是否仍存在
  4. 将死实例占用的消息重新放回 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 或 sentinel
  • key_prefix 必须非空且不能包含 { 或 },Python 和 Rust 两层都要校验
  • singleton 模式的 endpoints 长度必须等于 1
  • cluster 和 sentinel 模式的 endpoints 至少包含一个地址
  • sentinel 模式必须配置非空 master_name
  • cluster 模式只允许 db=0
  • master_name、sentinel_username 和 sentinel_password 在非 sentinel 模式下不生效
  • Redis backend 内部使用固定容量为 2 的 r2d2 同步连接池,分别满足一路串行业务命令和一路心跳续约同时 checkout 的需求;pool checkout timeout 固定为 5 秒,池大小和 checkout timeout 均不对外开放配置

Alternatives Considered

  1. 直接沿用当前 memory backend 的 Redis 语义
  • 这样实现会更小
  • 但会破坏当前 Python dequeue -> process -> ack 契约,也无法对齐 SQLite 的恢复语义
  1. 连同 Redis backend 一起重写 Python worker 流程
  • 这样后端设计自由度更高
  • 但会显著扩大范围,不适合这次仅增加 backend 的目标
  1. 增加运行期周期 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.rs
  • crates/ragfs/src/plugins/queuefs/mod.rs
  • crates/ragfs/src/plugins/queuefs/redis_backend.rs
  • openviking/utils/agfs_utils.py
  • openviking/storage/queuefs/named_queue.py

本次设计基线是:

  • 以 SQLite 语义为准
  • 用 Redis key 模型承载队列状态
  • 用 Lua 脚本保证状态迁移原子性
  • 在 singleton、cluster 和 sentinel 三种模式下保持一致的 QueueFS 契约
  • 不以当前 memory backend 作为语义参考

为避免 issue 化过程中丢失原设计信息,下面保留原设计中的完整细节展开。保持 issue 模板层级不变,但补回所有关键设计点。

  • 当前 SQLite 表结构与 Redis 对应设计

    SQLite表 SQLite表结构 SQLite数据示例 对应Redis key结构设计 Redis数据实例
    queue_metadata queue_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 1753890123
    queue_messages id 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 表同时表达了三类信息:

    1. 队列顺序
    2. 消息内容
    3. 消息状态: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_at
        • last_updated
        • last_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
      • 值:序列化后的 StoredMessage JSON
  • 操作映射

    QueueFS操作 SQLite语义 Redis设计
    create_queue 向 queue_metadata 插入一行 使用 Lua 脚本原子执行 SADD {key_prefix}:ov:queue:names {queue} 并初始化 {key_prefix}:ov:queue:{queue}:meta
    queue_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 并更新 meta
    peek 读取最前面的 pending,但不改状态 LINDEX pending 0,再 GET msg payload
    dequeue 最早的 pending 变成 processing 使用 Lua 脚本原子地移除第一个 pending id,并把 `{message_id}
    size 统计 status='pending' 的行数 LLEN pending
    ack 按 message_id 删除一条 processing 记录 使用 Lua 脚本扫描 processing,按 member 中的 message_id 匹配并删除对应记录,再 DEL msg payload
    clear 删除该队列所有消息行 使用 Lua 脚本原子删除 pending、processing 以及该队列下所有 payload key
    remove_queue 删除目标队列及其全部子队列 使用 Lua 脚本从队列注册表筛选名称等于 {queue} 或以 {queue}/ 开头的队列,并原子删除全部匹配队列
    recover_stale 在启动时,把异常实例占用的 processing 改回 pending 使用 Lua 脚本扫描 processing,按 `{message_id}
  • dequeue 语义要求

    Redis 实现必须对齐 SQLite 语义,不能对齐 memory 语义。

    目标行为:

    1. 取出最早的一条 pending 消息
    2. 暂时不删除 payload
    3. 先把这条消息标记成 processing
    4. 把 payload 返回给调用方
    5. 只有调用 ack 后才真正删除

    这样才能和当前 Python worker 流程保持一致:

    1. dequeue
    2. 业务处理
    3. ack
  • 原子流程

    • Create Queue
      • 使用 Lua 脚本实现
      • 原子步骤:
        1. SADD {key_prefix}:ov:queue:names {queue}
        2. 初始化 {key_prefix}:ov:queue:{queue}:meta
        3. 返回是否创建成功
      • 原因:
        • 保证队列注册和元信息初始化一次完成
        • 避免只注册队列名、但缺少元信息的半成功状态
    • Enqueue
      • 使用 Lua 脚本实现
      • 脚本落地方式:
        • 把 Lua 脚本写成 Rust 字符串常量,和 QueueFS Redis backend 代码一起管理
        • 由 Rust 在运行时通过 EVAL / EVALSHA 下发到 Redis 执行
      • 原子步骤:
        1. 序列化 StoredMessage
        2. SISMEMBER {key_prefix}:ov:queue:names {queue}
        3. 队列未注册时,在写入任何 key 前返回 NotFound
        4. SET {key_prefix}:ov:queue:{queue}:msg:{msg_id} {payload}
        5. RPUSH {key_prefix}:ov:queue:{queue}:pending {msg_id}
        6. 按需更新 {key_prefix}:ov:queue:{queue}:meta
        7. 返回 enqueue 结果
      • 原因:
        • 让 Enqueue / Dequeue / Ack 三个核心操作统一采用 Lua 原子执行,设计更整齐
        • 减少网络抖动或客户端异常导致的中间态
        • 避免出现 payload 已写但队列未入列,或队列已入列但附加元信息未更新完成的半成功状态
        • 避免多实例下 remove_queue 与 enqueue 并发时,出现 enqueue 返回成功但消息不在队列注册表中的孤儿状态
    • Dequeue
      • 使用 Lua 脚本实现,不拆成多次网络往返
      • 脚本落地方式:
        • 把 Lua 脚本写成 Rust 字符串常量,和 QueueFS Redis backend 代码一起管理
        • 由 Rust 在运行时通过 EVAL / EVALSHA 下发到 Redis 执行
      • 原子步骤:
        1. LPOP {key_prefix}:ov:queue:{queue}:pending
        2. 若为空,返回 nil
        3. GET {key_prefix}:ov:queue:{queue}:msg:{msg_id}
        4. payload 不存在时使用 LPUSH 把 message_id 放回 pending,并返回存储损坏错误
        5. 生成 {message_id}|{instance_id} 的 processing member
        6. ZADD {key_prefix}:ov:queue:{queue}:processing {now} {processing_member}
        7. 返回 payload
      • 原因:
        • 避免拿走 pending id 之后,却没来得及标记为 processing
        • 保持 pending -> processing 切换与 SQLite 事务语义一致
    • Ack
      • 使用 Lua 脚本实现
      • 脚本落地方式:
        • 把 Lua 脚本写成 Rust 字符串常量,和 QueueFS Redis backend 代码一起管理
        • 由 Rust 在运行时通过 EVAL / EVALSHA 下发到 Redis 执行
      • 原子步骤:
        1. 在 processing 中扫描 member,并按分隔串中的 message_id 查找对应 member
        2. ZREM {key_prefix}:ov:queue:{queue}:processing {processing_member}
        3. DEL {key_prefix}:ov:queue:{queue}:msg:{msg_id}
        4. 返回是否真的删除成功
    • Instance Heartbeat
      • 服务启动时生成唯一 instance_id,使用 UUID 或 ULID 即可
      • 实例启动后执行以下动作:
        1. 初始化 instance_id
        2. 写入 {key_prefix}:ov:queue:instance:{instance_id}:alive
        3. 设置 TTL 为 30 秒
        4. 每 10 秒续约一次该 key
        5. backend 正常关闭时停止心跳并删除该 key,使下一实例启动时立即恢复未完成任务
      • 原因:
        • 让 Redis 后端具备多实例下的实例存活判断能力
        • 为 recover_stale 提供“实例是否失活”的判断依据
    • Recover Stale
      • 使用 Lua 脚本实现,在 backend 启动时执行一次
      • 原子步骤:
        1. 扫描 {key_prefix}:ov:queue:{queue}:processing 中的 member
        2. 按 {message_id}|{instance_id} 解析每个 member 中的 message_id 和 instance_id
        3. 检查 {key_prefix}:ov:queue:instance:{instance_id}:alive 是否仍然存在
        4. 对于实例心跳已经失效的 message_id:
          • ZREM processing {processing_member}
          • RPUSH pending {message_id}
      • 原因:
        • 保证实例失活判断、状态移除和重新入队在一次脚本执行中完成
        • 避免恢复到一半中断,留下部分消息已移除但未重新入队的中间态
        • 只回收异常实例占用的 processing 消息,避免多实例并存时误回收正常处理中的任务
      • 运行期间不执行后台周期恢复。异常退出实例的心跳最多在 30 秒后失效;recover_stale 只处理 backend 启动时已经失效的实例。backend 在旧实例心跳失效前启动时不会回收对应消息,运行期间需要通过 Redis 运维操作手动处理,QueueFS 不提供运行期恢复接口。
  • 消息内容格式

    Redis 中的 payload 直接沿用当前 SQLite 的 StoredMessage JSON:

    {
      "id": "9d5d2f2e-7e9d-4f3f-9b73-1c0f5b7b0abc",
      "data": [104, 101, 108, 108, 111],
      "timestamp": 1753890000
    }
    

    原因:

    • Python 层行为不用改
    • 不引入新的序列化迁移成本
    • 保留现有的非 UTF-8 字节兼容性
  • 失败语义

    目标投递语义仍然是 at-least-once。

    场景 结果
    enqueue 成功,worker 尚未消费 消息仍留在 pending
    dequeue 成功,业务处理中崩溃,尚未 ack 消息停留在 processing;旧实例心跳失效后启动的 backend 通过 recover_stale 将其放回 pending
    dequeue 成功,ack 成功后崩溃 消息已经完成,不再重试
    dequeue 成功,但 payload key 丢失 视为存储损坏,应返回错误并记录日志
  • 实现边界与细节

    • 配置透传
      • QueueFS 配置入口包含这些字段:

        • backend
        • db_path
        • recover_stale_sec
        • busy_timeout_ms
        • redis
      • Redis backend 的配置面按下面的方式实现:

        1. storage.agfs.queuefs.backend 增加 redis
        2. storage.agfs.queuefs 下新增 redis 子对象
        3. Python 配置组装阶段把 queuefs.redis 原样透传到 QueueFS plugin config
        4. Rust QueueFSPlugin::parse_backend_config() 在 backend=redis 时解析 redis 子对象并构造 RedisQueueOptions
      • 配置结构使用嵌套对象,不把 Redis 参数平铺到 queuefs 顶层

      • queuefs.redis.mode 表示 Redis 拓扑模式,与 queuefs.mode 的 shared / worker QueueFS 路径命名空间模式相互独立

      • redis 子对象字段定义:

        字段 类型 说明
        mode string Redis 连接模式,允许值为 singleton、cluster、sentinel,默认值为 singleton
        key_prefix string QueueFS Redis key 业务前缀,默认值为 default,不能为空;所有 key 使用 {key_prefix}:ov:*
        endpoints string[] Redis endpoint 列表;singleton 必须且只能配置一个,cluster 至少配置一个初始节点,sentinel 至少配置一个 Sentinel 节点
        master_name string | null Sentinel 服务名,仅 sentinel 模式使用且必须配置
        username string | null Redis 数据节点 ACL 用户名
        password string | null Redis 数据节点 ACL 密码
        sentinel_username string | null Sentinel ACL 用户名,仅 sentinel 模式使用
        sentinel_password string | null Sentinel ACL 密码,仅 sentinel 模式使用
        db int Redis database 编号
        connect_timeout_ms int 物理建连超时,单位毫秒;Singleton 用于目标实例,Cluster 用于数据节点,Sentinel 用于发现 Master 后的数据节点连接
        command_timeout_ms int 命令执行超时,单位毫秒
        tls_enabled bool 是否启用 TLS
        tls_insecure_skip_verify bool 是否跳过 TLS 证书校验
      • 透传和解析规则如下:

        1. Python openviking/utils/agfs_utils.py::_build_queuefs_plugin_config() 在 backend=redis 时写入:
          • backend = "redis"
          • redis = queuefs.redis
        2. Rust crates/ragfs/src/plugins/queuefs/mod.rs 在 plugin 元数据中新增:
          • backend 允许值包含 redis
          • redis 对象参数
        3. db_path 和 busy_timeout_ms 只在 SQLite backend 生效
        4. recover_stale_sec 不进入 Redis backend;Redis 启动恢复固定按实例心跳失活判断执行
        5. mode 必须为 singleton、cluster 或 sentinel
        6. key_prefix 不能为空且不能包含 { 或 },Python 和 Rust 两层执行相同校验
        7. singleton 模式的 endpoints 长度必须等于 1
        8. cluster 和 sentinel 模式的 endpoints 至少包含一个地址
        9. sentinel 模式必须配置非空 master_name
        10. cluster 模式只允许 db=0
        11. master_name、sentinel_username 和 sentinel_password 在非 sentinel 模式下不生效
      • 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 或运行期发现的节点数量不会直接增加 r2d2 pool 容量。

    • Redis 连接模式
      • 三种模式分别为 singleton、cluster 和 sentinel
      • singleton 使用 redis::Client + r2d2::Pool
      • cluster 使用 redis::cluster::ClusterClient + r2d2::Pool
      • sentinel 使用 redis::sentinel::SentinelClient + 最小 r2d2 manager
      • 关键边界:
        1. crates/ragfs/Cargo.toml 需要为 redis 依赖启用 cluster、sentinel 和 r2d2 feature
        2. r2d2 的职责是同步连接复用、容量限制、健康检查和被动淘汰,不把连接池表述为主动自动重连
        3. Cluster 直接使用 redis-rs 原生 r2d2 manager。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 失效
        4. 业务命令和实例心跳分别 checkout 独占连接;两者同时执行时使用不同 pooled connection
        5. 连接池固定 max_size=2、checkout timeout 固定为 5 秒,均不增加用户配置;cluster 连接内部管理的节点连接不计入该容量
        6. cluster 的 slot 路由、MOVED / ASK 处理、节点重连和异常节点切换由 ClusterConnection 自身能力负责,QueueFS 不维护 endpoint 轮转
        7. 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
        8. QueueFS 不在结果未知的写命令失败后自动重试 Lua 脚本,避免对 enqueue、dequeue 和 ack 产生二次执行风险
        9. backend 正常关闭时删除当前实例心跳;若连接已不可用,不主动为删除心跳创建新连接,而是依赖 30 秒 TTL 自然清理
    • Backend trait
      • 当前 QueueBackend trait 是同步接口
      • 实施方案如下:
        1. 在 crates/ragfs / QueueFS 自身范围内独立实现 Redis backend
        2. Redis backend 直接面向 QueueFS 的队列语义实现:enqueue、dequeue、ack、recover_stale
        3. Python 绑定和默认构建路径继续以 crates/ragfs-python 为主,不改变现有主工作流
        4. Redis backend 实现在 crates/ragfs/src/plugins/queuefs/redis_backend.rs
      • 这样实现的好处是:
        • QueueFS Redis backend 的职责边界清晰
        • 现有 ragfs-python 主路径不受影响
    • Queue clear
      • clear 使用 Lua 脚本实现
      • 原子步骤:
        1. 读出 pending 里的所有 id
        2. 读出 processing 里的所有 member,并按 {message_id}|{instance_id} 解析出其中的 message_id
        3. 删除对应的 payload key
        4. 删除 pending
        5. 删除 processing
      • 原因:
        • 和 enqueue、dequeue、ack 的实现风格保持一致
        • 避免执行到一半中断,留下半清理状态
        • 对当前预期队列规模,Lua 脚本可以直接满足需求
    • Queue remove
      • remove_queue 使用 Lua 脚本实现
      • 原子步骤:
        1. 从 {key_prefix}:ov:queue:names 读取全部注册队列
        2. 筛选名称等于目标队列或以 {queue}/ 开头的全部队列
        3. 对每个匹配队列删除 pending 中消息的 payload
        4. 对每个匹配队列删除 processing 中消息的 payload
        5. 删除每个匹配队列的 pending、processing 和 meta
        6. 从 {key_prefix}:ov:queue:names 移除全部匹配队列
        7. 没有匹配队列时返回 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 weaker dequeue semantics
  • sqlite: persistent, with pending -> processing -> ack -> recover_stale semantics

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:

  1. There is no Redis backend today that preserves QueueFS persistence and stateful delivery semantics.
  2. 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.
  3. Multi-instance recovery semantics are not defined for Redis yet, especially around stale processing messages after instance failure.
  4. Queue registration, payload storage, processing ownership, and stale recovery need a Redis-native data model with atomic state transitions.
  5. Redis configuration is not yet plumbed through the existing QueueFS config path in a nested and backend-specific way.
  6. The Redis backend does not yet define a consistent contract and configuration rules across singleton, cluster, and sentinel connection modes.

Relevant implementation entry points:

  • crates/ragfs/src/plugins/queuefs/backend.rs
  • crates/ragfs/src/plugins/queuefs/mod.rs
  • openviking/utils/agfs_utils.py
  • openviking/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
  • dequeue only moves a message from pending to processing
  • ack is the only operation that permanently deletes a processing message
  • recover_stale moves stale processing messages back to pending
  • Python continues to use the existing dequeue -> process -> ack flow without behavioral changes
  • Redis connection modes support singleton, cluster, and sentinel

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:names
    • SET
    • stores queue registry
  • {key_prefix}:ov:queue:{queue}:meta
    • HASH
    • stores created_at, last_updated, last_enqueue_ts
  • {key_prefix}:ov:queue:{queue}:pending
    • LIST
    • stores FIFO pending message_ids
  • {key_prefix}:ov:queue:{queue}:processing
    • ZSET
    • stores {message_id}|{instance_id} as member and processing_started_at as score
  • {key_prefix}:ov:queue:{queue}:msg:{message_id}
    • STRING
    • stores serialized StoredMessage JSON payload
  • {key_prefix}:ov:queue:instance:{instance_id}:alive
    • STRING with 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_id into pending, and update metadata
  • 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:

  1. scan each queue's processing zset
  2. parse {message_id}|{instance_id}
  3. check whether {key_prefix}:ov:queue:instance:{instance_id}:alive still exists
  4. 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() passes queuefs.redis through unchanged when backend=redis
  • Rust QueueFSPlugin::parse_backend_config() parses the nested redis object and builds RedisQueueOptions
  • db_path and busy_timeout_ms remain SQLite-only
  • recover_stale_sec does not apply to Redis; Redis recovery is based on dead-instance heartbeat
  • mode must be one of singleton, cluster, or sentinel
  • key_prefix must be non-empty and must not contain { or }, and must be validated in both Python and Rust
  • singleton requires exactly one endpoint
  • cluster and sentinel require at least one endpoint
  • sentinel requires a non-empty master_name
  • cluster only allows db=0
  • master_name, sentinel_username, and sentinel_password have no effect outside sentinel mode
  • the Redis backend internally uses a fixed-size r2d2 pool 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

  1. Reuse the current memory backend semantics for Redis
  • this would be smaller to implement
  • but it would break the current Python dequeue -> process -> ack contract and lose SQLite-aligned recovery semantics
  1. 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
  1. 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 processing ownership
  • preserving the same QueueFS behavior in singleton, cluster, and sentinel deployments
  • keeping the current Python worker lifecycle unchanged
  • isolating multiple QueueFS tenants or business domains with different key_prefix values

Additional Context

This issue is derived from the internal Redis backend design draft for QueueFS.

Relevant files:

  • crates/ragfs/src/plugins/queuefs/backend.rs
  • crates/ragfs/src/plugins/queuefs/mod.rs
  • crates/ragfs/src/plugins/queuefs/redis_backend.rs
  • openviking/utils/agfs_utils.py
  • openviking/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, and sentinel
  • do not use the current memory backend 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_metadata queue_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 1753890123
    queue_messages id 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_messages must be split in Redis

    In SQLite, one queue_messages table expresses three different concerns at once:

    1. queue order
    2. message payload
    3. message state: pending / processing

    Redis has no table abstraction, so these semantics must be split across different key types:

    • use LIST for FIFO pending order
    • use ZSET for processing state and recovery timing
    • use STRING for message payload

    This split is required if QueueFS is expected to preserve its current semantics.

  • Key structure

    key_prefix isolates QueueFS data for different business domains. Its default value is 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 real prefix is {default}:ov:. Different business domains use different key_prefix values so queue registry, messages, and instance heartbeats remain fully isolated.

    All three connection modes use the same key format. In cluster mode, all QueueFS keys for the same key_prefix are pinned to one slot through the {key_prefix} hash tag so Lua scripts operate on same-slot keys. key_prefix must be non-empty and must not contain { or }.

    Assume key_prefix=default, queue name Semantic, and message ID 9d5d....

    • 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_at
        • last_updated
        • last_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_at is for observability and debugging only, not for dead-instance reclaim decisions
      • format constraint: message_id and instance_id use 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 StoredMessage JSON
  • Operation mapping

    QueueFS operation SQLite semantics Redis design
    create_queue insert one row into queue_metadata atomically SADD {key_prefix}:ov:queue:names {queue} and initialize {key_prefix}:ov:queue:{queue}:meta through Lua
    queue_exists query queue_metadata or existing messages SISMEMBER {key_prefix}:ov:queue:names {queue}
    list_queues query metadata table and support legacy backfill SMEMBERS {key_prefix}:ov:queue:names, then filter by queue name prefix in code
    enqueue insert one pending row into queue_messages atomically check queue registration, then SET payload, RPUSH pending message_id, and update metadata through Lua
    peek read the earliest pending row without changing state LINDEX pending 0, then GET payload
    dequeue move the earliest pending row into processing atomically remove the first pending ID and add `{message_id}
    size count rows with status='pending' LLEN pending
    ack delete one processing row by message_id scan processing, match by message_id, remove the matching member, then DEL payload through Lua
    clear delete all message rows for one queue atomically delete pending, processing, and all payload keys for that queue through Lua
    remove_queue delete the target queue and all sub-queues atomically find queue names equal to {queue} or prefixed with {queue}/, then delete all matching queues through Lua
    recover_stale during startup, move abandoned processing rows back to pending scan processing, parse `{message_id}
  • Required dequeue semantics

    The Redis implementation must align with SQLite semantics, not memory semantics.

    Target behavior:

    1. take the earliest pending message
    2. do not delete its payload yet
    3. mark it as processing
    4. return the payload to the caller
    5. permanently delete it only after ack

    This is required to stay compatible with the current Python worker flow:

    1. dequeue
    2. business processing
    3. ack
  • Atomic flows

    • Create Queue
      • implemented with Lua
      • atomic steps:
        1. SADD {key_prefix}:ov:queue:names {queue}
        2. initialize {key_prefix}:ov:queue:{queue}:meta
        3. 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:
        1. serialize StoredMessage
        2. SISMEMBER {key_prefix}:ov:queue:names {queue}
        3. if the queue is not registered, return NotFound before writing any key
        4. SET {key_prefix}:ov:queue:{queue}:msg:{msg_id} {payload}
        5. RPUSH {key_prefix}:ov:queue:{queue}:pending {msg_id}
        6. update {key_prefix}:ov:queue:{queue}:meta when needed
        7. return enqueue result
      • reason:
        • keeps enqueue, dequeue, and ack consistently 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_queue races with enqueue and the message write succeeds even though the queue is no longer in the registry
    • 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:
        1. LPOP {key_prefix}:ov:queue:{queue}:pending
        2. if empty, return nil
        3. GET {key_prefix}:ov:queue:{queue}:msg:{msg_id}
        4. if payload is missing, use LPUSH to return message_id back to pending and return a corruption error
        5. build the processing member {message_id}|{instance_id}
        6. ZADD {key_prefix}:ov:queue:{queue}:processing {now} {processing_member}
        7. return payload
      • reason:
        • avoids taking a pending ID without marking it as processing
        • preserves SQLite-like pending -> processing transition 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:
        1. scan members in processing and find the one matching the requested message_id
        2. ZREM {key_prefix}:ov:queue:{queue}:processing {processing_member}
        3. DEL {key_prefix}:ov:queue:{queue}:msg:{msg_id}
        4. return whether deletion actually happened
    • Instance Heartbeat
      • create a unique instance_id when the service starts, using UUID or ULID
      • after startup:
        1. initialize instance_id
        2. write {key_prefix}:ov:queue:instance:{instance_id}:alive
        3. set TTL to 30 seconds
        4. renew it every 10 seconds
        5. on normal shutdown, stop heartbeat and delete the key so the next instance can recover unfinished work immediately
      • reason:
        • gives the Redis backend multi-instance liveness awareness
        • provides the liveness signal used by recover_stale
    • Recover Stale
      • implemented with Lua and executed once during backend startup
      • atomic steps:
        1. scan members in {key_prefix}:ov:queue:{queue}:processing
        2. parse message_id and instance_id from each {message_id}|{instance_id} member
        3. check whether {key_prefix}:ov:queue:instance:{instance_id}:alive still exists
        4. for each message_id whose instance heartbeat has expired:
          • ZREM processing {processing_member}
          • RPUSH pending {message_id}
      • 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_stale handles 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.
  • Payload format

    Redis payloads reuse the current SQLite StoredMessage JSON 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 pending
    dequeue succeeds, processing crashes before ack message remains in processing; after old-instance heartbeat expiry, a newly started backend can move it back to pending through recover_stale
    dequeue 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:

        • backend
        • db_path
        • recover_stale_sec
        • busy_timeout_ms
        • redis
      • Redis backend configuration should work as follows:

        1. add redis to storage.agfs.queuefs.backend
        2. add nested redis object under storage.agfs.queuefs
        3. Python config assembly passes queuefs.redis through unchanged into QueueFS plugin config
        4. Rust QueueFSPlugin::parse_backend_config() parses the nested redis object and builds RedisQueueOptions
      • use a nested config object rather than flattening Redis fields into the QueueFS top level

      • redis object fields:

        Field Type Description
        mode string Redis connection mode, one of singleton, cluster, or sentinel, default singleton
        key_prefix string QueueFS Redis business prefix, default default, must be non-empty; all keys use {key_prefix}:ov:*
        endpoints string[] Redis endpoints; singleton requires exactly one, cluster requires at least one seed node, sentinel requires at least one Sentinel node
        master_name string | null Sentinel service name; required only in sentinel mode
        username string | null Redis data-node ACL username
        password string | null Redis data-node ACL password
        sentinel_username string | null Sentinel ACL username, only for sentinel mode
        sentinel_password string | null Sentinel ACL password, only for sentinel mode
        db int Redis database number
        connect_timeout_ms int physical 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_ms int command timeout in milliseconds
        tls_enabled bool whether TLS is enabled
        tls_insecure_skip_verify bool whether to skip TLS certificate verification
      • passthrough and parsing rules:

        1. Python openviking/utils/agfs_utils.py::_build_queuefs_plugin_config() writes:
          • backend = "redis"
          • redis = queuefs.redis
        2. Rust crates/ragfs/src/plugins/queuefs/mod.rs extends plugin metadata with:
          • backend allowing redis
          • the redis object parameter
        3. db_path and busy_timeout_ms remain SQLite-only
        4. recover_stale_sec does not apply to Redis; Redis startup recovery is fixed to dead-instance heartbeat checks
        5. mode must be singleton, cluster, or sentinel
        6. key_prefix must be non-empty, must not contain { or }, and is validated in both Python and Rust
        7. singleton requires exactly one endpoint
        8. cluster and sentinel require at least one endpoint
        9. sentinel requires a non-empty master_name
        10. cluster only allows db=0
        11. master_name, sentinel_username, and sentinel_password are ignored outside sentinel mode
      • Redis connection parameters and key_prefix exist only inside queuefs.redis. The top-level config shape stays unchanged. The Redis backend internally uses a fixed-size r2d2 pool 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 increase r2d2 pool capacity.

    • Redis connection modes
      • the three supported modes are singleton, cluster, and sentinel
      • singleton uses redis::Client + r2d2::Pool
      • cluster uses redis::cluster::ClusterClient + r2d2::Pool
      • sentinel uses redis::sentinel::SentinelClient + a minimal r2d2 manager
      • key boundaries:
        1. crates/ragfs/Cargo.toml needs cluster, sentinel, and r2d2 features enabled on the redis dependency
        2. r2d2 is responsible for synchronous connection reuse, capacity limiting, health checks, and passive eviction; it should not be described as active auto-retry
        3. Cluster uses the native redis-rs r2d2 manager. Singleton uses a minimal custom manager that passes connect_timeout_ms to Client::get_connection_with_timeout(). Sentinel uses a minimal custom manager that, after redis-rs completes Master discovery, passes connect_timeout_ms to the target Master's Client::get_connection_with_timeout() and invalidates the topology generation after READONLY or MASTERDOWN
        4. business commands and heartbeat renewals check out separate pooled connections so long business commands do not block heartbeat refresh
        5. the pool stays at max_size=2 with a fixed 5-second checkout timeout; neither is user-configurable, and node connections maintained inside a cluster connection do not count toward that capacity
        6. slot routing, MOVED / ASK handling, node reconnect, and unhealthy-node switching in cluster are delegated to ClusterConnection; QueueFS does not maintain endpoint rotation itself
        7. in Sentinel mode, SentinelClient queries available Sentinel nodes, discovers and validates the current master, then uses connect_timeout_ms for 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 returns READONLY or MASTERDOWN, QueueFS invalidates the current topology generation so the next checkout rediscovers the master
        8. QueueFS does not automatically retry failed Lua write commands whose results are unknown, to avoid double execution of enqueue, dequeue, or ack
        9. 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
    • Backend trait
      • the current QueueBackend trait is synchronous
      • implementation plan:
        1. implement the Redis backend independently inside crates/ragfs / QueueFS
        2. keep the Redis backend directly focused on QueueFS queue semantics: enqueue, dequeue, ack, recover_stale
        3. keep Python bindings and the default build path centered on crates/ragfs-python
        4. place the Redis backend implementation in crates/ragfs/src/plugins/queuefs/redis_backend.rs
      • benefit:
        • clear responsibility boundary for the QueueFS Redis backend
        • no disruption to the current ragfs-python main path
    • Queue clear
      • implement clear with Lua
      • atomic steps:
        1. read all IDs from pending
        2. read all members from processing and parse message_id from {message_id}|{instance_id}
        3. delete corresponding payload keys
        4. delete pending
        5. delete processing
      • reason:
        • keeps implementation style aligned with enqueue, dequeue, and ack
        • avoids half-cleared states if interruption happens mid-operation
        • Lua is sufficient for the expected queue size
    • Queue remove
      • implement remove_queue with Lua
      • atomic steps:
        1. read all registered queues from {key_prefix}:ov:queue:names
        2. select queues equal to the target name or prefixed by {queue}/
        3. delete payloads referenced by pending for every matched queue
        4. delete payloads referenced by processing for every matched queue
        5. delete pending, processing, and meta for every matched queue
        6. remove all matched names from {key_prefix}:ov:queue:names
        7. return NotFound if there are no matches
      • 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_queue recursive deletion semantics, including virtual parent directories that only contain child queues

Contribution

  • [x] I am willing to contribute to implementing this feature

baojun-zhang avatar Aug 05 '26 01:08 baojun-zhang