Coverage for retraining/orchestrator.py: 100%

434 statements  

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

1"""Retraining pipeline orchestrator (Phase V2-17). 

2 

3Exposes each pipeline stage (plan, train, validate, backtest, commit, 

4promote, rollback, status) as both a plain Python function (called by 

5retraining/worker.py's continuous loop) and a CLI subcommand (for manual, 

6staged, one-stage-at-a-time invocation - `python -m retraining.orchestrator 

7<stage> ...`). This dual use is what lets retraining run either as a 

8toggleable continuous worker or purely on-demand. 

9 

10Reads config.json's phase_v2.retraining block directly, mirroring 

11performance/trigger_worker.py's _load_performance_triggers_config() 

12convention - these are strategy thresholds, not infra config. 

13""" 

14 

15from __future__ import annotations 

16 

17import argparse 

18import json 

19import logging 

20import subprocess 

21import sys 

22import uuid 

23from datetime import datetime, timedelta, timezone 

24from pathlib import Path 

25 

26from execution.secrets_io import secret_env 

27from performance.postgres_triggers import ensure_schema as ensure_performance_schema 

28from performance.postgres_triggers import fetch_candidate_triggers 

29from retraining import planning 

30from retraining.artifacts import ( 

31 ACTIVE_ARTIFACT_FILES, 

32 ALL_TRACKED_FILES, 

33 REQUIRED_CANDIDATE_FILES, 

34 candidate_dir, 

35 check_required_artifacts, 

36 compute_artifact_hashes, 

37 copy_backtest_report_to_active, 

38 copy_candidate_to_active, 

39 restore_active_from_version, 

40 verify_version_artifacts, 

41) 

42from retraining.auto_rollback import select_rollback_target 

43from retraining.backtest_gate import compare_backtests 

44from retraining.lean_backtest import run_lean_backtest 

45from retraining.postgres_registry import ( 

46 count_experience_events, 

47 ensure_schema, 

48 fetch_active_model_version, 

49 fetch_model_version, 

50 fetch_recent_retraining_events, 

51 fetch_rollback_candidates, 

52 fetch_stale_active_events, 

53 insert_model_version, 

54 insert_retraining_event, 

55 promote_model_version, 

56 update_model_version_status, 

57 update_retraining_event_status, 

58) 

59from retraining.rollback_hardening import compute_degradation_score 

60from retraining.status_export import build_status_view, write_status_file 

61from retraining.validation_gate import evaluate_validation_gate 

62from retraining.vault_client import commit_candidate_to_vault, restore_candidate_from_vault, vault_preflight 

63from risk.manual_override import write_manual_trade_lock_override 

64 

65logger = logging.getLogger(__name__) 

66 

67ROOT_DIR = Path(__file__).resolve().parent.parent 

68ML_DIR = ROOT_DIR / "ml" 

69BACKTESTS_DIR = ROOT_DIR / "backtests" 

70ACTIVE_TRAINING_METRICS_PATH = ML_DIR / "training_metrics.json" 

71ACTIVE_STRATEGY_REPORT_PATH = BACKTESTS_DIR / "strategy_report.json" 

72_CONFIG_PATH = ROOT_DIR / "config.json" 

73 

74_PLAN_LOOKBACK_DAYS = 30 

75 

76 

77def _load_retraining_config(config_path: Path = _CONFIG_PATH) -> dict: 

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

79 config = json.load(f) 

80 return config.get("phase_v2", {}).get("retraining", {}) 

81 

82 

83def _load_json_if_exists(path: Path) -> dict: 

84 if not path.exists(): 

85 return {} 

86 return json.loads(path.read_text(encoding="utf-8")) 

87 

88 

89def connect(postgres_dsn: str = ""): 

90 import psycopg 

91 

92 dsn = secret_env("POSTGRES_DSN", postgres_dsn) 

93 conn = psycopg.connect(dsn, autocommit=False) 

94 ensure_schema(conn) 

95 ensure_performance_schema(conn) # performance_triggers table must exist before we read it 

96 return conn 

97 

98 

99# --------------------------------------------------------------------------- 

100# Startup maintenance 

101# --------------------------------------------------------------------------- 

102 

103 

104def reconcile_stale_running_events(conn, config: dict) -> list[str]: 

105 """Marks any retraining_events row stuck in 'planned'/'running' status as 

106 failed, and rejects its candidate model_versions row if still 

107 'candidate'. Called once at RetrainingWorker startup, before the poll 

108 loop begins. 

109 

110 Why this exists: a worker crash, redeploy, or container recreate mid-cycle 

111 orphans that row forever - nothing else ever updates it again (`train()` 

112 itself only writes on completion or failure of its subprocess), so a 

113 single interrupted cycle silently blocks every future retraining attempt 

114 for the full `cooldown_minutes` window (`cooldown_remaining_seconds()` 

115 treats 'planned'/'running' as an active retraining in progress). Found and 

116 manually worked around during a real rehearsal - see 

117 development/Problems.md #48. 

118 

119 Staleness threshold defaults to 10800s (3h) - deliberately larger than the 

120 *sum* of every stage's own timeout in one full cycle (train 3600s + 

121 train_topology 900s + train_gating 300s + train_multitask 900s + 

122 train_sequence 1800s + train_strategy_selector 300s + backtest_gate 1800s + 

123 vault commit 120s ~= 9720s), not just the single largest one - a 

124 genuinely still-running cycle (owned 

125 by this worker or a concurrent manual `orchestrator train` CLI call) must 

126 never be falsely reconciled. Configurable via 

127 phase_v2.retraining.worker.stale_running_timeout_seconds. 

128 """ 

129 worker_config = config.get("worker", {}) 

130 staleness_seconds = float(worker_config.get("stale_running_timeout_seconds", 10800)) 

131 stale_events = fetch_stale_active_events(conn, staleness_seconds) 

132 

