Coverage for dao/power_rating_dao.py: 86.39%

256 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 15:10 +0000

1"""MT Power Rating: the engine's input, and what a run stores (SB-1807). 

2 

3The engine (`mt_tools.power_rating`) is pure. This module is the two ends of it: 

4 

5- **Gathering.** One season, age group and league (Homegrown with its Flex child 

6 league): the League and Flex results, read the way the leaderboards read them 

7 (`MatchDAO.get_season_results`), plus every tournament match at the age group 

8 (`tournament_id` set; they carry no division). `to_rated_matches` turns the 

9 rows into `RatedMatch`es and is pure, so the mapping is testable without a 

10 database. 

11- **Storing.** `write_run` writes a run, its ratings and its deltas. Only the 

12 latest run of a (season, age group, league) keeps deltas: older runs' are 

13 deleted once the new run is in. 

14- **Serving** (SB-1808). `run_payload` is a run with its ratings and conference 

15 names, cached in Redis by run id: a written run never changes, and the worker 

16 that writes runs cannot clear the API's cache (`caching.md`), so the key is the 

17 run id and `latest_run` stays uncached. The team reads (`runs`, 

18 `team_ratings`, `team_deltas`, `matches_by_ids`) are small and uncached. 

19 

20## Mapping (design "What counts") 

21 

22| Row | RatedMatch | 

23|---|---| 

24| `tournament_id` set | `competition="tournament"`, neutral (no home advantage) | 

25| League in a division of the league itself | `competition="league"`, `conference` = the division name | 

26| Flex (the child league) | `competition="flex"` | 

27| `match_status` forfeit | `forfeit=True`: read, counted in `matches_excluded`, never rated | 

28| A side that did not field this age group (a play-up) | not passed to the engine; counted as `other_age_group` | 

29| Completed with no score | not passed; counted as `no_score` | 

30 

31A team is **in pool** when it has a League fixture of the league itself (a 

32Homegrown conference) at this age group this season, in any status: a scheduled 

33fixture is as good a statement of conference membership as a played one, and 

34early in a season most teams have played few. A match against anyone else, a 

35Flex-only academy side or a tournament guest, is passed with that side out of 

36pool, and the engine excludes it as `out_of_pool_opponent`. Late in the season 

37this is the backtest's production rule (every Homegrown team has played). 

38Only played matches (`completed`, `forfeit`) are passed to the engine. 

39 

40## Fingerprint 

41 

42`fingerprint` hashes the whole engine input with `PARAMS_VERSION`: match ids, 

43dates, teams, scores, status, competition and pool flags. A score correction, a 

44forfeit, a new conference registration or a parameter change all change it. A 

45run whose fingerprint equals the latest run's is not written. 

46""" 

47 

48from __future__ import annotations 

49 

50import hashlib 

51import json 

52from collections import defaultdict 

53from dataclasses import asdict, dataclass, field 

54from datetime import UTC, date, datetime, time 

55from typing import TYPE_CHECKING, Any 

56 

57import structlog 

58 

59from dao.base_dao import MATCHES_READ_RELATION, BaseDAO, cache_get, cache_set 

60from dao.side_age_groups import effective_side_age_groups 

61from mt_tools import power_rating as engine 

62from mt_tools.power_rating import MasseyResult, PowerRatingResult, RatedMatch 

63 

64if TYPE_CHECKING: 

65 from collections.abc import Iterable, Mapping 

66 

67logger = structlog.get_logger() 

68 

69RUNS = "power_rating_runs" 

70RATINGS = "power_ratings" 

71DELTAS = "power_rating_match_deltas" 

72 

73READ_STATUSES = ("completed", "forfeit") 

74# Every match_status: League fixtures in any of them say which teams are in pool. 

75POOL_STATUSES = ("scheduled", "completed", "postponed", "cancelled", "tbd", "live", "forfeit") 

76LEAGUE_COMPETITIONS = {"League": "league", "Flex": "flex"} 

77 

78# Extra exclusion reasons, beside the engine's (forfeit, out_of_pool_opponent). 

79OTHER_AGE_GROUP = "other_age_group" 

80NO_SCORE = "no_score" 

81 

82# Rows per insert. PostgREST takes larger bodies, but a run is ~6.5k delta rows. 

