Coverage for mt_tools/ingest.py: 95.83%
96 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 17:31 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 17:31 +0000
1"""Ingest failures as admin tools (SB-1304): names the match ingest could not resolve.
3The same rules as /api/admin/ingest-failures (SB-829, SB-845): one row per name,
4`stale` is a hint and never a decision, and closing a row is a person's call that
5is recorded, not a delete. Closing defaults to a dry run.
6"""
8import os
9from datetime import UTC, datetime, timedelta
10from typing import Any, Literal, Protocol
12import structlog
13from pydantic import BaseModel
15from dao.ingest_failures_dao import CONFLICT_KINDS
16from mt_ai.tools.schemas import ToolError
18logger = structlog.get_logger()
20# How long an open ingest failure has to go unseen before it is flagged stale.
21#
22# A hint, never a decision: "absent" and "fixed" are not the same thing, and a
23# genuine problem that simply was not scraped this week must not auto-close. It
24# exists so the run report can de-emphasise a row rather than keep crying wolf
25# about it (SB-845).
26DEFAULT_INGEST_FAILURE_STALE_AFTER_DAYS = 7
28MAX_LIMIT = 200
31def ingest_failure_stale_after_days() -> int:
32 try:
33 return int(os.getenv("MT_INGEST_STALE_AFTER_DAYS", DEFAULT_INGEST_FAILURE_STALE_AFTER_DAYS))
34 except ValueError:
35 return DEFAULT_INGEST_FAILURE_STALE_AFTER_DAYS
38def last_seen_before(last_seen: str | None, cutoff: datetime) -> bool:
39 """Whether a row's last_seen predates the cutoff. Unparseable reads as fresh."""
40 if not last_seen:
41 return False
42 try:
43 seen = datetime.fromisoformat(last_seen.replace("Z", "+00:00"))
44 except ValueError:
45 return False
46 if seen.tzinfo is None:
47 seen = seen.replace(tzinfo=UTC)
48 return seen < cutoff
51class IngestSource(Protocol):
52 def open_failures( 52 ↛ exitline 52 didn't return from function 'open_failures' because
53 self,
54 since: str | None = None,
55 limit: int = 200,
56 *,
57 kinds: list[str] | None = None,
58 include_conflicts: bool = False,
59 ) -> list[dict[str, Any]]: ...
61 def get(self, failure_id: int) -> dict[str, Any] | None: ... 61 ↛ exitline 61 didn't return from function 'get' because
63 def resolve_by_id( 63 ↛ exitline 63 didn't return from function 'resolve_by_id' because
64 self, failure_id: int, *, resolved_by: str | None = None, note: str | None = None
65 ) -> dict[str, Any] | None: ...
68class IngestFailure(BaseModel):
69 id: int
70 kind: str | None = None
71 raw_name: str
72 league: str | None = None
73 source: str | None = None
74 match_count: int = 0
75 sample: str | None = None
76 first_seen: str | None = None
77 last_seen: str | None = None
78 stale: bool = False
79 resolved_at: str | None = None
80 resolution_note: str | None = None
82 @classmethod
83 def from_row(cls, row: dict[str, Any], cutoff: datetime) -> "IngestFailure":
84 known = {k: row.get(k) for k in cls.model_fields if k in row and k != "stale"}
85 for key in ("first_seen", "last_seen", "resolved_at"):
86 if known.get(key) is not None:
87 known[key] = str(known[key])
88 known["match_count"] = int(row.get("match_count") or 0)
89 return cls(**known, stale=last_seen_before(row.get("last_seen"), cutoff))
92class IngestFailuresResult(BaseModel):
93 """Open ingest failures, newest first. `failures` is null only when the read failed."""
95 failures: list[IngestFailure] | None = None
96 count: int = 0
97 matches_dropped: int = 0
98 stale_count: int = 0
99 stale_after_days: int = DEFAULT_INGEST_FAILURE_STALE_AFTER_DAYS
100 since: str | None = None
101 error: ToolError | None = None
104class ResolveIngestFailureResult(BaseModel):
105 status: Literal["would_resolve", "resolved", "already_resolved", "not_found"] | None = None
106 dry_run: bool = True
107 failure: IngestFailure | None = None
108 error: ToolError | None = None
111def _cutoff(now: datetime | None) -> tuple[int, datetime]:
112 days = ingest_failure_stale_after_days()
113 return days, (now or datetime.now(UTC)) - timedelta(days=days)
116def list_ingest_failures(
117 source: IngestSource,
118 since: str | None = None,
119 limit: int = 50,
120 now: datetime | None = None,
121 conflicts: bool = False,
122) -> IngestFailuresResult:
123 """Open rows, newest first. `conflicts` lists the feed-vs-person conflicts (SB-1787) instead."""
124 days, cutoff = _cutoff(now)
125 limit = max(1, min(limit, MAX_LIMIT))
126 try:
127 if conflicts:
128 rows = source.open_failures(since=since, limit=limit, kinds=sorted(CONFLICT_KINDS))
129 else:
130 rows = source.open_failures(since=since, limit=limit)
131 except Exception:
132 logger.exception("list_ingest_failures failed")
133 return IngestFailuresResult(
134 since=since,
135 stale_after_days=days,
136 error=ToolError(kind="unavailable", message="Ingest failures are unavailable right now."),
137 )
138 failures = [IngestFailure.from_row(r, cutoff) for r in rows]
139 return IngestFailuresResult(
140 failures=failures,
141 count=len(failures),
142 # A conflict row (SB-1787) cost no match: it landed, or was held.
143 matches_dropped=sum(f.match_count for f in failures if f.kind not in CONFLICT_KINDS),
144 stale_count=sum(1 for f in failures if f.stale),
145 stale_after_days=days,
146 since=since,
147 )
150def resolve_ingest_failure(
151 source: IngestSource,
152 failure_id: int,
153 resolved_by: str,
154 note: str | None = None,
155 dry_run: bool = True,
156 now: datetime | None = None,
157) -> ResolveIngestFailureResult:
158 """Close one failure by hand. Dry run (the default) says what would happen and writes nothing.
160 Idempotent: closing a closed row returns it unchanged as `already_resolved`, so
161 a client that retries a call (ADK's MCP client does, once) cannot re-stamp it.
162 """
163 _, cutoff = _cutoff(now)
164 try:
165 row = source.get(failure_id)
166 except Exception:
167 logger.exception("resolve_ingest_failure read failed", failure_id=failure_id)
168 return ResolveIngestFailureResult(
169 dry_run=dry_run,
170 error=ToolError(kind="unavailable", message="Ingest failures are unavailable right now."),
171 )
172 if row is None:
173 return ResolveIngestFailureResult(status="not_found", dry_run=dry_run)
174 if row.get("resolved_at"):
175 return ResolveIngestFailureResult(
176 status="already_resolved", dry_run=dry_run, failure=IngestFailure.from_row(row, cutoff)
177 )
178 if dry_run:
179 return ResolveIngestFailureResult(
180 status="would_resolve", dry_run=True, failure=IngestFailure.from_row(row, cutoff)
181 )
183 updated = source.resolve_by_id(failure_id, resolved_by=resolved_by, note=note)
184 if updated is None: 184 ↛ 185line 184 didn't jump to line 185 because the condition on line 184 was never true
185 return ResolveIngestFailureResult(
186 dry_run=False,
187 error=ToolError(kind="unavailable", message="The failure could not be closed right now."),
188 )
189 logger.info("ingest_failure_resolved", failure_id=failure_id, resolved_by=resolved_by)
190 return ResolveIngestFailureResult(status="resolved", dry_run=False, failure=IngestFailure.from_row(updated, cutoff))