Coverage for celery_tasks/tournament_filing.py: 100.00%
118 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1"""
2How an ingested match is filed under a tournament (SB-1747).
4A league message says where a match belongs with ``division``. A tournament
5message says it with ``tournament_id`` and four optional companions::
7 tournament_id the tournaments row the match belongs to
8 competition the feed's own name, e.g. "HD Group Play"
9 tournament_group the feed's own group label, e.g. "A"
10 tournament_round a round key, e.g. "group_stage"
11 tournament_round_order position within the round
13The feed's ``competition`` and ``tournament_group`` are raw. What is stored in
14``matches.tournament_group`` is one namespaced string built from them by
15``stored_group`` — MLS NEXT Fest runs a Homegrown and an Academy division side
16by side and both have a "Group A", so the raw label alone would merge them.
18Pure functions only — no DAO or database imports. ``dao.tournament_groups`` is
19itself pure; the stored format is frozen there (SB-1752), so this module never
20builds the string by hand.
21"""
23from __future__ import annotations
25import re
26from dataclasses import dataclass
27from typing import Any
29from dao.tournament_groups import GROUP_WHITESPACE, compose_group, split_group
31# The match_types.name every tournament message must carry. Compared without
32# case, as the match-type lookup is.
33TOURNAMENT_MATCH_TYPE = "Tournament"
35# Competitions that namespace a group. A competition whose first word is one
36# of these belongs to that division; anything else is its own namespace.
37DIVISION_TOKENS = frozenset({"HD", "AD"})
39GROUP_STAGE = "group_stage"
41# A round key is validated for shape, not membership: a feed that grows a new
42# round should land its matches and be noticed, not lose them (the caller logs
43# a key outside VALID_ROUNDS).
44ROUND_KEY_PATTERN = re.compile(r"^[a-z][a-z0-9]*(_[a-z0-9]+)*$")
45ROUND_KEY_MAX_LENGTH = 40
47# A run of whitespace inside a competition name. The same characters the
48# frozen format trims from the ends of a part, so "HD Group Play" and
49# "HD Group Play" are stored as the same bytes.
50_WHITESPACE_RUN = re.compile(f"[{re.escape(GROUP_WHITESPACE)}]+")
52# The matches columns a tournament filing owns, in the order they are compared.
53TOURNAMENT_COLUMNS = ("tournament_id", "tournament_group", "tournament_round", "tournament_round_order")
55# Message fields that mean nothing without tournament_id.
56_TOURNAMENT_ONLY_FIELDS = ("competition", "tournament_group", "tournament_round", "tournament_round_order")
59class TournamentFilingError(ValueError):
60 """The tournament fields on a message cannot be filed as sent.
62 Permanent: the same message will be just as wrong in ten minutes, so the
63 task records it in ``ingest_failures`` rather than retrying.
64 """
66 def __init__(self, errors: list[str]) -> None:
67 self.errors = errors
68 super().__init__("; ".join(errors))
71@dataclass(frozen=True)
72class TournamentFiling:
73 """Where a tournament message files its match.
75 ``tournament_group`` is the *stored* value (see ``stored_group``), not the
76 raw label the feed sent. ``competition`` is kept as sent, for log lines.
77 """
79 tournament_id: int
80 tournament_group: str | None = None
81 tournament_round: str | None = None
82 tournament_round_order: int | None = None
83 competition: str | None = None
85 def columns(self) -> dict[str, Any]:
86 """The filing as matches columns, nulls included."""
87 return {column: getattr(self, column) for column in TOURNAMENT_COLUMNS}
90def _blank_to_none(value: Any) -> Any:
91 """Empty and whitespace-only strings are absent; everything else is itself."""
92 if isinstance(value, str):
93 return value.strip(GROUP_WHITESPACE) or None
94 return value
97def _collapse_whitespace(value: str | None) -> str | None:
98 """Trim a competition and turn each inner run of whitespace into one space.
100 Letter case is left alone: only the division token is ever re-cased.
101 """
102 if not isinstance(value, str):
103 return value
104 return _WHITESPACE_RUN.sub(" ", value).strip(" ") or None
107def _is_int(value: Any) -> bool:
108 """A real integer. bool is an int in Python and is not one on the wire."""
109 return isinstance(value, int) and not isinstance(value, bool)
112def _split_division(competition: str | None) -> tuple[str | None, str | None]:
113 """Split "HD Group Play" into ("HD", "Group Play").
115 The division is the first whitespace-separated word, and only when it is
116 exactly HD or AD (any case, stored upper-case). Otherwise there is no
117 division and the competition is returned whole.
118 """
119 if not competition:
120 return None, None
121 words = competition.split(None, 1)
122 head = words[0]
123 rest = words[1] if len(words) > 1 else None
124 if head.upper() in DIVISION_TOKENS:
125 return head.upper(), _blank_to_none(rest)
126 return None, competition
129def stored_group(competition: str | None, group: str | None, round_key: str | None) -> str | None:
130 """Build the ``matches.tournament_group`` value for a feed's raw fields.
132 Group stage — the group is namespaced by its division, or by the whole
133 competition when it has none::
135 ("HD Group Play", "A", "group_stage") -> "HD · A"
136 ("AD Group Play", "A", "group_stage") -> "AD · A"
137 ("GA Cup Qualifier", "NEXT Pro", "group_stage") -> "GA Cup Qualifier · NEXT Pro"
138 (None, "Bracket A", "group_stage") -> "Bracket A"
140 Any other round — the feed's group label is not a group at all there
141 ("Playoffs"), so the competition is what the match is filed under::
143 ("HD Showcase", <anything>, "showcase") -> "HD · Showcase"
144 ("HD Group Play", "Playoffs", "placement_final") -> "HD · Group Play"
145 ("GA Cup Qualifier", <anything>, "final") -> "GA Cup Qualifier"
146 (None, "Bracket A", "final") -> "Bracket A"
148 Returns None — "no opinion", which never overwrites a stored group — when
149 the fields the round needs are not all there. Composing from what is left
150 would yield a different, shorter string ("HD" for "HD · A"), and bracket
151 follows key on the stored one::
153 (<anything>, <anything>, None) -> None
154 ("HD Group Play", None, "group_stage") -> None
155 (None, None, "final") -> None
157 Runs of whitespace inside the competition are collapsed to one space, so
158 the same competition always yields the same bytes.
160 Raises ValueError for a value ``compose_group`` rejects, rather than
161 storing a string that would split back into different parts.
162 """
163 competition = _collapse_whitespace(competition)
164 group = _blank_to_none(group)
165 round_key = _blank_to_none(round_key)
166 division, remainder = _split_division(competition)
168 if round_key is None:
169 return None
170 if round_key == GROUP_STAGE:
171 if group is None:
172 return None
173 return compose_group(division or competition, group)
174 if division:
175 return compose_group(division, remainder)
176 if competition:
177 return compose_group(None, competition)
178 return compose_group(None, group)
181def tournament_filing_errors(match_data: dict[str, Any]) -> list[str]:
182 """Everything wrong with a message's tournament fields; empty when fine.
184 A message with no tournament fields at all is fine — it is a league
185 message, and this has nothing to say about it.
186 """
187 errors: list[str] = []
188 tournament_id = match_data.get("tournament_id")
190 if tournament_id is None:
191 for field in _TOURNAMENT_ONLY_FIELDS:
192 if _blank_to_none(match_data.get(field)) is not None:
193 errors.append(f"{field} requires tournament_id")
194 return errors
196 if not _is_int(tournament_id) or tournament_id < 1:
197 errors.append("tournament_id must be an integer of 1 or more")
199 # The source match id is what a rescrape upserts on. Without it every
200 # rescrape of a tournament would fall back to teams-and-date, and two
201 # fixtures between the same teams on one day would overwrite each other.
202 if _blank_to_none(match_data.get("external_match_id")) is None:
203 errors.append("external_match_id is required when tournament_id is set")
205 match_type = _blank_to_none(match_data.get("match_type"))
206 if not isinstance(match_type, str) or match_type.lower() != TOURNAMENT_MATCH_TYPE.lower():
207 errors.append(f"match_type must be '{TOURNAMENT_MATCH_TYPE}' when tournament_id is set")
209 # A tournament match is filed on the tournament. Accepting a division as
210 # well would land it in a league table too.
211 if _blank_to_none(match_data.get("division")) is not None:
212 errors.append("division must be omitted when tournament_id is set")
214 for field in ("competition", "tournament_group"):
215 value = match_data.get(field)
216 if value is not None and not isinstance(value, str):
217 errors.append(f"{field} must be a string")
219 round_key = _blank_to_none(match_data.get("tournament_round"))
220 if round_key is not None and (
221 not isinstance(round_key, str)
222 or len(round_key) > ROUND_KEY_MAX_LENGTH
223 or not ROUND_KEY_PATTERN.match(round_key)
224 ):
225 errors.append(
226 f"tournament_round must be a lowercase snake_case key of at most {ROUND_KEY_MAX_LENGTH} characters"
227 )
229 round_order = match_data.get("tournament_round_order")
230 if round_order is not None and (not _is_int(round_order) or round_order < 0):
231 errors.append("tournament_round_order must be an integer of 0 or more")
233 if not errors:
234 try:
235 stored_group(match_data.get("competition"), match_data.get("tournament_group"), round_key)
236 except ValueError as exc:
237 errors.append(f"tournament group cannot be stored: {exc}")
239 return errors
242def read_tournament_filing(match_data: dict[str, Any]) -> TournamentFiling | None:
243 """The tournament filing on a message, or None for a league message.
245 Raises TournamentFilingError when the tournament fields are present but
246 cannot be filed: any of them without ``tournament_id``, a wrong type or
247 range, a malformed round key, a missing ``external_match_id``, or a group
248 the frozen format rejects.
249 """
250 errors = tournament_filing_errors(match_data)
251 if errors:
252 raise TournamentFilingError(errors)
254 if match_data.get("tournament_id") is None:
255 return None
257 round_key = _blank_to_none(match_data.get("tournament_round"))
258 return TournamentFiling(
259 tournament_id=match_data["tournament_id"],
260 tournament_group=stored_group(match_data.get("competition"), match_data.get("tournament_group"), round_key),
261 tournament_round=round_key,
262 tournament_round_order=match_data.get("tournament_round_order"),
263 competition=_blank_to_none(match_data.get("competition")),
264 )
267def _is_namespaced(group: Any) -> bool:
268 """Whether a stored group carries a division ("HD · A", not "Bracket A")."""
269 return isinstance(group, str) and split_group(group)["division"] is not None
272def tournament_changes(
273 existing_row: dict[str, Any], filing: TournamentFiling | None, *, fill_only: bool = False
274) -> dict[str, Any]:
275 """The tournament columns a rescrape should write to an existing row.
277 Only values the message actually carries: a null incoming value never
278 clears a stored one, so a rescrape that omits the group does not unfile a
279 match from it. Identical values yield an empty dict.
281 A stored namespaced group is never replaced by one without a namespace: a
282 message that lost its competition composes a bare "A", and writing that
283 over "HD · A" would orphan the bracket follows keyed on it.
285 ``fill_only`` is for a hand-entered row being adopted: only columns that
286 are null on the row are written, so a value somebody typed stays.
287 """
288 if filing is None:
289 return {}
290 changes: dict[str, Any] = {}
291 for column, value in filing.columns().items():
292 stored = existing_row.get(column)
293 if value is None or stored == value:
294 continue
295 if fill_only and stored is not None:
296 continue
297 if column == "tournament_group" and _is_namespaced(stored) and not _is_namespaced(value):
298 continue
299 changes[column] = value
300 return changes