Coverage for execution/live_readiness_io.py: 100%

137 statements  

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

1"""Evidence for the paper-to-live scorecard (V6.6.5, #352): read from what the project already writes, each source degrading 

2to "unknown" (which fails) rather than to a guess. `aq live-readiness` calls `gather_evidence`, then 

3`execution.live_readiness.build_scorecard`, and writes `visualization/grafana/live_readiness.json` for the dashboard.""" 

4 

5from __future__ import annotations 

6 

7import json 

8import subprocess 

9from collections.abc import Mapping, Sequence 

10from datetime import datetime, timezone 

11from pathlib import Path 

12from typing import Any 

13 

14from execution.live_readiness import Scorecard, build_scorecard, resolve_thresholds 

15 

16__all__ = ["READINESS_FILE", "DOCS_BLOCK", "gather_evidence", "forward_rows_from_branch", "write_scorecard", "readiness_scorecard", "write_docs_block"] 

17 

18READINESS_FILE = Path("visualization") / "grafana" / "live_readiness.json" 

19DOCS_BLOCK = ("<!-- AQ:READINESS_START -->", "<!-- AQ:READINESS_END -->") 

20 

21 

22def _json(path: Path) -> Any: 

23 try: 

24 return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else None 

25 except (OSError, ValueError): 

26 return None 

27 

28 

29def _latest(root: Path, pattern: str) -> Path | None: 

30 found = sorted(Path(root).glob(pattern), key=lambda path: (path.stat().st_mtime, str(path))) 

31 return found[-1] if found else None 

32 

33 

34def forward_rows_from_branch(root: Path) -> list[dict]: 

35 """The generations' ledger on the `forward-ledger` branch (local copy; `aq cycle status` fetches it). Empty when absent.""" 

36 try: 

37 result = subprocess.run(["git", "show", "forward-ledger:forward/generations.jsonl"], cwd=root, capture_output=True, text=True, encoding="utf-8", timeout=30, check=False) 

38 except (OSError, subprocess.SubprocessError): 

39 return [] 

40 return [json.loads(line) for line in result.stdout.splitlines() if line.strip()] if result.returncode == 0 else [] 

41 

42 

43def _forward(root: Path, rows: Sequence[Mapping[str, Any]]) -> dict[str, Any]: 

44 from evaluation.generation_ledger import judge_generations 

45 

46 registry = _json(Path(root) / "ml" / "generations" / "registry.json") or {} 

47 active = [str(entry.get("name")) for entry in registry.get("generations", []) if entry.get("stage") == "active"] 

48 if not rows: 

49 return {"forward_source": "forward/generations.jsonl (not found)"} 

50 judged = judge_generations(list(rows)) 

51 if not judged.get("chain_valid"): 

52 return {"forward_source": f"forward/generations.jsonl chain broken at row {judged.get('first_broken_row')}", "forward_sessions": 0} 

53 generations = judged.get("generations") or {} 

54 name = next((candidate for candidate in active if candidate in generations), None) or (sorted(generations)[0] if generations else None) 

55 if name is None: 

56 return {"forward_source": "forward/generations.jsonl (no generation)"} 

57 report = generations[name] 

58 alpha = report.get("alpha") or {} 

59 return {"forward_sessions": int(report.get("sessions") or 0), "forward_alpha_t": alpha.get("t_hac"), "forward_source": f"forward/generations.jsonl, {name}"} 

60 

61 

62def gather_evidence(root: Path, account_id: str | None = None, *, forward_rows: Sequence[Mapping[str, Any]] | None = None, 

63 paper_check: Mapping[str, Any] | None = None) -> dict[str, Any]: 

64 """Every metric's evidence for one account. `forward_rows` (default: the forward-ledger branch) and `paper_check` 

65 (`aq evaluate --paper-check`'s report) can be passed in; nothing here needs a broker, Redis or Postgres.""" 

66 from execution.accounts import resolve_account 

67 from execution.accounts_io import ACCOUNT_SECRETS, load_account_config, load_accounts 

68 from execution.live_credentials import postgres_dsn_is_live_safe 

69 from execution.live_credentials_io import load_postgres_dsn 

70 from execution.secrets_io import all_secret_status, load_secret 

71 

72 root = Path(root) 

73 evidence: dict[str, Any] = {} 

74 config = _json(root / "config.json") or {} 

75 try: 

76 accounts = load_accounts(root, config.get("phase_v2", {})) 

77 account = resolve_account(accounts, account_id) 

78 effective = load_account_config(config, account.id, root)["phase_v2"] 

79 evidence["accounts_valid"] = True 

80 except ValueError as error: 

81 evidence["accounts_valid"] = False 

82 evidence["accounts_error"] = str(error) 

83 account, effective = None, config.get("phase_v2", {}) 

84 

85 evidence.update(_forward(root, forward_rows if forward_rows is not None else forward_rows_from_branch(root))) 

86 alpha_proof = _json(root / "ml" / "evaluation" / "alpha_proof.json") or {} 

87 dsr = ((alpha_proof.get("periods") or {}).get("full") or {}).get("dsr") 

88 if isinstance(dsr, Mapping): 

89 dsr = dsr.get("value") 

90 evidence["book_dsr"] = dsr 

91 evidence["book_dsr_source"] = f"ml/evaluation/alpha_proof.json ({alpha_proof.get('run', '-')})" if alpha_proof else "ml/evaluation/alpha_proof.json (not found)" 

92 round_file = _latest(root, "ml/evaluation/v6*/r_round*.json") 

93 if round_file is not None: 

94 rounds = (_json(round_file) or {}).get("rounds") or {} 

95 last = rounds[sorted(rounds)[-1]] if rounds else {} 

96 evidence["round_pbo"] = last.get("pbo") 

