Coverage for celery_tasks/match_tasks.py: 11.90%

606 statements  

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

1""" 

2Match Processing Tasks 

3 

4Tasks for processing match data from the match-scraper service. 

5These tasks run asynchronously in Celery workers, allowing for: 

6- Non-blocking match data ingestion 

7- Automatic retries on failure 

8- Horizontal scaling of processing capacity 

9""" 

10 

11import time 

12from datetime import datetime 

13from typing import Any 

14from zoneinfo import ZoneInfo, ZoneInfoNotFoundError 

15 

16from celery import Task 

17 

18from celery_app import app 

19from celery_tasks.exceptions import UnresolvedNameError 

20from celery_tasks.final_score_alert import alert_if_new_final_score 

21from celery_tasks.tournament_filing import ( 

22 TournamentFiling, 

23 TournamentFilingError, 

24 read_tournament_filing, 

25 tournament_changes, 

26) 

27from celery_tasks.validation_tasks import validate_match_data 

28from dao.club_dao import ClubDAO 

29from dao.ingest_failures_dao import CONFLICT_SOURCE, SCORE_LOCKED, SCRAPED_OVERRODE_MANUAL, IngestFailuresDAO 

30from dao.ingest_plan import _PLACEHOLDERS as PLACEHOLDER_NAMES 

31from dao.league_dao import LeagueDAO 

32from dao.match_dao import FEED_SOURCES, MatchDAO, SupabaseConnection 

33from dao.match_type_dao import MatchTypeDAO 

34from dao.season_dao import SeasonDAO 

35from dao.team_dao import TeamDAO 

36from dao.team_sides import UNKNOWN_LEAGUE, league_named 

37from dao.tournament_dao import VALID_ROUNDS 

38from logging_config import get_logger 

39from notifications.ingest_alerts import alert_unresolved_name 

40 

41logger = get_logger(__name__) 

42 

43# The zone a zone-less match_time is read in when nothing better is known. 

44DEFAULT_KICKOFF_TZ = "America/New_York" 

45 

46# The longest match location stored (SB-1874). The feed's are a venue and a 

47# pitch ("Arizona Athletic Grounds - Field 20"), far shorter; a longer one is 

48# cut rather than costing the match. 

49MAX_LOCATION_LENGTH = 200 

50 

51 

52# How long a worker trusts that a tournament it has seen still exists. Short 

53# enough that a deleted tournament becomes a recorded failure rather than a 

54# foreign-key error retried until restart; long enough that a load of thousands 

55# of matches over one id asks a handful of times. 

56KNOWN_TOURNAMENT_SECONDS = 600 

57 

58# How long a worker keeps the leagues table it read for the tournament side 

59# guard (SB-1748). Six rows that change a few times a year, wanted twice per 

60# tournament message: read per call it is thousands of round trips a scrape. 

61KNOWN_LEAGUES_SECONDS = 600 

62 

63# How long a worker leaves resolve_ingest_failures_by_league alone after the 

64# database said it does not have it (SB-1748). Code deploys on merge and the 

65# migration is applied by hand afterwards; asking on every tournament message 

66# in between is thousands of calls that can only fail. Short enough that 

67# closing starts by itself once the migration lands. 

68RESOLVE_BY_LEAGUE_RETRY_SECONDS = 600 

69 

70 

71def _pair(pair: tuple[Any, Any]) -> str: 

72 """A score pair for a conflict line: "3-1", with "—" for a missing side.""" 

73 return "-".join("—" if v is None else str(v) for v in pair) 

74 

75 

76class DatabaseTask(Task): 

77 """ 

78 Base task class that provides database access. 

79 

80 The DAO and connection attributes are class-level so they're shared 

81 across all task executions in the same worker process. 

82 """ 

83 

84 _connection = None 

85 _dao = None 

86 _team_dao = None 

87 _season_dao = None 

88 _league_dao = None 

89 _match_type_dao = None 

90 _ingest_failures_dao = None 

91 _club_dao = None 

92 

93 # Names this worker has already confirmed good, so the "did this name used 

94 # to fail?" check costs one round trip per distinct name per worker rather 

95 # than one per match. A season load sees tens of names across thousands of 

96 # matches, so the difference is thousands of calls. 

97 # 

98 # A tournament message's team names are keyed with their league as well 

99 # (SB-1748): the same name resolves separately on each side, and a 

100 # Homegrown success must not be remembered as the Academy answer. 

101 _resolved_names: set[tuple[str, ...]] = set() 

102 

103 # (team_id, age_group_id, division_id) triples this worker has already 

104 # registered. Same reasoning as _resolved_names: a season load is thousands 

105 # of matches over a couple of dozen triples, and checking per match would be 

106 # thousands of round trips to learn the same thing. 

107 _ensured_mappings: set[tuple[int, int, int]] = set() 

108 

109 # Tournament ids this worker has confirmed exist, each with the monotonic 

110 # time until which that is trusted. A tournament load is thousands of 

111 # matches over one id (SB-1747). Only hits are remembered: a tournament 

112 # created after its first match arrived has to be found. And only for 

113 # KNOWN_TOURNAMENT_SECONDS: one deleted since has to be noticed. 

114 _known_tournaments: dict[int, float] = {} 

115 

116 # The leagues table as this worker last read it, with the monotonic time 

117 # until which it is trusted (SB-1748). None until a tournament message 

118 # that names a league needs it. 

119 _known_leagues: tuple[list[dict[str, Any]], float] | None = None 

120 

121 # The monotonic time before which resolve_ingest_failures_by_league is not 

122 # called, because the database did not have it when last asked (SB-1748). 

123 _resolve_by_league_retry_at: float = 0.0 

124 

125 # The clock the entries above expire against. An attribute so a test can 

126 # move time without sleeping. 

127 _clock = staticmethod(time.monotonic) 

128 

129 @property 

130 def dao(self): 

131 """Lazy initialization of MatchDAO to avoid creating connections at import time.""" 

132 if self._dao is None: 

133 if self._connection is None: 

134 self._connection = SupabaseConnection() 

135 self._dao = MatchDAO(self._connection) 

136 return self._dao 

137 

138 @property 

139 def team_dao(self): 

140 """Lazy initialization of TeamDAO for team lookups.""" 

141 if self._team_dao is None: 

142 if self._connection is None: 

143 self._connection = SupabaseConnection() 

144 self._team_dao = TeamDAO(self._connection) 

145 return self._team_dao 

146 

147 @property 

148 def season_dao(self): 

149 """Lazy initialization of SeasonDAO for season/age-group lookups.""" 

150 if self._season_dao is None: 

151 if self._connection is None: 

152 self._connection = SupabaseConnection() 

153 self._season_dao = SeasonDAO(self._connection) 

154 return self._season_dao 

155 

156 @property 

157 def league_dao(self): 

158 """Lazy initialization of LeagueDAO for division lookups.""" 

159 if self._league_dao is None: 

160 if self._connection is None: 

161 self._connection = SupabaseConnection() 

162 self._league_dao = LeagueDAO(self._connection) 

163 return self._league_dao 

164 

165 @property 

166 def match_type_dao(self): 

167 """Lazy initialization of MatchTypeDAO for competition lookups.""" 

168 if self._match_type_dao is None: 

169 if self._connection is None: 

170 self._connection = SupabaseConnection() 

171 self._match_type_dao = MatchTypeDAO(self._connection) 

172 return self._match_type_dao 

173 

174 @property 

175 def ingest_failures_dao(self): 

176 """Lazy initialization of IngestFailuresDAO for unresolved-name reporting.""" 

177 if self._ingest_failures_dao is None: 

178 if self._connection is None: 

179 self._connection = SupabaseConnection() 

180 self._ingest_failures_dao = IngestFailuresDAO(self._connection) 

181 return self._ingest_failures_dao 

182 

183 @property 

184 def club_dao(self): 

185 """Lazy initialization of ClubDAO for the home club's timezone.""" 

186 if self._club_dao is None: 

187 if self._connection is None: 

188 self._connection = SupabaseConnection() 

189 self._club_dao = ClubDAO(self._connection) 

190 return self._club_dao 

191 

192 def _note_name_resolved(self, kind: str, raw_name: str, source: str) -> None: 

193 """Close any open ingest_failures row for a name that now resolves. 

194 

195 Called on the success path so that adding an alias mid-load clears its 

196 own alert without anyone touching the table. 

197 """ 

198 key = (kind, raw_name.lower()) 

199 if key in self._resolved_names: 

200 return 

201 self._resolved_names.add(key) 

202 self.ingest_failures_dao.resolve(kind, raw_name, source=source) 

203 

204 def _note_tournament_team_resolved(self, raw_name: str, league_name: str | None, source: str) -> None: 

