Enterprise agent platform for building, deploying, and operating AI teammates.
feat(rag): refuse delete and rename of collections frozen for migration (#3753)
蓝鱼bluefish10de427ff63a
diff --git a/src/xagent/core/tools/core/RAG_tools/kb/coordinator.py b/src/xagent/core/tools/core/RAG_tools/kb/coordinator.pyindex 46f6f1886..a560bb465 100644--- a/src/xagent/core/tools/core/RAG_tools/kb/coordinator.py+++ b/src/xagent/core/tools/core/RAG_tools/kb/coordinator.py@@ -30,6 +30,7 @@ from ..core.schemas import (RegisterDocumentResponse,SparseSearchResponse,)+from ..management.migration_state import ensure_collection_writable_asyncfrom ..storage.factory import StorageFactoryfrom ..utils.user_scope import resolve_user_scopefrom .api_compatibility import KBApiCompatibilityFacade@@ -1023,14 +1024,16 @@ class KBCoordinator:"""int_user_id = _normalize_user_id(user_id)- handle = await self.open_collection(- KBContextRequest(- collection=collection,- user_id=int_user_id,- is_admin=is_admin,- hide_missing=True,- )+ request = KBContextRequest(+ collection=self._normalize_collection(collection),+ user_id=int_user_id,+ is_admin=is_admin,+ hide_missing=True,)+ collection = request.collection+ await self._ensure_writable(request, collection)++ handle = await self.open_collection(request)warnings: list[str] = warnings_out if warnings_out is not None else []deleted_counts: dict[str, int] = {}@@ -1219,14 +1222,17 @@ class KBCoordinator:"""int_user_id = _normalize_user_id(user_id)- handle = await self.open_collection(- KBContextRequest(- collection=old_name,- user_id=int_user_id,- is_admin=is_admin,- hide_missing=True,- )+ request = KBContextRequest(+ collection=self._normalize_collection(old_name),+ user_id=int_user_id,+ is_admin=is_admin,+ hide_missing=True,)+ old_name = request.collection+ # Source and target (as given and stripped): a frozen row can outlive its collection.+ await self._ensure_writable(request, old_name, new_name, new_name.strip())++ handle = await self.open_collection(request)warnings: list[str] = []@@ -1822,6 +1828,12 @@ class KBCoordinator:))+ async def _ensure_writable(self, request: KBContextRequest, *names: str) -> None:+ # The freeze row lives in this coordinator's store, not necessarily the ambient one.+ store = (await self.get_context(request)).metadata_store+ for name in dict.fromkeys(names):+ await ensure_collection_writable_async(name, store=store)+@staticmethoddef _normalize_collection(collection: str) -> str:normalized = collection.strip() if isinstance(collection, str) else ""diff --git a/src/xagent/core/tools/core/RAG_tools/management/collections.py b/src/xagent/core/tools/core/RAG_tools/management/collections.pyindex b3fb18134..f43fe0485 100644--- a/src/xagent/core/tools/core/RAG_tools/management/collections.py+++ b/src/xagent/core/tools/core/RAG_tools/management/collections.py@@ -50,6 +50,7 @@ from ..utils.lancedb_query_utils import _safe_count_rows, list_table_namesfrom ..utils.string_utils import build_lancedb_filter_expression, escape_lancedb_stringfrom ..utils.user_permissions import UserPermissionsfrom ..utils.user_scope import resolve_user_scope+from .migration_state import ensure_collection_writablelogger = logging.getLogger(__name__)@@ -1263,6 +1264,8 @@ def _delete_document_impl(Returns:DocumentOperationResult: Operation result with deletion counts."""+ ensure_collection_writable(collection)+vector_store = get_vector_index_store()authorized_via_legacy_source_path = Falsediff --git a/src/xagent/core/tools/core/RAG_tools/management/migration_state.py b/src/xagent/core/tools/core/RAG_tools/management/migration_state.pyindex 3497deffd..554cfedc6 100644--- a/src/xagent/core/tools/core/RAG_tools/management/migration_state.py+++ b/src/xagent/core/tools/core/RAG_tools/management/migration_state.py@@ -16,9 +16,11 @@ from typing import (Awaitable,Callable,Dict,+ Iterable,Iterator,Optional,TypeVar,+ Union,cast,)@@ -93,8 +95,10 @@ def _ensure_table(conn: Any) -> None:raise-def _read_row(collection_name: str) -> Optional[Dict[str, Any]]:- conn = get_metadata_store().get_raw_connection()+def _read_row(+ collection_name: str, store: Optional[Any] = None+) -> Optional[Dict[str, Any]]:+ conn = (store or get_metadata_store()).get_raw_connection()if MIGRATION_TABLE not in list_table_names(conn):return Nonetable = conn.open_table(MIGRATION_TABLE)@@ -106,9 +110,11 @@ def _read_row(collection_name: str) -> Optional[Dict[str, Any]]:return rows[0] if rows else None-def read_migration_state(collection_name: str) -> CollectionMigrationState:+def read_migration_state(+ collection_name: str, store: Optional[Any] = None+) -> CollectionMigrationState:"""Read the collection's state; missing table or row means idle."""- row = _read_row(collection_name)+ row = _read_row(collection_name, store)if row is None:return CollectionMigrationState()return CollectionMigrationState(@@ -178,9 +184,9 @@ def _is_admitted(collection: str) -> bool:@contextmanager-def pending_collection(collection: str) -> Iterator[None]:- """Open a scope whose first guard call decides admission for the collection."""- token = _PENDING.set(_PENDING.get() | {collection})+def pending_collection(*collections: str) -> Iterator[None]:+ """Open a scope whose first guard call per collection decides its admission."""+ token = _PENDING.set(_PENDING.get() | set(collections))admitted_token = _ADMITTED.set(_ADMITTED.get())try:yield@@ -214,20 +220,29 @@ async def admitted_context_async(collection: str) -> Context:F = TypeVar("F", bound=Callable[..., Awaitable[Any]])S = TypeVar("S", bound=Callable[..., Any])+Names = Union[str, Iterable[str], None]+++def _as_names(value: Names) -> tuple[str, ...]:+ if value is None:+ return ()+ if isinstance(value, str):+ return (value,)+ return tuple(value)def admits_collection(- get_name: Callable[..., Optional[str]],+ get_name: Callable[..., Names],) -> Callable[[F], F]:"""Open a pending admission for the handler; its first guard call checks."""def decorate(func: F) -> F:@functools.wraps(func)async def wrapper(*args: Any, **kwargs: Any) -> Any:- name = get_name(*args, **kwargs)- if name is None:+ names = _as_names(get_name(*args, **kwargs))+ if not names:return await func(*args, **kwargs)- with pending_collection(name):+ with pending_collection(*names):return await func(*args, **kwargs)return cast(F, wrapper)@@ -274,20 +289,24 @@ def _raise_if_frozen(collection_name: str, state: CollectionMigrationState) -> N)-def ensure_collection_writable(collection_name: str) -> None:+def ensure_collection_writable(+ collection_name: str, *, store: Optional[Any] = None+) -> None:"""Raise before a write when the collection is frozen for migration."""if _is_admitted(collection_name):return- _raise_if_frozen(collection_name, read_migration_state(collection_name))+ _raise_if_frozen(collection_name, read_migration_state(collection_name, store))if collection_name in _PENDING.get():_ADMITTED.set(_ADMITTED.get() | {collection_name})-async def ensure_collection_writable_async(collection_name: str) -> None:+async def ensure_collection_writable_async(+ collection_name: str, *, store: Optional[Any] = None+) -> None:"""Async guard: runs the blocking state read off the event loop."""if _is_admitted(collection_name):return- state = await asyncio.to_thread(read_migration_state, collection_name)+ state = await asyncio.to_thread(read_migration_state, collection_name, store)_raise_if_frozen(collection_name, state)if collection_name in _PENDING.get():_ADMITTED.set(_ADMITTED.get() | {collection_name})diff --git a/src/xagent/web/api/kb.py b/src/xagent/web/api/kb.pyindex 500832755..b28609dd2 100644--- a/src/xagent/web/api/kb.py+++ b/src/xagent/web/api/kb.py@@ -95,7 +95,9 @@ from ...core.tools.core.RAG_tools.kb.models import (from ...core.tools.core.RAG_tools.management.migration_state import (admits_collection,admitted_context_async,+ ensure_collection_writable,ensure_collection_writable_async,+ pending_collection,run_in_admitted_context,)from ...core.tools.core.RAG_tools.management.status import clear_ingestion_status@@ -2624,11 +2626,12 @@ class _WebFileLock:def _admission_collection(collection: Optional[str] = None,+ collection_name: Optional[str] = None,file: Optional[UploadFile] = None,**_: Any,) -> Optional[str]:"""Route param collector for ``admits_collection``; a bad name is left to the handler."""- name = collection+ name = collection if collection is not None else collection_nameif not (isinstance(name, str) and name.strip()):filename = getattr(file, "filename", None)if not filename:@@ -2642,6 +2645,18 @@ def _admission_collection(return None+def _rename_admission_collections(+ collection_name: str, new_name: Optional[str] = None, **_: Any+) -> tuple[str, ...]:+ names = []+ for raw in (collection_name, new_name):+ try:+ names.append(sanitize_path_component(raw or "", "collection"))+ except ValueError:+ pass+ return tuple(names)++def _cloud_admission_collection(request: "CloudIngestRequest", **_: Any) -> Optional[str]:@@ -5857,6 +5872,9 @@ class BatchDeleteFailureItem(BaseModel):name: str = Field(..., description="Collection name")error: str = Field(..., description="Error message")+ code: Optional[str] = Field(+ None, description="Machine-readable reason, e.g. kb_collection_migrating"+ )class BatchDeleteCollectionsResponse(BaseModel):@@ -6238,6 +6256,8 @@ def _perform_kb_collection_delete(if delete_mode == "config_only":return _perform_config_only_collection_delete(safe_collection, user_id)+ # The mode can turn full after the route's snapshot; check before any tombstone.+ ensure_collection_writable(safe_collection)mutation_scope = _resolve_collection_mutation_scope(collection_name=safe_collection,@@ -6333,6 +6353,9 @@ def _perform_kb_collection_delete(except HTTPException:raise+ except CollectionMigratingError:+ # The 409 mapping lives in handle_kb_exceptions; do not wrap as 500.+ raiseexcept Exception as exc:logger.exception("Failed to delete collection '%s'", collection_name)raise HTTPException(@@ -6346,6 +6369,7 @@ def _perform_kb_collection_delete()@with_kb_user_scope@handle_kb_exceptions+@admits_collection(_admission_collection)async def delete_collection_api(collection_name: str,_user: User = Depends(get_current_user),@@ -6376,6 +6400,14 @@ async def delete_collection_api(_user, access = _effective_knowledge_base_user(db, _user, safe_collection, action="delete")+ delete_mode: _DeleteMode = (+ "full"+ if _user.is_admin+ else _get_collection_delete_mode(safe_collection, int(_user.id), is_admin=False)+ )+ # A config-only delete removes just the caller's config row; only the data path is gated.+ if delete_mode == "full":+ await ensure_collection_writable_async(safe_collection)notify_knowledge_base_deleted(db, access.storage_user_id, safe_collection)result = _perform_kb_collection_delete(safe_collection,@@ -6429,22 +6461,24 @@ async def batch_delete_collections_api(effective_user, access = _effective_knowledge_base_user(db, _user, safe_name, action="delete")- # Validate the current delete mode before the lifecycle hook,- # then let the delete pipeline re-check it immediately before- # mutation. Ownership can change between these two points.- if not effective_user.is_admin:- _get_collection_delete_mode(+ delete_mode: _DeleteMode = (+ "full"+ if effective_user.is_admin+ else _get_collection_delete_mode(+ safe_name, int(effective_user.id), is_admin=False+ )+ )+ with pending_collection(safe_name):+ # A config-only delete removes just the caller's config row; gate data deletes only.+ if delete_mode == "full":+ await ensure_collection_writable_async(safe_name)+ notify_knowledge_base_deleted(db, access.storage_user_id, safe_name)+ result = _perform_kb_collection_delete(safe_name,int(effective_user.id),- is_admin=False,+ bool(effective_user.is_admin),+ db,)- notify_knowledge_base_deleted(db, access.storage_user_id, safe_name)- result = _perform_kb_collection_delete(- safe_name,- int(effective_user.id),- bool(effective_user.is_admin),- db,- )if result.status in ("success", "partial_success"):db.commit()deleted.append(name)@@ -6470,6 +6504,14 @@ async def batch_delete_collections_api(name,)continue+ except CollectionMigratingError as e:+ db.rollback()+ failed.append(+ BatchDeleteFailureItem(+ name=name, error=e.message, code="kb_collection_migrating"+ )+ )+ continueexcept Exception as e:db.rollback()logger.exception("Batch delete failed for collection %s: %s", name, e)@@ -6580,6 +6622,7 @@ async def check_documents_exist_api("/collections/{collection_name}/documents/{filename}",)@handle_kb_exceptions+@admits_collection(_admission_collection)async def delete_document_api(collection_name: str,filename: str,@@ -6619,6 +6662,7 @@ async def delete_document_api(# Collection-level gate + vector fallback (rename / metadata lag vs strict visibility).await _ensure_collection_access_for_document_delete(safe_collection_name, _user)+ await ensure_collection_writable_async(safe_collection_name)# Use storage abstraction layer to fetch document recordsvector_store = get_vector_index_store()@@ -7258,6 +7302,7 @@ async def delete_document_api("/collections/{collection_name}",)@handle_kb_exceptions+@admits_collection(_rename_admission_collections)async def rename_collection_api(collection_name: str,new_name: str = Form(..., description="New collection name"),@@ -7300,6 +7345,7 @@ async def rename_collection_api(# Access control checkawait _ensure_collection_access(safe_old_collection, _user, hide_missing=False)+ await ensure_collection_writable_async(safe_old_collection)# Validate that target collection doesn't exist or user has accessvisible_for_user = await _list_collections_with_retry(@@ -7362,6 +7408,8 @@ async def rename_collection_api(detail=_rename_target_has_files_detail(safe_new_collection),)+ # A frozen row can outlive its collection, so an absent target may still be frozen.+ await ensure_collection_writable_async(safe_new_collection)physical_rename_results = {}renamed_owner_ids: list[int] = []for owner_id in sorted(mutation_scope.owner_user_ids):diff --git a/tests/core/tools/adapters/vibe/test_kb_creation_tools.py b/tests/core/tools/adapters/vibe/test_kb_creation_tools.pyindex c9707cb28..c5c35d7a9 100644--- a/tests/core/tools/adapters/vibe/test_kb_creation_tools.py+++ b/tests/core/tools/adapters/vibe/test_kb_creation_tools.py@@ -158,7 +158,7 @@ def _collections_not_frozen(monkeypatch):monkeypatch.setattr(state_module,"read_migration_state",- lambda _name: state_module.CollectionMigrationState(),+ lambda _name, _store=None: state_module.CollectionMigrationState(),)@@ -1512,7 +1512,9 @@ async def test_create_kb_from_file_admits_once_for_all_files(monkeypatch.setattr(state_module,"read_migration_state",- lambda _name: state_module.CollectionMigrationState(state=state["value"]),+ lambda _name, _store=None: state_module.CollectionMigrationState(+ state=state["value"]+ ),)records = []for name in ("a.txt", "b.txt"):diff --git a/tests/core/tools/core/RAG_tools/kb/test_collection_lifecycle_facade_routing.py b/tests/core/tools/core/RAG_tools/kb/test_collection_lifecycle_facade_routing.pyindex ed2626fc9..e2f3a4fc5 100644--- a/tests/core/tools/core/RAG_tools/kb/test_collection_lifecycle_facade_routing.py+++ b/tests/core/tools/core/RAG_tools/kb/test_collection_lifecycle_facade_routing.py@@ -58,6 +58,10 @@ def _make_coordinator_with_mock_handle(handle: MagicMock) -> KBCoordinator:coordinator._handle_provider = MagicMock()coordinator._storage_factory = MagicMock()coordinator._storage_shim = MagicMock()+ # The freeze check resolves the context (and its metadata store) before opening.+ coordinator._storage_shim.get_metadata_store.return_value.get_collection = (+ AsyncMock(return_value=None)+ )coordinator._file_compatibility = MagicMock()coordinator._management = MagicMock()coordinator._parse_display_compatibility = MagicMock()diff --git a/tests/core/tools/core/RAG_tools/management/test_migration_state.py b/tests/core/tools/core/RAG_tools/management/test_migration_state.pyindex bf685e30c..a1e91aee8 100644--- a/tests/core/tools/core/RAG_tools/management/test_migration_state.py+++ b/tests/core/tools/core/RAG_tools/management/test_migration_state.py@@ -6,6 +6,7 @@ import asynciofrom contextlib import contextmanagerfrom pathlib import Pathfrom types import SimpleNamespace+from unittest.mock import AsyncMock, patchimport pytest@@ -15,6 +16,10 @@ from xagent.core.tools.core.RAG_tools.core.schemas import (IngestionResult,WebCrawlConfig,)+from xagent.core.tools.core.RAG_tools.kb.coordinator import KBCoordinator+from xagent.core.tools.core.RAG_tools.management import (+ collections as collections_module,+)from xagent.core.tools.core.RAG_tools.management import migration_state as state_modulefrom xagent.core.tools.core.RAG_tools.management.migration_state import (FROZEN,@@ -190,6 +195,19 @@ def test_unfrozen_collection_proceeds_past_guards(with pytest.raises(_Reached):document_ingestion._process_document_impl("kb", "/tmp/doc.pdf")+ reached_store = {}++ def _store() -> None:+ reached_store["called"] = True+ raise _Reached++ monkeypatch.setattr(collections_module, "get_vector_index_store", _store)+ with pytest.raises(_Reached):+ collections_module._delete_document_impl(+ collection="kb", doc_id="doc-1", user_id=1, coordinator=None+ )+ assert reached_store["called"]+def _migration_names() -> list[str]:conn = get_metadata_store().get_raw_connection()@@ -424,3 +442,239 @@ async def test_run_in_admitted_context_supports_overlapping_workers() -> None:finally:release.set()await holder+++def test_frozen_collection_blocks_document_delete_before_storage(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _freeze()++ def _boom() -> None:+ raise AssertionError("document delete reached the vector store")++ monkeypatch.setattr(collections_module, "get_vector_index_store", _boom)++ with pytest.raises(CollectionMigratingError):+ collections_module._delete_document_impl(+ collection="kb", doc_id="doc-1", user_id=1, coordinator=None+ )+++async def test_frozen_collection_blocks_collection_delete_and_rename() -> None:+ _freeze()+ coordinator = KBCoordinator()++ with pytest.raises(CollectionMigratingError):+ await coordinator.delete_collection("kb", user_id=None, is_admin=True)+ with pytest.raises(CollectionMigratingError):+ await coordinator.rename_collection(+ "kb", "new-name", user_id=None, is_admin=True+ )+++async def test_frozen_rename_refuses_before_opening_the_collection() -> None:+ _freeze()+ coordinator = KBCoordinator()++ with patch.object(+ coordinator,+ "open_collection",+ new=AsyncMock(side_effect=AssertionError("collection was opened")),+ ):+ with pytest.raises(CollectionMigratingError):+ await coordinator.rename_collection(+ "kb", "new-name", user_id=None, is_admin=True+ )+++class _FakeCollectionHandle:+ def list_collection_documents(self, **kwargs: object) -> list[str]:+ return []++ def delete_collection_data(self, **kwargs: object) -> dict[str, int]:+ return {"documents": 0}++ def count_documents(self, **kwargs: object) -> int:+ return 0++ async def delete_collection_config(self, *args: object, **kwargs: object) -> None:+ return None++ def rename_collection_data(self, *args: object, **kwargs: object) -> list[str]:+ return []++ def rename_collection_status(self, *args: object, **kwargs: object) -> list[str]:+ return []++ async def rename_collection_metadata(self, *args: object, **kwargs: object) -> None:+ return None+++# --- Single admission per operation -----------------------------------------+++class _RecordingHandle(_FakeCollectionHandle):+ def __init__(self) -> None:+ self.renames: list[str] = []++ def rename_collection_data(self, *args: object, **kwargs: object) -> list[str]:+ self.renames.append("data")+ return []++ def rename_collection_status(self, *args: object, **kwargs: object) -> list[str]:+ self.renames.append("status")+ return []++ async def rename_collection_metadata(self, *args: object, **kwargs: object) -> None:+ self.renames.append("metadata")+++async def test_rename_inside_admission_completes_after_a_freeze() -> None:+ write_migration_state("kb", CollectionMigrationState(state=IDLE))+ coordinator = KBCoordinator()+ handle = _RecordingHandle()++ with patch.object(+ coordinator, "open_collection", new=AsyncMock(return_value=handle)+ ):+ async with admitted_async("kb"):+ _freeze("kb")+ warnings = await coordinator.rename_collection(+ "kb", "kb-new", user_id=None, is_admin=True+ )++ assert warnings == []+ assert handle.renames == ["data", "status", "metadata"]+ # Rename never moves the row; the migration job owns its lifecycle.+ assert read_migration_state("kb").state == FROZEN+ assert read_migration_state("kb-new").state == IDLE+++async def test_direct_coordinator_rename_still_checks_outside_a_scope() -> None:+ _freeze("kb")+ coordinator = KBCoordinator()++ with pytest.raises(CollectionMigratingError):+ await coordinator.rename_collection("kb", "kb-new", user_id=None, is_admin=True)+++class _TenantHandle(_RecordingHandle):+ def list_collection_documents(self, **kwargs: object) -> list[str]:+ return ["doc-a"]++ def delete_documents_data(+ self, doc_ids: list[str], **kwargs: object+ ) -> dict[str, int]:+ return {"documents": len(doc_ids)}+++async def test_delete_and_rename_leave_the_migration_row_untouched() -> None:+ write_migration_state("kb", CollectionMigrationState(state=IDLE))+ coordinator = KBCoordinator()++ with patch.object(+ coordinator,+ "open_collection",+ new=AsyncMock(return_value=_TenantHandle()),+ ):+ async with admitted_async("kb"):+ _freeze("kb")+ await coordinator.delete_collection("kb", user_id=7, is_admin=False)+ await coordinator.rename_collection(+ "kb", "kb-new", user_id=7, is_admin=False+ )++ assert "kb" in _migration_names()+ assert read_migration_state("kb").state == FROZEN+ assert read_migration_state("kb-new").state == IDLE+++async def test_direct_coordinator_rename_checks_the_target_name() -> None:+ _freeze("kb-target")+ coordinator = KBCoordinator()++ with patch.object(+ coordinator,+ "open_collection",+ new=AsyncMock(side_effect=AssertionError("collection was opened")),+ ):+ with pytest.raises(CollectionMigratingError):+ await coordinator.rename_collection(+ "kb", "kb-target", user_id=1, is_admin=False+ )++[email protected]("operation", ["delete", "rename"])+async def test_coordinator_checks_the_canonical_source_name(operation: str) -> None:+ _freeze("kb")+ coordinator = KBCoordinator()++ with patch.object(+ coordinator,+ "open_collection",+ new=AsyncMock(side_effect=AssertionError("collection was opened")),+ ):+ with pytest.raises(CollectionMigratingError):+ if operation == "delete":+ await coordinator.delete_collection(" kb ", None, True)+ else:+ await coordinator.rename_collection(" kb ", "new-name", None, True)+++def _store_on(path: Path) -> SimpleNamespace:+ import lancedb++ conn = lancedb.connect(str(path))+ return SimpleNamespace(+ get_raw_connection=lambda: conn, get_collection=AsyncMock(return_value=None)+ )+++async def test_injected_coordinator_reads_the_freeze_from_its_own_store(+ tmp_path: Path,+) -> None:+ from unittest.mock import MagicMock++ store = _store_on(tmp_path / "injected")+ state_module._merge_row(+ store.get_raw_connection(),+ {"name": "kb-b", **CollectionMigrationState(state=FROZEN).to_row()},+ )+ _freeze("kb-a")+ shim = MagicMock()+ shim.get_metadata_store.return_value = store+ coordinator = KBCoordinator(storage_shim=shim)++ with patch.object(+ coordinator, "open_collection", new=AsyncMock(return_value=_RecordingHandle())+ ):+ with pytest.raises(CollectionMigratingError):+ await coordinator.rename_collection("src", "kb-b", None, True)+ with pytest.raises(CollectionMigratingError):+ await coordinator.delete_collection("kb-b", None, True)+ # Frozen only in the ambient store: not this coordinator's concern.+ await coordinator.rename_collection("src", "kb-a", None, True)+++async def test_direct_coordinator_rename_checks_the_stripped_target_name() -> None:+ _freeze("kb-target")+ coordinator = KBCoordinator()++ with patch.object(+ coordinator,+ "open_collection",+ new=AsyncMock(side_effect=AssertionError("collection was opened")),+ ):+ with pytest.raises(CollectionMigratingError):+ await coordinator.rename_collection(+ "kb", " kb-target ", user_id=1, is_admin=False+ )diff --git a/tests/web/api/test_kb_exception_decorator.py b/tests/web/api/test_kb_exception_decorator.pyindex a61e36c84..889348b54 100644--- a/tests/web/api/test_kb_exception_decorator.py+++ b/tests/web/api/test_kb_exception_decorator.py@@ -9,6 +9,7 @@ import pytestfrom fastapi import HTTPExceptionfrom xagent.core.tools.core.RAG_tools.core.exceptions import CollectionMigratingError+from xagent.core.tools.core.RAG_tools.core.schemas import CollectionOperationResultfrom xagent.core.tools.core.RAG_tools.kb.api_compatibility import KBApiOperationResultfrom xagent.core.tools.core.RAG_tools.utils.user_scope import get_user_scopefrom xagent.web.api.kb import handle_kb_exceptions, with_kb_user_scope@@ -913,3 +914,737 @@ def test_admission_collection_derives_the_handler_name_from_the_filename(assert _admission_collection(collection=collection, file=upload) == "report-v2"assert _admission_collection(collection="explicit", file=upload) == "explicit"assert _admission_collection(collection=None, file=None) is None+++async def test_delete_collection_route_maps_migration_freeze_to_409() -> None:+ from unittest.mock import AsyncMock, patch++ from xagent.web.api.kb import delete_collection_api++ user, db, access = _migration_mocks()+ with (+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ patch(+ "xagent.web.api.kb.ensure_collection_writable_async",+ new=AsyncMock(side_effect=_migration_error()),+ ),+ ):+ with pytest.raises(HTTPException) as exc_info:+ await delete_collection_api(collection_name="kb", _user=user, db=db)++ assert exc_info.value.status_code == 409+ assert exc_info.value.detail == _MIGRATION_DETAIL+++async def test_batch_delete_frozen_collection_is_per_item_failure_and_continues() -> (+ None+):+ from unittest.mock import MagicMock, patch++ from xagent.web.api.kb import (+ BatchDeleteCollectionsRequest,+ batch_delete_collections_api,+ )++ user, db, access = _migration_mocks()+ _freeze_state("frozen")+ success = MagicMock(status="success", message="")++ with (+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ patch(+ "xagent.web.api.kb._perform_kb_collection_delete",+ return_value=success,+ ) as delete_one,+ ):+ result = await batch_delete_collections_api(+ body=BatchDeleteCollectionsRequest(collection_names=["frozen", "ok"]),+ _user=user,+ db=db,+ )++ assert result.deleted == ["ok"]+ assert [item.name for item in result.failed] == ["frozen"]+ assert "being upgraded" in result.failed[0].error+ delete_one.assert_called_once()+ assert delete_one.call_args.args[0] == "ok"+++async def test_rename_route_refuses_before_physical_rename() -> None:+ from unittest.mock import AsyncMock, patch++ from xagent.web.api.kb import rename_collection_api++ user, db, access = _migration_mocks()+ _freeze_state("kb")+ with (+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ patch("xagent.web.api.kb._ensure_collection_access", new=AsyncMock()),+ patch("xagent.web.api.kb.rename_collection_storage") as physical_rename,+ ):+ with pytest.raises(HTTPException) as exc_info:+ await rename_collection_api(+ collection_name="kb",+ new_name="kb-new",+ _user=user,+ db=db,+ )++ assert exc_info.value.status_code == 409+ assert exc_info.value.detail["code"] == "kb_collection_migrating"+ assert "being upgraded" in exc_info.value.detail["message"]+ physical_rename.assert_not_called()+++async def test_delete_document_route_maps_migration_freeze_to_409() -> None:+ from unittest.mock import AsyncMock, patch++ from xagent.web.api.kb import delete_document_api++ user, db, access = _migration_mocks()+ with (+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ patch(+ "xagent.web.api.kb._ensure_collection_access_for_document_delete",+ new=AsyncMock(),+ ),+ patch("xagent.web.api.kb.get_vector_index_store") as vector_store,+ patch(+ "xagent.web.api.kb.ensure_collection_writable_async",+ new=AsyncMock(side_effect=_migration_error()),+ ),+ ):+ with pytest.raises(HTTPException) as exc_info:+ await delete_document_api(+ collection_name="kb",+ filename="doc.pdf",+ _user=user,+ db=db,+ )++ assert exc_info.value.status_code == 409+ assert exc_info.value.detail == _MIGRATION_DETAIL+ vector_store.assert_not_called()+++async def test_delete_route_admission_covers_the_core_guard() -> None:+ """A freeze after the route admission must not refuse the delete half-way."""+ from unittest.mock import patch++ from xagent.core.tools.core.RAG_tools.management import (+ migration_state as state_module,+ )+ from xagent.web.api.kb import delete_collection_api++ user, db, access = _migration_mocks()+ success = CollectionOperationResult(collection="kb", status="success", message="")++ def _perform(name: str, *args: object) -> object:+ # Freeze lands after the route admitted, before the core guard.+ _freeze_state(name)+ state_module.ensure_collection_writable(name)+ return success++ with (+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ patch("xagent.web.api.kb.notify_knowledge_base_deleted"),+ patch(+ "xagent.web.api.kb._perform_kb_collection_delete",+ side_effect=_perform,+ ),+ ):+ result = await delete_collection_api(collection_name="kb", _user=user, db=db)++ assert result is success+++async def test_batch_delete_route_admission_covers_the_core_guard() -> None:+ from unittest.mock import patch++ from xagent.core.tools.core.RAG_tools.management import (+ migration_state as state_module,+ )+ from xagent.web.api.kb import (+ BatchDeleteCollectionsRequest,+ batch_delete_collections_api,+ )++ user, db, access = _migration_mocks()+ success = CollectionOperationResult(collection="kb", status="success", message="")++ def _perform(name: str, *args: object) -> object:+ _freeze_state(name)+ state_module.ensure_collection_writable(name)+ return success++ with (+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ patch("xagent.web.api.kb.notify_knowledge_base_deleted"),+ patch(+ "xagent.web.api.kb._perform_kb_collection_delete",+ side_effect=_perform,+ ) as delete_one,+ ):+ result = await batch_delete_collections_api(+ body=BatchDeleteCollectionsRequest(collection_names=["a", "b"]),+ _user=user,+ db=db,+ )++ assert result.deleted == ["a", "b"]+ assert result.failed == []+ assert [call.args[0] for call in delete_one.call_args_list] == ["a", "b"]+++async def test_rename_route_admission_covers_the_coordinator_leg() -> None:+ """The coordinator must still rename everything when a freeze lands mid-route."""+ from types import SimpleNamespace+ from unittest.mock import AsyncMock, MagicMock, patch++ from xagent.core.tools.core.RAG_tools.management import (+ migration_state as state_module,+ )+ from xagent.web.api.kb import rename_collection_api++ user, db, access = _migration_mocks()+ renamed = {"vector": False, "status": False, "metadata": False}++ class _Facade:+ async def rename_collection_data(self, **kwargs: object) -> list[str]:+ # Route precheck saw idle; the freeze lands before this core leg.+ _freeze_state("kb")+ await state_module.ensure_collection_writable_async("kb")+ renamed["vector"] = True+ return []++ async def rename_collection_metadata(self, **kwargs: object) -> None:+ renamed["metadata"] = True++ def rename_collection_status(self, **kwargs: object) -> list[str]:+ renamed["status"] = True+ return []++ physical = MagicMock(+ status="not_found",+ error=None,+ old_collection_dir=None,+ new_collection_dir=None,+ )+ with (+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ patch("xagent.web.api.kb._ensure_collection_access", new=AsyncMock()),+ patch(+ "xagent.web.api.kb._list_collections_with_retry",+ new=AsyncMock(return_value=SimpleNamespace(collections=[])),+ ),+ patch(+ "xagent.web.api.kb._resolve_collection_mutation_scope",+ return_value=SimpleNamespace(+ owner_user_ids=[1], file_ids_by_owner={1: set()}+ ),+ ),+ patch(+ "xagent.web.api.kb.get_upload_path",+ return_value=MagicMock(exists=lambda: False),+ ),+ patch(+ "xagent.web.api.kb.rename_collection_storage", return_value=physical+ ) as physical_rename,+ patch(+ "xagent.web.api.kb._get_api_compatibility_facade", return_value=_Facade()+ ),+ patch("xagent.web.api.kb.notify_knowledge_base_renamed"),+ ):+ result = await rename_collection_api(+ collection_name="kb", new_name="kb-new", _user=user, db=db+ )++ physical_rename.assert_called_once()+ assert renamed == {"vector": True, "status": True, "metadata": True}+ assert result["status"] == "partial_success"+++async def test_delete_helper_lets_migration_refusal_through() -> None:+ """A direct core refusal must stay CollectionMigratingError, not become a 500."""+ from types import SimpleNamespace+ from unittest.mock import MagicMock, patch++ from xagent.web.api.kb import _perform_kb_collection_delete++ _freeze_state("kb")+ with patch(+ "xagent.web.api.kb._resolve_collection_mutation_scope",+ return_value=SimpleNamespace(owner_user_ids=[], file_ids_by_owner={}),+ ):+ with pytest.raises(CollectionMigratingError):+ _perform_kb_collection_delete("kb", 1, True, MagicMock())+++async def test_delete_route_authorizes_before_the_freeze_check() -> None:+ """A non-owner must not learn a foreign collection is migrating."""+ from unittest.mock import patch++ from xagent.web.api.kb import delete_collection_api++ user, db, _access = _migration_mocks()+ _freeze_state("kb")+ denied = HTTPException(status_code=403, detail="forbidden")+ with patch("xagent.web.api.kb._effective_knowledge_base_user", side_effect=denied):+ with pytest.raises(HTTPException) as exc_info:+ await delete_collection_api(collection_name="kb", _user=user, db=db)++ assert exc_info.value.status_code == 403+++async def test_rename_route_authorizes_before_the_freeze_check() -> None:+ from unittest.mock import patch++ from xagent.web.api.kb import rename_collection_api++ user, db, _access = _migration_mocks()+ _freeze_state("kb")+ denied = HTTPException(status_code=403, detail="forbidden")+ with patch("xagent.web.api.kb._effective_knowledge_base_user", side_effect=denied):+ with pytest.raises(HTTPException) as exc_info:+ await rename_collection_api(+ collection_name="kb", new_name="kb-new", _user=user, db=db+ )++ assert exc_info.value.status_code == 403+++async def test_config_only_delete_of_a_frozen_name_keeps_its_404() -> None:+ """Another tenant's documents make this delete config-only, so its 404 wins over 409."""+ from unittest.mock import MagicMock, patch++ from xagent.core.tools.core.RAG_tools.management.migration_state import (+ clear_migration_state,+ )+ from xagent.web.api.kb import delete_collection_api++ user, db, access = _migration_mocks()+ user.is_admin = False+ user.id = 2+ vector_store = MagicMock()+ vector_store.count_documents_grouped_by_collection.side_effect = [+ {"guessed": 1},+ {"guessed": 0},+ {"guessed": 1},+ {"guessed": 0},+ ]+ _freeze_state("guessed")+ try:+ with (+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ patch(+ "xagent.web.api.kb.get_vector_index_store",+ return_value=vector_store,+ ),+ patch(+ "xagent.web.api.kb.delete_collection_metadata_sync",+ return_value={"config_rows": 0, "metadata_rows": 0},+ ),+ patch("xagent.web.api.kb.notify_knowledge_base_deleted"),+ ):+ with pytest.raises(HTTPException) as exc_info:+ await delete_collection_api(+ collection_name="guessed", _user=user, db=db+ )+ finally:+ clear_migration_state("guessed")++ assert exc_info.value.status_code == 404+ assert "knowledge base list" in str(exc_info.value.detail)+++def _rename_route_patches(facade: object, physical: object) -> list[object]:+ from types import SimpleNamespace+ from unittest.mock import AsyncMock, MagicMock, patch++ user, _db, access = _migration_mocks()+ return [+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ patch("xagent.web.api.kb._ensure_collection_access", new=AsyncMock()),+ patch(+ "xagent.web.api.kb._list_collections_with_retry",+ new=AsyncMock(return_value=SimpleNamespace(collections=[])),+ ),+ patch(+ "xagent.web.api.kb._resolve_collection_mutation_scope",+ return_value=SimpleNamespace(+ owner_user_ids=[1], file_ids_by_owner={1: set()}+ ),+ ),+ patch(+ "xagent.web.api.kb.get_upload_path",+ return_value=MagicMock(exists=lambda: False),+ ),+ patch("xagent.web.api.kb.rename_collection_storage", return_value=physical),+ patch("xagent.web.api.kb._get_api_compatibility_facade", return_value=facade),+ patch("xagent.web.api.kb.notify_knowledge_base_renamed"),+ ]+++async def test_rename_into_an_absent_frozen_target_is_refused() -> None:+ """A frozen row can outlive its collection; renaming onto that name is a new write."""+ from contextlib import ExitStack+ from unittest.mock import MagicMock++ from xagent.web.api.kb import rename_collection_api++ user, db, _access = _migration_mocks()+ facade = MagicMock()+ physical = MagicMock(status="not_found", error=None)+ _freeze_state("kb-gone")+ with ExitStack() as stack:+ mocks = [+ stack.enter_context(p) for p in _rename_route_patches(facade, physical)+ ]+ with pytest.raises(HTTPException) as exc_info:+ await rename_collection_api(+ collection_name="kb-src", new_name="kb-gone", _user=user, db=db+ )++ assert exc_info.value.status_code == 409+ assert exc_info.value.detail["code"] == "kb_collection_migrating"+ mocks[5].assert_not_called()+ facade.rename_collection_data.assert_not_called()+++async def test_rename_route_admission_covers_the_target_in_the_coordinator_leg() -> (+ None+):+ from contextlib import ExitStack+ from unittest.mock import MagicMock++ from xagent.core.tools.core.RAG_tools.management import (+ migration_state as state_module,+ )+ from xagent.web.api.kb import rename_collection_api++ user, db, _access = _migration_mocks()+ renamed: list[str] = []++ class _Facade:+ async def rename_collection_data(self, **kwargs: object) -> list[str]:+ # Both names freeze after the route admitted them.+ _freeze_state("kb")+ _freeze_state("kb-new")+ await state_module.ensure_collection_writable_async("kb")+ await state_module.ensure_collection_writable_async("kb-new")+ renamed.append("vector")+ return []++ async def rename_collection_metadata(self, **kwargs: object) -> None:+ renamed.append("metadata")++ def rename_collection_status(self, **kwargs: object) -> list[str]:+ renamed.append("status")+ return []++ physical = MagicMock(+ status="not_found", error=None, old_collection_dir=None, new_collection_dir=None+ )+ with ExitStack() as stack:+ for p in _rename_route_patches(_Facade(), physical):+ stack.enter_context(p)+ await rename_collection_api(+ collection_name="kb", new_name="kb-new", _user=user, db=db+ )++ assert sorted(renamed) == ["metadata", "status", "vector"]+++async def test_non_admin_full_delete_of_a_frozen_collection_is_refused() -> None:+ from unittest.mock import patch++ from xagent.web.api.kb import delete_collection_api++ user, db, access = _migration_mocks()+ user.is_admin = False+ _freeze_state("kb")+ with (+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ patch("xagent.web.api.kb._get_collection_delete_mode", return_value="full"),+ patch("xagent.web.api.kb.notify_knowledge_base_deleted") as notify,+ patch("xagent.web.api.kb._perform_kb_collection_delete") as perform,+ ):+ with pytest.raises(HTTPException) as exc_info:+ await delete_collection_api(collection_name="kb", _user=user, db=db)++ assert exc_info.value.status_code == 409+ assert exc_info.value.detail["code"] == "kb_collection_migrating"+ notify.assert_not_called()+ perform.assert_not_called()++[email protected]("route", ["single", "batch"])+async def test_delete_that_turns_full_after_the_snapshot_checks_before_tombstones(+ route: str,+) -> None:+ from types import SimpleNamespace+ from unittest.mock import patch++ from xagent.web.api.kb import (+ BatchDeleteCollectionsRequest,+ batch_delete_collections_api,+ delete_collection_api,+ )++ user, db, access = _migration_mocks()+ user.is_admin = False+ _freeze_state("kb")+ with (+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ # The route sees config-only; an admitted ingest lands before the helper re-reads.+ patch(+ "xagent.web.api.kb._get_collection_delete_mode",+ side_effect=["config_only", "full"],+ ),+ patch("xagent.web.api.kb.notify_knowledge_base_deleted"),+ patch(+ "xagent.web.api.kb._resolve_collection_mutation_scope",+ return_value=SimpleNamespace(owner_user_ids=[1], file_ids_by_owner={}),+ ),+ patch("xagent.web.api.kb.tombstone_kb_ingest_targets_for_collection") as tomb,+ ):+ if route == "single":+ with pytest.raises(HTTPException) as exc_info:+ await delete_collection_api(collection_name="kb", _user=user, db=db)+ assert exc_info.value.detail["code"] == "kb_collection_migrating"+ else:+ result = await batch_delete_collections_api(+ body=BatchDeleteCollectionsRequest(collection_names=["kb"]),+ _user=user,+ db=db,+ )+ assert [item.name for item in result.failed] == ["kb"]++ tomb.assert_not_called()+++async def test_batch_delete_marks_a_migration_refusal_with_its_code() -> None:+ from unittest.mock import patch++ from xagent.web.api.kb import (+ BatchDeleteCollectionsRequest,+ batch_delete_collections_api,+ )++ user, db, access = _migration_mocks()+ _freeze_state("frozen")+ with patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ):+ result = await batch_delete_collections_api(+ body=BatchDeleteCollectionsRequest(collection_names=["frozen"]),+ _user=user,+ db=db,+ )++ assert [(item.name, item.code) for item in result.failed] == [+ ("frozen", "kb_collection_migrating")+ ]+++async def test_delete_document_route_admission_covers_the_core_guard() -> None:+ """A freeze after the route admission must not refuse the per-document delete."""+ from types import SimpleNamespace+ from unittest.mock import AsyncMock, MagicMock, patch++ from xagent.core.tools.core.RAG_tools.management import (+ migration_state as state_module,+ )+ from xagent.web.api.kb import delete_document_api++ user, db, access = _migration_mocks()+ store = MagicMock()+ store.list_document_records.return_value = [+ SimpleNamespace(doc_id="doc-1", file_id=None, source_path="doc.pdf")+ ]++ def _delete(collection: str, *args: object) -> object:+ _freeze_state(collection)+ state_module.ensure_collection_writable(collection)+ return SimpleNamespace(status="success", message="")++ with (+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ patch(+ "xagent.web.api.kb._ensure_collection_access_for_document_delete",+ new=AsyncMock(),+ ),+ patch("xagent.web.api.kb.get_vector_index_store", return_value=store),+ patch("xagent.web.api.kb._build_uploaded_filename_map", return_value={}),+ patch("xagent.web.api.kb.delete_document", side_effect=_delete) as delete,+ ):+ result = await delete_document_api(+ collection_name="kb",+ filename="doc.pdf",+ file_id=None,+ doc_id="doc-1",+ _user=user,+ db=db,+ )++ delete.assert_called_once()+ assert result["deleted_doc_ids"] == ["doc-1"]+++class _CoordinatorHandle:+ def __init__(self) -> None:+ self.calls: list[str] = []++ def list_collection_documents(self, **kwargs: object) -> list[str]:+ return []++ def delete_collection_data(self, **kwargs: object) -> dict[str, int]:+ self.calls.append("delete_data")+ return {"documents": 1}++ def count_documents(self, **kwargs: object) -> int:+ return 0++ async def delete_collection_config(self, *args: object, **kwargs: object) -> None:+ self.calls.append("delete_config")++ def rename_collection_data(self, *args: object, **kwargs: object) -> list[str]:+ self.calls.append("rename_data")+ return []++ def rename_collection_status(self, *args: object, **kwargs: object) -> list[str]:+ self.calls.append("rename_status")+ return []++ async def rename_collection_metadata(self, *args: object, **kwargs: object) -> None:+ self.calls.append("rename_metadata")+++async def test_delete_route_admission_reaches_the_real_coordinator_guard() -> None:+ """Route -> delete helper -> management facade thread -> coordinator, frozen mid-way."""+ from types import SimpleNamespace+ from unittest.mock import AsyncMock, patch++ from xagent.core.tools.core.RAG_tools.kb.coordinator import KBCoordinator+ from xagent.web.api.kb import delete_collection_api++ user, db, access = _migration_mocks()+ handle = _CoordinatorHandle()++ def _scope(**kwargs: object) -> object:+ _freeze_state("kb")+ return SimpleNamespace(owner_user_ids=[], file_ids_by_owner={})++ with (+ patch(+ "xagent.web.api.kb._effective_knowledge_base_user",+ return_value=(user, access),+ ),+ patch("xagent.web.api.kb.notify_knowledge_base_deleted"),+ patch(+ "xagent.web.api.kb._resolve_collection_mutation_scope", side_effect=_scope+ ),+ patch("xagent.web.api.kb._find_referenced_file_ids", return_value=set()),+ patch.object(+ KBCoordinator, "open_collection", new=AsyncMock(return_value=handle)+ ),+ ):+ await delete_collection_api(collection_name="kb", _user=user, db=db)++ assert "delete_data" in handle.calls+++async def test_rename_route_admission_reaches_the_real_coordinator_guard() -> None:+ from contextlib import ExitStack+ from unittest.mock import AsyncMock, MagicMock, patch++ from xagent.core.tools.core.RAG_tools.kb.coordinator import KBCoordinator+ from xagent.web.api import kb as kb_module+ from xagent.web.api.kb import rename_collection_api++ user, db, _access = _migration_mocks()+ handle = _CoordinatorHandle()++ def _physical(*args: object, **kwargs: object) -> object:+ _freeze_state("kb")+ _freeze_state("kb-new")+ return MagicMock(+ status="not_found",+ error=None,+ old_collection_dir=None,+ new_collection_dir=None,+ )++ real_facade = kb_module._get_api_compatibility_facade()+ with ExitStack() as stack:+ for p in _rename_route_patches(real_facade, MagicMock()):+ stack.enter_context(p)+ stack.enter_context(+ patch("xagent.web.api.kb.rename_collection_storage", side_effect=_physical)+ )+ stack.enter_context(+ patch.object(+ KBCoordinator, "open_collection", new=AsyncMock(return_value=handle)+ )+ )+ await rename_collection_api(+ collection_name="kb", new_name="kb-new", _user=user, db=db+ )++ assert "rename_data" in handle.calls