Coverage for retraining/planning.py: 100%
69 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Pure retraining control-layer decisions (Phase V2-17).
3Mirrors execution/order_gate.py's and performance/triggers.py's style: every
4function here operates on plain dicts/scalars, no Postgres/Redis/Lean
5dependency lives here. The caller (retraining/worker.py,
6retraining/orchestrator.py) is responsible for fetching
7performance_triggers rows (performance.postgres_triggers.fetch_candidate_triggers),
8recent retraining_events rows, and the total experience_events observation
9count, then handing them to evaluate_retraining_plan().
11Only triggers with retrain_candidate=True ever reach this module - Phase 16
12already enforces that in the SQL WHERE clause, but select_candidate_trigger()
13re-checks it defensively so this stays correct even if called with an
14unfiltered list in a test.
15"""
17from __future__ import annotations
19from datetime import datetime
20from typing import Any
22_ACTIVE_EVENT_STATUSES = ("planned", "running", "promoted")
24# V2-17.5 - priority weighting so select_candidate_trigger() picks the most
25# consequential eligible trigger, not just the newest one. A lone weak
26# topology event never reaches this list in the first place (performance/
27# triggers.py's persistence guards keep retrain_candidate=False for
28# one-off noise) - this scoring only breaks ties *among* triggers that
29# already cleared that bar.
30_SEVERITY_SCORE = {"critical": 30, "warning": 20, "info": 10}
31_TYPE_BASE_SCORE = {
32 "risk_lock_trigger": 5,
33 "drawdown_trigger": 4,
34 "sharpe_degradation_trigger": 3,
35 "win_rate_trigger": 3,
36 "confidence_decay_trigger": 3,
37 "regime_shift_trigger": 2,
38 "liquidity_warning_trigger": 2,
39 "observation_count_trigger": 1,
40 "topology_uncertainty_trigger": 2,
41 "topology_regime_mismatch_trigger": 2,
42 "cluster_drift_trigger": 2,
43 "model_topology_disagreement_trigger": 2,
44 "trigger_frequency_spike": 2,
45 # Phase 6 of the 5/10 -> 9/10 roadmap - comparable weight to
46 # sharpe_degradation_trigger/win_rate_trigger/confidence_decay_trigger:
47 # a decaying edge in the signal driving rank_sizing_enabled/the
48 # portfolio book is a first-class reason to retrain, same tier as any
49 # other model-quality trigger. select_candidate_trigger() already
50 # generically handles any retrain_candidate=True trigger type - no
51 # other change needed here.
52 "rank_ic_decay_trigger": 3,
53}
54_TOPOLOGY_TRIGGER_TYPES = {
55 "topology_uncertainty_trigger",
56 "topology_regime_mismatch_trigger",
57 "cluster_drift_trigger",
58 "model_topology_disagreement_trigger",
59}
60_REGIME_TOPOLOGY_COMBO_BONUS = 5
61_REPEAT_BONUS_PER_EXTRA = 2
62_REPEAT_BONUS_CAP = 6
65def _parse_timestamp(value) -> datetime:
66 if isinstance(value, datetime):
67 return value
68 return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
71def _trigger_priority_score(trigger: dict[str, Any], eligible: list[dict]) -> float:
72 """Combines severity + trigger-type importance + two persistence-aware
73 bonuses: a "regime shift plus a topology trigger co-occurring" combo
74 bonus (a regime shift alongside topology uncertainty/drift is a
75 stronger signal than either alone - applied only to the regime_shift
76 and topology-type triggers themselves, not to unrelated candidates that
77 merely happen to be eligible at the same time), and a capped "this
78 trigger type/scope has repeated" bonus (a topology mismatch seen 3
79 times among the eligible set outranks one seen once)."""
80 severity_score = _SEVERITY_SCORE.get(trigger.get("severity"), 10)
81 trigger_type = trigger.get("trigger_type")
82 type_score = _TYPE_BASE_SCORE.get(trigger_type, 1)
84 types_present = {candidate.get("trigger_type") for candidate in eligible}
85 is_combo_participant = trigger_type == "regime_shift_trigger" or trigger_type in _TOPOLOGY_TRIGGER_TYPES
86 combo_bonus = (
87 _REGIME_TOPOLOGY_COMBO_BONUS
88 if is_combo_participant and "regime_shift_trigger" in types_present and (types_present & _TOPOLOGY_TRIGGER_TYPES)
89 else 0
90 )
92 repeat_count = sum(
93 1
94 for candidate in eligible
95 if candidate.get("trigger_type") == trigger.get("trigger_type") and candidate.get("scope") == trigger.get("scope")
96 )
97 repeat_bonus = min((repeat_count - 1) * _REPEAT_BONUS_PER_EXTRA, _REPEAT_BONUS_CAP)
99 return severity_score + type_score + combo_bonus + repeat_bonus
102def select_candidate_trigger(triggers: list[dict], config: dict[str, Any]) -> dict[str, Any] | None:
103 """Highest-priority trigger among those with retrain_candidate=True and
104 an eligible severity, ties broken by newest first.
106 `eligible_severities` defaults to ("warning", "critical") - "info"
107 triggers (e.g. observation_count_trigger) never justify a retrain on
108 their own. Priority is `_trigger_priority_score()` - see its docstring
109 for the weighting (critical drawdown beats a topology warning; a
110 regime-shift+topology combo beats either alone; a repeated trigger
111 type/scope beats a single occurrence).
112 """
113 eligible_severities = set(config.get("eligible_severities", ("warning", "critical")))
114 eligible = [
115 trigger
116 for trigger in triggers
117 if trigger.get("retrain_candidate") and trigger.get("severity") in eligible_severities
118 ]
119 if not eligible:
120 return None
121 return max(
122 eligible,
123 key=lambda trigger: (_trigger_priority_score(trigger, eligible), _parse_timestamp(trigger["created_at"])),
124 )
127def min_observations_satisfied(observation_count: int, min_observations: int) -> bool:
128 """Whether enough observations have accumulated to consider retraining."""
129 return observation_count >= min_observations
132def cooldown_remaining_seconds(recent_events: list[dict], cooldown_minutes: float, now: datetime) -> float:
133 """Seconds until the cooldown clears, 0.0 if no active-status event is within it.
135 An event counts against the cooldown while its status is planned/running/
136 promoted - a rejected or failed retraining does not block the next
137 attempt, so noisy triggers can't wedge the system into a permanent
138 cooldown without ever producing a promoted model.
139 """
140 if cooldown_minutes <= 0:
141 return 0.0
143 cooldown_seconds = cooldown_minutes * 60.0
144 latest_active_at: datetime | None = None
145 for event in recent_events:
146 if event.get("status") not in _ACTIVE_EVENT_STATUSES:
147 continue
148 created_at = _parse_timestamp(event["created_at"])
149 if latest_active_at is None or created_at > latest_active_at:
150 latest_active_at = created_at
152 if latest_active_at is None:
153 return 0.0
155 elapsed_seconds = (now - latest_active_at).total_seconds()
156 remaining = cooldown_seconds - elapsed_seconds
157 return max(0.0, remaining)
160def count_events_in_last_day(recent_events: list[dict], now: datetime) -> int:
161 """How many of the events were created in the 24 hours before `now`."""
162 return sum(1 for event in recent_events if (now - _parse_timestamp(event["created_at"])).total_seconds() <= 86400)
165def evaluate_retraining_plan(
166 triggers: list[dict],
167 recent_events: list[dict],
168 observation_count: int,
169 config: dict[str, Any],
170 now: datetime,
171) -> dict[str, Any]:
172 """Top-level pure decision. Checks run in order; the first failure
173 short-circuits with an explanatory reason. The result is:
175 {
176 "should_plan": bool,
177 "reason": str,
178 "selected_trigger": dict | None,
179 "cooldown_remaining_seconds": float,
180 "daily_count": int,
181 "daily_limit_reached": bool,
182 }
183 """
184 if not config.get("enabled", True):
185 return {
186 "should_plan": False,
187 "reason": "retraining_disabled",
188 "selected_trigger": None,
189 "cooldown_remaining_seconds": 0.0,
190 "daily_count": 0,
191 "daily_limit_reached": False,
192 }
194 selected_trigger = select_candidate_trigger(triggers, config)
195 if selected_trigger is None:
196 return {
197 "should_plan": False,
198 "reason": "no_eligible_candidate_trigger",
199 "selected_trigger": None,
200 "cooldown_remaining_seconds": 0.0,
201 "daily_count": 0,
202 "daily_limit_reached": False,
203 }
205 min_observations = int(config.get("min_observations", 0))
206 if not min_observations_satisfied(observation_count, min_observations):
207 return {
208 "should_plan": False,
209 "reason": f"min_observations_not_satisfied ({observation_count} < {min_observations})",
210 "selected_trigger": selected_trigger,
211 "cooldown_remaining_seconds": 0.0,
212 "daily_count": 0,
213 "daily_limit_reached": False,
214 }
216 cooldown_minutes = float(config.get("cooldown_minutes", 0))
217 remaining = cooldown_remaining_seconds(recent_events, cooldown_minutes, now)
218 if remaining > 0:
219 return {
220 "should_plan": False,
221 "reason": f"cooldown_active ({remaining:.0f}s remaining)",
222 "selected_trigger": selected_trigger,
223 "cooldown_remaining_seconds": remaining,
224 "daily_count": 0,
225 "daily_limit_reached": False,
226 }
228 daily_count = count_events_in_last_day(recent_events, now)
229 max_per_day = int(config.get("max_retrainings_per_day", 0)) or None
230 daily_limit_reached = max_per_day is not None and daily_count >= max_per_day
231 if daily_limit_reached:
232 return {
233 "should_plan": False,
234 "reason": f"daily_retraining_limit_reached ({daily_count} >= {max_per_day})",
235 "selected_trigger": selected_trigger,
236 "cooldown_remaining_seconds": 0.0,
237 "daily_count": daily_count,
238 "daily_limit_reached": True,
239 }
241 return {
242 "should_plan": True,
243 "reason": f"eligible_candidate_trigger_selected ({selected_trigger['trigger_type']}/{selected_trigger['severity']})",
244 "selected_trigger": selected_trigger,
245 "cooldown_remaining_seconds": 0.0,
246 "daily_count": daily_count,
247 "daily_limit_reached": False,
248 }