Coverage for src/romfarmer/utils/size_tracking.py: 35%

102 statements  

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

1"""Size tracking infrastructure for ROM output estimation. 

2 

3Tracks actual output sizes per platform and compression format to enable 

4better storage budget estimation in future builds. 

5""" 

6 

7import json 

8import logging 

9from dataclasses import asdict, dataclass, field 

10from datetime import datetime 

11from pathlib import Path 

12 

13logger = logging.getLogger(__name__) 

14 

15 

16@dataclass 

17class PlatformSizeRecord: 

18 """Record of a single platform build's output size. 

19 

20 Attributes: 

21 platform: Platform name (e.g., 'nes', 'psx') 

22 compression: Compression format used (e.g., '7z', 'chd') 

23 selection: Selection strategy used (e.g., 'all', 'best_of') 

24 input_files: Number of input files 

25 output_files: Number of output files 

26 input_size_bytes: Total input size 

27 output_size_bytes: Total output size 

28 timestamp: When this record was created 

29 notes: Optional notes about the build 

30 """ 

31 

32 platform: str 

33 compression: str 

34 selection: str = "all" 

35 input_files: int = 0 

36 output_files: int = 0 

37 input_size_bytes: int = 0 

38 output_size_bytes: int = 0 

39 timestamp: str = field(default_factory=lambda: datetime.now().isoformat()) 

40 notes: str = "" 

41 

42 @property 

43 def compression_ratio(self) -> float: 

44 """Compression ratio (output/input). Lower is better.""" 

45 if self.input_size_bytes == 0: 

46 return 1.0 

47 return self.output_size_bytes / self.input_size_bytes 

48 

49 @property 

50 def output_mb(self) -> float: 

51 """Output size in MB.""" 

52 return self.output_size_bytes / (1024 * 1024) 

53 

54 @property 

55 def output_gb(self) -> float: 

56 """Output size in GB.""" 

57 return self.output_size_bytes / (1024 * 1024 * 1024) 

58 

59 

60class SizeDatabase: 

61 """Database of platform size records. 

62 

63 Stores historical size data in a JSON file for future estimation. 

64 """ 

65 

66 def __init__(self, db_path: Path | None = None): 

67 """Initialize size database. 

68 

69 Args: 

70 db_path: Path to JSON database file. Defaults to 'config/size_data.json' 

71 """ 

72 self.db_path = db_path or Path("config/size_data.json") 

73 self.records: dict[str, list[dict]] = {} # platform -> list of records 

74 self._load() 

75 

76 def _load(self): 

77 """Load records from disk.""" 

78 if self.db_path.exists(): 

79 try: 

80 with open(self.db_path) as f: 

81 self.records = json.load(f) 

82 logger.debug(f"Loaded {sum(len(v) for v in self.records.values())} size records") 

83 except Exception as e: 

84 logger.warning(f"Failed to load size database: {e}") 

85 self.records = {} 

86 else: 

87 logger.debug(f"No size database found at {self.db_path}") 

88 

89 def _save(self): 

90 """Save records to disk.""" 

91 try: 

92 self.db_path.parent.mkdir(parents=True, exist_ok=True) 

93 with open(self.db_path, "w") as f: 

94 json.dump(self.records, f, indent=2) 

95 logger.debug(f"Saved size database to {self.db_path}") 

96 except Exception as e: 

97 logger.error(f"Failed to save size database: {e}") 

98 

99 def add_record(self, record: PlatformSizeRecord): 

100 """Add a new size record. 

101 

102 Args: 

103 record: PlatformSizeRecord to add 

104 """ 

105 if record.platform not in self.records: 

106 self.records[record.platform] = [] 

107 

108 self.records[record.platform].append(asdict(record)) 

109 

110 # Keep only last 10 records per platform 

111 if len(self.records[record.platform]) > 10: 

112 self.records[record.platform] = self.records[record.platform][-10:] 

113 

114 self._save() 

115 

116 logger.info( 

117 f"Recorded size for {record.platform}: " 

118 f"{record.output_mb:.1f} MB ({record.compression}, {record.selection})" 

119 ) 

120 

121 def get_estimate( 

122 self, platform: str, compression: str = "7z", selection: str = "all" 

123 ) -> int | None: 

124 """Get estimated output size for a platform. 

125 

126 Uses historical data to estimate, with fallbacks. 

127 

128 Args: 

129 platform: Platform name 

130 compression: Compression format 

131 selection: Selection strategy 

132 

133 Returns: 

134 Estimated size in bytes, or None if no data available 

135 """ 

136 if platform not in self.records: 

137 return None 

138 

139 records = self.records[platform] 

140 

141 # Try to find exact match first 

142 for r in reversed(records): # Most recent first 

