Skip to content

The agent that grows with you

fix: repair-profiles reports a ledgered stray instead of copying it

Teknium0d1a35de83d5
diff --git a/hermes_cli/sessions_repair_profiles.py b/hermes_cli/sessions_repair_profiles.py
index eadb669f4de..d93bfeaab77 100644
--- a/hermes_cli/sessions_repair_profiles.py
+++ b/hermes_cli/sessions_repair_profiles.py
@@ -193,7 +193,15 @@ class RepairPlan:
db = session.db(store)
crossed = db.find_crossed_profile_sessions(store.profile)
moving: set[str] = set()
+ held = _ledgered_lineages([r for r in crossed["foreign"] if self._would_move(store, r)])
for row in crossed["foreign"]:
+ if row["id"] in held:
+ moving.add(row["id"]) # neither relabelled nor severed in place: it is a stray
+ self._add(Finding(
+ "wrong_store", store.profile, row["id"],
+ f"key {row['session_key']!r} ({row['message_count']} messages) sits in the "
+ f"{store.profile} store", reason=held[row["id"]]))
+ continue
self._plan_foreign_row(store, row, moving)
for row in crossed["mislabelled"]:
if row["id"] in moving:
@@ -213,6 +221,12 @@ class RepairPlan:
f"{row['parent_profile']!r}", action="sever parent_session_id",
_fix=lambda s, st=store, sid=row["id"]: {"severed": s.db(st).sever_crossed_parents([sid])}))
+ def _would_move(self, store: Store, row: dict[str, Any]) -> bool:
+ """Mirror of :meth:`_plan_foreign_row`: does the plan copy this row to another store?"""
+ if row["key_profile"] == "default" and store.profile != "default":
+ return self.legacy_main == "move" and self.routing_store is not None
+ return row["key_profile"] in self.claimed
+
def _plan_foreign_row(self, store: Store, row: dict[str, Any], moving: set[str]) -> None:
key_profile, sid = row["key_profile"], row["id"]
detail = f"key {row['session_key']!r} ({row['message_count']} messages) sits in the {store.profile} store"
@@ -392,9 +406,16 @@ class _MoveBatch:
if self._result is not None:
return self._result
src_db, dst_db = session.db(self.src), session.db(self.dst)
- payloads = {sid: src_db.export_session_for_move(sid) for sid in self.ids}
+ from hermes_state_profile_repair import SessionLedgeredError
+ payloads: dict[str, Optional[dict[str, Any]]] = {}
+ for sid in self.ids:
+ try:
+ payloads[sid] = src_db.export_session_for_move(sid)
+ except SessionLedgeredError as exc: # gained ledger rows since the scan: never copied
+ self._errors[sid] = exc
ordered = _parents_first([p for p in payloads.values() if p is not None])
- result: dict[str, dict[str, int]] = {sid: {"missing": 1} for sid, p in payloads.items() if p is None}
+ result: dict[str, dict[str, int]] = {sid: {"missing": 1} for sid, p in payloads.items()
+ if p is None and sid not in self._errors}
for payload in ordered:
sid, parent = payload["session"]["id"], payload["session"].get("parent_session_id")
if parent in self._errors:
@@ -429,6 +450,30 @@ class _MoveBatch:
return result
+def _ledgered_lineages(foreign: list[dict[str, Any]]) -> dict[str, str]:
+ """Stray rows that must stay put, each with the reason. A row the gateway ledger references
+ (admissions/workers, ``ON DELETE RESTRICT``) cannot be deleted from its store, so copying it
+ would leave the session in both; the stray rows linked to it by ``parent_session_id`` stay
+ with it, since moving a parent detaches the child left behind and a moved child loses its
+ parent. Whether a move should carry the ledger is a separate policy decision."""
+ by_id = {row["id"]: row for row in foreign}
+ groups: dict[str, set[str]] = {sid: {sid} for sid in by_id}
+ for row in foreign:
+ parent = row.get("parent_session_id")
+ if parent in by_id and groups[parent] is not groups[row["id"]]:
+ merged = groups[parent] | groups[row["id"]]
+ for sid in merged:
+ groups[sid] = merged
+ held: dict[str, str] = {}
+ for sid, row in by_id.items():
+ anchors = sorted(m for m in groups[sid] if by_id[m].get("ledgered"))
+ if row.get("ledgered"):
+ held[sid] = "has gateway admission/worker history, which a move cannot carry"
+ elif anchors:
+ held[sid] = f"its lineage holds {anchors[0]}, which has gateway admission/worker history"
+ return held
+
+
def _parents_first(payloads: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Order moved sessions so every parent in the batch precedes its children (a cycle, impossible
for a well-formed store, falls back to insertion order)."""
diff --git a/hermes_state_profile_repair.py b/hermes_state_profile_repair.py
index 38ff548b919..716f1a14946 100644
--- a/hermes_state_profile_repair.py
+++ b/hermes_state_profile_repair.py
@@ -58,6 +58,13 @@ def _table_columns(conn, table: str) -> list[str]:
_MESSAGE_MOVE_SKIP = frozenset({"id", "display_order"})
+class SessionLedgeredError(RuntimeError):
+ """A session with gateway admission/worker history cannot be moved between stores."""
+
+ def __init__(self, session_id: str) -> None:
+ super().__init__(f"{session_id} has gateway admission/worker history; not moved")
+
+
class SessionProfileRepairMixin:
"""Per-store crossed-profile identity: find, relabel, sever, move, and settle routing/topic rows."""
@@ -78,6 +85,7 @@ class SessionProfileRepairMixin:
" p.session_key AS parent_session_key "
"FROM sessions s LEFT JOIN sessions p ON p.id = s.parent_session_id "
"WHERE s.session_key LIKE 'agent:%' ORDER BY s.started_at, s.id")
+ ledgered = self._ledgered_session_ids()
found: dict[str, list[dict[str, Any]]] = {"mislabelled": [], "foreign": [], "crossed_parents": []}
for row in rows:
key_profile = session_key_profile(row["session_key"])
@@ -91,7 +99,8 @@ class SessionProfileRepairMixin:
if key_profile != owner:
found["foreign"].append({
"id": row["id"], "session_key": row["session_key"], "key_profile": key_profile,
- "message_count": int(row["message_count"] or 0)})
+ "message_count": int(row["message_count"] or 0),
+ "parent_session_id": row["parent_session_id"], "ledgered": row["id"] in ledgered})
parent_profile = session_key_profile(row["parent_session_key"])
if parent_profile is not None and parent_profile != key_profile:
found["crossed_parents"].append({
@@ -99,6 +108,23 @@ class SessionProfileRepairMixin:
"parent_session_id": row["parent_session_id"], "parent_profile": parent_profile})
return found
+ def _ledgered_session_ids(self) -> set[str]:
+ """Sessions the gateway's durable ledger references (``session_admissions`` /
+ ``worker_executions``, both ``ON DELETE RESTRICT``). A move copies only the transcript, so
+ such a row could never leave the source: report it instead of copying it. A store whose
+ schema predates the ledger has none."""
+ def _read(conn):
+ tables = {row[0] for row in conn.execute(
+ "SELECT name FROM sqlite_master WHERE type='table' "
+ "AND name IN ('session_admissions', 'worker_executions')")}
+ ids: set[str] = set()
+ if "session_admissions" in tables:
+ ids.update(r[0] for r in conn.execute("SELECT DISTINCT target_session_id FROM session_admissions"))
+ if "worker_executions" in tables:
+ ids.update(r[0] for r in conn.execute("SELECT DISTINCT session_id FROM worker_executions"))
+ return ids
+ return self._read_retrying_ioerr(_read)
+
def list_gateway_routing_rows(self) -> list[dict[str, Any]]:
return [dict(row) for row in self._read_all(
"SELECT scope, session_key, entry_json, updated_at FROM gateway_routing "
@@ -197,7 +223,12 @@ class SessionProfileRepairMixin:
"SELECT * FROM session_model_usage WHERE session_id = ?", (session_id,))]
return {"session": dict(session), "system_prompt": prompt, "tool_pin": tool_pin, "messages": messages,
"usage": usage}
- return self._read_retrying_ioerr(_read)
+ payload = self._read_retrying_ioerr(_read)
+ if payload is not None and session_id in self._ledgered_session_ids():
+ # Re-checked at apply time: the scan may predate a turn, and copying first would leave
+ # the session in both stores once the ledger's RESTRICT FK refuses the source delete.
+ raise SessionLedgeredError(session_id)
+ return payload
def import_moved_session(self, payload: dict[str, Any], *, profile_name: str) -> str:
"""Insert a moved session into THIS store as *profile_name*'s. ``present`` when the id already
diff --git a/tests/hermes_cli/test_sessions_repair_profiles.py b/tests/hermes_cli/test_sessions_repair_profiles.py
index b33eccbabf4..67c06ab0a4d 100644
--- a/tests/hermes_cli/test_sessions_repair_profiles.py
+++ b/tests/hermes_cli/test_sessions_repair_profiles.py
@@ -334,3 +334,77 @@ def test_a_failing_row_moves_alone_and_its_lineage_waits_with_it(homes, monkeypa
root.close()
acme.close()
assert not any(f["kind"] == "wrong_store" for f in _report()["findings"])
+
+
+def _admit(path: Path, sid: str, status: str) -> None:
+ conn = sqlite3.connect(path)
+ try:
+ conn.execute(
+ "INSERT INTO session_admissions(admission_id,request_id,principal_id,target_session_id,lineage_json,"
+ "payload_json,payload_digest,intent,status,outcome,owner_epoch,generation) "
+ "VALUES(?,?,'p','" + sid + "','[]','{}','d','queue',?,?,1,1)",
+ (f"adm-{sid}-{status}", f"req-{sid}", status, "completed" if status == "terminal" else None))
+ conn.commit()
+ finally:
+ conn.close()
+
+
[email protected]("status", ["terminal", "queued"])
+def test_a_ledgered_stray_is_reported_never_copied(homes, monkeypatch, status):
+ """``session_admissions``/``worker_executions`` reference ``sessions(id) ON DELETE RESTRICT``.
+ The move used to copy such a row into the target and then fail the source delete on the FK,
+ leaving the conversation in BOTH stores on every run. A row with ledger history (settled or
+ live) is report-only, together with the stray lineage linked to it; unrelated strays move."""
+ monkeypatch.setattr("hermes_cli.sessions_cmd_repair_profiles.default_snapshot", lambda store: "snap")
+ root = SessionDB(homes["default"] / "state.db")
+ try:
+ _session(root, "led", "agent:acme:telegram:dm:230", profile="acme")
+ _session(root, "led-kid", "agent:acme:telegram:dm:230", profile="acme", parent="led")
+ _session(root, "free", "agent:acme:telegram:dm:231", profile="acme")
+ finally:
+ root.close()
+ _admit(homes["default"] / "state.db", "led", status)
+
+ findings = {f["subject"]: f for f in _report()["findings"] if f["kind"] == "wrong_store"}
+ assert findings["led"]["action"] is None and "admission" in findings["led"]["reason"]
+ assert findings["led-kid"]["action"] is None and "led" in findings["led-kid"]["reason"]
+ assert findings["free"]["action"] == "move to the acme store"
+
+ assert _run(apply=True) == 0
+ assert _run(apply=True) == 0
+ root = SessionDB(homes["default"] / "state.db")
+ acme = SessionDB(homes["acme"] / "state.db")
+ try:
+ for sid in ("led", "led-kid"):
+ assert root.get_session(sid) is not None and acme.get_session(sid) is None, sid
+ assert root.get_session("led-kid")["parent_session_id"] == "led"
+ assert root.get_session("free") is None and len(acme.get_messages("free")) == 2
+ finally:
+ root.close()
+ acme.close()
+
+
+def test_ledger_rows_that_appear_after_the_scan_still_block_the_copy(homes, monkeypatch):
+ """The fence is re-checked at export: a scan that predates the row's first admission must
+ not copy it (the source delete would then fail and strand a duplicate)."""
+ from hermes_cli.sessions_repair_profiles import scan_stores
+ root = SessionDB(homes["default"] / "state.db")
+ try:
+ _session(root, "late", "agent:acme:telegram:dm:240", profile="acme")
+ finally:
+ root.close()
+ plan, session = scan_stores(read_only=False)
+ try:
+ _admit(homes["default"] / "state.db", "late", "terminal")
+ result = plan.apply(session, snapshot=lambda store: "snap")
+ finally:
+ session.close()
+ assert [f["subject"] for f in result["failures"]] == ["late"]
+ assert "admission/worker history" in result["failures"][0]["error"]
+ root = SessionDB(homes["default"] / "state.db")
+ acme = SessionDB(homes["acme"] / "state.db")
+ try:
+ assert root.get_session("late") is not None and acme.get_session("late") is None
+ finally:
+ root.close()
+ acme.close()