133 reconciled_ids: list[str] = [] 

134 for event in stale_events: 

135 retraining_id = str(event["retraining_id"]) 

136 update_retraining_event_status( 

137 conn, 

138 retraining_id, 

139 status="failed", 

140 notes=(event.get("notes") or []) 

141 + [ 

142 { 

143 "stage": "reconcile", 

144 "reason": "orphaned_on_startup", 

145 "detail": ( 

146 f"status was still '{event['status']}' after " 

147 f"{staleness_seconds:.0f}s with no update - the owning " 

148 "process likely crashed or was recreated mid-cycle." 

149 ), 

150 } 

151 ], 

152 ) 

153 

154 candidate_version_id = event.get("candidate_version_id") 

155 if candidate_version_id: 

156 candidate = fetch_model_version(conn, str(candidate_version_id)) 

157 if candidate and candidate.get("status") == "candidate": 

158 update_model_version_status(conn, str(candidate_version_id), status="rejected") 

159 

160 logger.warning( 

161 "reconcile_stale_running_events: %s was orphaned at status=%s - marked failed.", 

162 retraining_id, 

163 event["status"], 

164 ) 

165 reconciled_ids.append(retraining_id) 

166 

167 return reconciled_ids 

168 

169 

170# --------------------------------------------------------------------------- 

171# Pipeline stages 

172# --------------------------------------------------------------------------- 

173 

174 

175def plan(conn, config: dict, now: datetime | None = None) -> dict: 

176 now = now or datetime.now(timezone.utc) 

177 triggers = fetch_candidate_triggers(conn, limit=50) 

178 recent_events = fetch_recent_retraining_events( 

179 conn, since=now - timedelta(days=_PLAN_LOOKBACK_DAYS), limit=200 

180 ) 

181 observation_count = count_experience_events(conn) 

182 

183 result = planning.evaluate_retraining_plan(triggers, recent_events, observation_count, config, now) 

184 

185 if result["should_plan"]: 

186 retraining_id = str(uuid.uuid4()) 

187 selected = result["selected_trigger"] 

188 insert_retraining_event( 

189 conn, 

190 { 

191 "retraining_id": retraining_id, 

192 "source_trigger_id": selected["trigger_id"] if selected else None, 

193 "candidate_version_id": None, 

194 "status": "planned", 

195 "reason": result["reason"], 

196 "metrics": {}, 

197 "notes": [], 

198 }, 

199 ) 

200 result["retraining_id"] = retraining_id 

201 logger.info("plan: retraining %s planned - %s", retraining_id, result["reason"]) 

202 else: 

203 logger.info("plan: not planning - %s", result["reason"]) 

204 

205 return result 

206 

207 

208def train(conn, retraining_id: str, version_id: str | None = None, timeout_seconds: int = 3600) -> dict: 

209 """Runs `python train.py --candidate --version-id <id>` as a subprocess. 

210 

211 Training is CPU/GPU-heavy and must not block the worker's own event loop 

212 or share its Postgres connection lifetime - hence a subprocess, not an 

213 in-process import of train.py. 

214 """ 

215 version_id = version_id or str(uuid.uuid4()) 

216 update_retraining_event_status(conn, retraining_id, status="running", candidate_version_id=version_id) 

217 insert_model_version(conn, {"model_version_id": version_id, "status": "candidate"}) 

218 

219 train_script = ROOT_DIR / "train.py" 

220 try: 

221 result = subprocess.run( 

222 [sys.executable, str(train_script), "--candidate", "--version-id", version_id], 

223 cwd=str(ROOT_DIR), 

224 capture_output=True, 

225 text=True, 

226 timeout=timeout_seconds, check=False, 

227 ) 

228 except Exception as exc: # never let a training subprocess crash the orchestrator 

229 logger.error("train: subprocess failed to launch - %s", exc) 

230 update_retraining_event_status(conn, retraining_id, status="failed", notes=[{"stage": "train", "error": str(exc)}]) 

231 update_model_version_status(conn, version_id, status="rejected") 

232 return {"ok": False, "version_id": version_id, "error": str(exc)} 

233 

234 if result.returncode != 0: 

235 logger.error("train: candidate %s training failed - %s", version_id, result.stderr[-2000:]) 

236 update_retraining_event_status( 

237 conn, 

238 retraining_id, 

239 status="failed", 

240 notes=[{"stage": "train", "returncode": result.returncode, "stderr": result.stderr[-2000:]}], 

241 ) 

242 update_model_version_status(conn, version_id, status="rejected") 

243 return {"ok": False, "version_id": version_id, "error": result.stderr} 

244 

245 logger.info("train: candidate %s trained.", version_id) 

246 return {"ok": True, "version_id": version_id, "stdout": result.stdout} 

247 

248 

249def train_topology(conn, retraining_id: str, version_id: str, config: dict, timeout_seconds: int | None = None) -> dict: 

250 """Runs `python train_topology.py --version-id <id>` as a second, 

251 independently-failable subprocess (V2-17.5), between `train` and 

252 `validate`. Learned-topology training is best-effort: unlike `train`, 

253 a failure here is logged and swallowed - it never rejects the 

254 candidate model_version or overwrites a later stage's retraining_events 

255 status transition, it only appends a note. topology_model.json etc. are 

256 optional artifacts (see retraining/artifacts.py's OPTIONAL_TOPOLOGY_FILES) 

257 precisely so this stage can fail without blocking the primary model. 

258 """ 

259 topology_config = config.get("topology_training", {}) 

260 if not topology_config.get("enabled", True): 

261 return {"ok": False, "version_id": version_id, "reason": "topology_training_disabled"} 

262 

263 timeout_seconds = timeout_seconds or int(topology_config.get("timeout_seconds", 900)) 

264 train_topology_script = ROOT_DIR / "train_topology.py" 

265 try: 

