Coverage for retraining/artifacts.py: 100%

90 statements  

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

1"""Filesystem-only artifact helpers for candidate models (Phase V2-17). 

2 

3No Postgres dependency here - this module only touches ml/versions/<id>/ 

4and the active ml/ paths. Kept independent of train.py's own path constants 

5(rather than importing them) so retraining/ stays a lightweight package that 

6never pulls in torch/pandas/sklearn - only retraining/orchestrator.py's 

7`train` subcommand actually invokes train.py, and it does so as a 

8subprocess, not an import. 

9""" 

10 

11from __future__ import annotations 

12 

13import hashlib 

14import re 

15import shutil 

16from pathlib import Path 

17 

18ROOT_DIR = Path(__file__).resolve().parent.parent 

19ML_DIR = ROOT_DIR / "ml" 

20VERSIONS_DIR = ML_DIR / "versions" 

21 

22REQUIRED_CANDIDATE_FILES = ( 

23 "model_weights.json", 

24 "model.pt", 

25 "training_metrics.json", 

26 "strategy_report.json", 

27 "scaler.pkl", 

28 "scaler_stats.json", 

29 "feature_schema.json", 

30) 

31 

32# V2-17.5 - learned-topology artifacts (train_topology.py). Deliberately 

33# NOT part of REQUIRED_CANDIDATE_FILES: topology training is best-effort 

34# and independently failable (see retraining/orchestrator.py::train_topology()), 

35# so validate()'s gate must never reject a candidate purely for missing 

36# topology artifacts. 

37OPTIONAL_TOPOLOGY_FILES = ( 

38 "topology_model.json", 

39 "topology_training_metrics.json", 

40 "topology_feature_schema.json", 

41) 

42 

43# Learned-gating artifacts (train_gating.py). Same optional, best-effort, 

44# independently-failable contract as OPTIONAL_TOPOLOGY_FILES - never part 

45# of REQUIRED_CANDIDATE_FILES, never a validation gate. 

46OPTIONAL_GATING_FILES = ( 

47 "gating_model.json", 

48 "gating_training_metrics.json", 

49 "gating_feature_schema.json", 

50) 

51 

52# Multitask (direction+magnitude+volatility) artifacts (train_multitask.py). 

53# Same optional, best-effort, independently-failable contract as 

54# OPTIONAL_TOPOLOGY_FILES/OPTIONAL_GATING_FILES - never part of 

55# REQUIRED_CANDIDATE_FILES, never a validation gate. 

56OPTIONAL_MULTITASK_FILES = ( 

57 "multitask_model.json", 

58 "multitask_feature_schema.json", 

59 "multitask_training_metrics.json", 

60) 

61 

62# Phase 2 sequence-encoder artifacts (train_sequence.py). Same optional, 

63# best-effort, independently-failable contract as OPTIONAL_MULTITASK_FILES - 

64# never part of REQUIRED_CANDIDATE_FILES, never a validation gate. 

65OPTIONAL_SEQUENCE_FILES = ( 

66 "sequence_model.json", 

67 "sequence_feature_schema.json", 

68 "sequence_training_metrics.json", 

69) 

70 

71# Learned multi-leg strategy-selector artifacts (train_strategy_selector.py, 

72# V4.7, development/Problems.md #29's own framing). Same optional, 

73# best-effort, independently-failable contract as OPTIONAL_SEQUENCE_FILES - 

74# never part of REQUIRED_CANDIDATE_FILES, never a validation gate. In 

75# practice this trainer's own docstring documents that it has no data 

76# source to train from at all in this environment - these files will 

77# realistically never exist for a real candidate, but the contract stays 

78# identical to every other optional artifact set regardless. 

79OPTIONAL_STRATEGY_SELECTOR_FILES = ( 

80 "strategy_selector_model.json", 

81 "strategy_selector_training_metrics.json", 

82 "strategy_selector_feature_schema.json", 

83) 

84 

85# Every filename this package will hash/copy when present - used by 

86# commit()'s artifact-hashing so topology/gating/multitask/sequence/ 

87# strategy_selector files (when their trainers succeeded) get sha256'd and 

88# swept into the Aether-Vault commit alongside the required candidate files. 

89ALL_TRACKED_FILES = ( 

90 REQUIRED_CANDIDATE_FILES 

91 + OPTIONAL_TOPOLOGY_FILES 

92 + OPTIONAL_GATING_FILES 

93 + OPTIONAL_MULTITASK_FILES 

94 + OPTIONAL_SEQUENCE_FILES 

95 + OPTIONAL_STRATEGY_SELECTOR_FILES 

96) 

97 

98# Files copied into the active ml/ directory on promotion/rollback. Extended 

