Coverage for evaluation/research_cycle.py: 100%
153 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 research cycle's plan (V6.6.1): what is due today, whether a host may train, how to schedule it. Pure, stdlib only, so `aq cycle status` answers on any machine.
3The cycle: research a round -> freeze -> holdout -> shadow on the forward ledger -> ramp on the paper book -> decay -> retire, with a retrain when the calendar or the ledger asks for one. A step
4that spends the owner's budget or changes the book only ever reports itself as due here.
5"""
7from __future__ import annotations
9import ctypes
10import json
11import os
12import sys
13from collections.abc import Mapping, Sequence
14from pathlib import Path
15from typing import Any
17GIB = 1024.0 ** 3
18JUDGE_SESSIONS = (60, 252)
19RETRAIN_EVERY_SESSIONS = 252
20STALE_LEDGER_SESSIONS = 3
21RETRAIN_STAGES = ("refresh_data", "build_panel", "walk_forward", "score", "round", "register", "report")
22BOOTSTRAP_STAGE = "bootstrap_data"
23STACK_STAGES = (
24 "snapshot_active", "factor_audit", "dataset", "parity_audit", "multitask", "sequence", "gating", "walk_forward", "scores", "pins", "register", "report",
25)
26MODEL_AGE_WARNING_DAYS = 30
27HOSTS = ("local", "codespace")
30def total_memory_bytes() -> int | None:
31 """This machine's RAM, or None if it can't be read. Stdlib only, so the check works before anything heavy is installed."""
32 try:
33 if sys.platform == "win32":
34 class _Status(ctypes.Structure):
35 _fields_ = [
36 ("length", ctypes.c_ulong), ("load", ctypes.c_ulong), ("total_phys", ctypes.c_ulonglong), ("avail_phys", ctypes.c_ulonglong), ("total_page", ctypes.c_ulonglong),
37 ("avail_page", ctypes.c_ulonglong), ("total_virtual", ctypes.c_ulonglong), ("avail_virtual", ctypes.c_ulonglong), ("avail_extended", ctypes.c_ulonglong),
38 ]
40 status = _Status()
41 status.length = ctypes.sizeof(_Status)
42 return int(status.total_phys) if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)) else None
43 return int(os.sysconf("SC_PAGE_SIZE")) * int(os.sysconf("SC_PHYS_PAGES"))
44 except (AttributeError, OSError, ValueError):
45 return None
48MIN_RAM_GB = {"standard": 14.0, "low": 3.5} # retraining/slicing.PROFILES' min_total_gb; this module stays stdlib only
51def ram_preflight(host: str, *, total_bytes: int | None = None, min_gb: float | None = None, profile: str = "standard") -> dict[str, Any]:
52 """Whether this host may train. A local machine below the minimum refuses with the numbers: a retrain killed for memory hours in costs more than a clear no. Unknown RAM refuses too.
53 The minimum is the memory profile's unless `min_gb` overrides it: `low` (V6.6.10) trains the stack on a 4 GB machine, slower."""
54 if host not in HOSTS:
55 raise ValueError(f"unknown host {host!r}; expected one of {HOSTS}")
56 if profile not in MIN_RAM_GB:
57 raise ValueError(f"unknown memory profile {profile!r}; expected one of {sorted(MIN_RAM_GB)}")
58 min_gb = MIN_RAM_GB[profile] if min_gb is None else float(min_gb)
59 if host == "codespace":
60 return {"host": host, "ok": True, "reason": "the Codespace is the host: this machine only drives it"}
61 total = total_memory_bytes() if total_bytes is None else int(total_bytes)
62 if total is None:
63 return {"host": host, "ok": False, "total_gb": None, "min_gb": min_gb, "profile": profile, "reason": "this machine's RAM could not be read: refusing rather than guessing"}
64 gigabytes = total / GIB
65 ok = gigabytes >= min_gb
66 advice = ": use --memory-profile low (slower, fits 4 GB), --host codespace, or --smoke to prove the plumbing" if profile == "standard" else ": use --host codespace, or --smoke to prove the plumbing"
67 reason = f"{gigabytes:.1f} GB of RAM, {min_gb:g} GB needed under the {profile} profile" + ("" if ok else advice)
68 return {"host": host, "ok": ok, "total_gb": round(gigabytes, 1), "min_gb": min_gb, "profile": profile, "reason": reason}
71def retrain_stages(*, data_present: bool) -> list[str]:
72 """A fresh checkout builds its own data first, from public sources and the user's own SEC contact: this is what lets anyone retrain."""
73 return ([] if data_present else [BOOTSTRAP_STAGE]) + list(RETRAIN_STAGES)
76def stack_stages() -> list[str]:
77 """The model stack's retrain, in order. The first stage zips the active artifacts; nothing after it writes into the active `ml/` except the dataset build."""
78 return list(STACK_STAGES)
81def stack_plan(
82 procedure: Mapping[str, Any], *, run_id: str, python: str = "python", score_end: str | None = None, resume_id: str | None = None, profile: str = "standard",
83) -> list[tuple[str, list[str] | None]]:
84 """(stage, command) for each stage of the stack retrain; a stage with no command (None) runs in this process. Every trainer writes to
85 `ml/versions/<run id>_<part>/` (`--candidate`, `--version-id`), never over the installed models. `stack_asof` is a new procedure, so its scores are only written for a research round.
86 A `low` profile passes `--memory-profile low` to every trainer (V6.6.10); `standard` leaves the commands as they were."""
87 candidate = f"{run_id}_base"
88 memory = ["--memory-profile", profile] if profile != "standard" else []
89 peaks = ["--log-peak-memory", f"ml/cycle/retrain_{run_id}/memory_peaks.jsonl"] if profile != "standard" else []
90 walk_forward = [python, "train.py", "--walk-forward", "--include-multitask", "--include-sequence", "--mode", str(procedure.get("mode", "expanding")), *memory,
91 "--run-id-file", f"ml/cycle/retrain_{run_id}/walk_forward_run_id"]
92 if resume_id:
93 walk_forward += ["--resume-run-id", resume_id]
94 # the run's own folder (V6.6.10): the default ml/evaluation/v650/scores holds an earlier round's selection scores
95 scores = [python, "scripts/v650_ml_scores.py", "--run-id", resume_id or "<walk-forward run id>", "--end", score_end, "--out", f"ml/cycle/retrain_{run_id}/scores"] if score_end else None
96 # V6.6.10: the multitask and sequence trainers read the dataset and schema this run built, never the installed ones (which hold the
97 # universe of the last build: EOSUSD was still in it, #385)
98 built = ["--dataset-path", f"ml/versions/{candidate}/full_dataset.csv", "--feature-schema-path", f"ml/versions/{candidate}/feature_schema.json"]
99 return [
100 ("snapshot_active", None),
101 ("factor_audit", [python, "-m", "data_pipeline.factor_file_backfill", "--audit"]),
102 ("dataset", [python, "train.py", "--candidate", "--version-id", candidate, "--write-dataset", *memory]),
103 # the run's own dataset against its own scaler (V6.6.10): the installed dataset is not what this run trains on
104 ("parity_audit", [python, "scripts/feature_parity_audit.py", "--skip-synthetic", "--dataset", f"ml/versions/{candidate}/full_dataset.csv",
105 "--scaler-stats", f"ml/versions/{candidate}/scaler_stats.json", "--schema", f"ml/versions/{candidate}/feature_schema.json",
106 "--output", f"ml/cycle/retrain_{run_id}/feature_parity_report.json"]),
107 ("multitask", [python, "train_multitask.py", "--version-id", f"{run_id}_mt", *built, *memory, *peaks]),
108 ("sequence", [python, "train_sequence.py", "--version-id", f"{run_id}_seq", *built, *memory, *peaks]),
109 ("gating", [python, "train_gating.py", "--version-id", f"{run_id}_gate", *memory, *peaks]),
110 ("walk_forward", walk_forward),
111 ("scores", scores),
112 ("pins", None),
113 ("register", None),
114 ("report", None),
115 ]
118def validate_plan_flags(plan: Sequence[tuple[str, list[str] | None]], *, runner: Any) -> list[str]:
119 """Every `--flag` a planned command passes that its script's own `--help` does not list, as "script: --flag". [] is a plan the trainers accept.
120 A retrain that fails on a flag typo in its last stage has already spent the Codespace hours."""
121 problems: list[str] = []
122 for stage, command in plan:
123 if not command:
124 continue
125 python, rest = command[0], command[1:]
126 target = rest[:2] if rest and rest[0] == "-m" else rest[:1]
127 result = runner([python, *target, "--help"], capture_output=True, text=True)
128 if result.returncode != 0:
129 problems.append(f"{stage}: `{' '.join(target)} --help` exit {result.returncode}")
130 continue
131 text = (result.stdout or "") + (result.stderr or "")
132 problems.extend(f"{target[-1]}: {flag}" for flag in sorted({token for token in command if token.startswith("--")}) if flag not in text)
133 return problems
136def retrain_due(*, sessions_since_retrain: int | None, decay_states: Mapping[str, str], every_sessions: int = RETRAIN_EVERY_SESSIONS) -> dict[str, Any]:
137 """By the calendar, or because the book's generation is decaying. It reports; it starts nothing."""
138 decaying = sorted(name for name, state in decay_states.items() if state in ("decaying", "dead", "tripped"))
139 if decaying:
140 return {"due": True, "reason": f"{', '.join(decaying)} decaying or off the book"}
141 if sessions_since_retrain is None:
142 return {"due": True, "reason": "no retrain on record"}
143 return {"due": int(sessions_since_retrain) >= int(every_sessions), "reason": f"{int(sessions_since_retrain)} sessions since the last retrain, every {int(every_sessions)}"}
146def due_actions(
147 generations: Mapping[str, Mapping], judged: Mapping[str, Any], *, session: str | None, sessions_behind: int = 0, sessions_since_retrain: int | None = None, broker_keys: bool = False, policy_enabled: bool = False,
148 record_started: bool = True, model_age_days: float | None = None, max_model_age_days: float = 180.0,
149) -> list[dict]:
150 """What a person or a job should do next, most urgent first."""
151 actions: list[dict] = []
152 if judged.get("chain_valid") is False:
153 actions.append({"action": "investigate", "why": f"the generations' chain is broken at row {judged.get('first_broken_row')}: no figure from it can be used", "urgency": "now"})
154 if not record_started:
155 actions.append({"action": "gh workflow run research-cycle.yml", "why": "record not started: the generations' ledger has no row, and a missed session can't be backfilled", "urgency": "now"})
156 if sessions_behind > STALE_LEDGER_SESSIONS:
157 actions.append({"action": "gh workflow enable research-cycle.yml", "why": f"the last row is {sessions_behind} sessions old: GitHub disables a schedule after 60 days of no repo activity", "urgency": "now"})
158 latest = judged.get("latest_allocation") or {}
159 states = dict(latest.get("states") or {})
160 for name, row in sorted((judged.get("generations") or {}).items()):
161 sessions = int(row.get("sessions") or 0)
162 for mark in JUDGE_SESSIONS:
163 if sessions == mark:
164 actions.append({"action": f"aq evaluate --forward-ledger, then judge {name}", "why": f"{name} has reached {mark} forward sessions", "urgency": "today"})
165 for name, entry in sorted(generations.items()):
166 stage, state = entry.get("stage"), states.get(name)
167 if stage in ("active", "ramping", "fading", "winding_down") and state in ("dead", "tripped"):
168 actions.append({"action": f"aq cycle promote --generation {name} --to retired", "why": f"{name} is {state}: its capital left at the last row, and the registry should say so", "urgency": "today"})
169 if stage == "ramping" and float((latest.get("shares") or {}).get(name, 0.0)) >= 1.0:
170 actions.append({"action": f"aq cycle promote --generation {name} --to active", "why": f"{name} holds the whole book", "urgency": "today"})
171 if stage == "winding_down" and name in (latest.get("shares") or {}) and float(latest["shares"][name]) == 0.0:
172 actions.append({"action": f"aq cycle promote --generation {name} --to retired", "why": f"{name} has wound down to nothing", "urgency": "today"})
173 due = retrain_due(sessions_since_retrain=sessions_since_retrain, decay_states=states)
174 if any(entry.get("kind") == "model" for entry in generations.values()):
175 if due["due"]:
176 actions.append({"action": "aq cycle retrain --host codespace", "why": due["reason"], "urgency": "when convenient"})
177 if model_age_days is not None and model_age_days >= max_model_age_days - MODEL_AGE_WARNING_DAYS and not due["due"]:
178 days_left = max(0.0, max_model_age_days - model_age_days)
179 actions.append({"action": "aq cycle retrain --host codespace --procedure stack", "why": (f"the installed models are {model_age_days:.0f} days old and the kill switch stops a model book at "
180 f"{max_model_age_days:.0f} ({days_left:.0f} days left)"), "urgency": "when convenient"})
181 elif any(state in ("decaying", "dead", "tripped") for state in states.values()):
182 actions.append({"action": "aq cycle research: write a new round (RUNBOOK: Research cycle)", "why": "the book's rule is decaying and there is no model to refit", "urgency": "when convenient"})
183 if not broker_keys:
184 actions.append({"action": "bring the IB and Coinbase API keys (RUNBOOK: When the keys arrive)", "why": "the paper book can't start without them", "urgency": "owner"})
185 if not policy_enabled and any(entry.get("stage") == "ramping" for entry in generations.values()):
186 actions.append({"action": "set enabled in ml/generations/policy.json (owner decision)", "why": "a generation is ramping, and the book isn't reading the blended file", "urgency": "owner"})
187 return actions
190def status_view(generations: Mapping[str, Mapping], judged: Mapping[str, Any], actions: Sequence[Mapping], *, session: str | None, policy: Mapping[str, Any]) -> dict[str, Any]:
191 """The one view `aq cycle status`, the API and the dashboard all read. No secret and no path outside the repo."""
192 latest = judged.get("latest_allocation") or {}
193 # Before the first allocation row, the book is whatever is active: that is what `scripts/cycle_daily.py` starts from.
194 active = [name for name, entry in generations.items() if entry.get("stage") == "active"]
195 # An installed blend (V6.6.9, R-INSTALL2) fixes its shares by the owner's rule, not by the glide: say those, not an equal split nobody computed.
196 installed = {str(name): float(share) for name, share in (policy.get("installed_shares") or {}).items() if name in generations}
197 shares = latest.get("shares") or installed or {name: 1.0 / len(active) for name in active}
198 rows = []
199 for name, entry in sorted(generations.items()):
200 forward = (judged.get("generations") or {}).get(name) or {}
201 rows.append({
202 "id": name, "stage": entry.get("stage"), "tier": entry.get("tier"), "kind": entry.get("kind"), "share": float(shares.get(name, 0.0)), "state": (latest.get("states") or {}).get(name),
203 "sessions": forward.get("sessions"), "sharpe": forward.get("sharpe"), "alpha_t": (forward.get("alpha") or {}).get("t_hac"), "note": entry.get("note", ""),
204 })
205 return {
206 "session": session, "enabled": bool(policy.get("enabled")), "tbills": latest.get("tbills"), "chain_valid": judged.get("chain_valid"), "generations": rows, "due": list(actions),
207 "glide_policy": policy.get("glide_policy"), "glide": policy.get("glide"),
208 }
211def render_schedule(platform: str, *, repo: Path, python: str = "python", host: str = "local") -> str:
212 """The text of a weekly retrain-if-due job, Sunday 03:00. It renders only: `aq cycle schedule install` is what registers it, on a machine that passes the preflight."""
213 repo = Path(repo)
214 command = f"{python} aq_cli.py cycle retrain --host {host} --if-due"
215 if platform == "linux":
216 return f"0 3 * * 0 cd {repo} && {command} >> ml/cycle/schedule.log 2>&1\n"
217 if platform == "windows":
218 return (
219 '<?xml version="1.0" encoding="UTF-16"?>\n<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">\n'
220 " <Triggers><CalendarTrigger><StartBoundary>2026-11-08T03:00:00</StartBoundary><ScheduleByWeek><WeeksInterval>1</WeeksInterval><DaysOfWeek><Sunday/></DaysOfWeek></ScheduleByWeek></CalendarTrigger></Triggers>\n"
221 " <Settings><StartWhenAvailable>true</StartWhenAvailable><DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy></Settings>\n"
222 f" <Actions><Exec><Command>{python}</Command><Arguments>aq_cli.py cycle retrain --host {host} --if-due</Arguments><WorkingDirectory>{repo}</WorkingDirectory></Exec></Actions>\n</Task>\n"
223 )
224 raise ValueError(f"unknown platform {platform!r}; expected windows or linux")
227def install_command(platform: str, *, task_file: Path) -> list[str]:
228 """What registers the rendered job. Returned, not run, so a test can read it and a person can check it first."""
229 if platform == "windows":
230 return ["schtasks", "/Create", "/TN", "AetherQuantRetrain", "/XML", str(task_file), "/F"]
231 if platform == "linux":
232 return ["crontab", str(task_file)]
233 raise ValueError(f"unknown platform {platform!r}")
236def sessions_since_retrain(run_root: Path, sessions: Sequence[str]) -> int | None:
237 """Sessions recorded since the newest real retrain finished. A smoke run registers no procedure, so it never counts. None with none on record."""
238 newest = None
239 for state_path in Path(run_root).glob("retrain_*/state.json"):
240 state = read_json_or(state_path, {})
241 register = (state.get("done") or {}).get("register") or {}
242 if isinstance(register.get("result"), dict) and register["result"].get("procedure"):
243 stamp = str(register.get("at"))[:10]
244 newest = stamp if newest is None or stamp > newest else newest
245 return None if newest is None else sum(1 for day in sessions if day > newest)
248def read_json_or(path: Path, default: Any) -> Any:
249 """A JSON file's content, or `default` when the file does not exist."""
250 path = Path(path)
251 return json.loads(path.read_text(encoding="utf-8")) if path.exists() else default