fix(state): wrap the store loop guard around StoreHolder's choke points

SessionDB's _read_ctx and _execute_write forward to the store holder, and every read and write, through SessionDB or a backend repository, reaches StoreHolder._read_ctx or StoreHolder._execute_write on the holder itself. The guard wrapped the SessionDB names, so it saw none of those calls and uninstall left a plain function where the forwarding member had been.

install now wraps StoreHolder's two choke points and uninstall restores them, leaving SessionDB's members untouched. _caller skips frames under persistence/sqlite/ as it skips the hermes_state modules, so the reported site is still the code that made the call. The config key, modes, exception and message text are unchanged.
This commit is contained in:
yoniebans
2026-11-14 23:31:31 +01:00
parent a2b96f9e53
commit 46d290382c
3 changed files with 75 additions and 20 deletions

View File

@@ -8,8 +8,9 @@ worker (``asyncio.to_thread``, ``gateway.session_runtime_workers.tracked_write``
Off by default and free when off: nothing is wrapped until :func:`install` runs. The gateway installs
it at startup when config.yaml sets ``gateway.sessiondb_loop_guard`` (``warn`` logs each call site once with its
stack; ``raise`` raises :class:`LoopSessionDBCall` at the call). Tests call ``install('record')`` and
read :func:`recorded`. Only ``SessionDB``'s two storage choke points are wrapped (``_read_ctx`` and
``_execute_write``); every public read and write goes through one of them.
read :func:`recorded`. Only the store holder's two storage choke points are wrapped
(``StoreHolder._read_ctx`` and ``_execute_write``); every read and write, through ``SessionDB`` or a
backend repository, goes through one of them.
"""
import asyncio
import logging
@@ -46,10 +47,13 @@ def _caller(stack):
"""The innermost frame outside the store and this guard: the code that made the call."""
from hermes_cli._startup_fast import project_root_str
here = os.path.normcase(project_root_str())
backend = os.path.join(here, 'persistence', 'sqlite')
for frame in reversed(stack):
name = os.path.basename(frame.filename)
if os.path.normcase(os.path.realpath(os.path.dirname(frame.filename))) == here and (
name.startswith('hermes_state') or name == 'contextlib.py'):
folder = os.path.normcase(os.path.realpath(os.path.dirname(frame.filename)))
if folder == here and (name.startswith('hermes_state') or name == 'contextlib.py'):
continue
if folder == backend or folder.startswith(backend + os.sep):
continue
if name == 'contextlib.py':
continue
@@ -80,14 +84,14 @@ def _check(kind):
def install(mode):
"""Wrap ``SessionDB``'s storage choke points in ``mode``. Idempotent: a second call only
"""Wrap ``StoreHolder``'s storage choke points in ``mode``. Idempotent: a second call only
changes the mode. Returns the active mode (None: not installed)."""
if mode not in _MODES:
logger.warning('%s=%r is not one of %s; guard not installed', CONFIG_KEY, mode, '/'.join(_MODES))
return _state['mode']
from hermes_state import SessionDB
if not getattr(SessionDB, '_loop_guard_installed', False):
read, write = SessionDB._read_ctx, SessionDB._execute_write
from persistence.sqlite._holder import StoreHolder
if not getattr(StoreHolder, '_loop_guard_installed', False):
read, write = StoreHolder._read_ctx, StoreHolder._execute_write
def _read_ctx(self, *args, **kwargs):
_check('read')
@@ -97,19 +101,19 @@ def install(mode):
_check('write')
return write(self, *args, **kwargs)
_read_ctx.__wrapped__, _execute_write.__wrapped__ = read, write
SessionDB._read_ctx, SessionDB._execute_write = _read_ctx, _execute_write
SessionDB._loop_guard_installed = True
StoreHolder._read_ctx, StoreHolder._execute_write = _read_ctx, _execute_write
StoreHolder._loop_guard_installed = True
_state['mode'] = mode
return mode
def uninstall():
"""Restore the unwrapped methods (tests)."""
from hermes_state import SessionDB
if getattr(SessionDB, '_loop_guard_installed', False):
SessionDB._read_ctx = SessionDB._read_ctx.__wrapped__
SessionDB._execute_write = SessionDB._execute_write.__wrapped__
SessionDB._loop_guard_installed = False
from persistence.sqlite._holder import StoreHolder
if getattr(StoreHolder, '_loop_guard_installed', False):
StoreHolder._read_ctx = StoreHolder._read_ctx.__wrapped__
StoreHolder._execute_write = StoreHolder._execute_write.__wrapped__
StoreHolder._loop_guard_installed = False
_state['mode'] = None
clear()

View File

