diff --git a/crates/ragfs/src/plugins/queuefs/backend.rs b/crates/ragfs/src/plugins/queuefs/backend.rs index 50b79acb5d5..071c054118c 100644 --- a/crates/ragfs/src/plugins/queuefs/backend.rs +++ b/crates/ragfs/src/plugins/queuefs/backend.rs @@ -8,7 +8,7 @@ use chrono::{DateTime, Utc}; use rusqlite::{params, types::ValueRef, Connection, Row}; use serde::{Deserialize, Deserializer, Serialize}; use std::collections::{HashMap, VecDeque}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex, Weak}; use std::time::SystemTime; use std::time::{Duration, UNIX_EPOCH}; use uuid::Uuid; @@ -334,7 +334,7 @@ impl QueueBackend for MemoryBackend { /// SQLite queue backend with at-least-once delivery semantics. pub struct SQLiteQueueBackend { - conn: Mutex, + conn: Arc>, } impl SQLiteQueueBackend { @@ -389,10 +389,13 @@ impl SQLiteQueueBackend { .map_err(|e| Error::internal(format!("sqlite schema init error: {}", e)))?; let backend = Self { - conn: Mutex::new(conn), + conn: Arc::new(Mutex::new(conn)), }; backend.run_migrations()?; backend.recover_stale(options.recover_stale_sec)?; + if options.recover_stale_sec > 0 { + spawn_periodic_stale_sweep(Arc::downgrade(&backend.conn), options.recover_stale_sec); + } Ok(backend) } @@ -449,11 +452,15 @@ impl SQLiteQueueBackend { } fn recover_stale(&self, stale_sec: i64) -> Result { - let cutoff = Utc::now().timestamp() - stale_sec.max(0); let conn = self .conn .lock() .map_err(|e| Error::internal(format!("sqlite mutex poisoned: {}", e)))?; + Self::recover_stale_conn(&conn, stale_sec) + } + + fn recover_stale_conn(conn: &Connection, stale_sec: i64) -> Result { + let cutoff = Utc::now().timestamp() - stale_sec.max(0); let changed = if stale_sec <= 0 { conn.execute( @@ -790,6 +797,46 @@ impl QueueBackend for SQLiteQueueBackend { } } +/// Periodically re-run the stale-recovery sweep while the backend is alive. +/// +/// The mount-time recovery in [`SQLiteQueueBackend::open`] only heals orphaned +/// messages once per process start, so a worker that wedges *after* mounting +/// (alive but no longer processing) leaves its in-flight messages stuck until +/// every process restarts (issue #4303). When `stale_sec > 0`, this background +/// sweep re-runs the exact same atomic recovery UPDATE every `stale_sec` +/// seconds, so wedged in-flight messages become visible to healthy workers +/// again without a restart. +/// +/// The sweep thread holds only a [`Weak`] handle: it exits as soon as the +/// backend is dropped. A failed sweep (e.g. transient SQLite busy) is logged +/// and retried on the next tick. `stale_sec <= 0` never starts a sweep loop +/// because the recover-all-on-mount semantics of that mode would reset rows +/// still owned by live workers. +fn spawn_periodic_stale_sweep(conn: Weak>, stale_sec: i64) { + let spawn_result = std::thread::Builder::new() + .name("queuefs-stale-sweep".to_string()) + .spawn(move || { + let interval = Duration::from_secs(stale_sec.max(1) as u64); + loop { + std::thread::sleep(interval); + // The backend (and therefore the database handle) is gone: stop sweeping. + let Some(conn) = conn.upgrade() else { break }; + let guard = match conn.lock() { + Ok(guard) => guard, + Err(_) => continue, + }; + if let Err(error) = SQLiteQueueBackend::recover_stale_conn(&guard, stale_sec) { + tracing::warn!("queuefs periodic stale sweep failed: {error}"); + } + } + }); + if spawn_result.is_err() { + // The mount-time recovery already ran; a missing periodic sweeper only + // degrades back to the pre-existing restart-based behavior. + tracing::warn!("queuefs failed to spawn periodic stale sweep thread"); + } +} + #[cfg(test)] mod tests { use super::*; @@ -1008,6 +1055,66 @@ mod tests { assert_eq!(recovered.data, b"recover me"); } + #[test] + fn test_sqlite_backend_periodic_recovery_recovers_stale_in_flight_message() { + // A worker that dequeued a message and then wedged (never acks, never + // restarts) must have its in-flight message returned to `pending` by + // the periodic sweep once the message crosses the stale threshold — + // without reopening the database (issue #4303). + let dir = tempdir().unwrap(); + let db_path = dir.path().join("queue.db"); + let db_path_str = db_path.to_str().unwrap().to_string(); + + let mut backend = SQLiteQueueBackend::open( + &db_path_str, + SQLiteQueueOptions { + recover_stale_sec: 2, + busy_timeout_ms: 5_000, + }, + ) + .unwrap(); + backend.create_queue("test").unwrap(); + let msg = Message::new(b"wedged worker payload".to_vec()); + let msg_id = msg.id.clone(); + backend.enqueue("test", msg).unwrap(); + + let dequeued = backend.dequeue("test").unwrap().unwrap(); + assert_eq!(dequeued.id, msg_id); + + // Below the 2s stale threshold the sweep must leave the in-flight + // message alone (fresh messages are not re-queued). + std::thread::sleep(Duration::from_millis(1_200)); + assert!(backend.peek("test").unwrap().is_none()); + + // Sweeps run every 2s with the same cutoff as the mount-time + // recovery, so by t=5s the message has crossed the threshold and a + // sweep tick has re-queued it. + std::thread::sleep(Duration::from_millis(3_800)); + let recovered = backend.dequeue("test").unwrap().unwrap(); + assert_eq!(recovered.id, msg_id); + assert_eq!(recovered.data, b"wedged worker payload".to_vec()); + } + + #[test] + fn test_sqlite_backend_no_periodic_recovery_when_recover_stale_disabled() { + // recover_stale_sec = 0 (current default) keeps the historical + // behavior: no background sweep, an in-flight message stays + // `processing` until some process reopens the database. + let (_dir, _db_path_str, mut backend) = sqlite_backend(); + backend.create_queue("test").unwrap(); + let msg = Message::new(b"no sweep payload".to_vec()); + backend.enqueue("test", msg).unwrap(); + + let dequeued = backend.dequeue("test").unwrap().unwrap(); + assert!(dequeued.id.len() > 0); + + std::thread::sleep(Duration::from_millis(1_500)); + assert!( + backend.peek("test").unwrap().is_none(), + "no periodic sweep should run when recover_stale_sec <= 0" + ); + } + #[test] fn test_sqlite_backend_dequeue_legacy_go_row() { let (_dir, db_path_str, mut backend) = sqlite_backend(); diff --git a/crates/ragfs/src/plugins/queuefs/cache_backend.rs b/crates/ragfs/src/plugins/queuefs/cache_backend.rs index 5c89aafffee..9810bed11b1 100644 --- a/crates/ragfs/src/plugins/queuefs/cache_backend.rs +++ b/crates/ragfs/src/plugins/queuefs/cache_backend.rs @@ -4,7 +4,6 @@ use super::cache_protocol::{ queue_names_key, unix_secs, QueueKeys, ACK_SCRIPT, CLEAR_SCRIPT, CREATE_QUEUE_SCRIPT, DEQUEUE_SCRIPT, ENQUEUE_SCRIPT, HEARTBEAT_INTERVAL_SECS, HEARTBEAT_TTL_SECS, LIST_UNACKED_SCRIPT, PEEK_SCRIPT, RECOVER_STALE_SCRIPT, REMOVE_QUEUE_SCRIPT, - STARTUP_RECOVERY_SWEEPS, }; use crate::cache_runtime::{ CacheError, CacheOperation, CacheRuntime, Expiration, ScriptDefinition, ScriptRequest, @@ -110,7 +109,7 @@ impl CacheQueueStorage { heartbeat_receiver, )); let (recovery_stop, recovery_receiver) = watch::channel(false); - let recovery_task = tokio::spawn(run_startup_recovery( + let recovery_task = tokio::spawn(run_recovery_loop( Arc::clone(&runtime), key_prefix.clone(), recovery_receiver, @@ -492,13 +491,14 @@ async fn refresh_heartbeat(runtime: &CacheRuntime, key: &str) -> Result<()> { .map_err(|error| cache_error("heartbeat", error)) } -async fn run_startup_recovery( +async fn run_recovery_loop( runtime: Arc, key_prefix: String, mut stop: watch::Receiver, ) { let started_at = Instant::now(); - for sweep_index in 0..STARTUP_RECOVERY_SWEEPS { + let mut sweep_index = 0usize; + loop { let deadline = started_at + startup_recovery_delay_before_sweep(sweep_index); if deadline > Instant::now() { tokio::select! { @@ -511,13 +511,14 @@ async fn run_startup_recovery( } } if let Err(error) = recover_stale(&runtime, &key_prefix).await { - tracing::warn!("queuefs cache startup recover_stale failed: {error}"); + tracing::warn!("queuefs cache periodic recover_stale failed: {error}"); } + sweep_index = sweep_index.saturating_add(1); } } fn startup_recovery_delay_before_sweep(sweep_index: usize) -> Duration { - Duration::from_secs(HEARTBEAT_TTL_SECS * sweep_index as u64) + Duration::from_secs(HEARTBEAT_TTL_SECS.saturating_mul(sweep_index as u64)) } async fn recover_stale(runtime: &CacheRuntime, key_prefix: &str) -> Result { @@ -645,6 +646,81 @@ mod tests { ); } + #[test] + fn recovery_loop_offsets_never_overflow_at_large_sweep_indexes() { + // The recovery loop now runs for the lifetime of the storage, so the + // per-sweep offset must saturate instead of panicking (or wrapping) + // once the sweep counter grows unboundedly. + assert_eq!( + startup_recovery_delay_before_sweep(usize::MAX), + Duration::from_secs(u64::MAX) + ); + assert_eq!( + startup_recovery_delay_before_sweep(3), + Duration::from_secs(90) + ); + } + + #[tokio::test] + async fn periodic_recovery_returns_message_from_dead_instance_without_reopen() { + // Regression for issue #4303: after the startup sweeps are exhausted, + // a message owned by an instance whose heartbeat disappeared must + // still be re-queued by the long-running recovery loop of another + // live instance — without reopening any storage. + let Ok(endpoint) = std::env::var("REDIS_URL") else { + return; + }; + let runtime = CacheRuntime::redis(crate::cache_runtime::RedisProviderConfig { + endpoints: vec![endpoint], + connect_timeout_ms: 5_000, + command_timeout_ms: 1_000, + default_ttl_seconds: 60, + ..crate::cache_runtime::RedisProviderConfig::default() + }) + .await + .unwrap(); + let prefix = format!("queuefs-periodic-test:{}", Uuid::new_v4()); + let first = CacheQueueStorage::open(Arc::clone(&runtime), prefix.clone()) + .await + .unwrap(); + first.create_queue("jobs").await.unwrap(); + let message = Message::new(b"payload".to_vec()); + let message_id = message.id.clone(); + first.enqueue("jobs", message).await.unwrap(); + assert_eq!(first.dequeue("jobs").await.unwrap().unwrap().id, message_id); + + // A second, healthy instance keeps its recovery loop running. + let second = CacheQueueStorage::open(Arc::clone(&runtime), prefix.clone()) + .await + .unwrap(); + + // Wait past the three legacy startup sweeps (0s/30s/60s) so that any + // recovery observed afterwards is attributable to the new long-running + // sweep loop, not to the pre-existing startup behavior. + tokio::time::sleep(Duration::from_secs(65)).await; + + // Kill the first instance: dropping it removes its heartbeat key, so + // the periodic recovery loop of `second` re-queues the orphaned + // message on a later sweep. + drop(first); + + let recovered = tokio::time::timeout(Duration::from_secs(45), async { + loop { + if let Some(message) = second.dequeue("jobs").await.unwrap() { + break message; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + }) + .await + .expect("periodic recovery loop should re-queue the orphaned message"); + + assert_eq!(recovered.id, message_id); + second.shutdown().await.unwrap(); + runtime.del(&[queue_names_key(&prefix)]).await.unwrap(); + runtime.close().await.unwrap(); + } + #[test] fn drop_outside_tokio_runtime_removes_heartbeat() { let runtime = CacheRuntime::memory(); diff --git a/crates/ragfs/src/plugins/queuefs/cache_protocol.rs b/crates/ragfs/src/plugins/queuefs/cache_protocol.rs index 28963f943b1..a4a3afeeb54 100644 --- a/crates/ragfs/src/plugins/queuefs/cache_protocol.rs +++ b/crates/ragfs/src/plugins/queuefs/cache_protocol.rs @@ -4,7 +4,6 @@ use std::time::{SystemTime, UNIX_EPOCH}; pub(super) const HEARTBEAT_TTL_SECS: u64 = 30; pub(super) const HEARTBEAT_INTERVAL_SECS: u64 = 10; -pub(super) const STARTUP_RECOVERY_SWEEPS: usize = 3; pub(super) const CREATE_QUEUE_SCRIPT: &str = r#" if redis.call('SADD', KEYS[1], ARGV[1]) == 0 then diff --git a/crates/ragfs/src/plugins/queuefs/mod.rs b/crates/ragfs/src/plugins/queuefs/mod.rs index 43bbc85112e..e1be4263965 100644 --- a/crates/ragfs/src/plugins/queuefs/mod.rs +++ b/crates/ragfs/src/plugins/queuefs/mod.rs @@ -626,7 +626,7 @@ impl QueueFSPlugin { "recover_stale_sec", "int", "0", - "Recover processing messages older than this many seconds on startup (0 = recover all)", + "Recover processing messages older than this many seconds on startup and periodically while mounted; 0 recovers all processing messages once on mount only", ), ConfigParameter::optional( "busy_timeout_ms", diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md index 8bdfb2c9810..666ebe88bf7 100644 --- a/docs/en/guides/01-configuration.md +++ b/docs/en/guides/01-configuration.md @@ -1191,7 +1191,7 @@ This is a breaking configuration change. `storage.agfs.cache`, `storage.agfs.que | `mode` | str | QueueFS namespace mode: `"shared"` uses `/queue`; `"worker"` isolates each worker under `/queue/worker-` | `"shared"` | | `backend` | str | QueueFS backend: `"memory"`, `"sqlite"`, `"sqlite3"`, or `"cache"` | `"sqlite"` | | `db_path` | str (optional) | SQLite database path for QueueFS when backend is `"sqlite"` or `"sqlite3"` | `null` | -| `recover_stale_sec` | int | Recover `processing` queue messages older than this many seconds on startup. `0` means recover all stale processing messages | `0` | +| `recover_stale_sec` | int | Recover `processing` queue messages older than this many seconds on mount and every `recover_stale_sec` seconds while mounted (sqlite backend). `0` means recover all `processing` messages once on mount only | `0` | | `busy_timeout_ms` | int | SQLite busy timeout for QueueFS in milliseconds | `5000` | | `cache_key_prefix` | str | QueueFS key namespace when backend is `"cache"` | `"default"` | @@ -1203,7 +1203,7 @@ Notes: - `backend=cache` automatically binds the global `cache.provider + cache.params` configuration. - Redis Cluster slot routing, topology refresh, Sentinel discovery, and reconnects are handled by the Fred RedisProvider. - QueueFS cache keys use `{cache_key_prefix}:ov:*`; use different prefixes for deployments or tenants sharing one Redis cluster. -- Redis backend runs three bounded `recover_stale` sweeps in a dedicated startup recovery thread at startup, 30 seconds, and 60 seconds to cover the heartbeat-expiry window after a container restart; it does not run long-lived periodic recovery. +- Redis backend runs `recover_stale` sweeps in a dedicated recovery task: immediately at startup and then every 30 seconds (one heartbeat TTL) for the lifetime of the storage. Each sweep only re-queues messages whose owning instance heartbeat has expired, covering both the restart window of a container that died with live heartbeats and workers that stay alive but wedged (#4303). - If both `storage.agfs.queuefs.db_path` and legacy `storage.agfs.queue_db_path` are set, `storage.agfs.queuefs.db_path` wins. - If QueueFS backend is `memory`, any `db_path` or legacy `queue_db_path` is ignored. diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md index 2bd31b0f196..41a182243c7 100644 --- a/docs/zh/guides/01-configuration.md +++ b/docs/zh/guides/01-configuration.md @@ -1160,7 +1160,7 @@ RAGFS 默认使用 Rust binding 模式,通过 Rust 实现直接访问文件系 | `mode` | str | QueueFS 命名空间模式:`"shared"` 使用 `/queue`;`"worker"` 为每个 worker 隔离到 `/queue/worker-` | `"shared"` | | `backend` | str | QueueFS 后端:`"memory"`、`"sqlite"`、`"sqlite3"` 或 `"cache"` | `"sqlite"` | | `db_path` | str(可选) | 当 backend 为 `"sqlite"` 或 `"sqlite3"` 时使用的 QueueFS sqlite 数据库路径 | `null` | -| `recover_stale_sec` | int | 启动时恢复超过该秒数的 `processing` 队列消息;`0` 表示恢复全部 stale processing 消息 | `0` | +| `recover_stale_sec` | int | 挂载时及挂载期间每 `recover_stale_sec` 秒恢复超过该秒数的 `processing` 队列消息(仅 sqlite 后端);`0` 表示仅在挂载时一次性恢复全部 `processing` 消息 | `0` | | `busy_timeout_ms` | int | QueueFS sqlite 的 busy timeout,单位毫秒 | `5000` | | `cache_key_prefix` | str | 当 backend 为 `"cache"` 时使用的 QueueFS key 命名空间 | `"default"` | @@ -1176,7 +1176,7 @@ RAGFS 默认使用 Rust binding 模式,通过 Rust 实现直接访问文件系 - `username` 和 `password` 用于 Redis 数据节点;`sentinel_username` 和 `sentinel_password` 仅用于 Sentinel 节点。 - Cache backend 使用 `{cache_key_prefix}:ov:*` key;连接同一 Redis 集群的不同环境或租户必须配置不同的 `cache_key_prefix`。 - Cache backend 的实例心跳 TTL 为 30 秒,每 10 秒续约一次。 -- Cache backend 会在独立的 startup recovery 任务中按实例心跳状态执行三次有界 `recover_stale` 扫描,时间点分别为启动后立即、30 秒和 60 秒,用于覆盖容器异常退出后旧实例心跳尚未过期的恢复窗口;正常关闭会先删除 heartbeat,使新实例可以立即恢复 processing 消息。 +- Cache backend 会在独立的 recovery 任务中按实例心跳状态执行 `recover_stale` 扫描:启动后立即执行一次,之后每 30 秒(一个心跳 TTL)持续执行。每轮扫描只会重投所属实例心跳已过期的消息,既覆盖容器异常退出后旧实例心跳尚未过期的恢复窗口,也覆盖进程存活但已卡死(wedged)的场景(#4303);正常关闭会先删除 heartbeat,使新实例可以立即恢复 processing 消息。 - 所有 Redis 读命令都发送到主节点,不提供副本读配置。 - `tls_insecure_skip_verify=true` 时 endpoint 必须使用 `rediss://`。 - 如果同时设置了 `storage.agfs.queuefs.db_path` 和旧字段 `storage.agfs.queue_db_path`,以前者为准。 diff --git a/openviking_cli/utils/config/agfs_config.py b/openviking_cli/utils/config/agfs_config.py index 4d40dc07578..d5c3f4a1cf5 100644 --- a/openviking_cli/utils/config/agfs_config.py +++ b/openviking_cli/utils/config/agfs_config.py @@ -128,7 +128,7 @@ class QueueFSConfig(BaseModel): recover_stale_sec: int = Field( default=0, - description="Recover processing messages older than this many seconds on startup (0 = recover all).", + description="Recover processing messages older than this many seconds on mount and every recover_stale_sec seconds while mounted (sqlite backend; 0 = recover all once on mount).", ) busy_timeout_ms: int = Field(