Skip to content

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

feat(memory): re-embed the memory store into an explicit vector space (#3756)

蓝鱼bluefish21cf88e3d70f
diff --git a/docs/deployment.md b/docs/deployment.md
index dbf84d35a..88679939b 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -672,8 +672,7 @@ Restoring vector search is offline work, and it does not happen by itself:
authority back at the identity the stored vectors were written under, or
keep the current authority and re-embed the data to match it.
2. If re-embedding: quiesce all writers, back up the memory LanceDB directory,
- and re-embed every row offline under the current authority. Do not re-embed
- in place, and do not start a worker to do it.
+ and run `reembed_memory_table` (below) against the current authority.
3. Restart every worker together. Confirm `mode` is `vector` and
`supports_vector_search` is `true`.
@@ -682,6 +681,67 @@ as it is a deliberate one: semantic recall stays off until the step above is
done, and every note written in the meantime will need the same offline
re-embed before it becomes semantically searchable.
+### Re-embedding the memory table into a new vector space
+
+`reembed_memory_table` (`xagent.core.memory.embedding_migration`) is the
+offline step above. Run it with every writer stopped:
+
+```python
+from xagent.core.memory.embedding_migration import reembed_memory_table
+from xagent.core.model.embedding import create_embedding_adapter
+from xagent.providers.vector_store.lancedb import get_connection
+from xagent.web.memory_lifecycle import authority_embedding_config, memory_store_dir
+
+config = authority_embedding_config(snapshot) # read the global memory authority
+outcome = reembed_memory_table(
+ get_connection(memory_store_dir()),
+ "memories",
+ config,
+ encode=create_embedding_adapter(config).encode,
+)
+```
+
+It recomputes every note into `<table>__migrate_<identity>`, then verifies that
+table against the live one (same ids, same row count, a vector on every note
+that has text, and the target vector space declared in its schema). Notes with
+blank text are never encoded, matching how they were written. Only a verified
+table replaces the live one; otherwise the live table keeps serving and the
+outcome says what fell short. A run interrupted by its own failure resumes from
+the staging table and only embeds notes it is still missing. On a table that
+already declares the target space, a run only embeds, in place, notes that
+have text but no vector (`already_target`, with their count in
+`reembedded_rows`).
+
+Two tables are left behind on purpose:
+
+* `memories__pre_migrate_<identity>` holds the previous vectors and the previous
+ declared space.
+* `memories__migrate_<identity>` remains only when the run did not complete, so
+ the next run resumes it; delete it once you have decided not to retry. It is
+ also dropped automatically once the live table already declares the target
+ space or a run swaps it in.
+
+Writers must be stopped. The routine still re-reads the live table at its
+current version, carries notes written before its last version check, and
+refuses to swap while writers keep committing (`not_converged`). A write that
+commits during the swap itself — one table commit — is not carried over, and a
+note deleted in that instant can reappear. The run detects that case from the
+version the swap committed at and returns `swapped_over_a_write` instead of
+`complete`, keeping the backup; the detail names the live table versions that
+still hold the write (`table.checkout(version)`). Nothing in the memory write path
+takes a lock, so quiescence is what closes that window; do not treat the
+routine as safe next to live writers. Also do not run it next to admission: it
+waits for the same maintenance lock and fails with a lock timeout instead of
+running beside it.
+
+Rolling back: run the same routine with the previous identity and an adapter
+for the previous model. That re-embeds every note, including notes written
+after the migration, so nothing is lost. Restoring
+`memories__pre_migrate_<identity>` with `create_table("memories", data=...,
+mode="overwrite")` also works and is faster, but it discards every note written
+after the migration; use it only when you know there are none. Keep the backup
+until the new space has proven itself in production.
+
### Repairing BLOCKED_REPAIR
`blocked_repair` means admission found invalid legacy data (a NULL, empty or
diff --git a/src/xagent/core/memory/__init__.py b/src/xagent/core/memory/__init__.py
index 85c2a0797..e79b134f2 100644
--- a/src/xagent/core/memory/__init__.py
+++ b/src/xagent/core/memory/__init__.py
@@ -3,6 +3,8 @@ from .access_scope import bind_memory_access_scope as bind_memory_access_scope
from .base import MemoryStore as MemoryStore
from .core import MemoryNote as MemoryNote
from .core import MemoryResponse as MemoryResponse
+from .embedding_migration import MemoryReembedStatus as MemoryReembedStatus
+from .embedding_migration import reembed_memory_table as reembed_memory_table
from .lancedb import LanceDBMemoryStore as LanceDBMemoryStore
from .lancedb_maintenance import (
maintain_lancedb_memory_table as maintain_lancedb_memory_table,
diff --git a/src/xagent/core/memory/embedding_migration.py b/src/xagent/core/memory/embedding_migration.py
new file mode 100644
index 000000000..805ed79f9
--- /dev/null
+++ b/src/xagent/core/memory/embedding_migration.py
@@ -0,0 +1,734 @@
+"""Offline re-embedding migration for the LanceDB memory store.
+
+Recomputes every note's vector under one target identity into a staging table,
+verifies it against the live table, and only then replaces the live table in a
+single atomic overwrite. A config change alone cannot do this: when the old and
+new embeddings share a dimension, nothing else in the store notices.
+
+Invariant: the live table is replaced only by a table whose every note with
+text carries a vector produced by ``target_identity`` (notes with blank text
+carry none, as on the write path), which declares that space, and whose
+ids and row count match the source. Any shortfall leaves the live table alone;
+the previous vectors stay in the backup table for rollback. Writers must be
+quiesced (``docs/deployment.md``): the routine carries rows written before its
+last version check and refuses to swap while they keep arriving, but a write
+that commits during the swap's own table commit is not carried: no lock in the
+write path closes that window, so it is detected and reported instead.
+"""
+
+from __future__ import annotations
+
+import logging
+import math
+import os
+import shutil
+import sqlite3
+import tempfile
+from dataclasses import dataclass
+from enum import Enum
+from typing import Any, Callable, Mapping
+
+import pyarrow as pa # type: ignore
+from filelock import FileLock, Timeout
+
+from ..model.model import EmbeddingModelConfig
+from ..tools.core.RAG_tools.LanceDB.schema_manager import _safe_close_table
+from ..utils.lancedb_sql import sql_string_in
+from .lancedb_maintenance import (
+ DEFAULT_BATCH_SIZE,
+ DEFAULT_LOCK_TIMEOUT,
+ MaintenanceLockTimeout,
+ lancedb_lock_path,
+ validate_lock_timeout,
+)
+from .scope_columns import SCOPE_DIMS_COLUMN, USER_ID_COLUMN, strict_scope_columns
+from .vector_compatibility import (
+ EmbeddingIdentity,
+ VectorCompatibility,
+ _is_fully_admitted,
+ _lancedb_table_exists,
+ _prepared_schema,
+ canonical_embedding_identity,
+ classify_vector_compatibility,
+ embedding_identity_fingerprint,
+)
+
+logger = logging.getLogger(__name__)
+
+STAGING_SUFFIX = "__migrate_"
+BACKUP_SUFFIX = "__pre_migrate_"
+_SOURCE_COLUMNS = ["id", "text", "metadata"]
+_ID_CHUNK = 256
+
+
+class MemoryReembedStatus(str, Enum):
+ ABSENT = "absent"
+ ALREADY_TARGET = "already_target"
+ COMPLETE = "complete"
+ INCOMPATIBLE_SCHEMA = "incompatible_schema"
+ INVALID_SOURCE_DATA = "invalid_source_data"
+ EMBEDDING_FAILED = "embedding_failed"
+ VERIFICATION_FAILED = "verification_failed"
+ NOT_CONVERGED = "not_converged"
+ SWAPPED_OVER_A_WRITE = "swapped_over_a_write"
+
+
+@dataclass(frozen=True)
+class MemoryReembedOutcome:
+ status: MemoryReembedStatus
+ source_rows: int = 0
+ reembedded_rows: int = 0
+ passes: int = 0
+ staging_table: str | None = None
+ backup_table: str | None = None
+ detail: str | None = None
+
+
+class _InvalidSource(ValueError):
+ """The live or staging table holds a row this routine must not rewrite."""
+
+
+class _EmbeddingFailed(RuntimeError):
+ """The target model did not return one valid vector per text."""
+
+
+def _checkpoint(_stage: str, _batch: int | None = None) -> None:
+ """Test seam for deterministic interruption; intentionally does nothing."""
+
+
+def staging_table_name(table_name: str, identity: EmbeddingIdentity) -> str:
+ fingerprint = embedding_identity_fingerprint(identity)
+ return f"{table_name}{STAGING_SUFFIX}{fingerprint[:16]}"
+
+
+def backup_table_name(table_name: str, identity: EmbeddingIdentity) -> str:
+ fingerprint = embedding_identity_fingerprint(identity)
+ return f"{table_name}{BACKUP_SUFFIX}{fingerprint[:16]}"
+
+
+def _source_schema_supported(schema: Any) -> bool:
+ if any(
+ name not in schema.names or schema.field(name).type != pa.string()
+ for name in _SOURCE_COLUMNS
+ ):
+ return False
+ expected = {USER_ID_COLUMN: pa.int64(), SCOPE_DIMS_COLUMN: pa.list_(pa.string())}
+ if any(
+ name in schema.names and schema.field(name).type != kind
+ for name, kind in expected.items()
+ ):
+ return False
+ if "vector" not in schema.names:
+ return True
+ kind = schema.field("vector").type
+ return bool(pa.types.is_fixed_size_list(kind) and kind.value_type == pa.float32())
+
+
+def _vectors(texts: list[str], encode: Callable, dimension: int) -> list[list[float]]:
+ if not texts:
+ return []
+ try:
+ result = encode(texts)
+ except Exception as exc:
+ raise _EmbeddingFailed(f"encoding {len(texts)} notes failed: {exc}") from exc
+ if not isinstance(result, list) or len(result) != len(texts):
+ raise _EmbeddingFailed(f"encoding {len(texts)} notes returned a bad shape")
+ vectors = []
+ for vector in result:
+ if not isinstance(vector, (list, tuple)) or len(vector) != dimension:
+ raise _EmbeddingFailed(f"a note did not produce {dimension} dimensions")
+ try:
+ values = [float(value) for value in vector]
+ except (TypeError, ValueError) as exc:
+ raise _EmbeddingFailed(f"a re-embedded vector is not numeric: {exc}")
+ if not all(math.isfinite(value) for value in values):
+ raise _EmbeddingFailed("a re-embedded vector holds a non-finite value")
+ vectors.append(values)
+ return vectors
+
+
+def _blank_text(text: str | None) -> bool:
+ """Whether a note carries no text, and so no vector, by design."""
+ return not (text or "").strip()
+
+
+def _fill_staging(
+ source: Any,
+ staging: Any,
+ encode: Callable,
+ *,
+ batch_size: int,
+ dimension: int,
+ seen: sqlite3.Connection,
+) -> tuple[int, int]:
+ """Copy every source row the staging table is missing or holds stale."""
+ rows = embedded = 0
+ for index, batch in enumerate(
+ source.search().select(_SOURCE_COLUMNS).to_batches(batch_size=batch_size), 1
+ ):
+ records = []
+ for record in batch.to_pylist():
+ note_id = record["id"]
+ if not isinstance(note_id, str) or not note_id:
+ raise _InvalidSource("note ids must be non-empty strings")
+ try:
+ seen.execute("INSERT INTO source_ids VALUES (?)", (note_id,))
+ except sqlite3.IntegrityError:
+ raise _InvalidSource("note ids must be unique")
+ metadata = record["metadata"]
+ if metadata is not None and not isinstance(metadata, str):
+ raise _InvalidSource("note metadata must be a string or SQL NULL")
+ try:
+ owner, scope_dims = strict_scope_columns(metadata)
+ except ValueError as exc:
+ raise _InvalidSource(f"note {note_id!r}: {exc}")
+ records.append((note_id, record["text"], metadata, owner, scope_dims))
+ rows += len(records)
+ ids = [record[0] for record in records]
+ blank_ids = {record[0] for record in records if _blank_text(record[1])}
+ present: dict[str, tuple] = {}
+ staged: set[str] = set()
+ for offset in range(0, len(ids), _ID_CHUNK):
+ chunk = ids[offset : offset + _ID_CHUNK]
+ found = (
+ staging.search()
+ .where(sql_string_in("id", chunk))
+ .select(["id", "text", "metadata", USER_ID_COLUMN, SCOPE_DIMS_COLUMN])
+ .to_arrow()
+ )
+ for row in found.to_pylist():
+ staged.add(row["id"])
+ present[row["id"]] = (
+ row["text"],
+ row["metadata"],
+ row[USER_ID_COLUMN],
+ row[SCOPE_DIMS_COLUMN],
+ )
+ # A staged row with no vector is not reusable however well it
+ # matches: only a rewrite can give it one, so it counts as absent.
+ # Blank text carries no vector by contract, so it is exempt.
+ missing_vector = (
+ staging.search()
+ .where(f"({sql_string_in('id', chunk)}) AND vector IS NULL")
+ .select(["id"])
+ .to_arrow()
+ )
+ for row in missing_vector.to_pylist():
+ if row["id"] not in blank_ids:
+ present.pop(row["id"], None)
+ todo = [
+ record
+ for record in records
+ if present.get(record[0])
+ != (record[1] or "", record[2], record[3], record[4])
+ ]
+ if not todo:
+ _checkpoint("batch_skipped", index)
+ continue
+ stale = [record[0] for record in todo if record[0] in staged]
+ if stale:
+ staging.delete(sql_string_in("id", stale))
+ # Blank text is stored without a vector, exactly like the write path.
+ pending = [record for record in todo if not _blank_text(record[1])]
+ encoded = iter(
+ _vectors([record[1] or "" for record in pending], encode, dimension)
+ )
+ vectors = [None if _blank_text(record[1]) else next(encoded) for record in todo]
+ staging.add(
+ pa.Table.from_pylist(
+ [
+ {
+ "id": record[0],
+ "text": record[1],
+ "metadata": record[2],
+ "vector": vector,
+ USER_ID_COLUMN: record[3],
+ SCOPE_DIMS_COLUMN: record[4],
+ }
+ for record, vector in zip(todo, vectors)
+ ],
+ schema=staging.schema,
+ )
+ )
+ embedded += len(pending)
+ _checkpoint("batch_filled", index)
+ return rows, embedded
+
+
+def _verify(
+ connection: Any,
+ staging_name: str,
+ *,
+ identity: EmbeddingIdentity,
+ source_rows: int,
+ seen: sqlite3.Connection,
+ batch_size: int,
+) -> str | None:
+ """Why this staging table must not replace the source, or ``None``."""
+ staging = connection.open_table(staging_name)
+ try:
+ seen.execute("CREATE TABLE staging_ids (id TEXT PRIMARY KEY) WITHOUT ROWID")
+ try:
+ for batch in (
+ staging.search().select(["id"]).to_batches(batch_size=batch_size)
+ ):
+ for (note_id,) in zip(batch.column(0).to_pylist()):
+ try:
+ seen.execute("INSERT INTO staging_ids VALUES (?)", (note_id,))
+ except sqlite3.IntegrityError:
+ raise _InvalidSource("the staging table holds a duplicate id")
+ missing = [
+ row[0]
+ for row in seen.execute(
+ "SELECT id FROM source_ids "
+ "WHERE id NOT IN (SELECT id FROM staging_ids)"
+ )
+ ]
+ extra = [
+ row[0]
+ for row in seen.execute(
+ "SELECT id FROM staging_ids "
+ "WHERE id NOT IN (SELECT id FROM source_ids)"
+ )
+ ]
+ finally:
+ seen.execute("DROP TABLE staging_ids")
+ if extra:
+ staging.delete(sql_string_in("id", extra))
+ _checkpoint("staging_pruned")
+ if missing:
+ return f"{len(missing)} source notes are missing from the staging table"
+ if staging.count_rows() != source_rows:
+ return (
+ f"the staging table holds {staging.count_rows()} rows, "
+ f"the source {source_rows}"
+ )
+ # SQL trim keeps newlines and tabs, so blankness is judged like the writer.
+ offenders = sum(
+ not _blank_text(text)
+ for batch in staging.search()
+ .where("vector IS NULL")
+ .select(["text"])
+ .to_batches(batch_size=batch_size)
+ for text in batch.column(0).to_pylist()
+ )
+ if offenders:
+ return f"{offenders} staged notes carry no vector"
+ if (
+ classify_vector_compatibility(staging.schema, identity)
+ is not VectorCompatibility.MATCHING
+ ):
+ return "the staging table does not declare the target vector space"
+ if not _is_fully_admitted(staging):
+ return "the staging table is missing its admission certificate"
+ return None
+ finally:
+ _safe_close_table(staging)
+
+
+def _spill(connection: Any, source_name: str, scratch: str, batch_size: int) -> tuple:
+ """Copy ``source_name`` to an Arrow IPC file; return its path and schema."""
+ staged = os.path.join(scratch, f"spill-{source_name}.arrow")
+ source = connection.open_table(source_name)
+ try:
+ schema = source.schema
+ with pa.OSFile(staged, "wb") as sink, pa.ipc.new_file(sink, schema) as writer:
+ for batch in source.search().to_batches(batch_size=batch_size):
+ writer.write_batch(batch)
+ finally:
+ _safe_close_table(source)
+ return staged, schema
+
+
+def _replace_from(
+ connection: Any,
+ target_name: str,
+ spilled: str,
+ schema: Any,
+ *,
+ on_commit: Callable[[], None] | None = None,
+) -> int:
+ """Replace ``target_name`` with the rows at ``spilled``; return its new version.
+
+ ``on_commit`` runs once the overwrite has committed, before anything below
+ it can fail.
+ """
+ with pa.memory_map(spilled, "r") as mapped:
+ reader = pa.ipc.open_file(mapped)
+
+ def batches() -> Any:
+ for index in range(reader.num_record_batches):
+ yield reader.get_batch(index)
+
+ # Supported versions pull the first batch before they honour ``schema``,
+ # so an empty generator raises instead of writing the zero-row table.
+ data: Any = (
+ batches()
+ if reader.num_record_batches
+ else pa.Table.from_batches([], schema)
+ )
+ written = connection.create_table(
+ target_name, data=data, schema=schema, mode="overwrite"
+ )
+ if on_commit is not None:
+ on_commit()
+ try:
+ version = int(written.version)
+ finally:
+ _safe_close_table(written)
+ os.unlink(spilled)
+ return version
+
+
+def _copy_table(
+ connection: Any,
+ source_name: str,
+ target_name: str,
+ *,
+ scratch: str,
+ batch_size: int,
+) -> None:
+ """Atomically replace ``target_name`` with a copy of ``source_name``.
+
+ Rows spill through an Arrow IPC file: writing from a live table's lazy scan
+ deadlocks this LanceDB version, and neither table fits in memory.
+ """
+ _replace_from(
+ connection, target_name, *_spill(connection, source_name, scratch, batch_size)
+ )
+
+
+def _backfill_vectors(
+ connection: Any,
+ table_name: str,
+ encode: Callable,
+ *,
+ batch_size: int,
+ dimension: int,
+) -> int:
+ """Embed in place the notes with text but no vector; return how many."""
+ reader = connection.open_table(table_name)
+ writer = None
+ filled = 0
+ try:
+ writer = connection.open_table(table_name)
+ for batch in (
+ reader.search().where("vector IS NULL").to_batches(batch_size=batch_size)
+ ):
+ rows = [row for row in batch.to_pylist() if not _blank_text(row["text"])]
+ if not rows:
+ continue
+ for row, vector in zip(
+ rows, _vectors([row["text"] for row in rows], encode, dimension)
+ ):
+ row["vector"] = vector
+ # Only rows a writer has not touched since they were read are filled.
+ result = (
+ writer.merge_insert("id")
+ .when_matched_update_all(
+ where="target.vector IS NULL AND target.text = source.text AND "
+ "((target.metadata IS NULL AND source.metadata IS NULL) "
+ "OR target.metadata = source.metadata)"
+ )
+ .execute(pa.Table.from_pylist(rows, schema=reader.schema))
+ )
+ filled += int(result.num_updated_rows)
+ finally:
+ _safe_close_table(reader)
+ _safe_close_table(writer)
+ return filled
+
+
+def _current_version(connection: Any, table_name: str) -> int:
+ """The table's version on disk; an open handle stays pinned to its own."""
+ table = connection.open_table(table_name)
+ try:
+ return int(table.version)
+ finally:
+ _safe_close_table(table)
+
+
+def _staging_table(
+ connection: Any, name: str, source_schema: Any, identity: EmbeddingIdentity
+) -> Any:
+ """The staging table for this target, ready to be filled."""
+ if not _lancedb_table_exists(connection, name):
+ # ``_prepared_schema`` keeps an existing vector column as-is, so the
+ # source's is dropped: this table's vector takes the target width.
+ return connection.create_table(
+ name,
+ schema=_prepared_schema(
+ pa.schema(
+ [field for field in source_schema if field.name != "vector"],
+ metadata=source_schema.metadata,
+ ),
+ identity,
+ 1,
+ ),
+ )
+ staging = connection.open_table(name)
+ if classify_vector_compatibility(
+ staging.schema, identity
+ ) is VectorCompatibility.MATCHING and _is_fully_admitted(staging):
+ return staging
+ _safe_close_table(staging)
+ raise _InvalidSource(
+ f"staging table {name!r} does not hold the target vector space; "
+ "remove it before retrying"
+ )
+
+
+def reembed_memory_table(
+ connection: Any,
+ table_name: str,
+ target_identity: EmbeddingIdentity | EmbeddingModelConfig | Mapping[str, Any],
+ *,
+ encode: Callable[[list[str]], list[list[float]]],
+ batch_size: int = DEFAULT_BATCH_SIZE,
+ lock_timeout: float = DEFAULT_LOCK_TIMEOUT,
+ max_passes: int = 4,
+) -> MemoryReembedOutcome:
+ """Recompute every note's vector under ``target_identity`` and swap it in.
+
+ Resumable: the staging table persists across interruptions, and a rerun
+ only embeds notes it is missing or whose text changed; on a table already in
+ the target space it only embeds, in place, notes left without a vector.
+ Notes with blank text carry no vector, as on the write path. Before the swap it
+ must match the source's ids and row count and declare the target space; on
+ any shortfall the live table keeps the vectors it had, and the previous
+ table stays behind as a backup for rollback.
+
+ Args:
+ connection: A LanceDB connection to a writable local database.
+ table_name: The live memory table, usually ``memories``.
+ target_identity: The vector space every note is re-embedded into.
+ encode: One batch of texts to one vector per text, in order, each with
+ ``target_identity.dimension`` floats.
+ max_passes: Catch-up passes allowed while writers keep committing.
+ """
+ if type(batch_size) is not int or batch_size <= 0:
+ raise ValueError("batch_size must be a positive integer")
+ if type(max_passes) is not int or max_passes <= 0:
+ raise ValueError("max_passes must be a positive integer")
+ validate_lock_timeout(lock_timeout)
+ identity = canonical_embedding_identity(target_identity)
+ staging_name = staging_table_name(table_name, identity)
+ lock_path = lancedb_lock_path(connection, table_name, "maintenance")
+ lock = FileLock(lock_path, timeout=lock_timeout)
+ try:
+ lock.acquire()
+ except Timeout as exc:
+ raise MaintenanceLockTimeout(
+ f"Timed out after {lock_timeout}s waiting for the memory maintenance "
+ f"lock on table {table_name!r}; stop the other maintenance process"
+ ) from exc
+
+ def stop(status: MemoryReembedStatus, **fields: Any) -> MemoryReembedOutcome:
+ return MemoryReembedOutcome(status, staging_table=staging_name, **fields)
+
+ swapped = False
+
+ def mark_swapped() -> None:
+ nonlocal swapped
+ swapped = True
+
+ source = staging = None
+ scratch = ""
+ # A backup only means "the previous table" once the swap committed; any
+ # other exit drops the one this run wrote, and every abort leaves live intact.
+ backup_written = None
+ try:
+ if not _lancedb_table_exists(connection, table_name):
+ return stop(MemoryReembedStatus.ABSENT)
+ source = connection.open_table(table_name)
+ if (
+ classify_vector_compatibility(source.schema, identity)
+ is VectorCompatibility.MATCHING
+ ):
+ rows = source.count_rows()
+ supported = _source_schema_supported(source.schema)
+ _safe_close_table(source)
+ source = None
+ if _lancedb_table_exists(connection, staging_name):
+ connection.drop_table(staging_name)
+ if not supported:
+ return stop(MemoryReembedStatus.ALREADY_TARGET, source_rows=rows)
+ try:
+ filled = _backfill_vectors(
+ connection,
+ table_name,
+ encode,
+ batch_size=batch_size,
+ dimension=identity.dimension,
+ )
+ except _EmbeddingFailed as exc:
+ return stop(MemoryReembedStatus.EMBEDDING_FAILED, detail=str(exc))
+ return stop(
+ MemoryReembedStatus.ALREADY_TARGET,
+ source_rows=rows,
+ reembedded_rows=filled,
+ )
+ if not _source_schema_supported(source.schema):
+ return stop(
+ MemoryReembedStatus.INCOMPATIBLE_SCHEMA,
+ detail="the live memory table does not have the supported schema",
+ )
+ scratch = tempfile.mkdtemp(dir=os.path.dirname(lock_path), prefix=".reembed-")
+ try:
+ staging = _staging_table(connection, staging_name, source.schema, identity)
+ except _InvalidSource as exc:
+ return stop(MemoryReembedStatus.INCOMPATIBLE_SCHEMA, detail=str(exc))
+
+ source_rows = reembedded = 0
+ for pass_no in range(1, max_passes + 1):
+ # Handles stay pinned to the version they opened at, so a pass that
+ # has to see a write, and verification, both start afresh.
+ _safe_close_table(source)
+ source = connection.open_table(table_name)
+ _safe_close_table(staging)
+ staging = connection.open_table(staging_name)
+ snapshot = int(source.version)
+ seen = sqlite3.connect(os.path.join(scratch, f"ids-{pass_no}.sqlite"))
+ try:
+ seen.execute(
+ "CREATE TABLE source_ids (id TEXT PRIMARY KEY) WITHOUT ROWID"
+ )
+ try:
+ source_rows, pass_embedded = _fill_staging(
+ source,
+ staging,
+ encode,
+ batch_size=batch_size,
+ dimension=identity.dimension,
+ seen=seen,
+ )
+ reembedded += pass_embedded
+ detail = _verify(
+ connection,
+ staging_name,
+ identity=identity,
+ source_rows=source_rows,
+ seen=seen,
+ batch_size=batch_size,
+ )
+ except _InvalidSource as exc:
+ return stop(
+ MemoryReembedStatus.INVALID_SOURCE_DATA, detail=str(exc)
+ )
+ except _EmbeddingFailed as exc:
+ return stop(MemoryReembedStatus.EMBEDDING_FAILED, detail=str(exc))
+ finally:
+ seen.close()
+ if _current_version(connection, table_name) != snapshot:
+ # A commit landed after this pass read the source; the next pass
+ # sees it. Nothing was swapped, so nothing was lost.
+ logger.warning(
+ "Memory table %r changed during re-embedding pass %d",
+ table_name,
+ pass_no,
+ )
+ continue
+ if detail:
+ return stop(
+ MemoryReembedStatus.VERIFICATION_FAILED,
+ source_rows=source_rows,
+ reembedded_rows=reembedded,
+ passes=pass_no,
+ detail=detail,
+ )
+ # Spill the verified staging table before the live table is touched,
+ # so the swap itself is one commit and the version check below it is
+ # the last thing standing between a writer and being overwritten.
+ spilled, target_schema = _spill(
+ connection, staging_name, scratch, batch_size
+ )
+ backup_name = backup_table_name(table_name, identity)
+ _copy_table(
+ connection,
+ table_name,
+ backup_name,
+ scratch=scratch,
+ batch_size=batch_size,
+ )
+ backup_written = backup_name
+ _checkpoint("before_swap")
+ if _current_version(connection, table_name) != snapshot:
+ logger.warning(
+ "Memory table %r changed while its backup was written",
+ table_name,
+ )
+ continue
+ _safe_close_table(source)
+ source = None
+ _safe_close_table(staging)
+ staging = None
+ written = _replace_from(
+ connection, table_name, spilled, target_schema, on_commit=mark_swapped
+ )
+ _checkpoint("after_swap")
+ swapped = connection.open_table(table_name)
+ try:
+ verified = (
+ classify_vector_compatibility(swapped.schema, identity)
+ is VectorCompatibility.MATCHING
+ and swapped.count_rows() == source_rows
+ )
+ finally:
+ _safe_close_table(swapped)
+ if not verified:
+ raise RuntimeError(
+ "the swapped-in memory table failed its own verification"
+ )
+ connection.drop_table(staging_name)
+ if written != snapshot + 1:
+ # The overwrite landed on a later version: a write committed after
+ # the last check and is now only in the live table's history.
+ detail = (
+ f"a write committed during the swap was overwritten; versions "
+ f"{snapshot + 1}..{written - 1} of {table_name!r} still hold it"
+ )
+ logger.error("Memory table %r: %s", table_name, detail)
+ return stop(
+ MemoryReembedStatus.SWAPPED_OVER_A_WRITE,
+ source_rows=source_rows,
+ reembedded_rows=reembedded,
+ passes=pass_no,
+ backup_table=backup_name,
+ detail=detail,
+ )
+ logger.info(
+ "Re-embedded memory table %r into a new vector space (%d rows, "
+ "%d passes); previous table retained as %r",
+ table_name,
+ source_rows,
+ pass_no,
+ backup_name,
+ )
+ return stop(
+ MemoryReembedStatus.COMPLETE,
+ source_rows=source_rows,
+ reembedded_rows=reembedded,
+ passes=pass_no,
+ backup_table=backup_name,
+ )
+ return stop(
+ MemoryReembedStatus.NOT_CONVERGED,
+ source_rows=source_rows,
+ reembedded_rows=reembedded,
+ passes=max_passes,
+ detail=(
+ "writers kept committing to the memory table during migration; "
+ "the live table still holds the previous vector space"
+ ),
+ )
+ finally:
+ _safe_close_table(source)
+ _safe_close_table(staging)
+ if backup_written and not swapped:
+ try:
+ connection.drop_table(backup_written)
+ except Exception:
+ logger.warning("Could not drop the stale backup %r", backup_written)
+ if scratch:
+ shutil.rmtree(scratch, ignore_errors=True)
+ lock.release()
diff --git a/src/xagent/core/memory/lancedb.py b/src/xagent/core/memory/lancedb.py
index a1e3ffd42..80daad7f0 100644
--- a/src/xagent/core/memory/lancedb.py
+++ b/src/xagent/core/memory/lancedb.py
@@ -37,6 +37,7 @@ from .scope_columns import (
from .storage_admission import AdmittedLanceDBMemoryStore, DormantLanceDBMemoryHandle
from .vector_compatibility import (
EmbeddingIdentity,
+ VectorCompatibility,
_is_fully_admitted,
classify_vector_compatibility,
)
@@ -48,6 +49,9 @@ class LanceDBMemoryStore(MemoryStore):
"""LanceDB-based memory store implementation with vector search capabilities."""
_embedding_model: Optional[BaseEmbedding]
+ # The vector space this store was admitted for; ``None`` when the caller
+ # never certified one (the generic constructor).
+ _vector_identity: Optional[EmbeddingIdentity]
# Rows per backend batch on the streamed text-search path.
_stream_batch_size: int = DEFAULT_STREAM_BATCH_SIZE
@@ -109,6 +113,7 @@ class LanceDBMemoryStore(MemoryStore):
{},
ensure_table=False,
)
+ store._vector_identity = identity
store._verify_admitted_table(admitted, identity)
return store
@@ -151,6 +156,22 @@ class LanceDBMemoryStore(MemoryStore):
"after admission"
)
+ def _table_accepts_vectors(self, table: Any) -> bool:
+ """Whether vectors this store produces may enter or rank this table.
+
+ Admission certifies the table once, at startup. An offline re-embed
+ that swaps the table afterwards leaves this store holding the previous
+ adapter; writing its vectors here, or ranking this table with them,
+ would mix two models that may well share a dimension. Only an admitted
+ store knows its identity, so every other store keeps today's behavior.
+ """
+ if self._vector_identity is None:
+ return True
+ return (
+ classify_vector_compatibility(table.schema, self._vector_identity)
+ is not VectorCompatibility.MISMATCHING
+ )
+
def _set_up(
self,
db_dir: str,
@@ -162,6 +183,7 @@ class LanceDBMemoryStore(MemoryStore):
ensure_table: bool,
) -> None:
self._collection_name = collection_name
+ self._vector_identity = None
# Handle different types of embedding_model input
if embedding_model is None:
@@ -646,8 +668,15 @@ class LanceDBMemoryStore(MemoryStore):
}
# Add vector if available
- if data["vector"]:
+ if data["vector"] and self._table_accepts_vectors(table):
record["vector"] = data["vector"]
+ elif data["vector"]:
+ logger.warning(
+ "Memory table %r no longer holds this store's vector "
+ "space; storing memory %r without a vector",
+ self._collection_name,
+ data["id"],
+ )
# Try to add the record. On a schema mismatch, migrate the
# existing table in place (preserving all rows) instead of
@@ -931,7 +960,7 @@ class LanceDBMemoryStore(MemoryStore):
# Try vector search first
try:
query_embedding = self._get_embedding(query)
- if query_embedding:
+ if query_embedding and self._table_accepts_vectors(table):
# Check if vector column exists and has the right dimension
sample_df = table.search().limit(1).to_pandas()
if not sample_df.empty and "vector" in sample_df.columns:
diff --git a/src/xagent/web/memory_lifecycle.py b/src/xagent/web/memory_lifecycle.py
index 756ebf7e1..f4b308735 100644
--- a/src/xagent/web/memory_lifecycle.py
+++ b/src/xagent/web/memory_lifecycle.py
@@ -133,9 +133,10 @@ OPERATOR_GUIDANCE: dict[MemoryLifecycleState, str] = {
MemoryLifecycleState.RESTART_REQUIRED: (
"The global memory embedding authority no longer describes the vector "
"space the stored memories were written under, or admission left "
- "maintenance incomplete. Quiesce all writers, re-embed offline if the "
- "existing vectors must be preserved, then restart every worker "
- "together. Do not restart one worker into a mixed fleet."
+ "maintenance incomplete. Quiesce all writers, re-embed offline with "
+ "reembed_memory_table if the existing vectors must be preserved, then "
+ "restart every worker together. Do not restart one worker into a mixed "
+ "fleet."
),
MemoryLifecycleState.BLOCKED_REPAIR: (
"Persistent memory storage holds invalid legacy data or an "
diff --git a/tests/core/memory/test_embedding_migration.py b/tests/core/memory/test_embedding_migration.py
new file mode 100644
index 000000000..c9b9339a8
--- /dev/null
+++ b/tests/core/memory/test_embedding_migration.py
@@ -0,0 +1,735 @@
+"""Offline re-embedding migration of the LanceDB memory table."""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+
+import lancedb # type: ignore
+import pyarrow as pa # type: ignore
+import pytest
+
+import xagent.core.memory.embedding_migration as migration
+from xagent.core.memory.core import MemoryNote
+from xagent.core.memory.embedding_migration import (
+ MemoryReembedStatus,
+ backup_table_name,
+ reembed_memory_table,
+ staging_table_name,
+)
+from xagent.core.memory.lancedb import LanceDBMemoryStore
+from xagent.core.memory.scope_columns import SCOPE_DIMS_COLUMN, USER_ID_COLUMN
+from xagent.core.memory.storage_admission import (
+ DormantLanceDBMemoryHandle,
+ admit_lancedb_memory_storage,
+)
+from xagent.core.memory.vector_compatibility import (
+ VECTOR_IDENTITY_METADATA_KEY,
+ EmbeddingIdentity,
+ VectorCompatibility,
+ _is_fully_admitted,
+ classify_vector_compatibility,
+ create_or_recreate_vector_capable_table,
+)
+from xagent.core.model.embedding import BaseEmbedding
+from xagent.core.tools.core.RAG_tools.LanceDB.schema_manager import _safe_close_table
+from xagent.providers.vector_store.lancedb import clear_connection_cache
+
+OLD = EmbeddingIdentity(
+ "openai", "text-embedding-3-small", "https://api.openai.com/v1/embeddings", 4, None
+)
+# Same dimension as OLD on purpose: nothing but the declared space can tell them
+# apart, which is the case a config change alone silently mixes.
+NEW = EmbeddingIdentity(
+ "bailian", "qwen-embedding-v4", "https://example.test/v1", 4, None
+)
+
+
+class Encoder:
+ """Records every batch it is asked to embed and returns a fixed value."""
+
+ def __init__(self, value: float = 0.9, dimension: int = 4):
+ self.value = value
+ self.dimension = dimension
+ self.calls: list[list[str]] = []
+
+ def __call__(self, texts):
+ self.calls.append(list(texts))
+ return [[self.value] * self.dimension for _ in texts]
+
+
+def _row(note_id, text, user_id, value):
+ return {
+ "id": note_id,
+ "text": text,
+ "metadata": json.dumps({"content": text, "user_id": user_id}),
+ "vector": [value] * 4,
+ USER_ID_COLUMN: user_id,
+ SCOPE_DIMS_COLUMN: [],
+ }
+
+
+def _live(connection, rows=None, identity=OLD):
+ create_or_recreate_vector_capable_table(connection, "memories", identity)
+ if rows:
+ _append(connection, rows)
+ return connection.open_table("memories")
+
+
+def _append(connection, rows):
+ table = connection.open_table("memories")
+ try:
+ table.add(pa.Table.from_pylist(rows, schema=table.schema))
+ finally:
+ _safe_close_table(table)
+
+
+def _vectors(connection, name="memories"):
+ table = connection.open_table(name)
+ try:
+ return table.to_arrow().to_pylist()
+ finally:
+ _safe_close_table(table)
+
+
+def _names(connection):
+ return {str(name) for name in connection.table_names()}
+
+
+def connection(tmp_path):
+ clear_connection_cache()
+ yield lancedb.connect(str(tmp_path))
+ clear_connection_cache()
+
+
+def _three_notes():
+ return [
+ _row("a", "alpha", 1, 0.1),
+ _row("b", "beta", 1, 0.1),
+ _row("c", "gamma", 2, 0.1),
+ ]
+
+
+def test_same_dimension_swap_replaces_the_declared_space_and_every_vector(connection):
+ _live(connection, _three_notes())
+ encoder = Encoder(0.9)
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=encoder)
+
+ assert outcome.status is MemoryReembedStatus.COMPLETE
+ assert (outcome.source_rows, outcome.reembedded_rows) == (3, 3)
+ rows = _vectors(connection)
+ assert [row["id"] for row in rows] == ["a", "b", "c"]
+ assert all(row["vector"] == pytest.approx([0.9] * 4) for row in rows)
+ # Owners and scope survive the rebuild; they still come from the metadata.
+ assert [(row[USER_ID_COLUMN], row[SCOPE_DIMS_COLUMN]) for row in rows] == [
+ (1, []),
+ (1, []),
+ (2, []),
+ ]
+ live = connection.open_table("memories")
+ try:
+ assert (
+ classify_vector_compatibility(live.schema, NEW)
+ is VectorCompatibility.MATCHING
+ )
+ assert (
+ classify_vector_compatibility(live.schema, OLD)
+ is VectorCompatibility.MISMATCHING
+ )
+ assert json.loads(live.schema.metadata[VECTOR_IDENTITY_METADATA_KEY]) == (
+ NEW.as_dict()
+ )
+ assert _is_fully_admitted(live)
+ finally:
+ _safe_close_table(live)
+
+ backup = _vectors(connection, backup_table_name("memories", NEW))
+ assert all(row["vector"] == pytest.approx([0.1] * 4) for row in backup)
+ assert backup_table_name("memories", NEW) in _names(connection)
+ assert staging_table_name("memories", NEW) not in _names(connection)
+
+
+def test_a_second_run_is_a_no_op(connection):
+ _live(connection, _three_notes())
+ assert (
+ reembed_memory_table(connection, "memories", NEW, encode=Encoder()).status
+ is MemoryReembedStatus.COMPLETE
+ )
+ encoder = Encoder()
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=encoder)
+
+ assert outcome.status is MemoryReembedStatus.ALREADY_TARGET
+ assert encoder.calls == []
+
+
+def test_a_failed_staging_table_aborts_before_the_live_table_is_touched(
+ connection, monkeypatch
+):
+ _live(connection, _three_notes())
+
+ def drop_one(stage, batch=None):
+ if stage == "batch_filled" and batch == 1:
+ staging = connection.open_table(staging_table_name("memories", NEW))
+ try:
+ staging.delete("id = 'b'")
+ finally:
+ _safe_close_table(staging)
+
+ monkeypatch.setattr(migration, "_checkpoint", drop_one)
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert outcome.status is MemoryReembedStatus.VERIFICATION_FAILED
+ assert "missing" in outcome.detail
+ live = connection.open_table("memories")
+ try:
+ assert live.count_rows() == 3
+ assert (
+ classify_vector_compatibility(live.schema, OLD)
+ is VectorCompatibility.MATCHING
+ )
+ finally:
+ _safe_close_table(live)
+ assert backup_table_name("memories", NEW) not in _names(connection)
+
+
+def test_staging_ids_must_match_and_not_merely_add_up(connection, monkeypatch):
+ _live(connection, _three_notes())
+
+ def swap_ids(stage, batch=None):
+ if stage == "batch_filled" and batch == 1:
+ staging = connection.open_table(staging_table_name("memories", NEW))
+ try:
+ staging.delete("id = 'b'")
+ staging.add(
+ pa.Table.from_pylist(
+ [_row("ghost", "beta", 1, 0.9)], schema=staging.schema
+ )
+ )
+ finally:
+ _safe_close_table(staging)
+
+ monkeypatch.setattr(migration, "_checkpoint", swap_ids)
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert outcome.status is MemoryReembedStatus.VERIFICATION_FAILED
+ assert "missing" in outcome.detail
+ assert [row["id"] for row in _vectors(connection)] == ["a", "b", "c"]
+ assert all(
+ row["vector"] == pytest.approx([0.1] * 4) for row in _vectors(connection)
+ )
+
+
+def test_a_metadata_only_change_between_passes_is_carried(connection, monkeypatch):
+ _live(connection, _three_notes())
+ changed = []
+
+ def change_metadata(stage, batch=None):
+ if stage == "batch_filled" and not changed:
+ changed.append(True)
+ table = connection.open_table("memories")
+ try:
+ table.delete("id = 'b'")
+ finally:
+ _safe_close_table(table)
+ _append(
+ connection,
+ [
+ {
+ **_row("b", "beta", 9, 0.1),
+ "metadata": json.dumps(
+ {"content": "beta", "user_id": 9, "tags": ["carried"]}
+ ),
+ }
+ ],
+ )
+
+ monkeypatch.setattr(migration, "_checkpoint", change_metadata)
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert outcome.status is MemoryReembedStatus.COMPLETE
+ assert outcome.passes == 2
+ rows = {row["id"]: row for row in _vectors(connection)}
+ assert rows["b"][USER_ID_COLUMN] == 9
+ assert json.loads(rows["b"]["metadata"])["tags"] == ["carried"]
+
+
+def _staging_table(connection):
+ live = connection.open_table("memories")
+ try:
+ return migration._staging_table(
+ connection, staging_table_name("memories", NEW), live.schema, NEW
+ )
+ finally:
+ _safe_close_table(live)
+
+
+def _staged_row(note_id, text, user_id, value):
+ row = _row(note_id, text, user_id, 0.9)
+ row["vector"] = None if value is None else [value] * 4
+ return row
+
+
+def test_a_staged_row_without_a_vector_fails_verification(connection):
+ _live(connection, _three_notes())
+ staging = _staging_table(connection)
+ staging.add(
+ pa.Table.from_pylist(
+ [
+ _staged_row("a", "alpha", 1, 0.9),
+ _staged_row("b", "beta", 1, None),
+ _staged_row("c", "gamma", 2, 0.9),
+ ],
+ schema=staging.schema,
+ )
+ )
+ seen = sqlite3.connect(":memory:")
+ seen.execute("CREATE TABLE source_ids (id TEXT PRIMARY KEY) WITHOUT ROWID")
+ for note_id in ("a", "b", "c"):
+ seen.execute("INSERT INTO source_ids VALUES (?)", (note_id,))
+
+ detail = migration._verify(
+ connection,
+ staging_table_name("memories", NEW),
+ identity=NEW,
+ source_rows=3,
+ seen=seen,
+ batch_size=512,
+ )
+
+ _safe_close_table(staging)
+ seen.close()
+ assert "carry no vector" in detail
+ assert len(_vectors(connection)) == 3
+
+
+def test_a_staged_row_without_a_vector_is_embedded_by_the_next_run(connection):
+ _live(connection, _three_notes())
+ staging = _staging_table(connection)
+ staging.add(
+ pa.Table.from_pylist(
+ [
+ _staged_row("a", "alpha", 1, 0.9),
+ _staged_row("b", "beta", 1, None),
+ _staged_row("c", "gamma", 2, 0.9),
+ ],
+ schema=staging.schema,
+ )
+ )
+ _safe_close_table(staging)
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert outcome.status is MemoryReembedStatus.COMPLETE
+ assert all(
+ row["vector"] == pytest.approx([0.9] * 4) for row in _vectors(connection)
+ )
+
+
+def test_an_aborted_swap_leaves_no_backup_behind(connection, monkeypatch):
+ _live(connection, _three_notes())
+
+ def stop(stage, batch=None):
+ if stage == "before_swap":
+ raise RuntimeError("operator stopped the run")
+
+ monkeypatch.setattr(migration, "_checkpoint", stop)
+
+ with pytest.raises(RuntimeError, match="operator stopped"):
+ reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert backup_table_name("memories", NEW) not in _names(connection)
+ assert all(
+ row["vector"] == pytest.approx([0.1] * 4) for row in _vectors(connection)
+ )
+
+
+def test_a_failure_after_the_swap_keeps_the_backup(connection, monkeypatch):
+ _live(connection, _three_notes())
+
+ def stop(stage, batch=None):
+ if stage == "after_swap":
+ raise RuntimeError("process killed after the swap")
+
+ monkeypatch.setattr(migration, "_checkpoint", stop)
+
+ with pytest.raises(RuntimeError, match="after the swap"):
+ reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert all(
+ row["vector"] == pytest.approx([0.9] * 4) for row in _vectors(connection)
+ )
+ backup = _vectors(connection, backup_table_name("memories", NEW))
+ assert len(backup) == 3
+ assert all(row["vector"] == pytest.approx([0.1] * 4) for row in backup)
+
+
+def test_a_failure_once_the_swap_committed_keeps_the_backup(connection, monkeypatch):
+ _live(connection, _three_notes())
+ replace_from = migration._replace_from
+
+ def fail_after_the_commit(connection_, target_name, spilled, schema, **kwargs):
+ replace_from(connection_, target_name, spilled, schema, **kwargs)
+ if target_name == "memories":
+ raise OSError("the spilled file could not be removed")
+
+ monkeypatch.setattr(migration, "_replace_from", fail_after_the_commit)
+
+ with pytest.raises(OSError, match="could not be removed"):
+ reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert all(
+ row["vector"] == pytest.approx([0.9] * 4) for row in _vectors(connection)
+ )
+ backup = _vectors(connection, backup_table_name("memories", NEW))
+ assert all(row["vector"] == pytest.approx([0.1] * 4) for row in backup)
+
+
+def test_a_write_overwritten_by_the_swap_is_reported(connection, monkeypatch):
+ _live(connection, _three_notes())
+ replace_from = migration._replace_from
+
+ def write_first(connection_, target_name, spilled, schema, **kwargs):
+ if target_name == "memories":
+ _append(connection, [_row("late", "delta", 3, 0.1)])
+ return replace_from(connection_, target_name, spilled, schema, **kwargs)
+
+ monkeypatch.setattr(migration, "_replace_from", write_first)
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert outcome.status is MemoryReembedStatus.SWAPPED_OVER_A_WRITE
+ assert outcome.backup_table == backup_table_name("memories", NEW)
+ assert outcome.backup_table in _names(connection)
+ assert "late" not in {row["id"] for row in _vectors(connection)}
+ live = connection.open_table("memories")
+ try:
+ live.checkout(live.version - 1)
+ assert "late" in {row["id"] for row in live.to_arrow().to_pylist()}
+ finally:
+ _safe_close_table(live)
+
+
+def test_blank_notes_stay_without_a_vector(connection):
+ blank = _row("b", "", 1, 0.1)
+ blank["vector"] = None
+ spaces = _row("c", " \n\t", 2, 0.1)
+ spaces["vector"] = None
+ _live(connection, [_row("a", "alpha", 1, 0.1), blank, spaces])
+ encoder = Encoder()
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=encoder)
+
+ assert outcome.status is MemoryReembedStatus.COMPLETE
+ assert outcome.reembedded_rows == 1
+ assert encoder.calls == [["alpha"]]
+ rows = {row["id"]: row["vector"] for row in _vectors(connection)}
+ assert rows["a"] == pytest.approx([0.9] * 4)
+ assert (rows["b"], rows["c"]) == (None, None)
+
+
+def test_a_staged_blank_note_takes_the_source_text_verbatim(connection):
+ _live(connection, [_row("a", "", 1, 0.1)])
+ staging = _staging_table(connection)
+ staged = _staged_row("a", "", 1, None)
+ staged["text"] = None
+ staging.add(pa.Table.from_pylist([staged], schema=staging.schema))
+ _safe_close_table(staging)
+ encoder = Encoder()
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=encoder)
+
+ assert outcome.status is MemoryReembedStatus.COMPLETE
+ assert encoder.calls == []
+ row = _vectors(connection)[0]
+ assert (row["text"], row["vector"]) == ("", None)
+
+
+def _target_table_with_a_vectorless_note(connection):
+ missing = _row("b", "beta", 1, 0.1)
+ missing["vector"] = None
+ blank = _row("c", "", 2, 0.1)
+ blank["vector"] = None
+ _live(connection, [_row("a", "alpha", 1, 0.1), missing, blank], identity=NEW)
+
+
+def test_a_table_in_the_target_space_has_vectorless_notes_backfilled(connection):
+ _target_table_with_a_vectorless_note(connection)
+ encoder = Encoder()
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=encoder)
+
+ assert outcome.status is MemoryReembedStatus.ALREADY_TARGET
+ assert outcome.reembedded_rows == 1
+ assert encoder.calls == [["beta"]]
+ rows = {row["id"]: row["vector"] for row in _vectors(connection)}
+ assert rows["a"] == pytest.approx([0.1] * 4)
+ assert rows["b"] == pytest.approx([0.9] * 4)
+ assert rows["c"] is None
+
+
+def test_a_backfill_never_overwrites_a_note_edited_meanwhile(connection):
+ _target_table_with_a_vectorless_note(connection)
+
+ def edit_then_encode(texts):
+ table = connection.open_table("memories")
+ try:
+ table.update(where="id = 'b'", values={"text": "edited"})
+ finally:
+ _safe_close_table(table)
+ return [[0.9] * 4 for _ in texts]
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=edit_then_encode)
+
+ assert outcome.reembedded_rows == 0
+ row = next(row for row in _vectors(connection) if row["id"] == "b")
+ assert (row["text"], row["vector"]) == ("edited", None)
+
+
+def test_a_write_before_the_swap_joins_the_new_table_with_a_new_vector(
+ connection, monkeypatch
+):
+ _live(connection, _three_notes())
+ added = []
+
+ def add_note(stage, batch=None):
+ if stage == "batch_filled" and not added:
+ added.append("later")
+ _append(connection, [_row("later", "delta", 3, 0.1)])
+
+ monkeypatch.setattr(migration, "_checkpoint", add_note)
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert outcome.status is MemoryReembedStatus.COMPLETE
+ assert outcome.passes == 2
+ rows = {row["id"]: row for row in _vectors(connection)}
+ assert set(rows) == {"a", "b", "c", "later"}
+ assert all(row["vector"] == pytest.approx([0.9] * 4) for row in rows.values())
+ assert rows["later"][USER_ID_COLUMN] == 3
+
+
+def test_notes_deleted_before_the_swap_do_not_survive(connection, monkeypatch):
+ _live(connection, _three_notes())
+
+ def delete_note(stage, batch=None):
+ if stage == "batch_filled" and batch == 1:
+ table = connection.open_table("memories")
+ try:
+ table.delete("id = 'c'")
+ finally:
+ _safe_close_table(table)
+
+ monkeypatch.setattr(migration, "_checkpoint", delete_note)
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert outcome.status is MemoryReembedStatus.COMPLETE
+ assert [row["id"] for row in _vectors(connection)] == ["a", "b"]
+
+
+def test_writers_that_never_stop_leave_the_old_table_in_place(connection, monkeypatch):
+ _live(connection, _three_notes())
+ counter = []
+
+ def keep_writing(stage, batch=None):
+ if stage == "batch_filled":
+ counter.append(1)
+ _append(connection, [_row(f"w{len(counter)}", "delta", 4, 0.1)])
+
+ monkeypatch.setattr(migration, "_checkpoint", keep_writing)
+
+ outcome = reembed_memory_table(
+ connection, "memories", NEW, encode=Encoder(), max_passes=3
+ )
+
+ assert outcome.status is MemoryReembedStatus.NOT_CONVERGED
+ assert outcome.passes == 3
+ live = connection.open_table("memories")
+ try:
+ assert (
+ classify_vector_compatibility(live.schema, OLD)
+ is VectorCompatibility.MATCHING
+ )
+ assert live.count_rows() == 3 + len(counter)
+ finally:
+ _safe_close_table(live)
+ assert backup_table_name("memories", NEW) not in _names(connection)
+
+
+def test_interrupted_run_resumes_and_only_embeds_what_is_missing(
+ connection, monkeypatch
+):
+ _live(connection, _three_notes() + [_row("d", "delta", 2, 0.1)])
+
+ def interrupt(stage, batch=None):
+ if stage == "batch_filled" and batch == 1:
+ raise RuntimeError("interrupted")
+
+ monkeypatch.setattr(migration, "_checkpoint", interrupt)
+ with pytest.raises(RuntimeError, match="interrupted"):
+ reembed_memory_table(
+ connection, "memories", NEW, encode=Encoder(), batch_size=2
+ )
+ assert staging_table_name("memories", NEW) in _names(connection)
+ assert len(_vectors(connection)) == 4
+
+ monkeypatch.setattr(migration, "_checkpoint", lambda *args: None)
+ encoder = Encoder()
+ outcome = reembed_memory_table(
+ connection, "memories", NEW, encode=encoder, batch_size=2
+ )
+
+ assert outcome.status is MemoryReembedStatus.COMPLETE
+ assert sorted(text for call in encoder.calls for text in call) == ["delta", "gamma"]
+ assert all(
+ row["vector"] == pytest.approx([0.9] * 4) for row in _vectors(connection)
+ )
+
+
+def test_embedding_failure_keeps_the_live_table(connection):
+ _live(connection, _three_notes())
+
+ def broken(_texts):
+ raise RuntimeError("provider unavailable")
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=broken)
+
+ assert outcome.status is MemoryReembedStatus.EMBEDDING_FAILED
+ assert "provider unavailable" in outcome.detail
+ assert all(
+ row["vector"] == pytest.approx([0.1] * 4) for row in _vectors(connection)
+ )
+ assert backup_table_name("memories", NEW) not in _names(connection)
+
+
+def test_a_vector_of_the_wrong_width_is_refused(connection):
+ _live(connection, _three_notes())
+
+ outcome = reembed_memory_table(
+ connection, "memories", NEW, encode=Encoder(dimension=8)
+ )
+
+ assert outcome.status is MemoryReembedStatus.EMBEDDING_FAILED
+ live = connection.open_table("memories")
+ try:
+ assert (
+ classify_vector_compatibility(live.schema, OLD)
+ is VectorCompatibility.MATCHING
+ )
+ finally:
+ _safe_close_table(live)
+
+
+def test_duplicate_source_ids_abort_the_migration(connection):
+ _live(connection, _three_notes() + [_row("a", "alpha again", 1, 0.1)])
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert outcome.status is MemoryReembedStatus.INVALID_SOURCE_DATA
+ assert "unique" in outcome.detail
+ assert len(_vectors(connection)) == 4
+
+
+def test_a_vectorless_table_is_rebuilt_with_vectors(connection):
+ table = connection.create_table(
+ "memories",
+ pa.table(
+ {
+ "id": ["a", "b"],
+ "text": ["alpha", "beta"],
+ "metadata": [json.dumps({"user_id": 1})] * 2,
+ }
+ ),
+ )
+ _safe_close_table(table)
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert outcome.status is MemoryReembedStatus.COMPLETE
+ rows = _vectors(connection)
+ assert [row["vector"] for row in rows] == [
+ pytest.approx([0.9] * 4),
+ pytest.approx([0.9] * 4),
+ ]
+ assert [row[USER_ID_COLUMN] for row in rows] == [1, 1]
+
+
+def test_an_absent_table_is_reported_not_created(connection):
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert outcome.status is MemoryReembedStatus.ABSENT
+ assert "memories" not in _names(connection)
+
+
+def test_a_staging_table_from_another_space_is_refused(connection):
+ _live(connection, _three_notes())
+ staging = connection.create_table(
+ staging_table_name("memories", NEW), data=[_row("x", "x", 1, 0.9)]
+ )
+ _safe_close_table(staging)
+
+ outcome = reembed_memory_table(connection, "memories", NEW, encode=Encoder())
+
+ assert outcome.status is MemoryReembedStatus.INCOMPATIBLE_SCHEMA
+ assert "does not hold the target vector space" in outcome.detail
+ assert len(_vectors(connection)) == 3
+
+
+class ConstantEmbedding(BaseEmbedding):
+ def __init__(self, value: float = 0.5):
+ self.value = value
+
+ def encode(self, text, dimension=None, instruct=None):
+ vector = [self.value] * 4
+ return vector if isinstance(text, str) else [vector for _ in text]
+
+ def get_dimension(self):
+ return 4
+
+ @property
+ def abilities(self):
+ return ["embed"]
+
+
+def _admitted_store(connection, tmp_path):
+ outcome = admit_lancedb_memory_storage(
+ DormantLanceDBMemoryHandle(connection, "memories"),
+ OLD,
+ writers_quiesced=True,
+ )
+ assert outcome.admitted is not None
+ return LanceDBMemoryStore.open_admitted(
+ outcome.admitted,
+ OLD,
+ db_dir=str(tmp_path),
+ embedding_model=ConstantEmbedding(),
+ )
+
+
+def test_a_store_that_lost_its_table_to_a_reembed_writes_no_old_vectors(
+ connection, tmp_path
+):
+ _live(connection)
+ store = _admitted_store(connection, tmp_path)
+ assert store.add(MemoryNote(id="before", content="alpha")).success
+
+ assert (
+ reembed_memory_table(connection, "memories", NEW, encode=Encoder()).status
+ is MemoryReembedStatus.COMPLETE
+ )
+
+ assert store.add(MemoryNote(id="after", content="beta")).success
+ rows = {row["id"]: row for row in _vectors(connection)}
+ assert rows["before"]["vector"] == pytest.approx([0.9] * 4)
+ assert rows["after"]["vector"] is None
+ # The store's old adapter never ranked the new table either.
+ assert [note.id for note in store.search("beta", k=1)] == ["after"]
+ assert all(
+ row["vector"] in (None, pytest.approx([0.9] * 4)) for row in rows.values()
+ )