fix(state): SessionDB derives its own store's profile for unstamped session rows

The tui_gateway/run_agent writers now stamp profile_name explicitly, but
every OTHER creation path that passes no profile_name (cli.py /new,
hermes_cli/main.py --create-if-missing, foreign-session import, ACP
adapter, gateway branch/title paths, the #82616 peer self-heal INSERT,
and compression children of legacy NULL parents) still minted
profile_name = NULL rows. Rows minted NULL after the one-shot #94724
legacy-owner backfill ran stayed NULL forever: profile-keyed consumers
(desktop sidebar scope matching, @session:<profile>/<id> deep links, the
fail-closed owner ladder) treat NULL as unowned, so the sessions vanished
from the sidebar with their transcripts intact (#99222).

Fix the class at the choke point instead of chasing call sites: every
profile-tree state.db belongs to exactly one profile, so
SessionDB._insert_session_row (and the peer self-heal INSERT and the
compression-child publisher) derive the store's own profile from db_path
when the caller names none — <root>/state.db -> 'default',
<root>/profiles/<name>/state.db -> <name>. The same single-match contract
backfill_null_session_profiles and the web listing's row_profile stamp
already rely on. Explicit profile_name arguments always win; stores
outside the profile tree (tests, ad-hoc copies) keep NULL — never guess.

E2E-verified with real imports against a temp HERMES_HOME:
before (origin/main) a bare create_session on the default store persisted
NULL; after, 'default' / '<profile>' land in state.db for the default
store, a named-profile store, the peer self-heal insert, and a
compression child of a NULL parent, while explicit args and
outside-tree stores are unchanged.

Refs #99222
This commit is contained in:
Teknium
2026-08-31 05:12:41 -07:00
parent 6874b99d49
commit 5cc3da6827
2 changed files with 201 additions and 5 deletions

View File

@@ -5915,6 +5915,39 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# Session lifecycle
# =========================================================================
_PROFILE_DIR_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
def _own_profile_name(self) -> Optional[str]:
"""The profile that owns THIS store, derived from ``db_path`` alone.
Every profile-tree ``state.db`` belongs to exactly one profile
(``<root>/state.db`` → ``default``,
``<root>/profiles/<name>/state.db`` → ``<name>``), so the derivation
is a single match, never a guess — the same contract
:meth:`backfill_null_session_profiles` and the web listing's
``row_profile`` stamp rely on. Path-based (not
``get_active_profile_name()``) on purpose: a gateway serving a
NON-launch profile opens that profile's store directly, and the row
must be stamped with the store's owner, not the serving process's
launch profile. Returns ``None`` for stores outside the profile tree
(explicit ``db_path`` in tests, ad-hoc copies) — those rows keep the
legacy NULL rather than a fabricated owner.
"""
try:
from hermes_constants import get_default_hermes_root
root = get_default_hermes_root().resolve()
parent = Path(self.db_path).resolve().parent
if parent == root:
return "default"
if parent.parent == root / "profiles" and self._PROFILE_DIR_RE.match(
parent.name
):
return parent.name
except Exception:
logger.debug("own-profile derivation failed", exc_info=True)
return None
def _insert_session_row(
self,
session_id: str,
@@ -5929,7 +5962,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
thread_id: str = None,
parent_session_id: str = None,
cwd: str = None,
profile_name: str = None,
profile_name: Optional[str] = None,
git_repo_root: str = None,
origin_json: str = None,
display_name: str = None,
@@ -5968,7 +6001,23 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
``thread_id``/``display_name``/``origin_json``) are inherited too, so a
crash before the gateway re-records the peer can't strand the child
without a recoverable routing mapping (#59527).
When the caller passes no ``profile_name`` at all, the row is stamped
with THIS store's own profile (:meth:`_own_profile_name`) instead of
NULL. Every ``state.db`` belongs to exactly one profile — the same
single-match contract :meth:`backfill_null_session_profiles` relies
on — so the stamp is derivation, not a guess. Rows minted NULL after
that one-shot #94724 backfill ran stayed NULL forever, and
profile-keyed consumers (desktop sidebar scope matching,
``@session:<profile>/<id>`` deep links, the fail-closed owner ladder)
treat NULL as unowned: the session vanishes from the sidebar even
though its transcript is intact (#99222). Stores outside the profile
tree (explicit ``db_path`` in tests, ad-hoc copies) derive nothing
and keep NULL — never guess.
"""
if not (profile_name or "").strip():
profile_name = self._own_profile_name()
def _do(conn):
system_prompt_hash = self._store_system_prompt(conn, system_prompt)
conn.execute(
@@ -6216,9 +6265,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
"""INSERT INTO sessions (
id, source, user_id, session_key, chat_id,
chat_type, thread_id, display_name, origin_json,
started_at
profile_name, started_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
session_key = COALESCE(sessions.session_key, excluded.session_key),
chat_id = COALESCE(sessions.chat_id, excluded.chat_id),
@@ -6236,6 +6285,11 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
thread_id,
display_name,
origin_json,
# Same ownership stamp as _insert_session_row: a
# self-healed row is a first creation too, and an
# unowned (NULL) row vanishes from profile-keyed
# consumers (#99222).
self._own_profile_name(),
time.time(),
),
)
@@ -7137,8 +7191,13 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# compression-fork backfill (#59527 / cross-profile jump
# fix): the child stays on the parent's profile and keeps
# the gateway routing/origin columns so peer recovery
# still works after a crash at the boundary.
profile_name or parent["profile_name"],
# still works after a crash at the boundary. When neither
# names an owner (legacy NULL parent), stamp this store's
# own profile so the rotated child doesn't extend the
# unowned lineage (#99222).
profile_name
or parent["profile_name"]
or self._own_profile_name(),
parent["user_id"],
parent["session_key"],
parent["chat_id"],

View File

@@ -0,0 +1,137 @@
"""SessionDB stamps its own store's profile onto new session rows (#99222).
Every profile-tree ``state.db`` belongs to exactly one profile, so when a
creation path passes no ``profile_name`` the store derives its own owner
instead of persisting NULL. NULL rows minted after the one-shot #94724
legacy-owner backfill stayed NULL forever and vanished from profile-keyed
consumers (desktop sidebar scope matching, ``@session:<profile>/<id>`` deep
links). Stores outside the profile tree must NOT guess — they keep NULL.
"""
import sqlite3
import pytest
import hermes_state
from hermes_state import SessionDB
@pytest.fixture
def hermes_root(tmp_path, monkeypatch):
root = tmp_path / "hermes"
(root / "profiles" / "workprof").mkdir(parents=True)
monkeypatch.setenv("HERMES_HOME", str(root))
# get_default_hermes_root memoizes on (native_home, env) — the env change
# invalidates the memo by itself, but re-point DEFAULT_DB_PATH so any
# default-constructed SessionDB in the module under test stays sandboxed.
monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", root / "state.db")
return root
def _profile_of(db_path, session_id):
conn = sqlite3.connect(db_path)
try:
row = conn.execute(
"SELECT profile_name FROM sessions WHERE id = ?", (session_id,)
).fetchone()
return row[0] if row else None
finally:
conn.close()
def test_default_store_stamps_default(hermes_root):
db = SessionDB(db_path=hermes_root / "state.db")
try:
db.create_session("s_default", source="cli")
finally:
db.close()
assert _profile_of(hermes_root / "state.db", "s_default") == "default"
def test_named_profile_store_stamps_own_name(hermes_root):
db_path = hermes_root / "profiles" / "workprof" / "state.db"
db = SessionDB(db_path=db_path)
try:
db.create_session("s_prof", source="desktop")
finally:
db.close()
assert _profile_of(db_path, "s_prof") == "workprof"
def test_explicit_profile_name_wins(hermes_root):
db = SessionDB(db_path=hermes_root / "state.db")
try:
db.create_session("s_explicit", source="cli", profile_name="llm-wiki")
finally:
db.close()
assert _profile_of(hermes_root / "state.db", "s_explicit") == "llm-wiki"
def test_store_outside_profile_tree_never_guesses(hermes_root, tmp_path):
db_path = tmp_path / "elsewhere" / "state.db"
db_path.parent.mkdir()
db = SessionDB(db_path=db_path)
try:
db.create_session("s_outside", source="cli")
finally:
db.close()
assert _profile_of(db_path, "s_outside") is None
def test_compression_child_of_null_parent_is_stamped(hermes_root):
db_path = hermes_root / "state.db"
db = SessionDB(db_path=db_path)
try:
db.create_session("s_parent", source="cli")
# Simulate a legacy pre-ownership parent row.
conn = sqlite3.connect(db_path)
conn.execute(
"UPDATE sessions SET profile_name = NULL WHERE id = ?", ("s_parent",)
)
conn.commit()
conn.close()
db.publish_compression_child(
parent_session_id="s_parent",
child_session_id="s_child",
source="cli",
messages=[{"role": "user", "content": "hi"}],
require_compression_lease=False,
)
finally:
db.close()
assert _profile_of(db_path, "s_child") == "default"
def test_peer_self_heal_insert_is_stamped(hermes_root):
db_path = hermes_root / "state.db"
db = SessionDB(db_path=db_path)
try:
# No prior row: the #82616 self-heal INSERT creates it.
db.record_gateway_session_peer(
"s_selfheal",
source="telegram",
user_id="u1",
session_key="k1",
chat_id="c1",
)
finally:
db.close()
assert _profile_of(db_path, "s_selfheal") == "default"
def test_legacy_backfill_still_targets_only_null(hermes_root):
"""The one-shot #94724 backfill contract is unchanged: explicit owners are
never overwritten, and new rows no longer regenerate its input."""
db_path = hermes_root / "state.db"
db = SessionDB(db_path=db_path)
try:
db.create_session("s_new", source="cli")
conn = sqlite3.connect(db_path)
conn.execute("UPDATE sessions SET profile_name = NULL WHERE id = 's_new'")
conn.commit()
conn.close()
assert db.backfill_null_session_profiles("workprof") == 1
assert db.backfill_null_session_profiles("workprof") == 0
finally:
db.close()
assert _profile_of(db_path, "s_new") == "workprof"