Skip to content

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

fix: reindex lock acquisition fails when URI targets a file (Not a directory error) (#2228)

Matt Van Horn35acbc703bc1
diff --git a/openviking/storage/transaction/path_lock.py b/openviking/storage/transaction/path_lock.py
index 8883323a0..78a5f84da 100644
--- a/openviking/storage/transaction/path_lock.py
+++ b/openviking/storage/transaction/path_lock.py
@@ -94,6 +94,13 @@ class PathLockEngine:
return stat.get("isDir") is True
return getattr(stat, "isDir", None) is True
+ async def _is_existing_path_async(self, path: str) -> bool:
+ try:
+ await self._async_agfs.stat(path.rstrip("/") or "/")
+ return True
+ except Exception:
+ return False
+
def _get_prefixed_exact_lock_path(self, path: str) -> str:
path = path.rstrip("/") or "/"
parent = self._get_parent_path(path)
@@ -402,9 +409,13 @@ class PathLockEngine:
async def _scan_descendants_for_locks(self, path: str, exclude_owner_id: str) -> Optional[str]:
try:
try:
- await self._async_agfs.stat(path)
+ stat = await self._async_agfs.stat(path)
except Exception:
return None
+ if isinstance(stat, dict) and not stat.get("isDir", False):
+ return None
+ if not isinstance(stat, dict) and getattr(stat, "isDir", None) is not True:
+ return None
entries = await self._async_agfs.ls(path)
if not isinstance(entries, list):
return None
@@ -600,8 +611,12 @@ class PathLockEngine:
self, path: str, owner: LockOwner, timeout: Optional[float] = 0.0
) -> bool:
owner_id = owner.id
- lock_path = self._get_lock_path(path)
- owned_lock_type = await self._owned_lock_type(path, owner)
+ default_lock_path = self._get_lock_path(path)
+ lock_path = await self._get_exact_lock_path_async(path)
+ if lock_path != default_lock_path and not await self._is_existing_path_async(path):
+ lock_path = default_lock_path
+
+ owned_lock_type = await self._owned_lock_type_for_lock_path(lock_path, owner)
if owned_lock_type == LOCK_TYPE_TREE:
owner.add_lock(lock_path)
logger.debug(f"[TREE] Reusing owned TREE lock on: {path}")
diff --git a/tests/service/test_reindex_file_lock.py b/tests/service/test_reindex_file_lock.py
new file mode 100644
index 000000000..48f824e57
--- /dev/null
+++ b/tests/service/test_reindex_file_lock.py
@@ -0,0 +1,76 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Regression tests for reindexing single-file URIs under tree locks."""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+from openviking.server.identity import RequestContext, Role
+from openviking.service import reindex_executor as reindex_module
+from openviking.service.reindex_executor import ReindexExecutor
+from openviking.storage.transaction import init_lock_manager, release_all_locks, reset_lock_manager
+from openviking_cli.session.user_id import UserIdentifier
+
+
+class _FakeVikingFS:
+ def __init__(self, uri: str, path: str):
+ self._uri = uri
+ self._path = path
+
+ def _uri_to_path(self, uri: str, ctx=None):
+ assert uri == self._uri
+ return self._path
+
+ async def exists(self, uri: str, ctx=None):
+ return uri == self._uri
+
+ async def stat(self, uri: str, ctx=None):
+ assert uri == self._uri
+ return {"isDir": False}
+
+ async def read_file(self, uri: str, ctx=None):
+ assert uri == self._uri
+ return "# Profile\nSingle file reindex source.\n"
+
+
+async def test_reindex_single_file_uri_acquires_tree_lock_without_not_a_directory(
+ agfs_client, test_dir, monkeypatch, caplog
+):
+ uri = "viking://resources/profile.md"
+ path = f"{test_dir}/profile.md"
+ agfs_client.write(path, b"# Profile\nSingle file reindex source.\n")
+ init_lock_manager(agfs_client)
+
+ viking_fs = _FakeVikingFS(uri, path)
+ service = SimpleNamespace(
+ viking_fs=viking_fs,
+ vikingdb_manager=SimpleNamespace(has_queue_manager=True),
+ )
+ monkeypatch.setattr(reindex_module, "get_service", lambda: service)
+ monkeypatch.setattr(reindex_module, "get_viking_fs", lambda: viking_fs)
+
+ executor = ReindexExecutor()
+ executor._fetch_existing_record = AsyncMock(return_value=None)
+ executor._upsert_context = AsyncMock()
+ ctx = RequestContext(
+ user=UserIdentifier("acc1", "test_user", "test_agent"),
+ role=Role.ROOT,
+ )
+
+ try:
+ result = await executor._run(
+ uri=uri,
+ object_type="resource",
+ mode="vectors_only",
+ ctx=ctx,
+ )
+ finally:
+ await release_all_locks()
+ reset_lock_manager()
+
+ assert result["status"] == "completed"
+ assert result["uri"] == uri
+ assert result["scanned_records"] == 1
+ assert result["rebuilt_records"] == 1
+ assert "Not a directory" not in caplog.text
+ assert "Failed to create lock file" not in caplog.text
diff --git a/tests/transaction/test_path_lock.py b/tests/transaction/test_path_lock.py
index d04937608..dffb9c3fd 100644
--- a/tests/transaction/test_path_lock.py
+++ b/tests/transaction/test_path_lock.py
@@ -241,6 +241,67 @@ class TestPathLockBehavior:
await lock.release(tx)
+ async def test_acquire_tree_existing_file_uses_parent_sidecar_lock(self, agfs_client, test_dir):
+ lock = PathLockEngine(agfs_client)
+ tx = LockHandle(id="tx-tree-file")
+ file_path = f"{test_dir}/profile.md"
+ agfs_client.write(file_path, b"# Profile\n")
+
+ ok = await lock.acquire_tree(file_path, tx, timeout=3.0)
+ assert ok is True
+
+ lock_path = _single_lock_path(tx)
+ assert lock_path.startswith(f"{test_dir}/{EXACT_LOCK_FILE_PREFIX}profile.md.")
+ assert lock_path != f"{file_path}/{LOCK_FILE_NAME}"
+ content = agfs_client.cat(lock_path)
+ token = content.decode("utf-8") if isinstance(content, bytes) else content
+ assert ":T" in token
+ assert "tx-tree-file" in token
+
+ await lock.release(tx)
+ try:
+ agfs_client.stat(lock_path)
+ raise AssertionError("file tree lock should have been removed")
+ except AssertionError:
+ raise
+ except Exception:
+ pass
+
+ async def test_acquire_tree_existing_file_sidecar_sanitizes_name(self, agfs_client, test_dir):
+ lock = PathLockEngine(agfs_client)
+ tx = LockHandle(id="tx-tree-file-special")
+ file_path = f"{test_dir}/profile with spaces \u4e2d.md"
+ agfs_client.write(file_path, b"# Profile\n")
+
+ ok = await lock.acquire_tree(file_path, tx, timeout=3.0)
+ assert ok is True
+
+ lock_path = _single_lock_path(tx)
+ assert lock_path.startswith(f"{test_dir}/{EXACT_LOCK_FILE_PREFIX}profile_with_spaces")
+ assert lock_path.endswith(lock._get_prefixed_exact_lock_path(file_path).rsplit(".", 1)[-1])
+ content = agfs_client.cat(lock_path)
+ token = content.decode("utf-8") if isinstance(content, bytes) else content
+ assert ":T" in token
+
+ await lock.release(tx)
+
+ async def test_acquire_tree_existing_file_blocks_second_owner_until_release(
+ self, agfs_client, test_dir
+ ):
+ lock = PathLockEngine(agfs_client)
+ tx1 = LockHandle(id="tx-tree-file-hold")
+ tx2 = LockHandle(id="tx-tree-file-wait")
+ file_path = f"{test_dir}/blocked.md"
+ agfs_client.write(file_path, b"# Blocked\n")
+
+ assert await lock.acquire_tree(file_path, tx1, timeout=3.0) is True
+ assert await lock.acquire_tree(file_path, tx2, timeout=0.0) is False
+
+ await lock.release(tx1)
+
+ assert await lock.acquire_tree(file_path, tx2, timeout=3.0) is True
+ await lock.release(tx2)
+
async def test_acquire_tree_creates_missing_directory_after_conflict_check(
self, agfs_client, test_dir
):