266 result = subprocess.run( 

267 [sys.executable, str(train_topology_script), "--version-id", version_id], 

268 cwd=str(ROOT_DIR), 

269 capture_output=True, 

270 text=True, 

271 timeout=timeout_seconds, check=False, 

272 ) 

273 except Exception as exc: # never let a best-effort subprocess crash the orchestrator 

274 logger.warning("train_topology: subprocess failed to launch for %s - %s", version_id, exc) 

275 update_retraining_event_status( 

276 conn, retraining_id, status="running", notes=[{"stage": "train_topology", "error": str(exc)}] 

277 ) 

278 return {"ok": False, "version_id": version_id, "error": str(exc)} 

279 

280 if result.returncode != 0: 

281 logger.warning( 

282 "train_topology: candidate %s topology training failed (rc=%d) - continuing without it.", 

283 version_id, 

284 result.returncode, 

285 ) 

286 update_retraining_event_status( 

287 conn, 

288 retraining_id, 

289 status="running", 

290 notes=[{"stage": "train_topology", "returncode": result.returncode, "stderr": result.stderr[-2000:]}], 

291 ) 

292 return {"ok": False, "version_id": version_id, "error": result.stderr} 

293 

294 logger.info("train_topology: candidate %s topology model trained (or skipped for insufficient data).", version_id) 

295 return {"ok": True, "version_id": version_id, "stdout": result.stdout} 

296 

297 

298def train_gating(conn, retraining_id: str, version_id: str, config: dict, timeout_seconds: int | None = None) -> dict: 

299 """Runs `python train_gating.py --version-id <id>` as a third, 

300 independently-failable subprocess, right after train_topology(). Same 

301 best-effort contract: a failure here is logged and swallowed - it 

302 never rejects the primary candidate model_version. gating_model.json 

303 etc. are optional artifacts (see retraining/artifacts.py's 

304 OPTIONAL_GATING_FILES) precisely so this stage can fail without 

305 blocking the primary model. 

306 """ 

307 gating_config = config.get("gating_training", {}) 

308 if not gating_config.get("enabled", True): 

309 return {"ok": False, "version_id": version_id, "reason": "gating_training_disabled"} 

310 

311 timeout_seconds = timeout_seconds or int(gating_config.get("timeout_seconds", 300)) 

312 train_gating_script = ROOT_DIR / "train_gating.py" 

313 try: 

314 result = subprocess.run( 

315 [sys.executable, str(train_gating_script), "--version-id", version_id], 

316 cwd=str(ROOT_DIR), 

317 capture_output=True, 

318 text=True, 

319 timeout=timeout_seconds, check=False, 

320 ) 

321 except Exception as exc: # never let a best-effort subprocess crash the orchestrator 

322 logger.warning("train_gating: subprocess failed to launch for %s - %s", version_id, exc) 

323 update_retraining_event_status( 

324 conn, retraining_id, status="running", notes=[{"stage": "train_gating", "error": str(exc)}] 

325 ) 

326 return {"ok": False, "version_id": version_id, "error": str(exc)} 

327 

328 if result.returncode != 0: 

329 logger.warning( 

330 "train_gating: candidate %s gating training failed (rc=%d) - continuing without it.", 

331 version_id, 

332 result.returncode, 

333 ) 

334 update_retraining_event_status( 

335 conn, 

336 retraining_id, 

337 status="running", 

338 notes=[{"stage": "train_gating", "returncode": result.returncode, "stderr": result.stderr[-2000:]}], 

339 ) 

340 return {"ok": False, "version_id": version_id, "error": result.stderr} 

341 

342 logger.info("train_gating: candidate %s gating model trained (or skipped for insufficient data).", version_id) 

343 return {"ok": True, "version_id": version_id, "stdout": result.stdout} 

344 

345 

346def train_multitask(conn, retraining_id: str, version_id: str, config: dict, timeout_seconds: int | None = None) -> dict: 

347 """Runs `python train_multitask.py --version-id <id>` as a fourth, 

348 independently-failable subprocess, right after train_gating(). Same 

349 best-effort contract as train_topology()/train_gating(): a failure here 

350 is logged and swallowed - it never rejects the primary candidate model_ 

351 version. multitask_model.json etc. are optional artifacts (see 

352 retraining/artifacts.py's OPTIONAL_MULTITASK_FILES) precisely so this 

353 stage can fail without blocking the primary model. 

354 """ 

355 multitask_config = config.get("multitask_training", {}) 

356 if not multitask_config.get("enabled", True): 

357 return {"ok": False, "version_id": version_id, "reason": "multitask_training_disabled"} 

358 

359 timeout_seconds = timeout_seconds or int(multitask_config.get("timeout_seconds", 900)) 

360 train_multitask_script = ROOT_DIR / "train_multitask.py" 

361 try: 

362 result = subprocess.run( 

363 [sys.executable, str(train_multitask_script), "--version-id", version_id], 

364 cwd=str(ROOT_DIR), 

365 capture_output=True, 

366 text=True, 

367 timeout=timeout_seconds, check=False, 

368 ) 

369 except Exception as exc: # never let a best-effort subprocess crash the orchestrator 

370 logger.warning("train_multitask: subprocess failed to launch for %s - %s", version_id, exc) 

371 update_retraining_event_status( 

372 conn, retraining_id, status="running", notes=[{"stage": "train_multitask", "error": str(exc)}] 

373 ) 

374 return {"ok": False, "version_id": version_id, "error": str(exc)} 

375 

376 if result.returncode != 0: 

377 logger.warning( 

378 "train_multitask: candidate %s multitask training failed (rc=%d) - continuing without it.", 

379 version_id, 

380 result.returncode, 

381 ) 

382 update_retraining_event_status( 

383 conn, 

384 retraining_id, 

385 status="running", 

386 notes=[{"stage": "train_multitask", "returncode": result.returncode, "stderr": result.stderr[-2000:]}], 

387 ) 