205 """Close the open row for a team name that now resolves on one side (SB-1748). 

206 

207 _note_name_resolved closes every open row for the name whatever its 

208 league. On a tournament message that would close the Academy row on a 

209 Homegrown success, and the next Academy failure would reopen it and 

210 alert again. So the row closed, and the name remembered, is this 

211 league's only. 

212 """ 

213 key = ("team", raw_name.lower(), (league_name or "").lower()) 

214 if key in self._resolved_names: 

215 return 

216 # The database did not have the function a moment ago. Nothing is 

217 # closed and nothing remembered until it is asked again. 

218 if self._clock() < self._resolve_by_league_retry_at: 

219 return 

220 closed = self.ingest_failures_dao.resolve_in_league("team", raw_name, league=league_name, source=source) 

221 # None is a database without the function yet: nothing was closed, so 

222 # the name is not remembered, and the function is left alone for a 

223 # while rather than called twice per message until the migration lands. 

224 if closed is None: 

225 self._resolve_by_league_retry_at = self._clock() + RESOLVE_BY_LEAGUE_RETRY_SECONDS 

226 return 

227 self._resolved_names.add(key) 

228 

229 def _tournament_leagues(self) -> list[dict[str, Any]]: 

230 """The leagues table, read at most once per KNOWN_LEAGUES_SECONDS (SB-1748). 

231 

232 An empty answer is not kept: with no leagues every hint is unknown, 

233 and that should be asked again rather than believed for ten minutes. 

234 """ 

235 now = self._clock() 

236 if self._known_leagues is not None and self._known_leagues[1] > now: 

237 return self._known_leagues[0] 

238 rows = list(self.team_dao.league_rows() or []) 

239 self._known_leagues = (rows, now + KNOWN_LEAGUES_SECONDS) if rows else None 

240 return rows 

241 

242 def _resolve_team( 

243 self, 

244 name: str, 

245 *, 

246 league_id: int | None, 

247 league_name: str | None, 

248 sample: str, 

249 filing: TournamentFiling | None = None, 

250 age_group_id: int | None = None, 

251 leagues: list[dict[str, Any]] | None = None, 

252 ) -> dict[str, Any]: 

253 """The team a feed name refers to, or UnresolvedNameError. 

254 

255 resolve_team_by_name consults team_aliases as well as teams.name 

256 (SB-822) — the plain name lookup this used to call meant the aliases 

257 seeded for the Kitman feed never applied to the feed. Nothing is 

258 created here: an unknown name fails the task rather than inventing a 

259 lightweight team row that later collides on the unique constraint. 

260 

261 A tournament message (`filing`) resolves through 

262 resolve_tournament_team instead (SB-1748): Homegrown and Academy share 

263 an event and team names, so the name has to be on the message's side 

264 at its age group. One that exists only on the other side, or matches 

265 more than one team, fails with the reason in the failure's sample. 

266 """ 

267 if filing is None: 

268 team = self.team_dao.resolve_team_by_name(name, league_id=league_id) 

269 if not team: 

270 raise UnresolvedNameError("team", name, league=league_name, sample=sample) 

271 return team 

272 

273 team, resolution = self.team_dao.resolve_tournament_team(name, age_group_id, league_name, leagues=leagues) 

274 if resolution.status == UNKNOWN_LEAGUE: 

275 raise UnresolvedNameError("league", (league_name or "").strip(), sample=sample) 

276 if not team: 

277 detail = f"{sample} [{resolution.reason}]" if resolution.reason else sample 

278 raise UnresolvedNameError("team", name, league=league_name, sample=detail) 

279 return team 

280 

281 def _require_tournament(self, filing: TournamentFiling, *, league_name: str | None, sample: str) -> None: 

282 """Fail the message if its tournament does not exist (SB-1747). 

283 

284 Recorded as an 'invalid' ingest failure — one row for the id, however 

285 many matches it costs — and not retried: a tournament nobody created 

286 will not exist in ten minutes either. 

287 """ 

288 now = self._clock() 

289 if self._known_tournaments.get(filing.tournament_id, 0.0) > now: 

290 return 

291 self._known_tournaments.pop(filing.tournament_id, None) 

292 if not self.dao.tournament_exists(filing.tournament_id): 

293 raise UnresolvedNameError( 

294 "invalid", 

295 f"unknown tournament_id {filing.tournament_id}", 

296 league=league_name, 

297 sample=sample, 

298 ) 

299 self._known_tournaments[filing.tournament_id] = now + KNOWN_TOURNAMENT_SECONDS 

300 

301 @staticmethod 

302 def _is_other_fixture(candidate: dict[str, Any], external_match_id: Any) -> bool: 

303 """Whether a teams-and-date hit is a different fixture from the message. 

304 

305 The fallback lookup exists to adopt a hand-entered match, which has no 

306 source id. A hit that already carries one, different from the 

307 message's, is another fixture between the same teams on the same day — 

308 routine at a tournament — and updating it would overwrite one match 

309 with another's score (SB-1747). 

310 """ 

311 stored = candidate.get("match_id") 

312 if not stored or not external_match_id: 

313 return False 

314 return str(stored) != str(external_match_id) 

315 

316 @staticmethod 

317 def _require_row_on_tournament( 

318 existing_match: dict[str, Any], filing: TournamentFiling, *, league_name: str | None, sample: str 

319 ) -> None: 

320 """Fail a tournament message whose row belongs somewhere else (SB-1747). 

321 

322 A row found by its source id that sits in a league division, or on a 

323 different tournament, is not moved: re-filing it would take a match 

324 out of a league table, or out of one event and into another, on the 

325 strength of one message. Recorded as an 'invalid' ingest failure and 

326 not retried; the row is left exactly as it was. 

327 

328 A row that is on no tournament and in no division has nowhere to be 

329 moved from, and is filed. 

330 """ 

331 stored_tournament = existing_match.get("tournament_id") 

332 if stored_tournament == filing.tournament_id: 

333 return 

334 if stored_tournament is not None: 

335 where = f"tournament {stored_tournament}" 

336 elif existing_match.get("division_id") is not None: 

337 where = "a league division" 

338 else: 

339 return 

340 raise UnresolvedNameError( 

341 "invalid", 

342 f"tournament_id {filing.tournament_id} sent for a match already filed on {where}", 

343 league=league_name, 

344 sample=sample, 

345 ) 

346 

347 def _register_team_age_group(self, team: dict[str, Any], age_group_id: int | None, division: dict | None) -> None: 

348 """Record that this team plays this age group, in this division. 

349 

350 Nothing on the ingest path used to do this, so a team the scraper had 

351 been filing matches for all season did not exist at that age group as 

352 far as the product was concerned: /api/teams builds a team's age_groups 

353 purely from team_mappings, and the My Club team picker filters on it. 

354 NEFC had 44 U15 matches and an empty U15 team picker (SB-852). 

355 

356 Only the team's **own** league registers a mapping. A Homegrown team's 

357 Flex matches carry the Flex bracket's division_id, and writing that 

358 would give the team two divisions at one age group — while 

359 divisions_by_age_group is keyed by age group alone and takes last-wins, 

360 so the team's division would start displaying as a Flex bracket. Flex 

361 participation is already expressed by the matches, and Flex standings 

362 read matches directly (SB-835). 

363 

364 A team with no league_id yet is registered anyway: that is a team whose 

365 first mapping this is, and refusing would leave it stuck with none. 

366 """ 

367 if not division or age_group_id is None: 

368 return 

369 

370 division_id = division.get("id") 

371 if division_id is None: 

372 return 

373 

374 team_league_id = team.get("league_id") 

375 if team_league_id is not None and division.get("league_id") != team_league_id: 

376 return 

377 

378 key = (team["id"], age_group_id, division_id) 

379 if key in self._ensured_mappings: 

380 return 

381 self._ensured_mappings.add(key) 

382 

383 if self.team_dao.ensure_team_mapping(team["id"], age_group_id, division_id): 

384 logger.info( 

385 "Registered team age group", 

386 team_id=team["id"], 

387 age_group_id=age_group_id, 

388 division_id=division_id, 

389 ) 

390 

391 def _resolve_season_id(self, match_data: dict[str, Any]) -> int: 

392 """The season the message names, not the one the calendar is on. 

393 

394 A match belongs to the season it was played in. Filing by the current 

395 season instead makes every historical load land in the wrong year, and 

396 puts a May fixture re-scraped in August into the new season (SB-882). 

397 

398 Falls back to the current season when the message names none or names 

399 one MT does not have, and says so — a silent fallback is how 151 

400 matches with 2025-2026 dates ended up in 2026-2027. 

401 """ 

402 named = (match_data.get("season") or "").strip() 

403 if named: 

404 season = self.season_dao.get_season_by_name(named) 

405 if season: 

406 return season["id"] 

