Coverage for retraining/auto_rollback.py: 100%
33 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"""V5.1 Phase 6 (production safety): automated rollback selection.
3Pure - never touches Postgres or calls orchestrator.rollback() itself.
4retraining/worker.py is the caller: it assembles active_version/
5version_history/degradation_signals from Postgres (the same
6fetch_active_model_version()/fetch_rollback_candidates() calls
7retraining/status_export.py already uses), calls select_rollback_target(),
8and only THEN calls the EXISTING, already-fully-implemented
9orchestrator.rollback() when told to - this module makes no new
10promotion/rollback mechanism, it only decides whether the existing one
11should fire automatically instead of waiting for a human to run
12`aq retrain rollback`.
13"""
15from __future__ import annotations
17from typing import Any
20def select_rollback_target(
21 active_version: dict[str, Any],
22 version_history: list[dict],
23 degradation_signals: dict[str, Any],
24 config: dict[str, Any],
25) -> dict[str, Any]:
26 """Returns {"should_rollback": bool, "to_version_id": str | None,
27 "reason": str, "failures": list[str]}.
29 active_version: the currently active model_versions row (retraining/
30 postgres_registry.py::fetch_active_model_version()'s shape).
31 version_history: candidate rollback TARGETS, newest first (fetch_rollback_candidates()'s
32 shape - status in {"archived", "rolled_back"}).
33 degradation_signals: {"kill_switch_tripped": bool, "net_sharpe_decay": bool,
34 "rank_ic_decay": bool, "bars_since_promotion": int, "bars_since_last_rollback": int | None}
35 - the trigger flags plus the two "how long has X been true" counters this
36 function needs to enforce cooldown/runway (deliberately plain integers,
37 not timestamps - retraining/worker.py owns translating its own notion
38 of "how long" into a count, this module never needs to know what a
39 "bar" represents in that context).
41 GUARDRAIL - enabled defaults to False: an automatic weight swap is the
42 single most consequential action in this system, must be opt-in.
44 REFUSES to act (should_rollback=False, reason names exactly which
45 guard blocked it) when:
46 - config["enabled"] is not True.
47 - none of config["triggers"] (default ["kill_switch_tripped",
48 "net_sharpe_decay", "rank_ic_decay"]) are True in degradation_signals.
49 - degradation_signals["bars_since_promotion"] < config["min_bars_since_promotion"]
50 (default 40) - the active version needs a minimum runway to prove
51 itself before being judged.
52 - a rollback already happened within config["cooldown_bars"] (default
53 120) - degradation_signals["bars_since_last_rollback"] is None (never
54 rolled back) or >= cooldown_bars to pass this guard.
55 - no candidate in version_history satisfies config["require_prior_gate_pass"]
56 (default True) - metrics.validation_gate.passed must be True on the
57 chosen candidate; a version that never cleared the gate itself is
58 never a valid rollback target, no matter how badly the active one is
59 degrading.
61 Picks the NEWEST (version_history[0]) candidate that passes the gate
62 check - never an arbitrary/older one when a newer valid candidate
63 exists."""
64 failures: list[str] = []
66 # V6.6.7 (#371, formal/AetherFormal/AutoRollback.lean): `is True`, as documented. bool("false") is True, so a
67 # hand-edited string enabled the most consequential action in the system; a string trigger or gate flag did the same
68 if config.get("enabled", False) is not True:
69 return {"should_rollback": False, "to_version_id": None, "reason": "auto_rollback_disabled", "failures": []}
71 configured_triggers = list(config.get("triggers", ["kill_switch_tripped", "net_sharpe_decay", "rank_ic_decay"]))
72 fired_triggers = [name for name in configured_triggers if degradation_signals.get(name, False) is True]
73 if not fired_triggers:
74 return {
75 "should_rollback": False, "to_version_id": None,
76 "reason": "no_configured_trigger_fired", "failures": [],
77 }
79 min_bars_since_promotion = int(config.get("min_bars_since_promotion", 40))
80 bars_since_promotion = degradation_signals.get("bars_since_promotion")
81 if bars_since_promotion is None or int(bars_since_promotion) < min_bars_since_promotion:
82 failures.append("active_version_below_min_runway")
84 cooldown_bars = int(config.get("cooldown_bars", 120))
85 bars_since_last_rollback = degradation_signals.get("bars_since_last_rollback")
86 if bars_since_last_rollback is not None and int(bars_since_last_rollback) < cooldown_bars:
87 failures.append("cooldown_active")
89 require_prior_gate_pass = bool(config.get("require_prior_gate_pass", True))
90 to_version_id = None
91 if not failures:
92 for candidate in version_history:
93 if require_prior_gate_pass:
94 gate_passed = ((candidate.get("metrics") or {}).get("validation_gate") or {}).get("passed", False) is True
95 if not gate_passed:
96 continue
97 to_version_id = candidate.get("model_version_id")
98 break
99 if to_version_id is None:
100 failures.append("no_eligible_rollback_target")
102 if failures:
103 return {
104 "should_rollback": False, "to_version_id": None,
105 "reason": f"blocked: {', '.join(failures)}", "failures": failures,
106 }
108 return {
109 "should_rollback": True,
110 "to_version_id": to_version_id,
111 "reason": f"triggered_by: {', '.join(fired_triggers)}",
112 "failures": [],
113 }