The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: restore state.db / SessionDB regression guards dropped by #120071
teknium176cfc7b25747
diff --git a/tests/agent/test_overflow_overhead_aware_tokens.py b/tests/agent/test_overflow_overhead_aware_tokens.pyindex 0bd36902ef2..a8393494aba 100644--- a/tests/agent/test_overflow_overhead_aware_tokens.py+++ b/tests/agent/test_overflow_overhead_aware_tokens.py@@ -1,5 +1,8 @@-"""Anthropic long-context-tier (429) recovery: the retry diagnostics buffered-during recovery must flush correctly (muted vs. unmuted) on terminal failure."""+"""Overflow recovery handlers (413, context overflow, Anthropic long-context+tier 429) must hand the compressor an overhead-aware token estimate that counts+tool schemas, not a messages-only estimate (LCM issue 441). Also: the retry+diagnostics buffered during long-context recovery must flush correctly (muted+vs. unmuted) on terminal failure."""import pytest@@ -82,6 +85,34 @@ def _prefill():_SENTINEL_TOKENS = 987_654+def _make_413_error():+ err = Exception("Request entity too large")+ err.status_code = 413+ return err+++def _make_context_overflow_error():+ """A 400 the classifier routes to context_overflow."""+ err = Exception(+ "Error code: 400 - {'error': {'message': "+ "\"This endpoint's maximum context length is 128000 tokens. "+ "However, you requested about 200000 tokens. "+ "Please reduce the length of the messages.\"}}"+ )+ err.status_code = 400+ return err+++def _make_prompt_too_long_error():+ """Anthropic's 'prompt is too long' variant of context overflow."""+ err = Exception(+ "Error code: 400 - {'type': 'error', 'error': {'type': 'invalid_request_error', "+ "'message': 'prompt is too long: 233153 tokens > 200000 maximum'}}"+ )+ err.status_code = 400+ return err++def _make_long_context_tier_error():"""Build a 429 'extra usage required for long context requests' error."""err = Exception(@@ -124,3 +155,61 @@ def test_long_context_retry_carrier_survives_failure_flush(agent, muted, monkeypagent._flush_status_buffer()assert bool(printed) is not mutedassert observed+++# A tool schema big enough (~10k tokens) to dwarf the tiny test conversation,+# so a messages-only estimate cannot reach the floor asserted below.+_HEAVY_TOOL_DESCRIPTION = "Heavy schema padding. " * 2_000+_TOOL_OVERHEAD_FLOOR = 5_000+++ "make_error",+ [+ pytest.param(_make_413_error, id="413"),+ pytest.param(_make_context_overflow_error, id="context_overflow"),+ pytest.param(_make_prompt_too_long_error, id="prompt_too_long"),+ pytest.param(_make_long_context_tier_error, id="long_context_tier_429"),+ ],+)+def test_overflow_recovery_compresses_with_tool_overhead_counted(agent, make_error):+ """Each recovery path must pass approx_tokens that include tool-schema+ overhead: a messages-only estimate under-reports the request, so the+ compressor sizes its target wrong and the retry overflows again."""+ from agent.model_metadata import estimate_messages_tokens_rough++ agent.tools = [+ {+ "type": "function",+ "function": {+ "name": "heavy_tool",+ "description": _HEAVY_TOOL_DESCRIPTION,+ "parameters": {"type": "object", "properties": {}},+ },+ }+ ]+ history = _prefill()+ assert estimate_messages_tokens_rough(history + [{"role": "user", "content": "hello"}]) < 500++ agent.client.chat.completions.create.side_effect = [+ make_error(),+ _mock_response(content="Recovered", finish_reason="stop"),+ ]+ with (+ patch.object(agent, "_compress_context") as mock_compress,+ patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"),+ patch.object(agent, "_cleanup_task_resources"),+ ):+ mock_compress.return_value = (+ [{"role": "user", "content": "compressed"}],+ "compressed prompt",+ )+ result = agent.run_conversation("hello", conversation_history=history)++ assert result["final_response"] == "Recovered"+ passed = [c.kwargs.get("approx_tokens") for c in mock_compress.call_args_list]+ assert passed, "recovery never invoked the compressor"+ assert any(t is not None and t >= _TOOL_OVERHEAD_FLOOR for t in passed), (+ f"compressor got messages-only estimates {passed}; tool schemas were not counted"+ )diff --git a/tests/hermes_cli/test_web_server_sessiondb_eventloop.py b/tests/hermes_cli/test_web_server_sessiondb_eventloop.pyindex af83baeb5e4..ee0060a2795 100644--- a/tests/hermes_cli/test_web_server_sessiondb_eventloop.py+++ b/tests/hermes_cli/test_web_server_sessiondb_eventloop.py@@ -1,42 +1,117 @@-import ast+"""Dashboard session routes must run SessionDB open + work off the event loop.++Regression for #60747: /search, /stats, /{id} (and bulk delete) ran FTS and+SQLite inline on the loop thread, so a large state.db froze every other+dashboard request (rename too). These drive the real route handlers and record which+thread every SessionDB call lands on.+"""+import asyncioimport threading-from pathlib import Pathimport pytest-from hermes_cli import web_serverimport hermes_cli.web_models as _web_modelsimport hermes_cli.web_routers.sessions as _rt_sessionsimport hermes_cli.web_server_sessions as _web_server_sessions-from hermes_cli import web_server_sessions-from hermes_cli.web_routers import analytics as web_analytics-from hermes_cli.web_routers import sessions as web_sessions---TARGET_HANDLERS = {- "bulk_delete_sessions_endpoint",- "count_empty_sessions_endpoint",- "delete_empty_sessions_endpoint",- "get_session_latest_descendant",- "get_session_messages",- "delete_session_endpoint",- "export_session_endpoint",- "prune_sessions_endpoint",- "get_usage_analytics",- "get_models_analytics",- "search_sessions",- "get_session_stats",- "get_session_detail",-}---def _call_name(call: ast.Call) -> str | None:- if isinstance(call.func, ast.Name):- return call.func.id- if isinstance(call.func, ast.Attribute):- return call.func.attr- return None+++def test_bulk_delete_sessiondb_work_runs_off_event_loop(monkeypatch):+ loop_thread = threading.get_ident()+ db_threads: list[int] = []+ db_modes: list[bool] = []++ class _DB:+ def delete_sessions(self, ids):+ db_threads.append(threading.get_ident())+ assert ids == ["one", "two"]+ return 2++ def close(self):+ db_threads.append(threading.get_ident())++ def _open_db(profile=None, *, read_only):+ assert profile is None+ db_modes.append(read_only)+ return _DB()++ monkeypatch.setattr(_web_server_sessions, "_open_session_db_for_profile", _open_db)++ result = asyncio.run(+ _rt_sessions.bulk_delete_sessions_endpoint(+ _web_models.BulkDeleteSessions(ids=["one", "two"])+ )+ )++ assert result == {"ok": True, "deleted": 2}+ assert db_modes == [False]+ assert db_threads+ assert all(thread_id != loop_thread for thread_id in db_threads)+++class _ReadDB:+ """Read-only stand-in that records which thread every SessionDB call runs on."""++ def __init__(self, threads: list[int]):+ self._threads = threads++ def _hit(self, value=None):+ self._threads.append(threading.get_ident())+ return value++ def session_count(self, **_kw):+ return self._hit(3)++ def message_count(self):+ return self._hit(7)++ def session_count_by_source(self, **_kw):+ return self._hit({"cli": 3})++ def get_session(self, sid):+ return self._hit({"id": sid, "title": "t"})++ def get_session_rich_row(self, sid):+ return self._hit(None)++ def get_compression_tip(self, root_id):+ return self._hit(None)++ def search_sessions_by_id(self, q, **_kw):+ return self._hit([{"id": "sess-1", "preview": "hello", "started_at": 1.0}])++ def search_messages(self, **_kw):+ return self._hit([])++ def close(self):+ self._hit()+++ "call",+ [+ pytest.param(lambda: _rt_sessions.search_sessions(q="hello"), id="search"),+ pytest.param(lambda: _rt_sessions.get_session_stats(), id="stats"),+ pytest.param(lambda: _rt_sessions.get_session_detail("sess-1"), id="detail"),+ ],+)+def test_session_read_handlers_run_sessiondb_work_off_event_loop(monkeypatch, call):+ """Regression for #60747: /search, /stats and /{id} ran FTS + SQLite inline on the+ loop thread, so a large state.db froze every other dashboard request."""+ loop_thread = threading.get_ident()+ db_threads: list[int] = []++ def _open_db(profile=None, *, read_only):+ assert read_only is True+ return _ReadDB(db_threads)++ monkeypatch.setattr(_web_server_sessions, "_open_session_db_for_profile", _open_db)+ monkeypatch.setattr(_rt_sessions, "_resolve_session_id", lambda db, sid: sid)++ asyncio.run(call())++ assert db_threads, "handler never touched the SessionDB"+ assert all(thread_id != loop_thread for thread_id in db_threads)def test_session_rename_runs_writer_open_and_update_off_event_loop(monkeypatch):diff --git a/tests/hermes_state/test_hermes_state.py b/tests/hermes_state/test_hermes_state.pyindex 3c9e315d173..ac5302e816b 100644--- a/tests/hermes_state/test_hermes_state.py+++ b/tests/hermes_state/test_hermes_state.py@@ -3339,6 +3339,50 @@ class TestCompressionChainProjection:assert tip2_row["preview"].startswith("second conversation continuation")assert tip2_row["cwd"] == "/tmp/workspaces/second"+ def test_list_batches_tip_row_fetch_into_one_query(self, db, monkeypatch):+ """Projection must resolve tip rows for a whole page in one batched+ query, not one _get_session_rich_row() call per compression root."""+ import time as _time++ t0 = _time.time() - 7200+ self._build_compression_chain(db, t0)+ db.create_session("root2", "cli")+ db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (t0 + 100, "root2"))+ db.append_message("root2", "user", "second conversation start")+ db._conn.execute(+ "UPDATE sessions SET ended_at=?, end_reason=? WHERE id=?",+ (t0 + 200, "compression", "root2"),+ )+ db.create_session("tip2", "cli", parent_session_id="root2")+ db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (t0 + 201, "tip2"))+ db.append_message("tip2", "user", "second continuation")+ db._conn.commit()++ batch_calls = []+ single_calls = []+ original_batch = db._get_session_rich_rows_batch+ original_single = db._get_session_rich_row++ def counting_batch(session_ids, **kwargs):+ batch_calls.append(list(session_ids))+ return original_batch(session_ids, **kwargs)++ def counting_single(session_id, **kwargs):+ single_calls.append(session_id)+ return original_single(session_id, **kwargs)++ monkeypatch.setattr(db, "_get_session_rich_rows_batch", counting_batch)+ monkeypatch.setattr(db, "_get_session_rich_row", counting_single)++ sessions = db.list_sessions_rich(source="cli", limit=20)+ assert len(sessions) >= 2 # sanity: both chains actually surfaced++ # Two compression roots resolved with exactly one batched call, and+ # zero single-row calls — not one single-row call per root.+ assert len(batch_calls) == 1+ assert set(batch_calls[0]) == {"tip1", "tip2"}+ assert single_calls == []+diff --git a/tests/hermes_state/test_hermes_state_ux_messages.py b/tests/hermes_state/test_hermes_state_ux_messages.pyindex 01fefc956cc..edccf76380a 100644--- a/tests/hermes_state/test_hermes_state_ux_messages.py+++ b/tests/hermes_state/test_hermes_state_ux_messages.py@@ -43,3 +43,34 @@ def test_db_unavailable_commands_are_pinned_to_the_failing_profile(monkeypatch,for text in (no_cause, network):assert f"`hermes {selector}doctor`" in text and "`hermes doctor`" not in textassert "{profile_arg}" not in text+++def test_db_unavailable_details_line_carries_raw_cause_only_below_the_lead():+ """CLI banner (details=True): the raw SQLite text is kept for bug reports on+ its own ``Details:`` line and never leaks into the plain-language lead; with+ no recorded cause there is nothing to detail."""+ hermes_state._set_last_init_error("OperationalError: database is locked")+ try:+ text = format_session_db_unavailable(details=True)+ finally:+ hermes_state._set_last_init_error(None)+ lead, *rest = text.splitlines()+ assert "OperationalError" not in lead+ assert len(rest) == 1 and rest[0].startswith("Details: ") and "database is locked" in rest[0]++ no_cause = format_session_db_unavailable(details=True)+ assert "\n" not in no_cause and "Details:" not in no_cause+++def test_db_unavailable_network_drive_cause_does_not_offer_doctor_fix():+ """A locking-protocol failure means the DB sits on a network filesystem that+ cannot host SQLite's WAL; `hermes doctor --fix` cannot repair a mount, so it+ must not be the offered action (only moving the file helps)."""+ hermes_state._set_last_init_error("OperationalError: locking protocol")+ try:+ text = format_session_db_unavailable(details=True)+ finally:+ hermes_state._set_last_init_error(None)+ lead, details = text.splitlines()+ assert "doctor --fix" not in lead+ assert "locking protocol" not in lead and "locking protocol" in detailsdiff --git a/tests/hermes_state/test_tail_rewind_semantics.py b/tests/hermes_state/test_tail_rewind_semantics.pyindex 878163e806d..fcb69b91573 100644--- a/tests/hermes_state/test_tail_rewind_semantics.py+++ b/tests/hermes_state/test_tail_rewind_semantics.py@@ -253,3 +253,36 @@ class TestTailCountArchivesAsRewindSemantics:assert int(mc) == 4+++class TestCompressTagsCarriedTail:+ def test_compress_marks_carried_forward_tail_dicts(self):+ """compress() must tag its carried-forward tail dicts so the caller+ can pass an accurate tail_count to archive_and_compact (#86366);+ untagged, the tail originals are recalled as compacted history."""+ from unittest.mock import patch++ from agent.context_compressor import _COMPACTION_TAIL_MARKER, ContextCompressor++ with patch("agent.context_compressor.get_model_context_length", return_value=100_000):+ compressor = ContextCompressor(+ model="test/model", protect_first_n=2, protect_last_n=2, quiet_mode=True,+ )+ _ = compressor.context_length++ history = [+ {"role": "user" if i % 2 == 0 else "assistant", "content": f"filler turn {i} " + "x" * 400}+ for i in range(12)+ ]+ with patch("agent.context_compressor.call_llm", side_effect=RuntimeError("no provider")):+ out = compressor.compress(list(history))++ assert len(out) < len(history)+ tagged = [m for m in out if isinstance(m, dict) and m.get(_COMPACTION_TAIL_MARKER)]+ assert tagged, "carried-forward tail rows were not tagged"+ # The tag marks exactly the verbatim tail: the trailing run of the output,+ # each row a copy of an original from the end of the history.+ assert out[-len(tagged):] == tagged+ originals = {m["content"] for m in history[-len(tagged):]}+ assert {m["content"] for m in tagged} <= originals+ assert not any(m.get(_COMPACTION_TAIL_MARKER) for m in out[:2])diff --git a/tests/hermes_state/test_wal_checkpoint_strategy.py b/tests/hermes_state/test_wal_checkpoint_strategy.pyindex 2f5bf1c51e8..a3fa07c27e6 100644--- a/tests/hermes_state/test_wal_checkpoint_strategy.py+++ b/tests/hermes_state/test_wal_checkpoint_strategy.py@@ -6,6 +6,8 @@ transient per-cron-run connections closing many times an hour would racethe live gateway writer and corrupt B-tree pages (#45383)."""+import logging+import sqlite3from unittest.mock import MagicMockimport pytest@@ -70,6 +72,20 @@ class TestTryWalCheckpointPassive:"Periodic checkpoint should NOT use TRUNCATE")+ def test_failed_checkpoint_never_raises_and_is_not_silent(self, db, caplog):+ """The periodic checkpoint runs from the write path: a failing PASSIVE+ checkpoint must not raise into the caller, and must leave a WARNING."""+ real_conn = db._conn+ mock_conn = MagicMock()+ mock_conn.execute.side_effect = sqlite3.OperationalError("disk I/O error")+ db._conn = mock_conn+ try:+ with caplog.at_level(logging.WARNING, logger="hermes_state"):+ db._try_wal_checkpoint()+ finally:+ db._conn = real_conn+ assert any(r.levelno >= logging.WARNING for r in caplog.records)+@@ -102,6 +118,21 @@ class TestCloseUsesPassive:f"Expected 1 PASSIVE checkpoint at close, got {len(passive_calls)}")+ def test_failed_checkpoint_at_close_still_releases_the_handle(self, db):+ """close() is best-effort about the checkpoint: a failing PASSIVE at+ close must neither raise nor leave the handle open."""+ real_conn = db._conn+ mock_conn = MagicMock()+ mock_conn.execute.side_effect = sqlite3.OperationalError("database is locked")+ db._conn = mock_conn+ try:+ db.close()+ finally:+ real_conn.close()++ assert db._conn is None+ mock_conn.close.assert_called()+class TestVacuumUsesPassive:diff --git a/tests/tools/test_code_execution.py b/tests/tools/test_code_execution.pyindex d2a05364bb8..fa69d4c332b 100644--- a/tests/tools/test_code_execution.py+++ b/tests/tools/test_code_execution.py@@ -425,10 +425,36 @@ class TestStubSchemaDrift(unittest.TestCase):)- def test_generated_module_compiles(self):- """The generated hermes_tools.py for every allowed tool is valid Python."""- src = generate_hermes_tools_module(list(SANDBOX_ALLOWED_TOOLS))- compile(src, "hermes_tools.py", "exec")+ def test_generated_module_accepts_all_params(self):+ """Executing the generated hermes_tools module: every stub accepts all of+ its parameters as keyword arguments and forwards each one, by name and+ value, to the RPC call (a dropped or renamed kwarg is a TypeError or a+ silently ignored argument in the sandbox)."""+ import inspect++ for transport in ("uds", "file"):+ src = generate_hermes_tools_module(list(SANDBOX_ALLOWED_TOOLS), transport=transport)+ namespace = {"__name__": "hermes_tools"}+ exec(compile(src, "hermes_tools.py", "exec"), namespace)+ calls = []+ namespace["_call"] = lambda name, args: calls.append((name, args)) or "ok"++ generated = {name for name in SANDBOX_ALLOWED_TOOLS if callable(namespace.get(name))}+ self.assertEqual(generated, set(SANDBOX_ALLOWED_TOOLS), transport)+ for name in sorted(generated):+ params = inspect.signature(namespace[name]).parameters+ kwargs = {p: f"<{name}.{p}>" for p in params}+ calls.clear()+ self.assertEqual(namespace[name](**kwargs), "ok")+ self.assertEqual(calls, [(name, kwargs)], f"{transport}:{name}")++ # The pagination/output controls of search_files and patch's mode+ # must be real keyword parameters, not just mentioned in the docs.+ self.assertTrue(+ {"context", "offset", "output_mode", "order"}+ <= set(inspect.signature(namespace["search_files"]).parameters)+ )+ self.assertIn("mode", inspect.signature(namespace["patch"]).parameters)# ---------------------------------------------------------------------------