407 logger.warning( 

408 "Unknown season in message, falling back to current", 

409 season=named, 

410 external_match_id=match_data.get("external_match_id"), 

411 ) 

412 

413 current_season = self.season_dao.get_current_season() 

414 return current_season["id"] if current_season else 1 

415 

416 @staticmethod 

417 def _read_shootout(match_data: dict[str, Any]) -> tuple[int | None, int | None]: 

418 """The penalty shootout on the message, if it is one the DB will accept. 

419 

420 MLS NEXT Flex fixtures cannot end level — a regulation draw is decided 

421 on penalties (SB-1019/SB-1020). The matches table has carried the pair 

422 since the tournament work, under two CHECK constraints: both columns or 

423 neither, and only when regulation ended level. 

424 

425 A message that breaks either is reported and its shootout dropped, 

426 rather than raised: the alternative loses a real fixture over a field 

427 that is decoration on the scoreline. The scraper filters both shapes 

428 before sending, so anything arriving here came from somewhere else. 

429 """ 

430 home_pens = match_data.get("home_penalty_score") 

431 away_pens = match_data.get("away_penalty_score") 

432 if home_pens is None and away_pens is None: 

433 return None, None 

434 

435 label = ( 

436 f"{match_data.get('home_team')} vs {match_data.get('away_team')} ({match_data.get('external_match_id')})" 

437 ) 

438 if home_pens is None or away_pens is None: 

439 logger.warning( 

440 "Ignoring half a penalty shootout", 

441 match=label, 

442 home_penalty_score=home_pens, 

443 away_penalty_score=away_pens, 

444 ) 

445 return None, None 

446 

447 home_score = match_data.get("home_score") 

448 away_score = match_data.get("away_score") 

449 if home_score is None or away_score is None or home_score != away_score: 

450 logger.warning( 

451 "Ignoring a penalty shootout on a match that was not level", 

452 match=label, 

453 score=f"{home_score}-{away_score}", 

454 shootout=f"{home_pens}-{away_pens}", 

455 ) 

456 return None, None 

457 

458 return home_pens, away_pens 

459 

460 @staticmethod 

461 def _read_location(match_data: dict[str, Any]) -> str | None: 

462 """The message's location, cleaned and capped, or None when it has none (SB-1874). 

463 

464 Non-printable characters are dropped and whitespace collapsed: Postgres 

465 rejects a NUL in text, and a zero-width space would render as a blank 

466 line. A lone surrogate cannot be sent at all, so it is no location. A 

467 placeholder ("TBD", "TBA", "bye") is no location either — written, it 

468 would replace a real pitch and render as one. 

469 """ 

470 raw = match_data.get("location") 

471 if not isinstance(raw, str): 

472 return None 

473 try: 

474 raw.encode("utf-8") 

475 except UnicodeEncodeError: 

476 return None 

477 printable = "".join(c for c in raw if c.isprintable() or c.isspace()) 

478 location = " ".join(printable.split())[:MAX_LOCATION_LENGTH].rstrip() 

479 if not location or location.lower().strip(" .-") in PLACEHOLDER_NAMES: 

480 return None 

481 return location 

482 

483 @classmethod 

484 def _incoming_location(cls, existing_match: dict[str, Any], new_data: dict[str, Any]) -> str | None: 

485 """The location to write over the row's, or None to leave it alone (SB-1874). 

486 

487 A message without one never clears a stored location. A row read with 

488 no location key comes from a database the column has not reached yet 

489 (``migrate prod`` is run by hand, separately from any deploy), so 

490 nothing is written. 

491 """ 

492 if "location" not in existing_match: 

493 return None 

494 location = cls._read_location(new_data) 

495 if location and location != existing_match.get("location"): 

496 return location 

497 return None 

498 

499 @staticmethod 

500 def _feed_kickoff(match_data: dict[str, Any]) -> str | None: 

501 """The feed's own kickoff instant, as a UTC ISO 8601 string (SB-1203). 

502 

503 match-scraper sends ``scheduled_kickoff`` straight from the feed's UTC 

504 ``start_time``. It is exact, so it beats any reading of match_time. 

505 A value without an offset, or one that doesn't parse, is ignored with a 

506 warning: guessing its zone is the bug this replaces (SB-1202). 

507 """ 

508 raw = match_data.get("scheduled_kickoff") 

509 if not raw: 

510 return None 

511 try: 

512 parsed = datetime.fromisoformat(str(raw).replace("Z", "+00:00")) 

513 except ValueError: 

514 logger.warning("Ignoring an unparseable scheduled_kickoff", scheduled_kickoff=raw) 

515 return None 

516 if parsed.tzinfo is None: 

517 logger.warning("Ignoring a scheduled_kickoff with no UTC offset", scheduled_kickoff=raw) 

518 return None 

519 return parsed.astimezone(ZoneInfo("UTC")).strftime("%Y-%m-%dT%H:%M:%S+00:00") 

520 

521 @staticmethod 

522 def _build_scheduled_kickoff(match_data: dict[str, Any], venue_tz: str = DEFAULT_KICKOFF_TZ) -> str | None: 

523 """Combine match_date + match_time into a UTC ISO 8601 timestamp for scheduled_kickoff. 

524 

525 match_time is the venue's local wall-clock time, not US Eastern: the 

526 feed converts its UTC start to the event's own timezone (SB-1202). 

527 ``venue_tz`` is the IANA zone to read it in; an unknown name falls back 

528 to Eastern with a warning. 

529 

530 Returns None if match_time is absent or null. 

531 """ 

532 match_time = match_data.get("match_time") 

533 match_date = match_data.get("match_date") 

534 if match_time and match_date: 

535 try: 

536 zone = ZoneInfo(venue_tz) 

537 except (ZoneInfoNotFoundError, ValueError): 

538 logger.warning("Unknown kickoff timezone, reading match_time as Eastern", timezone=venue_tz) 

539 zone = ZoneInfo(DEFAULT_KICKOFF_TZ) 

540 naive = datetime.strptime(f"{match_date} {match_time}", "%Y-%m-%d %H:%M") 

541 local_dt = naive.replace(tzinfo=zone) 

542 utc_dt = local_dt.astimezone(ZoneInfo("UTC")) 

543 return utc_dt.strftime("%Y-%m-%dT%H:%M:%S+00:00") 

544 return None 

545 

546 def _home_timezone(self, home_team_id: int | None) -> str: 

547 """The home club's IANA timezone, or Eastern when it can't be found.""" 

548 if home_team_id is None: 

549 return DEFAULT_KICKOFF_TZ 

550 try: 

551 club = self.club_dao.get_club_for_team(home_team_id) 

552 except Exception as exc: 

553 logger.warning("Home club timezone lookup failed", home_team_id=home_team_id, error=str(exc)) 

554 return DEFAULT_KICKOFF_TZ 

555 return (club or {}).get("timezone") or DEFAULT_KICKOFF_TZ 

556 

557 def _resolve_kickoff(self, match_data: dict[str, Any], home_team_id: int | None) -> str | None: 

558 """The UTC kickoff to store: the feed's instant, else match_time read in the home club's zone. 

559 

560 The club lookup only happens on the fallback path, so a payload that 

561 carries scheduled_kickoff costs no extra query. 

562 """ 

563 feed_kickoff = self._feed_kickoff(match_data) 

564 if feed_kickoff: 

565 return feed_kickoff 

566 if not (match_data.get("match_time") and match_data.get("match_date")): 

567 return None 

568 return self._build_scheduled_kickoff(match_data, self._home_timezone(home_team_id)) 

569 

570 def _match_type_label(self, match_type_id: int | None) -> str: 

571 """A competition's name for a log line, falling back to its id.""" 

572 if match_type_id is None: 

573 return "none" 

574 row = self.match_type_dao.get_match_type_by_id(match_type_id) 

575 return (row or {}).get("name") or str(match_type_id) 

576 

577 @staticmethod 

578 def _feed_owns_filing(existing_match: dict[str, Any]) -> bool: 

579 """Whether the feed gets to re-file this match's competition and division. 

580 

581 Scraped data wins on results, and competition and division arrive from 

582 the feed the same way scores do — so a correction should land. A match 

583 somebody entered by hand is the exception: a friendly recorded against 

584 a league fixture's external id is a deliberate choice, and silently 

585 re-filing it would be the product overruling its user. 

586 

587 Adoption flips the answer rather than being a special case — populating 

588 an external id on a manual match stamps source='match-scraper' — so 

589 this reads the row's current owner, not how it was born. 

590 

591 A row with no source at all predates the column's use on this path and 

592 is treated as the feed's, which is what it is. 

593 

594 Exactly 'match-scraper': a row the live sender created carries 

595 'match-scraper-agent' and is not re-filed here. Tournament columns use 

596 _feed_owns_tournament_filing, which accepts both — the two disagree on 

597 purpose for now, and this one is the one that is behind. 

598 """ 

