返回 last30days-skill
test_polymarket_pipeline_survival.py
根目录 / tests / test_polymarket_pipeline_survival.py
1 """A matched Polymarket market survives the pipeline and renders in selection order.
2
3 The parser judges each market against the research subject (``EntityMatcher``)
4 and ranks events by ``selection_score``. These tests pin what happens after
5 parse: the matched market's question reaches the normalized item, the generic
6 relevance floor does not drop an item the matcher kept, the post-merge topic
7 and keyword filters read the matched market and not only the event title, and
8 the Markets block and footer list items by the same score.
9
10 Fixtures are the live Gamma events under ``fixtures/polymarket``.
11 """
12
13 import copy
14 import json
15 from pathlib import Path
16 from unittest.mock import patch
17
18 from lib import normalize, pipeline, polymarket, render, schema, signals
19
20 FIXTURES = Path(__file__).parent / "fixtures" / "polymarket"
21 TO_DATE = "2026-11-16"
22 FROM_DATE = "2026-10-17"
23 NFL_CHAMPION = "Pro Football: 2027 Champion"
24 WIN_TOTAL = "Pro Football: 49ers 2026 Win Total"
25 ROOKIE = "NBA: 2026-27 Rookie of the Year"
26 GAME = "Vikings vs. 49ers"
27 SEASON_QUERY = "What are people saying about the San Francisco 49ers this season?"
28 LENDEBORG = {"name": "Yaxel Lendeborg", "relation": "player"}
29
30
31 def _fixture(name):
32 return json.loads((FIXTURES / f"{name}.json").read_text())
33
34
35 def _win_total_with_more_volume():
36 """The win-total event with more 30-day money than the champion event, so
37 volume order and selection order disagree."""
38 event = copy.deepcopy(_fixture("pro_football_49ers_2026_win_total"))
39 event["volume1mo"] = 50_000_000
40 return event
41
42
43 def _game_event():
44 return {
45 "id": "g1", "title": GAME, "slug": "nfl-min-sf-2026-11-22",
46 "active": True, "closed": False, "negRisk": False,
47 "volume1mo": 900_000, "liquidity": 200_000, "endDate": "2026-11-23T01:00:00Z",
48 "markets": [{
49 "id": "m1", "question": GAME, "outcomes": '["Vikings", "49ers"]',
50 "outcomePrices": '["0.31", "0.69"]', "volume": "850000", "volumeNum": 850_000,
51 "liquidity": "200000", "endDate": "2026-11-23T01:00:00Z",
52 "active": True, "closed": False,
53 }],
54 }
55
56
57 def _parse(topic, *events, hints=None):
58 return polymarket.parse_polymarket_response(
59 {"events": list(events)}, topic=topic, to_date=TO_DATE, hints=hints,
60 )
61
62
63 def _normalized(topic, *events, hints=None):
64 return normalize.normalize_source_items(
65 "polymarket", _parse(topic, *events, hints=hints), FROM_DATE, TO_DATE,
66 )
67
68
69 def _by_title(items):
70 return {item.title: item for item in items}
71
72
73 def _report(topic, items):
74 return schema.Report(
75 topic=topic, range_from=FROM_DATE, range_to=TO_DATE,
76 generated_at="2026-11-16T12:00:00Z", provider_runtime=None,
77 query_plan=None, clusters=[], ranked_candidates=[],
78 items_by_source={"polymarket": items}, errors_by_source={},
79 )
80
81
82 # --- Normalize ---
83
84
85 def test_normalized_item_carries_the_matched_market_and_its_score():
86 item = _by_title(_normalized("49ers", _fixture("pro_football_2027_champion")))[NFL_CHAMPION]
87
88 assert "Will the San Francisco 49ers win the 2027 NFL league championship?" in item.body
89 assert item.metadata["matched_market"]["label"] == "San Francisco 49ers"
90 assert item.metadata["selection_tier"] == 1
91 assert item.metadata["selection_score"] > 0
92
93
94 # --- The relevance floor ---
95
96
97 def test_game_market_survives_the_floor_under_a_wordy_ranking_query():
98 items = _normalized("49ers", _game_event(), _fixture("pro_football_2027_champion"))
99 for item in items:
100 # The game scored 0.15-0.21 against the planner's phrasing; pin it under.
101 item.local_relevance = 0.1 if item.title == GAME else 0.6
102
103 kept = signals.prune_low_relevance(items)
104
105 assert GAME in {item.title for item in kept}
106
107
108 def test_unmatched_polymarket_item_is_still_held_to_the_floor():
109 items = _normalized("49ers", _fixture("pro_football_2027_champion"))
110 legacy = schema.SourceItem(
111 item_id="legacy", source="polymarket", title="Some other market", body="",
112 url="https://polymarket.com/event/other", engagement={"volume": 1000},
113 )
114 legacy.local_relevance = 0.05
115 items[0].local_relevance = 0.6
116
117 kept = signals.prune_low_relevance([*items, legacy])
118
119 assert "legacy" not in {item.item_id for item in kept}
120
121
122 # --- Post-merge topic and keyword filters ---
123
124
125 def test_champion_item_survives_the_topic_filter():
126 items = _normalized("49ers", _fixture("pro_football_2027_champion"))
127
128 kept = polymarket.filter_items_against_topic("49ers", items)
129
130 assert [item.title for item in kept] == [NFL_CHAMPION]
131
132
133 def test_related_player_award_survives_the_topic_filter_with_hints():
134 hints = {"kind": "team", "related": [LENDEBORG]}
135 items = _normalized("Warriors", _fixture("nba_2026_27_rookie_of_the_year"), hints=hints)
136
137 assert [item.title for item in polymarket.filter_items_against_topic(
138 "Warriors", items, hints)] == [ROOKIE]
139 assert polymarket.filter_items_against_topic("Warriors", items) == []
140
141
142 def test_keywords_keep_the_champion_item_through_its_outcome_label():
143 items = _normalized("49ers", _fixture("pro_football_2027_champion"))
144
145 kept = polymarket.filter_items_against_keywords(items, ["49ers", "niners"])
146
147 assert [item.title for item in kept] == [NFL_CHAMPION]
148
149
150 # --- Render order and the matched line ---
151
152
153 def _forty_niners_items():
154 return _normalized("49ers", _fixture("pro_football_2027_champion"), _win_total_with_more_volume())
155
156
157 def test_markets_block_lists_by_selection_score_not_volume():
158 lines = render._render_polymarket_markets(_report("49ers", _forty_niners_items()))
159
160 assert lines[0] == "## Polymarket Markets"
161 assert NFL_CHAMPION in lines[2]
162 assert WIN_TOTAL in lines[3]
163
164
165 def test_footer_lists_by_selection_score_not_volume():
166 summaries = render._polymarket_top_markets(_forty_niners_items(), topic="49ers")
167
168 assert "championship" in summaries[0]
169 assert "12.5 wins" in summaries[1]
170
171
172 def test_items_without_a_score_still_sort_by_volume():
173 def legacy(item_id, question, volume):
174 return schema.SourceItem(
175 item_id=item_id, source="polymarket", title=question, body="",
176 url=f"https://polymarket.com/event/{item_id}", engagement={"volume": volume},
177 metadata={"question": question, "outcome_prices": [("Yes", 0.4)]},
178 )
179
180 items = [
181 legacy("small", "Will the 49ers make the playoffs?", 100),
182 legacy("big", "Will the 49ers win the NFC West?", 900),
183 ]
184
185 lines = render._render_polymarket_markets(_report("49ers", items))
186 summaries = render._polymarket_top_markets(items, topic="49ers")
187
188 assert "NFC West" in lines[2] and "playoffs" in lines[3]
189 assert "NFC West" in summaries[0] and "playoffs" in summaries[1]
190
191
192 def test_matched_line_names_the_entity_and_its_contender_rank():
193 lines = render._render_polymarket_markets(_report("49ers", _forty_niners_items()))
194
195 assert lines[2].startswith(
196 "- 📊 Polymarket · Pro Football: 2027 Champion: "
197 "San Francisco 49ers 14.5%, #1 of 32 (up 1.8 pts this month)"
198 )
199
200
201 def test_related_player_line_names_the_player_and_relation():
202 hints = {"kind": "team", "related": [LENDEBORG]}
203 items = _normalized("Warriors", _fixture("nba_2026_27_rookie_of_the_year"), hints=hints)
204
205 lines = render._render_polymarket_markets(_report("Warriors", items))
206
207 assert len(lines) == 3
208 assert "Yaxel Lendeborg (player) 34.6%, #1 of 30" in lines[2]
209 # The player's own price is said once.
210 assert lines[2].count("34.6%") == 1
211
212
213 def test_alias_matched_market_is_kept_in_the_markets_block():
214 event = {
215 "id": "f1", "title": "F1 Drivers Champion 2026", "slug": "f1-drivers-champion-2026",
216 "active": True, "closed": False, "negRisk": False,
217 "volume1mo": 2_000_000, "liquidity": 500_000, "endDate": "2026-12-07T00:00:00Z",
218 "markets": [{
219 "id": "f1m", "question": "Will Max Verstappen win the 2026 F1 Drivers Championship?",
220 "groupItemTitle": "Max Verstappen",
221 "outcomes": '["Yes", "No"]', "outcomePrices": '["0.40", "0.60"]',
222 "volume": "900000", "volumeNum": 900_000, "liquidity": "100000",
223 "endDate": "2026-12-07T00:00:00Z", "active": True, "closed": False,
224 }],
225 }
226 items = _normalized("Formula 1", event, hints={"aliases": ["F1"]})
227 assert items
228
229 lines = render._render_polymarket_markets(_report("Formula 1", items))
230
231 assert any("Max Verstappen" in line and "40%" in line for line in lines)
232
233
234 def test_win_total_line_leads_with_the_matched_rung():
235 lines = render._render_polymarket_markets(_report("49ers", _forty_niners_items()))
236
237 assert "Pro Football: 49ers 2026 Win Total: 12.5+ Wins 77.5%" in lines[3]
238 assert "#" not in lines[3].split(" — ")[0]
239
240
241 # --- End to end ---
242
243
244 def test_mock_run_for_49ers_leads_the_compact_markets_block_with_the_champion():
245 raw = _parse(
246 "49ers", _fixture("pro_football_2027_champion"), _win_total_with_more_volume(), _game_event(),
247 )
248 plan = {
249 "intent": "general",
250 "freshness_mode": "balanced_recent",
251 "cluster_mode": "story",
252 "subqueries": [{
253 "label": "primary",
254 "search_query": "49ers",
255 "ranking_query": SEASON_QUERY,
256 "sources": ["polymarket"],
257 }],
258 "source_weights": {"polymarket": 1.0},
259 }
260
261 def fake_retrieve(**kwargs):
262 return (copy.deepcopy(raw), {}) if kwargs.get("source") == "polymarket" else ([], {})
263
264 with patch.object(pipeline, "_retrieve_stream", side_effect=fake_retrieve):
265 report = pipeline.run(
266 topic="49ers", config={}, depth="quick", mock=True,
267 requested_sources=["polymarket"], web_backend="none",
268 external_plan=plan, as_of_date=TO_DATE,
269 )
270
271 titles = {item.title for item in report.items_by_source["polymarket"]}
272 assert {NFL_CHAMPION, WIN_TOTAL, GAME} <= titles
273
274 compact = render.render_compact(report)
275 block = compact.split("## Polymarket Markets", 1)[1].strip().splitlines()
276 assert block[0].startswith("- 📊 Polymarket · Pro Football: 2027 Champion: San Francisco 49ers 14.5%")
277
278
279 def _small_game(index):
280 title = f"Warriors vs. Team{index}"
281 return {
282 "id": f"wg{index}", "title": title, "slug": f"nba-gsw-team{index}",
283 "active": True, "closed": False, "negRisk": False,
284 "volume1mo": 5_000_000, "liquidity": 900_000, "endDate": "2026-12-20T01:00:00Z",
285 "markets": [{
286 "id": f"wm{index}", "question": title, "outcomes": '["Warriors", "Team"]',
287 "outcomePrices": '["0.55", "0.45"]', "volume": "1500", "volumeNum": 1_500,
288 "liquidity": "1000", "endDate": "2026-12-20T01:00:00Z",
289 "active": True, "closed": False,
290 }],
291 }
292
293
294 def test_related_player_race_survives_the_stream_cut_at_quick_depth():
295 hints = {"kind": "team", "related": [LENDEBORG]}
296 raw = _parse(
297 "Warriors", _fixture("nba_2026_27_rookie_of_the_year"),
298 *(_small_game(index) for index in range(8)), hints=hints,
299 )
300 plan = {
301 "intent": "general",
302 "freshness_mode": "balanced_recent",
303 "cluster_mode": "story",
304 "subqueries": [{
305 "label": "primary",
306 "search_query": "Warriors",
307 "ranking_query": "What are people saying about Warriors?",
308 "sources": ["polymarket"],
309 }],
310 "source_weights": {"polymarket": 1.0},
311 "polymarket_hints": hints,
312 }
313
314 def fake_retrieve(**kwargs):
315 return (copy.deepcopy(raw), {}) if kwargs.get("source") == "polymarket" else ([], {})
316
317 with patch.object(pipeline, "_retrieve_stream", side_effect=fake_retrieve):
318 report = pipeline.run(
319 topic="Warriors", config={}, depth="quick", mock=True,
320 requested_sources=["polymarket"], web_backend="none",
321 external_plan=plan, as_of_date=TO_DATE,
322 )
323
324 titles = [item.title for item in report.items_by_source["polymarket"]]
325 assert ROOKIE in titles
326 compact = render.render_compact(report)
327 block = compact.split("## Polymarket Markets", 1)[1].strip().splitlines()
328 assert ROOKIE in block[0]
329
330
331 def test_race_with_suppressed_odds_still_lists_the_matched_player():
332 """When a race's Yes prices sum well over one, the parser withholds the
333 event's odds and outcome list but keeps the subject's own market, which
334 is priced on its own book. The Markets block still lists it."""
335 hints = {"kind": "team", "related": [{"name": "Ty Jerome", "relation": "player"}]}
336 items = _normalized(
337 "Memphis Grizzlies", _fixture("nba_2026_27_most_improved_player"), hints=hints,
338 )
339 for item in items:
340 # What the parser stores for a race whose Yes prices are impossible.
341 item.metadata["odds"] = None
342 item.metadata["outcome_prices"] = []
343
344 lines = render._render_polymarket_markets(_report("Memphis Grizzlies", items))
345
346 assert len(lines) == 3
347 assert ": Ty Jerome (player) 34" in lines[2]
348 assert ", #1 of " in lines[2]
349
350
351 # --- Partial search ---
352
353
354 def _retrieve_polymarket(topic):
355 subquery = schema.SubQuery(
356 label="primary", search_query=topic, ranking_query=topic, sources=["polymarket"],
357 )
358 return pipeline._retrieve_stream_impl(
359 topic=topic, subquery=subquery, source="polymarket", config={}, depth="quick",
360 date_range=(FROM_DATE, TO_DATE),
361 runtime=schema.ProviderRuntime(
362 reasoning_provider="none", planner_model="none", rerank_model="none",
363 ),
364 mock=False,
365 )
366
367
368 def test_partial_search_is_reported_partial_and_not_memoized(monkeypatch):
369 from lib import fetch_memo
370
371 fetch_memo.reset()
372 calls = []
373
374 def search(topic, *_args, **kwargs):
375 calls.append(kwargs.get("deadline"))
376 return {
377 "events": [_fixture("pro_football_2027_champion")], "_cap": 5,
378 "error": "HTTP 429: Rate limit", "partial": True,
379 }
380
381 monkeypatch.setattr(polymarket, "search_polymarket", search)
382
383 items, artifact = _retrieve_polymarket("49ers")
384 _retrieve_polymarket("49ers")
385
386 assert items
387 assert artifact["_source_outcome"]["state"] == schema.PARTIAL
388 assert len(calls) == 2
389 assert all(isinstance(deadline, float) for deadline in calls)
390 fetch_memo.reset()
391
391 lines PYTHON