Coverage for dao/ingest_failures_dao.py: 84.21%

98 statements  

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

1"""Names the match ingest could not resolve (SB-829). 

2 

3A dropped match used to leave nothing behind but a `logger.error` in a worker 

4pod. Worse, the scraper's own run report could not see it: that report counts 

5errors from the RabbitMQ *publish*, and publishing succeeds whether or not 

6missing-table later accepts the match. A load where every name was unknown 

7reported "1432 found, 1432 submitted, 0 errors" and landed nothing. 

8 

9This DAO records one row per distinct unresolved name — never one per dropped 

10match — so seven bad spellings read as seven problems with counts rather than 

11four hundred alerts. 

12""" 

13 

14from __future__ import annotations 

15 

16from typing import Any 

17 

18import structlog 

19from postgrest.exceptions import APIError 

20 

21from dao.base_dao import BaseDAO 

22 

23logger = structlog.get_logger() 

24 

25DEFAULT_SOURCE = "match-scraper" 

26 

27# PostgREST's "could not find the function in the schema cache": the 

28# resolve-by-league migration has not reached this database yet (SB-1748). 

29_FUNCTION_NOT_FOUND = "PGRST202" 

30 

31# Kinds that record a disagreement between the feed and a person rather than a 

32# name that could not be resolved (SB-1787). The match was not dropped — it 

33# landed, or the row it would have changed was left alone — so these rows are 

34# not counted as matches lost. 

35SCORE_LOCKED = "score_locked" 

36SCRAPED_OVERRODE_MANUAL = "scraped_overrode_manual" 

37CONFLICT_KINDS = frozenset({SCORE_LOCKED, SCRAPED_OVERRODE_MANUAL}) 

38# The source a conflict row is recorded under, whoever sent the message: one 

39# disagreement about one match is one row. 

40CONFLICT_SOURCE = "mt-worker" 

41 

42 

43class IngestFailuresDAO(BaseDAO): 

44 """Read and write the ingest_failures table.""" 

45 

46 # Said once per worker, not once per team per match: until the migration 

47 # is applied every tournament message would repeat it twice. 

48 _missing_resolve_by_league_logged = False 

49 

50 def record( 

51 self, 

52 kind: str, 

53 raw_name: str, 

54 *, 

55 league: str | None = None, 

56 source: str | None = None, 

57 sample: str | None = None, 

58 ) -> dict[str, Any] | None: 

59 """Record one occurrence of an unresolved name. 

60 

61 Returns `{"id", "match_count", "should_alert"}`, or None if the write 

62 itself failed. `should_alert` is what keeps the alert stream readable: 

63 the first sighting of a name is worth a message, the four hundredth is 

64 worth a counter. It means "not yet announced" rather than "never seen 

65 before", so a name that was fixed and later regresses alerts again. 

66 

67 The upsert is done in a database function because a season load runs 

68 many workers concurrently against the same handful of bad names, and a 

69 read-modify-write from here would lose counts. 

70 

71 This must never be the reason a task fails: it is the diagnostic path, 

72 and a diagnostic that can take down ingest is worse than no diagnostic. 

73 """ 

74 try: 

75 response = self.client.rpc( 

76 "record_ingest_failure", 

77 { 

78 "p_kind": kind, 

79 "p_raw_name": raw_name, 

80 "p_league": league, 

81 "p_source": source or DEFAULT_SOURCE, 

82 "p_sample": sample, 

83 }, 

84 ).execute() 

85 rows = response.data or [] 

86 return rows[0] if rows else None 

87 except Exception: 

88 logger.exception("Could not record ingest failure", kind=kind, raw_name=raw_name) 

89 return None 

90 

91 def resolved_with_sample( 

92 self, 

93 kind: str, 

94 raw_name: str, 

95 sample: str, 

96 *, 

97 league: str | None = None, 

98 source: str | None = None, 

99 ) -> bool: 