599 return (existing_match.get("source") or "match-scraper") == "match-scraper" 

600 

601 @staticmethod 

602 def _feed_owns_tournament_filing(existing_match: dict[str, Any]) -> bool: 

603 """Whether the feed gets to re-file this match's tournament columns. 

604 

605 The same rule as _feed_owns_filing, for any source in FEED_SOURCES: a 

606 corrected group, round or order on a rescrape has to reach the rows 

607 match-scraper-agent created, which is most of them (SB-1747). 

608 """ 

609 return (existing_match.get("source") or "match-scraper") in FEED_SOURCES 

610 

611 @staticmethod 

612 def _score_locked(existing_match: dict[str, Any]) -> bool: 

613 """Whether a person locked this match's result against the feed (SB-1787). 

614 

615 A locked row keeps its scores, shootout, status and home/away 

616 assignment whatever a message says. Home/away is held with the score: 

617 swapping the teams under a held 3-1 would turn it into the other 

618 side's win. Date, kickoff and filing still follow the feed. 

619 """ 

620 return bool(existing_match.get("score_locked")) 

621 

622 @staticmethod 

623 def _person_sourced(source: str | None) -> bool: 

624 """Whether a row with this source is one a person entered (SB-1787). 

625 

626 Read from the row's source as it was *before* this message: adopting a 

627 hand-entered row stamps it 'match-scraper', and after that the row is 

628 the feed's. A row with no source is the feed's, as in _feed_owns_filing. 

629 

630 updated_by is deliberately not the signal. The legacy sync endpoint 

631 stamps it for the scraper's own service account, and any edit — a 

632 kickoff time — sets it for good, so it does not say whose the score is. 

633 The known gap: a person who edits a *scraped* row's score through an 

634 edit endpoint is not distinguishable from the feed until matches carry 

635 a provenance column for the score itself. 

636 """ 

637 return (source or "match-scraper") not in FEED_SOURCES 

638 

639 def _held_by_lock( 

640 self, existing_match: dict[str, Any], new_data: dict[str, Any], home_team_id: int, away_team_id: int 

641 ) -> list[str]: 

642 """What this message would have changed on a score-locked row, as "what MT → feed". 

643 

644 Empty when the row is not locked, or the feed agrees with it. 

645 

646 When the feed has the sides the other way round, its score is turned to 

647 MT's orientation before comparing: a locked 2-1 that the feed sends as 

648 a swapped 1-2 is a disagreement about home/away only, not the score. 

649 """ 

650 if not self._score_locked(existing_match): 

651 return [] 

652 

653 held: list[str] = [] 

654 new_score = (new_data.get("home_score"), new_data.get("away_score")) 

655 new_pens = self._read_shootout(new_data) 

656 

657 existing_sides = (existing_match.get("home_team_id"), existing_match.get("away_team_id")) 

658 if existing_sides != (home_team_id, away_team_id): 

659 held.append(f"home/away {existing_sides[0]}/{existing_sides[1]} → {home_team_id}/{away_team_id}") 

660 if existing_sides == (away_team_id, home_team_id): 

661 new_score = (new_score[1], new_score[0]) 

662 new_pens = (new_pens[1], new_pens[0]) 

663 

664 existing_score = (existing_match.get("home_score"), existing_match.get("away_score")) 

665 if None not in new_score and new_score != existing_score: 

666 held.append(f"score {_pair(existing_score)} → {_pair(new_score)}") 

667 

668 existing_pens = (existing_match.get("home_penalty_score"), existing_match.get("away_penalty_score")) 

669 if new_pens != (None, None) and new_pens != existing_pens: 

670 held.append(f"shootout {_pair(existing_pens)} → {_pair(new_pens)}") 

671 

672 # A status is only a disagreement when the feed has a result behind 

673 # it. Without a score the feed's scheduled/tbd says nothing about a 

674 # locked result — it is what the feed says before it has one. 

675 new_status = self._incoming_status(existing_match, new_data) 

676 existing_status = existing_match.get("match_status") 

677 if ( 

678 None not in new_score 

679 and existing_status is not None 

680 and new_status not in (None, "scheduled", "tbd") 

681 and new_status != existing_status 

682 ): 

683 held.append(f"status {existing_status} → {new_status}") 

684 

685 return held 

686 

687 @staticmethod 

688 def _overridden_score(existing_match: dict[str, Any], written: dict[str, Any]) -> str | None: 

689 """The score or shootout a write replaced, as "what: before → after", or None. 

690 

691 Filling a score that was empty replaces nothing, and neither does 

692 writing the value already there. 

693 """ 

694 changes = [] 

695 for home_key, away_key, label in ( 

696 ("home_score", "away_score", "score"), 

697 ("home_penalty_score", "away_penalty_score", "shootout"), 

698 ): 

699 if home_key not in written and away_key not in written: 

700 continue 

701 before = (existing_match.get(home_key), existing_match.get(away_key)) 

702 after = (written.get(home_key, before[0]), written.get(away_key, before[1])) 

703 if before == (None, None) or before == after: 

704 continue 

705 changes.append(f"{label} {_pair(before)} → {_pair(after)}") 

706 return "; ".join(changes) or None 

707 

708 def _record_conflict( 

709 self, 

710 kind: str, 

711 existing_match: dict[str, Any], 

712 detail: str, 

713 *, 

714 league: str | None, 

715 source: str, 

716 sample: str, 

717 ) -> None: 

718 """Record a feed-vs-person disagreement where an admin will see it (SB-1787). 

719 

720 In ingest_failures, one row per match per kind ("match <id>"), so a 

721 match re-sent every night is one finding with a count. Recording never 

722 fails the task — IngestFailuresDAO.record swallows its own errors. 

723 

724 A row an admin has closed is not reopened by the same disagreement: the 

725 feed re-sends a locked match every night, and a closed finding that 

726 reopens every morning trains people to ignore the list. A *different* 

727 detail — the feed's score moved again — reopens it. 

728 """ 

729 raw_name = f"match {existing_match.get('id')}" 

730 full_sample = f"{sample}: {detail}" 

731 # Keyed on kind + match alone: the message's league label and sender 

732 # go into neither, so two senders or spellings cannot split one 

733 # disagreement into two rows. Both are in the log line. 

734 if self.ingest_failures_dao.resolved_with_sample( 

735 kind, raw_name, full_sample, league=None, source=CONFLICT_SOURCE 

736 ): 

737 logger.info("Conflict already closed by a person", kind=kind, match_id=existing_match.get("id")) 

738 return 

739 logger.warning( 

740 "Feed disagrees with a person's result", 

741 kind=kind, 

742 match_id=existing_match.get("id"), 

743 external_match_id=existing_match.get("match_id"), 

744 detail=detail, 

745 league=league, 

746 source=source, 

747 ) 

748 self.ingest_failures_dao.record(kind, raw_name, league=None, source=CONFLICT_SOURCE, sample=full_sample) 

749 

750 # Statuses a person sets. The scraper derives status from date and score, 

751 # and says postponed only for a fixture parked on the feed's placeholder 

752 # date (SB-1136) — it can never say one was played-but-void or cancelled. 

753 HELD_STATUSES = frozenset({"postponed", "cancelled"}) 

754 

755 @staticmethod 

756 def _incoming_date(existing_match: dict[str, Any], new_data: dict[str, Any]) -> str | None: 

757 """The new match_date to write, or None to leave the row's date alone. 

758 

759 A postponed fixture is parked by MLS NEXT on a placeholder date (in 

760 2026-2027, Tuesday 8 June 2027: 103 fixtures and nothing else that day). 

761 That date is not a reschedule, and copying it would stack every 

762 postponement on one fake Tuesday and lose the date the match was due. 

763 So a postponed message never moves the date; the next real date does 

764 (SB-1136). 

765 """ 

766 if new_data.get("match_status") == "postponed": 

767 return None 

768 new_date = new_data.get("match_date") 

769 existing_date = existing_match.get("match_date") 

770 if new_date and existing_date and new_date != existing_date: 

771 return new_date 

772 return None 

773 

774 @classmethod 

775 def _incoming_status(cls, existing_match: dict[str, Any], new_data: dict[str, Any]) -> str | None: 

776 """The status a re-scrape should leave on the row (SB-1135). 

777 

778 A postponed or cancelled status may have been set by a person, and the 

779 feed cannot say cancelled at all. A postponed fixture still sitting on its old date with 

780 no score reads to the scraper as "played, score pending", so it arrived 

781 as tbd and silently undid the human's call. 

782 

783 The held status gives way only to evidence the feed can actually carry: 

784 a real score (the match was played) or a new date (it was rescheduled, 

785 and the feed's status for the new date is the right one). 

786 """ 

