Coverage for src/romfarmer/farmhand/optimizer/graph.py: 0%
75 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-04 16:33 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-04 16:33 -0700
1"""Budget-optimizer loop and top-level run_optimizer() entry point.
3LEGACY: this in-process evaluator-optimizer (LLM critic over a pool collected
4from a prior superset build) is superseded by the intent loop
5(``romfarmer.intent``: agent proposes a Spec, ``dry_run`` over cached catalogs,
6``validate_spec`` applies the same guards). Kept for ``romfarmer farmhand
7optimize`` until that command is retargeted; LangGraph is no longer required.
8"""
10from __future__ import annotations
12import logging
13from pathlib import Path
14from typing import Any
16from .nodes import evaluator_critic, finalize, init_builder, run_build_estimate
17from .pool import collect_pool as _collect_pool
18from .state import BudgetState, IterationLog, OptimizerResult
20logger = logging.getLogger(__name__)
23# ---------------------------------------------------------------------------
24# Conditional edge routing
25# ---------------------------------------------------------------------------
28def route_after_build(state: BudgetState) -> str:
29 """Decide the next node after run_build_estimate.
31 Returns:
32 "done" → finalize (within tolerance)
33 "exhausted" → finalize (max iterations or stall)
34 "critic" → evaluator_critic (needs adjustment)
35 """
36 delta = state.get("delta_to_target", 0)
37 tol = state["tolerance_bytes"]
39 if abs(delta) <= tol:
40 logger.info(f" route: converged (|delta|={abs(delta) / 1024**3:.2f} GB ≤ tol)")
41 return "done"
43 if state["iteration"] >= state["max_iterations"]:
44 logger.info(f" route: exhausted (max_iterations={state['max_iterations']} reached)")
45 return "exhausted"
47 if state.get("no_progress_count", 0) >= 2:
48 logger.info(" route: exhausted (no_progress_count >= 2)")
49 return "exhausted"
51 return "critic"
54# ---------------------------------------------------------------------------
55# Graph builder
56# ---------------------------------------------------------------------------
59class _OptimizerLoop:
60 """The former LangGraph graph as a plain loop (intent brief v3 Q4: LangGraph dropped).
62 Topology::
64 init_builder → run_build_estimate ─┬─ done/exhausted → finalize
65 └─ critic → evaluator_critic → run_build_estimate
66 """
68 def invoke(self, state: dict[str, Any]) -> dict[str, Any]:
69 state = dict(state)
70 state.update(init_builder(state)) # type: ignore[arg-type]
71 while True:
72 state.update(run_build_estimate(state)) # type: ignore[arg-type]
73 route = route_after_build(state) # type: ignore[arg-type]
74 if route in ("done", "exhausted"):
75 break
76 state.update(evaluator_critic(state)) # type: ignore[arg-type]
77 state.update(finalize(state)) # type: ignore[arg-type]
78 return state
81def build_optimizer_graph() -> _OptimizerLoop:
82 """Return the optimizer loop (kept for callers that used the LangGraph app's ``.invoke``)."""
83 return _OptimizerLoop()
86def run_optimizer(
87 build_name: str,
88 target_total_bytes: int,
89 target_free_bytes: int = 30 * 1024**3,
90 tolerance_bytes: int = 5 * 1024**3,
91 max_iterations: int = 8,
92 pool_root: Path | None = None,
93 platform_overrides: dict[str, float] | None = None,
94 collect_pool_first: bool = False,
95 output_base: Path | None = None,
96) -> OptimizerResult:
97 """Run the (legacy, in-process) budget optimizer loop.
99 Args:
100 build_name: Name of the build (used to locate pool manifests and
101 write the audit log).
102 target_total_bytes: Total capacity of the target volume in bytes.
103 target_free_bytes: Desired free headroom after the build (e.g. 30 GB).
104 tolerance_bytes: Acceptable deviation from ``target_free_bytes``
105 on either side (e.g. ±5 GB).
106 max_iterations: Hard cap on the number of critic-adjust cycles.
107 pool_root: Path to the ``.pool`` directory containing platform
108 manifests. Defaults to
109 ``output/{build_name}/.pool``.
110 platform_overrides: Optional per-platform threshold pins that take
111 precedence over the generation threshold.
112 collect_pool_first: If True, run :func:`~.pool.collect_pool` to
113 (re-)generate pool manifests before optimizing.
114 Requires ``output_base`` to point to the superset
115 build output.
116 output_base: Only needed when ``collect_pool_first=True``.
118 Returns:
119 :class:`~.state.OptimizerResult` with verdict, final thresholds,
120 final report, and full iteration history.
121 """
122 from romfarmer.core.paths import get_paths
124 workspace = get_paths().workspace_root
126 if pool_root is None:
127 pool_root = workspace / "output" / build_name / ".pool"
129 if collect_pool_first:
130 if output_base is None:
131 output_base = workspace / "output"
132 logger.info(f"Collecting pool manifest from {output_base / build_name} …")
133 _collect_pool(build_name=build_name, output_base=output_base, workspace_root=workspace)
135 if not pool_root.exists():
136 raise FileNotFoundError(
137 f"Pool root not found: {pool_root}\n"
138 "Run collect_pool() first or pass collect_pool_first=True."
139 )
141 # ── Pre-check: is the target achievable at all? ────────────────────────
142 from .pool import estimate_build_size, load_pool
144 _pool = load_pool(pool_root)
145 _max_report = estimate_build_size(_pool, {}) # all thresholds = 0.0
146 _target_used = target_total_bytes - target_free_bytes
147 if _max_report.total_size_bytes < _target_used - tolerance_bytes:
148 _max_gb = _max_report.total_size_bytes / 1024**3
149 _tgt_gb = _target_used / 1024**3
150 logger.warning(
151 f"Pool capacity {_max_gb:.1f} GB is less than target {_tgt_gb:.1f} GB. "
152 f"Optimizer will run but cannot reach target — reporting best-effort result."
153 )
155 app = build_optimizer_graph()
157 initial_state: dict[str, Any] = {
158 "build_name": build_name,
159 "pool_root": str(pool_root),
160 "target_total_bytes": target_total_bytes,
161 "target_free_bytes": target_free_bytes,
162 "tolerance_bytes": tolerance_bytes,
163 "max_iterations": max_iterations,
164 # Remaining fields are seeded by init_builder
165 "thresholds": {},
166 "platform_overrides": platform_overrides or {},
167 "last_report": None,
168 "last_used_bytes": 0,
169 "last_free_bytes": target_total_bytes,
170 "delta_to_target": -(target_total_bytes - target_free_bytes),
171 "iteration": 0,
172 "no_progress_count": 0,
173 "verdict": None,
174 "history": [],
175 "per_generation_max_bytes": {},
176 "per_generation_max_rating": {},
177 }
179 logger.info(
180 f"Starting optimizer: build={build_name}, "
181 f"target={target_total_bytes / 1024**3:.0f} GB, "
182 f"headroom={target_free_bytes / 1024**3:.0f} GB ±{tolerance_bytes / 1024**3:.0f} GB, "
183 f"max_iter={max_iterations}"
184 )
186 final_state = app.invoke(initial_state)
188 # Re-hydrate history from dicts to IterationLog objects
189 history = [_dict_to_iterlog(h) for h in (final_state.get("history") or [])]
191 from .state import BuildReport
193 last_report_dict = final_state.get("last_report")
194 last_report: BuildReport | None = None
195 if last_report_dict:
196 try:
197 last_report = BuildReport(**last_report_dict)
198 except Exception:
199 pass
201 return OptimizerResult(
202 verdict=final_state.get("verdict") or "infeasible",
203 final_thresholds=final_state.get("thresholds", {}),
204 final_report=last_report,
205 history=history,
206 iterations_used=final_state.get("iteration", 0),
207 )
210def _dict_to_iterlog(d: Any) -> IterationLog:
211 if isinstance(d, IterationLog):
212 return d
213 if isinstance(d, dict):
214 return IterationLog(
215 iteration=d.get("iteration", 0),
216 thresholds=d.get("thresholds", {}),
217 used_bytes=d.get("used_bytes", 0),
218 free_bytes=d.get("free_bytes", 0),
219 delta_bytes=d.get("delta_bytes", 0),
220 action=d.get("action", ""),
221 critic_rationale=d.get("critic_rationale", ""),
222 wall_time_s=d.get("wall_time_s", 0.0),
223 is_spike=d.get("is_spike", False),
224 )
225 return IterationLog(0, {}, 0, 0, 0, "", "")