388 return {"ok": False, "version_id": version_id, "error": result.stderr} 

389 

390 logger.info("train_multitask: candidate %s multitask model trained (or skipped for insufficient data).", version_id) 

391 return {"ok": True, "version_id": version_id, "stdout": result.stdout} 

392 

393 

394def train_sequence(conn, retraining_id: str, version_id: str, config: dict, timeout_seconds: int | None = None) -> dict: 

395 """Runs `python train_sequence.py --version-id <id>` as a fifth, 

396 independently-failable subprocess (Phase 2), right after 

397 train_multitask(). Same best-effort contract as the other optional 

398 stages: a failure here is logged and swallowed - it never rejects the 

399 primary candidate model_version. sequence_model.json etc. are optional 

400 artifacts (see retraining/artifacts.py's OPTIONAL_SEQUENCE_FILES) 

401 precisely so this stage can fail without blocking the primary model. 

402 """ 

403 sequence_config = config.get("sequence_training", {}) 

404 if not sequence_config.get("enabled", True): 

405 return {"ok": False, "version_id": version_id, "reason": "sequence_training_disabled"} 

406 

407 timeout_seconds = timeout_seconds or int(sequence_config.get("timeout_seconds", 1800)) 

408 train_sequence_script = ROOT_DIR / "train_sequence.py" 

409 try: 

410 result = subprocess.run( 

411 [sys.executable, str(train_sequence_script), "--version-id", version_id], 

412 cwd=str(ROOT_DIR), 

413 capture_output=True, 

414 text=True, 

415 timeout=timeout_seconds, check=False, 

416 ) 

417 except Exception as exc: # never let a best-effort subprocess crash the orchestrator 

418 logger.warning("train_sequence: subprocess failed to launch for %s - %s", version_id, exc) 

419 update_retraining_event_status( 

420 conn, retraining_id, status="running", notes=[{"stage": "train_sequence", "error": str(exc)}] 

421 ) 

422 return {"ok": False, "version_id": version_id, "error": str(exc)} 

423 

424 if result.returncode != 0: 

425 logger.warning( 

426 "train_sequence: candidate %s sequence training failed (rc=%d) - continuing without it.", 

427 version_id, 

428 result.returncode, 

429 ) 

430 update_retraining_event_status( 

431 conn, 

432 retraining_id, 

433 status="running", 

434 notes=[{"stage": "train_sequence", "returncode": result.returncode, "stderr": result.stderr[-2000:]}], 

435 ) 

436 return {"ok": False, "version_id": version_id, "error": result.stderr} 

437 

438 logger.info("train_sequence: candidate %s sequence model trained (or skipped for insufficient data).", version_id) 

439 return {"ok": True, "version_id": version_id, "stdout": result.stdout} 

440 

441 

442def train_strategy_selector( 

443 conn, retraining_id: str, version_id: str, config: dict, timeout_seconds: int | None = None 

444) -> dict: 

445 """Runs `python train_strategy_selector.py --version-id <id>` as a 

446 sixth, independently-failable subprocess (V4.7, development/Problems.md 

447 #29's own framing), right after train_sequence(). Same best-effort 

448 contract as the other optional stages: a failure here is logged and 

449 swallowed - it never rejects the primary candidate model_version. 

450 strategy_selector_model.json etc. are optional artifacts (see 

451 retraining/artifacts.py's OPTIONAL_STRATEGY_SELECTOR_FILES) precisely 

452 so this stage can fail without blocking the primary model. 

453 

454 In practice this stage's own trainer script documents that it has no 

455 data source to train from at all in this environment yet (unlike the 

456 other optional stages above, which are dormant only until enough 

457 Postgres experience_events VOLUME accumulates) - it will realistically 

458 exit 0/skip every single retraining run until real option positions 

459 actually trade. The stage still runs unconditionally (when enabled) 

460 for the same reason every other optional stage does: cheap, harmless, 

461 and ready the moment real data exists. 

462 """ 

463 strategy_selector_config = config.get("strategy_selector_training", {}) 

464 if not strategy_selector_config.get("enabled", True): 

465 return {"ok": False, "version_id": version_id, "reason": "strategy_selector_training_disabled"} 

466 

467 timeout_seconds = timeout_seconds or int(strategy_selector_config.get("timeout_seconds", 300)) 

468 train_strategy_selector_script = ROOT_DIR / "train_strategy_selector.py" 

469 try: 

470 result = subprocess.run( 

471 [sys.executable, str(train_strategy_selector_script), "--version-id", version_id], 

472 cwd=str(ROOT_DIR), 

473 capture_output=True, 

474 text=True, 

475 timeout=timeout_seconds, check=False, 

476 ) 

477 except Exception as exc: # never let a best-effort subprocess crash the orchestrator 

478 logger.warning("train_strategy_selector: subprocess failed to launch for %s - %s", version_id, exc) 

479 update_retraining_event_status( 

480 conn, retraining_id, status="running", notes=[{"stage": "train_strategy_selector", "error": str(exc)}] 

481 ) 

482 return {"ok": False, "version_id": version_id, "error": str(exc)} 

483 

484 if result.returncode != 0: 

485 logger.warning( 

486 "train_strategy_selector: candidate %s strategy-selector training failed (rc=%d) - continuing without it.", 

487 version_id, 

488 result.returncode, 

489 ) 

490 update_retraining_event_status( 

491 conn, 

492 retraining_id, 

493 status="running", 

494 notes=[ 

495 {"stage": "train_strategy_selector", "returncode": result.returncode, "stderr": result.stderr[-2000:]} 

496 ], 

497 ) 

498 return {"ok": False, "version_id": version_id, "error": result.stderr} 

499 

500 logger.info( 

501 "train_strategy_selector: candidate %s strategy-selector model trained (or skipped for insufficient data).", 

502 version_id, 

503 ) 

