Coverage for mt_tools/qualification_rules.py: 97.16%
111 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:10 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:10 +0000
1"""MLS NEXT qualification rules, one reviewed YAML file per season (SB-1549).
3The rules live in `backend/qualification_rules/<season>.yaml`, encoded from the
4reviewed research (docs/03-architecture/mls-next-qualification-facts.md). This
5module loads and validates them; it never decides anything. Agents read them to
6say what is at stake in a match, and the validation exists so they can only say
7what a source said:
9- a `confirmed` rule must cite a source;
10- `slots` is a positive count or null. Null is "MLS has not said"; 0 is rejected,
11 because a 0 would read as "no places", a claim nobody made (CLAUDE.md: never
12 pun absent into zero);
13- rule ids are unique, age groups are real MLS NEXT age groups, and unknown keys
14 are an error rather than silently dropped.
16A malformed file fails loudly at load. A rule that quietly vanished would make a
17stakes claim look unsupported, or worse, let a stale one stand.
18"""
20from datetime import date
21from functools import lru_cache
22from pathlib import Path
23from typing import Literal, Self
25import yaml
26from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
28RULES_DIR = Path(__file__).resolve().parent.parent / "qualification_rules"
30AgeGroup = Literal["U13", "U14", "U15", "U16", "U17", "U19"]
31Tier = Literal["Homegrown", "Academy"]
32ConferenceKind = Literal["league", "flex", "ppp"]
35class RulesError(ValueError):
36 """The rules file is missing or does not validate."""
39class Selector(BaseModel):
40 """Who a rule picks. All fields optional; an absent selector means "not published"."""
42 model_config = ConfigDict(extra="forbid", frozen=True)
44 rank: int | None = Field(default=None, ge=1)
45 group_winner: bool = False
46 event_winner: bool = False
49class QualificationRule(BaseModel):
50 model_config = ConfigDict(extra="forbid", frozen=True)
52 id: str = Field(pattern=r"^[a-z0-9]+(-[a-z0-9]+)*$")
53 competition: str = Field(min_length=1)
54 pathway: str = Field(min_length=1)
55 tier: Tier | None
56 age_groups: tuple[AgeGroup, ...] = Field(min_length=1)
57 conference_kind: ConferenceKind | None
58 selector: Selector | None
59 slots: int | None
60 qualifies: bool = True
61 confirmed: bool
62 source_url: str | None = None
63 source_date: date | None = None
64 claims: tuple[str, ...] = ()
65 summary: str = Field(min_length=1)
67 @field_validator("slots")
68 @classmethod
69 def _slots_positive_or_null(cls, value: int | None) -> int | None:
70 if value is not None and value < 1:
71 raise ValueError("slots must be a positive count, or null when not published (never 0)")
72 return value
74 @field_validator("source_url")
75 @classmethod
76 def _url_shape(cls, value: str | None) -> str | None:
77 if value is not None and not value.startswith("https://"):
78 raise ValueError("source_url must be an https:// URL")
79 return value
81 @model_validator(mode="after")
82 def _confirmed_needs_source(self) -> Self:
83 if self.confirmed and not (self.source_url and self.source_date):
84 raise ValueError(f"rule {self.id!r} is confirmed but has no source_url/source_date")
85 return self
88class RuleSet(BaseModel):
89 model_config = ConfigDict(extra="forbid", frozen=True)
91 season: str = Field(pattern=r"^\d{4}-\d{2}$")
92 target: str
93 reviewed: date
94 rules: tuple[QualificationRule, ...] = Field(min_length=1)
96 @model_validator(mode="after")
97 def _unique_ids(self) -> Self:
98 seen: set[str] = set()
99 for rule in self.rules:
100 if rule.id in seen:
101 raise ValueError(f"duplicate rule id {rule.id!r}")
102 seen.add(rule.id)
103 return self
105 def get(self, rule_id: str) -> QualificationRule | None:
106 return next((r for r in self.rules if r.id == rule_id), None)
108 def applicable(
109 self,
110 age_group: str,
111 conference_kind: str | None = None,
112 tier: str | None = "Homegrown",
113 *,
114 confirmed_only: bool = False,
115 ) -> list[QualificationRule]:
116 """Routes that a table of this kind, at this age, feeds.
118 Only qualifying routes (`qualifies: true`) tied to a conference kind are
119 returned: a match is played in a table, and a table is what a rule can
120 say something about. `confirmed_only` drops inferred rules.
121 """
122 return [
123 r
124 for r in self.rules
125 if r.qualifies
126 and r.conference_kind is not None
127 and r.conference_kind == conference_kind
128 and age_group in r.age_groups
129 and (tier is None or r.tier == tier)
130 and (r.confirmed or not confirmed_only)
131 ]
134def parse_rules(text: str) -> RuleSet:
135 """Validate a rules document. Raises RulesError with the reason."""
136 try:
137 data = yaml.safe_load(text)
138 except yaml.YAMLError as exc:
139 raise RulesError(f"rules file is not valid YAML: {exc}") from exc
140 if not isinstance(data, dict):
141 raise RulesError("rules file must be a mapping with season, target, reviewed and rules")
142 try:
143 return RuleSet.model_validate(data)
144 except ValueError as exc:
145 raise RulesError(str(exc)) from exc
148@lru_cache(maxsize=8)
149def load_rules(season: str = "2026-27", rules_dir: Path = RULES_DIR) -> RuleSet:
150 """The reviewed rules for a season ("2026-27"). Cached: the file ships with the image."""
151 path = rules_dir / f"{season}.yaml"
152 if not path.is_file():
153 raise RulesError(f"no qualification rules for season {season!r}")
154 rules = parse_rules(path.read_text(encoding="utf-8"))
155 if rules.season != season: 155 ↛ 156line 155 didn't jump to line 156 because the condition on line 155 was never true
156 raise RulesError(f"{path.name} declares season {rules.season!r}")
157 return rules
160def season_key(season_name: str | None) -> str | None:
161 """MT's season name ("2026-2027") as a rules key ("2026-27"); None when it isn't one."""
162 if not season_name:
163 return None
164 parts = season_name.strip().split("-")
165 if len(parts) != 2 or not all(p.isdigit() and len(p) == 4 for p in parts):
166 return None
167 return f"{parts[0]}-{parts[1][2:]}"
170def conference_kind(league_name: str | None, division_name: str | None) -> ConferenceKind | None:
171 """The rules' conference kind for an MT division, from its league and name.
173 In MT, Flex conferences are divisions of the league "Flex" (Empire, Turnpike,
174 New England...); Pro Player Pathway divisions carry "(Pro Player Pathway)" in
175 their name; any other Homegrown or Academy division is a league conference.
176 Which tier it is comes from `tier_of`.
177 """
178 league = (league_name or "").strip().casefold()
179 name = (division_name or "").casefold()
180 if league == "flex":
181 return "flex"
182 if "pro player pathway" in name:
183 return "ppp"
184 if league in ("homegrown", "academy"):
185 return "league"
186 return None
189def tier_of(league_name: str | None) -> Tier | None:
190 """The MLS NEXT tier of an MT league: Flex is played by Homegrown teams."""
191 league = (league_name or "").strip().casefold()
192 if league in ("homegrown", "flex"):
193 return "Homegrown"
194 if league == "academy":
195 return "Academy"
196 return None