83_WRITE_BATCH = 1000 

84_PAGE = 1000 

85 

86# The run as served: everything but the fingerprint and parameters. 

87_RUN_COLUMNS = ( 

88 "id, season_id, age_group_id, league_id, computed_at, through_date, params_version, " 

89 "matches_counted, matches_excluded, national, publication_reason" 

90) 

91_RATING_COLUMNS = ( 

92 "team_id, rating, rank, island, conference_division_id, conference_rank, mp, w, d, l, xconf_mp, sos, tier, badges" 

93) 

94_DELTA_COLUMNS = ( 

95 "match_id, team_id, opponent_id, rating_before, opponent_before, expected, result, k, margin_mult, delta" 

96) 

97_SCORE_COLUMNS = ( 

98 "id, match_date, home_team_id, away_team_id, home_score, away_score, home_penalty_score, away_penalty_score" 

99) 

100# A run's payload never changes once complete; a week is long enough to matter, short enough to expire. 

101RUN_PAYLOAD_TTL = 7 * 86400 

102 

103# What the tournament read takes of each match. Explicit, not `*`: no user columns. 

104_TOURNAMENT_COLUMNS = ( 

105 "id, match_date, scheduled_kickoff, match_status, home_team_id, away_team_id, " 

106 "home_score, away_score, home_penalty_score, away_penalty_score, " 

107 "age_group_id, home_age_group_id, away_age_group_id, tournament_id, " 

108 "match_type:match_types(name)" 

109) 

110 

111 

112# --- pure: rows -> engine input --------------------------------------------------- 

113 

114 

115@dataclass(frozen=True) 

116class LeagueScope: 

117 """A top-level league and what its results are read from.""" 

118 

119 league_id: int 

120 name: str 

121 league_ids: tuple[int, ...] # the league and its child leagues (Flex) 

122 match_type_ids: tuple[int, ...] # what those leagues declare: League, Flex 

123 

124 

125@dataclass(frozen=True) 

126class Gathered: 

127 """One age group's engine input, and what was read but cannot be rated.""" 

128 

129 matches: tuple[RatedMatch, ...] 

130 other_age_group: int = 0 

131 no_score: int = 0 

132 # Conference (division) name -> division id, for power_ratings.conference_division_id. 

133 conference_ids: dict[str, int] = field(default_factory=dict) 

134 

135 

136def _kickoff(value: Any) -> time | None: 

137 """The time of a scheduled kickoff, in UTC; None when unset or unreadable.""" 

138 if not value: 

139 return None 

140 try: 

141 moment = value if isinstance(value, datetime) else datetime.fromisoformat(str(value)) 

142 except ValueError: 

143 return None 

144 if moment.tzinfo is not None: 144 ↛ 146line 144 didn't jump to line 146 because the condition on line 144 was always true

145 moment = moment.astimezone(UTC) 

146 return moment.time() 

147 

148 

149def _day(value: Any) -> date: 

150 return value if isinstance(value, date) else date.fromisoformat(str(value)[:10]) 

151 

152 

153def to_rated_matches(rows: Iterable[dict], age_group_id: int, home_league_id: int) -> Gathered: 

154 """League, Flex and tournament rows at one age group -> the engine's input. 

155 

156 Rows are `get_season_results`' flat shape; tournament rows carry 

157 `tournament_id` and need no division. A row read twice (by both reads) is 

158 taken once, as a tournament match. Rows of any status may be passed: only 

159 `READ_STATUSES` rows are rated, the rest only establish who is in pool. 

160 """ 

161 by_id: dict[int, dict] = {} 

162 for row in rows: 

163 seen = by_id.get(row["id"]) 

164 if seen is None or (row.get("tournament_id") and not seen.get("tournament_id")): 164 ↛ 162line 164 didn't jump to line 162 because the condition on line 164 was always true

165 by_id[row["id"]] = row 

166 

167 pool: set[int] = set() 

168 conference_ids: dict[str, int] = {} 

169 for row in by_id.values(): 

170 if row.get("tournament_id") or row.get("match_type_name") != "League": 

171 continue 

172 if row.get("league_id") != home_league_id: 

173 continue 

174 home_age, away_age = effective_side_age_groups(row) 

