Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(auth): serialize API key registry writes (#3377)
Qin Haojie370fe45f6f6f
diff --git a/openviking/server/api_keys/legacy.py b/openviking/server/api_keys/legacy.pyindex a13aa939d..d19b1095e 100644--- a/openviking/server/api_keys/legacy.py+++ b/openviking/server/api_keys/legacy.py@@ -16,6 +16,8 @@ from argon2.exceptions import VerifyMismatchErrorfrom openviking.pyagfs import AGFSAlreadyExistsError, AGFSNotFoundError, AsyncAGFSClientfrom openviking.server.api_keys.models import AccountInfo, UserKeyEntryfrom openviking.server.identity import ResolvedIdentity, Role+from openviking.storage.errors import LockAcquisitionError, ResourceBusyError+from openviking.storage.transaction import LockContext, get_lock_managerfrom openviking.storage.viking_fs import VikingFSfrom openviking_cli.exceptions import (AlreadyExistsError,@@ -651,18 +653,38 @@ class LegacyAPIKeyManager:async def _save_accounts_json(self) -> None:"""Persist the global accounts list."""- data = {- "accounts": {- aid: {"created_at": info.created_at} for aid, info in self._accounts.items()- }- }- await self._write_json(ACCOUNTS_PATH, data)+ try:+ async with LockContext(+ get_lock_manager(), [ACCOUNTS_PATH], lock_mode="exact", timeout=10.0+ ):+ data = {+ "accounts": {+ aid: {"created_at": info.created_at}+ for aid, info in self._accounts.items()+ }+ }+ await self._write_json(ACCOUNTS_PATH, data)+ except LockAcquisitionError as exc:+ raise ResourceBusyError(+ "Another account operation is in progress. Please retry.",+ uri=ACCOUNTS_PATH,+ conflict_type="account_registry_busy",+ ) from excasync def _save_users_json(self, account_id: str) -> None:"""Persist a single account's user registry."""- account = self._accounts.get(account_id)- if account is None:- return- data = {"users": account.users}path = USERS_PATH_TEMPLATE.format(account_id=account_id)- await self._write_json(path, data)+ try:+ async with LockContext(+ get_lock_manager(), [path], lock_mode="exact", timeout=10.0+ ):+ account = self._accounts.get(account_id)+ if account is None:+ return+ await self._write_json(path, {"users": account.users})+ except LockAcquisitionError as exc:+ raise ResourceBusyError(+ "Another user operation is in progress for this account. Please retry.",+ uri=path,+ conflict_type="user_registry_busy",+ ) from excdiff --git a/openviking/storage/transaction/lock_context.py b/openviking/storage/transaction/lock_context.pyindex 05212ddf0..424cca343 100644--- a/openviking/storage/transaction/lock_context.py+++ b/openviking/storage/transaction/lock_context.py@@ -2,12 +2,12 @@# SPDX-License-Identifier: AGPL-3.0"""LockContext — async context manager for acquiring/releasing path locks."""-from typing import Optional+from typing import Any, Optionalfrom openviking.storage.errors import LockAcquisitionErrorfrom openviking.storage.transaction.lock_handle import LockHandlefrom openviking.storage.transaction.lock_lease import OwnedLockLease-from openviking.storage.transaction.lock_manager import LockManager+from openviking.storage.transaction.lock_manager import LOCK_TIMEOUT_DEFAULT, LockManagerclass LockContext:@@ -25,6 +25,7 @@ class LockContext:mv_dst_path: Optional[str] = None,src_is_dir: bool = True,handle: Optional[LockHandle] = None,+ timeout: Any = LOCK_TIMEOUT_DEFAULT,):self._manager = lock_managerself._paths = paths@@ -32,6 +33,7 @@ class LockContext:self._mv_dst_path = mv_dst_pathself._src_is_dir = src_is_dirself._handle: Optional[LockHandle] = handle+ self._timeout = timeoutself._owns_handle = handle is Noneself._locks_before: list[str] = []self._acquired_lock_paths: list[str] = []@@ -45,11 +47,15 @@ class LockContext:if self._lock_mode == "tree":for path in self._paths:- success = await self._manager.acquire_tree(self._handle, path)+ success = await self._manager.acquire_tree(+ self._handle, path, timeout=self._timeout+ )if not success:breakelif self._lock_mode == "exact":- success = await self._manager.acquire_exact_path_batch(self._handle, self._paths)+ success = await self._manager.acquire_exact_path_batch(+ self._handle, self._paths, timeout=self._timeout+ )elif self._lock_mode == "mv":if self._mv_dst_path is None:raise LockAcquisitionError("mv lock mode requires mv_dst_path")@@ -58,6 +64,7 @@ class LockContext:self._paths[0],self._mv_dst_path,src_is_dir=self._src_is_dir,+ timeout=self._timeout,)else:raise LockAcquisitionError(f"Unsupported lock mode: {self._lock_mode}")diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex cff1d4a5f..53f99c57e 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -43,6 +43,19 @@ def _seed_secret(user_id: str, seed: str) -> str:ROOT_KEY = "admin-api-test-root-key-abcdef1234567890ab"+class _NoopLockContext:+ """The lightweight fake storage does not exercise transaction locking."""++ def __init__(self, *_args, **_kwargs):+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return False++class _FakeAGFS:def __init__(self):self._files = {}@@ -134,7 +147,13 @@ def _build_lightweight_admin_test_app() -> FastAPI:@pytest_asyncio.fixture(scope="function")-async def lightweight_admin_app():+async def lightweight_admin_app(monkeypatch):+ monkeypatch.setattr(+ "openviking.server.api_keys.legacy.get_lock_manager", lambda: None+ )+ monkeypatch.setattr(+ "openviking.server.api_keys.legacy.LockContext", _NoopLockContext+ )app = _build_lightweight_admin_test_app()await app.state.api_key_manager.load()return appdiff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.pyindex 8d614bfea..309c02efe 100644--- a/tests/server/test_api_key_manager.py+++ b/tests/server/test_api_key_manager.py@@ -3,6 +3,7 @@"""Tests for APIKeyManager (openviking/server/api_keys.py)."""+import asyncioimport hashlibimport uuid@@ -11,8 +12,10 @@ import pytest_asynciofrom openviking.pyagfs.exceptions import AGFSNotFoundErrorfrom openviking.server.api_keys import APIKeyManager+from openviking.server.api_keys.legacy import ACCOUNTS_PATHfrom openviking.server.identity import Rolefrom openviking.service.core import OpenVikingService+from openviking.storage.transaction import LockContext, get_lock_managerfrom openviking_cli.exceptions import (AlreadyExistsError,InvalidArgumentError,@@ -165,6 +168,36 @@ async def test_register_user(manager: APIKeyManager):assert identity.user_id == "bob"+async def test_concurrent_registry_writes_wait_for_locks(manager: APIKeyManager):+ first_account = _uid()+ second_account = _uid()++ async with LockContext(get_lock_manager(), [ACCOUNTS_PATH], lock_mode="exact"):+ account_tasks = [+ asyncio.create_task(manager.create_account(first_account, "alice")),+ asyncio.create_task(manager.create_account(second_account, "bob")),+ ]+ await asyncio.sleep(0.05)+ assert all(not task.done() for task in account_tasks)++ await asyncio.gather(*account_tasks)+ accounts = await manager._read_json(ACCOUNTS_PATH)+ assert {first_account, second_account} <= set(accounts["accounts"])++ users_path = f"/local/{first_account}/_system/users.json"+ async with LockContext(get_lock_manager(), [users_path], lock_mode="exact"):+ user_tasks = [+ asyncio.create_task(manager.register_user(first_account, "bob")),+ asyncio.create_task(manager.register_user(first_account, "carol")),+ ]+ await asyncio.sleep(0.05)+ assert all(not task.done() for task in user_tasks)++ await asyncio.gather(*user_tasks)+ users = await manager._read_json(users_path)+ assert set(users["users"]) == {"alice", "bob", "carol"}++async def test_register_duplicate_user_raises(manager: APIKeyManager):"""Registering duplicate user should raise AlreadyExistsError."""acct = _uid()