Coverage for src/romfarmer/farmhand/optimizer/nodes.py: 0%

148 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-04 16:33 -0700

1"""LangGraph optimizer node functions. 

2 

3Each function corresponds to one graph node. They receive the full 

4:class:`~.state.BudgetState` and return a partial dict that LangGraph 

5merges back into the state. 

6 

7Nodes 

8----- 

9init_builder 

10 Seed the state: load pool manifests, set default thresholds, compute 

11 target headroom, enforce gen3/4 floor. 

12 

13run_build_estimate 

14 Apply current thresholds to the pool → :class:`~.state.BuildReport`, 

15 compute delta, detect multi-disc spikes, append to history. 

16 

17evaluator_critic 

18 Compose LLM payload, call the critic, apply deterministic guards, 

19 return updated thresholds. 

20 

21finalize 

22 Verify final state, emit audit log, return :class:`~.state.OptimizerResult`. 

23""" 

24 

25from __future__ import annotations 

26 

27import dataclasses 

28import json 

29import logging 

30import time 

31from pathlib import Path 

32from typing import Any 

33 

34from .pool import DEFAULT_THRESHOLDS, estimate_build_size, load_pool 

35from .state import BudgetState, BuildReport, CriticDecision, IterationLog 

36 

37logger = logging.getLogger(__name__) 

38 

39# Threshold adjustment must snap to this granularity 

40_STEP_SNAP = 0.05 

41 

42# If the size delta improved by less than this between two iterations, 

43# increment no_progress_count 

44_PROGRESS_THRESHOLD_BYTES = 1 * 1024**3 # 1 GB 

45 

46# Generations the LLM is allowed to adjust (ascending priority = tighten first) 

47_ADJUSTABLE_GENS = ["gen5", "gen5_handheld", "gen6", "gen6_handheld", "gen7", "gen7_handheld"] 

48 

49# Generations that are permanently floored at 0.0 

50_FLOOR_GENS = {"gen3", "gen4", "arcade", "portable", "unknown"} 

51 

52 

53# --------------------------------------------------------------------------- 

54# Node: init_builder 

55# --------------------------------------------------------------------------- 

56 

57 

58def init_builder(state: BudgetState) -> dict[str, Any]: 

59 """Load pool manifests and seed thresholds. 

60 

61 Expected input keys (must be pre-populated by the caller): 

62 build_name, pool_root, target_total_bytes, target_free_bytes, 

63 tolerance_bytes, max_iterations. 

64 

65 Returns partial state update with pool-derived data and seeded thresholds. 

66 """ 

67 pool_root = Path(state["pool_root"]) 

68 pool = load_pool(pool_root) 

69 

70 if not pool: 

71 logger.warning(f"No pool manifests found at {pool_root}. Run collect_pool() first.") 

72 

73 # Discover all generations represented in the pool and compute pool stats 

74 all_gens: set[str] = set() 

75 per_gen_max_bytes: dict[str, int] = {} 

76 per_gen_max_rating: dict[str, float] = {} 

77 for entries in pool.values(): 

78 for e in entries: 

79 all_gens.add(e.generation) 

80 per_gen_max_bytes[e.generation] = per_gen_max_bytes.get(e.generation, 0) + e.size_bytes 

81 cur_max = per_gen_max_rating.get(e.generation, 0.0) 

82 if e.rating > cur_max: 

83 per_gen_max_rating[e.generation] = e.rating 

84 

85 # Seed thresholds: start from defaults, ensure all discovered gens are present 

86 thresholds = {gen: DEFAULT_THRESHOLDS.get(gen, 0.0) for gen in all_gens} 

87 

88 # Business rule: gen3/gen4 always floor to 0.0 on init 

89 for gen in _FLOOR_GENS: 

90 thresholds[gen] = 0.0 

91 

92 # Cap seeded thresholds at the actual max rating in the pool for each generation. 

93 # If the default seed (e.g. 0.9) exceeds all ratings in the pool (max=0.8), 

94 # it would include zero games from that generation — a useless starting point. 

95 for gen in list(thresholds.keys()): 

96 if gen in _FLOOR_GENS: 

97 continue 

98 pool_max = per_gen_max_rating.get(gen, 0.0) 

99 if thresholds[gen] > pool_max: 

100 old = thresholds[gen] 

101 thresholds[gen] = pool_max 

102 logger.info( 

103 f" Capped seed threshold for {gen}: {old:.2f} → {pool_max:.2f} (pool max rating)" 

104 ) 

