Skip to content

The agent that grows with you

fix(state): verified compression lineage for ancestor reads + fork marker

Yingliang Zhange5867d9bae01
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index e9d34a5a4aa..daf0bd1bfaa 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -3304,8 +3304,10 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
default_page = requested_limit is None
latest_page = order == "latest" or (order is None and default_page)
limit = 500 if default_page else min(requested_limit, 500)
+ # Compression lineage: return root→tip messages, matching the REST router (#51058).
messages = await asyncio.to_thread(
- db.get_messages, resolved_id, limit=limit, offset=offset, latest=latest_page)
+ db.get_messages, resolved_id, limit=limit, offset=offset, latest=latest_page,
+ include_ancestors=True)
return web.json_response({
"object": "list", "session_id": resolved_id,
"data": [self._message_response(m) for m in messages],
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index b6e8915e92a..96cc9439b04 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -1667,9 +1667,32 @@ class SessionMessagesMixin:
return model_history, display_history
def _resume_lineage_ids(self, session_id: str) -> List[str]:
- """Session ids a display resume materializes: the compression lineage, or the session alone for an
- explicit ``/branch`` copy. Shared with the resume guard so it counts exactly what a resume loads."""
- return [session_id] if self._is_explicit_branch_session(session_id) else self._session_lineage_root_to_tip(session_id)
+ """Session ids a display resume materializes: the VERIFIED compression lineage (root → tip; each
+ hop's parent ended ``compression`` and the child is a genuine continuation), or the session alone
+ for anything else — an explicit ``/branch`` copy, an API fork, a reset child, or a plain session.
+ The raw parent walker ``_session_lineage_root_to_tip`` is intentionally NOT used here: it crosses
+ fork/reset boundaries and misclassifies API forks (parent ended ``branched``, no marker) as
+ compression lineages. Shared with the resume guard so it counts exactly what a resume loads."""
+ if not session_id:
+ return [session_id]
+ session = self.get_session(session_id)
+ if not session or self._is_explicit_fork_child_row(session):
+ return [session_id]
+ # _is_compression_child_row is the per-hop gate: the child must not be an explicit
+ # branch/delegate/tool child AND its parent must have ended 'compression'.
+ chain = [session_id]
+ current = session
+ seen = {session_id}
+ while len(chain) < 100: # defensive bound, same as _session_lineage_root_to_tip
+ if not self._is_compression_child_row(current):
+ break
+ parent = self.get_session(current["parent_session_id"])
+ if not parent or parent["id"] in seen:
+ break
+ seen.add(parent["id"])
+ chain.append(parent["id"])
+ current = parent
+ return list(reversed(chain))
def _resume_count_scope(self, session_id: str, tip_only: bool) -> Tuple[List[str], str]:
"""``tip_only``: the tip's ACTIVE rows (model restore); else the full-lineage DISPLAY set."""
diff --git a/tests/gateway/test_session_api.py b/tests/gateway/test_session_api.py
index 09efd8f9841..54313492174 100644
--- a/tests/gateway/test_session_api.py
+++ b/tests/gateway/test_session_api.py
@@ -1,6 +1,7 @@
"""Focused tests for API server session-control endpoints."""
import asyncio
+import json
import threading
from unittest.mock import AsyncMock, MagicMock, patch
@@ -194,6 +195,61 @@ async def test_session_model_lock_persists_off_the_event_loop(adapter, session_d
assert session_db.get_session(session_id)["model"] == "x-ai/grok-4.5"
+async def test_session_messages_returns_compression_ancestors(adapter, session_db):
+ """GET /api/sessions/{id}/messages on a compression continuation returns the
+ root→tip transcript, not just the tip's rows (#51058)."""
+ source_id = session_db.create_session("compress-source", "api_server")
+ session_db.replace_messages(
+ source_id,
+ [
+ {"role": "user", "content": "before compression"},
+ {"role": "assistant", "content": "before answer"},
+ ],
+ )
+ session_db.end_session(source_id, "compression")
+ child_id = session_db.create_session(
+ "compress-tip", "api_server", parent_session_id=source_id
+ )
+ session_db.append_message(child_id, role="user", content="after compression")
+
+ app = _create_session_app(adapter)
+ async with TestClient(TestServer(app)) as cli:
+ resp = await cli.get(f"/api/sessions/{child_id}/messages")
+ assert resp.status == 200
+ payload = await resp.json()
+
+ assert payload["session_id"] == child_id
+ assert [m["content"] for m in payload["data"]] == [
+ "before compression",
+ "before answer",
+ "after compression",
+ ]
+ assert [m["role"] for m in payload["data"]] == ["user", "assistant", "user"]
+
+
+async def test_fork_session_writes_branched_from_marker(adapter, session_db):
+ """The API fork must stamp _branched_from like the CLI/TUI branch paths, so the
+ fork is never misclassified as a compression continuation."""
+ source_id = session_db.create_session("fork-source", "api_server")
+ session_db.replace_messages(source_id, [{"role": "user", "content": "hello"}])
+
+ app = _create_session_app(adapter)
+ async with TestClient(TestServer(app)) as cli:
+ resp = await cli.post(f"/api/sessions/{source_id}/fork", json={"id": "fork-child"})
+ assert resp.status == 201
+ payload = await resp.json()
+
+ assert payload["session"]["id"] == "fork-child"
+ fork = session_db.get_session("fork-child")
+ assert fork["parent_session_id"] == source_id
+ assert session_db._is_explicit_branch_session("fork-child")
+ cfg = fork["model_config"]
+ if isinstance(cfg, str):
+ cfg = json.loads(cfg)
+ assert cfg["_branched_from"] == source_id
+
@pytest.mark.asyncio
async def test_run_agent_binds_api_session_context_for_tool_env(adapter, monkeypatch):
"""API-server request sessions should reach tools and terminal subprocess env."""
diff --git a/tests/hermes_state/test_display_projection_parity.py b/tests/hermes_state/test_display_projection_parity.py
index c34c64c17eb..194d1d48e08 100644
--- a/tests/hermes_state/test_display_projection_parity.py
+++ b/tests/hermes_state/test_display_projection_parity.py
@@ -150,6 +150,8 @@ class TestAncestorPrefix:
db.append_message(parent, "user", f"P user {i}")
db.append_message(parent, "assistant", f"P assistant {i}")
db.archive_and_compact(parent, [{"role": "user", "content": "[parent summary]"}])
+ # A real rotation stamps the parent end_reason='compression' (publish_compression_child).
+ db.end_session(parent, "compression")
db.create_session(child, source="desktop", parent_session_id=parent)
db.append_message(child, "user", "C user 0")
diff --git a/tests/hermes_state/test_hermes_state.py b/tests/hermes_state/test_hermes_state.py
index 4aa8110c082..e803af4eeb6 100644
--- a/tests/hermes_state/test_hermes_state.py
+++ b/tests/hermes_state/test_hermes_state.py
@@ -5591,6 +5591,8 @@ class TestGetMessagesPagination:
"root",
[{"role": "user", "content": f"root-{i}"} for i in range(3)],
)
+ # A real rotation stamps the parent end_reason='compression' (publish_compression_child).
+ db.end_session("root", "compression")
db.create_session(
session_id="tip",
source="compression",
@@ -6477,6 +6479,8 @@ class TestGetMessagesAncestors:
db.create_session("parent", source="tui")
db.append_message("parent", role="user", content="early ask")
db.append_message("parent", role="assistant", content="early answer")
+ # A real rotation stamps the parent end_reason='compression' (publish_compression_child).
+ db.end_session("parent", "compression")
db.create_session("child", source="tui", parent_session_id="parent")
db.append_message("child", role="user", content="continuation ask")
@@ -6513,10 +6517,79 @@ class TestGetMessagesAncestors:
"copied turn"
]
+ def test_include_ancestors_api_fork_stays_single_session(self, db):
+ """An API fork (parent ended 'branched', transcript copied, NO _branched_from
+ marker — what _handle_fork_session produced before the marker fix) must not be
+ mistaken for a compression lineage: ancestor expansion returns the fork's own
+ copied transcript only, never the parent's rows re-prepended (which duplicated
+ every turn and produced the [assistant, user, assistant] order ehz0ah hit)."""
+ db.create_session("source", source="tui")
+ db.append_message("source", role="user", content="question")
+ db.append_message("source", role="assistant", content="answer")
+ db.end_session("source", "branched")
+ # Exactly what the API fork handler does, minus the _branched_from marker.
+ db.create_session("fork", source="api_server", parent_session_id="source")
+ db.replace_messages("fork", db.get_messages("source"))
+
+ assert [m["content"] for m in db.get_messages("fork", include_ancestors=True)] == [
+ "question",
+ "answer",
+ ]
+ conversation = db.get_messages_as_conversation("fork", include_ancestors=True)
+ assert [m["role"] for m in conversation] == ["user", "assistant"]
+ assert [m["content"] for m in conversation] == ["question", "answer"]
+
+ def test_include_ancestors_reset_child_stays_single_session(self, db):
+ """A /reset continuation (_reset_from marker, parent ended 'session_reset') is a
+ fresh conversation, not a compression lineage: ancestor expansion must not cross
+ the reset boundary."""
+ db.create_session("parent", source="tui")
+ db.append_message("parent", role="user", content="old conversation")
+ db.end_session("parent", "session_reset")
+ db.create_session(
+ "child",
+ source="tui",
+ parent_session_id="parent",
+ model_config={"_reset_from": "parent"},
+ )
+ db.append_message("child", role="user", content="fresh start")
+
+ assert [m["content"] for m in db.get_messages("child", include_ancestors=True)] == [
+ "fresh start"
+ ]
+ conversation = db.get_messages_as_conversation("child", include_ancestors=True)
+ assert [m["content"] for m in conversation] == ["fresh start"]
+
+ def test_include_ancestors_deep_lineage_verified_chain(self, db):
+ """A multi-hop compression lineage merges root→tip, and a plain (non-compression)
+ grandparent above the root is not crossed: only verified compression hops count."""
+ db.create_session("grandparent", source="tui")
+ db.append_message("grandparent", role="user", content="plain old turn")
+ db.end_session("grandparent", "stopped")
+ db.create_session("root", source="tui", parent_session_id="grandparent")
+ db.append_message("root", role="user", content="root turn")
+ db.end_session("root", "compression")
+ db.create_session("mid", source="tui", parent_session_id="root")
+ db.append_message("mid", role="user", content="mid turn")
+ db.end_session("mid", "compression")
+ db.create_session("tip", source="tui", parent_session_id="mid")
+ db.append_message("tip", role="user", content="tip turn")
+
+ assert db._resume_lineage_ids("tip") == ["root", "mid", "tip"]
+ assert [m["content"] for m in db.get_messages("tip", include_ancestors=True)] == [
+ "root turn",
+ "mid turn",
+ "tip turn",
+ ]
+ conversation = db.get_messages_as_conversation("tip", include_ancestors=True)
+ assert [m["content"] for m in conversation] == ["root turn", "mid turn", "tip turn"]
+
def test_include_ancestors_paging_still_applies(self, db):
"""Paging applies to the merged lineage set, not per-session."""
db.create_session("parent", source="tui")
db.append_message("parent", role="user", content="p1")
+ # A real rotation stamps the parent end_reason='compression' (publish_compression_child).
+ db.end_session("parent", "compression")
db.create_session("child", source="tui", parent_session_id="parent")
for i in range(2, 6):
db.append_message("child", role="user", content=f"c{i}")