返回 last30days-skill
test_source_outcomes.py
根目录 / tests / test_source_outcomes.py
1 import socket
2 import urllib.error
3 from types import SimpleNamespace
4 from unittest.mock import MagicMock, call, patch
5
6 import pytest
7
8 from lib import (
9 bird_x,
10 health,
11 http,
12 jobs,
13 pipeline,
14 reddit,
15 reddit_listing,
16 render,
17 schema,
18 youtube_yt,
19 )
20
21
22 def _report(*, source_status=None, items_by_source=None, errors_by_source=None):
23 return schema.Report(
24 topic="test topic",
25 range_from="2026-06-10",
26 range_to="2026-07-10",
27 generated_at="2026-07-10T18:22:03Z",
28 provider_runtime=schema.ProviderRuntime(
29 reasoning_provider="gemini",
30 planner_model="test-planner",
31 rerank_model="test-reranker",
32 ),
33 query_plan=schema.QueryPlan(
34 intent="general",
35 freshness_mode="balanced_recent",
36 cluster_mode="story",
37 raw_topic="test topic",
38 subqueries=[
39 schema.SubQuery(
40 label="primary",
41 search_query="test topic",
42 ranking_query="test topic",
43 sources=["x"],
44 )
45 ],
46 source_weights={"x": 1.0},
47 ),
48 clusters=[],
49 ranked_candidates=[],
50 items_by_source=items_by_source or {},
51 errors_by_source=errors_by_source or {},
52 source_status=source_status or {},
53 )
54
55
56 @pytest.mark.parametrize(
57 ("error", "expected"),
58 [
59 (http.HTTPError("HTTP 429", status_code=429), schema.RATE_LIMITED),
60 (http.HTTPError("HTTP 401", status_code=401), schema.AUTH_FAILED),
61 (http.HTTPError("HTTP 402", status_code=402), schema.PAYMENT_REQUIRED),
62 (http.HTTPError("HTTP 403", status_code=403), schema.AUTH_FAILED),
63 (http.HTTPError("Invalid JSON response"), schema.SCHEMA_DRIFT),
64 (http.HTTPError("Connection error: reset"), schema.UNREACHABLE),
65 (http.HTTPError("Request timed out"), health.TIMEOUT),
66 ],
67 )
68 def test_http_error_exposes_run_outcome_state(error, expected):
69 assert error.outcome_state == expected
70
71
72 @patch("lib.http.time.sleep")
73 @patch("lib.http.urllib.request.urlopen")
74 def test_http_wrapper_classifies_dns_failure(mock_urlopen, _mock_sleep):
75 mock_urlopen.side_effect = urllib.error.URLError(
76 socket.gaierror(-2, "Name or service not known")
77 )
78
79 with pytest.raises(http.HTTPError) as caught:
80 http.get("https://unreachable.example", retries=1)
81
82 assert caught.value.outcome_state == schema.UNREACHABLE
83
84
85 def test_source_specific_text_failures_are_mapped():
86 assert bird_x.classify_run_failure("likely Twitter anti-bot interstitial") == schema.SCHEMA_DRIFT
87 assert reddit.classify_run_failure("blocked by Reddit interstitial") == schema.RATE_LIMITED
88 assert youtube_yt.classify_run_failure("Sign in to confirm you're not a bot") == schema.RATE_LIMITED
89 assert youtube_yt.classify_run_failure("Search timed out after 1s") == health.TIMEOUT
90
91
92 def test_bundle_distinguishes_clean_no_results_from_failure():
93 clean = schema.RetrievalBundle()
94 clean.mark_attempted("x")
95
96 failed = schema.RetrievalBundle()
97 failed.mark_attempted("x")
98 failed.record_failure("x", schema.RATE_LIMITED, "HTTP 429")
99
100 assert clean.source_status["x"].state == schema.NO_RESULTS
101 assert failed.source_status["x"].state == schema.RATE_LIMITED
102 assert failed.source_status["x"].fix_hint == "doctor"
103
104
105 @patch("lib.http.urllib.request.urlopen")
106 def test_stream_adapter_recovers_http_failure_laundered_as_empty(mock_urlopen):
107 mock_urlopen.side_effect = urllib.error.HTTPError(
108 "https://api.example.com",
109 401,
110 "Unauthorized",
111 {},
112 None,
113 )
114
115 def source_that_launders_failure(*_args, **_kwargs):
116 try:
117 http.get("https://api.example.com", retries=1)
118 except http.HTTPError:
119 return [], {}
120 raise AssertionError("request should have failed")
121
122 with patch("lib.pipeline._retrieve_stream_impl", side_effect=source_that_launders_failure):
123 items, artifact = pipeline._retrieve_stream()
124
125 assert items == []
126 assert artifact["_source_outcome"]["state"] == schema.AUTH_FAILED
127
128
129 @patch("lib.http.time.sleep")
130 @patch("lib.http.urllib.request.urlopen")
131 def test_reddit_nested_worker_propagates_failure_capture(mock_urlopen, _mock_sleep):
132 mock_urlopen.side_effect = urllib.error.HTTPError(
133 "https://api.scrapecreators.com/v1/reddit/search",
134 429,
135 "Too Many Requests",
136 {},
137 None,
138 )
139
140 with http.capture_failures() as failures:
141 result = reddit.search_reddit(
142 "test topic",
143 "2026-06-10",
144 "2026-07-10",
145 depth="quick",
146 token="dummy-token",
147 )
148
149 assert result["items"] == []
150 assert failures[-1].outcome_state == schema.RATE_LIMITED
151
152
153 def _reddit_429(url="https://www.reddit.com/svc/shreddit/search/"):
154 return urllib.error.HTTPError(url, 429, "Too Many Requests", {}, None)
155
156
157 @patch("lib.http.time.sleep")
158 @patch("lib.http.urllib.request.urlopen")
159 def test_reddit_listing_fanout_propagates_failure_capture(mock_urlopen, _mock_sleep):
160 mock_urlopen.side_effect = _reddit_429(
161 "https://www.reddit.com/svc/shreddit/community-more-posts/hot/"
162 )
163
164 with http.capture_failures() as failures:
165 posts = reddit_listing.fetch_listings(["example"], depth="quick", query="test topic")
166
167 assert posts == []
168 assert failures[-1].outcome_state == schema.RATE_LIMITED
169
170
171 @patch("lib.http.time.sleep")
172 @patch("lib.http.urllib.request.urlopen")
173 def test_reddit_discovery_listing_fanout_propagates_failure_capture(mock_urlopen, _mock_sleep):
174 mock_urlopen.side_effect = _reddit_429(
175 "https://www.reddit.com/svc/shreddit/community-more-posts/rising/"
176 )
177
178 with http.capture_failures() as failures:
179 result = reddit_listing.fetch_discovery_listings(["example"], query="test topic")
180
181 assert result["items"] == []
182 # The discovery path reads this list, not the sink — a blocked feed must not
183 # look like an empty one there either.
184 assert result["errors"]
185 assert any("429" in error for error in result["errors"])
186 assert failures[-1].outcome_state == schema.RATE_LIMITED
187
188
189 @patch("lib.http.urllib.request.urlopen")
190 def test_tee_failures_does_not_hide_from_parent_sink(mock_urlopen):
191 # tee_failures must never become capture_failures: the latter replaces the
192 # sink, which would silently re-break the Reddit lanes above.
193 mock_urlopen.side_effect = urllib.error.HTTPError(
194 "https://api.example.com/missing", 404, "Not Found", {}, None
195 )
196
197 with http.capture_failures() as parent:
198 with http.tee_failures() as local:
199 with pytest.raises(http.HTTPError):
200 http.get("https://api.example.com/missing", retries=1)
201
202 assert len(local) == 1
203 assert local == parent
204
205
206 @patch("lib.http.urllib.request.urlopen")
207 def test_jobs_expected_probe_misses_do_not_degrade_final_result(mock_urlopen):
208 miss = urllib.error.HTTPError(
209 "https://boards-api.greenhouse.io/v1/boards/example/jobs",
210 404,
211 "Not Found",
212 {},
213 None,
214 )
215 success = MagicMock()
216 success.status = 200
217 success.read.return_value = (
218 b'{"jobs":[{"id":"1","title":"Engineer",'
219 b'"jobUrl":"https://jobs.ashbyhq.com/example/1"}]}'
220 )
221 success.__enter__.return_value = success
222 success.__exit__.return_value = False
223 mock_urlopen.side_effect = [miss, success]
224
225 with patch("lib.jobs._candidate_slugs", return_value=["example"]):
226 with http.capture_failures() as failures:
227 provider, slug, _ = jobs._probe_ats("Example")
228
229 assert provider == jobs.ATS_PROVIDER_ASHBY
230 assert slug == "example"
231 assert failures == []
232
233
234 @pytest.mark.parametrize(
235 ("source", "artifact", "expected"),
236 [
237 ("perplexity", {"error": "timeout"}, health.TIMEOUT),
238 (
239 "grounding",
240 {"reason": "keyless-search-unavailable"},
241 schema.UNREACHABLE,
242 ),
243 ],
244 )
245 def test_stream_adapter_converts_legacy_error_artifacts(source, artifact, expected):
246 with patch("lib.pipeline._retrieve_stream_impl", return_value=([], artifact)):
247 _, converted = pipeline._retrieve_stream(source=source)
248
249 assert converted["_source_outcome"]["state"] == expected
250
251
252 @pytest.mark.parametrize(
253 ("source", "detail", "expected"),
254 [
255 ("truthsocial", "Truth Social token expired", schema.AUTH_FAILED),
256 (
257 "bluesky",
258 "Cloudflare blocked the request (403 Forbidden). This is a network-level block, not an auth issue.",
259 schema.UNREACHABLE,
260 ),
261 ],
262 )
263 def test_legacy_result_uses_source_specific_outcome(source, detail, expected):
264 artifact = pipeline._result_outcome_artifact(source, {"error": detail})
265
266 assert artifact["_source_outcome"]["state"] == expected
267
268
269 def test_captured_http_failure_overrides_generic_artifact_error():
270 failure = http.HTTPError("HTTP 429: Too Many Requests", status_code=429)
271 outcome = pipeline._resolve_stream_outcome(
272 "tiktok",
273 pipeline._outcome_artifact(health.ERROR, "request failed"),
274 [failure],
275 )
276
277 assert outcome["state"] == schema.RATE_LIMITED
278
279
280 def test_bundle_records_items_then_429_as_partial():
281 item = schema.SourceItem(
282 item_id="x1",
283 source="x",
284 title="A post",
285 body="body",
286 url="https://x.com/example/status/1",
287 )
288 bundle = schema.RetrievalBundle()
289 bundle.mark_attempted("x")
290 bundle.add_items("primary", "x", [item])
291 bundle.record_failure("x", schema.RATE_LIMITED, "429 after first page")
292
293 outcome = bundle.source_status["x"]
294 assert outcome.state == schema.PARTIAL
295 assert outcome.items_returned == 1
296 assert outcome.detail == "429 after first page"
297
298
299 def test_pipeline_records_clean_empty_source_as_no_results():
300 plan = {
301 "intent": "general",
302 "freshness_mode": "balanced_recent",
303 "cluster_mode": "story",
304 "subqueries": [
305 {
306 "label": "primary",
307 "search_query": "test topic",
308 "ranking_query": "test topic",
309 "sources": ["x"],
310 }
311 ],
312 "source_weights": {"x": 1.0},
313 }
314 with patch("lib.pipeline._retrieve_stream", return_value=([], {})):
315 report = pipeline.run(
316 topic="test topic",
317 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
318 depth="quick",
319 requested_sources=["x"],
320 mock=True,
321 external_plan=plan,
322 )
323
324 assert report.source_status["x"].state == schema.NO_RESULTS
325 assert "x" not in report.errors_by_source
326
327
328 def _perplexity_plan():
329 return {
330 "intent": "general",
331 "freshness_mode": "balanced_recent",
332 "cluster_mode": "story",
333 "subqueries": [
334 {
335 "label": "primary",
336 "search_query": "test topic",
337 "ranking_query": "test topic",
338 "sources": ["perplexity"],
339 }
340 ],
341 "source_weights": {"perplexity": 1.0},
342 }
343
344
345 def test_pipeline_records_both_mode_semantic_leg_failure_as_partial():
346 raw_item = {
347 "id": "PXS1",
348 "title": "Search result",
349 "url": "https://example.com/result",
350 "snippet": "Raw search evidence",
351 # Inside the pinned as_of window below. A wall-clock relative date
352 # (today-5) falls outside 2026-07-21..2026-08-20 once the calendar
353 # moves past late August, and the failure then records as ERROR.
354 "date": "2026-08-15",
355 "relevance": 0.8,
356 "why_relevant": "Perplexity Search result",
357 "engagement": {},
358 }
359 artifact = {
360 "mode": "both",
361 "search": {"mode": "search"},
362 "agent": {
363 "error": "failed",
364 "agentErrorMessage": "Provider rejected synthesis",
365 },
366 "itemCount": 1,
367 }
368 with patch("lib.pipeline._retrieve_stream_impl", return_value=([raw_item], artifact)):
369 report = pipeline.run(
370 topic="test topic",
371 config={
372 "LAST30DAYS_REASONING_PROVIDER": "gemini",
373 "PERPLEXITY_API_KEY": "pplx-test",
374 },
375 depth="quick",
376 lookback_days=30,
377 as_of_date="2026-08-20",
378 requested_sources=["perplexity"],
379 mock=True,
380 external_plan=_perplexity_plan(),
381 )
382
383 assert report.range_from == "2026-07-21"
384 assert report.range_to == "2026-08-20"
385 outcome = report.source_status["perplexity"]
386 assert outcome.state == schema.PARTIAL
387 assert outcome.items_returned == 1
388 assert outcome.detail == "agent leg: Provider rejected synthesis"
389
390
391 def test_pipeline_records_both_mode_semantic_failure_without_items():
392 artifact = {
393 "mode": "both",
394 "search": {"mode": "search"},
395 "agent": {
396 "error": "failed",
397 "agentErrorMessage": "Provider rejected synthesis",
398 },
399 "itemCount": 0,
400 }
401 with patch("lib.pipeline._retrieve_stream_impl", return_value=([], artifact)):
402 report = pipeline.run(
403 topic="test topic",
404 config={
405 "LAST30DAYS_REASONING_PROVIDER": "gemini",
406 "PERPLEXITY_API_KEY": "pplx-test",
407 },
408 depth="quick",
409 requested_sources=["perplexity"],
410 mock=True,
411 external_plan=_perplexity_plan(),
412 )
413
414 outcome = report.source_status["perplexity"]
415 assert outcome.state == health.ERROR
416 assert outcome.items_returned == 0
417 assert outcome.detail == "agent leg: Provider rejected synthesis"
418
419
420 def test_pipeline_preserves_typed_http_failure():
421 plan = {
422 "intent": "general",
423 "freshness_mode": "balanced_recent",
424 "cluster_mode": "story",
425 "subqueries": [
426 {
427 "label": "primary",
428 "search_query": "test topic",
429 "ranking_query": "test topic",
430 "sources": ["x"],
431 }
432 ],
433 "source_weights": {"x": 1.0},
434 }
435 failure = http.HTTPError("HTTP 429: Too Many Requests", status_code=429)
436 with patch("lib.pipeline._retrieve_stream", side_effect=failure):
437 report = pipeline.run(
438 topic="test topic",
439 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
440 depth="quick",
441 requested_sources=["x"],
442 mock=True,
443 external_plan=plan,
444 )
445
446 assert report.source_status["x"].state == schema.RATE_LIMITED
447 assert report.source_status["x"].items_returned == 0
448 assert "x" in report.errors_by_source
449
450
451 def test_footer_and_synthesis_note_surface_failed_source():
452 report = _report(
453 source_status={
454 "x": schema.SourceOutcome(
455 source="x",
456 state=schema.RATE_LIMITED,
457 detail="HTTP 429 after retry budget",
458 fix_hint="doctor",
459 )
460 },
461 errors_by_source={"x": "HTTP 429 after retry budget"},
462 )
463
464 text = render.render_compact(report)
465
466 # A failed source that returned zero items is surfaced to synthesis via the
467 # evidence blocks (## Partial Coverage), NOT as a user-facing footer line -
468 # zero-item sources are dropped from the emoji tree (see test_render_footer).
469 assert "## Partial Coverage" in text
470 assert "A failed source is not evidence of no discussion" in text
471 assert "🔵 X: rate-limited: HTTP 429 after retry budget (run doctor for fixes)" not in text
472
473
474 def test_report_source_status_round_trips_through_schema_serialization():
475 report = _report(
476 source_status={
477 "x": schema.SourceOutcome(
478 source="x",
479 state=schema.PARTIAL,
480 items_returned=12,
481 detail="429 after 12 items",
482 at="2026-07-10T18:22:03Z",
483 fix_hint="doctor",
484 )
485 }
486 )
487
488 payload = schema.to_dict(report)
489 restored = schema.report_from_dict(payload)
490
491 assert payload["source_status"]["x"]["state"] == schema.PARTIAL
492 assert restored.source_status["x"] == report.source_status["x"]
493
494
495 # --- strict exit (LAST30DAYS_STRICT_EXIT, issue #384) ---
496
497 import last30days as cli
498
499
500 def _outcome(source, state, **kwargs):
501 return schema.SourceOutcome(source=source, state=state, **kwargs)
502
503
504 def test_strict_exit_disabled_by_default_even_when_degraded():
505 report = _report(
506 source_status={"x": _outcome("x", schema.RATE_LIMITED, detail="429")}
507 )
508 assert cli._strict_exit_code(report, None, {}) == 0
509
510
511 def test_strict_exit_returns_3_for_degraded_run(capsys):
512 report = _report(
513 source_status={"x": _outcome("x", schema.AUTH_FAILED, detail="401")}
514 )
515 rc = cli._strict_exit_code(report, None, {"LAST30DAYS_STRICT_EXIT": "1"})
516 assert rc == 3
517 assert "strict-exit: degraded sources: x" in capsys.readouterr().err
518
519
520 def test_strict_discovery_flushes_report_before_degraded_receipt(monkeypatch):
521 streams = MagicMock()
522 monkeypatch.setattr(cli, "sys", SimpleNamespace(stdout=streams.stdout, stderr=streams.stderr))
523 source_status = {"x": _outcome("x", schema.AUTH_FAILED)}
524 assert cli._discovery_strict_exit_code(source_status, {}) == 0
525 assert streams.mock_calls == []
526
527 assert cli._discovery_strict_exit_code(source_status, {"LAST30DAYS_STRICT_EXIT": "1"}) == 3
528 assert streams.mock_calls == [
529 call.stdout.flush(),
530 call.stderr.write("[last30days] strict-exit: degraded sources: x\n"),
531 call.stderr.flush(),
532 ]
533
534
535 def test_strict_exit_treats_payment_required_as_degraded(capsys):
536 report = _report(
537 source_status={
538 "x": _outcome("x", schema.PAYMENT_REQUIRED, detail="xapi: payment required")
539 }
540 )
541 rc = cli._strict_exit_code(report, None, {"LAST30DAYS_STRICT_EXIT": "1"})
542 assert rc == 3
543 assert "strict-exit: degraded sources: x" in capsys.readouterr().err
544
545
546 def test_strict_exit_clean_states_return_0():
547 report = _report(
548 source_status={
549 "reddit": _outcome("reddit", health.OK, items_returned=12),
550 "hn": _outcome("hn", schema.NO_RESULTS),
551 "tiktok": _outcome("tiktok", schema.SKIPPED_UNCONFIGURED, attempted=False),
552 }
553 )
554 assert cli._strict_exit_code(report, None, {"LAST30DAYS_STRICT_EXIT": "true"}) == 0
555
556
557 def test_strict_exit_checks_entity_reports_in_comparison_runs():
558 lead = _report(source_status={"reddit": _outcome("reddit", health.OK)})
559 entity = _report(
560 source_status={"x": _outcome("x", schema.UNREACHABLE, detail="dns")}
561 )
562 rc = cli._strict_exit_code(lead, [("other", entity)], {"LAST30DAYS_STRICT_EXIT": "on"})
563 assert rc == 3
564
565
566 def test_strict_exit_env_key_is_registered():
567 # Unregistered keys are silently dropped by env config loading (#707 class).
568 from lib import env as env_module
569 import inspect
570
571 assert "LAST30DAYS_STRICT_EXIT" in inspect.getsource(env_module)
572
573
574 def test_captured_failure_selection_prefers_most_specific():
575 auth = http.HTTPError("HTTP 401: Unauthorized", status_code=401)
576 rate = http.HTTPError("HTTP 429: Too Many Requests", status_code=429)
577 # Order must not matter: auth-failed wins over rate-limited either way.
578 for failures in ([auth, rate], [rate, auth]):
579 outcome = pipeline._resolve_stream_outcome("x", None, failures)
580 assert outcome["state"] == schema.AUTH_FAILED
581
582
583 def test_bundle_keeps_ok_with_lane_detail_across_subqueries():
584 """A swallowed lane failure on a source that delivered items stays ``ok``
585 and carries the loss as detail; a later clean subquery keeps that detail."""
586 item = schema.SourceItem(
587 item_id="r1",
588 source="reddit",
589 title="A thread",
590 body="body",
591 url="https://www.reddit.com/r/test/comments/abc/",
592 )
593 bundle = schema.RetrievalBundle()
594 bundle.mark_attempted("reddit")
595 bundle.record_detail("reddit", "3 sub-requests rate-limited (HTTP 429)")
596 bundle.add_items("primary", "reddit", [item])
597
598 outcome = bundle.source_status["reddit"]
599 assert outcome.state == health.OK
600 assert outcome.items_returned == 1
601 assert outcome.detail == "3 sub-requests rate-limited (HTTP 429)"
602 assert outcome.fix_hint is None
603
604 bundle.add_items("secondary", "reddit", [])
605 outcome = bundle.source_status["reddit"]
606 assert outcome.state == health.OK
607 assert outcome.detail == "3 sub-requests rate-limited (HTTP 429)"
608
609
610 def test_finalize_turns_an_empty_ok_source_with_lane_failures_into_that_failure():
611 """Zero items after filtering plus swallowed 429s is not 'completed cleanly
612 with zero matches'; it is the rate limit, so ## Partial Coverage fires and
613 doctor does not list the source as succeeded."""
614 bundle = schema.RetrievalBundle()
615 bundle.mark_attempted("polymarket")
616 bundle.record_detail("polymarket", "5 sub-requests rate-limited (HTTP 429)", state=schema.RATE_LIMITED)
617 bundle.add_items("primary", "polymarket", [])
618 finalized = pipeline._finalize_source_status(bundle.source_status, {"polymarket": []})
619 outcome = finalized["polymarket"]
620 assert outcome.state == schema.RATE_LIMITED
621 assert outcome.detail == "5 sub-requests rate-limited (HTTP 429)"
622 assert outcome.items_returned == 0
623
624
625 # --- payment-required: credit exhaustion is not an auth failure (KTD6) ---
626
627
628 def test_classify_failure_402_status_is_payment_required():
629 assert http.classify_failure(status_code=402) == schema.PAYMENT_REQUIRED
630 # A 402 with a non-JSON / empty body still classifies by status alone.
631 err = http.HTTPError("HTTP 402: Payment Required", 402, "<html>upgrade</html>")
632 assert err.outcome_state == schema.PAYMENT_REQUIRED
633
634
635 @pytest.mark.parametrize(
636 "message",
637 [
638 "Your enrolled account does not have any credits",
639 "insufficient credits",
640 "ScrapeCreators: Insufficient credits remaining",
641 "xapi: payment required (X API credits exhausted)",
642 "Xquik key unpaid: payment required (402)",
643 "You are out of credits for this billing period",
644 ],
645 )
646 def test_classify_failure_credit_exhaustion_markers(message):
647 assert http.classify_failure(message=message) == schema.PAYMENT_REQUIRED
648
649
650 def test_classify_failure_bare_word_credits_is_not_a_marker():
651 # The onboarding copy mentions "10,000 free credits"; a message that merely
652 # contains the word must not be branded as credit exhaustion.
653 state = http.classify_failure(message="Sign up for 10,000 free credits")
654 assert state != schema.PAYMENT_REQUIRED
655
656
657 @pytest.mark.parametrize("status", [401, 403])
658 def test_classify_failure_401_403_stay_auth_failed(status):
659 assert http.classify_failure(status_code=status) == schema.AUTH_FAILED
660 assert http.classify_failure(message=f"HTTP {status}: nope") == schema.AUTH_FAILED
661
662
663 def test_payment_required_wins_over_auth_marker_in_same_message():
664 # A credit-exhaustion message that also carries an auth word is about
665 # money, not identity: the payment branch runs before the 401/403 branch.
666 state = http.classify_failure(
667 status_code=403,
668 message="Forbidden: your enrolled account does not have any credits",
669 )
670 assert state == schema.PAYMENT_REQUIRED
671
672
673 def test_cross_source_insufficient_credits_reclassifies_from_error():
674 # ScrapeCreators-backed sources surface credit exhaustion as a plain
675 # legacy error string; the shared classifier now types it.
676 artifact = pipeline._result_outcome_artifact(
677 "tiktok", {"items": [], "error": "ScrapeCreators: insufficient credits"}
678 )
679 assert artifact["_source_outcome"]["state"] == schema.PAYMENT_REQUIRED
680 state, attempted = pipeline._classify_source_failure(
681 http.HTTPError("HTTP 402: insufficient credits", status_code=402)
682 )
683 assert (state, attempted) == (schema.PAYMENT_REQUIRED, True)
684
685
686 def test_captured_failure_selection_ranks_payment_required_above_rate_limit():
687 pay = http.HTTPError("HTTP 402: Payment Required", status_code=402)
688 rate = http.HTTPError("HTTP 429: Too Many Requests", status_code=429)
689 for failures in ([pay, rate], [rate, pay]):
690 outcome = pipeline._resolve_stream_outcome("x", None, failures)
691 assert outcome["state"] == schema.PAYMENT_REQUIRED
692
693
694 def test_lane_failure_summary_names_credit_exhaustion():
695 text = pipeline._summarize_lane_failures(
696 [http.HTTPError("HTTP 402: Payment Required", status_code=402)]
697 )
698 assert text == "1 sub-request credits exhausted (HTTP 402)"
699
700
701 def test_render_summary_labels_payment_required_per_source():
702 x_outcome = schema.SourceOutcome(
703 source="x", state=schema.PAYMENT_REQUIRED, detail="xapi: payment required"
704 )
705 other = schema.SourceOutcome(
706 source="tiktok", state=schema.PAYMENT_REQUIRED, detail="insufficient credits"
707 )
708 x_text = render._format_outcome(x_outcome)
709 assert x_text.startswith("X API credits exhausted")
710 assert "xapi: payment required" in x_text
711 assert render._format_outcome(other).startswith("credits exhausted")
712 # The Partial Coverage note carries the label too.
713 report = _report(source_status={"x": x_outcome, "tiktok": other})
714 note = "\n".join(render._render_source_outcome_note(report))
715 assert "X API credits exhausted" in note
716 assert "credits exhausted" in note
717
718
719 def test_postmortem_labels_payment_required():
720 from lib import doctor
721
722 pm = {
723 "engine_version": "test",
724 "mode": "postmortem",
725 "present": True,
726 "topic": "t",
727 "at": "2026-07-10T18:22:03Z",
728 "outcomes": {
729 "x": schema.to_dict(
730 schema.SourceOutcome(
731 source="x",
732 state=schema.PAYMENT_REQUIRED,
733 detail="xapi: payment required (X API credits exhausted)",
734 )
735 ),
736 "tiktok": schema.to_dict(
737 schema.SourceOutcome(
738 source="tiktok",
739 state=schema.PAYMENT_REQUIRED,
740 detail="insufficient credits",
741 )
742 ),
743 },
744 }
745 text = doctor.render_postmortem_text(pm)
746 assert "Failed:" in text
747 assert "x — X API credits exhausted" in text
748 assert "tiktok — credits exhausted" in text
749 assert "auth-failed" not in text
750
751
752 def test_json_export_carries_payment_required():
753 report = _report(
754 source_status={"x": _outcome("x", schema.PAYMENT_REQUIRED, detail="402")}
755 )
756 assert schema.to_agent_export(report)["source_status"]["x"] == "payment-required"
757 restored = schema.report_from_dict(schema.to_dict(report))
758 assert restored.source_status["x"].state == schema.PAYMENT_REQUIRED
759
759 lines PYTHON