105 

106 logger.info(f"init_builder: {len(pool)} platforms, generations: {sorted(all_gens)}") 

107 logger.info(f"Seeded thresholds: {thresholds}") 

108 

109 return { 

110 "iteration": 0, 

111 "thresholds": thresholds, 

112 "platform_overrides": state.get("platform_overrides") or {}, 

113 "last_report": None, 

114 "last_used_bytes": 0, 

115 "last_free_bytes": state["target_total_bytes"], 

116 "delta_to_target": -(state["target_total_bytes"] - state["target_free_bytes"]), 

117 "no_progress_count": 0, 

118 "verdict": None, 

119 "history": [], 

120 "per_generation_max_bytes": per_gen_max_bytes, 

121 "per_generation_max_rating": per_gen_max_rating, 

122 } 

123 

124 

125# --------------------------------------------------------------------------- 

126# Node: run_build_estimate 

127# --------------------------------------------------------------------------- 

128 

129 

130def run_build_estimate(state: BudgetState) -> dict[str, Any]: 

131 """Apply current thresholds to pool → BuildReport, compute delta. 

132 

133 This is the tight inner loop — pure in-memory estimation. 

134 """ 

135 t0 = time.time() 

136 

137 pool_root = Path(state["pool_root"]) 

138 pool = load_pool(pool_root) 

139 

140 report: BuildReport = estimate_build_size( 

141 pool=pool, 

142 thresholds=state["thresholds"], 

143 platform_overrides=state.get("platform_overrides") or {}, 

144 ) 

145 

146 target_used = state["target_total_bytes"] - state["target_free_bytes"] 

147 delta = report.total_size_bytes - target_used 

148 free = state["target_total_bytes"] - report.total_size_bytes 

149 

150 # Detect multi-disc capacity spike 

151 iteration = state["iteration"] + 1 

152 prev_delta = state.get("delta_to_target", 0) 

153 prev_abs = abs(prev_delta) 

154 curr_abs = abs(delta) 

155 # Spike: delta got worse or barely improved (<1 GB) after a threshold change 

156 is_spike = ( 

157 iteration > 1 

158 and prev_abs > 0 

159 and (curr_abs > prev_abs * 0.8) # less than 20% improvement 

160 and abs(prev_abs - curr_abs) < 1 * 1024**3 

161 ) 

162 

163 # No-progress detection 

164 no_progress = state.get("no_progress_count", 0) 

165 if iteration > 1: 

166 improvement = prev_abs - curr_abs 

167 if improvement < _PROGRESS_THRESHOLD_BYTES: 

168 no_progress += 1 

169 else: 

170 no_progress = 0 

171 

172 log_entry = IterationLog( 

173 iteration=iteration, 

174 thresholds=dict(state["thresholds"]), 

175 used_bytes=report.total_size_bytes, 

176 free_bytes=free, 

177 delta_bytes=delta, 

178 action=_describe_action(state["thresholds"], state.get("history", [])), 

179 critic_rationale="(initial estimate)" if iteration == 1 else "", 

180 wall_time_s=round(time.time() - t0, 2), 

181 is_spike=is_spike, 

182 ) 

183 

184 gb = report.total_size_bytes / 1024**3 

185 free_gb = free / 1024**3 

186 delta_gb = delta / 1024**3 

187 direction = "OVER" if delta > 0 else "UNDER" 

188 logger.info( 

189 f"[iter {iteration}] used={gb:.1f} GB free={free_gb:.1f} GB " 

190 f"delta={delta_gb:+.1f} GB ({direction})" + (" ⚡ spike" if is_spike else "") 

191 ) 

192 

193 return { 

194 "iteration": iteration, 

195 "last_report": dataclasses.asdict(report), 

196 "last_used_bytes": report.total_size_bytes, 

197 "last_free_bytes": free, 

198 "delta_to_target": delta, 

199 "no_progress_count": no_progress, 

200 "history": [dataclasses.asdict(log_entry)], 

201 } 

202 

203 

204def _describe_action(thresholds: dict[str, float], history: list[Any]) -> str: 

205 """Build a short description of what changed since the previous iteration.""" 

206 if not history: 

207 return "initial" 

208 prev = history[-1] 

209 prev_thresholds = prev.get("thresholds", {}) if isinstance(prev, dict) else {} 

210 changes = [] 

211 for gen, val in thresholds.items(): 

212 prev_val = prev_thresholds.get(gen, val) 

