Files
hermes-agent/tests/tools/test_react_to_message_tool.py
joaomarcos 39e480c051 fix(state): close leaked SessionDB connections on exception paths (#83226)
SessionDB could leave native SQLite handles open when construction failed
partway through schema/pragma/FTS/repair/lock/interrupt handling. Other
short-lived callers (MCP reads/polling, session search, reactions, trace
upload, insights, shutdown recovery) opened temporary SessionDB handles
without a complete ownership boundary. API-server profile caches and
RetainDB shutdown had similar late-close races. Under sustained load this
exhausted file descriptors (EMFILE).

- Close partially initialized SessionDB connections on every constructor
  exception path via a finally block guarded by an initialization-complete
  flag.
- Close temporary/cross-profile SessionDB handles in finally blocks across
  CLI, MCP, search, trace, reactions, insights, and recovery paths.
- Add API-server per-profile cache ownership and disconnect cleanup.
- Make RetainDB writer-queue shutdown exception-safe: track connections per
  thread, close on worker exit, reject new enqueues after shutdown starts,
  and sweep any connections left by short-lived threads.
- Add regression coverage for constructor failures, worker-thread readers,
  API disconnect failures, shutdown recovery, RetainDB late enqueue, and
  foreign-loop async clients.

Salvage notes: the original PR's per-thread WAL-reader ownership changes
were superseded by main's read-connection pool (permits + checkout/return);
its cron timeout-abandon fix is credited separately to #72822's earlier
identical fix.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 21:41:26 -07:00

23 lines
667 B
Python

"""Ownership tests for desktop message reactions."""
from unittest.mock import MagicMock
from tools import react_to_message_tool as reactions
def test_reaction_database_closes_when_write_fails(monkeypatch):
db = MagicMock()
db.latest_message_row_id.return_value = 42
db.set_message_reaction.side_effect = RuntimeError("write failed")
monkeypatch.setattr(reactions, "_open_session_db", lambda: db)
monkeypatch.setattr(
reactions,
"get_session_env",
lambda _name, _default="": "session-1",
)
result = reactions.react_to_message_tool("👍")
assert "write failed" in result
db.close.assert_called_once()