787 new_status = new_data.get("match_status") 

788 existing_status = existing_match.get("match_status") 

789 

790 # A result already on the row outranks the feed calling the match off 

791 # (SB-1136): a live-scored match is not un-played by a placeholder date. 

792 if new_status == "postponed" and existing_status in ("completed", "forfeit"): 

793 return existing_status 

794 

795 # A match a person is scoring live (SB-1891). Before it has a result 

796 # the feed still calls the fixture scheduled/tbd, and writing that 

797 # would un-start the match mid-game. A real score still wins: that is 

798 # the feed's final result. 

799 if ( 

800 existing_status == "live" 

801 and new_status in (None, "scheduled", "tbd") 

802 and (new_data.get("home_score") is None or new_data.get("away_score") is None) 

803 ): 

804 return existing_status 

805 

806 if existing_status not in cls.HELD_STATUSES: 

807 return new_status 

808 

809 if new_data.get("home_score") is not None and new_data.get("away_score") is not None: 

810 return new_status 

811 

812 if cls._incoming_date(existing_match, new_data): 

813 return new_status 

814 

815 return existing_match["match_status"] 

816 

817 def _check_needs_update( 

818 self, 

819 existing_match: dict[str, Any], 

820 new_data: dict[str, Any], 

821 home_team_id: int, 

822 away_team_id: int, 

823 match_type_id: int | None = None, 

824 division_id: int | None = None, 

825 filing: TournamentFiling | None = None, 

826 adopted: bool = False, 

827 ) -> bool: 

828 """ 

829 Check if the existing match needs to be updated based on new data. 

830 

831 Returns True if any of these conditions are met: 

832 - Home/away teams swapped (home_team_id or away_team_id differ) 

833 - Status changed (scheduled → tbd, tbd → completed, etc.) 

834 - Scores changed (were null, now have values) 

835 - Scores were updated (different values) 

836 - Competition or division changed (SB-847) 

837 - Tournament filing changed (SB-1747) 

838 - The feed sends a location other than the row's (SB-1874) 

839 

840 Status transition examples: 

841 - scheduled → tbd: Match played, awaiting score 

842 - tbd → tbd: No change (skip) 

843 - tbd → completed: Score posted (update with scores) 

844 - scheduled → completed: Direct completion (skip tbd) 

845 

846 Competition and division were not compared until SB-847, which made a 

847 wrongly-filed match impossible to correct by re-scraping: the row was 

848 found, nothing recognised as changed, and the run reported success. 68 

849 Flex fixtures sat in prod as League through three clean re-submits. 

850 """ 

851 # Check competition / division re-filing (SB-847) 

852 if self._feed_owns_filing(existing_match): 

853 if match_type_id is not None and existing_match.get("match_type_id") != match_type_id: 

854 logger.debug(f"match_type changed: {existing_match.get('match_type_id')} → {match_type_id}") 

855 return True 

856 if division_id is not None and existing_match.get("division_id") != division_id: 

857 logger.debug(f"division changed: {existing_match.get('division_id')} → {division_id}") 

858 return True 

859 

860 # Check tournament re-filing (SB-1747). An adopted row only has its 

861 # nulls filled. 

862 if self._feed_owns_tournament_filing(existing_match): 

863 tournament_updates = tournament_changes(existing_match, filing, fill_only=adopted) 

864 if tournament_updates: 

865 logger.debug(f"tournament filing changed: {tournament_updates}") 

866 return True 

867 

868 # Where it is played is not part of the result, so a locked row takes 

869 # it too (SB-1874). 

870 new_location = self._incoming_location(existing_match, new_data) 

871 if new_location: 

872 logger.debug(f"location changed: {existing_match.get('location')} → {new_location}") 

873 return True 

874 

875 # A locked row's result is not the feed's to change (SB-1787): the 

876 # home/away, status, score and shootout checks below are skipped. 

877 # The kickoff is read in the row's own home club's zone: its home/away 

878 # is held, so the feed's home side is not the one playing at home. 

879 if self._score_locked(existing_match): 

880 return self._dated_or_kicked_off(existing_match, new_data, existing_match.get("home_team_id")) 

881 

882 # Check home/away team swap 

883 if existing_match.get("home_team_id") != home_team_id or existing_match.get("away_team_id") != away_team_id: 

884 logger.debug( 

885 f"Team assignment changed: home {existing_match.get('home_team_id')} → {home_team_id}, " 

886 f"away {existing_match.get('away_team_id')} → {away_team_id}" 

887 ) 

888 return True 

889 

890 # Check status change 

891 existing_status = existing_match.get("match_status", "scheduled") 

892 new_status = self._incoming_status(existing_match, new_data) or "scheduled" 

893 if existing_status != new_status: 

894 logger.debug(f"Status changed: {existing_status} → {new_status}") 

895 return True 

896 

897 # Check score changes 

898 existing_home_score = existing_match.get("home_score") 

899 existing_away_score = existing_match.get("away_score") 

900 new_home_score = new_data.get("home_score") 

901 new_away_score = new_data.get("away_score") 

902 

903 # If new data has scores and they differ from existing 

904 if new_home_score is not None and new_away_score is not None: 

905 if existing_home_score != new_home_score or existing_away_score != new_away_score: 

906 logger.debug( 

907 f"Scores changed: {existing_home_score}-{existing_away_score} → {new_home_score}-{new_away_score}" 

908 ) 

909 return True 

910 

911 # Check the penalty shootout (SB-1020). Without this a fixture whose 

912 # score was already right but whose shootout was missing — every Flex 

913 # draw ingested before this shipped — reads as unchanged and is never 

914 # corrected, the same trap SB-847 documented above. 

915 new_pens = self._read_shootout(new_data) 

916 if new_pens != (None, None): 

917 existing_pens = ( 

918 existing_match.get("home_penalty_score"), 

919 existing_match.get("away_penalty_score"), 

920 ) 

921 if existing_pens != new_pens: 

922 logger.debug(f"Penalty shootout changed: {existing_pens} → {new_pens}") 

923 return True 

924 

925 return self._dated_or_kicked_off(existing_match, new_data, home_team_id) 

926 

927 def _dated_or_kicked_off(self, existing_match: dict[str, Any], new_data: dict[str, Any], home_team_id: int) -> bool: 

928 """Whether the feed moves the match's date or sets/changes its kickoff.""" 

929 # Check if match_date changed (rescheduled match) 

930 new_date = self._incoming_date(existing_match, new_data) 

931 if new_date: 

932 logger.debug(f"match_date changed: {existing_match.get('match_date')} → {new_date}") 

933 return True 

934 

935 # Check if scheduled_kickoff can be set/updated from the feed 

936 new_kickoff = self._resolve_kickoff(new_data, home_team_id) 

937 existing_kickoff = existing_match.get("scheduled_kickoff") 

938 if new_kickoff and new_kickoff != existing_kickoff: 

939 logger.debug(f"scheduled_kickoff changed: {existing_kickoff} → {new_kickoff}") 

940 return True 

941 

942 return False 

943 

944 def _update_match_scores( 

945 self, 

946 existing_match: dict[str, Any], 

947 new_data: dict[str, Any], 

948 home_team_id: int | None = None, 

949 away_team_id: int | None = None, 

950 match_type_id: int | None = None, 

951 division_id: int | None = None, 

952 filing: TournamentFiling | None = None, 

953 adopted: bool = False, 

954 ) -> dict[str, Any] | bool: 

955 """ 

956 Update an existing match's scores, status, team assignments and filing. 

957 

958 Returns the fields written (truthy) on success, False when nothing 

959 changed or the write failed. The caller compares them with the row 

960 before to decide whether a final-score alert is due (SB-1619). 

961 

962 Updates scores, status, match_date, scheduled_kickoff, location, 

963 home_team_id/away_team_id when a home/away swap is detected, and 

964 match_type_id/division_id and the tournament columns when the feed 

965 re-files the match (SB-847, SB-1747). ``adopted`` marks a hand-entered 

966 row taken over by this message: its tournament columns are only filled 

967 where they are null. 

968 """ 

969 try: 

970 match_id = existing_match["id"] 

971 

972 # Prepare update data 

973 update_data: dict[str, object] = {} 

974 

975 # Correct competition and division. Logged by name, not id: a line 

976 # reading "match_type corrected: 1 → 5" tells nobody that a fixture 

977 # moved from League to Flex, and the whole point of this is that a 

978 # competition move stops being silent. 

979 if self._feed_owns_filing(existing_match): 

980 if match_type_id is not None and match_type_id != existing_match.get("match_type_id"): 

981 update_data["match_type_id"] = match_type_id 

982 logger.info( 

983 f"Match {match_id} match_type corrected: " 

984 f"{self._match_type_label(existing_match.get('match_type_id'))} → " 

985 f"{self._match_type_label(match_type_id)}" 

986 ) 

