Skip to content

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

fix(storage): preserve source files when rm index cleanup fails (#3519)

Rocke Dongcfddab1a2311
diff --git a/docs/en/concepts/09-transaction.md b/docs/en/concepts/09-transaction.md
index 4a60190f5..613950c2c 100644
--- a/docs/en/concepts/09-transaction.md
+++ b/docs/en/concepts/09-transaction.md
@@ -86,7 +86,7 @@ Memory extraction is idempotent — re-extracting from the same archive produces
| Problem | Solution |
|---------|----------|
-| Delete file first, then index -> file gone but index remains -> search returns non-existent file | **Reverse order**: delete index first, then file. Index deletion failure -> both file and index intact |
+| Delete file first, then index -> file gone but index remains -> search returns non-existent file | **Reverse order**: delete index first, then file. Index deletion failure -> the source file remains and retry completes any partial index cleanup |
**Locking strategy** (depends on target type):
- Deleting a **directory**: `lock_mode="tree"`, locks the directory and its subtree
@@ -102,7 +102,10 @@ Operation flow:
5. Release lock
```
-VectorDB deletion fails -> exception thrown, lock auto-released, file and index both intact. FS deletion fails -> VectorDB already deleted but file remains, retry is safe.
+Index URI collection or VectorDB deletion fails -> exception thrown, lock auto-released, and the
+source file remains. A backend may already have deleted part of a multi-record index operation, but
+retry is safe and completes cleanup. FS deletion fails -> VectorDB already deleted but file remains,
+retry is also safe.
### mv(old_uri, new_uri)
diff --git a/docs/zh/concepts/09-transaction.md b/docs/zh/concepts/09-transaction.md
index b22f72245..033aacf9d 100644
--- a/docs/zh/concepts/09-transaction.md
+++ b/docs/zh/concepts/09-transaction.md
@@ -85,7 +85,7 @@ Memory 提取是幂等的 — 从同一个 archive 重新提取会得到相同
| 问题 | 方案 |
|------|------|
-| 先删文件再删索引 -> 文件已删但索引残留 -> 搜索返回不存在的文件 | **调换顺序**:先删索引再删文件。索引删除失败 -> 文件和索引都在,搜索正常 |
+| 先删文件再删索引 -> 文件已删但索引残留 -> 搜索返回不存在的文件 | **调换顺序**:先删索引再删文件。索引删除失败 -> 源文件仍在,重试可完成可能只执行了一部分的索引清理 |
**加锁策略**(根据目标类型区分):
- 删除**目录**:`lock_mode="tree"`,锁目录自身及其整棵子树
@@ -101,7 +101,9 @@ Memory 提取是幂等的 — 从同一个 archive 重新提取会得到相同
5. 释放锁
```
-VectorDB 删除失败 -> 直接抛异常,锁自动释放,文件和索引都在。FS 删除失败 -> VectorDB 已删但文件还在,重试即可。
+索引 URI 收集或 VectorDB 删除失败 -> 直接抛异常,锁自动释放,源文件仍在。多记录删除在部分
+后端可能已经执行了一部分,但重试可以安全补完清理。FS 删除失败 -> VectorDB 已删但文件还在,
+重试同样安全。
### mv(old_uri, new_uri)
diff --git a/openviking/storage/vectordb/collection/collection.py b/openviking/storage/vectordb/collection/collection.py
index b4499d08b..dc08699af 100644
--- a/openviking/storage/vectordb/collection/collection.py
+++ b/openviking/storage/vectordb/collection/collection.py
@@ -2,7 +2,7 @@
# SPDX-License-Identifier: AGPL-3.0
import importlib
from abc import ABC, abstractmethod
-from typing import Any, Dict, List, Optional, Type
+from typing import Any, Dict, List, Optional, Type, cast
from openviking.storage.vectordb.collection.result import AggregateResult, SearchResult
from openviking.storage.vectordb.index.index import IIndex
@@ -475,6 +475,7 @@ class Collection:
offset: int = 0,
filters: Optional[Dict[str, Any]] = None,
output_fields: Optional[List[str]] = None,
+ raise_on_error: bool = False,
):
"""Retrieve random documents from the index.
@@ -485,6 +486,7 @@ class Collection:
filters (Optional[Dict[str, Any]]): Query filters to narrow down results. Defaults to None.
output_fields (Optional[List[str]]): List of field names to include in results.
If None, returns all fields. Defaults to None.
+ raise_on_error (bool): Propagate HTTP errors for deletion lookups. Defaults to False.
Returns:
SearchResult: Random documents from the index with field values (scores are not meaningful).
@@ -494,6 +496,15 @@ class Collection:
"""
if self.__collection is None:
raise RuntimeError("Collection is closed")
+ if raise_on_error:
+ return cast(Any, self.__collection).search_by_random(
+ index_name,
+ limit,
+ offset,
+ filters,
+ output_fields,
+ raise_on_error=True,
+ )
return self.__collection.search_by_random(index_name, limit, offset, filters, output_fields)
def search_by_scalar(
diff --git a/openviking/storage/vectordb/collection/http_collection.py b/openviking/storage/vectordb/collection/http_collection.py
index 1405e7e7b..cee2078c7 100644
--- a/openviking/storage/vectordb/collection/http_collection.py
+++ b/openviking/storage/vectordb/collection/http_collection.py
@@ -25,6 +25,16 @@ headers = {
}
+def _parse_success_response(response, operation: str) -> Dict[str, Any]:
+ if response.status_code != 200:
+ raise RuntimeError(f"Failed to {operation}: HTTP {response.status_code}: {response.text}")
+ result = json.loads(response.text)
+ error_code = result.get("code")
+ if error_code != 0:
+ raise RuntimeError(f"Failed to {operation}: code {error_code}: {result.get('message', '')}")
+ return result
+
+
def get_or_create_http_collection(
host: str = "127.0.0.1", port: int = 5000, meta_data: Optional[Dict[str, Any]] = None
):
@@ -353,9 +363,7 @@ class HttpCollection(ICollection):
timeout=DEFAULT_TIMEOUT,
)
# logger.info(f"DeleteData response: {response.text}")
- if response.status_code != 200:
- return {}
- result = json.loads(response.text)
+ result = _parse_success_response(response, "delete data")
return result.get("data", {})
def delete_all_data(self):
@@ -515,6 +523,7 @@ class HttpCollection(ICollection):
offset: int = 0,
filters: Optional[Dict[str, Any]] = None,
output_fields: Optional[List[str]] = None,
+ raise_on_error: bool = False,
) -> SearchResult:
url = self.url_prefix + "api/vikingdb/data/search/random"
response = requests.post(
@@ -532,10 +541,14 @@ class HttpCollection(ICollection):
timeout=DEFAULT_TIMEOUT,
)
# logger.info(f"SearchByRandom response: {response.text}")
- if response.status_code != 200:
- return SearchResult()
-
- data = json.loads(response.text).get("data", {})
+ if raise_on_error:
+ payload = _parse_success_response(response, "query data for deletion")
+ else:
+ if response.status_code != 200:
+ return SearchResult()
+ payload = json.loads(response.text)
+
+ data = payload.get("data", {})
result = SearchResult()
if isinstance(data, dict) and "data" in data:
result.data = [
diff --git a/openviking/storage/vectordb_adapters/base.py b/openviking/storage/vectordb_adapters/base.py
index 1b69237c1..37101dddf 100644
--- a/openviking/storage/vectordb_adapters/base.py
+++ b/openviking/storage/vectordb_adapters/base.py
@@ -464,6 +464,7 @@ class CollectionAdapter(ABC):
output_fields: Optional[list[str]] = None,
order_by: Optional[str] = None,
order_desc: bool = False,
+ raise_on_error: bool = False,
) -> list[Dict[str, Any]]:
coll = self.get_collection()
vectordb_filter = self._compile_filter(filter)
@@ -489,13 +490,23 @@ class CollectionAdapter(ABC):
output_fields=output_fields,
)
else:
- result = coll.search_by_random(
- index_name=self._index_name,
- limit=limit,
- offset=offset,
- filters=vectordb_filter,
- output_fields=output_fields,
- )
+ if raise_on_error:
+ result = coll.search_by_random(
+ index_name=self._index_name,
+ limit=limit,
+ offset=offset,
+ filters=vectordb_filter,
+ output_fields=output_fields,
+ raise_on_error=True,
+ )
+ else:
+ result = coll.search_by_random(
+ index_name=self._index_name,
+ limit=limit,
+ offset=offset,
+ filters=vectordb_filter,
+ output_fields=output_fields,
+ )
records: list[Dict[str, Any]] = []
for item in result.data:
@@ -519,7 +530,12 @@ class CollectionAdapter(ABC):
coll = self.get_collection()
delete_ids = list(ids or [])
if not delete_ids and filter is not None:
- matched = self.query(filter=filter, limit=limit, output_fields=["id"])
+ matched = self.query(
+ filter=filter,
+ limit=limit,
+ output_fields=["id"],
+ raise_on_error=self.mode == "http",
+ )
delete_ids = [record["id"] for record in matched if record.get("id")]
if not delete_ids:
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index 1e1676073..e9ebfdaf7 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -695,7 +695,9 @@ class VikingFS:
lock_mode=lock_mode,
handle=lock_handle,
):
- uris_to_delete = await self._collect_uris(path, recursive, ctx=ctx)
+ uris_to_delete = (
+ await self._collect_uris(path, recursive, ctx=ctx) if is_dir else []
+ )
uris_to_delete.append(target_uri)
real_ctx = self._ctx_or_default(ctx)
estimated_count = await _estimate_deleted_count(path, real_ctx)
@@ -804,7 +806,9 @@ class VikingFS:
)
async with lock_context as active_lock_handle:
- uris_to_move = await self._collect_uris(old_path, recursive=True, ctx=ctx)
+ uris_to_move = (
+ await self._collect_uris(old_path, recursive=True, ctx=ctx) if is_dir else []
+ )
uris_to_move.append(target_uri)
# Check if it's temp directory (files already encrypted)
@@ -824,8 +828,15 @@ class VikingFS:
)
except Exception as e:
if "not found" in str(e).lower():
- await self._delete_from_vector_store(uris_to_move, ctx=ctx)
- logger.info(f"[VikingFS] mv source not found, cleaned orphan index: {old_uri}")
+ try:
+ await self._delete_from_vector_store(uris_to_move, ctx=ctx)
+ except Exception:
+ # Orphan cleanup is best effort here; preserve the copy error.
+ pass
+ else:
+ logger.info(
+ f"[VikingFS] mv source not found, cleaned orphan index: {old_uri}"
+ )
raise
# Remove carried lock file from the copy (directory only)
@@ -2958,19 +2969,23 @@ class VikingFS:
async def _collect(p: str):
try:
- for entry in await self._ls_entries(p, ctx=ctx):
- name = entry.get("name", "")
- if name in [".", ".."]:
- continue
- full_path = f"{p}/{name}".replace("//", "/")
- if entry.get("isDir"):
- uris.append(self._path_to_uri(full_path, ctx=ctx))
- if recursive:
- await _collect(full_path)
- else:
- uris.append(self._path_to_uri(full_path, ctx=ctx))
- except Exception:
- pass
+ entries = await self._ls_entries(p, ctx=ctx)
+ except Exception as exc:
+ if is_not_found_error(exc):
+ return
+ raise
+
+ for entry in entries:
+ name = entry.get("name", "")
+ if name in [".", ".."]:
+ continue
+ full_path = f"{p}/{name}".replace("//", "/")
+ if entry.get("isDir"):
+ uris.append(self._path_to_uri(full_path, ctx=ctx))
+ if recursive:
+ await _collect(full_path)
+ else:
+ uris.append(self._path_to_uri(full_path, ctx=ctx))
await _collect(path)
return uris
@@ -2993,6 +3008,7 @@ class VikingFS:
logger.debug(f"[VikingFS] Deleted from vector store: {uri}")
except Exception as e:
logger.warning(f"[VikingFS] Failed to delete from vector store: {e}")
+ raise
async def _update_vector_store_uris(
self,
diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.py
index 877030eb5..5e7218b26 100644
--- a/openviking/storage/viking_vector_index_backend.py
+++ b/openviking/storage/viking_vector_index_backend.py
@@ -463,7 +463,7 @@ class _SingleAccountBackend:
return await self._async_adapter.call("delete", filter=filter)
except Exception as e:
logger.error("Error deleting by filter: %s", e)
- return 0
+ raise
async def exists(self, id: str) -> bool:
try: