| 1 | """Deterministic, source-grounded act-time freshness verification.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import hashlib |
| 6 | import math |
| 7 | import re |
| 8 | from collections import Counter, defaultdict |
| 9 | from dataclasses import dataclass |
| 10 | from datetime import datetime, timezone |
| 11 | from typing import Any, Callable |
| 12 | |
| 13 | from . import dates, github, grounding, health, polymarket, schema, stocktwits |
| 14 | |
| 15 | |
| 16 | @dataclass(frozen=True) |
| 17 | class Claim: |
| 18 | """A conservative, machine-verifiable claim extracted from one source item.""" |
| 19 | |
| 20 | claim_id: str |
| 21 | candidate_id: str |
| 22 | text: str |
| 23 | source: str |
| 24 | source_item_id: str |
| 25 | source_url: str |
| 26 | source_timestamp: str | None |
| 27 | datum_kind: str |
| 28 | datum_key: str |
| 29 | original_value: Any |
| 30 | datum_market_id: str | None = None |
| 31 | |
| 32 | |
| 33 | @dataclass(frozen=True) |
| 34 | class RefetchedDatum: |
| 35 | value: Any |
| 36 | url: str |
| 37 | timestamp: str | None = None |
| 38 | values: dict[str, Any] | None = None |
| 39 | legacy_values: dict[str, Any] | None = None |
| 40 | market_values: dict[str, Any] | None = None |
| 41 | blocked_repeats: frozenset[str] = frozenset() |
| 42 | legacy_blocked_repeats: frozenset[str] | None = None |
| 43 | |
| 44 | |
| 45 | Refetcher = Callable[[schema.SourceItem | None, str], RefetchedDatum | dict[str, Any] | Any] |
| 46 | |
| 47 | _STATUS_PATTERN = re.compile( |
| 48 | r"\b(?P<subject>[A-Z][A-Za-z0-9&.'’/+_-]*(?:\s+[A-Z0-9][A-Za-z0-9&.'’/+_-]*){0,5})" |
| 49 | r"\s+(?P<copula>is|was|remains|became|has been)\s+" |
| 50 | r"(?P<status>open|closed|active|inactive|available|unavailable|" |
| 51 | r"approved|rejected|launched|discontinued|online|offline)\b" |
| 52 | ) |
| 53 | _STATUS_COPULA_PRIORITY = {"was": 0, "became": 1, "has been": 2, "is": 3, "remains": 3} |
| 54 | _DATE_ONLY_RE = re.compile(r"\d{4}-\d{2}-\d{2}") |
| 55 | _OPPOSITE_STATUS = { |
| 56 | "open": "closed", |
| 57 | "closed": "open", |
| 58 | "active": "inactive", |
| 59 | "inactive": "active", |
| 60 | "available": "unavailable", |
| 61 | "unavailable": "available", |
| 62 | "approved": "rejected", |
| 63 | "rejected": "approved", |
| 64 | "launched": "discontinued", |
| 65 | "discontinued": "launched", |
| 66 | "online": "offline", |
| 67 | "offline": "online", |
| 68 | } |
| 69 | _REFETCHABLE_SOURCES = frozenset({"polymarket", "github", "stocktwits"}) |
| 70 | _USABLE_SOURCE_STATES = frozenset({health.OK, schema.PARTIAL}) |
| 71 | |
| 72 | |
| 73 | def _now() -> str: |
| 74 | return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") |
| 75 | |
| 76 | |
| 77 | def _claim_id(candidate_id: str, kind: str, key: str) -> str: |
| 78 | digest = hashlib.sha256(f"{candidate_id}\0{kind}\0{key}".encode()).hexdigest()[:12] |
| 79 | return f"claim-{digest}" |
| 80 | |
| 81 | |
| 82 | def _star_observation_time(*receipts: object) -> str | None: |
| 83 | """Keep the precision of a recorded count, including older day-only observations.""" |
| 84 | for receipt in receipts: |
| 85 | if isinstance(receipt, str) and dates.parse_date(receipt) is not None: |
| 86 | return receipt.strip() |
| 87 | return None |
| 88 | |
| 89 | |
| 90 | def _claim( |
| 91 | grounded: grounding.GroundedClaimText, |
| 92 | kind: str, |
| 93 | key: str, |
| 94 | value: Any, |
| 95 | text: str, |
| 96 | *, |
| 97 | datum_market_id: str | None = None, |
| 98 | ) -> Claim: |
| 99 | item = grounded.item |
| 100 | timestamp = item.published_at |
| 101 | if kind == "github_stars": |
| 102 | timestamp = _star_observation_time( |
| 103 | item.metadata.get("repo_counts_observed_at"), item.metadata.get("repo_counts_observed_on"), |
| 104 | ) |
| 105 | return Claim( |
| 106 | claim_id=_claim_id(grounded.candidate_id, kind, key), |
| 107 | candidate_id=grounded.candidate_id, |
| 108 | text=text, |
| 109 | source=item.source, |
| 110 | source_item_id=item.item_id, |
| 111 | source_url=item.url, |
| 112 | source_timestamp=timestamp, |
| 113 | datum_kind=kind, |
| 114 | datum_key=key, |
| 115 | original_value=value, |
| 116 | datum_market_id=datum_market_id, |
| 117 | ) |
| 118 | |
| 119 | |
| 120 | def extract_claims(report: schema.Report) -> list[Claim]: |
| 121 | """Extract only structured numerics/dates and tightly shaped status claims.""" |
| 122 | claims: list[Claim] = [] |
| 123 | item_level_repos: set[tuple[str, str]] = set() |
| 124 | for grounded in grounding.claim_source_map(report).values(): |
| 125 | item = grounded.item |
| 126 | if item.source == "polymarket": |
| 127 | outcome_pairs = item.metadata.get("outcome_prices") or [] |
| 128 | raw_market_ids = item.metadata.get("outcome_market_ids") |
| 129 | aligned_market_ids = ( |
| 130 | raw_market_ids |
| 131 | if isinstance(raw_market_ids, (list, tuple)) |
| 132 | and len(raw_market_ids) == len(outcome_pairs) |
| 133 | else None |
| 134 | ) |
| 135 | valid_pairs: list[tuple[str, float, str | None]] = [] |
| 136 | for idx, pair in enumerate(outcome_pairs): |
| 137 | if not isinstance(pair, (list, tuple)) or len(pair) != 2: |
| 138 | continue |
| 139 | name, value = pair |
| 140 | if isinstance(value, bool) or not isinstance(value, (int, float)): |
| 141 | continue |
| 142 | try: |
| 143 | numeric = float(value) |
| 144 | except OverflowError: |
| 145 | continue |
| 146 | if not math.isfinite(numeric): |
| 147 | continue |
| 148 | key = str(name).strip() |
| 149 | if not key: |
| 150 | continue |
| 151 | market_id = ( |
| 152 | str(aligned_market_ids[idx] or "").strip() or None |
| 153 | if aligned_market_ids is not None |
| 154 | else None |
| 155 | ) |
| 156 | valid_pairs.append((key, numeric, market_id)) |
| 157 | outcome_counts = Counter(key.casefold() for key, _value, _mid in valid_pairs) |
| 158 | seen_outcomes: dict[str, int] = defaultdict(int) |
| 159 | for key, numeric, market_id in valid_pairs: |
| 160 | normalized_key = key.casefold() |
| 161 | occurrence = seen_outcomes[normalized_key] |
| 162 | seen_outcomes[normalized_key] += 1 |
| 163 | datum_key = ( |
| 164 | f"{key}\x1f{occurrence}" |
| 165 | if outcome_counts[normalized_key] > 1 |
| 166 | else key |
| 167 | ) |
| 168 | claims.append( |
| 169 | _claim( |
| 170 | grounded, |
| 171 | "polymarket_probability", |
| 172 | datum_key, |
| 173 | numeric, |
| 174 | f"{item.title}: {key} is {numeric * 100:g}%", |
| 175 | datum_market_id=market_id, |
| 176 | ) |
| 177 | ) |
| 178 | end_date = item.metadata.get("end_date") |
| 179 | if isinstance(end_date, str) and re.fullmatch(r"\d{4}-\d{2}-\d{2}", end_date): |
| 180 | claims.append( |
| 181 | _claim( |
| 182 | grounded, |
| 183 | "polymarket_end_date", |
| 184 | "end_date", |
| 185 | end_date, |
| 186 | f"{item.title} closes {end_date}", |
| 187 | ) |
| 188 | ) |
| 189 | elif item.source == "github": |
| 190 | stars = schema.engagement_value(item, "stars") |
| 191 | repo = _github_repo(item) |
| 192 | if repo and stars is not None: |
| 193 | item_level_repos.add((grounded.candidate_id, repo.casefold())) |
| 194 | claims.append( |
| 195 | _claim( |
| 196 | grounded, |
| 197 | "github_stars", |
| 198 | "stars", |
| 199 | stars, |
| 200 | f"{repo} has {stars:,} GitHub stars", |
| 201 | ) |
| 202 | ) |
| 203 | elif item.source == "stocktwits": |
| 204 | aggregate = item.metadata.get("sentiment_aggregate") or {} |
| 205 | pct = aggregate.get("pct_bullish") if isinstance(aggregate, dict) else None |
| 206 | symbol = str(item.metadata.get("symbol") or item.container or "").strip() |
| 207 | if symbol and isinstance(pct, (int, float)) and not isinstance(pct, bool): |
| 208 | claims.append( |
| 209 | _claim( |
| 210 | grounded, |
| 211 | "stocktwits_bullish_pct", |
| 212 | "pct_bullish", |
| 213 | float(pct), |
| 214 | f"StockTwits ${symbol} tagged sentiment is {float(pct):g}% bullish", |
| 215 | ) |
| 216 | ) |
| 217 | |
| 218 | # Status assertions are accepted only when a short, explicit subject + |
| 219 | # copula + status occurs in the exact candidate text tied above. |
| 220 | status_text = " ".join(part for part in (grounded.title, grounded.summary) if part) |
| 221 | match = _STATUS_PATTERN.search(status_text) |
| 222 | if match: |
| 223 | subject = match.group("subject").strip() |
| 224 | status = match.group("status").lower() |
| 225 | claims.append( |
| 226 | _claim( |
| 227 | grounded, |
| 228 | "status_assertion", |
| 229 | subject.lower(), |
| 230 | status, |
| 231 | match.group(0), |
| 232 | ) |
| 233 | ) |
| 234 | |
| 235 | claims.extend(_candidate_star_claims(report, item_level_repos)) |
| 236 | return claims |
| 237 | |
| 238 | |
| 239 | def _candidate_star_claims( |
| 240 | report: schema.Report, |
| 241 | item_level_repos: set[tuple[str, str]], |
| 242 | ) -> list[Claim]: |
| 243 | """Emit star claims from candidate enrichment metadata. |
| 244 | |
| 245 | Star enrichment attaches ``metadata["github_stars"]`` (repo -> stars) |
| 246 | after reranking, so these facts never appear on item-level engagement - |
| 247 | typically the candidate's primary item is a non-GitHub source. Each repo |
| 248 | becomes one repo-keyed claim unless the same candidate already claimed it |
| 249 | at item level; a different candidate's item-level claim never suppresses |
| 250 | this candidate's own verdict (and its inline freshness flag). |
| 251 | """ |
| 252 | claims: list[Claim] = [] |
| 253 | candidates_by_id = { |
| 254 | candidate.candidate_id: candidate for candidate in report.ranked_candidates |
| 255 | } |
| 256 | for grounded in grounding.claim_source_map(report).values(): |
| 257 | candidate = candidates_by_id.get(grounded.candidate_id) |
| 258 | if candidate is None: |
| 259 | continue |
| 260 | stars_map = candidate.metadata.get("github_stars") |
| 261 | if not isinstance(stars_map, dict): |
| 262 | continue |
| 263 | observed = candidate.metadata.get("github_stars_observed_at") |
| 264 | for repo, raw_stars in sorted(stars_map.items()): |
| 265 | if not isinstance(repo, str) or not re.fullmatch(r"[^/\s]+/[^/\s]+", repo): |
| 266 | continue |
| 267 | stars = schema.github_repo_count(raw_stars) |
| 268 | if stars is None: |
| 269 | continue |
| 270 | if (grounded.candidate_id, repo.casefold()) in item_level_repos: |
| 271 | continue |
| 272 | item = grounded.item |
| 273 | claims.append( |
| 274 | Claim( |
| 275 | claim_id=_claim_id(grounded.candidate_id, "github_stars", repo), |
| 276 | candidate_id=grounded.candidate_id, |
| 277 | text=f"{repo} has {stars:,} GitHub stars", |
| 278 | source="github", |
| 279 | source_item_id=item.item_id, |
| 280 | source_url=f"https://github.com/{repo}", |
| 281 | source_timestamp=_star_observation_time(observed.get(repo)) if isinstance(observed, dict) else None, |
| 282 | datum_kind="github_stars", |
| 283 | datum_key=repo, |
| 284 | original_value=stars, |
| 285 | ) |
| 286 | ) |
| 287 | return claims |
| 288 | |
| 289 | |
| 290 | def _github_repo(item: schema.SourceItem) -> str | None: |
| 291 | if item.container and re.fullmatch(r"[^/\s]+/[^/\s]+", item.container): |
| 292 | return item.container |
| 293 | match = re.match(r"https?://github\.com/([^/]+/[^/#?]+)", item.url) |
| 294 | return match.group(1).removesuffix(".git") if match else None |
| 295 | |
| 296 | |
| 297 | def _default_refetchers() -> dict[str, Refetcher]: |
| 298 | return { |
| 299 | "polymarket": polymarket.refetch_datum, |
| 300 | "github": github.refetch_datum, |
| 301 | "stocktwits": stocktwits.refetch_datum, |
| 302 | } |
| 303 | |
| 304 | |
| 305 | def _coerce_blocked_repeats(raw: Any) -> frozenset[str]: |
| 306 | if not isinstance(raw, (list, tuple, set, frozenset)): |
| 307 | return frozenset() |
| 308 | return frozenset(str(name).strip().casefold() for name in raw if name and str(name).strip()) |
| 309 | |
| 310 | |
| 311 | def _coerce_refetched(value: RefetchedDatum | dict[str, Any] | Any, fallback_url: str) -> RefetchedDatum: |
| 312 | if isinstance(value, RefetchedDatum): |
| 313 | return value |
| 314 | if isinstance(value, dict) and "value" in value: |
| 315 | raw_legacy_blocked = value.get("legacy_blocked_repeats") |
| 316 | return RefetchedDatum( |
| 317 | value=value["value"], |
| 318 | url=str(value.get("url") or fallback_url), |
| 319 | timestamp=value.get("timestamp"), |
| 320 | values=value.get("values") if isinstance(value.get("values"), dict) else None, |
| 321 | legacy_values=( |
| 322 | value.get("legacy_values") |
| 323 | if isinstance(value.get("legacy_values"), dict) |
| 324 | else None |
| 325 | ), |
| 326 | market_values=( |
| 327 | value.get("market_values") |
| 328 | if isinstance(value.get("market_values"), dict) |
| 329 | else None |
| 330 | ), |
| 331 | blocked_repeats=_coerce_blocked_repeats(value.get("blocked_repeats")), |
| 332 | legacy_blocked_repeats=( |
| 333 | _coerce_blocked_repeats(raw_legacy_blocked) |
| 334 | if raw_legacy_blocked is not None |
| 335 | else None |
| 336 | ), |
| 337 | ) |
| 338 | return RefetchedDatum(value=value, url=fallback_url) |
| 339 | |
| 340 | |
| 341 | def _format_verdict_value(kind: str, value: Any) -> str: |
| 342 | """Format a verdict value the way the matching claim text renders it.""" |
| 343 | if kind == "polymarket_probability": |
| 344 | try: |
| 345 | return f"{float(value) * 100:g}%" |
| 346 | except (TypeError, ValueError): |
| 347 | return str(value) |
| 348 | if kind == "stocktwits_bullish_pct": |
| 349 | try: |
| 350 | return f"{float(value):g}%" |
| 351 | except (TypeError, ValueError): |
| 352 | return str(value) |
| 353 | if isinstance(value, bool): |
| 354 | return str(value) |
| 355 | if isinstance(value, int): |
| 356 | return f"{value:,}" |
| 357 | if isinstance(value, float): |
| 358 | return f"{value:g}" |
| 359 | return str(value) |
| 360 | |
| 361 | |
| 362 | def _values_match(claim: Claim, current: Any) -> bool: |
| 363 | if claim.datum_kind == "github_stars": |
| 364 | return not isinstance(current, bool) and claim.original_value == current |
| 365 | if claim.datum_kind == "polymarket_probability": |
| 366 | try: |
| 367 | return abs(float(claim.original_value) - float(current)) < 0.005 |
| 368 | except (TypeError, ValueError): |
| 369 | return False |
| 370 | if isinstance(claim.original_value, (int, float)) and isinstance(current, (int, float)): |
| 371 | return float(claim.original_value) == float(current) |
| 372 | return claim.original_value == current |
| 373 | |
| 374 | |
| 375 | def _item_identity(source: str, url: str | None, item_id: str) -> tuple[str, str]: |
| 376 | return (source, (url or "").strip() or item_id) |
| 377 | |
| 378 | |
| 379 | def _parse_timestamp(raw: str | None) -> tuple[datetime, bool] | None: |
| 380 | if not isinstance(raw, str): |
| 381 | return None |
| 382 | text = raw.strip() |
| 383 | if not text: |
| 384 | return None |
| 385 | try: |
| 386 | parsed = dates.parse_date(text) |
| 387 | except (ValueError, TypeError, OverflowError, OSError): |
| 388 | parsed = None |
| 389 | if parsed is None: |
| 390 | try: |
| 391 | iso = datetime.fromisoformat(text) |
| 392 | except ValueError: |
| 393 | return None |
| 394 | parsed = ( |
| 395 | iso.astimezone(timezone.utc) |
| 396 | if iso.tzinfo is not None |
| 397 | else iso.replace(tzinfo=timezone.utc) |
| 398 | ) |
| 399 | return parsed, bool(_DATE_ONLY_RE.fullmatch(text)) |
| 400 | |
| 401 | |
| 402 | def _is_strictly_newer( |
| 403 | item_ts: tuple[datetime, bool], |
| 404 | reference_ts: tuple[datetime, bool], |
| 405 | ) -> bool: |
| 406 | item_dt, item_date_only = item_ts |
| 407 | ref_dt, ref_date_only = reference_ts |
| 408 | if not item_date_only and not ref_date_only: |
| 409 | return item_dt > ref_dt |
| 410 | return item_dt.date() > ref_dt.date() |
| 411 | |
| 412 | |
| 413 | def _newer_status_contradiction( |
| 414 | report: schema.Report, |
| 415 | claim: Claim, |
| 416 | ) -> schema.SourceItem | None: |
| 417 | if not claim.source_timestamp: |
| 418 | return None |
| 419 | claim_ts = _parse_timestamp(claim.source_timestamp) |
| 420 | if claim_ts is None: |
| 421 | return None |
| 422 | opposite = _OPPOSITE_STATUS.get(str(claim.original_value)) |
| 423 | if not opposite: |
| 424 | return None |
| 425 | subject_tokens = [ |
| 426 | token.lower() |
| 427 | for token in re.findall(r"[A-Za-z0-9]+", claim.datum_key) |
| 428 | if len(token) >= 3 |
| 429 | ] |
| 430 | if not subject_tokens: |
| 431 | return None |
| 432 | claim_identity = _item_identity(claim.source, claim.source_url, claim.source_item_id) |
| 433 | matched: list[tuple[tuple[datetime, bool], schema.SourceItem, dict[int, set[str]]]] = [] |
| 434 | for items in report.items_by_source.values(): |
| 435 | for item in items: |
| 436 | if _item_identity(item.source, item.url, item.item_id) == claim_identity: |
| 437 | continue |
| 438 | item_ts = _parse_timestamp(item.published_at) |
| 439 | if item_ts is None or not _is_strictly_newer(item_ts, claim_ts): |
| 440 | continue |
| 441 | text = f"{item.title} {item.snippet} {item.body}" |
| 442 | statuses_by_priority: dict[int, set[str]] = defaultdict(set) |
| 443 | for match in _STATUS_PATTERN.finditer(text): |
| 444 | asserted_subject = [ |
| 445 | token.lower() |
| 446 | for token in re.findall(r"[A-Za-z0-9]+", match.group("subject")) |
| 447 | if len(token) >= 3 |
| 448 | ] |
| 449 | if asserted_subject == subject_tokens: |
| 450 | status = match.group("status").lower() |
| 451 | if status in {opposite, claim.original_value}: |
| 452 | priority = _STATUS_COPULA_PRIORITY[match.group("copula")] |
| 453 | statuses_by_priority[priority].add(status) |
| 454 | if statuses_by_priority: |
| 455 | matched.append((item_ts, item, statuses_by_priority)) |
| 456 | if not matched: |
| 457 | return None |
| 458 | newest = [ |
| 459 | entry |
| 460 | for entry in matched |
| 461 | if not any(_is_strictly_newer(other[0], entry[0]) for other in matched) |
| 462 | ] |
| 463 | newest.sort( |
| 464 | key=lambda entry: ( |
| 465 | -entry[0][0].timestamp(), |
| 466 | entry[1].source, |
| 467 | entry[1].url, |
| 468 | entry[1].item_id, |
| 469 | ) |
| 470 | ) |
| 471 | aggregated: dict[int, set[str]] = defaultdict(set) |
| 472 | opposite_item: dict[int, schema.SourceItem] = {} |
| 473 | for _item_ts, item, item_statuses in newest: |
| 474 | for priority, statuses in item_statuses.items(): |
| 475 | aggregated[priority].update(statuses) |
| 476 | if opposite in statuses and priority not in opposite_item: |
| 477 | opposite_item[priority] = item |
| 478 | top_priority = max(aggregated) |
| 479 | top_statuses = aggregated[top_priority] |
| 480 | if top_statuses == {opposite}: |
| 481 | return opposite_item[top_priority] |
| 482 | return None |
| 483 | |
| 484 | |
| 485 | def _normalize_datum_key(key: str) -> str: |
| 486 | if "\x1f" in key: |
| 487 | name, occurrence = key.rsplit("\x1f", 1) |
| 488 | return f"{name.strip().casefold()}\x1f{occurrence.strip()}" |
| 489 | return key.strip().casefold() |
| 490 | |
| 491 | |
| 492 | def _lookup_cached_datum( |
| 493 | cached: tuple[str | None, RefetchedDatum], |
| 494 | claim: Claim, |
| 495 | ) -> RefetchedDatum | None: |
| 496 | """Resolve ``claim.datum_key`` from a cached snapshot using refetch_datum semantics.""" |
| 497 | cached_key, cached_datum = cached |
| 498 | if ( |
| 499 | claim.datum_kind == "polymarket_probability" |
| 500 | and claim.datum_market_id |
| 501 | and cached_datum.market_values is not None |
| 502 | ): |
| 503 | value = cached_datum.market_values.get(claim.datum_market_id) |
| 504 | if value is not None: |
| 505 | return RefetchedDatum( |
| 506 | value=value, |
| 507 | url=cached_datum.url, |
| 508 | timestamp=cached_datum.timestamp, |
| 509 | values=cached_datum.values, |
| 510 | legacy_values=cached_datum.legacy_values, |
| 511 | market_values=cached_datum.market_values, |
| 512 | blocked_repeats=cached_datum.blocked_repeats, |
| 513 | legacy_blocked_repeats=cached_datum.legacy_blocked_repeats, |
| 514 | ) |
| 515 | return None |
| 516 | values = cached_datum.values |
| 517 | legacy_values = cached_datum.legacy_values |
| 518 | if values or legacy_values or cached_datum.market_values is not None: |
| 519 | value = polymarket.resolve_snapshot_value( |
| 520 | values or {}, |
| 521 | claim.datum_key, |
| 522 | legacy_values=legacy_values, |
| 523 | blocked_repeats=cached_datum.blocked_repeats, |
| 524 | legacy_blocked_repeats=cached_datum.legacy_blocked_repeats, |
| 525 | allow_occurrence_zero=(claim.datum_kind == "polymarket_probability"), |
| 526 | ) |
| 527 | if value is not None: |
| 528 | return RefetchedDatum( |
| 529 | value=value, |
| 530 | url=cached_datum.url, |
| 531 | timestamp=cached_datum.timestamp, |
| 532 | values=values, |
| 533 | legacy_values=legacy_values, |
| 534 | market_values=cached_datum.market_values, |
| 535 | blocked_repeats=cached_datum.blocked_repeats, |
| 536 | legacy_blocked_repeats=cached_datum.legacy_blocked_repeats, |
| 537 | ) |
| 538 | return None |
| 539 | if cached_key is not None and _normalize_datum_key(cached_key) == _normalize_datum_key(claim.datum_key): |
| 540 | return cached_datum if cached_datum.value is not None else None |
| 541 | return None |
| 542 | |
| 543 | |
| 544 | def _point_refetch_key(item: schema.SourceItem, claim: Claim) -> tuple[str, ...]: |
| 545 | """Identify the source snapshot shared by claims in one verification pass.""" |
| 546 | if claim.source == "polymarket": |
| 547 | key = item.metadata.get("event_id") or item.url |
| 548 | elif claim.source == "stocktwits": |
| 549 | window = item.metadata.get("freshness_window") or {} |
| 550 | return tuple( |
| 551 | str(value or "").strip().casefold() |
| 552 | for value in ( |
| 553 | claim.source, |
| 554 | item.metadata.get("symbol") or item.container or item.url, |
| 555 | window.get("depth"), |
| 556 | window.get("from_date"), |
| 557 | window.get("to_date"), |
| 558 | ) |
| 559 | ) |
| 560 | elif claim.source == "github": |
| 561 | key = _github_repo(item) or item.url |
| 562 | else: |
| 563 | key = item.item_id |
| 564 | return claim.source, str(key).strip().casefold() |
| 565 | |
| 566 | |
| 567 | def _point_verdict( |
| 568 | claim: Claim, |
| 569 | checked_at: str, |
| 570 | refreshed: RefetchedDatum, |
| 571 | ) -> schema.FreshnessVerdict: |
| 572 | """Build the current/stale verdict for a successfully re-fetched datum.""" |
| 573 | matches = _values_match(claim, refreshed.value) |
| 574 | return schema.FreshnessVerdict( |
| 575 | claim_id=claim.claim_id, |
| 576 | candidate_id=claim.candidate_id, |
| 577 | claim=claim.text, |
| 578 | source=claim.source, |
| 579 | source_item_id=claim.source_item_id, |
| 580 | verdict="current" if matches else "stale", |
| 581 | checked_at=checked_at, |
| 582 | source_url=claim.source_url, |
| 583 | source_timestamp=claim.source_timestamp, |
| 584 | evidence_url=refreshed.url, |
| 585 | evidence_timestamp=refreshed.timestamp or checked_at, |
| 586 | original_value=claim.original_value, |
| 587 | current_value=refreshed.value, |
| 588 | detail=None if matches else ( |
| 589 | "moved: " |
| 590 | f"{_format_verdict_value(claim.datum_kind, claim.original_value)}" |
| 591 | " -> " |
| 592 | f"{_format_verdict_value(claim.datum_kind, refreshed.value)}" |
| 593 | ), |
| 594 | ) |
| 595 | |
| 596 | |
| 597 | def _unsupported( |
| 598 | claim: Claim, |
| 599 | checked_at: str, |
| 600 | detail: str, |
| 601 | ) -> schema.FreshnessVerdict: |
| 602 | return schema.FreshnessVerdict( |
| 603 | claim_id=claim.claim_id, |
| 604 | candidate_id=claim.candidate_id, |
| 605 | claim=claim.text, |
| 606 | source=claim.source, |
| 607 | source_item_id=claim.source_item_id, |
| 608 | verdict="unsupported", |
| 609 | checked_at=checked_at, |
| 610 | source_url=claim.source_url, |
| 611 | source_timestamp=claim.source_timestamp, |
| 612 | # No fresh evidence was obtained; the original source stays on |
| 613 | # source_url/source_timestamp and the evidence fields stay empty. |
| 614 | evidence_url="", |
| 615 | evidence_timestamp=None, |
| 616 | original_value=claim.original_value, |
| 617 | detail=detail, |
| 618 | ) |
| 619 | |
| 620 | |
| 621 | def verify_report( |
| 622 | report: schema.Report, |
| 623 | *, |
| 624 | refetchers: dict[str, Refetcher] | None = None, |
| 625 | allow_network: bool = True, |
| 626 | checked_at: str | None = None, |
| 627 | ) -> list[schema.FreshnessVerdict]: |
| 628 | """Attach and return deterministic freshness verdicts for ``report``.""" |
| 629 | checked = checked_at or _now() |
| 630 | dispatch = _default_refetchers() if refetchers is None else refetchers |
| 631 | grounded_items = { |
| 632 | candidate_id: grounded.item |
| 633 | for candidate_id, grounded in grounding.claim_source_map(report).items() |
| 634 | } |
| 635 | fallback_items: dict[tuple[str, str], schema.SourceItem] = {} |
| 636 | for source_items in report.items_by_source.values(): |
| 637 | for item in source_items: |
| 638 | fallback_items[_item_identity(item.source, item.url, item.item_id)] = item |
| 639 | for candidate in report.ranked_candidates: |
| 640 | for item in candidate.source_items: |
| 641 | fallback_items.setdefault( |
| 642 | _item_identity(item.source, item.url, item.item_id), item |
| 643 | ) |
| 644 | |
| 645 | verdicts: list[schema.FreshnessVerdict] = [] |
| 646 | point_cache: dict[tuple[str, ...], tuple[str | None, RefetchedDatum]] = {} |
| 647 | point_errors: dict[tuple[str, ...], str] = {} |
| 648 | for claim in extract_claims(report): |
| 649 | if claim.datum_kind == "status_assertion": |
| 650 | contradiction = _newer_status_contradiction(report, claim) |
| 651 | if contradiction: |
| 652 | verdicts.append( |
| 653 | schema.FreshnessVerdict( |
| 654 | claim_id=claim.claim_id, |
| 655 | candidate_id=claim.candidate_id, |
| 656 | claim=claim.text, |
| 657 | source=claim.source, |
| 658 | source_item_id=claim.source_item_id, |
| 659 | verdict="contradicted", |
| 660 | checked_at=checked, |
| 661 | source_url=claim.source_url, |
| 662 | source_timestamp=claim.source_timestamp, |
| 663 | evidence_url=contradiction.url, |
| 664 | evidence_timestamp=contradiction.published_at, |
| 665 | original_value=claim.original_value, |
| 666 | current_value=_OPPOSITE_STATUS.get(str(claim.original_value)), |
| 667 | detail=f"Newer {contradiction.source} item disagrees", |
| 668 | ) |
| 669 | ) |
| 670 | else: |
| 671 | verdicts.append( |
| 672 | _unsupported( |
| 673 | claim, |
| 674 | checked, |
| 675 | "Status could not be positively re-derived from a current source", |
| 676 | ) |
| 677 | ) |
| 678 | continue |
| 679 | |
| 680 | if claim.datum_kind == "github_stars" and claim.datum_key != "stars": |
| 681 | # Candidate-enrichment star claim: the repo slug in datum_key is |
| 682 | # the refetch subject. The datum came from post-rerank enrichment, |
| 683 | # not the github search source, so it bypasses the grounding-item |
| 684 | # lookup and the per-source outcome gate. |
| 685 | refetcher = dispatch.get("github") |
| 686 | if refetcher is None: |
| 687 | verdicts.append( |
| 688 | _unsupported(claim, checked, "No point-refetch verifier is registered") |
| 689 | ) |
| 690 | continue |
| 691 | if not allow_network: |
| 692 | verdicts.append( |
| 693 | _unsupported(claim, checked, "Network verification is disabled for this run") |
| 694 | ) |
| 695 | continue |
| 696 | cache_key = ("github", claim.datum_key.strip().casefold()) |
| 697 | if cache_key in point_errors: |
| 698 | verdicts.append(_unsupported(claim, checked, point_errors[cache_key])) |
| 699 | continue |
| 700 | try: |
| 701 | cached = point_cache.get(cache_key) |
| 702 | if cached: |
| 703 | # Any snapshot for this repo is the star count, whether an |
| 704 | # item-level claim ("stars") or a repo-keyed one fetched it. |
| 705 | refreshed = cached[1] |
| 706 | else: |
| 707 | refreshed = _coerce_refetched( |
| 708 | refetcher(None, claim.datum_key), claim.source_url |
| 709 | ) |
| 710 | point_cache[cache_key] = (claim.datum_key, refreshed) |
| 711 | verdicts.append(_point_verdict(claim, checked, refreshed)) |
| 712 | except Exception as exc: # verifier failures degrade to a typed verdict |
| 713 | detail = f"Re-check failed: {exc}" |
| 714 | point_errors[cache_key] = detail |
| 715 | verdicts.append(_unsupported(claim, checked, detail)) |
| 716 | continue |
| 717 | |
| 718 | item = grounded_items.get(claim.candidate_id) |
| 719 | if item is None or item.source != claim.source: |
| 720 | item = fallback_items.get( |
| 721 | _item_identity(claim.source, claim.source_url, claim.source_item_id) |
| 722 | ) |
| 723 | outcome = report.source_status.get(claim.source) |
| 724 | if item is None: |
| 725 | verdicts.append(_unsupported(claim, checked, "Grounding source item is unavailable")) |
| 726 | continue |
| 727 | if outcome and outcome.state not in _USABLE_SOURCE_STATES: |
| 728 | verdicts.append( |
| 729 | _unsupported( |
| 730 | claim, |
| 731 | checked, |
| 732 | f"Source status is {outcome.state}; the datum could not be re-checked", |
| 733 | ) |
| 734 | ) |
| 735 | continue |
| 736 | refetcher = dispatch.get(claim.source) |
| 737 | if claim.source not in _REFETCHABLE_SOURCES or refetcher is None: |
| 738 | verdicts.append(_unsupported(claim, checked, "No point-refetch verifier is registered")) |
| 739 | continue |
| 740 | if not allow_network: |
| 741 | verdicts.append(_unsupported(claim, checked, "Network verification is disabled for this run")) |
| 742 | continue |
| 743 | cache_key = _point_refetch_key(item, claim) |
| 744 | if cache_key in point_errors: |
| 745 | verdicts.append(_unsupported(claim, checked, point_errors[cache_key])) |
| 746 | continue |
| 747 | try: |
| 748 | cached = point_cache.get(cache_key) |
| 749 | if cached is not None: |
| 750 | refreshed = _lookup_cached_datum(cached, claim) |
| 751 | if refreshed is None: |
| 752 | verdicts.append( |
| 753 | _unsupported( |
| 754 | claim, |
| 755 | checked, |
| 756 | "Re-fetched snapshot did not include this datum", |
| 757 | ) |
| 758 | ) |
| 759 | continue |
| 760 | else: |
| 761 | refreshed = _coerce_refetched(refetcher(item, claim.datum_key), claim.source_url) |
| 762 | if refreshed.value is None: |
| 763 | point_cache[cache_key] = (None, refreshed) |
| 764 | verdicts.append( |
| 765 | _unsupported( |
| 766 | claim, |
| 767 | checked, |
| 768 | "Re-fetched snapshot did not include this datum", |
| 769 | ) |
| 770 | ) |
| 771 | continue |
| 772 | point_cache[cache_key] = (claim.datum_key, refreshed) |
| 773 | verdicts.append(_point_verdict(claim, checked, refreshed)) |
| 774 | except Exception as exc: # verifier failures degrade to a typed verdict |
| 775 | detail = f"Re-check failed: {exc}" |
| 776 | # A miss on one datum says nothing of the snapshot's other data. |
| 777 | if not getattr(exc, "datum_only", False): |
| 778 | point_errors[cache_key] = detail |
| 779 | elif cache_key not in point_cache and getattr(exc, "snapshot", None): |
| 780 | # Keep the fetched snapshot so sibling claims reuse it. |
| 781 | snapshot = exc.snapshot |
| 782 | raw_legacy_blocked = snapshot.get("legacy_blocked_repeats") |
| 783 | point_cache[cache_key] = ( |
| 784 | None, |
| 785 | RefetchedDatum( |
| 786 | value=None, |
| 787 | url=str(snapshot.get("url") or claim.source_url), |
| 788 | timestamp=snapshot.get("timestamp"), |
| 789 | values=dict(snapshot.get("values") or {}), |
| 790 | legacy_values=( |
| 791 | dict(snapshot.get("legacy_values") or {}) |
| 792 | if isinstance(snapshot.get("legacy_values"), dict) |
| 793 | else None |
| 794 | ), |
| 795 | market_values=( |
| 796 | dict(snapshot.get("market_values") or {}) |
| 797 | if isinstance(snapshot.get("market_values"), dict) |
| 798 | else None |
| 799 | ), |
| 800 | blocked_repeats=_coerce_blocked_repeats(snapshot.get("blocked_repeats")), |
| 801 | legacy_blocked_repeats=( |
| 802 | _coerce_blocked_repeats(raw_legacy_blocked) |
| 803 | if raw_legacy_blocked is not None |
| 804 | else None |
| 805 | ), |
| 806 | ), |
| 807 | ) |
| 808 | verdicts.append(_unsupported(claim, checked, detail)) |
| 809 | |
| 810 | report.freshness_verdicts = verdicts |
| 811 | return verdicts |
| 812 |