504 return {"ok": True, "version_id": version_id, "stdout": result.stdout} 

505 

506 

507def validate(conn, retraining_id: str, version_id: str, config: dict) -> dict: 

508 version_dir = candidate_dir(version_id) 

509 present, missing = check_required_artifacts(version_dir) 

510 if not present: 

511 reason = f"missing_candidate_artifacts: {missing}" 

512 update_model_version_status(conn, version_id, status="rejected") 

513 update_retraining_event_status(conn, retraining_id, status="rejected", reason=reason) 

514 return {"ok": False, "reason": reason} 

515 

516 candidate_metrics = _load_json_if_exists(version_dir / "training_metrics.json") 

517 candidate_report = _load_json_if_exists(version_dir / "strategy_report.json") 

518 active_metrics = _load_json_if_exists(ACTIVE_TRAINING_METRICS_PATH) 

519 active_report = _load_json_if_exists(ACTIVE_STRATEGY_REPORT_PATH) 

520 # V5.1 Phase 4 (item 7) - see evaluate_validation_gate()'s own docstring. 

521 candidate_ranking_metrics = { 

522 "sequence": _load_json_if_exists(version_dir / "sequence_training_metrics.json") or None, 

523 "multitask": _load_json_if_exists(version_dir / "multitask_training_metrics.json") or None, 

524 } 

525 

526 gate_result = evaluate_validation_gate( 

527 candidate_metrics, candidate_report, active_metrics, active_report, config.get("validation_gate", {}), 

528 candidate_ranking_metrics=candidate_ranking_metrics, 

529 ) 

530 

531 if not gate_result["passed"]: 

532 update_model_version_status(conn, version_id, status="rejected", metrics={"validation_gate": gate_result}) 

533 update_retraining_event_status( 

534 conn, 

535 retraining_id, 

536 status="rejected", 

537 metrics={"validation_gate": gate_result}, 

538 reason=f"validation_gate_failed: {gate_result['failures']}", 

539 ) 

540 logger.info("validate: candidate %s rejected - %s", version_id, gate_result["failures"]) 

541 return {"ok": False, "gate": gate_result} 

542 

543 update_model_version_status(conn, version_id, status="candidate", metrics={"validation_gate": gate_result}) 

544 logger.info("validate: candidate %s passed validation gate.", version_id) 

545 return {"ok": True, "gate": gate_result} 

546 

547 

548def backtest(conn, retraining_id: str, version_id: str, config: dict) -> dict: 

549 version_dir = candidate_dir(version_id) 

550 candidate_report = _load_json_if_exists(version_dir / "strategy_report.json") 

551 active_report = _load_json_if_exists(ACTIVE_STRATEGY_REPORT_PATH) 

552 

553 comparison = compare_backtests(active_report, candidate_report, config.get("backtest_gate", {})) 

554 lean_result = run_lean_backtest(version_dir, config.get("backtest_gate", {})) 

555 report = {"comparison": comparison, "lean": lean_result} 

556 

557 report_path = BACKTESTS_DIR / f"candidate_{version_id}_report.json" 

558 report_path.parent.mkdir(parents=True, exist_ok=True) 

559 report_path.write_text(json.dumps(report, indent=2), encoding="utf-8") 

560 

561 passed = comparison["passed"] 

562 status = "candidate" if passed else "rejected" 

563 update_model_version_status(conn, version_id, status=status, metrics={"backtest_gate": report}) 

564 update_retraining_event_status( 

565 conn, 

566 retraining_id, 

567 status=("running" if passed else "rejected"), 

568 metrics={"backtest_gate": report}, 

569 reason=("backtest_gate_passed" if passed else f"backtest_gate_failed: {comparison['reasons']}"), 

570 ) 

571 logger.info("backtest: candidate %s %s.", version_id, "passed" if passed else "rejected") 

572 return {"ok": passed, "report": report} 

573 

574 

575def _vault_repo_root(vault_config: dict) -> Path: 

576 return (ROOT_DIR / str(vault_config.get("repo_path", "."))).resolve() 

577 

578 

579def _path_in_vault(path: Path, vault_root: Path) -> str | None: 

580 """`path` relative to the vault's repo, or None when `vault.repo_path` doesn't contain it.""" 

581 try: 

582 return path.resolve().relative_to(vault_root).as_posix() 

583 except ValueError: 

584 return None 

585 

586 

587def preflight_vault(conn, retraining_id: str, config: dict) -> dict: 

588 """Fails the event before any training when a candidate could not be committed anyway.""" 

589 vault_config = config.get("vault", {}) 

590 result = vault_preflight(vault_config, cwd=_vault_repo_root(vault_config)) 

591 if not result["ok"]: 

592 update_retraining_event_status( 

593 conn, retraining_id, status="failed", notes=[{"stage": "vault_preflight", "reason": result["reason"]}] 

594 ) 

595 logger.warning("preflight_vault: %s - retraining %s not started.", result["reason"], retraining_id) 

596 return result 

597 

598 

599def commit(conn, retraining_id: str, version_id: str, config: dict) -> dict: 

600 version_dir = candidate_dir(version_id) 

601 vault_config = config.get("vault", {}) 

602 add_paths = list(vault_config.get("add_paths", ["train.py", "main.py", "config.json"])) 

603 vault_root = _vault_repo_root(vault_config) 

604 candidate_path = _path_in_vault(version_dir, vault_root) 

605 if candidate_path is None and vault_config.get("enabled", True): 

606 result = {"ok": False, "stage": "path_outside_vault", "vault_commit": None, "push_state": None, "steps": { 

607 "path_outside_vault": {"ok": False, "error": f"{version_dir} is outside vault.repo_path {vault_root}"}, 

608 }} 

609 update_retraining_event_status( 

610 conn, retraining_id, status="failed", notes=[{"stage": "commit", "steps": result["steps"]}] 

611 ) 

