Coverage for retraining/artifact_pins.py: 100%

45 statements  

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

1"""Pins of the installed model artifacts (V6.6.9, #382): one sha256 per file `main.py` loads. 

2 

3The models, their schemas and the scaler are one set: a scaler refitted on other data leaves every file readable and 

4every input mis-scaled. Nothing compared them, so a rewritten `ml/scaler_stats.json` went unnoticed for as long as the 

5shipped book did not read the models. `ml/artifact_pins.json` records the set; anything that scores with the models 

6checks it first and refuses on a difference. 

7 

8Stdlib only. 

9""" 

10 

11from __future__ import annotations 

12 

13import hashlib 

14import json 

15from collections.abc import Mapping 

16from pathlib import Path 

17 

18EXPERTS = ("bullish", "bearish", "sideways", "volatility") 

19# What `main.py` loads (its `_ensure_ready`), relative to `ml/`. A file that does not exist is not pinned. 

20PINNED_FILES: tuple[str, ...] = ( 

21 "model_weights.json", "feature_schema.json", "scaler_stats.json", 

22 "multitask_model.json", "multitask_feature_schema.json", 

23 "sequence_model.json", "sequence_feature_schema.json", 

24 "gating_model.json", "gating_feature_schema.json", 

25 "topology_model.json", "topology_feature_schema.json", 

26 "rl_sizing_model.json", 

27 *(f"expert_models/{name}/{file}" for name in EXPERTS for file in ("model_weights.json", "multitask_model.json")), 

28) 

29NOTE = "sha256 of the installed model artifacts, one set (retraining/artifact_pins.py). Rewritten only by an install or a restore." 

30 

31 

32def file_sha256(path: Path) -> str: 

33 """The sha256 of a file's bytes.""" 

34 return hashlib.sha256(Path(path).read_bytes()).hexdigest() 

35 

36 

37def compute_artifact_pins(ml_dir: Path | str, files: tuple[str, ...] = PINNED_FILES) -> dict[str, str]: 

38 """{relative path: sha256} of every pinned file that exists under `ml_dir`.""" 

39 ml_dir = Path(ml_dir) 

40 return {name: file_sha256(ml_dir / name) for name in files if (ml_dir / name).is_file()} 

41 

42 

43def write_artifact_pins(ml_dir: Path | str, path: Path | str) -> dict[str, str]: 

44 """Record the current set at `path` (atomic, sorted, LF) and return it.""" 

45 pins = compute_artifact_pins(ml_dir) 

46 path = Path(path) 

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

48 temporary = path.with_name(path.name + ".tmp") 

49 temporary.write_text(json.dumps({"note": NOTE, "files": pins}, indent=1, sort_keys=True) + "\n", encoding="utf-8", newline="\n") 

50 temporary.replace(path) 

51 return pins 

52 

53 

54def load_artifact_pins(path: Path | str) -> dict[str, str]: 

55 """The recorded set, or {} when there is no readable record.""" 

56 try: 

57 payload = json.loads(Path(path).read_text(encoding="utf-8")) 

58 except (OSError, ValueError): 

59 return {} 

60 files = payload.get("files") if isinstance(payload, Mapping) else None 

61 return {str(name): str(digest) for name, digest in files.items()} if isinstance(files, Mapping) else {} 

62 

63 

64def check_artifact_pins(ml_dir: Path | str, pins: Mapping[str, str]) -> list[str]: 

65 """The pinned files that are missing or no longer match, sorted. [] is a healthy set; an empty record pins nothing, 

66 so a caller that requires a record must check for one itself (`artifact_problems`).""" 

67 ml_dir = Path(ml_dir) 

68 return sorted(name for name, digest in pins.items() if not (ml_dir / name).is_file() or file_sha256(ml_dir / name) != digest) 

69 

70 

71def snapshot_active(ml_dir: Path | str, destination: Path | str) -> Path: 

72 """Zip the active artifact set (every pinned file that exists, and the pin record) to `destination` before anything is retrained, so a 

73 retrain that stops half way can never leave the models without the scaler they were fitted with (#382).""" 

74 import zipfile 

75 

76 ml_dir, destination = Path(ml_dir), Path(destination) 

77 destination.parent.mkdir(parents=True, exist_ok=True) 

78 names = [*compute_artifact_pins(ml_dir), *(["artifact_pins.json"] if (ml_dir / "artifact_pins.json").is_file() else [])] 

79 with zipfile.ZipFile(destination, "w", zipfile.ZIP_DEFLATED) as archive: 

80 for name in names: 

81 archive.write(ml_dir / name, f"ml/{name}") 

82 return destination 

83 

84 

85def artifact_problems(ml_dir: Path | str, pins_path: Path | str) -> list[str]: 

86 """Why the installed models may not be scored with, as messages: no record, or the files that differ from it.""" 

87 pins = load_artifact_pins(pins_path) 

88 if not pins: 

89 return [f"no artifact pins at {Path(pins_path).name}"] 

90 return [f"{name} does not match its pin" for name in check_artifact_pins(ml_dir, pins)]