Coverage for risk/kill_switch.py: 100%

100 statements  

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

1"""V5.1 Phase 6 (production safety): the automatic, per-bar circuit 

2breaker. Deliberately trips the EXISTING trade-lock machinery (main.py's 

3self.trade_lock_active/self.trade_lock_reason, already consumed by 

4execution/order_gate.py::resolve_order_permission()'s risk_locks_healthy 

5input, analyzer/market_analyzer.py's Priority 1 reduce_risk check, state.json, 

6and the audit log) rather than adding a second, parallel lock - a second 

7lock would create two sources of truth that can disagree, and `aq 

8trade-lock --off`/`--auto` would no longer be a complete story. 

9 

10Pure, deterministic, cheap: evaluate_kill_switch() does only dict/threshold 

11comparisons over ALREADY-COMPUTED inputs (a rolling per-bar return history, 

12a drawdown-velocity figure, etc. - all assembled by main.py once per bar 

13from state it already tracks) - no I/O, no per-bar work heavier than a 

14handful of float comparisons, respecting main.py's per-bar latency budget 

15the same way every other pure risk/analyzer module in this codebase does. 

16 

17GUARDRAIL - fail-open at two levels, matching execution/cost_model.py:: 

18build_net_edge_decision()'s own contract: 

19 1. config["enabled"] is False (the function-level default) -> never trips, 

20 full no-op, regardless of any other input. 

21 2. Even when enabled, each INDIVIDUAL condition's own threshold defaults 

22 to a value that condition can never cross - so enabling the kill 

23 switch with only some thresholds configured only activates those 

24 specific checks, never accidentally activates an unconfigured one. 

25""" 

26 

27from __future__ import annotations 

28 

29import math 

30from dataclasses import asdict, dataclass, field 

31from typing import Any 

32 

33# Deliberately extreme "this condition can never fire" sentinels - not 0.0 

34# or None, which would either behave surprisingly (0.0 is a real threshold 

35# some configs might genuinely want) or require every comparison below to 

36# be null-guarded twice. A value this far outside any plausible input 

37# reliably degrades a single unconfigured condition to a no-op without 

38# touching the others. 

39_NEVER_BELOW = -1e12 

40_NEVER_ABOVE = 1e12 

41 

42 

43@dataclass(frozen=True) 

44class KillSwitchDecision: 

45 """The kill switch's verdict on one bar: tripped or not, severity, triggers, the reason and what it observed against which thresholds.""" 

46 tripped: bool 

47 severity: str 

48 triggers: list[str] = field(default_factory=list) 

49 reason: str = "" 

50 recommended_action: str = "none" 

51 observed: dict = field(default_factory=dict) 

52 thresholds: dict = field(default_factory=dict) 

53 

54 def to_dict(self) -> dict[str, Any]: 

55 return asdict(self) 

56 

57 @property 

58 def rolling_sharpe_tripped(self) -> bool: 

59 """The next bar's `runtime_metrics["rolling_sharpe_tripped_last_bar"]` (the `release_rolling_sharpe` band).""" 

60 return "rolling_sharpe_below_floor" in self.triggers 

61 

62 @property 

63 def rolling_sharpe_below_run(self) -> int: 

64 """The next bar's `runtime_metrics["rolling_sharpe_below_run_last_bar"]` (`trip_confirm_bars`'s counter): the 

65 consecutive bars the rolling Sharpe has read below the floor, whether or not the trip is confirmed yet.""" 

66 return int(self.observed.get("rolling_sharpe_below_run", 0) or 0) 

67 

68 

69def _finite_or_none(value) -> float | None: 

70 """V5.4.5 (development/Problems.md #117): normalizes a runtime metric to 

71 a finite float or None. The individual trigger guards below only check 

72 `is not None` before a one-sided comparison - and every one of those 

73 comparisons is False for NaN (`nan < floor` / `nan > cap`), so a NaN 

74 metric silently skipped its own condition while the switch appeared 

75 armed. NaN now degrades exactly like the documented None path.""" 

76 if value is None: 

77 return None 

78 try: 

79 as_float = float(value) 

80 except (TypeError, ValueError): 

81 return None 

82 return as_float if math.isfinite(as_float) else None 

83 

84 

85def _rolling_sharpe( 

86 returns: list[float], trading_days_per_year: int = 252, min_return_std_floor: float = 0.0 

87) -> float | None: 

