Files
thor/tests/fakes.py
T
jaredandClaude Opus 5.5 983ba27386
CI / Lint (flake8, house style) (pull_request) Successful in 50s
CI / Test (pytest) (pull_request) Successful in 52s
CI / Security (bandit, pip-audit) (pull_request) Successful in 1m1s
CI / Integration (MariaDB) (pull_request) Successful in 1m40s
CI / Scan (secrets, workflows, shell, patterns) (pull_request) Successful in 1m15s
CI / Deploy (pull_request) Skipped
Engine, memory check, symptom checks, outbox, T1 replay
- thor/engine.py: one incident per root cause. New causes held one cycle, symptoms attached
  to the highest cause they relate to (same host, or cluster-wide effects for causes that
  can stall the cluster), priority only rises, rate-limited refresh, cleared after 15 min.
- thor/checks/memory.py: node_vmstat_oom_kill + kernel oom-kill lines; global vs cgroup,
  victim and CT, trigger cpuset; P3 / P2 (loop) / P1 (Ceph or other hosts stalling).
- thor/checks/symptoms.py: scrape timeouts, pvestatd timeouts, Ceph alerts switching on.
- thor/outbox.py: live actions to Tinker with backoff; shadow actions are only recorded.
- Migration 2: incidents, actions, observations.
- PromQL/LogQL regex escaping fixed (found by recording against the real Prometheus).
- tests/replay.py + tests/fixtures/t1.json: 2026-11-23 replayed through the real monitor:
  exactly one ticket (P1 from the start: pvestatd timed out on three other hosts with the
  first kill), 15 symptoms as Also seen, cleared 06:18, Loki's 06:00 outage delays only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 23:02:10 -05:00

184 lines
6.4 KiB
Python

"""Test doubles: an in-memory Store, an HTTP session that serves canned replies, sources."""
import json
from typing import Any, Dict, List, Optional
import requests
from thor.clients import SourceError
from thor.db import DatabaseError
class FakeStore:
"""Same methods as thor.db.Store, kept in memory. Set ``down = True`` to simulate CT 149 away."""
def __init__(self):
self.down = False
self.state: Dict[str, Any] = {}
self.cycles: List[dict] = []
self.sources: Dict[str, dict] = {}
self.blind: List[dict] = []
self.calls: List[str] = []
self.incidents: Dict[str, dict] = {}
self.actions: List[dict] = []
self.observations: Dict[str, dict] = {}
def _check(self, name):
self.calls.append(name)
if self.down:
raise DatabaseError('Lost connection to MySQL server')
def set_state(self, key, value, now):
self._check('set_state')
self.state[key] = json.loads(json.dumps(value, default=str))
def get_state(self, key, default=None):
self._check('get_state')
return self.state.get(key, default)
def record_cycle(self, **kw):
self._check('record_cycle')
self.cycles.append(kw)
return len(self.cycles)
def prune_cycles(self, older_than):
self._check('prune_cycles')
before = len(self.cycles)
self.cycles = [c for c in self.cycles if c['started'] >= older_than]
return before - len(self.cycles)
def source_statuses(self):
self._check('source_statuses')
return {k: dict(v) for k, v in self.sources.items()}
def save_source_status(self, name, up, since, last_ok, last_error, now):
self._check('save_source_status')
self.sources[name] = {'up': up, 'since': since, 'last_ok': last_ok, 'last_error': last_error}
def open_blind_period(self, source, started, reason):
self._check('open_blind_period')
self.blind.append({'source': source, 'started': started, 'ended': None, 'reason': reason})
def close_blind_period(self, source, ended):
self._check('close_blind_period')
for b in self.blind:
if b['source'] == source and b['ended'] is None:
b['ended'] = ended
def save_incident(self, inc, now):
self._check('save_incident')
self.incidents[inc['key']] = json.loads(json.dumps(inc, default=str))
def load_incidents(self, since):
self._check('load_incidents')
return [dict(i) for i in self.incidents.values()
if i['state'] in ('pending', 'open') or i['last_seen'] >= since]
def add_action(self, action):
self._check('add_action')
a = json.loads(json.dumps(action, default=str))
a.update(id=len(self.actions) + 1, status='pending' if a['mode'] == 'live' else 'shadow',
attempts=0, next_attempt_at=a['created'] if a['mode'] == 'live' else None, ticket_id=None)
self.actions.append(a)
return a['id']
def due_actions(self, now, limit=20):
self._check('due_actions')
return [a for a in self.actions if a['status'] == 'pending' and a['next_attempt_at'] <= now][:limit]
def mark_action_sent(self, action_id, ticket_id, now):
self._check('mark_action_sent')
a = self.actions[action_id - 1]
a.update(status='sent', ticket_id=ticket_id, sent_at=now)
def mark_action_failed(self, action_id, error, attempts, retry_at):
self._check('mark_action_failed')
a = self.actions[action_id - 1]
a.update(status='pending' if retry_at is not None else 'failed', attempts=attempts,
next_attempt_at=retry_at, error=error)
def incident_ticket(self, key):
self._check('incident_ticket')
ids = [a['ticket_id'] for a in self.actions if a['incident_key'] == key and a.get('ticket_id')]
return ids[-1] if ids else None
def save_observation(self, f, now):
self._check('save_observation')
o = self.observations.get(f['key'])
if o:
o['start'], o['end'] = min(o['start'], f['start']), max(o['end'], f['end'])
o['summary'], o['role'] = f['summary'], f['role']
else:
self.observations[f['key']] = json.loads(json.dumps(f, default=str))
def blind_periods(self, since):
self._check('blind_periods')
return [b for b in self.blind if b['ended'] is None or b['ended'] >= since]
class FakeResponse:
def __init__(self, status: int = 200, body: Any = None, text: Optional[str] = None):
self.status_code = status
self._body = body
self.text = text if text is not None else json.dumps(body)
def json(self):
if self._body is None:
raise ValueError('no JSON')
return self._body
def raise_for_status(self):
if self.status_code >= 400:
raise requests.HTTPError(f'HTTP {self.status_code}')
class FakeSession:
"""Serves replies in order for each (method, url-prefix). Records every request."""
def __init__(self):
self.routes: List[tuple] = []
self.requests: List[dict] = []
def add(self, method: str, url_prefix: str, *replies):
self.routes.append((method.upper(), url_prefix, list(replies)))
return self
def _serve(self, method, url, **kw):
self.requests.append({'method': method, 'url': url, **kw})
for m, prefix, replies in self.routes:
if m == method and url.startswith(prefix):
reply = replies[0] if len(replies) == 1 else replies.pop(0)
if isinstance(reply, Exception):
raise reply
return reply
raise requests.ConnectionError(f'no route for {method} {url}')
def get(self, url, **kw):
return self._serve('GET', url, **kw)
def post(self, url, **kw):
return self._serve('POST', url, **kw)
class FakeSource:
def __init__(self, name: str, up: bool = True, error: str = 'connection refused'):
self.name = name
self.up = up
self.error = error
self.pings = 0
def ping(self):
self.pings += 1
if not self.up:
raise SourceError(self.name, self.error)
class Clock:
def __init__(self, t: float = 1_795_575_600.0): # 2026-11-25 03:00:00 UTC
self.t = t
def __call__(self):
return self.t
def advance(self, seconds: float):
self.t += seconds