Skip to content
Python

fix(memhub): migrate without a model profile and check readback against the pre-migration store

alvinfeib5ec0861f068
diff --git a/memhub/apps/cli/src/cli.ts b/memhub/apps/cli/src/cli.ts
index 54ec50f..159bb5c 100644
--- a/memhub/apps/cli/src/cli.ts
+++ b/memhub/apps/cli/src/cli.ts
@@ -4155,6 +4155,8 @@ const SDK_MIGRATION_FAILURES: Record<string, string> = {
"核对发现新版本还读不到你的全部记忆,没有切换数据源。",
sdk_migration_model_profile_required:
"迁移需要先有可用的模型配置,用来核对新版本能否读回记忆。请先用 memhub models setup 完成配置,再运行 memhub restart 重试。",
+ sdk_migration_vector_profile_missing:
+ "记忆的向量来自一个已删除的模型配置,当前配置读不回它们,所以没有迁移。请重新添加并启用那个模型配置,再运行 memhub restart 重试。",
};
const MIGRATION_ISSUES_URL =
diff --git a/memhub/apps/core/src/one_memory/cli.py b/memhub/apps/core/src/one_memory/cli.py
index 28510ab..f52cd08 100644
--- a/memhub/apps/core/src/one_memory/cli.py
+++ b/memhub/apps/core/src/one_memory/cli.py
@@ -584,6 +584,7 @@ def _sdk_migration_status(options: Sequence[str], stream: TextIO) -> int:
}
else:
from one_memory.hy_runtime_config import HY_MEMORY_NAMESPACE
+ from one_memory.hy_sdk_runtime import builtin_retrieval_snapshot
from one_memory.sdk_data_plane_migration import (
MemoryAuthority,
SdkDataPlaneMigrationStore,
@@ -595,14 +596,14 @@ def _sdk_migration_status(options: Sequence[str], stream: TextIO) -> int:
authority = SdkDataPlaneMigrationStore(database_path).authority()
if authority is MemoryAuthority.SDK:
- profile = read_active_profile(database_path)
+ profile = read_active_profile(database_path) or builtin_retrieval_snapshot()
leftovers = bool(
legacy_tables_present(database_path)
or abandoned_staging_present(
data_dir=settings.data_dir,
namespace=HY_MEMORY_NAMESPACE,
)
- or (profile is not None and legacy_vector_collections(settings.data_dir, profile))
+ or legacy_vector_collections(settings.data_dir, profile)
)
state = "required" if leftovers else "not_required"
else:
diff --git a/memhub/apps/core/src/one_memory/sdk_migration_runner.py b/memhub/apps/core/src/one_memory/sdk_migration_runner.py
index e4a7da3..55eda1e 100644
--- a/memhub/apps/core/src/one_memory/sdk_migration_runner.py
+++ b/memhub/apps/core/src/one_memory/sdk_migration_runner.py
@@ -23,6 +23,7 @@ from pathlib import Path
from typing import Any
from one_memory.database_access import main_database
+from one_memory.hy_sdk_runtime import builtin_retrieval_snapshot
from one_memory.imports.models import EvidenceRecord
from one_memory.imports.storage import EvidenceStore
from one_memory.memory_server.contracts import (
@@ -51,6 +52,7 @@ from one_memory.sdk_migration_bundle import inspect_sdk_migration_bundle
from one_memory.sdk_migration_verify import (
MemoryReadbackFailed,
ReadbackReport,
+ expected_memory_ids,
legacy_memory_ids_from,
legacy_memory_ids_from_bundle,
read_active_profile,
@@ -61,6 +63,8 @@ from one_memory.sdk_vector_reattach import (
ReattachedCollection,
legacy_vector_collections,
reattach_legacy_vectors,
+ stored_memory_ids,
+ vectors_belong_to_another_space,
)
from one_memory.target_schema import drop_legacy_tables, legacy_tables_present
@@ -704,13 +708,14 @@ def run_startup_migration(
step["authority"] = authority.value
log.migration_id = authority_migration
with log.step("preflight.profile_read") as step:
- profile = read_active_profile(database_path)
- step["profile_present"] = profile is not None
+ active = read_active_profile(database_path)
+ step["profile_present"] = active is not None
+ # No active profile means no generation model, not no embedding: the
+ # vectors are the built-in model's, which is also what the Runtime reads.
+ profile = active if active is not None else builtin_retrieval_snapshot()
if authority is MemoryAuthority.SDK:
with log.step("preflight.leftovers_scan") as step:
- vectors_waiting = profile is not None and bool(
- legacy_vector_collections(data_dir, profile)
- )
+ vectors_waiting = bool(legacy_vector_collections(data_dir, profile))
leftovers = bool(legacy_tables_present(database_path)) or abandoned_staging_present(
data_dir=data_dir, namespace=namespace
)
@@ -721,7 +726,6 @@ def run_startup_migration(
reattached: tuple[ReattachedCollection, ...] = ()
readback: ReadbackReport | None = None
if vectors_waiting:
- assert profile is not None
progress("vectors")
with log.step("vectors.reattach") as step:
reattached = reattach_legacy_vectors(data_dir, profile)
@@ -773,12 +777,14 @@ def run_startup_migration(
step["chat"] = len(legacy.chat)
step["productivity"] = len(legacy.productivity)
step["users"] = len(legacy.users)
- if profile is None and not legacy.empty:
- # Without the embedding profile the Runtime's collections cannot be
- # named, so neither reattached nor read back. Legacy stays intact.
- log.check("preflight.model_profile_check", "sdk_migration_model_profile_required")
- raise DataPlaneMigrationError("sdk_migration_model_profile_required")
- log.check("preflight.model_profile_check", None)
+ if active is None and not legacy.empty and vectors_belong_to_another_space(
+ data_dir, profile
+ ):
+ # The memories live in the space of a profile that is no longer active,
+ # so the built-in model cannot read them. Legacy stays intact.
+ log.check("preflight.vector_space_check", "sdk_migration_vector_profile_missing")
+ raise DataPlaneMigrationError("sdk_migration_vector_profile_missing")
+ log.check("preflight.vector_space_check", None)
with capture_fence(data_dir):
# Builds through 19 left a staged SDK copy beside the original store.
# Settling it before the bundle means the bundle holds the original
@@ -834,17 +840,23 @@ def run_startup_migration(
step.update(preparation.as_document())
reattached = ()
readback = None
- if profile is not None:
- progress("vectors")
- with log.step("vectors.reattach") as step:
- reattached = reattach_legacy_vectors(data_dir, profile)
- step["collections"] = len(reattached)
- if not legacy.empty:
- assert profile is not None
+ # Before reattach touches the store, and after the staging
+ # recovery above has settled which store is the original.
+ with log.step("verify.stored_ids") as step:
+ expected, missing = expected_memory_ids(legacy, stored_memory_ids(data_dir))
+ step["chat_expected"] = len(expected.chat)
+ step["chat_missing_before_migration"] = missing
+ progress("vectors")
+ with log.step("vectors.reattach") as step:
+ reattached = reattach_legacy_vectors(data_dir, profile)
+ step["collections"] = len(reattached)
+ if not expected.empty:
progress("verify")
with log.step("verify.readback") as step:
with client_for(profile) as client:
- readback = verify_readback(client, legacy)
+ readback = verify_readback(
+ client, expected, chat_missing_before_migration=missing
+ )
step.update(readback.as_document())
if not readback.passed:
store.set_phase(migration_id, phase="readback_failed", state="blocked")
diff --git a/memhub/apps/core/src/one_memory/sdk_migration_verify.py b/memhub/apps/core/src/one_memory/sdk_migration_verify.py
index 529e5e8..19fab77 100644
--- a/memhub/apps/core/src/one_memory/sdk_migration_verify.py
+++ b/memhub/apps/core/src/one_memory/sdk_migration_verify.py
@@ -14,7 +14,7 @@ import json
import sqlite3
from collections.abc import Iterator
from contextlib import closing, contextmanager
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any
@@ -47,6 +47,8 @@ class ReadbackReport:
chat_readable: int
productivity_expected: int
productivity_readable: int
+ #: Confirmed in the mirror, gone from the SDK before this migration began.
+ chat_missing_before_migration: int = 0
@property
def passed(self) -> bool:
@@ -63,6 +65,7 @@ class ReadbackReport:
"chat_readable": self.chat_readable,
"productivity_expected": self.productivity_expected,
"productivity_readable": self.productivity_readable,
+ "chat_missing_before_migration": self.chat_missing_before_migration,
"passed": self.passed,
}
@@ -115,6 +118,27 @@ def read_legacy_memory_ids(connection: sqlite3.Connection) -> LegacyMemoryIds:
)
+def expected_memory_ids(
+ legacy: LegacyMemoryIds, stored: frozenset[str]
+) -> tuple[LegacyMemoryIds, int]:
+ """What the readback must find, and how many confirmed chats it need not.
+
+ A 1.0.4 library can hold confirmed rows whose SDK node the SDK had already
+ merged or deleted: no migration could read those back (658 confirmed, 657
+ in the store, and the whole upgrade failed). So chat is held to what the
+ store held before this run, and anything in there must still read back.
+
+ If none of the confirmed chats is in the store, that is not history: the
+ store is empty or is the wrong one. Nothing is excused then, so the
+ readback still fails on every id instead of checking nothing just before
+ the mirror is dropped.
+ """
+ chat = tuple(memory_id for memory_id in legacy.chat if memory_id in stored)
+ if not chat:
+ return legacy, 0
+ return replace(legacy, chat=chat), len(legacy.chat) - len(chat)
+
+
def legacy_memory_ids_from(database_path: Path) -> LegacyMemoryIds:
with main_database(database_path).read() as connection:
return read_legacy_memory_ids(connection)
@@ -179,14 +203,18 @@ def runtime_sdk_client(
from one_memory.model_profiles import ModelProfileStore
from one_memory.secrets import KeyringSecretStore, SecretStoreUnavailableError
- try:
- secret = ModelProfileStore(database_path).resolve_snapshot_secret(
- profile.profile_id, profile.revision, KeyringSecretStore()
- )
- except SecretStoreUnavailableError:
- raise DataPlaneMigrationError("sdk_migration_secure_storage_unavailable") from None
- if profile.has_api_key and secret is None:
- raise DataPlaneMigrationError("sdk_migration_model_secret_unavailable")
+ secret: str | None = None
+ # Without a key there is nothing to resolve, and the built-in retrieval
+ # snapshot has no stored version to look one up by.
+ if profile.has_api_key:
+ try:
+ secret = ModelProfileStore(database_path).resolve_snapshot_secret(
+ profile.profile_id, profile.revision, KeyringSecretStore()
+ )
+ except SecretStoreUnavailableError:
+ raise DataPlaneMigrationError("sdk_migration_secure_storage_unavailable") from None
+ if secret is None:
+ raise DataPlaneMigrationError("sdk_migration_model_secret_unavailable")
lease = acquire_client(profile, api_key=secret, data_dir=data_dir)
try:
yield lease.client
@@ -194,7 +222,9 @@ def runtime_sdk_client(
lease.close()
-def verify_readback(client: Any, legacy: LegacyMemoryIds) -> ReadbackReport:
+def verify_readback(
+ client: Any, legacy: LegacyMemoryIds, *, chat_missing_before_migration: int = 0
+) -> ReadbackReport:
listed: set[str] = set()
for user_id in legacy.users or ("local",):
offset = 0
@@ -228,5 +258,6 @@ def verify_readback(client: Any, legacy: LegacyMemoryIds) -> ReadbackReport:
chat_readable=sum(1 for memory_id in legacy.chat if readable(memory_id)),
productivity_expected=len(legacy.productivity),
productivity_readable=sum(1 for memory_id in legacy.productivity if readable(memory_id)),
+ chat_missing_before_migration=chat_missing_before_migration,
)
diff --git a/memhub/apps/core/src/one_memory/sdk_vector_reattach.py b/memhub/apps/core/src/one_memory/sdk_vector_reattach.py
index 2c69243..11c03bd 100644
--- a/memhub/apps/core/src/one_memory/sdk_vector_reattach.py
+++ b/memhub/apps/core/src/one_memory/sdk_vector_reattach.py
@@ -9,6 +9,7 @@ one. Runtime code only reaches vectors through the SDK. This module runs from
from __future__ import annotations
+import re
import sqlite3
from collections.abc import Iterator
from contextlib import closing
@@ -21,6 +22,8 @@ from one_memory.model_profiles import ModelProfileSnapshot
from one_memory.sdk_data_plane_migration import DataPlaneMigrationError
_BATCH = 500
+#: Every name a MemHub build gave an embedding space's base collection.
+_SPACE_NAME = re.compile(r"^(?:memhub_[0-9a-f]{16}|one_memory_[0-9a-f]{12})(?:_|$)")
def open_offline_chroma(directory: Path) -> Any:
@@ -51,13 +54,20 @@ def _vector_directory(data_dir: Path) -> Path:
return data_dir / "hy-memory" / "governed-v2" / "vector"
-def _stored_names(data_dir: Path) -> tuple[str, ...]:
+def _stored_names(data_dir: Path, *, filled: bool = False) -> tuple[str, ...]:
+ """Collection names; with `filled`, only those holding at least one row."""
database = _vector_directory(data_dir) / "chroma.sqlite3"
if not database.is_file():
return ()
with closing(sqlite3.connect(f"file:{database}?mode=ro", uri=True)) as connection:
try:
- rows = connection.execute("SELECT name FROM collections").fetchall()
+ rows = connection.execute(
+ "SELECT DISTINCT collections.name FROM collections "
+ "JOIN segments ON segments.collection = collections.id "
+ "JOIN embeddings ON embeddings.segment_id = segments.id"
+ if filled
+ else "SELECT name FROM collections"
+ ).fetchall()
except sqlite3.Error:
return ()
return tuple(sorted(str(row[0]) for row in rows))
@@ -80,6 +90,59 @@ def legacy_vector_collections(
return tuple(pairs)
+def vectors_belong_to_another_space(data_dir: Path, profile: ModelProfileSnapshot) -> bool:
+ """Vectors exist, but only in embedding spaces `profile` does not name.
+
+ Counted rows, not names: every Runtime opens its read collection with
+ `get_or_create`, so an empty collection under the expected base proves
+ nothing. Read-only, so a preflight can ask before anything changes.
+ """
+ current, legacy_bases = vector_collection_bases(profile)
+ known = (current, *legacy_bases)
+ filled = _stored_names(data_dir, filled=True)
+ return not any(
+ name == base or name.startswith(f"{base}_") for name in filled for base in known
+ ) and any(_SPACE_NAME.match(name) for name in filled)
+
+
+def stored_memory_ids(data_dir: Path) -> frozenset[str]:
+ """Every id in the vector store as found, across all embedding spaces.
+
+ All of them on purpose. A memory stranded under a space the Runtime will
+ not read must count as present, so the readback then fails on it instead
+ of excusing it. Both the point id and the SDK's `node_id` are kept: the
+ SDK derives a point id from a node id that is not a UUID.
+
+ Callers must have stopped every SDK writer. A store that cannot be read
+ raises: "unknown" must never be taken for "absent".
+ """
+ if not (_vector_directory(data_dir) / "chroma.sqlite3").is_file():
+ return frozenset()
+ found: set[str] = set()
+ try:
+ client = open_offline_chroma(_vector_directory(data_dir))
+ try:
+ for collection in client.list_collections():
+ offset = 0
+ while True:
+ page = collection.get(include=["metadatas"], limit=_BATCH, offset=offset)
+ ids = list(page["ids"])
+ if not ids:
+ break
+ found.update(ids)
+ found.update(
+ str(metadata["node_id"])
+ for metadata in page["metadatas"] or ()
+ if metadata and metadata.get("node_id")
+ )
+ offset += len(ids)
+ finally:
+ client.close()
+ except Exception as error:
+ raise DataPlaneMigrationError("sdk_migration_vector_store_unreadable") from error
+ return frozenset(found)
+
+
def _records(collection: Any) -> Iterator[dict[str, Any]]:
offset = 0
while True:
diff --git a/memhub/apps/core/tests/test_cli_restore.py b/memhub/apps/core/tests/test_cli_restore.py
index 2b9fe9c..95451d9 100644
--- a/memhub/apps/core/tests/test_cli_restore.py
+++ b/memhub/apps/core/tests/test_cli_restore.py
@@ -175,7 +175,13 @@ def test_sdk_migrate_reports_each_step_then_the_result(tmp_path, monkeypatch) ->
assert code == 0, output.getvalue()
lines = [json.loads(line) for line in output.getvalue().splitlines()]
- assert [line["step"] for line in lines[:-1]] == ["bundle", "prepare", "cutover", "cleanup"]
+ assert [line["step"] for line in lines[:-1]] == [
+ "bundle",
+ "prepare",
+ "vectors",
+ "cutover",
+ "cleanup",
+ ]
assert lines[-1]["state"] == "cutover"
assert lines[-1]["bundle_id"] == f"{lines[-1]['migration_id']}-pre-cutover"
assert not (tmp_path / ".sdk-migration-capture-fence.json").exists()
diff --git a/memhub/apps/core/tests/test_sdk_data_plane_migration.py b/memhub/apps/core/tests/test_sdk_data_plane_migration.py
index d180e2a..c722980 100644
--- a/memhub/apps/core/tests/test_sdk_data_plane_migration.py
+++ b/memhub/apps/core/tests/test_sdk_data_plane_migration.py
@@ -708,6 +708,7 @@ def test_cutover_waits_until_the_new_runtime_reads_every_chat_memory(store, acti
"chat_readable": 1,
"productivity_expected": 0,
"productivity_readable": 0,
+ "chat_missing_before_migration": 0,
"passed": False,
}
assert store.authority() is MemoryAuthority.LEGACY
@@ -774,17 +775,187 @@ def test_retired_coding_experiences_do_not_block_but_an_empty_store_does(store,
assert (result.readback.productivity_expected, result.readback.productivity_readable) == (2, 1)
-def test_memories_without_a_model_profile_keep_legacy_authority(store, monkeypatch):
+def test_a_home_without_a_model_profile_migrates_on_the_builtin_embedding(store, monkeypatch):
+ """#234: no generation model was ever configured, and the upgrade stopped.
+
+ No profile means no LLM, not no embedding: the vectors are the built-in
+ model's, the same space the Runtime reads with. They are reattached and
+ read back through it, and the client is opened without resolving a key.
+ """
+ from one_memory.hy_sdk_runtime import builtin_retrieval_snapshot, vector_collection_bases
+
monkeypatch.setattr("one_memory.sdk_migration_runner.read_active_profile", lambda _db: None)
+ home = store.database_path.parent
+ builtin = builtin_retrieval_snapshot()
+ _current, legacy_bases = vector_collection_bases(builtin)
+ client = _chroma(home)
+ _fill(client, f"{legacy_bases[0]}_512", ["m1", "m2"])
+ del client
+ _confirmed(store, "m1", "m2")
+ opened: list[str] = []
+
+ def open_client(profile):
+ opened.append(profile.profile_id)
+ return _reading({"m1", "m2"})(profile)
+
+ result = run_startup_migration(
+ data_dir=home,
+ runtime_build="21",
+ sdk_version="2.0.5",
+ namespace="governed-v2",
+ open_client=open_client,
+ )
+
+ assert result.state == "cutover"
+ assert opened == [builtin.profile_id]
+ assert [item.legacy for item in result.reattached] == [f"{legacy_bases[0]}_512"]
+ assert result.readback is not None and result.readback.passed
+ assert store.authority() is MemoryAuthority.SDK
+
+
+def test_the_builtin_readback_client_resolves_no_secret(tmp_path, monkeypatch):
+ """The built-in snapshot has no stored version and no key to look up."""
+ from one_memory import sdk_migration_verify
+ from one_memory.hy_sdk_runtime import builtin_retrieval_snapshot
+
+ leased: list[tuple[str, object]] = []
+
+ class Lease:
+ client = object()
+
+ def close(self) -> None:
+ leased.append(("closed", None))
+
+ def acquire(profile, *, api_key, data_dir):
+ leased.append((profile.profile_id, api_key))
+ return Lease()
+
+ def no_lookup(*_args, **_kwargs):
+ raise AssertionError("a key-less profile must not touch the secret store")
+
+ monkeypatch.setattr("one_memory.hy_sdk_runtime.acquire_client", acquire)
+ monkeypatch.setattr(
+ "one_memory.model_profiles.ModelProfileStore.resolve_snapshot_secret", no_lookup
+ )
+ with sdk_migration_verify.runtime_sdk_client(
+ tmp_path / "missing.sqlite3", tmp_path, builtin_retrieval_snapshot()
+ ) as client:
+ assert client is Lease.client
+ assert leased == [("builtin-retrieval", None), ("closed", None)]
+
+
+def test_vectors_left_by_a_deleted_profile_stop_the_upgrade_by_name(store, monkeypatch):
+ """No active profile, and the vectors sit in another profile's space.
+
+ The built-in model cannot read them, so the old abort was right for this
+ one shape; it now says what is actually wrong, before anything changes.
+ """
+ from one_memory.hy_sdk_runtime import vector_collection_bases
+ from one_memory.model_profiles import ModelProfileSnapshot, ProviderKind
+
+ monkeypatch.setattr("one_memory.sdk_migration_runner.read_active_profile", lambda _db: None)
+ deleted = ModelProfileSnapshot(
+ profile_id="deleted",
+ revision=3,
+ provider_kind=ProviderKind.OPENAI_COMPATIBLE,
+ base_url="https://models.example/v1",
+ model="chat",
+ embedding_provider_kind=ProviderKind.OPENAI_COMPATIBLE,
+ embedding_base_url="https://models.example/v1",
+ embedding_model="text-embedding-3-large",
+ embedding_dimensions=1024,
+ timeout_seconds=60,
+ max_concurrency=1,
+ context_window=None,
+ has_api_key=True,
+ )
+ current, _legacy = vector_collection_bases(deleted)
+ home = store.database_path.parent
+ client = _chroma(home)
+ _fill(client, f"{current}_1024", ["m1"])
+ del client
_confirmed(store, "m1")
- with pytest.raises(DataPlaneMigrationError, match="sdk_migration_model_profile_required"):
+ with pytest.raises(DataPlaneMigrationError, match="sdk_migration_vector_profile_missing"):
+ run_startup_migration(
+ data_dir=home,
+ runtime_build="21",
+ sdk_version="2.0.5",
+ namespace="governed-v2",
+ open_client=_reading({"m1"}),
+ )
+ assert store.authority() is MemoryAuthority.LEGACY
+ assert not (home / "backups").exists()
+
+
+def test_confirmed_chats_the_sdk_had_already_merged_do_not_fail_the_upgrade(
+ store, active_profile
+):
+ """#229/#240: 658 confirmed chats, 657 in the store, and the upgrade failed.
+
+ A 1.0.4 library can hold confirmed rows whose SDK node had been merged or
+ deleted before the upgrade; no migration can read those back. The check
+ holds chat to what the store held before this run and counts the rest.
+ """
+ from one_memory.hy_sdk_runtime import vector_collection_bases
+
+ home = store.database_path.parent
+ stored = [f"chat-{index:03d}" for index in range(657)]
+ current, _legacy = vector_collection_bases(active_profile)
+ client = _chroma(home)
+ _fill(client, f"{current}_512", stored)
+ del client
+ _confirmed(store, *stored, "chat-merged-before-upgrade")
+
+ result = run_startup_migration(
+ data_dir=home,
+ runtime_build="21",
+ sdk_version="2.0.5",
+ namespace="governed-v2",
+ open_client=_reading(set(stored)),
+ )
+
+ assert result.state == "cutover"
+ assert result.readback is not None
+ assert result.readback.as_document() == {
+ "chat_expected": 657,
+ "chat_readable": 657,
+ "productivity_expected": 0,
+ "productivity_readable": 0,
+ "chat_missing_before_migration": 1,
+ "passed": True,
+ }
+ assert store.authority() is MemoryAuthority.SDK
+
+
+def test_a_chat_in_the_store_before_the_upgrade_must_still_read_back(store, active_profile):
+ """Only what was already gone is excused; losing a stored memory still fails."""
+ from one_memory.hy_sdk_runtime import vector_collection_bases
+ from one_memory.sdk_migration_verify import MemoryReadbackFailed
+
+ home = store.database_path.parent
+ current, _legacy = vector_collection_bases(active_profile)
+ client = _chroma(home)
+ _fill(client, f"{current}_512", ["m1", "m2"])
+ del client
+ _confirmed(store, "m1", "m2", "merged")
+
+ with pytest.raises(MemoryReadbackFailed) as caught:
run_startup_migration(
- data_dir=store.database_path.parent,
+ data_dir=home,
runtime_build="21",
sdk_version="2.0.5",
namespace="governed-v2",
+ open_client=_reading({"m1"}),
)
+ assert caught.value.report.as_document() == {
+ "chat_expected": 2,
+ "chat_readable": 1,
+ "productivity_expected": 0,
+ "productivity_readable": 0,
+ "chat_missing_before_migration": 1,
+ "passed": False,
+ }
assert store.authority() is MemoryAuthority.LEGACY
@@ -1072,7 +1243,13 @@ def test_host_capture_is_fenced_for_the_whole_migration(store):
)
assert result.state == "cutover"
- assert fenced == {"bundle": True, "prepare": True, "cutover": True, "cleanup": True}
+ assert fenced == {
+ "bundle": True,
+ "prepare": True,
+ "vectors": True,
+ "cutover": True,
+ "cleanup": True,
+ }
assert not sdk_migration_capture_fenced(home)
diff --git a/memhub/apps/core/tests/test_sdk_migration_log.py b/memhub/apps/core/tests/test_sdk_migration_log.py
index 95a6c7b..894e711 100644
--- a/memhub/apps/core/tests/test_sdk_migration_log.py
+++ b/memhub/apps/core/tests/test_sdk_migration_log.py
@@ -306,7 +306,7 @@ def test_the_runner_names_the_step_and_sub_step_that_failed(tmp_path, monkeypatc
("step.finished", "preflight.profile_read"),
("step.finished", "preflight.resumable_identity"),
("step.finished", "preflight.legacy_ids_scan"),
- ("step.finished", "preflight.model_profile_check"),
+ ("step.finished", "preflight.vector_space_check"),
("step.finished", "prepare.recover_abandoned_staging"),
("step.finished", "bundle.ensure"),
("step.finished", "bundle.restore_point"),
diff --git a/memhub/apps/core/tests/test_sdk_migration_restore.py b/memhub/apps/core/tests/test_sdk_migration_restore.py
index ae75768..5ef4845 100644
--- a/memhub/apps/core/tests/test_sdk_migration_restore.py
+++ b/memhub/apps/core/tests/test_sdk_migration_restore.py
@@ -463,11 +463,17 @@ def test_a_run_killed_after_its_restore_point_is_rolled_back_on_the_next_start(h
def test_a_preflight_failure_changes_nothing_and_needs_no_restore(home, monkeypatch):
+ def unreadable(_data_dir, _profile):
+ raise DataPlaneMigrationError("sdk_migration_vector_profile_missing")
+
monkeypatch.setattr("one_memory.sdk_migration_runner.read_active_profile", lambda _db: None)
+ monkeypatch.setattr(
+ "one_memory.sdk_migration_runner.vectors_belong_to_another_space", unreadable
+ )
before = _state(home)
report: dict[str, object] = {}
- with pytest.raises(DataPlaneMigrationError, match="sdk_migration_model_profile_required"):
+ with pytest.raises(DataPlaneMigrationError, match="sdk_migration_vector_profile_missing"):
_run(home, report=report)
assert report == {}
diff --git a/memhub/apps/desktop/src/stable-runtime.ts b/memhub/apps/desktop/src/stable-runtime.ts
index 1bb7710..ee7ccf8 100644
--- a/memhub/apps/desktop/src/stable-runtime.ts
+++ b/memhub/apps/desktop/src/stable-runtime.ts
@@ -133,6 +133,7 @@ const SAFE_STABLE_RUNTIME_ERROR_CODES = new Set([
"sdk_migration_preflight_failed",
"sdk_migration_memory_unreadable",
"sdk_migration_model_profile_required",
+ "sdk_migration_vector_profile_missing",
"sdk_migration_model_secret_unavailable",
"sdk_migration_secure_storage_unavailable",
"sdk_migration_disk_space_insufficient",
@@ -219,6 +220,8 @@ export const STABLE_RUNTIME_USER_MESSAGES: Record<string, string> = {
"升级前核对发现,新版本还读不到你的全部记忆,所以没有切换数据源,旧数据保持原样可用。请把这个提示反馈给我们;原有记忆数据不会丢失。",
sdk_migration_model_profile_required:
"升级记忆数据格式需要先有可用的模型配置,用来核对新版本能否读回你的记忆。请在旧版本中完成模型配置后重启;你的记忆数据不会受到影响。",
+ sdk_migration_vector_profile_missing:
+ "你的记忆是用一个已删除的模型配置生成向量的,当前没有可用的模型配置能读回它们,所以没有升级。请在旧版本中重新添加那个模型配置并启用后重启;你的记忆数据不会受到影响。",
sdk_migration_model_secret_unavailable:
"模型密钥读不到(可能被系统钥匙串拒绝),无法核对新版本能否读回你的记忆。请允许 MemHub 访问钥匙串后重新启动;你的记忆数据不会受到影响。",
sdk_migration_secure_storage_unavailable:
diff --git a/memhub/docs/contracts/sdk-data-plane-migration-v1.md b/memhub/docs/contracts/sdk-data-plane-migration-v1.md
index 03e7ac9..83aec8f 100644
--- a/memhub/docs/contracts/sdk-data-plane-migration-v1.md
+++ b/memhub/docs/contracts/sdk-data-plane-migration-v1.md
@@ -77,25 +77,33 @@ then:
2. **prepare**: applies the management schema migrations, discards SDK staging
left by builds through 19 (§5) and makes legacy queue work self-contained
(§4);
-3. **vectors**: for the active embedding profile, renames every
+3. **vectors**: for the active embedding profile (the built-in model when no
+ profile is active), renames every
`one_memory_<old hash>…` collection to the current `memhub_<hash>…` name
through Chroma's public client. A current collection that already holds
writes is merged in first (newer record wins on a shared id); counts are
checked after each step;
4. **verify**: opens the public SDK client exactly as the Runtime will and reads
the legacy confirmed memory ids back (`list_memories`, then `get`). Every
- chat memory must read back. Coding/Working may be fewer, because the SDK's
- Coding reconciler deletes experiences it retires, but not zero when the
- legacy mirror has some. Otherwise the run stops with
- `sdk_migration_memory_unreadable` and the counts, before anything
- irreversible; legacy authority and tables stay intact;
+ confirmed chat memory that was in the vector store before this run (any
+ collection, read before step 3) must read back. A confirmed chat the SDK had
+ already merged or deleted before the upgrade cannot, and is only counted
+ (`chat_missing_before_migration`); if none of them is in the store, none is
+ excused. Coding/Working may be fewer, because the SDK's Coding reconciler
+ deletes experiences it retires, but not zero when the legacy mirror has
+ some. Otherwise the run stops with `sdk_migration_memory_unreadable` and
+ the counts, before anything irreversible; legacy authority and tables stay
+ intact;
5. **cutover**: re-verifies the bundle, repeats §4, commits SDK authority;
6. **cleanup**: drops the legacy tables (including the `evidence_search`
index) and runs `VACUUM` (skipped if the disk is too full).
-A home with legacy memories but no active model profile is not migrated
-(`sdk_migration_model_profile_required`): its collections can be neither named
-nor read back.
+A home with no active model profile has no generation model, but its vectors
+are the built-in embedding model's, the same space the Runtime reads with; it
+migrates through that space and no key is resolved. Only when its legacy
+memories have vectors solely under another embedding space (a profile since
+deleted) is it not migrated (`sdk_migration_vector_profile_missing`, in the
+preflight, before anything changes).
A home already on SDK authority still reports `required` while legacy-named
vector collections exist for its profile (build 20 homes). `sdk-migrate` then