Coverage for dao/ingest_plan_dao.py: 90.00%
406 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:03 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 15:03 +0000
1"""Planning and applying a tournament's teams and aliases against the database (SB-1763).
3`plan` reads; `apply` writes, and only what a reviewer approved. The rules for
4what to propose are pure and live in `dao.ingest_plan`; whether a name
5resolves is asked of `TeamDAO.resolve_tournament_team`, the resolver ingest
6uses, so a plan cannot disagree with ingest about what "resolved" means.
8Ingest calls none of this. A team is only ever created here, by an admin,
9from a plan a person has read.
10"""
12from __future__ import annotations
14import hashlib
15from dataclasses import dataclass, field
16from datetime import UTC, datetime
17from typing import Any
19import structlog
21from dao.base_dao import BaseDAO, clear_cache
22from dao.club_dao import CLUBS_CACHE_PATTERN
23from dao.ingest_plan import (
24 ALIAS,
25 UNKNOWN_AGE_GROUP,
26 Verdict,
27 World,
28 action_error,
29 build_plan,
30 is_approved,
31 name_key,
32 normalise,
33 parse_brackets_input,
34 parse_teams_input,
35 plan_id_for,
36 side_label,
37)
38from dao.team_dao import TEAMS_CACHE_PATTERN, TeamDAO, like_literal
39from dao.team_sides import (
40 MISSING,
41 RESOLVED,
42 WRONG_SIDE,
43 Candidate,
44 classify,
45 league_named,
46 sides_at_age,
47 team_sides,
48 top_level_league,
49)
51logger = structlog.get_logger()
53APPLIED = "applied"
54WOULD_APPLY = "would_apply"
55ALREADY_APPLIED = "already_applied"
56REFUSED = "refused"
57SKIPPED = "skipped"
58FAILED = "failed"
60NOT_APPROVED = "not approved"
62# PostgREST returns at most this many rows a request (supabase/config.toml).
63_PAGE = 1000
65# team_aliases.source says which system a spelling came from; for an alias
66# made here that is the plan, by name, so the row can be traced to its review.
67ALIAS_SOURCE_PREFIX = "ingest-plan:"
70class _SnapshotTeamDAO(TeamDAO):
71 """`resolve_tournament_team` over rows read once, instead of per name.
73 A tournament is some fifteen hundred names, and the resolver asks the
74 database two or three questions about each. Only the two row lookups are
75 replaced here — every rule, their order and the side guard are TeamDAO's
76 own code — and `found` keeps the teams the last lookup returned, which for
77 a name on the wrong side is the team that owns it.
78 """
80 def __init__(self, teams: list[dict], aliases: list[dict]):
81 # Deliberately no BaseDAO.__init__: there is no client to hold.
82 self._by_id = {row["id"]: row for row in teams}
83 self._by_name: dict[str, list[dict]] = {}
84 for row in teams:
85 self._by_name.setdefault((row.get("name") or "").casefold(), []).append(row)
86 self._aliases: dict[str, list[dict]] = {}
87 for row in aliases:
88 self._aliases.setdefault((row.get("external_name") or "").casefold(), []).append(row)
89 self.found: list[dict] = []
91 def _side_rows(self, *, name: str | None = None, ids: list[int] | None = None) -> list[dict]:
92 if ids is not None:
93 rows = [self._by_id[team_id] for team_id in ids if team_id in self._by_id]
94 else:
95 rows = list(self._by_name.get((name or "").casefold(), []))
96 self.found = rows
97 return rows
99 def _exact_alias_rows(self, normalized: str) -> list[dict]:
100 return list(self._aliases.get(normalized.casefold(), []))
102 def _log_unresolved(self, normalized, hint, age_group_id, resolution) -> None:
103 """Nothing: a plan reports every unresolved name itself, in one place.
105 Ingest's resolver warns once per name per message, which is right for
106 a message. Here it would be a warning for each of an event's fifteen
107 hundred names, on every plan and every apply.
108 """
111@dataclass
112class _Context:
113 """What MT holds at one moment, and the resolver over it."""
115 world: World
116 league_rows: list[dict]
117 resolver: _SnapshotTeamDAO
119 def verdict(self, name: str, age_group: str | None, league: str | None) -> Verdict:
120 age_group_id = self.world.age_group_id(age_group)
121 if age_group_id is None: 121 ↛ 122line 121 didn't jump to line 122 because the condition on line 121 was never true
122 return Verdict(UNKNOWN_AGE_GROUP, reason=f"unknown age group '{age_group or ''}'")
123 return self.resolve(name, age_group_id, league)
125 def resolve(self, name: str, age_group_id: int | None, league: str | None) -> Verdict:
126 self.resolver.found = []
127 team, resolution = self.resolver.resolve_tournament_team(name, age_group_id, league, leagues=self.league_rows)
128 return Verdict(
129 status=resolution.status,
130 team_id=team["id"] if team else None,
131 reason=resolution.reason,
132 candidate_ids=tuple(row["id"] for row in self.resolver.found),
133 )
136@dataclass
137class _Result:
138 outcome: str
139 detail: str | None = None
140 steps: list[str] = field(default_factory=list)
141 ids: dict = field(default_factory=dict)
144@dataclass
145class _Todo:
146 """What one action still needs written.
148 `steps` are `(description, write)`; each write is handed `ids` and adds
149 what it made to it — the club, team, alias and registration ids that are
150 the record of what an apply touched. `claims` are run instead of the
151 writes in a dry run, to tell later actions what this one would have made.
152 """
154 steps: list = field(default_factory=list)
155 claims: list = field(default_factory=list)
156 ids: dict = field(default_factory=dict)
159@dataclass
160class _Request:
161 """One apply request.
163 The `pending_*` fields are filled only by a dry run: what earlier actions
164 of the request would have created, so that a later action sharing a new
165 team, club or alias is judged as the real run — which finds those rows in
166 the database — would judge it.
167 """
169 plan_id: str
170 dry_run: bool
171 user_id: str | None
172 context: _Context | None = None
173 current: str | None = None
174 pending_teams: dict = field(default_factory=dict)
175 pending_clubs: set = field(default_factory=set)
176 pending_aliases: dict = field(default_factory=dict)
179class _Refused(Exception):
180 """An action's precondition does not hold. The text is for the admin."""
183class PlanDatabaseError(ValueError):
184 """The plan was not made against this database. The text is for the admin."""
187class IngestPlanDAO(BaseDAO):
188 """Plan, and apply, the teams and aliases a tournament's names need."""
190 def __init__(self, connection_holder, *, team_dao, club_dao, ingest_failures_dao):
191 super().__init__(connection_holder)
192 self.team_dao = team_dao
193 self.club_dao = club_dao
194 self.ingest_failures_dao = ingest_failures_dao
196 def database_fingerprint(self) -> str:
197 """A short name for the database this server is connected to.
199 A digest of the project URL: an identifier, not a secret, and not the
200 URL. A plan carries it so that apply can refuse a plan made against
201 another database, where the same ids are different teams and clubs.
202 """
203 url = (getattr(self.connection_holder, "url", None) or "").strip().rstrip("/").lower()
204 return hashlib.sha256(url.encode()).hexdigest()[:12]
206 # === Reading ===
208 def _all(self, table: str, columns: str) -> list[dict]:
209 rows: list[dict] = []
210 while True:
211 page = (
212 self.client.table(table).select(columns).order("id").range(len(rows), len(rows) + _PAGE - 1).execute()
213 ).data or []
214 rows.extend(page)
215 if len(page) < _PAGE: 215 ↛ 210line 215 didn't jump to line 210 because the condition on line 215 was always true
216 return rows
218 def _context(self) -> _Context:
219 """Every team, alias, club, league, conference and age group, read once."""
220 team_rows = self._all("teams", TeamDAO._SIDE_COLUMNS)
221 alias_rows = self._all("team_aliases", "id, team_id, league_id, source, external_name")
222 league_rows = self.team_dao.league_rows()
223 world = World(
224 teams=[
225 {
226 "id": row["id"],
227 "name": row.get("name"),
228 "club_id": row.get("club_id"),
229 "league_id": row.get("league_id"),
230 "mappings": [
231 (mapping.get("age_group_id"), (mapping.get("divisions") or {}).get("league_id"))
232 for mapping in row.get("team_mappings") or []
233 ],
234 }
235 for row in team_rows
236 ],
237 clubs={row["id"]: row.get("name") for row in self._all("clubs", "id, name")},
238 leagues={row["id"]: row for row in league_rows},
239 divisions=self._all("divisions", "id, name, league_id"),
240 age_groups={row["id"]: row.get("name") for row in self._all("age_groups", "id, name")},
241 )
242 return _Context(world=world, league_rows=league_rows, resolver=_SnapshotTeamDAO(team_rows, alias_rows))
244 def _near_matches(self, name: str) -> list[dict]:
245 """Teams a person might recognise this name as. Shown, never acted on."""
246 result = (self.team_dao.reconcile_names([name]) or [{}])[0]
247 if result.get("status") in ("known", "alias"): 247 ↛ 248line 247 didn't jump to line 248 because the condition on line 247 was never true
248 return [{"team_id": result.get("team_id"), "team_name": result.get("team_name"), "via": result["status"]}]
249 return [
250 {"team_id": row.get("id"), "team_name": row.get("name"), "club_id": row.get("club_id")}
251 for row in result.get("similar") or []
252 ]
254 def plan(self, teams: Any, brackets: Any = None) -> dict:
255 """What a tournament's names resolve to, and what to do about the rest.
257 Read-only: nothing is written, whatever the input. Raises
258 PlanInputError for input it cannot read. Returns
259 `{"plan_id", "database", "report", "actions"}`, `database` being the
260 fingerprint apply will ask for.
261 """
262 entries, matches = parse_teams_input(teams)
263 bracket_rows = parse_brackets_input(brackets)
264 context = self._context()
265 verdicts = {entry.key: context.verdict(entry.name, entry.age_group, entry.league) for entry in entries}
266 plan = build_plan(entries, matches, verdicts, context.world, bracket_rows, near_matches=self._near_matches)
267 plan_id = plan_id_for(plan["actions"], datetime.now(UTC).isoformat())
268 logger.info(
269 "Ingest plan built",
270 plan_id=plan_id,
271 entries=len(entries),
272 matches=len(matches),
273 actions=len(plan["actions"]),
274 )
275 return {"plan_id": plan_id, "database": self.database_fingerprint(), **plan}
277 # === Applying ===
279 def apply(
280 self,
281 plan_id: str,
282 actions: list[Any],
283 *,
284 database: str | None,
285 dry_run: bool = False,
286 user_id: str | None = None,
287 ) -> dict:
288 """Ensure each approved action of a reviewed plan. Idempotent.
290 `database` is the fingerprint the plan was made against. A plan with
291 none, or with another database's, is refused whole (PlanDatabaseError)
292 before any action is looked at: its ids name different rows here.
294 Every action is then judged on its own: `applied`, `already_applied`,
295 `refused` (a precondition no longer holds, or it would duplicate a
296 team name), `skipped` (not approved) or `failed`. One refusal does not
297 stop the rest. With `dry_run` every check is made and nothing is
298 written; what would be written is reported as `would_apply`. An action
299 that wrote anything reports the ids it created or touched in `ids`.
301 Afterwards, if anything was applied, the teams cache is cleared and
302 the open `team` ingest failures for the names just applied are closed
303 when they now resolve, with the plan named in the note.
304 """
305 own = self.database_fingerprint()
306 if not database:
307 raise PlanDatabaseError(
308 "The plan does not say which database it was made against. Plan again with a current mt."
309 )
310 if database != own:
311 raise PlanDatabaseError(
312 f"The plan was made against another database ({database}); this one is {own}. Plan again here."
313 )
315 request = _Request(plan_id=plan_id, dry_run=dry_run, user_id=user_id)
316 results: list[dict] = []
317 applied: list[dict] = []
318 wrote = False
319 for index, action in enumerate(actions):
320 row = {
321 "id": action.get("id") if isinstance(action, dict) else None,
322 "type": action.get("type") if isinstance(action, dict) else None,
323 "external_name": action.get("external_name") if isinstance(action, dict) else None,
324 }
325 if not is_approved(action):
326 result = _Result(SKIPPED, NOT_APPROVED)
327 else:
328 error = action_error(action)
329 if error:
330 result = _Result(REFUSED, error)
331 else:
332 if request.context is None:
333 request.context = self._context()
334 result = self._apply_one(action, request)
335 wrote = wrote or result.outcome in (APPLIED, FAILED)
336 if result.outcome == APPLIED:
337 applied.append(action)
338 results.append({**row, "index": index, "outcome": result.outcome, "detail": result.detail})
339 if result.steps:
340 results[-1]["steps"] = result.steps
341 if result.outcome in (APPLIED, FAILED):
342 results[-1]["ids"] = result.ids
344 closed: list[dict] = []
345 if wrote:
346 clear_cache(TEAMS_CACHE_PATTERN)
347 clear_cache(CLUBS_CACHE_PATTERN)
348 if applied:
349 closed = self._close_resolved_failures(plan_id, user_id, applied)
351 summary = dict.fromkeys((APPLIED, WOULD_APPLY, ALREADY_APPLIED, REFUSED, SKIPPED, FAILED), 0)
352 for row in results:
353 summary[row["outcome"]] += 1
354 logger.info("Ingest plan applied", plan_id=plan_id, dry_run=dry_run, user_id=user_id, **summary)
355 return {
356 "plan_id": plan_id,
357 "dry_run": dry_run,
358 "results": results,
359 "summary": summary,
360 "failures_closed": closed,
361 }
363 def _apply_one(self, action: dict, request: _Request) -> _Result:
364 plan_id = request.plan_id
365 try:
366 ensure = self._ensure_alias if action["type"] == ALIAS else self._ensure_team
367 todo = ensure(action, request)
368 except _Refused as exc:
369 return _Result(REFUSED, str(exc))
370 except Exception:
371 logger.exception("Could not check an ingest plan action", plan_id=plan_id, action_id=action.get("id"))
372 return _Result(FAILED, "could not check this action")
374 if not todo.steps:
375 return _Result(ALREADY_APPLIED)
376 described = [text for text, _ in todo.steps]
377 if request.dry_run:
378 # What this action would make, for the actions after it in the request.
379 for claim in todo.claims:
380 claim()
381 return _Result(WOULD_APPLY, steps=described)
383 done: list[str] = []
384 try:
385 for text, write in todo.steps:
386 write(todo.ids)
387 done.append(text)
388 except Exception:
389 # Each step is an ensure, so applying the plan again finishes the rest.
390 logger.exception(
391 "Ingest plan action failed part-way",
392 plan_id=plan_id,
393 action_id=action.get("id"),
394 done=done,
395 ids=todo.ids,
396 )
397 detail = f"stopped after {len(done)} of {len(todo.steps)} steps; apply again to finish"
398 return _Result(FAILED, detail, done, todo.ids)
399 logger.info(
400 "Ingest plan action applied",
401 plan_id=plan_id,
402 action_id=action.get("id"),
403 action_type=action["type"],
404 user_id=request.user_id,
405 steps=done,
406 ids=todo.ids,
407 )
408 return _Result(APPLIED, steps=done, ids=todo.ids)
410 # -- preconditions --
412 def _league_id(self, league: str | None, context: _Context) -> int | None:
413 if league is None: 413 ↛ 414line 413 didn't jump to line 414 because the condition on line 413 was never true
414 return None
415 league_id = league_named(league, context.world.leagues)
416 if league_id is None: 416 ↛ 417line 416 didn't jump to line 417 because the condition on line 416 was never true
417 raise _Refused(f"MT has no league named '{league}'")
418 return league_id
420 def _check_fixes(self, action: dict, context: _Context) -> tuple[int, set[int | None]]:
421 """Each entry the action fixes, against the database as it is now.
423 Every entry must either still fail the way the plan recorded or
424 resolve; anything else refuses the action. Returns how many still
425 fail, and the teams the rest now resolve to — for the caller to tell
426 "already done" from "done differently by someone else".
427 """
428 fixes = action.get("fixes") or []
429 if not fixes:
430 raise _Refused("the action lists no entries it fixes, so there is nothing to check it against")
431 resolved_to: set[int | None] = set()
432 failing = 0
433 for fix in fixes:
434 verdict = context.verdict(fix["name"], fix["age_group"], fix.get("league"))
435 where = f"'{fix['name']}' ({fix['age_group']}, {side_label(fix.get('league'))})"
436 if verdict.status == RESOLVED:
437 resolved_to.add(verdict.team_id)
438 continue
439 expected = fix.get("status")
440 if expected not in (WRONG_SIDE, MISSING): 440 ↛ 441line 440 didn't jump to line 441 because the condition on line 440 was never true
441 raise _Refused(f"{where} has no recorded status to check against")
442 if verdict.status != expected:
443 detail = f" ({verdict.reason})" if verdict.reason else ""
444 raise _Refused(f"{where} no longer fails as {expected}: it is now {verdict.status}{detail}")
445 failing += 1
446 return failing, resolved_to
448 def _on_side_at_each_age(self, team: dict, action: dict, side: str, context: _Context) -> None:
449 """Refuse unless the team is the resolver's answer for `side` at every age the action fixes.
451 The resolver's own guard, one age group at a time: a team registered
452 on the other side at that age, or on both, is not a team an alias may
453 point that age group's fixtures at — whatever it is at other ages.
454 """
455 mappings = [
456 (mapping.get("age_group_id"), (mapping.get("divisions") or {}).get("league_id"))
457 for mapping in team.get("team_mappings") or []
458 ]
459 leagues = context.world.leagues
460 for age_group in sorted({fix["age_group"] for fix in action.get("fixes") or []}):
461 age_group_id = context.world.age_group_id(age_group)
462 if age_group_id is None: 462 ↛ 463line 462 didn't jump to line 463 because the condition on line 462 was never true
463 raise _Refused(f"MT has no age group '{age_group}'")
464 candidate = Candidate(
465 team_id=team["id"],
466 sides=team_sides(mappings, team.get("league_id"), age_group_id, leagues),
467 sides_at_age=sides_at_age(mappings, age_group_id, leagues),
468 )
469 if classify([candidate], side).status != RESOLVED:
470 found = ", ".join(sorted(candidate.sides)) or "no side"
471 raise _Refused(
472 f"team {team['id']} ('{team.get('name')}') is not on the {side} side at {age_group}: "
473 f"it is {found} there"
474 )
476 def _alias_steps(
477 self,
478 request: _Request,
479 name: str,
480 league_id: int,
481 league: str,
482 team_id: int | None,
483 target: str,
484 describe: str,
485 claims: list,
486 ) -> list[tuple[str, Any]]:
487 """The write that makes `name` an alias in this league, if it is not one.
489 `team_id` is None for a team this request has yet to create; the
490 write reads the id from the ids gathered by the steps before it.
491 `target` names the team for a dry run, where it may have no id yet.
492 """
493 in_league = {
494 row["team_id"] for row in self.team_dao._exact_alias_rows(name) if row.get("league_id") == league_id
495 }
496 if team_id is not None and in_league == {team_id}:
497 return []
498 if in_league: 498 ↛ 499line 498 didn't jump to line 499 because the condition on line 498 was never true
499 ids = ", ".join(str(other) for other in sorted(in_league))
500 raise _Refused(f"'{name}' is already a {league} alias for team {ids}")
501 pending = request.pending_aliases.get((name_key(name), league_id))
502 if pending:
503 if pending["target"] == target: 503 ↛ 505line 503 didn't jump to line 505 because the condition on line 503 was always true
504 return []
505 raise _Refused(f"'{name}' is already made a {league} alias by action {pending['action']} in this plan")
506 conflict = self.team_dao.alias_conflict(name, team_id or 0, league_id)
507 if conflict: 507 ↛ 508line 507 didn't jump to line 508 because the condition on line 507 was never true
508 raise _Refused(f"'{name}' already reaches team {conflict.get('id')} in {league}")
510 def write(ids: dict) -> None:
511 row = self.team_dao.add_team_alias(
512 ids["team_id"],
513 name,
514 source=f"{ALIAS_SOURCE_PREFIX}{request.plan_id}",
515 kind="feed_variant",
516 league_id=league_id,
517 )
518 ids["alias_id"] = row.get("id")
520 claims.append(
521 lambda: request.pending_aliases.setdefault(
522 (name_key(name), league_id), {"target": target, "action": request.current}
523 )
524 )
525 return [(describe, write)]
527 def _ensure_alias(self, action: dict, request: _Request) -> _Todo:
528 context = request.context
529 request.current = action.get("id")
530 name, team_id = normalise(action["external_name"]), action["team_id"]
531 league_id = self._league_id(action["league"], context)
532 league = context.world.leagues[league_id]["name"]
534 rows = self.team_dao._side_rows(ids=[team_id])
535 if not rows:
536 raise _Refused(f"team {team_id} does not exist")
537 team = rows[0]
538 if name_key(team.get("name")) != name_key(action["team_name"]):
539 raise _Refused(f"team {team_id} is '{team.get('name')}', not '{normalise(action['team_name'])}'")
540 self._on_side_at_each_age(team, action, top_level_league(league_id, context.world.leagues), context)
542 todo = _Todo(ids={"team_id": team_id})
543 steps = self._alias_steps(
544 request,
545 name,
546 league_id,
547 league,
548 team_id,
549 f"team:{team_id}",
550 f"alias '{name}' ({league}) → team {team_id}",
551 todo.claims,
552 )
553 if not steps:
554 return todo
555 failing, resolved_to = self._check_fixes(action, context)
556 others = resolved_to - {team_id}
557 if others: 557 ↛ 558line 557 didn't jump to line 558 because the condition on line 557 was never true
558 ids = ", ".join(str(other) for other in sorted(others, key=str))
559 raise _Refused(f"'{name}' now resolves to team {ids}, not {team_id}")
560 if failing: 560 ↛ 562line 560 didn't jump to line 562 because the condition on line 560 was always true
561 todo.steps = steps
562 return todo
564 def _club(self, action: dict, request: _Request) -> dict | None:
565 """The club an action names: the row, or None for one still to create.
567 In a dry run a club an earlier action of the request would create is
568 returned with no id, as the real run would find it made.
569 """
570 if action.get("club_id") is not None:
571 rows = self.client.table("clubs").select("id, name").eq("id", action["club_id"]).limit(1).execute().data
572 if not rows: 572 ↛ 573line 572 didn't jump to line 573 because the condition on line 572 was never true
573 raise _Refused(f"club {action['club_id']} does not exist")
574 if name_key(rows[0].get("name")) != name_key(action["club_name"]):
575 raise _Refused(
576 f"club {action['club_id']} is '{rows[0].get('name')}', not '{normalise(action['club_name'])}'"
577 )
578 return rows[0]
579 wanted = normalise(action["new_club_name"])
580 rows = (self.client.table("clubs").select("id, name").ilike("name", like_literal(wanted)).execute().data) or []
581 rows = [row for row in rows if name_key(row.get("name")) == name_key(wanted)]
582 if rows:
583 return rows[0]
584 if name_key(wanted) in request.pending_clubs:
585 return {"id": None, "name": wanted}
586 return None
588 def _placement_ids(self, action: dict, league_id: int | None, context: _Context) -> list[tuple[int, int, str]]:
589 """Each placement as (age group id, division id, description).
591 A conference MT does not have refuses the action: it is never created
592 here. So does one on the other side — a registration there is what
593 makes a team answer to both.
594 """
595 placements = action.get("placements") or []
596 if placements and league_id is None: 596 ↛ 597line 596 didn't jump to line 597 because the condition on line 596 was never true
597 raise _Refused("a team with no league cannot be placed in a conference")
598 side = top_level_league(league_id, context.world.leagues)
599 found = []
600 for placement in placements:
601 where = f"{placement['league']} {placement['conference']} ({placement['age_group']})"
602 placed_league = league_named(placement["league"], context.world.leagues)
603 if placed_league is None: 603 ↛ 604line 603 didn't jump to line 604 because the condition on line 603 was never true
604 raise _Refused(f"MT has no league named '{placement['league']}'")
605 if top_level_league(placed_league, context.world.leagues) != side:
606 raise _Refused(f"{where} is not a {side} conference")
607 division = next(
608 (
609 row
610 for row in context.world.divisions
611 if row.get("league_id") == placed_league
612 and name_key(row.get("name")) == name_key(placement["conference"])
613 ),
614 None,
615 )
616 if division is None:
617 raise _Refused(f"MT has no conference '{placement['conference']}' in {placement['league']}")
618 age_group_id = context.world.age_group_id(placement["age_group"])
619 if age_group_id is None: 619 ↛ 620line 619 didn't jump to line 620 because the condition on line 619 was never true
620 raise _Refused(f"MT has no age group '{placement['age_group']}'")
621 if (age_group_id, division["id"], where) not in found: 621 ↛ 600line 621 didn't jump to line 600 because the condition on line 621 was always true
622 found.append((age_group_id, division["id"], where))
623 return found
625 def _ensure_team(self, action: dict, request: _Request) -> _Todo:
626 context = request.context
627 request.current = action.get("id")
628 plan_id = request.plan_id
629 team_name, external_name = normalise(action["team_name"]), normalise(action["external_name"])
630 league_id = self._league_id(action.get("league"), context)
631 league = context.world.leagues[league_id]["name"] if league_id is not None else None
632 if league_id is not None and context.world.leagues[league_id].get("parent_league_id") is not None:
633 side = top_level_league(league_id, context.world.leagues)
634 raise _Refused(f"{league} is not a top-level league: a team's league is its side, {side}")
635 wants_alias = name_key(team_name) != name_key(external_name)
636 if wants_alias and league_id is None: 636 ↛ 637line 636 didn't jump to line 637 because the condition on line 636 was never true
637 raise _Refused("a team with no league cannot take a league-scoped alias: name it as the feed does")
639 placements = self._placement_ids(action, league_id, context)
640 club = self._club(action, request)
641 club_key = (
642 ("id", club["id"]) if club and club["id"] is not None else ("new", name_key(action.get("new_club_name")))
643 )
644 existing = self.team_dao._side_rows(name=team_name)
645 if len(existing) > 1: 645 ↛ 646line 645 didn't jump to line 646 because the condition on line 645 was never true
646 ids = ", ".join(str(row["id"]) for row in existing)
647 raise _Refused(f"the name '{team_name}' is already taken by teams {ids}")
648 failing, resolved_to = self._check_fixes(action, context)
650 todo = _Todo()
651 pending = request.pending_teams.get(name_key(team_name))
652 if existing:
653 team = existing[0]
654 if club is None or team.get("club_id") != club["id"] or team.get("league_id") != league_id:
655 raise _Refused(f"the name '{team_name}' is already taken by team {team['id']}")
656 # The same team in the same club and league: this action's own,
657 # from an earlier apply — if what it fixes agrees. A name that now
658 # resolves to some other team is not this action's to move.
659 others = resolved_to - {team["id"]}
660 if others:
661 ids = ", ".join(str(other) for other in sorted(others, key=str))
662 raise _Refused(f"'{external_name}' now resolves to team {ids}, not to '{team_name}' ({team['id']})")
663 todo.ids.update(club_id=club["id"], team_id=team["id"])
664 target = f"team:{team['id']}"
665 registered = {
666 (mapping.get("age_group_id"), mapping.get("division_id"))
667 for mapping in self.client.table("team_mappings")
668 .select("age_group_id, division_id")
669 .eq("team_id", team["id"])
670 .execute()
671 .data
672 or []
673 }
674 elif pending:
675 # A dry run: an earlier action of this request would have made it.
676 if pending["club"] != club_key or pending["league_id"] != league_id:
677 raise _Refused(
678 f"the name '{team_name}' is already taken by the team action {pending['action']} creates"
679 )
680 if resolved_to: 680 ↛ 681line 680 didn't jump to line 681 because the condition on line 680 was never true
681 raise _Refused(f"'{external_name}' now resolves without this team")
682 target = f"new:{name_key(team_name)}"
683 registered = pending["registered"]
684 else:
685 if resolved_to: 685 ↛ 686line 685 didn't jump to line 686 because the condition on line 685 was never true
686 raise _Refused(f"'{external_name}' now resolves without this team")
687 target = f"new:{name_key(team_name)}"
688 registered = set()
689 if club is None:
690 club_name = normalise(action["new_club_name"])
692 def create_club(ids: dict) -> None:
693 created = self.club_dao.create_club(
694 name=club_name, city="", description=f"Created by mt ingest plan {plan_id}"
695 )
696 ids.update(club_id=created["id"], club_created=True)
698 todo.steps.append((f"create club '{club_name}'", create_club))
699 todo.claims.append(lambda: request.pending_clubs.add(name_key(club_name)))
700 elif club["id"] is not None:
701 todo.ids["club_id"] = club["id"]
703 def create_team(ids: dict) -> None:
704 row = {"name": team_name, "club_id": ids["club_id"], "league_id": league_id}
705 created = self.client.table("teams").insert(row).execute().data
706 if not created: 706 ↛ 707line 706 didn't jump to line 707 because the condition on line 706 was never true
707 raise RuntimeError("team insert returned no row")
708 ids.update(team_id=created[0]["id"], team_created=True)
709 # Names are looked up through the cache; the next action must see this one.
710 clear_cache(TEAMS_CACHE_PATTERN)
712 todo.steps.append((f"create team '{team_name}' ({league or 'no league'})", create_team))
713 claimed = {"club": club_key, "league_id": league_id, "action": action.get("id"), "registered": set()}
714 todo.claims.append(lambda: request.pending_teams.setdefault(name_key(team_name), claimed))
715 pending = claimed
717 for age_group_id, division_id, where in placements:
718 if (age_group_id, division_id) in registered:
719 continue
721 def register(ids: dict, age_group_id: int = age_group_id, division_id: int = division_id) -> None:
722 self.team_dao.ensure_team_mapping(ids["team_id"], age_group_id, division_id)
723 found = (
724 self.client.table("team_mappings")
725 .select("id")
726 .eq("team_id", ids["team_id"])
727 .eq("age_group_id", age_group_id)
728 .eq("division_id", division_id)
729 .limit(1)
730 .execute()
731 ).data
732 # ensure_team_mapping never raises; a row that is not there is the failure.
733 if not found: 733 ↛ 734line 733 didn't jump to line 734 because the condition on line 733 was never true
734 raise RuntimeError("team mapping was not written")
735 ids.setdefault("mapping_ids", []).append(found[0]["id"])
737 todo.steps.append((f"register in {where}", register))
738 if pending: 738 ↛ 717line 738 didn't jump to line 717 because the condition on line 738 was always true
739 # For a dry run: a later action sharing the team does not register it twice.
740 todo.claims.append(lambda key=(age_group_id, division_id): pending["registered"].add(key))
742 if wants_alias:
743 todo.steps += self._alias_steps(
744 request,
745 external_name,
746 league_id,
747 league,
748 todo.ids.get("team_id"),
749 target,
750 f"alias '{external_name}' ({league}) → '{team_name}'",
751 todo.claims,
752 )
753 return todo
755 # -- afterwards --
757 def _close_resolved_failures(self, plan_id: str, user_id: str | None, applied: list[dict]) -> list[dict]:
758 """Close the open `team` failures for the names just applied, if they now resolve.
760 Only rows for an applied action's own name and league: a row this
761 request did not fix is not this plan's to close. A failure row carries
762 no age group of its own; the one in its sample match is used, and a
763 row whose sample has none is left open — without an age group the
764 resolver cannot say what ingest would do. Read after the writes, from
765 the database as it now is.
766 """
767 try:
768 names = {(name_key(action["external_name"]), name_key(action.get("league"))) for action in applied}
769 open_rows = [
770 row
771 for row in self.ingest_failures_dao.open_failures(limit=_PAGE, kinds=["team"])
772 if row.get("kind") == "team" and (name_key(row.get("raw_name")), name_key(row.get("league"))) in names
773 ]
774 if not open_rows:
775 return []
776 context = self._context()
777 closed = []
778 for row in open_rows:
779 age_group_id = _sample_age_group_id(row.get("sample"), context.world)
780 if age_group_id is None:
781 continue
782 verdict = context.resolve(row.get("raw_name") or "", age_group_id, row.get("league"))
783 if verdict.status != RESOLVED: 783 ↛ 784line 783 didn't jump to line 784 because the condition on line 783 was never true
784 continue
785 done = self.ingest_failures_dao.resolve_by_id(row["id"], resolved_by=user_id, note=f"plan {plan_id}")
786 if done: 786 ↛ 778line 786 didn't jump to line 778 because the condition on line 786 was always true
787 closed.append(
788 {
789 "id": row["id"],
790 "raw_name": row.get("raw_name"),
791 "league": row.get("league"),
792 "team_id": verdict.team_id,
793 }
794 )
795 return closed
796 except Exception:
797 # The teams and aliases are written; a failure row left open closes
798 # itself the next time ingest sees the name.
799 logger.exception("Could not close resolved ingest failures", plan_id=plan_id)
800 return []
803def _sample_age_group_id(sample: str | None, world: World) -> int | None:
804 """The age group of a failure's sample match, or None if it names none.
806 Ingest writes the sample as "Home vs Away, 2026-12-02 U15", then the
807 resolver's reason in square brackets.
808 """
809 text = (sample or "").split(" [")[0].split()
810 return world.age_group_id(text[-1]) if text else None