返回 last30days-skill
test_pipeline_cancellation.py
根目录 / tests / test_pipeline_cancellation.py
1 from __future__ import annotations
2
3 import threading
4 import time
5 import urllib.error
6 from dataclasses import replace
7 from unittest import mock
8 from uuid import uuid4
9
10 import pytest
11
12 from lib import dates, health, http, pipeline, schema
13
14
15 @pytest.fixture
16 def x_run(monkeypatch):
17 topic = f"Widget compiler {uuid4().hex}"
18 today = dates.get_date_range(30)[1]
19 post = {
20 "id": "1", "url": "https://x.com/widget/status/1",
21 "author_handle": "widget", "text": f"{topic} ships incremental builds",
22 "date": today, "engagement": {"likes": 100}, "relevance": 1.0,
23 }
24 plan = schema.QueryPlan(
25 raw_topic=topic, intent="opinion", freshness_mode="balanced_recent",
26 cluster_mode="debate", source_weights={"x": 1.0},
27 subqueries=[schema.SubQuery(
28 label="primary", search_query=topic, ranking_query=topic, sources=["x"],
29 )],
30 )
31 runtime = schema.ProviderRuntime(
32 reasoning_provider="native", planner_model="", rerank_model="",
33 x_search_backend="xapi",
34 )
35 monkeypatch.setattr(pipeline.providers, "resolve_runtime", lambda *a: (runtime, None))
36 monkeypatch.setattr(pipeline, "available_sources", lambda *a, **k: ["x"])
37 monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["xapi"])
38 monkeypatch.setattr(pipeline.planner, "plan_query", lambda **k: plan)
39 monkeypatch.setattr(pipeline.entity_extract, "extract_entities", lambda *a, **k: {
40 "x_handles": ["widget"], "x_hashtags": [], "reddit_subreddits": [],
41 })
42 return topic, post, plan, runtime
43
44
45 @pytest.mark.parametrize("expired", [True, False])
46 def test_enrichment_lifecycle_stops_late_supplemental_requests(monkeypatch, x_run, expired):
47 topic, post, _, _ = x_run
48 release = threading.Event()
49 finished = threading.Event()
50 stream_finished = threading.Event()
51 calls = []
52 if not expired:
53 release.set()
54
55 def topic_search(*args, **kwargs):
56 calls.append("topic")
57 assert release.wait(5)
58 return {"items": [post, {
59 **post, "id": "2", "url": "https://x.com/widget/status/2",
60 "text": f"{topic} community discusses authentication errors and setup tutorials for new users",
61 }]}
62
63 def from_search(*args, **kwargs):
64 calls.append("FROM")
65 return []
66
67 def about_search(*args, **kwargs):
68 calls.append("ABOUT")
69 return []
70
71 original_run = pipeline.run
72 original_stream = pipeline._retrieve_stream
73
74 def tracked_stream(**kwargs):
75 try:
76 return original_stream(**kwargs)
77 finally:
78 stream_finished.set()
79
80 def tracked_run(**kwargs):
81 try:
82 return original_run(**kwargs)
83 finally:
84 finished.set()
85
86 monkeypatch.setattr(pipeline, "run", tracked_run)
87 monkeypatch.setattr(pipeline, "_retrieve_stream", tracked_stream)
88 monkeypatch.setattr(pipeline.x_api, "search_x", topic_search)
89 monkeypatch.setattr(pipeline.x_api, "search_handles", from_search)
90 monkeypatch.setattr(pipeline.x_api, "search_mentions", about_search)
91 start = time.monotonic()
92 try:
93 result = pipeline.enrich_nominations(
94 [pipeline.Nomination(name=topic, seed_score=1)],
95 config={"X_BEARER_TOKEN": "dummy", "LAST30DAYS_X_BACKEND": "xapi"},
96 depth="default", requested_sources=["x"], budget_seconds=1 if expired else 5,
97 max_workers=1,
98 )
99 elapsed = time.monotonic() - start
100 finally:
101 release.set()
102 assert finished.wait(5), "the actual abandoned pipeline worker must finish"
103 assert stream_finished.wait(5), "the in-flight stream must finish before checking for late requests"
104 if expired:
105 assert elapsed < 2
106 assert result[0].error == "enrichment budget exhausted"
107 assert calls == ["topic"], f"new adapter requests after return: {calls}"
108 else:
109 assert result[0].report is not None and result[0].error is None
110 assert "FROM" in calls and "ABOUT" in calls
111
112
113 @pytest.mark.parametrize("stop", ["cancel", "deadline"])
114 def test_x_failover_stops_after_inflight_backend(monkeypatch, x_run, stop):
115 topic, _, plan, runtime = x_run
116 cancel = threading.Event()
117 config = {"_enrich_cancel": cancel, "_research_deadline": time.monotonic() + 10}
118 calls = []
119
120 def first(*args, **kwargs):
121 calls.append("xapi")
122 if stop == "cancel":
123 cancel.set()
124 else:
125 config["_research_deadline"] = time.monotonic() - 1
126 return {"items": []}
127
128 monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["xapi", "xquik"])
129 monkeypatch.setattr(pipeline.x_api, "search_x", first)
130 monkeypatch.setattr(pipeline.xquik, "search_xquik", lambda *a, **k: calls.append("xquik") or {"items": []})
131 try:
132 pipeline._retrieve_stream_impl(
133 topic=topic, subquery=plan.subqueries[0], source="x", config=config,
134 depth="quick", date_range=dates.get_date_range(30), runtime=runtime, mock=False,
135 )
136 except pipeline.SourceRunError:
137 pass
138 assert calls == ["xapi"]
139
140
141 @pytest.mark.parametrize("backend", ["xapi", "bird", "xquik", "grok"])
142 def test_supplemental_stops_between_lanes(monkeypatch, x_run, backend):
143 topic, _, plan, runtime = x_run
144 runtime = replace(runtime, x_search_backend=backend)
145 cancel = threading.Event()
146 calls = []
147 adapter = {"xapi": pipeline.x_api, "bird": pipeline.bird_x,
148 "xquik": pipeline.xquik, "grok": pipeline.grok_x}[backend]
149
150 def from_search(*args, **kwargs):
151 calls.append("FROM")
152 cancel.set()
153 return ([], False) if backend == "grok" else []
154
155 def about_search(*args, **kwargs):
156 calls.append("ABOUT")
157 return ([], False) if backend == "grok" else []
158
159 monkeypatch.setattr(adapter, "search_handles", from_search)
160 monkeypatch.setattr(adapter, "search_mentions", about_search)
161 monkeypatch.setattr(pipeline.grok_x, "search_name", lambda *a, **k: calls.append("NAME") or ([], False))
162 pipeline._run_supplemental_searches(
163 topic=topic, bundle=schema.RetrievalBundle(), plan=plan,
164 config={"_enrich_cancel": cancel, "X_BEARER_TOKEN": "dummy", "XQUIK_API_KEY": "dummy"},
165 depth="default", date_range=dates.get_date_range(30), runtime=runtime, mock=False,
166 rate_limited_sources=set(), rate_limit_lock=threading.Lock(), x_handle="widget",
167 x_related=["related"],
168 )
169 assert calls == ["FROM"]
170
171
172 def test_enrichment_skips_queued_nomination_after_budget(monkeypatch, x_run):
173 topic, post, _, _ = x_run
174 release = threading.Event()
175 finished = threading.Event()
176 calls = []
177
178 def search(*args, **kwargs):
179 calls.append(args[1])
180 try:
181 assert release.wait(5)
182 return {"items": [post]}
183 finally:
184 finished.set()
185
186 monkeypatch.setattr(pipeline.x_api, "search_x", search)
187 try:
188 result = pipeline.enrich_nominations(
189 [pipeline.Nomination(name=name, seed_score=1) for name in (topic, "queued widget")],
190 config={"X_BEARER_TOKEN": "dummy"}, requested_sources=["x"],
191 max_workers=1, budget_seconds=1,
192 )
193 finally:
194 release.set()
195 assert finished.wait(5)
196 for thread in threading.enumerate():
197 if thread.name.startswith("discover-enrich-"):
198 thread.join(timeout=5)
199 assert not thread.is_alive()
200 assert calls == [topic]
201 assert all(entry.report is None and entry.error for entry in result)
202
203
204 @pytest.mark.parametrize("phase", ["stream", "discovery", "thin"])
205 def test_fanout_timeout_stops_late_x_failover(monkeypatch, x_run, phase):
206 topic, _, plan, runtime = x_run
207 release = threading.Event()
208 finished = threading.Event()
209 calls = []
210 original_stream = pipeline._retrieve_stream
211 original_discovery = pipeline._fetch_discovery_source
212
213 def stream(*args, **kwargs):
214 try:
215 return original_stream(*args, **kwargs)
216 finally:
217 finished.set()
218
219 def discovery(*args, **kwargs):
220 try:
221 return original_discovery(*args, **kwargs)
222 finally:
223 finished.set()
224
225 def search(*args, **kwargs):
226 calls.append("xapi")
227 assert release.wait(5)
228 return {"items": []}
229
230 monkeypatch.setattr(pipeline, "_retrieve_stream", stream)
231 monkeypatch.setattr(pipeline, "_fetch_discovery_source", discovery)
232 monkeypatch.setattr(pipeline.x_api, "search_x", search)
233 monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["xapi", "xquik"])
234 monkeypatch.setattr(pipeline.xquik, "search_xquik", lambda *a, **k: calls.append("xquik") or {"items": []})
235 for constant in ("STREAM_FUTURE_TIMEOUT_SECONDS", "DISCOVERY_FUTURE_TIMEOUT_SECONDS", "THIN_RETRY_FUTURE_TIMEOUT_SECONDS"):
236 monkeypatch.setattr(pipeline, constant, 0.05)
237 started = time.monotonic()
238 try:
239 if phase == "stream":
240 result = pipeline.run(topic=topic, config={"X_BEARER_TOKEN": "dummy"}, depth="quick", requested_sources=["x"])
241 elif phase == "discovery":
242 result = pipeline.nominate_candidates(
243 mock.Mock(domain=topic, sources=["x"]), from_date=dates.get_date_range(30)[0],
244 to_date=dates.get_date_range(30)[1], depth="quick", mock=False, config={}, lookback_days=30,
245 )
246 else:
247 result = schema.RetrievalBundle()
248 pipeline._retry_thin_sources(
249 topic=topic, bundle=result, plan=plan, config={}, depth="default",
250 date_range=dates.get_date_range(30), runtime=runtime, mock=False,
251 rate_limited_sources=set(), rate_limit_lock=threading.Lock(),
252 settings={"per_stream_limit": 6},
253 )
254 assert time.monotonic() - started < 1
255 assert result.source_status["x"].state == health.TIMEOUT
256 finally:
257 release.set()
258 assert finished.wait(5)
259 assert calls == ["xapi"]
260
261
262 def test_provider_scoring_does_not_start_after_cancelled_rerank(monkeypatch, x_run):
263 topic, post, _, _ = x_run
264 cancel = threading.Event()
265 calls = []
266 monkeypatch.setattr(pipeline.x_api, "search_x", lambda *a, **k: {"items": [post]})
267 original = pipeline.rerank.rerank_candidates
268
269 def rerank(**kwargs):
270 calls.append("rerank")
271 result = original(**kwargs)
272 cancel.set()
273 return result
274
275 monkeypatch.setattr(pipeline.rerank, "rerank_candidates", rerank)
276 monkeypatch.setattr(pipeline.rerank, "score_fun", lambda **k: calls.append("score"))
277 with pytest.raises(TimeoutError):
278 pipeline.run(topic=topic, config={"_enrich_cancel": cancel}, depth="quick", requested_sources=["x"])
279 assert "rerank" in calls and "score" not in calls
280
281
282 def test_planner_does_not_start_after_cancelled_source_resolution(monkeypatch, x_run):
283 topic, _, _, _ = x_run
284 cancel = threading.Event()
285 calls = []
286
287 def available(*args, **kwargs):
288 cancel.set()
289 return ["x"]
290
291 original = pipeline.planner.plan_query
292
293 def plan(**kwargs):
294 calls.append("planner")
295 return original(**kwargs)
296
297 monkeypatch.setattr(pipeline, "available_sources", available)
298 monkeypatch.setattr(pipeline.planner, "plan_query", plan)
299 with pytest.raises(TimeoutError):
300 pipeline.run(topic=topic, config={"_enrich_cancel": cancel}, depth="quick", requested_sources=["x"])
301 assert calls == []
302
303
304 @pytest.mark.parametrize("adapter", ["grok", "bird", "xquik", "xapi"])
305 def test_adapter_cancellation_stops_its_next_request(monkeypatch, adapter):
306 cancel = threading.Event()
307 calls = []
308
309 def request(*args, **kwargs):
310 calls.append(adapter)
311 cancel.set()
312 if adapter == "grok":
313 return {"error": "temporary transport failure"}
314 if adapter == "bird":
315 from lib.subproc import SubprocResult
316 return SubprocResult(0, "<html>interstitial</html>", ""), None
317 if adapter == "xapi":
318 return {
319 "data": [{"id": "1", "text": "Widget release", "created_at": dates.get_date_range(30)[1]}],
320 "meta": {"next_token": "next-page"},
321 }
322 return {"tweets": []}
323
324 if adapter == "grok":
325 monkeypatch.setattr(pipeline.grok_x, "_invoke", request)
326 result = pipeline.grok_x.search_x("widget compiler", *dates.get_date_range(30), cancel=cancel)
327 elif adapter == "bird":
328 monkeypatch.setattr(pipeline.bird_x, "_invoke_bird_subprocess", request)
329 result = pipeline.bird_x.search_x("widget compiler", *dates.get_date_range(30), cancel=cancel)
330 elif adapter == "xquik":
331 monkeypatch.setattr(pipeline.xquik.http, "get", request)
332 topic = "best widget compiler tools for incremental development"
333 assert len(pipeline.xquik.expand_xquik_queries(topic, "default")) > 1
334 result = pipeline.xquik.search_xquik(topic, *dates.get_date_range(30), token="dummy", cancel=cancel)
335 else:
336 monkeypatch.setattr(pipeline.x_api.http, "get", request)
337 result = pipeline.x_api.search_x("dummy", "widget compiler", *dates.get_date_range(30), cancel=cancel)
338 assert result["items"], "keep the completed page as partial evidence"
339 assert calls == [adapter]
340 assert result.get("error") or result.get("warning")
341
342
343 def test_http_cancellation_stops_retry_without_backoff(monkeypatch):
344 cancel = threading.Event()
345 calls = []
346
347 def request(*args, **kwargs):
348 calls.append("request")
349 cancel.set()
350 raise urllib.error.HTTPError("https://example.invalid", 503, "temporarily unavailable", {}, None)
351
352 monkeypatch.setattr(http.urllib.request, "urlopen", request)
353 started = time.monotonic()
354 with pytest.raises(http.DeadlineExceeded):
355 http.get("https://example.invalid", retries=3, cancel=cancel)
356 assert time.monotonic() - started < 0.5
357 assert calls == ["request"]
358
359
360 def test_http_cancellation_bounds_inflight_body_wait(monkeypatch):
361 cancel = threading.Event()
362 release = threading.Event()
363 finished = threading.Event()
364 calls = []
365 response = mock.MagicMock()
366 response.__enter__.return_value = response
367 response.status = 200
368
369 def read(size=-1):
370 calls.append("body")
371 cancel.set()
372 try:
373 assert release.wait(5)
374 return b'{"ok": true}'
375 finally:
376 finished.set()
377
378 response.read.side_effect = read
379 monkeypatch.setattr(http.urllib.request, "urlopen", lambda *a, **k: response)
380 started = time.monotonic()
381 try:
382 with pytest.raises(http.DeadlineExceeded):
383 http.get("https://example.invalid", retries=3, cancel=cancel)
384 assert time.monotonic() - started < 0.5
385 assert not finished.is_set(), "the caller must stop waiting while the body read remains blocked"
386 finally:
387 release.set()
388 assert finished.wait(5)
389 assert calls == ["body"]
390
391
392 @pytest.mark.parametrize("outcome", ["cancelled", "partial", "empty"])
393 def test_xquik_final_query_preserves_stop_status_and_items(monkeypatch, outcome):
394 cancel = threading.Event()
395 tweet = {"id": "123", "text": "Widget release", "author": {"username": "widget"}}
396
397 def request(*args, **kwargs):
398 if outcome != "empty":
399 cancel.set()
400 if outcome == "cancelled":
401 raise http.DeadlineExceeded()
402 return {"tweets": [tweet] if outcome == "partial" else []}
403
404 monkeypatch.setattr(pipeline.xquik.http, "get", request)
405 result = pipeline.xquik.search_xquik("Widget", *dates.get_date_range(30), depth="quick", token="dummy", cancel=cancel)
406 if outcome == "empty":
407 assert result == {"items": []}
408 else:
409 assert "timed out" in result.get("error", "")
410 assert len(result["items"]) == (1 if outcome == "partial" else 0)
411
412
413 def test_sole_xquik_backend_reports_cancelled_final_request(monkeypatch, x_run):
414 topic, _, plan, runtime = x_run
415 cancel = threading.Event()
416
417 def request(*args, **kwargs):
418 cancel.set()
419 raise http.DeadlineExceeded()
420
421 monkeypatch.setattr(pipeline.xquik.http, "get", request)
422 monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["xquik"])
423 with pytest.raises(pipeline.SourceRunError) as caught:
424 pipeline._retrieve_stream_impl(
425 topic=topic, subquery=plan.subqueries[0], source="x",
426 config={"XQUIK_API_KEY": "dummy", "_enrich_cancel": cancel},
427 depth="quick", date_range=dates.get_date_range(30),
428 runtime=replace(runtime, x_search_backend="xquik"), mock=False,
429 )
430 assert caught.value.outcome_state == health.TIMEOUT
431
432
433 def test_grok_retains_items_and_reports_cancelled_fanout(monkeypatch):
434 cancel = threading.Event()
435
436 def invoke(*args, **kwargs):
437 cancel.set()
438 return {"text": "id: 2087568620465607078\nhandle: widget\ncreated_at: Wed, 12 Aug 2026 15:55:18 GMT\nlikes: 10\ntext: Widget compiler release\n"}
439
440 monkeypatch.setattr(pipeline.grok_x, "_invoke", invoke)
441 result = pipeline.grok_x.search_x("Widget compiler", "2026-07-14", "2026-08-13", cancel=cancel)
442 assert result["items"], "the completed query remains useful partial evidence"
443 assert "timed out" in result.get("error", "")
444
445
446 @pytest.mark.parametrize("cancelled", [True, False])
447 def test_grok_final_empty_query_reports_cancellation(monkeypatch, cancelled):
448 cancel = threading.Event()
449
450 def invoke(*args, **kwargs):
451 if cancelled:
452 cancel.set()
453 return {"text": "No matching posts found."}
454
455 monkeypatch.setattr(pipeline.grok_x, "_invoke", invoke)
456 result = pipeline.grok_x.search_x("Widget", "2026-07-14", "2026-08-13", depth="quick", cancel=cancel)
457 if cancelled:
458 assert "timed out" in result.get("error", "")
459 else:
460 assert result == {"items": []}
461
462
463 def test_grok_partial_cancellation_keeps_revoked_session_reason(monkeypatch):
464 cancel = threading.Event()
465 calls = []
466
467 def invoke(*args, **kwargs):
468 calls.append("invoke")
469 if len(calls) == 1:
470 return {"text": "id: 2087568620465607078\nhandle: widget\ncreated_at: Wed, 12 Aug 2026 15:55:18 GMT\nlikes: 10\ntext: Widget compiler release\n"}
471 cancel.set()
472 return {"error": "Grok session expired", "auth_revoked": True}
473
474 monkeypatch.setattr(pipeline.grok_x, "_invoke", invoke)
475 items, error = pipeline._fetch_x_backend(
476 "grok", "Widget compiler", "2026-07-14", "2026-08-13", "default",
477 {"_enrich_cancel": cancel},
478 )
479 assert len(items) == 1
480 assert "session expired" in error
481 assert "timed out" not in error
482
483
484 @pytest.mark.parametrize("partial", [True, False])
485 def test_grok_short_remaining_budget_reports_timeout(monkeypatch, partial):
486 now = [100.0]
487 deadline = 120.0 if partial else 105.0
488 calls = []
489
490 def invoke(*args, **kwargs):
491 calls.append("invoke")
492 now[0] = 116.0
493 return {"text": "id: 2087568620465607078\nhandle: widget\ncreated_at: Wed, 12 Aug 2026 15:55:18 GMT\nlikes: 10\ntext: Widget compiler release\n"}
494
495 monkeypatch.setattr(pipeline.grok_x.time, "monotonic", lambda: now[0])
496 monkeypatch.setattr(pipeline.grok_x, "_invoke", invoke)
497 monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["grok"])
498 kwargs = dict(
499 topic="Widget", subquery=schema.SubQuery(label="primary", search_query="Widget", ranking_query="Widget", sources=["x"]),
500 source="x", config={"_research_deadline": deadline}, depth="default",
501 date_range=("2026-07-14", "2026-08-13"), mock=False,
502 runtime=schema.ProviderRuntime(reasoning_provider="native", planner_model="", rerank_model="", x_search_backend="grok"),
503 )
504 if partial:
505 items, artifact = pipeline._retrieve_stream(**kwargs)
506 assert len(items) == 1
507 assert artifact["_source_outcome"]["state"] == health.TIMEOUT
508 assert calls == ["invoke"]
509 else:
510 with pytest.raises(pipeline.SourceRunError) as caught:
511 pipeline._retrieve_stream(**kwargs)
512 assert caught.value.outcome_state == health.TIMEOUT
513 assert calls == []
514 assert now[0] < deadline
515
516
517 @pytest.mark.parametrize("failure", ["exception", "outcome"])
518 def test_rate_limit_stops_queued_streams_before_fanout_finishes(monkeypatch, x_run, failure):
519 topic, _, plan, _ = x_run
520 plan.subqueries = [replace(plan.subqueries[0], label=f"query-{index}") for index in range(6)]
521 calls = []
522 lock = threading.Lock()
523
524 def request(*args, **kwargs):
525 with lock:
526 index = len(calls)
527 calls.append(index)
528 if index == 0:
529 # Hold the 429 until the other in-flight streams are waiting on
530 # this same request in the run's fetch memo.
531 threading.Event().wait(0.3)
532 if failure == "exception":
533 raise http.HTTPError("Rate limit exceeded", status_code=429)
534 return {"items": [], "error": "xapi: rate limited (429)"}
535 return {"items": []}
536
537 monkeypatch.setattr(pipeline.x_api, "search_x", request)
538 report = pipeline.run(
539 topic=topic, config={"X_BEARER_TOKEN": "dummy", "_max_source_fetches": 6},
540 depth="quick", requested_sources=["x"], internal_subrun=True,
541 )
542 # Every stream searches the same raw topic: in-flight streams share the
543 # one request and its 429, and queued streams see the rate-limit signal.
544 assert calls == [0], "X streams must share the rate-limited request, not repeat it"
545 assert report.source_status["x"].state == health.RATE_LIMITED
546
546 lines PYTHON