88 """None (never 0.0) when there are fewer than 2 observations - the 

89 caller must be able to tell "not enough data yet" apart from 

90 "genuinely zero Sharpe" (a std of exactly 0.0 with >=2 observations IS 

91 reported as 0.0, same convention evaluation/rank_book_simulator.py:: 

92 _annualized_sharpe() already uses). 

93 

94 GUARDRAIL (Problems.md - a sticky kill-switch trip from a numerically 

95 meaningless reading): std <= max(0.0, min_return_std_floor) also 

96 returns a clean 0.0 - widening the exact-zero guard above into a 

97 near-zero guard. mean/std*sqrt(trading_days_per_year) is numerically 

98 explosive whenever std is small but nonzero: a return window that's 

99 mostly flat/cash (e.g. a mostly-uninvested portfolio) with just a 

100 couple of small real values mixed in can swing to wildly extreme 

101 Sharpe readings - both directions - purely from which few nonzero 

102 values happen to still be inside the window, not from genuine risk- 

103 adjusted performance. Reproduced directly against a real backtest's 

104 equity curve: a near-flat window produced Sharpe swings of +2.25 and 

105 -2.28 bar-to-bar from noise alone. min_return_std_floor=0.0 (default) 

106 reproduces today's exact behavior for any caller that doesn't pass it.""" 

107 if len(returns) < 2: 

108 return None 

109 # V5.4.5 (Problems.md #117): one non-finite return poisons mean/std into 

110 # NaN, which then silently skipped the Sharpe comparison downstream. 

111 # A window containing any non-finite value is not a readable window - 

112 # degrade to None (the documented "insufficient data" path). 

113 if any(not math.isfinite(float(value)) for value in returns): 

114 return None 

115 mean = sum(returns) / len(returns) 

116 # a product, not `** 2`: float power raises OverflowError on a huge return where a product gives inf (V6.6.7, #363) 

117 variance = sum((value - mean) * (value - mean) for value in returns) / (len(returns) - 1) 

118 if not (math.isfinite(mean) and math.isfinite(variance)): 

119 return None 

120 std = math.sqrt(variance) 

121 if std <= max(0.0, min_return_std_floor): 

122 return 0.0 

123 sharpe = (mean / std) * math.sqrt(trading_days_per_year) 

124 return sharpe if math.isfinite(sharpe) else None 

125 

126 

127def evaluate_kill_switch(runtime_metrics: dict[str, Any], config: dict[str, Any]) -> KillSwitchDecision: 

128 """Evaluated once per bar by main.py, fed a `runtime_metrics` dict it 

129 assembles from state it already tracks: 

130 - "recent_bar_returns": list[float] - a rolling per-bar portfolio 

131 return history (main.py's own bounded deque), used to compute a 

132 rolling Sharpe over the trailing `evaluation_bars` window. 

133 - "drawdown_velocity_pct_per_bar": float | None - this bar's total 

134 drawdown minus the previous bar's (a one-bar rate of change, not 

135 an average - a single sharp bar is exactly what this exists to 

136 catch quickly). 

137 - "live_rank_ic": float | None - the most recent rank-IC-decay 

138 trigger's metric_value, if the LATEST entry in 

139 visualization/grafana/retraining_status.json's last_trigger 

140 happens to be a rank_ic_decay_trigger (main.py never opens its own 

141 Postgres connection - this is the same "read a locally-cached file 

142 a separate Postgres-connected worker refreshes" pattern 

143 read_manual_trade_lock_override()/load_cached_fred_series() already 

144 use). None whenever the latest trigger isn't rank-IC-shaped, not 

145 just when the file is missing - a stale/wrong-shaped signal must 

146 never be treated as a real reading. 

147 - "consecutive_losses": int | None - main.py's own realized-trade 

148 streak counter. 

149 - "slippage_divergence_bps": float | None - realized-vs-expected 

150 round-trip cost divergence from the most recent fill(s) 

151 (execution/cost_model.py's expected estimate vs. the actual fill 

152 price main.py's OnOrderEvent observes). None until at least one 

153 fill has been observed this session. 

154 - "model_age_days": float | None - age of the active model artifact 

155 on disk. 

156 - "reconciliation_breach": bool - True when execution/reconciliation.py:: 

157 reconcile_positions()'s max_abs_weight_drift exceeded 

158 phase_v2.reconciliation.max_tolerated_drift this bar (Step 6.2) 

159 and phase_v2.reconciliation.trips_kill_switch is true - reconciliation 

160 failures trip the switch rather than being logged and ignored. 

161 

162 Any key's value being None simply skips that one condition (never 

163 raises, never counts as a trip) - a bar where a given signal isn't 

164 available yet degrades that ONE condition, not the whole switch.""" 

