Coverage for src/romfarmer/engine/telemetry.py: 96%

53 statements  

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

1"""UnitTelemetryStore — per-unit (source_bytes → output_bytes → duration) records. 

2 

3This is the feedback loop for the ``CostModel``: EXECUTE records, for every 

4unit that produced terminal artifacts, how many source bytes went in, how 

5many output bytes came out, and how long ``_run_unit`` took wall-clock, 

6keyed by ``(platform, tool)`` where *tool* is the first element of the 

7negotiated ``FormatChain`` (``"chd"``, ``"7z"``, …). ``duration_seconds`` 

8is EXECUTE's own wall time (extraction + transcode + CAS ingest for that 

9unit) — the one phase the CostModel's byte-ratio priors never measured. 

10An action-cache hit still records its (near-zero) duration; there is no 

11separate flag for it, so a consumer averaging durations should be aware a 

12mix of cold and cached runs will pull the mean down. 

13 

14Design: 

15- Raw ``sqlite3`` on the shared ``romfarmer.db`` (same file as the action 

16 cache), WAL mode. No ORM, no ``game_id`` join — the legacy 

17 ``rom_transformations`` table needed a ``ScrapedGame`` join and lost 22 % of 

18 its rows to NULL ``game_id``. 

19- **Write-time filter**: a record with ``source_bytes <= 0`` or 

20 ``output/source > MAX_RATIO`` is a corrupt observation (the legacy table 

21 holds xbox360 rows at 13×), not a wide distribution. It is rejected and 

22 logged, never stored. Ratios slightly above 1.0 are legitimate 

23 (incompressible payload + container overhead), hence 1.5. 

24- Idempotent per ``(platform, tool, unit_id)`` so cache-hit rebuilds do not 

25 inflate the sample count. 

26""" 

27 

28from __future__ import annotations 

29 

30import logging 

31import sqlite3 

32from pathlib import Path 

33 

34logger = logging.getLogger(__name__) 

35 

36MAX_RATIO = 1.5 

37 

38_DDL = """ 

39CREATE TABLE IF NOT EXISTS unit_telemetry ( 

40 platform TEXT NOT NULL, 

41 tool TEXT NOT NULL, 

42 unit_id TEXT NOT NULL, 

43 source_bytes INTEGER NOT NULL, 

44 output_bytes INTEGER NOT NULL, 

45 duration_seconds REAL NOT NULL DEFAULT 0.0, 

46 tool_version TEXT NOT NULL DEFAULT '', 

47 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), 

48 PRIMARY KEY (platform, tool, unit_id) 

49); 

50CREATE INDEX IF NOT EXISTS ix_unit_telemetry_key ON unit_telemetry (platform, tool); 

51""" 

52 

53 

54class UnitTelemetryStore: 

55 """SQLite facade over ``unit_telemetry``. Sole writer: the EXECUTE phase.""" 

56 

57 def __init__(self, db_path: Path) -> None: 

58 self._db_path = db_path 

59 db_path.parent.mkdir(parents=True, exist_ok=True) 

60 self._conn = sqlite3.connect(str(db_path), check_same_thread=False, isolation_level=None) 

61 self._conn.execute("PRAGMA journal_mode=WAL") 

62 self._conn.execute("PRAGMA busy_timeout=30000") 

63 self._conn.executescript(_DDL) 

64 try: 

65 self._conn.execute( 

66 "ALTER TABLE unit_telemetry ADD COLUMN duration_seconds REAL NOT NULL DEFAULT 0.0" 

67 ) 

68 except sqlite3.OperationalError: 

69 pass # column already exists (fresh table already has it via _DDL) 

70 

71 def close(self) -> None: 

72 self._conn.close() 

73 

74 def __enter__(self) -> UnitTelemetryStore: 

75 return self 

76 

77 def __exit__(self, *_: object) -> None: 

78 self.close() 

79 

80 # ------------------------------------------------------------------ 

81 

82 def record( 

83 self, 

84 platform: str, 

85 tool: str, 

86 unit_id: str, 

87 source_bytes: int, 

88 output_bytes: int, 

89 tool_version: str = "", 

90 duration_seconds: float = 0.0, 

91 ) -> bool: 

92 """Store one observation. Returns ``False`` (and logs) if rejected.""" 

93 if source_bytes <= 0 or output_bytes < 0: 

94 logger.warning( 

95 "telemetry rejected %s/%s %s: source_bytes=%d output_bytes=%d", 

96 platform, 

97 tool, 

98 unit_id[:12], 

99 source_bytes, 

100 output_bytes, 

101 ) 

102 return False 

103 ratio = output_bytes / source_bytes 

104 if ratio > MAX_RATIO: 

105 logger.warning( 

106 "telemetry rejected %s/%s %s: ratio %.2f > %.1f (corrupt observation)", 

107 platform, 

108 tool, 

109 unit_id[:12], 

110 ratio, 

111 MAX_RATIO, 

112 ) 

113 return False 

114 if duration_seconds < 0: 

115 logger.warning( 

116 "telemetry rejected %s/%s %s: duration_seconds=%.3f < 0", 

117 platform, 

118 tool, 

119 unit_id[:12], 

120 duration_seconds, 

121 ) 

122 return False 

123 with self._conn: 

124 self._conn.execute( 

125 """ 

126 INSERT INTO unit_telemetry 

127 (platform, tool, unit_id, source_bytes, output_bytes, duration_seconds, tool_version) 

128 VALUES (?, ?, ?, ?, ?, ?, ?) 

129 ON CONFLICT(platform, tool, unit_id) DO UPDATE SET 

130 source_bytes = excluded.source_bytes, 

131 output_bytes = excluded.output_bytes, 

132 duration_seconds = excluded.duration_seconds, 

133 tool_version = excluded.tool_version, 

134 created_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') 

135 """, 

136 (platform, tool, unit_id, source_bytes, output_bytes, duration_seconds, tool_version), 

137 ) 

138 return True 

139 

140 def ratio(self, platform: str, tool: str) -> tuple[float, int] | None: 

141 """``(sum(output)/sum(source), n)`` for the key, or ``None`` when n == 0.""" 

142 row = self._conn.execute( 

143 "SELECT SUM(output_bytes), SUM(source_bytes), COUNT(*) FROM unit_telemetry " 

144 "WHERE platform = ? AND tool = ?", 

145 (platform, tool), 

146 ).fetchone() 

147 if row is None or not row[2] or not row[1]: 

148 return None 

149 return float(row[0]) / float(row[1]), int(row[2]) 

150 

151 def quantiles(self, platform: str, tool: str) -> dict[str, float]: 

152 """Per-unit ratio quantiles ``{p10, p50, p90}`` (empty dict when no data).""" 

153 rows = self._conn.execute( 

154 "SELECT output_bytes * 1.0 / source_bytes FROM unit_telemetry " 

155 "WHERE platform = ? AND tool = ? ORDER BY 1", 

156 (platform, tool), 

157 ).fetchall() 

158 if not rows: 

159 return {} 

160 vals = [float(r[0]) for r in rows] 

161 n = len(vals) 

162 

163 def pick(q: float) -> float: 

164 return vals[min(n - 1, int(q * n))] 

165 

166 return {"p10": pick(0.10), "p50": pick(0.50), "p90": pick(0.90), "n": float(n)}