100 """Whether this row is closed and last recorded exactly this sample (SB-1787). 

101 

102 A conflict row (CONFLICT_KINDS) a person has closed should stay closed 

103 while the feed keeps saying the same thing; record() would reopen it. 

104 The row is found by the same identity record() upserts on. 

105 

106 False when there is no such row, it is open, or the read fails — the 

107 caller then records, and a duplicate finding beats a lost one. 

108 """ 

109 try: 

110 query = ( 

111 self.client.table("ingest_failures") 

112 .select("sample, resolved_at") 

113 .eq("kind", kind) 

114 .ilike("raw_name", raw_name) 

115 .eq("source", source or DEFAULT_SOURCE) 

116 ) 

117 query = query.is_("league", "null") if league is None else query.eq("league", league) 

118 rows = query.limit(1).execute().data or [] 

119 except Exception: 

120 logger.exception("Could not read ingest failure", kind=kind, raw_name=raw_name) 

121 return False 

122 return bool(rows) and rows[0].get("resolved_at") is not None and rows[0].get("sample") == sample 

123 

124 def resolve(self, kind: str, raw_name: str, *, source: str | None = None) -> int: 

125 """Close any open rows for a name that now resolves. 

126 

127 Called on the success path, so an alias added mid-load clears its own 

128 alert without anyone touching the table. 

129 """ 

130 try: 

131 response = self.client.rpc( 

132 "resolve_ingest_failures", 

133 {"p_kind": kind, "p_raw_name": raw_name, "p_source": source or DEFAULT_SOURCE}, 

134 ).execute() 

135 return int(response.data or 0) 

136 except Exception: 

137 logger.exception("Could not resolve ingest failures", kind=kind, raw_name=raw_name) 

138 return 0 

139 

140 def resolve_in_league( 

141 self, kind: str, raw_name: str, *, league: str | None, source: str | None = None 

142 ) -> int | None: 

143 """Close the open row for a name that now resolves in one league (SB-1748). 

144 

145 A tournament message resolves a name per side, and each side has its 

146 own row. `resolve` ignores the league, so a Homegrown success would 

147 close the Academy row for the same name; the next Academy failure 

148 reopens it with notified_at cleared, and the name alerts again on 

149 every flap. `league` is matched as the feed spelled it, and None 

150 matches only rows recorded with none. 

151 

152 Returns None when the database does not have the function yet. The row 

153 is then left open — the league-blind `resolve` is not a fallback, 

154 because closing the wrong side's row is the fault this exists to end — 

155 and the caller should ask again rather than remember the answer. 

156 """ 

157 try: 

158 response = self.client.rpc( 

159 "resolve_ingest_failures_by_league", 

160 { 

161 "p_kind": kind, 

162 "p_raw_name": raw_name, 

163 "p_league": league, 

164 "p_source": source or DEFAULT_SOURCE, 

165 }, 

166 ).execute() 

167 return int(response.data or 0) 

168 except APIError as exc: 

169 if exc.code == _FUNCTION_NOT_FOUND: 

170 if not self._missing_resolve_by_league_logged: 

171 self._missing_resolve_by_league_logged = True 

172 logger.warning( 

173 "resolve_ingest_failures_by_league is not installed — leaving failure rows open", 

174 kind=kind, 

175 raw_name=raw_name, 

176 league=league, 

177 ) 

178 return None 

179 logger.exception("Could not resolve ingest failures", kind=kind, raw_name=raw_name, league=league) 

180 return 0 

181 except Exception: 

182 logger.exception("Could not resolve ingest failures", kind=kind, raw_name=raw_name, league=league) 

183 return 0 

184 

185 def get(self, failure_id: int) -> dict[str, Any] | None: 

186 """One row by id, open or resolved; None if there is no such id. 

187 

188 Raises on a database error: the caller (an admin preview, SB-1304) must be 

189 able to tell "no such row" from "could not look". 

190 """ 

191 response = self.client.table("ingest_failures").select("*").eq("id", failure_id).execute() 

