Files
hermes-agent/tests/hermes_state/test_session_db_context_manager.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

101 lines
3.8 KiB
Python

"""``SessionDB`` must support ``with``, so an owning scope releases its fds.
Historically a SessionDB handle could not be released by dropping the last
reference: once its background token writer started, the instance pinned
ITSELF two ways (the writer thread's bound-method target, and a strong
``atexit`` drain hook that only ``close()`` unregistered), so ``__del__``
never ran for exactly the instances that leaked ``state.db``/``-wal``/
``-shm`` descriptors (#88033). The writer now retires after an idle window
and the atexit hook is a weak reference, so abandoned handles are eventually
GC-collectible -- but eventual collection is not deterministic release.
Owning call sites are still expected to close explicitly; the ownership
comments in ``run_agent.py`` and ``tui_gateway/methods_session.py`` say so in
those words. This module pins the ergonomic half of that contract: an owner can
scope a handle with ``with`` and be exception-safe by construction, instead of
hand-writing a ``try/finally`` at each of the ~59 instantiation sites (#88033).
Following ``test_session_db_read_conn_pool.py``, these assert on the
``sqlite_safe_read`` tracking registry rather than on raw descriptor counts:
SQLite's unix VFS parks a closed descriptor on a per-inode reuse list while any
connection still holds POSIX locks on that inode, so descriptor counts lag the
real connection count and make such assertions flaky.
"""
import pytest
from hermes_state import SessionDB
def _live_count(path) -> int:
"""Live-connection count the tracking registry holds for *path*."""
import hermes_cli.sqlite_safe_read as mod
with mod._live_lock:
return mod._live_connections.get(mod._key(path), 0)
def test_with_block_closes_the_handle(tmp_path):
"""The whole point: leaving the scope releases the connection."""
path = tmp_path / "state.db"
with SessionDB(db_path=path) as db:
db.create_session(session_id="s1", source="cli", model="m")
db.append_message("s1", role="user", content="hello")
assert db._conn is not None
assert _live_count(path) > 0
assert db._conn is None
assert _live_count(path) == 0
def test_enter_returns_the_same_handle(tmp_path):
"""``with SessionDB(...) as db`` must bind the instance, not a wrapper.
Returning anything else would silently break every attribute access in the
body, so this is cheap insurance on the one line that is easy to get wrong.
"""
db = SessionDB(db_path=tmp_path / "state.db")
with db as entered:
assert entered is db
assert db._conn is None
def test_exception_inside_the_block_still_closes_and_propagates(tmp_path):
"""Exception safety is the reason to prefer ``with`` over a bare close().
The handle must be released on the failure path (the path that leaked
hardest, since it is the one callers forget), and ``__exit__`` must NOT
suppress: swallowing a caller's error to release a descriptor would trade
one bug for a worse one.
"""
path = tmp_path / "state.db"
db = SessionDB(db_path=path)
with pytest.raises(ValueError, match="boom"):
with db:
db.create_session(session_id="s1", source="cli", model="m")
raise ValueError("boom")
assert db._conn is None
assert _live_count(path) == 0
def test_closing_inside_the_block_leaves_the_exit_clean(tmp_path):
"""``close()`` is documented idempotent; the scope must not fight a caller.
A call site converted to ``with`` may still hold an explicit ``close()``
(or hit one on an internal error path). The second close from ``__exit__``
must be a no-op rather than an error.
"""
path = tmp_path / "state.db"
with SessionDB(db_path=path) as db:
db.create_session(session_id="s1", source="cli", model="m")
db.close()
assert db._conn is None
assert _live_count(path) == 0