Enterprise agent platform for building, deploying, and operating AI teammates.
feat(rag): switch a frozen collection's embedding model safely (#3755)
蓝鱼bluefishb6a659a1b29c
diff --git a/src/xagent/core/tools/core/RAG_tools/core/exceptions.py b/src/xagent/core/tools/core/RAG_tools/core/exceptions.pyindex ed2f23d45..1ab28b21c 100644--- a/src/xagent/core/tools/core/RAG_tools/core/exceptions.py+++ b/src/xagent/core/tools/core/RAG_tools/core/exceptions.py@@ -148,3 +148,9 @@ class CollectionMigratingError(RagCoreException):"""Raised when a write targets a collection frozen for embedding migration."""pass+++class CollectionNotFrozenError(RagCoreException):+ """Raised when an embedding switch targets a collection that is not frozen."""++ passdiff --git a/src/xagent/core/tools/core/RAG_tools/kb/api_compatibility.py b/src/xagent/core/tools/core/RAG_tools/kb/api_compatibility.pyindex 75121e66c..2003a65c2 100644--- a/src/xagent/core/tools/core/RAG_tools/kb/api_compatibility.py+++ b/src/xagent/core/tools/core/RAG_tools/kb/api_compatibility.py@@ -620,39 +620,41 @@ class KBApiCompatibilityFacade:collection: str,store: Any,) -> CollectionInfo | None:- if not _has_store_method(store, "save_collection"):+ if not _has_store_method(store, "save_collection_if_absent"):return Nonecollection_info: CollectionInfo | None = None+ row_existed = Falseif _has_store_method(store, "get_collection"):try:loaded = store.get_collection(collection)loaded = await maybe_await(loaded)except ValueError:collection_info = CollectionInfo(name=collection)+ row_existed = Falseelse:if isinstance(loaded, CollectionInfo):collection_info = loaded+ row_existed = Trueelif loaded is None:collection_info = CollectionInfo(name=collection)+ row_existed = Falseelse:collection_info = CollectionInfo(name=collection)+ row_existed = Falseif collection_info is None:return None- extra_metadata = dict(collection_info.extra_metadata or {})- if extra_metadata.get(KB_STORAGE_METADATA_KEY) is not None:- return collection_info+ from ..management.collection_manager import merge_collection_extra_metadata- extra_metadata[KB_STORAGE_METADATA_KEY] = {- "backend": deployment_kb_backend().value- }- updated_collection = collection_info.model_copy(- update={"extra_metadata": extra_metadata}+ return await merge_collection_extra_metadata(+ store,+ collection_info,+ KB_STORAGE_METADATA_KEY,+ {"backend": deployment_kb_backend().value},+ row_existed=row_existed,)- await maybe_await(store.save_collection(updated_collection))- return updated_collectionasync def get_collection_config(self,diff --git a/src/xagent/core/tools/core/RAG_tools/kb/pipeline_compatibility.py b/src/xagent/core/tools/core/RAG_tools/kb/pipeline_compatibility.pyindex 9046b5250..fbe168ffd 100644--- a/src/xagent/core/tools/core/RAG_tools/kb/pipeline_compatibility.py+++ b/src/xagent/core/tools/core/RAG_tools/kb/pipeline_compatibility.py@@ -167,14 +167,15 @@ class KBPipelineCompatibilityFacade:if extra_metadata.get(KB_STORAGE_METADATA_KEY) is not None:return collection_info- extra_metadata[KB_STORAGE_METADATA_KEY] = {- "backend": deployment_kb_backend().value- }- updated_collection = collection_info.model_copy(- update={"extra_metadata": extra_metadata}+ from ..management.collection_manager import merge_collection_extra_metadata++ return await merge_collection_extra_metadata(+ metadata_store,+ collection_info,+ KB_STORAGE_METADATA_KEY,+ {"backend": deployment_kb_backend().value},+ row_existed=True,)- await metadata_store.save_collection(updated_collection)- return updated_collectiondef ensure_collection_backend_binding(self, collection: strdiff --git a/src/xagent/core/tools/core/RAG_tools/kb/tool_compatibility.py b/src/xagent/core/tools/core/RAG_tools/kb/tool_compatibility.pyindex 9ce67c13b..682bca6c0 100644--- a/src/xagent/core/tools/core/RAG_tools/kb/tool_compatibility.py+++ b/src/xagent/core/tools/core/RAG_tools/kb/tool_compatibility.py@@ -317,20 +317,21 @@ class KBToolCompatibilityFacade:with self._storage_context():metadata_store = get_metadata_store()+ row_existed = Truetry:collection_info = await metadata_store.get_collection(collection)except ValueError:collection_info = CollectionInfo(name=collection)+ row_existed = False- extra_metadata = dict(collection_info.extra_metadata or {})- if extra_metadata.get(KB_STORAGE_METADATA_KEY) is not None:- return collection_info+ from ..management.collection_manager import (+ merge_collection_extra_metadata,+ )- extra_metadata[KB_STORAGE_METADATA_KEY] = {- "backend": deployment_kb_backend().value- }- updated_collection = collection_info.model_copy(- update={"extra_metadata": extra_metadata}+ return await merge_collection_extra_metadata(+ metadata_store,+ collection_info,+ KB_STORAGE_METADATA_KEY,+ {"backend": deployment_kb_backend().value},+ row_existed=row_existed,)- await metadata_store.save_collection(updated_collection)- return updated_collectiondiff --git a/src/xagent/core/tools/core/RAG_tools/management/collection_manager.py b/src/xagent/core/tools/core/RAG_tools/management/collection_manager.pyindex 26045148c..99f48156a 100644--- a/src/xagent/core/tools/core/RAG_tools/management/collection_manager.py+++ b/src/xagent/core/tools/core/RAG_tools/management/collection_manager.py@@ -24,6 +24,7 @@ from typing import (import pyarrow as pa # type: ignore+from ..core.exceptions import CollectionNotFrozenErrorfrom ..core.parser_registry import get_supported_parsers, validate_parser_compatibilityfrom ..core.schemas import CollectionInfofrom ..LanceDB.schema_manager import _safe_close_table@@ -33,6 +34,7 @@ from ..utils.lancedb_query_utils import list_table_namesfrom ..utils.model_resolution_pin import pinned_resolutionfrom ..utils.model_resolver import resolve_embedding_adapterfrom ..utils.tag_mapping import register_tag_mapping+from .migration_state import FROZEN, read_migration_stateif TYPE_CHECKING:from ..kb import (@@ -44,6 +46,8 @@ if TYPE_CHECKING:T = TypeVar("T")+WRITE_MAX_RETRIES = 3+logger = logging.getLogger(__name__)# In-memory locks for collection operations to prevent concurrent initialization conflicts.@@ -110,6 +114,20 @@ def _normalize_collection_config_user_id(user_id: Optional[int]) -> int:return 0 if user_id is None else int(user_id)+# Columns the stats paths own. Binding columns are deliberately absent: they are+# written only through the guarded binding paths or first-time initialization.+_STATS_FIELDS = (+ "documents",+ "processed_documents",+ "parses",+ "chunks",+ "embeddings",+ "last_accessed_at",+)+_COUNT_FIELDS = _STATS_FIELDS[:-1]+_BINDING_FIELDS = ("embedding_model_id", "embedding_dimension")++def _normalize_model_id(model_id: Optional[str]) -> Optional[str]:if not isinstance(model_id, str):return None@@ -270,6 +288,41 @@ def _get_collection_lock(collection_name: str) -> asyncio.Lock:return _collection_locks[lock_key]+def _is_deterministic_write_error(exc: Exception) -> bool:+ """Errors a retry cannot fix: missing row, malformed call, unknown column."""+ return isinstance(exc, ValueError) and any(+ marker in str(exc)+ for marker in ("not found", "not both", "Cannot update collection_metadata")+ )+++async def _with_retry(+ operation: Callable[[], Awaitable[T]],+ *,+ description: str,+ deterministic: Optional[Callable[[Exception], bool]] = None,+) -> T:+ """Run ``operation``, backing off unless ``deterministic`` calls the error final."""+ for attempt in range(WRITE_MAX_RETRIES):+ try:+ return await operation()+ except Exception as exc:+ final = deterministic(exc) if deterministic else False+ if final or attempt == WRITE_MAX_RETRIES - 1:+ logger.error(+ "Failed to run %s after %s attempts: %s",+ description,+ attempt + 1,+ exc,+ )+ raise+ logger.warning(+ "Attempt %s of %s failed, retrying: %s", attempt + 1, description, exc+ )+ await asyncio.sleep(0.1 * (2**attempt))+ raise AssertionError("unreachable")++class CollectionManager:"""Manager for collection metadata operations with LanceDB storage.@@ -317,10 +370,10 @@ class CollectionManager:"""Save collection metadata to storage with retry mechanism.Takes the cross-thread guard as well as the asyncio lock: this does a- full-row overwrite and is reachable from the concurrent ingestion hot- path (the legacy-migration branch of resolve_effective_embedding_model_sync),- so without it a stale-read overwrite could clobber a concurrent- stats/embedding-init write on the same collection.+ full-row overwrite, so without the lock a stale-read overwrite could+ clobber a concurrent stats or binding write on the same collection.+ Callers that only mean to create a row must use+ ``save_collection_if_absent`` instead.Args:collection: CollectionInfo to save@@ -330,6 +383,130 @@ class CollectionManager:async with lock, _collection_thread_guard(collection.name):await self._save_collection_with_retry(collection)+ async def save_collection_if_absent(self, collection: CollectionInfo) -> bool:+ """Create the row only if no row with that name exists; never overwrites."""+ lock = _get_collection_lock(collection.name)++ async with lock, _collection_thread_guard(collection.name):+ return await self._save_collection_if_absent_with_retry(collection)++ async def _save_collection_if_absent_with_retry(+ self, collection: CollectionInfo+ ) -> bool:+ return await _with_retry(+ lambda: self._get_metadata_store().save_collection_if_absent(collection),+ description=f"creation of collection {collection.name}",+ )++ async def update_collection_fields(+ self,+ collection: CollectionInfo,+ field_names: tuple[str, ...],+ *,+ require_uninitialized: bool = False,+ expected_model_id: Optional[str] = None,+ store: Optional[MetadataStore] = None,+ recreate_missing: bool = False,+ ) -> bool:+ """Write only ``field_names`` of an existing row, under the collection locks.++ ``store`` targets a store other than the factory's (duck-typed facades+ pass their own). ``recreate_missing`` re-inserts a row that disappeared+ between the caller's read and this write instead of raising.+ """+ lock = _get_collection_lock(collection.name)++ async with lock, _collection_thread_guard(collection.name):+ return await self._update_fields_with_retry(+ collection,+ field_names,+ require_uninitialized=require_uninitialized,+ expected_model_id=expected_model_id,+ store=store,+ recreate_missing=recreate_missing,+ )++ async def _update_fields_with_retry(+ self,+ collection: CollectionInfo,+ field_names: tuple[str, ...],+ *,+ require_uninitialized: bool = False,+ expected_model_id: Optional[str] = None,+ store: Optional[MetadataStore] = None,+ recreate_missing: bool = False,+ ) -> bool:+ """Partial write with the same commit-conflict retry as ``save_collection``.++ A retried compare-and-set re-evaluates its guard, so a concurrent switch+ still wins and the call returns ``False``. A missing row is re-raised+ immediately (search/ingestion resolve the model before the row exists, and+ retrying would stall that path), unless ``recreate_missing`` asks for the+ row to be re-inserted like the whole-row save it replaced.+ """+ target = store if store is not None else self._get_metadata_store()+ try:+ return await _with_retry(+ lambda: target.update_collection_fields(+ collection,+ field_names,+ require_uninitialized=require_uninitialized,+ expected_model_id=expected_model_id,+ ),+ description=f"field update of collection {collection.name}",+ deterministic=_is_deterministic_write_error,+ )+ except ValueError as exc:+ if not (recreate_missing and "not found" in str(exc)):+ raise+ # Insert unbound: the row was deleted, so its stale binding must not+ # come back (a switch may have landed after the read).+ blank = collection.model_copy(+ update={"embedding_model_id": None, "embedding_dimension": None}+ )+ created = await _with_retry(+ lambda: target.save_collection_if_absent(blank),+ description=f"re-creation of collection {collection.name}",+ )+ if created:+ return True+ # Another writer created the row in the meantime: update it.+ return await self._update_fields_with_retry(+ collection,+ field_names,+ require_uninitialized=require_uninitialized,+ expected_model_id=expected_model_id,+ store=target,+ )++ async def _write_initial_binding(+ self,+ collection_name: str,+ updated: CollectionInfo,+ *,+ requested_model_id: str,+ require_uninitialized: bool = False,+ expected_model_id: Optional[str] = None,+ ) -> CollectionInfo:+ """Apply a first/canonical binding only if the stored one did not move first."""+ applied = await self._update_fields_with_retry(+ updated,+ _BINDING_FIELDS + ("schema_version",),+ require_uninitialized=require_uninitialized,+ expected_model_id=expected_model_id,+ )+ if applied:+ return updated+ fresh = await self.get_collection(collection_name)+ if _normalize_model_id(fresh.embedding_model_id) == _normalize_model_id(+ updated.embedding_model_id+ ):+ return fresh+ raise ValueError(+ f"Collection '{collection_name}' already initialized with "+ f"model '{fresh.embedding_model_id}'. Cannot change to '{requested_model_id}'."+ )+async def delete_collection_metadata(self,collection_name: str,@@ -348,43 +525,12 @@ class CollectionManager:delete_orphaned_metadata=delete_orphaned_metadata,)- async def _save_collection_with_retry(- self, collection: CollectionInfo, max_retries: int = 3- ) -> None:- """Save collection with retry mechanism for concurrent updates.-- Args:- collection: CollectionInfo to save- max_retries: Maximum number of retry attempts-- Raises:- Exception: If all retry attempts fail- """- for attempt in range(max_retries):- try:- await self._get_metadata_store().save_collection(collection)- return-- except Exception as e:- if attempt == max_retries - 1:- logger.error(- "Failed to save collection %s after %s attempts: %s",- collection.name,- max_retries,- e,- )- raise-- # Exponential backoff- wait_time = 0.1 * (2**attempt)- logger.warning(- "Save attempt %s failed for %s, retrying in %ss: %s",- attempt + 1,- collection.name,- wait_time,- e,- )- await asyncio.sleep(wait_time)+ async def _save_collection_with_retry(self, collection: CollectionInfo) -> None:+ """Save collection with retry mechanism for concurrent updates."""+ await _with_retry(+ lambda: self._get_metadata_store().save_collection(collection),+ description=f"save of collection {collection.name}",+ )async def _ensure_metadata_table(self) -> None:"""Ensure collection_metadata table exists in LanceDB.@@ -486,9 +632,11 @@ class CollectionManager:# Get current statetry:collection = await self.get_collection(collection_name)+ row_exists = Trueexcept ValueError:# Collection doesn't exist, create itcollection = CollectionInfo(name=collection_name)+ row_exists = False# Check if already initializedif collection.is_initialized:@@ -526,14 +674,19 @@ class CollectionManager:),})- await self._save_collection_with_retry(updated_collection)+ migrated = await self._write_initial_binding(+ collection_name,+ updated_collection,+ requested_model_id=embedding_model_id,+ expected_model_id=collection.embedding_model_id,+ )logger.info("Migrated collection '%s' embedding model from '%s' to canonical ID '%s'",collection_name,existing_model_id,canonical_model_id,)- return updated_collection+ return migratedraise ValueError(f"Collection '{collection_name}' already initialized with "@@ -558,8 +711,24 @@ class CollectionManager:})- # Save to storage- await self._save_collection_with_retry(updated_collection)+ if row_exists:+ updated_collection = await self._write_initial_binding(+ collection_name,+ updated_collection,+ requested_model_id=embedding_model_id,+ require_uninitialized=True,+ )+ else:+ inserted = await self._save_collection_if_absent_with_retry(+ updated_collection+ )+ if not inserted:+ updated_collection = await self._write_initial_binding(+ collection_name,+ updated_collection,+ requested_model_id=embedding_model_id,+ require_uninitialized=True,+ )logger.info("Initialized collection '%s' with embedding model '%s'",@@ -602,7 +771,7 @@ class CollectionManager:# Auto-create collection if it doesn't existcollection = CollectionInfo(name=collection_name)# Save the newly created collection to storage- await self._save_collection_with_retry(collection)+ await self._save_collection_if_absent_with_retry(collection)# Update statisticsupdated_data = {"documents": collection.documents + documents_delta,@@ -623,7 +792,18 @@ class CollectionManager:updated_data["document_names"] = new_document_namesupdated_collection = collection.model_copy(update=updated_data)- await self._save_collection_with_retry(updated_collection)+ # Persist the version read-side migration applied, or a legacy row is+ # re-migrated on every read and its counts reset from zero.+ fields = (+ _STATS_FIELDS+ + (("document_names",) if "document_names" in updated_data else ())+ + ("schema_version",)+ )+ # The read and this write are not atomic: the old whole-row save+ # recreated a row deleted in between, and stats must keep working then.+ await self._update_fields_with_retry(+ updated_collection, fields, recreate_missing=True+ )return updated_collection@@ -681,22 +861,21 @@ class CollectionManager:async def mark_collection_accessed(self, collection_name: str) -> None:"""Update last_accessed_at.- Takes the same lock as the other stat RMW sites: the write is a full-row- overwrite, so a stale read here would clobber a concurrent stat increment- on the per-page hot path.+ Only that column is written, so a stale read here cannot clobber a+ concurrent stat increment or a completed model switch."""lock = _get_collection_lock(collection_name)try:async with lock, _collection_thread_guard(collection_name):- collection = await self.get_collection(collection_name)- updated = collection.model_copy(- update={- "last_accessed_at": datetime.now(timezone.utc).replace(+ await self._update_fields_with_retry(+ CollectionInfo(+ name=collection_name,+ last_accessed_at=datetime.now(timezone.utc).replace(tzinfo=None- )- }+ ),+ ),+ ("last_accessed_at",),)- await self._save_collection_with_retry(updated)except Exception as e:logger.debug("Failed to update last_accessed_at for %s: %s", collection_name, e@@ -854,6 +1033,92 @@ def mark_collection_accessed_sync(collection_name: str) -> None:)+async def merge_collection_extra_metadata(+ store: MetadataStore,+ collection_info: CollectionInfo,+ key: str,+ value: Any,+ *,+ row_existed: bool,+) -> CollectionInfo:+ """Add ``key`` to a row's ``extra_metadata``, keeping the keys it already has.++ A row that vanished since the caller's read is recreated; if another writer+ created it first, its row is re-read and only ``key`` is merged into it.+ """+ for _ in range(2):+ extra = dict(collection_info.extra_metadata or {})+ if extra.get(key) is not None:+ return collection_info+ extra[key] = value+ updated = collection_info.model_copy(update={"extra_metadata": extra})+ if row_existed:+ try:+ await collection_manager.update_collection_fields(+ updated, ("extra_metadata",), store=store+ )+ return updated+ except ValueError as exc:+ if "not found" not in str(exc):+ raise+ create = updated.model_copy(+ update={"embedding_model_id": None, "embedding_dimension": None}+ )+ if await _with_retry(+ lambda: store.save_collection_if_absent(create),+ description=f"creation of collection {updated.name}",+ ):+ return updated+ # Another writer created the row first: merge into what it wrote.+ collection_info = await store.get_collection(updated.name)+ row_existed = True+ raise ValueError(f"Could not update extra_metadata of collection {updated.name}")+++def write_collection_binding_sync(+ collection_name: str,+ embedding_model_id: str,+ embedding_dimension: int,+ *,+ expected_model_id: Optional[str] = None,+ require_uninitialized: bool = False,+) -> bool:+ """Write a collection's bound model pair, only while it is frozen.++ Returns ``False`` when the store's compare-and-set guard no longer holds, so+ a caller can tell its own write from a concurrent one.+ """+ state = read_migration_state(collection_name)+ if state.state != FROZEN:+ raise CollectionNotFrozenError(+ f"Collection '{collection_name}' is not frozen for an embedding "+ "binding change.",+ details={"collection": collection_name, "migration_state": state.state},+ )+ target = CollectionInfo(+ name=collection_name,+ embedding_model_id=embedding_model_id,+ embedding_dimension=embedding_dimension,+ )+ applied = _sync_wrapper(collection_manager.update_collection_fields)(+ target,+ _BINDING_FIELDS,+ expected_model_id=expected_model_id,+ require_uninitialized=require_uninitialized,+ )+ if applied or not require_uninitialized:+ return applied+ stored = _sync_wrapper(collection_manager.get_collection)(+ collection_name+ ).embedding_model_id+ if stored is None or _normalize_model_id(stored) is not None:+ return False+ # A whitespace-only id reads as unbound but the unbound clause misses it.+ return _sync_wrapper(collection_manager.update_collection_fields)(+ target, _BINDING_FIELDS, expected_model_id=stored+ )++def _mark_collection_accessed_sync_impl(collection_name: str) -> None:_sync_wrapper(collection_manager.mark_collection_accessed)(collection_name)@@ -1248,7 +1513,16 @@ async def _rebuild_collection_stats_impl()rebuilt = base_info.model_copy(update=update_data)- await collection_manager.save_collection(rebuilt)+ fields = _STATS_FIELDS + (+ (("document_names",) if document_count == 0 else ()) + ("schema_version",)+ )+ if existing_info is None:+ inserted = await collection_manager.save_collection_if_absent(rebuilt)+ if inserted:+ return rebuilt+ await collection_manager.update_collection_fields(+ rebuilt, fields, recreate_missing=True+ )return rebuilt@@ -1373,7 +1647,7 @@ def _resolve_effective_embedding_model_sync_impl(inferred_model_id,)try:- updated_collection = collection_info.model_copy(+ candidate = collection_info.model_copy(update={"embedding_model_id": inferred_model_id,"embedding_dimension": inferred_dimension@@ -1381,7 +1655,34 @@ def _resolve_effective_embedding_model_sync_impl(else collection_info.embedding_dimension,})- _sync_wrapper(collection_manager.save_collection)(updated_collection)+ applied = _sync_wrapper(collection_manager.update_collection_fields)(+ candidate, _BINDING_FIELDS, require_uninitialized=True+ )+ if not applied:+ fresh = get_collection_sync(collection_name)+ # Inferring is slow enough for a switch to land meanwhile; it wins.+ bound = _normalize_model_id(fresh.embedding_model_id)+ if bound:+ logger.info(+ "Collection '%s' was bound to '%s' while inferring",+ collection_name,+ bound,+ )+ return bound+ if fresh.embedding_model_id is not None:+ # A whitespace-only id reads as unbound but the unbound+ # clause does not match it: repair it by exact value.+ _sync_wrapper(collection_manager.update_collection_fields)(+ candidate,+ _BINDING_FIELDS,+ expected_model_id=fresh.embedding_model_id,+ )+ # Losing that compare-and-set means a switch won: use it.+ stored = _normalize_model_id(+ get_collection_sync(collection_name).embedding_model_id+ )+ if stored:+ return storedexcept Exception as save_error:logger.warning("Failed to persist inferred embedding metadata for collection '%s': %s",@@ -1424,6 +1725,18 @@ async def rebuild_collection_metadata() -> None:await _get_maintenance_compatibility_facade().rebuild_collection_metadata()+async def _read_stored_collection(+ collection_name: str,+) -> Optional["CollectionInfo"]:+ """Read the current row; ``None`` means it does not exist."""+ try:+ return await get_metadata_store().get_collection(collection_name)+ except ValueError as exc:+ if "not found" in str(exc):+ return None+ raise++_ENGINE_COUNTS = ("documents", "parses", "chunks", "embeddings")@@ -1557,19 +1870,50 @@ async def _rebuild_collection_metadata_impl() -> None:break# Vectors the engine counts but no embeddings_* table holds: keep the- # stored model. Zero vectors still clear it so the KB can be rebound.- updated_collection = (- collection- if collection.embeddings > 0 and embedding_model_id is None- else collection.model_copy(- update={- "embedding_model_id": embedding_model_id,- "embedding_dimension": embedding_dimension,- }- )+ # stored model, since the vectors are still there under another tag.+ # Zero vectors clear it so the KB can be rebound to another model,+ # except while it is frozen (a migration owns the binding then).+ keep_binding = collection.embeddings > 0 and embedding_model_id is None+ binding: dict[str, Any] = (+ {}+ if keep_binding+ else {+ "embedding_model_id": embedding_model_id,+ "embedding_dimension": embedding_dimension,+ })- # Use the async save_collection method through sync wrapper- _sync_wrapper(collection_manager.save_collection)(updated_collection)+ current = await _read_stored_collection(collection.name)+ updated_collection = collection.model_copy(update=binding)+ inserted = False+ if current is None:+ inserted = _sync_wrapper(collection_manager.save_collection_if_absent)(+ updated_collection+ )+ if current is not None or not inserted:+ _sync_wrapper(collection_manager.update_collection_fields)(+ updated_collection,+ _COUNT_FIELDS + ("schema_version",),+ recreate_missing=True,+ )+ if binding and current is not None and current.is_initialized:+ # Unbinding is only safe while the row still holds the model+ # that was read, and skips a collection frozen at this check+ # (an unfreeze landing between check and write is not seen).+ if (+ binding["embedding_model_id"] is None+ and read_migration_state(collection.name).state != FROZEN+ ):+ _sync_wrapper(collection_manager.update_collection_fields)(+ updated_collection,+ tuple(binding),+ expected_model_id=current.embedding_model_id,+ )+ elif binding:+ _sync_wrapper(collection_manager.update_collection_fields)(+ updated_collection,+ tuple(binding),+ require_uninitialized=True,+ )except Exception as e:logger.error("Failed to rebuild collection '%s': %s", collection.name, e)diff --git a/src/xagent/core/tools/core/RAG_tools/management/embedding_switch.py b/src/xagent/core/tools/core/RAG_tools/management/embedding_switch.pynew file mode 100644index 000000000..1bf232e2b--- /dev/null+++ b/src/xagent/core/tools/core/RAG_tools/management/embedding_switch.py@@ -0,0 +1,144 @@+"""Switch one collection's bound embedding model while it is frozen.++The switch writes the model id and dimension together, records the transition in+``collection_migration_state``, and leaves every other metadata column and+``main_pointers`` untouched. Rolling back is the same call with the previous+model, after the collection is frozen again, provided that model is still+configured under the id it is recorded with: a legacy row bound to an alias that+no longer resolves to itself cannot be rolled back by this call.+"""++from __future__ import annotations++import logging+from dataclasses import dataclass+from typing import Optional++from xagent.core.model.model import EmbeddingModelConfig++from ..core.exceptions import CollectionNotFrozenError, EmbeddingAdapterError+from ..utils.model_resolver import _load_model_from_hub+from .collection_manager import (+ _normalize_model_id,+ get_collection_sync,+ write_collection_binding_sync,+)+from .migration_state import (+ FROZEN,+ CollectionMigrationState,+ read_migration_state,+ update_migration_state_if_frozen,+)++logger = logging.getLogger(__name__)+++@dataclass(frozen=True)+class CollectionEmbeddingSwitch:+ """One applied switch: what the collection used and what it uses now."""++ collection_name: str+ source_model_id: Optional[str]+ target_model_id: str+ target_dimension: int+++def _resolve_configured_model(target_model_id: str) -> tuple[str, int]:+ """Return the hub config for ``target_model_id``, never an env fallback.++ Binding a model the hub does not know would silently switch the collection to+ whatever the environment default is.+ """+ config = _load_model_from_hub(+ target_model_id, EmbeddingModelConfig, EmbeddingAdapterError+ )+ canonical = _normalize_model_id(config.id)+ if not canonical or canonical != _normalize_model_id(target_model_id):+ raise ValueError(+ f"Embedding model '{target_model_id}' resolves to '{canonical}'; "+ "switch to the configured model id."+ )+ if not isinstance(config.dimension, int):+ raise ValueError(+ f"Embedding model '{target_model_id}' has no dimension; cannot bind it."+ )+ return canonical, config.dimension+++def switch_collection_embedding_model(+ collection_name: str, target_model_id: str+) -> CollectionEmbeddingSwitch:+ """Bind ``collection_name`` to ``target_model_id``.++ Raises:+ CollectionNotFrozenError: If the collection is not frozen for migration.+ EmbeddingAdapterError: If the model hub is unavailable or has no such model.+ ValueError: If the collection does not exist, the resolved id differs from+ the requested one, or the stored binding moved while switching.+ """+ state = read_migration_state(collection_name)+ if state.state != FROZEN:+ raise CollectionNotFrozenError(+ f"Collection '{collection_name}' is not frozen for an embedding "+ "switch; freeze it first.",+ details={"collection": collection_name, "migration_state": state.state},+ )++ canonical_model_id, dimension = _resolve_configured_model(target_model_id)++ stored = get_collection_sync(collection_name)+ observed_model_id = stored.embedding_model_id+ observed = _normalize_model_id(observed_model_id)+ source_model_id = observed+ if state.target_model_id == canonical_model_id and observed == canonical_model_id:+ # Re-applying a switch that already landed: keep the original rollback+ # origin, including an unbound one (``None``).+ source_model_id = state.source_model_id++ # The record goes first: if the binding write fails, retrying the switch is+ # idempotent and still knows the source model to roll back to.+ if not update_migration_state_if_frozen(+ collection_name,+ CollectionMigrationState(+ state=FROZEN,+ source_model_id=source_model_id,+ target_model_id=canonical_model_id,+ ),+ ):+ raise CollectionNotFrozenError(+ f"Collection '{collection_name}' was unfrozen while switching.",+ details={"collection": collection_name, "migration_state": "unfrozen"},+ )++ applied = write_collection_binding_sync(+ collection_name,+ canonical_model_id,+ dimension,+ # Exactly one guard: the store rejects both, and an unbound row is not+ # matched by an exact-value compare-and-set.+ expected_model_id=observed_model_id if observed is not None else None,+ require_uninitialized=observed is None,+ )+ if not applied:+ # A concurrent identical switch may have written the same target.+ current_model_id = _normalize_model_id(+ get_collection_sync(collection_name).embedding_model_id+ )+ if current_model_id != canonical_model_id:+ raise ValueError(+ f"Collection '{collection_name}' embedding model changed while "+ "switching; retry the switch."+ )++ logger.info(+ "Switched collection '%s' embedding model from '%s' to '%s'",+ collection_name,+ source_model_id,+ canonical_model_id,+ )+ return CollectionEmbeddingSwitch(+ collection_name=collection_name,+ source_model_id=source_model_id,+ target_model_id=canonical_model_id,+ target_dimension=dimension,+ )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.pyindex 554cfedc6..b304aa67a 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@@ -152,6 +152,43 @@ def write_migration_state(return stamped+def update_migration_state_if_frozen(+ collection_name: str,+ state: CollectionMigrationState,+) -> bool:+ """Write ``state`` only while the stored row is still frozen.++ Returns ``False`` when an unfreeze landed after the caller's read, so a+ migration step cannot put a frozen row back over it.+ """+ if state.state not in (IDLE, FROZEN):+ raise ValueError(f"Unsupported migration state: {state.state!r}")+ stamped = replace(+ state,+ updated_at=datetime.now(timezone.utc).replace(tzinfo=None),+ )+ conn = get_metadata_store().get_raw_connection()+ _ensure_table(conn)+ where = f"name = '{escape_lancedb_string(collection_name)}' AND state = '{FROZEN}'"+ for attempt in range(WRITE_MAX_RETRIES - 1):+ try:+ return _update_row(conn, where, stamped.to_row())+ except Exception as exc:+ logger.warning(+ "Retrying migration state update for %s: %s", collection_name, exc+ )+ time.sleep(0.1 * (2**attempt))+ return _update_row(conn, where, stamped.to_row())+++def _update_row(conn: Any, where: str, values: Dict[str, Any]) -> bool:+ table = conn.open_table(MIGRATION_TABLE)+ try:+ return bool(table.update(where, values).rows_updated)+ finally:+ _safe_close_table(table)++def _merge_row(conn: Any, row: dict[str, Any]) -> None:_ensure_table(conn)table = conn.open_table(MIGRATION_TABLE)diff --git a/src/xagent/core/tools/core/RAG_tools/storage/contracts.py b/src/xagent/core/tools/core/RAG_tools/storage/contracts.pyindex 37a3422e2..a53f3e938 100644--- a/src/xagent/core/tools/core/RAG_tools/storage/contracts.py+++ b/src/xagent/core/tools/core/RAG_tools/storage/contracts.py@@ -313,6 +313,37 @@ class MetadataStore(ABC):async def save_collection(self, collection: CollectionInfo) -> None:"""Create or update collection metadata."""+ @abstractmethod+ async def save_collection_if_absent(self, collection: CollectionInfo) -> bool:+ """Create the row only when no row with that name exists.++ A writer that decided the row was missing must not overwrite one that+ appeared since (it may already carry a different binding). Returns+ whether it inserted.+ """++ @abstractmethod+ async def update_collection_fields(+ self,+ collection: CollectionInfo,+ field_names: Iterable[str],+ *,+ require_uninitialized: bool = False,+ expected_model_id: Optional[str] = None,+ ) -> bool:+ """Update only ``field_names`` of an existing collection row.++ Whole-row writes let a writer that read before a concurrent change put+ the old values back. Callers that do not own a column must not write it.++ The binding columns are written only while the guard holds:+ ``require_uninitialized`` means the row is not fully bound yet,+ ``expected_model_id`` means it still stores exactly that value (used by+ the alias-to-canonical rewrite). A guarded update that matches no row+ returns ``False`` instead of overwriting; an unguarded update raises+ ``ValueError`` when the row is missing.+ """+@abstractmethodasync def list_collections(self,diff --git a/src/xagent/core/tools/core/RAG_tools/storage/lancedb_stores.py b/src/xagent/core/tools/core/RAG_tools/storage/lancedb_stores.pyindex 15000d31b..93b4e83df 100644--- a/src/xagent/core/tools/core/RAG_tools/storage/lancedb_stores.py+++ b/src/xagent/core/tools/core/RAG_tools/storage/lancedb_stores.py@@ -30,7 +30,12 @@ from ..core.config import (MAIN_POINTERS_NO_MATCH_FILTER,IndexPolicy,)-from ..core.schemas import CollectionInfo, IndexResult+from ..core.schemas import (+ LANCEDB_NULL_INT_SENTINEL,+ LANCEDB_NULL_STR_SENTINEL,+ CollectionInfo,+ IndexResult,+)from ..LanceDB.schema_manager import ensure_documents_tablefrom ..utils.lancedb_query_utils import (build_fts_query,@@ -316,6 +321,74 @@ class LanceDBMetadataStore(MetadataStore):finally:_safe_close_table(table)+ async def save_collection_if_absent(self, collection: CollectionInfo) -> bool:+ from ..LanceDB.schema_manager import _safe_close_table++ conn = await self._get_connection()+ await self.ensure_collection_metadata_table()++ data = collection.to_storage()+ data["updated_at"] = datetime.now(timezone.utc).replace(tzinfo=None)++ table = conn.open_table("collection_metadata")+ try:+ result = (+ table.merge_insert(["name"])+ .when_not_matched_insert_all()+ .execute([data])+ )+ finally:+ _safe_close_table(table)+ return bool(result.num_inserted_rows)++ async def update_collection_fields(+ self,+ collection: CollectionInfo,+ field_names: Iterable[str],+ *,+ require_uninitialized: bool = False,+ expected_model_id: Optional[str] = None,+ ) -> bool:+ from ..LanceDB.schema_manager import _safe_close_table++ if require_uninitialized and expected_model_id is not None:+ raise ValueError(+ "Pass either require_uninitialized or expected_model_id, not both"+ )+ stored = collection.to_storage()+ payload: dict[str, Any] = {}+ for name in field_names:+ if name == "name" or name not in stored:+ raise ValueError(f"Cannot update collection_metadata field '{name}'")+ payload[name] = stored[name]+ payload["updated_at"] = datetime.now(timezone.utc).replace(tzinfo=None)++ conn = await self._get_connection()+ await self.ensure_collection_metadata_table()+ where = f"name = '{escape_lancedb_string(collection.name)}'"+ if require_uninitialized:+ where += (+ " AND (embedding_model_id IS NULL"+ f" OR embedding_model_id = '{LANCEDB_NULL_STR_SENTINEL}'"+ " OR embedding_dimension IS NULL"+ f" OR embedding_dimension = {LANCEDB_NULL_INT_SENTINEL})"+ )+ elif expected_model_id is not None:+ where += (+ " AND embedding_model_id = "+ f"'{escape_lancedb_string(expected_model_id)}'"+ )+ table = conn.open_table("collection_metadata")+ try:+ updated = table.update(where, payload)+ finally:+ _safe_close_table(table)+ if updated.rows_updated:+ return True+ if require_uninitialized or expected_model_id is not None:+ return False+ raise ValueError(f"Collection '{collection.name}' not found")+async def list_collections(self,user_id: Optional[int] = None,diff --git a/tests/core/tools/adapters/vibe/test_kb_creation_tools.py b/tests/core/tools/adapters/vibe/test_kb_creation_tools.pyindex c5c35d7a9..2c03cedfb 100644--- a/tests/core/tools/adapters/vibe/test_kb_creation_tools.py+++ b/tests/core/tools/adapters/vibe/test_kb_creation_tools.py@@ -77,6 +77,25 @@ class _FakeMetadataStore:self.saved_collections.append(collection)self.collection = collection+ async def save_collection_if_absent(self, collection: CollectionInfo) -> bool:+ if self.collection is not None and self.collection.name == collection.name:+ return False+ self.collection = collection+ return True++ async def update_collection_fields(+ self, collection: CollectionInfo, field_names: object, **_: object+ ) -> bool:+ if self.collection is None or self.collection.name != collection.name:+ raise ValueError(f"Collection '{collection.name}' not found")+ update = {+ name: getattr(collection, name)+ for name in field_names+ if hasattr(self.collection, name)+ }+ self.collection = self.collection.model_copy(update=update)+ return True+async def delete_collection_metadata(self,*,@@ -178,6 +197,8 @@ async def test_agent_kb_service_prepare_collection_sanitizes_without_writing():side_effect=ValueError("Collection 'agent url kb' not found"))metadata_store.save_collection = AsyncMock()+ metadata_store.save_collection_if_absent = AsyncMock(return_value=True)+ metadata_store.update_collection_fields = AsyncMock(return_value=True)service = AgentKnowledgeBaseService(user_id=71)with patch(@@ -201,6 +222,8 @@ async def test_agent_kb_service_publish_collection_preserves_existing_backend_bimetadata_store.save_collection_config = AsyncMock()metadata_store.get_collection = AsyncMock(return_value=existing)metadata_store.save_collection = AsyncMock()+ metadata_store.save_collection_if_absent = AsyncMock(return_value=True)+ metadata_store.update_collection_fields = AsyncMock(return_value=True)service = AgentKnowledgeBaseService(user_id=71)ingest_config = IngestionConfig(embedding_model_id=DEFAULT_EMBEDDING_MODEL_ID)@@ -224,6 +247,8 @@ async def test_agent_kb_service_publish_collection_persists_config():side_effect=ValueError("Collection 'agent url kb' not found"))metadata_store.save_collection = AsyncMock()+ metadata_store.save_collection_if_absent = AsyncMock(return_value=True)+ metadata_store.update_collection_fields = AsyncMock(return_value=True)service = AgentKnowledgeBaseService(user_id=71)ingest_config = IngestionConfig(embedding_model_id=DEFAULT_EMBEDDING_MODEL_ID)@@ -234,7 +259,8 @@ async def test_agent_kb_service_publish_collection_persists_config():await service.publish_collection("agent url kb", ingest_config)metadata_store.save_collection_config.assert_awaited_once()- metadata_store.save_collection.assert_awaited_once()+ metadata_store.save_collection_if_absent.assert_awaited_once()+ metadata_store.save_collection.assert_not_awaited()_, save_kwargs = metadata_store.save_collection_config.await_argsassert save_kwargs["collection"] == "agent url kb"assert save_kwargs["user_id"] == 71@@ -253,6 +279,8 @@ async def test_agent_kb_service_publish_collection_raises_on_config_save_failureside_effect=ValueError("Collection 'agent kb' not found"))metadata_store.save_collection = AsyncMock()+ metadata_store.save_collection_if_absent = AsyncMock(return_value=True)+ metadata_store.update_collection_fields = AsyncMock(return_value=True)service = AgentKnowledgeBaseService(user_id=71)ingest_config = IngestionConfig(embedding_model_id=DEFAULT_EMBEDDING_MODEL_ID)@@ -722,8 +750,9 @@ async def test_create_kb_from_file_failed_ingest_records_operation_outcome(# leave it alone; the cleanup of a collection the import created is covered# by test_cleanup_failed_agent_collection_* below.assert metadata_store.deleted_collections == []- assert metadata_store.saved_collections[-1].owners == []- assert metadata_store.saved_collections[-1].extra_metadata["kb_storage"] == {+ assert metadata_store.collection is not None+ assert metadata_store.collection.owners == []+ assert metadata_store.collection.extra_metadata["kb_storage"] == {"backend": "lancedb"}@@ -974,9 +1003,9 @@ async def test_create_kb_from_url_partial_failure_preserves_pipeline_policy(}assert metadata_store.saved_configs[-1]["collection"] == "agent_url_kb"assert metadata_store.saved_configs[-1]["user_id"] == 71- assert metadata_store.saved_collections- assert metadata_store.saved_collections[-1].owners == []- assert metadata_store.saved_collections[-1].extra_metadata["kb_storage"] == {+ assert metadata_store.collection is not None+ assert metadata_store.collection.owners == []+ assert metadata_store.collection.extra_metadata["kb_storage"] == {"backend": "lancedb"}@@ -1005,6 +1034,8 @@ async def test_agent_publish_keeps_settings_changed_during_the_crawl():side_effect=ValueError("Collection 'agent url kb' not found"))metadata_store.save_collection = AsyncMock()+ metadata_store.save_collection_if_absent = AsyncMock(return_value=True)+ metadata_store.update_collection_fields = AsyncMock(return_value=True)service = AgentKnowledgeBaseService(user_id=71)with patch(@@ -1272,6 +1303,8 @@ async def test_agent_publish_keeps_settings_when_the_config_read_fails():return_value=CollectionInfo(name="agent url kb"))metadata_store.save_collection = AsyncMock()+ metadata_store.save_collection_if_absent = AsyncMock(return_value=True)+ metadata_store.update_collection_fields = AsyncMock(return_value=True)service = AgentKnowledgeBaseService(user_id=71)with patch(@@ -1299,6 +1332,8 @@ async def test_agent_publish_of_a_new_collection_survives_a_config_read_failure(side_effect=ValueError("Collection 'agent url kb' not found"))metadata_store.save_collection = AsyncMock()+ metadata_store.save_collection_if_absent = AsyncMock(return_value=True)+ metadata_store.update_collection_fields = AsyncMock(return_value=True)service = AgentKnowledgeBaseService(user_id=71)with patch(diff --git a/tests/core/tools/core/RAG_tools/kb/test_api_compatibility.py b/tests/core/tools/core/RAG_tools/kb/test_api_compatibility.pyindex 63c4d0410..305eb7301 100644--- a/tests/core/tools/core/RAG_tools/kb/test_api_compatibility.py+++ b/tests/core/tools/core/RAG_tools/kb/test_api_compatibility.py@@ -44,6 +44,25 @@ class _FakeMetadataStore:self.saved_collections.append(collection)self.collection = collection+ async def save_collection_if_absent(self, collection: CollectionInfo) -> bool:+ if self.collection is not None and self.collection.name == collection.name:+ return False+ self.collection = collection+ return True++ async def update_collection_fields(+ self, collection: CollectionInfo, field_names: object, **_: object+ ) -> bool:+ if self.collection is None or self.collection.name != collection.name:+ raise ValueError(f"Collection '{collection.name}' not found")+ update = {+ name: getattr(collection, name)+ for name in field_names+ if hasattr(self.collection, name)+ }+ self.collection = self.collection.model_copy(update=update)+ return True+async def save_collection_config(self,*,@@ -119,7 +138,6 @@ async def test_save_collection_config_creates_owner_neutral_backend_binding() ->)assert metadata_store.saved_configs == [("demo", "{}", 7)]- assert metadata_store.saved_collections == [metadata_store.collection]assert metadata_store.collection is not Noneassert metadata_store.collection.owners == []assert metadata_store.collection.extra_metadata["kb_storage"] == {@@ -161,7 +179,6 @@ async def test_save_collection_config_creates_backend_binding_when_store_returnsuser_id=7,)- assert metadata_store.saved_collections == [metadata_store.collection]assert metadata_store.collection is not Noneassert metadata_store.collection.name == "demo"assert metadata_store.collection.extra_metadata["kb_storage"] == {diff --git a/tests/core/tools/core/RAG_tools/kb/test_milvus_collection_handle.py b/tests/core/tools/core/RAG_tools/kb/test_milvus_collection_handle.pyindex a853cbefc..3982c44ed 100644--- a/tests/core/tools/core/RAG_tools/kb/test_milvus_collection_handle.py+++ b/tests/core/tools/core/RAG_tools/kb/test_milvus_collection_handle.py@@ -856,14 +856,16 @@ def test_an_ingest_scope_resolves_each_collection_and_kb_id_once(monkeypatch.setattr(collection_handle,"ensure_milvus_collection",- lambda client, model, dimension: ensured.append((model, dimension))- or f"{model}-{dimension}",+ lambda client, model, dimension: (+ ensured.append((model, dimension)) or f"{model}-{dimension}"+ ),)monkeypatch.setattr(collection_handle,"get_or_create_kb_id",- lambda conn, collection, user_id: owners.append((collection, user_id))- or f"{collection}-{user_id}",+ lambda conn, collection, user_id: (+ owners.append((collection, user_id)) or f"{collection}-{user_id}"+ ),)handle, _ledger, connections = _handle()other = MilvusCollectionHandle(@@ -1135,7 +1137,9 @@ async def test_metadata_rebuild_keeps_the_model_without_lancedb_vectors()store, saved = MagicMock(), AsyncMock()monkeypatch.setattr(collection_manager, "get_vector_index_store", lambda: store)- monkeypatch.setattr(collection_manager.collection_manager, "save_collection", saved)+ monkeypatch.setattr(+ collection_manager.collection_manager, "save_collection_if_absent", saved+ )await collection_manager._rebuild_collection_metadata_impl()@@ -1143,6 +1147,55 @@ async def test_metadata_rebuild_keeps_the_model_without_lancedb_vectors(saved.assert_awaited_once_with(listed)+async def test_metadata_rebuild_writes_counts_only_for_a_bound_row(+ milvus_deployment: None, monkeypatch: pytest.MonkeyPatch+) -> None:+ listed = CollectionInfo(+ name="kb", embeddings=3, embedding_model_id="m", embedding_dimension=3+ )+ stored = CollectionInfo(+ name="kb", embeddings=3, embedding_model_id="m", embedding_dimension=3+ )+ monkeypatch.setattr(+ collections,+ "list_collections",+ AsyncMock(return_value=SimpleNamespace(status="success", collections=[listed])),+ )+ monkeypatch.setattr(+ collections,+ "_resolve_coordinator",+ lambda _coordinator: SimpleNamespace(+ aggregate_collection_stats_sync=lambda **_: {+ "kb": {"documents": 2, "parses": 2, "chunks": 3, "embeddings": 3}+ }+ ),+ )+ monkeypatch.setattr(+ collection_manager, "get_vector_index_store", lambda: MagicMock()+ )+ monkeypatch.setattr(+ collection_manager,+ "_read_stored_collection",+ AsyncMock(return_value=stored),+ )+ insert = AsyncMock()+ update = AsyncMock(return_value=True)+ monkeypatch.setattr(+ collection_manager.collection_manager, "save_collection_if_absent", insert+ )+ monkeypatch.setattr(+ collection_manager.collection_manager, "update_collection_fields", update+ )++ await collection_manager._rebuild_collection_metadata_impl()++ insert.assert_not_awaited()+ fields = update.await_args.args[1]+ assert fields == collection_manager._COUNT_FIELDS + ("schema_version",)+ written = update.await_args.args[0]+ assert (written.embedding_model_id, written.embedding_dimension) == ("m", 3)++def test_file_statuses_skip_the_legacy_indexed_fallback(milvus_deployment: None, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/core/tools/core/RAG_tools/kb/test_pipeline_compatibility.py b/tests/core/tools/core/RAG_tools/kb/test_pipeline_compatibility.pyindex 0c6a88c1d..2d74dedba 100644--- a/tests/core/tools/core/RAG_tools/kb/test_pipeline_compatibility.py+++ b/tests/core/tools/core/RAG_tools/kb/test_pipeline_compatibility.py@@ -48,6 +48,25 @@ class _FakeMetadataStore:self.saved.append(collection)self.collection = collection+ async def save_collection_if_absent(self, collection: CollectionInfo) -> bool:+ if self.collection is not None and self.collection.name == collection.name:+ return False+ self.collection = collection+ return True++ async def update_collection_fields(+ self, collection: CollectionInfo, field_names: object, **_: object+ ) -> bool:+ if self.collection is None or self.collection.name != collection.name:+ raise ValueError(f"Collection '{collection.name}' not found")+ update = {+ name: getattr(collection, name)+ for name in field_names+ if hasattr(self.collection, name)+ }+ self.collection = self.collection.model_copy(update=update)+ return True+class _FakeStorageShim:def __init__(self, metadata_store: _FakeMetadataStore) -> None:@@ -67,7 +86,10 @@ def test_ensure_collection_backend_binding_sets_lancedb_when_missing() -> None:assert updated is not Noneassert updated.extra_metadata["kb_storage"] == {"backend": "lancedb"}- assert metadata_store.saved == [updated]+ assert metadata_store.collection is not None+ assert metadata_store.collection.extra_metadata["kb_storage"] == {+ "backend": "lancedb"+ }@pytest.mark.asyncio@@ -83,7 +105,10 @@ async def test_ensure_collection_backend_binding_async_sets_lancedb_when_missingassert updated is not Noneassert updated.extra_metadata["kb_storage"] == {"backend": "lancedb"}- assert metadata_store.saved == [updated]+ assert metadata_store.collection is not None+ assert metadata_store.collection.extra_metadata["kb_storage"] == {+ "backend": "lancedb"+ }def test_ensure_collection_backend_binding_preserves_existing_binding() -> None:@@ -187,7 +212,7 @@ def test_process_document_binds_collection_after_first_ingest(assert metadata_store.collection.extra_metadata["kb_storage"] == {"backend": "lancedb"}- assert metadata_store.saved == [metadata_store.collection]+ assert metadata_store.saved == []@pytest.mark.parametrize(@@ -514,7 +539,9 @@ async def test_web_ingestion_zero_success_reports_incomplete_rollback_outcome(class _FailingSaveMetadataStore(_FakeMetadataStore):- async def save_collection(self, collection: CollectionInfo) -> None:+ async def update_collection_fields(+ self, collection: CollectionInfo, field_names: object, **_: object+ ) -> bool:raise RuntimeError("save failed")diff --git a/tests/core/tools/core/RAG_tools/kb/test_rebuild_collection_stats_event_loop.py b/tests/core/tools/core/RAG_tools/kb/test_rebuild_collection_stats_event_loop.pyindex 6474575d2..4a9cee1e3 100644--- a/tests/core/tools/core/RAG_tools/kb/test_rebuild_collection_stats_event_loop.py+++ b/tests/core/tools/core/RAG_tools/kb/test_rebuild_collection_stats_event_loop.py@@ -50,6 +50,14 @@ class _StubMetadataStore:async def get_collection(self, collection_name: str) -> CollectionInfo | None:return CollectionInfo(name=collection_name)+ async def update_collection_fields(+ self, collection: CollectionInfo, field_names, **kwargs+ ) -> bool:+ return True++ async def save_collection_if_absent(self, collection: CollectionInfo) -> bool:+ return True+@pytest.fixturedef slow_vector_store(monkeypatch: pytest.MonkeyPatch) -> _SlowVectorStore:diff --git a/tests/core/tools/core/RAG_tools/kb/test_tool_compatibility.py b/tests/core/tools/core/RAG_tools/kb/test_tool_compatibility.pyindex afa6a5c8e..affc8a75c 100644--- a/tests/core/tools/core/RAG_tools/kb/test_tool_compatibility.py+++ b/tests/core/tools/core/RAG_tools/kb/test_tool_compatibility.py@@ -38,6 +38,25 @@ class _FakeMetadataStore:self.saved.append(collection)self.collection = collection+ async def save_collection_if_absent(self, collection: CollectionInfo) -> bool:+ if self.collection is not None and self.collection.name == collection.name:+ return False+ self.collection = collection+ return True++ async def update_collection_fields(+ self, collection: CollectionInfo, field_names: object, **_: object+ ) -> bool:+ if self.collection is None or self.collection.name != collection.name:+ raise ValueError(f"Collection '{collection.name}' not found")+ update = {+ name: getattr(collection, name)+ for name in field_names+ if hasattr(self.collection, name)+ }+ self.collection = self.collection.model_copy(update=update)+ return True+async def delete_collection_metadata(self,*,@@ -173,7 +192,10 @@ async def test_ensure_agent_collection_backend_binding_creates_missing_metadata(assert updated.name == "demo"assert updated.owners == []assert updated.extra_metadata["kb_storage"] == {"backend": "lancedb"}- assert metadata_store.saved == [updated]+ assert metadata_store.collection is not None+ assert metadata_store.collection.extra_metadata["kb_storage"] == {+ "backend": "lancedb"+ }@pytest.mark.asyncio@@ -229,8 +251,9 @@ async def test_publish_agent_collection_binds_backend_with_the_config(monkeypatc)assert published == [7]- assert metadata_store.saved[-1].owners == []- assert metadata_store.saved[-1].extra_metadata["kb_storage"] == {+ assert metadata_store.collection is not None+ assert metadata_store.collection.owners == []+ assert metadata_store.collection.extra_metadata["kb_storage"] == {"backend": "lancedb"}diff --git a/tests/core/tools/core/RAG_tools/management/test_embedding_switch.py b/tests/core/tools/core/RAG_tools/management/test_embedding_switch.pynew file mode 100644index 000000000..eb4cae0b8--- /dev/null+++ b/tests/core/tools/core/RAG_tools/management/test_embedding_switch.py@@ -0,0 +1,1173 @@+"""Switch/rollback primitive and every writer that could put a stale model back."""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any, Optional++import pytest++from xagent.core.tools.core.RAG_tools.core.exceptions import (+ CollectionNotFrozenError,+ EmbeddingAdapterError,+)+from xagent.core.tools.core.RAG_tools.core.schemas import CollectionInfo+from xagent.core.tools.core.RAG_tools.kb import (+ KBApiCompatibilityFacade,+ KBPipelineCompatibilityFacade,+ KBToolCompatibilityFacade,+)+from xagent.core.tools.core.RAG_tools.management import collection_manager as cm+from xagent.core.tools.core.RAG_tools.management import (+ collections,+)+from xagent.core.tools.core.RAG_tools.management import embedding_switch as es+from xagent.core.tools.core.RAG_tools.management.embedding_switch import (+ switch_collection_embedding_model,+)+from xagent.core.tools.core.RAG_tools.management.migration_state import (+ FROZEN,+ IDLE,+ CollectionMigrationState,+ read_migration_state,+ write_migration_state,+)+from xagent.core.tools.core.RAG_tools.storage.factory import get_metadata_store+from xagent.core.tools.core.RAG_tools.utils import migration_utils++OLD_MODEL, OLD_DIM = "model-old", 4+NEW_MODEL, NEW_DIM = "model-new", 8+++def _bind_models(monkeypatch: pytest.MonkeyPatch) -> None:+ models = {+ "old": (OLD_MODEL, OLD_DIM),+ "new": (NEW_MODEL, NEW_DIM),+ OLD_MODEL: (OLD_MODEL, OLD_DIM),+ NEW_MODEL: (NEW_MODEL, NEW_DIM),+ }++ def _resolve(model_id: str, **_: Any) -> tuple[SimpleNamespace, object]:+ model, dimension = models[model_id]+ return SimpleNamespace(id=model, dimension=dimension), object()++ def _load(model_id: str, *_: Any) -> SimpleNamespace:+ model, dimension = models[model_id]+ return SimpleNamespace(id=model, dimension=dimension)++ monkeypatch.setattr(cm, "resolve_embedding_adapter", _resolve)+ monkeypatch.setattr(es, "_load_model_from_hub", _load)+++async def _save(+ name: str = "kb", model: str = OLD_MODEL, dim: int = OLD_DIM, **kw: Any+):+ await cm.collection_manager.save_collection(+ CollectionInfo(+ name=name, embedding_model_id=model, embedding_dimension=dim, **kw+ )+ )+++def _save_sync(name: str = "kb", **kw: Any) -> None:+ asyncio.run(_save(name, **kw))+++def _freeze(name: str = "kb") -> None:+ write_migration_state(name, CollectionMigrationState(state=FROZEN))+++def _switch(monkeypatch: pytest.MonkeyPatch, name: str = "kb") -> None:+ _save_sync(name)+ _freeze(name)+ _bind_models(monkeypatch)+ switch_collection_embedding_model(name, NEW_MODEL)+++def _binding(name: str = "kb") -> tuple[Optional[str], Optional[int]]:+ row = asyncio.run(cm.collection_manager.get_collection(name))+ return row.embedding_model_id, row.embedding_dimension+++def _delete_row(name: str) -> None:+ from xagent.core.tools.core.RAG_tools.LanceDB.schema_manager import (+ _safe_close_table,+ )++ conn = get_metadata_store().get_raw_connection()+ table = conn.open_table("collection_metadata")+ try:+ table.delete(f"name = '{name}'")+ finally:+ _safe_close_table(table)+++def _raw_row(name: str = "kb") -> dict[str, Any]:+ from xagent.core.tools.core.RAG_tools.LanceDB.schema_manager import (+ _safe_close_table,+ )++ conn = get_metadata_store().get_raw_connection()+ table = conn.open_table("collection_metadata")+ try:+ rows = table.search().where(f"name = '{name}'").to_arrow().to_pylist()+ finally:+ _safe_close_table(table)+ assert rows+ return rows[0]+++def test_switch_sets_both_binding_fields_and_records_the_transition(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync(documents=3)+ _freeze()+ _bind_models(monkeypatch)++ result = switch_collection_embedding_model("kb", NEW_MODEL)++ assert _binding() == (NEW_MODEL, NEW_DIM)+ assert asyncio.run(cm.collection_manager.get_collection("kb")).documents == 3+ state = read_migration_state("kb")+ assert state.state == FROZEN+ assert state.source_model_id == OLD_MODEL+ assert state.target_model_id == NEW_MODEL+ assert result.target_dimension == NEW_DIM+++def test_switch_writes_only_the_binding_columns(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync()+ _freeze()+ _bind_models(monkeypatch)+ store = get_metadata_store()+ real_update = store.update_collection_fields+ seen: list[tuple[tuple[str, ...], dict[str, Any]]] = []++ async def _spy(collection: CollectionInfo, field_names: Any, **kw: Any) -> bool:+ seen.append((tuple(field_names), kw))+ return await real_update(collection, field_names, **kw)++ monkeypatch.setattr(store, "update_collection_fields", _spy)++ switch_collection_embedding_model("kb", NEW_MODEL)++ assert [fields for fields, _ in seen] == [+ ("embedding_model_id", "embedding_dimension")+ ]+ assert seen[0][1]["expected_model_id"] == OLD_MODEL+ assert seen[0][1]["require_uninitialized"] is False+++def test_a_lost_race_on_the_same_target_is_a_success(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync()+ _freeze()+ _bind_models(monkeypatch)+ store = get_metadata_store()+ real_update = store.update_collection_fields++ async def _lose_but_the_target_landed(collection, fields, **kw):+ if "embedding_model_id" in fields:+ await real_update(collection, fields)+ return False+ return await real_update(collection, fields, **kw)++ monkeypatch.setattr(store, "update_collection_fields", _lose_but_the_target_landed)++ result = switch_collection_embedding_model("kb", NEW_MODEL)++ assert result.target_model_id == NEW_MODEL+ assert _binding() == (NEW_MODEL, NEW_DIM)+++def test_switch_refuses_a_collection_that_is_not_frozen(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync()+ _bind_models(monkeypatch)++ with pytest.raises(CollectionNotFrozenError):+ switch_collection_embedding_model("kb", NEW_MODEL)++ assert _binding() == (OLD_MODEL, OLD_DIM)+++def test_switch_refuses_an_idle_migration_record(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync()+ write_migration_state("kb", CollectionMigrationState(state=IDLE))+ _bind_models(monkeypatch)++ with pytest.raises(CollectionNotFrozenError):+ switch_collection_embedding_model("kb", NEW_MODEL)++ assert _binding() == (OLD_MODEL, OLD_DIM)+++def test_switch_refuses_a_model_without_a_dimension(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync()+ _freeze()+ monkeypatch.setattr(+ es,+ "_load_model_from_hub",+ lambda model_id, *_: SimpleNamespace(id=model_id, dimension=None),+ )++ with pytest.raises(ValueError, match="no dimension"):+ switch_collection_embedding_model("kb", NEW_MODEL)++ assert _binding() == (OLD_MODEL, OLD_DIM)+ assert read_migration_state("kb").target_model_id is None+++def test_switch_refuses_a_missing_collection(monkeypatch: pytest.MonkeyPatch) -> None:+ _freeze("ghost")+ _bind_models(monkeypatch)++ with pytest.raises(ValueError):+ switch_collection_embedding_model("ghost", "new")+++def test_switch_refuses_a_model_the_hub_does_not_configure(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync()+ _freeze()+ _bind_models(monkeypatch)++ def _missing(*_: Any) -> None:+ raise EmbeddingAdapterError("model not found in hub")++ monkeypatch.setattr(es, "_load_model_from_hub", _missing)++ with pytest.raises(EmbeddingAdapterError):+ switch_collection_embedding_model("kb", NEW_MODEL)++ assert _binding() == (OLD_MODEL, OLD_DIM)+ assert read_migration_state("kb").target_model_id is None+++def test_switch_refuses_an_alias_instead_of_binding_another_id(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync()+ _freeze()+ _bind_models(monkeypatch)+ monkeypatch.setattr(+ es,+ "_load_model_from_hub",+ lambda *_: SimpleNamespace(id=NEW_MODEL, dimension=NEW_DIM),+ )++ with pytest.raises(ValueError, match="configured model id"):+ switch_collection_embedding_model("kb", "new-alias")++ assert _binding() == (OLD_MODEL, OLD_DIM)+ assert read_migration_state("kb").target_model_id is None+++def test_switch_raises_when_the_binding_moves_under_it(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync()+ _freeze()+ _bind_models(monkeypatch)++ async def _lost(*_: Any, **__: Any) -> bool:+ return False++ monkeypatch.setattr(get_metadata_store(), "update_collection_fields", _lost)++ with pytest.raises(ValueError, match="changed while switching"):+ switch_collection_embedding_model("kb", NEW_MODEL)++ assert _binding() == (OLD_MODEL, OLD_DIM)+++def test_switch_refuses_a_collection_unfrozen_while_switching(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync()+ _freeze()+ _bind_models(monkeypatch)+ real_get = es.get_collection_sync++ def _unfreeze_during_read(name: str) -> CollectionInfo:+ row = real_get(name)+ write_migration_state(name, CollectionMigrationState(state=IDLE))+ return row++ monkeypatch.setattr(es, "get_collection_sync", _unfreeze_during_read)++ with pytest.raises(CollectionNotFrozenError, match="unfrozen"):+ switch_collection_embedding_model("kb", NEW_MODEL)++ assert _binding() == (OLD_MODEL, OLD_DIM)+ assert read_migration_state("kb").state == IDLE+++def test_binding_write_refuses_an_unfrozen_collection(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync()+ _bind_models(monkeypatch)++ with pytest.raises(CollectionNotFrozenError):+ cm.write_collection_binding_sync("kb", NEW_MODEL, NEW_DIM)++ assert _binding() == (OLD_MODEL, OLD_DIM)+++def test_stats_update_persists_the_migrated_schema_version() -> None:+ asyncio.run(+ cm.collection_manager.save_collection(+ CollectionInfo(name="kb", schema_version="0.0.0", documents=2)+ )+ )++ cm.update_collection_stats_sync("kb", documents_delta=1)++ row = _raw_row()+ assert row["schema_version"] == "1.0.0"+ assert row["documents"] == 3+++def test_rollback_is_the_same_call_with_the_previous_model(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ switch_collection_embedding_model("kb", OLD_MODEL)++ assert _binding() == (OLD_MODEL, OLD_DIM)+ state = read_migration_state("kb")+ assert state.source_model_id == NEW_MODEL+ assert state.target_model_id == OLD_MODEL+++def test_partial_updates_retry_commit_conflicts(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ store = get_metadata_store()+ real = store.update_collection_fields+ calls = {"n": 0}++ async def _flaky(collection, field_names, **kw):+ calls["n"] += 1+ if calls["n"] == 1:+ raise RuntimeError("commit conflict")+ return await real(collection, field_names, **kw)++ monkeypatch.setattr(store, "update_collection_fields", _flaky)++ cm.update_collection_stats_sync("kb", documents_delta=1)++ assert calls["n"] == 2+ row = asyncio.run(store.get_collection("kb"))+ assert row.documents == 1+ assert (row.embedding_model_id, row.embedding_dimension) == (NEW_MODEL, NEW_DIM)+++def test_stats_update_cannot_revert_a_switch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ real_get = cm.collection_manager.get_collection+ stale = CollectionInfo(+ name="kb", embedding_model_id=OLD_MODEL, embedding_dimension=OLD_DIM+ )+ calls = {"n": 0}++ async def _stale_once(name: str) -> CollectionInfo:+ calls["n"] += 1+ return stale if calls["n"] == 1 else await real_get(name)++ monkeypatch.setattr(cm.collection_manager, "get_collection", _stale_once)++ cm.update_collection_stats_sync("kb", documents_delta=1)++ row = asyncio.run(real_get("kb"))+ assert (row.embedding_model_id, row.embedding_dimension) == (NEW_MODEL, NEW_DIM)+ assert row.documents == 1+++def test_access_timestamp_update_touches_only_that_column(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ before = asyncio.run(cm.collection_manager.get_collection("kb"))++ cm.mark_collection_accessed_sync("kb")++ row = asyncio.run(cm.collection_manager.get_collection("kb"))+ assert row.last_accessed_at > before.last_accessed_at+ assert (row.embedding_model_id, row.embedding_dimension) == (NEW_MODEL, NEW_DIM)+ assert row.documents == before.documents+++def test_stats_rebuild_cannot_revert_a_switch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ store = get_metadata_store()+ stale = CollectionInfo(+ name="kb",+ embedding_model_id=OLD_MODEL,+ embedding_dimension=OLD_DIM,+ documents=2,+ )++ async def _stale(_: str) -> CollectionInfo:+ return stale++ real_get = store.get_collection+ calls = {"n": 0}++ async def _stale_once(name: str) -> CollectionInfo:+ calls["n"] += 1+ return stale if calls["n"] == 1 else await real_get(name)++ monkeypatch.setattr(store, "get_collection", _stale_once)+ coordinator = SimpleNamespace(+ aggregate_collection_stats_sync=lambda **_: {+ "kb": {"documents": 5, "parses": 5, "chunks": 5, "embeddings": 5}+ }+ )++ asyncio.run(cm._rebuild_collection_stats_impl("kb", coordinator))++ assert _binding() == (NEW_MODEL, NEW_DIM)+++def test_inferred_model_cannot_overwrite_a_switch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ real_get = cm.get_collection_sync+ stale = CollectionInfo(name="kb", embeddings=5)+ calls = {"n": 0}++ def _stale_once(name: str) -> CollectionInfo:+ calls["n"] += 1+ return stale if calls["n"] == 1 else real_get(name)++ monkeypatch.setattr(cm, "get_collection_sync", _stale_once)+ monkeypatch.setattr(+ migration_utils,+ "_infer_embedding_config_from_collection",+ lambda _name: (OLD_MODEL, OLD_DIM),+ )++ resolved = cm.resolve_effective_embedding_model_sync("kb", None)++ assert resolved == NEW_MODEL+ assert _binding() == (NEW_MODEL, NEW_DIM)+++def test_switch_repairs_a_whitespace_binding(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ asyncio.run(+ cm.collection_manager.save_collection(+ CollectionInfo(+ name="kb", embedding_model_id=" ", embedding_dimension=OLD_DIM+ )+ )+ )+ _freeze()+ _bind_models(monkeypatch)++ result = switch_collection_embedding_model("kb", NEW_MODEL)++ assert _binding() == (NEW_MODEL, NEW_DIM)+ assert result.source_model_id is None+++def test_a_lost_whitespace_repair_returns_the_stored_model(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ asyncio.run(+ cm.collection_manager.save_collection(+ CollectionInfo(+ name="kb",+ embedding_model_id=" ",+ embedding_dimension=OLD_DIM,+ embeddings=5,+ )+ )+ )+ monkeypatch.setattr(+ migration_utils,+ "_infer_embedding_config_from_collection",+ lambda _name: (OLD_MODEL, OLD_DIM),+ )+ store = get_metadata_store()+ real_update = store.update_collection_fields++ async def _lose_the_repair_to_a_switch(collection, fields, **kw):+ if kw.get("expected_model_id") == " ":+ await real_update(+ collection.model_copy(+ update={+ "embedding_model_id": NEW_MODEL,+ "embedding_dimension": NEW_DIM,+ }+ ),+ fields,+ )+ return False+ return await real_update(collection, fields, **kw)++ monkeypatch.setattr(store, "update_collection_fields", _lose_the_repair_to_a_switch)++ resolved = cm.resolve_effective_embedding_model_sync("kb", None)++ assert resolved == NEW_MODEL+ assert _binding() == (NEW_MODEL, NEW_DIM)+++def test_inference_repairs_a_whitespace_binding(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ asyncio.run(+ cm.collection_manager.save_collection(+ CollectionInfo(+ name="kb",+ embedding_model_id=" ",+ embedding_dimension=OLD_DIM,+ embeddings=5,+ )+ )+ )+ monkeypatch.setattr(+ migration_utils,+ "_infer_embedding_config_from_collection",+ lambda _name: (OLD_MODEL, OLD_DIM),+ )++ resolved = cm.resolve_effective_embedding_model_sync("kb", None)++ assert resolved == OLD_MODEL+ assert _raw_row()["embedding_model_id"] == OLD_MODEL+++def test_initialization_cannot_revert_a_switch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ real_get = cm.collection_manager.get_collection+ stale = CollectionInfo(name="kb")+ calls = {"n": 0}++ async def _stale_once(name: str) -> CollectionInfo:+ calls["n"] += 1+ return stale if calls["n"] == 1 else await real_get(name)++ monkeypatch.setattr(cm.collection_manager, "get_collection", _stale_once)++ with pytest.raises(ValueError, match="already initialized"):+ asyncio.run(cm.collection_manager.initialize_collection_embedding("kb", "old"))++ assert _binding() == (NEW_MODEL, NEW_DIM)+++def test_initialization_cannot_revert_a_switch_when_the_row_looks_missing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ _bind_models(monkeypatch)+ real_get = cm.collection_manager.get_collection+ calls = {"n": 0}++ async def _missing_once(name: str) -> CollectionInfo:+ calls["n"] += 1+ if calls["n"] == 1:+ raise ValueError(f"Collection '{name}' not found")+ return await real_get(name)++ monkeypatch.setattr(cm.collection_manager, "get_collection", _missing_once)++ with pytest.raises(ValueError, match="already initialized"):+ asyncio.run(cm.collection_manager.initialize_collection_embedding("kb", "old"))++ assert _binding() == (NEW_MODEL, NEW_DIM)+++def test_alias_canonicalization_cannot_revert_a_switch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ real_get = cm.collection_manager.get_collection+ stale = CollectionInfo(+ name="kb", embedding_model_id=OLD_MODEL, embedding_dimension=OLD_DIM+ )+ calls = {"n": 0}++ async def _stale_once(name: str) -> CollectionInfo:+ calls["n"] += 1+ return stale if calls["n"] == 1 else await real_get(name)++ monkeypatch.setattr(cm.collection_manager, "get_collection", _stale_once)+ monkeypatch.setattr(+ cm, "_embedding_model_ids_equivalent", lambda _a, _b: (True, OLD_MODEL, OLD_DIM)+ )++ with pytest.raises(ValueError, match="already initialized"):+ asyncio.run(+ cm.collection_manager.initialize_collection_embedding("kb", "old-alias")+ )++ assert _binding() == (NEW_MODEL, NEW_DIM)+++def test_metadata_rebuild_cannot_clear_a_switch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ stale = CollectionInfo(name="kb")+ store = get_metadata_store()+ real_get = store.get_collection+ calls = {"n": 0}++ async def _stale_once(name: str) -> CollectionInfo:+ calls["n"] += 1+ return stale if calls["n"] == 1 else await real_get(name)++ async def _list_collections(**_: Any) -> SimpleNamespace:+ return SimpleNamespace(status="success", collections=[stale], message="")++ monkeypatch.setattr(store, "get_collection", _stale_once)+ monkeypatch.setattr(collections, "list_collections", _list_collections)+ monkeypatch.setattr(+ "xagent.core.tools.core.RAG_tools.kb.collection_handle.ledger_holds_vectors",+ lambda: False,+ )+ monkeypatch.setattr(cm, "get_vector_index_store", lambda: SimpleNamespace())+ monkeypatch.setattr(+ collections,+ "_resolve_coordinator",+ lambda _coordinator: SimpleNamespace(+ aggregate_collection_stats_sync=lambda **_: {+ "kb": {"documents": 0, "parses": 0, "chunks": 0, "embeddings": 0}+ }+ ),+ )++ asyncio.run(cm._rebuild_collection_metadata_impl())++ row = asyncio.run(real_get("kb"))+ assert (row.embedding_model_id, row.embedding_dimension) == (NEW_MODEL, NEW_DIM)+++def test_reapplying_a_switch_keeps_the_rollback_origin(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)++ result = switch_collection_embedding_model("kb", NEW_MODEL)++ assert result.source_model_id == OLD_MODEL+ state = read_migration_state("kb")+ assert state.source_model_id == OLD_MODEL+ assert state.target_model_id == NEW_MODEL+++def test_reapplying_a_switch_with_an_unbound_origin_keeps_it_none(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ asyncio.run(cm.collection_manager.save_collection(CollectionInfo(name="kb")))+ _freeze()+ _bind_models(monkeypatch)++ first = switch_collection_embedding_model("kb", NEW_MODEL)+ second = switch_collection_embedding_model("kb", NEW_MODEL)++ assert first.source_model_id is None+ assert second.source_model_id is None+ assert read_migration_state("kb").source_model_id is None+ assert _binding() == (NEW_MODEL, NEW_DIM)+++ "error",+ [+ "Pass either require_uninitialized or expected_model_id, not both",+ "Cannot update collection_metadata field 'name'",+ ],+)+def test_deterministic_store_errors_are_not_retried(+ monkeypatch: pytest.MonkeyPatch, error: str+) -> None:+ _save_sync()+ store = get_metadata_store()+ calls = {"n": 0}++ async def _reject(*_: Any, **__: Any) -> bool:+ calls["n"] += 1+ raise ValueError(error)++ monkeypatch.setattr(store, "update_collection_fields", _reject)++ with pytest.raises(ValueError, match=error):+ asyncio.run(+ cm.collection_manager.update_collection_fields(+ CollectionInfo(name="kb", documents=1), ("documents",)+ )+ )++ assert calls["n"] == 1+++def test_missing_row_update_is_not_retried(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ store = get_metadata_store()+ real = store.update_collection_fields+ calls = {"n": 0}++ async def _spy(*args, **kwargs):+ calls["n"] += 1+ return await real(*args, **kwargs)++ monkeypatch.setattr(store, "update_collection_fields", _spy)++ cm.mark_collection_accessed_sync("ghost")++ assert calls["n"] == 1+++def test_same_model_initialization_race_returns_the_stored_row(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync(documents=3)+ _bind_models(monkeypatch)+ real_get = cm.collection_manager.get_collection+ stale = CollectionInfo(name="kb")+ calls = {"n": 0}++ async def _stale_once(name: str) -> CollectionInfo:+ calls["n"] += 1+ return stale if calls["n"] == 1 else await real_get(name)++ monkeypatch.setattr(cm.collection_manager, "get_collection", _stale_once)++ result = asyncio.run(+ cm.collection_manager.initialize_collection_embedding("kb", "old")+ )++ assert result.embedding_model_id == OLD_MODEL+ assert result.documents == 3+ assert _binding() == (OLD_MODEL, OLD_DIM)+++def test_stats_recreates_a_deleted_row_without_a_binding(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync(documents=1)+ stale = CollectionInfo(+ name="kb",+ documents=1,+ embedding_model_id=OLD_MODEL,+ embedding_dimension=OLD_DIM,+ )++ async def _read_then_delete(_: str) -> CollectionInfo:+ _delete_row("kb")+ return stale++ monkeypatch.setattr(cm.collection_manager, "get_collection", _read_then_delete)++ cm.update_collection_stats_sync("kb", documents_delta=1)++ row = _raw_row()+ assert row["documents"] == 2+ assert (row["embedding_model_id"], row["embedding_dimension"]) == ("", -1)+++def test_stats_recreate_cannot_put_a_switched_model_back(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ stale = CollectionInfo(+ name="kb",+ documents=1,+ embedding_model_id=OLD_MODEL,+ embedding_dimension=OLD_DIM,+ )++ async def _read_then_delete(_: str) -> CollectionInfo:+ _delete_row("kb")+ return stale++ monkeypatch.setattr(cm.collection_manager, "get_collection", _read_then_delete)++ cm.update_collection_stats_sync("kb", documents_delta=1)++ row = _raw_row()+ assert (row["embedding_model_id"], row["embedding_dimension"]) == ("", -1)+++def test_merging_extra_metadata_recreates_the_row_unbound(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync(name="demo")+ store = get_metadata_store()+ real_get = store.get_collection+ calls = {"n": 0}++ async def _read_then_delete(name: str) -> CollectionInfo:+ calls["n"] += 1+ row = await real_get(name)+ if calls["n"] == 1:+ _delete_row(name)+ return row++ monkeypatch.setattr(store, "get_collection", _read_then_delete)++ asyncio.run(+ KBApiCompatibilityFacade()._ensure_collection_backend_binding_with_store(+ "demo", store+ )+ )++ row = asyncio.run(real_get("demo"))+ assert (row.embedding_model_id, row.embedding_dimension) == (None, None)+ assert row.extra_metadata["kb_storage"] == {"backend": "lancedb"}+++def test_stats_rebuild_recreates_a_row_deleted_after_the_read(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync(documents=1)+ store = get_metadata_store()+ real_get = store.get_collection++ async def _read_then_delete(name: str) -> CollectionInfo:+ row = await real_get(name)+ _delete_row(name)+ return row++ monkeypatch.setattr(store, "get_collection", _read_then_delete)+ coordinator = SimpleNamespace(+ aggregate_collection_stats_sync=lambda **_: {+ "kb": {"documents": 5, "parses": 5, "chunks": 5, "embeddings": 5}+ }+ )++ asyncio.run(cm._rebuild_collection_stats_impl("kb", coordinator))++ assert _raw_row()["documents"] == 5+++def test_initialization_persists_the_migrated_schema_version(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ asyncio.run(+ cm.collection_manager.save_collection(+ CollectionInfo(name="kb", schema_version="0.0.0")+ )+ )+ _bind_models(monkeypatch)++ cm.initialize_collection_embedding_sync("kb", "old")++ assert _raw_row()["schema_version"] == "1.0.0"+++def test_stats_auto_create_cannot_clear_a_switch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ real_get = cm.collection_manager.get_collection++ async def _missing(_: str) -> CollectionInfo:+ raise ValueError("Collection 'kb' not found")++ monkeypatch.setattr(cm.collection_manager, "get_collection", _missing)++ cm.update_collection_stats_sync("kb", documents_delta=1)++ row = asyncio.run(real_get("kb"))+ assert (row.embedding_model_id, row.embedding_dimension) == (NEW_MODEL, NEW_DIM)+ assert row.documents == 1+++def test_backend_bindings_create_a_missing_row() -> None:+ store = get_metadata_store()++ asyncio.run(+ KBApiCompatibilityFacade()._ensure_collection_backend_binding_with_store(+ "api-demo", store+ )+ )+ asyncio.run(+ KBToolCompatibilityFacade().ensure_agent_collection_backend_binding("tool-demo")+ )++ for name in ("api-demo", "tool-demo"):+ row = asyncio.run(store.get_collection(name))+ assert row.extra_metadata["kb_storage"] == {"backend": "lancedb"}+++def test_backend_binding_keeps_an_existing_binding() -> None:+ _save_sync(name="demo")+ store = get_metadata_store()++ asyncio.run(+ KBApiCompatibilityFacade()._ensure_collection_backend_binding_with_store(+ "demo", store+ )+ )++ assert _binding("demo") == (OLD_MODEL, OLD_DIM)+ assert asyncio.run(store.get_collection("demo")).extra_metadata["kb_storage"] == {+ "backend": "lancedb"+ }+++def test_api_binding_does_not_overwrite_a_row_that_appeared(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync(name="demo", extra_metadata={"other": "kept"})+ store = get_metadata_store()+ real_get = store.get_collection+ calls = {"n": 0}++ async def _missing_once(name: str) -> CollectionInfo:+ calls["n"] += 1+ if calls["n"] == 1:+ raise ValueError(f"Collection '{name}' not found")+ return await real_get(name)++ monkeypatch.setattr(store, "get_collection", _missing_once)++ asyncio.run(+ KBApiCompatibilityFacade()._ensure_collection_backend_binding_with_store(+ "demo", store+ )+ )++ assert _binding("demo") == (OLD_MODEL, OLD_DIM)+ extra = asyncio.run(real_get("demo")).extra_metadata+ assert extra["other"] == "kept"+ assert extra["kb_storage"] == {"backend": "lancedb"}+++def test_tool_binding_does_not_overwrite_a_row_that_appeared(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync(name="demo", extra_metadata={"other": "kept"})+ store = get_metadata_store()+ real_get = store.get_collection+ calls = {"n": 0}++ async def _missing_once(name: str) -> CollectionInfo:+ calls["n"] += 1+ if calls["n"] == 1:+ raise ValueError(f"Collection '{name}' not found")+ return await real_get(name)++ monkeypatch.setattr(store, "get_collection", _missing_once)++ asyncio.run(+ KBToolCompatibilityFacade().ensure_agent_collection_backend_binding("demo")+ )++ assert _binding("demo") == (OLD_MODEL, OLD_DIM)+ extra = asyncio.run(real_get("demo")).extra_metadata+ assert extra["other"] == "kept"+ assert extra["kb_storage"] == {"backend": "lancedb"}+++def test_metadata_rebuild_creation_cannot_clear_a_switch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ stale = CollectionInfo(name="kb")++ async def _list_collections(**_: Any) -> SimpleNamespace:+ return SimpleNamespace(status="success", collections=[stale], message="")++ async def _missing(_name: str) -> None:+ return None++ monkeypatch.setattr(cm, "_read_stored_collection", _missing)+ monkeypatch.setattr(collections, "list_collections", _list_collections)+ monkeypatch.setattr(+ "xagent.core.tools.core.RAG_tools.kb.collection_handle.ledger_holds_vectors",+ lambda: False,+ )+ monkeypatch.setattr(cm, "get_vector_index_store", lambda: SimpleNamespace())+ monkeypatch.setattr(+ collections,+ "_resolve_coordinator",+ lambda _coordinator: SimpleNamespace(+ aggregate_collection_stats_sync=lambda **_: {+ "kb": {"documents": 0, "parses": 0, "chunks": 0, "embeddings": 0}+ }+ ),+ )++ asyncio.run(cm._rebuild_collection_metadata_impl())++ assert _binding() == (NEW_MODEL, NEW_DIM)+++def test_metadata_rebuild_does_not_unbind_a_frozen_kb(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ stale = CollectionInfo(name="kb", embeddings=0)++ async def _list_collections(**_: Any) -> SimpleNamespace:+ return SimpleNamespace(status="success", collections=[stale], message="")++ monkeypatch.setattr(collections, "list_collections", _list_collections)+ monkeypatch.setattr(+ "xagent.core.tools.core.RAG_tools.kb.collection_handle.ledger_holds_vectors",+ lambda: False,+ )+ monkeypatch.setattr(cm, "get_vector_index_store", lambda: SimpleNamespace())+ monkeypatch.setattr(+ collections,+ "_resolve_coordinator",+ lambda _coordinator: SimpleNamespace(+ aggregate_collection_stats_sync=lambda **_: {+ "kb": {"documents": 0, "parses": 0, "chunks": 0, "embeddings": 0}+ }+ ),+ )++ asyncio.run(cm._rebuild_collection_metadata_impl())++ assert _binding() == (NEW_MODEL, NEW_DIM)+++def test_metadata_rebuild_recreates_a_row_deleted_after_the_read(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _save_sync()++ async def _list_collections(**_: Any) -> SimpleNamespace:+ return SimpleNamespace(+ status="success", collections=[CollectionInfo(name="kb")], message=""+ )++ real_read = cm._read_stored_collection++ async def _read_then_delete(name: str) -> CollectionInfo:+ row = await real_read(name)+ _delete_row(name)+ return row++ monkeypatch.setattr(cm, "_read_stored_collection", _read_then_delete)+ monkeypatch.setattr(collections, "list_collections", _list_collections)+ monkeypatch.setattr(+ "xagent.core.tools.core.RAG_tools.kb.collection_handle.ledger_holds_vectors",+ lambda: False,+ )+ monkeypatch.setattr(cm, "get_vector_index_store", lambda: SimpleNamespace())+ monkeypatch.setattr(+ collections,+ "_resolve_coordinator",+ lambda _coordinator: SimpleNamespace(+ aggregate_collection_stats_sync=lambda **_: {+ "kb": {"documents": 0, "parses": 0, "chunks": 0, "embeddings": 0}+ }+ ),+ )++ asyncio.run(cm._rebuild_collection_metadata_impl())++ row = _raw_row()+ assert (row["embedding_model_id"], row["embedding_dimension"]) == ("", -1)+++class _SaveOnlyStore:+ def __init__(self) -> None:+ self.saved: list[CollectionInfo] = []++ async def get_collection(self, name: str) -> CollectionInfo:+ return CollectionInfo(name=name)++ async def save_collection(self, collection: CollectionInfo) -> None:+ self.saved.append(collection)+++def test_api_binding_requires_the_insert_only_method() -> None:+ store = _SaveOnlyStore()++ result = asyncio.run(+ KBApiCompatibilityFacade()._ensure_collection_backend_binding_with_store(+ "demo", store+ )+ )++ assert result is None+ assert store.saved == []+++def test_stats_rebuild_creation_cannot_clear_a_switch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _switch(monkeypatch)+ store = get_metadata_store()+ real_get = store.get_collection+ calls = {"n": 0}++ async def _missing_once(name: str) -> CollectionInfo:+ calls["n"] += 1+ if calls["n"] == 1:+ raise ValueError(f"Collection '{name}' not found")+ return await real_get(name)++ monkeypatch.setattr(store, "get_collection", _missing_once)+ coordinator = SimpleNamespace(+ aggregate_collection_stats_sync=lambda **_: {+ "kb": {"documents": 5, "parses": 5, "chunks": 5, "embeddings": 5}+ }+ )++ asyncio.run(cm._rebuild_collection_stats_impl("kb", coordinator))++ assert _binding() == (NEW_MODEL, NEW_DIM)+++class _UpdatingStore:+ def __init__(self, collection: CollectionInfo) -> None:+ self.collection = collection+ self.updated: list[tuple[tuple[str, ...], Any]] = []+ self.saved = 0++ async def get_collection(self, _name: str) -> CollectionInfo:+ return self.collection++ async def update_collection_fields(self, collection, field_names, **kw):+ self.updated.append((tuple(field_names), collection.extra_metadata))+ return True++ async def save_collection(self, collection) -> None:+ self.saved += 1+++def test_backend_binding_updates_only_extra_metadata() -> None:+ store = _UpdatingStore(+ CollectionInfo(+ name="demo", embedding_model_id=NEW_MODEL, embedding_dimension=NEW_DIM+ )+ )+ facade = KBPipelineCompatibilityFacade(+ storage_shim=SimpleNamespace(get_metadata_store=lambda: store)+ )++ asyncio.run(facade.ensure_collection_backend_binding_async("demo"))++ assert store.saved == 0+ assert store.updated[0][0] == ("extra_metadata",)diff --git a/tests/core/tools/core/RAG_tools/storage/test_metadata_partial_update.py b/tests/core/tools/core/RAG_tools/storage/test_metadata_partial_update.pynew file mode 100644index 000000000..6ee175616--- /dev/null+++ b/tests/core/tools/core/RAG_tools/storage/test_metadata_partial_update.py@@ -0,0 +1,203 @@+"""Partial collection_metadata writes: only the named columns change."""++from __future__ import annotations++import asyncio+from typing import Any++import pytest++from xagent.core.tools.core.RAG_tools.core.schemas import CollectionInfo+from xagent.core.tools.core.RAG_tools.storage.factory import get_metadata_store+++def _save(**kw: Any) -> None:+ asyncio.run(get_metadata_store().save_collection(CollectionInfo(**kw)))+++def _row(name: str = "kb") -> CollectionInfo:+ return asyncio.run(get_metadata_store().get_collection(name))+++def test_partial_update_leaves_other_columns_alone() -> None:+ _save(+ name="kb",+ embedding_model_id="model-new",+ embedding_dimension=8,+ documents=1,+ extra_metadata={"keep": "me"},+ )++ asyncio.run(+ get_metadata_store().update_collection_fields(+ CollectionInfo(name="kb", documents=7), ("documents",)+ )+ )++ row = _row()+ assert row.documents == 7+ assert (row.embedding_model_id, row.embedding_dimension) == ("model-new", 8)+ assert row.extra_metadata == {"keep": "me"}+++def test_require_uninitialized_binds_an_unbound_row() -> None:+ _save(name="kb")++ applied = asyncio.run(+ get_metadata_store().update_collection_fields(+ CollectionInfo(+ name="kb", embedding_model_id="model-new", embedding_dimension=8+ ),+ ("embedding_model_id", "embedding_dimension"),+ require_uninitialized=True,+ )+ )++ assert applied is True+ assert (x := _row()).embedding_model_id == "model-new"+ assert x.embedding_dimension == 8+++def test_require_uninitialized_never_overwrites_a_binding() -> None:+ _save(name="kb", embedding_model_id="model-new", embedding_dimension=8)++ applied = asyncio.run(+ get_metadata_store().update_collection_fields(+ CollectionInfo(+ name="kb", embedding_model_id="model-old", embedding_dimension=4+ ),+ ("embedding_model_id", "embedding_dimension"),+ require_uninitialized=True,+ )+ )++ assert applied is False+ assert (row := _row()).embedding_model_id == "model-new"+ assert row.embedding_dimension == 8+++def test_expected_model_id_guards_a_rewrite() -> None:+ _save(name="kb", embedding_model_id="alias", embedding_dimension=4)++ applied = asyncio.run(+ get_metadata_store().update_collection_fields(+ CollectionInfo(+ name="kb", embedding_model_id="model-old", embedding_dimension=4+ ),+ ("embedding_model_id", "embedding_dimension"),+ expected_model_id="other",+ )+ )+ assert applied is False+ assert _row().embedding_model_id == "alias"++ applied = asyncio.run(+ get_metadata_store().update_collection_fields(+ CollectionInfo(+ name="kb", embedding_model_id="model-old", embedding_dimension=4+ ),+ ("embedding_model_id", "embedding_dimension"),+ expected_model_id="alias",+ )+ )+ assert applied is True+ assert _row().embedding_model_id == "model-old"+++def test_save_if_absent_inserts_a_new_row() -> None:+ inserted = asyncio.run(+ get_metadata_store().save_collection_if_absent(+ CollectionInfo(name="kb", documents=3)+ )+ )++ assert inserted is True+ assert _row().documents == 3+++def test_save_if_absent_never_overwrites_an_existing_row() -> None:+ _save(name="kb", embedding_model_id="model-new", embedding_dimension=8, documents=2)++ inserted = asyncio.run(+ get_metadata_store().save_collection_if_absent(+ CollectionInfo(+ name="kb", embedding_model_id="model-old", embedding_dimension=4+ )+ )+ )++ assert inserted is False+ row = _row()+ assert (row.embedding_model_id, row.embedding_dimension) == ("model-new", 8)+ assert row.documents == 2+++def test_require_uninitialized_repairs_a_half_bound_row() -> None:+ store = get_metadata_store()+ asyncio.run(+ store.save_collection_if_absent(+ CollectionInfo(name="kb", embedding_model_id="model-old")+ )+ )++ applied = asyncio.run(+ store.update_collection_fields(+ CollectionInfo(+ name="kb", embedding_model_id="model-new", embedding_dimension=8+ ),+ ("embedding_model_id", "embedding_dimension"),+ require_uninitialized=True,+ )+ )++ assert applied is True+ row = _row()+ assert (row.embedding_model_id, row.embedding_dimension) == ("model-new", 8)+++def test_missing_row_raises_unless_require_uninitialized() -> None:+ with pytest.raises(ValueError, match="not found"):+ asyncio.run(+ get_metadata_store().update_collection_fields(+ CollectionInfo(name="ghost", documents=1), ("documents",)+ )+ )++ applied = asyncio.run(+ get_metadata_store().update_collection_fields(+ CollectionInfo(name="ghost", embedding_model_id="m", embedding_dimension=1),+ ("embedding_model_id", "embedding_dimension"),+ require_uninitialized=True,+ )+ )+ assert applied is False+++def test_both_guards_are_rejected() -> None:+ _save(name="kb")++ with pytest.raises(ValueError, match="not both"):+ asyncio.run(+ get_metadata_store().update_collection_fields(+ CollectionInfo(+ name="kb", embedding_model_id="m", embedding_dimension=1+ ),+ ("embedding_model_id", "embedding_dimension"),+ require_uninitialized=True,+ expected_model_id="m",+ )+ )+++def test_unknown_or_key_fields_are_rejected() -> None:+ _save(name="kb")++ for field in ("name", "not_a_column"):+ with pytest.raises(ValueError, match="Cannot update"):+ asyncio.run(+ get_metadata_store().update_collection_fields(+ CollectionInfo(name="kb", documents=1), (field,)+ )+ )++ assert _row().documents == 0