987 if division_id is not None and division_id != existing_match.get("division_id"): 

988 update_data["division_id"] = division_id 

989 logger.info( 

990 f"Match {match_id} division corrected: {existing_match.get('division_id')} → {division_id}" 

991 ) 

992 

993 # Correct the tournament filing. On a row just adopted from a 

994 # person, only what they left empty (SB-1747). 

995 if self._feed_owns_tournament_filing(existing_match): 

996 tournament_updates = tournament_changes(existing_match, filing, fill_only=adopted) 

997 if tournament_updates: 

998 update_data.update(tournament_updates) 

999 logger.info(f"Match {match_id} tournament filing corrected: {tournament_updates}") 

1000 

1001 # Fill or change the location; a message without one leaves it 

1002 # (SB-1874). 

1003 new_location = self._incoming_location(existing_match, new_data) 

1004 if new_location: 

1005 update_data["location"] = new_location 

1006 

1007 # A locked row keeps its result: home/away, scores, shootout and 

1008 # status are not written (SB-1787). 

1009 locked = self._score_locked(existing_match) 

1010 

1011 # Correct home/away team swap if team IDs differ 

1012 if not locked and home_team_id is not None and home_team_id != existing_match.get("home_team_id"): 

1013 update_data["home_team_id"] = home_team_id 

1014 logger.info( 

1015 f"Match {match_id} home_team_id corrected: {existing_match.get('home_team_id')} → {home_team_id}" 

1016 ) 

1017 if not locked and away_team_id is not None and away_team_id != existing_match.get("away_team_id"): 

1018 update_data["away_team_id"] = away_team_id 

1019 logger.info( 

1020 f"Match {match_id} away_team_id corrected: {existing_match.get('away_team_id')} → {away_team_id}" 

1021 ) 

1022 

1023 if not locked: 

1024 # Update scores as a pair, as _check_needs_update compares 

1025 # them. Half a score is not a result: written alone it turned a 

1026 # stored 2-1 into 3-1 once a location change let the row 

1027 # through (SB-1874). 

1028 if new_data.get("home_score") is not None and new_data.get("away_score") is not None: 

1029 update_data["home_score"] = new_data["home_score"] 

1030 update_data["away_score"] = new_data["away_score"] 

1031 

1032 # Update the penalty shootout, both columns together (SB-1020). 

1033 home_pens, away_pens = self._read_shootout(new_data) 

1034 if home_pens is not None and away_pens is not None: 

1035 update_data["home_penalty_score"] = home_pens 

1036 update_data["away_penalty_score"] = away_pens 

1037 

1038 # Update status if provided, unless a person's postponed/cancelled 

1039 # still stands (SB-1135) 

1040 new_status = self._incoming_status(existing_match, new_data) 

1041 if new_status: 

1042 update_data["match_status"] = new_status 

1043 

1044 # Update match_date if changed (rescheduled match) 

1045 new_date = self._incoming_date(existing_match, new_data) 

1046 if new_date: 

1047 update_data["match_date"] = new_date 

1048 logger.info(f"Match {match_id} rescheduled: {existing_match.get('match_date')} → {new_date}") 

1049 

1050 # Update scheduled_kickoff if the feed gives one and it differs 

1051 # A locked row keeps its home side, so its kickoff is read in that 

1052 # side's club zone, not the feed's home side's (SB-1787). 

1053 kickoff_home = existing_match.get("home_team_id") if locked or home_team_id is None else home_team_id 

1054 new_kickoff = self._resolve_kickoff(new_data, kickoff_home) 

1055 if new_kickoff and new_kickoff != existing_match.get("scheduled_kickoff"): 

1056 update_data["scheduled_kickoff"] = new_kickoff 

1057 

1058 # Note: updated_by field expects UUID, not string. 

1059 # For match-scraper updates, we'll skip this field since it's optional. 

1060 # If we need to track match-scraper updates, we should use 'source' field instead. 

1061 

1062 if not update_data: 

1063 logger.warning(f"No update data provided for match {match_id}") 

1064 return False 

1065 

1066 # A match on a tournament is written through the DAO method that 

1067 # clears the tournament cache where this process shares the API's 

1068 # cache (SB-1747). The worker cannot clear the API's cache, so the 

1069 # clear is a no-op here and the tournament page catches up within 

1070 # about a minute, when the short TTL on the tournament reads 

1071 # expires (SB-1756). League matches are written directly, as before. 

1072 if existing_match.get("tournament_id") is not None or "tournament_id" in update_data: 

1073 written = self.dao.update_ingested_tournament_match(match_id, update_data) 

1074 else: 

1075 response = self.dao.client.table("matches").update(update_data).eq("id", match_id).execute() 

1076 written = bool(response.data) 

1077 

1078 if written: 

1079 logger.info(f"Successfully updated match {match_id}: {update_data}") 

1080 return update_data 

1081 else: 

1082 logger.error(f"Update returned no data for match {match_id}") 

1083 return False 

1084 

1085 except Exception as e: 

1086 logger.error(f"Error updating match scores: {e}", exc_info=True) 

1087 return False 

1088 

1089 

1090@app.task( 

1091 bind=True, 

1092 base=DatabaseTask, 

1093 name="celery_tasks.match_tasks.process_match_data", 

1094 max_retries=3, 

1095 default_retry_delay=60, # Retry after 1 minute 

1096 autoretry_for=(Exception,), # Auto-retry on any exception 

1097 # ...except a name that does not exist. Waiting ten minutes will not make 

1098 # an unknown team known; retrying three times only delays the moment 

1099 # anyone finds out (SB-829). 

1100 dont_autoretry_for=(UnresolvedNameError,), 

1101 retry_backoff=True, # Exponential backoff 

1102 retry_backoff_max=600, # Max 10 minutes backoff 

1103 retry_jitter=True, # Add random jitter to prevent thundering herd 

1104) 

1105def process_match_data(self: DatabaseTask, match_data: dict[str, Any]) -> dict[str, Any]: 

1106 """ 

1107 Process match data from match-scraper and insert into database. 

1108 

1109 This task: 

1110 1. Validates the match data 

1111 2. Extracts/creates teams if needed 

1112 3. Inserts or updates the match in the database 

1113 4. Returns the created/updated match ID 

1114 

1115 Args: 

1116 match_data: Dictionary containing match information 

1117 Required fields: 

1118 - home_team: str 

1119 - away_team: str 

1120 - match_date: str (ISO format) 

1121 - season: str 

1122 - age_group: str 

1123 - division: str (league messages; omitted on a tournament message) 

1124 Optional fields: 

1125 - home_score: int 

1126 - away_score: int 

1127 - home_penalty_score / away_penalty_score: int, as a pair, only 

1128 when regulation ended level 

1129 - match_status: str 

1130 - match_type: str ("Tournament" on a tournament message) 

1131 - league: str (scopes team and division lookups) 

1132 - external_match_id: str (the source match id a rescrape upserts 

1133 on; required on a tournament message) 

1134 - source: str (provenance; defaults to "match-scraper") 

1135 - location: str (venue and pitch, stored on the match, SB-1874; 

1136 a blank one never clears a stored value) 

1137 - match_time: str ("HH:MM", the venue's local time) 

1138 - scheduled_kickoff: str (ISO 8601 with offset, the feed's UTC 

1139 kickoff; preferred over match_time when present) 

1140 Tournament fields (SB-1747) — tournament_id makes the message a 

1141 tournament message; the rest mean nothing without it: 

1142 - tournament_id: int 

1143 - competition: str (the feed's own name, e.g. "HD Group Play") 

1144 - tournament_group: str (the feed's own label, e.g. "A") 

1145 - tournament_round: str (a round key, e.g. "group_stage") 

1146 - tournament_round_order: int 

1147 

1148 Returns: 

1149 Dict containing: 

1150 - match_id: int - The database ID of the created/updated match 

1151 - status: str - 'created' or 'updated' 

1152 - message: str - Success message 

1153 

1154 Raises: 

1155 ValidationError: If match data is invalid 

1156 DatabaseError: If database operation fails 

1157 """ 

1158 try: 

1159 mls_id = match_data.get("external_match_id", "N/A") 

1160 logger.info( 

1161 f"Processing match data: {match_data.get('home_team')} vs {match_data.get('away_team')} (MLS ID: {mls_id})" 

1162 ) 

1163 

1164 sample = ( 

1165 f"{match_data.get('home_team')} vs {match_data.get('away_team')}, " 

1166 f"{match_data.get('match_date')} {match_data.get('age_group', '')}" 

1167 ).strip() 

1168 

1169 # Step 0: Read the tournament filing, if the message carries one 

1170 # (SB-1747). Read ahead of the general validation, which reports the 

