Coverage for evaluation/generation_registry.py: 100%

134 statements  

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

1"""Which model generations exist and what each may hold (V6.6.1): the registry `ml/generations/registry.json`, the owner's admission rule R-ADMIT1, and a hash-chained log. 

2 

3A refit of a frozen procedure is a new vintage of the same generation, so `procedure_sha256` hashes the procedure (trainer code, features, label, seeds), not the weights. A new 

4procedure is a new candidate and goes through a research round. Real money is outside this file: nothing here touches a broker setting or a live flag. 

5 

6Stdlib only at import, apart from the project's own hash chain. 

7""" 

8 

9from __future__ import annotations 

10 

11import json 

12from collections.abc import Mapping 

13from dataclasses import asdict, dataclass, field 

14from pathlib import Path 

15from typing import Any 

16 

17from audit.hash_chain import GENESIS_HASH, compute_entry_hash, verify_chain 

18 

19# On the book, in order: gaining capital, a settled holder, still earning but falling short of its claim, on its way out. Several generations can sit in these at once. 

20STAGES = ("candidate", "frozen", "shadow", "ramping", "active", "fading", "winding_down", "retired", "rejected") 

21BOOK_STAGES = ("ramping", "active", "fading", "winding_down") 

22SETTLED_SESSIONS = 252 

23TIERS = ("installed", "tier1", "tier2", "none") 

24TIER2_MIN_SESSIONS = 60 

25SPENT_HOLDOUT_MIN_SESSIONS = 252 

26TIER2_MAX_NO_DATA = 0.10 

27CAP_LIFT_CHECKPOINTS = (252, 504, 756) 

28CAP_LIFT_ALPHA_T = 2.0 

29LIFECYCLE_EVENT = "generation_lifecycle" 

30 

31 

32@dataclass(frozen=True) 

33class Generation: 

34 """One model generation in the registry: its kind, admission tier, lifecycle stage, definition and admission evidence.""" 

35 id: str 

36 kind: str 

37 tier: str 

38 stage: str 

39 born: str 

40 procedure_sha256: str 

41 definition: Mapping = field(default_factory=dict) 

42 freeze_path: str | None = None 

43 needs: str | None = None 

44 vintages: tuple[str, ...] = () 

45 expected_sharpe: float = 0.0 

46 note: str = "" 

47 admission: Mapping = field(default_factory=dict) # selection_pass, hold_pass, edge_pass: set once, by a round's stored verdict 

48 

49 

50@dataclass(frozen=True) 

51class AdmissionEvidence: 

52 """What the admission rule (R-ADMIT1) reads about a generation: its selection, hold and edge passes, forward record, decay state and guard.""" 

53 selection_pass: bool = False 

54 hold_pass: bool = False 

55 edge_pass: bool = False 

56 holdouts_spent: bool = False 

57 forward_ok_sessions: int = 0 

58 no_data_share: float = 0.0 

59 mean_diff_vs_incumbent: float | None = None 

60 guard_tripped: bool = False 

61 decay_state: str = "healthy" 

62 forward_alpha_t: float | None = None 

63 score: float | None = None # shrunk Sharpe (`portfolio.generation_blend.shrunk_sharpe`); a generation short of its claim can still be earning 

64 

65 

66def load_registry(path: Path) -> dict[str, Generation]: 

67 """Read `ml/generations/registry.json` into `Generation` records by name, refusing an unknown stage.""" 

68 raw = json.loads(Path(path).read_text(encoding="utf-8")) 

69 out: dict[str, Generation] = {} 

70 for entry in raw["generations"]: 

71 if entry["stage"] not in STAGES: 

72 raise ValueError(f"{entry['id']}: unknown stage {entry['stage']!r}") 

73 if entry["tier"] not in TIERS: 

74 raise ValueError(f"{entry['id']}: unknown tier {entry['tier']!r}") 

75 out[entry["id"]] = Generation(**{**entry, "vintages": tuple(entry.get("vintages") or ())}) 

76 return out 

77 

78 

79def save_registry(path: Path, generations: Mapping[str, Generation]) -> None: 

80 """Atomic, sorted, LF: one registry has one hash, and a crash can't leave half a file.""" 

81 path = Path(path) 

82 payload = {"note": "Which generations exist. `aq cycle promote` changes a stage by rule; a hand edit is visible in git.", "generations": [ 

83 {**asdict(generations[name]), "vintages": list(generations[name].vintages)} for name in sorted(generations) 

84 ]} 

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

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

87 temporary.write_text(json.dumps(payload, indent=1, sort_keys=True) + "\n", encoding="utf-8", newline="\n") 

88 temporary.replace(path) 

89 

90 

91def _tier2_forward_passes(evidence: AdmissionEvidence) -> bool: 

92 """R-ADMIT1's 60-session test. A zero-alpha candidate passes it about half the time, so the 30% cap is what bounds a false pass.""" 

93 difference = evidence.mean_diff_vs_incumbent 

94 return ( 

95 evidence.forward_ok_sessions >= TIER2_MIN_SESSIONS and difference is not None and difference == difference and difference >= 0.0 

96 and not evidence.guard_tripped and evidence.no_data_share <= TIER2_MAX_NO_DATA 

97 ) 

98 

99 

100def admitted_to_shadow(evidence: AdmissionEvidence) -> bool: 

