Coverage for execution/live_readiness.py: 100%
85 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"""The paper-to-live scorecard (V6.6.5, #352): every condition for live capital, measured, with its evidence and its date.
3Six groups, each a few metrics with a threshold. A metric without evidence is **unknown, and unknown fails**: a scorecard is
4ready only when every metric has been measured and passed. Stale evidence (a field test or a verification run older than
5its limit) fails too. Thresholds are pre-set here and can be tightened in `config.json`'s `phase_v2.live_readiness`; the
6scorecard reports, it never trades (`enforce_before_live` defaults to false, and main.py reads nothing else from it).
7"""
9from __future__ import annotations
11import math
12from collections.abc import Mapping
13from dataclasses import asdict, dataclass
14from datetime import date, datetime
15from typing import Any, Literal
17__all__ = ["GROUPS", "DEFAULT_THRESHOLDS", "ReadinessMetric", "Scorecard", "resolve_thresholds", "build_scorecard", "render_markdown", "live_mode_allowed"]
19Status = Literal["pass", "fail", "unknown"]
20GROUPS = ("edge", "paper", "safety", "operations", "code", "accounts")
21DEFAULT_THRESHOLDS: dict[str, float] = {
22 "forward_sessions_min": 60, "forward_alpha_t_min": 2.0, "book_dsr_min": 0.95, "round_pbo_max": 0.5,
23 "paper_trading_days_min": 120, "paper_rebalances_min": 6,
24 "field_test_max_age_days": 90, "max_total_drawdown_pct_max": 0.15,
25 "backup_max_age_days": 7, "verification_max_age_days": 30, "mutation_score_min": 0.9,
26}
29@dataclass(frozen=True)
30class ReadinessMetric:
31 """One measured condition: its value, threshold and comparator, pass/fail/unknown, and where the evidence came from."""
33 key: str
34 group: str
35 label: str
36 value: Any
37 threshold: str
38 status: Status
39 evidence: str
40 measured_at: str | None = None
43@dataclass(frozen=True)
44class Scorecard:
45 """Every metric for one account, `ready` only when all pass (unknown counts as fail), and the blocking keys."""
47 ready: bool
48 account: str
49 generated_at: str
50 metrics: tuple[ReadinessMetric, ...]
51 blocking: tuple[str, ...]
53 def to_dict(self) -> dict[str, Any]:
54 counts = {status: sum(1 for metric in self.metrics if metric.status == status) for status in ("pass", "fail", "unknown")}
55 return {"ready": self.ready, "account": self.account, "generated_at": self.generated_at, "counts": counts,
56 "metrics": [asdict(metric) for metric in self.metrics], "blocking": list(self.blocking)}
59def resolve_thresholds(raw: Mapping[str, Any] | None) -> dict[str, float]:
60 """The defaults, each replaced by a finite number from config (`phase_v2.live_readiness.thresholds`)."""
61 out = dict(DEFAULT_THRESHOLDS)
62 for key, value in ((raw or {}).get("thresholds") or {}).items():
63 if key in out and isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(float(value)):
64 out[key] = float(value)
65 return out
68def _number(value: Any) -> float | None:
69 if isinstance(value, bool) or not isinstance(value, (int, float)):
70 return None
71 return float(value) if math.isfinite(float(value)) else None
74def _age_days(stamp: Any, now: datetime) -> float | None:
75 if not stamp:
76 return None
77 try:
78 day = date.fromisoformat(str(stamp)[:10])
79 except ValueError:
80 return None
81 return float((now.date() - day).days)
84def _metric(key: str, group: str, label: str, value: Any, threshold: str, passed: bool | None, evidence: str, measured_at: Any = None) -> ReadinessMetric:
85 status: Status = "unknown" if passed is None else ("pass" if passed else "fail")
86 return ReadinessMetric(key, group, label, value, threshold, status, evidence, str(measured_at) if measured_at else None)
89def _at_least(value: Any, floor: float) -> bool | None:
90 number = _number(value)
91 return None if number is None else number >= floor
94def _at_most(value: Any, ceiling: float) -> bool | None:
95 number = _number(value)
96 return None if number is None else number <= ceiling
99def _flag(value: Any) -> bool | None:
100 return value if isinstance(value, bool) else None
103def build_scorecard(evidence: Mapping[str, Any], thresholds: Mapping[str, float] | None = None, *, now: datetime, account: str = "default") -> Scorecard:
104 """The scorecard from `evidence` (see `execution/live_readiness_io.gather_evidence` for the keys). Pure."""
105 limits = {**DEFAULT_THRESHOLDS, **(thresholds or {})}
106 field_test = evidence.get("field_test") or {}
107 verification = evidence.get("verification") or {}
108 field_age, verification_age, backup_age = _age_days(field_test.get("date"), now), _age_days(verification.get("date"), now), _age_days(evidence.get("backup_date"), now)
109 metrics = [
110 _metric("forward_sessions", "edge", "Forward record sessions", evidence.get("forward_sessions"), f">= {limits['forward_sessions_min']:.0f}",
111 _at_least(evidence.get("forward_sessions"), limits["forward_sessions_min"]), str(evidence.get("forward_source", "forward/generations.jsonl"))),
112 _metric("forward_alpha_t", "edge", "Forward alpha t (HAC)", evidence.get("forward_alpha_t"), f">= {limits['forward_alpha_t_min']:.1f}",
113 _at_least(evidence.get("forward_alpha_t"), limits["forward_alpha_t_min"]), "judge_candidate on the incumbent generation"),
114 _metric("book_dsr", "edge", "Deflated Sharpe of the book", evidence.get("book_dsr"), f">= {limits['book_dsr_min']:.2f}",
115 _at_least(evidence.get("book_dsr"), limits["book_dsr_min"]), str(evidence.get("book_dsr_source", "ml/evaluation/alpha_proof.json"))),
116 _metric("round_pbo", "edge", "PBO of the latest research round", evidence.get("round_pbo"), f"< {limits['round_pbo_max']:.2f}",
117 (lambda value: None if value is None else value < limits["round_pbo_max"])(_number(evidence.get("round_pbo"))), str(evidence.get("round_source", "-"))),
118 _metric("paper_trading_days", "paper", "Paper trading days", evidence.get("paper_trading_days"), f">= {limits['paper_trading_days_min']:.0f}",
119 _at_least(evidence.get("paper_trading_days"), limits["paper_trading_days_min"]), "aq evaluate --paper-check"),
120 _metric("paper_rebalances", "paper", "Paper rebalances", evidence.get("paper_rebalances"), f">= {limits['paper_rebalances_min']:.0f}",
121 _at_least(evidence.get("paper_rebalances"), limits["paper_rebalances_min"]), "aq evaluate --paper-check"),
122 _metric("paper_bands", "paper", "Every paper metric inside its reference band", evidence.get("paper_bands_all_inside"), "all inside",
123 _flag(evidence.get("paper_bands_all_inside")), "evaluation/paper_protocol.band_check"),
124 _metric("field_test", "safety", "Field test (orders, trip, flatten, breach, restart, outages, accounts)",
125 f"{field_test.get('passed')}/{field_test.get('total')}" if field_test else None, f"all, <= {limits['field_test_max_age_days']:.0f} days old",
126 None if not field_test else bool(field_test.get("all_passed")) and field_age is not None and field_age <= limits["field_test_max_age_days"],
127 str(field_test.get("path", "ml/evaluation/field_test/")), field_test.get("date")),
128 _metric("kill_switch_enabled", "safety", "Kill switch enabled", evidence.get("kill_switch_enabled"), "true", _flag(evidence.get("kill_switch_enabled")), "phase_v2.risk.kill_switch.enabled"),
129 _metric("reconciliation_trips", "safety", "A reconciliation breach trips the kill switch", evidence.get("reconciliation_trips_kill_switch"), "true",
130 _flag(evidence.get("reconciliation_trips_kill_switch")), "phase_v2.reconciliation.trips_kill_switch"),
131 _metric("max_total_drawdown", "safety", "Live total-drawdown limit", evidence.get("max_total_drawdown_pct"), f"<= {limits['max_total_drawdown_pct_max']:.2f}",
132 _at_most(evidence.get("max_total_drawdown_pct"), limits["max_total_drawdown_pct_max"]), "phase_v2.live.max_allowed_total_drawdown_pct"),
133 _metric("secrets", "operations", "Broker secrets resolve from a file, Docker secret or keyring", evidence.get("secrets_detail"), "all, stored safely",
134 _flag(evidence.get("secrets_all_safe")), "aq secrets status"),
135 _metric("postgres_dsn", "operations", "Postgres password is not the published default", evidence.get("postgres_dsn_safe"), "true",
136 _flag(evidence.get("postgres_dsn_safe")), "execution.live_credentials.postgres_dsn_is_live_safe"),
137 _metric("audit_chain", "operations", "Audit chain verifies", evidence.get("audit_chain_valid"), "true", _flag(evidence.get("audit_chain_valid")), "visualization/grafana/audit_log.json"),
138 _metric("alerts", "operations", "Telegram alerts configured", evidence.get("telegram_configured"), "true", _flag(evidence.get("telegram_configured")), "AETHER_TELEGRAM_*"),
139 _metric("backup", "operations", "Postgres backup", evidence.get("backup_date"), f"<= {limits['backup_max_age_days']:.0f} days old",
140 None if backup_age is None else backup_age <= limits["backup_max_age_days"], "scripts/backup_postgres.py", evidence.get("backup_date")),
141 _metric("image_digest", "operations", "Deployed image digest recorded", evidence.get("image_digest"), "recorded",
142 None if evidence.get("image_digest") is None else bool(evidence.get("image_digest")), "state/deploy/image_digest.txt"),
143 _metric("verification", "code", "Last full verification green", verification.get("summary"), f"all pass, <= {limits['verification_max_age_days']:.0f} days old",
144 None if not verification else bool(verification.get("all_passed")) and verification_age is not None and verification_age <= limits["verification_max_age_days"],
145 str(verification.get("path", "-")), verification.get("date")),
146 _metric("mutation_score", "code", "Mutation kill rate of the safety modules", evidence.get("mutation_score"), f">= {limits['mutation_score_min']:.2f}",
147 _at_least(evidence.get("mutation_score"), limits["mutation_score_min"]), str(evidence.get("mutation_source", "-"))),
148 _metric("accounts_valid", "accounts", "Account registry valid (overrides only tighten)", evidence.get("accounts_valid"), "true", _flag(evidence.get("accounts_valid")), "aq accounts validate"),
149 _metric("live_account", "accounts", "The account is a real brokerage with capital set", evidence.get("live_account_detail"), "broker != paper, capital_usd set",
150 _flag(evidence.get("live_account_ok")), "accounts.json"),
151 ]
152 blocking = tuple(f"{metric.label}: {metric.status}" for metric in metrics if metric.status != "pass")
153 return Scorecard(ready=not blocking, account=account, generated_at=now.strftime("%Y-%m-%dT%H:%M:%SZ"), metrics=tuple(metrics), blocking=blocking)
156def render_markdown(scorecard: Scorecard) -> str:
157 """The scorecard as a Markdown table (the docs' generated block and `aq live-readiness --markdown`)."""
158 def show(value: Any) -> str:
159 if value is None:
160 return "-"
161 if isinstance(value, float):
162 return f"{value:.3g}"
163 return str(value).replace("|", "/")
165 counts = scorecard.to_dict()["counts"]
166 head = (f"**{'READY' if scorecard.ready else 'NOT READY'}** for live capital (account `{scorecard.account}`, {scorecard.generated_at}): "
167 f"{counts['pass']} pass, {counts['fail']} fail, {counts['unknown']} unknown. Unknown counts as fail.")
168 rows = ["| Group | Check | Measured | Needs | Status |", "|---|---|---|---|---|"]
169 marks = {"pass": "pass", "fail": "**fail**", "unknown": "**unknown**"}
170 for metric in scorecard.metrics:
171 rows.append(f"| {metric.group} | {metric.label} | {show(metric.value)} | {metric.threshold} | {marks[metric.status]} |")
172 return head + "\n\n" + "\n".join(rows) + "\n"
175def live_mode_allowed(scorecard_doc: Mapping[str, Any] | None, *, enforce: bool) -> bool:
176 """With `phase_v2.live_readiness.enforce_before_live` on, live mode needs the last written scorecard to be ready."""
177 if not enforce:
178 return True
179 return bool(scorecard_doc) and scorecard_doc.get("ready") is True