Coverage for src/romfarmer/ir/catalog.py: 90%

77 statements  

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

1"""Catalog — the typed game-unit layer of the ROM Farmer IR. 

2 

3After CATALOG phase, no downstream component sees individual disc files. 

4Multi-disc atomicity is structural: grouping happens once in ``CatalogBuilder`` 

5(Phase 3); the only way to reach a ``DiscRef`` is through its parent 

6``GameUnit``. See docs/compiler-refactor/04-edge-case-designs.md §1. 

7""" 

8 

9from __future__ import annotations 

10 

11import hashlib 

12from collections.abc import Set as AbstractSet 

13from dataclasses import dataclass 

14from pathlib import Path 

15from typing import NewType 

16 

17from .identity import Identity 

18 

19PlatformId = NewType("PlatformId", str) 

20UnitId = NewType("UnitId", str) # stable: sha1(f"{platform}:{canonical_name}") 

21 

22 

23@dataclass(frozen=True, slots=True) 

24class SourceRef: 

25 """A source file with its platform context.""" 

26 

27 path: Path 

28 platform: PlatformId 

29 

30 

31@dataclass(frozen=True, slots=True) 

32class DiscRef: 

33 """One disc within a (possibly multi-disc) game. 

34 

35 Single-disc games are represented as a 1-tuple of ``DiscRef`` — there is 

36 no "loose file" concept in the IR. 

37 """ 

38 

39 index: int # 1-based disc number 

40 source: SourceRef 

41 identity: Identity 

42 dat_name: str | None = None # canonical DAT entry for THIS disc 

43 

44 

45@dataclass(frozen=True, slots=True) 

46class GameUnit: 

47 """The atomic unit of selection and scheduling: one game (N discs). 

48 

49 Invariants (enforced in ``__post_init__``): 

50 - ``discs`` must contain at least one ``DiscRef``. 

51 - ``discs`` must be sorted by ``index`` in ascending order. 

52 

53 Non-contiguous indices are *not* rejected here — that is a 

54 ``CatalogBuilder`` policy (quarantine + ``CatalogWarning``), not a unit 

55 invariant. 

56 """ 

57 

58 unit_id: UnitId 

59 platform: PlatformId 

60 canonical_name: str # disc-tag-stripped normalised name 

61 discs: tuple[DiscRef, ...] # INVARIANT: len >= 1, sorted by index 

62 region: frozenset[str] = frozenset() 

63 languages: frozenset[str] = frozenset() 

64 rating: float | None = None 

65 tier: int | None = None 

66 generation: str | None = None 

67 

68 def __post_init__(self) -> None: 

69 if not self.discs: 

70 raise ValueError("GameUnit.discs must not be empty") 

71 indices = [d.index for d in self.discs] 

72 if indices != sorted(indices): 

73 raise ValueError(f"GameUnit.discs must be sorted by index; got {indices}") 

74 

75 @property 

76 def is_multi_disc(self) -> bool: 

77 return len(self.discs) > 1 

78 

79 @property 

80 def source_size(self) -> int: 

81 """Total uncompressed size of all discs. 

82 

83 This is the ONLY size figure the budget pass may consult. Summing all 

84 discs gives all-or-nothing budget accounting for multi-disc sets. 

85 """ 

86 return sum(d.identity.size or 0 for d in self.discs) 

87 

88 @classmethod 

89 def from_discs( 

90 cls, 

91 platform: PlatformId, 

92 canonical_name: str, 

93 discs: tuple[DiscRef, ...], 

94 ) -> GameUnit: 

95 """Construct a ``GameUnit``, computing ``unit_id`` and sorting discs. 

96 

97 ``unit_id = sha1(f"{platform}:{canonical_name}".encode()).hexdigest()`` 

98 """ 

99 unit_id = UnitId(hashlib.sha1(f"{platform}:{canonical_name}".encode()).hexdigest()) 

100 sorted_discs = tuple(sorted(discs, key=lambda d: d.index)) 

101 return cls( 

102 unit_id=unit_id, 

103 platform=platform, 

104 canonical_name=canonical_name, 

105 discs=sorted_discs, 

106 ) 

107 

108 

109@dataclass(frozen=True, slots=True) 

110class CatalogWarning: 

111 """A non-fatal anomaly detected while building the catalog.""" 

112 

113 unit_key: str 

114 reason: str # e.g. "non-contiguous disc set: [1, 3]" 

115 

116 

117@dataclass(frozen=True, slots=True) 

118class Catalog: 

119 """Immutable snapshot of the known game universe for one platform (or all). 

120 

121 ``platform`` is ``None`` for a merged multi-platform catalog produced by 

122 the generation pass. 

123 

124 The ENTIRE mutation surface is ``keep`` / ``without`` / ``merge`` — all 

125 three return NEW ``Catalog`` instances. There is deliberately no API that 

126 adds, removes, or replaces an individual ``DiscRef``. 

127 """ 

128 

129 platform: PlatformId | None 

130 units: tuple[GameUnit, ...] 

131 warnings: tuple[CatalogWarning, ...] = () 

132 

133 def keep(self, ids: AbstractSet[UnitId]) -> Catalog: 

134 """Return a new ``Catalog`` containing only units whose id is in ``ids``.""" 

135 return Catalog( 

136 platform=self.platform, 

137 units=tuple(u for u in self.units if u.unit_id in ids), 

138 warnings=self.warnings, 

139 ) 

140 

141 def without(self, ids: AbstractSet[UnitId]) -> Catalog: 

142 """Return a new ``Catalog`` with units in ``ids`` removed.""" 

143 return Catalog( 

144 platform=self.platform, 

145 units=tuple(u for u in self.units if u.unit_id not in ids), 

146 warnings=self.warnings, 

147 ) 

148 

149 def merge(self, other: Catalog) -> Catalog: 

150 """Combine two catalogs; requires disjoint ``unit_id`` sets. 

151 

152 Raises: 

153 ValueError: if any ``unit_id`` appears in both catalogs. 

154 """ 

155 self_ids = {u.unit_id for u in self.units} 

156 other_ids = {u.unit_id for u in other.units} 

157 overlap = self_ids & other_ids 

158 if overlap: 

159 raise ValueError( 

160 f"Catalog.merge requires disjoint unit_ids; overlap: {sorted(overlap)[:5]}" 

161 ) 

162 return Catalog( 

163 platform=None, # merged catalog spans platforms 

164 units=self.units + other.units, 

165 warnings=self.warnings + other.warnings, 

166 ) 

167 

168 

169@dataclass(frozen=True, slots=True) 

170class PassTrace: 

171 """Audit log for one planner pass — powers ``romfarmer plan --explain``.""" 

172 

173 pass_name: str 

174 removed: tuple[tuple[UnitId, str], ...] # (unit_id, human-readable reason) 

175 added: tuple[tuple[UnitId, str], ...] = () 

176 notes: tuple[str, ...] = () # pass-level facts, e.g. the unrated median used by budget 

177 

178 

179@dataclass(frozen=True, slots=True) 

180class PassResult: 

181 """Output of one pure planner pass.""" 

182 

183 catalog: Catalog 

184 trace: PassTrace