Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
perf(pathlock): batch Redis lease refresh by scope (#6665)
zhanglistarecd54b27c483
diff --git a/crates/ragfs/src/lock/cache_provder.rs b/crates/ragfs/src/lock/cache_provder.rsindex 9f5f27b97..4cac8233e 100644--- a/crates/ragfs/src/lock/cache_provder.rs+++ b/crates/ragfs/src/lock/cache_provder.rs@@ -1,5 +1,6 @@//! Redis-backed PathLock storage.+use std::collections::BTreeMap;use std::sync::Arc;use async_trait::async_trait;@@ -18,6 +19,9 @@ const ROLLBACK_BATCH_ID: &str = "pathlock.rollback_batch.v1";const COMPARE_WRITE_ID: &str = "pathlock.compare_write.v1";const COMPARE_REMOVE_ID: &str = "pathlock.compare_remove.v1";const REFRESH_ID: &str = "pathlock.refresh.v1";+const REFRESH_BATCH_ID: &str = "pathlock.refresh_batch.v1";+// Bound each Lua execution so large leases do not monopolize Redis.+const REFRESH_BATCH_SIZE: usize = 256;const IS_LOCKED_ID: &str = "pathlock.is_locked.v1";const SCAN_DESCENDANTS_ID: &str = "pathlock.scan_descendants.v1";const READ_MANY_ID: &str = "pathlock.read_many.v1";@@ -357,6 +361,41 @@ return { "ok" }"#);+const REFRESH_BATCH_SCRIPT: &str = token_script!(+ r#"+local owner = ARGV[1]+local time_ns = ARGV[2]+local ttl_ms = ARGV[3]+if not normalize_decimal(time_ns) then+ return { "invalid_request", "invalid time_ns" }+end+local results = {}+local refreshed = false+for index = 4, #ARGV do+ local path = ARGV[index]+ local raw = redis.call("HGET", KEYS[1], path)+ if not raw then+ table.insert(results, { "missing" })+ else+ local token = decode_token(raw)+ if not token then+ table.insert(results, { "invalid_token", raw })+ elseif token.owner ~= owner then+ table.insert(results, { "owner_mismatch" })+ else+ redis.call("HSET", KEYS[1], path, token.owner .. ":" .. time_ns .. ":" .. token.kind)+ table.insert(results, { "ok" })+ refreshed = true+ end+ end+end+if refreshed then+ redis.call("PEXPIRE", KEYS[1], ttl_ms)+end+return results+"#+);+const IS_LOCKED_SCRIPT: &str = token_script!(r#"local path = ARGV[1]@@ -433,6 +472,7 @@ const SCRIPT_DEFINITIONS: &[ScriptDefinition] = &[script!(COMPARE_WRITE_ID, COMPARE_WRITE_SCRIPT),script!(COMPARE_REMOVE_ID, COMPARE_REMOVE_SCRIPT),script!(REFRESH_ID, REFRESH_SCRIPT),+ script!(REFRESH_BATCH_ID, REFRESH_BATCH_SCRIPT),script!(IS_LOCKED_ID, IS_LOCKED_SCRIPT),script!(SCAN_DESCENDANTS_ID, SCAN_DESCENDANTS_SCRIPT),script!(READ_MANY_ID, READ_MANY_SCRIPT),@@ -619,6 +659,25 @@ impl RedisPathLockProvider {.map_err(|_| PathLockError::InvalidToken(format!("invalid token at '{path}': {raw}")))}+ /// Decode the shared single-token and batch per-path refresh response.+ fn decode_refresh_result(lock_path: &str, values: &[ScriptValue]) -> PathLockResult<bool> {+ let status = Self::result_status(values, "refresh")?;+ match status {+ "ok" if values.len() == 1 => Ok(true),+ "missing" | "owner_mismatch" if values.len() == 1 => Ok(false),+ "invalid_token" if values.len() == 2 => Err(PathLockError::InvalidToken(format!(+ "invalid token at '{lock_path}': {}",+ Self::result_string(&values[1], "refresh")?+ ))),+ "invalid_request" if values.len() == 2 => Err(PathLockError::InvalidRequest(+ Self::result_string(&values[1], "refresh")?.to_string(),+ )),+ _ => Err(PathLockError::Internal(format!(+ "Redis PathLock refresh returned invalid status '{status}'"+ ))),+ }+ }+/// Decode a conflict or invalid-token script response.fn decode_error_result(operation: &str,@@ -950,21 +1009,77 @@ impl PathLockProvider for RedisPathLockProvider {],).await?;- let status = Self::result_status(&values, "refresh")?;- match status {- "ok" if values.len() == 1 => Ok(true),- "missing" | "owner_mismatch" if values.len() == 1 => Ok(false),- "invalid_token" if values.len() == 2 => Err(PathLockError::InvalidToken(format!(- "invalid token at '{lock_path}': {}",- Self::result_string(&values[1], "refresh")?- ))),- "invalid_request" if values.len() == 2 => Err(PathLockError::InvalidRequest(- Self::result_string(&values[1], "refresh")?.to_string(),- )),- _ => Err(PathLockError::Internal(format!(- "Redis PathLock refresh returned invalid status '{status}'"- ))),+ Self::decode_refresh_result(lock_path, &values)+ }++ /// Refresh each scope HASH in bounded batches while preserving input order.+ async fn refresh_tokens(+ &self,+ lock_paths: &[String],+ owner_id: &str,+ time_ns: u128,+ ) -> Vec<PathLockResult<bool>> {+ let mut results: Vec<_> = lock_paths.iter().map(|_| Ok(false)).collect();+ let mut groups: BTreeMap<String, Vec<(usize, &str)>> = BTreeMap::new();+ for (index, path) in lock_paths.iter().enumerate() {+ match self.tokens_key_for_path(path) {+ Ok(key) => groups.entry(key).or_default().push((index, path)),+ Err(error) => results[index] = Err(error),+ }+ }+ for (key, paths) in groups {+ for batch in paths.chunks(REFRESH_BATCH_SIZE) {+ let mut args = vec![+ Self::bytes(owner_id),+ Self::bytes(time_ns.to_string()),+ Self::bytes(self.hash_ttl_ms.to_string()),+ ];+ args.extend(batch.iter().map(|(_, path)| Self::bytes(*path)));+ match self+ .execute_array(REFRESH_BATCH_ID, key.clone(), args)+ .await+ {+ Ok(values)+ if matches!(+ Self::result_status(&values, "refresh_batch"),+ Ok("invalid_request")+ ) =>+ {+ for (index, path) in batch {+ results[*index] = Self::decode_refresh_result(path, &values);+ }+ }+ Ok(values) if values.len() == batch.len() => {+ for ((index, path), value) in batch.iter().zip(values) {+ results[*index] = match value {+ ScriptValue::Array(values) => {+ Self::decode_refresh_result(path, &values)+ }+ other => Err(PathLockError::Internal(format!(+ "Redis PathLock batch refresh returned non-array result: {other:?}"+ ))),+ };+ }+ }+ Ok(values) => {+ for (index, _) in batch {+ results[*index] = Err(PathLockError::Internal(format!(+ "Redis PathLock batch refresh returned {} results for {} paths",+ values.len(),+ batch.len()+ )));+ }+ }+ Err(error) => {+ for (index, _) in batch {+ results[*index] =+ Err(PathLockError::Io(format!("batch refresh failed: {error}")));+ }+ }+ }+ }}+ results}/// Remove one owned token using complete-token compare-and-remove.@@ -1021,6 +1136,10 @@ impl PathLockProvider for RedisPathLockProvider {}}+#[cfg(test)]+#[path = "cache_refresh_tests.rs"]+mod refresh_tests;+#[cfg(test)]mod tests {use std::sync::atomic::{AtomicUsize, Ordering};diff --git a/crates/ragfs/src/lock/cache_refresh_tests.rs b/crates/ragfs/src/lock/cache_refresh_tests.rsnew file mode 100644index 000000000..858fbb199--- /dev/null+++ b/crates/ragfs/src/lock/cache_refresh_tests.rs@@ -0,0 +1,348 @@+//! Regression coverage for batched Redis lease refresh.++use super::*;+use crate::cache_runtime::{CacheResult, MemoryMockProvider, ScriptResult};+use crate::lock::manager::{PathLockConfig, PathLockManager};+use crate::plugins::memfs::MemFileSystem;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Mutex;+use std::time::Duration;++fn mock_provider<F>(handler: F) -> (Arc<CacheRuntime>, RedisPathLockProvider)+where+ F: Fn(ScriptRequest) -> CacheResult<ScriptValue> + Send + Sync + 'static,+{+ let mock = MemoryMockProvider::new()+ .with_script_handler(move |request| ScriptResult::encode(&handler(request)?));+ let runtime = CacheRuntime::memory_with_provider(Arc::new(mock));+ let provider = RedisPathLockProvider::new(runtime.clone(), "batch-refresh-test", 30.0).unwrap();+ (runtime, provider)+}++fn status(value: &str) -> ScriptValue {+ ScriptValue::Array(vec![ScriptValue::Bytes(value.as_bytes().to_vec())])+}++#[tokio::test]+async fn same_scope_refresh_uses_one_script_for_twenty_paths() {+ let calls = Arc::new(AtomicUsize::new(0));+ let observed = calls.clone();+ let (runtime, provider) = mock_provider(move |request| {+ assert_eq!(request.script_id, REFRESH_BATCH_ID);+ assert_eq!(request.keys.len(), 1);+ assert_eq!(request.args[0], Bytes::from("owner"));+ assert_eq!(request.args[1], Bytes::from("200"));+ assert_eq!(request.args[2], Bytes::from("60000"));+ assert_eq!(request.args.len(), 23);+ observed.fetch_add(1, Ordering::SeqCst);+ Ok(ScriptValue::Array(vec![status("ok"); 20]))+ });+ assert!(provider.refresh_tokens(&[], "owner", 200).await.is_empty());+ assert_eq!(calls.load(Ordering::SeqCst), 0);+ let paths: Vec<_> = (0..20).map(|i| format!("/local/account-a/{i}")).collect();+ let results = provider.refresh_tokens(&paths, "owner", 200).await;+ assert_eq!(results.len(), 20);+ assert!(results.iter().all(|result| matches!(result, Ok(true))));+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ runtime.close().await.unwrap();+}++#[tokio::test]+async fn refresh_groups_scopes_and_preserves_mixed_result_order() {+ let calls = Arc::new(AtomicUsize::new(0));+ let observed = calls.clone();+ let (runtime, provider) = mock_provider(move |request| {+ assert_eq!(request.script_id, REFRESH_BATCH_ID);+ observed.fetch_add(1, Ordering::SeqCst);+ let results = request.args[3..]+ .iter()+ .map(|path| {+ let path = std::str::from_utf8(path).unwrap();+ if path.ends_with("/missing") {+ status("missing")+ } else if path.ends_with("/foreign") {+ status("owner_mismatch")+ } else if path.ends_with("/bad") {+ ScriptValue::Array(vec![+ ScriptValue::Bytes(b"invalid_token".to_vec()),+ ScriptValue::Bytes(b"broken".to_vec()),+ ])+ } else {+ status("ok")+ }+ })+ .collect();+ Ok(ScriptValue::Array(results))+ });+ let paths = [+ "/local/account-b/good",+ "/local/account-a/missing",+ "/local/account-b/bad",+ "/local/account-a/foreign",+ "/local/account-a/good",+ "/unsupported",+ ]+ .map(String::from);+ let results = provider.refresh_tokens(&paths, "owner", 200).await;+ assert_eq!(results.len(), paths.len());+ assert!(matches!(results[0], Ok(true)));+ assert!(matches!(results[1], Ok(false)));+ assert!(+ matches!(&results[2], Err(PathLockError::InvalidToken(message)) if message.contains(&paths[2]))+ );+ assert!(matches!(results[3], Ok(false)));+ assert!(matches!(results[4], Ok(true)));+ assert!(matches!(results[5], Err(PathLockError::InvalidRequest(_))));+ assert_eq!(calls.load(Ordering::SeqCst), 2);+ runtime.close().await.unwrap();+}++#[tokio::test]+async fn failed_scope_does_not_prevent_other_scopes_refreshing() {+ let (runtime, provider) = mock_provider(|request| {+ if request.keys[0].contains("account-a") {+ return Err(CacheError::Unavailable(+ "injected refresh failure".to_string(),+ ));+ }+ Ok(ScriptValue::Array(vec![+ status("ok");+ request.args.len() - 3+ ]))+ });+ let paths = [+ "/local/account-a/a",+ "/local/account-b/b",+ "/local/account-a/c",+ ]+ .map(String::from);+ let results = provider.refresh_tokens(&paths, "owner", 200).await;+ assert!(matches!(results[0], Err(PathLockError::Io(_))));+ assert!(matches!(results[1], Ok(true)));+ assert!(matches!(results[2], Err(PathLockError::Io(_))));+ runtime.close().await.unwrap();+}++#[tokio::test]+async fn large_refresh_is_split_into_bounded_scripts() {+ let sizes = Arc::new(Mutex::new(Vec::new()));+ let observed = sizes.clone();+ let (runtime, provider) = mock_provider(move |request| {+ let size = request.args.len() - 3;+ observed.lock().unwrap().push(size);+ Ok(ScriptValue::Array(vec![status("ok"); size]))+ });+ let paths: Vec<_> = (0..REFRESH_BATCH_SIZE + 1)+ .map(|i| format!("/local/account-a/{i}"))+ .collect();+ let results = provider.refresh_tokens(&paths, "owner", 200).await;+ assert_eq!(results.len(), paths.len());+ assert!(results.iter().all(|result| matches!(result, Ok(true))));+ assert_eq!(*sizes.lock().unwrap(), vec![REFRESH_BATCH_SIZE, 1]);+ runtime.close().await.unwrap();+}++#[tokio::test]+async fn malformed_batch_response_never_reports_refresh_success() {+ let (runtime, provider) = mock_provider(|_| Ok(ScriptValue::Array(vec![status("ok")])));+ let paths = ["/local/account-a/a", "/local/account-a/b"].map(String::from);+ let results = provider.refresh_tokens(&paths, "owner", 200).await;+ assert_eq!(results.len(), 2);+ assert!(results+ .iter()+ .all(|result| matches!(result, Err(PathLockError::Internal(_)))));+ runtime.close().await.unwrap();+}++#[tokio::test]+async fn batch_invalid_request_is_preserved_for_every_path() {+ // Inject Lua's early-return shape; every u128 supplied by Rust is a valid time_ns.+ let (runtime, provider) = mock_provider(|request| {+ assert_eq!(request.script_id, REFRESH_BATCH_ID);+ Ok(ScriptValue::Array(vec![+ ScriptValue::Bytes(b"invalid_request".to_vec()),+ ScriptValue::Bytes(b"invalid time_ns".to_vec()),+ ]))+ });+ for size in [2, 1, 3, 20, REFRESH_BATCH_SIZE + 1] {+ let paths: Vec<_> = (0..size).map(|i| format!("/local/account-a/{i}")).collect();+ let results = provider.refresh_tokens(&paths, "owner", u128::MAX).await;+ assert_eq!(results.len(), size);+ assert!(+ results.iter().all(|result| matches!(+ result,+ Err(PathLockError::InvalidRequest(message)) if message == "invalid time_ns"+ )),+ "batch size {size}: {results:?}"+ );+ }+ runtime.close().await.unwrap();+}++#[tokio::test]+async fn manager_uses_batch_for_manual_and_background_refresh() {+ let calls = Arc::new(AtomicUsize::new(0));+ let observed = calls.clone();+ let (runtime, provider) = mock_provider(move |request| match request.script_id.as_str() {+ ACQUIRE_BATCH_ID => {+ let owner = std::str::from_utf8(&request.args[0]).unwrap();+ let time = std::str::from_utf8(&request.args[1]).unwrap();+ let mut results = vec![ScriptValue::Bytes(b"ok".to_vec())];+ for pair in request.args[4..].chunks_exact(2) {+ let kind = std::str::from_utf8(&pair[1]).unwrap();+ results.extend([+ ScriptValue::Bytes(pair[0].to_vec()),+ ScriptValue::Bytes(b"created".to_vec()),+ ScriptValue::Bytes(Vec::new()),+ ScriptValue::Bytes(format!("{owner}:{time}:{kind}").into_bytes()),+ ]);+ }+ Ok(ScriptValue::Array(results))+ }+ REFRESH_BATCH_ID => {+ assert_eq!(request.args.len(), 23);+ observed.fetch_add(1, Ordering::SeqCst);+ Ok(ScriptValue::Array(vec![status("ok"); 20]))+ }+ other => panic!("manager should use batch refresh, got {other}"),+ });+ let manager = PathLockManager::new(+ Arc::new(MemFileSystem::new()),+ Arc::new(provider),+ PathLockConfig {+ lock_expire_secs: 1.0,+ ..PathLockConfig::default()+ },+ );+ let paths: Vec<_> = (0..20).map(|i| format!("/local/account-a/{i}")).collect();+ let lease = manager+ .acquire_exact_batch(&paths, Duration::ZERO, None)+ .await+ .unwrap();+ assert_eq!(manager.refresh(&lease).await.unwrap(), "refreshed");+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ tokio::time::timeout(Duration::from_secs(3), async {+ while calls.load(Ordering::SeqCst) < 2 {+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .expect("background refresh must use the batch provider");+ runtime.close().await.unwrap();+}++#[tokio::test]+async fn redis_batch_preserves_kind_ownership_errors_and_hash_ttl() {+ let Ok(endpoint) = std::env::var("REDIS_URL") else {+ return;+ };+ let runtime = CacheRuntime::redis(crate::cache_runtime::RedisProviderConfig {+ endpoints: vec![endpoint],+ command_timeout_ms: 1_000,+ ..crate::cache_runtime::RedisProviderConfig::default()+ })+ .await+ .unwrap();+ let service = format!("batch-refresh-real-{}", uuid::Uuid::new_v4());+ let provider = RedisPathLockProvider::new(runtime.clone(), &service, 1.0).unwrap();+ let paths = [+ "/local/account-a/bad",+ "/local/account-a/exact",+ "/local/account-a/missing",+ "/local/account-a/foreign",+ "/local/account-b/tree",+ "/local/account-a/exact",+ "/local/account-c/foreign",+ ]+ .map(String::from);+ for (index, owner, kind) in [+ (1, "owner", PathLockKind::Exact),+ (3, "other", PathLockKind::Exact),+ (4, "owner", PathLockKind::Tree),+ (6, "other", PathLockKind::Tree),+ ] {+ provider+ .try_create_token(+ &paths[index],+ &LockToken {+ owner_id: owner.to_string(),+ time_ns: 100,+ lock_type: kind,+ },+ )+ .await+ .unwrap();+ }+ runtime+ .register_script(ScriptDefinition {+ id: "pathlock.test.batch_corrupt.v1",+ redis_lua: "return redis.call('HSET', KEYS[1], ARGV[1], 'broken')",+ })+ .unwrap();+ runtime+ .execute_script(ScriptRequest {+ script_id: "pathlock.test.batch_corrupt.v1".to_string(),+ keys: vec![provider.tokens_key_for_path(&paths[0]).unwrap()],+ args: vec![Bytes::from(paths[0].clone())],+ })+ .await+ .unwrap();+ runtime+ .register_script(ScriptDefinition {+ id: "pathlock.test.batch_long_ttl.v1",+ redis_lua: "return redis.call('PEXPIRE', KEYS[1], 60000)",+ })+ .unwrap();+ for path in [&paths[1], &paths[4], &paths[6]] {+ runtime+ .execute_script(ScriptRequest {+ script_id: "pathlock.test.batch_long_ttl.v1".to_string(),+ keys: vec![provider.tokens_key_for_path(path).unwrap()],+ args: vec![],+ })+ .await+ .unwrap();+ }+ let results = provider.refresh_tokens(&paths, "owner", u128::MAX).await;+ assert_eq!(results.len(), paths.len());+ assert!(matches!(results[0], Err(PathLockError::InvalidToken(_))));+ assert!(matches!(results[1], Ok(true)));+ assert!(matches!(results[2], Ok(false)));+ assert!(matches!(results[3], Ok(false)));+ assert!(matches!(results[4], Ok(true)));+ assert!(matches!(results[5], Ok(true)));+ assert!(matches!(results[6], Ok(false)));+ for (index, kind) in [(1, PathLockKind::Exact), (4, PathLockKind::Tree)] {+ let token = provider.read_token(&paths[index]).await.unwrap().unwrap();+ assert_eq!(token.owner_id, "owner");+ assert_eq!(token.time_ns, u128::MAX);+ assert_eq!(token.lock_type, kind);+ }+ let foreign = provider.read_token(&paths[3]).await.unwrap().unwrap();+ assert_eq!(foreign.owner_id, "other");+ assert_eq!(foreign.time_ns, 100);+ runtime+ .register_script(ScriptDefinition {+ id: "pathlock.test.batch_ttl.v1",+ redis_lua: "return redis.call('PTTL', KEYS[1])",+ })+ .unwrap();+ for (path, refreshed) in [(&paths[1], true), (&paths[4], true), (&paths[6], false)] {+ let ttl = runtime+ .execute_script(ScriptRequest {+ script_id: "pathlock.test.batch_ttl.v1".to_string(),+ keys: vec![provider.tokens_key_for_path(path).unwrap()],+ args: vec![],+ })+ .await+ .unwrap()+ .decode()+ .unwrap();+ if refreshed {+ assert!(matches!(ttl, ScriptValue::Integer(value) if value > 0 && value <= 2_000));+ } else {+ assert!(matches!(ttl, ScriptValue::Integer(value) if value > 2_000));+ }+ }+ runtime.close().await.unwrap();+}diff --git a/crates/ragfs/src/lock/manager.rs b/crates/ragfs/src/lock/manager.rsindex 68e816943..2cbe038e2 100644--- a/crates/ragfs/src/lock/manager.rs+++ b/crates/ragfs/src/lock/manager.rs@@ -524,11 +524,11 @@ impl PathLockManager {let pending_handoff = entry.pending_handoff;let mut any_ok = false;let mut released_handoff_paths = Vec::new();- for lp in &lock_paths {- match refresh_provider- .refresh_token(lp, &owner.owner_id, now_ns)- .await- {+ let results = refresh_provider+ .refresh_tokens(&lock_paths, &owner.owner_id, now_ns)+ .await;+ for (lp, result) in lock_paths.iter().zip(results) {+ match result {Ok(true) => {any_ok = true;debug!(lease_ref = %lease_ref, owner_id = %owner.owner_id, lock_path = %lp, "pathlock lease automatically refreshed");@@ -1373,12 +1373,12 @@ impl PathLockManager {let mut all_ok = true;let mut any_ok = false;- for lp in &lock_paths {- match self- .provider- .refresh_token(lp, &owner.owner_id, now_ns)- .await- {+ for result in self+ .provider+ .refresh_tokens(&lock_paths, &owner.owner_id, now_ns)+ .await+ {+ match result {Ok(true) => any_ok = true,Ok(false) => all_ok = false,Err(_) => all_ok = false,diff --git a/crates/ragfs/src/lock/provider.rs b/crates/ragfs/src/lock/provider.rsindex d6ec86b89..41a130871 100644--- a/crates/ragfs/src/lock/provider.rs+++ b/crates/ragfs/src/lock/provider.rs@@ -119,6 +119,22 @@ pub trait PathLockProvider: Send + Sync {time_ns: u128,) -> PathLockResult<bool>;+ /// Refresh owned tokens, returning one result per input path in input order.+ /// A failed path must not prevent the remaining paths from being refreshed.+ /// Backends without batch support retain the single-token behavior.+ async fn refresh_tokens(+ &self,+ lock_paths: &[String],+ owner_id: &str,+ time_ns: u128,+ ) -> Vec<PathLockResult<bool>> {+ let mut results = Vec::with_capacity(lock_paths.len());+ for lock_path in lock_paths {+ results.push(self.refresh_token(lock_path, owner_id, time_ns).await);+ }+ results+ }+/// Remove the token at `lock_path` if owned by `owner_id`./// `force` bypasses storage CAS after the ownership check./// Returns `true` if removed, `false` if not found or wrong owner.@@ -312,6 +328,34 @@ mod tests {use super::*;+ /// Verify the fallback reports each path and continues after a token error.+ #[tokio::test]+ async fn batch_refresh_fallback_preserves_per_path_results() {+ let fs = Arc::new(MemFileSystem::new());+ fs.mkdir("/data", 0o755).await.unwrap();+ for (path, raw) in [+ ("/data/bad", "not-a-token"),+ ("/data/good", "owner:100:T"),+ ("/data/foreign", "other:100:E"),+ ] {+ fs.write(path, raw.as_bytes(), 0, WriteFlag::Create)+ .await+ .unwrap();+ }+ let provider = FilesystemPathLockProvider::new(fs, 30.0);+ let paths = ["bad", "good", "foreign", "missing"].map(|name| format!("/data/{name}"));+ let results = provider.refresh_tokens(&paths, "owner", 200).await;+ assert_eq!(results.len(), paths.len());+ assert!(matches!(results[0], Err(PathLockError::InvalidToken(_))));+ assert!(matches!(results[1], Ok(true)));+ assert!(matches!(results[2], Ok(false)));+ assert!(matches!(results[3], Ok(false)));+ let token = provider.read_token(&paths[1]).await.unwrap().unwrap();+ assert_eq!(token.time_ns, 200);+ assert_eq!(token.lock_type, crate::lock::PathLockKind::Tree);+ assert!(provider.refresh_tokens(&[], "owner", 200).await.is_empty());+ }+/// Verify legacy encrypted lock files are treated as removable upgrade leftovers.#[tokio::test]async fn read_token_cleans_up_legacy_encrypted_lock() {