Coverage for retraining/lean_backtest.py: 100%
29 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"""Best-effort optional Lean CLI backtest wrapper (Phase V2-17).
3"If Lean is available" per the user's spec: find_lean_binary() returning
4None is the actual gate - run_lean_backtest() never attempts subprocess.run
5in that case. Same catch-everything-never-raise shape as
6retraining/vault_client.py's run_av_command(), since neither the `lean` nor
7`av` binaries are guaranteed to be on PATH in every environment this runs in,
8and a missing optional tool must never crash the retraining pipeline.
9"""
11from __future__ import annotations
13import logging
14import shutil
15import subprocess
16from pathlib import Path
18logger = logging.getLogger(__name__)
21def find_lean_binary(config: dict) -> str | None:
22 """shutil.which('lean') or an explicit config override; None if unavailable."""
23 configured = config.get("lean_binary", "lean")
24 return shutil.which(configured)
27def run_lean_backtest(version_dir: Path, config: dict) -> dict:
28 """Runs `lean backtest <version_dir>` if Lean is available, best-effort.
30 Returns {"ran": bool, "ok": bool | None, "output_path": str | None, "error": str | None}.
31 ran=False means no subprocess was ever attempted (Lean missing, or
32 run_lean_backtest disabled via config["run_lean_backtest"]=False).
33 """
34 if not config.get("run_lean_backtest", True):
35 return {"ran": False, "ok": None, "output_path": None, "error": "lean_backtest_disabled"}
37 # a candidate's version folder holds model artifacts, not the algorithm: `lean backtest` on it can only fail. A candidate
38 # is Lean-confirmed by installing it and running the project (the R-LEAN13 route), not from here.
39 if not (Path(version_dir) / "main.py").is_file():
40 return {"ran": False, "ok": None, "output_path": None, "error": "not_a_lean_project"}
42 lean_binary = find_lean_binary(config)
43 if lean_binary is None:
44 return {"ran": False, "ok": None, "output_path": None, "error": "lean_not_available"}
46 timeout_seconds = int(config.get("lean_timeout_seconds", 1800))
47 try:
48 result = subprocess.run(
49 [lean_binary, "backtest", str(version_dir)],
50 cwd=str(version_dir),
51 capture_output=True,
52 text=True,
53 timeout=timeout_seconds, check=False,
54 )
55 except FileNotFoundError:
56 return {"ran": False, "ok": None, "output_path": None, "error": "lean_binary_not_found"}
57 except subprocess.TimeoutExpired:
58 return {"ran": True, "ok": False, "output_path": None, "error": "lean_backtest_timed_out"}
59 except Exception as exc: # never let an optional Lean run crash the pipeline
60 logger.error("run_lean_backtest: unexpected error - %s", exc)
61 return {"ran": True, "ok": False, "output_path": None, "error": str(exc)}
63 ok = result.returncode == 0
64 return {
65 "ran": True,
66 "ok": ok,
67 "output_path": str(version_dir) if ok else None,
68 "error": None if ok else (result.stderr or result.stdout or "lean_backtest_failed"),
69 }