612 return result 

613 if candidate_path is not None: 

614 add_paths.append(candidate_path) 

615 

616 candidate_report = _load_json_if_exists(version_dir / "strategy_report.json") 

617 strategy = candidate_report.get("backtest", {}).get("strategy", {}) 

618 metrics = { 

619 "sharpe": float(strategy.get("sharpe", 0.0) or 0.0), 

620 "drawdown": float(strategy.get("max_drawdown", 0.0) or 0.0), 

621 } 

622 

623 if vault_config.get("enabled", True): 

624 # `av add` rejects the whole call on one missing path; provenance extras must not cost a candidate its commit. 

625 extras = [path for path in vault_config.get("extra_add_paths", []) if (vault_root / path).exists()] 

626 result = commit_candidate_to_vault( 

627 version_id, add_paths, metrics, {**vault_config, "extra_add_paths": extras}, cwd=vault_root 

628 ) 

629 else: 

630 # promotion.require_vault_commit alone decides whether such a candidate can go live. 

631 result = {"ok": True, "stage": "disabled", "vault_commit": None, "push_state": None, "steps": {}} 

632 

633 if not result["ok"]: 

634 update_retraining_event_status( 

635 conn, retraining_id, status="failed", notes=[{"stage": "commit", "steps": result["steps"]}] 

636 ) 

637 logger.warning("commit: candidate %s vault commit failed at stage %s.", version_id, result["stage"]) 

638 return result 

639 

640 hashes = compute_artifact_hashes(version_dir, filenames=ALL_TRACKED_FILES) 

641 update_model_version_status( 

642 conn, 

643 version_id, 

644 status="candidate", 

645 aether_vault_commit=result["vault_commit"], 

646 artifact_hashes=hashes, 

647 ) 

648 update_retraining_event_status( 

649 conn, 

650 retraining_id, 

651 status="validated", 

652 candidate_version_id=version_id, 

653 metrics={"vault_commit": result["vault_commit"]}, 

654 reason="vault_commit_succeeded", 

655 ) 

656 logger.info("commit: candidate %s committed to vault (%s).", version_id, result["vault_commit"]) 

657 return result 

658 

659 

660def _generations_enabled() -> bool: 

661 """`ml/generations/policy.json`'s `enabled`. Absent or damaged reads as off, which is today's single-slot behaviour.""" 

662 from json_safety import load_json_lenient 

663 

664 payload = load_json_lenient(ML_DIR / "generations" / "policy.json") 

665 return bool(isinstance(payload, dict) and payload.get("enabled") is True) 

666 

667 

668def promote(conn, version_id: str, retraining_id: str | None = None, config: dict | None = None) -> dict: 

669 config = config or {} 

670 version = fetch_model_version(conn, version_id) 

671 if version is None: 

672 return {"ok": False, "error": "model_version_not_found"} 

673 if version.get("status") != "candidate": 

674 return {"ok": False, "error": "promotion_requires_validated_candidate_status"} 

675 if config.get("promotion", {}).get("require_vault_commit", True) and not version.get("aether_vault_commit"): 

676 return {"ok": False, "error": "promotion_requires_vault_commit"} 

677 if _generations_enabled(): 

678 # With generations on, a model reaches the book through a share of it, by rule, never by replacing the one active model in one step. 

679 logger.info("promote: %s stays a candidate: generations are enabled, so it goes through `aq cycle research` and `aq cycle promote`.", version_id) 

680 return {"ok": False, "error": "generations_enabled_use_aq_cycle", "version_id": version_id} 

681 

682 active_files = tuple(config.get("promotion", {}).get("active_artifact_files", ACTIVE_ARTIFACT_FILES)) 

683 version_dir = candidate_dir(version_id) 

684 active = fetch_active_model_version(conn) 

685 

686 # V5.4.7 (Problems.md #124): promote previously copied files without 

687 # ever checking them against the hashes recorded at commit time - 

688 # post-commit corruption/tampering promoted blindly. Verify BEFORE any 

689 # file moves or status flips. 

690 stored_hashes = version.get("artifact_hashes") or {} 

691 preflight = verify_version_artifacts( 

692 version_dir, filenames=active_files, expected_hashes=stored_hashes 

693 ) 

694 required_present = [name for name in REQUIRED_CANDIDATE_FILES if name in active_files] 

695 missing_required = [name for name in required_present if name in preflight["missing"]] 

696 if missing_required or preflight["mismatched"]: 

697 logger.error( 

698 "promote: artifact verification failed for %s - missing=%s mismatched=%s", 

699 version_id, missing_required, preflight["mismatched"], 

700 ) 

701 return { 

702 "ok": False, 

703 "error": "candidate_artifact_verification_failed", 

704 "missing": missing_required, 

705 "mismatched": preflight["mismatched"], 

706 } 

707 

708 hashes = copy_candidate_to_active(version_dir, ml_dir=ML_DIR, filenames=active_files) 

709 copy_backtest_report_to_active(version_dir, BACKTESTS_DIR) 

710 

711 promote_model_version(conn, old_active_id=active["model_version_id"] if active else None, new_active_id=version_id) 

712 update_model_version_status(conn, version_id, status="active", artifact_hashes=hashes) 

713 if retraining_id: 

714 update_retraining_event_status(conn, retraining_id, status="promoted") 

715 

716 write_status_file(build_status_view(conn)) 

717 logger.info("promote: %s is now the active model.", version_id) 

718 

719 if config.get("promotion", {}).get("auto_clear_trade_lock", True): 

720 write_manual_trade_lock_override(False, _CONFIG_PATH) 

721 logger.info("promote: cleared trade-lock override so trading resumes on the new model.") 

722 

723 return {"ok": True, "version_id": version_id} 

724 

725 

726def rollback(conn, to_version_id: str, config: dict | None = None) -> dict: 

727 config = config or {} 