192 rows = response.data or [] 

193 return rows[0] if rows else None 

194 

195 def resolve_by_id( 

196 self, 

197 failure_id: int, 

198 *, 

199 resolved_by: str | None = None, 

200 note: str | None = None, 

201 ) -> dict[str, Any] | None: 

202 """Close one row by hand, recording who and why. 

203 

204 The automatic resolve only fires when the same name resolves later. A 

205 name fixed at the *sender* is never submitted again, so nothing 

206 triggers it and the row stays open forever — reported on every 

207 subsequent run as a problem that no longer exists (SB-845). 

208 

209 Returns the row, or None if there is no such id. An already-resolved 

210 row is returned unchanged rather than re-stamped: the first decision is 

211 the one worth keeping. 

212 """ 

213 try: 

214 existing = self.client.table("ingest_failures").select("*").eq("id", failure_id).execute() 

215 rows = existing.data or [] 

216 if not rows: 

217 return None 

218 if rows[0].get("resolved_at"): 

219 return rows[0] 

220 

221 updated = ( 

222 self.client.table("ingest_failures") 

223 .update( 

224 { 

225 "resolved_at": "now()", 

226 "resolved_by": resolved_by, 

227 "resolution_note": note, 

228 } 

229 ) 

230 .eq("id", failure_id) 

231 .execute() 

232 ) 

233 return (updated.data or [None])[0] 

234 except Exception: 

235 logger.exception("Could not resolve ingest failure by id", failure_id=failure_id) 

236 return None 

237 

238 def mark_notified(self, failure_ids: list[int]) -> None: 

239 """Stamp rows that have been alerted on, so they are not re-announced.""" 

240 if not failure_ids: 

241 return 

242 try: 

243 self.client.table("ingest_failures").update({"notified_at": "now()"}).in_("id", failure_ids).execute() 

244 except Exception: 

245 logger.exception("Could not mark ingest failures notified", failure_ids=failure_ids) 

246 

247 def notified_since(self, iso_timestamp: str) -> int: 

248 """How many rows have been alerted on since a point in time. 

249 

250 Backs the per-window alert cap. A brand-new season can arrive with 

251 dozens of unknown names, and a message per name would be its own kind 

252 of unreadable. 

253 """ 

254 try: 

255 response = ( 

256 self.client.table("ingest_failures") 

257 .select("id", count="exact") 

258 .gte("notified_at", iso_timestamp) 

259 .execute() 

260 ) 

261 return response.count or 0 

262 except Exception: 

263 logger.exception("Could not count notified ingest failures") 

264 return 0 

265 

266 def open_failures( 

267 self, 

268 since: str | None = None, 

269 limit: int = 200, 

270 *, 

271 kinds: list[str] | None = None, 

272 include_conflicts: bool = False, 

273 ) -> list[dict[str, Any]]: 

274 """Unresolved rows, newest first. 

275 

276 `since` filters on last_seen, which is what a scraper run wants: the 

277 names that cost it matches during the run it just finished, not every 

278 name that has ever been wrong. 

279 

280 Conflict rows (CONFLICT_KINDS, SB-1787) are left out unless asked for: 

281 they are not dropped matches, and match-scraper sums `match_count` over 

282 this list as "rejected by MT". `kinds` returns only those kinds, 

283 conflict kinds included; `include_conflicts` returns every kind. 

284 """ 

285 try: 

286 query = self.client.table("ingest_failures").select("*").is_("resolved_at", "null") 

287 if since: 

288 query = query.gte("last_seen", since) 

289 if kinds: 

290 query = query.in_("kind", list(kinds)) 

291 elif not include_conflicts: 

292 query = query.not_.in_("kind", sorted(CONFLICT_KINDS)) 

293 response = query.order("last_seen", desc=True).limit(limit).execute() 

294 return response.data or [] 

295 except Exception: 

296 logger.exception("Could not read ingest failures") 

297 return []