Skip to content

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

feat(kb): give one run an owned migration window per collection (#3827)

蓝鱼bluefish842c4196a341
diff --git a/src/xagent/core/tools/core/RAG_tools/management/collection_manager.py b/src/xagent/core/tools/core/RAG_tools/management/collection_manager.py
index a1bf822ce..1ca4e9835 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
@@ -405,6 +405,7 @@ class CollectionManager:
*,
require_uninitialized: bool = False,
expected_model_id: Optional[str] = None,
+ expected_updated_at: Optional[datetime] = None,
store: Optional[MetadataStore] = None,
recreate_missing: bool = False,
) -> bool:
@@ -422,6 +423,7 @@ class CollectionManager:
field_names,
require_uninitialized=require_uninitialized,
expected_model_id=expected_model_id,
+ expected_updated_at=expected_updated_at,
store=store,
recreate_missing=recreate_missing,
)
@@ -433,6 +435,7 @@ class CollectionManager:
*,
require_uninitialized: bool = False,
expected_model_id: Optional[str] = None,
+ expected_updated_at: Optional[datetime] = None,
store: Optional[MetadataStore] = None,
recreate_missing: bool = False,
) -> bool:
@@ -445,6 +448,12 @@ class CollectionManager:
row to be re-inserted like the whole-row save it replaced.
"""
target = store if store is not None else self._get_metadata_store()
+ # Passed only when set: stores that predate the guard keep working.
+ fence = (
+ {}
+ if expected_updated_at is None
+ else {"expected_updated_at": expected_updated_at}
+ )
try:
return await _with_retry(
lambda: target.update_collection_fields(
@@ -452,6 +461,7 @@ class CollectionManager:
field_names,
require_uninitialized=require_uninitialized,
expected_model_id=expected_model_id,
+ **fence,
),
description=f"field update of collection {collection.name}",
deterministic=_is_deterministic_write_error,
@@ -476,6 +486,7 @@ class CollectionManager:
field_names,
require_uninitialized=require_uninitialized,
expected_model_id=expected_model_id,
+ expected_updated_at=expected_updated_at,
store=target,
)
@@ -1103,11 +1114,13 @@ def write_collection_binding_sync(
*,
expected_model_id: Optional[str] = None,
require_uninitialized: bool = False,
+ expected_updated_at: Optional[datetime] = None,
) -> 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.
+ a caller can tell its own write from a concurrent one. ``expected_updated_at``
+ also requires the row to be unchanged since the caller read it.
"""
state = read_migration_state(collection_name)
if state.state != FROZEN:
@@ -1126,6 +1139,7 @@ def write_collection_binding_sync(
_BINDING_FIELDS,
expected_model_id=expected_model_id,
require_uninitialized=require_uninitialized,
+ expected_updated_at=expected_updated_at,
)
if applied or not require_uninitialized:
return applied
@@ -1136,7 +1150,36 @@ def write_collection_binding_sync(
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
+ target,
+ _BINDING_FIELDS,
+ expected_model_id=stored,
+ expected_updated_at=expected_updated_at,
+ )
+
+
+def fence_collection_binding_sync(collection_name: str) -> None:
+ """Touch ``updated_at`` so a binding write guarded by an earlier read misses.
+
+ A missing row has nothing to fence. A touch that misses found the row
+ written since this read, which fences it as well.
+ """
+ _sync_wrapper(_fence_collection_binding)(collection_name)
+
+
+async def _fence_collection_binding(collection_name: str) -> None:
+ try:
+ # The store, not the manager: the manager reports any read error as missing.
+ current = await collection_manager._get_metadata_store().get_collection(
+ collection_name
+ )
+ except ValueError as exc:
+ if "not found" not in str(exc):
+ raise
+ return
+ await collection_manager.update_collection_fields(
+ CollectionInfo(name=collection_name),
+ (),
+ expected_updated_at=current.updated_at,
)
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.py
index 1bf232e2b..697e30075 100644
--- a/src/xagent/core/tools/core/RAG_tools/management/embedding_switch.py
+++ b/src/xagent/core/tools/core/RAG_tools/management/embedding_switch.py
@@ -26,8 +26,9 @@ from .collection_manager import (
from .migration_state import (
FROZEN,
CollectionMigrationState,
+ MigrationWindow,
read_migration_state,
- update_migration_state_if_frozen,
+ record_migration_transition,
)
logger = logging.getLogger(__name__)
@@ -65,25 +66,40 @@ def _resolve_configured_model(target_model_id: str) -> tuple[str, int]:
return canonical, config.dimension
+def _held_state(window: MigrationWindow) -> CollectionMigrationState:
+ state = read_migration_state(window.collection_name)
+ if state.state != FROZEN or (state.owner, state.updated_at) != (
+ window.owner,
+ window.updated_at,
+ ):
+ raise CollectionNotFrozenError(
+ f"Collection '{window.collection_name}' is not frozen by this run; "
+ "claim it first.",
+ details={
+ "collection": window.collection_name,
+ "migration_state": state.state,
+ },
+ )
+ return state
+
+
def switch_collection_embedding_model(
- collection_name: str, target_model_id: str
+ window: MigrationWindow, target_model_id: str
) -> CollectionEmbeddingSwitch:
- """Bind ``collection_name`` to ``target_model_id``.
+ """Bind the collection ``window`` holds to ``target_model_id``.
+
+ The source is the binding read here, after the claim. The transition is
+ recorded only while this run still holds the row version it wrote last, and
+ the binding moves only if the collection row is unchanged since that read.
Raises:
- CollectionNotFrozenError: If the collection is not frozen for migration.
+ CollectionNotFrozenError: If this run does not hold the window.
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.
+ the requested one, or the stored row 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},
- )
-
+ collection_name = window.collection_name
+ state = _held_state(window)
canonical_model_id, dimension = _resolve_configured_model(target_model_id)
stored = get_collection_sync(collection_name)
@@ -97,38 +113,32 @@ def switch_collection_embedding_model(
# 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"},
- )
+ record_migration_transition(window, source_model_id, canonical_model_id)
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.
+ # Exactly one binding 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,
+ expected_updated_at=stored.updated_at,
)
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:
+ current = get_collection_sync(collection_name)
+ # Both fields: a row bound to the target without a dimension is not switched.
+ if (
+ _normalize_model_id(current.embedding_model_id) != canonical_model_id
+ or current.embedding_dimension != dimension
+ ):
raise ValueError(
- f"Collection '{collection_name}' embedding model changed while "
- "switching; retry the switch."
+ f"Collection '{collection_name}' changed while switching; retry "
+ "the switch."
)
+ # The target is bound; accept that only while this run holds the window,
+ # or a taken-over run would report the new owner's switch as its own.
+ _held_state(window)
logger.info(
"Switched collection '%s' embedding model from '%s' to '%s'",
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 3d0f9a942..27879e6df 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
@@ -6,10 +6,11 @@ import asyncio
import functools
import logging
import time
+import uuid
from contextlib import asynccontextmanager, contextmanager
from contextvars import Context, ContextVar, copy_context
from dataclasses import dataclass, replace
-from datetime import datetime, timezone
+from datetime import datetime, timedelta, timezone
from typing import (
Any,
AsyncIterator,
@@ -29,7 +30,7 @@ import pyarrow as pa # type: ignore
from xagent.core.utils.blocking import run_blocking
-from ..core.exceptions import CollectionMigratingError
+from ..core.exceptions import CollectionMigratingError, CollectionNotFrozenError
from ..LanceDB.schema_manager import _safe_close_table
from ..storage.factory import get_metadata_store
from ..utils.lancedb_query_utils import list_table_names
@@ -43,6 +44,8 @@ from .write_leases import (
)
MIGRATION_TABLE = "collection_migration_state"
+# No collection can be named this, and the writers below refuse the name.
+_INSERT_GUARD = "/insert-guard"
IDLE = "idle"
FROZEN = "frozen"
WRITE_MAX_RETRIES = 3
@@ -73,18 +76,24 @@ _SCHEMA = pa.schema(
("source_model_id", pa.string()),
("target_model_id", pa.string()),
("updated_at", pa.timestamp("us")),
+ ("owner", pa.string()),
]
)
@dataclass(frozen=True)
class CollectionMigrationState:
- """Migration freeze state stored in its own LanceDB table."""
+ """Migration freeze state stored in its own LanceDB table.
+
+ ``owner`` is the run holding the frozen row's window, ``None`` when no run
+ does; only the window functions below write it.
+ """
state: str = IDLE
source_model_id: Optional[str] = None
target_model_id: Optional[str] = None
updated_at: Optional[datetime] = None
+ owner: Optional[str] = None
def to_row(self) -> Dict[str, Any]:
return {
@@ -104,13 +113,42 @@ def _row_state(row: Dict[str, Any]) -> str:
def _ensure_table(conn: Any) -> None:
- if MIGRATION_TABLE in list_table_names(conn):
+ if MIGRATION_TABLE not in list_table_names(conn):
+ try:
+ conn.create_table(MIGRATION_TABLE, schema=_SCHEMA)
+ return
+ except Exception:
+ if MIGRATION_TABLE not in list_table_names(conn):
+ raise
+ if _has_owner_column(conn):
return
+ table = conn.open_table(MIGRATION_TABLE)
try:
- conn.create_table(MIGRATION_TABLE, schema=_SCHEMA)
+ table.add_columns([pa.field("owner", pa.string())])
except Exception:
- if MIGRATION_TABLE not in list_table_names(conn):
+ # Of two racing upgrades LanceDB fails one; the column is there for it.
+ if not _has_owner_column(conn):
raise
+ finally:
+ _safe_close_table(table)
+
+
+def _has_owner_column(conn: Any) -> bool:
+ table = _open_listed_table(conn)
+ try:
+ return "owner" in table.schema.names
+ finally:
+ _safe_close_table(table)
+
+
+def _open_listed_table(conn: Any) -> Any:
+ for attempt in range(WRITE_MAX_RETRIES - 1):
+ try:
+ return conn.open_table(MIGRATION_TABLE)
+ except ValueError:
+ # Listed while another process is still committing its creation.
+ time.sleep(0.1 * (2**attempt))
+ return conn.open_table(MIGRATION_TABLE)
def _read_row(
@@ -140,6 +178,7 @@ def read_migration_state(
source_model_id=row.get("source_model_id"),
target_model_id=row.get("target_model_id"),
updated_at=row.get("updated_at"),
+ owner=row.get("owner"),
)
@@ -147,58 +186,38 @@ def write_migration_state(
collection_name: str,
state: CollectionMigrationState,
) -> CollectionMigrationState:
- """Store ``state`` for one collection; only this module writes the table."""
+ """Store ``state`` for a collection no run holds; only this module writes.
+
+ Raises:
+ CollectionMigratingError: If a run holds the collection's window.
+ """
+ _refuse_guard_name(collection_name)
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),
+ owner=None,
)
conn = get_metadata_store().get_raw_connection()
row = {"name": collection_name, **stamped.to_row()}
for attempt in range(WRITE_MAX_RETRIES - 1):
try:
- _merge_row(conn, row)
- return stamped
+ written = _merge_row(conn, row)
+ break
except Exception as exc:
# Retries any error; the final attempt below re-raises.
logger.warning(
"Retrying migration state write for %s: %s", collection_name, exc
)
time.sleep(0.1 * (2**attempt))
- _merge_row(conn, row)
+ else:
+ written = _merge_row(conn, row)
+ if not written:
+ raise _held_error(collection_name)
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:
@@ -207,27 +226,227 @@ def _update_row(conn: Any, where: str, values: Dict[str, Any]) -> bool:
_safe_close_table(table)
-def _merge_row(conn: Any, row: dict[str, Any]) -> None:
+def _merge_row(conn: Any, row: dict[str, Any]) -> bool:
_ensure_table(conn)
+ if _insert_new_row(conn, row):
+ return True
+ where = f"name = '{escape_lancedb_string(row['name'])}' AND owner IS NULL"
+ return _update_row(conn, where, {k: v for k, v in row.items() if k != "name"})
+
+
+def _insert_new_row(conn: Any, row: Dict[str, Any]) -> bool:
+ """Insert ``row`` only if its collection has no row yet; whether it did.
+
+ The same commit rewrites the guard row, so two racing inserts conflict in
+ LanceDB and the one it re-runs finds the other's row; plain inserts never
+ conflict, so both would land.
+ """
+ guard = {"name": _INSERT_GUARD, "state": IDLE, "updated_at": _next_stamp(None)}
table = conn.open_table(MIGRATION_TABLE)
try:
- table.merge_insert(
- ["name"]
- ).when_matched_update_all().when_not_matched_insert_all().execute([row])
+ if not table.search().where(f"name = '{_INSERT_GUARD}'").to_arrow().num_rows:
+ table.add(pa.Table.from_pylist([guard], schema=_SCHEMA))
+ result = (
+ table.merge_insert(["name"])
+ .when_matched_update_all(where=f"target.name = '{_INSERT_GUARD}'")
+ .when_not_matched_insert_all()
+ .execute(pa.Table.from_pylist([guard, row], schema=_SCHEMA))
+ )
finally:
_safe_close_table(table)
+ return bool(result.num_inserted_rows)
def clear_migration_state(collection_name: str) -> None:
- """Remove the collection's row; a missing table or row is a no-op."""
+ """Remove the collection's row unless a run holds it.
+
+ A missing table or row is a no-op.
+
+ Raises:
+ CollectionMigratingError: If a run holds the collection's window.
+ """
+ _refuse_guard_name(collection_name)
conn = get_metadata_store().get_raw_connection()
if MIGRATION_TABLE not in list_table_names(conn):
return
+ _ensure_table(conn)
table = conn.open_table(MIGRATION_TABLE)
try:
- table.delete(f"name = '{escape_lancedb_string(collection_name)}'")
+ table.delete(
+ f"name = '{escape_lancedb_string(collection_name)}' AND owner IS NULL"
+ )
finally:
_safe_close_table(table)
+ row = _read_row(collection_name)
+ if row is not None and row.get("owner") is not None:
+ raise _held_error(collection_name)
+
+
+@dataclass
+class MigrationWindow:
+ """One run's hold on a frozen collection.
+
+ ``updated_at`` is the row version this run wrote last: each owned write
+ must still find it and advances it in place.
+ """
+
+ collection_name: str
+ owner: str
+ updated_at: datetime
+
+
+def claim_migration_window(collection_name: str, *, holder: str) -> MigrationWindow:
+ """Freeze a collection no run holds, for one run named after ``holder``.
+
+ An absent or idle row is claimed; an idle row keeps its recorded
+ transition, the rollback origin of the last switch.
+
+ Raises:
+ CollectionMigratingError: If the row is frozen, or changed after it was
+ read; the details name its owner and when it was written.
+ """
+ _refuse_guard_name(collection_name)
+ conn = get_metadata_store().get_raw_connection()
+ _ensure_table(conn)
+ owner = f"{holder}:{uuid.uuid4().hex}"
+ row = _read_row(collection_name)
+ stamp = _next_stamp(None if row is None else row.get("updated_at"))
+ claim = {"state": FROZEN, "updated_at": stamp, "owner": owner}
+ if row is None:
+ claimed = _insert_new_row(conn, {"name": collection_name, **claim})
+ elif _row_state(row) == IDLE:
+ where = _version_is(
+ collection_name, IDLE, row.get("owner"), row.get("updated_at")
+ )
+ claimed = _update_row(conn, where, claim)
+ else:
+ claimed = False
+ if claimed:
+ # Decided on the row read back, not on the count of a commit LanceDB re-ran.
+ current = read_migration_state(collection_name)
+ claimed = (current.owner, current.updated_at) == (owner, stamp)
+ if not claimed:
+ raise _held_error(collection_name)
+ return MigrationWindow(collection_name, owner, stamp)
+
+
+def take_over_migration_window(
+ collection_name: str, observed: CollectionMigrationState, *, holder: str
+) -> MigrationWindow:
+ """Give the frozen row ``observed`` was read from to a new run.
+
+ The caller states that the run holding it is gone; nothing here checks
+ that. The row changes only while it is still exactly the one observed, and
+ the collection row is fenced before this returns, so a binding write the
+ previous run prepared can no longer land. If the fence fails, the row is
+ already taken but no window is returned: take it over again.
+
+ Raises:
+ CollectionNotFrozenError: If ``observed`` is not a frozen row.
+ CollectionMigratingError: If the row changed after it was observed.
+ """
+ _refuse_guard_name(collection_name)
+ if observed.state != FROZEN:
+ raise CollectionNotFrozenError(
+ f"Collection '{collection_name}' is not frozen; claim it instead.",
+ details={"collection": collection_name, "migration_state": observed.state},
+ )
+ conn = get_metadata_store().get_raw_connection()
+ _ensure_table(conn)
+ owner = f"{holder}:{uuid.uuid4().hex}"
+ stamp = _next_stamp(observed.updated_at)
+ where = _version_is(collection_name, FROZEN, observed.owner, observed.updated_at)
+ if not _update_row(conn, where, {"updated_at": stamp, "owner": owner}):
+ raise _held_error(collection_name)
+ # collection_manager imports this module.
+ from .collection_manager import fence_collection_binding_sync
+
+ fence_collection_binding_sync(collection_name)
+ return MigrationWindow(collection_name, owner, stamp)
+
+
+def record_migration_transition(
+ window: MigrationWindow,
+ source_model_id: Optional[str],
+ target_model_id: str,
+) -> None:
+ """Record the switch this run is about to apply, while it holds ``window``."""
+ _write_owned(
+ window,
+ {"source_model_id": source_model_id, "target_model_id": target_model_id},
+ )
+
+
+def release_migration_window(window: MigrationWindow) -> None:
+ """Unfreeze the collection; the recorded transition stays as rollback origin."""
+ _write_owned(window, {"state": IDLE, "owner": None})
+
+
+def _write_owned(window: MigrationWindow, values: Dict[str, Any]) -> None:
+ stamp = _next_stamp(window.updated_at)
+ where = _version_is(window.collection_name, FROZEN, window.owner, window.updated_at)
+ conn = get_metadata_store().get_raw_connection()
+ if not _update_row(conn, where, {**values, "updated_at": stamp}):
+ raise CollectionNotFrozenError(
+ f"Collection '{window.collection_name}' is no longer frozen by this "
+ "run; read its migration state before acting on it.",
+ details={
+ "collection": window.collection_name,
+ "owner": window.owner,
+ "migration_state": "not-owned",
+ },
+ )
+ window.updated_at = stamp
+
+
+def _refuse_guard_name(collection_name: str) -> None:
+ if collection_name == _INSERT_GUARD:
+ raise ValueError(f"'{_INSERT_GUARD}' is reserved by the migration table.")
+
+
+def _version_is(
+ collection_name: str,
+ state: str,
+ owner: Optional[str],
+ stamp: Optional[datetime],
+) -> str:
+ owner_sql = (
+ "owner IS NULL"
+ if owner is None
+ else f"owner = '{escape_lancedb_string(owner)}'"
+ )
+ stamp_sql = (
+ "updated_at IS NULL"
+ if stamp is None
+ else f"updated_at = timestamp '{stamp.strftime('%Y-%m-%d %H:%M:%S.%f')}'"
+ )
+ return (
+ f"name = '{escape_lancedb_string(collection_name)}' "
+ f"AND state = '{state}' AND {owner_sql} AND {stamp_sql}"
+ )
+
+
+def _next_stamp(previous: Optional[datetime]) -> datetime:
+ now = datetime.now(timezone.utc).replace(tzinfo=None)
+ if previous is None or now > previous:
+ return now
+ # A clock that did not advance must still change the row version.
+ return previous + timedelta(microseconds=1)
+
+
+def _held_error(collection_name: str) -> CollectionMigratingError:
+ current = read_migration_state(collection_name)
+ return CollectionMigratingError(
+ f"Knowledge base '{collection_name}' was not changed: its migration row "
+ f"is {current.state}, owner {current.owner or 'unrecorded'}, written "
+ f"{current.updated_at}.",
+ details={
+ "collection": collection_name,
+ "migration_state": current.state,
+ "owner": current.owner,
+ "updated_at": current.updated_at,
+ },
+ )
def verify_active_leases(collection: Optional[str] = None) -> None:
diff --git a/src/xagent/core/tools/core/RAG_tools/storage/contracts.py b/src/xagent/core/tools/core/RAG_tools/storage/contracts.py
index c9f0463a7..bab850fff 100644
--- a/src/xagent/core/tools/core/RAG_tools/storage/contracts.py
+++ b/src/xagent/core/tools/core/RAG_tools/storage/contracts.py
@@ -9,7 +9,7 @@ from __future__ import annotations
import logging
from abc import ABC, abstractmethod
from dataclasses import dataclass
-from datetime import timedelta
+from datetime import datetime, timedelta
from enum import Enum
from typing import (
Any,
@@ -338,6 +338,7 @@ class MetadataStore(ABC):
*,
require_uninitialized: bool = False,
expected_model_id: Optional[str] = None,
+ expected_updated_at: Optional[datetime] = None,
) -> bool:
"""Update only ``field_names`` of an existing collection row.
@@ -347,9 +348,11 @@ class MetadataStore(ABC):
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.
+ the alias-to-canonical rewrite), ``expected_updated_at`` means the row
+ was not written since it was read with that ``updated_at`` (a stored
+ NULL, never written since creation, also matches). A guarded update that
+ matches no row returns ``False`` instead of overwriting; an unguarded
+ update raises ``ValueError`` when the row is missing.
"""
@abstractmethod
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.py
index e9ecc93c5..15cb8525c 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
@@ -359,6 +359,7 @@ class LanceDBMetadataStore(MetadataStore):
*,
require_uninitialized: bool = False,
expected_model_id: Optional[str] = None,
+ expected_updated_at: Optional[datetime] = None,
) -> bool:
from ..LanceDB.schema_manager import _safe_close_table
@@ -389,6 +390,11 @@ class LanceDBMetadataStore(MetadataStore):
" AND embedding_model_id = "
f"'{escape_lancedb_string(expected_model_id)}'"
)
+ if expected_updated_at is not None:
+ stamp = expected_updated_at.strftime("%Y-%m-%d %H:%M:%S.%f")
+ # Every write sets updated_at, so NULL means no write since creation
+ # (a read reports it as the read time; see migrate_collection_metadata).
+ where += f" AND (updated_at = timestamp '{stamp}' OR updated_at IS NULL)"
table = conn.open_table("collection_metadata")
try:
updated = table.update(where, payload)
@@ -396,7 +402,11 @@ class LanceDBMetadataStore(MetadataStore):
_safe_close_table(table)
if updated.rows_updated:
return True
- if require_uninitialized or expected_model_id is not None:
+ if (
+ require_uninitialized
+ or expected_model_id is not None
+ or expected_updated_at is not None
+ ):
return False
raise ValueError(f"Collection '{collection.name}' not found")
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.py
index eb4cae0b8..018005d30 100644
--- a/tests/core/tools/core/RAG_tools/management/test_embedding_switch.py
+++ b/tests/core/tools/core/RAG_tools/management/test_embedding_switch.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
+from datetime import datetime
from types import SimpleNamespace
from typing import Any, Optional
@@ -29,9 +30,10 @@ from xagent.core.tools.core.RAG_tools.management.embedding_switch import (
from xagent.core.tools.core.RAG_tools.management.migration_state import (
FROZEN,
IDLE,
- CollectionMigrationState,
+ MigrationWindow,
+ claim_migration_window,
read_migration_state,
- write_migration_state,
+ release_migration_window,
)
from xagent.core.tools.core.RAG_tools.storage.factory import get_metadata_store
from xagent.core.tools.core.RAG_tools.utils import migration_utils
@@ -74,15 +76,16 @@ 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 _freeze(name: str = "kb") -> MigrationWindow:
+ return claim_migration_window(name, holder="test")
-def _switch(monkeypatch: pytest.MonkeyPatch, name: str = "kb") -> None:
+def _switch(monkeypatch: pytest.MonkeyPatch, name: str = "kb") -> MigrationWindow:
_save_sync(name)
- _freeze(name)
+ window = _freeze(name)
_bind_models(monkeypatch)
- switch_collection_embedding_model(name, NEW_MODEL)
+ switch_collection_embedding_model(window, NEW_MODEL)
+ return window
def _binding(name: str = "kb") -> tuple[Optional[str], Optional[int]]:
@@ -122,10 +125,10 @@ def test_switch_sets_both_binding_fields_and_records_the_transition(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_save_sync(documents=3)
- _freeze()
+ window = _freeze()
_bind_models(monkeypatch)
- result = switch_collection_embedding_model("kb", NEW_MODEL)
+ result = switch_collection_embedding_model(window, NEW_MODEL)
assert _binding() == (NEW_MODEL, NEW_DIM)
assert asyncio.run(cm.collection_manager.get_collection("kb")).documents == 3
@@ -140,7 +143,7 @@ def test_switch_writes_only_the_binding_columns(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_save_sync()
- _freeze()
+ window = _freeze()
_bind_models(monkeypatch)
store = get_metadata_store()
real_update = store.update_collection_fields
@@ -152,20 +155,21 @@ def test_switch_writes_only_the_binding_columns(
monkeypatch.setattr(store, "update_collection_fields", _spy)
- switch_collection_embedding_model("kb", NEW_MODEL)
+ switch_collection_embedding_model(window, 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
+ assert seen[0][1]["expected_updated_at"] is not None
def test_a_lost_race_on_the_same_target_is_a_success(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_save_sync()
- _freeze()
+ window = _freeze()
_bind_models(monkeypatch)
store = get_metadata_store()
real_update = store.update_collection_fields
@@ -178,7 +182,7 @@ def test_a_lost_race_on_the_same_target_is_a_success(
monkeypatch.setattr(store, "update_collection_fields", _lose_but_the_target_landed)
- result = switch_collection_embedding_model("kb", NEW_MODEL)
+ result = switch_collection_embedding_model(window, NEW_MODEL)
assert result.target_model_id == NEW_MODEL
assert _binding() == (NEW_MODEL, NEW_DIM)
@@ -189,31 +193,34 @@ def test_switch_refuses_a_collection_that_is_not_frozen(
) -> None:
_save_sync()
_bind_models(monkeypatch)
+ window = MigrationWindow("kb", "test:never-claimed", datetime.now())
with pytest.raises(CollectionNotFrozenError):
- switch_collection_embedding_model("kb", NEW_MODEL)
+ switch_collection_embedding_model(window, NEW_MODEL)
assert _binding() == (OLD_MODEL, OLD_DIM)
-def test_switch_refuses_an_idle_migration_record(
+def test_switch_refuses_a_released_window(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_save_sync()
- write_migration_state("kb", CollectionMigrationState(state=IDLE))
+ window = _freeze()
+ release_migration_window(window)
_bind_models(monkeypatch)
with pytest.raises(CollectionNotFrozenError):
- switch_collection_embedding_model("kb", NEW_MODEL)
+ switch_collection_embedding_model(window, NEW_MODEL)
assert _binding() == (OLD_MODEL, OLD_DIM)
+ assert read_migration_state("kb").state == IDLE
def test_switch_refuses_a_model_without_a_dimension(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_save_sync()
- _freeze()
+ window = _freeze()
monkeypatch.setattr(
es,
"_load_model_from_hub",
@@ -221,25 +228,25 @@ def test_switch_refuses_a_model_without_a_dimension(
)
with pytest.raises(ValueError, match="no dimension"):
- switch_collection_embedding_model("kb", NEW_MODEL)
+ switch_collection_embedding_model(window, 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")
+ window = _freeze("ghost")
_bind_models(monkeypatch)
with pytest.raises(ValueError):
- switch_collection_embedding_model("ghost", "new")
+ switch_collection_embedding_model(window, "new")
def test_switch_refuses_a_model_the_hub_does_not_configure(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_save_sync()
- _freeze()
+ window = _freeze()
_bind_models(monkeypatch)
def _missing(*_: Any) -> None:
@@ -248,7 +255,7 @@ def test_switch_refuses_a_model_the_hub_does_not_configure(
monkeypatch.setattr(es, "_load_model_from_hub", _missing)
with pytest.raises(EmbeddingAdapterError):
- switch_collection_embedding_model("kb", NEW_MODEL)
+ switch_collection_embedding_model(window, NEW_MODEL)
assert _binding() == (OLD_MODEL, OLD_DIM)
assert read_migration_state("kb").target_model_id is None
@@ -258,7 +265,7 @@ def test_switch_refuses_an_alias_instead_of_binding_another_id(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_save_sync()
- _freeze()
+ window = _freeze()
_bind_models(monkeypatch)
monkeypatch.setattr(
es,
@@ -267,7 +274,7 @@ def test_switch_refuses_an_alias_instead_of_binding_another_id(
)
with pytest.raises(ValueError, match="configured model id"):
- switch_collection_embedding_model("kb", "new-alias")
+ switch_collection_embedding_model(window, "new-alias")
assert _binding() == (OLD_MODEL, OLD_DIM)
assert read_migration_state("kb").target_model_id is None
@@ -277,7 +284,7 @@ def test_switch_raises_when_the_binding_moves_under_it(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_save_sync()
- _freeze()
+ window = _freeze()
_bind_models(monkeypatch)
async def _lost(*_: Any, **__: Any) -> bool:
@@ -286,28 +293,60 @@ def test_switch_raises_when_the_binding_moves_under_it(
monkeypatch.setattr(get_metadata_store(), "update_collection_fields", _lost)
with pytest.raises(ValueError, match="changed while switching"):
- switch_collection_embedding_model("kb", NEW_MODEL)
+ switch_collection_embedding_model(window, NEW_MODEL)
assert _binding() == (OLD_MODEL, OLD_DIM)
+def test_a_touched_partial_binding_is_not_reported_as_switched(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ asyncio.run(
+ cm.collection_manager.save_collection(
+ CollectionInfo(name="kb", embedding_model_id=NEW_MODEL)
+ )
+ )
+ window = _freeze()
+ _bind_models(monkeypatch)
+ real_get = es.get_collection_sync
+ reads: list[str] = []
+
+ def _touch_after_the_first_read(name: str) -> CollectionInfo:
+ row = real_get(name)
+ if not reads:
+ cm.mark_collection_accessed_sync(name)
+ reads.append(name)
+ return row
+
+ monkeypatch.setattr(es, "get_collection_sync", _touch_after_the_first_read)
+
+ with pytest.raises(ValueError, match="changed while switching"):
+ switch_collection_embedding_model(window, NEW_MODEL)
+ assert _binding() == (NEW_MODEL, None)
+
+ result = switch_collection_embedding_model(window, NEW_MODEL)
+
+ assert result.target_dimension == NEW_DIM
+ assert _binding() == (NEW_MODEL, NEW_DIM)
+
+
def test_switch_refuses_a_collection_unfrozen_while_switching(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_save_sync()
- _freeze()
+ window = _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))
+ release_migration_window(window)
return row
monkeypatch.setattr(es, "get_collection_sync", _unfreeze_during_read)
- with pytest.raises(CollectionNotFrozenError, match="unfrozen"):
- switch_collection_embedding_model("kb", NEW_MODEL)
+ with pytest.raises(CollectionNotFrozenError, match="no longer frozen"):
+ switch_collection_embedding_model(window, NEW_MODEL)
assert _binding() == (OLD_MODEL, OLD_DIM)
assert read_migration_state("kb").state == IDLE
@@ -342,8 +381,8 @@ def test_stats_update_persists_the_migrated_schema_version() -> None:
def test_rollback_is_the_same_call_with_the_previous_model(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- _switch(monkeypatch)
- switch_collection_embedding_model("kb", OLD_MODEL)
+ window = _switch(monkeypatch)
+ switch_collection_embedding_model(window, OLD_MODEL)
assert _binding() == (OLD_MODEL, OLD_DIM)
state = read_migration_state("kb")
@@ -481,10 +520,10 @@ def test_switch_repairs_a_whitespace_binding(
)
)
)
- _freeze()
+ window = _freeze()
_bind_models(monkeypatch)
- result = switch_collection_embedding_model("kb", NEW_MODEL)
+ result = switch_collection_embedding_model(window, NEW_MODEL)
assert _binding() == (NEW_MODEL, NEW_DIM)
assert result.source_model_id is None
@@ -669,9 +708,9 @@ def test_metadata_rebuild_cannot_clear_a_switch(
def test_reapplying_a_switch_keeps_the_rollback_origin(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- _switch(monkeypatch)
+ window = _switch(monkeypatch)
- result = switch_collection_embedding_model("kb", NEW_MODEL)
+ result = switch_collection_embedding_model(window, NEW_MODEL)
assert result.source_model_id == OLD_MODEL
state = read_migration_state("kb")
@@ -683,11 +722,11 @@ 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()
+ window = _freeze()
_bind_models(monkeypatch)
- first = switch_collection_embedding_model("kb", NEW_MODEL)
- second = switch_collection_embedding_model("kb", NEW_MODEL)
+ first = switch_collection_embedding_model(window, NEW_MODEL)
+ second = switch_collection_embedding_model(window, NEW_MODEL)
assert first.source_model_id is None
assert second.source_model_id is None
diff --git a/tests/core/tools/core/RAG_tools/management/test_migration_window.py b/tests/core/tools/core/RAG_tools/management/test_migration_window.py
new file mode 100644
index 000000000..2be222f71
--- /dev/null
+++ b/tests/core/tools/core/RAG_tools/management/test_migration_window.py
@@ -0,0 +1,571 @@
+"""One run's migration window: claim, owned writes, take-over and binding fence.
+
+Every case runs on real LanceDB; the races run in separate processes.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import multiprocessing
+from dataclasses import replace
+from types import SimpleNamespace
+from typing import Any, Callable, Optional
+
+import lancedb
+import pyarrow as pa
+import pytest
+
+from xagent.core.tools.core.RAG_tools.core.exceptions import (
+ CollectionMigratingError,
+ CollectionNotFrozenError,
+)
+from xagent.core.tools.core.RAG_tools.core.schemas import CollectionInfo
+from xagent.core.tools.core.RAG_tools.management import collection_manager as cm
+from xagent.core.tools.core.RAG_tools.management import embedding_switch as es
+from xagent.core.tools.core.RAG_tools.management import migration_state as state_module
+from xagent.core.tools.core.RAG_tools.management.migration_state import (
+ FROZEN,
+ IDLE,
+ MIGRATION_TABLE,
+ CollectionMigrationState,
+ MigrationWindow,
+ claim_migration_window,
+ clear_migration_state,
+ ensure_collection_writable,
+ read_migration_state,
+ record_migration_transition,
+ release_migration_window,
+ take_over_migration_window,
+ write_migration_state,
+)
+from xagent.core.tools.core.RAG_tools.storage.factory import get_metadata_store
+from xagent.core.tools.core.RAG_tools.utils.string_utils import (
+ validate_collection_name,
+)
+
+OLD_MODEL, OLD_DIM = "model-old", 4
+NEW_MODEL, NEW_DIM = "model-new", 8
+_OLD_SCHEMA = pa.schema(
+ [
+ ("name", pa.string()),
+ ("state", pa.string()),
+ ("source_model_id", pa.string()),
+ ("target_model_id", pa.string()),
+ ("updated_at", pa.timestamp("us")),
+ ]
+)
+
+
+def _conn() -> Any:
+ return get_metadata_store().get_raw_connection()
+
+
+def _rows(name: str) -> list[dict[str, Any]]:
+ table = lancedb.connect(_conn().uri).open_table(MIGRATION_TABLE)
+ return table.search().where(f"name = '{name}'").to_arrow().to_pylist()
+
+
+def _bind_models(monkeypatch: pytest.MonkeyPatch) -> None:
+ models = {OLD_MODEL: OLD_DIM, NEW_MODEL: NEW_DIM}
+ monkeypatch.setattr(
+ es,
+ "_load_model_from_hub",
+ lambda model_id, *_: SimpleNamespace(id=model_id, dimension=models[model_id]),
+ )
+
+
+def _save(name: str = "kb") -> None:
+ asyncio.run(
+ cm.collection_manager.save_collection(
+ CollectionInfo(
+ name=name, embedding_model_id=OLD_MODEL, embedding_dimension=OLD_DIM
+ )
+ )
+ )
+
+
+def _save_legacy(name: str = "kb") -> None:
+ asyncio.run(get_metadata_store().ensure_collection_metadata_table())
+ table = _conn().open_table("collection_metadata")
+ row = {
+ "name": name,
+ "schema_version": "0.0.0",
+ "embedding_model_id": OLD_MODEL,
+ "embedding_dimension": OLD_DIM,
+ "documents": 0,
+ "embeddings": 0,
+ "document_names": "[]",
+ "extra_metadata": "{}",
+ }
+ table.add(pa.Table.from_pylist([row], schema=table.schema))
+ stored = table.search().where(f"name = '{name}'").to_arrow()
+ assert stored["updated_at"].to_pylist() == [None]
+
+
+def _binding(name: str = "kb") -> Optional[str]:
+ return asyncio.run(cm.collection_manager.get_collection(name)).embedding_model_id
+
+
+def _claim_or_report(holder: str, name: str) -> Optional[str]:
+ try:
+ return claim_migration_window(name, holder=holder).owner
+ except CollectionMigratingError:
+ return None
+ except Exception as exc:
+ # Reported, not raised: a raising process strands the others at the barrier.
+ return f"error: {exc!r}"
+
+
+def _claim_rounds(holder: str, names: list[str], start: Any) -> list[Any]:
+ won = []
+ for name in names:
+ start.wait()
+ won.append(_claim_or_report(holder, name))
+ return won
+
+
+def _race_claims(names: list[str], runs: int = 4) -> list[list[Any]]:
+ spawn = multiprocessing.get_context("spawn")
+ with spawn.Manager() as manager:
+ start = manager.Barrier(runs)
+ with spawn.Pool(runs) as pool:
+ results = [
+ pool.apply_async(_claim_rounds, (f"run{i}", names, start))
+ for i in range(runs)
+ ]
+ return [result.get(timeout=240) for result in results]
+
+
+def _assert_one_winner_each(names: list[str], outcomes: list[list[Any]]) -> None:
+ assert not [o for won in outcomes for o in won if str(o).startswith("error")]
+ for index, name in enumerate(names):
+ winners = [won[index] for won in outcomes if won[index] is not None]
+ assert len(winners) == 1, (name, outcomes)
+ rows = _rows(name)
+ assert len(rows) == 1, (name, rows)
+ assert rows[0]["state"] == FROZEN
+ assert rows[0]["owner"] == winners[0]
+
+
+def test_concurrent_first_claims_have_exactly_one_winner() -> None:
+ names = [f"fresh{i}" for i in range(4)]
+
+ _assert_one_winner_each(names, _race_claims(names))
+
+
+def test_concurrent_claims_of_an_idle_row_have_exactly_one_winner() -> None:
+ names = [f"idle{i}" for i in range(4)]
+ for name in names:
+ write_migration_state(name, CollectionMigrationState(state=IDLE))
+
+ _assert_one_winner_each(names, _race_claims(names))
+
+
+def _old_table(*rows: dict[str, Any]) -> None:
+ _conn().create_table(MIGRATION_TABLE, schema=_OLD_SCHEMA).add(
+ pa.Table.from_pylist(list(rows), schema=_OLD_SCHEMA)
+ )
+
+
+def test_an_old_table_is_read_unchanged_and_upgraded_by_concurrent_claims() -> None:
+ legacy = {"name": "legacy", "state": FROZEN, "target_model_id": NEW_MODEL}
+ _old_table(legacy, {"name": "done", "state": IDLE, "source_model_id": OLD_MODEL})
+
+ assert read_migration_state("legacy").state == FROZEN
+ assert "owner" not in _conn().open_table(MIGRATION_TABLE).schema.names
+
+ names = [f"upgrade{i}" for i in range(4)]
+ outcomes = _race_claims_one_name_each(names)
+
+ assert all(o and not o.startswith("error") for o in outcomes), outcomes
+ assert "owner" in _conn().open_table(MIGRATION_TABLE).schema.names
+ assert read_migration_state("legacy") == CollectionMigrationState(
+ state=FROZEN, target_model_id=NEW_MODEL
+ )
+ assert read_migration_state("done").source_model_id == OLD_MODEL
+
+
+def _claim_one(holder: str, name: str, start: Any) -> Optional[str]:
+ start.wait()
+ return _claim_or_report(holder, name)
+
+
+def _race_claims_one_name_each(names: list[str]) -> list[Any]:
+ spawn = multiprocessing.get_context("spawn")
+ with spawn.Manager() as manager:
+ start = manager.Barrier(len(names))
+ with spawn.Pool(len(names)) as pool:
+ results = [
+ pool.apply_async(_claim_one, (f"run{i}", name, start))
+ for i, name in enumerate(names)
+ ]
+ return [result.get(timeout=240) for result in results]
+
+
+def test_a_claim_waits_for_a_table_another_process_is_still_creating(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ write_migration_state("other", CollectionMigrationState(state=IDLE))
+ real_conn = _conn()
+ opens = []
+
+ class _CreatedElsewhere:
+ def __getattr__(self, name: str) -> Any:
+ if name != "open_table":
+ return getattr(real_conn, name)
+
+ def _open(table_name: str) -> Any:
+ opens.append(table_name)
+ if len(opens) == 1:
+ raise ValueError(f"Table '{table_name}' was not found")
+ return real_conn.open_table(table_name)
+
+ return _open
+
+ monkeypatch.setattr(
+ state_module,
+ "get_metadata_store",
+ lambda: SimpleNamespace(get_raw_connection=lambda: _CreatedElsewhere()),
+ )
+
+ window = claim_migration_window("kb", holder="first")
+
+ assert len(opens) > 1
+ assert read_migration_state("kb").owner == window.owner
+
+
+def test_a_frozen_collection_is_refused_with_its_owner_and_time() -> None:
+ window = claim_migration_window("kb", holder="first")
+
+ with pytest.raises(CollectionMigratingError) as refused:
+ claim_migration_window("kb", holder="second")
+
+ assert refused.value.details["owner"] == window.owner
+ assert refused.value.details["updated_at"] == window.updated_at
+ assert read_migration_state("kb").owner == window.owner
+
+
+def test_a_claim_keeps_the_rollback_origin_and_admission_sees_it() -> None:
+ window = claim_migration_window("kb", holder="first")
+ record_migration_transition(window, OLD_MODEL, NEW_MODEL)
+ release_migration_window(window)
+ ensure_collection_writable("kb")
+
+ claim_migration_window("kb", holder="second")
+
+ state = read_migration_state("kb")
+ assert (state.source_model_id, state.target_model_id) == (OLD_MODEL, NEW_MODEL)
+ with pytest.raises(CollectionMigratingError):
+ ensure_collection_writable("kb")
+
+
+def test_a_claim_loses_when_the_idle_row_changed_after_its_read(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ write_migration_state("kb", CollectionMigrationState(state=IDLE))
+ real_read = state_module._read_row
+ reads = []
+
+ def _read_then_rewrite(name: str, store: Any = None) -> Any:
+ row = real_read(name, store)
+ if not reads:
+ reads.append(row)
+ write_migration_state(name, CollectionMigrationState(state=IDLE))
+ return row
+
+ monkeypatch.setattr(state_module, "_read_row", _read_then_rewrite)
+
+ with pytest.raises(CollectionMigratingError):
+ claim_migration_window("kb", holder="late")
+
+ assert read_migration_state("kb").owner is None
+ assert read_migration_state("kb").state == IDLE
+
+
+def test_a_claim_trusts_the_row_it_reads_back_over_a_reported_insert(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ first = claim_migration_window("kb", holder="first")
+ real_read = state_module._read_row
+ reads = []
+
+ def _absent_on_first_read(name: str, store: Any = None) -> Any:
+ reads.append(name)
+ return None if len(reads) == 1 else real_read(name, store)
+
+ monkeypatch.setattr(state_module, "_read_row", _absent_on_first_read)
+ monkeypatch.setattr(state_module, "_insert_new_row", lambda *_: True)
+
+ with pytest.raises(CollectionMigratingError):
+ claim_migration_window("kb", holder="second")
+
+ assert read_migration_state("kb").owner == first.owner
+
+
+def test_owned_writes_refuse_another_owner_at_the_same_version() -> None:
+ window = claim_migration_window("kb", holder="first")
+ intruder = MigrationWindow("kb", "intruder", window.updated_at)
+
+ with pytest.raises(CollectionNotFrozenError):
+ record_migration_transition(intruder, OLD_MODEL, NEW_MODEL)
+ with pytest.raises(CollectionNotFrozenError):
+ release_migration_window(intruder)
+
+ state = read_migration_state("kb")
+ assert (state.state, state.owner, state.target_model_id) == (
+ FROZEN,
+ window.owner,
+ None,
+ )
+
+
+def test_owned_writes_refuse_a_version_the_owner_already_moved_past() -> None:
+ window = claim_migration_window("kb", holder="first")
+ stale = replace(window)
+ record_migration_transition(window, OLD_MODEL, NEW_MODEL)
+
+ with pytest.raises(CollectionNotFrozenError):
+ record_migration_transition(stale, NEW_MODEL, OLD_MODEL)
+ with pytest.raises(CollectionNotFrozenError):
+ release_migration_window(stale)
+
+ state = read_migration_state("kb")
+ assert (state.state, state.source_model_id) == (FROZEN, OLD_MODEL)
+ assert state.updated_at == window.updated_at
+
+
+def test_a_take_over_is_refused_once_the_observed_row_changed() -> None:
+ window = claim_migration_window("kb", holder="first")
+ observed = read_migration_state("kb")
+ record_migration_transition(window, OLD_MODEL, NEW_MODEL)
+
+ with pytest.raises(CollectionMigratingError):
+ take_over_migration_window("kb", observed, holder="operator")
+
+ release_migration_window(window)
+ assert read_migration_state("kb").state == IDLE
+
+
+def test_a_take_over_is_refused_for_another_owner_at_the_same_version() -> None:
+ claim_migration_window("kb", holder="first")
+ observed = replace(read_migration_state("kb"), owner="someone-else")
+
+ with pytest.raises(CollectionMigratingError):
+ take_over_migration_window("kb", observed, holder="operator")
+
+
+def test_a_taken_over_run_can_no_longer_write_and_the_taker_can() -> None:
+ window = claim_migration_window("kb", holder="first")
+ record_migration_transition(window, OLD_MODEL, NEW_MODEL)
+
+ taker = take_over_migration_window(
+ "kb", read_migration_state("kb"), holder="operator"
+ )
+
+ with pytest.raises(CollectionNotFrozenError):
+ release_migration_window(window)
+ state = read_migration_state("kb")
+ assert (state.state, state.owner) == (FROZEN, taker.owner)
+ assert (state.source_model_id, state.target_model_id) == (OLD_MODEL, NEW_MODEL)
+ release_migration_window(taker)
+ assert read_migration_state("kb").state == IDLE
+
+
+def test_a_take_over_of_an_idle_row_is_refused() -> None:
+ write_migration_state("kb", CollectionMigrationState(state=IDLE))
+
+ with pytest.raises(CollectionNotFrozenError):
+ take_over_migration_window("kb", read_migration_state("kb"), holder="op")
+
+
+def test_an_unowned_frozen_row_from_an_old_table_can_be_taken_over() -> None:
+ _old_table({"name": "legacy", "state": FROZEN, "source_model_id": OLD_MODEL})
+
+ window = take_over_migration_window(
+ "legacy", read_migration_state("legacy"), holder="operator"
+ )
+ release_migration_window(window)
+
+ state = read_migration_state("legacy")
+ assert (state.state, state.owner, state.source_model_id) == (
+ IDLE,
+ None,
+ OLD_MODEL,
+ )
+
+
+def test_unowned_writers_refuse_a_held_window() -> None:
+ window = claim_migration_window("kb", holder="first")
+
+ with pytest.raises(CollectionMigratingError):
+ write_migration_state("kb", CollectionMigrationState(state=IDLE))
+ with pytest.raises(CollectionMigratingError):
+ clear_migration_state("kb")
+
+ state = read_migration_state("kb")
+ assert (state.state, state.owner) == (FROZEN, window.owner)
+ release_migration_window(window)
+ clear_migration_state("kb")
+ assert _rows("kb") == []
+
+
+def test_a_stale_run_cannot_replace_the_record_of_a_later_switch(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _save()
+ _bind_models(monkeypatch)
+ stalled = claim_migration_window("kb", holder="stalled")
+ es.switch_collection_embedding_model(stalled, NEW_MODEL)
+
+ later = take_over_migration_window(
+ "kb", read_migration_state("kb"), holder="operator"
+ )
+ release_migration_window(later)
+ again = claim_migration_window("kb", holder="later")
+ es.switch_collection_embedding_model(again, OLD_MODEL)
+ release_migration_window(again)
+
+ with pytest.raises(CollectionNotFrozenError):
+ release_migration_window(stalled)
+ with pytest.raises(CollectionNotFrozenError):
+ es.switch_collection_embedding_model(stalled, NEW_MODEL)
+ state = read_migration_state("kb")
+ assert (state.state, state.source_model_id, state.target_model_id) == (
+ IDLE,
+ NEW_MODEL,
+ OLD_MODEL,
+ )
+ assert _binding() == OLD_MODEL
+
+
+def test_the_switch_records_the_binding_read_after_the_claim(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _save()
+ _bind_models(monkeypatch)
+ first = claim_migration_window("kb", holder="first")
+ es.switch_collection_embedding_model(first, NEW_MODEL)
+ release_migration_window(first)
+
+ second = claim_migration_window("kb", holder="second")
+ result = es.switch_collection_embedding_model(second, OLD_MODEL)
+
+ assert result.source_model_id == NEW_MODEL
+ assert read_migration_state("kb").source_model_id == NEW_MODEL
+ assert _binding() == OLD_MODEL
+
+
+def _take_over_after_the_frozen_check(
+ monkeypatch: pytest.MonkeyPatch, then: Callable[[MigrationWindow], Any]
+) -> None:
+ real_read = cm.read_migration_state
+
+ def _taken_over_after_the_check(name: str) -> Any:
+ state = real_read(name)
+ monkeypatch.setattr(cm, "read_migration_state", real_read)
+ then(take_over_migration_window(name, real_read(name), holder="operator"))
+ return state
+
+ monkeypatch.setattr(cm, "read_migration_state", _taken_over_after_the_check)
+
+
[email protected]("save", [_save, _save_legacy], ids=["row", "legacy-row"])
+def test_a_flip_prepared_before_a_take_over_cannot_land_after_it(
+ monkeypatch: pytest.MonkeyPatch, save: Callable[[], None]
+) -> None:
+ save()
+ _bind_models(monkeypatch)
+ stalled = claim_migration_window("kb", holder="stalled")
+ _take_over_after_the_frozen_check(monkeypatch, release_migration_window)
+
+ with pytest.raises(ValueError, match="changed while switching"):
+ es.switch_collection_embedding_model(stalled, NEW_MODEL)
+
+ assert _binding() == OLD_MODEL
+ assert read_migration_state("kb").state == IDLE
+
+
+def test_a_taken_over_run_is_refused_even_once_its_target_is_bound(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _save()
+ _bind_models(monkeypatch)
+ stalled = claim_migration_window("kb", holder="stalled")
+
+ def _switch_and_release(taker: MigrationWindow) -> None:
+ es.switch_collection_embedding_model(taker, NEW_MODEL)
+ release_migration_window(taker)
+
+ _take_over_after_the_frozen_check(monkeypatch, _switch_and_release)
+
+ with pytest.raises(CollectionNotFrozenError):
+ es.switch_collection_embedding_model(stalled, NEW_MODEL)
+
+ assert _binding() == NEW_MODEL
+ state = read_migration_state("kb")
+ assert (state.state, state.source_model_id, state.target_model_id) == (
+ IDLE,
+ OLD_MODEL,
+ NEW_MODEL,
+ )
+
+
+def test_a_legacy_row_never_written_since_creation_can_be_switched(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _save_legacy()
+ _bind_models(monkeypatch)
+ window = claim_migration_window("kb", holder="first")
+
+ es.switch_collection_embedding_model(window, NEW_MODEL)
+
+ assert _binding() == NEW_MODEL
+
+
+def test_a_take_over_of_a_collection_without_a_metadata_row_succeeds(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ window = claim_migration_window("ghost", holder="first")
+
+ taker = take_over_migration_window(
+ "ghost", read_migration_state("ghost"), holder="operator"
+ )
+
+ assert read_migration_state("ghost").owner == taker.owner != window.owner
+ assert [r.getMessage() for r in caplog.records if r.levelno >= logging.ERROR] == []
+
+
+def test_the_insert_guard_row_cannot_be_a_collection() -> None:
+ claim_migration_window("kb", holder="first")
+
+ table = _conn().open_table(MIGRATION_TABLE)
+ others = {row["name"] for row in table.to_arrow().to_pylist()} - {"kb"}
+
+ assert len(others) == 1
+ with pytest.raises(ValueError):
+ validate_collection_name(others.pop())
+
+
+ "write",
+ [
+ lambda name: claim_migration_window(name, holder="run"),
+ lambda name: take_over_migration_window(
+ name, CollectionMigrationState(state=FROZEN), holder="run"
+ ),
+ lambda name: write_migration_state(name, CollectionMigrationState(FROZEN)),
+ clear_migration_state,
+ ],
+ ids=["claim", "take-over", "write", "clear"],
+)
+def test_every_writer_refuses_the_insert_guard_name(
+ write: Callable[[str], Any],
+) -> None:
+ claim_migration_window("kb", holder="first")
+ version = _conn().open_table(MIGRATION_TABLE).version
+
+ with pytest.raises(ValueError, match="reserved"):
+ write(state_module._INSERT_GUARD)
+
+ assert _conn().open_table(MIGRATION_TABLE).version == version