Files
hermes-agent/tests/gateway/test_transcript_read_failure.py
T
teknium1 d10bb2ab6f test: make tests/ mirror the source tree; drop issue numbers from filenames
`scripts/run_tests.sh tests/<dir>/` is how a change gets its regression
coverage run, so a test filed under the wrong directory is a test nobody
runs when that code changes. Two kinds of drift had accumulated.

Parallel directories for one source package, folded into the mirror:
  tests/acp        -> tests/acp_adapter   (its __init__/conftest move with it)
  tests/cli        -> tests/hermes_cli    (prompt_toolkit fixture merged into
                                           hermes_cli/conftest.py)
  tests/run_agent  -> tests/agent         (backoff fixture becomes
                                           agent/conftest.py)
  tests/relay      -> tests/gateway/relay
  tests/state      -> tests/hermes_state

246 loose files at tests/ root, routed by the package they import/patch:
hermes_cli, hermes_state, agent, gateway, tools, plugins, tui_gateway, cron.
Installer and desktop-update script tests go to tests/scripts/{install,
desktop_update}/. 43 tests of root-level modules (batch_runner, utils,
hermes_constants, packaging) stay at the root.

Filenames drop their issue numbers (95 files: test_89315_x.py -> test_x.py);
the number stays in the module docstring where it has context.

Collisions: test_cli_skin_integration.py existed in both tests/ and tests/cli
with different subsets — merged into one (10 tests, all kept);
run_agent/test_pre_compress_memory_context.py -> agent/..._handoff.py;
tests/test_account_usage.py -> agent/test_account_usage_fetch.py;
tests/test_web_server.py -> hermes_cli/test_web_server_ws_ping.py.
Deleted: test_minisweagent_path.py (empty since PR #2804),
test_model_picker_scroll.py (tested a private copy of the logic, imported
nothing), test_process_loop_event_loop_warning.py (asserted asyncio behaviour,
imported nothing from Hermes).

Repo-root path arithmetic (Path(__file__).parents[N], dirname chains) is
bumped for the 202 files that changed depth and verified by evaluating every
such expression against the new location. classify_changes' desktop-updater
lane prefix, tests-os.yml's ignore glob and every in-tree path comment follow
the moves. tests/test_tests_tree_layout.py keeps the tree from drifting back.
2026-09-13 09:18:02 -07:00

125 lines
5.1 KiB
Python

"""A failed transcript read must not masquerade as an empty history (#100788).
The gateway restore path (``_handle_message``) already fails closed on
current main (#100910). This file covers the surviving half of PR #100887:
the slash-command handlers, which used to let ``TranscriptReadError``
propagate into the dispatch wrapper and reply with nothing at all.
Incident shape: a malformed ``state.db`` made every
``SessionStore.load_transcript`` raise; the except-block swallowed it and
returned ``[]``. Restore then rebuilt the turn from "no history", so a
long-running chat silently restarted as a brand-new conversation and the
model happily answered as if nothing had ever been discussed.
Two guarantees under test:
A. ``load_transcript`` raises ``TranscriptReadError`` on a read failure,
while a genuinely empty session still returns ``[]``.
B. Slash-command handlers that read the transcript reply with
``HISTORY_UNREADABLE`` instead of raising into the dispatch wrapper
(which logs and sends nothing).
Offline: SQLite on tmp_path only, no network.
"""
import sqlite3
import pytest
from gateway.config import GatewayConfig
from gateway.session import SessionStore
from gateway.session_transcript import TranscriptReadError
@pytest.fixture
def store(tmp_path):
return SessionStore(sessions_dir=tmp_path / "gw", config=GatewayConfig())
# --------------------------------------------------------------------------
# A. read failure != empty transcript (landed on main via #100910; kept as
# the contract the slash-command handlers below rely on)
# --------------------------------------------------------------------------
class TestLoadTranscriptReadFailure:
def test_read_failure_raises_instead_of_returning_empty(self, store, monkeypatch):
db = store._db
assert db is not None
db.create_session("s1", "telegram", session_key="telegram:1")
db.append_message("s1", "user", "the conversation we must not forget")
boom = sqlite3.DatabaseError("database disk image is malformed")
def _raise(*_args, **_kwargs):
raise boom
monkeypatch.setattr(db, "get_messages_as_conversation", _raise)
with pytest.raises(TranscriptReadError) as excinfo:
store.load_transcript("s1")
assert excinfo.value.session_id == "s1"
assert excinfo.value.__cause__ is boom
def test_genuinely_empty_session_still_returns_empty_list(self, store):
db = store._db
assert db is not None
db.create_session("s2", "telegram", session_key="telegram:2")
assert store.load_transcript("s2") == []
def test_no_db_still_returns_empty_list(self, store):
# "No DB for this session" really is an empty transcript, not a
# failure — that path must keep its [] contract.
store._db = None
assert store.load_transcript("nope") == []
# --------------------------------------------------------------------------
# B. slash-command handlers surface the failure instead of dying silently.
# Before: the handler raised, base.py's dispatch wrapper logged
# "Command '/x' dispatch failed" and the user got NO reply at all.
# --------------------------------------------------------------------------
class TestSlashCommandsOnUnreadableTranscript:
def test_history_unreadable_text_is_explicit(self):
from gateway.slash_commands_status import HISTORY_UNREADABLE
assert "unreadable" in HISTORY_UNREADABLE
assert "not a new conversation" in HISTORY_UNREADABLE
@pytest.mark.asyncio
async def test_btw_replies_history_unreadable_on_read_failure(self):
"""The except-branch must actually run: after the Sep 2026 decomposition the
constant lived in slash_commands_status but was not imported by slash_commands,
so this path raised NameError (#102117 follow-up)."""
from unittest.mock import AsyncMock, MagicMock
from gateway.slash_commands_status import HISTORY_UNREADABLE
from tests.gateway.test_background_command import _make_event, _make_runner
runner = _make_runner()
store = AsyncMock()
store.get_or_create_session.return_value = MagicMock(session_id="s1")
store.load_transcript.side_effect = TranscriptReadError("malformed")
store._store = runner.session_store
runner._async_session_store = store
result = await runner._handle_btw_command(_make_event(text="/btw what?"))
assert result == HISTORY_UNREADABLE
def test_every_transcript_reading_handler_catches_the_error(self):
"""No `await ...load_transcript(` in the mixin may be left uncaught."""
import inspect
import re
from gateway import slash_commands as sc
src = inspect.getsource(sc)
# Each awaited load_transcript must sit inside a try: whose handlers
# include TranscriptReadError within the following ~6 lines.
for m in re.finditer(r"await self\.async_session_store\.load_transcript\(", src):
window = src[m.end() : m.end() + 400]
assert "except TranscriptReadError" in window, src[m.start() - 200 : m.end() + 100]