101 """Selection and the one holdout read; or, once the holdouts are spent, selection and a year of forward sessions.""" 

102 if not evidence.selection_pass: 

103 return False 

104 if evidence.hold_pass: 

105 return True 

106 return evidence.holdouts_spent and evidence.forward_ok_sessions >= SPENT_HOLDOUT_MIN_SESSIONS 

107 

108 

109def cap_lifted(evidence: AdmissionEvidence) -> bool: 

110 """A tier-2 generation takes over only on forward alpha, read at fixed checkpoints so the looks are countable.""" 

111 t = evidence.forward_alpha_t 

112 return ( 

113 t is not None and t == t and t >= CAP_LIFT_ALPHA_T and evidence.forward_ok_sessions >= CAP_LIFT_CHECKPOINTS[0] 

114 and evidence.no_data_share <= TIER2_MAX_NO_DATA and not evidence.guard_tripped 

115 ) 

116 

117 

118def _book_stage(stage: str, evidence: AdmissionEvidence) -> str: 

119 """Where a generation on the book belongs. Falling short of its claim isn't the end of it: while its score stays positive it keeps earning a share, at `fading`. It winds down only 

120 once it has stopped earning, and comes back if the record recovers. A stage moves one step at a time.""" 

121 score = evidence.score 

122 earning = score is None or (score == score and score > 0.0) 

123 behind = evidence.decay_state in ("watch", "decaying") 

124 if stage == "ramping": 

125 settled = evidence.forward_ok_sessions >= SETTLED_SESSIONS and evidence.decay_state == "healthy" 

126 return "active" if settled else "ramping" 

127 if stage == "active": 

128 return "fading" if behind or not earning else "active" 

129 if stage == "fading": 

130 if not earning or (evidence.decay_state == "decaying" and score is not None and score <= 0.0): 

131 return "winding_down" 

132 return "active" if not behind else "fading" 

133 return "fading" if earning and evidence.decay_state == "healthy" and score is not None else "winding_down" 

134 

135 

136def next_stage(generation: Generation, evidence: AdmissionEvidence) -> str: 

137 """R-ADMIT1. Moves forward only on evidence, off the book at once on a guard trip or dead state, and never by more than the rule says. Non-finite evidence holds.""" 

138 stage = generation.stage 

139 if stage in ("retired", "rejected"): 

140 return stage 

141 dying = evidence.guard_tripped or evidence.decay_state == "dead" 

142 if stage in BOOK_STAGES: 

143 if dying: 

144 return "retired" 

145 return _book_stage(stage, evidence) 

146 if dying and stage == "shadow": 

147 return "rejected" 

148 if generation.tier == "none": 

149 return stage # observed only (Problems #335): a generation with no selection pass never ramps, whatever a hand-entered record says 

150 if stage in ("candidate", "frozen"): 

151 if evidence.edge_pass: 

152 return "ramping" 

153 return "shadow" if admitted_to_shadow(evidence) else stage 

154 if stage == "shadow": 

155 if evidence.edge_pass or (evidence.selection_pass and _tier2_forward_passes(evidence)): 

156 return "ramping" # a forward pass alone is not enough: the cap on a false pass assumes the selection gate was passed (Problems #335) 

157 return stage 

158 return stage 

159 

160 

161def share_cap(generation: Generation, evidence: AdmissionEvidence, tier2_cap: float = 0.30) -> float: 

162 """What the generation may hold of the paper book: all of it with a full pass or as the installed book, the tier-2 cap until its forward alpha lifts it, otherwise nothing. 

163 A tier-`none` generation is observed only and holds nothing under any evidence (Problems #335): a lifted cap is a tier-2 privilege.""" 

164 if generation.stage in ("retired", "rejected", "candidate", "frozen", "shadow") or generation.tier == "none": 

165 return 0.0 

166 if generation.tier in ("tier1", "installed") or evidence.edge_pass: 

167 return 1.0 

168 if generation.tier == "tier2": 

169 return 1.0 if cap_lifted(evidence) else float(tier2_cap) 

170 return 0.0 

171 

172 

173def read_lifecycle(path: Path) -> list[dict]: 

174 """The lifecycle log's rows, or [] when the file does not exist.""" 

175 path = Path(path) 

176 return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] if path.exists() else [] 

177 

178 

179def append_lifecycle(path: Path, *, event: str, payload: Mapping[str, Any], created_at: str) -> dict[str, Any]: 

180 """A hash-chained line for each change of stage or vintage, so the record of how a generation reached the book can't be edited later without showing.""" 

181 rows = read_lifecycle(path) 

182 previous = rows[-1]["hash"] if rows else GENESIS_HASH 

183 body = {"event": event, **payload} 

184 row = {"prev_hash": previous, "event_type": LIFECYCLE_EVENT, "created_at": created_at, "payload": body} 

185 row["hash"] = compute_entry_hash(previous, LIFECYCLE_EVENT, created_at, body) 

186 path = Path(path) 

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

188 with path.open("a", encoding="utf-8", newline="\n") as handle: 

189 handle.write(json.dumps(row, sort_keys=True) + "\n") 

190 return row 

191 

192 

193def lifecycle_is_intact(path: Path) -> tuple[bool, int | None]: 

194 """Verify the hash chain of the lifecycle log: (valid, index of the first broken row or None).""" 

195 return verify_chain(read_lifecycle(path))