Coverage for src/romfarmer/farmhand/optimizer/thresholds.py: 0%
52 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
1"""Apply optimizer threshold results to build config YAML files.
3The optimizer loop produces per-generation rating thresholds
4(e.g., ``{"gen6": 0.85, "gen7": 0.92}``). This module writes those
5thresholds back into build spec YAML files so the actual build picks
6them up via the ``optimizer_thresholds`` field on :class:`BuildSpec`.
8The YAML is re-serialized with ``yaml.dump`` (comments are not preserved),
9which is an acceptable trade-off for automation. Human-edited build configs
10should commit the result to version control.
11"""
13from __future__ import annotations
15import json
16import logging
17from dataclasses import dataclass
18from pathlib import Path
20import yaml
22logger = logging.getLogger(__name__)
25@dataclass
26class ApplyResult:
27 """Summary of a threshold-apply operation on a single build config."""
29 build_name: str
30 config_path: Path
31 thresholds_written: dict[str, float]
32 previous_thresholds: dict[str, float] | None
33 changed: bool
36def apply_thresholds_to_build(
37 build_path: Path,
38 thresholds: dict[str, float],
39 *,
40 dry_run: bool = False,
41) -> ApplyResult:
42 """Write *thresholds* into a build config YAML file.
44 Reads the file, sets the ``optimizer_thresholds`` top-level key, and
45 writes it back. All other fields are preserved (though comment
46 formatting may be lost on re-serialization).
48 Args:
49 build_path: Absolute path to the build config YAML file.
50 thresholds: Generation → min_rating dict from the optimizer.
51 dry_run: If True, compute what would change but do not write.
53 Returns:
54 :class:`ApplyResult` describing what changed.
55 """
56 if not build_path.exists():
57 raise FileNotFoundError(f"Build config not found: {build_path}")
59 raw = yaml.safe_load(build_path.read_text()) or {}
60 build_name = raw.get("name", build_path.stem)
61 previous = raw.get("optimizer_thresholds")
63 # Strip zero-threshold gens — they're the default and add no value in YAML
64 cleaned = {gen: val for gen, val in thresholds.items() if val > 0.0}
66 changed = cleaned != (previous or {})
68 if changed and not dry_run:
69 if cleaned:
70 raw["optimizer_thresholds"] = cleaned
71 else:
72 raw.pop("optimizer_thresholds", None)
74 build_path.write_text(yaml.dump(raw, default_flow_style=False, sort_keys=False))
75 logger.info(
76 f"Applied thresholds to '{build_name}': "
77 f"{', '.join(f'{k}={v}' for k, v in sorted(cleaned.items()))}"
78 )
79 elif not changed:
80 logger.info(f"No change needed for '{build_name}'")
82 return ApplyResult(
83 build_name=build_name,
84 config_path=build_path,
85 thresholds_written=cleaned,
86 previous_thresholds=previous,
87 changed=changed,
88 )
91def apply_thresholds_to_builds(
92 build_names: list[str],
93 thresholds: dict[str, float],
94 builds_dir: Path | None = None,
95 *,
96 dry_run: bool = False,
97) -> list[ApplyResult]:
98 """Apply *thresholds* to multiple build config YAML files.
100 Args:
101 build_names: Build identifiers (must match ``{name}.yaml`` in
102 *builds_dir*).
103 thresholds: Generation → min_rating dict from the optimizer.
104 builds_dir: Directory containing build config files. Defaults to
105 ``config/builds/`` relative to workspace root.
106 dry_run: If True, no files are written.
108 Returns:
109 List of :class:`ApplyResult`, one per build name.
110 """
111 if builds_dir is None:
112 from romfarmer.core.paths import get_paths
114 builds_dir = get_paths().workspace_root / "config" / "builds"
116 results: list[ApplyResult] = []
117 for name in build_names:
118 path = builds_dir / f"{name}.yaml"
119 if not path.exists():
120 logger.warning(f"Build config not found: {path} — skipping")
121 continue
122 result = apply_thresholds_to_build(path, thresholds, dry_run=dry_run)
123 results.append(result)
125 return results
128def load_thresholds_from_optimizer_log(log_path: Path) -> dict[str, float]:
129 """Read final_thresholds from an optimizer audit log JSON file.
131 Optimizer logs are written to ``output/{build_name}/optimizer.log.json``.
133 Args:
134 log_path: Path to the ``optimizer.log.json`` file.
136 Returns:
137 Generation → threshold dict.
139 Raises:
140 FileNotFoundError: If *log_path* does not exist.
141 KeyError: If the log does not contain ``final_thresholds``.
142 """
143 if not log_path.exists():
144 raise FileNotFoundError(f"Optimizer log not found: {log_path}")
146 with open(log_path) as f:
147 data = json.load(f)
149 if "final_thresholds" not in data:
150 raise KeyError(
151 f"'final_thresholds' not found in optimizer log: {log_path}. "
152 "Make sure the optimizer ran to completion."
153 )
155 return {k: float(v) for k, v in data["final_thresholds"].items()}