返回 last30days-skill
test_timeout_architecture.py
根目录 / tests / test_timeout_architecture.py
1 """Timeout architecture: shared X-chain deadline and bounded stream waits."""
2
3 from concurrent.futures import Future
4 from contextlib import contextmanager
5 import queue
6 import threading
7 import time
8 from types import SimpleNamespace
9 from unittest import mock
10 from uuid import uuid4
11
12 import pytest
13
14 from lib import health, http, pipeline, render, schema, xai_x
15
16
17 def test_stream_timeouts_are_bounded():
18 for name in (
19 "STREAM_FUTURE_TIMEOUT_SECONDS",
20 "DISCOVERY_FUTURE_TIMEOUT_SECONDS",
21 "THIN_RETRY_FUTURE_TIMEOUT_SECONDS",
22 "X_CHAIN_DEADLINE_SECONDS",
23 ):
24 value = getattr(pipeline, name)
25 assert 0 < value <= 600, f"{name}={value} must be a finite wall-clock bound"
26
27
28 def test_background_deep_research_outlives_standard_stream_deadline(monkeypatch):
29 clock = 0.0
30 submitted = {}
31 expired = {}
32
33 class StreamFuture(Future):
34 def __init__(self, source):
35 super().__init__()
36 self.source = source
37
38 def cancel(self):
39 expired[self.source] = clock
40 return super().cancel()
41
42 class SimulatedExecutor:
43 def submit(self, fn, **kwargs):
44 source = kwargs["source"]
45 assert source not in submitted
46 submitted[source] = kwargs["config"]["_research_deadline"]
47 return StreamFuture(source)
48
49 @contextmanager
50 def executor(max_workers):
51 yield SimulatedExecutor()
52
53 def wait(futures, *, timeout, return_when):
54 nonlocal clock
55 clock += timeout
56 done = set()
57 for future in futures:
58 if future.source == "perplexity" and clock >= 200:
59 future.set_result((
60 [{
61 "title": "Deadline probe results",
62 "url": "https://example.test/deadline-probe",
63 "date": "2026-08-15",
64 "snippet": "The deadline probe completed after 200 seconds.",
65 }],
66 {"label": "perplexity", "responseId": "deep-complete"},
67 ))
68 done.add(future)
69 return done, futures - done
70
71 monkeypatch.setattr(pipeline, "time", SimpleNamespace(monotonic=lambda: clock))
72 monkeypatch.setattr(pipeline, "_abandoning_executor", executor)
73 monkeypatch.setattr(pipeline, "futures_wait", wait)
74 report = pipeline.run(
75 topic="deadline probe",
76 config={"_deep_research": True, "PERPLEXITY_API_KEY": "dummy"},
77 depth="quick",
78 requested_sources=["reddit", "perplexity"],
79 mock=True,
80 web_backend="none",
81 as_of_date="2026-08-31",
82 )
83
84 assert report.source_status["reddit"].state == health.TIMEOUT
85 assert expired == {"reddit": 180}
86 assert submitted == {"reddit": 180, "perplexity": 600}
87 assert report.source_status["perplexity"].state == health.OK
88 assert [item.url for item in report.items_by_source["perplexity"]] == [
89 "https://example.test/deadline-probe",
90 ]
91 assert any(
92 item.get("responseId") == "deep-complete"
93 for item in report.artifacts["grounding"]
94 )
95
96
97 def test_fetch_x_backend_forwards_deadline(monkeypatch):
98 seen = {}
99 monkeypatch.setattr(
100 pipeline.grok_x, "search_x",
101 lambda *a, **k: (seen.update(grok=k.get("deadline")), {"items": []})[1],
102 )
103 monkeypatch.setattr(
104 pipeline.xai_x, "search_x",
105 lambda *a, **k: (seen.update(xai=k.get("deadline_monotonic")), {"items": []})[1],
106 )
107 monkeypatch.setattr(pipeline.xai_x, "parse_x_response", lambda *a, **k: [])
108 monkeypatch.setattr(
109 pipeline.xquik, "search_xquik",
110 lambda *a, **k: (seen.update(xquik=k.get("deadline")), {"items": []})[1],
111 )
112 monkeypatch.setattr(pipeline.xquik, "parse_xquik_response", lambda r: [])
113 monkeypatch.setattr(
114 pipeline.x_api, "search_x",
115 lambda *a, **k: (seen.update(xapi=k.get("deadline")), {"items": []})[1],
116 )
117 monkeypatch.setattr(
118 pipeline.bird_x, "search_x",
119 lambda *a, **k: (seen.update(bird=k.get("deadline")), {"items": [], "error": ""})[1],
120 )
121 monkeypatch.setattr(pipeline.bird_x, "parse_bird_response", lambda *a, **k: [])
122 monkeypatch.setattr(
123 pipeline.xurl_x, "search_x",
124 lambda *a, **k: (seen.update(xurl=k.get("deadline")), {"items": [], "error": ""})[1],
125 )
126 monkeypatch.setattr(pipeline.xurl_x, "parse_x_response", lambda *a, **k: [])
127 deadline = time.monotonic() + 90
128 cfg = {"XAI_API_KEY": "k", "X_BEARER_TOKEN": "b"}
129 monkeypatch.setattr(pipeline.env, "get_xquik_token", lambda c: "q")
130 pipeline._fetch_x_backend("grok", "q", "2026-08-01", "2026-08-31", "quick", cfg, deadline=deadline)
131 assert seen["grok"] == deadline
132 pipeline._fetch_x_backend("xai", "q", "2026-08-01", "2026-08-31", "quick", cfg, deadline=deadline)
133 assert seen["xai"] == deadline
134 pipeline._fetch_x_backend("xquik", "q", "2026-08-01", "2026-08-31", "quick", cfg, deadline=deadline)
135 assert seen["xquik"] == deadline
136 pipeline._fetch_x_backend("xapi", "q", "2026-08-01", "2026-08-31", "quick", cfg, deadline=deadline)
137 assert seen["xapi"] == deadline
138 pipeline._fetch_x_backend("bird", "q", "2026-08-01", "2026-08-31", "quick", cfg, deadline=deadline)
139 assert seen["bird"] == deadline
140 pipeline._fetch_x_backend("xurl", "q", "2026-08-01", "2026-08-31", "quick", cfg, deadline=deadline)
141 assert seen["xurl"] == deadline
142
143
144 def test_x_chain_skips_past_deadline(monkeypatch):
145 monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["xapi", "xquik"])
146 calls = []
147 monkeypatch.setattr(
148 pipeline, "_fetch_x_backend",
149 lambda *a, **k: (calls.append(a[0]), ([], "boom"))[1],
150 )
151 # First monotonic() call sets the deadline, the second (chain check) is past it.
152 monkeypatch.setattr(
153 pipeline.time, "monotonic",
154 mock.Mock(side_effect=[1000.0, 2000.0, 2000.0]),
155 )
156 plan = mock.Mock()
157 plan.domain = "topic"
158 items, err = pipeline._fetch_discovery_source(
159 "x", plan, from_date="2026-08-01", to_date="2026-08-31",
160 depth="quick", mock=False, config={}, keyword_gate=True,
161 )
162 assert items == []
163 assert "budget exhausted" in (err or "")
164 assert calls == [], "no backend may start past the shared deadline"
165
166
167 def test_enrich_cancel_skips_network(monkeypatch):
168 cancel = threading.Event()
169 cancel.set()
170 subquery = schema.SubQuery(
171 label="primary", search_query="topic",
172 ranking_query="topic", sources=["reddit"], weight=1.0,
173 )
174 items, artifact = pipeline._retrieve_stream_impl(
175 topic="topic", subquery=subquery, source="reddit",
176 config={"_enrich_cancel": cancel}, depth="quick",
177 date_range=("2026-08-01", "2026-08-31"),
178 runtime=mock.Mock(), mock=True,
179 )
180 assert items == []
181 assert artifact["_source_outcome"]["state"] == health.TIMEOUT
182 assert artifact["_source_outcome"]["attempted"] is False
183
184
185 def test_enrich_cancel_skips_real_transport(monkeypatch):
186 """Same early exit with mock=False: no transport call may fire."""
187 cancel = threading.Event()
188 cancel.set()
189 monkeypatch.setattr(
190 pipeline.grounding, "web_search",
191 mock.Mock(side_effect=AssertionError("transport must not fire")),
192 )
193 subquery = schema.SubQuery(
194 label="primary", search_query="topic",
195 ranking_query="topic", sources=["grounding"], weight=1.0,
196 )
197 items, artifact = pipeline._retrieve_stream_impl(
198 topic="topic", subquery=subquery, source="grounding",
199 config={"_enrich_cancel": cancel}, depth="quick",
200 date_range=("2026-08-01", "2026-08-31"),
201 runtime=mock.Mock(), mock=False,
202 )
203 assert items == []
204 assert artifact["_source_outcome"]["state"] == health.TIMEOUT
205 assert artifact["_source_outcome"]["attempted"] is False
206 assert pipeline.grounding.web_search.call_count == 0
207
208
209 def test_discovery_timeout_records_timeout_partial(monkeypatch):
210 monkeypatch.setattr(pipeline, "DISCOVERY_FUTURE_TIMEOUT_SECONDS", 0.05)
211 def slow(*a, **k):
212 time.sleep(0.4)
213 return [], None
214 monkeypatch.setattr(pipeline, "_fetch_discovery_source", slow)
215 plan = mock.Mock()
216 plan.sources = ["reddit"]
217 plan.domain = "topic"
218 start = time.monotonic()
219 bundle = pipeline.nominate_candidates(
220 plan, from_date="2026-08-01", to_date="2026-08-31",
221 depth="quick", mock=False, config={}, lookback_days=30,
222 )
223 elapsed = time.monotonic() - start
224 assert elapsed < 1.5, f"hung lane must not stall nominate (took {elapsed:.2f}s)"
225 outcome = bundle.source_status["reddit"]
226 assert outcome.state == health.TIMEOUT
227
228
229 def test_xai_single_attempt_with_deadline(monkeypatch):
230 seen = {}
231 def fake_post(url, payload, headers=None, **kwargs):
232 seen.update(kwargs)
233 return {"output": []}
234 monkeypatch.setattr(pipeline.xai_x.http, "post", fake_post)
235 deadline = time.monotonic() + 90
236 xai_x.search_x("k", "m", "topic", "2026-08-01", "2026-08-31", deadline_monotonic=deadline)
237 assert seen.get("retries") == 1
238 assert seen.get("deadline_monotonic") == deadline
239
240
241 def test_bird_clamps_timeout_to_remaining_deadline(monkeypatch):
242 from lib import bird_x
243 seen = []
244 monkeypatch.setattr(
245 bird_x, "_run_bird_search",
246 lambda q, count, timeout, deadline=None, top=False: (seen.append(timeout), {"items": [], "error": ""})[1],
247 )
248 monkeypatch.setattr(bird_x, "parse_bird_response", lambda *a, **k: [])
249 bird_x.search_x("topic", "2026-08-01", "2026-08-31", depth="default",
250 deadline=time.monotonic() + 5)
251 assert seen, "at least the first search must run"
252 assert all(t <= 5 for t in seen), f"per-attempt timeouts must fit the budget: {seen}"
253
254
255 def test_bird_skips_subprocess_past_deadline(monkeypatch):
256 from lib import bird_x
257 calls = []
258 monkeypatch.setattr(
259 bird_x, "_run_bird_search",
260 lambda *a, **k: (calls.append(a), {"items": [], "error": ""})[1],
261 )
262 result = bird_x.search_x("topic", "2026-08-01", "2026-08-31",
263 deadline=time.monotonic() - 1)
264 assert calls == []
265 assert "budget exhausted" in result.get("error", "")
266
267
268 def test_xurl_skips_subprocess_past_deadline(monkeypatch):
269 from lib import xurl_x
270 calls = []
271 monkeypatch.setattr(
272 xurl_x.subprocess, "run",
273 lambda *a, **k: (calls.append(k.get("timeout")), mock.Mock(returncode=0, stdout="{}", stderr=""))[1],
274 )
275 result = xurl_x.search_x("topic", deadline=time.monotonic() - 1)
276 assert calls == []
277 assert "budget exhausted" in result.get("error", "")
278 xurl_x.search_x("topic", deadline=time.monotonic() + 5)
279 assert calls and calls[-1] <= 5
280
281
282 def test_grok_fanout_respects_cancel(monkeypatch):
283 from lib import grok_x
284 calls = []
285 monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
286 def fake_run(cmd, **kwargs):
287 import subprocess
288 calls.append(cmd)
289 return subprocess.CompletedProcess(cmd, 0, "no posts", "")
290 monkeypatch.setattr(grok_x.subproc, "run_with_timeout", fake_run)
291 cancel = threading.Event()
292 cancel.set()
293 result = grok_x.search_x("topic", "2026-08-01", "2026-08-31", cancel=cancel)
294 assert calls == [], "a cancelled fan-out must not start subprocesses"
295 assert result["items"] == []
296
297
298 def test_discovery_xapi_warning_reaches_bundle_artifact(monkeypatch):
299 monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["xapi"])
300 monkeypatch.setattr(
301 pipeline.x_api, "search_x",
302 lambda *a, **k: {"items": [{"id": "1"}], "warning": "window truncated to 7 days"},
303 )
304 plan = mock.Mock()
305 plan.domain = "topic"
306 warnings: list[str] = []
307 items, err = pipeline._fetch_discovery_source(
308 "x", plan, from_date="2026-08-01", to_date="2026-08-31",
309 depth="quick", mock=False, config={}, keyword_gate=True,
310 warnings=warnings,
311 )
312 assert items and err is None
313 assert warnings == ["X: xapi window truncated to 7 days"]
314
315
316 def test_nominate_surfaces_x_receipts_as_artifact(monkeypatch):
317 def fake_source(source, plan, **kwargs):
318 warnings = kwargs.get("warnings")
319 if warnings is not None:
320 warnings.extend(["X: xapi window truncated to 7 days"])
321 return [], None
322 monkeypatch.setattr(pipeline, "_fetch_discovery_source", fake_source)
323 plan = mock.Mock()
324 plan.sources = ["x"]
325 plan.domain = "topic"
326 bundle = pipeline.nominate_candidates(
327 plan, from_date="2026-08-01", to_date="2026-08-31",
328 depth="quick", mock=False, config={}, lookback_days=30,
329 )
330 assert bundle.artifacts.get("x_partial_coverage") == ["X: xapi window truncated to 7 days"]
331
332
333 def test_thin_retry_skipped_when_cancelled(monkeypatch):
334 cancel = threading.Event()
335 cancel.set()
336 calls = []
337 monkeypatch.setattr(
338 pipeline, "_retrieve_stream",
339 lambda **k: (calls.append(k.get("source")), ([], {}))[1],
340 )
341 bundle = schema.RetrievalBundle()
342 plan = mock.Mock()
343 plan.subqueries = [schema.SubQuery(
344 label="primary", search_query="Kanye West",
345 ranking_query="Kanye West", sources=["reddit"], weight=1.0,
346 )]
347 plan.freshness_mode = "breaking"
348 pipeline._retry_thin_sources(
349 topic="Kanye West", bundle=bundle, plan=plan,
350 config={"_enrich_cancel": cancel}, depth="default",
351 date_range=("2026-08-01", "2026-08-31"), runtime=mock.Mock(),
352 mock=False, rate_limited_sources=set(),
353 rate_limit_lock=threading.Lock(),
354 settings={"per_stream_limit": 6, "pool_limit": 15, "rerank_limit": 12},
355 )
356 assert calls == [], "no thin-retry fetch may start once cancelled"
357
358
359 def test_inline_retry_skipped_after_budget_expiry(monkeypatch):
360 monkeypatch.setattr(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 0.05)
361 retrieve_calls: list[str] = []
362 sleep_calls: list[float] = []
363 gate = threading.Event()
364 def fake_retrieve(**kwargs):
365 retrieve_calls.append(kwargs.get("source"))
366 if kwargs.get("source") == "reddit":
367 gate.wait(0.6)
368 return [], {}
369 raise http.HTTPError("Service unavailable", status_code=503)
370 monkeypatch.setattr(pipeline, "_retrieve_stream", fake_retrieve)
371 monkeypatch.setattr(time, "sleep", lambda s: sleep_calls.append(s))
372 report = pipeline.run(
373 topic="timeout probe",
374 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
375 depth="quick",
376 requested_sources=["reddit", "x"],
377 mock=True,
378 )
379 assert retrieve_calls.count("x") == 1, "a timed-out budget must not buy a retry"
380 assert sleep_calls == []
381 assert report is not None
382
383
384 def test_cancel_set_on_drain_failure(monkeypatch):
385 seen: dict = {}
386 def fake_run(**kwargs):
387 seen["cancel"] = kwargs["config"].get("_enrich_cancel")
388 return mock.Mock()
389 monkeypatch.setattr(pipeline, "run", fake_run)
390 orig_get = queue.Queue.get
391 first = {"done": False}
392 def flaky_get(self, *a, **k):
393 if not first["done"]:
394 first["done"] = True
395 raise RuntimeError("drain boom")
396 return orig_get(self, *a, **k)
397 monkeypatch.setattr(queue.Queue, "get", flaky_get)
398 nominations = [pipeline.Nomination(name="t", seed_score=1.0)]
399 with pytest.raises(RuntimeError, match="drain boom"):
400 pipeline.enrich_nominations(nominations, config={}, budget_seconds=5)
401 assert seen["cancel"] is not None and seen["cancel"].is_set()
402
403
404 # Hung-lane regressions: the worker blocks far past the budget, so a caller
405 # that still joins it on executor exit fails the elapsed bound.
406 HANG_SECONDS = 5.0
407 RETURN_BOUND_SECONDS = 1.5
408
409
410 def test_nominate_does_not_join_hung_lane(monkeypatch):
411 monkeypatch.setattr(pipeline, "DISCOVERY_FUTURE_TIMEOUT_SECONDS", 0.05)
412 release = threading.Event()
413 def hung(*a, **k):
414 release.wait(HANG_SECONDS)
415 return [], None
416 monkeypatch.setattr(pipeline, "_fetch_discovery_source", hung)
417 plan = mock.Mock()
418 plan.sources = ["reddit"]
419 plan.domain = "topic"
420 start = time.monotonic()
421 try:
422 bundle = pipeline.nominate_candidates(
423 plan, from_date="2026-08-01", to_date="2026-08-31",
424 depth="quick", mock=False, config={}, lookback_days=30,
425 )
426 elapsed = time.monotonic() - start
427 finally:
428 release.set()
429 assert elapsed < RETURN_BOUND_SECONDS, f"nominate joined the hung lane ({elapsed:.2f}s)"
430 assert bundle.source_status["reddit"].state == health.TIMEOUT
431
432
433 def test_nominate_drops_receipts_from_timed_out_x(monkeypatch):
434 monkeypatch.setattr(pipeline, "DISCOVERY_FUTURE_TIMEOUT_SECONDS", 0.05)
435 release = threading.Event()
436 def x_straggler(source, plan, **kwargs):
437 kwargs["warnings"].append("X: straggler receipt")
438 release.wait(HANG_SECONDS)
439 return [], None
440 monkeypatch.setattr(pipeline, "_fetch_discovery_source", x_straggler)
441 plan = mock.Mock()
442 plan.sources = ["x"]
443 plan.domain = "topic"
444 try:
445 bundle = pipeline.nominate_candidates(
446 plan, from_date="2026-08-01", to_date="2026-08-31",
447 depth="quick", mock=False, config={}, lookback_days=30,
448 )
449 finally:
450 release.set()
451 assert bundle.source_status["x"].state == health.TIMEOUT
452 assert "x_partial_coverage" not in bundle.artifacts
453
454
455 def test_run_does_not_join_hung_stream(monkeypatch):
456 monkeypatch.setattr(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 0.2)
457 release = threading.Event()
458 def fake_retrieve(**kwargs):
459 if kwargs.get("source") == "reddit":
460 release.wait(HANG_SECONDS)
461 return [], {}
462 monkeypatch.setattr(pipeline, "_retrieve_stream", fake_retrieve)
463 start = time.monotonic()
464 try:
465 report = pipeline.run(
466 topic="timeout probe",
467 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
468 depth="quick",
469 requested_sources=["reddit", "x"],
470 mock=True,
471 )
472 elapsed = time.monotonic() - start
473 finally:
474 release.set()
475 assert elapsed < RETURN_BOUND_SECONDS + 1.0, f"run() joined the hung stream ({elapsed:.2f}s)"
476 assert report.source_status["reddit"].state == health.TIMEOUT
477
478
479 def test_thin_retry_does_not_join_hung_retry(monkeypatch):
480 monkeypatch.setattr(pipeline, "THIN_RETRY_FUTURE_TIMEOUT_SECONDS", 0.05)
481 release = threading.Event()
482 def hung(**kwargs):
483 release.wait(HANG_SECONDS)
484 return [], {}
485 monkeypatch.setattr(pipeline, "_retrieve_stream", hung)
486 bundle = schema.RetrievalBundle()
487 plan = mock.Mock()
488 plan.subqueries = [schema.SubQuery(
489 label="primary", search_query="Kanye West",
490 ranking_query="Kanye West", sources=["reddit"], weight=1.0,
491 )]
492 plan.freshness_mode = "breaking"
493 start = time.monotonic()
494 try:
495 pipeline._retry_thin_sources(
496 topic="Kanye West", bundle=bundle, plan=plan,
497 config={}, depth="default",
498 date_range=("2026-08-01", "2026-08-31"), runtime=mock.Mock(),
499 mock=False, rate_limited_sources=set(),
500 rate_limit_lock=threading.Lock(),
501 settings={"per_stream_limit": 6, "pool_limit": 15, "rerank_limit": 12},
502 )
503 elapsed = time.monotonic() - start
504 finally:
505 release.set()
506 assert elapsed < RETURN_BOUND_SECONDS, f"thin retry joined the hung lane ({elapsed:.2f}s)"
507 assert bundle.source_status["reddit"].state == health.TIMEOUT
508
509
510 @pytest.mark.parametrize("stop_at", ["hashtag", "profile", "keyword", "transcript", "comments", "empty", "complete"])
511 def test_tiktok_budget_preserves_results_in_report(monkeypatch, stop_at):
512 """The lane must return its videos before the outer future discards them."""
513 from lib import tiktok
514
515 now = [1000.0]
516 calls = []
517 topic = "travel storytelling"
518 plan = schema.QueryPlan(
519 raw_topic=topic, intent="opinion", freshness_mode="balanced_recent",
520 cluster_mode="debate", source_weights={"tiktok": 1.0},
521 subqueries=[schema.SubQuery(
522 label="primary", search_query=topic, ranking_query=topic, sources=["tiktok"],
523 )],
524 )
525 runtime = schema.ProviderRuntime(
526 reasoning_provider="native", planner_model="", rerank_model="", x_search_backend="none",
527 )
528 raw = {
529 "aweme_id": "1", "desc": topic, "author": {"unique_id": "traveler"},
530 "statistics": {"play_count": 100},
531 }
532 endpoints = {
533 "hashtag": "/search/hashtag", "profile": "/profile/videos",
534 "keyword": "/search/keyword", "transcript": "/video/transcript",
535 "comments": "/video/comments", "empty": "/search/hashtag",
536 }
537
538 def fake_get(url, **kwargs):
539 calls.append((url, kwargs))
540 should_stop = url.endswith(endpoints.get(stop_at, "not-an-endpoint"))
541 if stop_at == "hashtag":
542 should_stop = should_stop and len(calls) == 2
543 if should_stop:
544 deadline = kwargs.get("deadline_monotonic")
545 # Without a shared deadline the request finishes after the stream cap.
546 now[0] = deadline if deadline is not None else 1007.0
547 raise http.DeadlineExceeded()
548 if url.endswith("/video/transcript"):
549 return {"transcript": "travel storytelling transcript"}
550 if url.endswith("/video/comments"):
551 return {"comments": [{"text": "great travel storytelling", "digg_count": 5}]}
552 return {"aweme_list": [raw], "search_item_list": [{"aweme_info": raw}]}
553
554 monkeypatch.setattr(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 6.0)
555 monkeypatch.setattr(pipeline.providers, "resolve_runtime", lambda *a: (runtime, None))
556 monkeypatch.setattr(pipeline, "available_sources", lambda *a, **k: ["tiktok"])
557 monkeypatch.setattr(pipeline.planner, "plan_query", lambda **k: plan)
558 monkeypatch.setattr(pipeline, "_retry_thin_sources", mock.Mock())
559 monkeypatch.setattr(tiktok.http, "get", fake_get)
560 monkeypatch.setattr(time, "monotonic", lambda: now[0])
561 cancel = threading.Event()
562 report = pipeline.run(
563 topic=topic, config={
564 "SCRAPECREATORS_API_KEY": "dummy-key",
565 "INCLUDE_SOURCES": "tiktok,tiktok_comments", "_enrich_cancel": cancel,
566 }, depth="quick", requested_sources=["tiktok"],
567 tiktok_hashtags=["travel", "slow", "unused"], tiktok_creators=["traveler"],
568 internal_subrun=True,
569 )
570 items = report.items_by_source.get("tiktok", [])
571 outcome = report.source_status["tiktok"]
572 if stop_at == "empty":
573 assert items == []
574 assert outcome.state == health.TIMEOUT
575 else:
576 assert len(items) == 1, "videos collected before the slow request must survive"
577 assert outcome.state == (health.OK if stop_at == "complete" else schema.PARTIAL)
578 if stop_at in ("comments", "complete"):
579 assert items[0].snippet == "travel storytelling transcript"
580 assert calls
581 assert all(call[1].get("deadline_monotonic") == 1005.0 for call in calls)
582 assert all(call[1].get("cancel") is cancel for call in calls)
583 if stop_at != "complete":
584 assert "timed out" in outcome.detail.lower()
585 expected_calls = {"empty": 1, "hashtag": 2, "profile": 4, "keyword": 5,
586 "transcript": 6, "comments": 7}
587 assert len(calls) == expected_calls[stop_at], "no new calls may start after the budget stop"
588 else:
589 assert report.errors_by_source == {}
590 assert items[0].metadata["top_comments"][0]["excerpt"] == "great travel storytelling"
591
592
593 def test_tiktok_returns_videos_before_stalled_transport_is_released(monkeypatch):
594 release = threading.Event()
595 transport_finished = threading.Event()
596 calls = []
597 raw = {"aweme_id": "1", "desc": "travel storytelling", "author": {"unique_id": "traveler"}}
598
599 def open_request(request, timeout):
600 calls.append(request.full_url)
601 response = mock.MagicMock()
602 response.__enter__.return_value = response
603 response.status = 200
604 if len(calls) == 1:
605 response.read.return_value = b'{"aweme_list": [{"aweme_id": "1", "desc": "travel storytelling", "author": {"unique_id": "traveler"}}]}'
606 else:
607 def held_read(size=-1):
608 try:
609 release.wait(HANG_SECONDS)
610 return b"{}"
611 finally:
612 transport_finished.set()
613 response.read.side_effect = held_read
614 return response
615
616 monkeypatch.setattr(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 2.0)
617 monkeypatch.setattr(http, "_open_request", open_request)
618 monkeypatch.setattr(pipeline.providers, "resolve_runtime", lambda *a: (
619 schema.ProviderRuntime(reasoning_provider="native", planner_model="", rerank_model=""), None,
620 ))
621 monkeypatch.setattr(pipeline, "available_sources", lambda *a, **k: ["tiktok"])
622 monkeypatch.setattr(pipeline.planner, "plan_query", lambda **k: schema.QueryPlan(
623 raw_topic=raw["desc"], intent="opinion", freshness_mode="balanced_recent",
624 cluster_mode="debate", source_weights={"tiktok": 1.0},
625 subqueries=[schema.SubQuery(label="primary", search_query=raw["desc"],
626 ranking_query=raw["desc"], sources=["tiktok"])],
627 ))
628 monkeypatch.setattr(pipeline, "_retry_thin_sources", mock.Mock())
629 try:
630 report = pipeline.run(
631 topic=raw["desc"], config={"SCRAPECREATORS_API_KEY": "dummy-key"}, depth="quick",
632 requested_sources=["tiktok"], tiktok_hashtags=["travel", "slow"], internal_subrun=True,
633 )
634 assert not release.is_set()
635 assert len(report.items_by_source.get("tiktok", [])) == 1
636 assert report.source_status["tiktok"].state == schema.PARTIAL
637 assert len(calls) == 2
638 finally:
639 release.set()
640 assert transport_finished.wait(2), "the held transport must finish before the test exits"
641
642
643 def _interstitial():
644 from lib.subproc import SubprocResult
645 return SubprocResult(returncode=0, stdout="<!DOCTYPE html><html>blocked</html>", stderr="")
646
647
648 def test_bird_decode_retry_skipped_when_delay_exceeds_budget(monkeypatch):
649 from lib import bird_x
650 timeouts, sleeps = [], []
651 monkeypatch.setattr(
652 bird_x, "_invoke_bird_subprocess",
653 lambda q, c, timeout, top=False, **_kwargs: (timeouts.append(timeout), (_interstitial(), None))[1],
654 )
655 monkeypatch.setattr(bird_x.time, "sleep", lambda s: sleeps.append(s))
656 response = bird_x._run_bird_search(
657 "q", count=10, timeout=60,
658 deadline=time.monotonic() + bird_x.JSON_DECODE_RETRY_DELAY - 2,
659 )
660 assert timeouts == [60] and sleeps == [], "no retry may start without budget for it"
661 assert "budget exhausted" in response["error"]
662 assert bird_x.classify_run_failure(response["error"]) == health.SCHEMA_DRIFT
663
664
665 def test_bird_decode_retry_reclamps_timeout_to_remaining_budget(monkeypatch):
666 from lib import bird_x
667 timeouts = []
668 monkeypatch.setattr(
669 bird_x, "_invoke_bird_subprocess",
670 lambda q, c, timeout, top=False, **_kwargs: (timeouts.append(timeout), (_interstitial(), None))[1],
671 )
672 monkeypatch.setattr(bird_x.time, "sleep", lambda s: None)
673 bird_x._run_bird_search("q", count=10, timeout=60, deadline=time.monotonic() + 30)
674 assert len(timeouts) == 2
675 assert timeouts[0] == 60 and timeouts[1] <= 30, f"retry must fit the budget: {timeouts}"
676
677
678 def test_bird_budget_stop_keeps_clean_empty_outcome(monkeypatch):
679 from lib import bird_x
680 deadline = time.monotonic() + 30
681 calls = []
682 def fake_run(query, count, timeout, deadline=None, top=False):
683 calls.append(query)
684 monkeypatch.setattr(bird_x.time, "monotonic", lambda: deadline + 1)
685 return {"items": []}
686 monkeypatch.setattr(bird_x, "_run_bird_search", fake_run)
687 response = bird_x.search_x(
688 "multi word agent topic", "2026-08-01", "2026-08-31", deadline=deadline,
689 )
690 assert len(calls) == 1, "zero-result retries must not start past the deadline"
691 assert response == {
692 "items": [],
693 "warning": "Partial coverage: optional zero-result retries skipped because the search budget was exhausted.",
694 }, f"clean no-results must carry a coverage warning without an error: {response}"
695
696
697 @pytest.mark.parametrize("entrypoint", ["research", "discovery"])
698 @pytest.mark.parametrize("outcome", ["budget-stop", "complete", "first-failure"])
699 def test_bird_budget_warning_reaches_report(monkeypatch, entrypoint, outcome):
700 topic = f"Widget compiler development {uuid4().hex}"
701 now = [1000.0]
702 calls = []
703 config = {
704 "LAST30DAYS_X_BACKEND": "bird", "AUTH_TOKEN": "dummy", "CT0": "dummy",
705 "_research_deadline": 1005.0,
706 }
707 plan = schema.QueryPlan(
708 raw_topic=topic, intent="opinion", freshness_mode="balanced_recent",
709 cluster_mode="debate", source_weights={"x": 1.0},
710 subqueries=[schema.SubQuery(
711 label="primary", search_query=topic, ranking_query=topic, sources=["x"],
712 )],
713 )
714 runtime = schema.ProviderRuntime(
715 reasoning_provider="native", planner_model="", rerank_model="",
716 x_search_backend="bird",
717 )
718
719 def bird_search(query, count, timeout, deadline=None, **kwargs):
720 calls.append((query, timeout, deadline))
721 if outcome != "complete":
722 now[0] = deadline - 0.5
723 if outcome == "first-failure":
724 return {"items": [], "error": "Invalid JSON response (anti-bot interstitial)"}
725 return {"items": []}
726
727 monkeypatch.setattr(pipeline.providers, "resolve_runtime", lambda *a: (runtime, None))
728 monkeypatch.setattr(pipeline, "available_sources", lambda *a, **k: ["x"])
729 monkeypatch.setattr(pipeline.env, "_x_backend_available", lambda backend, *a: backend == "bird")
730 monkeypatch.setattr(pipeline.planner, "plan_query", lambda **k: plan)
731 monkeypatch.setattr(pipeline.bird_x, "_run_bird_search", bird_search)
732 monkeypatch.setattr(time, "monotonic", lambda: now[0])
733 assert pipeline.env.x_backend_chain(config) == ["bird"]
734
735 if entrypoint == "discovery":
736 report = pipeline.run_discover(
737 domain=topic, config=config, depth="quick", requested_sources=["x"],
738 )
739 compact = render.render_discovery(report)
740 assert report.topics == []
741 else:
742 report = pipeline.run(
743 topic=topic, config=config, depth="quick", requested_sources=["x"],
744 internal_subrun=True,
745 )
746 compact = render.render_compact(report)
747 assert report.items_by_source.get("x", []) == []
748 if outcome == "first-failure":
749 assert "Invalid JSON response" in report.errors_by_source["x"]
750 else:
751 assert report.errors_by_source == {}
752
753 receipts = [warning for warning in report.warnings if "search budget" in warning]
754 if outcome == "budget-stop":
755 assert len(calls) == 1
756 assert calls[0][1:] == (5, 1005.0)
757 assert report.source_status["x"].state == schema.NO_RESULTS
758 assert receipts == [
759 "X: bird Partial coverage: optional zero-result retries skipped because the search budget was exhausted."
760 ]
761 assert receipts[0] in compact
762 elif outcome == "complete":
763 assert len(calls) > 1
764 assert report.source_status["x"].state == schema.NO_RESULTS
765 assert receipts == []
766 assert "search budget" not in compact
767 else:
768 assert len(calls) == 1
769 assert report.source_status["x"].state == health.SCHEMA_DRIFT
770 assert "Invalid JSON response" in report.source_status["x"].detail
771 assert receipts == []
772
772 lines PYTHON