Coverage for src/romfarmer/farmhand/optimizer/state.py: 0%
71 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"""State schema for the LangGraph budget optimizer loop."""
3from __future__ import annotations
5import operator
6from dataclasses import dataclass, field
7from pathlib import Path
8from typing import Annotated, Any, Literal
10from typing_extensions import TypedDict
12# ---------------------------------------------------------------------------
13# Supplementary dataclasses (not part of LangGraph state directly)
14# ---------------------------------------------------------------------------
17@dataclass
18class PoolEntry:
19 """A single game entry in the pool manifest for one platform.
21 Represents a game (or multi-disc group treated atomically) after the
22 superset build pass. ``size_bytes`` is the total compressed output size
23 for all discs in the group.
24 """
26 name: str
27 rating: float # 0.0 – 1.0 from scraped_games DB; 0.0 if not in DB
28 generation: str # e.g. "gen5", "gen6", "gen7_handheld"
29 size_bytes: int # compressed output size (sum across all discs)
30 multi_disc_group: str | None = None # None → single disc/cart
31 is_disc_anchor: bool = True # True → threshold check applies to this entry
32 platform: str = ""
35@dataclass
36class BuildReport:
37 """Estimated or actual build report for one selection pass.
39 When produced by :func:`estimate_build_size` it is purely in-memory
40 (no disk I/O). When produced after a real organize pass it may be
41 verified against the staging directory.
42 """
44 total_size_bytes: int
45 per_platform_sizes: dict[str, int] = field(default_factory=dict)
46 per_generation_sizes: dict[str, int] = field(default_factory=dict)
47 per_generation_game_counts: dict[str, int] = field(default_factory=dict)
48 per_platform_game_counts: dict[str, int] = field(default_factory=dict)
49 multi_disc_groups_included: int = 0
50 total_game_count: int = 0
51 # Set when this report comes from a real staged directory walk
52 staging_path: Path | None = None
53 is_estimated: bool = True
55 @property
56 def total_size_gb(self) -> float:
57 return self.total_size_bytes / (1024**3)
60@dataclass
61class IterationLog:
62 """Full record of one optimizer iteration."""
64 iteration: int
65 thresholds: dict[str, float]
66 used_bytes: int
67 free_bytes: int
68 delta_bytes: int # used - target_used; >0 = overshoot, <0 = undershoot
69 action: str # human-readable description of what changed
70 critic_rationale: str
71 wall_time_s: float = 0.0
72 is_spike: bool = False # True if large delta despite small threshold change
75@dataclass
76class CriticDecision:
77 """Validated output from the LLM critic node."""
79 thresholds: dict[str, float]
80 rationale: str
81 expected_direction: Literal["grow", "shrink", "hold"]
84@dataclass
85class OptimizerResult:
86 """Final result returned by :func:`run_optimizer`."""
88 verdict: Literal["converged", "exhausted", "infeasible"]
89 final_thresholds: dict[str, float]
90 final_report: BuildReport | None
91 history: list[IterationLog]
92 iterations_used: int
95# ---------------------------------------------------------------------------
96# LangGraph TypedDict state
97# ---------------------------------------------------------------------------
100class BudgetState(TypedDict):
101 """Mutable state threaded through the LangGraph optimizer loop.
103 Immutable fields (set in ``init_builder``, never changed):
104 target_total_bytes, target_free_bytes, tolerance_bytes,
105 max_iterations, build_name, pool_root
107 Mutable per-iteration fields:
108 iteration, thresholds, platform_overrides,
109 last_report, last_used_bytes, last_free_bytes, delta_to_target,
110 no_progress_count, verdict
112 Append-only lists (use ``operator.add`` reducer):
113 history
114 """
116 # ── Immutable targets ───────────────────────────────────────────────────
117 build_name: str
118 pool_root: str # str path so it is JSON-serializable
119 target_total_bytes: int # volume capacity
120 target_free_bytes: int # desired headroom (e.g. 30 GB)
121 tolerance_bytes: int # acceptable overshoot/undershoot of headroom (e.g. 5 GB)
122 max_iterations: int
124 # ── Current thresholds ─────────────────────────────────────────────────
125 # Keys are generation names from CONSOLE_GENERATIONS (e.g. "gen3", "gen5").
126 # Values are min_rating floats in [0.0, 1.0].
127 thresholds: dict[str, float]
128 # Optional per-platform pins that override the generation threshold.
129 platform_overrides: dict[str, float]
131 # ── Last build observation ─────────────────────────────────────────────
132 last_report: Any | None # BuildReport (Any to keep TypedDict serializable)
133 last_used_bytes: int
134 last_free_bytes: int # = target_total - last_used
135 delta_to_target: int # last_used - (target_total - target_free); + = overshoot
137 # ── Loop counters ──────────────────────────────────────────────────────
138 iteration: int
139 no_progress_count: int
140 verdict: str | None # None | "converged" | "exhausted" | "infeasible"
142 # ── Pool capacity snapshot (set in init_builder, immutable) ─────────────
143 # Max bytes available per generation if threshold were 0.0
144 per_generation_max_bytes: dict[str, int]
145 # Actual max rating observed per generation in the pool
146 per_generation_max_rating: dict[str, float]
148 # ── Append-only iteration log ──────────────────────────────────────────
149 history: Annotated[list[Any], operator.add]