728 target = fetch_model_version(conn, to_version_id) 

729 if target is None or target.get("status") not in ("archived", "rolled_back", "active"): 

730 return {"ok": False, "error": "rollback_target_not_eligible"} 

731 

732 active_files = tuple(config.get("promotion", {}).get("active_artifact_files", ACTIVE_ARTIFACT_FILES)) 

733 version_dir = candidate_dir(to_version_id) 

734 expected_hashes = target.get("artifact_hashes") or None 

735 

736 restore_result = restore_active_from_version( 

737 version_dir, ml_dir=ML_DIR, filenames=active_files, expected_hashes=expected_hashes 

738 ) 

739 

740 if not restore_result["ok"] and target.get("aether_vault_commit"): 

741 vault_config = config.get("vault", {}) 

742 vault_root = _vault_repo_root(vault_config) 

743 candidate_path = _path_in_vault(version_dir, vault_root) 

744 vault_restore = restore_candidate_from_vault( 

745 target["aether_vault_commit"], candidate_path, vault_config, cwd=vault_root, 

746 ) if candidate_path is not None else {"ok": False} 

747 if vault_restore["ok"]: 

748 restore_result = restore_active_from_version( 

749 version_dir, ml_dir=ML_DIR, filenames=active_files, expected_hashes=expected_hashes 

750 ) 

751 

752 if not restore_result["ok"]: 

753 logger.error("rollback: artifact restore failed for %s - %s", to_version_id, restore_result) 

754 return {"ok": False, "error": "artifact_hash_mismatch", "details": restore_result} 

755 

756 current_active = fetch_active_model_version(conn) 

757 promote_model_version( 

758 conn, 

759 old_active_id=current_active["model_version_id"] if current_active else None, 

760 new_active_id=to_version_id, 

761 ) 

762 update_model_version_status(conn, to_version_id, status="active") 

763 if current_active: 

764 update_model_version_status(conn, current_active["model_version_id"], status="rolled_back") 

765 

766 retraining_id = str(uuid.uuid4()) 

767 insert_retraining_event( 

768 conn, 

769 { 

770 "retraining_id": retraining_id, 

771 "source_trigger_id": None, 

772 "candidate_version_id": to_version_id, 

773 "status": "promoted", 

774 "reason": f"rollback to {to_version_id}", 

775 "metrics": {}, 

776 "notes": [], 

777 }, 

778 ) 

779 

780 write_status_file(build_status_view(conn)) 

781 logger.info("rollback: %s restored as active model.", to_version_id) 

782 return {"ok": True, "version_id": to_version_id} 

783 

784 

785def _hours_since(timestamp) -> float | None: 

786 if timestamp is None: 

787 return None 

788 from datetime import datetime, timezone 

789 

790 now = datetime.now(timezone.utc) 

791 if timestamp.tzinfo is None: 

792 timestamp = timestamp.replace(tzinfo=timezone.utc) 

793 return (now - timestamp).total_seconds() / 3600.0 

794 

795 

796def auto_rollback_status(conn, config: dict, degradation_overrides: dict | None = None) -> dict: 

797 """V5.1 Phase 6 (production safety) - read-only diagnostic backing 

798 `aq retrain auto-rollback --status`/`--dry-run` AND RetrainingWorker:: 

799 check_auto_rollback()'s own real (non-diagnostic) decision - both call 

800 this same function so there is exactly one place that assembles 

801 inputs for retraining.auto_rollback::select_rollback_target(). NEVER 

802 calls rollback() itself - the caller decides whether decision 

803 ["should_rollback"] is acted on. 

804 

805 "bars" in retraining.auto_rollback's own vocabulary means, in THIS 

806 offline/periodic-worker context (as opposed to main.py's per-Lean-bar 

807 live loop), ELAPSED HOURS since the relevant Postgres timestamp - a 

808 documented, explicit simplification: this worker has no notion of a 

809 Lean bar at all, it polls on a wall-clock interval. 

810 

811 degradation_overrides lets a caller supply live trigger flags 

812 (kill_switch_tripped/net_sharpe_decay/rank_ic_decay) this function has 

813 no way to observe on its own - {} (default) reports every trigger flag 

814 as False, so a bare call always honestly reports "no trigger fired" 

815 rather than fabricating a live signal it cannot actually see.""" 

816 auto_rollback_config = config.get("auto_rollback", {}) 

817 active_version = fetch_active_model_version(conn) 

818 version_history = fetch_rollback_candidates(conn) 

819 

820 bars_since_promotion = _hours_since(active_version["updated_at"]) if active_version else None 

821 last_rollback = next((v for v in version_history if v.get("status") == "rolled_back"), None) 

822 bars_since_last_rollback = _hours_since(last_rollback["updated_at"]) if last_rollback else None 

823 

824 degradation_signals = { 

825 "kill_switch_tripped": False, 

826 "net_sharpe_decay": False, 

827 "rank_ic_decay": False, 

828 "bars_since_promotion": bars_since_promotion, 

829 "bars_since_last_rollback": bars_since_last_rollback, 

830 } 

831 degradation_signals.update(degradation_overrides or {}) 

832 

833 decision = select_rollback_target(active_version or {}, version_history, degradation_signals, auto_rollback_config) 

834 return { 

835 "config": auto_rollback_config, 

836 "active_version_id": active_version["model_version_id"] if active_version else None, 

837 "degradation_signals": degradation_signals, 

838 # V5.5.0 (V5.4.1 follow-up): the continuous 0-1 composite was shipped 

839 # but never called; it is informational only - the binary 

840 # `decision` above stays the sole rollback trigger. 

841 "degradation_score": compute_degradation_score(degradation_signals), 

842 "decision": decision, 

843 } 

844 

845 

846def status(conn) -> dict: 

847 view = build_status_view(conn) 

848 write_status_file(view) 

849 return view 

850 

851 

