Coverage for src/romfarmer/analysis/knowledge.py: 43%
89 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""KnowledgeBase — the sole read facade over romfarmer.db for the planner.
3The planner passes must not query the database directly; they receive a
4``KnowledgeBase`` instance and call its typed methods. This keeps the passes
5pure (no I/O) when tested with a stub/fake.
6"""
8from __future__ import annotations
10import logging
11import re
12from pathlib import Path
13from typing import Any
15logger = logging.getLogger(__name__)
17# Disc-number tag pattern — mirrors the bridge's _DISC_TAG
18_DISC_TAG = re.compile(r"\s*\((?:Disc|Disk|CD)\s*\d+\)", re.IGNORECASE)
21class KnowledgeBase:
22 """Read-only facade over the romfarmer metadata database.
24 All query methods are safe to call when no database exists — they return
25 sensible defaults (``None`` / empty) rather than raising.
27 The class is intentionally *not* frozen or a dataclass because it holds an
28 optional heavy SQLAlchemy session. Planner passes see it only through the
29 type annotation and call the documented public methods.
31 Args:
32 db_path: Path to ``romfarmer.db``. If ``None`` or the file does not
33 exist, all queries silently return defaults.
34 """
36 def __init__(self, db_path: Path | None = None) -> None:
37 self._db: Any = None
38 self._db_path: Path | None = db_path if (db_path is not None and db_path.exists()) else None
39 if db_path is not None and db_path.exists():
40 try:
41 import importlib
43 MetadataDatabase = importlib.import_module(
44 "romfarmer.metadata.database"
45 ).MetadataDatabase
46 self._db = MetadataDatabase(db_path)
47 except Exception as exc: # pragma: no cover
48 logger.warning("KnowledgeBase: could not open %s: %s", db_path, exc)
50 # ------------------------------------------------------------------
51 # Rating / tier
52 # ------------------------------------------------------------------
54 def get_rating(self, platform: str, canonical_name: str) -> float | None:
55 """Return the scraped rating for *canonical_name* on *platform*.
57 Returns ``None`` when the game is unknown or the DB is unavailable.
58 Rating is normalised to 0.0–1.0.
59 """
60 if self._db is None:
61 return None
62 try:
63 import importlib
65 external_scores_mod = importlib.import_module("romfarmer.metadata.external_scores")
66 normalize_title = external_scores_mod.normalize_title
67 score_row = self._db.lookup_external_score(
68 platform=platform, normalized_title=normalize_title(canonical_name)
69 )
70 if score_row is not None:
71 val = score_row.best_score_normalized
72 if val is not None:
73 return float(val)
74 # Fall back to scraped game rating
75 ScrapedGame = importlib.import_module("romfarmer.metadata.database").ScrapedGame
76 session = self._db.get_session()
77 try:
78 game = (
79 session.query(ScrapedGame)
80 .filter_by(system=platform, name=canonical_name)
81 .first()
82 )
83 if game is not None and game.rating is not None:
84 return float(game.rating)
85 return None
86 finally:
87 session.close()
88 except Exception as exc: # pragma: no cover
89 logger.debug("KnowledgeBase.get_rating(%s, %s): %s", platform, canonical_name, exc)
90 return None
92 def get_ratings_bulk(self, platform: str, canonical_names: list[str]) -> dict[str, float]:
93 """Return {canonical_name: rating} for all names with known ratings.
95 More efficient than calling ``get_rating`` in a loop.
96 """
97 if self._db is None or not canonical_names:
98 return {}
99 result: dict[str, float] = {}
100 try:
101 import importlib
103 ScrapedGame = importlib.import_module("romfarmer.metadata.database").ScrapedGame
104 session = self._db.get_session()
105 try:
106 games = (
107 session.query(ScrapedGame)
108 .filter(
109 ScrapedGame.system == platform,
110 ScrapedGame.name.in_(canonical_names),
111 ScrapedGame.rating.isnot(None),
112 )
113 .all()
114 )
115 for g in games:
116 if g.rating is not None:
117 result[g.name] = float(g.rating)
118 return result
119 finally:
120 session.close()
121 except Exception as exc: # pragma: no cover
122 logger.debug("KnowledgeBase.get_ratings_bulk(%s): %s", platform, exc)
123 return result
125 # ------------------------------------------------------------------
126 # Arcade driver status
127 # ------------------------------------------------------------------
129 def get_arcade_driver_status(self, rom_name: str) -> str | None:
130 """Return the MAME driver_status for *rom_name* (e.g. ``"good"``).
132 Returns ``None`` when unknown.
133 """
134 if self._db is None:
135 return None
136 try:
137 import importlib
139 DatGameEntry = importlib.import_module("romfarmer.metadata.database").DatGameEntry
140 session = self._db.get_session()
141 try:
142 entry = session.query(DatGameEntry).filter_by(rom_name=rom_name).first()
143 if entry is not None:
144 status: str | None = getattr(entry, "driver_status", None)
145 return status
146 return None
147 finally:
148 session.close()
149 except Exception as exc: # pragma: no cover
150 logger.debug("KnowledgeBase.get_arcade_driver_status(%s): %s", rom_name, exc)
151 return None
153 def is_arcade_parent(self, rom_name: str) -> bool | None:
154 """Return whether *rom_name* is a parent entry (not a clone).
156 Returns ``None`` when unknown.
157 """
158 if self._db is None:
159 return None
160 try:
161 import importlib
163 DatGameEntry2 = importlib.import_module("romfarmer.metadata.database").DatGameEntry
164 session = self._db.get_session()
165 try:
166 entry = session.query(DatGameEntry2).filter_by(rom_name=rom_name).first()
167 if entry is not None:
168 is_parent: bool = entry.is_parent()
169 return is_parent
170 return None
171 finally:
172 session.close()
173 except Exception as exc: # pragma: no cover
174 logger.debug("KnowledgeBase.is_arcade_parent(%s): %s", rom_name, exc)
175 return None
177 # ------------------------------------------------------------------
178 # Compression telemetry (feeds CostModel posteriors)
179 # ------------------------------------------------------------------
181 def get_compression_ratio(self, platform: str, tool: str) -> tuple[float, int] | None:
182 """Return ``(aggregate_ratio, sample_count)`` for ``(platform, tool)``.
184 Source: ``unit_telemetry`` — written by EXECUTE per unit, measured
185 against the SOURCE FILE bytes the budget pass is fed. The legacy
186 ``rom_transformations`` table is deliberately NOT consulted: its ratios
187 were measured against the uncompressed bin/iso (psx 0.551 vs a real
188 0.828) and would seed the posterior on the wrong base.
190 Returns ``None`` when there is no data. The count is real — it is the
191 posterior weight in ``CostModel``.
192 """
193 if self._db_path is None:
194 return None
195 try:
196 from romfarmer.engine.telemetry import UnitTelemetryStore
198 with UnitTelemetryStore(self._db_path) as tele:
199 hit = tele.ratio(platform, tool)
200 if hit is not None:
201 return hit
202 except Exception as exc: # pragma: no cover
203 logger.debug("KnowledgeBase.get_compression_ratio(%s, %s): %s", platform, tool, exc)
204 return None