Skip to content

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

Transaction store (#136)

MaojiaSheng11d6a1ad2555
diff --git a/docs/en/concepts/04-viking-uri.md b/docs/en/concepts/04-viking-uri.md
index 77beaa7be..ecf039557 100644
--- a/docs/en/concepts/04-viking-uri.md
+++ b/docs/en/concepts/04-viking-uri.md
@@ -120,7 +120,7 @@ viking://
│ ├── entities/ # Each independent
│ └── events/ # Each independent
│
-├── agent/{unique_space_name}/
+├── agent/{unique_space_name}/ # unique_space_name see UserIdentifier
│ ├── skills/ # Skill definitions
│ ├── memories/
│ │ ├── cases/
diff --git a/docs/zh/concepts/09-transaction.md b/docs/zh/concepts/09-transaction.md
new file mode 100644
index 000000000..503ed683f
--- /dev/null
+++ b/docs/zh/concepts/09-transaction.md
@@ -0,0 +1,167 @@
+# 事务机制
+
+OpenViking 的事务机制为 AI Agent 上下文数据库提供可靠的操作保障,解决数据一致性、并发控制和错误恢复等核心问题。
+
+## 概览
+
+```
+操作请求 → TransactionManager → 锁保护 → 执行操作 → 状态更新
+ ↓ ↓ ↓
+ 事务ID分配和事务状态管理 路径锁校验和加锁
+
+
+事务生命周期:开始操作 → 创建事务 → 锁保护生效 → 文件系统同步操作 → 摘要和索引异步操作 → 移除锁保护 → 事务结束
+```
+
+**设计原则**:
+1. **最小化锁粒度**:仅支持路径锁机制,不实现复杂的 MVCC 等
+2. **写互斥优先**:暂不实现读锁(共享锁),先承诺写操作的互斥性
+3. **渐进式扩展**:避免过度设计,聚焦核心需求,未来需要时再添加更复杂的锁机制
+4. **默认生效**:所有数据操作命令均开启事务机制,用户无需额外配置
+
+## 核心需求分析
+
+OpenViking 的数据操作命令(如 `add_resource`、`rm`、`mv` 等)存在以下无保护操作问题:
+
+1. **并发冲突**:多个用户同时操作同一目录可能导致数据不一致
+2. **无原子性**:`add_resource` 多阶段操作中,某个阶段失败可能留下中间状态
+3. **无可观测性**:操作结果无法预测,用户无法直接观察到正在操作的状态
+
+## 系统一致性要求
+
+从系统分析的角度,OpenViking 要求实现组件间的分布式一致性:
+
+1. **向量索引的最终一致**:所有上下文数据的向量表征依托独立的向量数据库或向量索引实现,要求确保在任何操作序列下,向量表示的更新都能实现最终一致
+2. **文件系统的读写一致性**:所有上下文数据的文件系统表示依托 VikingFS 实现,底层为 AGFS 桥接的分布式文件系统,要求确保在任何操作序列下,文件系统的更新都能保证数据不会损坏或丢失
+3. **队列和异步数据处理的一致性**:所有上下文数据的异步操作依托队列实现,要求确保在任何操作序列下,队列中的数据都能实现最终一致,即队列中的数据会最终被处理,不会丢失或重复
+
+## TransactionManager(事务管理器)
+
+TransactionManager 是全局单例,负责管理事务生命周期和锁机制实现。
+
+### 核心职责
+
+- 分配事务ID
+- 管理事务生命周期(开始、提交、回滚)
+- 提供事务的锁机制实现接口,防止死锁
+
+### 关键特性
+
+```
+路径锁 + 写互斥 = 并发冲突防护
+```
+
+- **路径锁**:锁定目标目录,防止并发的目录级操作如目录删除、目录移动等
+- **写互斥**:同一时间只允许一个事务写操作,路径锁机制确保所有写操作的互斥性
+- **事务结束状态**:事务有明确的结束状态,包括完成、失败丢弃等
+
+### 事务状态机
+
+```
+INIT → AQUIRE → EXEC → COMMIT/FAIL → RELEASING → RELEASED
+```
+
+**状态说明**:
+- `INIT`:事务初始化完成,等待锁获取
+- `AQUIRE`:正在获取锁资源
+- `EXEC`:事务操作正在执行
+- `COMMIT/FAIL`:事务执行完成,进入最终状态
+- `RELEASING`:正在释放锁资源
+- `RELEASED`:锁资源已完全释放,事务结束
+
+### 事务记录属性
+
+```python
+TransactionRecord(
+ id: str, # 事务ID,采用 uuid 格式,唯一标识一个事务
+ locks: List[str], # 锁列表
+ status: str, # 当前状态
+ init_info: Dict, # 事务初始化信息
+ rollback_info: Dict, # 回滚信息
+ created_at: float, # 创建时间
+ updated_at: float, # 更新时间
+)
+```
+
+### 设计决策
+
+- 暂不实现共享锁(读锁),简化设计
+- 锁粒度仅限目录,不实现范围锁机制
+- 不实现复杂的死锁检测,通过超时机制防止死锁,事务超时后自动释放所有锁
+- 支持可选的自下而上并行加锁模式,提升大型目录树操作的性能和一致性
+- 事务状态机增加AQUIRE+RELEASING状态,明确跟踪锁释放过程,提高系统可观测性
+
+## 锁机制
+
+锁机制是事务管理的核心组件,当前只提供路径锁类型。
+
+### 锁类型
+
+| 锁类型 | 作用范围 | 用例 |
+|--------|----------|------|
+| 路径锁 | 整个目录 | 用于阻止目录被意外整体移动或删除,确保事务操作过程的路径合法性
+
+### 锁协议
+
+```
+viking://resources/github/volcengine/OpenViking/.path.ovlock
+```
+
+- 锁文件存在即表示已加锁
+- 文件内容为事务ID,用于标识当前事务
+- 事务操作完成后,删除锁文件以释放锁
+
+### 加锁流程
+
+#### 普通操作加锁流程
+
+```
+1. 检查目标目录是否存在
+2. 检查目标目录是否已被其他事务锁定
+3. 检查目标目录的父目录是否已被其他事务锁定
+4. 创建 .path.ovlock 文件,文件内容为事务ID
+5. 再次检查目标目录的父目录是否已被其他事务锁定
+6. 读取刚创建的 .path.ovlock 文件内容,确认为当前事务ID
+7. 一切正常,则返回加锁成功
+```
+
+#### rm 操作加锁流程
+
+```
+# 传统串行模式:存在更大的竞态条件窗口
+1. 检查目标目录是否存在
+2. 检查目标目录是否已被其他事务锁定
+3. 检查目标目录的父目录是否已被其他事务锁定
+4. 在目标目录下创建 .path.ovlock 文件,文件内容为事务ID
+5. 递归地在目标目录的所有子目录下创建 .path.ovlock 文件
+6. 如果发生加锁失败,移除所有已经创建的 .path.ovlock 文件
+7. 一切正常,则返回加锁成功
+
+# 自下而上并行模式
+1. 并行遍历整个目录树,收集所有子目录路径
+2. 按照目录层级从深到浅排序,从最深层子目录开始
+3. 以有限并行度(默认最大8)批量创建 .path.ovlock 文件
+4. 最后锁定目标目录
+5. 如果任一位置加锁失败,逆序移除所有已经创建的 .path.ovlock 文件
+```
+
+#### mv 操作加锁流程
+
+```
+1. 先参照 rm 操作对原目录进行加锁
+2. 再参照普通操作过程对新目录进行加锁
+```
+
+### 锁机制性能分析
+
+- 并行遍历采用广度优先策略,同时处理同一层级的所有目录
+- 并行加锁从最深层开始,逐层向上锁定,确保整个目录树的一致性
+- 有限并行度(默认最大8)避免AGFS服务过载
+- 加锁失败时采用逆序回滚,确保所有已加锁目录都能正确释放
+- 事务状态机明确区分锁管理过程(AQUIRE+RELEASING状态),提高系统可观测性和调试效率
+
+## 相关文档
+
+- [架构概述](./01-architecture.md) - 系统整体架构
+- [存储架构](./05-storage.md) - AGFS 和向量库
+- [会话管理](./08-session.md) - 会话和记忆管理
\ No newline at end of file
diff --git a/docs/zh/getting-started/03-quickstart-server.md b/docs/zh/getting-started/03-quickstart-server.md
index 9ae996898..6dba7cbdf 100644
--- a/docs/zh/getting-started/03-quickstart-server.md
+++ b/docs/zh/getting-started/03-quickstart-server.md
@@ -19,7 +19,7 @@ python -m openviking serve
python -m openviking serve --config /path/to/ov.conf
# 覆盖 host/port
-python -m openviking serve --port 8000
+python -m openviking serve --port 1933
```
你应该看到:
diff --git a/openviking/__init__.py b/openviking/__init__.py
index b5da2e4ac..d324236cb 100644
--- a/openviking/__init__.py
+++ b/openviking/__init__.py
@@ -25,6 +25,13 @@ except ImportError:
except ImportError:
__version__ = "0.0.0+unknown"
+try:
+ from pyagfs import AGFSClient
+except ImportError:
+ raise ImportError(
+ "pyagfs not found. Please install: pip install -e third_party/agfs/agfs-sdk/python"
+ )
+
__all__ = [
"OpenViking",
"SyncOpenViking",
diff --git a/openviking/core/directories.py b/openviking/core/directories.py
index a7e87e575..5f7f246ed 100644
--- a/openviking/core/directories.py
+++ b/openviking/core/directories.py
@@ -120,16 +120,17 @@ PRESET_DIRECTORIES: Dict[str, DirectoryDefinition] = {
overview="Globally shared resource storage, organized by project/topic. "
"No preset subdirectory structure, users create project directories as needed.",
),
+ "transactions": DirectoryDefinition(
+ path="",
+ abstract="Transaction scope. Stores transaction records",
+ overview="Per-account transaction storage",
+ ),
}
-def get_collection_for_uri(uri: str) -> str:
- """Determine which collection to store based on URI. Aligns with COLLECTION_NAME"""
- return "context"
-
-
def get_context_type_for_uri(uri: str) -> str:
"""Determine context_type based on URI."""
+ uri = uri[:20]
if "/memories" in uri:
return ContextType.MEMORY.value
elif "/resources" in uri:
@@ -156,7 +157,6 @@ class DirectoryInitializer:
logger = get_logger(__name__)
count = 0
-
for scope, root_defn in PRESET_DIRECTORIES.items():
if scope == "user":
logger.info("Skipping user scope (lazy initialization)")
@@ -173,8 +173,6 @@ class DirectoryInitializer:
count += 1
count += await self._initialize_children(scope, root_defn.children, root_uri)
-
- logger.info(f"Initialized {count} global directories")
return count
async def initialize_user_directories(self) -> int:
@@ -209,16 +207,23 @@ class DirectoryInitializer:
scope: str,
) -> bool:
"""Ensure directory exists, return whether newly created."""
- collection = get_collection_for_uri(uri)
-
- if not await self.vikingdb.collection_exists(collection):
- return False
+ from openviking.utils.logger import get_logger
+ logger = get_logger(__name__)
created = False
+ # 1. Ensure files exist in AGFS
+ if not await self._check_agfs_files_exist(uri):
+ logger.debug(f"[VikingFS] Creating directory: {uri} for scope {scope}")
+ await self._create_agfs_structure(uri, defn.abstract, defn.overview)
+ created = True
+ else:
+ logger.debug(f"[VikingFS] Directory {uri} already exists")
+
+ # 2. Ensure record exists in vector storage
+ from openviking.utils.config.vectordb_config import COLLECTION_NAME
- # 1. Ensure record exists in vector storage
existing = await self.vikingdb.filter(
- collection=collection,
+ collection=COLLECTION_NAME,
filter={"op": "must", "field": "uri", "conds": [uri]},
limit=1,
)
@@ -234,11 +239,6 @@ class DirectoryInitializer:
dir_emb_msg = EmbeddingMsgConverter.from_context(context)
await self.vikingdb.enqueue_embedding_msg(dir_emb_msg)
created = True
-
- # 2. Ensure files exist in AGFS
- if not await self._check_agfs_files_exist(uri):
- await self._create_agfs_structure(uri, defn.abstract, defn.overview)
-
return created
async def _check_agfs_files_exist(self, uri: str) -> bool:
diff --git a/openviking/server/routers/observer.py b/openviking/server/routers/observer.py
index d1e72ce53..78e1c335f 100644
--- a/openviking/server/routers/observer.py
+++ b/openviking/server/routers/observer.py
@@ -36,8 +36,7 @@ def _system_to_dict(status: SystemStatus) -> dict:
"is_healthy": status.is_healthy,
"errors": status.errors,
"components": {
- name: _component_to_dict(component)
- for name, component in status.components.items()
+ name: _component_to_dict(component) for name, component in status.components.items()
},
}
@@ -72,6 +71,16 @@ async def observer_vlm(
return Response(status="ok", result=_component_to_dict(component))
[email protected]("/transaction")
+async def observer_transaction(
+ _: bool = Depends(verify_api_key),
+):
+ """Get transaction system status."""
+ service = get_service()
+ component = service.debug.observer.transaction
+ return Response(status="ok", result=_component_to_dict(component))
+
+
@router.get("/system")
async def observer_system(
_: bool = Depends(verify_api_key),
diff --git a/openviking/service/core.py b/openviking/service/core.py
index 9c0d48e6f..e559698b0 100644
--- a/openviking/service/core.py
+++ b/openviking/service/core.py
@@ -22,6 +22,7 @@ from openviking.session.compressor import SessionCompressor
from openviking.session.user_id import UserIdentifier
from openviking.storage import VikingDBManager
from openviking.storage.collection_schemas import init_context_collection
+from openviking.storage.transaction import TransactionManager, init_transaction_manager
from openviking.storage.viking_fs import VikingFS, init_viking_fs
from openviking.utils import get_logger
from openviking.utils.config import get_openviking_config
@@ -70,6 +71,7 @@ class OpenVikingService:
self._resource_processor: Optional[ResourceProcessor] = None
self._skill_processor: Optional[SkillProcessor] = None
self._session_compressor: Optional[SessionCompressor] = None
+ self._transaction_manager: Optional[TransactionManager] = None
# Sub-services
self._fs_service = FSService()
@@ -106,6 +108,9 @@ class OpenVikingService:
vectordb_config=config.vectordb, agfs_config=config.agfs
)
+ # Initialize TransactionManager
+ self._transaction_manager = init_transaction_manager(agfs_config=config.agfs)
+
@property
def viking_fs(self) -> Optional[VikingFS]:
"""Get VikingFS instance."""
@@ -116,6 +121,11 @@ class OpenVikingService:
"""Get VikingDBManager instance."""
return self._vikingdb_manager
+ @property
+ def transaction_manager(self) -> Optional[TransactionManager]:
+ """Get TransactionManager instance."""
+ return self._transaction_manager
+
@property
def session_compressor(self) -> Optional[SessionCompressor]:
"""Get SessionCompressor instance."""
@@ -198,6 +208,11 @@ class OpenVikingService:
self._skill_processor = SkillProcessor(vikingdb=self._vikingdb_manager)
self._session_compressor = SessionCompressor(vikingdb=self._vikingdb_manager)
+ # Start TransactionManager if initialized
+ if self._transaction_manager:
+ await self._transaction_manager.start()
+ logger.info("TransactionManager started")
+
# Wire up sub-services
self._fs_service.set_viking_fs(self._viking_fs)
self._relation_service.set_viking_fs(self._viking_fs)
@@ -226,6 +241,10 @@ class OpenVikingService:
async def close(self) -> None:
"""Close OpenViking and release resources."""
+ if self._transaction_manager:
+ self._transaction_manager.stop()
+ self._transaction_manager = None
+
if self._agfs_manager:
self._agfs_manager.stop()
self._agfs_manager = None
diff --git a/openviking/service/debug_service.py b/openviking/service/debug_service.py
index faf8ce559..467063eae 100644
--- a/openviking/service/debug_service.py
+++ b/openviking/service/debug_service.py
@@ -1,4 +1,3 @@
-
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: Apache-2.0
"""
@@ -9,8 +8,14 @@ from dataclasses import dataclass
from typing import Dict, List, Optional
from openviking.storage import VikingDBManager
-from openviking.storage.observers import QueueObserver, VikingDBObserver, VLMObserver
+from openviking.storage.observers import (
+ QueueObserver,
+ TransactionObserver,
+ VikingDBObserver,
+ VLMObserver,
+)
from openviking.storage.queuefs import get_queue_manager
+from openviking.storage.transaction import get_transaction_manager
from openviking.utils.config import OpenVikingConfig
@@ -101,6 +106,25 @@ class ObserverService:
status=observer.get_status_table(),
)
+ @property
+ def transaction(self) -> ComponentStatus:
+ """Get transaction status."""
+ transaction_manager = get_transaction_manager()
+ if transaction_manager is None:
+ return ComponentStatus(
+ name="transaction",
+ is_healthy=False,
+ has_errors=True,
+ status="Transaction manager not initialized.",
+ )
+ observer = TransactionObserver(transaction_manager)
+ return ComponentStatus(
+ name="transaction",
+ is_healthy=observer.is_healthy(),
+ has_errors=observer.has_errors(),
+ status=observer.get_status_table(),
+ )
+
@property
def system(self) -> SystemStatus:
"""Get system overall status."""
@@ -108,6 +132,7 @@ class ObserverService:
"queue": self.queue,
"vikingdb": self.vikingdb,
"vlm": self.vlm,
+ "transaction": self.transaction,
}
errors = [f"{c.name} has errors" for c in components.values() if c.has_errors]
return SystemStatus(
diff --git a/openviking/storage/collection_schemas.py b/openviking/storage/collection_schemas.py
index 102498dc4..5cdb442bf 100644
--- a/openviking/storage/collection_schemas.py
+++ b/openviking/storage/collection_schemas.py
@@ -19,8 +19,6 @@ from openviking.utils.config.open_viking_config import OpenVikingConfig
logger = get_logger(__name__)
-COLLECTION_NAME = "context"
-
class CollectionSchemas:
"""
diff --git a/openviking/storage/observers/__init__.py b/openviking/storage/observers/__init__.py
index 3d80b045d..a0d3ece55 100644
--- a/openviking/storage/observers/__init__.py
+++ b/openviking/storage/observers/__init__.py
@@ -2,12 +2,14 @@
# SPDX-License-Identifier: Apache-2.0
from .base_observer import BaseObserver
from .queue_observer import QueueObserver
+from .transaction_observer import TransactionObserver
from .vikingdb_observer import VikingDBObserver
from .vlm_observer import VLMObserver
__all__ = [
"BaseObserver",
"QueueObserver",
+ "TransactionObserver",
"VikingDBObserver",
"VLMObserver",
]
diff --git a/openviking/storage/observers/transaction_observer.py b/openviking/storage/observers/transaction_observer.py
new file mode 100644
index 000000000..7791ef892
--- /dev/null
+++ b/openviking/storage/observers/transaction_observer.py
@@ -0,0 +1,222 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""
+TransactionObserver: Transaction system observability tool.
+
+Provides methods to observe and report transaction manager status.
+"""
+
+import time
+from typing import Any, Dict
+
+from openviking.storage.observers.base_observer import BaseObserver
+from openviking.storage.transaction import TransactionManager
+from openviking.storage.transaction.transaction_record import TransactionStatus
+from openviking.utils import run_async
+from openviking.utils.logger import get_logger
+
+logger = get_logger(__name__)
+
+
+class TransactionObserver(BaseObserver):
+ """
+ TransactionObserver: System observability tool for transaction management.
+
+ Provides methods to query transaction status and format output.
+ """
+
+ def __init__(self, transaction_manager: TransactionManager):
+ """Initialize transaction observer.
+
+ Args:
+ transaction_manager: Transaction manager instance to observe
+ """
+ self._transaction_manager = transaction_manager
+
+ async def get_status_table_async(self) -> str:
+ """Get transaction status table asynchronously.
+
+ Returns:
+ Formatted table string showing transaction status
+ """
+ if not self._transaction_manager:
+ return "Transaction manager not initialized."
+
+ transactions = self._transaction_manager.get_active_transactions()
+
+ if not transactions:
+ return "No active transactions."
+
+ return self._format_status_as_table(transactions)
+
+ def get_status_table(self) -> str:
+ """Get transaction status table synchronously.
+
+ Returns:
+ Formatted table string showing transaction status
+ """
+ return run_async(self.get_status_table_async())
+
+ def __str__(self) -> str:
+ """String representation returns status table.
+
+ Returns:
+ Formatted table string
+ """
+ return self.get_status_table()
+
+ def _format_status_as_table(self, transactions: Dict[str, Any]) -> str:
+ """Format transaction statuses as a table.
+
+ Args:
+ transactions: Dict mapping transaction IDs to TransactionRecord
+
+ Returns:
+ Formatted table string
+ """
+ from tabulate import tabulate
+
+ data = []
+
+ # Group transactions by status
+ status_counts = {
+ TransactionStatus.INIT: 0,
+ TransactionStatus.AQUIRE: 0,
+ TransactionStatus.EXEC: 0,
+ TransactionStatus.COMMIT: 0,
+ TransactionStatus.FAIL: 0,
+ TransactionStatus.RELEASING: 0,
+ TransactionStatus.RELEASED: 0,
+ }
+
+ for tx_id, tx in transactions.items():
+ duration = time.time() - tx.created_at
+ duration_str = f"{duration:.1f}s"
+
+ status_counts[tx.status] += 1
+
+ data.append(
+ {
+ "Transaction ID": tx_id[:8] + "...",
+ "Status": str(tx.status),
+ "Locks": len(tx.locks),
+ "Duration": duration_str,
+ "Created": time.strftime("%H:%M:%S", time.localtime(tx.created_at)),
+ }
+ )
+
+ status_priority = {
+ TransactionStatus.EXEC: 0,
+ TransactionStatus.AQUIRE: 1,
+ TransactionStatus.RELEASING: 2,
+ TransactionStatus.INIT: 3,
+ TransactionStatus.COMMIT: 4,
+ TransactionStatus.FAIL: 5,
+ TransactionStatus.RELEASED: 6,
+ }
+
+ data.sort(key=lambda x: status_priority.get(TransactionStatus(x["Status"]), 99))
+
+ total = len(transactions)
+ total_locks = sum(len(tx.locks) for tx in transactions.values())
+
+ summary_row = {
+ "Transaction ID": f"TOTAL ({total})",
+ "Status": "",
+ "Locks": total_locks,
+ "Duration": "",
+ "Created": "",
+ }
+ data.append(summary_row)
+
+ return tabulate(data, headers="keys", tablefmt="pretty")
+
+ def is_healthy(self) -> bool:
+ """Check if transaction system is healthy.
+
+ Returns:
+ True if system is healthy, False otherwise
+ """
+ return not self.has_errors()
+
+ def has_errors(self) -> bool:
+ """Check if transaction system has any errors.
+
+ Returns:
+ True if errors (failed transactions) exist, False otherwise
+ """
+ if not self._transaction_manager:
+ return True
+
+ transactions = self._transaction_manager.get_active_transactions()
+
+ # Check for failed transactions
+ for tx_id, tx in transactions.items():
+ if tx.status == TransactionStatus.FAIL:
+ logger.warning(f"Found failed transaction: {tx_id}")
+ return True
+
+ return False
+
+ def get_failed_transactions(self) -> Dict[str, Any]:
+ """Get all failed transactions.
+
+ Returns:
+ Dict mapping transaction IDs to failed TransactionRecord
+ """
+ if not self._transaction_manager:
+ return {}
+
+ transactions = self._transaction_manager.get_active_transactions()
+ return {
+ tx_id: tx for tx_id, tx in transactions.items() if tx.status == TransactionStatus.FAIL
+ }
+
+ def get_hanging_transactions(self, timeout_threshold: int = 300) -> Dict[str, Any]:
+ """Get transactions that have been running longer than threshold.
+
+ Args:
+ timeout_threshold: Timeout threshold in seconds (default: 300 = 5 minutes)
+
+ Returns:
+ Dict mapping transaction IDs to TransactionRecord that exceed threshold
+ """
+ if not self._transaction_manager:
+ return {}
+
+ transactions = self._transaction_manager.get_active_transactions()
+ current_time = time.time()
+
+ return {
+ tx_id: tx
+ for tx_id, tx in transactions.items()
+ if current_time - tx.created_at > timeout_threshold
+ }
+
+ def get_status_summary(self) -> Dict[str, int]:
+ """Get summary of transaction counts by status.
+
+ Returns:
+ Dict mapping status strings to counts
+ """
+ if not self._transaction_manager:
+ return {}
+
+ transactions = self._transaction_manager.get_active_transactions()
+
+ summary = {
+ "INIT": 0,
+ "AQUIRE": 0,
+ "EXEC": 0,
+ "COMMIT": 0,
+ "FAIL": 0,
+ "RELEASING": 0,
+ "RELEASED": 0,
+ "TOTAL": 0,
+ }
+
+ for tx in transactions.values():
+ summary[str(tx.status)] += 1
+ summary["TOTAL"] += 1
+
+ return summary
diff --git a/openviking/storage/queuefs/queue_manager.py b/openviking/storage/queuefs/queue_manager.py
index 9effe35c7..7585a1b76 100644
--- a/openviking/storage/queuefs/queue_manager.py
+++ b/openviking/storage/queuefs/queue_manager.py
@@ -11,6 +11,8 @@ import threading
import time
from typing import Any, Dict, Optional, Union
+from pyagfs import AGFSClient
+
from openviking.utils.logger import get_logger
from .embedding_queue import EmbeddingQueue
@@ -83,13 +85,6 @@ class QueueManager:
if self._started:
return
- try:
- from pyagfs import AGFSClient
- except ImportError:
- raise ImportError(
- "pyagfs not found. Please install: pip install -e third_party/agfs/agfs-sdk/python"
- )
-
self._agfs = AGFSClient(api_base_url=self._agfs_url, timeout=self.timeout)
self._started = True
diff --git a/openviking/storage/transaction/__init__.py b/openviking/storage/transaction/__init__.py
new file mode 100644
index 000000000..b6c06d6e5
--- /dev/null
+++ b/openviking/storage/transaction/__init__.py
@@ -0,0 +1,27 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""
+Transaction module for OpenViking.
+
+Provides transaction management and lock mechanisms for data operations.
+"""
+
+from openviking.storage.transaction.path_lock import PathLock
+from openviking.storage.transaction.transaction_manager import (
+ TransactionManager,
+ get_transaction_manager,
+ init_transaction_manager,
+)
+from openviking.storage.transaction.transaction_record import (
+ TransactionRecord,
+ TransactionStatus,
+)
+
+__all__ = [
+ "PathLock",
+ "TransactionManager",
+ "TransactionRecord",
+ "TransactionStatus",
+ "init_transaction_manager",
+ "get_transaction_manager",
+]
diff --git a/openviking/storage/transaction/path_lock.py b/openviking/storage/transaction/path_lock.py
new file mode 100644
index 000000000..4c1f878af
--- /dev/null
+++ b/openviking/storage/transaction/path_lock.py
@@ -0,0 +1,331 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""
+Path lock implementation for transaction management.
+
+Provides path-based locking mechanism to prevent concurrent directory operations.
+Lock protocol: viking://resources/.../.path.ovlock file exists = locked
+"""
+
+import asyncio
+from typing import List, Optional
+
+from pyagfs import AGFSClient
+
+from openviking.storage.transaction.transaction_record import TransactionRecord
+from openviking.utils.logger import get_logger
+
+logger = get_logger(__name__)
+
+# Lock file name
+LOCK_FILE_NAME = ".path.ovlock"
+
+
+class PathLock:
+ """Path lock manager for transaction-based directory locking.
+
+ Implements path-based locking using lock files (.path.ovlock) to prevent
+ concurrent operations on the same directory tree.
+ """
+
+ def __init__(self, agfs_client: AGFSClient):
+ """Initialize path lock manager.
+
+ Args:
+ agfs_client: AGFS client for file system operations
+ """
+ self._agfs = agfs_client
+
+ def _get_lock_path(self, path: str) -> str:
+ """Get lock file path for a directory.
+
+ Args:
+ path: Directory path to lock
+
+ Returns:
+ Lock file path (path/.path.ovlock)
+ """
+ # Remove trailing slash if present
+ path = path.rstrip("/")
+ return f"{path}/{LOCK_FILE_NAME}"
+
+ def _get_parent_path(self, path: str) -> Optional[str]:
+ """Get parent directory path.
+
+ Args:
+ path: Directory path
+
+ Returns:
+ Parent directory path or None if at root
+ """
+ path = path.rstrip("/")
+ if "/" not in path:
+ return None
+ parent = path.rsplit("/", 1)[0]
+ return parent if parent else None
+
+ async def _is_locked_by_other(self, lock_path: str, transaction_id: str) -> bool:
+ """Check if path is locked by another transaction.
+
+ Args:
+ lock_path: Lock file path
+ transaction_id: Current transaction ID
+
+ Returns:
+ True if locked by another transaction, False otherwise
+ """
+ try:
+ content = self._agfs.cat(lock_path)
+ if isinstance(content, bytes):
+ lock_owner = content.decode("utf-8").strip()
+ else:
+ lock_owner = str(content).strip()
+ return lock_owner != transaction_id
+ except Exception:
+ # Lock file doesn't exist or can't be read - not locked
+ return False
+
+ async def _create_lock_file(self, lock_path: str, transaction_id: str) -> None:
+ """Create lock file with transaction ID.
+
+ Args:
+ lock_path: Lock file path
+ transaction_id: Transaction ID to write to lock file
+ """
+ self._agfs.write(lock_path, transaction_id.encode("utf-8"))
+
+ async def _verify_lock_ownership(self, lock_path: str, transaction_id: str) -> bool:
+ """Verify lock file is owned by current transaction.
+
+ Args:
+ lock_path: Lock file path
+ transaction_id: Current transaction ID
+
+ Returns:
+ True if lock is owned by current transaction, False otherwise
+ """
+ try:
+ content = self._agfs.cat(lock_path)
+ if isinstance(content, bytes):
+ lock_owner = content.decode("utf-8").strip()
+ else:
+ lock_owner = str(content).strip()
+ return lock_owner == transaction_id
+ except Exception:
+ return False
+
+ async def _remove_lock_file(self, lock_path: str) -> None:
+ """Remove lock file.
+
+ Args:
+ lock_path: Lock file path
+ """
+ try:
+ self._agfs.rm(lock_path)
+ except Exception:
+ # Lock file might not exist, ignore
+ pass
+
+ async def acquire_normal(self, path: str, transaction: TransactionRecord) -> bool:
+ """Acquire path lock for normal operations.
+
+ Lock acquisition flow for normal operations:
+ 1. Check if target directory exists
+ 2. Check if target directory is locked by another transaction
+ 3. Check if parent directory is locked by another transaction
+ 4. Create .path.ovlock file with transaction ID
+ 5. Check again if parent directory is locked by another transaction
+ 6. Read lock file to confirm it contains current transaction ID
+ 7. Return success if all checks pass
+
+ Args:
+ path: Directory path to lock
+ transaction: Transaction record
+
+ Returns:
+ True if lock acquired successfully, False otherwise
+ """
+ transaction_id = transaction.id
+ lock_path = self._get_lock_path(path)
+ parent_path = self._get_parent_path(path)
+
+ # Step 1: Check if target directory exists
+ try:
+ self._agfs.stat(path)
+ except Exception:
+ logger.warning(f"Directory does not exist: {path}")
+ return False
+
+ # Step 2: Check if target directory is locked by another transaction
+ if await self._is_locked_by_other(lock_path, transaction_id):
+ logger.warning(f"Path already locked by another transaction: {path}")
+ return False
+
+ # Step 3: Check if parent directory is locked by another transaction
+ if parent_path:
+ parent_lock_path = self._get_lock_path(parent_path)
+ if await self._is_locked_by_other(parent_lock_path, transaction_id):
+ logger.warning(f"Parent path locked by another transaction: {parent_path}")
+ return False
+
+ # Step 4: Create lock file
+ try:
+ await self._create_lock_file(lock_path, transaction_id)
+ except Exception as e:
+ logger.error(f"Failed to create lock file: {e}")
+ return False
+
+ # Step 5: Check again if parent directory is locked
+ if parent_path:
+ parent_lock_path = self._get_lock_path(parent_path)
+ if await self._is_locked_by_other(parent_lock_path, transaction_id):
+ logger.warning(f"Parent path locked after lock creation: {parent_path}")
+ await self._remove_lock_file(lock_path)
+ return False
+
+ # Step 6: Verify lock ownership
+ if not await self._verify_lock_ownership(lock_path, transaction_id):
+ logger.error(f"Lock ownership verification failed: {path}")
+ return False
+
+ # Step 7: Success - add lock to transaction
+ transaction.add_lock(lock_path)
+ logger.debug(f"Lock acquired: {lock_path}")
+ return True
+
+ async def _collect_subdirectories(self, path: str) -> List[str]:
+ """Collect all subdirectory paths recursively.
+
+ Args:
+ path: Root directory path
+
+ Returns:
+ List of all subdirectory paths
+ """
+ subdirs = []
+ try:
+ entries = self._agfs.ls(path)
+ if isinstance(entries, list):
+ for entry in entries:
+ if isinstance(entry, dict) and entry.get("isDir"):
+ entry_path = entry.get("name", "")
+ if entry_path:
+ subdirs.append(entry_path)
+ # Recursively collect subdirectories
+ subdirs.extend(await self._collect_subdirectories(entry_path))
+ except Exception as e:
+ logger.warning(f"Failed to list directory {path}: {e}")
+
+ return subdirs
+
+ async def acquire_rm(
+ self, path: str, transaction: TransactionRecord, max_parallel: int = 8
+ ) -> bool:
+ """Acquire path lock for rm operation using bottom-up parallel locking.
+
+ Lock acquisition flow for rm operations (parallel bottom-up mode):
+ 1. Collect all subdirectory paths recursively
+ 2. Sort by depth (deepest first)
+ 3. Create lock files in batches with limited parallelism
+ 4. Lock the target directory last
+ 5. If any lock fails, release all acquired locks in reverse order
+
+ Args:
+ path: Directory path to lock
+ transaction: Transaction record
+ max_parallel: Maximum number of parallel lock operations
+
+ Returns:
+ True if all locks acquired successfully, False otherwise
+ """
+ transaction_id = transaction.id
+ lock_path = self._get_lock_path(path)
+ acquired_locks = []
+
+ # Step 1: Collect all subdirectories
+ subdirs = await self._collect_subdirectories(path)
+
+ # Step 2: Sort by depth (deepest first)
+ subdirs.sort(key=lambda p: p.count("/"), reverse=True)
+
+ # Step 3: Create lock files in batches
+ try:
+ # Lock subdirectories in batches
+ for i in range(0, len(subdirs), max_parallel):
+ batch = subdirs[i : i + max_parallel]
+ tasks = []
+ for subdir in batch:
+ subdir_lock_path = self._get_lock_path(subdir)
+ tasks.append(self._create_lock_file(subdir_lock_path, transaction_id))
+
+ # Execute batch in parallel
+ await asyncio.gather(*tasks)
+ acquired_locks.extend([self._get_lock_path(s) for s in batch])
+
+ # Step 4: Lock target directory
+ await self._create_lock_file(lock_path, transaction_id)
+ acquired_locks.append(lock_path)
+
+ # Add all locks to transaction
+ for lock in acquired_locks:
+ transaction.add_lock(lock)
+
+ logger.debug(f"RM locks acquired for {len(acquired_locks)} paths")
+ return True
+
+ except Exception as e:
+ logger.error(f"Failed to acquire RM locks: {e}")
+ # Step 5: Release all acquired locks in reverse order
+ for lock in reversed(acquired_locks):
+ await self._remove_lock_file(lock)
+ return False
+
+ async def acquire_mv(
+ self,
+ src_path: str,
+ dst_path: str,
+ transaction: TransactionRecord,
+ max_parallel: int = 8,
+ ) -> bool:
+ """Acquire path lock for mv operation.
+
+ Lock acquisition flow for mv operations:
+ 1. Lock source directory (using RM-style locking)
+ 2. Lock destination directory (using normal locking)
+
+ Args:
+ src_path: Source directory path
+ dst_path: Destination directory path
+ transaction: Transaction record
+ max_parallel: Maximum number of parallel lock operations
+
+ Returns:
+ True if all locks acquired successfully, False otherwise
+ """
+ # Step 1: Lock source directory
+ if not await self.acquire_rm(src_path, transaction, max_parallel):
+ logger.warning(f"Failed to lock source path: {src_path}")
+ return False
+
+ # Step 2: Lock destination directory
+ if not await self.acquire_normal(dst_path, transaction):
+ logger.warning(f"Failed to lock destination path: {dst_path}")
+ # Release source locks
+ await self.release(transaction)
+ return False
+
+ logger.debug(f"MV locks acquired: {src_path} -> {dst_path}")
+ return True
+
+ async def release(self, transaction: TransactionRecord) -> None:
+ """Release all locks held by the transaction.
+
+ Args:
+ transaction: Transaction record
+ """
+ # Release locks in reverse order (LIFO)
+ for lock_path in reversed(transaction.locks):
+ await self._remove_lock_file(lock_path)
+ transaction.remove_lock(lock_path)
+
+ logger.debug(f"Released {len(transaction.locks)} locks for transaction {transaction.id}")
diff --git a/openviking/storage/transaction/transaction_manager.py b/openviking/storage/transaction/transaction_manager.py
new file mode 100644
index 000000000..950305197
--- /dev/null
+++ b/openviking/storage/transaction/transaction_manager.py
@@ -0,0 +1,382 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""
+Transaction manager for OpenViking.
+
+Global singleton that manages transaction lifecycle and lock mechanisms.
+"""
+
+import asyncio
+import threading
+import time
+from typing import Any, Dict, Optional
+
+from pyagfs import AGFSClient
+
+from openviking.storage.transaction.path_lock import PathLock
+from openviking.storage.transaction.transaction_record import (
+ TransactionRecord,
+ TransactionStatus,
+)
+from openviking.utils.logger import get_logger
+
+logger = get_logger(__name__)
+
+# Global singleton instance
+_transaction_manager: Optional["TransactionManager"] = None
+_lock = threading.Lock()
+
+
+class TransactionManager:
+ """Transaction manager for OpenViking.
+
+ Global singleton that manages transaction lifecycle and lock mechanisms.
+ Responsible for:
+ - Allocating transaction IDs
+ - Managing transaction lifecycle (start, commit, rollback)
+ - Providing transaction lock mechanism interface, preventing deadlocks
+ """
+
+ def __init__(
+ self,
+ agfs_client: AGFSClient,
+ timeout: int = 3600,
+ max_parallel_locks: int = 8,
+ ):
+ """Initialize transaction manager.
+
+ Args:
+ agfs_client: AGFS client for file system operations
+ timeout: Transaction timeout in seconds (default: 3600)
+ max_parallel_locks: Maximum number of parallel lock operations (default: 8)
+ """
+ self._agfs = agfs_client
+ self._timeout = timeout
+ self._max_parallel_locks = max_parallel_locks
+ self._path_lock = PathLock(agfs_client)
+
+ # Active transactions: {transaction_id: TransactionRecord}
+ self._transactions: Dict[str, TransactionRecord] = {}
+
+ # Background task for timeout cleanup
+ self._cleanup_task: Optional[asyncio.Task] = None
+ self._running = False
+
+ logger.info(
+ f"TransactionManager initialized (timeout={timeout}s, max_parallel_locks={max_parallel_locks})"
+ )
+
+ async def start(self) -> None:
+ """Start transaction manager.
+
+ Starts the background cleanup task for timed-out transactions.
+ """
+ if self._running:
+ logger.debug("TransactionManager already running")
+ return
+
+ self._running = True
+ self._cleanup_task = asyncio.create_task(self._cleanup_loop())
+ logger.info("TransactionManager started")
+
+ def stop(self) -> None:
+ """Stop transaction manager.
+
+ Stops the background cleanup task and releases all resources.
+ """
+ if not self._running:
+ logger.debug("TransactionManager already stopped")
+ return
+
+ self._running = False
+
+ # Cancel cleanup task
+ if self._cleanup_task:
+ self._cleanup_task.cancel()
+ self._cleanup_task = None
+
+ # Release all active transactions
+ for tx_id in list(self._transactions.keys()):
+ self._transactions.pop(tx_id, None)
+
+ logger.info("TransactionManager stopped")
+
+ async def _cleanup_loop(self) -> None:
+ """Background loop for cleaning up timed-out transactions."""
+ while self._running:
+ try:
+ await asyncio.sleep(60) # Check every minute
+ await self._cleanup_timed_out()
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.error(f"Error in cleanup loop: {e}")
+
+ async def _cleanup_timed_out(self) -> None:
+ """Clean up timed-out transactions."""
+ current_time = time.time()
+ timed_out = []
+
+ for tx_id, tx in self._transactions.items():
+ if current_time - tx.updated_at > self._timeout:
+ timed_out.append(tx_id)
+
+ for tx_id in timed_out:
+ logger.warning(f"Transaction timed out: {tx_id}")
+ await self.rollback(tx_id)
+
+ def create_transaction(self, init_info: Optional[Dict[str, Any]] = None) -> TransactionRecord:
+ """Create a new transaction.
+
+ Args:
+ init_info: Transaction initialization information
+
+ Returns:
+ New transaction record
+ """
+ tx = TransactionRecord(init_info=init_info or {})
+ self._transactions[tx.id] = tx
+ logger.debug(f"Transaction created: {tx.id}")
+ return tx
+
+ def get_transaction(self, transaction_id: str) -> Optional[TransactionRecord]:
+ """Get transaction by ID.
+
+ Args:
+ transaction_id: Transaction ID
+
+ Returns:
+ Transaction record or None if not found
+ """
+ return self._transactions.get(transaction_id)
+
+ async def begin(self, transaction_id: str) -> bool:
+ """Begin a transaction.
+
+ Args:
+ transaction_id: Transaction ID
+
+ Returns:
+ True if transaction started successfully, False otherwise
+ """
+ tx = self.get_transaction(transaction_id)
+ if not tx:
+ logger.error(f"Transaction not found: {transaction_id}")
+ return False
+
+ tx.update_status(TransactionStatus.AQUIRE)
+ logger.debug(f"Transaction begun: {transaction_id}")
+ return True
+
+ async def commit(self, transaction_id: str) -> bool:
+ """Commit a transaction.
+
+ Args:
+ transaction_id: Transaction ID
+
+ Returns:
+ True if transaction committed successfully, False otherwise
+ """
+ tx = self.get_transaction(transaction_id)
+ if not tx:
+ logger.error(f"Transaction not found: {transaction_id}")
+ return False
+
+ # Update status to COMMIT
+ tx.update_status(TransactionStatus.COMMIT)
+
+ # Release all locks
+ tx.update_status(TransactionStatus.RELEASING)
+ await self._path_lock.release(tx)
+
+ # Update status to RELEASED
+ tx.update_status(TransactionStatus.RELEASED)
+
+ # Remove from active transactions
+ self._transactions.pop(transaction_id, None)
+
+ logger.debug(f"Transaction committed: {transaction_id}")
+ return True
+
+ async def rollback(self, transaction_id: str) -> bool:
+ """Rollback a transaction.
+
+ Args:
+ transaction_id: Transaction ID
+
+ Returns:
+ True if transaction rolled back successfully, False otherwise
+ """
+ tx = self.get_transaction(transaction_id)
+ if not tx:
+ logger.error(f"Transaction not found: {transaction_id}")
+ return False
+
+ # Update status to FAIL
+ tx.update_status(TransactionStatus.FAIL)
+
+ # Release all locks
+ tx.update_status(TransactionStatus.RELEASING)
+ await self._path_lock.release(tx)
+
+ # Update status to RELEASED
+ tx.update_status(TransactionStatus.RELEASED)
+
+ # Remove from active transactions
+ self._transactions.pop(transaction_id, None)
+
+ logger.debug(f"Transaction rolled back: {transaction_id}")
+ return True
+
+ async def acquire_lock_normal(self, transaction_id: str, path: str) -> bool:
+ """Acquire path lock for normal (non-rm/mv) operations.
+
+ Args:
+ transaction_id: Transaction ID
+ path: Directory path to lock
+
+ Returns:
+ True if lock acquired successfully, False otherwise
+ """
+ tx = self.get_transaction(transaction_id)
+ if not tx:
+ logger.error(f"Transaction not found: {transaction_id}")
+ return False
+
+ tx.update_status(TransactionStatus.AQUIRE)
+ success = await self._path_lock.acquire_normal(path, tx)
+
+ if success:
+ tx.update_status(TransactionStatus.EXEC)
+ else:
+ tx.update_status(TransactionStatus.FAIL)
+
+ return success
+
+ async def acquire_lock_rm(
+ self, transaction_id: str, path: str, max_parallel: Optional[int] = None
+ ) -> bool:
+ """Acquire path lock for rm operation.
+
+ Args:
+ transaction_id: Transaction ID
+ path: Directory path to lock
+ max_parallel: Maximum number of parallel lock operations (default: from config)
+
+ Returns:
+ True if lock acquired successfully, False otherwise
+ """
+ tx = self.get_transaction(transaction_id)
+ if not tx:
+ logger.error(f"Transaction not found: {transaction_id}")
+ return False
+
+ tx.update_status(TransactionStatus.AQUIRE)
+ parallel = max_parallel or self._max_parallel_locks
+ success = await self._path_lock.acquire_rm(path, tx, parallel)
+
+ if success:
+ tx.update_status(TransactionStatus.EXEC)
+ else:
+ tx.update_status(TransactionStatus.FAIL)
+
+ return success
+
+ async def acquire_lock_mv(
+ self,
+ transaction_id: str,
+ src_path: str,
+ dst_path: str,
+ max_parallel: Optional[int] = None,
+ ) -> bool:
+ """Acquire path lock for mv operation.
+
+ Args:
+ transaction_id: Transaction ID
+ src_path: Source directory path
+ dst_path: Destination directory path
+ max_parallel: Maximum number of parallel lock operations (default: from config)
+
+ Returns:
+ True if lock acquired successfully, False otherwise
+ """
+ tx = self.get_transaction(transaction_id)
+ if not tx:
+ logger.error(f"Transaction not found: {transaction_id}")
+ return False
+
+ tx.update_status(TransactionStatus.AQUIRE)
+ parallel = max_parallel or self._max_parallel_locks
+ success = await self._path_lock.acquire_mv(src_path, dst_path, tx, parallel)
+
+ if success:
+ tx.update_status(TransactionStatus.EXEC)
+ else:
+ tx.update_status(TransactionStatus.FAIL)
+
+ return success
+
+ def get_active_transactions(self) -> Dict[str, TransactionRecord]:
+ """Get all active transactions.
+
+ Returns:
+ Dictionary of active transactions {transaction_id: TransactionRecord}
+ """
+ return self._transactions.copy()
+
+ def get_transaction_count(self) -> int:
+ """Get the number of active transactions.
+
+ Returns:
+ Number of active transactions
+ """
+ return len(self._transactions)
+
+
+def init_transaction_manager(
+ agfs_config: Any,
+ tx_timeout: int = 3600,
+ max_parallel_locks: int = 8,
+) -> TransactionManager:
+ """Initialize transaction manager singleton.
+
+ Args:
+ agfs_config: AGFS configuration (url, timeout, etc.)
+ tx_timeout: Transaction timeout in seconds (default: 3600)
+ max_parallel_locks: Maximum number of parallel lock operations (default: 8)
+
+ Returns:
+ TransactionManager instance
+ """
+ global _transaction_manager
+
+ with _lock:
+ if _transaction_manager is not None:
+ logger.debug("TransactionManager already initialized")
+ return _transaction_manager
+
+ # Get AGFS URL from config
+ agfs_url = getattr(agfs_config, "url", "http://localhost:8080")
+ agfs_timeout = getattr(agfs_config, "timeout", 10)
+
+ # Create AGFS client
+ agfs_client = AGFSClient(api_base_url=agfs_url, timeout=agfs_timeout)
+
+ # Create transaction manager
+ _transaction_manager = TransactionManager(
+ agfs_client=agfs_client,
+ timeout=tx_timeout,
+ max_parallel_locks=max_parallel_locks,
+ )
+
+ logger.info("TransactionManager initialized as singleton")
+ return _transaction_manager
+
+
+def get_transaction_manager() -> Optional[TransactionManager]:
+ """Get transaction manager singleton.
+
+ Returns:
+ TransactionManager instance or None if not initialized
+ """
+ return _transaction_manager
diff --git a/openviking/storage/transaction/transaction_record.py b/openviking/storage/transaction/transaction_record.py
new file mode 100644
index 000000000..fba6480b9
--- /dev/null
+++ b/openviking/storage/transaction/transaction_record.py
@@ -0,0 +1,122 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""
+Transaction record and status definitions.
+
+Defines the data structures for tracking transaction lifecycle and state.
+"""
+
+import time
+import uuid
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Any, Dict, List
+
+
+class TransactionStatus(str, Enum):
+ """Transaction status enumeration.
+
+ Status machine: INIT -> AQUIRE -> EXEC -> COMMIT/FAIL -> RELEASING -> RELEASED
+ """
+
+ INIT = "INIT" # Transaction initialized, waiting for lock acquisition
+ AQUIRE = "AQUIRE" # Acquiring lock resources
+ EXEC = "EXEC" # Transaction operation in progress
+ COMMIT = "COMMIT" # Transaction completed successfully
+ FAIL = "FAIL" # Transaction failed
+ RELEASING = "RELEASING" # Releasing lock resources
+ RELEASED = "RELEASED" # Lock resources fully released, transaction ended
+
+ def __str__(self) -> str:
+ return self.value
+
+
+@dataclass
+class TransactionRecord:
+ """Transaction record for tracking transaction lifecycle.
+
+ Attributes:
+ id: Transaction ID in UUID format, uniquely identifies a transaction
+ locks: List of lock paths held by this transaction
+ status: Current transaction status
+ init_info: Transaction initialization information
+ rollback_info: Information for rollback operations
+ created_at: Creation timestamp (Unix timestamp in seconds)
+ updated_at: Last update timestamp (Unix timestamp in seconds)
+ """
+
+ id: str = field(default_factory=lambda: str(uuid.uuid4()))
+ locks: List[str] = field(default_factory=list)
+ status: TransactionStatus = field(default=TransactionStatus.INIT)
+ init_info: Dict[str, Any] = field(default_factory=dict)
+ rollback_info: Dict[str, Any] = field(default_factory=dict)
+ created_at: float = field(default_factory=time.time)
+ updated_at: float = field(default_factory=time.time)
+
+ def update_status(self, status: TransactionStatus) -> None:
+ """Update transaction status and timestamp.
+
+ Args:
+ status: New transaction statusudi
+ """
+ self.status = status
+ self.updated_at = time.time()
+
+ def add_lock(self, lock_path: str) -> None:
+ """Add a lock to the transaction.
+
+ Args:
+ lock_path: Path to be locked
+ """
+ if lock_path not in self.locks:
+ self.locks.append(lock_path)
+ self.updated_at = time.time()
+
+ def remove_lock(self, lock_path: str) -> None:
+ """Remove a lock from the transaction.
+
+ Args:
+ lock_path: Path to be unlocked
+ """
+ if lock_path in self.locks:
+ self.locks.remove(lock_path)
+ self.updated_at = time.time()
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert transaction record to dictionary.
+
+ Returns:
+ Dictionary representation of the transaction record
+ """
+ return {
+ "id": self.id,
+ "locks": self.locks,
+ "status": str(self.status),
+ "init_info": self.init_info,
+ "rollback_info": self.rollback_info,
+ "created_at": self.created_at,
+ "updated_at": self.updated_at,
+ }
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "TransactionRecord":
+ """Create transaction record from dictionary.
+
+ Args:
+ data: Dictionary representation of the transaction record
+
+ Returns:
+ TransactionRecord instance
+ """
+ status_str = data.get("status", "INIT")
+ status = TransactionStatus(status_str) if isinstance(status_str, str) else status_str
+
+ return cls(
+ id=data.get("id", str(uuid.uuid4())),
+ locks=data.get("locks", []),
+ status=status,
+ init_info=data.get("init_info", {}),
+ rollback_info=data.get("rollback_info", {}),
+ created_at=data.get("created_at", time.time()),
+ updated_at=data.get("updated_at", time.time()),
+ )
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index e49208c3f..af948871d 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -19,6 +19,8 @@ from datetime import datetime
from pathlib import PurePath
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+from pyagfs import AGFSClient
+
from openviking.storage.vikingdb_interface import VikingDBInterface
from openviking.utils.logger import get_logger
@@ -111,13 +113,6 @@ class VikingFS:
vector_store: Optional["VikingDBInterface"] = None,
timeout: int = 10,
):
- try:
- from pyagfs import AGFSClient
- except ImportError:
- raise ImportError(
- "pyagfs not found. Please install: pip install -e third_party/agfs/agfs-sdk/python"
- )
-
self.agfs = AGFSClient(api_base_url=agfs_url, timeout=timeout)
self.query_embedder = query_embedder
self.rerank_config = rerank_config
diff --git a/openviking/utils/async_utils.py b/openviking/utils/async_utils.py
index ef30b3206..bc60c8b92 100644
--- a/openviking/utils/async_utils.py
+++ b/openviking/utils/async_utils.py
@@ -4,8 +4,8 @@
Async helper utilities for running coroutines from sync code.
"""
-import atexit
import asyncio
+import atexit
import threading
from typing import Coroutine, TypeVar
@@ -55,17 +55,15 @@ def run_async(coro: Coroutine[None, None, T]) -> T:
coro: The coroutine to run
Returns:
- The result of the coroutine
+ The result of coroutine
"""
try:
loop = asyncio.get_running_loop()
- # Already in event loop, use nest_asyncio to allow nested calls
import nest_asyncio
nest_asyncio.apply()
return loop.run_until_complete(coro)
except RuntimeError:
- # No running event loop — dispatch to the shared background loop
loop = _get_loop()
future = asyncio.run_coroutine_threadsafe(coro, loop)
return future.result()
diff --git a/openviking/utils/config/vectordb_config.py b/openviking/utils/config/vectordb_config.py
index 8786abcaa..50ee4ee3a 100644
--- a/openviking/utils/config/vectordb_config.py
+++ b/openviking/utils/config/vectordb_config.py
@@ -4,6 +4,8 @@ from typing import Dict, Optional
from pydantic import BaseModel, Field, model_validator
+COLLECTION_NAME = "context"
+
class VolcengineConfig(BaseModel):
"""Configuration for Volcengine VikingDB."""
@@ -38,7 +40,7 @@ class VectorDBBackendConfig(BaseModel):
description="VectorDB backend type: 'local' (file-based), 'http' (remote service), or 'volcengine' (VikingDB)",
)
- name: Optional[str] = Field(default="context", description="Collection name for VectorDB")
+ name: Optional[str] = Field(default=COLLECTION_NAME, description="Collection name for VectorDB")
path: Optional[str] = Field(default="./data", description="Local storage path for 'local' type")