Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(pathlock): recover durable handoffs after provider migration (#6745)

zhanglistar871bde266774
diff --git a/crates/ragfs-python/src/lib.rs b/crates/ragfs-python/src/lib.rs
index b7ee33857..1ea462a9c 100644
--- a/crates/ragfs-python/src/lib.rs
+++ b/crates/ragfs-python/src/lib.rs
@@ -21,6 +21,7 @@ use uuid::Uuid;
/// Cached reference to the Python `openviking.storage.errors.LockAcquisitionError` class,
/// imported at module init so that native and Python code share the same exception type.
static LOCK_ACQUISITION_ERROR_TYPE: OnceLock<Py<PyType>> = OnceLock::new();
+static HANDOFF_RECOVERY_ERROR_TYPE: OnceLock<Py<PyType>> = OnceLock::new();
static RUST_TRACING_INIT_RESULT: OnceLock<Result<(), String>> = OnceLock::new();
static RUST_TRACING_GUARD: OnceLock<WorkerGuard> = OnceLock::new();
static RUST_TRACING_FILE_STATE: OnceLock<TracingFileState> = OnceLock::new();
@@ -159,6 +160,12 @@ fn init_tracing(log_level: &str, log_output: &str) -> PyResult<()> {
/// Map a PathLockError to the appropriate Python exception.
fn pathlock_err_to_py(err: PathLockError) -> PyErr {
match &err {
+ PathLockError::HandoffRecoveryRequired { reason } => Python::attach(|py| {
+ let ty = HANDOFF_RECOVERY_ERROR_TYPE
+ .get()
+ .expect("HandoffRecoveryRequired not initialized");
+ PyErr::from_type(ty.bind(py).clone(), reason.to_string())
+ }),
PathLockError::Conflict { .. }
| PathLockError::Timeout { .. }
| PathLockError::HandoffFailed(_)
@@ -225,8 +232,8 @@ use ragfs::core::{
use ragfs::leader::{LeaderLease, LeaderManager};
use ragfs::lock::types::PathLockError;
use ragfs::lock::{
- BorrowedPathLockLease, OwnedPathLockLease, PathLockConfig, PathLockHandoffRef, PathLockKind,
- PathLockManager, PathLockRequest,
+ BorrowedPathLockLease, OwnedPathLockLease, PathLockConfig, PathLockHandleMode,
+ PathLockHandoffRef, PathLockKind, PathLockManager, PathLockRequest,
};
use ragfs::metrics::{RagfsMetric, RagfsMetricValue};
@@ -513,7 +520,10 @@ fn pathlock_config_from_value(
}
let provider = string_field(pathlock, "provider", "filesystem")?;
- if !matches!(provider.as_str(), "filesystem" | "memory" | "sqlite" | "cache") {
+ if !matches!(
+ provider.as_str(),
+ "filesystem" | "memory" | "sqlite" | "cache"
+ ) {
return Err(format!(
"unsupported pathlock.provider: {provider}; expected filesystem, memory, sqlite, or cache"
));
@@ -1469,6 +1479,15 @@ fn handoff_ref_to_py_dict(py: Python<'_>, handoff: &PathLockHandoffRef) -> PyRes
dict.set_item("lease_ref", lease_ref)?;
}
dict.set_item("owner_id", &handoff.owner_id)?;
+ if let Some(mode) = handoff.handle_mode {
+ dict.set_item(
+ "handle_mode",
+ match mode {
+ PathLockHandleMode::LockPath => "lock_path",
+ PathLockHandleMode::LogicalPath => "logical_path",
+ },
+ )?;
+ }
dict.set_item("lock_paths", &handoff.lock_paths)?;
let covered = PyList::empty(py);
for req in &handoff.covered_paths {
@@ -1908,8 +1927,12 @@ impl RAGFSBindingClient {
let kw = kwargs.unwrap_or(&empty);
let req = git::parse_diff_paths_request(kw)?;
let resp = py_detach_blocking(py, move || {
- self.rt
- .block_on(svc.diff_paths(&req.account, req.base.as_deref(), &req.head, &req.paths))
+ self.rt.block_on(svc.diff_paths(
+ &req.account,
+ req.base.as_deref(),
+ &req.head,
+ &req.paths,
+ ))
})
.map_err(|e| git::map_git_error(py, e))?;
Ok(resp
@@ -3141,8 +3164,20 @@ impl RAGFSBindingClient {
.map(|v| v.extract(py))
.transpose()?
.filter(|s: &String| !s.is_empty());
+ let handle_mode = handoff_ref
+ .get("handle_mode")
+ .filter(|v| !v.bind(py).is_none())
+ .map(|v| -> PyResult<PathLockHandleMode> {
+ match v.extract::<String>(py)?.as_str() {
+ "lock_path" => Ok(PathLockHandleMode::LockPath),
+ "logical_path" => Ok(PathLockHandleMode::LogicalPath),
+ _ => Err(PyValueError::new_err("invalid handoff handle_mode")),
+ }
+ })
+ .transpose()?;
let handoff = PathLockHandoffRef {
lease_ref,
+ handle_mode,
owner_id,
lock_paths,
covered_paths,
@@ -3301,6 +3336,9 @@ fn ragfs_python(m: &Bound<'_, PyModule>) -> PyResult<()> {
LOCK_ACQUISITION_ERROR_TYPE
.set(exc_type)
.map_err(|_| PyRuntimeError::new_err("LockAcquisitionError already initialized"))?;
+ HANDOFF_RECOVERY_ERROR_TYPE
+ .set(errors_mod.getattr("HandoffRecoveryRequired")?.extract()?)
+ .map_err(|_| PyRuntimeError::new_err("HandoffRecoveryRequired already initialized"))?;
Ok(())
}
diff --git a/crates/ragfs/src/lock/cache_provder.rs b/crates/ragfs/src/lock/cache_provder.rs
index fb8697d09..3b2e6a372 100644
--- a/crates/ragfs/src/lock/cache_provder.rs
+++ b/crates/ragfs/src/lock/cache_provder.rs
@@ -2257,6 +2257,61 @@ return redis.call("HGET", KEYS[1], ARGV[2])
runtime.close().await.unwrap();
}
+ /// Classify filesystem migration without authorizing or changing old tokens.
+ #[tokio::test]
+ async fn manager_redis_classifies_filesystem_handoffs_without_reading_old_tokens() {
+ let Some((runtime, redis, _, key)) = test_managers("filesystem-migration").await else {
+ return;
+ };
+ let fs = Arc::new(MemFileSystem::new());
+ fs.mkdir("/local", 0o755).await.unwrap();
+ fs.mkdir("/local/account-a", 0o755).await.unwrap();
+ fs.mkdir("/local/account-a/a", 0o755).await.unwrap();
+ let old_provider = Arc::new(super::super::provider::FilesystemPathLockProvider::new(
+ fs.clone(),
+ 30.0,
+ ));
+ let old = PathLockManager::new(fs, old_provider.clone(), PathLockConfig::default());
+ let lease = old
+ .acquire_tree("/local/account-a/a", Duration::ZERO, None)
+ .await
+ .unwrap();
+ let mut handoff = old.to_handoff(&lease);
+ old.handoff(&lease).await.unwrap();
+ assert_eq!(handoff.handle_mode, Some(PathLockHandleMode::LockPath));
+ let old_token = old_provider
+ .read_token(&handoff.lock_paths[0])
+ .await
+ .unwrap();
+ for historic in [false, true] {
+ if historic {
+ handoff.handle_mode = None;
+ handoff.covered_paths.clear();
+ }
+ assert!(matches!(
+ redis.adopt(&handoff).await,
+ Err(PathLockError::HandoffRecoveryRequired {
+ reason: super::super::types::HandoffRecoveryReason::ProviderChanged,
+ })
+ ));
+ }
+ let fresh = redis
+ .acquire_tree("/local/account-a/a", Duration::ZERO, None)
+ .await
+ .unwrap();
+ assert_ne!(fresh.lease.owner_id, handoff.owner_id);
+ assert_eq!(
+ old_provider
+ .read_token(&handoff.lock_paths[0])
+ .await
+ .unwrap(),
+ old_token
+ );
+ redis.release(&fresh).await.unwrap();
+ runtime.del(&[key]).await.unwrap();
+ runtime.close().await.unwrap();
+ }
+
/// Verify Redis handoff can be adopted by another manager using logical handles.
#[tokio::test]
async fn manager_redis_adopts_handoff_across_managers() {
@@ -2286,13 +2341,14 @@ return redis.call("HGET", KEYS[1], ARGV[2])
.expect("producer must forget a released cross-manager handoff");
let legacy = PathLockHandoffRef {
lease_ref: None,
+ handle_mode: None,
owner_id: "owner-a".to_string(),
lock_paths: vec!["/local/account-a/a".to_string()],
covered_paths: Vec::new(),
};
assert!(matches!(
second.adopt(&legacy).await,
- Err(PathLockError::HandoffFailed(_))
+ Err(PathLockError::HandoffRecoveryRequired { .. })
));
runtime.del(&[key]).await.unwrap();
runtime.close().await.unwrap();
diff --git a/crates/ragfs/src/lock/manager.rs b/crates/ragfs/src/lock/manager.rs
index 5e5b729b1..8d1ef1c1f 100644
--- a/crates/ragfs/src/lock/manager.rs
+++ b/crates/ragfs/src/lock/manager.rs
@@ -21,9 +21,9 @@ use super::path::normalize_logical_path;
use super::provider::{AcquisitionChange, AtomicAcquisition, PathLockHandleMode, PathLockProvider};
use super::resolver::{LockPathResolver, ResolvedExactPaths};
use super::types::{
- BorrowedPathLockLease, LockToken, OwnedPathLockLease, PathLockConflict, PathLockError,
- PathLockHandoffRef, PathLockKind, PathLockLease, PathLockObserveSnapshot, PathLockRequest,
- PathLockResult,
+ BorrowedPathLockLease, HandoffRecoveryReason, LockToken, OwnedPathLockLease, PathLockConflict,
+ PathLockError, PathLockHandoffRef, PathLockKind, PathLockLease, PathLockObserveSnapshot,
+ PathLockRequest, PathLockResult,
};
/// Configuration for the PathLockManager.
@@ -1891,6 +1891,7 @@ impl PathLockManager {
pub fn to_handoff(&self, lease: &OwnedPathLockLease) -> PathLockHandoffRef {
PathLockHandoffRef {
lease_ref: Some(lease.lease.lease_ref.clone()),
+ handle_mode: Some(self.provider.handle_mode()),
owner_id: lease.lease.owner_id.clone(),
lock_paths: lease.lease.lock_paths.clone(),
covered_paths: lease.lease.covered_paths.clone(),
@@ -2001,16 +2002,54 @@ impl PathLockManager {
let legacy_handoff = handoff.covered_paths.is_empty();
let handle_mode = self.provider.handle_mode();
- if handle_mode == PathLockHandleMode::LogicalPath && legacy_handoff {
- return Err(PathLockError::HandoffFailed(
- "logical-path provider handoff requires covered_paths".to_string(),
- ));
- }
if !legacy_handoff && handoff.covered_paths.len() != handoff.lock_paths.len() {
return Err(PathLockError::InvalidRequest(
"handoff lock_paths and covered_paths must have equal lengths".to_string(),
));
}
+ // Shapes classify historic payloads only. Same-provider adoption still
+ // validates resolver mappings and live tokens below; migration acquires
+ // fresh coverage through the consumer and never authorizes old handles.
+ let source_mode = match handoff.handle_mode {
+ Some(mode) => mode,
+ None => {
+ let is_file = |lp: &str| {
+ let name = lp.rsplit('/').next().unwrap_or("");
+ name == PATH_LOCK_FILE || name.starts_with(EXACT_LOCK_FILE_PREFIX)
+ };
+ if handoff.lock_paths.iter().all(|lp| is_file(lp)) {
+ PathLockHandleMode::LockPath
+ } else if handoff.lock_paths.iter().any(|lp| is_file(lp)) {
+ return Err(PathLockError::InvalidRequest(
+ "handoff mixes logical and lock-file handles".to_string(),
+ ));
+ } else if legacy_handoff {
+ return Err(PathLockError::HandoffRecoveryRequired {
+ reason: HandoffRecoveryReason::CoverageMissing,
+ });
+ } else if handoff.lock_paths.iter().zip(&handoff.covered_paths).all(
+ |(lp, request)| {
+ normalize_logical_path(&request.path).is_ok_and(|path| lp == path)
+ },
+ ) {
+ PathLockHandleMode::LogicalPath
+ } else {
+ return Err(PathLockError::InvalidRequest(
+ "cannot infer handoff handle representation".to_string(),
+ ));
+ }
+ }
+ };
+ if source_mode != handle_mode {
+ return Err(PathLockError::HandoffRecoveryRequired {
+ reason: HandoffRecoveryReason::ProviderChanged,
+ });
+ }
+ if handle_mode == PathLockHandleMode::LogicalPath && legacy_handoff {
+ return Err(PathLockError::HandoffRecoveryRequired {
+ reason: HandoffRecoveryReason::CoverageMissing,
+ });
+ }
let mut expected_kinds = Vec::with_capacity(handoff.lock_paths.len());
// ponytail: legacy durable handoffs only persisted owner_id/handle_id + lock_paths.
@@ -2042,10 +2081,8 @@ impl PathLockManager {
self.provider
.read_token(lp)
.await?
- .ok_or_else(|| {
- PathLockError::HandoffFailed(format!(
- "lock path '{lp}' no longer exists"
- ))
+ .ok_or_else(|| PathLockError::HandoffRecoveryRequired {
+ reason: HandoffRecoveryReason::TokenUnavailable,
})?
.lock_type
}
@@ -2115,12 +2152,18 @@ impl PathLockManager {
&& token.lock_type == *expected_kind
&& now_ns.saturating_sub(token.time_ns)
< (self.lock_expire_ns() as f64 * LEASE_VALIDITY_RATIO) as u128 => {}
- _ => {
- return Err(PathLockError::HandoffFailed(format!(
- "lock path '{lock_path}' is no longer owned by '{}'",
- handoff.owner_id
+ Some(token)
+ if token.owner_id == handoff.owner_id && token.lock_type != *expected_kind =>
+ {
+ return Err(PathLockError::InvalidRequest(format!(
+ "handoff kind does not match token at '{lock_path}'"
)));
}
+ _ => {
+ return Err(PathLockError::HandoffRecoveryRequired {
+ reason: HandoffRecoveryReason::TokenUnavailable,
+ });
+ }
}
match self
.provider
@@ -2129,10 +2172,9 @@ impl PathLockManager {
{
Ok(true) => {}
Ok(false) => {
- return Err(PathLockError::HandoffFailed(format!(
- "lock path '{lock_path}' changed while adopting owner '{}'",
- handoff.owner_id
- )));
+ return Err(PathLockError::HandoffRecoveryRequired {
+ reason: HandoffRecoveryReason::TokenUnavailable,
+ });
}
Err(error) => return Err(error),
}
@@ -3334,6 +3376,7 @@ mod tests {
// Historic payload: no lease_ref, no covered_paths.
let legacy = PathLockHandoffRef {
lease_ref: None,
+ handle_mode: None,
owner_id: lease.lease.owner_id.clone(),
lock_paths: lease.lease.lock_paths.clone(),
covered_paths: Vec::new(),
@@ -3358,6 +3401,26 @@ mod tests {
consumer.release(&exact).await.unwrap();
}
+ #[tokio::test]
+ async fn remote_adopt_rejects_forged_kind_without_recovery() {
+ let (producer, consumer) = make_filesystem_managers().await;
+ let lease = producer
+ .acquire_exact("/data/a", Duration::ZERO, None)
+ .await
+ .unwrap();
+ let mut handoff = producer.to_handoff(&lease);
+ producer.handoff(&lease).await.unwrap();
+ handoff.covered_paths[0].kind = PathLockKind::Tree;
+ assert!(matches!(
+ consumer.adopt(&handoff).await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ // Rejection does not change the original Exact token or consume the handoff.
+ let adopted = consumer.adopt(&producer.to_handoff(&lease)).await.unwrap();
+ assert_eq!(adopted.lease.covered_paths[0].kind, PathLockKind::Exact);
+ consumer.release(&adopted).await.unwrap();
+ }
+
#[tokio::test]
async fn adopt_accepts_legacy_tree_path_with_covered_paths() {
let mgr = make_manager().await;
@@ -3376,6 +3439,7 @@ mod tests {
.unwrap();
let handoff = PathLockHandoffRef {
lease_ref: Some("legacy-covered-lease".to_string()),
+ handle_mode: None,
owner_id,
lock_paths: vec![lock_path],
covered_paths: vec![PathLockRequest {
diff --git a/crates/ragfs/src/lock/provider.rs b/crates/ragfs/src/lock/provider.rs
index 4d9e1a7d1..5df50b9ea 100644
--- a/crates/ragfs/src/lock/provider.rs
+++ b/crates/ragfs/src/lock/provider.rs
@@ -17,7 +17,8 @@ use super::codec::LockTokenCodec;
use super::types::{LockToken, PathLockError, PathLockRequest, PathLockResult};
/// Representation used for handles stored in a PathLock lease.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
pub enum PathLockHandleMode {
/// Handles are resolver-generated lock-file paths.
LockPath,
diff --git a/crates/ragfs/src/lock/types.rs b/crates/ragfs/src/lock/types.rs
index faacbe594..d7f328b08 100644
--- a/crates/ragfs/src/lock/types.rs
+++ b/crates/ragfs/src/lock/types.rs
@@ -79,6 +79,9 @@ pub struct PathLockHandoffRef {
/// Optional only for backward compatibility with historic queue payloads.
#[serde(default)]
pub lease_ref: Option<String>,
+ /// Provider handle representation; absent in historic queue payloads.
+ #[serde(default)]
+ pub handle_mode: Option<super::provider::PathLockHandleMode>,
/// Owner identity (preserved across handoff).
pub owner_id: String,
/// Lock-file paths held.
@@ -154,6 +157,20 @@ pub struct PathLockConflict {
pub conflicting_kind: PathLockKind,
}
+/// PathLock-specific error type.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum HandoffRecoveryReason {
+ /// The destination uses a different handle representation.
+ #[error("provider_changed")]
+ ProviderChanged,
+ /// Historic logical handles do not describe their lock kinds.
+ #[error("coverage_missing")]
+ CoverageMissing,
+ /// The original token no longer grants ownership.
+ #[error("token_unavailable")]
+ TokenUnavailable,
+}
+
/// PathLock-specific error type.
#[derive(Debug, thiserror::Error)]
pub enum PathLockError {
@@ -207,6 +224,13 @@ pub enum PathLockError {
#[error("handoff/adopt failed: {0}")]
HandoffFailed(String),
+ /// Durable work must acquire fresh coverage before continuing.
+ #[error("handoff recovery required: {reason}")]
+ HandoffRecoveryRequired {
+ /// Structured reason; unrelated failures must not trigger recovery.
+ reason: HandoffRecoveryReason,
+ },
+
/// Internal error.
#[error("lock internal error: {0}")]
Internal(String),
diff --git a/docs/en/concepts/09-transaction.md b/docs/en/concepts/09-transaction.md
index cbeec1375..ff3074c85 100644
--- a/docs/en/concepts/09-transaction.md
+++ b/docs/en/concepts/09-transaction.md
@@ -489,6 +489,106 @@ Legacy compatibility form:
Restart recovery requires persisted queue data. QueueFS uses SQLite by default. With the cache backend, durability depends on the configured Provider; the memory backend loses queued work when the process exits.
+### Single-instance path lock provider switch: filesystem → Redis
+
+This switches the **storage and coordination backend for path locks**: from
+`.ovlock` files managed by the filesystem provider to Redis lock records managed
+by the cache provider. Business files stay in their existing file storage, and
+QueueFS keeps its existing persistent queue backend, such as SQLite. Business
+data and queue messages do not need to move to Redis.
+
+This procedure supports only a **single instance with downtime**:
+
+1. Pause incoming requests and task submissions. Disable any automatic restart
+ or scheduling policy that could restart the old instance. Keep
+ the existing file storage and persistent queues.
+2. Stop the old service and all its queue consumer processes. Verify in the
+ process manager or deployment platform that every old instance PID / container
+ has exited, with no remaining child processes, standalone workers or other
+ writers using filesystem path locks against the same storage. Confirm that
+ the old instance's lock heartbeat renewal tasks have also stopped.
+ **Do not start the instance using Redis path locks until this check passes.**
+3. Change `storage.agfs.pathlock.provider` from `filesystem` to `cache` and
+ configure that cache provider to use Redis.
+4. Start one new instance. Verify that pending jobs recover from the existing
+ queue, acquire fresh path locks in Redis and resume consumption, then reopen
+ incoming requests and task submissions.
+
+`handoff` retains the lease in the old process and keeps its heartbeat running.
+Pausing requests or closing the listening port does not prove that the old
+writers have stopped; verify that all the processes above have exited. Process
+exit terminates their in-memory lease registries and heartbeat tasks, while
+`.ovlock` tokens may remain on disk. Draining the queue, deleting those lock
+files or waiting for old leases to expire is not required.
+
+Filesystem and Redis are independent lock coordination domains: Redis acquire
+**does not check or block old filesystem tokens**. If an old process remains
+alive, both backends can grant different owners the same path, allowing both
+processes to write business files. Waiting for old tokens to expire cannot
+replace the process exit check.
+
+New handoffs include `handle_mode`; historic payloads without it remain supported.
+On a provider change or an unavailable token, consumers acquire the complete
+logical coverage with its Exact/Tree kinds under a new owner before resuming.
+They prefer `covered_paths`, invert historic `.path.ovlock` Tree handles, and use
+the operation's complete requests for non-invertible Exact handles. Recovery
+never acquires only part of a mixed batch. Acquisition conflicts and service
+errors leave durable work pending for retry. Malformed coverage, invalidated
+references, and duplicate adoption do not trigger reacquisition. Old `.ovlock`
+files need no scanning or copying into Redis.
+
+Recovery requires a valid account context and rejects coverage outside that
+account. Semantic jobs preserve the Exact/Tree kind in `covered_paths`. When a
+historic message has no coverage kind and its original granularity cannot be
+determined, recovery conservatively acquires a Tree lock on the operation path
+and logs a warning. This can widen an original Exact lock to Tree and reduce
+concurrency during recovery.
+
+### Blocked recovery retries and alerts
+
+QueueFS has no global retry limit or dead-letter queue. AddResource, Reindex,
+ContentWrite and Semantic consumers allow up to eight retries per delivery chain
+after the initial attempt for `HandoffRecoveryBlocked`, persisting
+`lock_handoff_retry` in the replacement message. If the process crashes after
+the replacement is enqueued but before the original is ACKed, recovery can
+create separate delivery chains from both messages, each retaining its own
+counter. This is therefore not a global retry limit for the same work.
+Each retry waits `min(0.5 × 2^retry, 30)` seconds; backoff
+holds the current consumer slot. Cancellation during backoff or a failed
+enqueue leaves the original delivery unacknowledged. Exhaustion ends the work
+with a failure; task tracking transitions the associated task to FAILED with a
+queryable reason. Failures do not automatically enter a dead-letter queue.
+
+Each blocked recovery logs a warning; exhaustion logs an error. The counter
+`openviking_pathlock_recovery_blocked_total{queue, outcome}` distinguishes
+`retry` from `exhausted`. Enable `server.observability.metrics.enabled` and
+`server.observability.metrics.exporters.prometheus.enabled`, configure Prometheus
+to scrape `/metrics`, then add these example alert rules:
+
+```yaml
+groups:
+ - name: openviking-pathlock-recovery
+ rules:
+ - alert: OpenVikingPathlockRecoveryBlocked
+ expr: sum by (queue) (increase(openviking_pathlock_recovery_blocked_total{outcome="retry"}[5m])) >= 8
+ for: 1m
+ labels:
+ severity: warning
+ annotations:
+ summary: "OpenViking pathlock recovery is repeatedly blocked"
+ - alert: OpenVikingPathlockRecoveryExhausted
+ expr: sum by (queue) (increase(openviking_pathlock_recovery_blocked_total{outcome="exhausted"}[5m])) > 0
+ labels:
+ severity: critical
+ annotations:
+ summary: "OpenViking pathlock recovery retry limit reached"
+```
+
+Adjust thresholds for workload volume. Use the logged `task_id` and failure
+reason to investigate competing writers or Redis availability, then resubmit
+failed tasks after resolving the cause. See [Metrics](./12-metrics.md) and
+[Grafana and Prometheus](../guides/11-grafana-prometheus.md) for monitoring setup.
+
## Related Documentation
- [Architecture](./01-architecture.md) - System architecture overview
diff --git a/docs/zh/concepts/09-transaction.md b/docs/zh/concepts/09-transaction.md
index 3d3feabfe..d77549732 100644
--- a/docs/zh/concepts/09-transaction.md
+++ b/docs/zh/concepts/09-transaction.md
@@ -494,6 +494,89 @@ SQLite 仅支持同机共享同一个本地磁盘数据库文件,不支持 EFS
重启恢复要求队列内容已持久化。QueueFS 默认使用 SQLite;使用 cache 后端时,持久性取决于所配置的 Provider。memory 后端不保留进程退出后的任务。
+### 单实例路径锁 Provider 切换:filesystem → Redis
+
+这里切换的是 **路径锁的存储与协调后端**:从 filesystem Provider 使用的
+`.ovlock` 锁文件,切换为 cache Provider 使用的 Redis 锁记录。
+业务文件仍保存在原有文件存储中,QueueFS 仍使用原有持久化队列后端
+(例如 SQLite);业务数据和队列消息无需迁入 Redis。
+
+此流程仅支持 **单实例、停机切换**。按以下步骤操作:
+
+1. 暂停新请求和任务提交,禁用可能自动拉起旧实例的自动重启或调度策略,
+ 保留原有文件存储和持久化队列。
+2. 停止旧服务及其所有队列消费进程。在进程管理器或部署平台中核对旧实例的
+ PID / 容器已全部退出,且没有残留子进程、独立 worker 或其他访问同一存储的
+ filesystem 路径锁写入者;确认旧实例的锁心跳续租任务也已停止。
+ **完成此检查前,不得启动使用 Redis 路径锁的新实例。**
+3. 将 `storage.agfs.pathlock.provider` 从 `filesystem` 改为 `cache`,
+ 并将该 cache Provider 配置为使用 Redis。
+4. 启动一个新实例,检查积压任务从原队列恢复、在 Redis 中取得新路径锁并正常消费,
+ 再恢复请求入口和任务提交。
+
+`handoff` 会保留旧进程内的 lease 并继续心跳续租,因此停止请求入口或关闭监听端口
+不足以证明旧写入者已停止;必须确认上述进程全部退出。进程退出后,其内存中的
+lease registry 和心跳任务随之终止,磁盘上仍可能残留 `.ovlock` token。
+无需排空队列、删除这些锁文件或等待旧租约过期。
+
+filesystem 与 Redis 是相互独立的锁协调域,Redis 的 acquire **不会检查或阻挡
+旧 filesystem token**。如果旧进程仍在运行,同一路径可能同时被两套后端授予
+不同 owner,两个进程也可能同时写业务文件;等待旧 token 过期不能替代退出检查。
+
+新 handoff 包含 `handle_mode`;旧消息缺少该字段时仍可恢复。
+消费者遇到 Provider 变化或旧 token 不可用时,按完整逻辑路径和 Exact/Tree
+类型重新加锁,获得新 owner 后才执行任务。优先使用 `covered_paths`;
+旧 `.path.ovlock` 可反解 Tree 路径,无法反解的 Exact 文件名使用任务自身的
+完整路径请求。不会只恢复混合批次中的部分路径。
+重新加锁遇到冲突或服务错误时保留任务重试;非法覆盖、失效引用和重复 adopt
+不会触发重新加锁。旧 `.ovlock` 文件无需扫描或复制到 Redis。
+
+恢复必须携带有效账号上下文;缺少上下文或覆盖路径不属于该账号时拒绝恢复。
+语义任务优先保留 `covered_paths` 中的 Exact/Tree 类型;历史消息缺少覆盖类型、
+无法确定原始粒度时,按任务路径保守获取 Tree 锁并记录 warning。
+这可能将原来的 Exact 锁扩大为 Tree 锁,降低恢复期间的并发度。
+
+### 恢复阻塞的重试与告警
+
+QueueFS 没有全局最大重试次数或死信队列。AddResource、Reindex、ContentWrite
+和 Semantic 消费者对 `HandoffRecoveryBlocked` 的每条投递链最多重试 8 次
+(首次尝试之外),通过替代消息中的 `lock_handoff_retry` 持久化计数。
+如果替代消息已入队、原消息尚未 ACK 时进程崩溃,恢复后两条消息可能形成
+不同的投递链,各自沿用消息中的计数,因此这不是同一 work 的全局重试上限。
+每次重试前等待
+`min(0.5 × 2^retry, 30)` 秒;退避期间仍占用当前消费者槽位。
+等待取消或重新入队失败时,不 ACK 原消息;达到上限时结束该 work 并记录失败,
+关联任务通过任务跟踪机制进入 FAILED,可查询失败原因。失败不会自动进入死信队列。
+
+每次阻塞记录 warning,达到上限记录 error,并导出
+`openviking_pathlock_recovery_blocked_total{queue, outcome}`,其中 `outcome`
+为 `retry` 或 `exhausted`。先启用 `server.observability.metrics.enabled`
+和 `server.observability.metrics.exporters.prometheus.enabled`,配置 Prometheus
+抓取 `/metrics`,再将以下示例加入 Prometheus 告警规则:
+
+```yaml
+groups:
+ - name: openviking-pathlock-recovery
+ rules:
+ - alert: OpenVikingPathlockRecoveryBlocked
+ expr: sum by (queue) (increase(openviking_pathlock_recovery_blocked_total{outcome="retry"}[5m])) >= 8
+ for: 1m
+ labels:
+ severity: warning
+ annotations:
+ summary: "OpenViking 路径锁恢复反复阻塞"
+ - alert: OpenVikingPathlockRecoveryExhausted
+ expr: sum by (queue) (increase(openviking_pathlock_recovery_blocked_total{outcome="exhausted"}[5m])) > 0
+ labels:
+ severity: critical
+ annotations:
+ summary: "OpenViking 路径锁恢复已达重试上限"
+```
+
+阈值应按业务流量调整。告警后结合日志中的 `task_id` 和失败原因检查竞争写入者或
+Redis 可用性,解决原因后重新提交失败任务。指标启用和规则配置见
+[指标体系](./12-metrics.md)及 [Grafana 与 Prometheus](../guides/11-grafana-prometheus.md)。
+
## 相关文档
- [架构概述](./01-architecture.md) - 系统整体架构
diff --git a/openviking/metrics/collectors/pathlock.py b/openviking/metrics/collectors/pathlock.py
new file mode 100644
index 000000000..602187b89
--- /dev/null
+++ b/openviking/metrics/collectors/pathlock.py
@@ -0,0 +1,25 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Bounded counters for blocked durable pathlock recovery."""
+
+from typing import ClassVar
+
+from .base import EventMetricCollector
+
+
+class PathLockRecoveryCollector(EventMetricCollector):
+ """Export retry and exhaustion events without task/path label cardinality."""
+
+ SUPPORTED_EVENTS: ClassVar[frozenset[str]] = frozenset({"pathlock.recovery_blocked"})
+
+ def receive_hook(self, event_name: str, payload: dict, registry) -> None:
+ queue, outcome = payload.get("queue"), payload.get("outcome")
+ if queue not in {"AddResource", "Reindex", "ContentWrite", "Semantic"}:
+ return
+ if outcome not in {"retry", "exhausted"}:
+ return
+ registry.inc_counter(
+ "openviking_pathlock_recovery_blocked_total",
+ labels={"queue": queue, "outcome": outcome},
+ label_names=("queue", "outcome"),
+ )
diff --git a/openviking/metrics/global_api.py b/openviking/metrics/global_api.py
index ef756b6bc..3003f8239 100644
--- a/openviking/metrics/global_api.py
+++ b/openviking/metrics/global_api.py
@@ -38,6 +38,7 @@ from .collectors.cache import CacheCollector
from .collectors.embedding import EmbeddingCollector
from .collectors.encryption import EncryptionCollector
from .collectors.http import HTTPCollector
+from .collectors.pathlock import PathLockRecoveryCollector
from .collectors.queue import QueueDurationCollector
from .collectors.rerank import RerankCollector
from .collectors.resource import ResourceIngestionCollector
@@ -246,6 +247,7 @@ def _build_event_router(registry: MetricRegistry) -> EventCollectorRouter:
encryption_collector = EncryptionCollector()
telemetry_bridge_collector = TelemetryBridgeCollector()
queue_duration_collector = QueueDurationCollector()
+ pathlock_recovery_collector = PathLockRecoveryCollector()
def _receiver(collector, event_name: str):
"""
@@ -289,6 +291,7 @@ def _build_event_router(registry: MetricRegistry) -> EventCollectorRouter:
("encryption.key_version_usage", encryption_collector),
("telemetry.summary", telemetry_bridge_collector),
("queue.processed", queue_duration_collector),
+ ("pathlock.recovery_blocked", pathlock_recovery_collector),
):
router.register(event_name, _receiver(collector, event_name))
return router
diff --git a/openviking/service/task_queue_middleware.py b/openviking/service/task_queue_middleware.py
index ced5da664..2cd93fe95 100644
--- a/openviking/service/task_queue_middleware.py
+++ b/openviking/service/task_queue_middleware.py
@@ -98,7 +98,7 @@ class TaskWorkQueueMiddleware(QueueMiddleware):
except BaseException as exc:
if ctx.committed:
record_enqueued_work(ctx.queue, metadata.work_id)
- else:
+ elif registration is WorkRegistration.CREATED:
failure_message = str(exc) or type(exc).__name__
await run_to_completion(
lambda: self._tracker.mark_work_failed(
@@ -110,6 +110,9 @@ class TaskWorkQueueMiddleware(QueueMiddleware):
)
)
record_enqueued_work(ctx.queue, metadata.work_id)
+ # An existing work can still have an unacknowledged delivery. A
+ # failed replacement enqueue must preserve its state so recovery
+ # can execute the original rather than ACK it as terminal.
raise
if ctx.committed:
diff --git a/openviking/storage/errors.py b/openviking/storage/errors.py
index 0e18d787a..fdf10cd7b 100644
--- a/openviking/storage/errors.py
+++ b/openviking/storage/errors.py
@@ -65,6 +65,18 @@ class LockAcquisitionError(LockError):
"""Raised when lock acquisition fails."""
+class HandoffRecoveryRequired(LockAcquisitionError):
+ """A durable consumer must acquire fresh logical coverage before resuming."""
+
+ def __init__(self, reason: str):
+ super().__init__(f"handoff recovery required: {reason}")
+ self.reason = reason
+
+
+class HandoffRecoveryBlocked(LockAcquisitionError):
+ """Fresh acquisition failed; keep the durable work pending for retry."""
+
+
class InvalidPathLockRequestError(ValueError):
"""Raised when a native PathLock request or durable handoff is malformed."""
diff --git a/openviking/storage/pathlock_recovery.py b/openviking/storage/pathlock_recovery.py
new file mode 100644
index 000000000..f6bddc439
--- /dev/null
+++ b/openviking/storage/pathlock_recovery.py
@@ -0,0 +1,155 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Recover durable handoffs by acquiring fresh, complete logical coverage."""
+
+from __future__ import annotations
+
+from asyncio import sleep
+from typing import Any, Awaitable, Callable
+
+from openviking.metrics.datasources.base import EventMetricDataSource
+from openviking.storage.errors import (
+ HandoffRecoveryBlocked,
+ HandoffRecoveryRequired,
+ InvalidPathLockRequestError,
+)
+from openviking.storage.internal_names import MULTIWRITE_PATH_LOCK_FILE
+from openviking_cli.utils.logger import get_logger
+
+logger = get_logger(__name__)
+Requests = list[dict[str, str]]
+HANDOFF_RECOVERY_MAX_RETRIES = 8
+HANDOFF_RECOVERY_MAX_DELAY_SECS = 30.0
+
+
+async def prepare_handoff_retry(msg: Any, error: Exception, *, queue: str) -> dict | None:
+ """Bound recovery retries; keep the original delivery durable during backoff.
+
+ The incremented counter is persisted in the replacement message. If waiting
+ is cancelled or enqueue fails, callers must leave the original unacknowledged.
+ """
+ retry = msg.lock_handoff_retry
+ blocked = isinstance(error, HandoffRecoveryBlocked)
+ limit = HANDOFF_RECOVERY_MAX_RETRIES if blocked else 2
+ exhausted = retry >= limit
+ if blocked:
+ EventMetricDataSource._emit(
+ "pathlock.recovery_blocked",
+ {"queue": queue, "outcome": "exhausted" if exhausted else "retry"},
+ )
+ log = logger.error if exhausted else logger.warning
+ log(
+ "Pathlock recovery blocked queue=%s task_id=%s retry=%d limit=%d exhausted=%s: %s",
+ queue,
+ msg.task_id,
+ retry,
+ limit,
+ exhausted,
+ error,
+ )
+ if exhausted:
+ return None
+ if blocked:
+ await sleep(min(0.5 * 2**retry, HANDOFF_RECOVERY_MAX_DELAY_SECS))
+ payload = msg.to_dict()
+ payload["lock_handoff_retry"] = retry + 1
+ return payload
+
+
+def _validate_requests(requests: Any, account_id: str | None) -> Requests:
+ if not isinstance(requests, list) or not requests:
+ raise InvalidPathLockRequestError("handoff recovery requires complete logical coverage")
+ validated = []
+ for request in requests:
+ if not isinstance(request, dict):
+ raise InvalidPathLockRequestError("invalid handoff coverage")
+ path, kind = request.get("path"), request.get("kind")
+ if (
+ not isinstance(path, str)
+ or not path.startswith("/")
+ or (path != "/" and any(part in {".", "..", ""} for part in path[1:].split("/")))
+ or "\x00" in path
+ or kind not in {"exact", "tree"}
+ or any(
+ part == MULTIWRITE_PATH_LOCK_FILE or part.startswith(".exact.ovlock.")
+ for part in path.split("/")
+ )
+ ):
+ raise InvalidPathLockRequestError("invalid logical handoff coverage")
+ if account_id is not None and not (
+ path == f"/local/{account_id}" or path.startswith(f"/local/{account_id}/")
+ ):
+ raise InvalidPathLockRequestError("handoff coverage belongs to another account")
+ validated.append({"path": path, "kind": kind})
+ return validated
+
+
+def _covers(held: dict[str, str], requested: dict[str, str]) -> bool:
+ return (
+ held["path"] == requested["path"]
+ and (held["kind"] == "tree" or requested["kind"] == "exact")
+ ) or (
+ held["kind"] == "tree"
+ and (held["path"] == "/" or requested["path"].startswith(held["path"] + "/"))
+ )
+
+
+async def adopt_or_reacquire(
+ agfs: Any,
+ handoff: dict[str, Any],
+ *,
+ ctx: Any,
+ fallback_requests: Callable[[], Awaitable[Requests]] | None = None,
+) -> Any:
+ """Recover only typed adoption failures; acquire under a new owner.
+
+ Callers must supply the complete operation scope for historic handles that
+ cannot be inverted, and retain the result using a cancellation-safe guard.
+ """
+ account_id = getattr(ctx, "account_id", None)
+ if (
+ not isinstance(account_id, str)
+ or not account_id.strip()
+ or "/" in account_id
+ or account_id in {".", ".."}
+ or "\x00" in account_id
+ ):
+ raise InvalidPathLockRequestError("handoff recovery requires an account context")
+ kwargs = {"fs_ctx": {"account_id": account_id}}
+ try:
+ return await agfs.pathlock_adopt(handoff, **kwargs)
+ except HandoffRecoveryRequired as error:
+ operation = (
+ _validate_requests(await fallback_requests(), account_id)
+ if fallback_requests is not None
+ else None
+ )
+ requests = handoff.get("covered_paths")
+ if not requests:
+ suffix = f"/{MULTIWRITE_PATH_LOCK_FILE}"
+ handles = handoff.get("lock_paths") or []
+ # Never recover just the invertible subset of a mixed batch.
+ if handles and all(isinstance(p, str) and p.endswith(suffix) for p in handles):
+ requests = [{"path": p[: -len(suffix)] or "/", "kind": "tree"} for p in handles]
+ else:
+ requests = operation
+ requests = _validate_requests(requests, account_id)
+ if operation is not None and any(
+ not any(_covers(held, required) for held in requests) for required in operation
+ ):
+ raise InvalidPathLockRequestError(
+ "handoff coverage does not cover the queued operation"
+ )
+ try:
+ lease = await agfs.pathlock_acquire_batch(requests, **kwargs)
+ except ValueError:
+ raise
+ except Exception as blocked:
+ raise HandoffRecoveryBlocked(str(blocked)) from blocked
+ logger.info(
+ "Recovered pathlock handoff owner=%s reason=%s coverage=%s",
+ handoff.get("owner_id", handoff.get("handle_id")),
+ error.reason,
+ requests,
+ )
+ return lease
diff --git a/openviking/storage/queuefs/add_resource_processor.py b/openviking/storage/queuefs/add_resource_processor.py
index 27fe29e0d..cc50d6016 100644
--- a/openviking/storage/queuefs/add_resource_processor.py
+++ b/openviking/storage/queuefs/add_resource_processor.py
@@ -16,6 +16,7 @@ from openviking.service.task_work_index import (
bind_task_context_from_message,
extract_task_metadata,
)
+from openviking.storage.pathlock_recovery import adopt_or_reacquire, prepare_handoff_retry
from openviking.storage.pathlock_transfer import PathLockGuard
from openviking.storage.queuefs.add_resource_msg import AddResourceMsg
from openviking.storage.queuefs.named_queue import DequeueHandlerBase
@@ -53,16 +54,13 @@ class AddResourceProcessor(DequeueHandlerBase):
"""Adopt a pathlock handoff ref, returning an owned lease dict."""
if msg.lock_handoff is None:
return None
- try:
- return await self._viking_fs._async_agfs.pathlock_adopt(msg.lock_handoff)
- except Exception as handoff_error:
- try:
- return await self._resource_service.reacquire_add_resource_job_lock(
- msg.root_uri,
- ctx,
- )
- except Exception:
- raise handoff_error
+
+ async def requests():
+ return [{"path": self._viking_fs._uri_to_path(msg.root_uri, ctx=ctx), "kind": "tree"}]
+
+ return await adopt_or_reacquire(
+ self._viking_fs._async_agfs, msg.lock_handoff, ctx=ctx, fallback_requests=requests
+ )
async def _cleanup_staged_source(self, msg: AddResourceMsg, ctx: RequestContext) -> None:
if msg.staged_source is None:
@@ -89,7 +87,10 @@ class AddResourceProcessor(DequeueHandlerBase):
if msg.lock_handoff is not None:
lock_guard = PathLockGuard(self._viking_fs._async_agfs)
try:
- await lock_guard.adopt(msg.lock_handoff)
+ if msg.cleanup_empty_target_on_failure:
+ await lock_guard.acquire(lambda: self._load_lock(msg, ctx))
+ else:
+ await lock_guard.adopt(msg.lock_handoff)
if msg.cleanup_empty_target_on_failure:
await self._resource_service._cleanup_reserved_target_if_empty(
root_uri=msg.root_uri,
@@ -141,13 +142,12 @@ class AddResourceProcessor(DequeueHandlerBase):
await self._record_watch_execution(msg, "cancelled")
async def _requeue_lock_handoff(self, msg: AddResourceMsg, exc: Exception) -> bool:
- if msg.lock_handoff_retry >= 2:
+ payload = await prepare_handoff_retry(msg, exc, queue="AddResource")
+ if payload is None:
return False
from openviking.storage.queuefs import get_queue_manager
- payload = msg.to_dict()
- payload["lock_handoff_retry"] = msg.lock_handoff_retry + 1
await get_queue_manager().enqueue(self._queue_name, payload)
logger.warning(
"[AddResource] Requeued task %s after lock handoff failure: %s",
diff --git a/openviking/storage/queuefs/content_write_processor.py b/openviking/storage/queuefs/content_write_processor.py
index ea226069c..29f562dd4 100644
--- a/openviking/storage/queuefs/content_write_processor.py
+++ b/openviking/storage/queuefs/content_write_processor.py
@@ -18,6 +18,7 @@ from openviking.service.task_work_index import (
)
from openviking.storage.context_update_execution import commit_and_enqueue_plan
from openviking.storage.context_update_plan import ContextUpdatePlan
+from openviking.storage.pathlock_recovery import adopt_or_reacquire, prepare_handoff_retry
from openviking.storage.pathlock_transfer import PathLockGuard
from openviking.storage.queuefs.content_write_msg import ContentWriteMsg
from openviking.storage.queuefs.named_queue import DequeueHandlerBase
@@ -54,7 +55,7 @@ class ContentWriteProcessor(DequeueHandlerBase):
uris: set[str] = set()
result = msg.result if isinstance(msg.result, dict) else {}
- for field in ("created", "updated", "unchanged"):
+ for field in ("created", "updated", "unchanged", "deleted"):
values = result.get(field)
if isinstance(values, list):
uris.update(str(value) for value in values if value)
@@ -70,42 +71,33 @@ class ContentWriteProcessor(DequeueHandlerBase):
uris.add(str(plan["root_uri"]))
return sorted(uris)
- async def _reacquire_lock(self, msg: ContentWriteMsg, ctx: RequestContext) -> Dict[str, Any]:
- covered_paths = (
- msg.lock_handoff.get("covered_paths")
- if isinstance(msg.lock_handoff, dict)
- else None
- )
- if isinstance(covered_paths, list) and covered_paths:
- return await self._viking_fs._async_agfs.pathlock_acquire_batch(covered_paths)
-
- uris = self._uris_for_reacquire(msg)
- if not uris:
- raise ValueError("content-write lock reacquire has no resource URI")
- paths = [self._viking_fs._uri_to_path(uri, ctx=ctx) for uri in uris]
- if len(paths) == 1:
- return await self._viking_fs._async_agfs.pathlock_acquire_exact(paths[0])
- return await self._viking_fs._async_agfs.pathlock_acquire_exact_batch(paths)
-
async def _load_lock(self, msg: ContentWriteMsg, ctx: RequestContext) -> Dict[str, Any] | None:
if msg.lock_handoff is None:
return None
- try:
- return await self._viking_fs._async_agfs.pathlock_adopt(msg.lock_handoff)
- except Exception as handoff_error:
- try:
- return await self._reacquire_lock(msg, ctx)
- except Exception:
- raise handoff_error
+
+ async def requests():
+ uris = self._uris_for_reacquire(msg)
+ # Content-write producers acquire Exact locks on their write targets,
+ # including RNFV file plans; generated parent sidecars are not targets.
+ return [
+ {
+ "path": self._viking_fs._uri_to_path(uri, ctx=ctx),
+ "kind": "exact",
+ }
+ for uri in uris
+ ]
+
+ return await adopt_or_reacquire(
+ self._viking_fs._async_agfs, msg.lock_handoff, ctx=ctx, fallback_requests=requests
+ )
async def _requeue_lock_handoff(self, msg: ContentWriteMsg, exc: Exception) -> bool:
- if msg.lock_handoff_retry >= 2:
+ payload = await prepare_handoff_retry(msg, exc, queue="ContentWrite")
+ if payload is None:
return False
from openviking.storage.queuefs import get_queue_manager
- payload = msg.to_dict()
- payload["lock_handoff_retry"] = msg.lock_handoff_retry + 1
queue_manager = get_queue_manager()
await queue_manager.enqueue(queue_manager.CONTENT_WRITE, payload)
logger.warning(
@@ -174,14 +166,11 @@ class ContentWriteProcessor(DequeueHandlerBase):
)
metadata = extract_task_metadata(data)
- dispatch_complete = (
- metadata is not None
- and await tracker.is_enqueue_complete(
- msg.task_id,
- metadata.work_id,
- account_id=ctx.account_id,
- user_id=ctx.user.user_id,
- )
+ dispatch_complete = metadata is not None and await tracker.is_enqueue_complete(
+ msg.task_id,
+ metadata.work_id,
+ account_id=ctx.account_id,
+ user_id=ctx.user.user_id,
)
lock_guard = PathLockGuard(self._viking_fs._async_agfs)
if not dispatch_complete or (
@@ -209,7 +198,9 @@ class ContentWriteProcessor(DequeueHandlerBase):
try:
result_updates: Dict[str, Any] = {}
checkpoint_result = (
- deepcopy(task.result) if dispatch_complete and isinstance(task.result, dict) else None
+ deepcopy(task.result)
+ if dispatch_complete and isinstance(task.result, dict)
+ else None
)
if not dispatch_complete:
if lock_guard.lease is not None and msg.lock_scope == "semantic_handoff":
@@ -237,9 +228,7 @@ class ContentWriteProcessor(DequeueHandlerBase):
semantic_lock_handoff,
dispatch_refresh,
accepted=lambda value: (
- isinstance(value, tuple)
- and len(value) == 2
- and bool(value[1])
+ isinstance(value, tuple) and len(value) == 2 and bool(value[1])
),
)
if (
diff --git a/openviking/storage/queuefs/reindex_processor.py b/openviking/storage/queuefs/reindex_processor.py
index eac1e38be..e99a4b4b9 100644
--- a/openviking/storage/queuefs/reindex_processor.py
+++ b/openviking/storage/queuefs/reindex_processor.py
@@ -11,6 +11,7 @@ from typing import Any, Dict, Optional
from openviking.server.identity import RequestContext, Role
from openviking.service.task_tracker import TaskStatus, get_task_tracker
from openviking.service.task_work_index import bind_task_context_from_message, extract_task_metadata
+from openviking.storage.pathlock_recovery import adopt_or_reacquire, prepare_handoff_retry
from openviking.storage.pathlock_transfer import PathLockGuard
from openviking.storage.queuefs.named_queue import DequeueHandlerBase
from openviking.storage.queuefs.process_result import ProcessResult
@@ -46,10 +47,15 @@ class ReindexProcessor(DequeueHandlerBase):
async def _adopt_or_reacquire(self, msg: ReindexMsg, ctx: RequestContext) -> Dict[str, Any]:
agfs = self._viking_fs._async_agfs
if msg.lock_handoff is not None:
- try:
- return await agfs.pathlock_adopt(msg.lock_handoff)
- except Exception:
- pass
+
+ async def requests():
+ stat = await self._viking_fs.stat(msg.uri, ctx=ctx, skip_count=True)
+ kind = "tree" if stat.get("isDir", stat.get("is_dir")) else "exact"
+ return [{"path": self._viking_fs._uri_to_path(msg.uri, ctx=ctx), "kind": kind}]
+
+ return await adopt_or_reacquire(
+ agfs, msg.lock_handoff, ctx=ctx, fallback_requests=requests
+ )
stat = await self._viking_fs.stat(msg.uri, ctx=ctx, skip_count=True)
acquire = (
agfs.pathlock_acquire_tree
@@ -59,13 +65,12 @@ class ReindexProcessor(DequeueHandlerBase):
return await acquire(self._viking_fs._uri_to_path(msg.uri, ctx=ctx))
async def _requeue_lock_handoff(self, msg: ReindexMsg, exc: Exception) -> bool:
- if msg.lock_handoff_retry >= 2:
+ payload = await prepare_handoff_retry(msg, exc, queue="Reindex")
+ if payload is None:
return False
from openviking.storage.queuefs import get_queue_manager
- payload = msg.to_dict()
- payload["lock_handoff_retry"] = msg.lock_handoff_retry + 1
queue_manager = get_queue_manager()
await queue_manager.enqueue(queue_manager.REINDEX, payload)
logger.warning(
diff --git a/openviking/storage/queuefs/semantic_lock.py b/openviking/storage/queuefs/semantic_lock.py
index 672c0f57e..cf9c7c1f3 100644
--- a/openviking/storage/queuefs/semantic_lock.py
+++ b/openviking/storage/queuefs/semantic_lock.py
@@ -5,42 +5,15 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import Any, Callable, Dict, Iterable, Optional
+from typing import Any, Callable, Dict, Optional
-from openviking.storage.errors import InvalidPathLockRequestError, LockAcquisitionError
-from openviking.storage.internal_names import MULTIWRITE_PATH_LOCK_FILE
+from openviking.storage.pathlock_recovery import adopt_or_reacquire
from openviking.storage.pathlock_transfer import PathLockGuard
from openviking.storage.viking_fs import get_viking_fs
from openviking_cli.utils.logger import get_logger
logger = get_logger(__name__)
-_TREE_LOCK_SUFFIX = f"/{MULTIWRITE_PATH_LOCK_FILE}"
-
-
-def _is_recoverable_handoff_error(error: Exception) -> bool:
- """Return whether a durable handoff can be replaced by logical reacquisition."""
- message = str(error)
- if isinstance(error, LockAcquisitionError):
- return "is no longer owned by" in message or (
- "logical-path provider handoff requires covered_paths" in message
- )
- return isinstance(error, InvalidPathLockRequestError) and (
- "handoff coverage" in message and "does not map to lock path" in message
- )
-
-
-def _tree_paths_from_handoff(lock_paths: Iterable[str]) -> list[str]:
- """Extract tree lock directory paths from legacy lock file handles."""
- tree_paths: list[str] = []
- for lock_path in lock_paths:
- if not lock_path.endswith(_TREE_LOCK_SUFFIX):
- continue
- tree_path = lock_path[: -len(_TREE_LOCK_SUFFIX)] or "/"
- if tree_path not in tree_paths:
- tree_paths.append(tree_path)
- return tree_paths
-
@dataclass
class SemanticLockScope:
@@ -56,6 +29,7 @@ class SemanticLockScope:
*,
caller_lock: Optional[Dict[str, Any]] = None,
fallback_path_factory: Optional[Callable[[], str]] = None,
+ ctx: Any = None,
) -> "SemanticLockScope":
"""Resolve a live lock, reacquiring its original coverage when stale."""
if lock_handoff and caller_lock is not None:
@@ -65,30 +39,33 @@ class SemanticLockScope:
return cls(await viking_fs._async_agfs.pathlock_as_borrowed(caller_lock), _owned=False)
if lock_handoff:
viking_fs = get_viking_fs()
- try:
- return cls(await viking_fs._async_agfs.pathlock_adopt(lock_handoff), _owned=True)
- except (InvalidPathLockRequestError, LockAcquisitionError) as error:
- # ponytail: Replace this message check with a recoverable handoff
- # exception when the native binding exposes typed handoff failures.
- if not _is_recoverable_handoff_error(error):
- raise
- covered_paths = lock_handoff.get("covered_paths") or []
- if not covered_paths:
- tree_paths = _tree_paths_from_handoff(lock_handoff["lock_paths"])
- if not tree_paths and fallback_path_factory:
- tree_paths = [fallback_path_factory()]
- if not tree_paths:
- raise
- covered_paths = [{"path": path, "kind": "tree"} for path in tree_paths]
-
- lease = await viking_fs._async_agfs.pathlock_acquire_batch(covered_paths)
- logger.info(
- "Recovered semantic lock handoff %s by reacquiring %s",
- lock_handoff.get("owner_id"),
- covered_paths,
+ async def requests():
+ path = fallback_path_factory()
+ # File semantic plans can legitimately carry an Exact lease.
+ # Preserve its kind rather than escalating it to a Tree lease.
+ kind = next(
+ (
+ item.get("kind")
+ for item in lock_handoff.get("covered_paths") or []
+ if isinstance(item, dict) and item.get("path") == path
+ ),
+ "tree",
)
- return cls(lease, _owned=True)
+ if not lock_handoff.get("covered_paths"):
+ logger.warning(
+ "Recovering historic semantic handoff with conservative Tree coverage path=%s",
+ path,
+ )
+ return [{"path": path, "kind": kind}]
+
+ lease = await adopt_or_reacquire(
+ viking_fs._async_agfs,
+ lock_handoff,
+ ctx=ctx,
+ fallback_requests=requests if fallback_path_factory else None,
+ )
+ return cls(lease, _owned=True)
return cls(None)
async def close(self) -> None:
diff --git a/openviking/storage/queuefs/semantic_msg.py b/openviking/storage/queuefs/semantic_msg.py
index 3b6d63181..8b909acee 100644
--- a/openviking/storage/queuefs/semantic_msg.py
+++ b/openviking/storage/queuefs/semantic_msg.py
@@ -64,6 +64,7 @@ class SemanticMsg:
_task_work_id: str = ""
target_uri: str = ""
lock_handoff: Optional[Dict[str, Any]] = None
+ lock_handoff_retry: int = 0
is_code_repo: bool = False
ingest_options: IngestOptions = field(default_factory=IngestOptions)
coalesce_key: str = ""
@@ -124,6 +125,7 @@ class SemanticMsg:
plan: SemanticPlan | Dict[str, Any] | None = None,
queue_enqueued_at: float = 0.0,
failure_requeue_count: int = 0,
+ lock_handoff_retry: int = 0,
):
self.id = str(uuid4())
self.timestamp = int(datetime.now().timestamp())
@@ -143,6 +145,10 @@ class SemanticMsg:
self._task_work_id = _task_work_id
self.target_uri = target_uri
self.lock_handoff = lock_handoff
+ try:
+ self.lock_handoff_retry = max(0, int(lock_handoff_retry or 0))
+ except (TypeError, ValueError):
+ self.lock_handoff_retry = 0
self.is_code_repo = is_code_repo
self.ingest_options = IngestOptions.from_value(ingest_options)
self.coalesce_key = coalesce_key
@@ -226,6 +232,7 @@ class SemanticMsg:
_task_work_id=data.get("_task_work_id", ""),
target_uri=data.get("target_uri", ""),
lock_handoff=data.get("lock_handoff"),
+ lock_handoff_retry=data.get("lock_handoff_retry", 0),
is_code_repo=data.get("is_code_repo", False),
ingest_options=(
data.get("ingest_options")
diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.py
index e8146cc60..dbaa7d4f8 100644
--- a/openviking/storage/queuefs/semantic_processor.py
+++ b/openviking/storage/queuefs/semantic_processor.py
@@ -48,8 +48,13 @@ from openviking.storage.abstract_overview import (
plan_abstract_overview_refresh,
write_abstract_overview,
)
-from openviking.storage.errors import InvalidPathLockRequestError, LockAcquisitionError
+from openviking.storage.errors import (
+ HandoffRecoveryBlocked,
+ InvalidPathLockRequestError,
+ LockAcquisitionError,
+)
from openviking.storage.index_action import FieldPatch
+from openviking.storage.pathlock_recovery import prepare_handoff_retry
from openviking.storage.pathlock_transfer import PathLockGuard
from openviking.storage.queuefs.named_queue import DequeueHandlerBase
from openviking.storage.queuefs.process_result import ProcessResult
@@ -358,10 +363,21 @@ class SemanticProcessor(DequeueHandlerBase):
*,
work: SemanticMessageWork,
) -> ProcessResult:
+ if isinstance(error, HandoffRecoveryBlocked):
+ payload = await prepare_handoff_retry(msg, error, queue="Semantic")
+ if payload is None:
+ self._merge_request_stats(msg.telemetry_id, error_count=1)
+ await self._cleanup_local_artifact(msg)
+ return ProcessResult.failed(f"Pathlock recovery retry limit reached: {error}")
+ msg.lock_handoff_retry = payload["lock_handoff_retry"]
try:
await work.reenqueue_after_error()
self._merge_request_stats(msg.telemetry_id, requeue_count=1)
except Exception as requeue_err:
+ if isinstance(error, HandoffRecoveryBlocked):
+ # No replacement is durable: propagate so the original delivery
+ # remains recoverable rather than being ACKed as failed.
+ raise
logger.error(f"Failed to re-enqueue semantic message: {requeue_err}")
self._merge_request_stats(msg.telemetry_id, error_count=1)
await self._cleanup_local_artifact(msg)
@@ -912,6 +928,7 @@ class SemanticProcessor(DequeueHandlerBase):
scope = await SemanticLockScope.resolve(
msg.lock_handoff,
caller_lock=caller_lock,
+ ctx=ctx,
fallback_path_factory=lambda: viking_fs._uri_to_path(msg.uri, ctx=ctx),
)
if scope.lock is None and await viking_fs.exists(msg.uri, ctx=ctx):
diff --git a/openviking/storage/queuefs/semantic_work.py b/openviking/storage/queuefs/semantic_work.py
index 3d95de780..76fa39712 100644
--- a/openviking/storage/queuefs/semantic_work.py
+++ b/openviking/storage/queuefs/semantic_work.py
@@ -55,6 +55,7 @@ class SemanticMessageWork:
self.scope = await SemanticLockScope.resolve(
self.msg.lock_handoff,
caller_lock=self.caller_lock,
+ ctx=ctx,
fallback_path_factory=lambda: get_viking_fs()._uri_to_path(self.msg.uri, ctx=ctx),
)
diff --git a/tests/agfs/test_handoff_requeue_enqueue_failure.py b/tests/agfs/test_handoff_requeue_enqueue_failure.py
new file mode 100644
index 000000000..fabe617b2
--- /dev/null
+++ b/tests/agfs/test_handoff_requeue_enqueue_failure.py
@@ -0,0 +1,242 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Failed handoff replacements must survive a real SQLite QueueFS restart."""
+
+import json
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from openviking.pyagfs.async_client import AsyncAGFSClient
+from openviking.service import task_tracker as tracker_module
+from openviking.service.reindex_executor import ReindexExecutor
+from openviking.service.task_domain import TaskStatus, WorkState
+from openviking.service.task_store import PersistentTaskStore
+from openviking.service.task_tracker import TaskTracker
+from openviking.service.task_work_index import bind_task_context, extract_task_metadata
+from openviking.storage.errors import HandoffRecoveryBlocked
+from openviking.storage.queuefs import queue_manager as manager_module
+from openviking.storage.queuefs.add_resource_msg import AddResourceMsg
+from openviking.storage.queuefs.add_resource_processor import AddResourceProcessor
+from openviking.storage.queuefs.content_write_msg import ContentWriteMsg
+from openviking.storage.queuefs.content_write_processor import ContentWriteProcessor
+from openviking.storage.queuefs.named_queue import DequeueHandlerBase
+from openviking.storage.queuefs.process_result import ProcessResult
+from openviking.storage.queuefs.queue_manager import QueueManager
+from openviking.storage.queuefs.reindex_msg import ReindexMsg
+from openviking.storage.queuefs.reindex_processor import ReindexProcessor
+from openviking.storage.queuefs.semantic_msg import SemanticMsg
+from openviking.storage.queuefs.semantic_processor import SemanticProcessor
+from openviking.storage.queuefs.semantic_work import SemanticMessageWork, SkillSemanticMessageWork
+from openviking.storage.viking_fs import VikingFS
+from openviking.utils.agfs_utils import RagfsBindingConfig, create_agfs_client
+from openviking_cli.utils.config.agfs_config import AGFSConfig
+
+OWNER = {"account_id": "recovery", "user_id": "tester"}
+OUTPUT = "/local/recovery/resources/result.md"
+
+
+ "consumer", ["AddResource", "Reindex", "ContentWrite", "Semantic", "SemanticSkill"]
+)
+async def test_handoff_replacement_enqueue_failure_survives_restart(
+ tmp_path, monkeypatch, consumer
+):
+ """Use real retry methods, middleware, TaskStore, queue recovery and ACK.
+
+ Reindex runs its full consumer with only lock contention and the expensive
+ executor body substituted. Other cases drive their real retry methods from
+ a small handler, including both real SemanticMessageWork implementations.
+ """
+ config = RagfsBindingConfig(
+ agfs=AGFSConfig(
+ path=str(tmp_path),
+ backend="local",
+ queuefs={"backend": "sqlite", "recover_stale_sec": 0},
+ )
+ )
+ monkeypatch.setattr("openviking.storage.pathlock_recovery.sleep", AsyncMock())
+ queue_name = "Semantic" if consumer.startswith("Semantic") else consumer
+ message_type = {
+ "AddResource": AddResourceMsg,
+ "Reindex": ReindexMsg,
+ "ContentWrite": ContentWriteMsg,
+ "Semantic": SemanticMsg,
+ }[queue_name]
+ common = {"task_id": "task", **OWNER, "role": "root"}
+ if queue_name == "AddResource":
+ initial = AddResourceMsg(root_uri="viking://resources", path="/source/input.md", **common)
+ elif queue_name == "Reindex":
+ initial = ReindexMsg(
+ uri="viking://resources/result.md", object_type="resource", mode="index", **common
+ )
+ elif queue_name == "ContentWrite":
+ initial = ContentWriteMsg(
+ operation="write",
+ resource_id="viking://resources/result.md",
+ result={},
+ refresh={},
+ **common,
+ )
+ else:
+ initial = SemanticMsg(
+ uri="viking://resources",
+ context_type="skill" if consumer == "SemanticSkill" else "resource",
+ **common,
+ )
+
+ blocked = True
+ executed = []
+ clients = []
+
+ async def write_business_result(agfs, lease):
+ await agfs.write(
+ OUTPUT,
+ b"business executed",
+ fs_ctx={"account_id": OWNER["account_id"], "lease_ref": lease["lease_ref"]},
+ )
+ executed.append(OUTPUT)
+
+ def open_runtime():
+ client = create_agfs_client(config)
+ clients.append(client)
+ agfs = AsyncAGFSClient(client)
+ tracker = TaskTracker(PersistentTaskStore(client))
+ manager = QueueManager(client)
+ monkeypatch.setattr(tracker_module, "_instance", tracker)
+ monkeypatch.setattr(manager_module, "_instance", manager)
+ queue = manager.get_queue(queue_name, allow_create=True)
+ fs = VikingFS(client)
+ processors = {
+ "AddResource": lambda: AddResourceProcessor(None, queue_name, fs),
+ "Reindex": lambda: ReindexProcessor(fs),
+ "ContentWrite": lambda: ContentWriteProcessor(fs),
+ "Semantic": lambda: SemanticProcessor(
+ vlm_resolver=SimpleNamespace(get_vlm=AsyncMock())
+ ),
+ }
+ processor = processors[queue_name]()
+
+ if queue_name == "Reindex":
+
+ async def acquire(msg, ctx):
+ if blocked:
+ raise HandoffRecoveryBlocked("another owner holds coverage")
+ return await agfs.pathlock_acquire_exact(OUTPUT)
+
+ async def execute(_executor, *, lease_guard, **kwargs):
+ await write_business_result(agfs, lease_guard.lease)
+ return {"output": OUTPUT}
+
+ monkeypatch.setattr(processor, "_adopt_or_reacquire", acquire)
+ monkeypatch.setattr(ReindexExecutor, "_run", execute)
+ queue.set_dequeue_handler(processor)
+ else:
+
+ class Handler(DequeueHandlerBase):
+ async def on_dequeue(self, data):
+ msg = message_type.from_dict(json.loads(data["data"]))
+ if blocked:
+ error = HandoffRecoveryBlocked("another owner holds coverage")
+ if queue_name == "Semantic":
+ work_type = (
+ SkillSemanticMessageWork
+ if consumer == "SemanticSkill"
+ else SemanticMessageWork
+ )
+ work = work_type(processor, msg, caller_lock=None)
+ return await processor._requeue_semantic_msg_after_error(
+ msg, error, work=work
+ )
+ assert await processor._requeue_lock_handoff(msg, error)
+ return ProcessResult.requeued()
+ lease = await agfs.pathlock_acquire_exact(OUTPUT)
+ try:
+ await write_business_result(agfs, lease)
+ finally:
+ await agfs.pathlock_release(lease)
+ await tracker.complete("task", {"output": OUTPUT}, **OWNER)
+ return ProcessResult.success()
+
+ queue.set_dequeue_handler(Handler())
+ return agfs, tracker, manager, queue
+
+ try:
+ agfs, tracker, manager, queue = open_runtime()
+ await agfs.ensure_parent_dirs(OUTPUT, fs_ctx={"account_id": OWNER["account_id"]})
+ await tracker.create(
+ "reindex" if queue_name == "Reindex" else "add_resource", task_id="task", **OWNER
+ )
+ await tracker.start("task", **OWNER)
+ with bind_task_context("task", **OWNER):
+ await queue.enqueue(initial if queue_name == "Semantic" else initial.to_dict())
+ original = (await queue.snapshot())[0]
+ metadata = extract_task_metadata(original)
+
+ # Fault only the queue transport after registration, never the real
+ # middleware or any retry method. No replacement reaches SQLite.
+ original_write = queue._async_agfs.write
+ attempted = []
+
+ async def fail_enqueue(path, data, *args, **kwargs):
+ if path.endswith("/enqueue"):
+ attempted.append(json.loads(data))
+ raise OSError("replacement enqueue failed")
+ return await original_write(path, data, *args, **kwargs)
+
+ monkeypatch.setattr(queue._async_agfs, "write", fail_enqueue)
+ await queue.dequeue()
+ assert len(attempted) == 1
+ assert attempted[0]["_task_work_id"] == metadata.work_id
+ assert attempted[0]["lock_handoff_retry"] == 1
+ assert await tracker.get_work_state("task", metadata.work_id, **OWNER) is WorkState.RUNNING
+ assert (await tracker.get("task", **OWNER)).status is TaskStatus.RUNNING
+ assert await queue.snapshot() == [original]
+ status = await queue.get_status()
+ assert (status.pending, status.in_progress) == (0, 1)
+ assert executed == []
+ await agfs.run("close")
+ clients.remove(manager._agfs)
+
+ # Drop the original tracker, middleware, queue and native client.
+ # RecoverStale and the production snapshot bootstrap resume the work.
+ agfs, tracker, manager, queue = open_runtime()
+ assert (await tracker.get("task", **OWNER)).status is TaskStatus.RUNNING
+ status = await queue.get_status()
+ assert (status.pending, status.in_progress) == (1, 0)
+ await manager.prepare_task_tracking(tracker)
+ assert await tracker.get_work_state("task", metadata.work_id, **OWNER) is WorkState.PENDING
+
+ # Coverage is still blocked: the recovered original now successfully
+ # publishes its replacement and is ACKed, keeping the same logical work.
+ await queue.dequeue()
+ replacement = (await queue.snapshot())[0]
+ assert replacement["id"] != original["id"]
+ assert extract_task_metadata(replacement).work_id == metadata.work_id
+ assert json.loads(replacement["data"])["lock_handoff_retry"] == 1
+ assert await tracker.get_work_state("task", metadata.work_id, **OWNER) is WorkState.PENDING
+
+ blocked = False
+ await queue.dequeue()
+ assert executed == [OUTPUT]
+ assert await queue.snapshot() == []
+ assert await agfs.read(OUTPUT) == b"business executed"
+ assert await tracker.get_work_state("task", metadata.work_id, **OWNER) is WorkState.DONE
+ assert (await tracker.get("task", **OWNER)).status is TaskStatus.COMPLETED
+ # A duplicate original cannot execute the business body twice.
+ await queue.process_dequeued(original)
+ assert executed == [OUTPUT]
+ lease = await agfs.pathlock_acquire_exact(OUTPUT)
+ await agfs.pathlock_release(lease)
+ await agfs.run("close")
+ clients.remove(manager._agfs)
+
+ agfs, tracker, manager, queue = open_runtime()
+ assert await queue.snapshot() == []
+ assert (await tracker.get("task", **OWNER)).status is TaskStatus.COMPLETED
+ assert await agfs.read(OUTPUT) == b"business executed"
+ finally:
+ for client in clients:
+ await AsyncAGFSClient(client).run("close")
diff --git a/tests/agfs/test_pathlock_provider_migration.py b/tests/agfs/test_pathlock_provider_migration.py
new file mode 100644
index 000000000..6998f8263
--- /dev/null
+++ b/tests/agfs/test_pathlock_provider_migration.py
@@ -0,0 +1,648 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Single-instance restart with persisted filesystem handoffs and real Redis."""
+
+import asyncio
+import json
+import os
+import subprocess
+import sys
+import threading
+import time
+import uuid
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from openviking.pyagfs.async_client import AsyncAGFSClient
+from openviking.service import task_tracker as tracker_module
+from openviking.service.reindex_executor import ReindexExecutor
+from openviking.service.task_domain import TaskStatus, WorkState
+from openviking.service.task_store import PersistentTaskStore
+from openviking.service.task_tracker import TaskTracker
+from openviking.service.task_work_index import extract_task_metadata, get_task_context
+from openviking.storage.errors import (
+ HandoffRecoveryBlocked,
+ HandoffRecoveryRequired,
+ LockAcquisitionError,
+)
+from openviking.storage.pathlock_recovery import adopt_or_reacquire
+from openviking.storage.queuefs import queue_manager as manager_module
+from openviking.storage.queuefs.queue_manager import QueueManager
+from openviking.storage.queuefs.reindex_processor import ReindexProcessor
+from openviking.storage.viking_fs import VikingFS
+from openviking.utils.agfs_utils import RagfsBindingConfig, create_agfs_client
+from openviking_cli.utils.config.agfs_config import AGFSConfig
+from openviking_cli.utils.config.cache_config import CacheConfig
+
+
[email protected]("historic", [False, True])
+async def test_filesystem_process_exit_then_immediate_redis_recovery(tmp_path, historic):
+ redis_url = os.environ.get("REDIS_URL")
+ if not redis_url:
+ pytest.skip("REDIS_URL required for filesystem → Redis migration integration")
+ started = time.monotonic()
+ # The producer is a separate process; no old heartbeat or writer survives.
+ source = """
+import json, sys
+from pathlib import Path
+from openviking.utils.agfs_utils import RagfsBindingConfig, create_agfs_client
+from openviking_cli.utils.config.agfs_config import AGFSConfig
+client = create_agfs_client(RagfsBindingConfig(agfs=AGFSConfig(path=sys.argv[1], backend="local")))
+ctx = {"account_id": "migration"}
+requests = [
+ {"path": "/local/migration/resources/tree", "kind": "tree"},
+ {"path": "/local/migration/resources/信贷.md", "kind": "exact"},
+]
+client.ensure_parent_dirs("/local/migration/resources/tree/a.md", ctx=ctx)
+client.write("/local/migration/resources/信贷.md", b"before", ctx=ctx)
+lease = client.pathlock_acquire_batch(ctx, requests, 0.0, None)
+handoff = client.pathlock_to_handoff(ctx, lease)
+client.pathlock_handoff(ctx, lease)
+Path(sys.argv[2]).write_text(json.dumps(handoff))
+"""
+ handoff_file = tmp_path / "handoff.json"
+ completed = subprocess.run(
+ [sys.executable, "-c", source, str(tmp_path), str(handoff_file)],
+ cwd=Path(__file__).resolve().parents[2],
+ capture_output=True,
+ text=True,
+ timeout=20,
+ )
+ assert completed.returncode == 0, completed.stderr
+ handoff = json.loads(handoff_file.read_text())
+ assert handoff["handle_mode"] == "lock_path"
+ coverage = handoff["covered_paths"]
+ old_files = {p: p.read_bytes() for p in (tmp_path / "viking").rglob(".exact.ovlock.*")}
+ assert len(old_files) == 2
+ if historic:
+ handoff.pop("handle_mode")
+ handoff.pop("covered_paths")
+ handoff["handle_id"] = handoff.pop("owner_id")
+ handoff.pop("lease_ref")
+ config = RagfsBindingConfig(
+ agfs=AGFSConfig(path=str(tmp_path), backend="local", pathlock={"provider": "cache"}),
+ cache=CacheConfig(
+ provider="redis",
+ params={"endpoints": [redis_url], "command_timeout_ms": 1000},
+ ),
+ service_name=f"migration-{uuid.uuid4().hex}",
+ )
+ agfs = AsyncAGFSClient(create_agfs_client(config))
+ ctx = SimpleNamespace(account_id="migration")
+ with pytest.raises(HandoffRecoveryRequired) as raised:
+ await agfs.pathlock_adopt(handoff, fs_ctx={"account_id": "migration"})
+ assert raised.value.reason == "provider_changed"
+
+ async def operation_requests():
+ return coverage
+
+ lease = await adopt_or_reacquire(agfs, handoff, ctx=ctx, fallback_requests=operation_requests)
+ try:
+ assert lease["owner_id"] != handoff.get("owner_id", handoff.get("handle_id"))
+ recovered = await agfs.pathlock_to_handoff(lease)
+ assert recovered["covered_paths"] == coverage
+ assert recovered["handle_mode"] == "logical_path"
+ assert all(p.read_bytes() == data for p, data in old_files.items())
+ with pytest.raises(LockAcquisitionError):
+ await agfs.pathlock_acquire_exact("/local/migration/resources/tree/child.md")
+ with pytest.raises(LockAcquisitionError):
+ await agfs.pathlock_acquire_exact("/local/migration/resources/信贷.md")
+ await agfs.write(
+ "/local/migration/resources/tree/child.md",
+ b"replayed",
+ fs_ctx={"account_id": "migration", "lease_ref": lease["lease_ref"]},
+ )
+ finally:
+ await agfs.pathlock_release(lease)
+ next_lease = await agfs.pathlock_acquire_exact("/local/migration/resources/tree/child.md")
+ await agfs.pathlock_release(next_lease)
+ # Demonstrate recovery before the old 30-second lease expires.
+ assert time.monotonic() - started < 30
+
+
+_BACKLOG_PRODUCER = """
+import asyncio, json, sys, time
+from pathlib import Path
+from openviking.pyagfs.async_client import AsyncAGFSClient
+from openviking.service.task_store import PersistentTaskStore
+from openviking.service.task_tracker import TaskTracker, set_task_tracker
+from openviking.service.task_work_index import bind_task_context
+from openviking.storage.pathlock_transfer import PathLockGuard
+from openviking.storage.queuefs.queue_manager import QueueManager
+from openviking.storage.queuefs.reindex_msg import ReindexMsg
+from openviking.utils.agfs_utils import RagfsBindingConfig, create_agfs_client
+from openviking_cli.utils.config.agfs_config import AGFSConfig
+
+async def main():
+ client = create_agfs_client(RagfsBindingConfig(agfs=AGFSConfig(
+ path=sys.argv[1], backend="local",
+ queuefs={"backend": "sqlite", "recover_stale_sec": 0},
+ )))
+ agfs = AsyncAGFSClient(client)
+ tracker = TaskTracker(PersistentTaskStore(client))
+ set_task_tracker(tracker)
+ manager = QueueManager(client)
+ queue = manager.get_queue(manager.REINDEX, allow_create=True)
+ ctx = {"account_id": "migration"}
+ await agfs.ensure_parent_dirs("/local/migration/resources/tree/input.md", fs_ctx=ctx)
+ await agfs.write("/local/migration/resources/tree/input.md", b"input", fs_ctx=ctx)
+ await agfs.write("/local/migration/resources/信贷.md", b"before", fs_ctx=ctx)
+ expected = []
+ contended = len(sys.argv) > 5 and sys.argv[5] == "contended"
+ if contended:
+ await agfs.write("/local/migration/resources/tree/contended.md", b"", fs_ctx=ctx)
+ targets = [("tree", "tree"), ("tree", "tree")] if contended else [
+ ("tree", "tree"), ("信贷.md", "exact")]
+ for suffix, kind in targets:
+ path = "/local/migration/resources/" + suffix
+ uri = "viking://resources/" + suffix
+ task = await tracker.create("reindex", resource_id=uri,
+ account_id="migration", user_id="tester")
+ if not contended or not expected:
+ guard = PathLockGuard(agfs)
+ await guard.acquire(lambda: agfs.pathlock_acquire_batch(
+ [{"path": path, "kind": kind}], fs_ctx=ctx))
+ acquired_at = time.monotonic()
+ handoff = await guard.to_handoff()
+ old_owner = handoff["owner_id"]
+ old_lease_ref = handoff["lease_ref"]
+ if sys.argv[3] == "historic":
+ handoff.pop("handle_mode")
+ handoff.pop("covered_paths")
+ handoff["handle_id"] = handoff.pop("owner_id")
+ handoff.pop("lease_ref")
+ msg = ReindexMsg(task_id=task.task_id, uri=uri, object_type="resources",
+ mode="semantic", account_id="migration",
+ user_id="tester", role="root", lock_handoff=handoff,
+ lock_handoff_retry=int(sys.argv[6]) if len(sys.argv) > 6 else 0)
+ with bind_task_context(task.task_id, "migration", "tester"):
+ if contended and expected:
+ receipt = await queue.enqueue(msg.to_dict())
+ else:
+ receipt = await guard.handoff_and_dispatch(
+ handoff, lambda: queue.enqueue(msg.to_dict()))
+ assert guard.transferred and guard.lease is None
+ expected.append({"task_id": task.task_id, "work_id": receipt.work_id,
+ "uri": uri, "path": path,
+ "kind": kind, "old_owner": old_owner,
+ "old_lease_ref": old_lease_ref, "acquired_at": acquired_at})
+ # Binding write returns a byte-count description, so obtain backend delivery
+ # IDs from the durable snapshot rather than treating the receipt as an ID.
+ deliveries = await queue.snapshot()
+ for delivery in deliveries:
+ payload = delivery["data"]
+ if isinstance(payload, str):
+ payload = json.loads(payload)
+ item = next(item for item in expected if item["task_id"] == payload["task_id"])
+ item["message_id"] = delivery["id"]
+ if sys.argv[4] == "interrupted":
+ delivery = await queue.dequeue_raw()
+ assert delivery["id"] == expected[0]["message_id"]
+ status = await queue.get_status()
+ assert status.pending == (1 if sys.argv[4] == "interrupted" else 2)
+ assert status.in_progress == (1 if sys.argv[4] == "interrupted" else 0)
+ assert len(await queue.snapshot()) == 2
+ Path(sys.argv[2]).write_text(json.dumps(expected))
+ # Exit without ACK, lock release, queue clearing, or waiting for lease expiry.
+
+asyncio.run(main())
+"""
+
+
[email protected]("historic", [False, True], ids=["current", "historic"])
[email protected]("interrupted", [False, True], ids=["pending", "unacked"])
+async def test_sqlite_backlog_migrates_to_redis_and_is_consumed(
+ tmp_path, monkeypatch, historic, interrupted
+):
+ """Real QueueFS restart, worker, Task/Work recovery, ACK and durable completion.
+
+ Only the model-dependent executor body is replaced by a protected AGFS write.
+ Queue middleware, ReindexProcessor, lock recovery and worker dispatch are real.
+ """
+ redis_url = os.environ.get("REDIS_URL")
+ if not redis_url:
+ pytest.skip("REDIS_URL required for filesystem → Redis migration integration")
+ manifest = tmp_path / "expected.json"
+ producer = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ _BACKLOG_PRODUCER,
+ str(tmp_path),
+ str(manifest),
+ "historic" if historic else "current",
+ "interrupted" if interrupted else "pending",
+ ],
+ cwd=Path(__file__).resolve().parents[2],
+ capture_output=True,
+ text=True,
+ timeout=20,
+ )
+ assert producer.returncode == 0, producer.stderr
+ expected = json.loads(manifest.read_text())
+ by_uri = {item["uri"]: item for item in expected}
+ old_files = {p: p.read_bytes() for p in (tmp_path / "viking").rglob(".exact.ovlock.*")}
+ assert len(old_files) == 2
+ # The previous writer has exited. Bootstrap against the same SQLite database,
+ # immediately switching only the lock provider to Redis.
+ config = RagfsBindingConfig(
+ agfs=AGFSConfig(
+ path=str(tmp_path),
+ backend="local",
+ queuefs={"backend": "sqlite", "recover_stale_sec": 0},
+ pathlock={"provider": "cache"},
+ ),
+ cache=CacheConfig(
+ provider="redis",
+ params={"endpoints": [redis_url], "command_timeout_ms": 1000},
+ ),
+ service_name=f"backlog-migration-{uuid.uuid4().hex}",
+ )
+ client = create_agfs_client(config)
+ agfs = AsyncAGFSClient(client)
+ fs = VikingFS(client)
+ tracker = TaskTracker(PersistentTaskStore(client))
+ manager = QueueManager(client)
+ monkeypatch.setattr(tracker_module, "_instance", tracker)
+ monkeypatch.setattr(manager_module, "_instance", manager)
+ queue = manager.get_queue(
+ manager.REINDEX, dequeue_handler=ReindexProcessor(fs), allow_create=True
+ )
+ executed = []
+
+ async def protected_executor(self, *, uri, ctx, lease_guard, **kwargs):
+ item = by_uri[uri]
+ task_ctx = get_task_context()
+ assert task_ctx.task_id == item["task_id"]
+ assert task_ctx.work_id == item["work_id"]
+ assert ctx.account_id == "migration" and ctx.user.user_id == "tester"
+ assert (
+ await tracker.get_work_state(
+ item["task_id"], item["work_id"], account_id="migration", user_id="tester"
+ )
+ is WorkState.RUNNING
+ )
+ lease = lease_guard.lease
+ assert time.monotonic() - item["acquired_at"] < 30
+ assert lease["owner_id"] != item["old_owner"]
+ assert lease["lease_ref"] != item["old_lease_ref"]
+ handoff = await agfs.pathlock_to_handoff(lease)
+ assert handoff["handle_mode"] == "logical_path"
+ assert handoff["covered_paths"] == [{"path": item["path"], "kind": item["kind"]}]
+ output = item["path"] + "/consumed.md" if item["kind"] == "tree" else item["path"]
+ with pytest.raises(LockAcquisitionError):
+ await agfs.pathlock_acquire_exact(output)
+ await agfs.write(
+ output,
+ item["task_id"].encode(),
+ fs_ctx={"account_id": ctx.account_id, "lease_ref": lease["lease_ref"]},
+ )
+ executed.append(uri)
+ return {"uri": uri, "output": output}
+
+ monkeypatch.setattr(ReindexExecutor, "_run", protected_executor)
+ try:
+ status = await queue.get_status()
+ assert (status.pending, status.in_progress) == (2, 0)
+ messages = await queue.snapshot()
+ assert {message["id"] for message in messages} == {item["message_id"] for item in expected}
+ metadata = [extract_task_metadata(message) for message in messages]
+ assert {entry.work_id for entry in metadata} == {item["work_id"] for item in expected}
+ for item in expected:
+ assert (
+ await tracker.get_work_state(
+ item["task_id"], item["work_id"], account_id="migration", user_id="tester"
+ )
+ is None
+ )
+ restored = await manager.prepare_task_tracking(tracker)
+ assert {task.task_id for task in restored} == {item["task_id"] for item in expected}
+ for item in expected:
+ assert (
+ await tracker.get_work_state(
+ item["task_id"], item["work_id"], account_id="migration", user_id="tester"
+ )
+ is WorkState.PENDING
+ )
+ # Run the actual concurrent QueueManager worker rather than calling the
+ # recovery helper or processor directly.
+ manager.start()
+ async with asyncio.timeout(10):
+ while not (await queue.get_status()).is_complete:
+ await asyncio.sleep(0.05)
+ await asyncio.to_thread(manager.stop)
+ status = await queue.get_status()
+ assert status.processed == 2
+ assert status.error_count == status.requeue_count == 0, status.errors
+ assert sorted(executed) == sorted(by_uri)
+ assert await queue.snapshot() == []
+ assert all(p.read_bytes() == data for p, data in old_files.items())
+ for item in expected:
+ task = await tracker.get(item["task_id"], account_id="migration", user_id="tester")
+ assert task.status is TaskStatus.COMPLETED
+ assert task.result["uri"] == item["uri"]
+ assert await agfs.read(task.result["output"]) == item["task_id"].encode()
+ assert (
+ await tracker.get_work_state(
+ item["task_id"], item["work_id"], account_id="migration", user_id="tester"
+ )
+ is WorkState.DONE
+ )
+ # Releasing the recovered Tree/Exact lease allows the next writer.
+ lease = await agfs.pathlock_acquire_exact(task.result["output"])
+ await agfs.pathlock_release(lease)
+ finally:
+ await asyncio.to_thread(manager.stop)
+ await agfs.run("close")
+
+ # Reopen persistent storage to rule out merely clearing an in-memory queue
+ # or projecting task completion from the consumer's process-local cache.
+ reopened = create_agfs_client(config)
+ reopened_agfs = AsyncAGFSClient(reopened)
+ try:
+ restarted_queue = QueueManager(reopened).get_queue(QueueManager.REINDEX, allow_create=True)
+ assert await restarted_queue.snapshot() == []
+ assert (await restarted_queue.get_status()).is_complete
+ restarted_tracker = TaskTracker(PersistentTaskStore(reopened))
+ for item in expected:
+ task = await restarted_tracker.get(
+ item["task_id"], account_id="migration", user_id="tester"
+ )
+ assert task.status is TaskStatus.COMPLETED
+ assert await reopened_agfs.read(task.result["output"]) == item["task_id"].encode()
+ finally:
+ await reopened_agfs.run("close")
+
+
[email protected]("historic", [False, True], ids=["current", "historic"])
+async def test_two_queue_managers_recover_same_backlog_coverage(tmp_path, monkeypatch, historic):
+ """Two native clients compete for one old handoff using real SQLite/Redis.
+
+ Synchronization only forces the race and holds the winning write until the
+ losing consumer reports a real recovery conflict. No lock result is mocked.
+ """
+ redis_url = os.environ.get("REDIS_URL")
+ if not redis_url:
+ pytest.skip("REDIS_URL required for filesystem → Redis migration integration")
+ manifest = tmp_path / "contended.json"
+ producer = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ _BACKLOG_PRODUCER,
+ str(tmp_path),
+ str(manifest),
+ "historic" if historic else "current",
+ "pending",
+ "contended",
+ ],
+ cwd=Path(__file__).resolve().parents[2],
+ capture_output=True,
+ text=True,
+ timeout=20,
+ )
+ assert producer.returncode == 0, producer.stderr
+ expected = json.loads(manifest.read_text())
+ by_task = {item["task_id"]: item for item in expected}
+ assert len(by_task) == 2
+ assert len({item["old_owner"] for item in expected}) == 1
+ old_files = {p: p.read_bytes() for p in (tmp_path / "viking").rglob(".exact.ovlock.*")}
+ assert len(old_files) == 1
+ config = RagfsBindingConfig(
+ agfs=AGFSConfig(
+ path=str(tmp_path),
+ backend="local",
+ queuefs={"backend": "sqlite", "recover_stale_sec": 0},
+ pathlock={"provider": "cache"},
+ ),
+ cache=CacheConfig(
+ provider="redis",
+ params={"endpoints": [redis_url], "command_timeout_ms": 1000},
+ ),
+ service_name=f"contended-migration-{uuid.uuid4().hex}",
+ )
+ # Open both backends before processing: SQLite startup recovery must not
+ # reclaim a delivery that the other consumer has already started.
+ clients = [create_agfs_client(config) for _ in range(2)]
+ filesystems = [VikingFS(client) for client in clients]
+ managers = [QueueManager(client, max_concurrent_reindex=1) for client in clients]
+ tracker = TaskTracker(PersistentTaskStore(clients[0]))
+ monkeypatch.setattr(tracker_module, "_instance", tracker)
+ monkeypatch.setattr(manager_module, "_instance", managers[0])
+ queues = []
+ barrier = threading.Barrier(2)
+ conflict_seen, entered, finish = threading.Event(), threading.Event(), threading.Event()
+ state_lock = threading.Lock()
+ adoptions = 0
+ active = 0
+ executed = []
+ conflicts = []
+ original_requeue = ReindexProcessor._requeue_lock_handoff
+
+ async def record_conflict(self, msg, exc):
+ if isinstance(exc, HandoffRecoveryBlocked):
+ with state_lock:
+ conflicts.append(msg.task_id)
+ conflict_seen.set()
+ return await original_requeue(self, msg, exc)
+
+ monkeypatch.setattr(ReindexProcessor, "_requeue_lock_handoff", record_conflict)
+ for fs, manager in zip(filesystems, managers, strict=True):
+ original_adopt = fs._async_agfs.pathlock_adopt
+
+ async def simultaneous_adopt(*args, original=original_adopt, **kwargs):
+ nonlocal adoptions
+ with state_lock:
+ adoptions += 1
+ synchronize = adoptions <= 2
+ if synchronize:
+ await asyncio.to_thread(barrier.wait, 5)
+ return await original(*args, **kwargs)
+
+ monkeypatch.setattr(fs._async_agfs, "pathlock_adopt", simultaneous_adopt)
+ queues.append(
+ manager.get_queue(
+ manager.REINDEX, dequeue_handler=ReindexProcessor(fs), allow_create=True
+ )
+ )
+
+ async def protected_executor(self, *, uri, ctx, lease_guard, **kwargs):
+ nonlocal active
+ task_id = get_task_context().task_id
+ item = by_task[task_id]
+ lease = lease_guard.lease
+ agfs = lease_guard._agfs
+ assert lease["owner_id"] != item["old_owner"]
+ assert lease["lease_ref"] != item["old_lease_ref"]
+ handoff = await agfs.pathlock_to_handoff(lease)
+ assert handoff["covered_paths"] == [{"path": item["path"], "kind": "tree"}]
+ output = item["path"] + "/contended.md"
+ with state_lock:
+ active += 1
+ assert active == 1, "two consumers entered the protected write"
+ try:
+ entered.set()
+ assert await asyncio.to_thread(finish.wait, 5), "winning write was never released"
+ with pytest.raises(LockAcquisitionError):
+ await filesystems[0]._async_agfs.pathlock_acquire_exact(output)
+ previous = await agfs.read(output)
+ await agfs.write(
+ output,
+ previous + task_id.encode() + b"\n",
+ fs_ctx={"account_id": ctx.account_id, "lease_ref": lease["lease_ref"]},
+ )
+ with state_lock:
+ executed.append((task_id, lease["owner_id"]))
+ return {"uri": uri, "output": output}
+ finally:
+ with state_lock:
+ active -= 1
+
+ monkeypatch.setattr(ReindexExecutor, "_run", protected_executor)
+ try:
+ await managers[0].prepare_task_tracking(tracker)
+ for manager in managers:
+ manager.start()
+ assert await asyncio.to_thread(entered.wait, 5), "neither consumer acquired recovery lock"
+ assert await asyncio.to_thread(conflict_seen.wait, 5), (
+ "no real recovery contention observed"
+ )
+ assert len(executed) == 0
+ finish.set()
+ async with asyncio.timeout(10):
+ while not (await queues[0].get_status()).is_complete:
+ await asyncio.sleep(0.05)
+ for manager in managers:
+ await asyncio.to_thread(manager.stop)
+ assert len(conflicts) == 1
+ assert {task_id for task_id, _ in executed} == set(by_task)
+ assert len({owner for _, owner in executed}) == 2
+ assert active == 0
+ statuses = [await queue.get_status() for queue in queues]
+ assert sum(status.requeue_count for status in statuses) == 1
+ assert sum(status.error_count for status in statuses) == 0
+ assert await queues[0].snapshot() == []
+ assert all(p.read_bytes() == data for p, data in old_files.items())
+ for item in expected:
+ task = await tracker.get(item["task_id"], account_id="migration", user_id="tester")
+ assert task.status is TaskStatus.COMPLETED
+ assert (
+ await tracker.get_work_state(
+ item["task_id"], item["work_id"], account_id="migration", user_id="tester"
+ )
+ is WorkState.DONE
+ )
+ agfs = filesystems[0]._async_agfs
+ output = expected[0]["path"] + "/contended.md"
+ assert set((await agfs.read(output)).decode().splitlines()) == set(by_task)
+ lease = await agfs.pathlock_acquire_tree(expected[0]["path"])
+ await agfs.pathlock_release(lease)
+ finally:
+ finish.set()
+ for manager in managers:
+ await asyncio.to_thread(manager.stop)
+ for fs in filesystems:
+ await fs._async_agfs.run("close")
+ reopened = create_agfs_client(config)
+ agfs = AsyncAGFSClient(reopened)
+ try:
+ assert set((await agfs.read(output)).decode().splitlines()) == set(by_task)
+ assert (
+ await QueueManager(reopened)
+ .get_queue(QueueManager.REINDEX, allow_create=True)
+ .snapshot()
+ == []
+ )
+ finally:
+ await agfs.run("close")
+
+
+async def test_recovery_retry_exhaustion_fails_task_and_drains_queue(tmp_path, monkeypatch):
+ """A competing Redis owner survives; exhausted backlog is failed and ACKed."""
+ redis_url = os.environ.get("REDIS_URL")
+ if not redis_url:
+ pytest.skip("REDIS_URL required for filesystem → Redis migration integration")
+ manifest = tmp_path / "exhausted.json"
+ producer = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ _BACKLOG_PRODUCER,
+ str(tmp_path),
+ str(manifest),
+ "current",
+ "pending",
+ "contended",
+ "8",
+ ],
+ cwd=Path(__file__).resolve().parents[2],
+ capture_output=True,
+ text=True,
+ timeout=20,
+ )
+ assert producer.returncode == 0, producer.stderr
+ expected = json.loads(manifest.read_text())
+ client = create_agfs_client(
+ RagfsBindingConfig(
+ agfs=AGFSConfig(
+ path=str(tmp_path),
+ backend="local",
+ queuefs={"backend": "sqlite", "recover_stale_sec": 0},
+ pathlock={"provider": "cache"},
+ ),
+ cache=CacheConfig(
+ provider="redis",
+ params={"endpoints": [redis_url], "command_timeout_ms": 1000},
+ ),
+ service_name=f"exhausted-migration-{uuid.uuid4().hex}",
+ )
+ )
+ fs = VikingFS(client)
+ agfs = fs._async_agfs
+ tracker = TaskTracker(PersistentTaskStore(client))
+ manager = QueueManager(client)
+ monkeypatch.setattr(tracker_module, "_instance", tracker)
+ monkeypatch.setattr(manager_module, "_instance", manager)
+ queue = manager.get_queue(
+ manager.REINDEX, dequeue_handler=ReindexProcessor(fs), allow_create=True
+ )
+
+ async def forbidden_executor(*args, **kwargs):
+ raise AssertionError("exhausted recovery must not execute business writes")
+
+ monkeypatch.setattr(ReindexExecutor, "_run", forbidden_executor)
+ competing = await agfs.pathlock_acquire_tree(expected[0]["path"])
+ try:
+ await manager.prepare_task_tracking(tracker)
+ manager.start()
+ async with asyncio.timeout(10):
+ while not (await queue.get_status()).is_complete:
+ await asyncio.sleep(0.05)
+ await asyncio.to_thread(manager.stop)
+ status = await queue.get_status()
+ assert status.error_count == 2
+ assert status.requeue_count == 0
+ assert await queue.snapshot() == []
+ assert await agfs.read(expected[0]["path"] + "/contended.md") == b""
+ for item in expected:
+ task = await tracker.get(item["task_id"], account_id="migration", user_id="tester")
+ assert task.status is TaskStatus.FAILED
+ assert (
+ await tracker.get_work_state(
+ item["task_id"], item["work_id"], account_id="migration", user_id="tester"
+ )
+ is WorkState.FAILED
+ )
+ # Exhaustion must never release the unrelated competing writer's lease.
+ with pytest.raises(LockAcquisitionError):
+ await agfs.pathlock_acquire_exact(expected[0]["path"] + "/child.md")
+ finally:
+ await asyncio.to_thread(manager.stop)
+ await agfs.pathlock_release(competing)
+ await agfs.run("close")
diff --git a/tests/metrics/collectors/test_pathlock_recovery_metrics.py b/tests/metrics/collectors/test_pathlock_recovery_metrics.py
new file mode 100644
index 000000000..0dd518d8e
--- /dev/null
+++ b/tests/metrics/collectors/test_pathlock_recovery_metrics.py
@@ -0,0 +1,44 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Recovery retry events reach the exporter with bounded labels."""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from openviking.metrics.global_api import _build_event_router
+from openviking.observability.events import (
+ make_payload_subscriber,
+ register_event_subscriber,
+ unregister_event_subscriber,
+)
+from openviking.storage.errors import HandoffRecoveryBlocked
+from openviking.storage.pathlock_recovery import prepare_handoff_retry
+
+
+async def test_blocked_retry_and_exhaustion_export_alarm_counter(
+ registry, render_prometheus, monkeypatch
+):
+ router = _build_event_router(registry)
+ register_event_subscriber("test-pathlock", make_payload_subscriber(router.dispatch))
+ monkeypatch.setattr("openviking.storage.pathlock_recovery.sleep", AsyncMock())
+ try:
+ for retry in [0, 8]:
+ msg = SimpleNamespace(
+ task_id="sensitive-task", lock_handoff_retry=retry, to_dict=lambda: {}
+ )
+ await prepare_handoff_retry(msg, HandoffRecoveryBlocked("busy"), queue="Reindex")
+ router.dispatch("pathlock.recovery_blocked", {"queue": "arbitrary", "outcome": "retry"})
+ text = render_prometheus(registry)
+ assert (
+ 'openviking_pathlock_recovery_blocked_total{outcome="retry",queue="Reindex"} 1' in text
+ )
+ assert (
+ 'openviking_pathlock_recovery_blocked_total{outcome="exhausted",queue="Reindex"} 1'
+ in text
+ )
+ assert "sensitive-task" not in text and "arbitrary" not in text
+ finally:
+ unregister_event_subscriber("test-pathlock")
diff --git a/tests/service/test_task_queue_middleware.py b/tests/service/test_task_queue_middleware.py
index f41c51bfc..41434abca 100644
--- a/tests/service/test_task_queue_middleware.py
+++ b/tests/service/test_task_queue_middleware.py
@@ -167,6 +167,39 @@ async def test_enqueue_failure_records_failed_work(tracked_queue):
assert task.error == "write failed"
[email protected]("state", [WorkState.PENDING, WorkState.RUNNING])
[email protected]("failure", [OSError("write failed"), asyncio.CancelledError()])
+async def test_failed_replacement_enqueue_preserves_existing_work(tracked_queue, state, failure):
+ queue, tracker, transport = tracked_queue
+ message = await enqueue_task(queue, tracker, transport)
+ metadata = extract_task_metadata(message)
+ if state is WorkState.RUNNING:
+ await tracker.start_work("task-1", metadata.work_id, **OWNER)
+ transport.write.side_effect = failure
+ enqueued_work = []
+
+ with (
+ bind_task_context("task-1", "account", "user", enqueued_work=enqueued_work),
+ pytest.raises(type(failure)),
+ ):
+ await queue.enqueue(json.loads(message["data"]))
+
+ assert await tracker.get_work_state("task-1", metadata.work_id, **OWNER) is state
+ assert (await tracker.get("task-1", **OWNER)).status is TaskStatus.RUNNING
+ assert enqueued_work == []
+
+ class Handler(DequeueHandlerBase):
+ async def on_dequeue(self, data):
+ await tracker.complete("task-1", {"recovered": True}, **OWNER)
+ return ProcessResult.success({"recovered": True})
+
+ queue.set_dequeue_handler(Handler())
+ result = await queue.process_dequeued(message)
+ assert result.value == {"recovered": True}
+ assert await tracker.get_work_state("task-1", metadata.work_id, **OWNER) is WorkState.DONE
+ assert (await tracker.get("task-1", **OWNER)).status is TaskStatus.COMPLETED
+
+
async def test_cancelled_enqueue_discards_uncommitted_work(tracked_queue):
queue, tracker, transport = tracked_queue
await create_task(tracker)
diff --git a/tests/storage/test_pathlock_recovery.py b/tests/storage/test_pathlock_recovery.py
new file mode 100644
index 000000000..dede5857b
--- /dev/null
+++ b/tests/storage/test_pathlock_recovery.py
@@ -0,0 +1,296 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from openviking.storage.errors import (
+ HandoffRecoveryBlocked,
+ HandoffRecoveryRequired,
+ InvalidPathLockRequestError,
+ LockAcquisitionError,
+)
+from openviking.storage.pathlock_recovery import (
+ HANDOFF_RECOVERY_MAX_RETRIES,
+ adopt_or_reacquire,
+ prepare_handoff_retry,
+)
+from openviking.storage.pathlock_transfer import PathLockGuard
+
+CTX = SimpleNamespace(account_id="tenant")
+TREE = {"path": "/local/tenant/resources/tree", "kind": "tree"}
+EXACT = {"path": "/local/tenant/resources/file.md", "kind": "exact"}
+
+
+def client(error=None):
+ return SimpleNamespace(
+ pathlock_adopt=AsyncMock(side_effect=error, return_value={"lease_ref": "adopted"}),
+ pathlock_acquire_batch=AsyncMock(return_value={"lease_ref": "fresh"}),
+ pathlock_release=AsyncMock(),
+ )
+
+
+async def test_migration_preserves_mixed_coverage_and_account():
+ agfs = client(HandoffRecoveryRequired("provider_changed"))
+ requests = [TREE, EXACT]
+ fallback = AsyncMock(return_value=requests)
+ result = await adopt_or_reacquire(
+ agfs,
+ {"owner_id": "old", "covered_paths": requests},
+ ctx=CTX,
+ fallback_requests=fallback,
+ )
+ assert result == {"lease_ref": "fresh"}
+ agfs.pathlock_acquire_batch.assert_awaited_once_with(requests, fs_ctx={"account_id": "tenant"})
+
+
+ "error",
+ [
+ InvalidPathLockRequestError("forged coverage"),
+ LockAcquisitionError("already adopted"),
+ LockAcquisitionError("invalidated"),
+ RuntimeError("Redis disconnected during adopt"),
+ ],
+)
+async def test_unrelated_adopt_errors_never_reacquire(error):
+ agfs = client(error)
+ with pytest.raises(type(error)) as raised:
+ await adopt_or_reacquire(agfs, {"covered_paths": [TREE]}, ctx=CTX)
+ assert raised.value is error
+ agfs.pathlock_acquire_batch.assert_not_awaited()
+
+
+async def test_historic_tree_handles_are_inverted_as_a_complete_batch():
+ agfs = client(HandoffRecoveryRequired("provider_changed"))
+ paths = [TREE["path"], "/local/tenant/resources/other"]
+ await adopt_or_reacquire(agfs, {"lock_paths": [p + "/.path.ovlock" for p in paths]}, ctx=CTX)
+ agfs.pathlock_acquire_batch.assert_awaited_once_with(
+ [{"path": p, "kind": "tree"} for p in paths], fs_ctx={"account_id": "tenant"}
+ )
+
+
+async def test_historic_mixed_handles_require_complete_operation_fallback():
+ agfs = client(HandoffRecoveryRequired("provider_changed"))
+ handoff = {
+ "lock_paths": [
+ TREE["path"] + "/.path.ovlock",
+ "/local/tenant/resources/.exact.ovlock.file.md.123",
+ ]
+ }
+ with pytest.raises(InvalidPathLockRequestError):
+ await adopt_or_reacquire(agfs, handoff, ctx=CTX)
+ agfs.pathlock_acquire_batch.assert_not_awaited()
+ await adopt_or_reacquire(
+ agfs, handoff, ctx=CTX, fallback_requests=AsyncMock(return_value=[TREE, EXACT])
+ )
+ agfs.pathlock_acquire_batch.assert_awaited_once_with(
+ [TREE, EXACT], fs_ctx={"account_id": "tenant"}
+ )
+
+
+ "coverage",
+ [
+ {"path": "/local/other/resources/tree", "kind": "tree"},
+ {"path": "/local/tenant/resources/../tree", "kind": "tree"},
+ {"path": "/local/tenant/resources/tree", "kind": "unknown"},
+ {"path": "/local/tenant/resources/tree", "kind": "exact"},
+ {"path": "/local/tenant/resources/.path.ovlock", "kind": "tree"},
+ {"path": "/local/tenant/resources/unrelated", "kind": "tree"},
+ ],
+)
+async def test_recovery_rejects_invalid_account_path_kind_or_operation(coverage):
+ agfs = client(HandoffRecoveryRequired("provider_changed"))
+ with pytest.raises(InvalidPathLockRequestError):
+ await adopt_or_reacquire(
+ agfs,
+ {"covered_paths": [coverage]},
+ ctx=CTX,
+ fallback_requests=AsyncMock(return_value=[TREE]),
+ )
+ agfs.pathlock_acquire_batch.assert_not_awaited()
+
+
+async def test_reacquire_conflict_retains_typed_retry_reason():
+ agfs = client(HandoffRecoveryRequired("token_unavailable"))
+ agfs.pathlock_acquire_batch.side_effect = LockAcquisitionError("new owner holds tree")
+ with pytest.raises(HandoffRecoveryBlocked):
+ await adopt_or_reacquire(agfs, {"covered_paths": [TREE]}, ctx=CTX)
+
+
+async def test_cancelled_recovery_records_and_releases_fresh_lease():
+ started, finish = asyncio.Event(), asyncio.Event()
+ agfs = client(HandoffRecoveryRequired("provider_changed"))
+
+ async def acquire(*args, **kwargs):
+ started.set()
+ await finish.wait()
+ return {"lease_ref": "fresh"}
+
+ agfs.pathlock_acquire_batch.side_effect = acquire
+ guard = PathLockGuard(agfs)
+ task = asyncio.create_task(
+ guard.acquire(lambda: adopt_or_reacquire(agfs, {"covered_paths": [TREE]}, ctx=CTX))
+ )
+ await started.wait()
+ task.cancel()
+ finish.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert guard.lease == {"lease_ref": "fresh"}
+ await guard.close()
+ agfs.pathlock_release.assert_awaited_once_with({"lease_ref": "fresh"})
+
+
[email protected]("processor_name", ["AddResource", "Reindex", "ContentWrite"])
[email protected]("retry,delay", [(0, 0.5), (2, 2.0), (5, 16.0), (7, 30.0), (8, None)])
+async def test_migration_blockage_is_requeued_even_after_previous_retry_limit(
+ monkeypatch, processor_name, retry, delay
+):
+ from openviking.storage.queuefs.add_resource_processor import AddResourceProcessor
+ from openviking.storage.queuefs.content_write_processor import ContentWriteProcessor
+ from openviking.storage.queuefs.reindex_processor import ReindexProcessor
+
+ fs = SimpleNamespace(_async_agfs=SimpleNamespace())
+ processors = {
+ "AddResource": lambda: AddResourceProcessor(None, "AddResource", fs),
+ "Reindex": lambda: ReindexProcessor(fs),
+ "ContentWrite": lambda: ContentWriteProcessor(fs),
+ }
+ manager = SimpleNamespace(REINDEX="Reindex", CONTENT_WRITE="ContentWrite", enqueue=AsyncMock())
+ monkeypatch.setattr("openviking.storage.queuefs.get_queue_manager", lambda: manager)
+ sleep = AsyncMock()
+ monkeypatch.setattr("openviking.storage.pathlock_recovery.sleep", sleep)
+ msg = SimpleNamespace(
+ task_id="task",
+ lock_handoff_retry=retry,
+ to_dict=lambda: {"task_id": "task", "_task_work_id": "work"},
+ )
+ requeued = await processors[processor_name]()._requeue_lock_handoff(
+ msg, HandoffRecoveryBlocked("busy")
+ )
+ assert requeued is (delay is not None)
+ if delay is None:
+ sleep.assert_not_awaited()
+ manager.enqueue.assert_not_awaited()
+ return
+ sleep.assert_awaited_once_with(delay)
+ manager.enqueue.assert_awaited_once_with(
+ processor_name,
+ {"task_id": "task", "_task_work_id": "work", "lock_handoff_retry": retry + 1},
+ )
+
+
+async def test_content_write_historic_batch_recovers_all_exact_write_targets():
+ from openviking.storage.queuefs.content_write_processor import ContentWriteProcessor
+
+ agfs = client(HandoffRecoveryRequired("provider_changed"))
+ fs = SimpleNamespace(
+ _async_agfs=agfs,
+ _uri_to_path=lambda uri, ctx: uri.replace("viking://", f"/local/{ctx.account_id}/"),
+ )
+ msg = SimpleNamespace(
+ refresh={
+ "kind": "batch",
+ "refresh_kinds": {"viking://resources/a.md": "resource"},
+ "resource_plans": [{"plan": {"root_uri": "viking://resources/b.md"}}],
+ },
+ result={"deleted": ["viking://resources/c.md"]},
+ resource_id="viking://resources",
+ lock_handoff={"lock_paths": ["/local/tenant/resources/.exact.ovlock.a.md.123"]},
+ )
+ await ContentWriteProcessor(fs)._load_lock(msg, CTX)
+ agfs.pathlock_acquire_batch.assert_awaited_once_with(
+ [{"path": f"/local/tenant/resources/{p}.md", "kind": "exact"} for p in "abc"],
+ fs_ctx={"account_id": "tenant"},
+ )
+
+
+async def test_semantic_failed_migration_requeue_does_not_ack_original(monkeypatch):
+ from openviking.storage.queuefs.semantic_msg import SemanticMsg
+ from openviking.storage.queuefs.semantic_processor import SemanticProcessor
+
+ monkeypatch.setattr("openviking.storage.pathlock_recovery.sleep", AsyncMock())
+ processor = SemanticProcessor(
+ vlm_resolver=SimpleNamespace(get_vlm=AsyncMock(return_value=SimpleNamespace()))
+ )
+ work = SimpleNamespace(reenqueue_after_error=AsyncMock(side_effect=RuntimeError("disk full")))
+ processor._cleanup_local_artifact = AsyncMock()
+ with pytest.raises(RuntimeError, match="disk full"):
+ await processor._requeue_semantic_msg_after_error(
+ SemanticMsg(uri="viking://resources/tree", context_type="resource"),
+ HandoffRecoveryBlocked("busy"),
+ work=work,
+ )
+ processor._cleanup_local_artifact.assert_not_awaited()
+
+
+ "ctx", [None, SimpleNamespace(account_id=""), SimpleNamespace(account_id="../other")]
+)
+async def test_recovery_requires_valid_account_context(ctx):
+ agfs = client(HandoffRecoveryRequired("provider_changed"))
+ with pytest.raises(InvalidPathLockRequestError, match="account context"):
+ await adopt_or_reacquire(agfs, {"covered_paths": [TREE]}, ctx=ctx)
+ agfs.pathlock_adopt.assert_not_awaited()
+ agfs.pathlock_acquire_batch.assert_not_awaited()
+
+
+async def test_cancelled_backoff_keeps_original_message_unchanged(monkeypatch):
+ started = asyncio.Event()
+
+ async def wait(delay):
+ started.set()
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr("openviking.storage.pathlock_recovery.sleep", wait)
+ msg = SimpleNamespace(task_id="task", lock_handoff_retry=2, to_dict=lambda: {})
+ retry = asyncio.create_task(
+ prepare_handoff_retry(msg, HandoffRecoveryBlocked("busy"), queue="Reindex")
+ )
+ await started.wait()
+ retry.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await retry
+ assert msg.lock_handoff_retry == 2
+
+
+async def test_semantic_recovery_exhaustion_settles_failure_without_requeue():
+ from openviking.storage.queuefs.process_result import ProcessOutcome
+ from openviking.storage.queuefs.semantic_msg import SemanticMsg
+ from openviking.storage.queuefs.semantic_processor import SemanticProcessor
+
+ processor = SemanticProcessor(vlm_resolver=SimpleNamespace(get_vlm=AsyncMock()))
+ processor._cleanup_local_artifact = AsyncMock()
+ work = SimpleNamespace(reenqueue_after_error=AsyncMock())
+ msg = SemanticMsg(
+ uri="viking://resources/tree",
+ context_type="resource",
+ lock_handoff_retry=HANDOFF_RECOVERY_MAX_RETRIES,
+ )
+ restored = SemanticMsg.from_dict(msg.to_dict())
+ assert restored.lock_handoff_retry == HANDOFF_RECOVERY_MAX_RETRIES
+ result = await processor._requeue_semantic_msg_after_error(
+ restored, HandoffRecoveryBlocked("busy"), work=work
+ )
+ assert result.outcome is ProcessOutcome.FAILED
+ assert "retry limit" in result.error
+ work.reenqueue_after_error.assert_not_awaited()
+ processor._cleanup_local_artifact.assert_awaited_once_with(restored)
diff --git a/tests/storage/test_semantic_processor_lock_ownership.py b/tests/storage/test_semantic_processor_lock_ownership.py
index 5eedf5207..5da0dcee9 100644
--- a/tests/storage/test_semantic_processor_lock_ownership.py
+++ b/tests/storage/test_semantic_processor_lock_ownership.py
@@ -8,11 +8,11 @@ import json
from contextlib import nullcontext
from types import SimpleNamespace
from typing import cast
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
import pytest
-from openviking.storage.errors import InvalidPathLockRequestError
+from openviking.storage.errors import HandoffRecoveryRequired
from openviking.storage.queuefs.process_result import ProcessOutcome
from openviking.storage.queuefs.semantic_executor import SemanticTreeStats
from openviking.storage.queuefs.semantic_lock import SemanticLockScope
@@ -76,19 +76,14 @@ async def test_memory_semantic_directory_does_not_release_borrowed_lock(monkeypa
@pytest.mark.asyncio
-async def test_semantic_lock_reacquires_unicode_coverage_after_legacy_mapping_error(monkeypatch):
+async def test_semantic_lock_reacquires_unicode_coverage_after_provider_change(monkeypatch):
covered_path = "/local/default/resources/agent-memory/credit-risk/信贷风险管理_1.md"
lock_path = (
"/local/default/resources/agent-memory/credit-risk/.exact.ovlock.1.md.14dd8bad93aaa5b0"
)
lease = {"id": "reacquired-lock"}
pathlock = SimpleNamespace(
- pathlock_adopt=AsyncMock(
- side_effect=InvalidPathLockRequestError(
- f"invalid lock request: handoff coverage '{covered_path}' "
- f"does not map to lock path '{lock_path}'"
- )
- ),
+ pathlock_adopt=AsyncMock(side_effect=HandoffRecoveryRequired("provider_changed")),
pathlock_acquire_batch=AsyncMock(return_value=lease),
pathlock_release=AsyncMock(),
)
@@ -102,14 +97,52 @@ async def test_semantic_lock_reacquires_unicode_coverage_after_legacy_mapping_er
"covered_paths": [{"path": covered_path, "kind": "tree"}],
}
- scope = await SemanticLockScope.resolve(handoff)
+ scope = await SemanticLockScope.resolve(handoff, ctx=SimpleNamespace(account_id="default"))
assert scope.lock == lease
- pathlock.pathlock_acquire_batch.assert_awaited_once_with(handoff["covered_paths"])
+ pathlock.pathlock_acquire_batch.assert_awaited_once_with(
+ handoff["covered_paths"], fs_ctx={"account_id": "default"}
+ )
await scope.close()
pathlock.pathlock_release.assert_awaited_once_with(lease)
[email protected]("historic", [False, True])
+async def test_semantic_file_recovery_preserves_exact_or_uses_conservative_tree(
+ monkeypatch, historic
+):
+ path = "/local/default/resources/file.md"
+ pathlock = SimpleNamespace(
+ pathlock_adopt=AsyncMock(side_effect=HandoffRecoveryRequired("provider_changed")),
+ pathlock_acquire_batch=AsyncMock(return_value={"lease_ref": "new"}),
+ pathlock_release=AsyncMock(),
+ )
+ monkeypatch.setattr(
+ "openviking.storage.queuefs.semantic_lock.get_viking_fs",
+ lambda: _FakeVikingFS(pathlock),
+ )
+ warning = Mock()
+ monkeypatch.setattr("openviking.storage.queuefs.semantic_lock.logger.warning", warning)
+ handoff = {"lock_paths": ["/local/default/resources/.exact.ovlock.file.md.123"]}
+ if not historic:
+ handoff["covered_paths"] = [{"path": path, "kind": "exact"}]
+ scope = await SemanticLockScope.resolve(
+ handoff, ctx=SimpleNamespace(account_id="default"), fallback_path_factory=lambda: path
+ )
+ pathlock.pathlock_acquire_batch.assert_awaited_once_with(
+ [{"path": path, "kind": "tree" if historic else "exact"}],
+ fs_ctx={"account_id": "default"},
+ )
+ if historic:
+ warning.assert_called_once_with(
+ "Recovering historic semantic handoff with conservative Tree coverage path=%s", path
+ )
+ else:
+ warning.assert_not_called()
+ await scope.close()
+
+
def test_semantic_tree_stats_aggregate_multiple_plans_for_one_request():
telemetry_id = "reindex-request-stats"
SemanticProcessor._cache_tree_stats(
@@ -234,7 +267,7 @@ async def test_shared_scheduler_drains_each_messages_embeddings_before_unlock(
async def exists(self, uri, ctx=None):
return True
- async def pathlock_adopt(self, lease):
+ async def pathlock_adopt(self, lease, *, fs_ctx=None):
return lease
async def pathlock_release(self, lease):
diff --git a/tests/storage/test_semantic_processor_permanent_storage_error.py b/tests/storage/test_semantic_processor_permanent_storage_error.py
index f696975cf..02930d54c 100644
--- a/tests/storage/test_semantic_processor_permanent_storage_error.py
+++ b/tests/storage/test_semantic_processor_permanent_storage_error.py
@@ -107,7 +107,9 @@ async def test_storage_error_finishes_request_and_respects_lock_ownership(
env.retry_queue.enqueue.assert_not_awaited()
env.processor._account_breaker(msg.account_id).check()
if owned:
- env.pathlock.pathlock_adopt.assert_awaited_once_with(msg.lock_handoff)
+ env.pathlock.pathlock_adopt.assert_awaited_once_with(
+ msg.lock_handoff, fs_ctx={"account_id": msg.account_id}
+ )
env.pathlock.pathlock_release.assert_awaited_once_with(env.lease)
else:
env.pathlock.pathlock_as_borrowed.assert_awaited_once_with(env.lease)