Skip to content

The agent that grows with you

fix(onboarding): a run change lands on the compression tip in its own transaction

alt-glitchbad05d696183
diff --git a/agent/onboarding_record.py b/agent/onboarding_record.py
index a9f51e938e2..092e55c7e2f 100644
--- a/agent/onboarding_record.py
+++ b/agent/onboarding_record.py
@@ -38,8 +38,9 @@ def load(db, session_id: str) -> dict | None:
def _transition(db, session_id: str, event: Event | None) -> Step | None:
- """Expire, apply *event* and write the result in one database transaction, so Skip setup pressed
- while a card answer is being applied is never overwritten by the older copy. An ended run then
+ """Expire, apply *event* and write the result in one database transaction at the compression tip,
+ so Skip setup pressed while a card answer is being applied is never overwritten by the older copy,
+ and an id read before a rotation published still lands on the copy the chat reads. An ended run then
closes the install flag (a Skip or Done retried after a failed config write repairs it), unless
another run is still open: the flag belongs to that run, and an old chat must not end it."""
holder: dict[str, Step] = {}
@@ -54,7 +55,7 @@ def _transition(db, session_id: str, event: Event | None) -> Step | None:
if event is not None else Step(record, {}))
return holder["step"].record
- db.update_session_model_config_value(session_id, KEY, update)
+ db.update_conversation_model_config_value(session_id, KEY, update)
step = holder.get("step")
if step is not None and not is_active(step.record) and active_session_id(db) is None:
_close_install_flag()
diff --git a/hermes_state_compression.py b/hermes_state_compression.py
index 6539d5690fa..49d02ded151 100644
--- a/hermes_state_compression.py
+++ b/hermes_state_compression.py
@@ -86,6 +86,25 @@ _CHAIN_CAP = 1000
_CONVERSATION_MODEL_CONFIG_KEYS = ("onboarding_run",)
+def _walk_compression_chain(session_id: str, step) -> list[str]:
+ """Root-first ids from *session_id* through its tip; ``step(id)`` returns the ``_CHAIN_STEP_SQL`` row."""
+ current = session_id
+ chain = [current] if current else []
+ seen = set(chain)
+ # Defensive bound; ``seen`` guards cycles. 100 truncated real
+ # compression lineages (~180 deep), stranding root→tip walks on a
+ # stale mid id (#125041).
+ for _ in range(_CHAIN_CAP):
+ row = step(current)
+ child_id = row["id"] if row is not None else None
+ if not child_id or child_id in seen:
+ return chain
+ seen.add(child_id)
+ current = child_id
+ chain.append(child_id)
+ return chain
+
+
class SessionCompressionMixin:
"""Compression lineage, cooldown/streak counters, locks and turn leases."""
@@ -752,22 +771,10 @@ class SessionCompressionMixin:
written, while a stale websocket later creates a sibling that passes it). Instead exclude
branch/delegate/tool children and prefer children that continue the chain or are still live over
stale closed siblings such as ``ws_orphan_reap``."""
- current = session_id
- chain = [current] if current else []
- seen = set(chain)
- # Defensive bound; ``seen`` guards cycles. 100 truncated real
- # compression lineages (~180 deep), stranding root→tip walks on a
- # stale mid id (#125041).
- for _ in range(_CHAIN_CAP):
+ def step(current: str):
with self._read_ctx() as conn:
- row = conn.execute(_CHAIN_STEP_SQL, (current,)).fetchone()
- child_id = row["id"] if row is not None else None
- if not child_id or child_id in seen:
- return chain
- seen.add(child_id)
- current = child_id
- chain.append(child_id)
- return chain
+ return conn.execute(_CHAIN_STEP_SQL, (current,)).fetchone()
+ return _walk_compression_chain(session_id, step)
def get_compression_tip(self, session_id: str) -> Optional[str]:
"""Live tip of a compression chain (``get_compression_chain`` semantics); the input
@@ -775,6 +782,11 @@ class SessionCompressionMixin:
chain = self.get_compression_chain(session_id)
return chain[-1] if chain else session_id
+ def _compression_tip_on(self, conn, session_id: str) -> str:
+ """``get_compression_tip`` read on a writer's own connection: inside its transaction no rotation
+ can publish between finding the tip and writing it."""
+ return _walk_compression_chain(session_id, lambda current: conn.execute(_CHAIN_STEP_SQL, (current,)).fetchone())[-1]
+
def _is_compression_child_row(self, child: dict[str, Any]) -> bool:
parent_id = child.get("parent_session_id")
# A reset fork of a compression-ended parent is its own conversation, not the continuation (#114271).
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.py
index 25d657b4feb..0755614a6e3 100644
--- a/hermes_state_sessions.py
+++ b/hermes_state_sessions.py
@@ -832,21 +832,25 @@ class SessionSessionsMixin:
session = self.get_session(session_id) or {}
return _parse_model_config(session.get("model_config")).get(key, default)
- def update_session_model_config_value(self, session_id: str, key: str, update: Callable[[Any], Any]) -> bool:
- """Read ``key``, write ``update(value)`` back, in one write transaction, so a concurrent writer of
- the same key cannot be overwritten with a stale copy. ``update`` may run more than once (lock
- retry) and must be pure; returning None removes the key. False when the row does not exist."""
- def _do(conn) -> bool:
- row = conn.execute("SELECT model_config FROM sessions WHERE id = ?", (session_id,)).fetchone()
+ def update_conversation_model_config_value(self, session_id: str, key: str,
+ update: Callable[[Any], Any]) -> Optional[str]:
+ """Read a conversation-wide ``key`` at *session_id*'s compression tip and write ``update(value)``
+ back, in one write transaction: a concurrent writer of the key cannot be overwritten with a stale
+ copy, and a rotation cannot publish between finding the tip and writing it (the child would keep
+ the old copy). ``update`` may run more than once (lock retry) and must be pure; returning None
+ removes the key. Returns the id written, None when the row does not exist."""
+ def _do(conn) -> Optional[str]:
+ tip = self._compression_tip_on(conn, session_id)
+ row = conn.execute("SELECT model_config FROM sessions WHERE id = ?", (tip,)).fetchone()
if row is None:
- return False
+ return None
config = _parse_model_config(row[0])
if (value := update(config.get(key))) is None:
config.pop(key, None)
else:
config[key] = value
- conn.execute("UPDATE sessions SET model_config = ? WHERE id = ?", (json.dumps(config), session_id))
- return True
+ conn.execute("UPDATE sessions SET model_config = ? WHERE id = ?", (json.dumps(config), tip))
+ return tip
return self._execute_write(_do)
def session_ids_with_model_config_key(self, key: str) -> list[str]:
diff --git a/tests/tui_gateway/test_onboarding_session.py b/tests/tui_gateway/test_onboarding_session.py
index 9e30728f5d9..373eb30a500 100644
--- a/tests/tui_gateway/test_onboarding_session.py
+++ b/tests/tui_gateway/test_onboarding_session.py
@@ -197,6 +197,24 @@ def test_a_compression_rotation_carries_the_run_record(root):
assert onboarding_record.active_session_id(db) is None
+def test_skip_that_read_the_id_before_a_rotation_ends_the_run_at_the_tip(root, monkeypatch):
+ """Compression published a child between Skip reading the agent's id and writing the record."""
+ from hermes_cli.config import read_user_config_raw
+ db = server._get_db()
+ db.create_session("parent", "desktop")
+ onboarding_record.start(db, "parent", FACTS)
+ db.publish_compression_child(parent_session_id="parent", child_session_id="child", source="desktop",
+ messages=[{"role": "user", "content": "summary"}],
+ require_compression_lease=False)
+ monkeypatch.setitem(server._sessions, "ui-onb",
+ {"session_key": "parent", "agent": _agent(db, "parent"), "source": "desktop"})
+
+ assert _call("onboarding.skip", {"session_id": "ui-onb"})["result"] == {"skipped": True}
+ assert onboarding_record.load(db, "child")["phase"] == "skipped"
+ assert onboarding_record.active_session_id(db) is None
+ assert read_user_config_raw(root / "config.yaml")["onboarding"]["run"] is False
+
+
def test_a_skip_retried_after_a_failed_config_write_closes_the_install_flag(root, monkeypatch):
from hermes_cli import onboarding_run
from hermes_cli.config import read_user_config_raw