@@ -38,9 +38,20 @@ def test_loop_guard_attributes_storage_calls_to_external_caller(tmp_path, alias_
assert module._caller(stack) is caller
callers.append(module._caller(stack).name)
assert callers == ["first_caller", "second_caller"]
# An unrelated file sharing a storage-module basename remains attributable.
# A call through a backend repository is attributed past the repository and the holder.
caller = FrameSummary(str(root / "gateway/session_authority.py"), 120, "repository_caller")
stack = [
caller,
FrameSummary(str(root / "persistence/sqlite/conversation/sessions.py"), 680, "get"),
FrameSummary(str(root / "persistence/sqlite/_holder.py"), 950, "_read_retrying_ioerr"),
FrameSummary(str(root / "hermes_state_loop_guard.py"), 90, "_read_ctx"),
]
assert module._caller(stack) is caller
# An unrelated file sharing a storage-module basename or package path remains attributable.
foreign = FrameSummary(str(tmp_path / "foreign/hermes_state.py"), 1, "foreign_call")
assert module._caller([foreign]) is foreign
foreign = FrameSummary(str(tmp_path / "foreign/persistence/sqlite/_holder.py"), 1, "foreign_call")
assert module._caller([foreign]) is foreign
def test_startup_watchdog_failure_retains_gateway_logger(monkeypatch, caplog):

View File

@@ -59,8 +59,9 @@ def _site(record):
def test_guard_is_inert_until_installed(tmp_path):
from hermes_state import SessionDB
from persistence.sqlite._holder import StoreHolder
guard.uninstall()
assert not getattr(SessionDB, '_loop_guard_installed', False)
assert not getattr(StoreHolder, '_loop_guard_installed', False)
db = SessionDB(tmp_path / 'state.db')
async def on_loop():
@@ -92,6 +93,45 @@ def test_raise_mode_refuses_on_the_loop_thread_and_allows_workers(tmp_path):
db.close()
def test_a_backend_repository_call_on_the_loop_is_flagged_at_its_caller(tmp_path, recording):
from persistence import ProfileScope
from persistence.sqlite import SQLiteBackend
scope = ProfileScope(profile_dir=tmp_path, name='default')
backend = SQLiteBackend({scope.hermes_home_key: tmp_path / 'state.db'})
store = backend.open(scope)
async def repository_calls_on_loop():
assert store.sessions.get('missing') is None
store.runtime.begin_epoch(instance_id='owner')
try:
asyncio.run(repository_calls_on_loop())
records = recording.recorded()
assert asyncio.run(asyncio.to_thread(store.sessions.get, 'missing')) is None # a worker is fine
assert len(recording.recorded()) == len(records)
finally:
backend.close()
assert {record['kind'] for record in records} == {'read', 'write'}
assert {_site(record) for record in records} == {
('tests/gateway/test_sessiondb_loop_guard.py', 'repository_calls_on_loop')}
def test_uninstall_leaves_the_session_db_members_forwarding_to_the_holder():
from hermes_state import SessionDB, _HolderMember
from persistence.sqlite._holder import StoreHolder
guard.uninstall()
before = StoreHolder.__dict__['_read_ctx'], StoreHolder.__dict__['_execute_write']
guard.install('record')
try:
assert StoreHolder.__dict__['_read_ctx'] is not before[0]
assert isinstance(SessionDB.__dict__['_read_ctx'], _HolderMember)
assert isinstance(SessionDB.__dict__['_execute_write'], _HolderMember)
finally:
guard.uninstall()
assert (StoreHolder.__dict__['_read_ctx'], StoreHolder.__dict__['_execute_write']) == before
assert isinstance(SessionDB.__dict__['_read_ctx'], _HolderMember)
assert isinstance(SessionDB.__dict__['_execute_write'], _HolderMember)
def test_gateway_startup_installs_the_guard_from_config_yaml(tmp_path, monkeypatch):
from types import SimpleNamespace
from gateway import run
@@ -102,12 +142,12 @@ def test_gateway_startup_installs_the_guard_from_config_yaml(tmp_path, monkeypat
loop = asyncio.new_event_loop()
try:
start_loop_liveness_guards(owner, loop)
from hermes_state import SessionDB
assert SessionDB._loop_guard_installed and guard._state['mode'] == 'warn'
from persistence.sqlite._holder import StoreHolder
assert StoreHolder._loop_guard_installed and guard._state['mode'] == 'warn'
guard.uninstall()
(tmp_path / 'config.yaml').write_text('gateway: {}\n', encoding='utf-8')
start_loop_liveness_guards(owner, loop)
assert not getattr(SessionDB, '_loop_guard_installed', False) # unset: nothing wrapped
assert not getattr(StoreHolder, '_loop_guard_installed', False) # unset: nothing wrapped
finally:
guard.uninstall()
loop.close()