Coverage for scripts/lean_smoke/field_test.py: 100%
149 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 field test without a broker (V6.6.5, #351): main.py in Lean's `live-paper` (PaperBrokerage, FakeDataQueue), real
2Redis and Postgres, three runs, and a report with every check of `execution.field_test.judge_field_test`.
4- **Run 1, the default account.** The plan's order row fills, injected drift breaches reconciliation, and an injected
5 shock trips the kill switch, which flattens the book. Redis and then Postgres are stopped under the running engine.
6- **Run 2, the same project.** It restarts; its first reconciliation must match.
7- **Run 3, two named accounts at once** (`AQ_ACCOUNT=paper-a` and `paper-b`). Separate state directories, and the
8 audit events tagged with each account's id.
10Needs Docker, the `aether-quant-lean:17900` image and the compose Redis and Postgres. No QuantConnect login, no broker,
11no key and no money. Configs live in a temp directory; lean.json and config.json are never touched. It proves plumbing,
12never edge.
14 python scripts/lean_smoke/field_test.py [--bars 22] [--minutes-per-run 45] [--out-dir ml/evaluation/field_test]
15"""
17from __future__ import annotations
19import argparse
20import datetime as dt
21import json
22import os
23import shutil
24import subprocess
25import sys
26import tempfile
27import time
28from pathlib import Path
30ROOT = Path(__file__).resolve().parents[2]
31sys.path.insert(0, str(ROOT))
33from execution.field_test import judge_field_test, parse_field_test_log # noqa: E402
35IMAGE = "aether-quant-lean:17900"
36NETWORK = "aether-quant_aether-net"
37REDIS_IN, POSTGRES_IN = "redis://redis:6379/0", "postgresql://aether:aether_dev_password@postgres:5432/aether_quant"
38REDIS_HOST, POSTGRES_HOST = "redis://localhost:6380/0", "postgresql://aether:aether_dev_password@localhost:5433/aether_quant"
39SKIP = {".git", ".av", ".venv", "node_modules", "backtests", "backtests_invalid", "data", "data_pre2013", "data_wide", "data_crypto_wide", "data_backups",
40 "visualization", "state", "site", "Aether-quant-Obsidian-Vault", "__pycache__", "datasets", "versions", "cpp_inference_ext", "webui",
41 ".lake", "build", ".cache", ".hypothesis", ".pytest_cache", ".ruff_cache", ".matplotlib_cache", "aether_quant.egg-info", "notebooks", "docs"}
44def run(command: list[str], **kwargs) -> subprocess.CompletedProcess:
45 return subprocess.run(command, capture_output=True, text=True, encoding="utf-8", errors="replace", **kwargs, check=False)
48def copy_project(target: Path) -> None:
49 def ignore(directory: str, names: list[str]) -> set[str]:
50 return {name for name in names if name in SKIP}
51 shutil.copytree(ROOT, target, ignore=ignore)
54def engine(name: str, project: Path, results: Path, launcher: Path, account: str = "") -> None:
55 run(["docker", "rm", "-f", name])
56 results.mkdir(parents=True, exist_ok=True)
57 command = [
58 "docker", "run", "-d", "--name", name, "--network", NETWORK, "--memory", "1400m",
59 "-e", f"AETHER_REDIS_URL={REDIS_IN}", "-e", f"AETHER_POSTGRES_DSN={POSTGRES_IN}", "-e", "AQ_FIELD_TEST=1", "-e", f"AQ_ACCOUNT={account}",
60 "-v", f"{project}:/LeanCLI", "-v", f"{ROOT / 'data'}:/Lean/Data:ro", "-v", f"{ROOT / 'data'}:/LeanCLI/data:ro", "-v", f"{results}:/Results",
61 "-v", f"{launcher}:/Lean/Launcher/bin/Debug/config.json:ro", "-w", "/Lean/Launcher/bin/Debug", IMAGE,
62 ]
63 result = run(command)
64 if result.returncode:
65 raise SystemExit(f"docker run failed: {result.stderr}")
68def logs(name: str) -> str:
69 result = run(["docker", "logs", name])
70 return (result.stdout or "") + (result.stderr or "")
73def alive(name: str) -> bool:
74 return run(["docker", "inspect", "-f", "{{.State.Running}}", name]).stdout.strip() == "true"
77def wait_for_bar(name: str, bar: int, deadline: float) -> list[dict]:
78 while time.time() < deadline:
79 events = parse_field_test_log(logs(name))
80 if any(int(event.get("bar", 0)) >= bar for event in events) or not alive(name):
81 return events
82 time.sleep(20)
83 return parse_field_test_log(logs(name))
86def stop(name: str, out: Path) -> str:
87 text = logs(name)
88 out.write_text(text, encoding="utf-8")
89 run(["docker", "stop", "-t", "30", name])
90 text = logs(name)
91 out.write_text(text, encoding="utf-8")
92 run(["docker", "rm", "-f", name])
93 return text
96def summarize_run(events: list[dict]) -> dict:
97 by_event: dict[str, list[dict]] = {}
98 for event in events:
99 by_event.setdefault(event["event"], []).append(event)
100 orders = [e for e in by_event.get("order_event", []) if "Submitted" in e.get("status", "")]
101 fills = [e for e in by_event.get("order_event", []) if e.get("status", "").endswith("Filled") and "Partially" not in e.get("status", "")]
102 trip = by_event.get("kill_switch_tripped", [{}])[0].get("bar")
103 shock = by_event.get("shock", [{}])[0].get("bar")
104 # the strategy's own exposure (`risk`, the T-bill sweep excluded, as the lock's liquidation does); `value` if absent
105 gross_after = [float(e.get("risk", e["value"])) for e in by_event.get("gross", []) if trip is not None and int(e["bar"]) > int(trip) + 2]
106 first = by_event.get("first_reconciliation", [{}])[0]
107 return {
108 "orders_submitted": len(orders), "orders_filled": len(fills), "shock_bar": int(shock) if shock is not None else None,
109 "kill_switch_trip_bar": int(trip) if trip is not None else None, "gross_after_trip": gross_after[-1] if gross_after else None,
110 "reconciliation_breach": bool(by_event.get("reconciliation_breach")), "first_reconciliation_breach": first.get("breach") == "True" if first else None,
111 "bars_seen": max((int(e.get("bar", 0)) for e in events), default=0), "events": {key: len(value) for key, value in by_event.items()},
112 }
115def audit_facts() -> dict:
116 """The audit chain on the real Postgres: verified, and which accounts and events it holds."""
117 import psycopg
119 from audit.hash_chain import verify_chain
120 from audit.postgres_audit import fetch_all_events_ordered
122 with psycopg.connect(POSTGRES_HOST) as conn:
123 rows = fetch_all_events_ordered(conn)
124 valid, broken = verify_chain(rows)
125 payloads = [json.loads(row["payload"]) if isinstance(row.get("payload"), str) else (row.get("payload") or {}) for row in rows]
126 return {
127 "audit_chain_valid": bool(valid), "audit_first_broken": broken, "audit_entries": len(rows),
128 "account_ids_in_audit": sorted({str(p["account_id"]) for p in payloads if isinstance(p, dict) and p.get("account_id")}),
129 "reconciliation_audit_event": any(isinstance(p, dict) and p.get("event") == "reconciliation_breach" for p in payloads),
130 "kill_switch_audit_event": any(isinstance(p, dict) and p.get("event") == "kill_switch_tripped" for p in payloads),
131 }
134def main(argv: list[str] | None = None) -> int:
135 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
136 parser.add_argument("--bars", type=int, default=22, help="bars run 1 waits for (the plan trips the kill switch at 14)")
137 parser.add_argument("--minutes-per-run", type=float, default=45.0)
138 parser.add_argument("--out-dir", default=str(ROOT / "ml" / "evaluation" / "field_test"))
139 parser.add_argument("--work-dir", default=None)
140 args = parser.parse_args(argv)
141 stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%d")
142 out = Path(args.out_dir) / stamp
143 out.mkdir(parents=True, exist_ok=True)
144 work = Path(args.work_dir or tempfile.mkdtemp(prefix="aq_field_test_"))
145 project = work / "project"
146 if project.exists():
147 shutil.rmtree(project)
148 copy_project(project)
149 (project / "visualization" / "grafana").mkdir(parents=True, exist_ok=True)
150 (project / "data").mkdir(exist_ok=True) # the mount point of the repo's data (read-only)
151 launcher = work / "launcher.json"
152 made = run([sys.executable, str(ROOT / "scripts" / "lean_smoke" / "make_field_test_config.py"), "--lean-json", str(ROOT / "lean.json"), "--out", str(launcher),
153 "--project-config", str(project / "config.json")], cwd=ROOT)
154 if made.returncode:
155 raise SystemExit(made.stderr)
156 shutil.copyfile(ROOT / "accounts.example.json", project / "accounts.json")
157 print("services: docker compose up -d redis postgres", flush=True)
158 run(["docker", "compose", "up", "-d", "redis", "postgres"], cwd=ROOT)
159 time.sleep(10)
160 worker_env = {**os.environ, "AETHER_REDIS_URL": REDIS_HOST, "AETHER_POSTGRES_DSN": POSTGRES_HOST}
161 worker_log = (out / "audit_worker.log").open("w", encoding="utf-8")
162 worker = subprocess.Popen([sys.executable, "-m", "audit.postgres_worker"], cwd=ROOT, env=worker_env, stdout=worker_log, stderr=subprocess.STDOUT)
163 evidence: dict = {"runs": [], "outages": [], "date": stamp}
164 try:
165 print("run 1: default account, order, drift, shock, outages", flush=True)
166 engine("aq_field_test", project, work / "results1", launcher)
167 deadline = time.time() + args.minutes_per_run * 60
168 wait_for_bar("aq_field_test", 10, deadline)
169 for service, container in (("redis", "aether-quant-redis"), ("postgres", "aether-quant-postgres")):
170 run(["docker", "stop", container])
171 time.sleep(40)
172 evidence["outages"].append({"service": service, "engine_alive_after": alive("aq_field_test")})
173 run(["docker", "start", container])
174 time.sleep(15)
175 events = wait_for_bar("aq_field_test", args.bars, deadline)
176 stop("aq_field_test", out / "engine1.log")
177 evidence["runs"].append(summarize_run(events))
179 print("run 2: restart on the same project", flush=True)
180 engine("aq_field_test", project, work / "results2", launcher)
181 events2 = wait_for_bar("aq_field_test", 4, time.time() + args.minutes_per_run * 60)
182 stop("aq_field_test", out / "engine2.log")
183 second = summarize_run(events2)
184 evidence["restart"] = {"started": second["bars_seen"] >= 1, "reconciliation_breach_on_start": bool(second["first_reconciliation_breach"]), "summary": second}
186 print("run 3: two accounts at once", flush=True)
187 engine("aq_field_test_a", project, work / "results3a", launcher, account="paper-a")
188 engine("aq_field_test_b", project, work / "results3b", launcher, account="paper-b")
189 deadline3 = time.time() + args.minutes_per_run * 60
190 wait_for_bar("aq_field_test_a", 4, deadline3)
191 wait_for_bar("aq_field_test_b", 4, deadline3)
192 stop("aq_field_test_a", out / "engine3a.log")
193 stop("aq_field_test_b", out / "engine3b.log")
194 dirs = [project / "state" / "accounts" / account for account in ("paper-a", "paper-b")]
195 evidence["state_dirs_distinct"] = all(path.is_dir() for path in dirs)
196 evidence["state_dirs"] = [str(path.relative_to(project)) for path in dirs if path.is_dir()]
197 finally:
198 time.sleep(10)
199 worker.terminate()
200 worker_log.close()
201 try:
202 evidence.update(audit_facts())
203 if evidence["runs"]:
204 evidence["runs"][0]["reconciliation_audit_event"] = evidence["reconciliation_audit_event"]
205 except Exception as error:
206 evidence["audit_error"] = f"{type(error).__name__}: {error}"
207 judged = judge_field_test(evidence)
208 report = {"date": stamp, "evidence": evidence, "judged": judged, "image": IMAGE, "work_dir": str(work)}
209 (out / "report.json").write_text(json.dumps(report, indent=1, default=str) + "\n", encoding="utf-8")
210 print(json.dumps({name: check["status"] for name, check in judged["checks"].items()}, indent=1))
211 print(f"{judged['passed']}/{judged['total']} checks passed; report {out / 'report.json'}")
212 return 0 if judged["all_passed"] else 1
215if __name__ == "__main__":
216 raise SystemExit(main())