Skip to content
Python

fix(memhub): harden SDK migration inventory

alvinfei1dc7e957c077
diff --git a/memhub/apps/core/src/one_memory/hy_sdk_migration.py b/memhub/apps/core/src/one_memory/hy_sdk_migration.py
index 0d7fabe..71c05e9 100644
--- a/memhub/apps/core/src/one_memory/hy_sdk_migration.py
+++ b/memhub/apps/core/src/one_memory/hy_sdk_migration.py
@@ -101,6 +101,55 @@ class HySdkMigration:
)
return _memory_page(raw, limit=limit, offset=offset)
+ async def list_productivity_memories(self) -> tuple[dict[str, object], ...]:
+ raw = await _sdk_call(
+ "hy_sdk_productivity_inventory_failed",
+ self._loop_thread.run,
+ self._list_productivity_memories(),
+ )
+ return tuple(raw)
+
+ async def _list_productivity_memories(self) -> list[dict[str, object]]:
+ records: list[dict[str, object]] = []
+ for variant in ("working", "coding"):
+ store = await self.client._coding_store_for_exact_get(variant)
+ if store is None:
+ continue
+ with store._lock:
+ experiences = store._conn.execute(
+ "SELECT experience_id,user_id,agent_id,solution "
+ "FROM coding_memory_meta ORDER BY experience_id"
+ ).fetchall()
+ facts = store._conn.execute(
+ "SELECT fact_id,user_id,agent_id,statement,status "
+ "FROM working_fact ORDER BY fact_id"
+ ).fetchall()
+ records.extend(
+ {
+ "memory_id": str(row["experience_id"]),
+ "content": str(row["solution"]),
+ "status": "active",
+ "user_id": str(row["user_id"]),
+ "agent_id": str(row["agent_id"]),
+ "kind": "experience",
+ "variant": variant,
+ }
+ for row in experiences
+ )
+ records.extend(
+ {
+ "memory_id": str(row["fact_id"]),
+ "content": str(row["statement"]),
+ "status": str(row["status"]),
+ "user_id": str(row["user_id"]),
+ "agent_id": str(row["agent_id"]),
+ "kind": "fact",
+ "variant": variant,
+ }
+ for row in facts
+ )
+ return records
+
async def read_productivity_memory(
self,
memory_id: str,
diff --git a/memhub/apps/core/src/one_memory/sdk_migration_inventory.py b/memhub/apps/core/src/one_memory/sdk_migration_inventory.py
index 3d891c1..a929141 100644
--- a/memhub/apps/core/src/one_memory/sdk_migration_inventory.py
+++ b/memhub/apps/core/src/one_memory/sdk_migration_inventory.py
@@ -185,6 +185,10 @@ class SdkMigrationClient(Protocol):
variant: str | None,
) -> Awaitable[tuple[HySdkMemoryRecord, str] | None]: ...
+ def list_productivity_memories(
+ self,
+ ) -> Awaitable[tuple[dict[str, object], ...]]: ...
+
def delete_productivity_memory(
self,
memory_id: str,
@@ -293,18 +297,17 @@ def read_legacy_raw_inventory(
role,written_by,created_at,imported_at,verbatim,content_hash,revision
FROM evidence
WHERE content_kind='raw_conversation'
- AND COALESCE(created_at, imported_at) >= ?
AND (
(role='user' AND written_by='person')
OR role='assistant'
)
- ORDER BY source_id,conversation_id,COALESCE(created_at,imported_at),
+ ORDER BY source_id,conversation_id,workspace,
+ COALESCE(created_at,imported_at),
COALESCE(ingest_seq,rowid),evidence_id
- """,
- (cutoff.astimezone(UTC).isoformat(),),
+ """
).fetchall()
turns: list[LegacyRawInventory] = []
- current_key: tuple[str, str, str] | None = None
+ current_key: tuple[str, str, str, str] | None = None
current: list[sqlite3.Row] = []
def finish() -> None:
@@ -314,19 +317,25 @@ def read_legacy_raw_inventory(
if not assistants:
return
rows_for_turn = [current[0], *assistants]
+ completed_at = _parse_datetime(
+ assistants[-1]["created_at"] or assistants[-1]["imported_at"]
+ )
+ if completed_at is not None and completed_at.tzinfo is None:
+ completed_at = completed_at.replace(tzinfo=UTC)
+ if completed_at is None or completed_at.astimezone(UTC) < cutoff.astimezone(UTC):
+ return
evidence_ids = [str(row["evidence_id"]) for row in rows_for_turn]
source = str(current[0]["source_id"])
session_id = str(current[0]["conversation_id"])
digest = hashlib.sha256(
"\0".join((source, session_id, *evidence_ids)).encode()
).hexdigest()
- user_text = sanitize_model_input(
- str(rows_for_turn[0]["verbatim"]).strip()
- )[:_RAW_USER_MAX_CHARACTERS]
+ raw_user_text = str(rows_for_turn[0]["verbatim"] or "")
+ user_text = sanitize_model_input(raw_user_text)[:_RAW_USER_MAX_CHARACTERS]
content_parts = [f"[user]: {user_text}"]
- truncated = len(str(rows_for_turn[0]["verbatim"]).strip()) > len(user_text)
+ truncated = len(raw_user_text) > len(user_text)
for row in assistants:
- sanitized = sanitize_model_input(str(row["verbatim"]).strip())
+ sanitized = sanitize_model_input(str(row["verbatim"] or ""))
text = sanitized
prefix = "[assistant]: "
remaining = _RAW_TURN_MAX_CHARACTERS - len("\n".join(content_parts)) - 1
@@ -370,6 +379,7 @@ def read_legacy_raw_inventory(
str(row["source_id"]),
str(row["conversation_id"]),
str(row["user_id"]),
+ str(row["workspace"] or ""),
)
if key != current_key:
finish()
@@ -388,13 +398,39 @@ def classify_memory_inventory(
sdk: tuple[SdkMemoryInventory, ...],
) -> tuple[MemoryMigrationDecision, ...]:
"""Classify every legacy and SDK memory; no item may silently disappear."""
- sdk_by_id = {item.memory_id: item for item in sdk}
- claimed_sdk_ids: set[str] = set()
+ sdk_by_id: dict[str, list[SdkMemoryInventory]] = {}
+ for sdk_item in sdk:
+ sdk_by_id.setdefault(sdk_item.memory_id, []).append(sdk_item)
+ claimed_sdk_items: set[tuple[str, str | None, str | None]] = set()
decisions: list[MemoryMigrationDecision] = []
for item in legacy:
- current = sdk_by_id.get(item.canonical_memory_id)
+ candidates = [
+ candidate
+ for candidate in sdk_by_id.get(item.canonical_memory_id, ())
+ if (
+ candidate.productivity_kind == item.productivity_kind
+ and (
+ item.productivity_kind is None
+ or item.productivity_variant is None
+ or candidate.productivity_variant == item.productivity_variant
+ )
+ )
+ ]
+ if len(candidates) > 1:
+ claimed_sdk_items.update(_sdk_inventory_key(candidate) for candidate in candidates)
+ decisions.append(
+ MemoryMigrationDecision(
+ item_key=f"memory:{item.legacy_memory_id}",
+ action="quarantine",
+ legacy_memory_id=item.legacy_memory_id,
+ canonical_memory_id=item.canonical_memory_id,
+ reason="sdk_memory_id_ambiguous",
+ )
+ )
+ continue
+ current = candidates[0] if candidates else None
if current is not None:
- claimed_sdk_ids.add(current.memory_id)
+ claimed_sdk_items.add(_sdk_inventory_key(current))
if item.status == "deleted":
decisions.append(
MemoryMigrationDecision(
@@ -474,10 +510,10 @@ def classify_memory_inventory(
)
for sdk_item in sdk:
- if sdk_item.memory_id not in claimed_sdk_ids:
+ if _sdk_inventory_key(sdk_item) not in claimed_sdk_items:
decisions.append(
MemoryMigrationDecision(
- item_key=f"sdk:{sdk_item.memory_id}",
+ item_key=_sdk_item_key(sdk_item),
action="adopt",
legacy_memory_id=None,
canonical_memory_id=sdk_item.memory_id,
@@ -487,6 +523,25 @@ def classify_memory_inventory(
return tuple(decisions)
+def _sdk_inventory_key(
+ item: SdkMemoryInventory,
+) -> tuple[str, str | None, str | None]:
+ return (
+ item.memory_id,
+ item.productivity_kind,
+ item.productivity_variant,
+ )
+
+
+def _sdk_item_key(item: SdkMemoryInventory) -> str:
+ namespace = (
+ f"{item.productivity_variant}:{item.productivity_kind}"
+ if item.productivity_kind is not None
+ else "chat"
+ )
+ return f"sdk:{namespace}:{item.memory_id}"
+
+
async def read_sdk_memory_inventory(
client: SdkMigrationClient,
*,
@@ -494,7 +549,7 @@ async def read_sdk_memory_inventory(
user_id: str = "local",
page_size: int = 500,
) -> tuple[SdkMemoryInventory, ...]:
- records: dict[str, SdkMemoryInventory] = {}
+ records: list[SdkMemoryInventory] = []
offset = 0
while True:
page = await client.list_memories(
@@ -505,41 +560,45 @@ async def read_sdk_memory_inventory(
order="asc",
)
for memory in page.memories:
- records[memory.memory_id] = SdkMemoryInventory(
- memory_id=memory.memory_id,
- user_id=memory.user_id,
- agent_id=memory.agent_id,
- content_hash=content_hash(memory.content),
- status=memory.status,
+ records.append(
+ SdkMemoryInventory(
+ memory_id=memory.memory_id,
+ user_id=memory.user_id,
+ agent_id=memory.agent_id,
+ content_hash=content_hash(memory.content),
+ status=memory.status,
+ )
)
consumed = len(page.memories)
offset += consumed
if consumed == 0 or offset >= page.total:
break
- for item in legacy:
- if (
- item.productivity_kind is None
- or item.canonical_memory_id in records
- ):
- continue
- resolved = await client.read_productivity_memory(
- item.canonical_memory_id,
- kind=item.productivity_kind,
- variant=item.productivity_variant,
- )
- if resolved is None:
- continue
- memory, actual_variant = resolved
- records[memory.memory_id] = SdkMemoryInventory(
- memory_id=memory.memory_id,
- user_id=memory.user_id,
- agent_id=memory.agent_id,
- content_hash=content_hash(memory.content),
- status=memory.status or "active",
- productivity_kind=item.productivity_kind,
- productivity_variant=actual_variant,
+ del legacy
+ for memory in await client.list_productivity_memories():
+ try:
+ records.append(
+ SdkMemoryInventory(
+ memory_id=str(memory["memory_id"]),
+ user_id=str(memory["user_id"]),
+ agent_id=str(memory["agent_id"]),
+ content_hash=content_hash(str(memory["content"])),
+ status=str(memory["status"]),
+ productivity_kind=str(memory["kind"]),
+ productivity_variant=str(memory["variant"]),
+ )
+ )
+ except KeyError as error:
+ raise RuntimeError("invalid productivity inventory row") from error
+ return tuple(
+ sorted(
+ records,
+ key=lambda item: (
+ item.memory_id,
+ item.productivity_kind or "",
+ item.productivity_variant or "",
+ ),
)
- return tuple(records[key] for key in sorted(records))
+ )
def record_memory_migration_plan(
@@ -551,12 +610,12 @@ def record_memory_migration_plan(
) -> tuple[MemoryMigrationDecision, ...]:
decisions = classify_memory_inventory(legacy, sdk)
legacy_by_id = {item.legacy_memory_id: item for item in legacy}
- sdk_by_id = {item.memory_id: item for item in sdk}
+ sdk_by_item_key = {_sdk_item_key(item): item for item in sdk}
for decision in decisions:
source_hash = (
legacy_by_id[decision.legacy_memory_id].content_hash
if decision.legacy_memory_id is not None
- else sdk_by_id[decision.canonical_memory_id].content_hash
+ else sdk_by_item_key[decision.item_key].content_hash
)
operation_key = hashlib.sha256(
f"{migration_id}:{decision.item_key}:{decision.action}:{source_hash}".encode()
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 9dac2de..5586472 100644
--- a/memhub/apps/core/tests/test_sdk_data_plane_migration.py
+++ b/memhub/apps/core/tests/test_sdk_data_plane_migration.py
@@ -442,7 +442,7 @@ def test_inventory_classification_covers_every_legacy_and_sdk_state():
assert by_key["memory:delete-existing"].action == "delete"
assert by_key["memory:divergent"].action == "quarantine"
assert by_key["memory:unknown-layer"].reason == "legacy_layer_unknown"
- assert by_key["sdk:sdk-only"].action == "adopt"
+ assert by_key["sdk:chat:sdk-only"].action == "adopt"
assert len(decisions) == 8
@@ -484,9 +484,21 @@ class _MigrationClient:
return memory, candidate
return None
- async def delete_productivity_memory(
- self, memory_id, *, kind, variant, user_id
- ):
+ async def list_productivity_memories(self):
+ return tuple(
+ {
+ "memory_id": memory.memory_id,
+ "content": memory.content,
+ "status": memory.status or "active",
+ "user_id": memory.user_id,
+ "agent_id": memory.agent_id,
+ "kind": kind,
+ "variant": variant,
+ }
+ for (_memory_id, kind, variant), memory in self.productivity.items()
+ )
+
+ async def delete_productivity_memory(self, memory_id, *, kind, variant, user_id):
self.deleted_productivity.append((memory_id, kind, variant, user_id))
return {"success": True, "deleted_count": 1}
@@ -568,10 +580,17 @@ def test_sdk_inventory_adopts_mapped_productivity_ids_and_deletes_user_removed_f
user_id="local",
agent_id="scope",
),
+ ("sdk-only", "experience", "working"): HySdkMemoryRecord(
+ memory_id="sdk-only",
+ content="sdk only",
+ layer="experience",
+ status="active",
+ is_latest=True,
+ user_id="local",
+ agent_id="another-scope",
+ ),
}
- sdk = asyncio.run(
- read_sdk_memory_inventory(client, legacy=(active, deleted))
- )
+ sdk = asyncio.run(read_sdk_memory_inventory(client, legacy=(active, deleted)))
_start(store)
decisions = record_memory_migration_plan(
store,
@@ -582,6 +601,7 @@ def test_sdk_inventory_adopts_mapped_productivity_ids_and_deletes_user_removed_f
by_key = {decision.item_key: decision for decision in decisions}
assert by_key["memory:exp"].action == "matched"
assert by_key["memory:fact"].action == "delete"
+ assert by_key["sdk:working:experience:sdk-only"].action == "adopt"
asyncio.run(
execute_memory_migration_plan(
@@ -593,9 +613,26 @@ def test_sdk_inventory_adopts_mapped_productivity_ids_and_deletes_user_removed_f
)
)
assert client.imported == []
- assert client.deleted_productivity == [
- ("fact", "fact", None, "local")
- ]
+ assert client.deleted_productivity == [("fact", "fact", None, "local")]
+
+
+def test_productivity_id_in_both_variants_is_quarantined():
+ legacy = (_legacy("fact", layer="working_fact"),)
+ sdk = (
+ _sdk(
+ "fact",
+ productivity_kind="fact",
+ productivity_variant="working",
+ ),
+ _sdk(
+ "fact",
+ productivity_kind="fact",
+ productivity_variant="coding",
+ ),
+ )
+ (decision, *_sdk_only) = classify_memory_inventory(legacy, sdk)
+ assert decision.action == "quarantine"
+ assert decision.reason == "sdk_memory_id_ambiguous"
def test_recorded_plan_executes_import_delete_alias_and_adoption(store):
@@ -650,42 +687,109 @@ def test_legacy_raw_inventory_builds_recent_user_assistant_turns_without_tools(s
""",
(
(
- "u1", "k1", "local", "cursor", "/repo", "project",
- "session", "m1", "1", "raw_conversation", "user",
- "person", "2026-10-22T00:00:00+00:00", "question",
- content_hash("question"), 1, "2026-10-22T00:00:00+00:00",
- "2026-10-22T00:00:00+00:00", 1,
+ "u1",
+ "k1",
+ "local",
+ "cursor",
+ "/repo",
+ "project",
+ "session",
+ "m1",
+ "1",
+ "raw_conversation",
+ "user",
+ "person",
+ "2026-10-22T00:00:00+00:00",
+ "question",
+ content_hash("question"),
+ 1,
+ "2026-10-22T00:00:00+00:00",
+ "2026-10-22T00:00:00+00:00",
+ 1,
),
(
- "t1", "k2", "local", "cursor", "/repo", "project",
- "session", "m2", "2", "raw_conversation", "tool",
- "tool", "2026-10-22T00:00:01+00:00", "secret tool output",
- content_hash("secret tool output"), 1,
+ "t1",
+ "k2",
+ "local",
+ "cursor",
+ "/repo",
+ "project",
+ "session",
+ "m2",
+ "2",
+ "raw_conversation",
+ "tool",
+ "tool",
+ "2026-10-22T00:00:01+00:00",
+ "secret tool output",
+ content_hash("secret tool output"),
+ 1,
"2026-10-22T00:00:01+00:00",
- "2026-10-22T00:00:01+00:00", 2,
+ "2026-10-22T00:00:01+00:00",
+ 2,
),
(
- "a1", "k3", "local", "cursor", "/repo", "project",
- "session", "m3", "3", "raw_conversation", "assistant",
- "agent", "2026-10-22T00:00:02+00:00", "answer",
- content_hash("answer"), 1, "2026-10-22T00:00:02+00:00",
- "2026-10-22T00:00:02+00:00", 3,
+ "a1",
+ "k3",
+ "local",
+ "cursor",
+ "/repo",
+ "project",
+ "session",
+ "m3",
+ "3",
+ "raw_conversation",
+ "assistant",
+ "agent",
+ "2026-10-22T00:00:02+00:00",
+ "answer",
+ content_hash("answer"),
+ 1,
+ "2026-10-22T00:00:02+00:00",
+ "2026-10-22T00:00:02+00:00",
+ 3,
),
(
- "old-u", "k4", "local", "cursor", "/repo", "project",
- "old-session", "m4", "4", "raw_conversation", "user",
- "person", "2026-10-01T00:00:00+00:00", "old question",
- content_hash("old question"), 1,
+ "old-u",
+ "k4",
+ "local",
+ "cursor",
+ "/repo",
+ "project",
+ "old-session",
+ "m4",
+ "4",
+ "raw_conversation",
+ "user",
+ "person",
+ "2026-10-01T00:00:00+00:00",
+ "old question",
+ content_hash("old question"),
+ 1,
+ "2026-10-01T00:00:00+00:00",
"2026-10-01T00:00:00+00:00",
- "2026-10-01T00:00:00+00:00", 4,
+ 4,
),
(
- "old-a", "k5", "local", "cursor", "/repo", "project",
- "old-session", "m5", "5", "raw_conversation", "assistant",
- "agent", "2026-10-01T00:00:01+00:00", "old answer",
- content_hash("old answer"), 1,
+ "old-a",
+ "k5",
+ "local",
+ "cursor",
+ "/repo",
+ "project",
+ "old-session",
+ "m5",
+ "5",
+ "raw_conversation",
+ "assistant",
+ "agent",
"2026-10-01T00:00:01+00:00",
- "2026-10-01T00:00:01+00:00", 5,
+ "old answer",
+ content_hash("old answer"),
+ 1,
+ "2026-10-01T00:00:01+00:00",
+ "2026-10-01T00:00:01+00:00",
+ 5,
),
),
)
@@ -703,6 +807,86 @@ def test_legacy_raw_inventory_builds_recent_user_assistant_turns_without_tools(s
assert raw.memory_at.isoformat() == "2026-10-22T00:00:00+00:00"
+def test_raw_turn_cutoff_uses_completion_time_and_keeps_workspaces_separate(store):
+ database = store.database_path
+ rows = (
+ ("u0", "k0", "shared", "w0", "user", "person", "before", "2026-10-19T23:59:00+00:00", 1),
+ ("a0", "k1", "shared", "w0", "assistant", "agent", "after", "2026-10-20T00:01:00+00:00", 2),
+ ("u1", "k2", "same-session", "w1", "user", "person", "one", "2026-10-21T00:00:00+00:00", 3),
+ (
+ "a1",
+ "k3",
+ "same-session",
+ "w1",
+ "assistant",
+ "agent",
+ "first",
+ "2026-10-21T00:01:00+00:00",
+ 4,
+ ),
+ ("u2", "k4", "same-session", "w2", "user", "person", "two", "2026-10-21T00:02:00+00:00", 5),
+ (
+ "a2",
+ "k5",
+ "same-session",
+ "w2",
+ "assistant",
+ "agent",
+ "second",
+ "2026-10-21T00:03:00+00:00",
+ 6,
+ ),
+ )
+ with main_database(database).write() as connection, connection:
+ connection.executemany(
+ """
+ INSERT INTO evidence (
+ evidence_id,idempotency_key,user_id,source_id,conversation_id,
+ workspace,content_kind,role,written_by,verbatim,content_hash,
+ revision,created_at,imported_at,updated_at,ingest_seq
+ ) VALUES (?,?,'local','cursor',?,?,'raw_conversation',?,?,?,? ,1,?,?,?,?)
+ """,
+ tuple(
+ (
+ evidence_id,
+ key,
+ session,
+ workspace,
+ role,
+ written_by,
+ text,
+ content_hash(text),
+ timestamp,
+ timestamp,
+ timestamp,
+ sequence,
+ )
+ for (
+ evidence_id,
+ key,
+ session,
+ workspace,
+ role,
+ written_by,
+ text,
+ timestamp,
+ sequence,
+ ) in rows
+ ),
+ )
+
+ turns = read_legacy_raw_inventory(
+ database,
+ cutoff=datetime.fromisoformat("2026-10-20T00:00:00+00:00"),
+ )
+ assert {turn.content for turn in turns} == {
+ "[user]: before\n[assistant]: after",
+ "[user]: one\n[assistant]: first",
+ "[user]: two\n[assistant]: second",
+ }
+ assert {turn.metadata["workspace"] for turn in turns} == {"w0", "w1", "w2"}
+
+
def _legacy_raw(evidence_id, *, content="verbatim"):
return LegacyRawInventory(
evidence_id=evidence_id,
@@ -937,9 +1121,7 @@ class _MigrationVectorStore:
async def list_by_user(self, *, user_id, layers, **_kwargs):
return [
- node
- for node in self.nodes.values()
- if node.user_id == user_id and node.layer in layers
+ node for node in self.nodes.values() if node.user_id == user_id and node.layer in layers
]
@@ -969,10 +1151,19 @@ class _MigrationFactVector:
class _MigrationCodingStore:
def __init__(self):
self._conn = sqlite3.connect(":memory:", check_same_thread=False)
+ self._conn.row_factory = sqlite3.Row
+ self._conn.execute(
+ "CREATE TABLE coding_memory_meta ("
+ "experience_id TEXT PRIMARY KEY,user_id TEXT,agent_id TEXT,solution TEXT)"
+ )
self._conn.execute(
- "CREATE TABLE working_fact (fact_id TEXT PRIMARY KEY, user_id TEXT)"
+ "CREATE TABLE working_fact ("
+ "fact_id TEXT PRIMARY KEY,user_id TEXT,agent_id TEXT,"
+ "statement TEXT,status TEXT)"
+ )
+ self._conn.execute(
+ "INSERT INTO working_fact VALUES ('fact-1','local','scope','fact body','active')"
)
- self._conn.execute("INSERT INTO working_fact VALUES ('fact-1','local')")
self._conn.commit()
self._lock = threading.Lock()
self._fact_vec = _MigrationFactVector()
@@ -1044,6 +1235,7 @@ def test_offline_migration_writes_sdk_stores_without_public_client_import_method
)
)
raw_page = asyncio.run(migration.read_raw_inventory(user_id="local"))
+ productivity = asyncio.run(migration.list_productivity_memories())
deleted = asyncio.run(
migration.delete_productivity_memory(
"fact-1",
@@ -1056,17 +1248,23 @@ def test_offline_migration_writes_sdk_stores_without_public_client_import_method
assert raw_result["raw_id"] == "raw-1"
assert memory_result["memory_id"] == "memory-1"
assert [item.raw_id for item in raw_page.raw] == ["raw-1"]
+ assert productivity == (
+ {
+ "memory_id": "fact-1",
+ "content": "fact body",
+ "status": "active",
+ "user_id": "local",
+ "agent_id": "scope",
+ "kind": "fact",
+ "variant": "coding",
+ },
+ )
assert client._vector_store.nodes["raw-1"].layer is MemoryLayer.L1_RAW
assert client._vector_store.nodes["memory-1"].status is MemoryStatus.ACTIVE
assert client._graph_store.nodes["memory-1"].content == "prefers tea"
assert deleted["deleted_count"] == 1
assert client._coding._fact_vec.deleted == ["fact-1"]
- assert (
- client._coding._conn.execute(
- "SELECT COUNT(*) FROM working_fact"
- ).fetchone()[0]
- == 0
- )
+ assert client._coding._conn.execute("SELECT COUNT(*) FROM working_fact").fetchone()[0] == 0
assert not hasattr(client, "import_raw")
assert not hasattr(client, "import_memory_exact")
diff --git a/memhub/apps/desktop/src/startup-sdk-migration.test.ts b/memhub/apps/desktop/src/startup-sdk-migration.test.ts
index b1371ea..8219e96 100644
--- a/memhub/apps/desktop/src/startup-sdk-migration.test.ts
+++ b/memhub/apps/desktop/src/startup-sdk-migration.test.ts
@@ -32,6 +32,7 @@ it("fences hook capture only while startup migration is running", async () => {
it("runs bundle backfill and cutover inside the startup maintenance fence", async () => {
const calls: string[][] = [];
+ const ordering: string[] = [];
const execute = vi.fn(async (_core, args: string[]) => {
calls.push(args);
const command = args[0];
@@ -57,7 +58,19 @@ it("runs bundle backfill and cutover inside the startup maintenance fence", asyn
action: () => Promise<T>,
): Promise<T> => {
fenceCalls.push(dataDir);
- return action();
+ ordering.push("runtime-fence:start");
+ const result = await action();
+ ordering.push("runtime-fence:end");
+ return result;
+ };
+ const orderedCaptureFence = async <T>(
+ _dataDir: string,
+ action: () => Promise<T>,
+ ): Promise<T> => {
+ ordering.push("capture-fence:start");
+ const result = await action();
+ ordering.push("capture-fence:end");
+ return result;
};
const result = await runStartupSdkMigration({
@@ -66,11 +79,17 @@ it("runs bundle backfill and cutover inside the startup maintenance fence", asyn
runtimeBuild: "build-13",
execute,
fence,
- captureFence,
+ captureFence: orderedCaptureFence,
});
expect(result).toEqual({ state: "cutover" });
expect(fenceCalls).toEqual(["/data"]);
+ expect(ordering).toEqual([
+ "capture-fence:start",
+ "runtime-fence:start",
+ "runtime-fence:end",
+ "capture-fence:end",
+ ]);
expect(calls.map((args) => args[0])).toEqual([
"sdk-migration-status",
"migration-bundle",
diff --git a/memhub/apps/desktop/src/startup-sdk-migration.ts b/memhub/apps/desktop/src/startup-sdk-migration.ts
index a4e2e81..e49d249 100644
--- a/memhub/apps/desktop/src/startup-sdk-migration.ts
+++ b/memhub/apps/desktop/src/startup-sdk-migration.ts
@@ -63,8 +63,8 @@ export async function runStartupSdkMigration(
status.document.authority === "sdk" &&
status.document.state === "cleanup_required"
) {
- return fence(options.dataDir, () =>
- captureFence(options.dataDir, async () => {
+ return captureFence(options.dataDir, () =>
+ fence(options.dataDir, async () => {
const cleanup = await execute(
options.core,
["sdk-cleanup", "--yes", "--json"],
@@ -97,8 +97,8 @@ export async function runStartupSdkMigration(
? previousMigrationId
: `${MIGRATION_PREFIX}-${generation}`;
const bundleId = canResume ? previousBundleId : `${migrationId}-pre-cutover`;
- return fence(options.dataDir, () =>
- captureFence(options.dataDir, async () => {
+ return captureFence(options.dataDir, () =>
+ fence(options.dataDir, async () => {
const bundle = await execute(
options.core,
[