175 if home_age == age_group_id: 175 ↛ 177line 175 didn't jump to line 177 because the condition on line 175 was always true

176 pool.add(row["home_team_id"]) 

177 if away_age == age_group_id: 

178 pool.add(row["away_team_id"]) 

179 if row.get("division_name") and row.get("division_id") is not None: 179 ↛ 169line 179 didn't jump to line 169 because the condition on line 179 was always true

180 conference_ids.setdefault(row["division_name"], row["division_id"]) 

181 

182 matches: list[RatedMatch] = [] 

183 other_age_group = no_score = 0 

184 for row in sorted(by_id.values(), key=lambda r: r["id"]): 

185 if row.get("match_status") not in READ_STATUSES: 

186 continue 

187 if row.get("tournament_id"): 

188 competition, conference = "tournament", None 

189 else: 

190 competition = LEAGUE_COMPETITIONS.get(row.get("match_type_name")) 

191 if competition is None: 

192 continue 

193 league_match = competition == "league" and row.get("league_id") == home_league_id 

194 conference = row.get("division_name") if league_match else None 

195 if effective_side_age_groups(row) != (age_group_id, age_group_id): 

196 other_age_group += 1 

197 continue 

198 forfeit = row.get("match_status") == "forfeit" 

199 hs, as_ = row.get("home_score"), row.get("away_score") 

200 if not forfeit and (hs is None or as_ is None): 

201 no_score += 1 

202 continue 

203 matches.append( 

204 RatedMatch( 

205 match_id=row["id"], 

206 match_date=_day(row["match_date"]), 

207 home_team_id=row["home_team_id"], 

208 away_team_id=row["away_team_id"], 

209 # A forfeit is never rated, so a missing score there is immaterial. 

210 home_score=hs or 0, 

211 away_score=as_ or 0, 

212 competition=competition, 

213 neutral=competition == "tournament", 

214 forfeit=forfeit, 

215 home_in_pool=row["home_team_id"] in pool, 

216 away_in_pool=row["away_team_id"] in pool, 

217 kickoff_time=_kickoff(row.get("scheduled_kickoff")), 

218 conference=conference, 

219 home_penalty_score=row.get("home_penalty_score"), 

220 away_penalty_score=row.get("away_penalty_score"), 

221 ) 

222 ) 

223 return Gathered(tuple(matches), other_age_group, no_score, conference_ids) 

224 

225 

226def fingerprint(gathered: Gathered, params_version: str = engine.PARAMS_VERSION) -> str: 

227 """sha256 of the engine input: equal input, equal fingerprint, whatever the read order.""" 

228 payload = { 

229 "params_version": params_version, 

230 "matches": [asdict(m) for m in sorted(gathered.matches, key=lambda m: m.match_id)], 

231 "other_age_group": gathered.other_age_group, 

232 "no_score": gathered.no_score, 

233 "conference_ids": sorted(gathered.conference_ids.items()), 

234 } 

235 blob = json.dumps(payload, sort_keys=True, default=str, separators=(",", ":")) 

236 return hashlib.sha256(blob.encode()).hexdigest() 

237 

238 

239# --- pure: engine output -> rows ---------------------------------------------------- 

240 

241 

242def engine_params() -> dict[str, Any]: 

243 """The parameters a run was computed with, stored on the run.""" 

244 return { 

245 "start_rating": engine.START_RATING, 

246 "scale": engine.SCALE, 

247 "k": engine.K, 

248 "provisional_matches": engine.PROVISIONAL_MATCHES, 

249 "provisional_k_mult": engine.PROVISIONAL_K_MULT, 

250 "home_advantage": engine.HOME_ADVANTAGE, 

251 "margin_cap": engine.MARGIN_CAP, 

252 "min_matches": engine.MIN_MATCHES, 

253 "low_cross_conference": engine.LOW_CROSS_CONFERENCE, 

254 "national_island_share": engine.NATIONAL_ISLAND_SHARE, 

255 "national_min_cross_conference": engine.NATIONAL_MIN_CROSS_CONFERENCE, 

256 "massey_cap": engine.MASSEY_CAP, 

257 "massey_ridge": engine.MASSEY_RIDGE, 

258 } 

259 

260 

261def matches_excluded(result: PowerRatingResult, gathered: Gathered) -> dict[str, int]: 

