Coverage for execution/paper_readiness_io.py: 100%

29 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""IO layer for paper/live broker readiness (Phase V2-21/V2-22). 

2 

3Mirrors risk/manual_override.py's read pattern: a single-key, mtime-gated 

4config.json reader (see execution/config_cache.py) so a long-running 

5paper/live process can pick up a config edit at the next session rollover 

6without a restart. Also provides the one new Postgres query 

7paper_readiness_report.py needs - observation-mode experience_events, which 

8performance/postgres_triggers.py's existing fetch_recent_events()/ 

9fetch_events_since() don't filter by mode. 

10""" 

11 

12from __future__ import annotations 

13 

14import json 

15from datetime import datetime, timezone 

16from pathlib import Path 

17 

18from execution.config_cache import read_cached 

19 

20_PHASE_V2_KEY = "phase_v2" 

21_PAPER_TRADING_KEY = "paper_trading" 

22 

23 

24def read_paper_trading_config(config_path: Path) -> dict: 

25 """Mtime-gated read of phase_v2.paper_trading. Returns {} if the file or 

26 key is absent - never raises.""" 

27 return read_cached(config_path, _read_paper_trading_config_uncached) 

28 

29 

30def _read_paper_trading_config_uncached(config_path: Path) -> dict: 

31 if not config_path.exists(): 

32 return {} 

33 with config_path.open("r", encoding="utf-8") as f: 

34 config = json.load(f) 

35 value = config.get(_PHASE_V2_KEY, {}).get(_PAPER_TRADING_KEY, {}) 

36 return value if isinstance(value, dict) else {} 

37 

38 

39def fetch_observation_mode_events(conn, limit: int = 10_000, since: datetime | None = None) -> list[dict]: 

40 """Fetch experience_events payloads logged in mode='observation', oldest 

41 first - feeds evaluate_observation_readiness() via 

42 experience.observation_metrics.compute_observation_summary().""" 

43 if since is None: 

44 since = datetime.fromtimestamp(0, tz=timezone.utc) 

45 

46 try: 

47 with conn.cursor() as cur: 

48 cur.execute( 

49 "SELECT payload FROM experience_events WHERE mode = %(mode)s AND created_at > %(since)s " 

50 "ORDER BY created_at ASC LIMIT %(limit)s;", 

51 {"mode": "observation", "since": since, "limit": limit}, 

52 ) 

53 rows = cur.fetchall() 

54 except Exception as exc: 

55 # A database the experience worker never wrote to has no table yet (Problems #339, found on a real Postgres): that is "no observation events", which the readiness 

56 # check reports as not ready, not a crash. Any other database error still raises. 

57 if type(exc).__name__ != "UndefinedTable": 

58 raise 

59 conn.rollback() 

60 return [] 

61 

62 return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]