Coverage for retraining/worker.py: 100%
148 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"""Continuous, toggleable retraining worker (Phase V2-17).
3Mirrors performance/trigger_worker.py's TriggerWorker shape (Postgres-only,
4--once CLI flag, _pg_conn injection for tests, config read from config.json
5directly). Unlike TriggerWorker, each run_once() cycle can drive the full
6plan -> train -> validate -> backtest -> commit -> (promote) pipeline via
7retraining/orchestrator.py's stage functions.
9Three safety knobs keep this "no uncontrolled live learning":
10- config["enabled"] (phase_v2.retraining.enabled): a live off-switch checked
11 every cycle - flip it in config.json without touching the running
12 container.
13- config["worker"]["auto_promote"] (default False): the worker stops after
14 a successful vault commit (status="validated") and leaves promotion for a
15 manual `python -m retraining.orchestrator promote --version-id <id>` call.
16 Only when explicitly set True does the worker call promote() itself.
17- config["worker"]["auto_promote_blocked_in_live_mode"] (default True,
18 V2-22): even with auto_promote=True, the worker forces manual promotion
19 whenever phase_v2.runtime.mode == "live" - full autonomy is fine while no
20 live trading exists yet, but a model change should not silently go live
21 without a human looking at it once real orders are possible.
22"""
24from __future__ import annotations
26import argparse
27import json
28import logging
29import time
30from datetime import datetime, timedelta, timezone
31from pathlib import Path
32from uuid import uuid4
34from execution.runtime_config_io import read_runtime_mode
35from execution.secrets_io import secret_env
36from performance.postgres_triggers import ensure_schema as ensure_performance_schema
37from performance.postgres_triggers import fetch_triggers_since, insert_triggers
38from retraining.orchestrator import (
39 _CONFIG_PATH,
40 _load_retraining_config,
41 auto_rollback_status,
42 backtest,
43 commit,
44 plan,
45 preflight_vault,
46 promote,
47 reconcile_stale_running_events,
48 rollback,
49 status,
50 train,
51 train_gating,
52 train_multitask,
53 train_sequence,
54 train_strategy_selector,
55 train_topology,
56 validate,
57)
58from retraining.postgres_registry import ensure_schema
60logger = logging.getLogger(__name__)
62# V5.1 Phase 6 (production safety) - main.py's Phase 6 wiring writes
63# kill_switch.tripped into this same file every bar (see main.py::
64# _write_state()) - this worker never opens a connection to Lean's
65# process, it only reads the locally-mounted file, same "read a file a
66# separate process keeps fresh" pattern main.py itself uses in the other
67# direction for retraining_status.json.
68_STATE_PATH = Path(__file__).resolve().parent.parent / "visualization" / "state.json"
71class RetrainingWorker:
72 """Drives the retraining pipeline on a poll interval.
74 Parameters
75 ----------
76 postgres_dsn : psycopg3 DSN (overridden by AETHER_POSTGRES_DSN env)
77 config : phase_v2.retraining config dict
78 poll_interval : seconds to sleep between polls in run()
79 _pg_conn : injected psycopg3 connection (skips real connection — tests only)
80 """
82 def __init__(
83 self,
84 *,
85 postgres_dsn: str = "",
86 config: dict,
87 poll_interval: int = 300,
88 config_path: Path = _CONFIG_PATH,
89 _pg_conn=None,
90 ) -> None:
91 self.config = config
92 self.poll_interval = poll_interval
93 self._config_path = config_path
95 if _pg_conn is not None:
96 self._conn = _pg_conn
97 else:
98 import psycopg
100 dsn = secret_env("POSTGRES_DSN", postgres_dsn)
101 self._conn = psycopg.connect(dsn, autocommit=False)
102 logger.info("RetrainingWorker: PostgreSQL connected.")
104 ensure_schema(self._conn)
105 ensure_performance_schema(self._conn)
107 # Reconcile any retraining_events row orphaned by a prior crash/
108 # redeploy mid-cycle (see development/Problems.md #48) before the
109 # poll loop starts - otherwise a single interrupted cycle silently
110 # blocks every future retraining attempt for the full cooldown window.
111 reconciled = reconcile_stale_running_events(self._conn, self.config)
112 if reconciled:
113 logger.warning("RetrainingWorker: reconciled %d orphaned retraining_events row(s) on startup.", len(reconciled))
115 def run_once(self) -> dict:
116 """Runs at most one full retraining cycle. Returns a summary dict.
118 no-ops immediately (returns {"ran": False, "reason": "disabled"})
119 if config["enabled"] is False - the master toggle.
120 """
121 if not self.config.get("enabled", True):
122 return {"ran": False, "reason": "disabled"}
124 plan_result = plan(self._conn, self.config)
125 if not plan_result["should_plan"]:
126 return {"ran": False, "reason": plan_result["reason"]}
128 retraining_id = plan_result["retraining_id"]
129 preflight = preflight_vault(self._conn, retraining_id, self.config)
130 if not preflight["ok"]:
131 return {"ran": True, "reason": "vault_preflight_failed", "retraining_id": retraining_id,
132 "detail": preflight["reason"]}
134 train_result = train(self._conn, retraining_id)
135 if not train_result["ok"]:
136 return {"ran": True, "reason": "train_failed", "retraining_id": retraining_id}
138 version_id = train_result["version_id"]
140 # Best-effort learned-topology training (V2-17.5) - failure here is
141 # logged inside train_topology() itself and never blocks the
142 # primary candidate's own validate/backtest/commit/promote path.
143 train_topology(self._conn, retraining_id, version_id, self.config)
145 # Best-effort learned-gating training - same contract, failure is
146 # logged inside train_gating() itself and never blocks the primary
147 # candidate's own validate/backtest/commit/promote path.
148 train_gating(self._conn, retraining_id, version_id, self.config)
150 # Best-effort multitask (direction+magnitude+volatility) training -
151 # same contract, failure is logged inside train_multitask() itself
152 # and never blocks the primary candidate's own validate/backtest/
153 # commit/promote path.
154 train_multitask(self._conn, retraining_id, version_id, self.config)
156 # Best-effort Phase 2 sequence-encoder training - same contract,
157 # failure is logged inside train_sequence() itself and never
158 # blocks the primary candidate's own validate/backtest/commit/
159 # promote path.
160 train_sequence(self._conn, retraining_id, version_id, self.config)
162 # Best-effort learned strategy-selector training (V4.7,
163 # development/Problems.md #29's own framing) - same contract,
164 # failure is logged inside train_strategy_selector() itself and
165 # never blocks the primary candidate's own validate/backtest/
166 # commit/promote path. Realistically a no-op skip every cycle in
167 # this environment - see train_strategy_selector.py's own module
168 # docstring for why.
169 train_strategy_selector(self._conn, retraining_id, version_id, self.config)
171 validate_result = validate(self._conn, retraining_id, version_id, self.config)
172 if not validate_result["ok"]:
173 return {"ran": True, "reason": "validation_failed", "retraining_id": retraining_id, "version_id": version_id}
175 backtest_result = backtest(self._conn, retraining_id, version_id, self.config)
176 if not backtest_result["ok"]:
177 return {"ran": True, "reason": "backtest_failed", "retraining_id": retraining_id, "version_id": version_id}
179 commit_result = commit(self._conn, retraining_id, version_id, self.config)
180 if not commit_result["ok"]:
181 return {"ran": True, "reason": "vault_commit_failed", "retraining_id": retraining_id, "version_id": version_id}
183 worker_config = self.config.get("worker", {})
184 auto_promote = bool(worker_config.get("auto_promote", False))
185 auto_promote_blocked_in_live_mode = bool(worker_config.get("auto_promote_blocked_in_live_mode", True))
186 if auto_promote and auto_promote_blocked_in_live_mode and read_runtime_mode(self._config_path) == "live":
187 auto_promote = False
188 logger.warning(
189 "RetrainingWorker: auto_promote forced off because phase_v2.runtime.mode=='live' "
190 "(V2-22 safety net) - promote manually via `aq retrain promote --version-id <id>`."
191 )
192 if auto_promote:
193 promote_result = promote(self._conn, version_id, retraining_id, self.config)
194 status(self._conn)
195 return {
196 "ran": True,
197 "reason": "promoted" if promote_result["ok"] else "promotion_failed",
198 "retraining_id": retraining_id,
199 "version_id": version_id,
200 }
202 status(self._conn)
203 return {
204 "ran": True,
205 "reason": "validated_awaiting_manual_promotion",
206 "retraining_id": retraining_id,
207 "version_id": version_id,
208 }
210 def _live_degradation_signals(self) -> dict:
211 """V5.1 Phase 6 (production safety) - best-effort, never raises:
212 each individual signal degrades to False on any read failure,
213 matching this file's own "a best-effort stage's failure never
214 blocks the rest of the cycle" convention (train_topology()/
215 train_gating()/etc.). Two independent sources:
216 - kill_switch_tripped: state.json's kill_switch.tripped, written
217 every bar by main.py's own Phase 6 wiring.
218 - net_sharpe_decay / rank_ic_decay: whether a
219 sharpe_degradation_trigger / rank_ic_decay_trigger
220 (performance/triggers.py's own exact trigger_type strings -
221 NOT the more abstract net_sharpe_decay/rank_ic_decay names
222 phase_v2.retraining.auto_rollback.triggers uses, which is why
223 this method exists rather than reading trigger rows verbatim)
224 landed in performance_triggers within the lookback window."""
225 signals = {"kill_switch_tripped": False, "net_sharpe_decay": False, "rank_ic_decay": False}
227 try:
228 if _STATE_PATH.exists():
229 state = json.loads(_STATE_PATH.read_text(encoding="utf-8"))
230 signals["kill_switch_tripped"] = bool(state.get("kill_switch", {}).get("tripped", False))
231 except Exception as error:
232 logger.warning("RetrainingWorker: failed to read live kill-switch state - %s", error)
234 try:
235 lookback_hours = int(self.config.get("auto_rollback", {}).get("degradation_signal_lookback_hours", 24))
236 since = datetime.now(timezone.utc) - timedelta(hours=lookback_hours)
237 trigger_types = {row.get("trigger_type") for row in fetch_triggers_since(self._conn, since)}
238 signals["net_sharpe_decay"] = "sharpe_degradation_trigger" in trigger_types
239 signals["rank_ic_decay"] = "rank_ic_decay_trigger" in trigger_types
240 except Exception as error:
241 logger.warning("RetrainingWorker: failed to read recent performance triggers - %s", error)
243 return signals
245 def _notify_auto_rollback(self, decision: dict, rollback_result: dict) -> None:
246 """Manually constructs a performance_triggers row matching
247 performance/triggers.py::_make_trigger()'s exact field shape,
248 rather than calling that function - _make_trigger() dispatches on
249 a FIXED set of trigger_type strings via its own internal
250 _RECOMMENDED_ACTIONS/_is_retrain_candidate dicts that don't (and
251 shouldn't) know about auto-rollback. Reuses the SAME
252 insert_triggers() -> notifications/telegram_worker.py poll-and-
253 alert pathway every other trigger in this codebase already goes
254 through - this worker never calls Telegram directly."""
255 trigger_row = {
256 "trigger_id": str(uuid4()),
257 "created_at": datetime.now(timezone.utc),
258 "trigger_type": "auto_rollback_triggered",
259 "severity": "critical",
260 "mode": "live",
261 "scope": "model",
262 "metric_value": None,
263 "threshold": None,
264 "message": f"Auto-rollback: {decision.get('reason', '')}",
265 "recommended_action": (
266 f"Rolled back active model to {decision.get('to_version_id')}"
267 if rollback_result.get("ok")
268 else "Auto-rollback attempt FAILED - manual intervention required"
269 ),
270 "retrain_candidate": False,
271 }
272 try:
273 insert_triggers(self._conn, [trigger_row])
274 except Exception as error:
275 logger.error("RetrainingWorker: failed to insert auto-rollback notification trigger - %s", error)
277 def check_auto_rollback(self) -> dict:
278 """V5.1 Phase 6 (production safety) - fully independent of
279 run_once()'s plan->train->...->promote pipeline: this asks "is the
280 model CURRENTLY ACTIVE in production degrading enough to roll
281 back", not "should a new candidate be trained". Runs
282 orchestrator.auto_rollback_status() (the exact same read-only
283 diagnostic `aq retrain auto-rollback --status` uses) with live
284 degradation signals overlaid, and only calls the existing,
285 previously manual-stage-only orchestrator.rollback() when
286 phase_v2.retraining.auto_rollback.enabled is True AND the pure
287 selector (retraining/auto_rollback.py::select_rollback_target())
288 says so. Best-effort - never raises, matching this file's own
289 run()-loop exception handling."""
290 result = auto_rollback_status(self._conn, self.config, degradation_overrides=self._live_degradation_signals())
291 decision = result["decision"]
293 if decision["should_rollback"]:
294 logger.warning(
295 "RetrainingWorker: auto-rollback triggered - %s (degradation_score=%s)",
296 decision["reason"],
297 result.get("degradation_score"),
298 )
299 rollback_result = rollback(self._conn, decision["to_version_id"], self.config)
300 self._notify_auto_rollback(decision, rollback_result)
301 result = {**result, "rollback_result": rollback_result}
303 return result
305 def run(self) -> None:
306 logger.info("RetrainingWorker: entering run loop.")
307 while True:
308 try:
309 result = self.run_once()
310 logger.info("RetrainingWorker: cycle result - %s", result)
311 # V5.1 Phase 6 (production safety) - a SEPARATE check from
312 # run_once() above, on the same poll cadence: run_once()
313 # asks whether to train/promote a NEW candidate,
314 # check_auto_rollback() asks whether the model CURRENTLY
315 # ACTIVE in production should be rolled back. Both are
316 # best-effort and independent - one failing/no-op-ing never
317 # affects the other.
318 try:
319 rollback_check = self.check_auto_rollback()
320 if rollback_check["decision"]["should_rollback"]:
321 logger.warning("RetrainingWorker: auto-rollback cycle result - %s", rollback_check)
322 except Exception as exc:
323 logger.error("RetrainingWorker: check_auto_rollback() failed - %s", exc)
324 time.sleep(self.poll_interval)
325 except KeyboardInterrupt:
326 logger.info("RetrainingWorker: shutdown requested.")
327 break
328 except Exception as exc:
329 logger.error("RetrainingWorker error — %s. Retrying in %ds.", exc, self.poll_interval)
330 time.sleep(self.poll_interval)
332 def close(self) -> None:
333 try:
334 self._conn.close()
335 except Exception:
336 pass
339def main() -> None:
340 logging.basicConfig(
341 level=logging.INFO,
342 format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
343 )
344 parser = argparse.ArgumentParser(description="Aether Quant retraining worker")
345 parser.add_argument("--once", action="store_true", help="Run one cycle and exit")
346 parser.add_argument("--poll-interval", type=int, default=None, help="Overrides phase_v2.retraining.worker.poll_interval_seconds")
347 args = parser.parse_args()
349 postgres_dsn = secret_env("POSTGRES_DSN", "")
350 config = _load_retraining_config()
351 poll_interval = args.poll_interval
352 if poll_interval is None:
353 poll_interval = int(config.get("worker", {}).get("poll_interval_seconds", 300))
355 worker = RetrainingWorker(postgres_dsn=postgres_dsn, config=config, poll_interval=poll_interval)
356 try:
357 if args.once:
358 result = worker.run_once()
359 logger.info("--once: %s", result)
360 else:
361 worker.run()
362 finally:
363 worker.close()
366if __name__ == "__main__":
367 main()