262 """Every reason a read match was not rated; each key present, 0 when none.""" 

263 return {**result.matches_excluded, OTHER_AGE_GROUP: gathered.other_age_group, NO_SCORE: gathered.no_score} 

264 

265 

266def run_row( 

267 *, 

268 season_id: int, 

269 age_group_id: int, 

270 league_id: int, 

271 result: PowerRatingResult, 

272 gathered: Gathered, 

273 input_fingerprint: str, 

274 computed_at: datetime, 

275) -> dict[str, Any]: 

276 rated_ids = {d.match_id for d in result.deltas} 

277 rated_days = [m.match_date for m in gathered.matches if m.match_id in rated_ids] 

278 return { 

279 "season_id": season_id, 

280 "age_group_id": age_group_id, 

281 "league_id": league_id, 

282 "computed_at": computed_at.isoformat(), 

283 "through_date": max(rated_days).isoformat() if rated_days else None, 

284 "params": engine_params(), 

285 "params_version": engine.PARAMS_VERSION, 

286 "input_fingerprint": input_fingerprint, 

287 "matches_counted": result.matches_counted, 

288 "matches_excluded": matches_excluded(result, gathered), 

289 "national": result.publication.national, 

290 "publication_reason": result.publication.reason, 

291 } 

292 

293 

294def rating_rows( 

295 result: PowerRatingResult, audit: MasseyResult | None, conference_ids: Mapping[str, int] 

296) -> list[dict[str, Any]]: 

297 """One row per rated team, with its national, conference and Massey ranks. 

298 

299 - `rank`: national lists only, ranked teams in the main island, by rating. 

300 - `conference_rank`: ranked teams with a conference, within it, by rating. 

301 - `massey_rank`: ranked teams within their island, by the Massey audit. 

302 

303 Unranked teams (under MIN_MATCHES) carry no rank of any kind: listed, never placed. 

304 """ 

305 pub = result.publication 

306 ranked = [t for t in result.teams if t.ranked] # result.teams is rating high to low 

307 

308 national: dict[int, int] = {} 

309 if pub.national: 

310 main = [t for t in ranked if t.island == pub.main_island] 

311 national = {t.team_id: i for i, t in enumerate(main, start=1)} 

312 

313 per_conference: dict[str, list[int]] = defaultdict(list) 

314 for t in ranked: 

315 if t.conference: 315 ↛ 314line 315 didn't jump to line 314 because the condition on line 315 was always true

316 per_conference[t.conference].append(t.team_id) 

317 conference_rank = {team_id: i for ids in per_conference.values() for i, team_id in enumerate(ids, start=1)} 

318 

319 massey_rank: dict[int, int] = {} 

320 if audit is not None: 

321 per_island: dict[int, list[int]] = defaultdict(list) 

322 for t in ranked: 

323 if t.team_id in audit.ratings: 323 ↛ 322line 323 didn't jump to line 322 because the condition on line 323 was always true

324 per_island[t.island].append(t.team_id) 

325 for ids in per_island.values(): 

326 ordered = sorted(ids, key=lambda team_id: (-audit.ratings[team_id], team_id)) 

327 massey_rank.update({team_id: i for i, team_id in enumerate(ordered, start=1)}) 

328 

329 rows = [] 

330 for t in result.teams: 

331 badges = [] 

332 if t.ranked and t.provisional: 

333 badges.append("provisional") 

334 if t.low_cross_conference: 334 ↛ 336line 334 didn't jump to line 336 because the condition on line 334 was always true

335 badges.append("low_cross_conference") 

336 rows.append( 

337 { 

338 "team_id": t.team_id, 

339 "rating": t.rating, 

340 "start_rating": t.start_rating, 

341 "rank": national.get(t.team_id), 

342 "island": t.island, 

343 "conference_division_id": conference_ids.get(t.conference) if t.conference else None, 

344 "conference_rank": conference_rank.get(t.team_id), 

345 "mp": t.mp, 

346 "w": t.w, 

347 "d": t.d, 

348 "l": t.l, 

349 "xconf_mp": t.xconf_mp, 

350 "sos": t.sos, 

351 "tier": t.tier, 

352 "badges": badges, 

353 "massey_rank": massey_rank.get(t.team_id), 

354 } 

355 ) 

