Coverage for performance/trigger_worker.py: 100%

83 statements  

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

1"""Standalone worker that keeps performance_triggers current (V2-16). 

2 

3Mirrors experience/postgres_worker.py's shape: sync-only, DSN resolution via 

4AETHER_POSTGRES_DSN, --once CLI flag, _pg_conn constructor injection for 

5tests. Unlike postgres_worker.py, this worker reads config.json directly — 

6the 11 threshold keys are strategy config, not infra config, and there is 

7no Lean/main.py context here to inherit them from. 

8 

9This is the durable system of record for trigger history: main.py's 

10in-memory _build_performance_triggers_view() is a fast current-run 

11visualization only and is never the source Phase 17 should read from. 

12""" 

13 

14from __future__ import annotations 

15 

16import argparse 

17import json 

18import logging 

19import time 

20from datetime import datetime, timedelta, timezone 

21from pathlib import Path 

22 

23from execution.secrets_io import secret_env 

24from performance.postgres_triggers import ( 

25 ensure_schema, 

26 fetch_events_since, 

27 fetch_last_retraining_at, 

28 fetch_recent_events, 

29 fetch_triggers_since, 

30 get_watermark, 

31 insert_triggers, 

32 set_watermark, 

33) 

34from performance.rank_ic_monitor import compute_realized_rank_ic_observations 

35from performance.triggers import evaluate_all_triggers 

36 

37logger = logging.getLogger(__name__) 

38 

39_CONFIG_PATH = Path(__file__).resolve().parent.parent / "config.json" 

40 

41 

42def _load_performance_triggers_config(config_path: Path = _CONFIG_PATH) -> dict: 

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

44 config = json.load(f) 

45 return config.get("phase_v2", {}).get("performance_triggers", {}) 

46 

47 

48class TriggerWorker: 

49 """Evaluates performance triggers over new experience_events rows. 

50 

51 Parameters 

52 ---------- 

53 postgres_dsn : psycopg3 DSN (overridden by AETHER_POSTGRES_DSN env) 

54 config : phase_v2.performance_triggers config dict 

55 poll_interval : seconds to sleep between polls in run() 

56 batch_limit : max experience_events rows fetched per run_once() call 

57 _pg_conn : injected psycopg3 connection (skips real connection — tests only) 

58 """ 

59 

60 def __init__( 

61 self, 

62 *, 

63 postgres_dsn: str = "", 

64 config: dict, 

65 poll_interval: int = 30, 

66 batch_limit: int = 10_000, 

67 _pg_conn=None, 

68 ) -> None: 

69 self.config = config 

70 self.poll_interval = poll_interval 

71 self.batch_limit = batch_limit 

72 

73 if _pg_conn is not None: 

74 self._conn = _pg_conn 

75 else: 

76 import psycopg 

77 

78 dsn = secret_env("POSTGRES_DSN", postgres_dsn) 

79 self._conn = psycopg.connect(dsn, autocommit=False) 

80 logger.info("TriggerWorker: PostgreSQL connected.") 

81 

82 ensure_schema(self._conn) 

83 

84 def run_once(self) -> int: 

85 """Advance the watermark off the incremental new-events batch (cheap 

86 idle polls), but evaluate triggers over a true rolling window of 

87 durable Postgres history instead - the last `rolling_window_events` 

88 observations, bounded to the last `rolling_window_days` days or 

89 since the last retrain (whichever is more recent). This is what 

90 makes Sharpe/win-rate/confidence-decay/topology-drift meaningful 

91 instead of only reacting to whatever arrived since the last poll 

92 (the V2-16 limitation this phase fixes). 

93 

94 Returns count of NEW trigger rows inserted (post-suppression). 

95 """ 

96 since = get_watermark(self._conn) 

97 new_events = fetch_events_since(self._conn, since, limit=self.batch_limit) 

98 if not new_events: 

99 return 0 

100 

101 now = datetime.now(timezone.utc) 

102 rolling_days = int(self.config.get("rolling_window_days", 30)) 

103 history_since = now - timedelta(days=rolling_days) 

104 last_retrain_at = fetch_last_retraining_at(self._conn) 

105 if last_retrain_at is not None and last_retrain_at > history_since: 

106 history_since = last_retrain_at 

107 

108 history_events = fetch_recent_events( 

109 self._conn, 

110 limit=int(self.config.get("rolling_window_events", 500)), 

111 since=history_since, 

112 ) 

113 baseline_minutes = int(self.config.get("trigger_frequency_spike_baseline_minutes", 1440)) 

114 recent_triggers = fetch_triggers_since(self._conn, since=now - timedelta(minutes=baseline_minutes)) 

115 

116 # Phase 6 of the 5/10 -> 9/10 roadmap: rank_ic_observations self-joins 

117 # the same rolling-window history_events every other trigger reads 

118 # (ticker/date/close_price/resolved_predicted_rank_20d fields already 

119 # present per experience event) - no separate Postgres fetch needed. 

120 rank_ic_observations = compute_realized_rank_ic_observations( 

121 history_events, 

122 horizon_days=int(self.config.get("rank_ic_resolution_horizon_days", 20)), 

123 ) 

124 

125 report = evaluate_all_triggers( 

126 history_events, 

127 self.config, 

128 recent_triggers=recent_triggers, 

129 rank_ic_observations=rank_ic_observations, 

130 ) 

131 inserted = insert_triggers( 

132 self._conn, 

133 report["triggers"], 

134 suppression_minutes=int(self.config.get("suppression_minutes", 60)), 

135 ) 

136 set_watermark(self._conn, new_events[-1]["created_at"]) 

137 logger.info( 

138 "TriggerWorker: evaluated %d events (rolling window), inserted %d new trigger rows.", 

139 len(history_events), 

140 inserted, 

141 ) 

142 return inserted 

143 

144 def run(self) -> None: 

145 logger.info("TriggerWorker: entering run loop.") 

146 while True: 

147 try: 

148 self.run_once() 

149 time.sleep(self.poll_interval) 

150 except KeyboardInterrupt: 

151 logger.info("TriggerWorker: shutdown requested.") 

152 break 

153 except Exception as exc: 

154 logger.error("TriggerWorker error — %s. Retrying in %ds.", exc, self.poll_interval) 

155 time.sleep(self.poll_interval) 

156 

157 def close(self) -> None: 

158 try: 

159 self._conn.close() 

160 except Exception: 

161 pass 

162 

163 

164def main() -> None: 

165 logging.basicConfig( 

166 level=logging.INFO, 

167 format="%(asctime)s [%(levelname)s] %(name)s — %(message)s", 

168 ) 

169 parser = argparse.ArgumentParser(description="Aether Quant performance trigger worker") 

170 parser.add_argument("--once", action="store_true", help="Evaluate one batch and exit") 

171 parser.add_argument("--poll-interval", type=int, default=30) 

172 args = parser.parse_args() 

173 

174 postgres_dsn = secret_env("POSTGRES_DSN", "") 

175 config = _load_performance_triggers_config() 

176 

177 worker = TriggerWorker(postgres_dsn=postgres_dsn, config=config, poll_interval=args.poll_interval) 

178 try: 

179 if args.once: 

180 count = worker.run_once() 

181 logger.info("--once: inserted %d new trigger rows.", count) 

182 else: 

183 worker.run() 

184 finally: 

185 worker.close() 

186 

187 

188if __name__ == "__main__": 

189 main()