99# beyond model_weights.json/scaler.pkl/training_metrics.json (the user's 

100# literal 3-file list) because main.py's _validate_runtime_artifacts() 

101# actually requires feature_schema.json and scaler_stats.json too - omitting 

102# them would let promotion silently break the Lean runtime. Also includes 

103# the optional topology/gating files (V2-17.5 / gating learned weights) - 

104# copy_candidate_to_active() already skips any filename that doesn't exist 

105# in the candidate dir, so this is safe even for a candidate whose 

106# topology/gating training was skipped/failed. 

107ACTIVE_ARTIFACT_FILES = ( 

108 "model_weights.json", 

109 "scaler.pkl", 

110 "scaler_stats.json", 

111 "training_metrics.json", 

112 "feature_schema.json", 

113) + OPTIONAL_TOPOLOGY_FILES + OPTIONAL_GATING_FILES + OPTIONAL_MULTITASK_FILES + OPTIONAL_SEQUENCE_FILES + OPTIONAL_STRATEGY_SELECTOR_FILES 

114 

115 

116_VERSION_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") 

117 

118 

119def candidate_dir(version_id: str, ml_dir: Path = ML_DIR) -> Path: 

120 """Resolves ml/versions/<version_id>. V5.4.7 (Problems.md #124): 

121 validates the id's charset first - the value reaches here from CLI 

122 flags, and an absolute path or traversal segment previously joined 

123 straight into the base path. Defense-in-depth: normal callers pass 

124 UUIDs that already passed the DB lookup.""" 

125 if not version_id or not _VERSION_ID_PATTERN.match(version_id) or ".." in version_id: 

126 raise ValueError(f"invalid version_id: {version_id!r}") 

127 return ml_dir / "versions" / version_id 

128 

129 

130def verify_version_artifacts( 

131 version_dir: Path, 

132 filenames: tuple[str, ...] = ACTIVE_ARTIFACT_FILES, 

133 expected_hashes: dict[str, str] | None = None, 

134) -> dict: 

135 """V5.4.7 (Problems.md #124): shared pre-flight check used by BOTH 

136 promote and rollback. Returns {"missing": [...], "mismatched": [...], 

137 "present": [...]} - missing = required file absent from the version 

138 dir; mismatched = file present but sha256 differs from the committed 

139 hash. Only REQUIRED files are checked for presence; hash checks run 

140 only against names actually present in expected_hashes.""" 

141 missing: list[str] = [] 

142 mismatched: list[str] = [] 

143 present: list[str] = [] 

144 expected_hashes = expected_hashes or {} 

145 for name in filenames: 

146 source = version_dir / name 

147 if not source.exists(): 

148 missing.append(name) 

149 continue 

150 present.append(name) 

151 expected = expected_hashes.get(name) 

152 if expected is not None and _sha256_file(source) != expected: 

153 mismatched.append(name) 

154 return {"missing": missing, "mismatched": mismatched, "present": present} 

155 

156 

157def check_required_artifacts( 

158 version_dir: Path, filenames: tuple[str, ...] = REQUIRED_CANDIDATE_FILES 

159) -> tuple[bool, list[str]]: 

160 """Returns (all_present, missing_filenames).""" 

161 missing = [name for name in filenames if not (version_dir / name).exists()] 

162 return (len(missing) == 0, missing) 

163 

164 

165def check_topology_artifacts(version_dir: Path) -> tuple[bool, list[str]]: 

166 """Status/logging only - never a validation gate. Reports whether the 

167 optional learned-topology artifacts exist for a candidate, same 

168 (all_present, missing_filenames) shape as check_required_artifacts().""" 

169 return check_required_artifacts(version_dir, OPTIONAL_TOPOLOGY_FILES) 

170 

171 

172def check_gating_artifacts(version_dir: Path) -> tuple[bool, list[str]]: 

173 """Status/logging only - never a validation gate. Reports whether the 

174 optional learned-gating artifacts exist for a candidate, same 

175 (all_present, missing_filenames) shape as check_topology_artifacts().""" 

176 return check_required_artifacts(version_dir, OPTIONAL_GATING_FILES) 

177 

178 

179def check_multitask_artifacts(version_dir: Path) -> tuple[bool, list[str]]: 

180 """Status/logging only - never a validation gate. Reports whether the 

181 optional multitask artifacts exist for a candidate, same 

182 (all_present, missing_filenames) shape as check_topology_artifacts().""" 

183 return check_required_artifacts(version_dir, OPTIONAL_MULTITASK_FILES) 

184 

185 

186def check_sequence_artifacts(version_dir: Path) -> tuple[bool, list[str]]: 