356 return rows 

357 

358 

359def delta_rows(result: PowerRatingResult) -> list[dict[str, Any]]: 

360 return [ 

361 { 

362 "match_id": d.match_id, 

363 "team_id": d.team_id, 

364 "opponent_id": d.opponent_id, 

365 "rating_before": d.rating_before, 

366 "opponent_before": d.opponent_before, 

367 "expected": d.expected, 

368 "result": d.result, 

369 "k": d.k, 

370 "margin_mult": d.margin_mult, 

371 "delta": d.delta, 

372 } 

373 for d in result.deltas 

374 ] 

375 

376 

377def _batches(rows: list[dict], size: int = _WRITE_BATCH) -> Iterable[list[dict]]: 

378 for start in range(0, len(rows), size): 

379 yield rows[start : start + size] 

380 

381 

382# --- the DAO ------------------------------------------------------------------------ 

383 

384 

385class PowerRatingDAO(BaseDAO): 

386 """Read the Power Rating's input; read and write its runs.""" 

387 

388 def __init__(self, connection_holder): 

389 super().__init__(connection_holder) 

390 self._match_dao = None 

391 

392 @property 

393 def match_dao(self): 

394 """MatchDAO over the same connection; imported here because match_dao imports base_dao.""" 

395 if self._match_dao is None: 

396 from dao.match_dao import MatchDAO 

397 

398 self._match_dao = MatchDAO(self.connection_holder) 

399 return self._match_dao 

400 

401 # --- reference data ----------------------------------------------------------- 

402 

403 def current_season_id(self) -> int | None: 

404 from dao.season_dao import SeasonDAO 

405 

406 return SeasonDAO(self.connection_holder).get_current_season_id() 

407 

408 def resolve_league(self, name: str) -> LeagueScope | None: 

409 """A top-level, non-test league by name (case-insensitive), with its child leagues.""" 

410 rows = self.client.table("leagues").select("id, name, parent_league_id, match_type_id, is_test").execute().data 

411 rows = [r for r in rows or [] if not r.get("is_test")] 

412 league = next( 

413 ( 

414 r 

415 for r in rows 

416 if r.get("parent_league_id") is None and str(r.get("name", "")).casefold() == name.strip().casefold() 

417 ), 

418 None, 

419 ) 

420 if league is None: 

421 return None 

422 covered = [league, *(r for r in rows if r.get("parent_league_id") == league["id"])] 

423 return LeagueScope( 

424 league_id=league["id"], 

425 name=league["name"], 

426 league_ids=tuple(r["id"] for r in covered), 

427 match_type_ids=tuple(sorted({r["match_type_id"] for r in covered if r.get("match_type_id") is not None})), 

428 ) 

429 

430 def age_group_ids(self, names: Iterable[str]) -> dict[str, int]: 

431 """Name -> id for the age groups that exist; unknown names are absent.""" 

432 wanted = list(names) 

433 rows = self.client.table("age_groups").select("id, name").in_("name", wanted).execute().data 

434 return {r["name"]: r["id"] for r in rows or []} 

435 

436 # --- input -------------------------------------------------------------------- 

437 

438 def get_tournament_results(self, season_id: int, age_group_id: int) -> list[dict]: 

439 """Played tournament matches at one age group (or with a side at it), non-test, paged.""" 

440 a = int(age_group_id) 

441 rows: list[dict] = [] 

442 while True: 

443 page = ( 

444 self.client.table(MATCHES_READ_RELATION) 

445 .select(_TOURNAMENT_COLUMNS) 

446 .eq("season_id", season_id) 

447 .or_(f"age_group_id.eq.{a},home_age_group_id.eq.{a},away_age_group_id.eq.{a}") 

448 .not_.is_("tournament_id", "null") 

449 .in_("match_status", list(READ_STATUSES)) 

450 .eq("is_test", False) 

451 .order("match_date") 

452 .order("id") 

453 .range(len(rows), len(rows) + _PAGE - 1) 

454 .execute() 

455 ).data or [] 

456 if not page: 

457 break 

458 rows.extend(page) 

459 return [ 

460 {**r, "match_type_name": (r.get("match_type") or {}).get("name"), "league_id": None, "division_name": None} 

461 for r in rows 

462 ] 

463 