165 if not bool(config.get("enabled", False)): 

166 return KillSwitchDecision(tripped=False, severity="none", reason="kill_switch_disabled") 

167 

168 evaluation_bars = int(config.get("evaluation_bars", 60)) 

169 # GUARDRAIL (Problems.md - kill switch tripped on bar 2-3 of every 

170 # run): evaluation_bars was previously used ONLY as a slice bound 

171 # ([-evaluation_bars:]), never as a minimum-sample requirement, so 

172 # _rolling_sharpe() happily annualized a 2-observation mean/std by 

173 # sqrt(252) into an absurd magnitude and tripped the switch almost 

174 # immediately. min_bars_for_sharpe defaults to evaluation_bars itself 

175 # (the value's own documented intent - "the trailing window size") and 

176 # gates whether the rolling-Sharpe trigger is evaluated AT ALL this 

177 # bar, not just how much history it's computed over. 

178 min_bars_for_sharpe = int(config.get("min_bars_for_sharpe", evaluation_bars)) 

179 # GUARDRAIL (Problems.md - a real backtest's kill switch stuck sticky 

180 # on a spurious trip) - independent of min_bars_for_sharpe above: 

181 # count and variance are orthogonal failure modes. A window with 

182 # plenty of samples that are almost all exactly zero (e.g. a mostly- 

183 # cash portfolio) clears the count floor fine but is still numerically 

184 # degenerate for mean/std - see _rolling_sharpe()'s own docstring. 

185 # Default 0.0005 (std*sqrt(252) ~= 1% annualized) - below this, daily 

186 # returns are behaviorally indistinguishable from sitting in cash, far 

187 # more likely a near-zero-return artifact than a real low-vol edge. 

188 min_return_std_for_sharpe = float(config.get("min_return_std_for_sharpe", 0.0005)) 

189 min_rolling_sharpe = float(config.get("min_rolling_sharpe", _NEVER_BELOW)) 

190 max_drawdown_velocity_pct_per_bar = float(config.get("max_drawdown_velocity_pct_per_bar", _NEVER_ABOVE)) 

191 min_live_rank_ic = float(config.get("min_live_rank_ic", _NEVER_BELOW)) 

192 max_consecutive_losses = float(config.get("max_consecutive_losses", _NEVER_ABOVE)) 

193 max_slippage_divergence_bps = float(config.get("max_slippage_divergence_bps", _NEVER_ABOVE)) 

194 max_model_age_days = float(config.get("max_model_age_days", _NEVER_ABOVE)) 

195 

196 triggers: list[str] = [] 

197 observed: dict = {} 

198 

199 # evaluation_bars <= 0 previously meant "use the entire history" via 

200 # Python's own `[-0:]` == `[0:]` slice semantics - not a real window, 

201 # and not what a misconfigured 0/negative value should do. Treat it as 

202 # no window at all (insufficient data, trigger never evaluated) rather 

203 # than silently falling back to unbounded history. 

204 all_returns = list(runtime_metrics.get("recent_bar_returns") or []) 

205 recent_returns = all_returns[-evaluation_bars:] if evaluation_bars > 0 else [] 

206 observed["rolling_sharpe_num_bars"] = len(recent_returns) 

207 rolling_sharpe = ( 

208 _rolling_sharpe(recent_returns, min_return_std_floor=min_return_std_for_sharpe) 

209 if len(recent_returns) >= min_bars_for_sharpe 

210 else None 

211 ) 

212 observed["rolling_sharpe"] = rolling_sharpe 

213 # V6.3.0 (rule R-KILL): `release_rolling_sharpe` (default None = no band) keeps a rolling-Sharpe trip latched until 

214 # the Sharpe recovers above the release level, so a reading hovering at the floor does not flip the lock bar to bar. 

215 release_rolling_sharpe = _finite_or_none(config.get("release_rolling_sharpe")) 