852# --------------------------------------------------------------------------- 

853# CLI 

854# --------------------------------------------------------------------------- 

855 

856 

857def main() -> None: 

858 logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s — %(message)s") 

859 parser = argparse.ArgumentParser(description="Aether Quant retraining orchestrator") 

860 subparsers = parser.add_subparsers(dest="stage", required=True) 

861 

862 subparsers.add_parser("plan") 

863 

864 train_parser = subparsers.add_parser("train") 

865 train_parser.add_argument("--retraining-id", required=True) 

866 train_parser.add_argument("--version-id", default=None) 

867 

868 train_topology_parser = subparsers.add_parser("train_topology") 

869 train_topology_parser.add_argument("--retraining-id", required=True) 

870 train_topology_parser.add_argument("--version-id", required=True) 

871 

872 train_gating_parser = subparsers.add_parser("train_gating") 

873 train_gating_parser.add_argument("--retraining-id", required=True) 

874 train_gating_parser.add_argument("--version-id", required=True) 

875 

876 train_multitask_parser = subparsers.add_parser("train_multitask") 

877 train_multitask_parser.add_argument("--retraining-id", required=True) 

878 train_multitask_parser.add_argument("--version-id", required=True) 

879 

880 train_sequence_parser = subparsers.add_parser("train_sequence") 

881 train_sequence_parser.add_argument("--retraining-id", required=True) 

882 train_sequence_parser.add_argument("--version-id", required=True) 

883 

884 train_strategy_selector_parser = subparsers.add_parser("train_strategy_selector") 

885 train_strategy_selector_parser.add_argument("--retraining-id", required=True) 

886 train_strategy_selector_parser.add_argument("--version-id", required=True) 

887 

888 validate_parser = subparsers.add_parser("validate") 

889 validate_parser.add_argument("--retraining-id", required=True) 

890 validate_parser.add_argument("--version-id", required=True) 

891 

892 backtest_parser = subparsers.add_parser("backtest") 

893 backtest_parser.add_argument("--retraining-id", required=True) 

894 backtest_parser.add_argument("--version-id", required=True) 

895 

896 commit_parser = subparsers.add_parser("commit") 

897 commit_parser.add_argument("--retraining-id", required=True) 

898 commit_parser.add_argument("--version-id", required=True) 

899 

900 promote_parser = subparsers.add_parser("promote") 

901 promote_parser.add_argument("--version-id", required=True) 

902 promote_parser.add_argument("--retraining-id", default=None) 

903 

904 rollback_parser = subparsers.add_parser("rollback") 

905 rollback_parser.add_argument("--to-version-id", required=True) 

906 

907 # V5.1 Phase 6 (production safety) - read-only diagnostic, mirrors 

908 # `rollback`'s CLI shape but never calls rollback() itself; --dry-run is 

909 # accepted purely for CLI-ergonomics symmetry with a hypothetical future 

910 # non-dry-run mode - today auto-rollback_status() is ALWAYS read-only, so 

911 # --dry-run and its absence behave identically. 

912 auto_rollback_parser = subparsers.add_parser("auto-rollback") 

913 auto_rollback_parser.add_argument("--status", action="store_true") 

914 auto_rollback_parser.add_argument("--dry-run", action="store_true") 

915 

916 subparsers.add_parser("status") 

917 

918 args = parser.parse_args() 

919 config = _load_retraining_config() 

920 conn = connect() 

921 try: 

922 if args.stage == "plan": 

923 print(json.dumps(plan(conn, config), indent=2, default=str)) 

924 elif args.stage == "train": 

925 print(json.dumps(train(conn, args.retraining_id, args.version_id), indent=2, default=str)) 

926 elif args.stage == "train_topology": 

927 print(json.dumps(train_topology(conn, args.retraining_id, args.version_id, config), indent=2, default=str)) 

928 elif args.stage == "train_gating": 

929 print(json.dumps(train_gating(conn, args.retraining_id, args.version_id, config), indent=2, default=str)) 

930 elif args.stage == "train_multitask": 

931 print(json.dumps(train_multitask(conn, args.retraining_id, args.version_id, config), indent=2, default=str)) 

932 elif args.stage == "train_sequence": 

933 print(json.dumps(train_sequence(conn, args.retraining_id, args.version_id, config), indent=2, default=str)) 

934 elif args.stage == "train_strategy_selector": 

935 print( 

936 json.dumps( 

937 train_strategy_selector(conn, args.retraining_id, args.version_id, config), indent=2, default=str 

938 ) 

939 ) 

940 elif args.stage == "validate": 

941 print(json.dumps(validate(conn, args.retraining_id, args.version_id, config), indent=2, default=str)) 

942 elif args.stage == "backtest": 

943 print(json.dumps(backtest(conn, args.retraining_id, args.version_id, config), indent=2, default=str)) 

944 elif args.stage == "commit": 

945 print(json.dumps(commit(conn, args.retraining_id, args.version_id, config), indent=2, default=str)) 

946 elif args.stage == "promote": 

947 print(json.dumps(promote(conn, args.version_id, args.retraining_id, config), indent=2, default=str)) 

948 elif args.stage == "rollback": 

949 print(json.dumps(rollback(conn, args.to_version_id, config), indent=2, default=str)) 

950 elif args.stage == "auto-rollback": 

951 auto_rollback_result = auto_rollback_status(conn, config) 

952 if args.dry_run: 

953 # Same read-only result, explicitly labelled (V5.5.0): the 

954 # shape select_rollback_target_dry_run() documents. 

955 auto_rollback_result = {**auto_rollback_result, "dry_run": True} 

956 print(json.dumps(auto_rollback_result, indent=2, default=str)) 

957 elif args.stage == "status": 

958 print(json.dumps(status(conn), indent=2, default=str)) 

959 finally: 

960 conn.close() 

961 

962 

963if __name__ == "__main__": 

964 main()