464 def gather(self, season_id: int, age_group_id: int, scope: LeagueScope) -> Gathered: 

465 """One age group's engine input. Raises on a read error: "could not read" is not "no matches".""" 

466 league_rows = self.match_dao.get_season_results( 

467 season_id=season_id, 

468 age_group_id=age_group_id, 

469 league_ids=scope.league_ids, 

470 match_type_ids=scope.match_type_ids, 

471 statuses=POOL_STATUSES, 

472 include_test=False, 

473 ) 

474 tournament_rows = self.get_tournament_results(season_id, age_group_id) 

475 return to_rated_matches([*league_rows, *tournament_rows], age_group_id, scope.league_id) 

476 

477 # --- runs --------------------------------------------------------------------- 

478 

479 def _runs(self, season_id: int, age_group_id: int, league_id: int): 

480 return ( 

481 self.client.table(RUNS) 

482 .select("id, computed_at, input_fingerprint") 

483 .eq("season_id", season_id) 

484 .eq("age_group_id", age_group_id) 

485 .eq("league_id", league_id) 

486 ) 

487 

488 def latest_run(self, season_id: int, age_group_id: int, league_id: int) -> dict | None: 

489 """The newest run (id, computed_at, input_fingerprint), or None. Uncached by design.""" 

490 rows = ( 

491 self._runs(season_id, age_group_id, league_id) 

492 .order("computed_at", desc=True) 

493 .order("id", desc=True) 

494 .limit(1) 

495 .execute() 

496 ).data 

497 return rows[0] if rows else None 

498 

499 def latest_run_id(self, season_id: int, age_group_id: int, league_id: int) -> int | None: 

500 run = self.latest_run(season_id, age_group_id, league_id) 

501 return run["id"] if run else None 

502 

503 def run_as_of(self, season_id: int, age_group_id: int, league_id: int, at: datetime) -> dict | None: 

504 """The run users saw at `at`: the newest computed at or before it. For 7-day movement.""" 

505 rows = ( 

506 self._runs(season_id, age_group_id, league_id) 

507 .lte("computed_at", at.isoformat()) 

508 .order("computed_at", desc=True) 

509 .order("id", desc=True) 

510 .limit(1) 

511 .execute() 

512 ).data 

513 return rows[0] if rows else None 

514 

515 def write_run(self, run: dict, ratings: list[dict], deltas: list[dict]) -> int: 

516 """Insert a run with its ratings and deltas; drop older runs' deltas. Returns the run id. 

517 

518 PostgREST has no multi-statement transaction, so a failure after the run 

519 row is in deletes it again (ratings and deltas cascade) and re-raises: 

520 a half-written run must never be the latest. 

521 """ 

522 run_id = self.client.table(RUNS).insert(run).execute().data[0]["id"] 

523 try: 

524 for batch in _batches([{**r, "run_id": run_id} for r in ratings]): 

525 self.client.table(RATINGS).insert(batch).execute() 

526 for batch in _batches([{**d, "run_id": run_id} for d in deltas]): 

527 self.client.table(DELTAS).insert(batch).execute() 

528 except Exception: 

529 logger.exception("power_rating_write_failed", run_id=run_id) 

530 self.client.table(RUNS).delete().eq("id", run_id).execute() 

531 raise 

532 same_scope = self._runs(run["season_id"], run["age_group_id"], run["league_id"]) 

533 older = [r["id"] for r in same_scope.neq("id", run_id).execute().data or []] 

534 if older: 

535 # Latest run only (design "Data model"). A failure here leaves stale 

536 # deltas on old runs, which nothing reads; the next write retries it. 

537 try: 

538 self.client.table(DELTAS).delete().in_("run_id", older).execute() 

539 except Exception: 

540 logger.exception("power_rating_old_deltas_not_deleted", run_id=run_id) 

541 return run_id 

542 

543 # --- serving (SB-1808) -------------------------------------------------------- 

544 

545 def run_payload(self, run_id: int) -> dict | None: 

546 """A run, its ratings and its conferences' names, cached by run id. None for no such run. 

547 

548 A run is written row first, then ratings, so a reader can catch it with 

549 none of them (all ratings go in one insert: under `_WRITE_BATCH` teams). 

550 Such a payload is returned but not cached, so the next read sees it whole. 

551 """ 