213 if abs(val - prev_val) > 1e-6: 

214 direction = "↑" if val > prev_val else "↓" 

215 changes.append(f"{gen} {prev_val:.2f}{direction}{val:.2f}") 

216 return ", ".join(changes) if changes else "noop" 

217 

218 

219# --------------------------------------------------------------------------- 

220# Node: evaluator_critic 

221# --------------------------------------------------------------------------- 

222 

223 

224def evaluator_critic(state: BudgetState) -> dict[str, Any]: 

225 """Call the LLM critic and apply deterministic guards to proposed thresholds. 

226 

227 Guard pipeline (applied AFTER LLM output, BEFORE state update): 

228 1. Clamp all thresholds to [0.0, 1.0]. 

229 2. Floor gen3/gen4/arcade/portable/unknown to 0.0. 

230 3. Snap all changes to multiples of _STEP_SNAP (0.05). 

231 4. Hierarchy invariant: 

232 - If overshoot: reject any thresholds that lower a generation value 

233 compared to the previous iteration (critic should only tighten on overshoot). 

234 - If undershoot: reject any thresholds that raise a gen6/gen7 value 

235 if gen5 is not yet at 0.0 (must exhaust gen5 first). 

236 5. Multi-disc spike half-step: if last iteration was a spike, cap the 

237 maximum change magnitude at _STEP_SNAP / 2 (0.025, then snap to 0.05). 

238 """ 

239 from .llm_client import call_critic 

240 from .prompts import CRITIC_SYSTEM_PROMPT, build_user_payload 

241 

242 target_used = state["target_total_bytes"] - state["target_free_bytes"] 

243 delta = state["delta_to_target"] 

244 

245 history_raw = state.get("history", []) 

246 # Re-hydrate from dict to IterationLog for prompts helper 

247 history_logs = [_dict_to_iterlog(h) for h in history_raw] 

248 

249 report_dict = state.get("last_report") or {} 

250 per_gen_sizes = report_dict.get("per_generation_sizes", {}) 

251 per_gen_counts = report_dict.get("per_generation_game_counts", {}) 

252 

253 payload = build_user_payload( 

254 iteration=state["iteration"], 

255 target_used_bytes=target_used, 

256 actual_used_bytes=state["last_used_bytes"], 

257 thresholds=state["thresholds"], 

258 per_generation_sizes=per_gen_sizes, 

259 per_generation_game_counts=per_gen_counts, 

260 per_generation_max_bytes=state.get("per_generation_max_bytes") or {}, 

261 history_tail=history_logs, 

262 ) 

263 

264 decision: CriticDecision = call_critic(CRITIC_SYSTEM_PROMPT, payload) 

265 logger.info(f" Critic: {decision.rationale[:120]}") 

266 

267 # ── Deterministic guards ──────────────────────────────────────────────── 

268 guarded = _apply_guards( 

269 proposed=decision.thresholds, 

270 current=state["thresholds"], 

271 delta_bytes=delta, 

272 history=history_raw, 

273 ) 

274 

275 return {"thresholds": guarded} 

276 

277 

278def _dict_to_iterlog(d: Any) -> IterationLog: 

279 if isinstance(d, IterationLog): 

280 return d 

281 if isinstance(d, dict): 

282 return IterationLog( 

283 iteration=d.get("iteration", 0), 

284 thresholds=d.get("thresholds", {}), 

285 used_bytes=d.get("used_bytes", 0), 

286 free_bytes=d.get("free_bytes", 0), 

287 delta_bytes=d.get("delta_bytes", 0), 

288 action=d.get("action", ""), 

289 critic_rationale=d.get("critic_rationale", ""), 

290 wall_time_s=d.get("wall_time_s", 0.0), 

291 is_spike=d.get("is_spike", False), 

292 ) 

293 return IterationLog(0, {}, 0, 0, 0, "", "") 

294 

295 

296def _apply_guards( 

297 proposed: dict[str, float], 

298 current: dict[str, float], 

299 delta_bytes: int, 

300 history: list[Any], 

301) -> dict[str, float]: 

302 """Deterministic post-LLM guards — delegates to ``romfarmer.intent.guards``.""" 

303 from romfarmer.intent.guards import apply_guards 

304 

305 return apply_guards( 

306 proposed, current, delta_bytes, history, floor_keys=frozenset(_FLOOR_GENS), step=_STEP_SNAP 

307 ) 

308 

309 

310# --------------------------------------------------------------------------- 