143 if r["compression"] == compression and r["selection"] == selection: 

144 return r["output_size_bytes"] 

145 

146 # Try same compression, different selection 

147 for r in reversed(records): 

148 if r["compression"] == compression: 

149 # Scale based on selection strategy 

150 base_size = r["output_size_bytes"] 

151 base_selection = r["selection"] 

152 return self._scale_for_selection(base_size, base_selection, selection) 

153 

154 # Use any available data 

155 if records: 

156 return records[-1]["output_size_bytes"] 

157 

158 return None 

159 

160 def _scale_for_selection(self, size: int, from_sel: str, to_sel: str) -> int: 

161 """Scale a size estimate based on selection strategy change. 

162 

163 Args: 

164 size: Base size 

165 from_sel: Original selection strategy 

166 to_sel: Target selection strategy 

167 

168 Returns: 

169 Scaled size estimate 

170 """ 

171 # Selection strategy scaling factors 

172 # These are rough estimates - best_of typically has ~20-50 games 

173 scale_factors = { 

174 "all": 1.0, 

175 "best_of_extended": 0.15, 

176 "best_of": 0.10, 

177 } 

178 

179 from_factor = scale_factors.get(from_sel, 1.0) 

180 to_factor = scale_factors.get(to_sel, 1.0) 

181 

182 if from_factor == 0: 

183 return size 

184 

185 return int(size * to_factor / from_factor) 

186 

187 def get_all_platforms(self) -> list[str]: 

188 """Get list of all platforms with size data.""" 

189 return list(self.records.keys()) 

190 

191 def get_summary(self, platform: str) -> dict | None: 

192 """Get summary statistics for a platform. 

193 

194 Args: 

195 platform: Platform name 

196 

197 Returns: 

198 Dictionary with summary statistics, or None if no data 

199 """ 

200 if platform not in self.records: 

201 return None 

202 

203 records = self.records[platform] 

204 if not records: 

205 return None 

206 

207 sizes = [r["output_size_bytes"] for r in records] 

208 

209 return { 

210 "platform": platform, 

211 "record_count": len(records), 

212 "avg_size_mb": sum(sizes) / len(sizes) / (1024 * 1024), 

213 "min_size_mb": min(sizes) / (1024 * 1024), 

214 "max_size_mb": max(sizes) / (1024 * 1024), 

215 "compressions": list({r["compression"] for r in records}), 

216 "last_updated": records[-1]["timestamp"], 

217 } 

218 

219 

220# Global instance for convenience 

221_size_db: SizeDatabase | None = None 

222 

223 

224def get_size_db(db_path: Path | None = None) -> SizeDatabase: 

225 """Get the global size database instance. 

226 

227 Args: 

228 db_path: Optional path to database file 

229 

230 Returns: 

231 SizeDatabase instance 

232 """ 

233 global _size_db 

234 if _size_db is None: 

235 _size_db = SizeDatabase(db_path) 

236 return _size_db 

237 

238 

239def record_platform_size( 

240 platform: str, 

241 compression: str, 

242 output_size_bytes: int, 

243 selection: str = "all", 

244 input_files: int = 0, 

245 output_files: int = 0, 

246 input_size_bytes: int = 0, 

247 notes: str = "", 

248 db_path: Path | None = None, 

249): 

250 """Convenience function to record a platform's output size. 

251 

252 ``db_path`` selects the JSON file explicitly (the driver passes the 

253 workspace's ``config/size_data.json``); ``None`` uses the process-global 

254 database, whose default is cwd-relative. 

255 

256 Args: 

257 platform: Platform name 

258 compression: Compression format 

259 output_size_bytes: Total output size in bytes 

260 selection: Selection strategy used 

261 input_files: Number of input files 

262 output_files: Number of output files 

263 input_size_bytes: Total input size 

264 notes: Optional notes 

265 """ 

266 record = PlatformSizeRecord( 

267 platform=platform, 

268 compression=compression, 

269 selection=selection, 

270 input_files=input_files, 

271 output_files=output_files, 

272 input_size_bytes=input_size_bytes, 

273 output_size_bytes=output_size_bytes, 

274 notes=notes, 

275 ) 

276 db = SizeDatabase(db_path) if db_path is not None else get_size_db() 

277 db.add_record(record) 

278 

279 

280def estimate_platform_size( 

281 platform: str, 

282 compression: str = "7z", 

283 selection: str = "all", 

284) -> int | None: 

285 """Convenience function to estimate a platform's output size. 

286 

287 Args: 

288 platform: Platform name 

289 compression: Compression format 

290 selection: Selection strategy 

291 

292 Returns: 

293 Estimated size in bytes, or None if no data 

294 """ 

295 return get_size_db().get_estimate(platform, compression, selection)