97 evidence["round_source"] = f"{round_file.relative_to(root).as_posix()}, round {sorted(rounds)[-1] if rounds else '-'}" 

98 

99 if paper_check: 

100 evidence["paper_trading_days"] = paper_check.get("trading_days") 

101 evidence["paper_rebalances"] = paper_check.get("rebalances") 

102 evidence["paper_bands_all_inside"] = paper_check.get("all_inside") 

103 

104 field_report = _latest(root, "ml/evaluation/field_test/*/report.json") 

105 if field_report is not None: 

106 report = _json(field_report) or {} 

107 judged = report.get("judged") or {} 

108 evidence["field_test"] = {"date": report.get("date"), "all_passed": bool(judged.get("all_passed")), "passed": judged.get("passed"), 

109 "total": judged.get("total"), "path": field_report.relative_to(root).as_posix()} 

110 

111 kill_switch = (effective.get("risk") or {}).get("kill_switch") or {} 

112 evidence["kill_switch_enabled"] = bool(kill_switch.get("enabled")) if "enabled" in kill_switch else None 

113 reconciliation = effective.get("reconciliation") or {} 

114 evidence["reconciliation_trips_kill_switch"] = bool(reconciliation.get("trips_kill_switch")) if "trips_kill_switch" in reconciliation else None 

115 evidence["max_total_drawdown_pct"] = (effective.get("live") or {}).get("max_allowed_total_drawdown_pct") 

116 

117 if account is not None: 

118 needed = ACCOUNT_SECRETS.get(account.broker, ()) 

119 status = all_secret_status(account.id, needed) if needed else [] 

120 evidence["secrets_all_safe"] = bool(needed) and all(row["resolved"] and row["stored_safely"] for row in status) 

121 evidence["secrets_detail"] = "no broker secrets: a paper account" if not needed else ", ".join(f"{row['name']} {row['source'] or 'missing'}" for row in status) 

122 evidence["live_account_ok"] = account.broker != "paper" and account.capital_usd is not None 

123 evidence["live_account_detail"] = f"{account.id}: {account.broker}, capital {account.capital_usd}" 

124 dsn = load_postgres_dsn() 

125 evidence["postgres_dsn_safe"] = postgres_dsn_is_live_safe(dsn) if dsn else None 

126 audit = _json(root / "visualization" / "grafana" / "audit_log.json") 

127 evidence["audit_chain_valid"] = audit.get("chain_valid") if isinstance(audit, Mapping) and "chain_valid" in audit else None 

128 evidence["telegram_configured"] = load_secret("TELEGRAM_BOT_TOKEN").value is not None and load_secret("TELEGRAM_CHAT_ID").value is not None 

129 backup = _json(root / "state" / "backups" / "last_backup.json") 

130 evidence["backup_date"] = backup.get("date") if isinstance(backup, Mapping) else None 

131 digest = root / "state" / "deploy" / "image_digest.txt" 

132 evidence["image_digest"] = digest.read_text(encoding="utf-8").strip() if digest.is_file() else None 

133 

134 verification_file = _latest(root, "ml/evaluation/v6*/verification.json") 

135 if verification_file is not None: 

136 doc = _json(verification_file) or {} 

137 rows = doc.get("rows") or [] 

138 failed = [row for row in rows if str(row.get("result")) not in ("pass", "skip")] 

139 stamp = doc.get("date") or datetime.fromtimestamp(verification_file.stat().st_mtime, timezone.utc).date().isoformat() 

140 evidence["verification"] = {"date": stamp, "all_passed": bool(rows) and not failed, "summary": f"{len(rows) - len(failed)}/{len(rows)} surfaces pass", 

141 "path": verification_file.relative_to(root).as_posix()} 

142 mutation_file = _latest(root, "ml/evaluation/v6*/mutation_summary.json") 

143 if mutation_file is not None: 

144 doc = _json(mutation_file) or {} 

145 # the current tests' kill rate on every seed run after them, the lowest one counting (never a cherry-picked seed) 

146 after = [doc[key]["overall"][0] for key in doc if "after" in key and isinstance(doc[key], Mapping) and isinstance(doc[key].get("overall"), list)] 

147 if after: 

148 evidence["mutation_score"] = min(after) 

149 evidence["mutation_source"] = mutation_file.relative_to(root).as_posix() 

150 return evidence 

151 

152 

153def readiness_scorecard(root: Path, account_id: str | None = None, *, now: datetime | None = None, **kwargs: Any) -> Scorecard: 

154 config = _json(Path(root) / "config.json") or {} 

155 thresholds = resolve_thresholds((config.get("phase_v2") or {}).get("live_readiness")) 

156 return build_scorecard(gather_evidence(root, account_id, **kwargs), thresholds, now=now or datetime.now(timezone.utc), account=account_id or "default") 

157 

158 

159def write_scorecard(root: Path, scorecard: Scorecard) -> Path: 

160 from json_safety import atomic_write_json 

161 

162 path = Path(root) / READINESS_FILE 

163 path.parent.mkdir(parents=True, exist_ok=True) 

164 atomic_write_json(path, scorecard.to_dict(), indent=1) 

165 return path 

166 

167 

168def write_docs_block(path: Path, markdown: str) -> bool: 

169 """Replace the generated block between the AQ:READINESS markers in `path`; False when the markers are missing.""" 

170 target = Path(path) 

171 text = target.read_text(encoding="utf-8") 

172 start, end = DOCS_BLOCK 

173 if start not in text or end not in text: 

174 return False 

175 head, rest = text.split(start, 1) 

176 _, tail = rest.split(end, 1) 

177 target.write_text(f"{head}{start}\n{markdown.rstrip()}\n{end}{tail}", encoding="utf-8", newline="\n") 

178 return True