311# Node: finalize 

312# --------------------------------------------------------------------------- 

313 

314 

315def finalize(state: BudgetState) -> dict[str, Any]: 

316 """Verify convergence, write audit log, determine final verdict. 

317 

318 Verification checks (programmatic — no LLM involvement): 

319 1. Build report size matches pool estimate within 1 MB. 

320 2. All gen3/gen4/floor thresholds remain at 0.0. 

321 3. Generation hierarchy invariant: for adjustable generations in priority 

322 order, a younger generation's threshold must be >= older generation's 

323 (unless it's a floor gen). 

324 4. Final headroom within tolerance. 

325 """ 

326 delta = state.get("delta_to_target", 0) 

327 tol = state["tolerance_bytes"] 

328 

329 # Determine verdict 

330 verdict = state.get("verdict") 

331 if verdict is None: 

332 if abs(delta) <= tol: 

333 verdict = "converged" 

334 elif state["iteration"] >= state["max_iterations"]: 

335 verdict = "exhausted" 

336 elif state.get("no_progress_count", 0) >= 2: 

337 verdict = "exhausted" 

338 else: 

339 verdict = "infeasible" 

340 

341 # Programmatic verification 

342 warnings: list[str] = [] 

343 

344 # Check 1: floor thresholds 

345 final_t = state.get("thresholds", {}) 

346 for gen in _FLOOR_GENS: 

347 if gen in final_t and final_t[gen] > 1e-6: 

348 warnings.append(f"WARN: floor gen {gen} has threshold {final_t[gen]} (should be 0.0)") 

349 

350 # Check 2: hierarchy invariant (gen5 <= gen6) 

351 gen5_val = max(final_t.get("gen5", 0.0), final_t.get("gen5_handheld", 0.0)) 

352 gen6_val = min( 

353 final_t.get("gen6", 1.0), 

354 final_t.get("gen6_handheld", 1.0), 

355 final_t.get("gen7", 1.0), 

356 final_t.get("gen7_handheld", 1.0), 

357 ) 

358 if gen5_val > gen6_val + 1e-6: 

359 warnings.append( 

360 f"WARN: gen5 threshold ({gen5_val:.2f}) > gen6 threshold ({gen6_val:.2f}) — " 

361 "hierarchy violated" 

362 ) 

363 

364 # Check 3: headroom 

365 free_gb = state.get("last_free_bytes", 0) / 1024**3 

366 state["target_free_bytes"] / 1024**3 

367 if abs(delta) > tol and verdict == "converged": 

368 warnings.append( 

369 f"WARN: verdict=converged but |delta|={abs(delta) / 1024**3:.1f} GB > " 

370 f"tolerance={tol / 1024**3:.1f} GB" 

371 ) 

372 

373 for w in warnings: 

374 logger.warning(w) 

375 

376 # Write audit log 

377 _write_audit_log(state, verdict, warnings) 

378 

379 delta_gb = delta / 1024**3 

380 logger.info( 

381 f"finalize: verdict={verdict}, iterations={state['iteration']}, " 

382 f"free={free_gb:.1f} GB, delta={delta_gb:+.1f} GB" 

383 ) 

384 

385 return {"verdict": verdict} 

386 

387 

388def _write_audit_log(state: BudgetState, verdict: str, warnings: list[str]) -> None: 

389 """Write a JSON audit log to output/{build_name}/optimizer.log.json.""" 

390 try: 

391 from romfarmer.core.paths import get_paths 

392 

393 output_dir = get_paths().workspace_root / "output" / state["build_name"] 

394 output_dir.mkdir(parents=True, exist_ok=True) 

395 log_path = output_dir / "optimizer.log.json" 

396 payload = { 

397 "build_name": state["build_name"], 

398 "verdict": verdict, 

399 "iterations": state["iteration"], 

400 "final_thresholds": state.get("thresholds", {}), 

401 "final_used_gb": round(state.get("last_used_bytes", 0) / 1024**3, 2), 

402 "final_free_gb": round(state.get("last_free_bytes", 0) / 1024**3, 2), 

403 "delta_gb": round(state.get("delta_to_target", 0) / 1024**3, 2), 

404 "warnings": warnings, 

405 "history": state.get("history", []), 

406 } 

407 with open(log_path, "w") as f: 

408 json.dump(payload, f, indent=2, default=str) 

409 logger.info(f"Audit log: {log_path}") 

410 except Exception as e: 

411 logger.warning(f"Could not write audit log: {e}")