Coverage for scripts/wheel_smoke.py: 100%
74 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"""Smoke-test an INSTALLED wheel of Aether Quant (V5.5.0, CI `wheel-smoke`).
3Run it from OUTSIDE the repo checkout, in an environment where only the built
4wheel is installed (not `pip install -e .`, which puts the whole repo root on
5sys.path and hides every packaging gap):
7 python -m build --wheel
8 python -m venv /tmp/aq-wheel && /tmp/aq-wheel/bin/pip install dist/*.whl
9 cd /tmp && /tmp/aq-wheel/bin/python /path/to/repo/scripts/wheel_smoke.py
11It checks that
121. `aq_cli` resolves from site-packages, not from the working directory,
132. every module in every shipped package imports - a missing FIRST-PARTY
14 module is a packaging bug (pyproject.toml `py-modules`/`packages`); a
15 missing third-party dependency is reported but tolerated, since optional
16 extras (ib_insync, yfinance, ...) are not part of the wheel's own contract,
173. every `aq <subcommand> --help` exits 0 in a fresh interpreter, which runs
18 each command's lazy imports far enough to build its parser.
20Exit code 0 = healthy, 1 = at least one packaging failure. Prints one line
21per problem, so the CI log says exactly what to add to pyproject.toml.
22"""
24from __future__ import annotations
26import importlib
27import pkgutil
28import subprocess
29import sys
30from pathlib import Path
32# First-party roots shipped by pyproject.toml (kept in step by
33# tests/test_packaging_modules.py, which fails when this drifts).
34SHIPPED_PACKAGES = (
35 "risk", "execution", "data_pipeline", "evaluation", "portfolio", "features", "audit", "inference",
36 "analyzer", "monitoring", "topology", "liquidity", "experience", "aether_quant", "moe", "regime", "retraining", "notifications", "experts", "performance",
37 "lab",
38)
39SHIPPED_MODULES = (
40 "aq_cli", "aq_devtools", "aq_lab_cli", "aq_testtools", "generate_backtest_report", "generate_evaluation_report", "json_safety", "performance_probe", "risk_controls",
41)
42FIRST_PARTY = set(SHIPPED_PACKAGES) | set(SHIPPED_MODULES) | {"main", "train", "risk_controls"}
45def _iter_module_names() -> list[str]:
46 names = list(SHIPPED_MODULES)
47 for package_name in SHIPPED_PACKAGES:
48 package = importlib.import_module(package_name)
49 names.append(package_name)
50 for info in pkgutil.walk_packages(package.__path__, prefix=f"{package_name}."):
51 names.append(info.name)
52 return names
55def check_imports() -> tuple[list[str], list[str]]:
56 failures: list[str] = []
57 tolerated: list[str] = []
58 for name in _iter_module_names():
59 try:
60 importlib.import_module(name)
61 except ModuleNotFoundError as error:
62 missing_root = (error.name or "").split(".")[0]
63 if missing_root in FIRST_PARTY:
64 failures.append(f"{name}: missing first-party module {error.name!r} - add it to pyproject.toml")
65 else:
66 tolerated.append(f"{name}: optional third-party dependency {error.name!r} not installed")
67 except Exception as error:
68 failures.append(f"{name}: import raised {type(error).__name__}: {error}")
69 return failures, tolerated
72def subcommand_names() -> list[str]:
73 import aq_cli
75 parser = aq_cli.build_parser()
76 for action in parser._actions:
77 choices = getattr(action, "choices", None)
78 if isinstance(choices, dict) and choices:
79 return sorted(choices)
80 return []
83def check_help(names: list[str]) -> list[str]:
84 failures: list[str] = []
85 for name in names:
86 result = subprocess.run(
87 [sys.executable, "-c", f"import sys, aq_cli; sys.argv = ['aq', {name!r}, '--help']; aq_cli.main()"],
88 capture_output=True, text=True, timeout=120, check=False,
89 )
90 if result.returncode != 0:
91 failures.append(f"aq {name} --help exited {result.returncode}: {(result.stderr or result.stdout).strip()[-300:]}")
92 return failures
95def check_library() -> list[str]:
96 """V6.4.3: one real call per aether_quant module, from the installed wheel (package data included)."""
97 failures: list[str] = []
98 checks = {
99 "audit": lambda m: m.verify_chain([]) == (True, None),
100 "execution": lambda m: m.resolve_order_permission("observation", True, True, True)[0] is False,
101 "portfolio": lambda m: m.apply_book_neutrality({}, sector_by_symbol={}, dollar_neutral=True, sector_neutral=True,
102 gross_exposure_cap=1.0, max_weight_per_name=0.1,
103 sector_max_net_weight=0.1)[0] == {},
104 "risk": lambda m: m.cap_target_weight(0.1, 0.0, 1.0) == (0.1, False),
105 "io": lambda m: m.sanitize_json_finite([float("nan")]) == [None],
106 "formal": lambda m: len(m.targets()) == 37 and bool(m.load_cases("order_gate")["cases"]),
107 "cycle": lambda m: m.update_generation_shares({"a": 1.0, "b": 0.0}, {"a": "active", "b": "ramping"}, {}, {}, m.GlidePolicy())["b"] == 0.3,
108 "training": lambda m: m.purge_label_overlap(["train", "train", "validation"], 1) == ["train", "purged", "validation"],
109 "regime": lambda m: callable(m.build_market_regime_vector),
110 "topology": lambda m: callable(m.build_market_topology),
111 "moe": lambda m: callable(m.build_gating_decision),
112 "lab": lambda m: m.resolve("core")[0] == "ret_1" and m.half_life({1: 0.1, 5: 0.04}) is not None,
113 "liquidity": lambda m: m.estimate_high_low_spread.__name__ == "estimate_high_low_spread",
114 "analyzer": lambda m: bool(m.__all__),
115 "performance": lambda m: bool(m.__all__),
116 "experts": lambda m: bool(m.__all__),
117 "retraining": lambda m: callable(m.evaluate_validation_gate),
118 "notifications": lambda m: bool(m.__all__),
119 "monitoring": lambda m: bool(m.__all__),
120 "experience": lambda m: callable(m.compute_observation_summary),
121 "data": lambda m: m.first_filings_annual({}, "Assets") == [],
122 "research": lambda m: m.block_bootstrap_mean_ci([0.1, 0.2, 0.3], block=1, draws=20) is not None,
123 "evaluation": lambda m: m.newey_west_t_stat([0.1, 0.2, 0.3], lags=1) != 0.0,
124 "features": lambda m: m.cross_sectional_rank.__name__ == "cross_sectional_rank",
125 "inference": lambda m: callable(m.run_exported_model),
126 "sizing": lambda m: m.kelly_fraction(0.01, 0.04, fraction=1.0, cap=10.0) == 0.25,
127 "neutrality": lambda m: abs(m.net_beta(m.beta_neutralize({"a": 1.0, "b": 0.5}, {"a": 1.0, "b": 2.0}), {"a": 1.0, "b": 2.0})) < 1e-12,
128 "costs": lambda m: m.LinearCostModel(commission_bps=1.0, half_spread_bps=2.0).cost_bps(1e4) == 3.0,
129 "overfitting": lambda m: m.haircut_sharpe(1.0, 2520, 1, method="bonferroni")["haircut"] < 1e-9,
130 "backtest": lambda m: callable(m.backtest) and callable(m.simulate_target_weights),
131 "signals": lambda m: callable(m.forward_rank_targets),
132 "samples": lambda m: m.load_sample_prices().shape[1] == 11,
133 "models": lambda m: [entry["name"] for entry in m.catalog()] == ["example-crypto-mlp", "example-crypto-seq"],
134 "hello": lambda m: m.HELLO_RULE["id"] == "t3_crypto_trend_blend_x_eos",
135 }
136 for name, check in checks.items():
137 try:
138 if not check(importlib.import_module(f"aether_quant.{name}")):
139 failures.append(f"aether_quant.{name}: smoke call returned an unexpected value")
140 except Exception as error:
141 failures.append(f"aether_quant.{name}: {type(error).__name__}: {error}")
142 return failures
145def main() -> int:
146 import aq_cli
148 location = Path(aq_cli.__file__).resolve()
149 if "site-packages" not in location.parts and "dist-packages" not in location.parts:
150 print(f"FAIL: aq_cli resolved from {location}, not an installed wheel - run this OUTSIDE the checkout.")
151 return 1
153 import_failures, tolerated = check_imports()
154 import_failures += check_library()
155 names = subcommand_names()
156 help_failures = check_help(names) if names else ["no aq subcommands found on the parser"]
158 for line in tolerated:
159 print(f"note: {line}")
160 for line in import_failures + help_failures:
161 print(f"FAIL: {line}")
162 print(
163 f"wheel smoke: {len(import_failures)} import failure(s), {len(help_failures)} help failure(s) "
164 f"across {len(names)} subcommands (installed at {location.parent})"
165 )
166 return 1 if (import_failures or help_failures) else 0
169if __name__ == "__main__":
170 sys.exit(main())