| 1 | """Regression tests for PR 31: freshness verification & Polymarket matching/outcome parsing. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-094: Grounding item lookup keyed by candidate_id (with URL fallback) to avoid positional item_id collisions. |
| 5 | - HIGH-095: point_cache lookup alignment with polymarket.refetch_datum (casefold, occurrence-0, None -> unsupported) and extract_claims outcome_counts filtering. |
| 6 | - HIGH-096: _newer_status_contradiction undated claims, parsed UTC/date-only timestamps, copula priority (became > was, len == 1), newest-timestamp aggregation, and URL-based item identity. |
| 7 | - HIGH-194: Original-case all-caps acronym matching and _NOISE_WORDS exclusion in Polymarket EntityMatcher. |
| 8 | - HIGH-195: Multi-market Yes/No synthesis preserving resolved-No (0.0) and <= 0.005 outcomes under include_all_outcomes=True and >= RACE_PRICE_FLOOR. |
| 9 | - HIGH-196: _parse_outcome_prices non-list JSON safety, bool/non-finite/overflow/range rejection, and has_first guard against token-0 quote misattribution. |
| 10 | """ |
| 11 | |
| 12 | from __future__ import annotations |
| 13 | |
| 14 | import json |
| 15 | from types import SimpleNamespace |
| 16 | |
| 17 | import pytest |
| 18 | |
| 19 | from lib import freshness, polymarket, schema |
| 20 | from tests.test_freshness import _item, _report |
| 21 | |
| 22 | |
| 23 | # --------------------------------------------------------------------------- |
| 24 | # HIGH-094: Grounding item lookup by candidate_id (no positional ID collision) |
| 25 | # --------------------------------------------------------------------------- |
| 26 | |
| 27 | |
| 28 | def test_high094_colliding_github_item_ids_verify_against_own_repo(): |
| 29 | repo_a = _item( |
| 30 | "github", |
| 31 | item_id="GH1", |
| 32 | title="orgA/repo1 (500 stars)", |
| 33 | url="https://github.com/orgA/repo1", |
| 34 | container="orgA/repo1", |
| 35 | engagement={"stars": 500}, |
| 36 | ) |
| 37 | repo_b = _item( |
| 38 | "github", |
| 39 | item_id="GH1", |
| 40 | title="orgB/repo2 (10,000 stars)", |
| 41 | url="https://github.com/orgB/repo2", |
| 42 | container="orgB/repo2", |
| 43 | engagement={"stars": 10000}, |
| 44 | ) |
| 45 | report = _report(repo_a, repo_b) |
| 46 | seen_repos: list[str] = [] |
| 47 | |
| 48 | def fake_github_refetch(item, _key): |
| 49 | seen_repos.append(item.container) |
| 50 | counts = {"orgA/repo1": 500, "orgB/repo2": 10000} |
| 51 | return {"value": counts[item.container], "url": item.url} |
| 52 | |
| 53 | verdicts = freshness.verify_report( |
| 54 | report, |
| 55 | checked_at="2026-11-24T12:00:00Z", |
| 56 | refetchers={"github": fake_github_refetch}, |
| 57 | ) |
| 58 | |
| 59 | assert seen_repos == ["orgA/repo1", "orgB/repo2"] |
| 60 | assert [v.verdict for v in verdicts] == ["current", "current"] |
| 61 | assert [v.source_url for v in verdicts] == [repo_a.url, repo_b.url] |
| 62 | assert [v.evidence_url for v in verdicts] == [repo_a.url, repo_b.url] |
| 63 | |
| 64 | |
| 65 | def test_high094_colliding_stocktwits_and_polymarket_positional_ids(): |
| 66 | st_a = _item( |
| 67 | "stocktwits", |
| 68 | item_id="ST1", |
| 69 | title="$AAPL stream", |
| 70 | url="https://stocktwits.com/symbol/AAPL/1", |
| 71 | container="AAPL", |
| 72 | metadata={"symbol": "AAPL", "sentiment_aggregate": {"pct_bullish": 60}}, |
| 73 | ) |
| 74 | st_b = _item( |
| 75 | "stocktwits", |
| 76 | item_id="ST1", |
| 77 | title="$MSFT stream", |
| 78 | url="https://stocktwits.com/symbol/MSFT/1", |
| 79 | container="MSFT", |
| 80 | metadata={"symbol": "MSFT", "sentiment_aggregate": {"pct_bullish": 80}}, |
| 81 | ) |
| 82 | pm_a = _item( |
| 83 | "polymarket", |
| 84 | item_id="PM1", |
| 85 | title="Event A?", |
| 86 | url="https://polymarket.com/event/event-a", |
| 87 | metadata={"event_id": "101", "outcome_prices": [["Yes", 0.30]]}, |
| 88 | ) |
| 89 | pm_b = _item( |
| 90 | "polymarket", |
| 91 | item_id="PM1", |
| 92 | title="Event B?", |
| 93 | url="https://polymarket.com/event/event-b", |
| 94 | metadata={"event_id": "202", "outcome_prices": [["Yes", 0.70]]}, |
| 95 | ) |
| 96 | report = _report(st_a, st_b, pm_a, pm_b) |
| 97 | |
| 98 | verdicts = freshness.verify_report( |
| 99 | report, |
| 100 | checked_at="2026-11-24T12:00:00Z", |
| 101 | refetchers={ |
| 102 | "stocktwits": lambda item, _key: { |
| 103 | "value": {"AAPL": 60, "MSFT": 80}[item.metadata["symbol"]], |
| 104 | "url": item.url, |
| 105 | }, |
| 106 | "polymarket": lambda item, _key: { |
| 107 | "value": {"101": 0.30, "202": 0.70}[item.metadata["event_id"]], |
| 108 | "url": item.url, |
| 109 | }, |
| 110 | }, |
| 111 | ) |
| 112 | |
| 113 | assert [v.verdict for v in verdicts] == ["current", "current", "current", "current"] |
| 114 | assert [v.evidence_url for v in verdicts] == [st_a.url, st_b.url, pm_a.url, pm_b.url] |
| 115 | |
| 116 | |
| 117 | def test_high094_fallback_lookup_uses_source_url_not_colliding_item_id(monkeypatch): |
| 118 | repo_a = _item( |
| 119 | "github", |
| 120 | item_id="GH1", |
| 121 | title="orgA/repo1 (500 stars)", |
| 122 | url="https://github.com/orgA/repo1", |
| 123 | container="orgA/repo1", |
| 124 | engagement={"stars": 500}, |
| 125 | ) |
| 126 | repo_b = _item( |
| 127 | "github", |
| 128 | item_id="GH1", |
| 129 | title="orgB/repo2 (10,000 stars)", |
| 130 | url="https://github.com/orgB/repo2", |
| 131 | container="orgB/repo2", |
| 132 | engagement={"stars": 10000}, |
| 133 | ) |
| 134 | report = _report(repo_a, repo_b) |
| 135 | synthetic_claim = freshness.Claim( |
| 136 | claim_id="claim-synthetic", |
| 137 | candidate_id="candidate-missing", |
| 138 | text="orgA/repo1 has 500 GitHub stars", |
| 139 | source="github", |
| 140 | source_item_id="GH1", |
| 141 | source_url=repo_a.url, |
| 142 | source_timestamp=repo_a.published_at, |
| 143 | datum_kind="github_stars", |
| 144 | datum_key="stars", |
| 145 | original_value=500, |
| 146 | ) |
| 147 | monkeypatch.setattr(freshness, "extract_claims", lambda _report: [synthetic_claim]) |
| 148 | |
| 149 | verdicts = freshness.verify_report( |
| 150 | report, |
| 151 | checked_at="2026-11-24T12:00:00Z", |
| 152 | refetchers={ |
| 153 | "github": lambda item, _key: { |
| 154 | "value": {"orgA/repo1": 500, "orgB/repo2": 10000}[item.container], |
| 155 | "url": item.url, |
| 156 | } |
| 157 | }, |
| 158 | ) |
| 159 | |
| 160 | assert len(verdicts) == 1 |
| 161 | assert verdicts[0].verdict == "current" |
| 162 | assert verdicts[0].evidence_url == repo_a.url |
| 163 | |
| 164 | |
| 165 | # --------------------------------------------------------------------------- |
| 166 | # HIGH-095: point_cache lookup parity & extract_claims outcome_counts filter |
| 167 | # --------------------------------------------------------------------------- |
| 168 | |
| 169 | |
| 170 | def test_high095_cached_snapshot_resolves_casefolded_and_whitespace_keys(): |
| 171 | market = _item( |
| 172 | "polymarket", |
| 173 | title="Top AI lab?", |
| 174 | url="https://polymarket.com/event/top-ai-lab", |
| 175 | metadata={ |
| 176 | "event_id": "555", |
| 177 | "outcome_prices": [["Yes", 0.42], ["openai", 0.55]], |
| 178 | "end_date": "2026-12-31", |
| 179 | }, |
| 180 | ) |
| 181 | report = _report(market) |
| 182 | calls: list[str] = [] |
| 183 | |
| 184 | def fake_refetch(_item, key): |
| 185 | calls.append(key) |
| 186 | return { |
| 187 | "value": 0.42, |
| 188 | "values": {"Yes": 0.42, " OpenAI ": 0.55, "end_date": "2026-12-31"}, |
| 189 | "url": market.url, |
| 190 | "timestamp": "2026-11-24T12:00:00Z", |
| 191 | } |
| 192 | |
| 193 | verdicts = freshness.verify_report( |
| 194 | report, |
| 195 | checked_at="2026-11-24T12:05:00Z", |
| 196 | refetchers={"polymarket": fake_refetch}, |
| 197 | ) |
| 198 | |
| 199 | assert calls == ["Yes"] |
| 200 | assert [v.verdict for v in verdicts] == ["current", "current", "current"] |
| 201 | |
| 202 | |
| 203 | def test_high095_ambiguous_split_returns_unsupported_consistently_on_direct_and_cached( |
| 204 | monkeypatch, |
| 205 | ): |
| 206 | """When a previously unique unsuffixed outcome ('Yes') now appears multiple times |
| 207 | ('Yes\\x1f0' and 'Yes\\x1f1'), BOTH direct refetch_datum and cached verify_report |
| 208 | must return unsupported rather than arbitrarily matching occurrence 0.""" |
| 209 | market = _item( |
| 210 | "polymarket", |
| 211 | title="Multi-outcome shift", |
| 212 | url="https://polymarket.com/event/multi-shift", |
| 213 | metadata={ |
| 214 | "event_id": "556", |
| 215 | "outcome_prices": [["Alpha", 0.30], ["yes", 0.42]], |
| 216 | "end_date": "2026-12-31", |
| 217 | }, |
| 218 | ) |
| 219 | event = { |
| 220 | "id": "556", |
| 221 | "slug": "multi-shift", |
| 222 | "title": "Multi-outcome shift", |
| 223 | "active": True, |
| 224 | "closed": False, |
| 225 | "updatedAt": "2026-11-24T12:00:00Z", |
| 226 | "markets": [ |
| 227 | { |
| 228 | "active": True, |
| 229 | "closed": False, |
| 230 | "question": "Multi-outcome shift", |
| 231 | "liquidity": "5000", |
| 232 | "outcomes": '["Alpha", "Yes", "Yes"]', |
| 233 | "outcomePrices": '["0.30", "0.42", "0.28"]', |
| 234 | "endDate": "2026-12-31T00:00:00Z", |
| 235 | } |
| 236 | ], |
| 237 | } |
| 238 | calls: list[int] = [] |
| 239 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: calls.append(1) or event) |
| 240 | item = SimpleNamespace(metadata={"event_id": "556"}, url="", item_id="pm-556") |
| 241 | |
| 242 | # Direct fetch: ambiguous unsuffixed "yes" raises DatumNotFound, while explicit "yes\x1f0" succeeds. |
| 243 | with pytest.raises(polymarket.DatumNotFound): |
| 244 | polymarket.refetch_datum(item, "yes") |
| 245 | assert polymarket.refetch_datum(item, "yes\x1f0")["value"] == 0.42 |
| 246 | assert polymarket.refetch_datum(item, "yes\x1f1")["value"] == 0.28 |
| 247 | |
| 248 | # Cached lookup matches direct fetch identically using only 1 HTTP call. |
| 249 | calls.clear() |
| 250 | verdicts = freshness.verify_report( |
| 251 | _report(market), |
| 252 | checked_at="2026-11-24T12:05:00Z", |
| 253 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 254 | ) |
| 255 | assert len(calls) == 1 |
| 256 | assert [v.verdict for v in verdicts] == ["current", "unsupported", "current"] |
| 257 | |
| 258 | # When a snapshot carries a sole \x1f0 entry (no sibling \x1f1), unsuffixed lookup resolves it. |
| 259 | assert polymarket.resolve_snapshot_value({"Yes\x1f0": 0.42}, "yes") == 0.42 |
| 260 | assert polymarket.resolve_snapshot_value({"Yes\x1f0": 0.42, "Yes\x1f1": 0.28}, "yes") is None |
| 261 | |
| 262 | |
| 263 | def test_high095_end_date_does_not_match_occurrence_zero_outcome(): |
| 264 | market = _item( |
| 265 | "polymarket", |
| 266 | title="Weird labels", |
| 267 | url="https://polymarket.com/event/weird", |
| 268 | metadata={ |
| 269 | "event_id": "557", |
| 270 | "outcome_prices": [["Alpha", 0.50]], |
| 271 | "end_date": "2026-12-31", |
| 272 | }, |
| 273 | ) |
| 274 | verdicts = freshness.verify_report( |
| 275 | _report(market), |
| 276 | checked_at="2026-11-24T12:05:00Z", |
| 277 | refetchers={ |
| 278 | "polymarket": lambda _item, _key: { |
| 279 | "value": 0.50, |
| 280 | "values": {"Alpha": 0.50, "end_date\x1f0": 0.25}, |
| 281 | "url": market.url, |
| 282 | } |
| 283 | }, |
| 284 | ) |
| 285 | |
| 286 | assert [v.verdict for v in verdicts] == ["current", "unsupported"] |
| 287 | |
| 288 | |
| 289 | def test_high095_none_values_in_snapshot_or_miss_are_unsupported_not_stale(): |
| 290 | market = _item( |
| 291 | "polymarket", |
| 292 | title="Null end date", |
| 293 | url="https://polymarket.com/event/null-end", |
| 294 | metadata={ |
| 295 | "event_id": "558", |
| 296 | "outcome_prices": [["Yes", 0.42]], |
| 297 | "end_date": "2026-12-31", |
| 298 | }, |
| 299 | ) |
| 300 | verdicts = freshness.verify_report( |
| 301 | _report(market), |
| 302 | checked_at="2026-11-24T12:05:00Z", |
| 303 | refetchers={ |
| 304 | "polymarket": lambda _item, _key: { |
| 305 | "value": 0.42, |
| 306 | "values": {"Yes": 0.42, "end_date": None}, |
| 307 | "url": market.url, |
| 308 | } |
| 309 | }, |
| 310 | ) |
| 311 | |
| 312 | assert [v.verdict for v in verdicts] == ["current", "unsupported"] |
| 313 | assert "-> None" not in (verdicts[1].detail or "") |
| 314 | |
| 315 | # Cache miss returning value=None must also be unsupported while still caching values for siblings. |
| 316 | market2 = _item( |
| 317 | "polymarket", |
| 318 | title="Null first value", |
| 319 | url="https://polymarket.com/event/null-first", |
| 320 | metadata={ |
| 321 | "event_id": "559", |
| 322 | "outcome_prices": [["First", 0.40], ["Second", 0.60]], |
| 323 | }, |
| 324 | ) |
| 325 | calls = [] |
| 326 | |
| 327 | def refetch_null_first(_item, key): |
| 328 | calls.append(key) |
| 329 | return {"value": None, "values": {"First": None, "Second": 0.60}, "url": market2.url} |
| 330 | |
| 331 | verdicts2 = freshness.verify_report( |
| 332 | _report(market2), |
| 333 | checked_at="2026-11-24T12:05:00Z", |
| 334 | refetchers={"polymarket": refetch_null_first}, |
| 335 | ) |
| 336 | assert calls == ["First"] |
| 337 | assert [v.verdict for v in verdicts2] == ["unsupported", "current"] |
| 338 | |
| 339 | |
| 340 | def test_high095_extract_claims_filters_invalid_pairs_before_counting_duplicates(): |
| 341 | market = _item( |
| 342 | "polymarket", |
| 343 | title="Mixed valid and invalid pairs", |
| 344 | url="https://polymarket.com/event/mixed-pairs", |
| 345 | metadata={ |
| 346 | "event_id": "560", |
| 347 | "outcome_prices": [ |
| 348 | ["Yes", None], |
| 349 | ["Yes", True], |
| 350 | ["Yes", False], |
| 351 | ["Yes", "0.5"], |
| 352 | ["Yes", float("nan")], |
| 353 | ["Yes", float("inf")], |
| 354 | ["Yes", -float("inf")], |
| 355 | ["Yes", 10**400], |
| 356 | [" ", 0.1], |
| 357 | [" Yes ", 0.55], |
| 358 | ], |
| 359 | }, |
| 360 | ) |
| 361 | claims = freshness.extract_claims(_report(market)) |
| 362 | |
| 363 | assert len(claims) == 1 |
| 364 | assert claims[0].datum_key == "Yes" |
| 365 | assert claims[0].original_value == 0.55 |
| 366 | |
| 367 | |
| 368 | def test_high095_polymarket_refetch_datum_strips_whitespace_and_rejects_bad_occurrence(monkeypatch): |
| 369 | event = { |
| 370 | "id": "561", |
| 371 | "slug": "ws-outcome", |
| 372 | "title": "Whitespace outcome", |
| 373 | "active": True, |
| 374 | "closed": False, |
| 375 | "updatedAt": "2026-11-24T12:00:00Z", |
| 376 | "markets": [ |
| 377 | { |
| 378 | "active": True, |
| 379 | "closed": False, |
| 380 | "question": "Whitespace outcome", |
| 381 | "liquidity": "1000", |
| 382 | "outcomes": '[" OpenAI ", "Anthropic"]', |
| 383 | "outcomePrices": '["0.60", "0.40"]', |
| 384 | } |
| 385 | ], |
| 386 | } |
| 387 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: event) |
| 388 | item = SimpleNamespace(metadata={"event_id": "561"}, url="", item_id="pm-561") |
| 389 | |
| 390 | res = polymarket.refetch_datum(item, "openai") |
| 391 | assert res["value"] == 0.60 |
| 392 | assert "OpenAI" in res["values"] |
| 393 | |
| 394 | for bad_key in ("OpenAI\x1f-1", "OpenAI\x1fnotanint"): |
| 395 | with pytest.raises(polymarket.DatumNotFound): |
| 396 | polymarket.refetch_datum(item, bad_key) |
| 397 | |
| 398 | |
| 399 | # --------------------------------------------------------------------------- |
| 400 | # HIGH-096: _newer_status_contradiction (all 5 defects) |
| 401 | # --------------------------------------------------------------------------- |
| 402 | |
| 403 | |
| 404 | @pytest.mark.parametrize("bad_ts", [None, "", "not-a-timestamp"]) |
| 405 | def test_high096_undated_claim_is_never_contradicted_by_dated_items(bad_ts): |
| 406 | original = _item( |
| 407 | "grounding", |
| 408 | item_id="W1", |
| 409 | url="https://example.com/today", |
| 410 | title="Widget API is open", |
| 411 | published_at=bad_ts, |
| 412 | ) |
| 413 | old_item = _item( |
| 414 | "reddit", |
| 415 | item_id="R1", |
| 416 | url="https://reddit.com/r/dev/1", |
| 417 | title="Widget API is closed", |
| 418 | published_at="2026-10-25T12:00:00Z", |
| 419 | ) |
| 420 | report = _report(original) |
| 421 | report.items_by_source["reddit"] = [old_item] |
| 422 | |
| 423 | verdict = freshness.verify_report(report)[0] |
| 424 | assert verdict.verdict == "unsupported" |
| 425 | assert verdict.evidence_url == "" |
| 426 | |
| 427 | |
| 428 | @pytest.mark.parametrize( |
| 429 | ("claim_ts", "item_ts", "expected"), |
| 430 | [ |
| 431 | # Timezone offset: 12:00-05:00 == 17:00Z > 15:00Z (despite lexicographic '<') |
| 432 | ("2026-11-20T15:00:00Z", "2026-11-20T12:00:00-05:00", "contradicted"), |
| 433 | # Reverse timezone offset: 15:00Z < 17:00Z (despite lexicographic '>') |
| 434 | ("2026-11-20T12:00:00-05:00", "2026-11-20T15:00:00Z", "unsupported"), |
| 435 | # Date-only claim vs same-day datetime: NOT strictly newer |
| 436 | ("2026-11-20", "2026-11-20T00:00:00Z", "unsupported"), |
| 437 | ("2026-11-20", "2026-11-20T23:59:59Z", "unsupported"), |
| 438 | # Date-only claim vs next-day datetime: strictly newer |
| 439 | ("2026-11-20", "2026-11-21T00:00:00Z", "contradicted"), |
| 440 | # Date-only claim vs tz-shifted next UTC day (22:00-05:00 == next day 03:00Z) |
| 441 | ("2026-11-20", "2026-11-20T22:00:00-05:00", "contradicted"), |
| 442 | # Datetime claim vs same-day date-only item: NOT strictly newer |
| 443 | ("2026-11-20T08:00:00Z", "2026-11-20", "unsupported"), |
| 444 | # Datetime claim vs next-day date-only item: strictly newer |
| 445 | ("2026-11-20T23:00:00Z", "2026-11-21", "contradicted"), |
| 446 | # Equal UTC instants in different offset formats: NOT strictly newer |
| 447 | ("2026-11-20T15:00:00Z", "2026-11-20T10:00:00-05:00", "unsupported"), |
| 448 | ], |
| 449 | ) |
| 450 | def test_high096_timestamp_parsing_tz_offsets_and_date_only_precision(claim_ts, item_ts, expected): |
| 451 | original = _item( |
| 452 | "reddit", |
| 453 | item_id="R1", |
| 454 | url="https://reddit.com/r/dev/orig", |
| 455 | title="Widget API is open", |
| 456 | published_at=claim_ts, |
| 457 | ) |
| 458 | newer = _item( |
| 459 | "grounding", |
| 460 | item_id="W1", |
| 461 | url="https://status.example.com/update", |
| 462 | title="Widget API is closed", |
| 463 | published_at=item_ts, |
| 464 | ) |
| 465 | report = _report(original) |
| 466 | report.items_by_source["grounding"] = [newer] |
| 467 | |
| 468 | verdict = freshness.verify_report(report)[0] |
| 469 | assert verdict.verdict == expected |
| 470 | |
| 471 | |
| 472 | def test_high096_became_outranks_was_and_conflicting_was_remains_unsupported(): |
| 473 | original = _item( |
| 474 | "reddit", |
| 475 | item_id="R1", |
| 476 | url="https://reddit.com/r/dev/orig", |
| 477 | title="Service X is open", |
| 478 | published_at="2026-11-01T10:00:00Z", |
| 479 | ) |
| 480 | |
| 481 | # "was closed ... became open" agrees with "is open" -> NOT contradicted. |
| 482 | recovered = _item( |
| 483 | "grounding", |
| 484 | item_id="W1", |
| 485 | url="https://status.example.com/recovered", |
| 486 | title="Service X was closed yesterday and Service X became open today", |
| 487 | published_at="2026-11-10T10:00:00Z", |
| 488 | ) |
| 489 | report1 = _report(original) |
| 490 | report1.items_by_source["grounding"] = [recovered] |
| 491 | assert freshness.verify_report(report1)[0].verdict == "unsupported" |
| 492 | |
| 493 | # "was open ... became closed" contradicts "is open". |
| 494 | outage = _item( |
| 495 | "grounding", |
| 496 | item_id="W2", |
| 497 | url="https://status.example.com/outage", |
| 498 | title="Service X was open yesterday and Service X became closed today", |
| 499 | published_at="2026-11-10T10:00:00Z", |
| 500 | ) |
| 501 | report2 = _report(original) |
| 502 | report2.items_by_source["grounding"] = [outage] |
| 503 | v2 = freshness.verify_report(report2)[0] |
| 504 | assert v2.verdict == "contradicted" |
| 505 | assert v2.evidence_url == outage.url |
| 506 | |
| 507 | # Conflicting historical "was" assertions (len == 2 at priority 0) must NOT contradict. |
| 508 | ambiguous = _item( |
| 509 | "grounding", |
| 510 | item_id="W3", |
| 511 | url="https://status.example.com/ambiguous", |
| 512 | title="Service X was closed earlier and Service X was open later", |
| 513 | published_at="2026-11-10T10:00:00Z", |
| 514 | ) |
| 515 | report3 = _report(original) |
| 516 | report3.items_by_source["grounding"] = [ambiguous] |
| 517 | assert freshness.verify_report(report3)[0].verdict == "unsupported" |
| 518 | |
| 519 | |
| 520 | @pytest.mark.parametrize("reverse_order", [False, True]) |
| 521 | def test_high096_same_day_ties_aggregate_all_matching_items_order_independently(reverse_order): |
| 522 | original = _item( |
| 523 | "reddit", |
| 524 | item_id="R1", |
| 525 | url="https://reddit.com/r/dev/orig", |
| 526 | title="Widget API is open", |
| 527 | published_at="2026-11-01", |
| 528 | ) |
| 529 | historical_same_day = _item( |
| 530 | "grounding", |
| 531 | item_id="W1", |
| 532 | url="https://example.com/recap", |
| 533 | title="Widget API was open last week", |
| 534 | published_at="2026-11-10", |
| 535 | ) |
| 536 | current_same_day = _item( |
| 537 | "grounding", |
| 538 | item_id="W2", |
| 539 | url="https://example.com/outage", |
| 540 | title="Widget API is closed today", |
| 541 | published_at="2026-11-10", |
| 542 | ) |
| 543 | items = [historical_same_day, current_same_day] |
| 544 | if reverse_order: |
| 545 | items.reverse() |
| 546 | report = _report(original) |
| 547 | report.items_by_source["grounding"] = items |
| 548 | |
| 549 | verdict = freshness.verify_report(report)[0] |
| 550 | assert verdict.verdict == "contradicted" |
| 551 | assert verdict.evidence_url == current_same_day.url |
| 552 | |
| 553 | # Same-day conflicting equal-priority items remain unsupported regardless of order. |
| 554 | open_same_day = _item( |
| 555 | "grounding", |
| 556 | item_id="W3", |
| 557 | url="https://example.com/still-open", |
| 558 | title="Widget API is open today", |
| 559 | published_at="2026-11-10", |
| 560 | ) |
| 561 | conflict_items = [open_same_day, current_same_day] |
| 562 | if reverse_order: |
| 563 | conflict_items.reverse() |
| 564 | conflict_report = _report(original) |
| 565 | conflict_report.items_by_source["grounding"] = conflict_items |
| 566 | assert freshness.verify_report(conflict_report)[0].verdict == "unsupported" |
| 567 | |
| 568 | |
| 569 | def test_high096_colliding_positional_item_id_does_not_skip_newer_contradiction(): |
| 570 | original = _item( |
| 571 | "x", |
| 572 | item_id="X1", |
| 573 | url="https://x.com/usera/status/100", |
| 574 | title="Widget API is open", |
| 575 | published_at="2026-11-01T10:00:00Z", |
| 576 | ) |
| 577 | newer_same_id = _item( |
| 578 | "x", |
| 579 | item_id="X1", |
| 580 | url="https://x.com/userb/status/200", |
| 581 | title="Widget API is closed", |
| 582 | published_at="2026-11-05T10:00:00Z", |
| 583 | ) |
| 584 | report = _report(original) |
| 585 | report.items_by_source["x"] = [original, newer_same_id] |
| 586 | |
| 587 | verdict = freshness.verify_report(report)[0] |
| 588 | assert verdict.verdict == "contradicted" |
| 589 | assert verdict.evidence_url == newer_same_id.url |
| 590 | |
| 591 | |
| 592 | # --------------------------------------------------------------------------- |
| 593 | # HIGH-194: All-caps acronym requirement & _NOISE_WORDS exclusion |
| 594 | # --------------------------------------------------------------------------- |
| 595 | |
| 596 | |
| 597 | @pytest.mark.parametrize( |
| 598 | ("topic", "market_text"), |
| 599 | [ |
| 600 | ("World Health Organization", "Who will win the 2026 Super Bowl?"), |
| 601 | ("Wireless Internet Network", "Will Team Alpha win the championship?"), |
| 602 | ("Artificial Intelligence Regulation", "US air strike on Iran by June?"), |
| 603 | ("Nvidia Earnings Warning", "New York City mayoral race"), |
| 604 | ("Tariff Hearing Event", "The Federal Reserve cuts rates"), |
| 605 | ("Federal Oil Reserve", "Vote for Senate spending bill"), |
| 606 | # Lowercase acronym in market text must NOT trigger acronym credit. |
| 607 | ("Artificial General Intelligence", "Will labs reach agi before 2030?"), |
| 608 | # _NOISE_WORDS initialisms must NOT match even when the title is ALL-CAPS. |
| 609 | ("World Health Organization", "WHO WILL WIN THE 2026 SUPER BOWL?"), |
| 610 | ("Wireless Internet Network", "WILL TEAM ALPHA WIN THE CHAMPIONSHIP?"), |
| 611 | ("Tariff Hearing Event", "THE FEDERAL RESERVE CUTS RATES"), |
| 612 | ("Federal Oil Reserve", "FOR IMMEDIATE RELEASE: RATE CUT"), |
| 613 | ], |
| 614 | ) |
| 615 | def test_high194_false_positive_initialisms_are_rejected(topic, market_text): |
| 616 | matcher = polymarket.EntityMatcher(topic) |
| 617 | market = {"question": market_text, "groupItemTitle": "", "outcomes": '["Yes", "No"]'} |
| 618 | assert matcher.match(market, market_text) is None |
| 619 | assert polymarket.filter_items_against_topic(topic, [{"title": market_text}]) == [] |
| 620 | |
| 621 | |
| 622 | @pytest.mark.parametrize( |
| 623 | ("topic", "positive_text", "negative_text"), |
| 624 | [ |
| 625 | ("Artificial General Intelligence", "AGI by 2030?", "Will agi arrive by 2030?"), |
| 626 | ("National Basketball Association", "NBA Finals 2026 winner?", "nba finals 2026"), |
| 627 | ("Consumer Price Index", "Will CPI rise above 3%?", "cpi estimate for June"), |
| 628 | ("Securities Exchange Commission", "Will the SEC approve the ETF?", "in 30 sec flat"), |
| 629 | ], |
| 630 | ) |
| 631 | def test_high194_legitimate_all_caps_acronyms_still_match(topic, positive_text, negative_text): |
| 632 | matcher = polymarket.EntityMatcher(topic) |
| 633 | pos_market = {"question": positive_text, "groupItemTitle": "", "outcomes": '["Yes", "No"]'} |
| 634 | neg_market = {"question": negative_text, "groupItemTitle": "", "outcomes": '["Yes", "No"]'} |
| 635 | assert matcher.match(pos_market, positive_text) is not None |
| 636 | assert matcher.match(neg_market, negative_text) is None |
| 637 | assert len(polymarket.filter_items_against_topic(topic, [{"title": positive_text}])) == 1 |
| 638 | assert polymarket.filter_items_against_topic(topic, [{"title": negative_text}]) == [] |
| 639 | |
| 640 | |
| 641 | # --------------------------------------------------------------------------- |
| 642 | # HIGH-195: Multi-market Yes/No synthesis & include_all_outcomes / RACE_PRICE_FLOOR |
| 643 | # --------------------------------------------------------------------------- |
| 644 | |
| 645 | |
| 646 | def _binary_submarket(question: str, label: str, yes: float, *, closed: bool = False, liquidity: str = "500"): |
| 647 | return { |
| 648 | "active": not closed, |
| 649 | "closed": closed, |
| 650 | "question": question, |
| 651 | "groupItemTitle": label, |
| 652 | "liquidity": "0" if closed else liquidity, |
| 653 | "volume": "5000", |
| 654 | "outcomes": '["Yes", "No"]', |
| 655 | "outcomePrices": json.dumps([str(yes), str(round(1.0 - yes, 4))]), |
| 656 | "endDate": "2026-12-31T00:00:00Z", |
| 657 | } |
| 658 | |
| 659 | |
| 660 | def test_high195_resolved_multi_market_loser_verifies_as_stale_not_unsupported(monkeypatch): |
| 661 | resolved_event = { |
| 662 | "id": "901", |
| 663 | "slug": "race-resolved", |
| 664 | "title": "Who wins the race?", |
| 665 | "active": False, |
| 666 | "closed": True, |
| 667 | "updatedAt": "2026-11-24T12:00:00Z", |
| 668 | "markets": [ |
| 669 | _binary_submarket("Will Alice win the race?", "Alice", 1.0, closed=True), |
| 670 | _binary_submarket("Will Bob win the race?", "Bob", 0.0, closed=True), |
| 671 | _binary_submarket("Will Carol win the race?", "Carol", 0.0, closed=True), |
| 672 | ], |
| 673 | } |
| 674 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: resolved_event) |
| 675 | saved = _item( |
| 676 | "polymarket", |
| 677 | title="Who wins the race?", |
| 678 | url="https://polymarket.com/event/race-resolved", |
| 679 | metadata={ |
| 680 | "event_id": "901", |
| 681 | "outcome_prices": [["Alice", 0.50], ["Bob", 0.15], ["Carol", 0.35]], |
| 682 | }, |
| 683 | ) |
| 684 | |
| 685 | verdicts = freshness.verify_report( |
| 686 | _report(saved), |
| 687 | checked_at="2026-11-24T12:05:00Z", |
| 688 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 689 | ) |
| 690 | |
| 691 | by_claim = {v.original_value: v for v in verdicts} |
| 692 | assert by_claim[0.50].verdict == "stale" |
| 693 | assert by_claim[0.50].current_value == 1.0 |
| 694 | assert by_claim[0.15].verdict == "stale" |
| 695 | assert by_claim[0.15].current_value == 0.0 |
| 696 | assert by_claim[0.15].detail == "moved: 15% -> 0%" |
| 697 | assert by_claim[0.35].verdict == "stale" |
| 698 | assert by_claim[0.35].current_value == 0.0 |
| 699 | |
| 700 | |
| 701 | def test_high195_active_sub_floor_and_exact_floor_outcomes_preserved_on_refetch(monkeypatch): |
| 702 | event = { |
| 703 | "id": "902", |
| 704 | "slug": "race-active", |
| 705 | "title": "Active race?", |
| 706 | "active": True, |
| 707 | "closed": False, |
| 708 | "updatedAt": "2026-11-24T12:00:00Z", |
| 709 | "markets": [ |
| 710 | _binary_submarket("Will Favorite win the race?", "Favorite", 0.60), |
| 711 | _binary_submarket("Will ExactFloor win the race?", "ExactFloor", polymarket.RACE_PRICE_FLOOR), |
| 712 | _binary_submarket("Will Longshot win the race?", "Longshot", 0.002), |
| 713 | ], |
| 714 | } |
| 715 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: event) |
| 716 | item = SimpleNamespace(metadata={"event_id": "902"}, url="", item_id="pm-902") |
| 717 | |
| 718 | # Normal display parse (include_all_outcomes=False, no topic) keeps >= RACE_PRICE_FLOOR and drops 0.002. |
| 719 | [normal] = polymarket.parse_polymarket_response({"events": [event]}) |
| 720 | normal_names = [name for name, _p in normal["outcome_prices"]] |
| 721 | assert "Favorite" in normal_names |
| 722 | assert "ExactFloor" in normal_names |
| 723 | assert "Longshot" not in normal_names |
| 724 | |
| 725 | # Refetch (include_all_outcomes=True) preserves both ExactFloor (0.005) and Longshot (0.002). |
| 726 | assert polymarket.refetch_datum(item, "ExactFloor")["value"] == polymarket.RACE_PRICE_FLOOR |
| 727 | assert polymarket.refetch_datum(item, "Longshot")["value"] == 0.002 |
| 728 | |
| 729 | |
| 730 | # --------------------------------------------------------------------------- |
| 731 | # HIGH-196: _parse_outcome_prices robustness & token-0 quote isolation |
| 732 | # --------------------------------------------------------------------------- |
| 733 | |
| 734 | |
| 735 | @pytest.mark.parametrize( |
| 736 | ("outcomes", "prices", "expected"), |
| 737 | [ |
| 738 | ('["Yes", "No"]', "123", []), |
| 739 | ('["Yes", "No"]', "{}", []), |
| 740 | ('["Yes", "No"]', 123, []), |
| 741 | ('["Yes", "No"]', {"Yes": 0.5}, []), |
| 742 | ('["Yes", "No"]', True, []), |
| 743 | ("123", '["0.6", "0.4"]', [("Outcome 1", 0.6), ("Outcome 2", 0.4)]), |
| 744 | ("{}", '["0.6", "0.4"]', [("Outcome 1", 0.6), ("Outcome 2", 0.4)]), |
| 745 | (123, '["0.6", "0.4"]', [("Outcome 1", 0.6), ("Outcome 2", 0.4)]), |
| 746 | ], |
| 747 | ) |
| 748 | def test_high196_non_list_json_or_raw_values_do_not_crash(outcomes, prices, expected): |
| 749 | market = {"outcomes": outcomes, "outcomePrices": prices} |
| 750 | assert polymarket._parse_outcome_prices(market) == expected |
| 751 | |
| 752 | |
| 753 | @pytest.mark.parametrize( |
| 754 | "bad_first_price", |
| 755 | [None, "bad", True, False, "NaN", "Infinity", "-Infinity", "1e500", -0.05, 1.05, 10**400], |
| 756 | ) |
| 757 | def test_high196_malformed_first_price_never_attributes_token0_quote_to_second_outcome( |
| 758 | bad_first_price, |
| 759 | ): |
| 760 | market = { |
| 761 | "outcomes": ["Yes", "No"], |
| 762 | "outcomePrices": [bad_first_price, "0.35"], |
| 763 | "bestBid": 0.01, |
| 764 | "bestAsk": 0.99, |
| 765 | "spread": 0.98, |
| 766 | "lastTradePrice": 0.65, |
| 767 | } |
| 768 | assert polymarket._parse_outcome_prices(market, book_aware=True) == [] |
| 769 | # Even with a tight book (midpoint path), token-0 was missing so book_aware returns []. |
| 770 | tight_market = { |
| 771 | "outcomes": ["Yes", "No"], |
| 772 | "outcomePrices": [bad_first_price, "0.35"], |
| 773 | "bestBid": 0.64, |
| 774 | "bestAsk": 0.66, |
| 775 | "spread": 0.02, |
| 776 | } |
| 777 | assert polymarket._parse_outcome_prices(tight_market, book_aware=True) == [] |
| 778 | |
| 779 | |
| 780 | def test_high196_rejects_bool_non_finite_overflow_and_out_of_range_while_keeping_bounds(): |
| 781 | market = { |
| 782 | "outcomes": ["Zero", "BoolT", "BoolF", "NaN", "Inf", "Neg", "Over", "Big", "One"], |
| 783 | "outcomePrices": [ |
| 784 | "0.0", |
| 785 | True, |
| 786 | False, |
| 787 | float("nan"), |
| 788 | float("inf"), |
| 789 | -0.01, |
| 790 | 1.01, |
| 791 | 10**400, |
| 792 | "1.0", |
| 793 | ], |
| 794 | } |
| 795 | assert polymarket._parse_outcome_prices(market, book_aware=False) == [ |
| 796 | ("Zero", 0.0), |
| 797 | ("One", 1.0), |
| 798 | ] |
| 799 | |
| 800 | |
| 801 | def test_high196_three_outcome_market_with_skipped_middle_does_not_overwrite_third(): |
| 802 | market = { |
| 803 | "outcomes": ["A", "B", "C"], |
| 804 | "outcomePrices": ["0.5", None, "0.2"], |
| 805 | "bestBid": 0.10, |
| 806 | "bestAsk": 0.90, |
| 807 | "spread": 0.80, |
| 808 | "lastTradePrice": 0.60, |
| 809 | } |
| 810 | assert polymarket._parse_outcome_prices(market, book_aware=True) == [ |
| 811 | ("A", 0.60), |
| 812 | ("C", 0.20), |
| 813 | ] |
| 814 | |
| 815 | |
| 816 | # --------------------------------------------------------------------------- |
| 817 | # Greptile #1612 review fixes (6 regression tests) |
| 818 | # --------------------------------------------------------------------------- |
| 819 | |
| 820 | |
| 821 | def test_greptile1_collapsed_duplicate_matches_identically_on_direct_and_cached_lookup( |
| 822 | monkeypatch, |
| 823 | ): |
| 824 | """When two saved `Yes` rows collapse to one live `Yes` row (without a book drop), |
| 825 | direct fetch and cached lookup must agree on both `Yes\\x1f0` and `Yes\\x1f1`.""" |
| 826 | event = { |
| 827 | "id": "701", |
| 828 | "slug": "collapse-yes", |
| 829 | "title": "Collapsed Yes rows", |
| 830 | "active": True, |
| 831 | "closed": False, |
| 832 | "updatedAt": "2026-11-24T12:00:00Z", |
| 833 | "markets": [ |
| 834 | { |
| 835 | "active": True, |
| 836 | "closed": False, |
| 837 | "question": "Collapsed Yes rows", |
| 838 | "liquidity": "5000", |
| 839 | "outcomes": '["Alpha", "Yes"]', |
| 840 | "outcomePrices": '["0.35", "0.65"]', |
| 841 | } |
| 842 | ], |
| 843 | } |
| 844 | calls: list[int] = [] |
| 845 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: calls.append(1) or event) |
| 846 | item = SimpleNamespace(metadata={"event_id": "701"}, url="", item_id="pm-701") |
| 847 | |
| 848 | # Direct fetch: Yes\x1f0 resolves to 0.65; Yes\x1f1 raises DatumNotFound. |
| 849 | assert polymarket.refetch_datum(item, "Yes\x1f0")["value"] == 0.65 |
| 850 | with pytest.raises(polymarket.DatumNotFound): |
| 851 | polymarket.refetch_datum(item, "Yes\x1f1") |
| 852 | |
| 853 | # Cached lookup after another claim ("Alpha") fetches the event first: |
| 854 | # must match direct fetch identically using only 1 HTTP call. |
| 855 | calls.clear() |
| 856 | saved = _item( |
| 857 | "polymarket", |
| 858 | title="Collapsed Yes rows", |
| 859 | url="https://polymarket.com/event/collapse-yes", |
| 860 | metadata={ |
| 861 | "event_id": "701", |
| 862 | "outcome_prices": [["Alpha", 0.35], ["Yes", 0.65], ["Yes", 0.20]], |
| 863 | }, |
| 864 | ) |
| 865 | verdicts = freshness.verify_report( |
| 866 | _report(saved), |
| 867 | checked_at="2026-11-24T12:05:00Z", |
| 868 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 869 | ) |
| 870 | assert len(calls) == 1 |
| 871 | assert [v.verdict for v in verdicts] == ["current", "current", "unsupported"] |
| 872 | |
| 873 | # Reverse order (Yes\x1f0 fetched directly first, Alpha + Yes\x1f1 cached): same verdicts. |
| 874 | calls.clear() |
| 875 | saved_first = _item( |
| 876 | "polymarket", |
| 877 | title="Collapsed Yes rows", |
| 878 | url="https://polymarket.com/event/collapse-yes", |
| 879 | metadata={ |
| 880 | "event_id": "701", |
| 881 | "outcome_prices": [["Yes", 0.65], ["Yes", 0.20], ["Alpha", 0.35]], |
| 882 | }, |
| 883 | ) |
| 884 | verdicts_first = freshness.verify_report( |
| 885 | _report(saved_first), |
| 886 | checked_at="2026-11-24T12:05:00Z", |
| 887 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 888 | ) |
| 889 | assert len(calls) == 1 |
| 890 | assert [v.verdict for v in verdicts_first] == ["current", "unsupported", "current"] |
| 891 | |
| 892 | |
| 893 | def test_greptile1_book_dropped_repeat_still_blocked_on_cached_lookup(monkeypatch): |
| 894 | """When a sibling repeat was dropped by the book check, cached lookup must |
| 895 | also block `Bitcoin\\x1f0` and `Bitcoin\\x1f1` just like direct fetch.""" |
| 896 | question = "Will Bitcoin reach $150k in November?" |
| 897 | event = { |
| 898 | "id": "702", |
| 899 | "slug": "bitcoin-november", |
| 900 | "title": "Bitcoin in November", |
| 901 | "active": True, |
| 902 | "closed": False, |
| 903 | "updatedAt": "2026-11-24T12:00:00Z", |
| 904 | "markets": [ |
| 905 | { |
| 906 | "active": True, |
| 907 | "closed": False, |
| 908 | "question": "Will Ethereum reach $10k in November?", |
| 909 | "groupItemTitle": "ETH", |
| 910 | "liquidity": "500", |
| 911 | "outcomes": '["Yes", "No"]', |
| 912 | "outcomePrices": '["0.25", "0.75"]', |
| 913 | "bestBid": 0.24, |
| 914 | "bestAsk": 0.26, |
| 915 | "spread": 0.02, |
| 916 | }, |
| 917 | { |
| 918 | "active": True, |
| 919 | "closed": False, |
| 920 | "question": question, |
| 921 | "groupItemTitle": "A", |
| 922 | "liquidity": "500", |
| 923 | "outcomes": '["Yes", "No"]', |
| 924 | "outcomePrices": '["0.60", "0.40"]', |
| 925 | "bestBid": 0.01, |
| 926 | "bestAsk": 0.90, |
| 927 | "spread": 0.89, |
| 928 | }, |
| 929 | { |
| 930 | "active": True, |
| 931 | "closed": False, |
| 932 | "question": question, |
| 933 | "groupItemTitle": "B", |
| 934 | "liquidity": "500", |
| 935 | "outcomes": '["Yes", "No"]', |
| 936 | "outcomePrices": '["0.30", "0.70"]', |
| 937 | "bestBid": 0.29, |
| 938 | "bestAsk": 0.31, |
| 939 | "spread": 0.02, |
| 940 | }, |
| 941 | ], |
| 942 | } |
| 943 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: event) |
| 944 | legacy = polymarket._legacy_shorten_question(question).strip() |
| 945 | saved = _item( |
| 946 | "polymarket", |
| 947 | title="Bitcoin in November", |
| 948 | url="https://polymarket.com/event/bitcoin-november", |
| 949 | metadata={ |
| 950 | "event_id": "702", |
| 951 | # "ETH" fetches and populates cache first; both legacy repeats must still fail closed. |
| 952 | "outcome_prices": [["ETH", 0.25], [legacy, 0.60], [legacy, 0.30]], |
| 953 | }, |
| 954 | ) |
| 955 | verdicts = freshness.verify_report( |
| 956 | _report(saved), |
| 957 | checked_at="2026-11-24T12:05:00Z", |
| 958 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 959 | ) |
| 960 | assert [v.verdict for v in verdicts] == ["current", "unsupported", "unsupported"] |
| 961 | |
| 962 | |
| 963 | def test_greptile2_shared_group_title_uses_subject_so_swapped_prices_never_switch_markets( |
| 964 | monkeypatch, |
| 965 | ): |
| 966 | """Two child markets sharing groupItemTitle='OpenAI' (GPT-5 at 0.60, Sora 2 at 0.002): |
| 967 | full-event collision detection labels GPT-5 unambiguously as 'GPT-5' even during |
| 968 | display parsing, so verification tracks GPT-5 accurately whether unchanged or swapped, |
| 969 | and an older saved claim with ambiguous 'OpenAI' returns unsupported instead of |
| 970 | silently attributing Sora 2's swapped price to GPT-5.""" |
| 971 | event = { |
| 972 | "id": "703", |
| 973 | "slug": "ai-launches", |
| 974 | "title": "AI launches in Q4?", |
| 975 | "active": True, |
| 976 | "closed": False, |
| 977 | "updatedAt": "2026-11-24T12:00:00Z", |
| 978 | "markets": [ |
| 979 | _binary_submarket("Will GPT-5 win the benchmark?", "OpenAI", 0.60), |
| 980 | _binary_submarket("Will Sora 2 win the benchmark?", "OpenAI", 0.002), |
| 981 | _binary_submarket("Will Claude 5 win the benchmark?", "Anthropic", 0.40), |
| 982 | ], |
| 983 | } |
| 984 | # Display parse detects the full-event groupItemTitle collision and saves "GPT-5" (not "OpenAI"). |
| 985 | [display_item] = polymarket.parse_polymarket_response({"events": [event]}) |
| 986 | assert display_item["outcome_prices"] == [("GPT-5", 0.60), ("Anthropic", 0.40)] |
| 987 | |
| 988 | saved = _item( |
| 989 | "polymarket", |
| 990 | title=display_item["title"], |
| 991 | url="https://polymarket.com/event/ai-launches", |
| 992 | metadata={ |
| 993 | "event_id": "703", |
| 994 | "outcome_prices": [list(pair) for pair in display_item["outcome_prices"]], |
| 995 | }, |
| 996 | ) |
| 997 | |
| 998 | # Unchanged prices -> both current, and sub-floor Sora 2 is also directly refetchable. |
| 999 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: event) |
| 1000 | item = SimpleNamespace(metadata={"event_id": "703"}, url="", item_id="pm-703") |
| 1001 | assert polymarket.refetch_datum(item, "GPT-5")["value"] == 0.60 |
| 1002 | assert polymarket.refetch_datum(item, "Sora 2")["value"] == 0.002 |
| 1003 | assert polymarket.refetch_datum(item, "Anthropic")["value"] == 0.40 |
| 1004 | verdicts = freshness.verify_report( |
| 1005 | _report(saved), |
| 1006 | checked_at="2026-11-24T12:05:00Z", |
| 1007 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1008 | ) |
| 1009 | assert [v.verdict for v in verdicts] == ["current", "current"] |
| 1010 | |
| 1011 | # Swapped prices (GPT-5 drops to 0.002, Sora 2 rises to 0.60): |
| 1012 | # GPT-5 claim must be stale (60% -> 0.2%), NOT current! |
| 1013 | swapped_event = { |
| 1014 | **event, |
| 1015 | "markets": [ |
| 1016 | _binary_submarket("Will GPT-5 win the benchmark?", "OpenAI", 0.002), |
| 1017 | _binary_submarket("Will Sora 2 win the benchmark?", "OpenAI", 0.60), |
| 1018 | _binary_submarket("Will Claude 5 win the benchmark?", "Anthropic", 0.40), |
| 1019 | ], |
| 1020 | } |
| 1021 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: swapped_event) |
| 1022 | swapped_verdicts = freshness.verify_report( |
| 1023 | _report(saved), |
| 1024 | checked_at="2026-11-24T12:05:00Z", |
| 1025 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1026 | ) |
| 1027 | assert [v.verdict for v in swapped_verdicts] == ["stale", "current"] |
| 1028 | assert swapped_verdicts[0].current_value == 0.002 |
| 1029 | |
| 1030 | # A pre-PR saved claim carrying ambiguous "OpenAI" on this 2-market event |
| 1031 | # must return unsupported rather than reading Sora 2's swapped 0.60 as current. |
| 1032 | legacy_saved = _item( |
| 1033 | "polymarket", |
| 1034 | title=display_item["title"], |
| 1035 | url="https://polymarket.com/event/ai-launches", |
| 1036 | metadata={"event_id": "703", "outcome_prices": [["OpenAI", 0.60]]}, |
| 1037 | ) |
| 1038 | legacy_verdicts = freshness.verify_report( |
| 1039 | _report(legacy_saved), |
| 1040 | checked_at="2026-11-24T12:05:00Z", |
| 1041 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1042 | ) |
| 1043 | assert [v.verdict for v in legacy_verdicts] == ["unsupported"] |
| 1044 | |
| 1045 | |
| 1046 | def test_greptile_current_name_occurrence_zero_beats_legacy_cut_repeats(monkeypatch): |
| 1047 | """Verify current-over-legacy namespace precedence in resolve_snapshot_value AND |
| 1048 | that cross-market ambiguous labels without outcome_market_ids fail closed while |
| 1049 | new reports carrying outcome_market_ids resolve directly by market ID.""" |
| 1050 | # Direct unit test on resolve_snapshot_value: current Apple wins over legacy Apple\x1f0, |
| 1051 | # and Apple\x1f1 does not leak into legacy_values when current namespace owns 'Apple'. |
| 1052 | assert ( |
| 1053 | polymarket.resolve_snapshot_value( |
| 1054 | {"Apple": 0.70}, |
| 1055 | "Apple\x1f0", |
| 1056 | legacy_values={"Apple\x1f0": 0.20, "Apple\x1f1": 0.10}, |
| 1057 | ) |
| 1058 | == 0.70 |
| 1059 | ) |
| 1060 | assert ( |
| 1061 | polymarket.resolve_snapshot_value( |
| 1062 | {"Apple": 0.70}, |
| 1063 | "Apple\x1f1", |
| 1064 | legacy_values={"Apple\x1f0": 0.20, "Apple\x1f1": 0.10}, |
| 1065 | ) |
| 1066 | is None |
| 1067 | ) |
| 1068 | |
| 1069 | event = { |
| 1070 | "id": "707", |
| 1071 | "slug": "apple-markets", |
| 1072 | "title": "Apple milestones?", |
| 1073 | "active": True, |
| 1074 | "closed": False, |
| 1075 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1076 | "markets": [ |
| 1077 | {**_binary_submarket("Will Tim Cook remain CEO of the company?", "Apple", 0.70), "id": "m-tim"}, |
| 1078 | {**_binary_submarket("Will Apple reach a $4T market cap?", "$4T", 0.20), "id": "m-4t"}, |
| 1079 | {**_binary_submarket("Will Apple reach a $5T market cap?", "$5T", 0.10), "id": "m-5t"}, |
| 1080 | {**_binary_submarket("Will OldCut win the legacy milestone?", "Milestone", 0.30), "id": "m-old"}, |
| 1081 | ], |
| 1082 | } |
| 1083 | calls: list[int] = [] |
| 1084 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: calls.append(1) or event) |
| 1085 | item_no_ids = SimpleNamespace(metadata={"event_id": "707"}, url="", item_id="pm-707") |
| 1086 | |
| 1087 | # Without outcome_market_ids, 'Apple' is cross-market ambiguous across m-tim (groupItemTitle) |
| 1088 | # and m-4t/m-5t (legacy cut) -> unsupported; unambiguous legacy cuts ('OldCut', 'Tim Cook') resolve. |
| 1089 | with pytest.raises(polymarket.DatumNotFound): |
| 1090 | polymarket.refetch_datum(item_no_ids, "Apple") |
| 1091 | with pytest.raises(polymarket.DatumNotFound): |
| 1092 | polymarket.refetch_datum(item_no_ids, "Apple\x1f0") |
| 1093 | assert polymarket.refetch_datum(item_no_ids, "OldCut")["value"] == 0.30 |
| 1094 | assert polymarket.refetch_datum(item_no_ids, "Tim Cook")["value"] == 0.70 |
| 1095 | |
| 1096 | # With outcome_market_ids (new report), 'Apple' resolves directly via m-tim -> 0.70 |
| 1097 | # identically on direct refetch_datum and cached verify_report, even if m-5t is book-dropped. |
| 1098 | calls.clear() |
| 1099 | saved_with_ids = _item( |
| 1100 | "polymarket", |
| 1101 | title="Apple milestones?", |
| 1102 | url="https://polymarket.com/event/apple-markets", |
| 1103 | metadata={ |
| 1104 | "event_id": "707", |
| 1105 | "outcome_prices": [["Milestone", 0.30], ["Apple", 0.70], ["$4T", 0.20]], |
| 1106 | "outcome_market_ids": ["m-old", "m-tim", "m-4t"], |
| 1107 | }, |
| 1108 | ) |
| 1109 | verdicts = freshness.verify_report( |
| 1110 | _report(saved_with_ids), |
| 1111 | checked_at="2026-11-24T12:05:00Z", |
| 1112 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1113 | ) |
| 1114 | assert len(calls) == 1 |
| 1115 | assert [v.verdict for v in verdicts] == ["current", "current", "current"] |
| 1116 | assert verdicts[1].current_value == 0.70 |
| 1117 | |
| 1118 | dropped_legacy_event = { |
| 1119 | **event, |
| 1120 | "markets": [ |
| 1121 | {**_binary_submarket("Will Tim Cook remain CEO of the company?", "Apple", 0.70), "id": "m-tim"}, |
| 1122 | {**_binary_submarket("Will Apple reach a $4T market cap?", "$4T", 0.20), "id": "m-4t"}, |
| 1123 | { |
| 1124 | **_binary_submarket("Will Apple reach a $5T market cap?", "$5T", 0.10), |
| 1125 | "id": "m-5t", |
| 1126 | "bestBid": 0.01, |
| 1127 | "bestAsk": 0.99, |
| 1128 | "spread": 0.98, |
| 1129 | }, |
| 1130 | {**_binary_submarket("Will OldCut win the legacy milestone?", "Milestone", 0.30), "id": "m-old"}, |
| 1131 | ], |
| 1132 | } |
| 1133 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: dropped_legacy_event) |
| 1134 | assert polymarket.refetch_datum(saved_with_ids, "Apple")["value"] == 0.70 |
| 1135 | |
| 1136 | |
| 1137 | def test_greptile_r3_three_market_subject_group_title_cross_collision(monkeypatch): |
| 1138 | """Greptile R3 P1: |
| 1139 | - Market 1: 'Will GPT-5 win?' (subject 'GPT-5'), groupItemTitle='OpenAI', price 0.60 |
| 1140 | - Market 2: 'Will Sora win?' (subject 'Sora'), groupItemTitle='OpenAI', price 0.20 |
| 1141 | - Market 3: 'Will OpenAI release hardware?' (subject 'OpenAI'), groupItemTitle='GPT-5', price 0.002 |
| 1142 | Full-event disambiguation prevents Market 1 and Market 3 from both taking 'GPT-5', |
| 1143 | keeping labels stable between display parsing and refetch even if Market 3 trades above Market 1.""" |
| 1144 | event = { |
| 1145 | "id": "708", |
| 1146 | "slug": "openai-products", |
| 1147 | "title": "OpenAI milestones?", |
| 1148 | "active": True, |
| 1149 | "closed": False, |
| 1150 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1151 | "markets": [ |
| 1152 | _binary_submarket("Will GPT-5 win?", "OpenAI", 0.60), |
| 1153 | _binary_submarket("Will Sora win?", "OpenAI", 0.20), |
| 1154 | _binary_submarket("Will OpenAI release hardware?", "GPT-5", 0.002), |
| 1155 | ], |
| 1156 | } |
| 1157 | [display_item] = polymarket.parse_polymarket_response({"events": [event]}) |
| 1158 | # Market 1 must NOT take 'GPT-5' (collides with Market 3's groupItemTitle='GPT-5'). |
| 1159 | assert display_item["outcome_prices"] == [("Will GPT-5 win", 0.60), ("Sora", 0.20)] |
| 1160 | |
| 1161 | saved = _item( |
| 1162 | "polymarket", |
| 1163 | title=display_item["title"], |
| 1164 | url="https://polymarket.com/event/openai-products", |
| 1165 | metadata={ |
| 1166 | "event_id": "708", |
| 1167 | "outcome_prices": [list(pair) for pair in display_item["outcome_prices"]], |
| 1168 | }, |
| 1169 | ) |
| 1170 | |
| 1171 | # Market 3 surges to 0.85 (above Market 1's 0.60): Market 1 must stay 'current' at 0.60, |
| 1172 | # NOT read Market 3's 0.85! |
| 1173 | surged_event = { |
| 1174 | **event, |
| 1175 | "markets": [ |
| 1176 | _binary_submarket("Will GPT-5 win?", "OpenAI", 0.60), |
| 1177 | _binary_submarket("Will Sora win?", "OpenAI", 0.20), |
| 1178 | _binary_submarket("Will OpenAI release hardware?", "GPT-5", 0.85), |
| 1179 | ], |
| 1180 | } |
| 1181 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: surged_event) |
| 1182 | item = SimpleNamespace(metadata={"event_id": "708"}, url="", item_id="pm-708") |
| 1183 | assert polymarket.refetch_datum(item, "Will GPT-5 win")["value"] == 0.60 |
| 1184 | assert polymarket.refetch_datum(item, "Will OpenAI release hardware")["value"] == 0.85 |
| 1185 | |
| 1186 | verdicts = freshness.verify_report( |
| 1187 | _report(saved), |
| 1188 | checked_at="2026-11-24T12:05:00Z", |
| 1189 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1190 | ) |
| 1191 | assert [v.verdict for v in verdicts] == ["current", "current"] |
| 1192 | assert verdicts[0].current_value == 0.60 |
| 1193 | |
| 1194 | |
| 1195 | def test_greptile_r3_unsuffixed_legacy_shared_label_never_switches_on_price_swap(monkeypatch): |
| 1196 | """When an old report saved unsuffixed 'OpenAI' (0.60) for 'Will OpenAI release GPT-5?' |
| 1197 | while 'Will OpenAI release Sora?' was 0.002, and prices later swap (Sora=0.60, GPT-5=0.002), |
| 1198 | unsuffixed 'OpenAI' must return unsupported instead of reading Sora's swapped 0.60 via legacy OpenAI\\x1f0.""" |
| 1199 | swapped_event = { |
| 1200 | "id": "709", |
| 1201 | "slug": "openai-releases", |
| 1202 | "title": "OpenAI releases?", |
| 1203 | "active": True, |
| 1204 | "closed": False, |
| 1205 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1206 | "markets": [ |
| 1207 | _binary_submarket("Will OpenAI release GPT-5?", "OpenAI", 0.002), |
| 1208 | _binary_submarket("Will OpenAI release Sora?", "OpenAI", 0.60), |
| 1209 | ], |
| 1210 | } |
| 1211 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: swapped_event) |
| 1212 | item = SimpleNamespace(metadata={"event_id": "709"}, url="", item_id="pm-709") |
| 1213 | |
| 1214 | # Direct fetch: unsuffixed 'OpenAI' is ambiguous across legacy OpenAI\x1f0 and OpenAI\x1f1. |
| 1215 | with pytest.raises(polymarket.DatumNotFound): |
| 1216 | polymarket.refetch_datum(item, "OpenAI") |
| 1217 | |
| 1218 | # Cached verify_report also returns unsupported (never marks GPT-5 'current' from Sora's 0.60). |
| 1219 | old_saved = _item( |
| 1220 | "polymarket", |
| 1221 | title="OpenAI releases?", |
| 1222 | url="https://polymarket.com/event/openai-releases", |
| 1223 | metadata={"event_id": "709", "outcome_prices": [["OpenAI", 0.60]]}, |
| 1224 | ) |
| 1225 | verdicts = freshness.verify_report( |
| 1226 | _report(old_saved), |
| 1227 | checked_at="2026-11-24T12:05:00Z", |
| 1228 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1229 | ) |
| 1230 | assert [v.verdict for v in verdicts] == ["unsupported"] |
| 1231 | |
| 1232 | # Newly generated report labels both unambiguously by whole question, so swapped prices mark stale! |
| 1233 | initial_event = { |
| 1234 | **swapped_event, |
| 1235 | "markets": [ |
| 1236 | _binary_submarket("Will OpenAI release GPT-5?", "OpenAI", 0.60), |
| 1237 | _binary_submarket("Will OpenAI release Sora?", "OpenAI", 0.002), |
| 1238 | ], |
| 1239 | } |
| 1240 | [display_item] = polymarket.parse_polymarket_response({"events": [initial_event]}) |
| 1241 | assert display_item["outcome_prices"] == [("Will OpenAI release GPT-5", 0.60)] |
| 1242 | new_saved = _item( |
| 1243 | "polymarket", |
| 1244 | title="OpenAI releases?", |
| 1245 | url="https://polymarket.com/event/openai-releases", |
| 1246 | metadata={"event_id": "709", "outcome_prices": [list(p) for p in display_item["outcome_prices"]]}, |
| 1247 | ) |
| 1248 | new_verdicts = freshness.verify_report( |
| 1249 | _report(new_saved), |
| 1250 | checked_at="2026-11-24T12:05:00Z", |
| 1251 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1252 | ) |
| 1253 | assert [v.verdict for v in new_verdicts] == ["stale"] |
| 1254 | assert new_verdicts[0].current_value == 0.002 |
| 1255 | |
| 1256 | |
| 1257 | def test_greptile_r4_cross_market_group_title_vs_legacy_subject_returns_unsupported(monkeypatch): |
| 1258 | """Greptile R4 P1: |
| 1259 | - Market A: 'Will Alice win?', groupItemTitle='Bob', price 0.60 |
| 1260 | - Market B: 'Will Bob win?', groupItemTitle='', price 0.002 |
| 1261 | An older report could have saved Market A's 0.60 under 'Bob' (its groupItemTitle) |
| 1262 | when Market B was below the display floor. Refetch must NOT fall back to Market B's |
| 1263 | legacy 'Bob' (0.002) and mark Market A stale; it must return unsupported on both |
| 1264 | direct fetch and cached lookup, while unambiguous legacy names ('Alice') and |
| 1265 | legitimate legacy cut names still resolve cleanly.""" |
| 1266 | event = { |
| 1267 | "id": "710", |
| 1268 | "slug": "alice-bob-race", |
| 1269 | "title": "Race winner?", |
| 1270 | "active": True, |
| 1271 | "closed": False, |
| 1272 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1273 | "markets": [ |
| 1274 | _binary_submarket("Will Alice win?", "Bob", 0.60), |
| 1275 | _binary_submarket("Will Bob win?", "", 0.002), |
| 1276 | _binary_submarket("Will Carol win?", "Carol Winner", 0.35), |
| 1277 | ], |
| 1278 | } |
| 1279 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: event) |
| 1280 | item = SimpleNamespace(metadata={"event_id": "710"}, url="", item_id="pm-710") |
| 1281 | |
| 1282 | # Direct fetch: 'Bob' is cross-market ambiguous -> DatumNotFound (NOT Market B's 0.002). |
| 1283 | with pytest.raises(polymarket.DatumNotFound): |
| 1284 | polymarket.refetch_datum(item, "Bob") |
| 1285 | # Unambiguous legacy names ('Alice' -> 0.60, 'Carol' -> 0.35) and current labels still resolve. |
| 1286 | assert polymarket.refetch_datum(item, "Alice")["value"] == 0.60 |
| 1287 | assert polymarket.refetch_datum(item, "Carol")["value"] == 0.35 |
| 1288 | assert polymarket.refetch_datum(item, "Will Alice win")["value"] == 0.60 |
| 1289 | assert polymarket.refetch_datum(item, "Will Bob win")["value"] == 0.002 |
| 1290 | |
| 1291 | # Cached verify_report (after 'Carol Winner' fetches first): 'Bob' must be unsupported, |
| 1292 | # NOT stale (60% -> 0.2%), while 'Alice' (unambiguous legacy) resolves to current 0.60. |
| 1293 | calls: list[int] = [] |
| 1294 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: calls.append(1) or event) |
| 1295 | old_saved = _item( |
| 1296 | "polymarket", |
| 1297 | title="Race winner?", |
| 1298 | url="https://polymarket.com/event/alice-bob-race", |
| 1299 | metadata={ |
| 1300 | "event_id": "710", |
| 1301 | "outcome_prices": [["Carol Winner", 0.35], ["Bob", 0.60], ["Alice", 0.60]], |
| 1302 | }, |
| 1303 | ) |
| 1304 | verdicts = freshness.verify_report( |
| 1305 | _report(old_saved), |
| 1306 | checked_at="2026-11-24T12:05:00Z", |
| 1307 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1308 | ) |
| 1309 | assert len(calls) == 1 |
| 1310 | assert [v.verdict for v in verdicts] == ["current", "unsupported", "current"] |
| 1311 | |
| 1312 | # Also verify old saved 'GPT-5' / 'OpenAI' on the 3-market cross-collision event |
| 1313 | # return unsupported instead of reading the wrong market via legacy_values. |
| 1314 | three_market_event = { |
| 1315 | "id": "711", |
| 1316 | "slug": "openai-3mkt", |
| 1317 | "title": "OpenAI milestones?", |
| 1318 | "active": True, |
| 1319 | "closed": False, |
| 1320 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1321 | "markets": [ |
| 1322 | _binary_submarket("Will GPT-5 win?", "OpenAI", 0.60), |
| 1323 | _binary_submarket("Will Sora win?", "OpenAI", 0.20), |
| 1324 | _binary_submarket("Will OpenAI release hardware?", "GPT-5", 0.002), |
| 1325 | ], |
| 1326 | } |
| 1327 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: three_market_event) |
| 1328 | item_3 = SimpleNamespace(metadata={"event_id": "711"}, url="", item_id="pm-711") |
| 1329 | with pytest.raises(polymarket.DatumNotFound): |
| 1330 | polymarket.refetch_datum(item_3, "GPT-5") |
| 1331 | with pytest.raises(polymarket.DatumNotFound): |
| 1332 | polymarket.refetch_datum(item_3, "OpenAI") |
| 1333 | assert polymarket.refetch_datum(item_3, "Sora")["value"] == 0.20 |
| 1334 | |
| 1335 | |
| 1336 | def test_greptile_r5_unused_group_title_on_non_subject_question_does_not_block_sibling( |
| 1337 | monkeypatch, |
| 1338 | ): |
| 1339 | """Greptile R5 P2: |
| 1340 | 'Does Alice qualify?' has no 'Will ...' question subject, so the parser never |
| 1341 | names Alice's market from its groupItemTitle ('Bob'). That unused groupItemTitle |
| 1342 | must NOT block saved 'Bob' odds for 'Will Bob win?' (either directly or via |
| 1343 | legacy_values when Bob's own current label is its groupItemTitle).""" |
| 1344 | # Variant 1: Bob has no groupItemTitle (current label is 'Bob'). |
| 1345 | event_plain = { |
| 1346 | "id": "712", |
| 1347 | "slug": "qualify-plain", |
| 1348 | "title": "Qualification?", |
| 1349 | "active": True, |
| 1350 | "closed": False, |
| 1351 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1352 | "markets": [ |
| 1353 | _binary_submarket("Does Alice qualify?", "Bob", 0.60), |
| 1354 | _binary_submarket("Will Bob win?", "", 0.35), |
| 1355 | ], |
| 1356 | } |
| 1357 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: event_plain) |
| 1358 | item_plain = SimpleNamespace(metadata={"event_id": "712"}, url="", item_id="pm-712") |
| 1359 | assert polymarket.refetch_datum(item_plain, "Bob")["value"] == 0.35 |
| 1360 | |
| 1361 | # Variant 2: Bob has groupItemTitle='Bob Winner', so legacy 'Bob' MUST resolve |
| 1362 | # through legacy_values—proving Alice's unused groupItemTitle='Bob' did not purge it. |
| 1363 | event_legacy = { |
| 1364 | "id": "713", |
| 1365 | "slug": "qualify-legacy", |
| 1366 | "title": "Qualification?", |
| 1367 | "active": True, |
| 1368 | "closed": False, |
| 1369 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1370 | "markets": [ |
| 1371 | _binary_submarket("Does Alice qualify?", "Bob", 0.60), |
| 1372 | _binary_submarket("Will Bob win?", "Bob Winner", 0.35), |
| 1373 | ], |
| 1374 | } |
| 1375 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: event_legacy) |
| 1376 | item_legacy = SimpleNamespace(metadata={"event_id": "713"}, url="", item_id="pm-713") |
| 1377 | assert polymarket.refetch_datum(item_legacy, "Bob")["value"] == 0.35 |
| 1378 | |
| 1379 | saved = _item( |
| 1380 | "polymarket", |
| 1381 | title="Qualification?", |
| 1382 | url="https://polymarket.com/event/qualify-legacy", |
| 1383 | metadata={ |
| 1384 | "event_id": "713", |
| 1385 | "outcome_prices": [["Does Alice qualify", 0.60], ["Bob", 0.35]], |
| 1386 | }, |
| 1387 | ) |
| 1388 | verdicts = freshness.verify_report( |
| 1389 | _report(saved), |
| 1390 | checked_at="2026-11-24T12:05:00Z", |
| 1391 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1392 | ) |
| 1393 | assert [v.verdict for v in verdicts] == ["current", "current"] |
| 1394 | assert verdicts[1].current_value == 0.35 |
| 1395 | |
| 1396 | |
| 1397 | def test_greptile_r6_and_r7_market_id_matching_and_legacy_cross_market_ambiguity(monkeypatch): |
| 1398 | """Greptile R6 (4681850135) + R7 (4681961728): |
| 1399 | - 'Will Alice win?' (groupItemTitle='Bob', 0.60) |
| 1400 | - 'Will Bob win?' (groupItemTitle='Winner', 0.35) |
| 1401 | - 'Does X qualify?' (groupItemTitle='Bob', 0.002) |
| 1402 | - 'Does Y qualify?' (groupItemTitle='Winner', 0.002) |
| 1403 | 1. New parser keeps 'Alice' and 'Bob' AND records outcome_market_ids (preserved |
| 1404 | through normalize.normalize_source_items). |
| 1405 | 2. New reports (with outcome_market_ids) match directly by market ID, verifying |
| 1406 | 'Bob' -> 0.35 (current) and returning unsupported if that market ID disappears |
| 1407 | (never falling back to Alice). |
| 1408 | 3. Older reports (without outcome_market_ids) treat 'Bob' as ambiguous because |
| 1409 | an older display parse (filtering out 0.002 'Does ...' siblings) could have |
| 1410 | saved Alice's 0.60 under 'Bob', so both direct fetch and cached lookup return |
| 1411 | unsupported instead of marking Alice stale against Bob's 0.35.""" |
| 1412 | from lib import normalize |
| 1413 | |
| 1414 | event = { |
| 1415 | "id": "714", |
| 1416 | "slug": "alice-bob-does", |
| 1417 | "title": "Tournament outcomes?", |
| 1418 | "active": True, |
| 1419 | "closed": False, |
| 1420 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1421 | "markets": [ |
| 1422 | {**_binary_submarket("Will Alice win?", "Bob", 0.60), "id": "m-alice"}, |
| 1423 | {**_binary_submarket("Will Bob win?", "Winner", 0.35), "id": "m-bob"}, |
| 1424 | {**_binary_submarket("Does X qualify?", "Bob", 0.002), "id": "m-x"}, |
| 1425 | {**_binary_submarket("Does Y qualify?", "Winner", 0.002), "id": "m-y"}, |
| 1426 | ], |
| 1427 | } |
| 1428 | [parsed] = polymarket.parse_polymarket_response({"events": [event]}) |
| 1429 | assert parsed["outcome_prices"] == [("Alice", 0.60), ("Bob", 0.35)] |
| 1430 | assert parsed["outcome_market_ids"] == ["m-alice", "m-bob"] |
| 1431 | |
| 1432 | # normalize preserves outcome_market_ids in SourceItem.metadata. |
| 1433 | [normalized_item] = normalize.normalize_source_items( |
| 1434 | "polymarket", [parsed], "2026-10-25", "2026-11-24", |
| 1435 | ) |
| 1436 | assert normalized_item.metadata["outcome_market_ids"] == ["m-alice", "m-bob"] |
| 1437 | |
| 1438 | calls: list[int] = [] |
| 1439 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: calls.append(1) or event) |
| 1440 | |
| 1441 | # New report (with outcome_market_ids): direct refetch AND cached verify_report |
| 1442 | # both match by market ID -> Alice 0.60 (current), Bob 0.35 (current). |
| 1443 | assert polymarket.refetch_datum(normalized_item, "Bob")["value"] == 0.35 |
| 1444 | assert polymarket.refetch_datum(normalized_item, "Alice")["value"] == 0.60 |
| 1445 | calls.clear() |
| 1446 | new_verdicts = freshness.verify_report( |
| 1447 | _report(normalized_item), |
| 1448 | checked_at="2026-11-24T12:05:00Z", |
| 1449 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1450 | ) |
| 1451 | assert len(calls) == 1 |
| 1452 | assert [v.verdict for v in new_verdicts] == ["current", "current", "current"] |
| 1453 | assert new_verdicts[0].current_value == 0.60 |
| 1454 | assert new_verdicts[1].current_value == 0.35 |
| 1455 | |
| 1456 | # If Bob's specific sub-market is dropped (wide book), market_id lookup fails closed |
| 1457 | # to unsupported rather than falling back to a label collision. |
| 1458 | bob_dropped_event = { |
| 1459 | **event, |
| 1460 | "markets": [ |
| 1461 | event["markets"][0], |
| 1462 | {**event["markets"][1], "bestBid": 0.01, "bestAsk": 0.99, "spread": 0.98}, |
| 1463 | event["markets"][2], |
| 1464 | event["markets"][3], |
| 1465 | ], |
| 1466 | } |
| 1467 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: bob_dropped_event) |
| 1468 | dropped_verdicts = freshness.verify_report( |
| 1469 | _report(normalized_item), |
| 1470 | checked_at="2026-11-24T12:05:00Z", |
| 1471 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1472 | ) |
| 1473 | assert [v.verdict for v in dropped_verdicts] == ["current", "unsupported", "current"] |
| 1474 | |
| 1475 | # Older report (NO outcome_market_ids): 'Bob' could have been Alice (0.60 via |
| 1476 | # groupItemTitle when 0.002 'Does ...' siblings were omitted) -> unsupported on |
| 1477 | # BOTH direct fetch and cached lookup, while unambiguous 'Alice' still resolves! |
| 1478 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: calls.append(1) or event) |
| 1479 | item_no_ids = SimpleNamespace(metadata={"event_id": "714"}, url="", item_id="pm-714") |
| 1480 | with pytest.raises(polymarket.DatumNotFound): |
| 1481 | polymarket.refetch_datum(item_no_ids, "Bob") |
| 1482 | assert polymarket.refetch_datum(item_no_ids, "Alice")["value"] == 0.60 |
| 1483 | |
| 1484 | calls.clear() |
| 1485 | old_saved = _item( |
| 1486 | "polymarket", |
| 1487 | title="Tournament outcomes?", |
| 1488 | url="https://polymarket.com/event/alice-bob-does", |
| 1489 | metadata={"event_id": "714", "outcome_prices": [["Alice", 0.60], ["Bob", 0.60]]}, |
| 1490 | ) |
| 1491 | old_verdicts = freshness.verify_report( |
| 1492 | _report(old_saved), |
| 1493 | checked_at="2026-11-24T12:05:00Z", |
| 1494 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1495 | ) |
| 1496 | assert len(calls) == 1 |
| 1497 | assert [v.verdict for v in old_verdicts] == ["current", "unsupported"] |
| 1498 | |
| 1499 | |
| 1500 | def test_greptile_r8_last_remaining_active_market_still_verifies_by_market_id(monkeypatch): |
| 1501 | """Greptile R8 P1 (4682122363): |
| 1502 | When a two-market event loses one active market (closing/resolving or removed), |
| 1503 | parse_polymarket_response displays the lone remaining active market as raw Yes/No |
| 1504 | without outcome_market_ids. refetch_datum must still build market_values directly |
| 1505 | from eligible markets so both direct fetch and cached verification verify the |
| 1506 | remaining active market (and any closed sibling's resolution price) by market ID.""" |
| 1507 | from lib import normalize |
| 1508 | |
| 1509 | initial_event = { |
| 1510 | "id": "715", |
| 1511 | "slug": "two-to-one", |
| 1512 | "title": "Two-market race?", |
| 1513 | "active": True, |
| 1514 | "closed": False, |
| 1515 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1516 | "markets": [ |
| 1517 | {**_binary_submarket("Will Alice win?", "Alice", 0.60), "id": "m-alice"}, |
| 1518 | {**_binary_submarket("Will Bob win?", "Bob", 0.35), "id": "m-bob"}, |
| 1519 | ], |
| 1520 | } |
| 1521 | [parsed] = polymarket.parse_polymarket_response({"events": [initial_event]}) |
| 1522 | assert parsed["outcome_prices"] == [("Alice", 0.60), ("Bob", 0.35)] |
| 1523 | assert parsed["outcome_market_ids"] == ["m-alice", "m-bob"] |
| 1524 | [saved_item] = normalize.normalize_source_items( |
| 1525 | "polymarket", [parsed], "2026-10-25", "2026-11-24", |
| 1526 | ) |
| 1527 | |
| 1528 | # Scenario A: Bob closes (resolves to 0.0) while Alice stays active at 0.70. |
| 1529 | one_closed_event = { |
| 1530 | **initial_event, |
| 1531 | "markets": [ |
| 1532 | {**_binary_submarket("Will Alice win?", "Alice", 0.70), "id": "m-alice"}, |
| 1533 | {**_binary_submarket("Will Bob win?", "Bob", 0.0, closed=True), "id": "m-bob"}, |
| 1534 | ], |
| 1535 | } |
| 1536 | # Confirm display parse now emits Yes/No without outcome_market_ids. |
| 1537 | [refreshed_display] = polymarket.parse_polymarket_response( |
| 1538 | {"events": [one_closed_event]}, include_all_outcomes=True, include_closed=False, |
| 1539 | ) |
| 1540 | assert "outcome_market_ids" not in refreshed_display |
| 1541 | assert refreshed_display["outcome_prices"] == [("Yes", 0.70), ("No", 0.30)] |
| 1542 | |
| 1543 | calls: list[int] = [] |
| 1544 | monkeypatch.setattr( |
| 1545 | polymarket.http, "request", lambda *_a, **_k: calls.append(1) or one_closed_event, |
| 1546 | ) |
| 1547 | assert polymarket.refetch_datum(saved_item, "Alice")["value"] == 0.70 |
| 1548 | assert polymarket.refetch_datum(saved_item, "Bob")["value"] == 0.0 |
| 1549 | |
| 1550 | calls.clear() |
| 1551 | verdicts = freshness.verify_report( |
| 1552 | _report(saved_item), |
| 1553 | checked_at="2026-11-24T12:05:00Z", |
| 1554 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1555 | ) |
| 1556 | assert len(calls) == 1 |
| 1557 | assert [v.verdict for v in verdicts] == ["stale", "stale", "current"] |
| 1558 | assert verdicts[0].current_value == 0.70 |
| 1559 | assert verdicts[1].current_value == 0.0 |
| 1560 | |
| 1561 | # Scenario B: Bob is removed completely, leaving only Alice active at 0.70. |
| 1562 | # Alice verifies to 0.70 (stale), Bob fails closed to unsupported. |
| 1563 | only_alice_event = { |
| 1564 | **initial_event, |
| 1565 | "markets": [ |
| 1566 | {**_binary_submarket("Will Alice win?", "Alice", 0.70), "id": "m-alice"}, |
| 1567 | ], |
| 1568 | } |
| 1569 | calls.clear() |
| 1570 | monkeypatch.setattr( |
| 1571 | polymarket.http, "request", lambda *_a, **_k: calls.append(1) or only_alice_event, |
| 1572 | ) |
| 1573 | verdicts_only_alice = freshness.verify_report( |
| 1574 | _report(saved_item), |
| 1575 | checked_at="2026-11-24T12:05:00Z", |
| 1576 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1577 | ) |
| 1578 | assert len(calls) == 1 |
| 1579 | assert [v.verdict for v in verdicts_only_alice] == ["stale", "unsupported", "current"] |
| 1580 | assert verdicts_only_alice[0].current_value == 0.70 |
| 1581 | |
| 1582 | |
| 1583 | def test_greptile_r9_resolved_market_verifies_when_only_open_market_has_zero_liquidity( |
| 1584 | monkeypatch, |
| 1585 | ): |
| 1586 | """Greptile R9 P1 (4682261324): |
| 1587 | If one market resolves at 0% and the only open market has zero liquidity, |
| 1588 | parse_polymarket_response returns no display rows, yet refetch_datum and |
| 1589 | cached verify_report must still verify the resolved market by market ID.""" |
| 1590 | from lib import normalize |
| 1591 | |
| 1592 | initial_event = { |
| 1593 | "id": "716", |
| 1594 | "slug": "zero-liq-plus-resolved", |
| 1595 | "title": "Two-market race?", |
| 1596 | "active": True, |
| 1597 | "closed": False, |
| 1598 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1599 | "markets": [ |
| 1600 | {**_binary_submarket("Will Alice win?", "Alice", 0.40), "id": "m-alice"}, |
| 1601 | {**_binary_submarket("Will Bob win?", "Bob", 0.60), "id": "m-bob"}, |
| 1602 | ], |
| 1603 | } |
| 1604 | [parsed] = polymarket.parse_polymarket_response({"events": [initial_event]}) |
| 1605 | assert parsed["outcome_prices"] == [("Bob", 0.60), ("Alice", 0.40)] |
| 1606 | assert parsed["outcome_market_ids"] == ["m-bob", "m-alice"] |
| 1607 | [saved_item] = normalize.normalize_source_items( |
| 1608 | "polymarket", [parsed], "2026-10-25", "2026-11-24", |
| 1609 | ) |
| 1610 | |
| 1611 | # Alice stays open with zero liquidity; Bob resolves to 0.0 (closed=True). |
| 1612 | updated_event = { |
| 1613 | **initial_event, |
| 1614 | "markets": [ |
| 1615 | { |
| 1616 | **_binary_submarket("Will Alice win?", "Alice", 0.50), |
| 1617 | "id": "m-alice", |
| 1618 | "liquidity": "0", |
| 1619 | }, |
| 1620 | { |
| 1621 | **_binary_submarket("Will Bob win?", "Bob", 0.0, closed=True), |
| 1622 | "id": "m-bob", |
| 1623 | "liquidity": "0", |
| 1624 | }, |
| 1625 | ], |
| 1626 | } |
| 1627 | # Confirm display parse produces no rows when open market has zero liquidity. |
| 1628 | assert ( |
| 1629 | polymarket.parse_polymarket_response( |
| 1630 | {"events": [updated_event]}, include_all_outcomes=True, include_closed=False, |
| 1631 | ) |
| 1632 | == [] |
| 1633 | ) |
| 1634 | |
| 1635 | calls: list[int] = [] |
| 1636 | monkeypatch.setattr( |
| 1637 | polymarket.http, "request", lambda *_a, **_k: calls.append(1) or updated_event, |
| 1638 | ) |
| 1639 | # Direct fetch: Bob resolves to 0.0; Alice raises DatumNotFound with snapshot. |
| 1640 | assert polymarket.refetch_datum(saved_item, "Bob")["value"] == 0.0 |
| 1641 | with pytest.raises(polymarket.DatumNotFound) as exc_info: |
| 1642 | polymarket.refetch_datum(saved_item, "Alice") |
| 1643 | assert exc_info.value.snapshot is not None |
| 1644 | assert exc_info.value.snapshot["market_values"] == {"m-bob": 0.0} |
| 1645 | |
| 1646 | # Cached verify_report (Bob first, Alice second, end_date third): 1 HTTP call. |
| 1647 | calls.clear() |
| 1648 | verdicts = freshness.verify_report( |
| 1649 | _report(saved_item), |
| 1650 | checked_at="2026-11-24T12:05:00Z", |
| 1651 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1652 | ) |
| 1653 | assert len(calls) == 1 |
| 1654 | assert [v.verdict for v in verdicts] == ["stale", "unsupported", "unsupported"] |
| 1655 | assert verdicts[0].current_value == 0.0 |
| 1656 | assert verdicts[0].detail == "moved: 60% -> 0%" |
| 1657 | |
| 1658 | # Reverse claim order (Alice first misses and caches snapshot -> Bob still resolves). |
| 1659 | reversed_item = _item( |
| 1660 | "polymarket", |
| 1661 | item_id="pm-716-rev", |
| 1662 | url=saved_item.url, |
| 1663 | title=saved_item.title, |
| 1664 | metadata={ |
| 1665 | **saved_item.metadata, |
| 1666 | "outcome_prices": [("Alice", 0.40), ("Bob", 0.60)], |
| 1667 | "outcome_market_ids": ["m-alice", "m-bob"], |
| 1668 | }, |
| 1669 | ) |
| 1670 | calls.clear() |
| 1671 | rev_verdicts = freshness.verify_report( |
| 1672 | _report(reversed_item), |
| 1673 | checked_at="2026-11-24T12:05:00Z", |
| 1674 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1675 | ) |
| 1676 | assert len(calls) == 1 |
| 1677 | assert [v.verdict for v in rev_verdicts] == ["unsupported", "stale", "unsupported"] |
| 1678 | assert rev_verdicts[1].current_value == 0.0 |
| 1679 | assert rev_verdicts[1].detail == "moved: 60% -> 0%" |
| 1680 | |
| 1681 | |
| 1682 | def test_greptile_r9_yes_other_child_market_verifies_with_same_yes_rule(monkeypatch): |
| 1683 | """Greptile R9 P2 (4682261343): |
| 1684 | If a child market has ['Yes', 'Other'] outcomes, parse_polymarket_response |
| 1685 | saves its Yes price and market_id during multi-market synthesis. refetch_datum |
| 1686 | and cached verify_report must accept that same Yes outcome instead of |
| 1687 | requiring strictly {'yes', 'no'} on every child market.""" |
| 1688 | from lib import normalize |
| 1689 | |
| 1690 | event = { |
| 1691 | "id": "717", |
| 1692 | "slug": "yes-other-child", |
| 1693 | "title": "Mixed binary child race?", |
| 1694 | "active": True, |
| 1695 | "closed": False, |
| 1696 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1697 | "markets": [ |
| 1698 | { |
| 1699 | **_binary_submarket("Will Alice win?", "Alice", 0.55), |
| 1700 | "id": "m-alice", |
| 1701 | "volume": "50000", |
| 1702 | }, |
| 1703 | { |
| 1704 | **_binary_submarket("Will Bob win?", "Bob", 0.35), |
| 1705 | "id": "m-bob", |
| 1706 | "volume": "10000", |
| 1707 | "outcomes": '["Yes", "Other"]', |
| 1708 | }, |
| 1709 | ], |
| 1710 | } |
| 1711 | [parsed] = polymarket.parse_polymarket_response({"events": [event]}) |
| 1712 | assert parsed["outcome_prices"] == [("Alice", 0.55), ("Bob", 0.35)] |
| 1713 | assert parsed["outcome_market_ids"] == ["m-alice", "m-bob"] |
| 1714 | [saved_item] = normalize.normalize_source_items( |
| 1715 | "polymarket", [parsed], "2026-10-25", "2026-11-24", |
| 1716 | ) |
| 1717 | |
| 1718 | calls: list[int] = [] |
| 1719 | monkeypatch.setattr( |
| 1720 | polymarket.http, "request", lambda *_a, **_k: calls.append(1) or event, |
| 1721 | ) |
| 1722 | assert polymarket.refetch_datum(saved_item, "Alice")["value"] == 0.55 |
| 1723 | assert polymarket.refetch_datum(saved_item, "Bob")["value"] == 0.35 |
| 1724 | |
| 1725 | calls.clear() |
| 1726 | verdicts = freshness.verify_report( |
| 1727 | _report(saved_item), |
| 1728 | checked_at="2026-11-24T12:05:00Z", |
| 1729 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1730 | ) |
| 1731 | assert len(calls) == 1 |
| 1732 | assert [v.verdict for v in verdicts] == ["current", "current", "current"] |
| 1733 | assert verdicts[1].current_value == 0.35 |
| 1734 | |
| 1735 | |
| 1736 | def test_greptile_r10_closed_unsettled_market_does_not_mark_old_odds_current(monkeypatch): |
| 1737 | """Greptile R10 P1 (4682403571): |
| 1738 | A closed child market that stopped trading before settling still carries its |
| 1739 | pre-close odds (e.g. 60%/40%). Neither the empty-display fallback nor the |
| 1740 | market_values map may mark a saved 60% claim current without 0/1 settlement |
| 1741 | proof; a settled closed sibling (0%/100%) still verifies.""" |
| 1742 | from lib import normalize |
| 1743 | |
| 1744 | initial_event = { |
| 1745 | "id": "718", |
| 1746 | "slug": "closed-unsettled-vs-settled", |
| 1747 | "title": "Three-way race?", |
| 1748 | "active": True, |
| 1749 | "closed": False, |
| 1750 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1751 | "markets": [ |
| 1752 | {**_binary_submarket("Will Alice win?", "Alice", 0.60), "id": "m-alice"}, |
| 1753 | {**_binary_submarket("Will Bob win?", "Bob", 0.25), "id": "m-bob"}, |
| 1754 | {**_binary_submarket("Will Carol win?", "Carol", 0.15), "id": "m-carol"}, |
| 1755 | ], |
| 1756 | } |
| 1757 | [parsed] = polymarket.parse_polymarket_response({"events": [initial_event]}) |
| 1758 | assert parsed["outcome_prices"] == [("Alice", 0.60), ("Bob", 0.25), ("Carol", 0.15)] |
| 1759 | assert parsed["outcome_market_ids"] == ["m-alice", "m-bob", "m-carol"] |
| 1760 | [saved_item] = normalize.normalize_source_items( |
| 1761 | "polymarket", [parsed], "2026-10-25", "2026-11-24", |
| 1762 | ) |
| 1763 | |
| 1764 | # Scenario A: No display rows (Carol open w/ zero liquidity), Alice closed |
| 1765 | # before settling at old 60%/40% odds, Bob settled at 0%/100%. |
| 1766 | mixed_closed_event = { |
| 1767 | **initial_event, |
| 1768 | "markets": [ |
| 1769 | { |
| 1770 | **_binary_submarket("Will Alice win?", "Alice", 0.60, closed=True), |
| 1771 | "id": "m-alice", |
| 1772 | "liquidity": "0", |
| 1773 | }, |
| 1774 | { |
| 1775 | **_binary_submarket("Will Bob win?", "Bob", 0.0, closed=True), |
| 1776 | "id": "m-bob", |
| 1777 | "liquidity": "0", |
| 1778 | }, |
| 1779 | { |
| 1780 | **_binary_submarket("Will Carol win?", "Carol", 0.15), |
| 1781 | "id": "m-carol", |
| 1782 | "liquidity": "0", |
| 1783 | }, |
| 1784 | ], |
| 1785 | } |
| 1786 | calls: list[int] = [] |
| 1787 | monkeypatch.setattr( |
| 1788 | polymarket.http, "request", lambda *_a, **_k: calls.append(1) or mixed_closed_event, |
| 1789 | ) |
| 1790 | with pytest.raises(polymarket.DatumNotFound) as exc_info: |
| 1791 | polymarket.refetch_datum(saved_item, "Alice") |
| 1792 | assert exc_info.value.snapshot is not None |
| 1793 | assert exc_info.value.snapshot["market_values"] == {"m-bob": 0.0} |
| 1794 | assert polymarket.refetch_datum(saved_item, "Bob")["value"] == 0.0 |
| 1795 | |
| 1796 | calls.clear() |
| 1797 | verdicts = freshness.verify_report( |
| 1798 | _report(saved_item), |
| 1799 | checked_at="2026-11-24T12:05:00Z", |
| 1800 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1801 | ) |
| 1802 | assert len(calls) == 1 |
| 1803 | assert [v.verdict for v in verdicts] == [ |
| 1804 | "unsupported", # Alice: closed but unsettled 60%/40% must NOT pass as current |
| 1805 | "stale", # Bob: settled 0%/100% verifies 25% -> 0% |
| 1806 | "unsupported", # Carol: open with zero liquidity |
| 1807 | "unsupported", # end_date |
| 1808 | ] |
| 1809 | assert verdicts[1].current_value == 0.0 |
| 1810 | |
| 1811 | # Scenario B: Closed market with 0/1 prices but umaResolutionStatus='proposed' |
| 1812 | # (not yet finalized) is also rejected, while 'resolved' is accepted. |
| 1813 | proposed_vs_resolved_event = { |
| 1814 | **initial_event, |
| 1815 | "markets": [ |
| 1816 | { |
| 1817 | **_binary_submarket("Will Alice win?", "Alice", 1.0, closed=True), |
| 1818 | "id": "m-alice", |
| 1819 | "liquidity": "0", |
| 1820 | "umaResolutionStatus": "proposed", |
| 1821 | }, |
| 1822 | { |
| 1823 | **_binary_submarket("Will Bob win?", "Bob", 0.0, closed=True), |
| 1824 | "id": "m-bob", |
| 1825 | "liquidity": "0", |
| 1826 | "umaResolutionStatus": "resolved", |
| 1827 | }, |
| 1828 | { |
| 1829 | **_binary_submarket("Will Carol win?", "Carol", 0.15), |
| 1830 | "id": "m-carol", |
| 1831 | "liquidity": "0", |
| 1832 | }, |
| 1833 | ], |
| 1834 | } |
| 1835 | calls.clear() |
| 1836 | monkeypatch.setattr( |
| 1837 | polymarket.http, |
| 1838 | "request", |
| 1839 | lambda *_a, **_k: calls.append(1) or proposed_vs_resolved_event, |
| 1840 | ) |
| 1841 | verdicts_uma = freshness.verify_report( |
| 1842 | _report(saved_item), |
| 1843 | checked_at="2026-11-24T12:05:00Z", |
| 1844 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1845 | ) |
| 1846 | assert len(calls) == 1 |
| 1847 | assert [v.verdict for v in verdicts_uma] == [ |
| 1848 | "unsupported", |
| 1849 | "stale", |
| 1850 | "unsupported", |
| 1851 | "unsupported", |
| 1852 | ] |
| 1853 | assert verdicts_uma[1].current_value == 0.0 |
| 1854 | |
| 1855 | |
| 1856 | def test_greptile_r10_omitted_question_still_verifies_by_unique_market_id(monkeypatch): |
| 1857 | """Greptile R10 P2 (4682403585): |
| 1858 | If Gamma omits or blanks 'question' on a child market while returning its |
| 1859 | unique market ID and usable Yes price, refetch_datum and cached |
| 1860 | verify_report must still verify the saved market_id claim.""" |
| 1861 | from lib import normalize |
| 1862 | |
| 1863 | initial_event = { |
| 1864 | "id": "719", |
| 1865 | "slug": "omitted-question-recheck", |
| 1866 | "title": "Two-market race?", |
| 1867 | "active": True, |
| 1868 | "closed": False, |
| 1869 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1870 | "markets": [ |
| 1871 | {**_binary_submarket("Will Alice win?", "Alice", 0.60), "id": "m-alice"}, |
| 1872 | {**_binary_submarket("Will Bob win?", "Bob", 0.35), "id": "m-bob"}, |
| 1873 | ], |
| 1874 | } |
| 1875 | [parsed] = polymarket.parse_polymarket_response({"events": [initial_event]}) |
| 1876 | assert parsed["outcome_market_ids"] == ["m-alice", "m-bob"] |
| 1877 | [saved_item] = normalize.normalize_source_items( |
| 1878 | "polymarket", [parsed], "2026-10-25", "2026-11-24", |
| 1879 | ) |
| 1880 | |
| 1881 | alice_no_q = {**_binary_submarket("Will Alice win?", "Alice", 0.60), "id": "m-alice"} |
| 1882 | alice_no_q.pop("question") |
| 1883 | bob_blank_q = {**_binary_submarket("", "Bob", 0.45), "id": "m-bob"} |
| 1884 | updated_event = { |
| 1885 | **initial_event, |
| 1886 | "markets": [alice_no_q, bob_blank_q], |
| 1887 | } |
| 1888 | |
| 1889 | calls: list[int] = [] |
| 1890 | monkeypatch.setattr( |
| 1891 | polymarket.http, "request", lambda *_a, **_k: calls.append(1) or updated_event, |
| 1892 | ) |
| 1893 | assert polymarket.refetch_datum(saved_item, "Alice")["value"] == 0.60 |
| 1894 | assert polymarket.refetch_datum(saved_item, "Bob")["value"] == 0.45 |
| 1895 | |
| 1896 | calls.clear() |
| 1897 | verdicts = freshness.verify_report( |
| 1898 | _report(saved_item), |
| 1899 | checked_at="2026-11-24T12:05:00Z", |
| 1900 | refetchers={"polymarket": polymarket.refetch_datum}, |
| 1901 | ) |
| 1902 | assert len(calls) == 1 |
| 1903 | assert [v.verdict for v in verdicts] == ["current", "stale", "current"] |
| 1904 | assert verdicts[0].current_value == 0.60 |
| 1905 | assert verdicts[1].current_value == 0.45 |
| 1906 | |
| 1907 | |
| 1908 | |
| 1909 | |
| 1910 | |
| 1911 | |
| 1912 | |
| 1913 | def test_greptile3_bad_price_on_top_binary_market_does_not_hide_valid_siblings(): |
| 1914 | """If the highest-volume Yes/No market has a bad price (e.g., bool True), |
| 1915 | top_outcomes_are_binary must still read raw outcomes so valid siblings survive.""" |
| 1916 | bad_top = { |
| 1917 | "active": True, |
| 1918 | "closed": False, |
| 1919 | "question": "Will BadTop win the race?", |
| 1920 | "groupItemTitle": "BadTop", |
| 1921 | "liquidity": "500", |
| 1922 | "volume": "999999", |
| 1923 | "outcomes": '["Yes", "No"]', |
| 1924 | "outcomePrices": [True, "0.40"], |
| 1925 | "endDate": "2026-12-31T00:00:00Z", |
| 1926 | } |
| 1927 | valid_a = _binary_submarket("Will Alice win the race?", "Alice", 0.55) |
| 1928 | valid_b = _binary_submarket("Will Bob win the race?", "Bob", 0.35) |
| 1929 | event = { |
| 1930 | "id": "704", |
| 1931 | "slug": "bad-top-sibling", |
| 1932 | "title": "Who wins the race?", |
| 1933 | "active": True, |
| 1934 | "closed": False, |
| 1935 | "updatedAt": "2026-11-24T12:00:00Z", |
| 1936 | "markets": [bad_top, valid_a, valid_b], |
| 1937 | } |
| 1938 | |
| 1939 | [parsed] = polymarket.parse_polymarket_response({"events": [event]}) |
| 1940 | assert parsed["outcome_prices"] == [("Alice", 0.55), ("Bob", 0.35)] |
| 1941 | |
| 1942 | |
| 1943 | @pytest.mark.parametrize("bad_spread", ["NaN", "inf", "-inf", True, "bad", -0.05]) |
| 1944 | def test_greptile4_malformed_spread_does_not_return_midpoint_on_wide_book(bad_spread): |
| 1945 | """A malformed spread (e.g., 'NaN') must be treated as missing (using ask - bid), |
| 1946 | never coerced to 0.0 to accept a wide 0.01/0.99 book's midpoint.""" |
| 1947 | wide_with_trade = { |
| 1948 | "outcomes": '["Yes", "No"]', |
| 1949 | "outcomePrices": '["0.50", "0.50"]', |
| 1950 | "bestBid": 0.01, |
| 1951 | "bestAsk": 0.99, |
| 1952 | "spread": bad_spread, |
| 1953 | "lastTradePrice": 0.02, |
| 1954 | } |
| 1955 | assert polymarket._quoted_price(wide_with_trade, 0.50) == 0.02 |
| 1956 | assert polymarket._parse_outcome_prices(wide_with_trade) == [("Yes", 0.02), ("No", 0.98)] |
| 1957 | |
| 1958 | wide_no_trade = { |
| 1959 | "outcomes": '["Yes", "No"]', |
| 1960 | "outcomePrices": '["0.50", "0.50"]', |
| 1961 | "bestBid": 0.01, |
| 1962 | "bestAsk": 0.99, |
| 1963 | "spread": bad_spread, |
| 1964 | } |
| 1965 | assert polymarket._quoted_price(wide_no_trade, 0.50) is None |
| 1966 | assert polymarket._parse_outcome_prices(wide_no_trade) == [] |
| 1967 | |
| 1968 | # Tight bid/ask with bad spread still computes ask - bid = 0.08 <= 0.10 -> midpoint. |
| 1969 | tight_bad_spread = { |
| 1970 | "outcomes": '["Yes", "No"]', |
| 1971 | "outcomePrices": '["0.50", "0.50"]', |
| 1972 | "bestBid": 0.46, |
| 1973 | "bestAsk": 0.54, |
| 1974 | "spread": bad_spread, |
| 1975 | "lastTradePrice": 0.70, |
| 1976 | } |
| 1977 | assert polymarket._quoted_price(tight_bad_spread, 0.50) == 0.50 |
| 1978 | |
| 1979 | |
| 1980 | def test_greptile5_has_been_outranks_became_while_became_outranks_was(): |
| 1981 | """'became closed last year; has been open since May' must not contradict 'is open'.""" |
| 1982 | original = _item( |
| 1983 | "reddit", |
| 1984 | item_id="R1", |
| 1985 | url="https://reddit.com/r/dev/orig", |
| 1986 | title="Widget API is open", |
| 1987 | published_at="2026-11-01T10:00:00Z", |
| 1988 | ) |
| 1989 | recovered = _item( |
| 1990 | "grounding", |
| 1991 | item_id="W1", |
| 1992 | url="https://status.example.com/recovery", |
| 1993 | title="Widget API became closed last year. Widget API has been open since May.", |
| 1994 | published_at="2026-11-10T10:00:00Z", |
| 1995 | ) |
| 1996 | report = _report(original) |
| 1997 | report.items_by_source["grounding"] = [recovered] |
| 1998 | assert freshness.verify_report(report)[0].verdict == "unsupported" |
| 1999 | |
| 2000 | # Reverse: 'became open ... has been closed' contradicts 'is open'. |
| 2001 | relapsed = _item( |
| 2002 | "grounding", |
| 2003 | item_id="W2", |
| 2004 | url="https://status.example.com/relapse", |
| 2005 | title="Widget API became open last year. Widget API has been closed since May.", |
| 2006 | published_at="2026-11-10T10:00:00Z", |
| 2007 | ) |
| 2008 | report2 = _report(original) |
| 2009 | report2.items_by_source["grounding"] = [relapsed] |
| 2010 | v2 = freshness.verify_report(report2)[0] |
| 2011 | assert v2.verdict == "contradicted" |
| 2012 | assert v2.evidence_url == relapsed.url |
| 2013 | |
| 2014 | |
| 2015 | @pytest.mark.parametrize("unicode_digit", ["²", "٠", "①"]) |
| 2016 | def test_greptile6_non_ascii_digit_suffix_raises_datum_not_found_with_snapshot( |
| 2017 | monkeypatch, unicode_digit, |
| 2018 | ): |
| 2019 | """Non-ASCII unicode digits like '²' or '٠' pass str.isdigit() but must raise |
| 2020 | DatumNotFound with the fetched snapshot intact instead of ValueError.""" |
| 2021 | event = { |
| 2022 | "id": "706", |
| 2023 | "slug": "unicode-occ", |
| 2024 | "title": "Unicode suffix check", |
| 2025 | "active": True, |
| 2026 | "closed": False, |
| 2027 | "updatedAt": "2026-11-24T12:00:00Z", |
| 2028 | "markets": [ |
| 2029 | { |
| 2030 | "active": True, |
| 2031 | "closed": False, |
| 2032 | "question": "Unicode suffix check", |
| 2033 | "liquidity": "1000", |
| 2034 | "outcomes": '["OpenAI", "Anthropic"]', |
| 2035 | "outcomePrices": '["0.60", "0.40"]', |
| 2036 | } |
| 2037 | ], |
| 2038 | } |
| 2039 | monkeypatch.setattr(polymarket.http, "request", lambda *_a, **_k: event) |
| 2040 | item = SimpleNamespace(metadata={"event_id": "706"}, url="", item_id="pm-706") |
| 2041 | |
| 2042 | with pytest.raises(polymarket.DatumNotFound) as exc_info: |
| 2043 | polymarket.refetch_datum(item, f"OpenAI\x1f{unicode_digit}") |
| 2044 | assert exc_info.value.snapshot is not None |
| 2045 | assert exc_info.value.snapshot["values"]["OpenAI"] == 0.60 |
| 2046 | assert exc_info.value.snapshot["values"]["Anthropic"] == 0.40 |
| 2047 | |
| 2048 |