187 """Status/logging only - never a validation gate. Reports whether the 

188 optional Phase 2 sequence-encoder artifacts exist for a candidate, 

189 same (all_present, missing_filenames) shape as check_topology_artifacts().""" 

190 return check_required_artifacts(version_dir, OPTIONAL_SEQUENCE_FILES) 

191 

192 

193def check_strategy_selector_artifacts(version_dir: Path) -> tuple[bool, list[str]]: 

194 """Status/logging only - never a validation gate. Reports whether the 

195 optional learned strategy-selector artifacts exist for a candidate, 

196 same (all_present, missing_filenames) shape as check_topology_artifacts(). 

197 Realistically always (False, [...missing]) in this environment - see 

198 train_strategy_selector.py's own module docstring for why.""" 

199 return check_required_artifacts(version_dir, OPTIONAL_STRATEGY_SELECTOR_FILES) 

200 

201 

202def _sha256_file(path: Path) -> str: 

203 digest = hashlib.sha256() 

204 with path.open("rb") as f: 

205 for chunk in iter(lambda: f.read(1024 * 1024), b""): 

206 digest.update(chunk) 

207 return digest.hexdigest() 

208 

209 

210def compute_artifact_hashes( 

211 version_dir: Path, filenames: tuple[str, ...] = REQUIRED_CANDIDATE_FILES 

212) -> dict[str, str]: 

213 """sha256 per file (only for files that exist) - feeds model_versions.artifact_hashes.""" 

214 return {name: _sha256_file(version_dir / name) for name in filenames if (version_dir / name).exists()} 

215 

216 

217def copy_candidate_to_active( 

218 version_dir: Path, 

219 ml_dir: Path = ML_DIR, 

220 filenames: tuple[str, ...] = ACTIVE_ARTIFACT_FILES, 

221) -> dict[str, str]: 

222 """Copies the promotion artifact set from a candidate dir into ml/. 

223 

224 Returns the new active artifact hashes (post-copy, from the destination 

225 files) for storage on the newly-promoted model_versions row. 

226 """ 

227 ml_dir.mkdir(parents=True, exist_ok=True) 

228 hashes: dict[str, str] = {} 

229 for name in filenames: 

230 source = version_dir / name 

231 if not source.exists(): 

232 continue 

233 destination = ml_dir / name 

234 shutil.copy2(source, destination) 

235 hashes[name] = _sha256_file(destination) 

236 return hashes 

237 

238 

239def restore_active_from_version( 

240 version_dir: Path, 

241 ml_dir: Path = ML_DIR, 

242 filenames: tuple[str, ...] = ACTIVE_ARTIFACT_FILES, 

243 expected_hashes: dict[str, str] | None = None, 

244) -> dict: 

245 """Rollback primitive - copies version_dir's files into ml/, verifying 

246 sha256 against expected_hashes BEFORE activation if hashes are given. 

247 

248 Returns {"ok": bool, "hashes": {...}, "mismatched": [...]}. Never 

249 partially activates: if any expected hash mismatches, no files are 

250 copied at all. 

251 """ 

252 if expected_hashes: 

253 mismatched = [] 

254 for name, expected in expected_hashes.items(): 

255 source = version_dir / name 

256 if not source.exists(): 

257 mismatched.append(name) 

258 continue 

259 if _sha256_file(source) != expected: 

260 mismatched.append(name) 

261 if mismatched: 

262 return {"ok": False, "hashes": {}, "mismatched": mismatched} 

263 

264 hashes = copy_candidate_to_active(version_dir, ml_dir=ml_dir, filenames=filenames) 

265 # V5.4.7 (Problems.md #124): copy_candidate_to_active() silently skips 

266 # absent files - an entirely-missing version dir previously produced an 

267 # empty copy AND ok=True, so the registry flipped to "active" while ml/ 

268 # still held the PREVIOUS model's weights. A restore that would copy 

269 # nothing now fails instead. 

270 if not hashes: 

271 return {"ok": False, "hashes": {}, "mismatched": [], "reason": "no_artifacts_found"} 

272 return {"ok": True, "hashes": hashes, "mismatched": []} 

273 

274 

275def copy_backtest_report_to_active(version_dir: Path, backtests_dir: Path) -> None: 

276 """Copies a promoted candidate's own strategy_report.json/equity_curves.csv 

277 over the active backtests/strategy_report.json/equity_curves.csv, so the 

278 live dashboard reflects the newly-active model's backtest instead of the 

279 now-archived one.""" 

280 backtests_dir.mkdir(parents=True, exist_ok=True) 

281 for name in ("strategy_report.json", "equity_curves.csv"): 

282 source = version_dir / name 

283 if source.exists(): 

284 shutil.copy2(source, backtests_dir / name)