Repository navigation
Expand file tree
/
Copy pathhermes_state_loop_guard.py
More file actions
143 lines (118 loc) · 5.4 KB
/
Copy pathhermes_state_loop_guard.py
File metadata and controls
143 lines (118 loc) · 5.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
"""Debug guard: flag ``SessionDB`` storage calls made on a thread that is running an asyncio loop.
A synchronous SQLite read or write inside a coroutine blocks its whole event loop for as long as the
storage takes: on slow storage (a network filesystem holding WAL ``-shm`` locks) one call stops every
socket, timer, Stop and liveness probe the gateway serves. Async code reaches the store through a
worker (``asyncio.to_thread``, ``gateway.session_runtime_workers.tracked_write``) instead.
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 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
import os
import sys
import threading
import traceback
logger = logging.getLogger(__name__)
CONFIG_KEY = 'gateway.sessiondb_loop_guard'
_MODES = ('warn', 'raise', 'record')
_RECORD_MAX = 2000
_state = {'mode': None}
_records: list = []
_warned: set = set()
_lock = threading.Lock()
class LoopSessionDBCall(RuntimeError):
"""A SessionDB storage call ran on an event-loop thread (``gateway.sessiondb_loop_guard: raise``)."""
def _on_event_loop():
try:
asyncio.get_running_loop()
except RuntimeError:
return False
return True
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)
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
return frame
return stack[-1]
def _check(kind):
mode = _state['mode']
if mode is None or not _on_event_loop():
return
stack = traceback.extract_stack()[:-2]
caller = _caller(stack)
site = f'{caller.filename}:{caller.lineno}'
if mode == 'raise':
raise LoopSessionDBCall(f'SessionDB {kind} on the event-loop thread from {site}')
with _lock:
if mode == 'record':
if len(_records) < _RECORD_MAX:
_records.append({'kind': kind, 'site': site, 'function': caller.name,
'thread': threading.current_thread().name, 'stack': stack})
return
if site in _warned:
return
_warned.add(site)
logger.warning('SessionDB %s on the event-loop thread from %s (%s):\n%s', kind, site, caller.name,
''.join(traceback.format_list(stack[-12:])))
def install(mode):
"""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 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')
return read(self, *args, **kwargs)
def _execute_write(self, *args, **kwargs):
_check('write')
return write(self, *args, **kwargs)
_read_ctx.__wrapped__, _execute_write.__wrapped__ = read, write
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 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()
def recorded():
with _lock:
return list(_records)
def clear():
with _lock:
_records.clear()
_warned.clear()
def install_from_config(cfg):
"""Gateway startup hook: install in the mode ``gateway.sessiondb_loop_guard`` names in the raw
config.yaml mapping *cfg*; unset, empty, ``off`` or false does nothing."""
gateway = cfg.get('gateway') if isinstance(cfg, dict) else None
value = gateway.get('sessiondb_loop_guard') if isinstance(gateway, dict) else None
mode = str(value).strip().lower() if value not in (None, False) else ''
if mode in ('', 'off', 'false', 'none'):
return None
mode = install(mode)
if mode is not None:
print(f'[gateway] {CONFIG_KEY}={mode}: SessionDB calls on the event loop are flagged', file=sys.stderr)
return mode