216 held_by_band = ( 

217 release_rolling_sharpe is not None 

218 and bool(runtime_metrics.get("rolling_sharpe_tripped_last_bar", False)) 

219 and rolling_sharpe is not None 

220 and rolling_sharpe < release_rolling_sharpe 

221 ) 

222 # V6.4.0 (lead L7): `trip_confirm_bars` (default 1 = a trip on the first bar below the floor) asks for that many 

223 # consecutive readings below it, so one borderline bar cannot flip the lock; a latched trip is still held by the band. 

224 trip_confirm_bars = max(1, int(config.get("trip_confirm_bars", 1))) 

225 below_floor = rolling_sharpe is not None and rolling_sharpe < min_rolling_sharpe 

226 below_run = int(runtime_metrics.get("rolling_sharpe_below_run_last_bar", 0) or 0) + 1 if below_floor else 0 

227 observed["rolling_sharpe_below_run"] = below_run 

228 if rolling_sharpe is not None and ((below_floor and below_run >= trip_confirm_bars) or held_by_band): 

229 triggers.append("rolling_sharpe_below_floor") 

230 

231 drawdown_velocity = _finite_or_none(runtime_metrics.get("drawdown_velocity_pct_per_bar")) 

232 observed["drawdown_velocity_pct_per_bar"] = drawdown_velocity 

233 if drawdown_velocity is not None and drawdown_velocity > max_drawdown_velocity_pct_per_bar: 

234 triggers.append("drawdown_velocity_above_cap") 

235 

236 live_rank_ic = _finite_or_none(runtime_metrics.get("live_rank_ic")) 

237 observed["live_rank_ic"] = live_rank_ic 

238 if live_rank_ic is not None and live_rank_ic < min_live_rank_ic: 

239 triggers.append("live_rank_ic_below_floor") 

240 

241 consecutive_losses = _finite_or_none(runtime_metrics.get("consecutive_losses")) 

242 observed["consecutive_losses"] = consecutive_losses 

243 if consecutive_losses is not None and consecutive_losses > max_consecutive_losses: 

244 triggers.append("consecutive_losses_above_cap") 

245 

246 slippage_divergence_bps = _finite_or_none(runtime_metrics.get("slippage_divergence_bps")) 

247 observed["slippage_divergence_bps"] = slippage_divergence_bps 

248 if slippage_divergence_bps is not None and slippage_divergence_bps > max_slippage_divergence_bps: 

249 triggers.append("slippage_divergence_above_cap") 

250 

251 model_age_days = _finite_or_none(runtime_metrics.get("model_age_days")) 

252 observed["model_age_days"] = model_age_days 

253 if model_age_days is not None and model_age_days > max_model_age_days: 

254 triggers.append("model_age_above_cap") 

255 

256 if bool(runtime_metrics.get("reconciliation_breach", False)): 

257 triggers.append("reconciliation_breach") 

258 observed["reconciliation_breach"] = True 

259 

260 thresholds = { 

261 "evaluation_bars": evaluation_bars, 

262 "min_bars_for_sharpe": min_bars_for_sharpe, 

263 "min_return_std_for_sharpe": min_return_std_for_sharpe, 

264 "min_rolling_sharpe": min_rolling_sharpe, 

265 "release_rolling_sharpe": release_rolling_sharpe, 

266 "trip_confirm_bars": trip_confirm_bars, 

267 "max_drawdown_velocity_pct_per_bar": max_drawdown_velocity_pct_per_bar, 

268 "min_live_rank_ic": min_live_rank_ic, 

269 "max_consecutive_losses": max_consecutive_losses, 

270 "max_slippage_divergence_bps": max_slippage_divergence_bps, 

271 "max_model_age_days": max_model_age_days, 

272 } 

273 

274 if not triggers: 

275 return KillSwitchDecision( 

276 tripped=False, 

277 severity="none", 

278 triggers=[], 

279 reason="all_checks_within_thresholds", 

280 recommended_action="none", 

281 observed=observed, 

282 thresholds=thresholds, 

283 ) 

284 

285 severity = "critical" if len(triggers) > 1 else "warning" 

286 return KillSwitchDecision( 

287 tripped=True, 

288 severity=severity, 

289 triggers=triggers, 

290 reason=f"kill_switch_{'_and_'.join(triggers)}", 

291 recommended_action=str(config.get("action", "trade_lock")), 

292 observed=observed, 

293 thresholds=thresholds, 

294 )