Coverage for src/romfarmer/planner/passes/budget.py: 85%

46 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""budget pass — size-based selection. 

2 

3Selects the highest-rated games that fit within 

4``manifest.effective_budget_bytes``. 

5 

6Algorithm (mirrors ``SelectionFilter.RATING_BUDGET`` strategy): 

71. Sort units by rating descending, then by ``canonical_name`` asc for stability. 

8 Units with ``rating=None`` are ranked per ``manifest.budget_unrated_as`` 

9 (default: the per-platform median of rated units). 

102. Greedily accumulate units until adding the next unit would exceed the budget. 

11 Multi-disc sets are atomic (all-or-nothing: ``GameUnit.source_size`` sums all 

12 discs). 

133. Units beyond the budget are removed with a reason that includes predicted 

14 cumulative size. 

15 

16If ``manifest.effective_budget_bytes`` is ``None``, this pass is a no-op. 

17 

18The pass uses ``CostModel.predict_output_bytes`` for size estimation. 

19""" 

20 

21from __future__ import annotations 

22 

23from typing import TYPE_CHECKING 

24 

25from romfarmer.ir.catalog import Catalog, GameUnit, PassResult, PassTrace, UnitId 

26 

27if TYPE_CHECKING: 

28 from romfarmer.analysis.knowledge import KnowledgeBase 

29 from romfarmer.ir.manifest import BuildManifest 

30 from romfarmer.planner.costmodel import CostModel 

31 

32PASS_NAME = "budget" 

33 

34 

35def _rank(unit: GameUnit, unrated_rank: float) -> float: 

36 return unit.rating if unit.rating is not None else unrated_rank 

37 

38 

39def _median(values: list[float]) -> float: 

40 vs = sorted(values) 

41 n = len(vs) 

42 return vs[n // 2] if n % 2 else (vs[n // 2 - 1] + vs[n // 2]) / 2.0 

43 

44 

45def run( 

46 catalog: Catalog, 

47 manifest: BuildManifest, 

48 kb: KnowledgeBase, 

49 cost_model: CostModel, 

50) -> PassResult: 

51 """Greedily keep top-rated units within budget. 

52 

53 Unrated units are ranked per ``manifest.budget_unrated_as``: ``"median"`` 

54 (default) places them at the per-platform median of the rated units in the 

55 catalog entering this pass, so trimming removes genuinely low-rated 

56 content first and unrated content only when the budget reaches the middle. 

57 ``"worst"`` reproduces the old ``-inf`` behaviour. The median used is 

58 recorded in ``PassTrace.notes``. 

59 

60 The surviving catalog is returned in selection order (rating descending) 

61 so the executor's stop-early guard trims from the bottom, not 

62 alphabetically. 

63 """ 

64 budget = manifest.effective_budget_bytes 

65 if budget is None: 

66 return PassResult( 

67 catalog=catalog, 

68 trace=PassTrace(pass_name=PASS_NAME, removed=(), added=()), 

69 ) 

70 

71 platform = str(catalog.platform or manifest.platform or "") 

72 tool = manifest.chain[0] if manifest.chain else None 

73 

74 unrated_rank = manifest.unrated_rank() 

75 notes: list[str] = [] 

76 if unrated_rank is None: 

77 rated = [u.rating for u in catalog.units if u.rating is not None] 

78 unrated_rank = _median(rated) if rated else 0.0 

79 notes.append( 

80 f"unrated_as=median → {unrated_rank:.3f} (n_rated={len(rated)}/{len(catalog.units)})" 

81 ) 

82 else: 

83 notes.append(f"unrated_as={manifest.budget_unrated_as}") 

84 

85 sorted_units = sorted(catalog.units, key=lambda u: (-_rank(u, unrated_rank), u.canonical_name)) 

86 accumulated = 0 

87 kept: list[GameUnit] = [] 

88 removed: list[tuple[UnitId, str]] = [] 

89 labels: set[str] = set() 

90 

91 for unit in sorted_units: 

92 source_bytes = unit.source_size 

93 try: 

94 predicted, label = cost_model.predict_output_bytes(source_bytes, platform, tool) 

95 except Exception: 

96 # No prior at all — use source size as a pessimistic estimate 

97 predicted = source_bytes 

98 label = "fallback:source_size" 

99 labels.add(label) 

100 

101 if accumulated + predicted <= budget: 

102 kept.append(unit) 

103 accumulated += predicted 

104 else: 

105 removed.append( 

106 ( 

107 unit.unit_id, 

108 f"budget: adding {predicted:,} bytes (cumulative {accumulated:,}) " 

109 f"would exceed {budget:,} [{label}]", 

110 ) 

111 ) 

112 

113 notes.append( 

114 f"predicted_bytes={accumulated} budget={budget} tool={tool} [{', '.join(sorted(labels))}]" 

115 ) 

116 if removed: 

117 cut = [_rank(u, unrated_rank) for u in sorted_units if u.unit_id in {r[0] for r in removed}] 

118 notes.append( 

119 f"budget trimmed {len(removed)} units ranked {min(cut):.2f}–{max(cut):.2f} " 

120 f"(lowest-ranked first; unrated ranked at {unrated_rank:.2f})" 

121 ) 

122 new_catalog = Catalog(platform=catalog.platform, units=tuple(kept), warnings=catalog.warnings) 

123 return PassResult( 

124 catalog=new_catalog, 

125 trace=PassTrace( 

126 pass_name=PASS_NAME, 

127 removed=tuple(removed), 

128 added=(), 

129 notes=tuple(notes), 

130 ), 

131 )