1171 # same problems but as a retried ValueError: tournament fields that 

1172 # cannot be filed are permanent, and are recorded once per distinct 

1173 # problem in ingest_failures instead. 

1174 try: 

1175 filing = read_tournament_filing(match_data) 

1176 except TournamentFilingError as e: 

1177 raise UnresolvedNameError("invalid", str(e), league=match_data.get("league"), sample=sample) from e 

1178 if filing and filing.tournament_round and filing.tournament_round not in VALID_ROUNDS: 

1179 logger.warning( 

1180 "Tournament round is not one MT knows — filing it anyway", 

1181 tournament_round=filing.tournament_round, 

1182 tournament_id=filing.tournament_id, 

1183 external_match_id=match_data.get("external_match_id"), 

1184 ) 

1185 

1186 # Step 1: Validate the match data 

1187 validation_result = validate_match_data(match_data) 

1188 if not validation_result["valid"]: 

1189 error_msg = f"Invalid match data: {validation_result['errors']}" 

1190 logger.error(error_msg) 

1191 raise ValueError(error_msg) 

1192 

1193 # Step 2: Extract team information 

1194 home_team_name = match_data["home_team"] 

1195 away_team_name = match_data["away_team"] 

1196 # The feed's competition name scopes both lookups below. Team aliases 

1197 # and division names are unique per league, not globally, so resolving 

1198 # the league first is what keeps two competitions that share a name 

1199 # ("Florida" is a Homegrown division and a Flex one) apart. 

1200 league_name = match_data.get("league") 

1201 league_id = None 

1202 if league_name: 

1203 league_record = self.league_dao.get_league_by_name(league_name) 

1204 if league_record: 

1205 league_id = league_record["id"] 

1206 else: 

1207 logger.warning(f"League '{league_name}' not found - name lookups will not be league-scoped") 

1208 

1209 logger.debug(f"Looking up teams: {home_team_name}, {away_team_name} (league_id={league_id})") 

1210 

1211 # On a tournament message the league says which side's team a name 

1212 # means (SB-1748), so one MT does not have is a failure of its own: 

1213 # one row for the string, before any team is looked up. Left to the 

1214 # side guard, every team in the event would fail as "wrong side". A 

1215 # league message keeps the unscoped lookups it was warned about above. 

1216 tournament_leagues = None 

1217 if filing is not None and (league_name or "").strip(): 

1218 tournament_leagues = self._tournament_leagues() 

1219 known = {row["id"]: row for row in tournament_leagues} 

1220 if league_named(league_name, known) is None: 

1221 raise UnresolvedNameError("league", league_name.strip(), sample=sample) 

1222 

1223 # A tournament message's teams are resolved at its age group (SB-1748), 

1224 # so the age group is looked up here rather than after the division, 

1225 # where a league message still looks it up. 

1226 # 

1227 # A league match with an unknown age group falls back to id 1 on 

1228 # create. At a six-age-group tournament that default would file a 

1229 # whole age group's fixtures under another's, so here it is a 

1230 # failure (SB-1747). 

1231 age_group_id = None 

1232 if filing is not None: 

1233 if match_data.get("age_group"): 

1234 age_group_record = self.season_dao.get_age_group_by_name(match_data["age_group"]) 

1235 if age_group_record: 

1236 age_group_id = age_group_record["id"] 

1237 if age_group_id is None: 

1238 raise UnresolvedNameError( 

1239 "invalid", 

1240 f"unknown age group '{match_data.get('age_group') or ''}' on a tournament match", 

1241 league=league_name, 

1242 sample=sample, 

1243 ) 

1244 

1245 # Resolve teams. An unknown name fails the task; nothing is created. 

1246 home_team = self._resolve_team( 

1247 home_team_name, 

1248 league_id=league_id, 

1249 league_name=league_name, 

1250 sample=sample, 

1251 filing=filing, 

1252 age_group_id=age_group_id, 

1253 leagues=tournament_leagues, 

1254 ) 

1255 away_team = self._resolve_team( 

1256 away_team_name, 

1257 league_id=league_id, 

1258 league_name=league_name, 

1259 sample=sample, 

1260 filing=filing, 

1261 age_group_id=age_group_id, 

1262 leagues=tournament_leagues, 

1263 ) 

1264 

1265 # Both names are good. If either was failing before — an alias added 

1266 # part way through a load, say — close its row now. 

1267 source = match_data.get("source") or "match-scraper" 

1268 if filing is None: 

1269 self._note_name_resolved("team", home_team_name, source) 

1270 self._note_name_resolved("team", away_team_name, source) 

1271 else: 

1272 self._note_tournament_team_resolved(home_team_name, league_name, source) 

1273 self._note_tournament_team_resolved(away_team_name, league_name, source) 

1274 

1275 # Step 2b: Resolve how the feed files this match — competition and 

1276 # division — before the create/update fork. 

1277 # 

1278 # Both used to be resolved only on the create branch, which is half of 

1279 # why a wrongly-filed match could not be corrected by re-scraping 

1280 # (SB-847). The other half was that create ignored the feed's 

1281 # competition entirely and wrote match_type_id 1: 68 Flex fixtures 

1282 # went into prod as League (SB-846) and three clean re-submits could 

1283 # not move them. 

1284 match_type_id = None 

1285 match_type_name = match_data.get("match_type") 

1286 if match_type_name: 

1287 match_type_record = self.match_type_dao.get_match_type_by_name(match_type_name) 

1288 if not match_type_record: 

1289 # Same reasoning as an unknown division below: defaulting to 

1290 # League is exactly the failure this ticket exists to end. 

1291 raise UnresolvedNameError( 

1292 "match_type", 

1293 match_type_name, 

1294 league=league_name, 

1295 sample=sample, 

1296 ) 

1297 match_type_id = match_type_record["id"] 

1298 self._note_name_resolved("match_type", match_type_name, source) 

1299 

1300 division_record = None 

1301 division_id = None 

1302 if match_data.get("division"): 

1303 div_record = self.league_dao.get_division_by_name(match_data["division"], league_id=league_id) 

1304 if div_record: 

1305 division_record = div_record 

1306 division_id = div_record["id"] 

1307 else: 

1308 # Writing NULL here used to look like a warning and behave 

1309 # like data loss: get_league_table filters on division, so 

1310 # the match existed but appeared in no table at all. 

1311 raise UnresolvedNameError( 

1312 "division", 

1313 match_data["division"], 

1314 league=league_name, 

1315 sample=sample, 

1316 ) 

1317 

1318 # A tournament message resolved its age group above, before its teams. 

1319 if filing is None and match_data.get("age_group"): 

1320 age_group_record = self.season_dao.get_age_group_by_name(match_data["age_group"]) 

1321 if age_group_record: 

1322 age_group_id = age_group_record["id"] 

1323 else: 

1324 logger.warning(f"Age group not found: {match_data['age_group']}") 

1325 

1326 # A tournament message is filed on its tournament and has no division 

1327 # (the filing read above rejects one that sends both). 

1328 if filing: 

1329 self._require_tournament(filing, league_name=league_name, sample=sample) 

1330 

1331 # Record that both teams play this age group in this division. Nothing 

1332 # did, so a team the scraper had filed matches for all season did not 

1333 # exist at that age group as far as the team pickers were concerned 

1334 # (SB-852). 

1335 self._register_team_age_group(home_team, age_group_id, division_record) 

1336 self._register_team_age_group(away_team, age_group_id, division_record) 

1337 

1338 # Step 3: Check if match already exists 

1339 external_match_id = match_data.get("external_match_id") 

1340 existing_match = None 

1341 adopted = False 

1342 # The row's owner before this message: adoption below re-stamps a 

1343 # hand-entered row as the feed's (SB-1787). 

1344 source_before: str | None = None 

1345 

1346 # First try: Look up by external ID (fast path for previously scraped matches) 

1347 if external_match_id: 

1348 existing_match = self.dao.get_match_by_external_id(external_match_id) 

1349 logger.debug( 

1350 f"Lookup by external_match_id '{external_match_id}': {'found' if existing_match else 'not found'}" 

1351 ) 

1352 if existing_match: 

1353 source_before = existing_match.get("source") 

1354 

1355 # Second try: Fallback to lookup by teams + date + age_group (for manually-entered matches) 

1356 if not existing_match: 

1357 existing_match = self.dao.get_match_by_teams_and_date( 

1358 home_team_id=home_team["id"], 

1359 away_team_id=away_team["id"], 

1360 match_date=match_data["match_date"], 

1361 age_group_id=age_group_id, 

1362 ) 

1363 

1364 # A tournament message adopts a hit only when it is a hand-entered 

1365 # match on the same tournament (SB-1747). A league or friendly row, 

1366 # or one on another tournament, is a different match between the 

