Skip to content

Enterprise agent platform for building, deploying, and operating AI teammates.

feat(kb): lease admitted writers so a migration can wait for them (#3794)

蓝鱼bluefish56bcfc0c2696
diff --git a/src/xagent/core/tools/adapters/vibe/file_ingestion_tool.py b/src/xagent/core/tools/adapters/vibe/file_ingestion_tool.py
index 7b3f42236..79fa21e65 100644
--- a/src/xagent/core/tools/adapters/vibe/file_ingestion_tool.py
+++ b/src/xagent/core/tools/adapters/vibe/file_ingestion_tool.py
@@ -1,6 +1,7 @@
import logging
import re
import time
+from contextlib import AsyncExitStack
from dataclasses import dataclass
from functools import partial
from pathlib import Path
@@ -132,11 +133,14 @@ async def _create_knowledge_base_from_file_impl(
from ...core.RAG_tools.core.exceptions import CollectionMigratingError
from ...core.RAG_tools.management.migration_state import (
admitted_context_async,
+ holding_leases,
run_in_admitted_context,
+ verify_active_leases,
)
collection_name = ""
ingested_count = 0
+ leases = AsyncExitStack()
try:
from sqlalchemy.orm import Session
@@ -202,12 +206,19 @@ async def _create_knowledge_base_from_file_impl(
# the collection is ours to clean up if every file fails.
collection_existed_before = await kb_service.collection_exists(collection_name)
# One admission for every file, so a freeze between files cannot strand a partial.
+ # The lease goes in first and spans the same work, so a migration waits
+ # for this tool too.
+ await leases.enter_async_context(
+ holding_leases(collection_name, operation="agent-file-ingestion")
+ )
admission = await admitted_context_async(collection_name)
ingested_count = 0
errors = []
for record in file_records:
+ # The pipeline reports a lost lease as a failed file; stop the run.
+ verify_active_leases(collection_name)
try:
source_path = await async_ensure_uploaded_file_local_path(record)
except DurableObjectIntegrityError:
@@ -255,6 +266,9 @@ async def _create_knowledge_base_from_file_impl(
user_id=user_id,
is_admin=is_admin,
file_id=str(record.file_id),
+ # Before every write: a lease lost to a stalled process means a
+ # migration may already have started switching this collection.
+ commit_gate=partial(verify_active_leases, collection_name),
)
try:
result = await run_blocking(run_in_admitted_context, admission, func)
@@ -288,6 +302,7 @@ async def _create_knowledge_base_from_file_impl(
collection_name,
)
+ verify_active_leases(collection_name)
if ingested_count == 0:
if not collection_existed_before:
await kb_service.cleanup_failed_collection(collection_name)
@@ -353,3 +368,5 @@ async def _create_knowledge_base_from_file_impl(
message=str(e),
files_ingested=0,
).model_dump()
+ finally:
+ await leases.aclose()
diff --git a/src/xagent/core/tools/core/RAG_tools/kb/coordinator.py b/src/xagent/core/tools/core/RAG_tools/kb/coordinator.py
index a560bb465..9c5373b2c 100644
--- a/src/xagent/core/tools/core/RAG_tools/kb/coordinator.py
+++ b/src/xagent/core/tools/core/RAG_tools/kb/coordinator.py
@@ -30,7 +30,11 @@ from ..core.schemas import (
RegisterDocumentResponse,
SparseSearchResponse,
)
-from ..management.migration_state import ensure_collection_writable_async
+from ..management.migration_state import (
+ ensure_collection_writable_async,
+ holding_leases,
+ verify_active_leases,
+)
from ..storage.factory import StorageFactory
from ..utils.user_scope import resolve_user_scope
from .api_compatibility import KBApiCompatibilityFacade
@@ -1031,6 +1035,24 @@ class KBCoordinator:
hide_missing=True,
)
collection = request.collection
+ store = (await self.get_context(request)).metadata_store
+ async with holding_leases(
+ collection, operation="collection-delete", store=store
+ ):
+ return await self._delete_collection_body(
+ request, doc_ids, warnings_out, delete_orphaned_metadata
+ )
+
+ async def _delete_collection_body(
+ self,
+ request: KBContextRequest,
+ doc_ids: list[str] | None,
+ warnings_out: list[str] | None,
+ delete_orphaned_metadata: bool,
+ ) -> CollectionOperationResult:
+ collection = request.collection
+ int_user_id = request.user_id
+ is_admin = request.is_admin
await self._ensure_writable(request, collection)
handle = await self.open_collection(request)
@@ -1078,6 +1100,7 @@ class KBCoordinator:
if not is_admin and effective_doc_ids is None:
effective_doc_ids = affected_doc_ids
+ verify_active_leases(collection)
try:
if is_admin:
result_counts = await run_blocking(
@@ -1230,6 +1253,26 @@ class KBCoordinator:
)
old_name = request.collection
# Source and target (as given and stripped): a frozen row can outlive its collection.
+ store = (await self.get_context(request)).metadata_store
+ async with holding_leases(
+ old_name,
+ new_name,
+ new_name.strip(),
+ operation="collection-rename",
+ store=store,
+ ):
+ return await self._rename_collection_body(
+ request, old_name, new_name, int_user_id, is_admin
+ )
+
+ async def _rename_collection_body(
+ self,
+ request: KBContextRequest,
+ old_name: str,
+ new_name: str,
+ int_user_id: Optional[int],
+ is_admin: bool,
+ ) -> list[str]:
await self._ensure_writable(request, old_name, new_name, new_name.strip())
handle = await self.open_collection(request)
@@ -1243,6 +1286,8 @@ class KBCoordinator:
# gate: a hard exception (e.g. no DB connection) propagates out, and
# per-table failures are returned as a non-empty warnings list (the store
# catches them per table rather than raising) — short-circuit on those too.
+ verify_active_leases(old_name)
+ verify_active_leases(new_name)
data_warnings = await run_blocking(
handle.rename_collection_data,
new_name,
diff --git a/src/xagent/core/tools/core/RAG_tools/management/collections.py b/src/xagent/core/tools/core/RAG_tools/management/collections.py
index f43fe0485..5a7dc8f1e 100644
--- a/src/xagent/core/tools/core/RAG_tools/management/collections.py
+++ b/src/xagent/core/tools/core/RAG_tools/management/collections.py
@@ -50,7 +50,11 @@ from ..utils.lancedb_query_utils import _safe_count_rows, list_table_names
from ..utils.string_utils import build_lancedb_filter_expression, escape_lancedb_string
from ..utils.user_permissions import UserPermissions
from ..utils.user_scope import resolve_user_scope
-from .migration_state import ensure_collection_writable
+from .migration_state import (
+ ensure_collection_writable,
+ leased_collections,
+ verify_active_leases,
+)
logger = logging.getLogger(__name__)
@@ -1264,112 +1268,118 @@ def _delete_document_impl(
Returns:
DocumentOperationResult: Operation result with deletion counts.
"""
- ensure_collection_writable(collection)
-
- vector_store = get_vector_index_store()
+ with leased_collections(collection, operation="document-delete"):
+ ensure_collection_writable(collection)
- authorized_via_legacy_source_path = False
+ vector_store = get_vector_index_store()
- try:
- document_count = vector_store.count_rows(
- table_name="documents",
- filters={"collection": collection, "doc_id": doc_id},
- user_id=user_id,
- is_admin=is_admin,
- )
- except Exception as exc: # noqa: BLE001
- logger.error(
- "Failed to authorize document deletion %s/%s: %s",
- collection,
- doc_id,
- exc,
- )
- return DocumentOperationResult(
- status="error",
- collection=collection,
- doc_id=doc_id,
- new_status=DocumentProcessingStatus.FAILED,
- message=f"Failed to delete document: {exc}",
- warnings=[],
- details={},
- )
+ authorized_via_legacy_source_path = False
- if document_count == 0:
- owner_context = _load_document_owner_context(collection, doc_id)
- if owner_context is None:
+ try:
+ document_count = vector_store.count_rows(
+ table_name="documents",
+ filters={"collection": collection, "doc_id": doc_id},
+ user_id=user_id,
+ is_admin=is_admin,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.error(
+ "Failed to authorize document deletion %s/%s: %s",
+ collection,
+ doc_id,
+ exc,
+ )
return DocumentOperationResult(
status="error",
collection=collection,
doc_id=doc_id,
new_status=DocumentProcessingStatus.FAILED,
- message="Document not found or not accessible.",
+ message=f"Failed to delete document: {exc}",
warnings=[],
details={},
)
- owner_user_id = owner_context.get("owner_user_id")
- if owner_user_id is None:
- owner_user_id = _extract_user_id_from_source_path(
- owner_context.get("source_path")
+ if document_count == 0:
+ owner_context = _load_document_owner_context(collection, doc_id)
+ if owner_context is None:
+ return DocumentOperationResult(
+ status="error",
+ collection=collection,
+ doc_id=doc_id,
+ new_status=DocumentProcessingStatus.FAILED,
+ message="Document not found or not accessible.",
+ warnings=[],
+ details={},
+ )
+
+ owner_user_id = owner_context.get("owner_user_id")
+ if owner_user_id is None:
+ owner_user_id = _extract_user_id_from_source_path(
+ owner_context.get("source_path")
+ )
+
+ if not is_admin and owner_user_id != user_id:
+ return DocumentOperationResult(
+ status="error",
+ collection=collection,
+ doc_id=doc_id,
+ new_status=DocumentProcessingStatus.FAILED,
+ message="Document not found or not accessible.",
+ warnings=[],
+ details={},
+ )
+
+ authorized_via_legacy_source_path = (
+ owner_context.get("owner_user_id") is None
)
- if not is_admin and owner_user_id != user_id:
+ # Immediately before the write: a lease lost while resolving the
+ # document above would otherwise go unnoticed here.
+ verify_active_leases(collection)
+ try:
+ counts = coordinator.delete_documents_data_sync(
+ collection, [doc_id], user_id=user_id, is_admin=is_admin
+ )
+ _clear_ingestion_status_impl(
+ collection,
+ doc_id,
+ user_id=None if authorized_via_legacy_source_path else user_id,
+ is_admin=is_admin or authorized_via_legacy_source_path,
+ )
+ except Exception as exc: # noqa: BLE001
+ # The store wraps delete failures; report the root cause as before.
+ cause = (
+ exc.__cause__
+ if isinstance(exc, DatabaseOperationError) and exc.__cause__ is not None
+ else exc
+ )
+ logger.error(
+ "Failed to delete document %s/%s: %s",
+ collection,
+ doc_id,
+ cause,
+ exc_info=True,
+ )
return DocumentOperationResult(
status="error",
collection=collection,
doc_id=doc_id,
new_status=DocumentProcessingStatus.FAILED,
- message="Document not found or not accessible.",
+ message=f"Failed to delete document: {cause}",
warnings=[],
details={},
)
- authorized_via_legacy_source_path = owner_context.get("owner_user_id") is None
-
- try:
- counts = coordinator.delete_documents_data_sync(
- collection, [doc_id], user_id=user_id, is_admin=is_admin
- )
- _clear_ingestion_status_impl(
- collection,
- doc_id,
- user_id=None if authorized_via_legacy_source_path else user_id,
- is_admin=is_admin or authorized_via_legacy_source_path,
- )
- except Exception as exc: # noqa: BLE001
- # The store wraps delete failures; report the root cause as before.
- cause = (
- exc.__cause__
- if isinstance(exc, DatabaseOperationError) and exc.__cause__ is not None
- else exc
- )
- logger.error(
- "Failed to delete document %s/%s: %s",
- collection,
- doc_id,
- cause,
- exc_info=True,
- )
return DocumentOperationResult(
- status="error",
+ status="success",
collection=collection,
doc_id=doc_id,
new_status=DocumentProcessingStatus.FAILED,
- message=f"Failed to delete document: {cause}",
+ message="Document deleted successfully.",
warnings=[],
- details={},
+ details=counts,
)
- return DocumentOperationResult(
- status="success",
- collection=collection,
- doc_id=doc_id,
- new_status=DocumentProcessingStatus.FAILED,
- message="Document deleted successfully.",
- warnings=[],
- details=counts,
- )
-
def retry_document(
collection: str, doc_id: str, user_id: int, is_admin: bool = False
diff --git a/src/xagent/core/tools/core/RAG_tools/management/migration_state.py b/src/xagent/core/tools/core/RAG_tools/management/migration_state.py
index b304aa67a..3d0f9a942 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
@@ -19,6 +19,7 @@ from typing import (
Iterable,
Iterator,
Optional,
+ Set,
TypeVar,
Union,
cast,
@@ -26,11 +27,20 @@ from typing import (
import pyarrow as pa # type: ignore
+from xagent.core.utils.blocking import run_blocking
+
from ..core.exceptions import CollectionMigratingError
from ..LanceDB.schema_manager import _safe_close_table
from ..storage.factory import get_metadata_store
from ..utils.lancedb_query_utils import list_table_names
from ..utils.string_utils import escape_lancedb_string
+from .write_leases import (
+ LeaseLostError,
+ LeaseSet,
+ acquire_lease,
+ acquire_lease_async,
+ release_leases_async,
+)
MIGRATION_TABLE = "collection_migration_state"
IDLE = "idle"
@@ -47,6 +57,14 @@ _ADMITTED: ContextVar[frozenset[str]] = ContextVar(
_PENDING: ContextVar[frozenset[str]] = ContextVar(
"kb_pending_collections", default=frozenset()
)
+# (collection, lease_id) pairs this operation already holds, and the set that
+# renews and releases them when the operation ends.
+_LEASES: ContextVar[tuple[tuple[str, str], ...]] = ContextVar(
+ "kb_write_leases", default=()
+)
+# Every enclosing lease scope, innermost last: a nested scope must not hide a
+# lease the outer one lost.
+_LEASE_SETS: ContextVar[tuple[LeaseSet, ...]] = ContextVar("kb_lease_sets", default=())
_SCHEMA = pa.schema(
[
@@ -212,6 +230,165 @@ def clear_migration_state(collection_name: str) -> None:
_safe_close_table(table)
+def verify_active_leases(collection: Optional[str] = None) -> None:
+ """Raise when any lease set in this operation is broken.
+
+ Long writers call this at their commit points: a lease the migration has
+ already seen expire means the migration may have started its window, so the
+ operation must stop instead of writing behind it. Every enclosing set is
+ checked, so a nested scope cannot hide a lease the outer one lost.
+ """
+ sets = _LEASE_SETS.get()
+ if not sets:
+ return
+ if collection is not None and not holds_lease(collection):
+ raise CollectionMigratingError(
+ "No write lease is held for this collection; the operation must stop",
+ details={"collection": collection},
+ )
+ try:
+ for item in sets:
+ item.verify()
+ except LeaseLostError as exc:
+ raise CollectionMigratingError(
+ "Knowledge base write lease was lost; the operation must stop",
+ details={"collection": collection, "error": str(exc)},
+ ) from exc
+
+
+def holds_lease(collection: str) -> bool:
+ """Whether this scope already holds ``collection``'s lease."""
+ return any(name == collection for name, _ in _LEASES.get())
+
+
+def _push_scope(lease_set: LeaseSet) -> Any:
+ return _LEASE_SETS.set(_LEASE_SETS.get() + (lease_set,))
+
+
+def _current_set() -> Optional[LeaseSet]:
+ sets = _LEASE_SETS.get()
+ return sets[-1] if sets else None
+
+
+def _verify_enclosing() -> None:
+ """Refuse to start a nested scope inside an already-broken one."""
+ for item in _LEASE_SETS.get():
+ try:
+ item.verify()
+ except LeaseLostError as exc:
+ raise CollectionMigratingError(
+ "Knowledge base write lease was lost before this step",
+ details={"error": str(exc)},
+ ) from exc
+
+
+@contextmanager
+def _lease_scope(*, store: Optional[Any] = None) -> Iterator[LeaseSet]:
+ """The one place a scope is opened: push the set, reset it, release it."""
+ _verify_enclosing()
+ lease_set = LeaseSet(store=store)
+ sets_token = _push_scope(lease_set)
+ leases_token = _LEASES.set(_LEASES.get())
+ try:
+ yield lease_set
+ finally:
+ _LEASE_SETS.reset(sets_token)
+ _LEASES.reset(leases_token)
+ lease_set.release()
+
+
+@asynccontextmanager
+async def _lease_scope_async(*, store: Optional[Any] = None) -> AsyncIterator[LeaseSet]:
+ """``_lease_scope`` for event-loop callers: neither join nor I/O on the loop."""
+ _verify_enclosing()
+ lease_set = LeaseSet(store=store)
+ sets_token = _push_scope(lease_set)
+ leases_token = _LEASES.set(_LEASES.get())
+ try:
+ yield lease_set
+ finally:
+ _LEASE_SETS.reset(sets_token)
+ _LEASES.reset(leases_token)
+ # Stopping the heartbeat must not wait on an await: a second cancel
+ # would leave it renewing a row nobody releases.
+ lease_set.begin_stop()
+ ids = lease_set.lease_ids
+ try:
+ await asyncio.shield(run_blocking(lease_set.stop))
+ finally:
+ await asyncio.shield(_release_tracked(ids, store))
+
+
+def _take_lease(name: str, operation: str, store: Optional[Any]) -> None:
+ """Take ``name``'s lease unless an enclosing scope already holds it."""
+ if holds_lease(name):
+ # A second lease would be a second heartbeat whose loss the outer scope
+ # never sees; reuse what the outer scope already keeps alive.
+ return
+ _record_lease(name, acquire_lease(name, operation, store=store))
+
+
+async def _take_lease_async(name: str, operation: str, store: Optional[Any]) -> None:
+ if holds_lease(name):
+ return
+ task = asyncio.ensure_future(acquire_lease_async(name, operation, store=store))
+ try:
+ lease_id = await asyncio.shield(task)
+ except asyncio.CancelledError:
+ # The insert may land after the cancel; release whatever it produced so
+ # the row cannot delay a migration for a full TTL.
+ task.add_done_callback(functools.partial(_release_after_cancel, store=store))
+ raise
+ _record_lease(name, lease_id)
+
+
+# Releases still in flight: the loop keeps only a weak reference to a task.
+_RELEASE_TASKS: Set["asyncio.Future[Any]"] = set()
+
+
+def _release_tracked(ids: Iterable[str], store: Optional[Any]) -> "asyncio.Future[Any]":
+ task = asyncio.ensure_future(release_leases_async(list(ids), store=store))
+ _RELEASE_TASKS.add(task)
+ task.add_done_callback(_RELEASE_TASKS.discard)
+ return task
+
+
+def _release_after_cancel(
+ task: "asyncio.Future[str]", store: Optional[Any] = None
+) -> None:
+ if task.cancelled() or task.exception() is not None:
+ return
+ try:
+ _release_tracked([task.result()], store)
+ except RuntimeError: # pragma: no cover - loop gone with the request
+ logger.warning("No loop to release lease %s after cancellation", task.result())
+
+
+@asynccontextmanager
+async def holding_leases(
+ *names: str, operation: str, store: Optional[Any] = None
+) -> AsyncIterator[LeaseSet]:
+ """Lease collections for a long operation that starts outside a request scope.
+
+ The coordinator's delete and rename paths do their work after a guard that
+ returned immediately, so they hold nothing the freeze can see. They wrap
+ their whole body in this instead, and the leases then cover every write.
+ """
+ async with _lease_scope_async(store=store) as lease_set:
+ for name in dict.fromkeys(names):
+ await _take_lease_async(name, operation, store)
+ yield lease_set
+
+
+@contextmanager
+def leased_collections(*names: str, operation: str) -> Iterator[LeaseSet]:
+ """Sync counterpart of :func:`holding_leases`."""
+ with _lease_scope() as lease_set:
+ for name in dict.fromkeys(names):
+ _take_lease(name, operation, store=None)
+ yield lease_set
+
+
def _admit(collection: str) -> None:
_ADMITTED.set(_ADMITTED.get() | {collection})
@@ -220,30 +397,75 @@ def _is_admitted(collection: str) -> bool:
return collection in _ADMITTED.get()
+def _record_lease(collection: str, lease_id: str) -> None:
+ _LEASES.set(_LEASES.get() + ((collection, lease_id),))
+ lease_set = _current_set()
+ if lease_set is not None:
+ lease_set.add(lease_id)
+
+
+def _lease_for_guard(collection: str, *, store: Optional[Any] = None) -> None:
+ """Take the operation's lease before the freeze read, when one is due."""
+ if collection not in _PENDING.get() or holds_lease(collection):
+ return
+ _record_lease(collection, acquire_lease(collection, "write-guard", store=store))
+
+
+async def _lease_for_guard_async(
+ collection: str, *, store: Optional[Any] = None
+) -> None:
+ if collection not in _PENDING.get() or holds_lease(collection):
+ return
+ await _take_lease_async(collection, "write-guard", store)
+
+
@contextmanager
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
- finally:
- _ADMITTED.reset(admitted_token)
- _PENDING.reset(token)
+ with _lease_scope():
+ try:
+ yield
+ finally:
+ _ADMITTED.reset(admitted_token)
+ _PENDING.reset(token)
+
+
+@asynccontextmanager
+async def pending_collection_async(*collections: str) -> AsyncIterator[None]:
+ """``pending_collection`` for event-loop callers, releasing off the loop."""
+ token = _PENDING.set(_PENDING.get() | set(collections))
+ admitted_token = _ADMITTED.set(_ADMITTED.get())
+ async with _lease_scope_async():
+ try:
+ yield
+ finally:
+ _ADMITTED.reset(admitted_token)
+ _PENDING.reset(token)
@asynccontextmanager
async def admitted_async(collection: str) -> AsyncIterator[None]:
- """Check the freeze and mark the collection admitted for this scope."""
+ """Check the freeze and mark the collection admitted for this scope.
+
+ The lease goes in first: an operation that finds the collection frozen has
+ already been visible to the migration, which is what closes the gap between
+ checking and freezing.
+ """
if _is_admitted(collection):
yield
return
- await ensure_collection_writable_async(collection)
- token = _ADMITTED.set(_ADMITTED.get() | {collection})
- try:
- yield
- finally:
- _ADMITTED.reset(token)
+ async with _lease_scope_async():
+ await _take_lease_async(collection, "admitted_async", None)
+ await ensure_collection_writable_async(collection)
+ # Taken after the guard: resetting restores the post-guard state, so an
+ # admission the guard granted to the enclosing pending scope survives.
+ admitted_token = _ADMITTED.set(_ADMITTED.get() | {collection})
+ try:
+ yield
+ finally:
+ _ADMITTED.reset(admitted_token)
async def admitted_context_async(collection: str) -> Context:
@@ -279,7 +501,7 @@ def admits_collection(
names = _as_names(get_name(*args, **kwargs))
if not names:
return await func(*args, **kwargs)
- with pending_collection(*names):
+ async with pending_collection_async(*names):
return await func(*args, **kwargs)
return cast(F, wrapper)
@@ -332,6 +554,7 @@ def ensure_collection_writable(
"""Raise before a write when the collection is frozen for migration."""
if _is_admitted(collection_name):
return
+ _lease_for_guard(collection_name, store=store)
_raise_if_frozen(collection_name, read_migration_state(collection_name, store))
if collection_name in _PENDING.get():
_ADMITTED.set(_ADMITTED.get() | {collection_name})
@@ -343,6 +566,7 @@ async def ensure_collection_writable_async(
"""Async guard: runs the blocking state read off the event loop."""
if _is_admitted(collection_name):
return
+ await _lease_for_guard_async(collection_name, store=store)
state = await asyncio.to_thread(read_migration_state, collection_name, store)
_raise_if_frozen(collection_name, state)
if collection_name in _PENDING.get():
diff --git a/src/xagent/core/tools/core/RAG_tools/management/write_leases.py b/src/xagent/core/tools/core/RAG_tools/management/write_leases.py
new file mode 100644
index 000000000..b0da5b856
--- /dev/null
+++ b/src/xagent/core/tools/core/RAG_tools/management/write_leases.py
@@ -0,0 +1,497 @@
+"""Short-lived write leases for operations admitted before a migration freeze.
+
+The freeze guard admits an operation once per scope, and that admission lives in
+process-local context variables, so a migration running in another process cannot
+see a writer that was already admitted. Each admission records a lease row here
+instead, released when the scope exits; a scope that outlives the TTL renews its
+rows, and a crashed process leaves rows that expire.
+
+Ordering is the point: the writer inserts its lease *before* it reads the freeze
+state, and the migration writes the freeze *before* it reads leases. Either the
+writer sees the freeze and refuses, or the migration sees the lease and waits.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import socket
+import threading
+import time
+import uuid
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
+from typing import Any, Iterable, List, Optional, Tuple
+
+import pyarrow as pa # type: ignore
+
+from xagent.core.utils.blocking import run_blocking
+
+from ..LanceDB.schema_manager import _safe_close_table
+from ..storage.factory import get_metadata_store
+from ..utils.lancedb_query_utils import list_table_names
+from ..utils.string_utils import escape_lancedb_string
+
+LEASES_TABLE = "collection_write_leases"
+# Short enough that a crashed operation stops delaying a migration quickly; a
+# live scope renews its rows, so long ingests do not lose their lease.
+DEFAULT_LEASE_TTL_SECONDS = 120.0
+DEFAULT_WAIT_POLL_SECONDS = 1.0
+COMPACT_EVERY_ACQUIRES = 200
+# Writers and the migration compare wall clocks. Rows expire and are judged
+# expired with this much slack, so a clock that runs ahead cannot make another
+# host's live lease look dead; the cost is a slightly longer wait.
+EXPIRY_SKEW_MARGIN_SECONDS = 5.0
+LEASE_WRITE_RETRIES = 3
+GC_EVERY_RENEWALS = 60
+# Lease rows live for minutes; a week of versions would outgrow the rows.
+COMPACT_RETENTION = timedelta(minutes=10)
+
+logger = logging.getLogger(__name__)
+
+_SCHEMA = pa.schema(
+ [
+ ("name", pa.string()),
+ ("lease_id", pa.string()),
+ ("operation", pa.string()),
+ ("owner", pa.string()),
+ ("created_at", pa.timestamp("us")),
+ ("expires_at", pa.timestamp("us")),
+ ]
+)
+
+_acquire_count = 0
+_acquire_lock = threading.Lock()
+_compact_lock = threading.Lock()
+
+
+@dataclass(frozen=True)
+class WriteLease:
+ """One admitted operation that may still be writing to a collection."""
+
+ name: str
+ lease_id: str
+ operation: str
+ owner: str
+ created_at: Optional[datetime]
+ expires_at: Optional[datetime]
+
+
+def _now() -> datetime:
+ return datetime.now(timezone.utc).replace(tzinfo=None)
+
+
+def _store_connection(store: Optional[Any]) -> Any:
+ return (store or get_metadata_store()).get_raw_connection()
+
+
+def _ensure_table(conn: Any) -> None:
+ if LEASES_TABLE in list_table_names(conn):
+ return
+ try:
+ conn.create_table(LEASES_TABLE, schema=_SCHEMA)
+ except Exception:
+ if LEASES_TABLE not in list_table_names(conn):
+ raise
+
+
+def _compact(store: Optional[Any] = None) -> None:
+ if not _compact_lock.acquire(blocking=False):
+ return
+ table = None
+ try:
+ table = _store_connection(store).open_table(LEASES_TABLE)
+ table.optimize(cleanup_older_than=COMPACT_RETENTION)
+ except Exception: # noqa: BLE001 - compaction must never fail a write
+ logger.exception("Failed to compact %s", LEASES_TABLE)
+ finally:
+ _safe_close_table(table)
+ _compact_lock.release()
+
+
+def _maybe_compact(store: Optional[Any] = None) -> None:
+ """Compact the lease table once every few hundred operations, off the caller.
+
+ Rows are deleted on release, so the table only ever holds in-flight leases;
+ what accumulates is fragments and versions from the add/delete/heartbeat
+ writes. Compaction runs on a daemon thread so a slow merge never delays an
+ admission.
+ """
+ global _acquire_count
+ with _acquire_lock:
+ _acquire_count += 1
+ due = _acquire_count % COMPACT_EVERY_ACQUIRES == 0
+ if not due or _compact_lock.locked():
+ return
+ threading.Thread(
+ target=_compact, args=(store,), name="kb-lease-compact", daemon=True
+ ).start()
+
+
+def acquire_lease(
+ name: str,
+ operation: str,
+ *,
+ ttl_seconds: float = DEFAULT_LEASE_TTL_SECONDS,
+ store: Optional[Any] = None,
+) -> str:
+ """Record that this process may write ``name`` until it releases the lease.
+
+ Raises on failure: an admission the migration cannot see must not proceed
+ silently, the same way the freeze read fails closed.
+ """
+ conn = _store_connection(store)
+ _ensure_table(conn)
+ now = _now()
+ lease_id = uuid.uuid4().hex
+ row = {
+ "name": name,
+ "lease_id": lease_id,
+ "operation": operation,
+ "owner": f"{socket.gethostname()}:{os.getpid()}",
+ "created_at": now,
+ "expires_at": now + timedelta(seconds=max(1.0, float(ttl_seconds))),
+ }
+ table = conn.open_table(LEASES_TABLE)
+ try:
+ for attempt in range(LEASE_WRITE_RETRIES):
+ try:
+ table.add([row])
+ break
+ except Exception as exc:
+ # A concurrent commit conflicts with ours; retry like the freeze
+ # table's writer, and only then let the admission fail.
+ if attempt == LEASE_WRITE_RETRIES - 1:
+ raise
+ logger.warning("Retrying lease insert for %s: %s", name, exc)
+ time.sleep(0.1 * (2**attempt))
+ finally:
+ _safe_close_table(table)
+ _maybe_compact(store)
+ return lease_id
+
+
+def renew_leases(
+ lease_ids: Iterable[str],
+ *,
+ ttl_seconds: float = DEFAULT_LEASE_TTL_SECONDS,
+ store: Optional[Any] = None,
+) -> Tuple[int, List[str]]:
+ """Extend these leases; returns (renewed, lost ids).
+
+ A lease whose row is gone, or whose expiry has already passed, is lost: it
+ must not be revived, or a migration that saw it expire would never learn
+ that its owner is still writing.
+ """
+ ids = [lease_id for lease_id in lease_ids if lease_id]
+ if not ids:
+ return 0, []
+ conn = _store_connection(store)
+ if LEASES_TABLE not in list_table_names(conn):
+ return 0, list(ids)
+ table = conn.open_table(LEASES_TABLE)
+ renewed = 0
+ lost: List[str] = []
+ now = _now()
+ try:
+ for lease_id in ids:
+ where = f"lease_id = '{escape_lancedb_string(lease_id)}'"
+ rows = table.search().where(where).to_arrow().to_pylist()
+ if not rows:
+ lost.append(lease_id)
+ continue
+ expires_at = rows[0].get("expires_at")
+ if not isinstance(expires_at, datetime) or expires_at <= now:
+ lost.append(lease_id)
+ continue
+ target = now + timedelta(seconds=max(1.0, float(ttl_seconds)))
+ if expires_at >= target:
+ renewed += 1
+ continue
+ # The expiry test is repeated in the predicate: a row that expired
+ # between the read and this update is not extended.
+ live_where = (
+ f"{where} AND expires_at > TIMESTAMP '{now:%Y-%m-%d %H:%M:%S.%f}'"
+ )
+ updated = int(
+ getattr(
+ table.update(live_where, {"expires_at": target}), "rows_updated", 0
+ )
+ or 0
+ )
+ if updated:
+ renewed += 1
+ else:
+ lost.append(lease_id)
+ return renewed, lost
+ finally:
+ _safe_close_table(table)
+
+
+def release_leases(lease_ids: Iterable[str], *, store: Optional[Any] = None) -> int:
+ """Delete these leases; a missing table or row is a no-op."""
+ ids = [lease_id for lease_id in lease_ids if lease_id]
+ if not ids:
+ return 0
+ conn = _store_connection(store)
+ if LEASES_TABLE not in list_table_names(conn):
+ return 0
+ table = conn.open_table(LEASES_TABLE)
+ released = 0
+ try:
+ for lease_id in ids:
+ try:
+ table.delete(f"lease_id = '{escape_lancedb_string(lease_id)}'")
+ released += 1
+ except Exception as exc: # noqa: BLE001 - release the others anyway
+ logger.warning("Could not release lease %s: %s", lease_id, exc)
+ finally:
+ _safe_close_table(table)
+ return released
+
+
+def live_leases(name: str, *, store: Optional[Any] = None) -> List[WriteLease]:
+ """The unexpired leases for ``name``; a missing table means none."""
+ conn = _store_connection(store)
+ if LEASES_TABLE not in list_table_names(conn):
+ return []
+ table = conn.open_table(LEASES_TABLE)
+ try:
+ where = f"name = '{escape_lancedb_string(name)}'"
+ rows = table.search().where(where).to_arrow().to_pylist()
+ finally:
+ _safe_close_table(table)
+ # Err towards alive: a lease is live until it is a margin past its expiry.
+ cutoff = _now() - timedelta(seconds=EXPIRY_SKEW_MARGIN_SECONDS)
+ live: List[WriteLease] = []
+ for row in rows:
+ expires_at = row.get("expires_at")
+ if not isinstance(expires_at, datetime) or expires_at <= cutoff:
+ continue
+ live.append(
+ WriteLease(
+ name=str(row.get("name") or ""),
+ lease_id=str(row.get("lease_id") or ""),
+ operation=str(row.get("operation") or ""),
+ owner=str(row.get("owner") or ""),
+ created_at=row.get("created_at"),
+ expires_at=expires_at,
+ )
+ )
+ return live
+
+
+def purge_expired_leases(
+ name: Optional[str] = None, *, store: Optional[Any] = None
+) -> int:
+ """Delete expired rows, of ``name`` or of every collection; live rows stay.
+
+ One delete whose predicate repeats the expiry test (with the skew margin),
+ so a lease renewed between the caller's read and this call survives.
+ """
+ conn = _store_connection(store)
+ if LEASES_TABLE not in list_table_names(conn):
+ return 0
+ table = conn.open_table(LEASES_TABLE)
+ try:
+ cutoff = _now() - timedelta(seconds=EXPIRY_SKEW_MARGIN_SECONDS)
+ where = (
+ f"name = '{escape_lancedb_string(name)}'"
+ if name is not None
+ else "lease_id IS NOT NULL"
+ )
+ delete_where = (
+ f"{where} AND expires_at <= TIMESTAMP '{cutoff:%Y-%m-%d %H:%M:%S.%f}'"
+ )
+ try:
+ result = table.delete(delete_where)
+ except Exception as exc: # noqa: BLE001 - nothing is lost by retrying later
+ logger.warning("Could not purge expired leases: %s", exc)
+ return 0
+ return int(getattr(result, "num_deleted_rows", 0) or 0)
+ finally:
+ _safe_close_table(table)
+
+
+def wait_for_no_leases(
+ name: str,
+ *,
+ timeout_seconds: float,
+ poll_seconds: float = DEFAULT_WAIT_POLL_SECONDS,
+ store: Optional[Any] = None,
+) -> List[WriteLease]:
+ """Poll until ``name`` has no live lease; returns what is left at the deadline."""
+ deadline = time.monotonic() + max(0.0, float(timeout_seconds))
+ while True:
+ remaining = live_leases(name, store=store)
+ if not remaining:
+ purge_expired_leases(name, store=store)
+ return []
+ if time.monotonic() >= deadline:
+ return remaining
+ time.sleep(max(0.01, min(poll_seconds, max(0.01, deadline - time.monotonic()))))
+
+
+async def acquire_lease_async(
+ name: str,
+ operation: str,
+ *,
+ ttl_seconds: float = DEFAULT_LEASE_TTL_SECONDS,
+ store: Optional[Any] = None,
+) -> str:
+ return await run_blocking(
+ acquire_lease, name, operation, ttl_seconds=ttl_seconds, store=store
+ )
+
+
+async def release_leases_async(
+ lease_ids: Iterable[str], *, store: Optional[Any] = None
+) -> None:
+ """Release off the event loop; a failure is logged, never raised."""
+ ids = list(lease_ids)
+ try:
+ await run_blocking(release_leases, ids, store=store)
+ except Exception: # noqa: BLE001 - the write already happened
+ logger.exception("Failed to release write leases: %s", sorted(ids))
+
+
+class LeaseLostError(RuntimeError):
+ """A lease this operation held was purged; it must stop writing."""
+
+
+class LeaseSet:
+ """The leases one operation holds, kept alive for as long as it runs."""
+
+ def __init__(
+ self,
+ *,
+ ttl_seconds: float = DEFAULT_LEASE_TTL_SECONDS,
+ store: Optional[Any] = None,
+ ) -> None:
+ self._ttl = ttl_seconds
+ self._store = store
+ self._ids: List[str] = []
+ self._lost: List[str] = []
+ self._renewals = 0
+ self._closed = False
+ # Last successful renewal + TTL - margin: verify() fails past it even
+ # when a stalled heartbeat has not recorded the loss yet.
+ self._alive_until = time.monotonic() + self._lifetime()
+ self._lock = threading.Lock()
+ self._stop = threading.Event()
+ self._thread: Optional[threading.Thread] = None
+
+ def _lifetime(self) -> float:
+ ttl = float(self._ttl)
+ return ttl - min(EXPIRY_SKEW_MARGIN_SECONDS, ttl / 4.0)
+
+ @property
+ def lease_ids(self) -> List[str]:
+ with self._lock:
+ return list(self._ids)
+
+ @property
+ def lost(self) -> List[str]:
+ """Leases this scope could not renew: they are no longer held."""
+ with self._lock:
+ return list(self._lost)
+
+ def add(self, lease_id: str) -> None:
+ with self._lock:
+ if self._closed:
+ # Its row was deleted (or is about to be): nothing renews it.
+ raise LeaseLostError("This lease scope is already closed")
+ if not self._ids:
+ # A scope that reused an enclosing lease had nothing to renew;
+ # its lifetime starts with the first row it owns.
+ self._alive_until = time.monotonic() + self._lifetime()
+ self._ids.append(lease_id)
+ if self._thread is None:
+ self._thread = threading.Thread(
+ target=self._renew_loop,
+ name="kb-write-lease-heartbeat",
+ daemon=True,
+ )
+ self._thread.start()
+
+ def _renew_loop(self) -> None:
+ interval = max(0.05, float(self._ttl) / 3.0)
+ while not self._stop.wait(interval):
+ ids = self.lease_ids
+ started = time.monotonic()
+ try:
+ _renewed, lost = renew_leases(
+ ids, ttl_seconds=self._ttl, store=self._store
+ )
+ except Exception: # noqa: BLE001 - a transient store error is not loss
+ # The rows still have most of their TTL: keep trying, and let
+ # verify()'s local deadline decide when we can no longer claim them.
+ logger.warning("Failed to renew write leases; will retry")
+ self._renewals += 1
+ continue
+ with self._lock:
+ self._alive_until = started + self._lifetime()
+ if lost:
+ with self._lock:
+ for lease_id in lost:
+ if lease_id not in self._lost:
+ self._lost.append(lease_id)
+ logger.error(
+ "Lost %d of %d write leases; the operation must stop",
+ len(lost),
+ len(ids),
+ )
+ self._renewals += 1
+ if self._renewals % GC_EVERY_RENEWALS == 0:
+ # Off this thread: GC must not delay the next renewal.
+ threading.Thread(
+ target=self._gc, name="kb-lease-gc", daemon=True
+ ).start()
+
+ def _gc(self) -> None:
+ try:
+ purge_expired_leases(store=self._store)
+ except Exception: # noqa: BLE001 - GC must never fail a scope
+ logger.exception("Failed to purge expired write leases")
+
+ def verify(self) -> None:
+ """Raise when this scope no longer holds every lease it took.
+
+ Writers call this at their commit points: a lease lost to a stalled
+ process would otherwise let it write while the migration believes the
+ collection is quiet. A set that owns no row (a nested scope reusing the
+ enclosing lease) has no lifetime of its own to exceed.
+ """
+ if self._closed:
+ raise LeaseLostError("This lease scope was released")
+ lost = self.lost
+ if lost:
+ raise LeaseLostError(
+ f"Lost {len(lost)} write lease(s): {', '.join(sorted(lost))}"
+ )
+ if self.lease_ids and time.monotonic() > self._alive_until:
+ # No renewal landed within the TTL: the rows may already be gone.
+ raise LeaseLostError("Write leases were not renewed within their TTL")
+
+ def begin_stop(self) -> None:
+ """Close the set and stop the heartbeat; no join, so callable on a loop."""
+ with self._lock:
+ self._closed = True
+ self._stop.set()
+
+ def stop(self) -> List[str]:
+ """Stop renewing and return the ids; safe to call more than once."""
+ self.begin_stop()
+ thread = self._thread
+ if thread is not None:
+ thread.join(timeout=5.0)
+ return self.lease_ids
+
+ def release(self) -> None:
+ layer = self.stop()
+ with self._lock:
+ self._ids.clear()
+ try:
+ release_leases(layer, store=self._store)
+ except Exception: # noqa: BLE001 - the write already happened
+ logger.exception("Failed to release write leases: %s", sorted(layer))
diff --git a/src/xagent/core/tools/core/RAG_tools/pipelines/document_ingestion.py b/src/xagent/core/tools/core/RAG_tools/pipelines/document_ingestion.py
index e0c9186ea..2568d048a 100644
--- a/src/xagent/core/tools/core/RAG_tools/pipelines/document_ingestion.py
+++ b/src/xagent/core/tools/core/RAG_tools/pipelines/document_ingestion.py
@@ -23,6 +23,7 @@ from ..core.config import (
DEFAULT_TIKTOKEN_ENCODING,
)
from ..core.exceptions import (
+ CollectionMigratingError,
DatabaseOperationError,
DocumentValidationError,
EmbeddingAdapterError,
@@ -48,7 +49,12 @@ from ..management.collection_manager import (
update_collection_stats_sync,
validate_document_processing_sync,
)
-from ..management.migration_state import ensure_collection_writable
+from ..management.migration_state import (
+ ensure_collection_writable,
+ holds_lease,
+ leased_collections,
+ verify_active_leases,
+)
from ..management.status import write_ingestion_status
from ..parse.parse_document import parse_document
from ..progress import ProgressManager, ProgressTracker
@@ -783,6 +789,8 @@ def embed_document_chunks(
try:
if commit_gate is not None:
commit_gate()
+ # A lost lease means a migration may already be switching.
+ verify_active_leases(collection)
write_response = write_vectors_to_db(
collection=collection,
embeddings=embeddings_batch_async,
@@ -798,6 +806,9 @@ def embed_document_chunks(
else EmbeddingWriteResponse.model_validate(write_response)
)
result.current_step = "compute_embeddings"
+ except CollectionMigratingError:
+ # Not a store failure: the writer must stop, untouched.
+ raise
except Exception as exc: # noqa: BLE001
result.embedding_count = total_embedding_count
raise DatabaseOperationError(
@@ -943,6 +954,8 @@ def embed_document_chunks(
try:
if commit_gate is not None:
commit_gate()
+ # A lost lease means a migration may already be switching.
+ verify_active_leases(collection)
write_response = write_vectors_to_db(
collection=collection,
embeddings=embeddings_batch,
@@ -955,6 +968,9 @@ def embed_document_chunks(
else EmbeddingWriteResponse.model_validate(write_response)
)
result.current_step = "compute_embeddings"
+ except CollectionMigratingError:
+ # Not a store failure: the writer must stop, untouched.
+ raise
except Exception as exc: # noqa: BLE001
result.embedding_count = total_embedding_count
raise DatabaseOperationError(
@@ -1214,6 +1230,22 @@ def _process_document_impl(
- Downstream API layers should surface `result.failed_step` and
`result.warnings` to callers for better observability.
"""
+ if not holds_lease(collection):
+ # One lease for the whole ingestion, so a migration that starts after
+ # the admission check sees this writer and waits for it.
+ with leased_collections(collection, operation="document-ingestion"):
+ return process_document(
+ collection,
+ source_path,
+ config=config,
+ progress_manager=progress_manager,
+ user_id=user_id,
+ is_admin=is_admin,
+ file_id=file_id,
+ metadata_source_path=metadata_source_path,
+ commit_gate=commit_gate,
+ )
+
cfg = _apply_spreadsheet_ingestion_safeguards(
coerce_ingestion_config(config),
source_path,
diff --git a/src/xagent/web/api/kb.py b/src/xagent/web/api/kb.py
index 8d587114f..20d78d4c7 100644
--- a/src/xagent/web/api/kb.py
+++ b/src/xagent/web/api/kb.py
@@ -97,7 +97,7 @@ from ...core.tools.core.RAG_tools.management.migration_state import (
admitted_context_async,
ensure_collection_writable,
ensure_collection_writable_async,
- pending_collection,
+ pending_collection_async,
run_in_admitted_context,
)
from ...core.tools.core.RAG_tools.management.status import clear_ingestion_status
@@ -119,6 +119,7 @@ from ...core.tools.core.RAG_tools.utils.string_utils import (
generate_deterministic_doc_id,
)
from ...core.tools.core.RAG_tools.utils.user_scope import user_scope_context
+from ...core.utils.blocking import run_blocking
from ..auth_dependencies import get_current_user
from ..config import (
MAX_COLLECTION_NAME_LENGTH,
@@ -6469,7 +6470,7 @@ async def batch_delete_collections_api(
safe_name, int(effective_user.id), is_admin=False
)
)
- with pending_collection(safe_name):
+ async with pending_collection_async(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)
@@ -7170,7 +7171,9 @@ async def delete_document_api(
logger.error("%s", error_msg)
continue
try:
- delete_result = delete_document(
+ # The delete takes a write lease and does blocking store I/O.
+ delete_result = await run_blocking(
+ delete_document,
safe_collection_name,
resolved_doc_id,
int(_user.id),
diff --git a/tests/core/tools/adapters/vibe/test_kb_creation_tools.py b/tests/core/tools/adapters/vibe/test_kb_creation_tools.py
index 2c03cedfb..61b892ca4 100644
--- a/tests/core/tools/adapters/vibe/test_kb_creation_tools.py
+++ b/tests/core/tools/adapters/vibe/test_kb_creation_tools.py
@@ -31,6 +31,7 @@ from xagent.core.tools.core.RAG_tools.kb.operation_compatibility import (
RollbackStatus,
SideEffectPlane,
)
+from xagent.core.tools.core.RAG_tools.management import write_leases as leases
from xagent.core.tools.core.RAG_tools.pipelines.web_ingestion import (
_blocked_crawl_explanation,
)
@@ -43,6 +44,11 @@ class _FakeMetadataStore:
self.saved_collections: list[CollectionInfo] = []
self.deleted_collections: list[str] = []
+ def get_raw_connection(self) -> object:
+ from xagent.providers.vector_store.lancedb import get_connection_from_env
+
+ return get_connection_from_env()
+
async def save_collection_config(
self,
collection: str,
@@ -1607,3 +1613,199 @@ async def test_create_kb_from_file_admits_once_for_all_files(
assert result["success"] is True
assert result["files_ingested"] == 2
service.publish_collection.assert_awaited_once()
+
+
+async def test_create_kb_from_file_leases_the_collection_while_it_ingests(
+ tmp_path,
+):
+ source_file = tmp_path / "notes.txt"
+ source_file.write_text("hello", encoding="utf-8")
+ record = SimpleNamespace(
+ user_id=7,
+ filename="notes.txt",
+ storage_path=str(source_file),
+ file_id="file-1",
+ )
+ query = MagicMock()
+ query.filter.return_value = query
+ query.all.return_value = [record]
+ db = MagicMock()
+ db.query.return_value = query
+
+ leases_seen = []
+
+ def _ingest(*args, **kwargs):
+ leases_seen.append(leases.live_leases("agent_file_kb"))
+ kwargs["commit_gate"]()
+ return IngestionResult(
+ status="success",
+ doc_id="doc-1",
+ parse_hash="parse-1",
+ chunk_count=1,
+ embedding_count=1,
+ vector_count=1,
+ completed_steps=[_ingestion_step("register_document", doc_id="doc-1")],
+ failed_step=None,
+ message="ok",
+ warnings=[],
+ file_id="file-1",
+ )
+
+ service = MagicMock()
+ service.prepare_collection = AsyncMock(return_value="agent_file_kb")
+ service.publish_collection = AsyncMock()
+ service.collection_exists = AsyncMock(return_value=False)
+ service.cleanup_failed_collection = AsyncMock()
+
+ def fake_get_db():
+ yield from _fake_db_generator(db)
+
+ with (
+ patch("xagent.web.models.database.get_db", side_effect=fake_get_db),
+ patch(
+ "xagent.core.tools.adapters.vibe.agent_kb_service.AgentKnowledgeBaseService",
+ return_value=service,
+ ),
+ patch(
+ "xagent.core.tools.core.RAG_tools.pipelines.document_ingestion.run_document_ingestion",
+ new=Mock(side_effect=_ingest),
+ ),
+ ):
+ tool = CreateKnowledgeBaseFromFileTool(user_id=71, is_admin=False)
+ result = await tool.run_json_async(
+ {"file_ids": ["file-1"], "collection_name": "agent_file_kb"}
+ )
+
+ assert result["success"] is True
+ assert len(leases_seen) == 1
+ assert [lease.operation for lease in leases_seen[0]] == ["agent-file-ingestion"]
+ assert leases.live_leases("agent_file_kb") == []
+
+
[email protected]("lose_on", [1, 2])
+async def test_create_kb_from_file_stops_the_run_when_its_lease_is_lost(
+ tmp_path, lose_on
+):
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ records = []
+ for index in range(2):
+ path = tmp_path / f"notes{index}.txt"
+ path.write_text("hello", encoding="utf-8")
+ records.append(
+ SimpleNamespace(
+ user_id=7,
+ filename=path.name,
+ storage_path=str(path),
+ file_id=f"file-{index}",
+ )
+ )
+ query = MagicMock()
+ query.filter.return_value = query
+ query.all.return_value = records
+ db = MagicMock()
+ db.query.return_value = query
+
+ def _ingest(*args, **kwargs):
+ if lose_on == ingest.call_count:
+ # The pipeline wraps a failed commit gate as an ordinary failed file.
+ migration_state._LEASE_SETS.get()[-1]._lost.append("gone")
+ raise RuntimeError("commit gate refused")
+ return IngestionResult(
+ status="success",
+ doc_id="doc-1",
+ parse_hash="parse-1",
+ chunk_count=1,
+ embedding_count=1,
+ vector_count=1,
+ completed_steps=[_ingestion_step("register_document", doc_id="doc-1")],
+ failed_step=None,
+ message="ok",
+ warnings=[],
+ file_id="file-0",
+ )
+
+ ingest = Mock(side_effect=_ingest)
+ service = MagicMock()
+ service.prepare_collection = AsyncMock(return_value="agent_file_kb")
+ service.publish_collection = AsyncMock()
+ service.collection_exists = AsyncMock(return_value=False)
+ service.cleanup_failed_collection = AsyncMock()
+
+ def fake_get_db():
+ yield from _fake_db_generator(db)
+
+ with (
+ patch("xagent.web.models.database.get_db", side_effect=fake_get_db),
+ patch(
+ "xagent.core.tools.adapters.vibe.agent_kb_service.AgentKnowledgeBaseService",
+ return_value=service,
+ ),
+ patch(
+ "xagent.core.tools.core.RAG_tools.pipelines.document_ingestion.run_document_ingestion",
+ new=ingest,
+ ),
+ ):
+ tool = CreateKnowledgeBaseFromFileTool(user_id=71, is_admin=False)
+ result = await tool.run_json_async(
+ {"file_ids": ["file-0", "file-1"], "collection_name": "agent_file_kb"}
+ )
+
+ assert result["success"] is False
+ assert "upgraded" in result["message"]
+ assert ingest.call_count == lose_on
+ service.publish_collection.assert_not_awaited()
+ service.cleanup_failed_collection.assert_not_awaited()
+ assert leases.live_leases("agent_file_kb") == []
+
+
+async def test_create_kb_from_file_releases_its_lease_when_ingestion_fails(
+ tmp_path,
+):
+ source_file = tmp_path / "notes.txt"
+ source_file.write_text("hello", encoding="utf-8")
+ record = SimpleNamespace(
+ user_id=7,
+ filename="notes.txt",
+ storage_path=str(source_file),
+ file_id="file-1",
+ )
+ query = MagicMock()
+ query.filter.return_value = query
+ query.all.return_value = [record]
+ db = MagicMock()
+ db.query.return_value = query
+
+ def _ingest(*args, **kwargs):
+ raise RuntimeError("ingest exploded")
+
+ service = MagicMock()
+ service.prepare_collection = AsyncMock(return_value="agent_file_kb")
+ service.publish_collection = AsyncMock()
+ service.collection_exists = AsyncMock(return_value=False)
+ service.cleanup_failed_collection = AsyncMock()
+
+ def fake_get_db():
+ yield from _fake_db_generator(db)
+
+ with (
+ patch("xagent.web.models.database.get_db", side_effect=fake_get_db),
+ patch(
+ "xagent.core.tools.adapters.vibe.agent_kb_service.AgentKnowledgeBaseService",
+ return_value=service,
+ ),
+ patch(
+ "xagent.core.tools.core.RAG_tools.pipelines.document_ingestion.run_document_ingestion",
+ new=Mock(side_effect=_ingest),
+ ),
+ ):
+ tool = CreateKnowledgeBaseFromFileTool(user_id=71, is_admin=False)
+ result = await tool.run_json_async(
+ {"file_ids": ["file-1"], "collection_name": "agent_file_kb"}
+ )
+
+ assert result["success"] is False
+ assert leases.live_leases("agent_file_kb") == []
diff --git a/tests/core/tools/core/RAG_tools/management/test_collections.py b/tests/core/tools/core/RAG_tools/management/test_collections.py
index bf60a33dc..249052140 100644
--- a/tests/core/tools/core/RAG_tools/management/test_collections.py
+++ b/tests/core/tools/core/RAG_tools/management/test_collections.py
@@ -1418,3 +1418,27 @@ def test_delete_collection_removes_metadata_table_entry(temp_lancedb_dir: str) -
after_table = conn.open_table("collection_metadata")
after = after_table.search().where(f"name = '{collection}'").to_list()
assert after == []
+
+
+def test_a_lost_lease_stops_the_document_delete_before_the_write() -> None:
+ from xagent.core.tools.core.RAG_tools.core.exceptions import (
+ CollectionMigratingError,
+ )
+
+ vector_store = MagicMock()
+ vector_store.count_rows.return_value = 1
+
+ def _lost(collection: str) -> None:
+ raise CollectionMigratingError("lease lost")
+
+ with (
+ patch.object(
+ collections_module, "get_vector_index_store", return_value=vector_store
+ ),
+ patch.object(collections_module, "verify_active_leases", _lost),
+ patch.object(KBCoordinator, "delete_documents_data_sync") as mock_delete_data,
+ ):
+ with pytest.raises(CollectionMigratingError):
+ delete_document("demo", "doc-1", user_id=7, is_admin=False)
+
+ mock_delete_data.assert_not_called()
diff --git a/tests/core/tools/core/RAG_tools/management/test_write_leases.py b/tests/core/tools/core/RAG_tools/management/test_write_leases.py
new file mode 100644
index 000000000..6fb39bcb8
--- /dev/null
+++ b/tests/core/tools/core/RAG_tools/management/test_write_leases.py
@@ -0,0 +1,1261 @@
+"""Write leases: admitted operations stay visible to a migration across processes."""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from xagent.core.tools.core.RAG_tools.core.exceptions import CollectionMigratingError
+from xagent.core.tools.core.RAG_tools.management import write_leases as leases
+from xagent.core.tools.core.RAG_tools.management.migration_state import (
+ FROZEN,
+ CollectionMigrationState,
+ admitted_async,
+ ensure_collection_writable,
+ ensure_collection_writable_async,
+ pending_collection,
+ write_migration_state,
+)
+from xagent.core.tools.core.RAG_tools.management.write_leases import (
+ DEFAULT_LEASE_TTL_SECONDS,
+ LEASES_TABLE,
+ LeaseSet,
+ acquire_lease,
+ live_leases,
+ purge_expired_leases,
+ release_leases,
+ renew_leases,
+ wait_for_no_leases,
+)
+
+
+def _freeze(name: str = "kb") -> None:
+ write_migration_state(name, CollectionMigrationState(state=FROZEN))
+
+
+def _insert_lease(name: str, lease_id: str, expires_at: datetime) -> None:
+ from xagent.core.tools.core.RAG_tools.LanceDB.schema_manager import (
+ _safe_close_table,
+ )
+ from xagent.core.tools.core.RAG_tools.storage.factory import get_metadata_store
+
+ conn = get_metadata_store().get_raw_connection()
+ leases._ensure_table(conn)
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ table = conn.open_table(LEASES_TABLE)
+ try:
+ table.add(
+ [
+ {
+ "name": name,
+ "lease_id": lease_id,
+ "operation": "old",
+ "owner": "host:1",
+ "created_at": now,
+ "expires_at": expires_at,
+ }
+ ]
+ )
+ finally:
+ _safe_close_table(table)
+
+
+def test_a_lease_is_live_until_it_is_released() -> None:
+ lease_id = acquire_lease("kb", "test")
+
+ live = live_leases("kb")
+ assert [item.lease_id for item in live] == [lease_id]
+ assert live[0].operation == "test"
+
+ assert release_leases([lease_id]) == 1
+ assert live_leases("kb") == []
+
+
+def test_the_default_ttl_is_short_enough_for_a_crashed_writer_to_clear() -> None:
+ assert DEFAULT_LEASE_TTL_SECONDS <= 300
+
+
+def test_expired_leases_are_not_live() -> None:
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ long_gone = timedelta(seconds=leases.EXPIRY_SKEW_MARGIN_SECONDS + 60)
+ _insert_lease("kb", "expired", now - long_gone)
+ _insert_lease("kb", "live", now + timedelta(minutes=5))
+
+ assert [lease.lease_id for lease in live_leases("kb")] == ["live"]
+
+
+def test_renewal_extends_a_lease() -> None:
+ lease_id = acquire_lease("kb", "test", ttl_seconds=60)
+
+ assert renew_leases([lease_id], ttl_seconds=600) == (1, [])
+ assert live_leases("kb")[0].expires_at is not None
+
+
+def test_renewal_never_shortens_a_lease() -> None:
+ lease_id = acquire_lease("kb", "test", ttl_seconds=600)
+ before = live_leases("kb")[0].expires_at
+
+ assert renew_leases([lease_id], ttl_seconds=60) == (1, [])
+
+ assert live_leases("kb")[0].expires_at == before
+
+
+def test_purging_removes_only_expired_rows_of_that_collection() -> None:
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ long_gone = timedelta(seconds=leases.EXPIRY_SKEW_MARGIN_SECONDS + 60)
+ _insert_lease("kb", "expired", now - long_gone)
+ _insert_lease("kb", "live", now + timedelta(minutes=5))
+ _insert_lease("other", "expired-other", now - long_gone)
+
+ assert purge_expired_leases("kb") == 1
+
+ assert [lease.lease_id for lease in live_leases("kb")] == ["live"]
+ assert live_leases("other") == [] # expired, still present, ignored
+
+
+def test_waits_return_what_is_left_at_the_deadline(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ acquire_lease("kb", "test")
+ clock = {"now": 100.0}
+ monkeypatch.setattr(leases.time, "monotonic", lambda: clock["now"])
+ monkeypatch.setattr(
+ leases.time, "sleep", lambda seconds: clock.update(now=clock["now"] + seconds)
+ )
+
+ remaining = wait_for_no_leases("kb", timeout_seconds=2.0, poll_seconds=1.0)
+
+ assert [item.operation for item in remaining] == ["test"]
+
+
+def test_a_waiter_returns_once_the_lease_is_released(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ lease_id = acquire_lease("kb", "test")
+ clock = {"now": 100.0}
+ monkeypatch.setattr(leases.time, "monotonic", lambda: clock["now"])
+
+ def _sleep(seconds: float) -> None:
+ clock["now"] += seconds
+ release_leases([lease_id])
+
+ monkeypatch.setattr(leases.time, "sleep", _sleep)
+
+ assert wait_for_no_leases("kb", timeout_seconds=10.0, poll_seconds=1.0) == []
+
+
+def test_the_guard_writes_the_lease_before_it_reads_the_freeze_state(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state as state
+
+ observed: list = []
+
+ def _read(name: str, store=None):
+ observed.append([lease.lease_id for lease in live_leases(name)])
+ return CollectionMigrationState()
+
+ monkeypatch.setattr(state, "read_migration_state", _read)
+
+ with pending_collection("kb"):
+ ensure_collection_writable("kb")
+
+ assert observed and len(observed[0]) == 1
+
+
+async def test_the_async_guard_writes_the_lease_before_it_reads_the_freeze_state(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state as state
+
+ observed: list = []
+
+ def _read(name: str, store=None):
+ observed.append([lease.lease_id for lease in live_leases(name)])
+ return CollectionMigrationState()
+
+ monkeypatch.setattr(state, "read_migration_state", _read)
+
+ with pending_collection("kb"):
+ await ensure_collection_writable_async("kb")
+
+ assert observed and len(observed[0]) == 1
+
+
+def test_a_frozen_collection_refuses_and_leaves_no_lease() -> None:
+ _freeze("kb")
+
+ with pytest.raises(CollectionMigratingError):
+ with pending_collection("kb"):
+ ensure_collection_writable("kb")
+
+ assert live_leases("kb") == []
+
+
+def test_one_lease_covers_every_guard_call_of_the_operation() -> None:
+ with pending_collection("kb"):
+ ensure_collection_writable("kb")
+ ensure_collection_writable("kb")
+ ensure_collection_writable("kb")
+ assert len(live_leases("kb")) == 1
+
+ assert live_leases("kb") == []
+
+
+def test_a_rename_scope_leases_both_names() -> None:
+ with pending_collection("old", "new"):
+ ensure_collection_writable("old")
+ ensure_collection_writable("new")
+ assert len(live_leases("old")) == 1
+ assert len(live_leases("new")) == 1
+
+ assert live_leases("old") == []
+ assert live_leases("new") == []
+
+
+def test_a_scope_that_raises_releases_its_leases() -> None:
+ with pytest.raises(RuntimeError):
+ with pending_collection("kb"):
+ ensure_collection_writable("kb")
+ raise RuntimeError("boom")
+
+ assert live_leases("kb") == []
+
+
+def test_a_guard_outside_a_pending_scope_takes_no_lease() -> None:
+ ensure_collection_writable("kb")
+
+ assert live_leases("kb") == []
+
+
+async def test_admitted_async_holds_a_lease_until_the_scope_exits() -> None:
+ async with admitted_async("kb"):
+ assert len(live_leases("kb")) == 1
+
+ assert live_leases("kb") == []
+
+
+async def test_admitted_async_takes_the_lease_before_it_reads_the_freeze_state(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state as state
+
+ observed: list = []
+
+ def _read(name: str, store=None):
+ observed.append([lease.lease_id for lease in live_leases(name)])
+ return CollectionMigrationState()
+
+ monkeypatch.setattr(state, "read_migration_state", _read)
+
+ async with admitted_async("kb"):
+ pass
+
+ assert observed and len(observed[0]) == 1
+
+
+def test_a_waiter_clears_expired_rows_it_finds_nothing_live_for() -> None:
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ _insert_lease(
+ "kb", "expired", now - timedelta(seconds=leases.EXPIRY_SKEW_MARGIN_SECONDS + 60)
+ )
+
+ assert wait_for_no_leases("kb", timeout_seconds=0.0) == []
+
+ from xagent.core.tools.core.RAG_tools.LanceDB.schema_manager import (
+ _safe_close_table,
+ )
+ from xagent.core.tools.core.RAG_tools.storage.factory import get_metadata_store
+
+ conn = get_metadata_store().get_raw_connection()
+ table = conn.open_table(LEASES_TABLE)
+ try:
+ assert table.count_rows() == 0
+ finally:
+ _safe_close_table(table)
+
+
+async def test_admitted_async_inside_a_pending_scope_keeps_one_lease() -> None:
+ with pending_collection("kb"):
+ async with admitted_async("kb"):
+ assert len(live_leases("kb")) == 1
+
+ assert live_leases("kb") == []
+
+
+def test_the_heartbeat_extends_a_held_lease(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(leases, "EXPIRY_SKEW_MARGIN_SECONDS", 0.0)
+ held = LeaseSet(ttl_seconds=0.5)
+ try:
+ held.add(acquire_lease("kb", "test", ttl_seconds=0.5))
+ before = live_leases("kb")[0].expires_at
+ deadline = time.monotonic() + 5.0
+ while time.monotonic() < deadline:
+ rows = live_leases("kb")
+ if rows and rows[0].expires_at > before:
+ break
+ time.sleep(0.05)
+ assert live_leases("kb")[0].expires_at > before
+ finally:
+ held.release()
+
+
+def test_the_lease_table_is_compacted_periodically(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ compacted: list = []
+ store = object()
+ monkeypatch.setattr(leases, "_compact", compacted.append)
+ monkeypatch.setattr(leases, "_store_connection", lambda s: _RealConn(s))
+ monkeypatch.setattr(leases, "_acquire_count", leases.COMPACT_EVERY_ACQUIRES - 1)
+
+ acquire_lease("kb", "test", store=store)
+
+ deadline = time.monotonic() + 3.0
+ while not compacted and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert compacted == [store]
+
+
+class _RealConn:
+ """The default store's connection, whatever store the caller passed."""
+
+ def __init__(self, store: Any) -> None:
+ from xagent.core.tools.core.RAG_tools.storage.factory import (
+ get_metadata_store,
+ )
+
+ self._conn = get_metadata_store().get_raw_connection()
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._conn, name)
+
+
+def _optimize_recorder(calls: list) -> Any:
+ class _Table:
+ def optimize(self, **kwargs: Any) -> None:
+ calls.append(kwargs)
+
+ class _Conn:
+ def open_table(self, name: str) -> Any:
+ calls.append(name)
+ return _Table()
+
+ return SimpleNamespace(get_raw_connection=lambda: _Conn())
+
+
+def test_compaction_uses_the_lease_store_and_a_short_retention() -> None:
+ calls: list = []
+
+ leases._compact(_optimize_recorder(calls))
+
+ assert calls == [
+ LEASES_TABLE,
+ {"cleanup_older_than": leases.COMPACT_RETENTION},
+ ]
+ assert leases.COMPACT_RETENTION < timedelta(hours=1)
+
+
+def test_compaction_skips_while_another_one_runs() -> None:
+ calls: list = []
+ assert leases._compact_lock.acquire(blocking=False)
+ try:
+ leases._compact(_optimize_recorder(calls))
+ finally:
+ leases._compact_lock.release()
+
+ assert calls == []
+
+
+def test_a_lease_just_past_expiry_still_counts_as_live() -> None:
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ _insert_lease("kb", "soon", now - timedelta(seconds=1))
+
+ assert [lease.lease_id for lease in live_leases("kb")] == ["soon"]
+
+
+def test_purging_keeps_a_lease_renewed_between_the_read_and_the_delete(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ _insert_lease(
+ "kb", "expired", now - timedelta(seconds=leases.EXPIRY_SKEW_MARGIN_SECONDS + 60)
+ )
+ from xagent.core.tools.core.RAG_tools.storage.factory import get_metadata_store
+
+ conn = get_metadata_store().get_raw_connection()
+ table = conn.open_table(LEASES_TABLE)
+ state = {"renewed": False}
+ original_delete = table.delete
+
+ def _delete(where: str):
+ if not state["renewed"]:
+ state["renewed"] = True
+ # Another host renews its lease before our delete lands.
+ table.update(
+ "lease_id = 'expired'",
+ {"expires_at": now + timedelta(minutes=5)},
+ )
+ return original_delete(where)
+
+ class _Conn:
+ def __getattr__(self, name: str):
+ return getattr(conn, name)
+
+ def open_table(self, name: str):
+ if name == LEASES_TABLE:
+ return _Instrumented(table, _delete)
+ return conn.open_table(name)
+
+ monkeypatch.setattr(leases, "_store_connection", lambda store: _Conn())
+
+ purged = purge_expired_leases("kb")
+
+ assert state["renewed"] is True
+ assert purged == 0
+ assert [lease.lease_id for lease in live_leases("kb")] == ["expired"]
+
+
+class _Instrumented:
+ def __init__(self, table, delete) -> None:
+ self._table = table
+ self._delete = delete
+
+ def __getattr__(self, name: str):
+ return getattr(self._table, name)
+
+ def delete(self, where: str):
+ return self._delete(where)
+
+
+def test_a_scope_reports_a_lease_it_could_not_renew(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(leases, "renew_leases", lambda ids, **kwargs: (0, list(ids)))
+ held = LeaseSet(ttl_seconds=0.2)
+ try:
+ held.add(acquire_lease("kb", "test"))
+ deadline = time.monotonic() + 5.0
+ while not held.lost and time.monotonic() < deadline:
+ time.sleep(0.02)
+ assert held.lost
+ with pytest.raises(leases.LeaseLostError):
+ held.verify()
+ finally:
+ held.release()
+
+
+def test_a_scope_that_keeps_its_leases_verifies_clean() -> None:
+ held = LeaseSet()
+ try:
+ held.add(acquire_lease("kb", "test"))
+ held.verify()
+ finally:
+ held.release()
+
+
+def test_a_lease_insert_conflict_is_retried(monkeypatch: pytest.MonkeyPatch) -> None:
+ from xagent.core.tools.core.RAG_tools.storage.factory import get_metadata_store
+
+ table = get_metadata_store().get_raw_connection()
+ leases._ensure_table(table)
+ real_table = table.open_table(LEASES_TABLE)
+ calls = {"n": 0}
+ original_add = real_table.add
+
+ def _add(rows):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise RuntimeError("CommitConflict")
+ return original_add(rows)
+
+ monkeypatch.setattr(real_table, "add", _add)
+
+ class _Conn:
+ def __getattr__(self, name):
+ return getattr(table, name)
+
+ def open_table(self, name):
+ return real_table
+
+ monkeypatch.setattr(leases, "_store_connection", lambda store: _Conn())
+
+ assert acquire_lease("kb", "test")
+ assert calls["n"] == 2
+
+
+async def test_admitted_async_hands_its_admission_back_to_the_outer_scope() -> None:
+ with pending_collection("kb"):
+ async with admitted_async("kb"):
+ pass
+ _freeze()
+ # The outer scope still owns the admission the inner guard granted.
+ ensure_collection_writable("kb")
+
+ with pytest.raises(CollectionMigratingError):
+ ensure_collection_writable("kb")
+
+
+async def test_holding_leases_covers_the_work_and_never_leaks() -> None:
+ from xagent.core.tools.core.RAG_tools.management.migration_state import (
+ holding_leases,
+ )
+
+ async with holding_leases("kb", "other", operation="collection-delete"):
+ assert {lease.name for lease in live_leases("kb")} == {"kb"}
+ assert len(live_leases("other")) == 1
+
+ assert live_leases("kb") == []
+ assert live_leases("other") == []
+
+
+async def test_holding_leases_releases_on_failure() -> None:
+ from xagent.core.tools.core.RAG_tools.management.migration_state import (
+ holding_leases,
+ )
+
+ with pytest.raises(RuntimeError):
+ async with holding_leases("kb", operation="collection-rename"):
+ raise RuntimeError("rename exploded")
+
+ assert live_leases("kb") == []
+
+
+def test_leased_collections_covers_sync_work_and_never_leaks() -> None:
+ from xagent.core.tools.core.RAG_tools.management.migration_state import (
+ leased_collections,
+ )
+
+ with leased_collections("kb", operation="document-delete"):
+ assert len(live_leases("kb")) == 1
+
+ assert live_leases("kb") == []
+
+
+async def test_a_collection_delete_holds_its_lease_for_the_whole_work(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from unittest.mock import AsyncMock, MagicMock
+
+ from xagent.core.tools.core.RAG_tools.kb.coordinator import KBCoordinator
+ from xagent.core.tools.core.RAG_tools.storage.factory import get_metadata_store
+
+ coordinator = KBCoordinator()
+ store = get_metadata_store()
+
+ async def _context(request):
+ return SimpleNamespace(metadata_store=store)
+
+ seen = []
+ handle = MagicMock()
+ handle.list_collection_documents = MagicMock(
+ side_effect=lambda *args, **kwargs: seen.append(len(live_leases("kb"))) or []
+ )
+ handle.delete_collection_data = MagicMock(return_value={})
+ handle.delete_collection_config = MagicMock()
+
+ monkeypatch.setattr(coordinator, "get_context", _context)
+ monkeypatch.setattr(coordinator, "_ensure_writable", AsyncMock())
+ monkeypatch.setattr(coordinator, "open_collection", AsyncMock(return_value=handle))
+
+ await coordinator.delete_collection("kb", user_id=1, is_admin=True)
+
+ assert seen == [1]
+ assert live_leases("kb") == []
+
+
+async def test_a_collection_rename_leases_both_names(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from unittest.mock import AsyncMock, MagicMock
+
+ from xagent.core.tools.core.RAG_tools.kb.coordinator import KBCoordinator
+ from xagent.core.tools.core.RAG_tools.storage.factory import get_metadata_store
+
+ coordinator = KBCoordinator()
+ store = get_metadata_store()
+
+ async def _context(request):
+ return SimpleNamespace(metadata_store=store)
+
+ during = []
+ handle = MagicMock()
+
+ def _rename_data(*args, **kwargs):
+ during.append((len(live_leases("old")), len(live_leases("new"))))
+ return []
+
+ handle.rename_collection_data = MagicMock(side_effect=_rename_data)
+ handle.rename_collection_status = AsyncMock(return_value=[])
+ handle.rename_collection_metadata = AsyncMock()
+
+ monkeypatch.setattr(coordinator, "get_context", _context)
+ monkeypatch.setattr(coordinator, "_ensure_writable", AsyncMock())
+ monkeypatch.setattr(coordinator, "open_collection", AsyncMock(return_value=handle))
+
+ await coordinator.rename_collection("old", "new", user_id=1, is_admin=False)
+
+ assert during == [(1, 1)]
+ assert live_leases("old") == []
+ assert live_leases("new") == []
+
+
+def test_a_document_delete_holds_its_lease_for_the_whole_work(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from unittest.mock import MagicMock
+
+ from xagent.core.tools.core.RAG_tools.management import collections as manager
+
+ seen = []
+
+ class _Store:
+ def count_rows(self, **kwargs):
+ seen.append(len(live_leases("kb")))
+ return 0
+
+ def __getattr__(self, name):
+ return MagicMock()
+
+ monkeypatch.setattr(manager, "get_vector_index_store", lambda: _Store())
+
+ manager._delete_document_impl("kb", "doc-1", 7, False, coordinator=MagicMock())
+
+ assert seen == [1]
+ assert live_leases("kb") == []
+
+
+async def test_admitted_async_does_not_leave_the_name_admitted() -> None:
+ async with admitted_async("kb"):
+ pass
+
+ _freeze()
+ with pytest.raises(CollectionMigratingError):
+ ensure_collection_writable("kb")
+
+
+def test_the_heartbeat_collects_expired_rows_of_other_collections(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ purged = []
+ monkeypatch.setattr(leases, "renew_leases", lambda ids, **kwargs: (len(ids), []))
+ monkeypatch.setattr(
+ leases, "purge_expired_leases", lambda name=None, **kwargs: purged.append(name)
+ )
+ monkeypatch.setattr(leases, "GC_EVERY_RENEWALS", 1)
+ held = LeaseSet(ttl_seconds=0.2)
+ try:
+ held.add(acquire_lease("kb", "test"))
+ deadline = time.monotonic() + 5.0
+ while not purged and time.monotonic() < deadline:
+ time.sleep(0.02)
+ assert purged == [None]
+ finally:
+ held.release()
+
+
+def test_compaction_does_not_delay_the_admission(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(leases, "_compact", lambda store: time.sleep(1.0))
+ monkeypatch.setattr(leases, "_acquire_count", leases.COMPACT_EVERY_ACQUIRES - 1)
+
+ started = time.monotonic()
+ acquire_lease("kb", "test")
+ elapsed = time.monotonic() - started
+
+ assert elapsed < 0.5
+
+
+def test_renewing_an_expired_lease_reports_it_lost_instead_of_reviving_it(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ _insert_lease("kb", "expired", now - timedelta(seconds=60))
+
+ renewed, lost = renew_leases(["expired"], ttl_seconds=120)
+
+ assert renewed == 0
+ assert lost == ["expired"]
+ rows = live_leases("kb")
+ assert rows == []
+
+
+def test_one_failed_renewal_is_retried_instead_of_losing_the_leases(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls: list = []
+ real_renew = leases.renew_leases
+
+ def _flaky(ids: Any, **kwargs: Any) -> Any:
+ calls.append(len(ids))
+ if len(calls) == 1:
+ raise OSError("commit conflict")
+ return real_renew(ids, **kwargs)
+
+ monkeypatch.setattr(leases, "renew_leases", _flaky)
+ held = LeaseSet(ttl_seconds=0.6)
+ try:
+ held.add(acquire_lease("kb", "test"))
+ deadline = time.monotonic() + 5.0
+ while len(calls) < 3 and time.monotonic() < deadline:
+ time.sleep(0.02)
+ assert len(calls) >= 3
+ assert held.lost == []
+ held.verify()
+ finally:
+ held.release()
+
+
+def test_renewals_failing_past_the_ttl_fail_the_check(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ leases,
+ "renew_leases",
+ lambda ids, **kwargs: (_ for _ in ()).throw(OSError("gone")),
+ )
+ held = LeaseSet(ttl_seconds=0.2)
+ try:
+ held.add(acquire_lease("kb", "test"))
+ time.sleep(0.4)
+ assert held.lost == []
+ with pytest.raises(leases.LeaseLostError):
+ held.verify()
+ finally:
+ held.release()
+
+
+def test_a_stalled_heartbeat_fails_the_check_at_the_local_deadline() -> None:
+ held = LeaseSet(ttl_seconds=120)
+ try:
+ held.add(acquire_lease("kb", "test"))
+ held.verify()
+ held._alive_until = time.monotonic() - 1
+ with pytest.raises(leases.LeaseLostError):
+ held.verify()
+ finally:
+ held.release()
+
+
+def test_a_set_that_owns_no_lease_passes_however_long_it_opens() -> None:
+ held = LeaseSet(ttl_seconds=0.2)
+ try:
+ held._alive_until = time.monotonic() - 1
+ held.verify()
+ # Its own lifetime starts with the first row it owns.
+ held.add(acquire_lease("kb", "test"))
+ assert held._alive_until > time.monotonic()
+ held.verify()
+ finally:
+ held.release()
+
+
+def test_a_nested_scope_that_reuses_the_lease_keeps_passing_after_its_ttl() -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ with migration_state.leased_collections("kb", operation="outer"):
+ with migration_state.leased_collections("kb", operation="inner") as inner:
+ inner._alive_until = time.monotonic() - 1
+ migration_state.verify_active_leases("kb")
+
+
+def test_a_second_cancel_still_stops_the_heartbeat_and_releases(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ real = migration_state.acquire_lease_async
+
+ async def _slow(name: str, operation: str, **kwargs: Any) -> str:
+ await asyncio.sleep(0.2)
+ return await real(name, operation, **kwargs)
+
+ monkeypatch.setattr(migration_state, "acquire_lease_async", _slow)
+
+ async def _run() -> None:
+ async def _hold() -> None:
+ async with migration_state.holding_leases("kb", operation="test"):
+ pytest.fail("cancelled before admission") # pragma: no cover
+
+ task = asyncio.create_task(_hold())
+ await asyncio.sleep(0.05)
+ task.cancel()
+ await asyncio.sleep(0)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ asyncio.run(_run())
+ deadline = time.monotonic() + 5.0
+ while live_leases("kb") and time.monotonic() < deadline:
+ time.sleep(0.02)
+ assert live_leases("kb") == []
+
+
+def test_a_cancelled_scope_stops_its_heartbeat_before_any_await(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ async def _slow_blocking(fn: Any, *args: Any, **kwargs: Any) -> Any:
+ await asyncio.sleep(0.5)
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(migration_state, "run_blocking", _slow_blocking)
+ opened: list = []
+
+ async def _run() -> None:
+ async def _hold() -> None:
+ async with migration_state._lease_scope_async() as lease_set:
+ opened.append(lease_set)
+ await asyncio.sleep(10)
+
+ task = asyncio.create_task(_hold())
+ await asyncio.sleep(0)
+ task.cancel()
+ # A second cancel lands while the cleanup is still joining.
+ await asyncio.sleep(0.05)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert opened[-1]._stop.is_set()
+
+ asyncio.run(_run())
+
+
+def test_a_cancelled_acquire_releases_in_its_own_store(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ seen: list = []
+ marker = object()
+
+ async def _release(ids: Any, store: Any = None) -> None:
+ seen.append((list(ids), store))
+
+ monkeypatch.setattr(migration_state, "release_leases_async", _release)
+
+ async def _run() -> None:
+ task: asyncio.Future = asyncio.get_running_loop().create_future()
+ task.set_result("lease-id")
+ migration_state._release_after_cancel(task, store=marker)
+ await asyncio.sleep(0.05)
+
+ asyncio.run(_run())
+
+ assert seen == [(["lease-id"], marker)]
+
+
+def test_the_release_tasks_are_kept_alive_until_they_run() -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ async def _run() -> None:
+ task = migration_state._release_tracked(["not-a-lease"], None)
+ assert task in migration_state._RELEASE_TASKS
+ await task
+
+ asyncio.run(_run())
+ assert migration_state._RELEASE_TASKS == set()
+
+
+def test_releases_use_the_store_the_lease_was_taken_in(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ seen: list = []
+
+ async def _spy(name: str, operation: str, **kwargs: Any) -> str:
+ seen.append(kwargs.get("store"))
+ return "lease-id"
+
+ released: list = []
+
+ async def _release(ids: Any, **kwargs: Any) -> None:
+ released.append(kwargs.get("store"))
+
+ monkeypatch.setattr(migration_state, "acquire_lease_async", _spy)
+ monkeypatch.setattr(migration_state, "release_leases_async", _release)
+ marker = object()
+
+ async def _run() -> None:
+ async with migration_state.holding_leases("kb", operation="test", store=marker):
+ pass
+
+ asyncio.run(_run())
+
+ assert seen == [marker]
+ assert released == [marker]
+
+
+def test_a_released_set_fails_its_check_and_takes_no_more_leases() -> None:
+ held = LeaseSet(ttl_seconds=120)
+ held.add(acquire_lease("kb", "test"))
+ held.verify()
+ held.release()
+
+ with pytest.raises(leases.LeaseLostError):
+ held.verify()
+ with pytest.raises(leases.LeaseLostError):
+ held.add("late")
+
+
+def test_work_outliving_its_scope_cannot_pass_the_commit_gate() -> None:
+ from contextvars import copy_context
+
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ with pending_collection("kb"):
+ ensure_collection_writable("kb")
+ leftover = copy_context()
+
+ with pytest.raises(CollectionMigratingError):
+ leftover.run(migration_state.verify_active_leases, "kb")
+
+
+def test_one_failed_release_still_releases_the_other_leases(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ids = [acquire_lease(name, "rename") for name in ("a", "b", "c")]
+
+ class _Flaky:
+ def __init__(self, table: Any) -> None:
+ self._table = table
+
+ def delete(self, where: str) -> Any:
+ if ids[0] in where:
+ raise OSError("commit conflict")
+ return self._table.delete(where)
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._table, name)
+
+ real = leases._store_connection
+
+ class _Conn:
+ def __init__(self, conn: Any) -> None:
+ self._conn = conn
+
+ def open_table(self, name: str) -> Any:
+ return _Flaky(self._conn.open_table(name))
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._conn, name)
+
+ monkeypatch.setattr(leases, "_store_connection", lambda s: _Conn(real(s)))
+
+ assert release_leases(ids) == 2
+ assert live_leases("b") == [] and live_leases("c") == []
+ assert [lease.lease_id for lease in live_leases("a")] == [ids[0]]
+
+
+def test_a_renewal_does_not_revive_a_row_that_expired_after_the_read(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ lease_id = acquire_lease("kb", "test")
+ _expire_lease("kb", lease_id, -1)
+ real = leases._store_connection
+
+ class _Racing:
+ def __init__(self, table: Any) -> None:
+ self._table = table
+
+ def update(self, where: str, values: Any) -> Any:
+ # The row expires between the renewal's read and its write.
+ _expire_lease("kb", lease_id, 30)
+ return self._table.update(where, values)
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._table, name)
+
+ class _Conn:
+ def __init__(self, conn: Any) -> None:
+ self._conn = conn
+
+ def open_table(self, name: str) -> Any:
+ return _Racing(self._conn.open_table(name))
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._conn, name)
+
+ monkeypatch.setattr(leases, "_store_connection", lambda s: _Conn(real(s)))
+
+ assert renew_leases([lease_id]) == (0, [lease_id])
+ monkeypatch.setattr(leases, "_store_connection", real)
+ assert live_leases("kb") == [] or live_leases("kb")[0].expires_at < datetime.now(
+ timezone.utc
+ ).replace(tzinfo=None)
+
+
+def test_a_cancelled_acquire_releases_the_row_it_inserted(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ real = migration_state.acquire_lease_async
+
+ async def _slow(name: str, operation: str, **kwargs: Any) -> str:
+ await asyncio.sleep(0.2)
+ return await real(name, operation, **kwargs)
+
+ monkeypatch.setattr(migration_state, "acquire_lease_async", _slow)
+
+ async def _run() -> None:
+ async def _hold() -> None:
+ async with migration_state.holding_leases("kb", operation="test"):
+ pytest.fail("cancelled before admission") # pragma: no cover
+
+ task = asyncio.create_task(_hold())
+ await asyncio.sleep(0.05)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ deadline = time.monotonic() + 5.0
+ while time.monotonic() < deadline:
+ await asyncio.sleep(0.05)
+ if live_leases("kb") == [] and len(_inserted) > 0:
+ break
+
+ _inserted: list = []
+ monkeypatch.setattr(
+ migration_state,
+ "release_leases_async",
+ _tracking_release(migration_state.release_leases_async, _inserted),
+ )
+ asyncio.run(_run())
+
+ assert _inserted
+ assert live_leases("kb") == []
+
+
+def _tracking_release(real: Any, seen: list) -> Any:
+ async def _release(ids: Any, **kwargs: Any) -> Any:
+ ids = list(ids)
+ seen.extend(ids)
+ return await real(ids, **kwargs)
+
+ return _release
+
+
+def test_a_lost_handler_lease_stops_a_nested_holding_leases_scope() -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ async def _run() -> None:
+ async with migration_state.pending_collection_async("kb"):
+ await migration_state.ensure_collection_writable_async("kb")
+ async with migration_state.holding_leases("kb", operation="delete"):
+ migration_state._LEASE_SETS.get()[0]._lost.append("gone")
+ with pytest.raises(CollectionMigratingError):
+ migration_state.verify_active_leases("kb")
+
+ asyncio.run(_run())
+
+
+def test_a_lease_slightly_past_expiry_still_counts_as_held(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ _insert_lease("kb", "just-expired", now - timedelta(seconds=1))
+
+ assert [lease.lease_id for lease in live_leases("kb")] == ["just-expired"]
+
+
+def _mark_current_scope_lost() -> str:
+ """Exactly the state a lost lease leaves: the set records the id."""
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ lease_set = migration_state._LEASE_SETS.get()[-1]
+ lease_id = migration_state._LEASES.get()[-1][1]
+ lease_set._lost.append(lease_id)
+ return lease_id
+
+
[email protected]("scenario", ["delete", "rename", "document-delete"])
+def test_a_lost_outer_lease_stops_a_nested_lease_scope(scenario: str) -> None:
+ from xagent.core.tools.core.RAG_tools.core.exceptions import (
+ CollectionMigratingError,
+ )
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ with pending_collection("kb"):
+ ensure_collection_writable("kb")
+ _mark_current_scope_lost()
+
+ with pytest.raises(CollectionMigratingError):
+ with migration_state.leased_collections("kb", operation=scenario):
+ pytest.fail("a nested scope must not start") # pragma: no cover
+
+ async def _nested() -> None:
+ async with migration_state.holding_leases("kb", operation=scenario):
+ pytest.fail("a nested scope must not start") # pragma: no cover
+
+ with pytest.raises(CollectionMigratingError):
+ asyncio.run(_nested())
+
+
+def test_a_nested_scope_reuses_the_lease_instead_of_taking_a_second_one() -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ with pending_collection("kb"):
+ ensure_collection_writable("kb")
+ outer = {name: lease_id for name, lease_id in migration_state._LEASES.get()}
+
+ with migration_state.leased_collections("kb", operation="inner"):
+ inner = {name: lease_id for name, lease_id in migration_state._LEASES.get()}
+
+ assert outer["kb"] == inner["kb"]
+
+
+def test_verify_active_leases_checks_every_enclosing_scope() -> None:
+ from xagent.core.tools.core.RAG_tools.core.exceptions import (
+ CollectionMigratingError,
+ )
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ with migration_state.leased_collections("kb", operation="outer") as outer:
+ with migration_state.leased_collections("other", operation="inner"):
+ outer._lost.append("lost-id")
+ with pytest.raises(CollectionMigratingError):
+ migration_state.verify_active_leases("other")
+
+
+def test_a_lost_lease_fails_the_active_scope_check() -> None:
+ from xagent.core.tools.core.RAG_tools.core.exceptions import (
+ CollectionMigratingError,
+ )
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ with migration_state.leased_collections("kb", operation="test"):
+ _mark_current_scope_lost()
+ with pytest.raises(CollectionMigratingError):
+ migration_state.verify_active_leases("kb")
+
+
+def test_a_lease_that_cannot_be_inserted_stops_the_operation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ def _explode(*args: Any, **kwargs: Any) -> str:
+ raise RuntimeError("lease table unavailable")
+
+ monkeypatch.setattr(migration_state, "acquire_lease", _explode)
+ with pytest.raises(RuntimeError, match="lease table unavailable"):
+ with migration_state.leased_collections("kb", operation="test"):
+ pytest.fail("must not run without its lease") # pragma: no cover
+
+
+def test_pending_collection_async_releases_its_lease() -> None:
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ async def _run() -> None:
+ async with migration_state.pending_collection_async("kb"):
+ await migration_state.ensure_collection_writable_async("kb")
+ assert migration_state.holds_lease("kb")
+ assert live_leases("kb") == []
+
+ asyncio.run(_run())
+
+
+def test_a_scope_whose_lease_was_lost_fails_its_check() -> None:
+ from xagent.core.tools.core.RAG_tools.core.exceptions import (
+ CollectionMigratingError,
+ )
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
+ held = LeaseSet(ttl_seconds=0.2)
+ # A row that does not exist: the first renewal finds it gone.
+ held.add("not-a-real-lease")
+ set_token = migration_state._LEASE_SETS.set((held,))
+ leases_token = migration_state._LEASES.set((("kb", "not-a-real-lease"),))
+ try:
+ deadline = time.monotonic() + 5.0
+ while not held.lost and time.monotonic() < deadline:
+ time.sleep(0.02)
+ with pytest.raises(CollectionMigratingError):
+ migration_state.verify_active_leases("kb")
+ finally:
+ migration_state._LEASES.reset(leases_token)
+ migration_state._LEASE_SETS.reset(set_token)
+ held.release()
+
+
+def _expire_lease(name: str, lease_id: str, seconds_ago: float) -> None:
+ """Move an existing lease's expiry into the past."""
+ from xagent.core.tools.core.RAG_tools.storage.factory import get_metadata_store
+
+ conn = get_metadata_store().get_raw_connection()
+ table = conn.open_table(LEASES_TABLE)
+ edge = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(
+ seconds=seconds_ago
+ )
+ table.update(f"lease_id = '{lease_id}'", {"expires_at": edge})
+
+
+# --- real LanceDB: the lease table must work through the store's own API ---
+
+
+def test_lease_lifecycle_on_a_real_table() -> None:
+ lease_id = acquire_lease("kb", "document-ingestion")
+
+ live = live_leases("kb")
+ assert [lease.lease_id for lease in live] == [lease_id]
+ assert live[0].operation == "document-ingestion"
+
+ renewed, lost = renew_leases([lease_id])
+ assert (renewed, lost) == (1, [])
+ assert live_leases("kb")[0].expires_at > live[0].expires_at
+
+ assert release_leases([lease_id]) == 1
+ assert live_leases("kb") == []
+ assert renew_leases([lease_id]) == (0, [lease_id])
+
+
+def test_renewing_an_expired_row_counts_it_lost_on_a_real_table() -> None:
+ lease_id = acquire_lease("kb", "document-ingestion")
+ _expire_lease("kb", lease_id, 30)
+
+ assert renew_leases([lease_id]) == (0, [lease_id])
+ assert renew_leases([lease_id]) == (0, [lease_id])
+
+
+def test_a_lease_a_margin_past_its_expiry_still_reads_as_live() -> None:
+ lease_id = acquire_lease("kb", "document-ingestion")
+ _expire_lease("kb", lease_id, 1)
+
+ assert [lease.lease_id for lease in live_leases("kb")] == [lease_id]
+
+
+def test_purge_removes_only_expired_leases_on_a_real_table() -> None:
+ alive = acquire_lease("kb", "document-ingestion")
+ stale = acquire_lease("other", "document-ingestion")
+ _expire_lease("other", stale, 300)
+
+ assert purge_expired_leases() == 1
+ assert [lease.lease_id for lease in live_leases("kb")] == [alive]
+ assert live_leases("other") == []
+
+
+def test_the_lease_set_notices_a_real_lost_row() -> None:
+ lease_set = LeaseSet(ttl_seconds=0.05)
+ lease_id = acquire_lease("kb", "write-guard")
+ lease_set.add(lease_id)
+ release_leases([lease_id])
+
+ deadline = time.monotonic() + 2.0
+ while time.monotonic() < deadline and not lease_set.lost:
+ time.sleep(0.02)
+ lease_set.stop()
+
+ assert lease_set.lost == [lease_id]
+ with pytest.raises(leases.LeaseLostError):
+ lease_set.verify()
diff --git a/tests/core/tools/core/RAG_tools/pipelines/test_embed_document.py b/tests/core/tools/core/RAG_tools/pipelines/test_embed_document.py
index c49741873..9850fc787 100644
--- a/tests/core/tools/core/RAG_tools/pipelines/test_embed_document.py
+++ b/tests/core/tools/core/RAG_tools/pipelines/test_embed_document.py
@@ -473,3 +473,27 @@ def test_embed_document_chunks_forces_async_path_for_spreadsheets(
assert all(isinstance(call, str) for call in adapter.calls)
assert result.embedding_count == 2
assert result.vector_count == 2
+
+
[email protected]("use_async", [False, True])
+def test_a_lost_lease_stops_the_write_at_the_commit_point(
+ monkeypatch: pytest.MonkeyPatch, use_async: bool
+) -> None:
+ """Both embedding branches check the lease right before they write."""
+ from xagent.core.tools.core.RAG_tools.core.exceptions import (
+ CollectionMigratingError,
+ )
+
+ adapter = _StubAdapter()
+ events: List[tuple] = []
+ _install(monkeypatch, lambda **_: _read_response(_chunks(1, start=3)), events)
+
+ def _lost(collection: str) -> None:
+ raise CollectionMigratingError("lease lost")
+
+ monkeypatch.setattr(document_ingestion, "verify_active_leases", _lost)
+
+ with pytest.raises(CollectionMigratingError):
+ _embed(adapter, _cfg(use_async=use_async, batch_size=10))
+
+ assert events == []
diff --git a/tests/web/test_background_jobs.py b/tests/web/test_background_jobs.py
index ef40d4d6e..e074af13c 100644
--- a/tests/web/test_background_jobs.py
+++ b/tests/web/test_background_jobs.py
@@ -2530,9 +2530,6 @@ def test_deferred_job_survives_a_failed_reschedule(tmp_path, monkeypatch):
def test_admission_clears_the_migration_anchor_so_a_later_freeze_waits(
tmp_path, monkeypatch
):
- from xagent.core.tools.core.RAG_tools.core.exceptions import (
- CollectionMigratingError,
- )
from xagent.web.jobs.exceptions import BackgroundJobDeferred
from xagent.web.jobs.kb_tasks import (
_MIGRATION_DEFERRED_AT_KEY,
@@ -2541,13 +2538,16 @@ def test_admission_clears_the_migration_anchor_so_a_later_freeze_waits(
monkeypatch.setenv(CELERY_ENABLED, "false")
monkeypatch.delenv(CELERY_BROKER_URL, raising=False)
+ from xagent.core.tools.core.RAG_tools.management import migration_state
+
frozen = {"on": True}
- def guard(_collection: str) -> None:
- if frozen["on"]:
- raise CollectionMigratingError("Knowledge base is being upgraded")
+ def read_state(*_args: object) -> migration_state.CollectionMigrationState:
+ state = migration_state.FROZEN if frozen["on"] else migration_state.IDLE
+ return migration_state.CollectionMigrationState(state=state)
- monkeypatch.setattr("xagent.web.jobs.kb_tasks.ensure_collection_writable", guard)
+ # The real guard runs, so the admitted job holds its write lease.
+ monkeypatch.setattr(migration_state, "read_migration_state", read_state)
monkeypatch.setattr(
"xagent.web.jobs.kb_tasks._save_job_collection_config_after_ingest",
lambda *args, **kwargs: None,
diff --git a/tests/web/test_blocking_call_inventory.py b/tests/web/test_blocking_call_inventory.py
index ed9e17106..68c466f73 100644
--- a/tests/web/test_blocking_call_inventory.py
+++ b/tests/web/test_blocking_call_inventory.py
@@ -242,10 +242,21 @@ ALLOWED: dict[str, tuple[int, str]] = {
"immediately in the sync-to-async bridge.",
),
"core/tools/core/RAG_tools/management/collections.py": (2, READ),
+ "core/tools/core/RAG_tools/management/write_leases.py": (
+ 3,
+ "Three daemon helpers: the heartbeat that renews the operation's own "
+ "lease rows while its scope runs (stopped and joined before release, "
+ "and the async decorators release it off the event loop), plus the "
+ "fire-and-forget compaction and expired-row GC of the lease table, "
+ "neither of which writes application data. All belong to the "
+ "HTTP-route and execution classes retire_writers lists under "
+ "'Not covered'.",
+ ),
"core/tools/core/RAG_tools/management/migration_state.py": (
1,
"The freeze guard reads one state row (and opens the metadata "
- "connection to read it); it writes no row.",
+ "connection to read it). Lease writes go off the loop through "
+ "run_blocking, and a scope releases on its own exit.",
),
"core/tools/core/RAG_tools/pipelines/document_ingestion.py": (
2,