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
fix(transaction): unify stale lock handling with ownership checks (#1171)
Qin Haojie62116918265d
diff --git a/docs/en/concepts/09-transaction.md b/docs/en/concepts/09-transaction.mdindex edbda7249..0cc0115c0 100644--- a/docs/en/concepts/09-transaction.md+++ b/docs/en/concepts/09-transaction.md@@ -50,7 +50,8 @@ Storage Layer (VikingFS, VectorDB, QueueManager)class LockHandle:id: str # Unique ID used to generate fencing tokenslocks: list[str] # Acquired lock file paths- created_at: float # Creation time+ created_at: float # Handle creation time+ last_active_at: float # Last successful acquire/refresh time```**LockManager** is a global singleton managing lock lifecycle:@@ -142,7 +143,7 @@ Operation flow:4. Release POINT lock5. Clean up temp directory6. Enqueue SemanticMsg(lifecycle_lock_handle_id=...) -> DAG runs on final-7. DAG starts lock refresh loop (refreshes timestamp every lock_expire/2 seconds)+7. DAG starts lock refresh loop (refreshes the lock token and updates handle activity every lock_expire/2 seconds)8. DAG complete + all embeddings done -> release SUBTREE lock```@@ -306,7 +307,7 @@ Timeout (default 0 = no-wait) raises LockAcquisitionError**Stale lock detection**: PathLock checks the fencing token timestamp. Locks older than `lock_expire` (default 300s) are considered stale and are removed automatically during acquisition.-**In-process cleanup**: LockManager checks active LockHandles every 60 seconds. Handles created more than 3600 seconds ago are force-released.+**In-process cleanup**: LockManager checks active LockHandles every 60 seconds. Handles that still own lock files but have been inactive for longer than `lock_expire` are force-released.**Orphan locks**: Lock files left behind after a process crash are automatically removed via stale lock detection when any operation next attempts to acquire a lock on the same path.@@ -349,7 +350,7 @@ Path locks are enabled by default with no extra configuration needed. **The defa| Parameter | Type | Description | Default ||-----------|------|-------------|---------|| `lock_timeout` | float | Lock acquisition timeout (seconds). `0` = fail immediately if locked (default). `> 0` = wait/retry up to this many seconds. | `0.0` |-| `lock_expire` | float | Stale lock expiry threshold (seconds). Locks held longer than this by a crashed process are force-released. | `300.0` |+| `lock_expire` | float | Lock inactivity threshold (seconds). Locks not refreshed within this window are treated as stale and reclaimed. | `300.0` |### QueueFS Persistencediff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex 4a71fc4d7..b5f0f5e22 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -862,7 +862,7 @@ Path locks are enabled by default and usually require no configuration. **The de| Parameter | Type | Description | Default ||-----------|------|-------------|---------|| `lock_timeout` | float | Path lock acquisition timeout (seconds). `0` = fail immediately if locked (default). `> 0` = wait/retry up to this many seconds, then raise `LockAcquisitionError`. | `0.0` |-| `lock_expire` | float | Stale lock expiry threshold (seconds). Locks held longer than this by a crashed process are force-released. | `300.0` |+| `lock_expire` | float | Lock inactivity threshold (seconds). Locks not refreshed within this window are treated as stale and reclaimed. | `300.0` |For details on the lock mechanism, see [Path Locks and Crash Recovery](../concepts/09-transaction.md).diff --git a/docs/zh/concepts/09-transaction.md b/docs/zh/concepts/09-transaction.mdindex 45a10d632..9b29fc506 100644--- a/docs/zh/concepts/09-transaction.md+++ b/docs/zh/concepts/09-transaction.md@@ -49,7 +49,8 @@ Storage Layer (VikingFS, VectorDB, QueueManager)class LockHandle:id: str # 唯一标识,用于生成 fencing tokenlocks: list[str] # 已获取的锁文件路径- created_at: float # 创建时间+ created_at: float # handle 创建时间+ last_active_at: float # 最近一次成功 acquire/refresh 的时间```**LockManager** 是全局单例,管理锁生命周期:@@ -141,7 +142,7 @@ VectorDB 删除失败 -> 直接抛异常,锁自动释放,文件和索引都4. 释放 POINT 锁5. 清理临时目录6. 入队 SemanticMsg(lifecycle_lock_handle_id=...) -> DAG 在 final 上跑-7. DAG 启动锁刷新循环(每 lock_expire/2 秒刷新时间戳)+7. DAG 启动锁刷新循环(每 lock_expire/2 秒刷新锁 token 并更新 handle 活跃时间)8. DAG 完成 + 所有 embedding 完成 -> 释放 SUBTREE 锁```@@ -305,7 +306,7 @@ async with LockContext(lock_manager, [src], lock_mode="mv", mv_dst_parent_path=d**陈旧锁检测**:PathLock 检查 fencing token 中的时间戳。超过 `lock_expire`(默认 300s)的锁被视为陈旧锁,在加锁过程中自动移除。-**进程内清理**:LockManager 每 60 秒检查活跃的 LockHandle,创建超过 3600 秒的 handle 强制释放。+**进程内清理**:LockManager 每 60 秒检查活跃的 LockHandle。仍持有锁文件且失活时间超过 `lock_expire` 的 handle 会被强制释放。**孤儿锁**:进程崩溃后遗留的锁文件,在下次任何操作尝试获取同一路径锁时,通过 stale lock 检测自动移除。@@ -348,7 +349,7 @@ async with LockContext(lock_manager, [src], lock_mode="mv", mv_dst_parent_path=d| 参数 | 类型 | 说明 | 默认值 ||------|------|------|--------|| `lock_timeout` | float | 获取锁的等待超时(秒)。`0` = 立即失败(默认);`> 0` = 最多等待此时间 | `0.0` |-| `lock_expire` | float | 锁过期时间(秒),超过此时间的锁将被视为陈旧锁并强制释放 | `300.0` |+| `lock_expire` | float | 锁失活阈值(秒),超过此时间未被 refresh 的锁会被视为陈旧锁并回收 | `300.0` |### QueueFS 持久化diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex 65b6040ba..323e979a3 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -931,7 +931,7 @@ openviking --account acme --user alice --agent-id assistant-2 ls viking://| 参数 | 类型 | 说明 | 默认值 ||------|------|------|--------|| `lock_timeout` | float | 获取路径锁的等待超时(秒)。`0` = 立即失败(默认);`> 0` = 最多等待此时间后抛出 `LockAcquisitionError` | `0.0` |-| `lock_expire` | float | 锁过期时间(秒)。超过此时间的锁将被视为崩溃进程遗留的陈旧锁并强制释放 | `300.0` |+| `lock_expire` | float | 锁失活阈值(秒)。超过此时间未被 refresh 的锁会被视为陈旧锁并回收 | `300.0` |路径锁机制的详细说明见 [路径锁与崩溃恢复](../concepts/09-transaction.md)。diff --git a/openviking/storage/observers/lock_observer.py b/openviking/storage/observers/lock_observer.pyindex 4ae838f18..1e7bc5e81 100644--- a/openviking/storage/observers/lock_observer.py+++ b/openviking/storage/observers/lock_observer.py@@ -26,15 +26,16 @@ class LockObserver(BaseObserver):"id": h.id,"lock_count": len(h.locks),"created_at": h.created_at,+ "last_active_at": h.last_active_at,"duration_seconds": round(now - h.created_at, 1),+ "idle_seconds": round(now - h.last_active_at, 1),}for h in self._manager.get_active_handles().values()]def get_hanging_locks(self, threshold: float = 600) -> List[Dict[str, Any]]:- """Return locks that have been held longer than *threshold* seconds."""- now = time.time()- return [lock for lock in self.get_active_locks() if now - lock["created_at"] > threshold]+ """Return locks that have been idle longer than *threshold* seconds."""+ return [lock for lock in self.get_active_locks() if lock["idle_seconds"] > threshold]# ------ BaseObserver interface ------@@ -50,6 +51,7 @@ class LockObserver(BaseObserver):"Handle ID": l["id"][:8] + "...","Locks": l["lock_count"],"Duration": f"{l['duration_seconds']}s",+ "Idle": f"{l['idle_seconds']}s","Created": time.strftime("%H:%M:%S", time.localtime(l["created_at"])),}for l in locks@@ -59,6 +61,7 @@ class LockObserver(BaseObserver):"Handle ID": f"TOTAL ({len(locks)})","Locks": sum(l["lock_count"] for l in locks),"Duration": "",+ "Idle": "","Created": "",})diff --git a/openviking/storage/transaction/lock_handle.py b/openviking/storage/transaction/lock_handle.pyindex 8ab32a116..1b00fc941 100644--- a/openviking/storage/transaction/lock_handle.py+++ b/openviking/storage/transaction/lock_handle.py@@ -27,6 +27,10 @@ class LockHandle:id: str = field(default_factory=lambda: str(uuid.uuid4()))locks: list[str] = field(default_factory=list)created_at: float = field(default_factory=time.time)+ last_active_at: float = field(init=False)++ def __post_init__(self) -> None:+ self.last_active_at = self.created_atdef add_lock(self, lock_path: str) -> None:if lock_path not in self.locks:diff --git a/openviking/storage/transaction/lock_manager.py b/openviking/storage/transaction/lock_manager.pyindex 28878fe5e..1d1b949a0 100644--- a/openviking/storage/transaction/lock_manager.py+++ b/openviking/storage/transaction/lock_manager.py@@ -15,6 +15,8 @@ from openviking_cli.utils.logger import get_loggerlogger = get_logger(__name__)+_HANDLE_CLEANUP_INTERVAL_SECONDS = 60.0+class LockManager:"""Global singleton. Manages lock lifecycle and stale cleanup."""@@ -37,8 +39,16 @@ class LockManager:def redo_log(self) -> RedoLog:return self._redo_log+ def _mark_handle_active(self, handle: LockHandle) -> None:+ handle.last_active_at = time.time()+def get_active_handles(self) -> Dict[str, LockHandle]:- return dict(self._handles)+ active_handles: Dict[str, LockHandle] = {}+ for handle in list(self._handles.values()):+ current = self._reconcile_handle(handle)+ if current and current.locks:+ active_handles[current.id] = current+ return active_handlesasync def start(self) -> None:"""Start background cleanup and redo recovery."""@@ -69,16 +79,22 @@ class LockManager:async def acquire_point(self, handle: LockHandle, path: str, timeout: Optional[float] = None) -> bool:- return await self._path_lock.acquire_point(+ acquired = await self._path_lock.acquire_point(path, handle, timeout=timeout if timeout is not None else self._lock_timeout)+ if acquired:+ self._mark_handle_active(handle)+ return acquiredasync def acquire_subtree(self, handle: LockHandle, path: str, timeout: Optional[float] = None) -> bool:- return await self._path_lock.acquire_subtree(+ acquired = await self._path_lock.acquire_subtree(path, handle, timeout=timeout if timeout is not None else self._lock_timeout)+ if acquired:+ self._mark_handle_active(handle)+ return acquiredasync def acquire_subtree_batch(self,@@ -106,6 +122,7 @@ class LockManager:是否成功获取所有锁"""if not paths:+ self._mark_handle_active(handle)return True# 对路径进行排序,确保加锁顺序一致@@ -126,6 +143,7 @@ class LockManager:return Falseacquired.append(path)+ self._mark_handle_active(handle)return Trueexcept Exception as e:@@ -142,19 +160,39 @@ class LockManager:src_is_dir: bool = True,timeout: Optional[float] = None,) -> bool:- return await self._path_lock.acquire_mv(+ acquired = await self._path_lock.acquire_mv(src,dst_parent,handle,timeout=timeout if timeout is not None else self._lock_timeout,src_is_dir=src_is_dir,)+ if acquired:+ self._mark_handle_active(handle)+ return acquireddef get_handle(self, handle_id: str) -> Optional[LockHandle]:- return self._handles.get(handle_id)+ handle = self._handles.get(handle_id)+ if handle is None:+ return None+ current = self._reconcile_handle(handle)+ if current is None or not current.locks:+ return None+ return currentasync def refresh_lock(self, handle: LockHandle) -> None:- await self._path_lock.refresh(handle)+ current = self._reconcile_handle(handle)+ if current is None:+ return++ result = await self._path_lock.refresh(current)+ for lock_path in result.lost_paths:+ current.remove_lock(lock_path)++ if result.refreshed_paths:+ self._mark_handle_active(current)++ self._reconcile_handle(current)async def release(self, handle: LockHandle) -> None:await self._path_lock.release(handle)@@ -166,13 +204,35 @@ class LockManager:async def _stale_cleanup_loop(self) -> None:"""Check and release leaked handles every 60 s (in-process safety net)."""while self._running:- await asyncio.sleep(60)+ await asyncio.sleep(_HANDLE_CLEANUP_INTERVAL_SECONDS)now = time.time()- stale = [h for h in self._handles.values() if now - h.created_at > 3600]+ stale = []+ for handle in list(self._handles.values()):+ current = self._reconcile_handle(handle)+ if current and self._is_handle_stale(current, now):+ stale.append(current)for handle in stale:logger.warning(f"Releasing stale lock handle {handle.id}")await self.release(handle)+ def _is_handle_stale(self, handle: LockHandle, now: Optional[float] = None) -> bool:+ """Return True when a live lock handle has stopped refreshing for too long."""+ if not handle.locks:+ return False+ if now is None:+ now = time.time()+ return now - handle.last_active_at > self._path_lock._lock_expire++ def _reconcile_handle(self, handle: LockHandle) -> Optional[LockHandle]:+ had_locks = bool(handle.locks)+ lost_paths = self._path_lock.collect_lost_owner_locks(handle)+ for lock_path in lost_paths:+ handle.remove_lock(lock_path)+ if had_locks and not handle.locks:+ self._handles.pop(handle.id, None)+ return None+ return handle+# ------------------------------------------------------------------# Redo recovery (session_memory only)# ------------------------------------------------------------------diff --git a/openviking/storage/transaction/path_lock.py b/openviking/storage/transaction/path_lock.pyindex 867afc064..1b8232f23 100644--- a/openviking/storage/transaction/path_lock.py+++ b/openviking/storage/transaction/path_lock.py@@ -1,5 +1,6 @@import asyncioimport time+from dataclasses import dataclass, fieldfrom typing import Optional, Tuplefrom openviking.pyagfs import AGFSClient@@ -19,6 +20,13 @@ LOCK_TYPE_SUBTREE = "S"_POLL_INTERVAL = 0.2+@dataclass+class LockRefreshResult:+ refreshed_paths: list[str] = field(default_factory=list)+ lost_paths: list[str] = field(default_factory=list)+ failed_paths: list[str] = field(default_factory=list)++def _make_fencing_token(owner_id: str, lock_type: str = LOCK_TYPE_POINT) -> str:return f"{owner_id}:{time.time_ns()}:{lock_type}"@@ -96,6 +104,24 @@ class PathLock:except Exception:return None+ def _read_owner_and_type(self, lock_path: str) -> Tuple[Optional[str], Optional[str]]:+ token = self._read_token(lock_path)+ if token is None:+ return None, None+ owner_id, _, lock_type = _parse_fencing_token(token)+ return owner_id, lock_type++ def is_lock_owned_by(self, lock_path: str, owner_id: str) -> bool:+ current_owner_id, _ = self._read_owner_and_type(lock_path)+ return current_owner_id == owner_id++ def collect_lost_owner_locks(self, owner: LockOwner) -> list[str]:+ lost_paths: list[str] = []+ for lock_path in list(owner.locks):+ if not self.is_lock_owned_by(lock_path, owner.id):+ lost_paths.append(lock_path)+ return lost_paths+async def _is_locked_by_other(self, lock_path: str, owner_id: str) -> bool:token = self._read_token(lock_path)if token is None:@@ -109,13 +135,6 @@ class PathLock:token = _make_fencing_token(owner_id, lock_type)self._agfs.write(lock_path, token.encode("utf-8"))- async def _verify_lock_ownership(self, lock_path: str, owner_id: str) -> bool:- token = self._read_token(lock_path)- if token is None:- return False- lock_owner, _, _ = _parse_fencing_token(token)- return lock_owner == owner_id-async def _owned_lock_type(self, path: str, owner: LockOwner) -> Optional[str]:lock_path = self._get_lock_path(path)if lock_path not in owner.locks:@@ -274,7 +293,7 @@ class PathLock:await asyncio.sleep(_POLL_INTERVAL)continue- if not await self._verify_lock_ownership(lock_path, owner_id):+ if not self.is_lock_owned_by(lock_path, owner_id):logger.debug(f"[POINT] Lock ownership verification failed: {path}")if asyncio.get_running_loop().time() >= deadline:return False@@ -382,7 +401,7 @@ class PathLock:await asyncio.sleep(_POLL_INTERVAL)continue- if not await self._verify_lock_ownership(lock_path, owner_id):+ if not self.is_lock_owned_by(lock_path, owner_id):logger.debug(f"[SUBTREE] Lock ownership verification failed: {path}")if asyncio.get_running_loop().time() >= deadline:return False@@ -439,32 +458,38 @@ class PathLock:logger.debug(f"[MV] Locks acquired: {src_path} -> {dst_parent_path}")return True- async def refresh(self, owner: LockOwner) -> None:+ async def refresh(self, owner: LockOwner) -> LockRefreshResult:"""Rewrite all lock file timestamps to prevent stale cleanup."""+ result = LockRefreshResult()for lock_path in list(owner.locks):- token = self._read_token(lock_path)- if token:- parsed_owner_id, _, lock_type = _parse_fencing_token(token)- if parsed_owner_id == owner.id:- new_token = _make_fencing_token(owner.id, lock_type)- try:- self._agfs.write(lock_path, new_token.encode("utf-8"))- except Exception as e:- logger.warning(f"Failed to refresh lock {lock_path}: {e}")+ parsed_owner_id, lock_type = self._read_owner_and_type(lock_path)+ if parsed_owner_id != owner.id or lock_type is None:+ result.lost_paths.append(lock_path)+ continue+ new_token = _make_fencing_token(owner.id, lock_type)+ try:+ self._agfs.write(lock_path, new_token.encode("utf-8"))+ result.refreshed_paths.append(lock_path)+ except Exception as e:+ logger.warning(f"Failed to refresh lock {lock_path}: {e}")+ result.failed_paths.append(lock_path)+ return resultasync def release(self, owner: LockOwner) -> None:lock_count = len(owner.locks)- for lock_path in reversed(owner.locks):- await self._remove_lock_file(lock_path)+ released_count = 0+ for lock_path in reversed(list(owner.locks)):+ if self.is_lock_owned_by(lock_path, owner.id):+ await self._remove_lock_file(lock_path)+ released_count += 1owner.remove_lock(lock_path)- logger.debug(f"Released {lock_count} locks for owner {owner.id}")+ logger.debug(f"Released {released_count}/{lock_count} locks for owner {owner.id}")async def release_selected(self, owner: LockOwner, lock_paths: list[str]) -> None:for lock_path in reversed(lock_paths):if lock_path not in owner.locks:continue- if not await self._verify_lock_ownership(lock_path, owner.id):- continue- await self._remove_lock_file(lock_path)+ if self.is_lock_owned_by(lock_path, owner.id):+ await self._remove_lock_file(lock_path)owner.remove_lock(lock_path)diff --git a/openviking_cli/utils/config/transaction_config.py b/openviking_cli/utils/config/transaction_config.pyindex 262758a1a..3e394f7f9 100644--- a/openviking_cli/utils/config/transaction_config.py+++ b/openviking_cli/utils/config/transaction_config.py@@ -24,8 +24,8 @@ class TransactionConfig(BaseModel):lock_expire: float = Field(default=300.0,description=(- "Stale lock expiry threshold (seconds). "- "Locks held longer than this by a crashed process are force-released."+ "Lock inactivity threshold (seconds). "+ "Locks not refreshed within this window are treated as stale and reclaimed."),)diff --git a/tests/storage/test_lock_observer.py b/tests/storage/test_lock_observer.pynew file mode 100644index 000000000..84580886d--- /dev/null+++ b/tests/storage/test_lock_observer.py@@ -0,0 +1,51 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Tests for lock observer activity tracking."""++from unittest.mock import MagicMock++from openviking.storage.observers.lock_observer import LockObserver+from openviking.storage.transaction.lock_handle import LockHandle+++def _make_handle(handle_id: str, created_at: float, last_active_at: float) -> LockHandle:+ handle = LockHandle(id=handle_id)+ handle.created_at = created_at+ handle.last_active_at = last_active_at+ handle.add_lock(f"/local/{handle_id}/.path.ovlock")+ return handle+++def test_get_hanging_locks_uses_idle_time(monkeypatch):+ active_handle = _make_handle("active", created_at=0.0, last_active_at=900.0)+ stale_handle = _make_handle("stale", created_at=0.0, last_active_at=100.0)++ manager = MagicMock()+ manager.get_active_handles.return_value = {+ active_handle.id: active_handle,+ stale_handle.id: stale_handle,+ }++ monkeypatch.setattr("openviking.storage.observers.lock_observer.time.time", lambda: 1000.0)++ observer = LockObserver(manager)+ active_locks = observer.get_active_locks()+ active_info = next(lock for lock in active_locks if lock["id"] == active_handle.id)++ assert active_info["duration_seconds"] == 1000.0+ assert active_info["idle_seconds"] == 100.0+ assert [lock["id"] for lock in observer.get_hanging_locks(600)] == [stale_handle.id]+++def test_health_checks_ignore_long_running_but_active_lock(monkeypatch):+ active_handle = _make_handle("active", created_at=0.0, last_active_at=950.0)++ manager = MagicMock()+ manager.get_active_handles.return_value = {active_handle.id: active_handle}++ monkeypatch.setattr("openviking.storage.observers.lock_observer.time.time", lambda: 1000.0)++ observer = LockObserver(manager)++ assert observer.is_healthy() is True+ assert observer.has_errors() is Falsediff --git a/tests/transaction/test_lock_manager_staleness.py b/tests/transaction/test_lock_manager_staleness.pynew file mode 100644index 000000000..d9e588a9d--- /dev/null+++ b/tests/transaction/test_lock_manager_staleness.py@@ -0,0 +1,77 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Unit tests for LockManager staleness tracking."""++from unittest.mock import AsyncMock, MagicMock++from openviking.storage.transaction.lock_manager import LockManager+from openviking.storage.transaction.path_lock import LockRefreshResult+++async def test_refresh_lock_updates_last_active_without_changing_created_at(monkeypatch):+ lm = LockManager(agfs=MagicMock(), lock_expire=300.0)+ handle = lm.create_handle()+ handle.created_at = 100.0+ handle.last_active_at = 100.0+ handle.add_lock("/local/tx/.path.ovlock")+ lm._path_lock.collect_lost_owner_locks = lambda owner: []+ lm._path_lock.refresh = AsyncMock(+ return_value=LockRefreshResult(refreshed_paths=["/local/tx/.path.ovlock"])+ )++ monkeypatch.setattr("openviking.storage.transaction.lock_manager.time.time", lambda: 250.0)++ await lm.refresh_lock(handle)++ lm._path_lock.refresh.assert_awaited_once_with(handle)+ assert handle.created_at == 100.0+ assert handle.last_active_at == 250.0+++async def test_stale_cleanup_releases_only_inactive_handles(monkeypatch):+ lm = LockManager(agfs=MagicMock(), lock_expire=300.0)++ active_handle = lm.create_handle()+ active_handle.created_at = 0.0+ active_handle.last_active_at = 200.0+ active_handle.add_lock("/local/active/.path.ovlock")++ stale_handle = lm.create_handle()+ stale_handle.created_at = 0.0+ stale_handle.last_active_at = 0.0+ stale_handle.add_lock("/local/stale/.path.ovlock")++ unlocked_handle = lm.create_handle()+ unlocked_handle.created_at = 0.0+ unlocked_handle.last_active_at = 0.0++ released = []++ async def fake_sleep(_seconds):+ lm._running = False++ async def fake_release(handle):+ released.append(handle.id)+ lm._handles.pop(handle.id, None)++ monkeypatch.setattr("openviking.storage.transaction.lock_manager.asyncio.sleep", fake_sleep)+ monkeypatch.setattr("openviking.storage.transaction.lock_manager.time.time", lambda: 400.0)+ monkeypatch.setattr(lm, "release", fake_release)+ lm._path_lock.collect_lost_owner_locks = lambda owner: []++ lm._running = True+ await lm._stale_cleanup_loop()++ assert released == [stale_handle.id]+ assert active_handle.id in lm.get_active_handles()+ assert unlocked_handle.id not in lm.get_active_handles()+++def test_get_handle_returns_none_when_lock_ownership_is_lost():+ lm = LockManager(agfs=MagicMock(), lock_expire=300.0)+ handle = lm.create_handle()+ handle.add_lock("/local/stale/.path.ovlock")+ lm._path_lock.collect_lost_owner_locks = lambda owner: list(owner.locks)++ assert lm.get_handle(handle.id) is None+ assert handle.id not in lm.get_active_handles()diff --git a/tests/transaction/test_path_lock.py b/tests/transaction/test_path_lock.pyindex fb3e59709..6de9b134d 100644--- a/tests/transaction/test_path_lock.py+++ b/tests/transaction/test_path_lock.py@@ -3,7 +3,7 @@"""Tests for path lock with fencing tokens."""import time-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockfrom openviking.storage.transaction.lock_handle import LockHandlefrom openviking.storage.transaction.path_lock import (@@ -73,6 +73,67 @@ class TestPathLockStale:assert lock.is_lock_stale("/test/.path.ovlock", expire_seconds=300.0) is False+class TestPathLockOwnership:+ async def test_refresh_reports_refreshed_lost_and_failed_paths(self):+ owned_path = "/locks/owned/.path.ovlock"+ lost_path = "/locks/lost/.path.ovlock"+ missing_path = "/locks/missing/.path.ovlock"+ failed_path = "/locks/failed/.path.ovlock"++ tokens = {+ owned_path: _make_fencing_token("tx-1", LOCK_TYPE_POINT),+ lost_path: _make_fencing_token("tx-2", LOCK_TYPE_SUBTREE),+ failed_path: _make_fencing_token("tx-1", LOCK_TYPE_SUBTREE),+ }+ agfs = MagicMock()++ def read_side_effect(lock_path):+ if lock_path == missing_path:+ raise FileNotFoundError(lock_path)+ return tokens[lock_path].encode("utf-8")++ def write_side_effect(lock_path, content):+ if lock_path == failed_path:+ raise OSError("write failed")+ tokens[lock_path] = content.decode("utf-8")++ agfs.read.side_effect = read_side_effect+ agfs.write.side_effect = write_side_effect++ lock = PathLock(agfs)+ tx = LockHandle(id="tx-1")+ for lock_path in [owned_path, lost_path, missing_path, failed_path]:+ tx.add_lock(lock_path)++ result = await lock.refresh(tx)++ assert result.refreshed_paths == [owned_path]+ assert set(result.lost_paths) == {lost_path, missing_path}+ assert result.failed_paths == [failed_path]++ async def test_release_skips_locks_no_longer_owned(self):+ owned_path = "/locks/owned/.path.ovlock"+ replaced_path = "/locks/replaced/.path.ovlock"++ tokens = {+ owned_path: _make_fencing_token("tx-1", LOCK_TYPE_POINT),+ replaced_path: _make_fencing_token("tx-2", LOCK_TYPE_POINT),+ }+ agfs = MagicMock()+ agfs.read.side_effect = lambda lock_path: tokens[lock_path].encode("utf-8")++ lock = PathLock(agfs)+ lock._remove_lock_file = AsyncMock(return_value=True)+ tx = LockHandle(id="tx-1")+ tx.add_lock(owned_path)+ tx.add_lock(replaced_path)++ await lock.release(tx)++ lock._remove_lock_file.assert_awaited_once_with(owned_path)+ assert tx.locks == []++class TestPathLockBehavior:"""Behavioral tests using real AGFS backend."""