1367 # same teams that day; so is a hit that already carries a different 

1368 # source id — routine at a tournament. Either is left alone and 

1369 # this message creates its own row. A league message takes the hit 

1370 # as it always has. 

1371 if existing_match and filing is not None: 

1372 if existing_match.get("tournament_id") != filing.tournament_id: 

1373 logger.info( 

1374 f"Ignoring fallback match {existing_match['id']}: it is not on tournament " 

1375 f"{filing.tournament_id}" 

1376 ) 

1377 existing_match = None 

1378 elif self._is_other_fixture(existing_match, external_match_id): 

1379 logger.info( 

1380 f"Ignoring fallback match {existing_match['id']}: it is source match " 

1381 f"{existing_match.get('match_id')}, not {external_match_id}" 

1382 ) 

1383 existing_match = None 

1384 

1385 if existing_match: 

1386 source_before = existing_match.get("source") 

1387 logger.info( 

1388 f"Found manually-entered match via fallback lookup: " 

1389 f"{home_team_name} vs {away_team_name} on {match_data['match_date']}" 

1390 + (f" ({match_data['age_group']})" if match_data.get("age_group") else "") 

1391 ) 

1392 

1393 # If found a match without external_match_id, populate it 

1394 if external_match_id and not existing_match.get("match_id"): 

1395 logger.info(f"Populating match_id '{external_match_id}' on existing match {existing_match['id']}") 

1396 success = self.dao.update_match_external_id( 

1397 match_id=existing_match["id"], external_match_id=external_match_id 

1398 ) 

1399 if success: 

1400 # Update the existing_match dict to reflect the new match_id 

1401 existing_match["match_id"] = external_match_id 

1402 existing_match["source"] = "match-scraper" 

1403 adopted = True 

1404 logger.info(f"Successfully populated match_id on match {existing_match['id']}") 

1405 else: 

1406 logger.warning(f"Failed to populate match_id on match {existing_match['id']}") 

1407 

1408 # A tournament message never moves a row off a league or off another 

1409 # tournament (SB-1747). 

1410 if existing_match and filing is not None: 

1411 self._require_row_on_tournament(existing_match, filing, league_name=league_name, sample=sample) 

1412 

1413 # Step 4: Insert or update match 

1414 if existing_match: 

1415 # A locked result is held (SB-1787). What the feed said is worked 

1416 # out against the row as read, and recorded once the message has 

1417 # been processed — not before, or every autoretry of a failed 

1418 # write would count the same disagreement again. 

1419 held = self._held_by_lock(existing_match, match_data, home_team["id"], away_team["id"]) 

1420 

1421 # Check if this is a score update 

1422 needs_update = self._check_needs_update( 

1423 existing_match, 

1424 match_data, 

1425 home_team["id"], 

1426 away_team["id"], 

1427 match_type_id=match_type_id, 

1428 division_id=division_id, 

1429 filing=filing, 

1430 adopted=adopted, 

1431 ) 

1432 

1433 if needs_update: 

1434 logger.info( 

1435 f"Updating existing match DB ID {existing_match['id']} (MLS ID: {external_match_id}): " 

1436 f"{home_team_name} vs {away_team_name}" 

1437 ) 

1438 success = self._update_match_scores( 

1439 existing_match, 

1440 match_data, 

1441 home_team["id"], 

1442 away_team["id"], 

1443 match_type_id=match_type_id, 

1444 division_id=division_id, 

1445 filing=filing, 

1446 adopted=adopted, 

1447 ) 

1448 

1449 if success: 

1450 written = success if isinstance(success, dict) else {} 

1451 # Scraped data wins on results, but a person's score it 

1452 # replaced is surfaced, not just logged (SB-1787). Whose 

1453 # score it was is the row's source before this message; 

1454 # once adopted the row is the feed's, so an adoption that 

1455 # carried no score leaves nothing to compare later. 

1456 if self._person_sourced(source_before): 

1457 overridden = self._overridden_score(existing_match, written) 

1458 if overridden: 

1459 self._record_conflict( 

1460 SCRAPED_OVERRODE_MANUAL, 

1461 existing_match, 

1462 overridden, 

1463 league=league_name, 

1464 source=source, 

1465 sample=sample, 

1466 ) 

1467 alert_if_new_final_score(existing_match, {**existing_match, **written}) 

1468 result = { 

1469 "db_id": existing_match["id"], 

1470 "mls_id": external_match_id, 

1471 "status": "updated", 

1472 "message": f"Updated match scores: {home_team_name} vs {away_team_name}", 

1473 } 

1474 else: 

1475 raise Exception(f"Failed to update match {existing_match['id']}") 

1476 else: 

1477 logger.info( 

1478 f"Match already exists with DB ID {existing_match['id']} (MLS ID: {external_match_id}). " 

1479 "No changes needed." 

1480 ) 

1481 result = { 

1482 "db_id": existing_match["id"], 

1483 "mls_id": external_match_id, 

1484 "status": "skipped", 

1485 "message": f"Match unchanged: {home_team_name} vs {away_team_name}", 

1486 } 

1487 

1488 if held: 

1489 self._record_conflict( 

1490 SCORE_LOCKED, 

1491 existing_match, 

1492 "held " + "; ".join(held), 

1493 league=league_name, 

1494 source=source, 

1495 sample=sample, 

1496 ) 

1497 else: 

1498 logger.info(f"Creating new match (MLS ID: {external_match_id}): {home_team_name} vs {away_team_name}") 

1499 

1500 # Resolve names to IDs before calling create_match 

1501 season_id = self._resolve_season_id(match_data) 

1502 

1503 # Resolved once above, for both branches. 1 remains the fallback 

1504 # for a league feed that names an age group we do not have; a 

1505 # tournament message with one has already failed above. 

1506 age_group_id_for_create = age_group_id or 1 

1507 

1508 scheduled_kickoff = self._resolve_kickoff(match_data, home_team["id"]) 

1509 home_pens, away_pens = self._read_shootout(match_data) 

1510 

1511 match_id = self.dao.create_match( 

1512 home_team_id=home_team["id"], 

1513 away_team_id=away_team["id"], 

1514 match_date=match_data["match_date"], 

1515 season_id=season_id, 

1516 home_score=match_data.get("home_score"), 

1517 away_score=match_data.get("away_score"), 

1518 match_status=match_data.get("match_status", "scheduled"), 

1519 # The message says where it came from — a backfill or a manual 

1520 # entry is not a scraper run, and rule 6 wants that queryable. 

1521 source=match_data.get("source") or "match-scraper", 

1522 match_id=external_match_id, 

1523 age_group_id=age_group_id_for_create, 

1524 division_id=division_id, 

1525 match_type_id=match_type_id, 

1526 scheduled_kickoff=scheduled_kickoff, 

1527 home_penalty_score=home_pens, 

1528 away_penalty_score=away_pens, 

1529 location=self._read_location(match_data), 

1530 **(filing.columns() if filing else {}), 

1531 ) 

1532 if match_id: 

1533 alert_if_new_final_score( 

1534 None, 

1535 { 

1536 "id": match_id, 

1537 "home_score": match_data.get("home_score"), 

1538 "away_score": match_data.get("away_score"), 

1539 "match_status": match_data.get("match_status", "scheduled"), 

1540 }, 

1541 ) 

1542 result = { 

1543 "db_id": match_id, 

1544 "mls_id": external_match_id, 

1545 "status": "created", 

1546 "message": f"Created match: {home_team_name} vs {away_team_name}", 

1547 } 

1548 else: 

1549 raise Exception("Failed to create match") 

1550 

1551 logger.info(f"Successfully processed match: {result}") 

1552 return result 

1553 

1554 except UnresolvedNameError as e: 

1555 # Permanent. Record it so the name is reported once with a count 

1556 # rather than once per dropped match, alert if it is newly seen, and 

1557 # fail without retrying (dont_autoretry_for above). 

1558 logger.warning( 

1559 "Match dropped — unresolved name", 

1560 kind=e.kind, 

1561 raw_name=e.raw_name, 

1562 league=e.league, 

1563 ) 

1564 record = self.ingest_failures_dao.record( 

1565 e.kind, 

1566 e.raw_name, 

1567 league=e.league, 

1568 source=match_data.get("source") or "match-scraper", 

1569 sample=e.sample, 

1570 ) 

1571 alert_unresolved_name( 

1572 self.ingest_failures_dao, 

1573 kind=e.kind, 

1574 raw_name=e.raw_name, 

1575 league=e.league, 

1576 sample=e.sample, 

1577 record=record, 

1578 ) 

1579 raise 

1580 

1581 except Exception as e: 

1582 logger.error(f"Error processing match data: {e}", exc_info=True) 

1583 # Celery will auto-retry based on configuration 

1584 raise