552 key = f"mt:dao:power_rating:run:{int(run_id)}" 

553 cached = cache_get(key) 

554 if cached is not None: 

555 return cached 

556 rows = self.client.table(RUNS).select(_RUN_COLUMNS).eq("id", run_id).limit(1).execute().data 

557 if not rows: 

558 return None 

559 ratings: list[dict] = [] 

560 while True: 

561 page = ( 

562 self.client.table(RATINGS) 

563 .select(_RATING_COLUMNS) 

564 .eq("run_id", run_id) 

565 .order("team_id") 

566 .range(len(ratings), len(ratings) + _PAGE - 1) 

567 .execute() 

568 ).data or [] 

569 ratings.extend(page) 

570 if len(page) < _PAGE: 570 ↛ 560line 570 didn't jump to line 560 because the condition on line 570 was always true

571 break 

572 division_ids = sorted({r["conference_division_id"] for r in ratings if r.get("conference_division_id")}) 

573 conferences: dict[str, str] = {} 

574 if division_ids: 

575 divisions = self.client.table("divisions").select("id, name").in_("id", division_ids).execute().data 

576 # JSON keys are strings: the cached copy and the fresh one must look alike. 

577 conferences = {str(d["id"]): d["name"] for d in divisions or []} 

578 payload = {"run": rows[0], "ratings": ratings, "conferences": conferences} 

579 if ratings or not rows[0].get("matches_counted"): 

580 cache_set(key, payload, RUN_PAYLOAD_TTL) 

581 return payload 

582 

583 def runs(self, season_id: int, age_group_id: int, league_id: int) -> list[dict]: 

584 """Every run of a scope, oldest first (id, computed_at, through_date).""" 

585 return ( 

586 self.client.table(RUNS) 

587 .select("id, computed_at, through_date") 

588 .eq("season_id", season_id) 

589 .eq("age_group_id", age_group_id) 

590 .eq("league_id", league_id) 

591 .order("computed_at") 

592 .order("id") 

593 .execute() 

594 ).data or [] 

595 

596 def team_ratings(self, team_id: int, run_ids: Iterable[int]) -> list[dict]: 

597 """One team's rating rows in the given runs; a run it was not rated in has none.""" 

598 ids = list(run_ids) 

599 if not ids: 

600 return [] 

601 return ( 

602 self.client.table(RATINGS) 

603 .select("run_id, rating, rank, conference_rank, mp") 

604 .eq("team_id", team_id) 

605 .in_("run_id", ids) 

606 .execute() 

607 ).data or [] 

608 

609 def team_deltas(self, run_id: int, team_id: int) -> list[dict]: 

610 """One team's per-match rating changes in a run (only the latest run keeps any).""" 

611 return ( 

612 self.client.table(DELTAS).select(_DELTA_COLUMNS).eq("run_id", run_id).eq("team_id", team_id).execute() 

613 ).data or [] 

614 

615 def massey_ranks(self, run_id: int) -> dict[int, int]: 

616 """team_id -> stored Massey rank (within its island) for a run's ranked teams (SB-1812). 

617 

618 Read apart from `run_payload`, uncached: the admin audit is the only 

619 reader, and the cached payloads' shape stays as it was. 

620 """ 

621 ranks: dict[int, int] = {} 

622 offset = 0 

623 while True: 

624 page = ( 

625 self.client.table(RATINGS) 

626 .select("team_id, massey_rank") 

627 .eq("run_id", run_id) 

628 .order("team_id") 

629 .range(offset, offset + _PAGE - 1) 

630 .execute() 

631 ).data or [] 

632 ranks.update({r["team_id"]: r["massey_rank"] for r in page if r.get("massey_rank") is not None}) 

633 offset += len(page) 

634 if len(page) < _PAGE: 634 ↛ 623line 634 didn't jump to line 623 because the condition on line 634 was always true

635 return ranks 

636 

637 def matches_by_ids(self, match_ids: Iterable[int]) -> list[dict]: 

638 """Date and score of the given matches, for "why it moved".""" 

639 ids = sorted(set(match_ids)) 

640 if not ids: 

641 return [] 

642 return self.client.table(MATCHES_READ_RELATION).select(_SCORE_COLUMNS).in_("id", ids).execute().data or []