Skip to content

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

refactor(storage): 异步化存储锁与 IO (#2143)

Qin Haojie2406c0e6e1d2
diff --git a/openviking/parse/parsers/upload_utils.py b/openviking/parse/parsers/upload_utils.py
index ce746eb5a..7a61e82e2 100644
--- a/openviking/parse/parsers/upload_utils.py
+++ b/openviking/parse/parsers/upload_utils.py
@@ -273,31 +273,22 @@ async def upload_directory(
parent_uris.add(target_uri.rsplit("/", 1)[0])
# --- Phase 2: Pre-create all directories ---
- # Memoized mkdir: each unique agfs path is created at most once.
+ # Memoized mkdir: each unique VikingFS path is created at most once.
# This is equivalent to _ensure_parent_dirs but avoids redundant HTTP calls
# by tracking already-processed paths across all directories.
_created: Set[str] = set()
- def _mkdir_with_parents(agfs_path: str) -> None:
- parts = agfs_path.lstrip("/").split("/")
- for i in range(1, len(parts) + 1):
- p = "/" + "/".join(parts[:i])
- if p in _created:
- continue
- try:
- viking_fs.agfs.mkdir(p)
- _created.add(p)
- except Exception as e:
- if "already" in str(e).lower():
- _created.add(p)
- else:
- logger.warning(f"Failed to create directory {p}: {e}")
-
- def _create_all_dirs() -> None:
- for dir_uri in sorted(parent_uris):
- _mkdir_with_parents(viking_fs._uri_to_path(dir_uri))
-
- await asyncio.to_thread(_create_all_dirs)
+ for dir_uri in sorted(parent_uris):
+ if dir_uri in _created:
+ continue
+ try:
+ await viking_fs.mkdir(dir_uri, exist_ok=True)
+ _created.add(dir_uri)
+ except Exception as e:
+ if "already" in str(e).lower():
+ _created.add(dir_uri)
+ else:
+ logger.warning(f"Failed to create directory {dir_uri}: {e}")
# --- Phase 3: Upload files concurrently ---
sem = asyncio.Semaphore(_UPLOAD_CONCURRENCY)
diff --git a/openviking/pyagfs/__init__.py b/openviking/pyagfs/__init__.py
index 033dcd764..989153083 100644
--- a/openviking/pyagfs/__init__.py
+++ b/openviking/pyagfs/__init__.py
@@ -10,6 +10,7 @@ import sys
import sysconfig
from pathlib import Path
+from .async_client import AsyncAGFSClient
from .client import AGFSClient, FileHandle
from .exceptions import (
AGFSAlreadyExistsError,
@@ -146,6 +147,7 @@ except Exception:
__all__ = [
"AGFSClient",
+ "AsyncAGFSClient",
"AGFSBindingClient",
"RAGFSBindingClient",
"FileHandle",
diff --git a/openviking/pyagfs/async_client.py b/openviking/pyagfs/async_client.py
new file mode 100644
index 000000000..57423db87
--- /dev/null
+++ b/openviking/pyagfs/async_client.py
@@ -0,0 +1,90 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Async adapter for the synchronous AGFS client."""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Iterator
+from typing import Any, BinaryIO, Dict, List, Union
+
+
+class AsyncAGFSClient:
+ """Run blocking AGFS client operations off the event loop.
+
+ This is intentionally a thin adapter over the existing synchronous client.
+ If AGFS later provides native async methods, they can be swapped in here
+ without changing storage and transaction call sites.
+ """
+
+ def __init__(self, client: Any):
+ self._client = client
+
+ @property
+ def sync_client(self) -> Any:
+ return self._client
+
+ async def run(self, method_name: str, /, *args: Any, **kwargs: Any) -> Any:
+ return await asyncio.to_thread(getattr(self._client, method_name), *args, **kwargs)
+
+ async def ls(self, path: str = "/") -> List[Dict[str, Any]]:
+ return await self.run("ls", path)
+
+ async def read(self, path: str, offset: int = 0, size: int = -1, stream: bool = False) -> Any:
+ kwargs: Dict[str, Any] = {}
+ if offset != 0:
+ kwargs["offset"] = offset
+ if size != -1:
+ kwargs["size"] = size
+ if stream:
+ kwargs["stream"] = stream
+ return await self.run("read", path, **kwargs)
+
+ async def cat(self, path: str, offset: int = 0, size: int = -1, stream: bool = False) -> Any:
+ kwargs: Dict[str, Any] = {}
+ if offset != 0:
+ kwargs["offset"] = offset
+ if size != -1:
+ kwargs["size"] = size
+ if stream:
+ kwargs["stream"] = stream
+ return await self.run("cat", path, **kwargs)
+
+ async def write(
+ self, path: str, data: Union[bytes, Iterator[bytes], BinaryIO], max_retries: int = 3
+ ) -> str:
+ if max_retries == 3:
+ return await self.run("write", path, data)
+ return await self.run("write", path, data, max_retries=max_retries)
+
+ async def mkdir(self, path: str, mode: str = "755") -> Dict[str, Any]:
+ if mode == "755":
+ return await self.run("mkdir", path)
+ return await self.run("mkdir", path, mode=mode)
+
+ async def ensure_parent_dirs(self, path: str, mode: str = "755") -> Dict[str, Any]:
+ if mode == "755":
+ return await self.run("ensure_parent_dirs", path)
+ return await self.run("ensure_parent_dirs", path, mode=mode)
+
+ async def rm(self, path: str, recursive: bool = False, force: bool = True) -> Dict[str, Any]:
+ kwargs: Dict[str, Any] = {}
+ if recursive:
+ kwargs["recursive"] = recursive
+ if not force:
+ kwargs["force"] = force
+ return await self.run("rm", path, **kwargs)
+
+ async def stat(self, path: str) -> Dict[str, Any]:
+ return await self.run("stat", path)
+
+ async def mv(self, old_path: str, new_path: str) -> Dict[str, Any]:
+ return await self.run("mv", old_path, new_path)
+
+ async def cp(self, src_path: str, dst_path: str, recursive: bool = False) -> Any:
+ from .helpers import cp
+
+ return await asyncio.to_thread(cp, self._client, src_path, dst_path, recursive=recursive)
+
+ async def grep(self, **kwargs: Any) -> Dict[str, Any]:
+ return await self.run("grep", **kwargs)
diff --git a/openviking/server/api_keys/legacy.py b/openviking/server/api_keys/legacy.py
index 681e7376f..caca99fd2 100644
--- a/openviking/server/api_keys/legacy.py
+++ b/openviking/server/api_keys/legacy.py
@@ -13,6 +13,7 @@ from typing import Dict, Optional
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
+from openviking.pyagfs import AsyncAGFSClient
from openviking.server.api_keys.models import AccountInfo, UserKeyEntry
from openviking.server.identity import AccountNamespacePolicy, ResolvedIdentity, Role
from openviking.storage.viking_fs import VikingFS
@@ -64,6 +65,7 @@ class LegacyAPIKeyManager:
"""
self._root_key = root_key
self._viking_fs = viking_fs
+ self._async_agfs = AsyncAGFSClient(viking_fs.agfs)
self._api_key_hashing_enabled = api_key_hashing_enabled
self._accounts: Dict[str, AccountInfo] = {}
# Prefix index: key_prefix -> list[UserKeyEntry]
@@ -632,8 +634,7 @@ class LegacyAPIKeyManager:
async def _read_json(self, path: str) -> Optional[dict]:
"""Read a JSON file from AGFS with encryption support. Returns None if not found."""
try:
- # Read file directly using AGFS
- content = self._viking_fs.agfs.read(path)
+ content = await self._async_agfs.read(path)
if isinstance(content, bytes):
raw = content
else:
@@ -662,12 +663,10 @@ class LegacyAPIKeyManager:
account_id = parts[2] if len(parts) >= 3 else "default"
content = await self._viking_fs.encrypt_bytes(account_id, content)
- # Ensure parent directories exist
- self._ensure_parent_dirs(path)
- # Write file directly using AGFS
- self._viking_fs.agfs.write(path, content)
+ await self._ensure_parent_dirs_async(path)
+ await self._async_agfs.write(path, content)
- def _ensure_parent_dirs(self, path: str) -> None:
+ async def _ensure_parent_dirs_async(self, path: str) -> None:
"""Recursively create all parent directories for a file path."""
# Handle direct AGFS paths
if path.startswith("/local/"):
@@ -678,7 +677,7 @@ class LegacyAPIKeyManager:
for i in range(1, len(parts)):
parent = "/" + "/".join(parts[:i])
try:
- self._viking_fs.agfs.mkdir(parent)
+ await self._async_agfs.mkdir(parent)
except Exception:
pass
diff --git a/openviking/server/api_keys/new.py b/openviking/server/api_keys/new.py
index 426c19e35..bb99dda9b 100644
--- a/openviking/server/api_keys/new.py
+++ b/openviking/server/api_keys/new.py
@@ -453,8 +453,8 @@ class NewAPIKeyManager:
async def _write_json(self, path: str, data: dict) -> None:
return await self._legacy._write_json(path, data)
- def _ensure_parent_dirs(self, path: str) -> None:
- return self._legacy._ensure_parent_dirs(path)
+ async def _ensure_parent_dirs_async(self, path: str) -> None:
+ return await self._legacy._ensure_parent_dirs_async(path)
async def _save_accounts_json(self) -> None:
return await self._legacy._save_accounts_json()
diff --git a/openviking/server/routers/tasks.py b/openviking/server/routers/tasks.py
index f712bd8a9..e197c62c0 100644
--- a/openviking/server/routers/tasks.py
+++ b/openviking/server/routers/tasks.py
@@ -27,7 +27,7 @@ async def get_task(
):
"""Get the status of a single background task."""
tracker = get_task_tracker()
- task = tracker.get(
+ task = await tracker.get(
task_id,
account_id=_ctx.account_id,
user_id=_ctx.user.user_id,
@@ -53,7 +53,7 @@ async def list_tasks(
):
"""List background tasks with optional filters."""
tracker = get_task_tracker()
- tasks = tracker.list_tasks(
+ tasks = await tracker.list_tasks(
task_type=task_type,
status=status,
resource_id=resource_id,
diff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.py
index eb89e1e95..1ec209968 100644
--- a/openviking/service/reindex_executor.py
+++ b/openviking/service/reindex_executor.py
@@ -100,7 +100,7 @@ class ReindexExecutor:
tracker = get_task_tracker()
if wait:
- if tracker.has_running(
+ if await tracker.has_running(
REINDEX_TASK_TYPE,
uri,
account_id=ctx.account_id,
@@ -118,7 +118,7 @@ class ReindexExecutor:
ctx=ctx,
)
- task = tracker.create_if_no_running(
+ task = await tracker.create_if_no_running(
REINDEX_TASK_TYPE,
uri,
account_id=ctx.account_id,
@@ -447,7 +447,7 @@ class ReindexExecutor:
ctx: RequestContext,
) -> None:
tracker = get_task_tracker()
- tracker.start(task_id, account_id=ctx.account_id, user_id=ctx.user.user_id)
+ await tracker.start(task_id, account_id=ctx.account_id, user_id=ctx.user.user_id)
try:
result = await self._run(
uri=uri,
@@ -455,9 +455,19 @@ class ReindexExecutor:
mode=mode,
ctx=ctx,
)
- tracker.complete(task_id, result, account_id=ctx.account_id, user_id=ctx.user.user_id)
+ await tracker.complete(
+ task_id,
+ result,
+ account_id=ctx.account_id,
+ user_id=ctx.user.user_id,
+ )
except Exception as exc:
- tracker.fail(task_id, str(exc), account_id=ctx.account_id, user_id=ctx.user.user_id)
+ await tracker.fail(
+ task_id,
+ str(exc),
+ account_id=ctx.account_id,
+ user_id=ctx.user.user_id,
+ )
async def _reindex_resource(
self,
@@ -1088,8 +1098,7 @@ class ReindexExecutor:
for file_uri in file_uris:
counters.scanned_records += 1
body = await self._safe_read_text(file_uri, ctx=ctx)
- mf = MemoryFileUtils.read(body) if body else MemoryFile()
- memory_content = mf.content
+ memory_content = MemoryFileUtils.read(body).content if body else ""
existing = await self._fetch_existing_record(uri=file_uri, level=2, ctx=ctx)
abstract = self._best_non_empty(
self._record_abstract(existing),
diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.py
index 8511ee6ed..90256ded7 100644
--- a/openviking/service/resource_service.py
+++ b/openviking/service/resource_service.py
@@ -292,7 +292,7 @@ class ResourceService:
task_tracker = get_task_tracker()
root_uri = result.get("root_uri", "")
- task = task_tracker.create(
+ task = await task_tracker.create(
"add_resource",
resource_id=root_uri,
account_id=ctx.account_id,
@@ -310,10 +310,10 @@ class ResourceService:
)
)
else:
- task_tracker.start(
+ await task_tracker.start(
task.task_id, account_id=ctx.account_id, user_id=ctx.user.user_id
)
- task_tracker.complete(
+ await task_tracker.complete(
task.task_id,
{"root_uri": root_uri},
account_id=ctx.account_id,
@@ -347,27 +347,27 @@ class ResourceService:
task_tracker = get_task_tracker()
request_wait_tracker = get_request_wait_tracker()
- task_tracker.start(task_id, account_id=account_id, user_id=user_id)
+ await task_tracker.start(task_id, account_id=account_id, user_id=user_id)
try:
await request_wait_tracker.wait_for_request(telemetry_id)
status = request_wait_tracker.build_queue_status(telemetry_id)
errors = sum(int(group.get("error_count", 0) or 0) for group in status.values())
if errors:
- task_tracker.fail(
+ await task_tracker.fail(
task_id,
f"queue processing failed: {status}",
account_id=account_id,
user_id=user_id,
)
else:
- task_tracker.complete(
+ await task_tracker.complete(
task_id,
{"queue_status": status},
account_id=account_id,
user_id=user_id,
)
except Exception as exc:
- task_tracker.fail(task_id, str(exc), account_id=account_id, user_id=user_id)
+ await task_tracker.fail(task_id, str(exc), account_id=account_id, user_id=user_id)
finally:
request_wait_tracker.cleanup(telemetry_id)
unregister_wait_telemetry(telemetry_id)
@@ -546,7 +546,7 @@ class ResourceService:
from openviking.service.task_tracker import get_task_tracker
task_tracker = get_task_tracker()
- task = task_tracker.create(
+ task = await task_tracker.create(
"add_skill",
account_id=ctx.account_id,
user_id=ctx.user.user_id,
@@ -563,10 +563,10 @@ class ResourceService:
)
)
else:
- task_tracker.start(
+ await task_tracker.start(
task.task_id, account_id=ctx.account_id, user_id=ctx.user.user_id
)
- task_tracker.complete(
+ await task_tracker.complete(
task.task_id,
{},
account_id=ctx.account_id,
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.py
index c7d004a00..4e1e41c2b 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -259,7 +259,7 @@ class SessionService:
async def get_commit_task(self, task_id: str, ctx: RequestContext) -> Optional[Dict[str, Any]]:
"""Query background commit task status by task_id for the calling owner."""
- task = get_task_tracker().get(
+ task = await get_task_tracker().get(
task_id,
account_id=ctx.account_id,
user_id=ctx.user.user_id,
diff --git a/openviking/service/task_store.py b/openviking/service/task_store.py
index 770bbd026..770e9c8d5 100644
--- a/openviking/service/task_store.py
+++ b/openviking/service/task_store.py
@@ -8,15 +8,16 @@ import json
from copy import deepcopy
from typing import Any, Dict, List, Optional, Protocol
+from openviking.pyagfs import AsyncAGFSClient
from openviking.pyagfs.exceptions import AGFSAlreadyExistsError
class TaskStore(Protocol):
- def create(self, task: Any) -> None: ...
+ async def create(self, task: Any) -> None: ...
- def update(self, task: Any) -> None: ...
+ async def update(self, task: Any) -> None: ...
- def get(
+ async def get(
self,
task_id: str,
*,
@@ -24,9 +25,13 @@ class TaskStore(Protocol):
user_id: Optional[str] = None,
) -> Optional[Dict[str, Any]]: ...
- def list(self, account_id: str, *, user_id: Optional[str] = None) -> List[Dict[str, Any]]: ...
+ async def list(
+ self, account_id: str, *, user_id: Optional[str] = None
+ ) -> List[Dict[str, Any]]: ...
- def delete(self, task_id: str, *, account_id: str, user_id: Optional[str] = None) -> None: ...
+ async def delete(
+ self, task_id: str, *, account_id: str, user_id: Optional[str] = None
+ ) -> None: ...
class InMemoryTaskStore:
@@ -35,13 +40,13 @@ class InMemoryTaskStore:
def __init__(self) -> None:
self._tasks: Dict[str, Dict[str, Any]] = {}
- def create(self, task: Any) -> None:
+ async def create(self, task: Any) -> None:
self._tasks[task.task_id] = _task_to_payload(task)
- def update(self, task: Any) -> None:
+ async def update(self, task: Any) -> None:
self._tasks[task.task_id] = _task_to_payload(task)
- def get(
+ async def get(
self,
task_id: str,
*,
@@ -57,7 +62,7 @@ class InMemoryTaskStore:
return None
return deepcopy(payload)
- def list(self, account_id: str, *, user_id: Optional[str] = None) -> List[Dict[str, Any]]:
+ async def list(self, account_id: str, *, user_id: Optional[str] = None) -> List[Dict[str, Any]]:
return [
deepcopy(payload)
for payload in self._tasks.values()
@@ -65,7 +70,7 @@ class InMemoryTaskStore:
and (user_id is None or payload.get("user_id") == user_id)
]
- def delete(self, task_id: str, *, account_id: str, user_id: Optional[str] = None) -> None:
+ async def delete(self, task_id: str, *, account_id: str, user_id: Optional[str] = None) -> None:
payload = self._tasks.get(task_id)
if (
payload
@@ -82,15 +87,15 @@ class PersistentTaskStore:
RESERVED_DIRNAME = "tasks"
def __init__(self, agfs: Any) -> None:
- self._agfs = agfs
+ self._agfs = agfs if isinstance(agfs, AsyncAGFSClient) else AsyncAGFSClient(agfs)
- def create(self, task: Any) -> None:
- self._write_task(task)
+ async def create(self, task: Any) -> None:
+ await self._write_task(task)
- def update(self, task: Any) -> None:
- self._write_task(task)
+ async def update(self, task: Any) -> None:
+ await self._write_task(task)
- def get(
+ async def get(
self,
task_id: str,
*,
@@ -101,17 +106,17 @@ class PersistentTaskStore:
return None
path = self._task_path(account_id, user_id, task_id)
try:
- raw = self._agfs.read(path)
+ raw = await self._agfs.read(path)
except Exception:
return None
return json.loads(_decode_bytes(raw))
- def list(self, account_id: str, *, user_id: Optional[str] = None) -> List[Dict[str, Any]]:
+ async def list(self, account_id: str, *, user_id: Optional[str] = None) -> List[Dict[str, Any]]:
if not user_id:
return []
directory = self._task_dir(account_id, user_id)
try:
- items = self._agfs.ls(directory)
+ items = await self._agfs.ls(directory)
except Exception:
return []
tasks: List[Dict[str, Any]] = []
@@ -120,36 +125,36 @@ class PersistentTaskStore:
if not path.endswith(".json"):
continue
try:
- raw = self._agfs.read(path)
+ raw = await self._agfs.read(path)
tasks.append(json.loads(_decode_bytes(raw)))
except Exception:
continue
return tasks
- def delete(self, task_id: str, *, account_id: str, user_id: Optional[str] = None) -> None:
+ async def delete(self, task_id: str, *, account_id: str, user_id: Optional[str] = None) -> None:
if not user_id:
return
- self._agfs.rm(self._task_path(account_id, user_id, task_id), force=True)
+ await self._agfs.rm(self._task_path(account_id, user_id, task_id), force=True)
- def _write_task(self, task: Any) -> None:
+ async def _write_task(self, task: Any) -> None:
account_id = getattr(task, "account_id", None)
user_id = getattr(task, "user_id", None)
if not account_id or not user_id:
raise ValueError("PersistentTaskStore requires account_id and user_id")
- self._ensure_task_dir(account_id, user_id)
- self._agfs.write(
+ await self._ensure_task_dir(account_id, user_id)
+ await self._agfs.write(
self._task_path(account_id, user_id, task.task_id),
json.dumps(_task_to_payload(task), ensure_ascii=False).encode("utf-8"),
)
- def _ensure_task_dir(self, account_id: str, user_id: str) -> None:
- self._mkdir_if_missing(self._account_dir(account_id))
- self._mkdir_if_missing(self._task_root_dir(account_id))
- self._mkdir_if_missing(self._task_dir(account_id, user_id))
+ async def _ensure_task_dir(self, account_id: str, user_id: str) -> None:
+ await self._mkdir_if_missing(self._account_dir(account_id))
+ await self._mkdir_if_missing(self._task_root_dir(account_id))
+ await self._mkdir_if_missing(self._task_dir(account_id, user_id))
- def _mkdir_if_missing(self, path: str) -> None:
+ async def _mkdir_if_missing(self, path: str) -> None:
try:
- self._agfs.mkdir(path)
+ await self._agfs.mkdir(path)
except AGFSAlreadyExistsError:
return
except Exception as exc:
diff --git a/openviking/service/task_tracker.py b/openviking/service/task_tracker.py
index ff65363c5..b4cae3667 100644
--- a/openviking/service/task_tracker.py
+++ b/openviking/service/task_tracker.py
@@ -118,7 +118,8 @@ def _sanitize_error(error: str) -> str:
class TaskTracker:
"""Async task tracker with pluggable storage and in-memory compatibility cache.
- Thread-safe: all mutations go through ``_lock``.
+ Async lifecycle operations are serialized by ``_async_lock``. The thread
+ lock only protects sync snapshot reads of the local cache.
"""
MAX_TASKS = 10_000
@@ -130,6 +131,7 @@ class TaskTracker:
self._store = store or InMemoryTaskStore()
self._tasks: Dict[str, TaskRecord] = {}
self._lock = threading.Lock()
+ self._async_lock = asyncio.Lock()
self._cleanup_task: Optional[asyncio.Task] = None
logger.info(
"[TaskTracker] Initialized (store=%s, max_tasks=%d)",
@@ -160,40 +162,51 @@ class TaskTracker:
while True:
try:
await asyncio.sleep(self.CLEANUP_INTERVAL)
- self._evict_expired()
+ await self._evict_expired()
except asyncio.CancelledError:
break
except Exception:
logger.exception("[TaskTracker] Cleanup error")
- def _evict_expired(self) -> None:
+ async def _evict_expired(self) -> None:
"""Remove expired tasks and enforce MAX_TASKS."""
now = time.time()
- with self._lock:
- to_delete = []
- for tid, t in self._tasks.items():
- if t.status == TaskStatus.COMPLETED and (now - t.updated_at) > self.TTL_COMPLETED:
- to_delete.append(tid)
- elif t.status == TaskStatus.FAILED and (now - t.updated_at) > self.TTL_FAILED:
- to_delete.append(tid)
- for tid in to_delete:
- task = self._tasks[tid]
+ async with self._async_lock:
+ deleted_tasks: List[TaskRecord] = []
+ with self._lock:
+ expired_ids = []
+ for tid, t in self._tasks.items():
+ if (
+ t.status == TaskStatus.COMPLETED
+ and (now - t.updated_at) > self.TTL_COMPLETED
+ ):
+ expired_ids.append(tid)
+ elif t.status == TaskStatus.FAILED and (now - t.updated_at) > self.TTL_FAILED:
+ expired_ids.append(tid)
+
+ for tid in expired_ids:
+ task = self._tasks.pop(tid, None)
+ if task is not None:
+ deleted_tasks.append(task)
+
+ if len(self._tasks) > self.MAX_TASKS:
+ sorted_tasks = sorted(self._tasks.items(), key=lambda x: x[1].created_at)
+ excess = len(self._tasks) - self.MAX_TASKS
+ for tid, _ in sorted_tasks[:excess]:
+ task = self._tasks.pop(tid, None)
+ if task is not None:
+ deleted_tasks.append(task)
+
+ for task in deleted_tasks:
if isinstance(self._store, InMemoryTaskStore) and task.account_id:
- self._store.delete(tid, account_id=task.account_id, user_id=task.user_id)
- del self._tasks[tid]
-
- # FIFO eviction if still over limit
- if len(self._tasks) > self.MAX_TASKS:
- sorted_tasks = sorted(self._tasks.items(), key=lambda x: x[1].created_at)
- excess = len(self._tasks) - self.MAX_TASKS
- for tid, _ in sorted_tasks[:excess]:
- task = self._tasks[tid]
- if isinstance(self._store, InMemoryTaskStore) and task.account_id:
- self._store.delete(tid, account_id=task.account_id, user_id=task.user_id)
- del self._tasks[tid]
-
- if to_delete:
- logger.debug("[TaskTracker] Evicted %d expired tasks", len(to_delete))
+ await self._store.delete(
+ task.task_id,
+ account_id=task.account_id,
+ user_id=task.user_id,
+ )
+
+ if expired_ids:
+ logger.debug("[TaskTracker] Evicted %d expired tasks", len(expired_ids))
@staticmethod
def _matches_owner(
@@ -216,7 +229,7 @@ class TaskTracker:
# ── CRUD ──
- def create(
+ async def create(
self,
task_type: str,
resource_id: Optional[str] = None,
@@ -233,9 +246,10 @@ class TaskTracker:
account_id=account_id,
user_id=user_id,
)
- with self._lock:
- self._tasks[task.task_id] = task
- self._store.create(task)
+ async with self._async_lock:
+ await self._store.create(task)
+ with self._lock:
+ self._tasks[task.task_id] = task
logger.debug(
"[TaskTracker] Created task %s type=%s resource=%s",
task.task_id,
@@ -244,7 +258,7 @@ class TaskTracker:
)
return self._copy(task)
- def create_if_no_running(
+ async def create_if_no_running(
self,
task_type: str,
resource_id: str,
@@ -258,18 +272,22 @@ class TaskTracker:
This eliminates the race condition between has_running() and create().
"""
self._validate_owner(account_id, user_id)
- with self._lock:
- # Check for existing running tasks
+ async with self._async_lock:
+ for task in await self._load_all_from_store(account_id, user_id):
+ with self._lock:
+ self._tasks[task.task_id] = task
+
+ with self._lock:
+ tasks = list(self._tasks.values())
has_active = any(
t.task_type == task_type
and t.resource_id == resource_id
and self._matches_owner(t, account_id, user_id)
and t.status in (TaskStatus.PENDING, TaskStatus.RUNNING)
- for t in self._tasks.values()
+ for t in tasks
)
if has_active:
return None
- # Create atomically within same lock
task = TaskRecord(
task_id=str(uuid4()),
task_type=task_type,
@@ -277,8 +295,9 @@ class TaskTracker:
account_id=account_id,
user_id=user_id,
)
- self._tasks[task.task_id] = task
- self._store.create(task)
+ await self._store.create(task)
+ with self._lock:
+ self._tasks[task.task_id] = task
logger.debug(
"[TaskTracker] Created task %s type=%s resource=%s",
task.task_id,
@@ -287,22 +306,23 @@ class TaskTracker:
)
return self._copy(task)
- def start(
+ async def start(
self,
task_id: str,
account_id: Optional[str] = None,
user_id: Optional[str] = None,
) -> None:
"""Transition task to RUNNING."""
- with self._lock:
- task = self._load_for_update(task_id, account_id, user_id)
+ async with self._async_lock:
+ task = await self._load_for_update(task_id, account_id, user_id)
if task:
task.status = TaskStatus.RUNNING
task.updated_at = time.time()
- self._tasks[task.task_id] = task
- self._store.update(task)
+ await self._store.update(task)
+ with self._lock:
+ self._tasks[task.task_id] = task
- def complete(
+ async def complete(
self,
task_id: str,
result: Optional[Dict[str, Any]] = None,
@@ -310,17 +330,18 @@ class TaskTracker:
user_id: Optional[str] = None,
) -> None:
"""Transition task to COMPLETED with optional result."""
- with self._lock:
- task = self._load_for_update(task_id, account_id, user_id)
+ async with self._async_lock:
+ task = await self._load_for_update(task_id, account_id, user_id)
if task:
task.status = TaskStatus.COMPLETED
task.result = result
task.updated_at = time.time()
- self._tasks[task.task_id] = task
- self._store.update(task)
+ await self._store.update(task)
+ with self._lock:
+ self._tasks[task.task_id] = task
logger.info("[TaskTracker] Task %s completed", task_id)
- def fail(
+ async def fail(
self,
task_id: str,
error: str,
@@ -328,34 +349,37 @@ class TaskTracker:
user_id: Optional[str] = None,
) -> None:
"""Transition task to FAILED with sanitized error."""
- with self._lock:
- task = self._load_for_update(task_id, account_id, user_id)
+ async with self._async_lock:
+ task = await self._load_for_update(task_id, account_id, user_id)
if task:
task.status = TaskStatus.FAILED
task.error = _sanitize_error(error)
task.updated_at = time.time()
- self._tasks[task.task_id] = task
- self._store.update(task)
+ await self._store.update(task)
+ with self._lock:
+ self._tasks[task.task_id] = task
logger.warning("[TaskTracker] Task %s failed: %s", task_id, _sanitize_error(error))
- def get(
+ async def get(
self,
task_id: str,
account_id: Optional[str] = None,
user_id: Optional[str] = None,
) -> Optional[TaskRecord]:
"""Look up a single task. Returns a snapshot copy (None if not found)."""
- with self._lock:
- task = self._tasks.get(task_id)
+ async with self._async_lock:
+ with self._lock:
+ task = self._tasks.get(task_id)
if task is None and account_id is not None:
- task = self._load_from_store(task_id, account_id, user_id)
+ task = await self._load_from_store(task_id, account_id, user_id)
if task is not None:
- self._tasks[task.task_id] = task
+ with self._lock:
+ self._tasks[task.task_id] = task
if task is None or not self._matches_owner(task, account_id, user_id):
return None
return self._copy(task)
- def list_tasks(
+ async def list_tasks(
self,
task_type: Optional[str] = None,
status: Optional[str] = None,
@@ -365,15 +389,16 @@ class TaskTracker:
user_id: Optional[str] = None,
) -> List[TaskRecord]:
"""List tasks with optional filters. Most-recent first. Returns snapshot copies."""
- with self._lock:
+ async with self._async_lock:
if account_id is not None:
- for task in self._load_all_from_store(account_id, user_id):
- self._tasks[task.task_id] = task
- tasks = [
- self._copy(t)
- for t in self._tasks.values()
- if self._matches_owner(t, account_id, user_id)
- ]
+ loaded = await self._load_all_from_store(account_id, user_id)
+ if loaded:
+ with self._lock:
+ for task in loaded:
+ self._tasks[task.task_id] = task
+ with self._lock:
+ source = list(self._tasks.values())
+ tasks = [self._copy(t) for t in source if self._matches_owner(t, account_id, user_id)]
if task_type:
tasks = [t for t in tasks if t.task_type == task_type]
if status:
@@ -383,7 +408,7 @@ class TaskTracker:
tasks.sort(key=lambda t: t.created_at, reverse=True)
return tasks[:limit]
- def has_running(
+ async def has_running(
self,
task_type: str,
resource_id: str,
@@ -391,30 +416,36 @@ class TaskTracker:
user_id: Optional[str] = None,
) -> bool:
"""Check if there is already a running task for the given type+resource."""
- with self._lock:
+ async with self._async_lock:
if account_id is not None:
- for task in self._load_all_from_store(account_id, user_id):
- self._tasks[task.task_id] = task
+ loaded = await self._load_all_from_store(account_id, user_id)
+ if loaded:
+ with self._lock:
+ for task in loaded:
+ self._tasks[task.task_id] = task
+ with self._lock:
+ tasks = list(self._tasks.values())
return any(
t.task_type == task_type
and t.resource_id == resource_id
and self._matches_owner(t, account_id, user_id)
and t.status in (TaskStatus.PENDING, TaskStatus.RUNNING)
- for t in self._tasks.values()
+ for t in tasks
)
- def _load_for_update(
+ async def _load_for_update(
self,
task_id: str,
account_id: Optional[str],
user_id: Optional[str],
) -> Optional[TaskRecord]:
- task = self._tasks.get(task_id)
+ with self._lock:
+ task = self._tasks.get(task_id)
if task is not None:
- return task
+ return task if self._matches_owner(task, account_id, user_id) else None
if account_id is None or user_id is None:
return None
- return self._load_from_store(task_id, account_id, user_id)
+ return await self._load_from_store(task_id, account_id, user_id)
@staticmethod
def _record_from_payload(payload: Dict[str, Any]) -> TaskRecord:
@@ -422,21 +453,23 @@ class TaskTracker:
data["status"] = TaskStatus(data["status"])
return TaskRecord(**data)
- def _load_from_store(
+ async def _load_from_store(
self,
task_id: str,
account_id: str,
user_id: Optional[str],
) -> Optional[TaskRecord]:
- payload = self._store.get(task_id, account_id=account_id, user_id=user_id)
+ payload = await self._store.get(task_id, account_id=account_id, user_id=user_id)
if payload is None:
return None
return self._record_from_payload(payload)
- def _load_all_from_store(self, account_id: str, user_id: Optional[str]) -> List[TaskRecord]:
+ async def _load_all_from_store(
+ self, account_id: str, user_id: Optional[str]
+ ) -> List[TaskRecord]:
return [
self._record_from_payload(payload)
- for payload in self._store.list(account_id, user_id=user_id)
+ for payload in await self._store.list(account_id, user_id=user_id)
]
@staticmethod
diff --git a/openviking/session/compressor_v2.py b/openviking/session/compressor_v2.py
index 3deaf36fe..a00756ac6 100644
--- a/openviking/session/compressor_v2.py
+++ b/openviking/session/compressor_v2.py
@@ -20,7 +20,7 @@ from openviking.core.namespace import (
from openviking.message import Message
from openviking.server.identity import RequestContext
from openviking.session.memory import ExtractLoop, MemoryUpdater
-from openviking.session.memory.dataclass import MemoryFile, ResolvedOperations
+from openviking.session.memory.dataclass import ResolvedOperations
from openviking.session.memory.memory_isolation_handler import MemoryIsolationHandler
from openviking.session.memory.memory_updater import MemoryUpdateResult
from openviking.session.memory.utils.json_parser import JsonUtils
@@ -36,6 +36,7 @@ from openviking_cli.utils.config import get_openviking_config
logger = get_logger(__name__)
MAX_SOURCE_TRAJECTORIES = 5 # keep only the most recent N trajectory URIs per experience
+_MEMORY_LOCK_RETRY_WARNING_INTERVAL_SECONDS = 10.0
ExtractPostApply = Callable[[MemoryUpdateResult, Dict[str, List[str]], Any], Awaitable[None]]
@@ -53,6 +54,28 @@ def _append_unique(paths: list[str], path: str) -> None:
paths.append(path)
+def _log_memory_lock_retry(
+ *,
+ retry_count: int,
+ max_retries: int,
+ last_warning_at: float,
+ phase_label: str = "",
+) -> float:
+ now = asyncio.get_running_loop().time()
+ max_label = max_retries or "unlimited"
+ prefix = f"[{phase_label}] " if phase_label else ""
+ message = (
+ f"{prefix}Failed to acquire memory locks, retrying "
+ f"(attempt={retry_count}, max={max_label})..."
+ )
+
+ if retry_count == 1 or now - last_warning_at >= _MEMORY_LOCK_RETRY_WARNING_INTERVAL_SECONDS:
+ logger.warning(message)
+ return now
+
+ return last_warning_at
+
+
def _render_memory_schema_locks(
*,
schemas: list[Any],
@@ -250,6 +273,7 @@ class SessionCompressorV2:
retry_interval = config.memory.v2_lock_retry_interval_seconds
max_retries = config.memory.v2_lock_max_retries
retry_count = 0
+ last_lock_retry_warning_at = 0.0
# 循环重试获取锁(机制确保不会死锁)
while True:
@@ -268,9 +292,10 @@ class SessionCompressorV2:
f"{retry_count} retries (max={max_retries})"
)
- logger.warning(
- "Failed to acquire memory locks, retrying "
- f"(attempt={retry_count}, max={max_retries or 'unlimited'})..."
+ last_lock_retry_warning_at = _log_memory_lock_retry(
+ retry_count=retry_count,
+ max_retries=max_retries,
+ last_warning_at=last_lock_retry_warning_at,
)
if retry_interval > 0:
await asyncio.sleep(retry_interval)
@@ -634,6 +659,7 @@ class SessionCompressorV2:
retry_interval = config.memory.v2_lock_retry_interval_seconds
max_retries = config.memory.v2_lock_max_retries
retry_count = 0
+ last_lock_retry_warning_at = 0.0
while True:
lock_acquired = await lock_manager.acquire_exact_tree_batch(
transaction_handle,
@@ -649,6 +675,12 @@ class SessionCompressorV2:
f"[{phase_label}] Failed to acquire memory locks after "
f"{retry_count} retries (max={max_retries})"
)
+ last_lock_retry_warning_at = _log_memory_lock_retry(
+ retry_count=retry_count,
+ max_retries=max_retries,
+ last_warning_at=last_lock_retry_warning_at,
+ phase_label=phase_label,
+ )
if retry_interval > 0:
await asyncio.sleep(retry_interval)
@@ -798,7 +830,6 @@ class SessionCompressorV2:
This is the system-side management of source_trajectories — the LLM never
outputs this field; the pipeline appends the batch after a write or edit.
"""
- from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils
normalized_traj_uris = [uri for uri in traj_uris if uri]
if not normalized_traj_uris:
return
diff --git a/openviking/session/session.py b/openviking/session/session.py
index d3865964c..616f004b5 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -1073,7 +1073,7 @@ class Session:
# Create TaskRecord for tracking Phase 2
tracker = get_task_tracker()
- task = tracker.create(
+ task = await tracker.create(
"session_commit",
resource_id=self.session_id,
account_id=self.ctx.account_id,
@@ -1141,7 +1141,7 @@ class Session:
),
blocked_by=f"archive_{archive_index - 1:03d}",
)
- tracker.fail(
+ await tracker.fail(
task_id,
f"Previous archive archive_{archive_index - 1:03d} failed; "
"cannot continue session commit",
@@ -1150,7 +1150,11 @@ class Session:
)
return
- tracker.start(task_id, account_id=self.ctx.account_id, user_id=self.ctx.user.user_id)
+ await tracker.start(
+ task_id,
+ account_id=self.ctx.account_id,
+ user_id=self.ctx.user.user_id,
+ )
request_wait_tracker.register_request(telemetry.telemetry_id)
register_telemetry(telemetry)
try:
@@ -1158,7 +1162,7 @@ class Session:
# redo-log protection
if redo_enabled:
redo_task_id = str(uuid.uuid4())
- redo_log.write_pending(
+ await redo_log.write_pending_async(
redo_task_id,
{
"archive_uri": archive_uri,
@@ -1291,7 +1295,7 @@ class Session:
logger.warning(f"Failed to create relation to {usage.uri}: {e}")
if redo_enabled and redo_task_id:
- redo_log.mark_done(redo_task_id)
+ await redo_log.mark_done_async(redo_task_id)
# Update active_count (using snapshot, not self._usage_records)
if self._vikingdb_manager:
@@ -1339,7 +1343,7 @@ class Session:
# Write .done file last — signals that all state is finalized
await self._write_done_file(archive_uri, first_message_id, last_message_id)
- tracker.complete(
+ await tracker.complete(
task_id,
{
"session_id": self.session_id,
@@ -1361,7 +1365,7 @@ class Session:
logger.info(f"Session {self.session_id} memory extraction completed")
except asyncio.CancelledError as e:
if redo_enabled and redo_task_id:
- redo_log.mark_done(redo_task_id)
+ await redo_log.mark_done_async(redo_task_id)
try:
await self._write_failed_marker(
archive_uri,
@@ -1370,7 +1374,7 @@ class Session:
)
except Exception:
logger.debug("Failed to write cancelled marker for session %s", self.session_id)
- tracker.fail(
+ await tracker.fail(
task_id,
f"cancelled: {e}",
account_id=self.ctx.account_id,
@@ -1380,13 +1384,13 @@ class Session:
raise
except Exception as e:
if redo_enabled and redo_task_id:
- redo_log.mark_done(redo_task_id)
+ await redo_log.mark_done_async(redo_task_id)
await self._write_failed_marker(
archive_uri,
stage="memory_extraction",
error=str(e),
)
- tracker.fail(
+ await tracker.fail(
task_id, str(e), account_id=self.ctx.account_id, user_id=self.ctx.user.user_id
)
logger.exception(f"Memory extraction failed for session {self.session_id}")
diff --git a/openviking/storage/collection_schemas.py b/openviking/storage/collection_schemas.py
index 7514ff6da..33d02d3ca 100644
--- a/openviking/storage/collection_schemas.py
+++ b/openviking/storage/collection_schemas.py
@@ -21,6 +21,7 @@ from openviking.server.identity import RequestContext, Role
from openviking.storage.errors import (
CollectionNotFoundError,
EmbeddingConfigurationError,
+ EmbeddingRebuildRequiredError,
)
from openviking.storage.queuefs.embedding_msg import EmbeddingMsg
from openviking.storage.queuefs.named_queue import DequeueHandlerBase
@@ -276,14 +277,19 @@ async def init_context_collection(storage) -> bool:
)
return False
- logger.warning(
+ if existing_count == 0 and hasattr(storage, "update_collection_description"):
+ await storage.update_collection_description(
+ _encode_collection_description(
+ base_description or "Unified context collection",
+ embedding_meta,
+ )
+ )
+ return False
+
+ raise EmbeddingRebuildRequiredError(
"Existing collection embedding metadata does not match current configuration. "
- "existing=%s, current=%s. Continuing anyway — search quality may degrade if "
- "the embedding model actually changed.",
- existing_embedding_meta,
- embedding_meta,
+ "Rebuild is required before using the current embedding model."
)
- return False
class TextEmbeddingHandler(DequeueHandlerBase):
diff --git a/openviking/storage/queuefs/named_queue.py b/openviking/storage/queuefs/named_queue.py
index f672c440f..350991bb2 100644
--- a/openviking/storage/queuefs/named_queue.py
+++ b/openviking/storage/queuefs/named_queue.py
@@ -7,6 +7,7 @@ from dataclasses import dataclass, field
from datetime import datetime
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
+from openviking.pyagfs import AsyncAGFSClient
from openviking_cli.utils.logger import get_logger
if TYPE_CHECKING:
@@ -114,6 +115,7 @@ class NamedQueue:
self.name = name
self.path = f"{mount_point}/{name}"
self._agfs = agfs
+ self._async_agfs = AsyncAGFSClient(agfs)
self._enqueue_hook = enqueue_hook
self._dequeue_handler = dequeue_handler
self._initialized = False
@@ -195,7 +197,7 @@ class NamedQueue:
"""Ensure queue directory is created in AGFS."""
if not self._initialized:
try:
- self._agfs.mkdir(self.path)
+ await self._async_agfs.mkdir(self.path)
except Exception as e:
if "exist" not in str(e).lower():
logger.warning(f"[NamedQueue] Failed to ensure queue {self.name}: {e}")
@@ -213,7 +215,7 @@ class NamedQueue:
if isinstance(data, dict):
data = json.dumps(data)
- msg_id = self._agfs.write(enqueue_file, data.encode("utf-8"))
+ msg_id = await self._async_agfs.write(enqueue_file, data.encode("utf-8"))
return msg_id if isinstance(msg_id, str) else str(msg_id)
async def ack(self, msg_id: str) -> None:
@@ -227,16 +229,16 @@ class NamedQueue:
return
ack_file = f"{self.path}/ack"
try:
- self._agfs.write(ack_file, msg_id.encode("utf-8"))
+ await self._async_agfs.write(ack_file, msg_id.encode("utf-8"))
except Exception as e:
logger.warning(f"[NamedQueue] Ack failed for {self.name} msg_id={msg_id}: {e}")
- def _read_queue_message(self) -> Optional[Dict[str, Any]]:
+ async def _read_queue_message(self) -> Optional[Dict[str, Any]]:
"""Read and remove one message from the AGFS queue; return parsed dict or None.
Normalises the various return types AGFSClient.read() may produce.
"""
- content = self._agfs.read(f"{self.path}/dequeue")
+ content = await self._async_agfs.read(f"{self.path}/dequeue")
if not content or content == b"{}":
return None
if isinstance(content, bytes):
@@ -262,7 +264,7 @@ class NamedQueue:
"""
await self._ensure_initialized()
try:
- data = self._read_queue_message()
+ data = await self._read_queue_message()
if data is None:
return None
# Capture message ID before passing data to handler (handler may modify it)
@@ -283,7 +285,7 @@ class NamedQueue:
"""Get and remove message from queue without invoking the handler."""
await self._ensure_initialized()
try:
- return self._read_queue_message()
+ return await self._read_queue_message()
except Exception as e:
logger.debug(f"[NamedQueue] Dequeue raw failed for {self.name}: {e}")
return None
@@ -304,7 +306,7 @@ class NamedQueue:
peek_file = f"{self.path}/peek"
try:
- content = self._agfs.read(peek_file)
+ content = await self._async_agfs.read(peek_file)
if not content or content == b"{}":
return None
if isinstance(content, bytes):
@@ -323,7 +325,7 @@ class NamedQueue:
size_file = f"{self.path}/size"
try:
- content = self._agfs.read(size_file)
+ content = await self._async_agfs.read(size_file)
if not content:
return 0
if isinstance(content, bytes):
@@ -342,7 +344,7 @@ class NamedQueue:
clear_file = f"{self.path}/clear"
try:
- self._agfs.write(clear_file, b"")
+ await self._async_agfs.write(clear_file, b"")
return True
except Exception as e:
logger.error(f"[NamedQueue] Clear failed for {self.name}: {e}")
diff --git a/openviking/storage/queuefs/semantic_dag.py b/openviking/storage/queuefs/semantic_dag.py
index 4dccd98f6..cf1f58d16 100644
--- a/openviking/storage/queuefs/semantic_dag.py
+++ b/openviking/storage/queuefs/semantic_dag.py
@@ -298,7 +298,9 @@ class SemanticDagExecutor:
try:
entries = await self._viking_fs.ls(uri, ctx=self._ctx)
except Exception as e:
- logger.warning(f"[SemanticDagExecutor] Failed to list directory {uri}: {e} from {from_hint}")
+ logger.warning(
+ f"[SemanticDagExecutor] Failed to list directory {uri}: {e} from {from_hint}"
+ )
return [], []
children_dirs: List[str] = []
@@ -437,7 +439,9 @@ class SemanticDagExecutor:
if not target_path:
return True
try:
- target_dirs, target_files = await self._list_dir(target_path, "_check_dir_children_changed")
+ target_dirs, target_files = await self._list_dir(
+ target_path, "_check_dir_children_changed"
+ )
current_file_names = {f.split("/")[-1] for f in current_files}
target_file_names = {f.split("/")[-1] for f in target_files}
if current_file_names != target_file_names:
diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.py
index 59a4b1072..4389c96d6 100644
--- a/openviking/storage/queuefs/semantic_processor.py
+++ b/openviking/storage/queuefs/semantic_processor.py
@@ -469,10 +469,17 @@ class SemanticProcessor(DequeueHandlerBase):
return None
return self._dag_executor.get_stats()
- async def _process_memory_directory(
- self, msg: SemanticMsg, lock: LockLease = NO_LOCK
- ) -> None:
- """Process a memory directory with special handling."""
+ async def _process_memory_directory(self, msg: SemanticMsg, lock: LockLease = NO_LOCK) -> None:
+ """Process a memory directory with special handling.
+
+ For memory directories:
+ - Memory files are already vectorized via embedding queue
+ - Only generate abstract.md and overview.md
+ - Vectorize the generated abstract.md and overview.md
+
+ Args:
+ msg: The semantic message containing directory info and changes
+ """
viking_fs = get_viking_fs()
dir_uri = msg.uri
ctx = self._current_ctx
@@ -613,9 +620,7 @@ class SemanticProcessor(DequeueHandlerBase):
lock=lock,
)
except Exception as e:
- raise RuntimeError(
- f"Failed to write abstract/overview for {dir_uri}: {e}"
- ) from e
+ raise RuntimeError(f"Failed to write abstract/overview for {dir_uri}: {e}") from e
if not wrote_semantics:
_mark_done()
return
diff --git a/openviking/storage/queuefs/semantic_sidecar.py b/openviking/storage/queuefs/semantic_sidecar.py
index 7e512f821..8bb129373 100644
--- a/openviking/storage/queuefs/semantic_sidecar.py
+++ b/openviking/storage/queuefs/semantic_sidecar.py
@@ -27,7 +27,10 @@ async def write_semantic_sidecars(
return False
try:
- from openviking.storage.transaction import LockContext, get_lock_manager
+ from openviking.storage.transaction import (
+ LockContext,
+ get_lock_manager,
+ )
lock_manager = get_lock_manager()
except Exception:
diff --git a/openviking/storage/transaction/__init__.py b/openviking/storage/transaction/__init__.py
index 2aa5a40dc..c635ce6b1 100644
--- a/openviking/storage/transaction/__init__.py
+++ b/openviking/storage/transaction/__init__.py
@@ -17,6 +17,7 @@ from openviking.storage.transaction.lock_lease import (
)
from openviking.storage.transaction.lock_manager import (
LockManager,
+ get_lock_handle_async,
get_lock_manager,
init_lock_manager,
release_all_locks,
@@ -37,6 +38,7 @@ __all__ = [
"OwnedLockLease",
"PathLockEngine",
"RedoLog",
+ "get_lock_handle_async",
"get_lock_manager",
"init_lock_manager",
"release_all_locks",
diff --git a/openviking/storage/transaction/lock_lease.py b/openviking/storage/transaction/lock_lease.py
index 021ba9af5..3b91b6b1e 100644
--- a/openviking/storage/transaction/lock_lease.py
+++ b/openviking/storage/transaction/lock_lease.py
@@ -126,9 +126,9 @@ class OwnedLockLease(LockLease):
manager: Optional[LockManager] = None,
) -> "OwnedLockLease":
manager = manager or get_lock_manager()
- handle = manager.get_handle(ref.handle_id)
+ handle = await manager.get_handle_async(ref.handle_id)
if handle is None:
- handle = manager.adopt_handle(ref.handle_id, ref.lock_paths)
+ handle = await manager.adopt_handle_async(ref.handle_id, ref.lock_paths)
if handle is None:
raise LockAcquisitionError(f"Lock handle is no longer active: {ref.handle_id}")
return cls(manager, handle)
diff --git a/openviking/storage/transaction/lock_manager.py b/openviking/storage/transaction/lock_manager.py
index f2a7bcd41..3d9bfc217 100644
--- a/openviking/storage/transaction/lock_manager.py
+++ b/openviking/storage/transaction/lock_manager.py
@@ -5,9 +5,9 @@
import asyncio
import json
import time
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Protocol
-from openviking.pyagfs import AGFSClient
+from openviking.pyagfs import AGFSClient, AsyncAGFSClient
from openviking.storage.transaction.lock_handle import LockHandle
from openviking.storage.transaction.path_lock import PathLockEngine
from openviking.storage.transaction.redo_log import RedoLog
@@ -19,6 +19,19 @@ _HANDLE_CLEANUP_INTERVAL_SECONDS = 60.0
_USE_MANAGER_DEFAULT_TIMEOUT = object()
+class _LockManagerLike(Protocol):
+ def get_handle(self, handle_id: str) -> Optional[LockHandle]: ...
+
+
+async def get_lock_handle_async(
+ lock_manager: _LockManagerLike, handle_id: str
+) -> Optional[LockHandle]:
+ getter = getattr(lock_manager, "get_handle_async", None)
+ if getter is not None:
+ return await getter(handle_id)
+ return await asyncio.to_thread(lock_manager.get_handle, handle_id)
+
+
class LockManager:
"""Global singleton. Manages lock lifecycle and stale cleanup."""
@@ -30,6 +43,7 @@ class LockManager:
redo_recovery_enabled: bool = True,
):
self._agfs = agfs
+ self._async_agfs = AsyncAGFSClient(agfs)
self._path_lock = PathLockEngine(agfs, lock_expire=lock_expire)
self._lock_timeout = lock_timeout
self._redo_recovery_enabled = redo_recovery_enabled
@@ -61,6 +75,14 @@ class LockManager:
active_handles[current.id] = current
return active_handles
+ async def get_active_handles_async(self) -> Dict[str, LockHandle]:
+ active_handles: Dict[str, LockHandle] = {}
+ for handle in list(self._handles.values()):
+ current = await self._reconcile_handle_async(handle)
+ if current and current.locks:
+ active_handles[current.id] = current
+ return active_handles
+
async def start(self) -> None:
"""Start background cleanup and redo recovery."""
self._running = True
@@ -304,6 +326,33 @@ class LockManager:
self._mark_handle_active(adopted)
return adopted
+ async def adopt_handle_async(
+ self, handle_id: str, lock_paths: List[str]
+ ) -> Optional[LockHandle]:
+ handle = await self.get_handle_async(handle_id)
+ if handle is not None:
+ return handle
+
+ adopted = LockHandle(id=handle_id)
+ for lock_path in dict.fromkeys(lock_paths):
+ if await self._path_lock.is_lock_owned_by_async(lock_path, handle_id):
+ adopted.add_lock(lock_path)
+ if not adopted.locks:
+ return None
+
+ self._handles[adopted.id] = adopted
+ self._mark_handle_active(adopted)
+ return adopted
+
+ async def get_handle_async(self, handle_id: str) -> Optional[LockHandle]:
+ handle = self._handles.get(handle_id)
+ if handle is None:
+ return None
+ current = await self._reconcile_handle_async(handle)
+ if current is None or not current.locks:
+ return None
+ return current
+
def is_path_locked(self, path: str, ignore_stale: bool = True) -> bool:
"""Check whether *path* is currently locked.
@@ -318,8 +367,16 @@ class LockManager:
logger.warning(f"is_path_locked failed for {path}: {e}")
return False
+ async def is_path_locked_async(self, path: str, ignore_stale: bool = True) -> bool:
+ """Async variant for request/background paths."""
+ try:
+ return await self._path_lock.is_locked_async(path, ignore_stale=ignore_stale)
+ except Exception as e:
+ logger.warning(f"is_path_locked_async failed for {path}: {e}")
+ return False
+
async def refresh_lock(self, handle: LockHandle) -> None:
- current = self._reconcile_handle(handle)
+ current = await self._reconcile_handle_async(handle)
if current is None:
return
@@ -330,7 +387,7 @@ class LockManager:
if result.refreshed_paths:
self._mark_handle_active(current)
- self._reconcile_handle(current)
+ await self._reconcile_handle_async(current)
async def release(self, handle: LockHandle) -> None:
await self._path_lock.release(handle)
@@ -346,7 +403,7 @@ class LockManager:
now = time.time()
stale = []
for handle in list(self._handles.values()):
- current = self._reconcile_handle(handle)
+ current = await self._reconcile_handle_async(handle)
if current and self._is_handle_stale(current, now):
stale.append(current)
for handle in stale:
@@ -371,19 +428,29 @@ class LockManager:
return None
return handle
+ async def _reconcile_handle_async(self, handle: LockHandle) -> Optional[LockHandle]:
+ had_locks = bool(handle.locks)
+ lost_paths = await self._path_lock.collect_lost_owner_locks_async(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)
# ------------------------------------------------------------------
async def _recover_pending_redo(self) -> None:
- pending_ids = self._redo_log.list_pending()
+ pending_ids = await self._redo_log.list_pending_async()
for task_id in pending_ids:
logger.info(f"Recovering pending redo task: {task_id}")
try:
- info = self._redo_log.read(task_id)
+ info = await self._redo_log.read_async(task_id)
if info:
await self._redo_session_memory(info)
- self._redo_log.mark_done(task_id)
+ await self._redo_log.mark_done_async(task_id)
except Exception as e:
logger.error(f"Redo recovery failed for {task_id}: {e}", exc_info=True)
@@ -418,7 +485,7 @@ class LockManager:
agfs_path = viking_fs._uri_to_path(messages_uri, ctx=ctx)
messages = []
try:
- content = self._agfs.cat(agfs_path)
+ content = await self._async_agfs.cat(agfs_path)
if isinstance(content, bytes):
content = content.decode("utf-8")
for line in content.strip().split("\n"):
@@ -524,5 +591,5 @@ async def release_all_locks() -> None:
"""Release all active lock handles. **Test-only utility.**"""
if _lock_manager is None:
return
- for handle in list(_lock_manager.get_active_handles().values()):
+ for handle in list((await _lock_manager.get_active_handles_async()).values()):
await _lock_manager.release(handle)
diff --git a/openviking/storage/transaction/path_lock.py b/openviking/storage/transaction/path_lock.py
index f788174d9..8883323a0 100644
--- a/openviking/storage/transaction/path_lock.py
+++ b/openviking/storage/transaction/path_lock.py
@@ -5,7 +5,7 @@ import time
from dataclasses import dataclass, field
from typing import Optional, Tuple
-from openviking.pyagfs import AGFSClient
+from openviking.pyagfs import AGFSClient, AsyncAGFSClient
from openviking.storage.transaction.lock_handle import LockOwner
from openviking_cli.utils.logger import get_logger
@@ -24,6 +24,7 @@ _READ_ONLY_TREE_LOCK_TYPES = {"P", "S"}
# Default poll interval when waiting for a lock (seconds)
_POLL_INTERVAL = 0.2
_WAIT_LOG_INTERVAL = 10.0
+_last_timeout_warning_at: dict[str, float] = {}
@dataclass
@@ -55,9 +56,18 @@ def _parse_fencing_token(token: str) -> Tuple[str, int, str]:
return token, 0, LOCK_TYPE_EXACT
+def _log_timeout_waiting(message: str) -> None:
+ now = asyncio.get_running_loop().time()
+ last_warning_at = _last_timeout_warning_at.get(message, 0.0)
+ if not last_warning_at or now - last_warning_at >= _WAIT_LOG_INTERVAL:
+ logger.warning(message)
+ _last_timeout_warning_at[message] = now
+
+
class PathLockEngine:
def __init__(self, agfs_client: AGFSClient, lock_expire: float = 300.0):
self._agfs = agfs_client
+ self._async_agfs = AsyncAGFSClient(agfs_client)
self._lock_expire = lock_expire
def _get_lock_path(self, path: str) -> str:
@@ -75,6 +85,15 @@ class PathLockEngine:
return stat.get("isDir") is True
return getattr(stat, "isDir", None) is True
+ async def _is_existing_directory_async(self, path: str) -> bool:
+ try:
+ stat = await self._async_agfs.stat(path.rstrip("/") or "/")
+ except Exception:
+ return False
+ if isinstance(stat, dict):
+ return stat.get("isDir") is True
+ return getattr(stat, "isDir", None) is True
+
def _get_prefixed_exact_lock_path(self, path: str) -> str:
path = path.rstrip("/") or "/"
parent = self._get_parent_path(path)
@@ -100,20 +119,29 @@ class PathLockEngine:
return [primary]
return [primary, prefixed]
- def _ensure_directory_exists(self, path: str):
- """确保目录存在,不存在则创建"""
+ async def _get_exact_lock_path_async(self, path: str) -> str:
+ """Async variant for acquire paths, where stat may be remote/blocking."""
+ if await self._is_existing_directory_async(path):
+ return self._get_lock_path(path)
+ return self._get_prefixed_exact_lock_path(path)
+
+ async def _get_exact_lock_paths_async(self, path: str) -> list[str]:
+ primary = await self._get_exact_lock_path_async(path)
+ prefixed = self._get_prefixed_exact_lock_path(path)
+ if primary == prefixed:
+ return [primary]
+ return [primary, prefixed]
+
+ async def _ensure_directory_exists_async(self, path: str):
+ """Async variant for lock acquisition paths."""
try:
- # 检查路径是否存在
- self._agfs.stat(path)
+ await self._async_agfs.stat(path)
except Exception:
- # 路径不存在,尝试创建目录
try:
parent = self._get_parent_path(path)
if parent:
- # 递归创建父目录
- self._ensure_directory_exists(parent)
- # 创建当前目录
- self._agfs.mkdir(path)
+ await self._ensure_directory_exists_async(parent)
+ await self._async_agfs.mkdir(path)
logger.debug(f"Directory created: {path}")
except Exception as e:
logger.warning(f"Failed to create directory {path}: {e}")
@@ -138,6 +166,17 @@ class PathLockEngine:
except Exception:
return None
+ async def _read_token_async(self, lock_path: str) -> Optional[str]:
+ try:
+ content = await self._async_agfs.read(lock_path)
+ if isinstance(content, bytes):
+ token = content.decode("utf-8").strip()
+ else:
+ token = str(content).strip()
+ return token if token else None
+ 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:
@@ -145,10 +184,26 @@ class PathLockEngine:
owner_id, _, lock_type = _parse_fencing_token(token)
return owner_id, lock_type
+ async def _read_owner_and_type_async(
+ self, lock_path: str
+ ) -> Tuple[Optional[str], Optional[str]]:
+ token = await self._read_token_async(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
+ async def is_lock_owned_by_async(self, lock_path: str, owner_id: str) -> bool:
+ current_owner_id, _ = await self._read_owner_and_type_async(lock_path)
+ return current_owner_id == owner_id
+
+ async def _is_lock_owned_by_async(self, lock_path: str, owner_id: str) -> bool:
+ return await self.is_lock_owned_by_async(lock_path, owner_id)
+
def is_locked(self, path: str, ignore_stale: bool = True) -> bool:
"""Check whether *path* is currently locked.
@@ -195,6 +250,42 @@ class PathLockEngine:
return False
+ async def is_locked_async(self, path: str, ignore_stale: bool = True) -> bool:
+ """Async variant of is_locked for request/background paths."""
+ own_lock_path = self._get_lock_path(path)
+ token = await self._read_token_async(own_lock_path)
+ if token is not None:
+ if not (
+ ignore_stale and await self._is_lock_stale_async(own_lock_path, self._lock_expire)
+ ):
+ return True
+
+ for exact_lock_path in await self._get_exact_lock_paths_async(path):
+ if exact_lock_path == own_lock_path:
+ continue
+ exact_token = await self._read_token_async(exact_lock_path)
+ if exact_token is not None:
+ if not (
+ ignore_stale
+ and await self._is_lock_stale_async(exact_lock_path, self._lock_expire)
+ ):
+ return True
+
+ parent = self._get_parent_path(path)
+ while parent:
+ ancestor_lock = self._get_lock_path(parent)
+ ancestor_token = await self._read_token_async(ancestor_lock)
+ if ancestor_token is not None:
+ _, _, lock_type = _parse_fencing_token(ancestor_token)
+ if lock_type == LOCK_TYPE_TREE and not (
+ ignore_stale
+ and await self._is_lock_stale_async(ancestor_lock, self._lock_expire)
+ ):
+ return True
+ parent = self._get_parent_path(parent)
+
+ return False
+
def collect_lost_owner_locks(self, owner: LockOwner) -> list[str]:
lost_paths: list[str] = []
for lock_path in list(owner.locks):
@@ -202,8 +293,15 @@ class PathLockEngine:
lost_paths.append(lock_path)
return lost_paths
+ async def collect_lost_owner_locks_async(self, owner: LockOwner) -> list[str]:
+ lost_paths: list[str] = []
+ for lock_path in list(owner.locks):
+ if not await self._is_lock_owned_by_async(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)
+ token = await self._read_token_async(lock_path)
if token is None:
return False
lock_owner, _, _ = _parse_fencing_token(token)
@@ -213,7 +311,7 @@ class PathLockEngine:
self, lock_path: str, owner_id: str, lock_type: str = LOCK_TYPE_EXACT
) -> None:
token = _make_fencing_token(owner_id, lock_type)
- self._agfs.write(lock_path, token.encode("utf-8"))
+ await self._async_agfs.write(lock_path, token.encode("utf-8"))
async def _owned_lock_type(self, path: str, owner: LockOwner) -> Optional[str]:
lock_path = self._get_lock_path(path)
@@ -224,7 +322,7 @@ class PathLockEngine:
) -> Optional[str]:
if lock_path not in owner.locks:
return None
- token = self._read_token(lock_path)
+ token = await self._read_token_async(lock_path)
if token is None:
return None
lock_owner, _, lock_type = _parse_fencing_token(token)
@@ -242,7 +340,7 @@ class PathLockEngine:
async def _remove_lock_file(self, lock_path: str) -> bool:
try:
- self._agfs.rm(lock_path)
+ await self._async_agfs.rm(lock_path)
return True
except Exception as e:
if "not found" in str(e).lower():
@@ -259,11 +357,21 @@ class PathLockEngine:
age = (time.time_ns() - ts) / 1e9
return age > expire_seconds
+ async def _is_lock_stale_async(self, lock_path: str, expire_seconds: float = 300.0) -> bool:
+ token = await self._read_token_async(lock_path)
+ if token is None:
+ return True
+ _, ts, _ = _parse_fencing_token(token)
+ if ts == 0:
+ return True
+ age = (time.time_ns() - ts) / 1e9
+ return age > expire_seconds
+
async def _check_ancestors_for_tree(self, path: str, exclude_owner_id: str) -> Optional[str]:
parent = self._get_parent_path(path)
while parent:
lock_path = self._get_lock_path(parent)
- token = self._read_token(lock_path)
+ token = await self._read_token_async(lock_path)
if token is not None:
owner_id, _, lock_type = _parse_fencing_token(token)
if owner_id != exclude_owner_id and lock_type == LOCK_TYPE_TREE:
@@ -273,7 +381,7 @@ class PathLockEngine:
async def _check_path_lock(self, path: str, exclude_owner_id: str) -> Optional[str]:
lock_path = self._get_lock_path(path)
- token = self._read_token(lock_path)
+ token = await self._read_token_async(lock_path)
if token is None:
return None
owner_id, _, _ = _parse_fencing_token(token)
@@ -282,8 +390,8 @@ class PathLockEngine:
return None
async def _check_exact_path_lock(self, path: str, exclude_owner_id: str) -> Optional[str]:
- for lock_path in self._get_exact_lock_paths(path):
- token = self._read_token(lock_path)
+ for lock_path in await self._get_exact_lock_paths_async(path):
+ token = await self._read_token_async(lock_path)
if token is None:
continue
owner_id, _, _ = _parse_fencing_token(token)
@@ -294,10 +402,10 @@ class PathLockEngine:
async def _scan_descendants_for_locks(self, path: str, exclude_owner_id: str) -> Optional[str]:
try:
try:
- self._agfs.stat(path)
+ await self._async_agfs.stat(path)
except Exception:
return None
- entries = self._agfs.ls(path)
+ entries = await self._async_agfs.ls(path)
if not isinstance(entries, list):
return None
for entry in entries:
@@ -308,7 +416,7 @@ class PathLockEngine:
continue
entry_path = f"{path.rstrip('/')}/{name}"
if name.startswith(EXACT_LOCK_FILE_PREFIX):
- token = self._read_token(entry_path)
+ token = await self._read_token_async(entry_path)
if token is not None:
owner_id, _, _ = _parse_fencing_token(token)
if owner_id != exclude_owner_id:
@@ -318,7 +426,7 @@ class PathLockEngine:
continue
subdir = entry_path
subdir_lock = self._get_lock_path(subdir)
- token = self._read_token(subdir_lock)
+ token = await self._read_token_async(subdir_lock)
if token is not None:
owner_id, _, _ = _parse_fencing_token(token)
if owner_id != exclude_owner_id:
@@ -343,8 +451,8 @@ class PathLockEngine:
It does not conflict with sibling exact paths.
"""
owner_id = owner.id
- lock_path = self._get_exact_lock_path(path)
- if lock_path in owner.locks and self.is_lock_owned_by(lock_path, owner_id):
+ lock_path = await self._get_exact_lock_path_async(path)
+ if lock_path in owner.locks and await self._is_lock_owned_by_async(lock_path, owner_id):
owner.add_lock(lock_path)
logger.debug(f"[EXACT] Reusing owned exact lock on: {path}")
return True
@@ -361,12 +469,12 @@ class PathLockEngine:
while True:
existing_exact_lock = await self._check_exact_path_lock(path, owner_id)
if existing_exact_lock:
- if self.is_lock_stale(existing_exact_lock, self._lock_expire):
+ if await self._is_lock_stale_async(existing_exact_lock, self._lock_expire):
logger.warning(f"[EXACT] Removing stale exact lock: {existing_exact_lock}")
await self._remove_lock_file(existing_exact_lock)
continue
if asyncio.get_running_loop().time() >= deadline:
- logger.warning(f"[EXACT] Timeout waiting for exact lock on: {path}")
+ _log_timeout_waiting(f"[EXACT] Timeout waiting for exact lock on: {path}")
return False
now = asyncio.get_running_loop().time()
if timeout is None and now >= next_wait_log_at:
@@ -380,30 +488,30 @@ class PathLockEngine:
same_path_lock = self._get_lock_path(path)
if same_path_lock != lock_path:
- token = self._read_token(same_path_lock)
+ token = await self._read_token_async(same_path_lock)
if token is not None:
lock_owner, _, _ = _parse_fencing_token(token)
if lock_owner != owner_id:
- if self.is_lock_stale(same_path_lock, self._lock_expire):
+ if await self._is_lock_stale_async(same_path_lock, self._lock_expire):
logger.warning(f"[EXACT] Removing stale lock: {same_path_lock}")
await self._remove_lock_file(same_path_lock)
continue
if asyncio.get_running_loop().time() >= deadline:
- logger.warning(f"[EXACT] Timeout waiting for lock: {path}")
+ _log_timeout_waiting(f"[EXACT] Timeout waiting for lock: {path}")
return False
await asyncio.sleep(_POLL_INTERVAL)
continue
ancestor_conflict = await self._check_ancestors_for_tree(path, owner_id)
if ancestor_conflict:
- if self.is_lock_stale(ancestor_conflict, self._lock_expire):
+ if await self._is_lock_stale_async(ancestor_conflict, self._lock_expire):
logger.warning(
f"[EXACT] Removing stale ancestor TREE lock: {ancestor_conflict}"
)
await self._remove_lock_file(ancestor_conflict)
continue
if asyncio.get_running_loop().time() >= deadline:
- logger.warning(
+ _log_timeout_waiting(
f"[EXACT] Timeout waiting for ancestor TREE lock: {ancestor_conflict}"
)
return False
@@ -421,7 +529,7 @@ class PathLockEngine:
if (
lock_path != self._get_lock_path(path)
and parent
- and not self._ensure_directory_exists(parent)
+ and not await self._ensure_directory_exists_async(parent)
):
logger.warning(f"[EXACT] Failed to ensure parent directory exists: {parent}")
return False
@@ -432,7 +540,7 @@ class PathLockEngine:
logger.error(f"[EXACT] Failed to create lock file: {e}")
return False
- if not self.is_lock_owned_by(lock_path, owner_id):
+ if not await self._is_lock_owned_by_async(lock_path, owner_id):
logger.debug(f"[EXACT] Lost lock write race on: {path}")
if asyncio.get_running_loop().time() >= deadline:
return False
@@ -445,19 +553,19 @@ class PathLockEngine:
if not conflict_after:
conflict_after = await self._check_ancestors_for_tree(path, owner_id)
if conflict_after:
- their_token = self._read_token(conflict_after)
+ their_token = await self._read_token_async(conflict_after)
if their_token:
their_owner_id, their_ts, _ = _parse_fencing_token(their_token)
- my_token = self._read_token(lock_path)
+ my_token = await self._read_token_async(lock_path)
_, my_ts, _ = (
_parse_fencing_token(my_token) if my_token else ("", 0, LOCK_TYPE_EXACT)
)
if (my_ts, owner_id) > (their_ts, their_owner_id):
logger.debug(f"[EXACT] Backing off (livelock guard) on {path}")
- if self.is_lock_owned_by(lock_path, owner_id):
+ if await self._is_lock_owned_by_async(lock_path, owner_id):
await self._remove_lock_file(lock_path)
if asyncio.get_running_loop().time() >= deadline:
- if self.is_lock_owned_by(lock_path, owner_id):
+ if await self._is_lock_owned_by_async(lock_path, owner_id):
await self._remove_lock_file(lock_path)
return False
now = asyncio.get_running_loop().time()
@@ -470,7 +578,7 @@ class PathLockEngine:
await asyncio.sleep(_POLL_INTERVAL)
continue
- if not self.is_lock_owned_by(lock_path, owner_id):
+ if not await self._is_lock_owned_by_async(lock_path, owner_id):
logger.debug(f"[EXACT] Lock ownership verification failed: {path}")
if asyncio.get_running_loop().time() >= deadline:
return False
@@ -512,18 +620,17 @@ class PathLockEngine:
while True:
if await self._is_locked_by_other(lock_path, owner_id):
- if self.is_lock_stale(lock_path, self._lock_expire):
+ if await self._is_lock_stale_async(lock_path, self._lock_expire):
logger.warning(f"[TREE] Removing stale lock: {lock_path}")
await self._remove_lock_file(lock_path)
continue
if asyncio.get_running_loop().time() >= deadline:
- logger.warning(f"[TREE] Timeout waiting for lock on: {path}")
+ _log_timeout_waiting(f"[TREE] Timeout waiting for lock on: {path}")
return False
now = asyncio.get_running_loop().time()
if timeout is None and now >= next_wait_log_at:
logger.info(
- f"[TREE] Still waiting for lock on: {path} "
- f"(waited={now - wait_start:.1f}s)"
+ f"[TREE] Still waiting for lock on: {path} (waited={now - wait_start:.1f}s)"
)
next_wait_log_at = now + _WAIT_LOG_INTERVAL
await asyncio.sleep(_POLL_INTERVAL)
@@ -532,12 +639,12 @@ class PathLockEngine:
# Check ancestor paths for TREE locks held by other owners
ancestor_conflict = await self._check_ancestors_for_tree(path, owner_id)
if ancestor_conflict:
- if self.is_lock_stale(ancestor_conflict, self._lock_expire):
+ if await self._is_lock_stale_async(ancestor_conflict, self._lock_expire):
logger.warning(f"[TREE] Removing stale ancestor TREE lock: {ancestor_conflict}")
await self._remove_lock_file(ancestor_conflict)
continue
if asyncio.get_running_loop().time() >= deadline:
- logger.warning(
+ _log_timeout_waiting(
f"[TREE] Timeout waiting for ancestor TREE lock: {ancestor_conflict}"
)
return False
@@ -553,24 +660,26 @@ class PathLockEngine:
exact_conflict = await self._check_exact_path_lock(path, owner_id)
if exact_conflict:
- if self.is_lock_stale(exact_conflict, self._lock_expire):
+ if await self._is_lock_stale_async(exact_conflict, self._lock_expire):
logger.warning(f"[TREE] Removing stale exact lock: {exact_conflict}")
await self._remove_lock_file(exact_conflict)
continue
if asyncio.get_running_loop().time() >= deadline:
- logger.warning(f"[TREE] Timeout waiting for exact lock: {exact_conflict}")
+ _log_timeout_waiting(f"[TREE] Timeout waiting for exact lock: {exact_conflict}")
return False
await asyncio.sleep(_POLL_INTERVAL)
continue
desc_conflict = await self._scan_descendants_for_locks(path, owner_id)
if desc_conflict:
- if self.is_lock_stale(desc_conflict, self._lock_expire):
+ if await self._is_lock_stale_async(desc_conflict, self._lock_expire):
logger.warning(f"[TREE] Removing stale descendant lock: {desc_conflict}")
await self._remove_lock_file(desc_conflict)
continue
if asyncio.get_running_loop().time() >= deadline:
- logger.warning(f"[TREE] Timeout waiting for descendant lock: {desc_conflict}")
+ _log_timeout_waiting(
+ f"[TREE] Timeout waiting for descendant lock: {desc_conflict}"
+ )
return False
now = asyncio.get_running_loop().time()
if timeout is None and now >= next_wait_log_at:
@@ -582,7 +691,7 @@ class PathLockEngine:
await asyncio.sleep(_POLL_INTERVAL)
continue
- if not self._ensure_directory_exists(path):
+ if not await self._ensure_directory_exists_async(path):
logger.warning(f"[TREE] Failed to ensure directory exists: {path}")
return False
@@ -599,10 +708,10 @@ class PathLockEngine:
if not conflict_after:
conflict_after = await self._check_ancestors_for_tree(path, owner_id)
if conflict_after:
- their_token = self._read_token(conflict_after)
+ their_token = await self._read_token_async(conflict_after)
if their_token:
their_owner_id, their_ts, _ = _parse_fencing_token(their_token)
- my_token = self._read_token(lock_path)
+ my_token = await self._read_token_async(lock_path)
_, my_ts, _ = (
_parse_fencing_token(my_token) if my_token else ("", 0, LOCK_TYPE_TREE)
)
@@ -624,7 +733,7 @@ class PathLockEngine:
await asyncio.sleep(_POLL_INTERVAL)
continue
- if not self.is_lock_owned_by(lock_path, owner_id):
+ if not await self._is_lock_owned_by_async(lock_path, owner_id):
logger.debug(f"[TREE] Lock ownership verification failed: {path}")
if asyncio.get_running_loop().time() >= deadline:
return False
@@ -684,13 +793,13 @@ class PathLockEngine:
"""Rewrite all lock file timestamps to prevent stale cleanup."""
result = LockRefreshResult()
for lock_path in list(owner.locks):
- parsed_owner_id, lock_type = self._read_owner_and_type(lock_path)
+ parsed_owner_id, lock_type = await self._read_owner_and_type_async(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"))
+ await self._async_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}")
@@ -701,7 +810,7 @@ class PathLockEngine:
lock_count = len(owner.locks)
released_count = 0
for lock_path in reversed(list(owner.locks)):
- if self.is_lock_owned_by(lock_path, owner.id):
+ if await self._is_lock_owned_by_async(lock_path, owner.id):
await self._remove_lock_file(lock_path)
released_count += 1
owner.remove_lock(lock_path)
@@ -712,6 +821,6 @@ class PathLockEngine:
for lock_path in reversed(lock_paths):
if lock_path not in owner.locks:
continue
- if self.is_lock_owned_by(lock_path, owner.id):
+ if await self._is_lock_owned_by_async(lock_path, owner.id):
await self._remove_lock_file(lock_path)
owner.remove_lock(lock_path)
diff --git a/openviking/storage/transaction/redo_log.py b/openviking/storage/transaction/redo_log.py
index 467d246bd..de8f6fcbb 100644
--- a/openviking/storage/transaction/redo_log.py
+++ b/openviking/storage/transaction/redo_log.py
@@ -5,7 +5,7 @@
import json
from typing import Any, Dict, List
-from openviking.pyagfs import AGFSClient
+from openviking.pyagfs import AGFSClient, AsyncAGFSClient
from openviking_cli.utils.logger import get_logger
logger = get_logger(__name__)
@@ -21,39 +21,39 @@ class RedoLog:
"""
def __init__(self, agfs: AGFSClient):
- self._agfs = agfs
+ self._async_agfs = AsyncAGFSClient(agfs)
def _task_path(self, task_id: str) -> str:
return f"{_REDO_ROOT}/{task_id}/redo.json"
- def _ensure_dirs(self, dir_path: str) -> None:
+ async def _ensure_dirs_async(self, dir_path: str) -> None:
parts = dir_path.strip("/").split("/")
current = ""
for part in parts:
current = f"{current}/{part}"
try:
- self._agfs.mkdir(current)
+ await self._async_agfs.mkdir(current)
except Exception:
pass
- def write_pending(self, task_id: str, info: Dict[str, Any]) -> None:
+ async def write_pending_async(self, task_id: str, info: Dict[str, Any]) -> None:
"""Write a redo marker before the operation starts."""
dir_path = f"{_REDO_ROOT}/{task_id}"
- self._ensure_dirs(dir_path)
+ await self._ensure_dirs_async(dir_path)
data = json.dumps(info, default=str).encode("utf-8")
- self._agfs.write(self._task_path(task_id), data)
+ await self._async_agfs.write(self._task_path(task_id), data)
- def mark_done(self, task_id: str) -> None:
+ async def mark_done_async(self, task_id: str) -> None:
"""Delete the redo marker after a successful operation."""
try:
- self._agfs.rm(f"{_REDO_ROOT}/{task_id}", recursive=True)
+ await self._async_agfs.rm(f"{_REDO_ROOT}/{task_id}", recursive=True)
except Exception as e:
logger.warning(f"Failed to clean redo marker {task_id}: {e}")
- def list_pending(self) -> List[str]:
+ async def list_pending_async(self) -> List[str]:
"""Return all pending task IDs (directories under _REDO_ROOT)."""
try:
- entries = self._agfs.ls(_REDO_ROOT)
+ entries = await self._async_agfs.ls(_REDO_ROOT)
if not isinstance(entries, list):
return []
return [
@@ -64,10 +64,10 @@ class RedoLog:
except Exception:
return []
- def read(self, task_id: str) -> Dict[str, Any]:
+ async def read_async(self, task_id: str) -> Dict[str, Any]:
"""Read the info dict of a pending task."""
try:
- content = self._agfs.cat(self._task_path(task_id))
+ content = await self._async_agfs.cat(self._task_path(task_id))
if isinstance(content, bytes):
content = content.decode("utf-8")
return json.loads(content)
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index 35d41e611..80d8a61a7 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -31,6 +31,7 @@ from openviking.core.namespace import (
from openviking.core.namespace import (
is_accessible as namespace_is_accessible,
)
+from openviking.pyagfs import AsyncAGFSClient
from openviking.pyagfs.exceptions import (
AGFSClientError,
AGFSDirectoryNotEmptyError,
@@ -220,6 +221,7 @@ class VikingFS:
encryptor: Optional[Any] = None,
):
self.agfs = agfs
+ self._async_agfs = AsyncAGFSClient(agfs)
self.query_embedder = query_embedder
self.rerank_config = rerank_config
self.vector_store = vector_store
@@ -239,11 +241,6 @@ class VikingFS:
bound = self._bound_ctx.get()
return bound or self._default_ctx()
- @staticmethod
- async def _run_in_threadpool(func: Any, /, *args: Any, **kwargs: Any) -> Any:
- """Run blocking AGFS operations in the default thread pool."""
- return await asyncio.to_thread(func, *args, **kwargs)
-
async def _encrypt_content(self, content: bytes, ctx: Optional[RequestContext] = None) -> bytes:
"""Encrypt content if encryption is enabled."""
if not self._encryptor:
@@ -360,7 +357,7 @@ class VikingFS:
if self._encryptor:
# When encryption is enabled: must read entire file for decryption
- result = await self._run_in_threadpool(self.agfs.read, path, 0, -1)
+ result = await self._async_agfs.read(path, 0, -1)
if isinstance(result, bytes):
raw = result
elif result is not None and hasattr(result, "content"):
@@ -378,7 +375,7 @@ class VikingFS:
raw = raw[offset:]
else:
# When not encrypted: normal read
- result = await self._run_in_threadpool(self.agfs.read, path, offset, size)
+ result = await self._async_agfs.read(path, offset, size)
if isinstance(result, bytes):
raw = result
elif result is not None and hasattr(result, "content"):
@@ -401,7 +398,7 @@ class VikingFS:
data = data.encode("utf-8")
data = await self._encrypt_content(data, ctx=ctx)
- return await self._run_in_threadpool(self.agfs.write, path, data)
+ return await self._async_agfs.write(path, data)
async def mkdir(
self,
@@ -416,7 +413,7 @@ class VikingFS:
# Always ensure parent directories exist before creating this directory
await self._ensure_parent_dirs(path)
try:
- await self._run_in_threadpool(self.agfs.mkdir, path)
+ await self._async_agfs.mkdir(path)
except Exception as exc:
message = str(exc).lower()
already_exists = "exist" in message or "already" in message
@@ -467,7 +464,7 @@ class VikingFS:
# Check existence and determine lock strategy
try:
- stat = await self._run_in_threadpool(self.agfs.stat, path)
+ stat = await self._async_agfs.stat(path)
is_dir = stat.get("isDir", False) if isinstance(stat, dict) else False
except Exception as exc:
if not is_not_found_error(exc):
@@ -509,7 +506,7 @@ class VikingFS:
estimated_count = await _estimate_deleted_count(path, real_ctx)
await self._delete_from_vector_store(uris_to_delete, ctx=ctx)
try:
- result = await self._run_in_threadpool(self.agfs.rm, path, recursive=recursive)
+ result = await self._async_agfs.rm(path, recursive=recursive)
except AGFSDirectoryNotEmptyError:
raise FailedPreconditionError(
f"Directory not empty: {uri}. Use recursive=True to delete non-empty directories."
@@ -542,7 +539,6 @@ class VikingFS:
Implemented as cp + rm to avoid lock files being carried by FS mv.
On VectorDB update failure the copy is cleaned up so the source stays intact.
"""
- from openviking.pyagfs.helpers import cp as agfs_cp
from openviking.storage.transaction import LockContext, get_lock_manager
self._ensure_mutable_access(old_uri, ctx)
@@ -553,7 +549,7 @@ class VikingFS:
# Verify source exists and determine type before locking.
try:
- stat = await self._run_in_threadpool(self.agfs.stat, old_path)
+ stat = await self._async_agfs.stat(old_path)
is_dir = stat.get("isDir", False) if isinstance(stat, dict) else False
except Exception as exc:
if not is_not_found_error(exc):
@@ -591,9 +587,7 @@ class VikingFS:
# Copy source to destination (source still intact)
try:
if is_temp or not self._encryptor:
- await self._run_in_threadpool(
- agfs_cp, self.agfs, old_path, new_path, recursive=is_dir
- )
+ await self._async_agfs.cp(old_path, new_path, recursive=is_dir)
else:
if is_dir:
await self._recursive_copy_dir_with_encryption(old_uri, new_uri, ctx=ctx)
@@ -609,7 +603,7 @@ class VikingFS:
if is_dir and (is_temp or not self._encryptor):
carried_lock = new_path.rstrip("/") + "/.path.ovlock"
try:
- await self._run_in_threadpool(self.agfs.rm, carried_lock)
+ await self._async_agfs.rm(carried_lock)
except Exception:
pass
@@ -619,15 +613,15 @@ class VikingFS:
except Exception:
try:
if is_dir:
- await self._run_in_threadpool(self.agfs.rm, new_path, recursive=True)
+ await self._async_agfs.rm(new_path, recursive=True)
else:
- await self._run_in_threadpool(self.agfs.rm, new_path)
+ await self._async_agfs.rm(new_path)
except Exception:
pass
raise
# Delete source
- await self._run_in_threadpool(self.agfs.rm, old_path, recursive=is_dir)
+ await self._async_agfs.rm(old_path, recursive=is_dir)
return {}
async def _recursive_copy_dir_with_encryption(
@@ -766,8 +760,7 @@ class VikingFS:
excluded_path = self._uri_to_path(normalized_excluded_uri, ctx=ctx)
try:
- result = await asyncio.to_thread(
- self.agfs.grep,
+ result = await self._async_agfs.grep(
path=path,
pattern=pattern,
recursive=True,
@@ -951,7 +944,7 @@ class VikingFS:
try:
self._ensure_access(entry_uri, ctx)
path = self._uri_to_path(entry_uri, ctx=ctx)
- result = await self._run_in_threadpool(self.agfs.read, path, 0, -1)
+ result = await self._async_agfs.read(path, 0, -1)
if isinstance(result, bytes):
content = result
elif result is not None and hasattr(result, "content"):
@@ -1006,9 +999,9 @@ class VikingFS:
"""
self._ensure_access(uri, ctx)
path = self._uri_to_path(uri, ctx=ctx)
- result = await self._run_in_threadpool(self.agfs.stat, path)
+ result = await self._async_agfs.stat(path)
if isinstance(result, dict):
- result["isLocked"] = self._is_path_locked(path)
+ result["isLocked"] = await self._is_path_locked_async(path)
# Add count for directories if vector store available
if result.get("isDir", False):
try:
@@ -1024,12 +1017,12 @@ class VikingFS:
logger.warning(f"[VikingFS] Failed to count nodes for directory stat: {e}")
return result
- def _is_path_locked(self, path: str) -> bool:
- """Best-effort path-lock lookup; returns False when LockManager is absent."""
+ async def _is_path_locked_async(self, path: str) -> bool:
+ """Best-effort async path-lock lookup; returns False when LockManager is absent."""
try:
from openviking.storage.transaction import get_lock_manager
- return get_lock_manager().is_path_locked(path)
+ return await get_lock_manager().is_path_locked_async(path)
except Exception:
return False
@@ -1240,7 +1233,7 @@ class VikingFS:
self._ensure_access(uri, ctx)
path = self._uri_to_path(uri, ctx=ctx)
try:
- info = await self._run_in_threadpool(self.agfs.stat, path)
+ info = await self._async_agfs.stat(path)
except Exception as exc:
mapped = map_exception(exc, resource=uri)
if mapped is not None:
@@ -1253,9 +1246,7 @@ class VikingFS:
)
file_path = f"{path}/.abstract.md"
try:
- content_bytes = self._handle_agfs_read(
- await self._run_in_threadpool(self.agfs.read, file_path)
- )
+ content_bytes = self._handle_agfs_read(await self._async_agfs.read(file_path))
except Exception as exc:
if not is_not_found_error(exc):
mapped = map_exception(exc, resource=uri)
@@ -1280,7 +1271,7 @@ class VikingFS:
self._ensure_access(uri, ctx)
path = self._uri_to_path(uri, ctx=ctx)
try:
- info = await self._run_in_threadpool(self.agfs.stat, path)
+ info = await self._async_agfs.stat(path)
except Exception as exc:
mapped = map_exception(exc, resource=uri)
if mapped is not None:
@@ -1293,9 +1284,7 @@ class VikingFS:
)
file_path = f"{path}/.overview.md"
try:
- content_bytes = self._handle_agfs_read(
- await self._run_in_threadpool(self.agfs.read, file_path)
- )
+ content_bytes = self._handle_agfs_read(await self._async_agfs.read(file_path))
except Exception as exc:
if not is_not_found_error(exc):
mapped = map_exception(exc, resource=uri)
@@ -1710,7 +1699,7 @@ class VikingFS:
At account root (/local/{account}), uses LISTABLE_SCOPES whitelist.
At other levels, uses _INTERNAL_NAMES blacklist.
"""
- entries = await self._run_in_threadpool(self.agfs.ls, path)
+ entries = await self._async_agfs.ls(path)
parts = [p for p in path.strip("/").split("/") if p]
if len(parts) == 2 and parts[0] == "local":
return [e for e in entries if e.get("name") in VikingURI.LISTABLE_SCOPES]
@@ -2014,14 +2003,25 @@ class VikingFS:
async def _ensure_parent_dirs(self, path: str) -> None:
"""Recursively create all parent directories."""
- parts = path.lstrip("/").split("/")
- for i in range(1, len(parts)):
- parent = "/" + "/".join(parts[:i])
+ try:
+ await self._async_agfs.ensure_parent_dirs(path)
+ except Exception as e:
+ logger.debug(f"Failed to ensure parent directories for {path}: {e}")
+ parent = path.rstrip("/").rsplit("/", 1)[0]
+ await self._mkdir_path_with_parents(parent)
+
+ async def _mkdir_path_with_parents(self, dir_path: str) -> None:
+ parts = [part for part in dir_path.strip("/").split("/") if part]
+ current = ""
+ for part in parts:
+ current = f"{current}/{part}"
try:
- await self._run_in_threadpool(self.agfs.mkdir, parent)
+ await self._async_agfs.mkdir(current)
except Exception as e:
- if "exist" not in str(e).lower() and "already" not in str(e).lower():
- logger.debug(f"Failed to create parent directory {parent}: {e}")
+ message = str(e).lower()
+ if "exist" in message or "already" in message:
+ continue
+ logger.debug(f"Failed to create parent directory {current}: {e}")
# ========== Relation Table Internal Methods ==========
@@ -2031,9 +2031,7 @@ class VikingFS:
"""Read .relations.json."""
table_path = f"{dir_path}/.relations.json"
try:
- content = self._handle_agfs_read(
- await self._run_in_threadpool(self.agfs.read, table_path)
- )
+ content = self._handle_agfs_read(await self._async_agfs.read(table_path))
content = await self._decrypt_content(content, ctx=ctx)
data = json.loads(content.decode("utf-8"))
except FileNotFoundError:
@@ -2069,7 +2067,7 @@ class VikingFS:
content = content.encode("utf-8")
content = await self._encrypt_content(content, ctx=ctx)
- await self._run_in_threadpool(self.agfs.write, table_path, content)
+ await self._async_agfs.write(table_path, content)
# ========== Batch Read (backward compatible) ==========
@@ -2107,7 +2105,7 @@ class VikingFS:
content = content.encode("utf-8")
content = await self._encrypt_content(content, ctx=ctx)
- await self._run_in_threadpool(self.agfs.write, path, content)
+ await self._async_agfs.write(path, content)
async def read_file(
self,
@@ -2131,7 +2129,7 @@ class VikingFS:
# Verify the file exists before reading, because AGFS read returns
# empty bytes for non-existent files instead of raising an error.
try:
- stat = await self._run_in_threadpool(self.agfs.stat, path)
+ stat = await self._async_agfs.stat(path)
except Exception:
raise NotFoundError(uri, "file")
if isinstance(stat, dict) and stat.get("isDir", False):
@@ -2140,7 +2138,7 @@ class VikingFS:
details={"resource": uri, "expected": "file", "actual": "directory"},
)
try:
- content = await self._run_in_threadpool(self.agfs.read, path)
+ content = await self._async_agfs.read(path)
if isinstance(content, bytes):
raw = content
elif content is not None and hasattr(content, "content"):
@@ -2171,7 +2169,7 @@ class VikingFS:
self._ensure_access(uri, ctx)
path = self._uri_to_path(uri, ctx=ctx)
try:
- stat = await self._run_in_threadpool(self.agfs.stat, path)
+ stat = await self._async_agfs.stat(path)
except Exception:
raise NotFoundError(uri, "file")
if isinstance(stat, dict) and stat.get("isDir", False):
@@ -2180,7 +2178,7 @@ class VikingFS:
details={"resource": uri, "expected": "file", "actual": "directory"},
)
try:
- raw = self._handle_agfs_read(await self._run_in_threadpool(self.agfs.read, path))
+ raw = self._handle_agfs_read(await self._async_agfs.read(path))
raw = await self._decrypt_content(raw, ctx=ctx)
return raw
except Exception:
@@ -2198,7 +2196,7 @@ class VikingFS:
await self._ensure_parent_dirs(path)
content = await self._encrypt_content(content, ctx=ctx)
- await self._run_in_threadpool(self.agfs.write, path, content)
+ await self._async_agfs.write(path, content)
async def append_file(
self,
@@ -2213,9 +2211,7 @@ class VikingFS:
try:
existing = ""
try:
- existing_bytes = self._handle_agfs_read(
- await self._run_in_threadpool(self.agfs.read, path)
- )
+ existing_bytes = self._handle_agfs_read(await self._async_agfs.read(path))
existing_bytes = await self._decrypt_content(existing_bytes, ctx=ctx)
existing = self._decode_bytes(existing_bytes)
except FileNotFoundError:
@@ -2229,7 +2225,7 @@ class VikingFS:
await self._ensure_parent_dirs(path)
final_content = (existing + content).encode("utf-8")
final_content = await self._encrypt_content(final_content, ctx=ctx)
- await self._run_in_threadpool(self.agfs.write, path, final_content)
+ await self._async_agfs.write(path, final_content)
except Exception as e:
logger.error(f"[VikingFS] Failed to append to file {uri}: {e}")
@@ -2365,7 +2361,7 @@ class VikingFS:
content_bytes = await self.read_file_bytes(from_uri, ctx=ctx)
await self.write_file(to_uri, content_bytes, ctx=ctx)
- await self._run_in_threadpool(self.agfs.rm, from_path)
+ await self._async_agfs.rm(from_path)
# ========== Temp File Operations (backward compatible) ==========
@@ -2380,6 +2376,20 @@ class VikingFS:
return VikingURI.create_temp_uri()
return VikingURI.create_temp_uri(space=real_ctx.user.user_space_name())
+ async def persist_temp_tree(
+ self,
+ temp_uri: str,
+ target_uri: str,
+ ctx: Optional[RequestContext] = None,
+ ) -> None:
+ """Persist an already-encrypted temp tree without rewriting file bytes."""
+ self._ensure_access(temp_uri, ctx)
+ self._ensure_mutable_access(target_uri, ctx)
+ src_path = self._uri_to_path(temp_uri, ctx=ctx)
+ dst_path = self._uri_to_path(target_uri, ctx=ctx)
+ await self._ensure_parent_dirs(dst_path)
+ await self._async_agfs.cp(src_path, dst_path, recursive=True)
+
async def delete_temp(self, temp_uri: str, ctx: Optional[RequestContext] = None) -> None:
"""Delete temp directory and its contents."""
self._ensure_mutable_access(temp_uri, ctx)
@@ -2393,8 +2403,8 @@ class VikingFS:
if entry.get("isDir"):
await self.delete_temp(f"{temp_uri}/{name}", ctx=ctx)
else:
- await self._run_in_threadpool(self.agfs.rm, entry_path)
- await self._run_in_threadpool(self.agfs.rm, path)
+ await self._async_agfs.rm(entry_path)
+ await self._async_agfs.rm(path)
except Exception as e:
logger.warning(f"[VikingFS] Failed to delete temp {temp_uri}: {e}")
@@ -2456,7 +2466,7 @@ class VikingFS:
try:
await self._ensure_parent_dirs(path)
try:
- await self._run_in_threadpool(self.agfs.mkdir, path)
+ await self._async_agfs.mkdir(path)
except Exception as e:
if "exist" not in str(e).lower():
raise
diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.py
index 59f437447..02fff3bca 100644
--- a/openviking/storage/viking_vector_index_backend.py
+++ b/openviking/storage/viking_vector_index_backend.py
@@ -72,6 +72,27 @@ URI_REWRITE_OUTPUT_FIELDS = [
]
+class _AsyncVectorAdapter:
+ """Thread-offloaded facade for sync vector adapters."""
+
+ def __init__(self, adapter: Any):
+ self._adapter = adapter
+
+ async def call(self, method_name: str, /, *args: Any, **kwargs: Any) -> Any:
+ return await asyncio.to_thread(getattr(self._adapter, method_name), *args, **kwargs)
+
+ async def run(self, func: Any, /, *args: Any, **kwargs: Any) -> Any:
+ return await asyncio.to_thread(func, *args, **kwargs)
+
+ async def collection_meta(self) -> Dict[str, Any]:
+ return await asyncio.to_thread(lambda: self._adapter.get_collection().get_meta_data() or {})
+
+ async def update_collection_description(self, description: str) -> None:
+ await asyncio.to_thread(
+ lambda: self._adapter.get_collection().update(description=description)
+ )
+
+
class _SingleAccountBackend:
"""绑定单个 account 的后端实现(内部类)"""
@@ -95,6 +116,7 @@ class _SingleAccountBackend:
"""
self._bound_account_id = bound_account_id
self._adapter = shared_adapter or create_collection_adapter(config)
+ self._async_adapter = _AsyncVectorAdapter(self._adapter)
self._collection_config: Dict[str, Any] = {}
self._meta_data_cache: Dict[str, Any] = {}
self._mode = self._adapter.mode
@@ -135,6 +157,9 @@ class _SingleAccountBackend:
filtered = self._filter_known_fields(payload)
return {k: v for k, v in filtered.items() if v is not None}
+ async def _refresh_meta_data_async(self) -> None:
+ self._meta_data_cache = await self._async_adapter.collection_meta()
+
# =========================================================================
# Collection Management
# =========================================================================
@@ -148,7 +173,8 @@ class _SingleAccountBackend:
vector_dim = field.get("Dim")
break
- created = self._adapter.create_collection(
+ created = await self._async_adapter.call(
+ "create_collection",
name=name,
schema=collection_meta,
distance=self._distance_metric,
@@ -163,7 +189,7 @@ class _SingleAccountBackend:
"distance": self._distance_metric,
"schema": schema,
}
- self._refresh_meta_data(self._get_collection())
+ await self._refresh_meta_data_async()
logger.info("Created collection: %s", name)
return True
except Exception as e:
@@ -172,7 +198,7 @@ class _SingleAccountBackend:
async def drop_collection(self) -> bool:
try:
- dropped = self._adapter.drop_collection()
+ dropped = await self._async_adapter.call("drop_collection")
if dropped:
self._collection_config = {}
self._meta_data_cache = {}
@@ -182,9 +208,7 @@ class _SingleAccountBackend:
return False
async def collection_exists(self) -> bool:
- # Some adapters perform blocking HTTP requests (for example via
- # requests), so move the existence check off the event loop.
- return await asyncio.to_thread(self._adapter.collection_exists)
+ return await self._async_adapter.call("collection_exists")
async def get_collection_info(self) -> Optional[Dict[str, Any]]:
if not await self.collection_exists():
@@ -200,14 +224,13 @@ class _SingleAccountBackend:
async def get_collection_meta(self) -> Optional[Dict[str, Any]]:
if not await self.collection_exists():
return None
- return self._get_collection().get_meta_data()
+ return await self._async_adapter.collection_meta()
async def update_collection_description(self, description: str) -> bool:
if not await self.collection_exists():
return False
- coll = self._get_collection()
- coll.update(description=description)
- self._refresh_meta_data(coll)
+ await self._async_adapter.update_collection_description(description)
+ await self._refresh_meta_data_async()
return True
# =========================================================================
@@ -238,13 +261,13 @@ class _SingleAccountBackend:
if not payload.get("id"):
payload["id"] = str(uuid.uuid4())
- payload = self._prepare_upsert_payload(payload)
- ids = self._adapter.upsert(payload)
+ payload = await self._async_adapter.run(self._prepare_upsert_payload, payload)
+ ids = await self._async_adapter.call("upsert", payload)
return ids[0] if ids else ""
async def get(self, ids: List[str]) -> List[Dict[str, Any]]:
try:
- records = await asyncio.to_thread(self._adapter.get, ids)
+ records = await self._async_adapter.call("get", ids)
if self._bound_account_id:
records = [r for r in records if r.get("account_id") == self._bound_account_id]
return records
@@ -261,7 +284,7 @@ class _SingleAccountBackend:
logger.warning("Attempted to delete records outside bound account")
ids = valid_ids
- return self._adapter.delete(ids=ids)
+ return await self._async_adapter.call("delete", ids=ids)
except Exception as e:
logger.error("Error deleting records: %s", e)
return 0
@@ -269,7 +292,7 @@ class _SingleAccountBackend:
async def delete_by_filter(self, filter: FilterExpr) -> int:
"""Root-only: 直接通过 filter 删除"""
try:
- return self._adapter.delete(filter=filter)
+ return await self._async_adapter.call("delete", filter=filter)
except Exception as e:
logger.error("Error deleting by filter: %s", e)
return 0
@@ -321,8 +344,8 @@ class _SingleAccountBackend:
f"[_SingleAccountBackend.query] Applied account filter, final filter={filter}"
)
- return await asyncio.to_thread(
- self._adapter.query,
+ return await self._async_adapter.call(
+ "query",
query_vector=query_vector,
sparse_query_vector=sparse_query_vector,
filter=filter,
@@ -440,7 +463,7 @@ class _SingleAccountBackend:
else:
filter = account_filter
- return self._adapter.count(filter=filter)
+ return await self._async_adapter.call("count", filter=filter)
except Exception as e:
logger.error("Error counting records: %s", e)
return 0
@@ -449,7 +472,7 @@ class _SingleAccountBackend:
try:
if self._bound_account_id:
return await self.delete_by_filter(Eq("account_id", self._bound_account_id)) > 0
- return self._adapter.clear()
+ return await self._async_adapter.call("clear")
except Exception as e:
logger.error("Error clearing collection: %s", e)
return False
@@ -460,7 +483,7 @@ class _SingleAccountBackend:
async def close(self) -> None:
try:
- self._adapter.close()
+ await self._async_adapter.call("close")
self._collection_config = {}
self._meta_data_cache = {}
logger.info("_SingleAccountBackend closed")
diff --git a/openviking/utils/resource_processor.py b/openviking/utils/resource_processor.py
index 6a6656e5e..f76ebb8a7 100644
--- a/openviking/utils/resource_processor.py
+++ b/openviking/utils/resource_processor.py
@@ -7,7 +7,6 @@ Handles coordinated writes and self-iteration processes
as described in the OpenViking design document.
"""
-import asyncio
import time
from typing import TYPE_CHECKING, Any, Dict, List, Optional
@@ -336,18 +335,8 @@ class ResourceProcessor:
if resource_lock.active:
if not should_summarize and temp_uri:
- from openviking.pyagfs.helpers import cp as agfs_cp
-
viking_fs = get_viking_fs()
- src_path = viking_fs._uri_to_path(temp_uri, ctx=ctx)
- dst_path = viking_fs._uri_to_path(root_uri, ctx=ctx)
- await asyncio.to_thread(
- agfs_cp,
- viking_fs.agfs,
- src_path,
- dst_path,
- recursive=True,
- )
+ await viking_fs.persist_temp_tree(temp_uri, root_uri, ctx=ctx)
await viking_fs.delete_temp(parse_result.temp_dir_path, ctx=ctx)
await resource_lock.close()
diff --git a/tests/agfs/test_async_client.py b/tests/agfs/test_async_client.py
new file mode 100644
index 000000000..201a06b96
--- /dev/null
+++ b/tests/agfs/test_async_client.py
@@ -0,0 +1,47 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import pytest
+
+import openviking.pyagfs.async_client as async_client
+from openviking.pyagfs import AsyncAGFSClient
+
+
+class _SyncAGFS:
+ def read(self, path, **kwargs):
+ return ("read", path, kwargs)
+
+ def write(self, path, data, **kwargs):
+ return ("write", path, data, kwargs)
+
+ def rm(self, path, **kwargs):
+ return ("rm", path, kwargs)
+
+
+async def test_async_agfs_client_hides_threadpool(monkeypatch):
+ to_thread_calls = []
+
+ async def fake_to_thread(func, *args, **kwargs):
+ to_thread_calls.append((func.__name__, args, kwargs))
+ return func(*args, **kwargs)
+
+ monkeypatch.setattr(async_client.asyncio, "to_thread", fake_to_thread)
+
+ sync_agfs = _SyncAGFS()
+ agfs = AsyncAGFSClient(sync_agfs)
+
+ assert agfs.sync_client is sync_agfs
+ assert await agfs.write("/tasks/1", b"data") == ("write", "/tasks/1", b"data", {})
+ assert await agfs.read("/queue/dequeue") == ("read", "/queue/dequeue", {})
+ assert await agfs.rm("/redo/id", recursive=True) == (
+ "rm",
+ "/redo/id",
+ {"recursive": True},
+ )
+
+ assert to_thread_calls == [
+ ("write", ("/tasks/1", b"data"), {}),
+ ("read", ("/queue/dequeue",), {}),
+ ("rm", ("/redo/id",), {"recursive": True}),
+ ]
diff --git a/tests/misc/test_resource_processor_mv.py b/tests/misc/test_resource_processor_mv.py
index 145d07168..d26be743a 100644
--- a/tests/misc/test_resource_processor_mv.py
+++ b/tests/misc/test_resource_processor_mv.py
@@ -117,6 +117,9 @@ class _FakeVikingFS:
async def delete_temp(self, temp_dir_path, ctx=None):
return None
+ async def persist_temp_tree(self, temp_uri, target_uri, ctx=None):
+ self.agfs.write(self._uri_to_path(target_uri, ctx=ctx), b"content")
+
def _uri_to_path(self, uri, ctx=None):
return f"/mock/{uri.replace('viking://', '')}"
diff --git a/tests/server/test_api_resources.py b/tests/server/test_api_resources.py
index 06f7560e9..a65417e03 100644
--- a/tests/server/test_api_resources.py
+++ b/tests/server/test_api_resources.py
@@ -825,7 +825,7 @@ async def test_monitor_marks_failed_on_queue_error(
await asyncio.sleep(1.0)
- task = get_task_tracker().get(task_id)
+ task = await get_task_tracker().get(task_id)
assert task is not None
assert task.status.value == "failed", f"Expected failed, got {task.status.value}"
assert "queue processing failed" in task.error
diff --git a/tests/server/test_auth.py b/tests/server/test_auth.py
index b2692041d..9a848aa4b 100644
--- a/tests/server/test_auth.py
+++ b/tests/server/test_auth.py
@@ -320,13 +320,13 @@ async def test_task_endpoints_are_user_scoped():
reset_task_tracker()
account_id = _uid()
tracker = get_task_tracker()
- alice_task = tracker.create(
+ alice_task = await tracker.create(
"session_commit",
resource_id="alice-session",
account_id=account_id,
user_id="alice",
)
- bob_task = tracker.create(
+ bob_task = await tracker.create(
"session_commit",
resource_id="bob-session",
account_id=account_id,
diff --git a/tests/session/conftest.py b/tests/session/conftest.py
index a5ad6c58f..d49df6270 100644
--- a/tests/session/conftest.py
+++ b/tests/session/conftest.py
@@ -23,7 +23,9 @@ async def _drain_background_tasks(client: AsyncOpenViking):
tracker = get_task_tracker()
for _ in range(100): # up to 10s
pending = [
- t for t in tracker.list_tasks() if t.status in (TaskStatus.PENDING, TaskStatus.RUNNING)
+ t
+ for t in await tracker.list_tasks()
+ if t.status in (TaskStatus.PENDING, TaskStatus.RUNNING)
]
if not pending:
break
diff --git a/tests/session/memory/test_compressor_v2.py b/tests/session/memory/test_compressor_v2.py
index 594b4537f..01e1a0a66 100644
--- a/tests/session/memory/test_compressor_v2.py
+++ b/tests/session/memory/test_compressor_v2.py
@@ -15,12 +15,13 @@ import pytest
from openviking.message import Message, TextPart
from openviking.server.identity import RequestContext, Role
+from openviking.session import compressor_v2 as compressor_v2_module
from openviking.session.compressor_v2 import SessionCompressorV2
from openviking.session.memory.dataclass import MemoryField, MemoryFile, MemoryTypeSchema
+from openviking.session.memory.extract_loop import ExtractLoop
from openviking.session.memory.memory_isolation_handler import RoleScope
from openviking.session.memory.memory_updater import ExtractContext, MemoryUpdateResult
from openviking.session.memory.merge_op import FieldType, MergeOp
-from openviking.session.memory.extract_loop import ExtractLoop
from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils.config import get_openviking_config, initialize_openviking_config
@@ -281,6 +282,28 @@ def create_test_conversation() -> List[Message]:
class TestCompressorV2:
"""Tests for SessionCompressorV2."""
+ @pytest.mark.asyncio
+ async def test_memory_lock_retry_logging_is_throttled(self, monkeypatch):
+ warnings = []
+ debug_logs = []
+ monkeypatch.setattr(compressor_v2_module.logger, "warning", warnings.append)
+ monkeypatch.setattr(compressor_v2_module.logger, "debug", debug_logs.append)
+
+ last_warning_at = compressor_v2_module._log_memory_lock_retry(
+ retry_count=1,
+ max_retries=0,
+ last_warning_at=0.0,
+ )
+ compressor_v2_module._log_memory_lock_retry(
+ retry_count=2,
+ max_retries=0,
+ last_warning_at=last_warning_at,
+ )
+
+ assert len(warnings) == 1
+ assert "attempt=1" in warnings[0]
+ assert debug_logs == []
+
@pytest.mark.asyncio
async def test_extract_long_term_memories_includes_latest_archive_overview(self):
"""Latest archive overview should be prepended to the v2 conversation context."""
@@ -789,7 +812,10 @@ class TestExtractLoopPatchRepair:
assert "Regenerate the complete operations JSON" in second_call_content
assert target_uri in second_call_content
assert other_uri in second_call_content
- assert operations.upsert_operations[0].memory_fields["content"].blocks[0].search == "- Likes reading"
+ assert (
+ operations.upsert_operations[0].memory_fields["content"].blocks[0].search
+ == "- Likes reading"
+ )
@pytest.mark.asyncio
async def test_invalid_patch_search_repairs_only_once(self):
@@ -883,7 +909,10 @@ class TestExtractLoopPatchRepair:
message["content"] for call_messages in vlm.messages for message in call_messages
)
assert all_messages.count("SEARCH/REPLACE patch could not be applied") == 1
- assert operations.upsert_operations[0].memory_fields["content"].blocks[0].search == "- Missing two"
+ assert (
+ operations.upsert_operations[0].memory_fields["content"].blocks[0].search
+ == "- Missing two"
+ )
@pytest.mark.asyncio
async def test_fuzzy_patch_success_does_not_trigger_repair(self):
@@ -972,4 +1001,7 @@ class TestExtractLoopPatchRepair:
operations, _tools_used = await loop.run()
assert len(vlm.messages) == 1
- assert operations.upsert_operations[0].memory_fields["content"].blocks[0].search == "- Likes reading"
+ assert (
+ operations.upsert_operations[0].memory_fields["content"].blocks[0].search
+ == "- Likes reading"
+ )
diff --git a/tests/session/test_session_commit.py b/tests/session/test_session_commit.py
index a71ee0a5c..490710999 100644
--- a/tests/session/test_session_commit.py
+++ b/tests/session/test_session_commit.py
@@ -21,7 +21,7 @@ async def _wait_for_task(task_id: str, timeout: float = 30.0) -> dict:
"""Poll the task tracker until the task reaches a terminal state."""
tracker = get_task_tracker()
for _ in range(int(timeout / 0.1)):
- task = tracker.get(task_id)
+ task = await tracker.get(task_id)
if task and task.status.value in ("completed", "failed"):
return task.to_dict()
await asyncio.sleep(0.1)
diff --git a/tests/session/test_session_context.py b/tests/session/test_session_context.py
index 2dbb7f71d..cc60c4392 100644
--- a/tests/session/test_session_context.py
+++ b/tests/session/test_session_context.py
@@ -105,7 +105,7 @@ def _estimate_tokens(text: str) -> int:
async def _wait_for_task(task_id: str, timeout: float = 30.0) -> dict:
tracker = get_task_tracker()
for _ in range(int(timeout / 0.1)):
- task = tracker.get(task_id)
+ task = await tracker.get(task_id)
if task and task.status.value in ("completed", "failed"):
return task.to_dict()
await asyncio.sleep(0.1)
diff --git a/tests/storage/test_collection_schemas.py b/tests/storage/test_collection_schemas.py
index 8b692e616..e071ee153 100644
--- a/tests/storage/test_collection_schemas.py
+++ b/tests/storage/test_collection_schemas.py
@@ -17,8 +17,8 @@ from openviking.storage.collection_schemas import (
_build_embedding_metadata,
init_context_collection,
)
-from openviking.storage.expr import Eq
from openviking.storage.errors import EmbeddingRebuildRequiredError
+from openviking.storage.expr import Eq
from openviking.storage.queuefs.embedding_msg import EmbeddingMsg
from openviking.storage.viking_vector_index_backend import _SingleAccountBackend
from openviking_cli.utils.config.vectordb_config import VectorDBBackendConfig
@@ -689,7 +689,9 @@ async def test_single_account_backend_collection_exists_runs_in_threadpool(monke
called["kwargs"] = kwargs
return func(*args, **kwargs)
- monkeypatch.setattr("openviking.storage.viking_vector_index_backend.asyncio.to_thread", _fake_to_thread)
+ monkeypatch.setattr(
+ "openviking.storage.viking_vector_index_backend.asyncio.to_thread", _fake_to_thread
+ )
backend = _SingleAccountBackend(
config=VectorDBBackendConfig(backend="local", name="context", dimension=2),
@@ -704,6 +706,122 @@ async def test_single_account_backend_collection_exists_runs_in_threadpool(monke
assert called["kwargs"] == {}
+async def test_single_account_backend_upsert_runs_adapter_in_threadpool(monkeypatch):
+ calls = []
+
+ class _Collection:
+ def get_meta_data(self):
+ return {
+ "Fields": [
+ {"FieldName": "id"},
+ {"FieldName": "uri"},
+ {"FieldName": "abstract"},
+ {"FieldName": "account_id"},
+ ]
+ }
+
+ class _Adapter:
+ mode = "local"
+
+ def get_collection(self):
+ return _Collection()
+
+ def upsert(self, data):
+ return [data["id"]]
+
+ async def _fake_to_thread(func, /, *args, **kwargs):
+ calls.append((func.__name__, args, kwargs))
+ return func(*args, **kwargs)
+
+ monkeypatch.setattr(
+ "openviking.storage.viking_vector_index_backend.asyncio.to_thread", _fake_to_thread
+ )
+
+ backend = _SingleAccountBackend(
+ config=VectorDBBackendConfig(backend="local", name="context", dimension=2),
+ bound_account_id="acc1",
+ shared_adapter=_Adapter(),
+ )
+
+ record_id = await backend.upsert(
+ {
+ "id": "rec-1",
+ "uri": "viking://resources/sample",
+ "abstract": "sample",
+ "account_id": "acc1",
+ "unknown": "legacy",
+ }
+ )
+
+ assert record_id == "rec-1"
+ assert [call[0] for call in calls] == ["_prepare_upsert_payload", "upsert"]
+ assert calls[-1][1] == (
+ {
+ "id": "rec-1",
+ "uri": "viking://resources/sample",
+ "abstract": "sample",
+ "account_id": "acc1",
+ },
+ )
+
+
+async def test_single_account_backend_mutations_run_adapter_in_threadpool(monkeypatch):
+ calls = []
+
+ class _Adapter:
+ mode = "local"
+
+ def drop_collection(self):
+ return True
+
+ def delete(self, **kwargs):
+ calls.append(("adapter_delete_kwargs", kwargs))
+ return 2
+
+ def count(self, **kwargs):
+ calls.append(("adapter_count_kwargs", kwargs))
+ return 3
+
+ def clear(self):
+ return True
+
+ def close(self):
+ return None
+
+ async def _fake_to_thread(func, /, *args, **kwargs):
+ calls.append((func.__name__, args, kwargs))
+ return func(*args, **kwargs)
+
+ monkeypatch.setattr(
+ "openviking.storage.viking_vector_index_backend.asyncio.to_thread", _fake_to_thread
+ )
+
+ backend = _SingleAccountBackend(
+ config=VectorDBBackendConfig(backend="local", name="context", dimension=2),
+ bound_account_id=None,
+ shared_adapter=_Adapter(),
+ )
+ filter_expr = Eq("account_id", "acc1")
+
+ assert await backend.drop_collection() is True
+ assert await backend.delete(["rec-1"]) == 2
+ assert await backend.delete_by_filter(filter_expr) == 2
+ assert await backend.count(filter=filter_expr) == 3
+ assert await backend.clear() is True
+ await backend.close()
+
+ assert [call[0] for call in calls if not call[0].startswith("adapter_")] == [
+ "drop_collection",
+ "delete",
+ "delete",
+ "count",
+ "clear",
+ "close",
+ ]
+
+
@pytest.mark.asyncio
async def test_single_account_backend_query_runs_adapter_in_threadpool(monkeypatch):
called = {}
@@ -735,7 +853,9 @@ async def test_single_account_backend_query_runs_adapter_in_threadpool(monkeypat
called["kwargs"] = kwargs
return func(*args, **kwargs)
- monkeypatch.setattr("openviking.storage.viking_vector_index_backend.asyncio.to_thread", _fake_to_thread)
+ monkeypatch.setattr(
+ "openviking.storage.viking_vector_index_backend.asyncio.to_thread", _fake_to_thread
+ )
backend = _SingleAccountBackend(
config=VectorDBBackendConfig(backend="local", name="context", dimension=2),
diff --git a/tests/storage/test_viking_fs_async_stat.py b/tests/storage/test_viking_fs_async_stat.py
new file mode 100644
index 000000000..920e53f07
--- /dev/null
+++ b/tests/storage/test_viking_fs_async_stat.py
@@ -0,0 +1,36 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import pytest
+
+import openviking.storage.transaction as transaction_module
+from openviking.storage.viking_fs import VikingFS
+
+
+class _StatAGFS:
+ def stat(self, path):
+ return {"name": path.rsplit("/", 1)[-1], "isDir": False}
+
+
+class _AsyncOnlyLockManager:
+ def __init__(self):
+ self.paths = []
+
+ async def is_path_locked_async(self, path, ignore_stale=True):
+ self.paths.append((path, ignore_stale))
+ return True
+
+ def is_path_locked(self, path, ignore_stale=True):
+ raise AssertionError("stat() should use the async lock lookup")
+
+
+async def test_stat_uses_async_lock_lookup(monkeypatch):
+ lock_manager = _AsyncOnlyLockManager()
+ monkeypatch.setattr(transaction_module, "get_lock_manager", lambda: lock_manager)
+
+ fs = VikingFS(agfs=_StatAGFS())
+ result = await fs.stat("viking://resources/file.txt")
+
+ assert result["isLocked"] is True
+ assert lock_manager.paths == [("/local/default/resources/file.txt", True)]
diff --git a/tests/storage/test_viking_fs_grep.py b/tests/storage/test_viking_fs_grep.py
index d6aed7a13..8fea8283b 100644
--- a/tests/storage/test_viking_fs_grep.py
+++ b/tests/storage/test_viking_fs_grep.py
@@ -36,7 +36,7 @@ async def test_grep_preserves_dfs_order_and_node_limit(monkeypatch):
}
return entries.get(uri, [])
- def fake_agfs_read(path, offset, size):
+ def fake_agfs_read(path, offset=0, size=-1):
contents = {
"/resources/dir_a/a1.md": "match a1 line1\nskip\nmatch a1 line3",
"/resources/dir_a/a2.md": "match a2 line1",
@@ -92,7 +92,7 @@ async def test_grep_parallel_reads_respect_concurrency_limit(monkeypatch):
active_reads = 0
max_active_reads = 0
- def fake_agfs_read(path, offset, size):
+ def fake_agfs_read(path, offset=0, size=-1):
nonlocal active_reads, max_active_reads
active_reads += 1
max_active_reads = max(max_active_reads, active_reads)
@@ -129,7 +129,7 @@ async def test_grep_parallel_reads_work_with_blocking_agfs_read(monkeypatch):
return [{"name": f"file{i}.md", "isDir": False} for i in range(8)]
return []
- def fake_agfs_read(path, offset, size):
+ def fake_agfs_read(path, offset=0, size=-1):
time.sleep(0.05)
return f"match from {path}".encode()
@@ -165,7 +165,7 @@ async def test_grep_stops_scheduling_later_batches_after_node_limit(monkeypatch)
read_paths = []
- def fake_agfs_read(path, offset, size):
+ def fake_agfs_read(path, offset=0, size=-1):
read_paths.append(path)
contents = {
"/resources/file0.md": "match file0 line1\nmatch file0 line2",
diff --git a/tests/test_session_async_commit.py b/tests/test_session_async_commit.py
index 3ce9e7dad..de0249d60 100644
--- a/tests/test_session_async_commit.py
+++ b/tests/test_session_async_commit.py
@@ -92,7 +92,7 @@ async def test_commit_endpoint_returns_accepted_with_task_id(api_client):
if task_id:
tracker = get_task_tracker()
for _ in range(300):
- task = tracker.get(task_id)
+ task = await tracker.get(task_id)
if task and task.status in (TaskStatus.COMPLETED, TaskStatus.FAILED):
break
await asyncio.sleep(0.1)
diff --git a/tests/test_session_task_tracking.py b/tests/test_session_task_tracking.py
index 617580ac7..839524a9d 100644
--- a/tests/test_session_task_tracking.py
+++ b/tests/test_session_task_tracking.py
@@ -64,9 +64,9 @@ def _make_tracked_commit(behavior="instant", result_overrides=None, gate=None, s
started: asyncio.Event to set when background task starts (for "gated")
"""
- async def mock_commit(_sid, _ctx):
+ async def mock_commit(_sid, _ctx, **_kwargs):
tracker = get_task_tracker()
- task = tracker.create(
+ task = await tracker.create(
"session_commit",
resource_id=_sid,
account_id=_ctx.account_id,
@@ -75,7 +75,7 @@ def _make_tracked_commit(behavior="instant", result_overrides=None, gate=None, s
archive_uri = f"viking://session/test/{_sid}/history/archive_001"
async def _background():
- tracker.start(task.task_id, account_id=_ctx.account_id, user_id=_ctx.user.user_id)
+ await tracker.start(task.task_id, account_id=_ctx.account_id, user_id=_ctx.user.user_id)
try:
if started:
started.set()
@@ -96,14 +96,14 @@ def _make_tracked_commit(behavior="instant", result_overrides=None, gate=None, s
}
if result_overrides:
final_result.update(result_overrides)
- tracker.complete(
+ await tracker.complete(
task.task_id,
final_result,
account_id=_ctx.account_id,
user_id=_ctx.user.user_id,
)
except Exception as e:
- tracker.fail(
+ await tracker.fail(
task.task_id,
str(e),
account_id=_ctx.account_id,
@@ -343,18 +343,18 @@ async def test_add_resource_async_returns_task_id(api_client):
async def fake_add_resource(**kwargs):
tracker = get_task_tracker()
root_uri = "viking://resources/async-test"
- task = tracker.create(
+ task = await tracker.create(
"add_resource",
resource_id=root_uri,
account_id=kwargs["ctx"].account_id,
user_id=kwargs["ctx"].user.user_id,
)
- tracker.start(
+ await tracker.start(
task.task_id,
account_id=kwargs["ctx"].account_id,
user_id=kwargs["ctx"].user.user_id,
)
- tracker.complete(
+ await tracker.complete(
task.task_id,
{"root_uri": root_uri},
account_id=kwargs["ctx"].account_id,
@@ -405,7 +405,7 @@ async def test_add_resource_async_task_lifecycle(api_client):
async def fake_add_resource(**kwargs):
tracker = get_task_tracker()
root_uri = "viking://resources/test-resource"
- task = tracker.create(
+ task = await tracker.create(
"add_resource",
resource_id=root_uri,
account_id=kwargs["ctx"].account_id,
@@ -413,13 +413,13 @@ async def test_add_resource_async_task_lifecycle(api_client):
)
async def _background():
- tracker.start(
+ await tracker.start(
task.task_id,
account_id=kwargs["ctx"].account_id,
user_id=kwargs["ctx"].user.user_id,
)
await asyncio.sleep(0.05)
- tracker.complete(
+ await tracker.complete(
task.task_id,
{"root_uri": root_uri},
account_id=kwargs["ctx"].account_id,
@@ -459,18 +459,18 @@ async def test_add_resource_task_list_filter(api_client):
async def fake_add_resource(**kwargs):
tracker = get_task_tracker()
root_uri = "viking://resources/filter-test"
- task = tracker.create(
+ task = await tracker.create(
"add_resource",
resource_id=root_uri,
account_id=kwargs["ctx"].account_id,
user_id=kwargs["ctx"].user.user_id,
)
- tracker.start(
+ await tracker.start(
task.task_id,
account_id=kwargs["ctx"].account_id,
user_id=kwargs["ctx"].user.user_id,
)
- tracker.complete(
+ await tracker.complete(
task.task_id,
{"root_uri": root_uri},
account_id=kwargs["ctx"].account_id,
@@ -504,17 +504,17 @@ async def test_add_skill_async_returns_task_id(api_client):
async def fake_add_skill(**kwargs):
tracker = get_task_tracker()
- task = tracker.create(
+ task = await tracker.create(
"add_skill",
account_id=kwargs["ctx"].account_id,
user_id=kwargs["ctx"].user.user_id,
)
- tracker.start(
+ await tracker.start(
task.task_id,
account_id=kwargs["ctx"].account_id,
user_id=kwargs["ctx"].user.user_id,
)
- tracker.complete(
+ await tracker.complete(
task.task_id,
{},
account_id=kwargs["ctx"].account_id,
diff --git a/tests/test_task_tracker.py b/tests/test_task_tracker.py
index a6b4d7d74..da1ca2501 100644
--- a/tests/test_task_tracker.py
+++ b/tests/test_task_tracker.py
@@ -21,6 +21,8 @@ from openviking.service.task_tracker import (
)
from openviking_cli.session.user_id import UserIdentifier
+pytestmark = pytest.mark.asyncio
+
@pytest.fixture(autouse=True)
def clean_singleton():
@@ -106,86 +108,86 @@ class _FakeAgfsExistingDir(_FakeAgfs):
# ── Basic CRUD ──
-def test_create_task(tracker: TaskTracker):
- task = tracker.create("session_commit", resource_id="sess-123", **_owner_kwargs())
+async def test_create_task(tracker: TaskTracker):
+ task = await tracker.create("session_commit", resource_id="sess-123", **_owner_kwargs())
assert task.task_id
assert task.task_type == "session_commit"
assert task.resource_id == "sess-123"
assert task.status == TaskStatus.PENDING
-def test_start_task(tracker: TaskTracker):
- task = tracker.create("session_commit", **_owner_kwargs())
- tracker.start(task.task_id)
- retrieved = tracker.get(task.task_id)
+async def test_start_task(tracker: TaskTracker):
+ task = await tracker.create("session_commit", **_owner_kwargs())
+ await tracker.start(task.task_id)
+ retrieved = await tracker.get(task.task_id)
assert retrieved is not None
assert retrieved.status == TaskStatus.RUNNING
-def test_complete_task(tracker: TaskTracker):
- task = tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
- tracker.start(task.task_id)
- tracker.complete(task.task_id, {"memories_extracted": 3})
- retrieved = tracker.get(task.task_id)
+async def test_complete_task(tracker: TaskTracker):
+ task = await tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
+ await tracker.start(task.task_id)
+ await tracker.complete(task.task_id, {"memories_extracted": 3})
+ retrieved = await tracker.get(task.task_id)
assert retrieved is not None
assert retrieved.status == TaskStatus.COMPLETED
assert retrieved.result == {"memories_extracted": 3}
-def test_fail_task(tracker: TaskTracker):
- task = tracker.create("session_commit", **_owner_kwargs())
- tracker.start(task.task_id)
- tracker.fail(task.task_id, "LLM timeout")
- retrieved = tracker.get(task.task_id)
+async def test_fail_task(tracker: TaskTracker):
+ task = await tracker.create("session_commit", **_owner_kwargs())
+ await tracker.start(task.task_id)
+ await tracker.fail(task.task_id, "LLM timeout")
+ retrieved = await tracker.get(task.task_id)
assert retrieved is not None
assert retrieved.status == TaskStatus.FAILED
assert "LLM timeout" in retrieved.error
-def test_get_nonexistent_returns_none(tracker: TaskTracker):
- assert tracker.get("does-not-exist") is None
+async def test_get_nonexistent_returns_none(tracker: TaskTracker):
+ assert await tracker.get("does-not-exist") is None
# ── List / Filter ──
-def test_list_all(tracker: TaskTracker):
- tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
- tracker.create("resource_ingest", resource_id="r1", **_owner_kwargs())
- tasks = tracker.list_tasks()
+async def test_list_all(tracker: TaskTracker):
+ await tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
+ await tracker.create("resource_ingest", resource_id="r1", **_owner_kwargs())
+ tasks = await tracker.list_tasks()
assert len(tasks) == 2
-def test_list_filter_by_type(tracker: TaskTracker):
- tracker.create("session_commit", **_owner_kwargs())
- tracker.create("resource_ingest", **_owner_kwargs())
- tasks = tracker.list_tasks(task_type="session_commit")
+async def test_list_filter_by_type(tracker: TaskTracker):
+ await tracker.create("session_commit", **_owner_kwargs())
+ await tracker.create("resource_ingest", **_owner_kwargs())
+ tasks = await tracker.list_tasks(task_type="session_commit")
assert len(tasks) == 1
assert tasks[0].task_type == "session_commit"
-def test_list_filter_by_status(tracker: TaskTracker):
- t1 = tracker.create("session_commit", **_owner_kwargs())
- tracker.create("session_commit", **_owner_kwargs())
- tracker.start(t1.task_id)
- tracker.complete(t1.task_id, {})
+async def test_list_filter_by_status(tracker: TaskTracker):
+ t1 = await tracker.create("session_commit", **_owner_kwargs())
+ await tracker.create("session_commit", **_owner_kwargs())
+ await tracker.start(t1.task_id)
+ await tracker.complete(t1.task_id, {})
- completed = tracker.list_tasks(status="completed")
+ completed = await tracker.list_tasks(status="completed")
assert len(completed) == 1
- pending = tracker.list_tasks(status="pending")
+ pending = await tracker.list_tasks(status="pending")
assert len(pending) == 1
-def test_list_filter_by_resource_id(tracker: TaskTracker):
- tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
- tracker.create("session_commit", resource_id="s2", **_owner_kwargs())
- tasks = tracker.list_tasks(resource_id="s1")
+async def test_list_filter_by_resource_id(tracker: TaskTracker):
+ await tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
+ await tracker.create("session_commit", resource_id="s2", **_owner_kwargs())
+ tasks = await tracker.list_tasks(resource_id="s1")
assert len(tasks) == 1
assert tasks[0].resource_id == "s1"
-def test_get_hides_task_from_other_owner(tracker: TaskTracker):
- task = tracker.create(
+async def test_get_hides_task_from_other_owner(tracker: TaskTracker):
+ task = await tracker.create(
"session_commit",
resource_id="s1",
account_id="acme",
@@ -193,7 +195,7 @@ def test_get_hides_task_from_other_owner(tracker: TaskTracker):
)
assert (
- tracker.get(
+ await tracker.get(
task.task_id,
account_id="acme",
user_id="bob",
@@ -202,37 +204,37 @@ def test_get_hides_task_from_other_owner(tracker: TaskTracker):
)
-def test_list_tasks_filters_by_owner(tracker: TaskTracker):
- tracker.create(
+async def test_list_tasks_filters_by_owner(tracker: TaskTracker):
+ await tracker.create(
"session_commit",
resource_id="alice-task",
account_id="acme",
user_id="alice",
)
- tracker.create(
+ await tracker.create(
"session_commit",
resource_id="bob-task",
account_id="acme",
user_id="bob",
)
- tasks = tracker.list_tasks(account_id="acme", user_id="alice")
+ tasks = await tracker.list_tasks(account_id="acme", user_id="alice")
assert len(tasks) == 1
assert tasks[0].resource_id == "alice-task"
-def test_list_limit(tracker: TaskTracker):
+async def test_list_limit(tracker: TaskTracker):
for i in range(10):
- tracker.create("session_commit", resource_id=f"s{i}", **_owner_kwargs())
- tasks = tracker.list_tasks(limit=3)
+ await tracker.create("session_commit", resource_id=f"s{i}", **_owner_kwargs())
+ tasks = await tracker.list_tasks(limit=3)
assert len(tasks) == 3
-def test_list_order_most_recent_first(tracker: TaskTracker):
- tracker.create("session_commit", resource_id="first", **_owner_kwargs())
- tracker.create("session_commit", resource_id="second", **_owner_kwargs())
- tasks = tracker.list_tasks()
+async def test_list_order_most_recent_first(tracker: TaskTracker):
+ await tracker.create("session_commit", resource_id="first", **_owner_kwargs())
+ await tracker.create("session_commit", resource_id="second", **_owner_kwargs())
+ tasks = await tracker.list_tasks()
assert tasks[0].resource_id == "second"
assert tasks[1].resource_id == "first"
@@ -240,39 +242,39 @@ def test_list_order_most_recent_first(tracker: TaskTracker):
# ── Duplicate detection ──
-def test_has_running_detects_pending(tracker: TaskTracker):
- tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
- assert tracker.has_running("session_commit", "s1") is True
+async def test_has_running_detects_pending(tracker: TaskTracker):
+ await tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
+ assert await tracker.has_running("session_commit", "s1") is True
-def test_has_running_detects_running(tracker: TaskTracker):
- t = tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
- tracker.start(t.task_id)
- assert tracker.has_running("session_commit", "s1") is True
+async def test_has_running_detects_running(tracker: TaskTracker):
+ t = await tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
+ await tracker.start(t.task_id)
+ assert await tracker.has_running("session_commit", "s1") is True
-def test_has_running_false_after_complete(tracker: TaskTracker):
- t = tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
- tracker.start(t.task_id)
- tracker.complete(t.task_id, {})
- assert tracker.has_running("session_commit", "s1") is False
+async def test_has_running_false_after_complete(tracker: TaskTracker):
+ t = await tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
+ await tracker.start(t.task_id)
+ await tracker.complete(t.task_id, {})
+ assert await tracker.has_running("session_commit", "s1") is False
-def test_has_running_false_after_fail(tracker: TaskTracker):
- t = tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
- tracker.start(t.task_id)
- tracker.fail(t.task_id, "error")
- assert tracker.has_running("session_commit", "s1") is False
+async def test_has_running_false_after_fail(tracker: TaskTracker):
+ t = await tracker.create("session_commit", resource_id="s1", **_owner_kwargs())
+ await tracker.start(t.task_id)
+ await tracker.fail(t.task_id, "error")
+ assert await tracker.has_running("session_commit", "s1") is False
-def test_create_if_no_running_isolated_by_owner(tracker: TaskTracker):
- alice_task = tracker.create_if_no_running(
+async def test_create_if_no_running_isolated_by_owner(tracker: TaskTracker):
+ alice_task = await tracker.create_if_no_running(
"reindex",
"viking://resources/demo",
account_id="acme",
user_id="alice",
)
- bob_task = tracker.create_if_no_running(
+ bob_task = await tracker.create_if_no_running(
"reindex",
"viking://resources/demo",
account_id="acme",
@@ -287,8 +289,8 @@ def test_create_if_no_running_isolated_by_owner(tracker: TaskTracker):
# ── Serialization ──
-def test_to_dict(tracker: TaskTracker):
- task = tracker.create(
+async def test_to_dict(tracker: TaskTracker):
+ task = await tracker.create(
"session_commit",
resource_id="s1",
**_owner_kwargs(),
@@ -310,26 +312,26 @@ def test_to_dict(tracker: TaskTracker):
# ── Sanitization ──
-def test_sanitize_removes_sk_key():
+async def test_sanitize_removes_sk_key():
assert "[REDACTED]" in _sanitize_error("Error with sk-ant-api03-DAqSxxxxx")
-def test_sanitize_removes_ghp_token():
+async def test_sanitize_removes_ghp_token():
assert "[REDACTED]" in _sanitize_error("Auth failed ghp_" + "x" * 36)
-def test_sanitize_removes_bearer_token():
+async def test_sanitize_removes_bearer_token():
assert "[REDACTED]" in _sanitize_error("Bearer xoxb-1234567890-abcdefghij")
-def test_sanitize_truncates_long_error():
+async def test_sanitize_truncates_long_error():
long_error = "x" * 1000
sanitized = _sanitize_error(long_error)
assert len(sanitized) <= 520 # 500 + "...[truncated]"
assert sanitized.endswith("...[truncated]")
-def test_sanitize_preserves_safe_error():
+async def test_sanitize_preserves_safe_error():
safe = "LLM timeout after 30s"
assert _sanitize_error(safe) == safe
@@ -337,77 +339,81 @@ def test_sanitize_preserves_safe_error():
# ── TTL / Eviction ──
-def test_evict_expired_completed(tracker: TaskTracker):
- t = tracker.create("session_commit", **_owner_kwargs())
- tracker.start(t.task_id)
- tracker.complete(t.task_id, {})
+async def test_evict_expired_completed(tracker: TaskTracker):
+ t = await tracker.create("session_commit", **_owner_kwargs())
+ await tracker.start(t.task_id)
+ await tracker.complete(t.task_id, {})
# Simulate old timestamp (access internal state; get() returns defensive copies)
tracker._tasks[t.task_id].updated_at = time.time() - tracker.TTL_COMPLETED - 1
- tracker._evict_expired()
- assert tracker.get(t.task_id) is None
+ await tracker._evict_expired()
+ assert await tracker.get(t.task_id) is None
-def test_evict_keeps_recent_completed(tracker: TaskTracker):
- t = tracker.create("session_commit", **_owner_kwargs())
- tracker.start(t.task_id)
- tracker.complete(t.task_id, {})
- tracker._evict_expired()
- assert tracker.get(t.task_id) is not None
+async def test_evict_keeps_recent_completed(tracker: TaskTracker):
+ t = await tracker.create("session_commit", **_owner_kwargs())
+ await tracker.start(t.task_id)
+ await tracker.complete(t.task_id, {})
+ await tracker._evict_expired()
+ assert await tracker.get(t.task_id) is not None
-def test_evict_fifo_when_over_limit(tracker: TaskTracker):
+async def test_evict_fifo_when_over_limit(tracker: TaskTracker):
tracker.MAX_TASKS = 5
tasks = []
for i in range(7):
- tasks.append(tracker.create("session_commit", resource_id=f"s{i}", **_owner_kwargs()))
- tracker._evict_expired()
+ tasks.append(await tracker.create("session_commit", resource_id=f"s{i}", **_owner_kwargs()))
+ await tracker._evict_expired()
assert tracker.count() == 5
# Oldest should be gone
- assert tracker.get(tasks[0].task_id) is None
- assert tracker.get(tasks[1].task_id) is None
+ assert await tracker.get(tasks[0].task_id) is None
+ assert await tracker.get(tasks[1].task_id) is None
# Newest should remain
- assert tracker.get(tasks[6].task_id) is not None
+ assert await tracker.get(tasks[6].task_id) is not None
# ── Singleton ──
-def test_singleton():
+async def test_singleton():
t1 = get_task_tracker()
t2 = get_task_tracker()
assert t1 is t2
-def test_singleton_reset():
+async def test_singleton_reset():
t1 = get_task_tracker()
reset_task_tracker()
t2 = get_task_tracker()
assert t1 is not t2
-def test_persistent_store_cross_tracker_visibility():
+async def test_persistent_store_cross_tracker_visibility():
agfs = _FakeAgfs()
store = PersistentTaskStore(agfs)
tracker1 = TaskTracker(store=store)
tracker2 = TaskTracker(store=store)
- task = tracker1.create("session_commit", resource_id="sess-123", **_owner_kwargs())
- tracker1.start(task.task_id, account_id="acme", user_id="alice")
- tracker1.complete(task.task_id, {"ok": True}, account_id="acme", user_id="alice")
+ task = await tracker1.create("session_commit", resource_id="sess-123", **_owner_kwargs())
+ await tracker1.start(task.task_id, account_id="acme", user_id="alice")
+ await tracker1.complete(task.task_id, {"ok": True}, account_id="acme", user_id="alice")
- loaded = tracker2.get(task.task_id, account_id="acme", user_id="alice")
+ loaded = await tracker2.get(task.task_id, account_id="acme", user_id="alice")
assert loaded is not None
assert loaded.status == TaskStatus.COMPLETED
assert loaded.result == {"ok": True}
-def test_persistent_store_writes_task_record_json():
+async def test_persistent_store_writes_task_record_json():
agfs = _FakeAgfs()
store = PersistentTaskStore(agfs)
tracker = TaskTracker(store=store)
- task = tracker.create("add_resource", resource_id="viking://resources/demo", **_owner_kwargs())
+ task = await tracker.create(
+ "add_resource",
+ resource_id="viking://resources/demo",
+ **_owner_kwargs(),
+ )
raw = agfs.files[f"/local/acme/tasks/alice/{task.task_id}.json"]
payload = json.loads(raw.decode("utf-8"))
@@ -419,50 +425,50 @@ def test_persistent_store_writes_task_record_json():
assert "schema_version" not in payload
-def test_inmemory_store_keeps_tasktracker_tasks_dict():
+async def test_inmemory_store_keeps_tasktracker_tasks_dict():
tracker = TaskTracker(store=InMemoryTaskStore())
- task = tracker.create("session_commit", **_owner_kwargs())
+ task = await tracker.create("session_commit", **_owner_kwargs())
assert task.task_id in tracker._tasks
-def test_persistent_store_survives_tracker_reset():
+async def test_persistent_store_survives_tracker_reset():
agfs = _FakeAgfs()
tracker1 = TaskTracker(store=PersistentTaskStore(agfs))
- task = tracker1.create("session_commit", resource_id="sess-123", **_owner_kwargs())
- tracker1.start(task.task_id, account_id="acme", user_id="alice")
+ task = await tracker1.create("session_commit", resource_id="sess-123", **_owner_kwargs())
+ await tracker1.start(task.task_id, account_id="acme", user_id="alice")
tracker2 = TaskTracker(store=PersistentTaskStore(agfs))
- loaded = tracker2.get(task.task_id, account_id="acme", user_id="alice")
+ loaded = await tracker2.get(task.task_id, account_id="acme", user_id="alice")
assert loaded is not None
assert loaded.status == TaskStatus.RUNNING
-def test_persistent_store_ignores_existing_task_dirs():
+async def test_persistent_store_ignores_existing_task_dirs():
agfs = _FakeAgfsExistingDir()
tracker = TaskTracker(store=PersistentTaskStore(agfs))
- first = tracker.create("session_commit", resource_id="sess-1", **_owner_kwargs())
- second = tracker.create("session_commit", resource_id="sess-2", **_owner_kwargs())
+ first = await tracker.create("session_commit", resource_id="sess-1", **_owner_kwargs())
+ second = await tracker.create("session_commit", resource_id="sess-2", **_owner_kwargs())
assert first.task_id != second.task_id
assert agfs.files[f"/local/acme/tasks/alice/{first.task_id}.json"]
assert agfs.files[f"/local/acme/tasks/alice/{second.task_id}.json"]
-def test_create_requires_owner(tracker: TaskTracker):
+async def test_create_requires_owner(tracker: TaskTracker):
with pytest.raises(TypeError):
- tracker.create("session_commit", resource_id="sess-123")
+ await tracker.create("session_commit", resource_id="sess-123")
-def test_create_if_no_running_requires_owner(tracker: TaskTracker):
+async def test_create_if_no_running_requires_owner(tracker: TaskTracker):
with pytest.raises(TypeError):
- tracker.create_if_no_running("reindex", "viking://resources/demo")
+ await tracker.create_if_no_running("reindex", "viking://resources/demo")
-def test_create_rejects_blank_owner_values(tracker: TaskTracker):
+async def test_create_rejects_blank_owner_values(tracker: TaskTracker):
with pytest.raises(ValueError, match="Task ownership requires"):
- tracker.create(
+ await tracker.create(
"session_commit",
resource_id="sess-123",
account_id="",
@@ -470,10 +476,9 @@ def test_create_rejects_blank_owner_values(tracker: TaskTracker):
)
async def test_session_service_get_commit_task_is_owner_scoped():
tracker = get_task_tracker()
- task = tracker.create("session_commit", resource_id="sess-123", **_owner_kwargs())
+ task = await tracker.create("session_commit", resource_id="sess-123", **_owner_kwargs())
service = SessionService()
owner_result = await service.get_commit_task(task.task_id, _make_ctx())
@@ -485,10 +490,9 @@ async def test_session_service_get_commit_task_is_owner_scoped():
assert other_result is None
async def test_session_service_get_commit_task_also_filters_account():
tracker = get_task_tracker()
- task = tracker.create("session_commit", resource_id="sess-123", **_owner_kwargs())
+ task = await tracker.create("session_commit", resource_id="sess-123", **_owner_kwargs())
service = SessionService()
other_account_result = await service.get_commit_task(
diff --git a/tests/test_upload_utils.py b/tests/test_upload_utils.py
index 8aa6cce84..045a5af7d 100644
--- a/tests/test_upload_utils.py
+++ b/tests/test_upload_utils.py
@@ -378,9 +378,7 @@ class TestUploadDirectory:
@pytest.mark.asyncio
async def test_creates_root_dir(self, tmp_dir: Path, viking_fs: FakeVikingFS) -> None:
await upload_directory(tmp_dir, "viking://temp/root", viking_fs)
- # _mkdir_with_parents strips leading slash then re-adds it, so the stored agfs
- # path is the _uri_to_path() result with a "/" prefix.
- assert any("temp/root" in d for d in viking_fs.agfs.dirs)
+ assert "viking://temp/root" in viking_fs.dirs
@pytest.mark.asyncio
async def test_custom_ignore_dirs(self, tmp_dir: Path, viking_fs: FakeVikingFS) -> None:
diff --git a/tests/transaction/test_lock_context.py b/tests/transaction/test_lock_context.py
index 263819222..a29580caa 100644
--- a/tests/transaction/test_lock_context.py
+++ b/tests/transaction/test_lock_context.py
@@ -83,7 +83,7 @@ class TestLockContextFailure:
async with LockContext(lm, ["/local/nonexistent-xyz"], lock_mode="unknown"):
pass
- assert len(lm.get_active_handles()) == 0
+ assert len(await lm.get_active_handles_async()) == 0
class TestLockContextExternalHandle:
diff --git a/tests/transaction/test_lock_manager.py b/tests/transaction/test_lock_manager.py
index 36285b2bf..209e9a816 100644
--- a/tests/transaction/test_lock_manager.py
+++ b/tests/transaction/test_lock_manager.py
@@ -61,17 +61,17 @@ class TestLockManagerBasic:
assert len(handle.locks) == 2
await lm.release(handle)
- assert handle.id not in lm.get_active_handles()
+ assert handle.id not in await lm.get_active_handles_async()
async def test_release_removes_from_active(self, lm, test_dir):
handle = lm.create_handle()
await lm.acquire_exact_path(handle, test_dir)
- assert handle.id in lm.get_active_handles()
+ assert handle.id in await lm.get_active_handles_async()
await lm.release(handle)
- assert handle.id not in lm.get_active_handles()
+ assert handle.id not in await lm.get_active_handles_async()
async def test_stop_releases_all(self, agfs_client, lm, test_dir):
h1 = lm.create_handle()
@@ -83,7 +83,7 @@ class TestLockManagerBasic:
await lm.acquire_exact_path(h2, sub)
await lm.stop()
- assert len(lm.get_active_handles()) == 0
+ assert len(await lm.get_active_handles_async()) == 0
async def test_exact_path_allows_missing_target(self, lm):
handle = lm.create_handle()
@@ -104,14 +104,15 @@ class TestLockManagerBasic:
async def test_recover_pending_redo_preserves_cancelled_error(self, lm):
lm._redo_log = MagicMock()
- lm._redo_log.list_pending.return_value = ["redo-task"]
- lm._redo_log.read.return_value = {"archive_uri": "a", "session_uri": "b"}
+ lm._redo_log.list_pending_async = AsyncMock(return_value=["redo-task"])
+ lm._redo_log.read_async = AsyncMock(return_value={"archive_uri": "a", "session_uri": "b"})
+ lm._redo_log.mark_done_async = AsyncMock()
lm._redo_session_memory = AsyncMock(side_effect=asyncio.CancelledError("shutdown"))
with pytest.raises(asyncio.CancelledError):
await lm._recover_pending_redo()
- lm._redo_log.mark_done.assert_not_called()
+ lm._redo_log.mark_done_async.assert_not_awaited()
async def test_start_skips_redo_recovery_when_disabled(self, client):
lm_disabled = LockManager(
diff --git a/tests/transaction/test_lock_manager_staleness.py b/tests/transaction/test_lock_manager_staleness.py
index d9e588a9d..92dd87f5c 100644
--- a/tests/transaction/test_lock_manager_staleness.py
+++ b/tests/transaction/test_lock_manager_staleness.py
@@ -15,6 +15,7 @@ async def test_refresh_lock_updates_last_active_without_changing_created_at(monk
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.collect_lost_owner_locks_async = AsyncMock(return_value=[])
lm._path_lock.refresh = AsyncMock(
return_value=LockRefreshResult(refreshed_paths=["/local/tx/.path.ovlock"])
)
@@ -58,13 +59,15 @@ async def test_stale_cleanup_releases_only_inactive_handles(monkeypatch):
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._path_lock.collect_lost_owner_locks_async = AsyncMock(return_value=[])
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()
+ active_handles = await lm.get_active_handles_async()
+ assert active_handle.id in active_handles
+ assert unlocked_handle.id not in active_handles
def test_get_handle_returns_none_when_lock_ownership_is_lost():
diff --git a/tests/transaction/test_path_lock.py b/tests/transaction/test_path_lock.py
index 6a6897318..d04937608 100644
--- a/tests/transaction/test_path_lock.py
+++ b/tests/transaction/test_path_lock.py
@@ -5,6 +5,7 @@
import time
from unittest.mock import AsyncMock, MagicMock
+from openviking.storage.transaction import path_lock as path_lock_module
from openviking.storage.transaction.lock_handle import LockHandle
from openviking.storage.transaction.path_lock import (
EXACT_LOCK_FILE_PREFIX,
@@ -137,6 +138,13 @@ class TestPathLockIsLocked:
lock = PathLockEngine(agfs, lock_expire=300.0)
assert lock.is_locked("/local/u/foo", ignore_stale=False) is True
+ async def test_is_locked_async_uses_async_agfs_path(self):
+ token = _make_fencing_token("tx-1", LOCK_TYPE_TREE)
+ agfs = self._agfs_with_locks({"/local/u/.path.ovlock": token.encode("utf-8")})
+ lock = PathLockEngine(agfs)
+
+ assert await lock.is_locked_async("/local/u/foo/bar") is True
+
class TestPathLockOwnership:
async def test_refresh_reports_refreshed_lost_and_failed_paths(self):
@@ -268,6 +276,33 @@ class TestPathLockBehavior:
await lock.release(parent)
+ async def test_fail_fast_tree_conflict_warning_is_throttled(
+ self, agfs_client, test_dir, monkeypatch
+ ):
+ lock = PathLockEngine(agfs_client)
+ parent = LockHandle(id="tx-parent-tree")
+ child = LockHandle(id="tx-child-tree")
+ child_retry = LockHandle(id="tx-child-tree-retry")
+ target = f"{test_dir}/blocked-resource"
+
+ assert await lock.acquire_tree(test_dir, parent, timeout=3.0) is True
+
+ warnings = []
+ debug_logs = []
+ path_lock_module._last_timeout_warning_at.clear()
+ monkeypatch.setattr(path_lock_module.logger, "warning", warnings.append)
+ monkeypatch.setattr(path_lock_module.logger, "debug", debug_logs.append)
+
+ assert await lock.acquire_tree(target, child, timeout=0.0) is False
+ assert await lock.acquire_tree(target, child_retry, timeout=0.0) is False
+
+ timeout_warnings = [message for message in warnings if "Timeout waiting" in message]
+ assert len(timeout_warnings) == 1
+ assert "Timeout waiting for ancestor TREE lock" in timeout_warnings[0]
+ assert debug_logs == []
+
+ await lock.release(parent)
+
async def test_acquire_exact_path_allows_missing_target(self, agfs_client):
lock = PathLockEngine(agfs_client)
tx = LockHandle(id="tx-no-dir")
diff --git a/tests/transaction/test_redo_log.py b/tests/transaction/test_redo_log.py
index b161f0c31..8f3ae9271 100644
--- a/tests/transaction/test_redo_log.py
+++ b/tests/transaction/test_redo_log.py
@@ -15,64 +15,64 @@ def redo(agfs_client):
class TestRedoLogBasic:
- def test_write_and_read(self, redo):
+ async def test_write_and_read(self, redo):
task_id = uuid.uuid4().hex
info = {"archive_uri": "viking://test/archive", "session_uri": "viking://test/session"}
- redo.write_pending(task_id, info)
+ await redo.write_pending_async(task_id, info)
- result = redo.read(task_id)
+ result = await redo.read_async(task_id)
assert result["archive_uri"] == "viking://test/archive"
assert result["session_uri"] == "viking://test/session"
- redo.mark_done(task_id)
+ await redo.mark_done_async(task_id)
- def test_list_pending(self, redo):
+ async def test_list_pending(self, redo):
t1 = uuid.uuid4().hex
t2 = uuid.uuid4().hex
- redo.write_pending(t1, {"key": "v1"})
- redo.write_pending(t2, {"key": "v2"})
+ await redo.write_pending_async(t1, {"key": "v1"})
+ await redo.write_pending_async(t2, {"key": "v2"})
- pending = redo.list_pending()
+ pending = await redo.list_pending_async()
assert t1 in pending
assert t2 in pending
- redo.mark_done(t1)
- pending_after = redo.list_pending()
+ await redo.mark_done_async(t1)
+ pending_after = await redo.list_pending_async()
assert t1 not in pending_after
assert t2 in pending_after
- redo.mark_done(t2)
+ await redo.mark_done_async(t2)
- def test_mark_done_removes_task(self, redo):
+ async def test_mark_done_removes_task(self, redo):
task_id = uuid.uuid4().hex
- redo.write_pending(task_id, {"x": 1})
- redo.mark_done(task_id)
+ await redo.write_pending_async(task_id, {"x": 1})
+ await redo.mark_done_async(task_id)
- pending = redo.list_pending()
+ pending = await redo.list_pending_async()
assert task_id not in pending
- def test_read_nonexistent_returns_empty(self, redo):
- result = redo.read("nonexistent-task-id")
+ async def test_read_nonexistent_returns_empty(self, redo):
+ result = await redo.read_async("nonexistent-task-id")
assert result == {}
- def test_list_pending_empty(self, redo):
+ async def test_list_pending_empty(self, redo):
# Should not crash even if _REDO_ROOT doesn't exist yet
- pending = redo.list_pending()
+ pending = await redo.list_pending_async()
assert isinstance(pending, list)
- def test_mark_done_idempotent(self, redo):
+ async def test_mark_done_idempotent(self, redo):
task_id = uuid.uuid4().hex
- redo.write_pending(task_id, {"x": 1})
- redo.mark_done(task_id)
+ await redo.write_pending_async(task_id, {"x": 1})
+ await redo.mark_done_async(task_id)
# Second mark_done should not raise
- redo.mark_done(task_id)
+ await redo.mark_done_async(task_id)
- def test_overwrite_pending(self, redo):
+ async def test_overwrite_pending(self, redo):
task_id = uuid.uuid4().hex
- redo.write_pending(task_id, {"version": 1})
- redo.write_pending(task_id, {"version": 2})
+ await redo.write_pending_async(task_id, {"version": 1})
+ await redo.write_pending_async(task_id, {"version": 2})
- result = redo.read(task_id)
+ result = await redo.read_async(task_id)
assert result["version"] == 2
- redo.mark_done(task_id)
+ await redo.mark_done_async(task_id)