| 1 | """Regression tests for PR 24: pipeline & schema budget, failover, and outcome integrity. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-025: finalization_deadline enforcement & live elapsed across Digg/Reddit/dev.to/Amazon |
| 5 | - HIGH-026: X failover preserves x_receipts, runs x_judge retry/pruning, ranks chain_errors by specificity |
| 6 | - HIGH-027: _attempt_x_backend classifies Bird errors with bird_x and catches non-HTTP exceptions |
| 7 | - HIGH-028: RetrievalBundle.record_failure specificity preservation, Phase 2 any_revoked short-circuit, |
| 8 | and xapi _guard_lane non-failure partial-coverage contract |
| 9 | - HIGH-029: Reddit ScrapeCreators backfill TimeoutError classification, _enrich_cancel wakeup, |
| 10 | and inner exception preservation |
| 11 | - HIGH-030: Proportional Reddit lane_deadline scaling prevents premature paid SC spend on <= 65s budgets |
| 12 | - HIGH-032: RetrievalBundle.add_items completion-order independence for promoted lane_state vs hard failures |
| 13 | """ |
| 14 | |
| 15 | from __future__ import annotations |
| 16 | |
| 17 | import threading |
| 18 | import time |
| 19 | from unittest import mock |
| 20 | |
| 21 | import pytest |
| 22 | |
| 23 | from lib import ( |
| 24 | amazon, |
| 25 | bird_x, |
| 26 | devto, |
| 27 | digg, |
| 28 | health, |
| 29 | http, |
| 30 | pipeline, |
| 31 | reddit, |
| 32 | reddit_keyless, |
| 33 | schema, |
| 34 | subproc, |
| 35 | x_api, |
| 36 | youtube_yt, |
| 37 | ) |
| 38 | |
| 39 | |
| 40 | def _source_item( |
| 41 | source: str, |
| 42 | item_id: str, |
| 43 | url: str, |
| 44 | *, |
| 45 | title: str = "Title", |
| 46 | body: str = "Body", |
| 47 | author: str = "alice", |
| 48 | engagement: dict | None = None, |
| 49 | metadata: dict | None = None, |
| 50 | ) -> schema.SourceItem: |
| 51 | return schema.SourceItem( |
| 52 | item_id=item_id, |
| 53 | source=source, |
| 54 | title=title, |
| 55 | body=body, |
| 56 | url=url, |
| 57 | author=author, |
| 58 | engagement=engagement or {}, |
| 59 | metadata=metadata or {}, |
| 60 | ) |
| 61 | |
| 62 | |
| 63 | def _x_post(post_id: str, text: str, author: str = "alice") -> dict: |
| 64 | return { |
| 65 | "id": post_id, |
| 66 | "text": text, |
| 67 | "url": f"https://x.com/{author}/status/{post_id}", |
| 68 | "author_handle": author, |
| 69 | "date": "2026-11-05", |
| 70 | "engagement": {"likes": 42, "reposts": 5, "replies": 3}, |
| 71 | "relevance": 0.9, |
| 72 | } |
| 73 | |
| 74 | |
| 75 | def _reddit_post(post_id: str, title: str = "Elon Musk discussion") -> dict: |
| 76 | return { |
| 77 | "id": post_id, |
| 78 | "title": title, |
| 79 | "url": f"https://www.reddit.com/r/elonmusk/comments/{post_id}/slug/", |
| 80 | "subreddit": "elonmusk", |
| 81 | "date": "2026-11-05", |
| 82 | "engagement": {"score": 50, "num_comments": 12}, |
| 83 | "relevance": 0.9, |
| 84 | "metadata": {"post_id": post_id}, |
| 85 | } |
| 86 | |
| 87 | |
| 88 | def _x_plan(topic: str = "AI safety") -> schema.QueryPlan: |
| 89 | return schema.QueryPlan( |
| 90 | intent="general", |
| 91 | freshness_mode="balanced_recent", |
| 92 | cluster_mode="story", |
| 93 | raw_topic=topic, |
| 94 | subqueries=[ |
| 95 | schema.SubQuery( |
| 96 | label="primary", |
| 97 | search_query=topic, |
| 98 | ranking_query=topic, |
| 99 | sources=["x"], |
| 100 | ) |
| 101 | ], |
| 102 | source_weights={"x": 1.0}, |
| 103 | ) |
| 104 | |
| 105 | |
| 106 | def _runtime(x_backend: str | None = None) -> schema.ProviderRuntime: |
| 107 | return schema.ProviderRuntime( |
| 108 | reasoning_provider="local", |
| 109 | planner_model="", |
| 110 | rerank_model="", |
| 111 | x_search_backend=x_backend, |
| 112 | ) |
| 113 | |
| 114 | |
| 115 | # --------------------------------------------------------------------------- |
| 116 | # HIGH-025: Post-ranking enrichments respect finalization_deadline & live elapsed |
| 117 | # --------------------------------------------------------------------------- |
| 118 | |
| 119 | |
| 120 | class TestHigh025FinalizationDeadline: |
| 121 | def test_expired_finalization_deadline_skips_digg_reddit_devto_amazon(self, monkeypatch): |
| 122 | now = [1000.0] |
| 123 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 124 | |
| 125 | calls: list[str] = [] |
| 126 | monkeypatch.setattr( |
| 127 | pipeline.digg, "enrich_source_items", |
| 128 | lambda *a, **k: calls.append("digg") or a[0], |
| 129 | ) |
| 130 | monkeypatch.setattr( |
| 131 | pipeline.devto, "enrich_source_items", |
| 132 | lambda *a, **k: calls.append("devto") or a[0], |
| 133 | ) |
| 134 | monkeypatch.setattr( |
| 135 | pipeline.amazon, "enrich_source_items", |
| 136 | lambda *a, **k: calls.append("amazon") or a[0], |
| 137 | ) |
| 138 | |
| 139 | items_by_source = { |
| 140 | "digg": [ |
| 141 | _source_item( |
| 142 | "digg", "d1", "https://di.gg/ai/d1", |
| 143 | engagement={"postCount": 5}, metadata={"clusterUrlId": "d1"}, |
| 144 | ) |
| 145 | ], |
| 146 | "reddit": [ |
| 147 | _source_item( |
| 148 | "reddit", "r1", "https://www.reddit.com/r/test/comments/r1/x/", |
| 149 | engagement={"score": 20, "num_comments": 5}, |
| 150 | ) |
| 151 | ], |
| 152 | "devto": [ |
| 153 | _source_item( |
| 154 | "devto", "101", "https://dev.to/alice/post-101", |
| 155 | engagement={"reactions": 10, "comments": 4}, |
| 156 | ) |
| 157 | ], |
| 158 | "amazon": [ |
| 159 | _source_item( |
| 160 | "amazon", "B0001", "https://www.amazon.com/dp/B0001", |
| 161 | metadata={"asin": "B0001"}, |
| 162 | ) |
| 163 | ], |
| 164 | } |
| 165 | |
| 166 | # Standalone CLI pattern: _finalization_deadline set in past, NO _research_deadline. |
| 167 | # Use mock.patch.object for reddit_keyless.enrich_source_items so teardown |
| 168 | # nests cleanly inside conftest's autouse _no_reddit_kept_thread_comments patch. |
| 169 | with mock.patch.object( |
| 170 | pipeline.reddit_keyless, "enrich_source_items", |
| 171 | side_effect=lambda *a, **k: calls.append("reddit") or a[0], |
| 172 | ): |
| 173 | pipeline._finalize_items_by_source( |
| 174 | items_by_source, |
| 175 | topic="test topic", |
| 176 | config={"_finalization_deadline": 999.0}, |
| 177 | depth="default", |
| 178 | mock=False, |
| 179 | ) |
| 180 | assert calls == [] |
| 181 | |
| 182 | # Positive control: before finalization_deadline, all four enrichments run. |
| 183 | seen_deadlines: dict[str, float | None] = {} |
| 184 | monkeypatch.setattr( |
| 185 | pipeline.digg, "enrich_source_items", |
| 186 | lambda items, **kw: seen_deadlines.setdefault("digg", kw.get("deadline")) or items, |
| 187 | ) |
| 188 | monkeypatch.setattr( |
| 189 | pipeline.devto, "enrich_source_items", |
| 190 | lambda items, **kw: seen_deadlines.setdefault("devto", kw.get("deadline")) or items, |
| 191 | ) |
| 192 | monkeypatch.setattr( |
| 193 | pipeline.amazon, "enrich_source_items", |
| 194 | lambda items, **kw: seen_deadlines.setdefault("amazon", kw.get("deadline")) or items, |
| 195 | ) |
| 196 | |
| 197 | with mock.patch.object( |
| 198 | pipeline.reddit_keyless, "enrich_source_items", |
| 199 | side_effect=lambda items, **kw: seen_deadlines.setdefault("reddit", kw.get("deadline")) or items, |
| 200 | ): |
| 201 | pipeline._finalize_items_by_source( |
| 202 | items_by_source, |
| 203 | topic="test topic", |
| 204 | config={"_finalization_deadline": 1050.0, "_research_deadline": 1070.0}, |
| 205 | depth="default", |
| 206 | mock=False, |
| 207 | ) |
| 208 | # _finalization_deadline (1050.0) is tighter than _research_deadline - 10s (1060.0). |
| 209 | assert seen_deadlines == { |
| 210 | "digg": 1050.0, |
| 211 | "reddit": 1050.0, |
| 212 | "devto": 1050.0, |
| 213 | "amazon": 1050.0, |
| 214 | } |
| 215 | |
| 216 | def test_reddit_receives_clamped_finalization_deadline_not_raw_research_deadline(self, monkeypatch): |
| 217 | now = [1000.0] |
| 218 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 219 | captured: list[float | None] = [] |
| 220 | with mock.patch.object( |
| 221 | pipeline.reddit_keyless, "enrich_source_items", |
| 222 | side_effect=lambda items, **kw: captured.append(kw.get("deadline")) or items, |
| 223 | ): |
| 224 | pipeline._finalize_items_by_source( |
| 225 | {"reddit": [_source_item("reddit", "r1", "https://www.reddit.com/r/t/comments/r1/x/")]}, |
| 226 | topic="topic", |
| 227 | config={"_research_deadline": 1080.0}, |
| 228 | depth="default", |
| 229 | mock=False, |
| 230 | ) |
| 231 | # _finalization_deadline reserves DISCOVERY_FINALIZATION_RESERVE_SECONDS (10s). |
| 232 | assert captured == [1080.0 - pipeline.DISCOVERY_FINALIZATION_RESERVE_SECONDS] |
| 233 | |
| 234 | def test_amazon_receives_live_elapsed_after_earlier_sources_finalize(self, monkeypatch): |
| 235 | now = [1000.0] |
| 236 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 237 | |
| 238 | def slow_devto(items, **kwargs): |
| 239 | now[0] += 45.0 |
| 240 | return items |
| 241 | |
| 242 | amazon_kwargs: dict = {} |
| 243 | |
| 244 | def capture_amazon(items, **kwargs): |
| 245 | amazon_kwargs.update(kwargs) |
| 246 | return items |
| 247 | |
| 248 | monkeypatch.setattr(pipeline.devto, "enrich_source_items", slow_devto) |
| 249 | monkeypatch.setattr(pipeline.amazon, "enrich_source_items", capture_amazon) |
| 250 | |
| 251 | pipeline._finalize_items_by_source( |
| 252 | { |
| 253 | "devto": [ |
| 254 | _source_item( |
| 255 | "devto", "101", "https://dev.to/a/101", |
| 256 | engagement={"comments": 2}, |
| 257 | ) |
| 258 | ], |
| 259 | "amazon": [ |
| 260 | _source_item( |
| 261 | "amazon", "B0001", "https://www.amazon.com/dp/B0001", |
| 262 | metadata={"asin": "B0001"}, |
| 263 | ) |
| 264 | ], |
| 265 | }, |
| 266 | topic="widget", |
| 267 | config={}, |
| 268 | depth="default", |
| 269 | mock=False, |
| 270 | elapsed=100.0, |
| 271 | ) |
| 272 | # Entry elapsed was 100s; devto took 45s -> Amazon must see ~145s, not stale 100s. |
| 273 | assert amazon_kwargs["elapsed"] == pytest.approx(145.0) |
| 274 | assert amazon_kwargs["deadline"] == pytest.approx(1180.0) |
| 275 | |
| 276 | def test_amazon_remaining_lane_budget_and_enrich_respect_deadline(self, monkeypatch): |
| 277 | monkeypatch.setattr(amazon.time, "monotonic", lambda: 1000.0) |
| 278 | # Small elapsed (5s) but tight deadline (20s left < MIN_USEFUL_REVIEW_BUDGET 45s) -> skip (0). |
| 279 | assert amazon._remaining_lane_budget(5.0, deadline=1020.0) == 0 |
| 280 | # Deadline 52s left (between 45s and 60s) -> clamps budget to 52s. |
| 281 | assert amazon._remaining_lane_budget(5.0, deadline=1052.0) == 52 |
| 282 | # enrich_source_items must skip firing fetcher when deadline is below floor. |
| 283 | fired: list[str] = [] |
| 284 | item = _source_item( |
| 285 | "amazon", "B0001", "https://www.amazon.com/dp/B0001", |
| 286 | metadata={"asin": "B0001", "name": "Widget", "num_ratings": 100}, |
| 287 | ) |
| 288 | amazon.enrich_source_items( |
| 289 | [item], depth="default", elapsed=5.0, deadline=1020.0, |
| 290 | fetcher=lambda url: fired.append(url) or {"records": []}, |
| 291 | ) |
| 292 | assert fired == [] |
| 293 | |
| 294 | def test_digg_enrich_source_items_stops_at_deadline_and_threads_bounds(self, monkeypatch): |
| 295 | now = [1000.0] |
| 296 | seen_calls: list[tuple[float, float | None, threading.Event | None]] = [] |
| 297 | |
| 298 | def fake_run(cmd, *, timeout, env=None, deadline_monotonic=None, cancel=None): |
| 299 | seen_calls.append((timeout, deadline_monotonic, cancel)) |
| 300 | now[0] += 10.0 # exhaust deadline after first cluster |
| 301 | return subproc.SubprocResult( |
| 302 | returncode=0, |
| 303 | stdout=( |
| 304 | '{"results": [{"body": "Great point", "xUrl": "https://x.com/u/status/1",' |
| 305 | ' "author": {"username": "u"}}]}' |
| 306 | ), |
| 307 | stderr="", |
| 308 | ) |
| 309 | |
| 310 | monkeypatch.setattr(digg.time, "monotonic", lambda: now[0]) |
| 311 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/digg-pp-cli") |
| 312 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 313 | |
| 314 | cancel = threading.Event() |
| 315 | items = [ |
| 316 | _source_item( |
| 317 | "digg", "ID1", "https://di.gg/ai/ID1", |
| 318 | engagement={"postCount": 5}, metadata={"clusterUrlId": "ID1"}, |
| 319 | ), |
| 320 | _source_item( |
| 321 | "digg", "ID2", "https://di.gg/ai/ID2", |
| 322 | engagement={"postCount": 5}, metadata={"clusterUrlId": "ID2"}, |
| 323 | ), |
| 324 | ] |
| 325 | digg.enrich_source_items(items, top_k=3, deadline=1006.0, cancel=cancel) |
| 326 | # Only first cluster fetched (timeout clamped to 6.0s); second stopped after deadline passed. |
| 327 | assert seen_calls == [(6.0, 1006.0, cancel)] |
| 328 | assert len(items[0].metadata.get("posts", [])) == 1 |
| 329 | assert not items[1].metadata.get("posts") |
| 330 | |
| 331 | def test_devto_enrich_source_items_respects_deadline(self, monkeypatch): |
| 332 | now = [1000.0] |
| 333 | monkeypatch.setattr(devto.time, "monotonic", lambda: now[0]) |
| 334 | |
| 335 | called: list[tuple[str, float | None]] = [] |
| 336 | |
| 337 | def fake_fetch(article_id: str, deadline: float | None = None): |
| 338 | called.append((article_id, deadline)) |
| 339 | return [{"author": "a", "text": "Nice writeup", "replies": 2}] |
| 340 | |
| 341 | monkeypatch.setattr(devto, "_fetch_comments", fake_fetch) |
| 342 | |
| 343 | # Already expired -> skips without invoking _fetch_comments. |
| 344 | expired_item = _source_item( |
| 345 | "devto", "10", "https://dev.to/a/10", engagement={"comments": 3}, |
| 346 | ) |
| 347 | devto.enrich_source_items([expired_item], deadline=999.0) |
| 348 | assert called == [] |
| 349 | assert not expired_item.metadata.get("top_comments") |
| 350 | |
| 351 | # Active deadline -> forwards deadline to _fetch_comments. |
| 352 | active_item = _source_item( |
| 353 | "devto", "11", "https://dev.to/a/11", engagement={"comments": 3}, |
| 354 | ) |
| 355 | devto.enrich_source_items([active_item], deadline=1008.0) |
| 356 | assert called == [("11", 1008.0)] |
| 357 | assert active_item.metadata.get("top_comments") |
| 358 | |
| 359 | def test_deep_research_finalization_deadline_preserved(self, monkeypatch): |
| 360 | now = [1000.0] |
| 361 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 362 | deadline = pipeline._finalization_deadline( |
| 363 | {"_deep_research": True, "_finalization_deadline": 2500.0}, |
| 364 | run_started=1000.0, |
| 365 | ) |
| 366 | assert deadline == 2500.0 |
| 367 | |
| 368 | |
| 369 | # --------------------------------------------------------------------------- |
| 370 | # HIGH-026: X failover preserves x_receipts, runs x_judge, ranks chain_errors |
| 371 | # --------------------------------------------------------------------------- |
| 372 | |
| 373 | |
| 374 | class TestHigh026XFailoverControlFlow: |
| 375 | def test_fallback_preserves_x_receipts_and_runs_x_judge_pruning_and_retry(self, monkeypatch): |
| 376 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["grok", "xapi"]) |
| 377 | monkeypatch.setattr(pipeline.fetch_memo, "fetch_once", lambda _k, fn, **_kw: fn()) |
| 378 | |
| 379 | xapi_calls: list[str] = [] |
| 380 | |
| 381 | def fake_attempt(backend, q, from_date, to_date, depth, config, warnings=None, deadline=None): |
| 382 | if backend == "grok": |
| 383 | return [], "connection reset", health.UNREACHABLE |
| 384 | xapi_calls.append(q) |
| 385 | if warnings is not None: |
| 386 | warnings.append("X: xapi window truncated to 7 days") |
| 387 | if len(xapi_calls) == 1: |
| 388 | # Initial fallback returns mostly off-topic flood + 1 on-topic post. |
| 389 | return [ |
| 390 | _x_post("1", "Completely unrelated celebrity gossip about movies"), |
| 391 | _x_post("2", "Another unrelated sports score from last night"), |
| 392 | _x_post("3", "Weather forecast for tomorrow morning"), |
| 393 | _x_post("4", "SQLite write-ahead logging benchmark results"), |
| 394 | ], "", None |
| 395 | # Retry query improves on-topic ratio. |
| 396 | return [ |
| 397 | _x_post("10", "SQLite write-ahead logging lock contention fix"), |
| 398 | _x_post("11", "SQLite WAL checkpoint tuning guide"), |
| 399 | _x_post("12", "Random unrelated cat video"), |
| 400 | ], "", None |
| 401 | |
| 402 | monkeypatch.setattr(pipeline, "_attempt_x_backend", fake_attempt) |
| 403 | |
| 404 | items, artifact = pipeline._retrieve_stream_impl( |
| 405 | topic="SQLite write-ahead logging", |
| 406 | subquery=schema.SubQuery( |
| 407 | label="primary", |
| 408 | search_query="SQLite write-ahead logging", |
| 409 | ranking_query="SQLite write-ahead logging", |
| 410 | sources=["x"], |
| 411 | ), |
| 412 | source="x", |
| 413 | config={"X_BEARER_TOKEN": "dummy"}, |
| 414 | depth="default", |
| 415 | date_range=("2026-10-10", "2026-11-10"), |
| 416 | runtime=_runtime("grok"), |
| 417 | mock=False, |
| 418 | raw_topic="SQLite write-ahead logging", |
| 419 | ) |
| 420 | |
| 421 | # Fallback warning receipt must survive failover! |
| 422 | assert artifact.get("x_receipts") == ["X: xapi window truncated to 7 days"] |
| 423 | # Failover detail metadata must also survive! |
| 424 | assert "X served via xapi after grok: connection reset" in artifact["_source_outcome_detail"] |
| 425 | # x_judge must have retried against fallback backend AND pruned off-topic items! |
| 426 | assert len(xapi_calls) == 2 |
| 427 | texts = [it["text"] for it in items] |
| 428 | assert all("SQLite" in text for text in texts) |
| 429 | assert not any("cat video" in text or "celebrity" in text for text in texts) |
| 430 | assert any("pruned" in w for w in artifact.get("_warnings", [])) |
| 431 | |
| 432 | def test_failover_selects_most_specific_prior_failure_from_chain_errors(self, monkeypatch): |
| 433 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["grok", "bird", "xai"]) |
| 434 | monkeypatch.setattr(pipeline.fetch_memo, "fetch_once", lambda _k, fn, **_kw: fn()) |
| 435 | |
| 436 | def fake_attempt(backend, q, from_date, to_date, depth, config, warnings=None, deadline=None): |
| 437 | if backend == "grok": |
| 438 | return [], "grok session expired", health.AUTH_FAILED |
| 439 | if backend == "bird": |
| 440 | return [], "timed out after 30s", health.TIMEOUT |
| 441 | return [_x_post("100", "SQLite WAL tuning tips")], "", None |
| 442 | |
| 443 | monkeypatch.setattr(pipeline, "_attempt_x_backend", fake_attempt) |
| 444 | |
| 445 | items, artifact = pipeline._retrieve_stream_impl( |
| 446 | topic="SQLite WAL", |
| 447 | subquery=schema.SubQuery( |
| 448 | label="primary", search_query="SQLite WAL", ranking_query="SQLite WAL", sources=["x"], |
| 449 | ), |
| 450 | source="x", |
| 451 | config={"XAI_API_KEY": "dummy"}, |
| 452 | depth="quick", |
| 453 | date_range=("2026-10-10", "2026-11-10"), |
| 454 | runtime=_runtime("grok"), |
| 455 | mock=False, |
| 456 | raw_topic="SQLite WAL", |
| 457 | ) |
| 458 | |
| 459 | assert len(items) == 1 |
| 460 | # Earlier grok AUTH_FAILED must NOT be masked by later bird TIMEOUT. |
| 461 | assert artifact["_source_outcome"]["state"] == schema.AUTH_FAILED |
| 462 | assert "grok: grok session expired" in artifact["_source_outcome"]["detail"] |
| 463 | assert "re-login needed for primary backend" in artifact["_source_outcome"]["detail"] |
| 464 | |
| 465 | def test_all_backends_failed_selects_most_specific_error_in_chain(self, monkeypatch): |
| 466 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["grok", "xai"]) |
| 467 | monkeypatch.setattr(pipeline.fetch_memo, "fetch_once", lambda _k, fn, **_kw: fn()) |
| 468 | |
| 469 | def fake_attempt(backend, *_a, **_k): |
| 470 | if backend == "grok": |
| 471 | return [], "grok session expired", health.AUTH_FAILED |
| 472 | return [], "unexpected failure", health.ERROR |
| 473 | |
| 474 | monkeypatch.setattr(pipeline, "_attempt_x_backend", fake_attempt) |
| 475 | |
| 476 | with pytest.raises(pipeline.SourceRunError) as exc_info: |
| 477 | pipeline._retrieve_stream_impl( |
| 478 | topic="SQLite", |
| 479 | subquery=schema.SubQuery( |
| 480 | label="primary", search_query="SQLite", ranking_query="SQLite", sources=["x"], |
| 481 | ), |
| 482 | source="x", |
| 483 | config={}, |
| 484 | depth="quick", |
| 485 | date_range=("2026-10-10", "2026-11-10"), |
| 486 | runtime=_runtime("grok"), |
| 487 | mock=False, |
| 488 | raw_topic="SQLite", |
| 489 | ) |
| 490 | |
| 491 | assert exc_info.value.outcome_state == health.AUTH_FAILED |
| 492 | assert "grok: grok session expired" in str(exc_info.value) |
| 493 | |
| 494 | def test_mixed_result_items_plus_err_still_preserves_x_receipts_and_prunes(self, monkeypatch): |
| 495 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["grok"]) |
| 496 | monkeypatch.setattr(pipeline.fetch_memo, "fetch_once", lambda _k, fn, **_kw: fn()) |
| 497 | |
| 498 | def fake_attempt(backend, q, from_date, to_date, depth, config, warnings=None, deadline=None): |
| 499 | if warnings is not None: |
| 500 | warnings.append("X: grok partial window") |
| 501 | return [ |
| 502 | _x_post("1", "SQLite write-ahead logging details"), |
| 503 | _x_post("2", "Unrelated baking recipe for sourdough"), |
| 504 | ], "grok session expired", health.AUTH_FAILED |
| 505 | |
| 506 | monkeypatch.setattr(pipeline, "_attempt_x_backend", fake_attempt) |
| 507 | monkeypatch.setattr(pipeline.x_judge, "should_retry_x_search", lambda *a, **k: False) |
| 508 | |
| 509 | items, artifact = pipeline._retrieve_stream_impl( |
| 510 | topic="SQLite write-ahead logging", |
| 511 | subquery=schema.SubQuery( |
| 512 | label="primary", |
| 513 | search_query="SQLite write-ahead logging", |
| 514 | ranking_query="SQLite write-ahead logging", |
| 515 | sources=["x"], |
| 516 | ), |
| 517 | source="x", |
| 518 | config={}, |
| 519 | depth="default", |
| 520 | date_range=("2026-10-10", "2026-11-10"), |
| 521 | runtime=_runtime("grok"), |
| 522 | mock=False, |
| 523 | raw_topic="SQLite write-ahead logging", |
| 524 | ) |
| 525 | |
| 526 | assert artifact.get("x_receipts") == ["X: grok partial window"] |
| 527 | assert artifact["_source_outcome"]["state"] == health.AUTH_FAILED |
| 528 | assert [it["id"] for it in items] == ["1"] |
| 529 | |
| 530 | |
| 531 | # --------------------------------------------------------------------------- |
| 532 | # HIGH-027: _attempt_x_backend Bird classification + non-HTTP exception failover |
| 533 | # --------------------------------------------------------------------------- |
| 534 | |
| 535 | |
| 536 | class TestHigh027AttemptXBackend: |
| 537 | @pytest.mark.parametrize( |
| 538 | "message,expected_state", |
| 539 | [ |
| 540 | ("cookie expired", health.AUTH_FAILED), |
| 541 | ("expired cookie on profile", health.AUTH_FAILED), |
| 542 | ("login required to continue", health.AUTH_FAILED), |
| 543 | ("Could not authenticate you", health.AUTH_FAILED), |
| 544 | ("session rejected by X", health.AUTH_FAILED), |
| 545 | ("HTML interstitial returned", health.SCHEMA_DRIFT), |
| 546 | ], |
| 547 | ) |
| 548 | def test_bird_error_uses_bird_x_classify_run_failure(self, monkeypatch, message, expected_state): |
| 549 | monkeypatch.setattr(pipeline, "_fetch_x_backend", lambda *a, **k: ([], message)) |
| 550 | items, detail, state = pipeline._attempt_x_backend( |
| 551 | "bird", "topic", "2026-10-10", "2026-11-10", "default", {}, |
| 552 | ) |
| 553 | assert items == [] |
| 554 | assert detail == message |
| 555 | assert state == expected_state |
| 556 | |
| 557 | def test_bird_cookie_expired_failover_emits_auth_failed_and_relogin(self, monkeypatch): |
| 558 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["bird", "xai"]) |
| 559 | monkeypatch.setattr(pipeline.fetch_memo, "fetch_once", lambda _k, fn, **_kw: fn()) |
| 560 | |
| 561 | def fake_fetch(backend, *_a, **_k): |
| 562 | if backend == "bird": |
| 563 | return [], "cookie expired" |
| 564 | return [_x_post("1", "SQLite WAL benchmark")], "" |
| 565 | |
| 566 | monkeypatch.setattr(pipeline, "_fetch_x_backend", fake_fetch) |
| 567 | |
| 568 | items, artifact = pipeline._retrieve_stream_impl( |
| 569 | topic="SQLite", |
| 570 | subquery=schema.SubQuery( |
| 571 | label="primary", search_query="SQLite", ranking_query="SQLite", sources=["x"], |
| 572 | ), |
| 573 | source="x", |
| 574 | config={}, |
| 575 | depth="quick", |
| 576 | date_range=("2026-10-10", "2026-11-10"), |
| 577 | runtime=_runtime("bird"), |
| 578 | mock=False, |
| 579 | raw_topic="SQLite", |
| 580 | ) |
| 581 | assert len(items) == 1 |
| 582 | assert artifact["_source_outcome"]["state"] == schema.AUTH_FAILED |
| 583 | assert "re-login needed for primary backend" in artifact["_source_outcome"]["detail"] |
| 584 | |
| 585 | @pytest.mark.parametrize( |
| 586 | "exc,expected_state", |
| 587 | [ |
| 588 | (OSError("network is unreachable"), health.UNREACHABLE), |
| 589 | (TimeoutError("socket stalled"), health.TIMEOUT), |
| 590 | (KeyError("data"), health.ERROR), |
| 591 | (ValueError("bad payload"), health.ERROR), |
| 592 | (RuntimeError("grok session expired"), health.AUTH_FAILED), |
| 593 | ], |
| 594 | ) |
| 595 | def test_non_http_exceptions_return_failure_tuple_and_fail_over(self, monkeypatch, exc, expected_state): |
| 596 | monkeypatch.setattr(pipeline, "_fetch_x_backend", mock.Mock(side_effect=exc)) |
| 597 | items, detail, state = pipeline._attempt_x_backend( |
| 598 | "grok", "topic", "2026-10-10", "2026-11-10", "default", {}, |
| 599 | ) |
| 600 | assert items == [] |
| 601 | assert detail.startswith(f"{type(exc).__name__}: ") |
| 602 | assert state == expected_state |
| 603 | |
| 604 | def test_non_http_exception_fails_over_to_backup_backend_in_chain(self, monkeypatch): |
| 605 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["grok", "xai"]) |
| 606 | monkeypatch.setattr(pipeline.fetch_memo, "fetch_once", lambda _k, fn, **_kw: fn()) |
| 607 | |
| 608 | def fake_fetch(backend, *_a, **_k): |
| 609 | if backend == "grok": |
| 610 | raise RuntimeError("unexpected subprocess crash") |
| 611 | return [_x_post("77", "SQLite WAL improvements")], "" |
| 612 | |
| 613 | monkeypatch.setattr(pipeline, "_fetch_x_backend", fake_fetch) |
| 614 | |
| 615 | items, artifact = pipeline._retrieve_stream_impl( |
| 616 | topic="SQLite", |
| 617 | subquery=schema.SubQuery( |
| 618 | label="primary", search_query="SQLite", ranking_query="SQLite", sources=["x"], |
| 619 | ), |
| 620 | source="x", |
| 621 | config={}, |
| 622 | depth="quick", |
| 623 | date_range=("2026-10-10", "2026-11-10"), |
| 624 | runtime=_runtime("grok"), |
| 625 | mock=False, |
| 626 | raw_topic="SQLite", |
| 627 | ) |
| 628 | assert [it["id"] for it in items] == ["77"] |
| 629 | assert "RuntimeError: unexpected subprocess crash" in artifact["_source_outcome_detail"] |
| 630 | |
| 631 | @pytest.mark.parametrize("exc_cls", [KeyboardInterrupt, SystemExit]) |
| 632 | def test_base_exceptions_are_not_swallowed(self, monkeypatch, exc_cls): |
| 633 | monkeypatch.setattr(pipeline, "_fetch_x_backend", mock.Mock(side_effect=exc_cls())) |
| 634 | with pytest.raises(exc_cls): |
| 635 | pipeline._attempt_x_backend("grok", "topic", "2026-10-10", "2026-11-10", "default", {}) |
| 636 | |
| 637 | |
| 638 | # --------------------------------------------------------------------------- |
| 639 | # HIGH-028: record_failure specificity, Phase 2 any_revoked, xapi _guard_lane |
| 640 | # --------------------------------------------------------------------------- |
| 641 | |
| 642 | |
| 643 | class TestHigh028FailureSpecificityAndPhase2Guards: |
| 644 | @pytest.mark.parametrize("with_items", [False, True]) |
| 645 | def test_record_failure_never_clobbers_auth_failed_with_less_specific_failure(self, with_items): |
| 646 | bundle = schema.RetrievalBundle() |
| 647 | if with_items: |
| 648 | bundle.add_items("primary", "x", [_source_item("x", "X1", "https://x.com/a/status/1")]) |
| 649 | bundle.record_failure("x", schema.AUTH_FAILED, "grok session revoked") |
| 650 | bundle.record_failure("x", health.TIMEOUT, "ABOUT-lane timed out") |
| 651 | bundle.record_failure("x", health.UNREACHABLE, "connection reset") |
| 652 | bundle.record_failure("x", health.ERROR, "generic error") |
| 653 | |
| 654 | assert bundle.source_status["x"].state == schema.AUTH_FAILED |
| 655 | assert bundle.source_status["x"].detail == "grok session revoked" |
| 656 | assert bundle.errors_by_source["x"] == "grok session revoked" |
| 657 | |
| 658 | def test_record_failure_upgrades_to_more_specific_failure_and_keeps_errors_aligned(self): |
| 659 | bundle = schema.RetrievalBundle() |
| 660 | bundle.add_items("primary", "x", [_source_item("x", "X1", "https://x.com/a/status/1")]) |
| 661 | bundle.record_failure("x", health.TIMEOUT, "lane timed out") |
| 662 | assert bundle.source_status["x"].state == schema.PARTIAL |
| 663 | assert bundle.errors_by_source["x"] == "lane timed out" |
| 664 | |
| 665 | bundle.record_failure("x", schema.AUTH_FAILED, "grok session revoked") |
| 666 | assert bundle.source_status["x"].state == schema.AUTH_FAILED |
| 667 | assert bundle.source_status["x"].detail == "grok session revoked" |
| 668 | assert bundle.errors_by_source["x"] == "grok session revoked" |
| 669 | |
| 670 | def test_record_failure_preserves_payment_required_over_generic_error(self): |
| 671 | bundle = schema.RetrievalBundle() |
| 672 | bundle.record_failure("x", health.PAYMENT_REQUIRED, "402 credits exhausted") |
| 673 | bundle.record_failure("x", health.ERROR, "later generic error") |
| 674 | |
| 675 | assert bundle.source_status["x"].state == health.PAYMENT_REQUIRED |
| 676 | assert bundle.source_status["x"].detail == "402 credits exhausted" |
| 677 | assert bundle.errors_by_source["x"] == "402 credits exhausted" |
| 678 | |
| 679 | def test_phase2_skips_remaining_lanes_after_auth_revocation(self, monkeypatch): |
| 680 | bundle = schema.RetrievalBundle() |
| 681 | bundle.add_items( |
| 682 | "primary", |
| 683 | "x", |
| 684 | [ |
| 685 | _source_item("x", "X1", "https://x.com/extracted1/status/1", author="extracted1", body="AI safety note 1"), |
| 686 | _source_item("x", "X2", "https://x.com/extracted1/status/2", author="extracted1", body="AI safety note 2"), |
| 687 | ], |
| 688 | ) |
| 689 | calls: list[str] = [] |
| 690 | |
| 691 | def fake_handles(handles, *args, **kwargs): |
| 692 | calls.append(f"from:{','.join(handles)}") |
| 693 | # First call (explicit handle) reports auth revocation. |
| 694 | return [], True |
| 695 | |
| 696 | def fake_mentions(*args, **kwargs): |
| 697 | calls.append("about") |
| 698 | return [], False |
| 699 | |
| 700 | def fake_name(*args, **kwargs): |
| 701 | calls.append("name") |
| 702 | return [], False |
| 703 | |
| 704 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["grok"]) |
| 705 | monkeypatch.setattr( |
| 706 | pipeline.entity_extract, "extract_entities", |
| 707 | lambda *_a, **_k: {"x_handles": ["extracted1"], "x_hashtags": [], "reddit_subreddits": []}, |
| 708 | ) |
| 709 | monkeypatch.setattr(pipeline.grok_x, "search_handles", fake_handles) |
| 710 | monkeypatch.setattr(pipeline.grok_x, "search_mentions", fake_mentions) |
| 711 | monkeypatch.setattr(pipeline.grok_x, "search_name", fake_name) |
| 712 | |
| 713 | pipeline._run_supplemental_searches( |
| 714 | topic="AI safety", |
| 715 | bundle=bundle, |
| 716 | plan=_x_plan("AI safety"), |
| 717 | config={}, |
| 718 | depth="default", |
| 719 | date_range=("2026-10-10", "2026-11-10"), |
| 720 | runtime=_runtime("grok"), |
| 721 | mock=False, |
| 722 | rate_limited_sources=set(), |
| 723 | rate_limit_lock=threading.Lock(), |
| 724 | x_handle="primaryuser", |
| 725 | x_related=["peeruser"], |
| 726 | ) |
| 727 | |
| 728 | # Only the first explicit FROM-lane call ran; extracted FROM, ABOUT, NAME, and related all skipped! |
| 729 | assert calls == ["from:primaryuser"] |
| 730 | assert bundle.source_status["x"].state == schema.AUTH_FAILED |
| 731 | assert "FROM-lane (explicit)" in bundle.source_status["x"].detail |
| 732 | assert bundle.errors_by_source["x"] == bundle.source_status["x"].detail |
| 733 | |
| 734 | def test_xapi_guard_lane_deadline_records_partial_coverage_not_failure(self, monkeypatch): |
| 735 | now = [1000.0] |
| 736 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 737 | |
| 738 | bundle = schema.RetrievalBundle() |
| 739 | bundle.add_items( |
| 740 | "primary", "x", |
| 741 | [_source_item("x", "X1", "https://x.com/steipete/status/1", author="steipete", body="AI safety")], |
| 742 | ) |
| 743 | |
| 744 | handle_calls = 0 |
| 745 | |
| 746 | def fake_search_handles(*args, **kwargs): |
| 747 | nonlocal handle_calls |
| 748 | handle_calls += 1 |
| 749 | # Advance clock past supplemental_deadline before ABOUT lane runs. |
| 750 | now[0] += 200.0 |
| 751 | return [] |
| 752 | |
| 753 | mention_mock = mock.Mock(return_value=[]) |
| 754 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["xapi"]) |
| 755 | monkeypatch.setattr( |
| 756 | pipeline.entity_extract, "extract_entities", |
| 757 | lambda *_a, **_k: {"x_handles": [], "x_hashtags": [], "reddit_subreddits": []}, |
| 758 | ) |
| 759 | monkeypatch.setattr(pipeline.x_api, "search_handles", fake_search_handles) |
| 760 | monkeypatch.setattr(pipeline.x_api, "search_mentions", mention_mock) |
| 761 | |
| 762 | pipeline._run_supplemental_searches( |
| 763 | topic="AI safety", |
| 764 | bundle=bundle, |
| 765 | plan=_x_plan("AI safety"), |
| 766 | config={"X_BEARER_TOKEN": "dummy", "_research_deadline": 1050.0}, |
| 767 | depth="default", |
| 768 | date_range=("2026-10-10", "2026-11-10"), |
| 769 | runtime=_runtime("xapi"), |
| 770 | mock=False, |
| 771 | rate_limited_sources=set(), |
| 772 | rate_limit_lock=threading.Lock(), |
| 773 | x_handle="steipete", |
| 774 | ) |
| 775 | |
| 776 | assert handle_calls == 1 |
| 777 | mention_mock.assert_not_called() |
| 778 | assert bundle.artifacts.get("x_partial_coverage") == [ |
| 779 | f"X handle lanes: {x_api.DEADLINE_DETAIL}" |
| 780 | ] |
| 781 | # Must NOT call record_failure -> source stays OK and errors_by_source stays empty. |
| 782 | assert bundle.source_status["x"].state == health.OK |
| 783 | assert bundle.errors_by_source == {} |
| 784 | |
| 785 | def test_non_xapi_guard_lane_deadline_still_records_failure(self, monkeypatch): |
| 786 | now = [1000.0] |
| 787 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 788 | |
| 789 | bundle = schema.RetrievalBundle() |
| 790 | bundle.add_items( |
| 791 | "primary", "x", |
| 792 | [_source_item("x", "X1", "https://x.com/steipete/status/1", author="steipete", body="AI safety")], |
| 793 | ) |
| 794 | |
| 795 | def expire_during_from(*args, **kwargs): |
| 796 | now[0] += 200.0 |
| 797 | return [] |
| 798 | |
| 799 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["bird"]) |
| 800 | monkeypatch.setattr( |
| 801 | pipeline.entity_extract, "extract_entities", |
| 802 | lambda *_a, **_k: {"x_handles": [], "x_hashtags": [], "reddit_subreddits": []}, |
| 803 | ) |
| 804 | monkeypatch.setattr(pipeline.bird_x, "search_handles", expire_during_from) |
| 805 | monkeypatch.setattr(pipeline.bird_x, "search_mentions", mock.Mock(return_value=[])) |
| 806 | |
| 807 | pipeline._run_supplemental_searches( |
| 808 | topic="AI safety", |
| 809 | bundle=bundle, |
| 810 | plan=_x_plan("AI safety"), |
| 811 | config={"_research_deadline": 1050.0}, |
| 812 | depth="default", |
| 813 | date_range=("2026-10-10", "2026-11-10"), |
| 814 | runtime=_runtime("bird"), |
| 815 | mock=False, |
| 816 | rate_limited_sources=set(), |
| 817 | rate_limit_lock=threading.Lock(), |
| 818 | x_handle="steipete", |
| 819 | ) |
| 820 | |
| 821 | assert bundle.source_status["x"].state == schema.PARTIAL |
| 822 | assert "timed out" in bundle.source_status["x"].detail.lower() |
| 823 | |
| 824 | |
| 825 | # --------------------------------------------------------------------------- |
| 826 | # HIGH-029: Reddit ScrapeCreators backfill timeout classification & _enrich_cancel |
| 827 | # --------------------------------------------------------------------------- |
| 828 | |
| 829 | |
| 830 | class TestHigh029RedditBackfillTimeoutAndCancel: |
| 831 | def test_backfill_timeout_classified_as_timeout_not_error(self, monkeypatch): |
| 832 | monkeypatch.setattr(pipeline, "REDDIT_SC_BACKFILL_MIN_SECONDS", 10.0) |
| 833 | monkeypatch.setattr(pipeline, "REDDIT_SC_BACKFILL_RETURN_MARGIN_SECONDS", 5.0) |
| 834 | monkeypatch.setattr(pipeline, "REDDIT_LANE_RETURN_MARGIN_SECONDS", 0.0) |
| 835 | monkeypatch.setattr(pipeline, "REDDIT_SC_BACKFILL_RESERVE_SECONDS", 0.0) |
| 836 | |
| 837 | # No free items + insufficient budget left for SC backfill -> TimeoutError -> health.TIMEOUT. |
| 838 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=[]): |
| 839 | items, artifact = pipeline._retrieve_stream_impl( |
| 840 | topic="Elon Musk", |
| 841 | subquery=schema.SubQuery( |
| 842 | label="primary", search_query="Elon Musk", ranking_query="Elon Musk", sources=["reddit"], |
| 843 | ), |
| 844 | source="reddit", |
| 845 | config={ |
| 846 | "SCRAPECREATORS_API_KEY": "dummy", |
| 847 | "_research_deadline": time.monotonic() + 8.0, # 8 - 5 = 3s < 10s min |
| 848 | }, |
| 849 | depth="quick", |
| 850 | date_range=("2026-10-10", "2026-11-10"), |
| 851 | runtime=_runtime(), |
| 852 | mock=False, |
| 853 | ) |
| 854 | |
| 855 | assert items == [] |
| 856 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 857 | assert "timed out" in artifact["_source_outcome"]["detail"].lower() |
| 858 | |
| 859 | def test_backfill_custom_timeout_error_without_keyword_still_classified_timeout(self): |
| 860 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=[]), \ |
| 861 | mock.patch.object( |
| 862 | pipeline, "_run_reddit_backfill", |
| 863 | side_effect=TimeoutError("budget gone without keyword"), |
| 864 | ): |
| 865 | items, artifact = pipeline._retrieve_stream_impl( |
| 866 | topic="Elon Musk", |
| 867 | subquery=schema.SubQuery( |
| 868 | label="primary", search_query="Elon Musk", ranking_query="Elon Musk", sources=["reddit"], |
| 869 | ), |
| 870 | source="reddit", |
| 871 | config={"SCRAPECREATORS_API_KEY": "dummy"}, |
| 872 | depth="quick", |
| 873 | date_range=("2026-10-10", "2026-11-10"), |
| 874 | runtime=_runtime(), |
| 875 | mock=False, |
| 876 | ) |
| 877 | |
| 878 | assert items == [] |
| 879 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 880 | |
| 881 | def test_backfill_wakes_promptly_on_enrich_cancel(self): |
| 882 | cancel = threading.Event() |
| 883 | release = threading.Event() |
| 884 | |
| 885 | def slow_call(): |
| 886 | release.wait(10.0) |
| 887 | return {"posts": []} |
| 888 | |
| 889 | timer = threading.Timer(0.15, cancel.set) |
| 890 | timer.start() |
| 891 | started = time.monotonic() |
| 892 | try: |
| 893 | with pytest.raises(TimeoutError, match="timed out"): |
| 894 | pipeline._run_reddit_backfill( |
| 895 | { |
| 896 | "_research_deadline": time.monotonic() + 120.0, |
| 897 | "_enrich_cancel": cancel, |
| 898 | }, |
| 899 | slow_call, |
| 900 | ) |
| 901 | finally: |
| 902 | timer.cancel() |
| 903 | release.set() |
| 904 | |
| 905 | elapsed = time.monotonic() - started |
| 906 | assert elapsed < 2.0, f"expected cancel wakeup within ~0.25s, took {elapsed:.2f}s" |
| 907 | |
| 908 | def test_backfill_preserves_inner_timeout_error_verbatim(self): |
| 909 | def inner_timeout(): |
| 910 | raise TimeoutError("upstream socket read stalled after 5s") |
| 911 | |
| 912 | with pytest.raises(TimeoutError, match="upstream socket read stalled after 5s"): |
| 913 | pipeline._run_reddit_backfill( |
| 914 | {"_research_deadline": time.monotonic() + 120.0}, |
| 915 | inner_timeout, |
| 916 | ) |
| 917 | |
| 918 | def test_backfill_timeout_with_free_items_sets_detail_state_to_timeout(self): |
| 919 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=[_reddit_post("a")]), \ |
| 920 | mock.patch.object( |
| 921 | pipeline, "_run_reddit_backfill", |
| 922 | side_effect=TimeoutError("no room left"), |
| 923 | ): |
| 924 | items, artifact = pipeline._retrieve_stream_impl( |
| 925 | topic="Elon Musk", |
| 926 | subquery=schema.SubQuery( |
| 927 | label="primary", search_query="Elon Musk", ranking_query="Elon Musk", sources=["reddit"], |
| 928 | ), |
| 929 | source="reddit", |
| 930 | config={"SCRAPECREATORS_API_KEY": "dummy"}, |
| 931 | depth="quick", |
| 932 | date_range=("2026-10-10", "2026-11-10"), |
| 933 | runtime=_runtime(), |
| 934 | mock=False, |
| 935 | ) |
| 936 | |
| 937 | assert len(items) == 1 |
| 938 | assert artifact["_source_outcome_detail_state"] == health.TIMEOUT |
| 939 | |
| 940 | |
| 941 | # --------------------------------------------------------------------------- |
| 942 | # HIGH-030: Proportional Reddit lane_deadline scaling on tight budgets |
| 943 | # --------------------------------------------------------------------------- |
| 944 | |
| 945 | |
| 946 | class TestHigh030ProportionalRedditLaneDeadline: |
| 947 | def test_tight_60s_budget_with_sc_key_gives_free_lane_real_share_and_avoids_sc_spend(self, monkeypatch): |
| 948 | now = 1000.0 |
| 949 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now) |
| 950 | monkeypatch.setattr(reddit_keyless.time, "monotonic", lambda: now) |
| 951 | |
| 952 | seen_deadline: list[float | None] = [] |
| 953 | |
| 954 | def fake_public(*_args, **_kwargs): |
| 955 | dl = reddit_keyless._lane_deadline.get() |
| 956 | seen_deadline.append(dl) |
| 957 | assert not reddit_keyless._out_of_time(dl) |
| 958 | return [_reddit_post(c) for c in "abcde"] |
| 959 | |
| 960 | with mock.patch("lib.reddit_public.search_reddit_public", side_effect=fake_public), \ |
| 961 | mock.patch("lib.reddit.search_and_enrich") as sc_mock: |
| 962 | items, _artifact = pipeline._retrieve_stream_impl( |
| 963 | topic="Elon Musk", |
| 964 | subquery=schema.SubQuery( |
| 965 | label="primary", search_query="Elon Musk", ranking_query="Elon Musk", sources=["reddit"], |
| 966 | ), |
| 967 | source="reddit", |
| 968 | config={ |
| 969 | "SCRAPECREATORS_API_KEY": "dummy", |
| 970 | "_research_deadline": now + 60.0, |
| 971 | }, |
| 972 | depth="quick", |
| 973 | date_range=("2026-10-10", "2026-11-10"), |
| 974 | runtime=_runtime(), |
| 975 | mock=False, |
| 976 | ) |
| 977 | |
| 978 | # margin = min(20, 60*0.15=9) = 9; reserve = min(45, 60*0.35=21) = 21 -> free lane gets 30s! |
| 979 | assert seen_deadline == [pytest.approx(now + 30.0)] |
| 980 | assert len(items) == 5 |
| 981 | sc_mock.assert_not_called() |
| 982 | |
| 983 | def test_tight_15s_budget_without_sc_key_runs_free_lane_instead_of_immediate_timeout(self, monkeypatch): |
| 984 | now = 1000.0 |
| 985 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now) |
| 986 | monkeypatch.setattr(reddit_keyless.time, "monotonic", lambda: now) |
| 987 | |
| 988 | seen_deadline: list[float | None] = [] |
| 989 | |
| 990 | def fake_public(*_args, **_kwargs): |
| 991 | dl = reddit_keyless._lane_deadline.get() |
| 992 | seen_deadline.append(dl) |
| 993 | assert not reddit_keyless._out_of_time(dl) |
| 994 | return [_reddit_post("a")] |
| 995 | |
| 996 | with mock.patch("lib.reddit_public.search_reddit_public", side_effect=fake_public): |
| 997 | items, artifact = pipeline._retrieve_stream_impl( |
| 998 | topic="Elon Musk", |
| 999 | subquery=schema.SubQuery( |
| 1000 | label="primary", search_query="Elon Musk", ranking_query="Elon Musk", sources=["reddit"], |
| 1001 | ), |
| 1002 | source="reddit", |
| 1003 | config={"_research_deadline": now + 15.0}, |
| 1004 | depth="quick", |
| 1005 | date_range=("2026-10-10", "2026-11-10"), |
| 1006 | runtime=_runtime(), |
| 1007 | mock=False, |
| 1008 | ) |
| 1009 | |
| 1010 | # margin = min(20, 15*0.15=2.25) = 2.25 -> free lane gets 12.75s! |
| 1011 | assert seen_deadline == [pytest.approx(now + 12.75)] |
| 1012 | assert len(items) == 1 |
| 1013 | assert "_source_outcome" not in artifact |
| 1014 | |
| 1015 | |
| 1016 | # --------------------------------------------------------------------------- |
| 1017 | # HIGH-032: Parallel completion-order independence in RetrievalBundle.add_items |
| 1018 | # --------------------------------------------------------------------------- |
| 1019 | |
| 1020 | |
| 1021 | class TestHigh032AddItemsOrderIndependence: |
| 1022 | @pytest.mark.parametrize("lane_state", [schema.AUTH_FAILED, schema.RATE_LIMITED]) |
| 1023 | def test_empty_lane_state_stream_then_populated_sibling_matches_reverse_order(self, lane_state): |
| 1024 | item = _source_item("reddit", "R1", "https://www.reddit.com/r/t/comments/r1/x/") |
| 1025 | |
| 1026 | # Order A: empty stream with swallowed lane failure finishes FIRST, sibling with item finishes SECOND. |
| 1027 | bundle_a = schema.RetrievalBundle() |
| 1028 | bundle_a.mark_attempted("reddit") |
| 1029 | bundle_a.record_detail("reddit", "sub-request failure", state=lane_state) |
| 1030 | bundle_a.add_items("sqA", "reddit", []) |
| 1031 | # While empty, lane_state is promoted. |
| 1032 | assert bundle_a.source_status["reddit"].state == lane_state |
| 1033 | # Sibling delivers item -> must revert cleanly to OK, retaining detail & lane_failure_state! |
| 1034 | bundle_a.add_items("sqB", "reddit", [item]) |
| 1035 | |
| 1036 | # Order B: sibling with item finishes FIRST, empty stream with swallowed lane failure finishes SECOND. |
| 1037 | bundle_b = schema.RetrievalBundle() |
| 1038 | bundle_b.mark_attempted("reddit") |
| 1039 | bundle_b.add_items("sqB", "reddit", [item]) |
| 1040 | bundle_b.record_detail("reddit", "sub-request failure", state=lane_state) |
| 1041 | bundle_b.add_items("sqA", "reddit", []) |
| 1042 | |
| 1043 | for outcome in (bundle_a.source_status["reddit"], bundle_b.source_status["reddit"]): |
| 1044 | assert outcome.state == health.OK |
| 1045 | assert outcome.items_returned == 1 |
| 1046 | assert outcome.detail == "sub-request failure" |
| 1047 | assert outcome.lane_failure_state == lane_state |
| 1048 | assert outcome.fix_hint is None |
| 1049 | |
| 1050 | def test_all_empty_streams_keep_promoted_lane_state(self): |
| 1051 | bundle = schema.RetrievalBundle() |
| 1052 | bundle.mark_attempted("polymarket") |
| 1053 | bundle.record_detail("polymarket", "5 sub-requests rate-limited", state=schema.RATE_LIMITED) |
| 1054 | bundle.add_items("sqA", "polymarket", []) |
| 1055 | bundle.add_items("sqB", "polymarket", []) |
| 1056 | |
| 1057 | outcome = bundle.source_status["polymarket"] |
| 1058 | assert outcome.state == schema.RATE_LIMITED |
| 1059 | assert outcome.items_returned == 0 |
| 1060 | assert outcome.detail == "5 sub-requests rate-limited" |
| 1061 | assert outcome.lane_failure_state == schema.RATE_LIMITED |
| 1062 | |
| 1063 | def test_hard_record_failure_still_preserved_when_sibling_delivers_items(self): |
| 1064 | item = _source_item("x", "X1", "https://x.com/a/status/1") |
| 1065 | |
| 1066 | # Hard AUTH_FAILED stays AUTH_FAILED. |
| 1067 | auth_bundle = schema.RetrievalBundle() |
| 1068 | auth_bundle.record_failure("x", schema.AUTH_FAILED, "grok revoked") |
| 1069 | auth_bundle.add_items("sqB", "x", [item]) |
| 1070 | assert auth_bundle.source_status["x"].state == schema.AUTH_FAILED |
| 1071 | assert auth_bundle.source_status["x"].detail == "grok revoked" |
| 1072 | assert auth_bundle.source_status["x"].fix_hint == "doctor" |
| 1073 | |
| 1074 | # Hard TIMEOUT becomes PARTIAL when items exist. |
| 1075 | timeout_bundle = schema.RetrievalBundle() |
| 1076 | timeout_bundle.record_failure("x", health.TIMEOUT, "timed out") |
| 1077 | timeout_bundle.add_items("sqB", "x", [item]) |
| 1078 | assert timeout_bundle.source_status["x"].state == schema.PARTIAL |
| 1079 | assert timeout_bundle.source_status["x"].detail == "timed out" |
| 1080 | assert timeout_bundle.source_status["x"].fix_hint == "doctor" |
| 1081 | |
| 1082 | |
| 1083 | # --------------------------------------------------------------------------- |
| 1084 | # Greptile P1 #1: Deadline-skipped enrichments record [] for fixture replay |
| 1085 | # --------------------------------------------------------------------------- |
| 1086 | |
| 1087 | |
| 1088 | class TestGreptileP1DeadlineSkippedFixtureReplay: |
| 1089 | @pytest.mark.parametrize("source", ["youtube", "digg", "reddit", "devto", "amazon"]) |
| 1090 | def test_deadline_skipped_enrichment_records_empty_and_replays_cleanly( |
| 1091 | self, tmp_path, monkeypatch, source, |
| 1092 | ): |
| 1093 | fixture_dir = tmp_path / source |
| 1094 | now = [1000.0] |
| 1095 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 1096 | |
| 1097 | def _make_item() -> schema.SourceItem: |
| 1098 | if source == "digg": |
| 1099 | return _source_item( |
| 1100 | "digg", "item-1", "https://di.gg/ai/item-1", |
| 1101 | engagement={"postCount": 5}, metadata={"clusterUrlId": "item-1"}, |
| 1102 | ) |
| 1103 | if source == "reddit": |
| 1104 | return _source_item( |
| 1105 | "reddit", "item-1", "https://www.reddit.com/r/test/comments/item1/x/", |
| 1106 | engagement={"score": 20, "num_comments": 5}, metadata={"existing": "keep"}, |
| 1107 | ) |
| 1108 | if source == "devto": |
| 1109 | return _source_item( |
| 1110 | "devto", "item-1", "https://dev.to/alice/post-1", |
| 1111 | engagement={"reactions": 10, "comments": 4}, metadata={"existing": "keep"}, |
| 1112 | ) |
| 1113 | if source == "amazon": |
| 1114 | return _source_item( |
| 1115 | "amazon", "item-1", "https://www.amazon.com/dp/B0001", |
| 1116 | metadata={"asin": "B0001", "existing": "keep"}, |
| 1117 | ) |
| 1118 | return _source_item( |
| 1119 | "youtube", "item-1", "https://www.youtube.com/watch?v=item1", |
| 1120 | metadata={"existing": "keep"}, |
| 1121 | ) |
| 1122 | |
| 1123 | fail_live = lambda *_a, **_k: pytest.fail(f"live enrichment ran for {source}") |
| 1124 | |
| 1125 | item = _make_item() |
| 1126 | original_metadata = dict(item.metadata) |
| 1127 | |
| 1128 | # Record mode after finalization_deadline has expired: live call skipped, |
| 1129 | # but empty exchange [] must still be recorded for offline replay. |
| 1130 | with mock.patch.object(pipeline.youtube_yt, "backfill_transcripts", side_effect=fail_live), \ |
| 1131 | mock.patch.object(pipeline.digg, "enrich_source_items", side_effect=fail_live), \ |
| 1132 | mock.patch.object(pipeline.reddit_keyless, "enrich_source_items", side_effect=fail_live), \ |
| 1133 | mock.patch.object(pipeline.devto, "enrich_source_items", side_effect=fail_live), \ |
| 1134 | mock.patch.object(pipeline.amazon, "enrich_source_items", side_effect=fail_live): |
| 1135 | with http.recording_requests(fixture_dir): |
| 1136 | recorded = pipeline._finalize_items_by_source( |
| 1137 | {source: [item]}, |
| 1138 | topic="agents", |
| 1139 | config={"_finalization_deadline": 999.0}, |
| 1140 | depth="quick", |
| 1141 | mock=False, |
| 1142 | ) |
| 1143 | |
| 1144 | assert recorded[source][0].metadata == original_metadata |
| 1145 | |
| 1146 | # Replay mode (even with a generous deadline) must match the recorded |
| 1147 | # empty exchange without raising Unrecorded CLI-backed source request |
| 1148 | # and leave item metadata untouched. |
| 1149 | replay_item = _make_item() |
| 1150 | with mock.patch.object(pipeline.youtube_yt, "backfill_transcripts", side_effect=fail_live), \ |
| 1151 | mock.patch.object(pipeline.digg, "enrich_source_items", side_effect=fail_live), \ |
| 1152 | mock.patch.object(pipeline.reddit_keyless, "enrich_source_items", side_effect=fail_live), \ |
| 1153 | mock.patch.object(pipeline.devto, "enrich_source_items", side_effect=fail_live), \ |
| 1154 | mock.patch.object(pipeline.amazon, "enrich_source_items", side_effect=fail_live): |
| 1155 | with http.replaying_requests(fixture_dir): |
| 1156 | replayed = pipeline._finalize_items_by_source( |
| 1157 | {source: [replay_item]}, |
| 1158 | topic="agents", |
| 1159 | config={"_finalization_deadline": 1500.0}, |
| 1160 | depth="quick", |
| 1161 | mock=False, |
| 1162 | ) |
| 1163 | |
| 1164 | assert len(replayed[source]) == 1 |
| 1165 | assert replayed[source][0].metadata == original_metadata |
| 1166 | |
| 1167 | |
| 1168 | # --------------------------------------------------------------------------- |
| 1169 | # Greptile P1 #2: Cancelled / expired Reddit SC backfill stops paid HTTP spend |
| 1170 | # --------------------------------------------------------------------------- |
| 1171 | |
| 1172 | |
| 1173 | class TestGreptileP1CancelledBackfillStopsSpend: |
| 1174 | def test_enrich_cancel_during_subreddit_search_stops_global_and_comment_calls(self, monkeypatch): |
| 1175 | reddit.reset_scrapecreators_memo() |
| 1176 | cancel = threading.Event() |
| 1177 | worker_done = threading.Event() |
| 1178 | endpoints: list[str] = [] |
| 1179 | |
| 1180 | def fake_http_get(url, **kwargs): |
| 1181 | endpoints.append(url) |
| 1182 | if "/subreddit/search" in url: |
| 1183 | # Cancel arrives while first paid subreddit call is in flight. |
| 1184 | cancel.set() |
| 1185 | return { |
| 1186 | "posts": [{ |
| 1187 | "id": "p1", |
| 1188 | "title": "SQLite WAL write-ahead logging", |
| 1189 | "permalink": "/r/sqlite/comments/p1/wal/", |
| 1190 | "subreddit": "sqlite", |
| 1191 | "created_utc": 1793836800, |
| 1192 | "ups": 40, |
| 1193 | "num_comments": 10, |
| 1194 | }] |
| 1195 | } |
| 1196 | raise AssertionError(f"paid ScrapeCreators call fired after cancel: {url}") |
| 1197 | |
| 1198 | monkeypatch.setattr(reddit.http, "get", fake_http_get) |
| 1199 | |
| 1200 | def call(): |
| 1201 | try: |
| 1202 | return reddit.search_and_enrich_memo( |
| 1203 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1204 | depth="default", token="dummy-sc-key", subreddits=["sqlite"], |
| 1205 | ) |
| 1206 | finally: |
| 1207 | worker_done.set() |
| 1208 | |
| 1209 | with pytest.raises(TimeoutError, match="timed out"): |
| 1210 | pipeline._run_reddit_backfill( |
| 1211 | { |
| 1212 | "_research_deadline": time.monotonic() + 120.0, |
| 1213 | "_enrich_cancel": cancel, |
| 1214 | }, |
| 1215 | call, |
| 1216 | ) |
| 1217 | |
| 1218 | assert worker_done.wait(timeout=2.0), "worker thread should exit promptly after cancel" |
| 1219 | assert len(endpoints) == 1 and endpoints[0].endswith("/subreddit/search") |
| 1220 | assert not any( |
| 1221 | url.endswith("/reddit/search") or "/post/comments" in url for url in endpoints |
| 1222 | ) |
| 1223 | # Paid request already started before cancel -> cached in _SC_MEMO so a |
| 1224 | # retry with a fresh deadline never buys the same search twice. |
| 1225 | assert len(reddit._SC_MEMO) == 1 |
| 1226 | with pytest.raises(TimeoutError): |
| 1227 | reddit.search_and_enrich_memo( |
| 1228 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1229 | depth="default", token="dummy-sc-key", subreddits=["sqlite"], |
| 1230 | deadline_monotonic=time.monotonic() + 120.0, |
| 1231 | ) |
| 1232 | assert len(endpoints) == 1 |
| 1233 | |
| 1234 | def test_wait_deadline_expiry_during_subreddit_search_stops_subsequent_paid_calls(self, monkeypatch): |
| 1235 | reddit.reset_scrapecreators_memo() |
| 1236 | monkeypatch.setattr(pipeline, "REDDIT_SC_BACKFILL_MIN_SECONDS", 0.05) |
| 1237 | monkeypatch.setattr(pipeline, "REDDIT_SC_BACKFILL_RETURN_MARGIN_SECONDS", 0.0) |
| 1238 | |
| 1239 | import json as _json |
| 1240 | from lib import bounded_get |
| 1241 | |
| 1242 | worker_done = threading.Event() |
| 1243 | endpoints: list[str] = [] |
| 1244 | |
| 1245 | def fake_bounded_get(req, *, timeout, deadline_monotonic, cancel=None, on_start=None, **_kwargs): |
| 1246 | url = req.full_url |
| 1247 | endpoints.append(url) |
| 1248 | if "/subreddit/search" in url: |
| 1249 | if on_start is not None: |
| 1250 | on_start() |
| 1251 | # Sleep past wait_deadline (~0.15s) before returning. |
| 1252 | time.sleep(0.25) |
| 1253 | payload = _json.dumps({ |
| 1254 | "posts": [{ |
| 1255 | "id": "p2", |
| 1256 | "title": "SQLite WAL benchmark", |
| 1257 | "permalink": "/r/sqlite/comments/p2/wal/", |
| 1258 | "subreddit": "sqlite", |
| 1259 | "created_utc": 1793836800, |
| 1260 | "ups": 50, |
| 1261 | "num_comments": 12, |
| 1262 | }] |
| 1263 | }).encode("utf-8") |
| 1264 | return 200, payload, None |
| 1265 | raise AssertionError(f"paid ScrapeCreators call fired past deadline: {url}") |
| 1266 | |
| 1267 | monkeypatch.setattr(bounded_get, "get", fake_bounded_get) |
| 1268 | monkeypatch.setattr(http.usage, "begin_http", lambda *_a, **_kw: None) |
| 1269 | monkeypatch.setattr(http.usage, "finish", lambda *_a, **_kw: None) |
| 1270 | |
| 1271 | def call(): |
| 1272 | try: |
| 1273 | return reddit.search_and_enrich_memo( |
| 1274 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1275 | depth="default", token="dummy-sc-key", subreddits=["sqlite"], |
| 1276 | ) |
| 1277 | finally: |
| 1278 | worker_done.set() |
| 1279 | |
| 1280 | with pytest.raises(TimeoutError, match="timed out"): |
| 1281 | pipeline._run_reddit_backfill( |
| 1282 | {"_research_deadline": time.monotonic() + 0.15}, |
| 1283 | call, |
| 1284 | ) |
| 1285 | |
| 1286 | assert worker_done.wait(timeout=2.0), "worker thread should stop after deadline expiry" |
| 1287 | assert len(endpoints) == 1 and "/subreddit/search" in endpoints[0] |
| 1288 | assert not any( |
| 1289 | "/reddit/search?" in url or "/post/comments" in url for url in endpoints |
| 1290 | ) |
| 1291 | # Paid request already dispatched via on_start before deadline -> cached in _SC_MEMO. |
| 1292 | assert len(reddit._SC_MEMO) == 1 |
| 1293 | |
| 1294 | |
| 1295 | # --------------------------------------------------------------------------- |
| 1296 | # Greptile P1 #3: Timeout must not hide PAYMENT_REQUIRED / AUTH_FAILED in X chain |
| 1297 | # --------------------------------------------------------------------------- |
| 1298 | |
| 1299 | |
| 1300 | class TestGreptileP1XChainTimeoutSpecificity: |
| 1301 | @pytest.mark.parametrize( |
| 1302 | "primary_backend,primary_err,primary_state", |
| 1303 | [ |
| 1304 | ("xapi", "payment required (X API credits exhausted)", health.PAYMENT_REQUIRED), |
| 1305 | ("grok", "grok session expired", health.AUTH_FAILED), |
| 1306 | ], |
| 1307 | ) |
| 1308 | def test_specific_primary_failure_beats_later_chain_timeout( |
| 1309 | self, monkeypatch, primary_backend, primary_err, primary_state, |
| 1310 | ): |
| 1311 | now = [1000.0] |
| 1312 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 1313 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: [primary_backend, "xai"]) |
| 1314 | monkeypatch.setattr(pipeline.fetch_memo, "fetch_once", lambda _k, fn, **_kw: fn()) |
| 1315 | |
| 1316 | def fake_attempt(backend, *_a, **_k): |
| 1317 | if backend == primary_backend: |
| 1318 | return [], primary_err, primary_state |
| 1319 | # Second backend exhausts the chain deadline. |
| 1320 | now[0] += 200.0 |
| 1321 | return [], "request timed out", health.TIMEOUT |
| 1322 | |
| 1323 | monkeypatch.setattr(pipeline, "_attempt_x_backend", fake_attempt) |
| 1324 | |
| 1325 | with pytest.raises(pipeline.SourceRunError) as exc_info: |
| 1326 | pipeline._retrieve_stream_impl( |
| 1327 | topic="SQLite", |
| 1328 | subquery=schema.SubQuery( |
| 1329 | label="primary", search_query="SQLite", ranking_query="SQLite", sources=["x"], |
| 1330 | ), |
| 1331 | source="x", |
| 1332 | config={"_research_deadline": 1050.0}, |
| 1333 | depth="quick", |
| 1334 | date_range=("2026-10-10", "2026-11-10"), |
| 1335 | runtime=_runtime(primary_backend), |
| 1336 | mock=False, |
| 1337 | raw_topic="SQLite", |
| 1338 | ) |
| 1339 | |
| 1340 | assert exc_info.value.outcome_state == primary_state |
| 1341 | assert f"{primary_backend}: {primary_err}" in str(exc_info.value) |
| 1342 | |
| 1343 | def test_chain_timeout_beats_generic_primary_error_with_matching_message(self, monkeypatch): |
| 1344 | now = [1000.0] |
| 1345 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 1346 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["xai", "xquik"]) |
| 1347 | monkeypatch.setattr(pipeline.fetch_memo, "fetch_once", lambda _k, fn, **_kw: fn()) |
| 1348 | |
| 1349 | def fake_attempt(backend, *_a, **_k): |
| 1350 | if backend == "xai": |
| 1351 | return [], "unexpected server glitch", health.ERROR |
| 1352 | # Second backend returns generic error after exhausting chain_deadline. |
| 1353 | now[0] += 200.0 |
| 1354 | return [], "incomplete response", health.ERROR |
| 1355 | |
| 1356 | monkeypatch.setattr(pipeline, "_attempt_x_backend", fake_attempt) |
| 1357 | |
| 1358 | with pytest.raises(pipeline.SourceRunError) as exc_info: |
| 1359 | pipeline._retrieve_stream_impl( |
| 1360 | topic="SQLite", |
| 1361 | subquery=schema.SubQuery( |
| 1362 | label="primary", search_query="SQLite", ranking_query="SQLite", sources=["x"], |
| 1363 | ), |
| 1364 | source="x", |
| 1365 | config={"_research_deadline": 1050.0}, |
| 1366 | depth="quick", |
| 1367 | date_range=("2026-10-10", "2026-11-10"), |
| 1368 | runtime=_runtime("xai"), |
| 1369 | mock=False, |
| 1370 | raw_topic="SQLite", |
| 1371 | ) |
| 1372 | |
| 1373 | assert exc_info.value.outcome_state == health.TIMEOUT |
| 1374 | assert "timed out" in str(exc_info.value).lower() |
| 1375 | |
| 1376 | |
| 1377 | # --------------------------------------------------------------------------- |
| 1378 | # Greptile P2 #4: Skip x_judge retry when serving backend reported AUTH_FAILED |
| 1379 | # --------------------------------------------------------------------------- |
| 1380 | |
| 1381 | |
| 1382 | class TestGreptileP2SkipJudgeRetryOnRevokedBackend: |
| 1383 | def test_mixed_result_with_auth_failed_skips_judge_retry_but_still_prunes(self, monkeypatch): |
| 1384 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["grok"]) |
| 1385 | monkeypatch.setattr(pipeline.fetch_memo, "fetch_once", lambda _k, fn, **_kw: fn()) |
| 1386 | |
| 1387 | attempt_calls: list[tuple[str, str]] = [] |
| 1388 | |
| 1389 | def fake_attempt(backend, q, *_a, **_k): |
| 1390 | attempt_calls.append((backend, q)) |
| 1391 | return [ |
| 1392 | _x_post("1", "Unrelated movie review about action heroes"), |
| 1393 | _x_post("2", "Unrelated baseball game score from yesterday"), |
| 1394 | _x_post("3", "Unrelated weather alert for coastal cities"), |
| 1395 | _x_post("4", "SQLite write-ahead logging concurrency benchmark"), |
| 1396 | ], "grok session expired", health.AUTH_FAILED |
| 1397 | |
| 1398 | monkeypatch.setattr(pipeline, "_attempt_x_backend", fake_attempt) |
| 1399 | |
| 1400 | items, artifact = pipeline._retrieve_stream_impl( |
| 1401 | topic="SQLite write-ahead logging", |
| 1402 | subquery=schema.SubQuery( |
| 1403 | label="primary", |
| 1404 | search_query="SQLite write-ahead logging", |
| 1405 | ranking_query="SQLite write-ahead logging", |
| 1406 | sources=["x"], |
| 1407 | ), |
| 1408 | source="x", |
| 1409 | config={}, |
| 1410 | depth="default", |
| 1411 | date_range=("2026-10-10", "2026-11-10"), |
| 1412 | runtime=_runtime("grok"), |
| 1413 | mock=False, |
| 1414 | raw_topic="SQLite write-ahead logging", |
| 1415 | ) |
| 1416 | |
| 1417 | # Revoked backend must NOT be called a second time by x_judge retry! |
| 1418 | assert len(attempt_calls) == 1 |
| 1419 | # Off-topic pruning must still run on the returned items. |
| 1420 | assert [it["id"] for it in items] == ["4"] |
| 1421 | assert artifact["_source_outcome"]["state"] == health.AUTH_FAILED |
| 1422 | |
| 1423 | def test_healthy_fallback_after_primary_auth_failed_still_runs_judge_retry(self, monkeypatch): |
| 1424 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["grok", "xai"]) |
| 1425 | monkeypatch.setattr(pipeline.fetch_memo, "fetch_once", lambda _k, fn, **_kw: fn()) |
| 1426 | |
| 1427 | xai_calls: list[str] = [] |
| 1428 | |
| 1429 | def fake_attempt(backend, q, *_a, **_k): |
| 1430 | if backend == "grok": |
| 1431 | return [], "grok session expired", health.AUTH_FAILED |
| 1432 | xai_calls.append(q) |
| 1433 | if len(xai_calls) == 1: |
| 1434 | return [ |
| 1435 | _x_post("1", "Unrelated movie review about action heroes"), |
| 1436 | _x_post("2", "Unrelated baseball game score from yesterday"), |
| 1437 | _x_post("3", "Unrelated weather alert for coastal cities"), |
| 1438 | _x_post("4", "SQLite write-ahead logging concurrency benchmark"), |
| 1439 | ], "", None |
| 1440 | return [ |
| 1441 | _x_post("10", "SQLite write-ahead logging checkpoint tuning"), |
| 1442 | _x_post("11", "SQLite write-ahead logging read scalability"), |
| 1443 | ], "", None |
| 1444 | |
| 1445 | monkeypatch.setattr(pipeline, "_attempt_x_backend", fake_attempt) |
| 1446 | |
| 1447 | items, artifact = pipeline._retrieve_stream_impl( |
| 1448 | topic="SQLite write-ahead logging", |
| 1449 | subquery=schema.SubQuery( |
| 1450 | label="primary", |
| 1451 | search_query="SQLite write-ahead logging", |
| 1452 | ranking_query="SQLite write-ahead logging", |
| 1453 | sources=["x"], |
| 1454 | ), |
| 1455 | source="x", |
| 1456 | config={"XAI_API_KEY": "dummy"}, |
| 1457 | depth="default", |
| 1458 | date_range=("2026-10-10", "2026-11-10"), |
| 1459 | runtime=_runtime("grok"), |
| 1460 | mock=False, |
| 1461 | raw_topic="SQLite write-ahead logging", |
| 1462 | ) |
| 1463 | |
| 1464 | # Healthy fallback xai must still run x_judge retry (initial + retry = 2 calls). |
| 1465 | assert len(xai_calls) == 2 |
| 1466 | assert [it["id"] for it in items] == ["10", "11"] |
| 1467 | # Primary grok AUTH_FAILED outcome must still be preserved. |
| 1468 | assert artifact["_source_outcome"]["state"] == schema.AUTH_FAILED |
| 1469 | assert "re-login needed for primary backend" in artifact["_source_outcome"]["detail"] |
| 1470 | |
| 1471 | |
| 1472 | # --------------------------------------------------------------------------- |
| 1473 | # Greptile Round 2 P1 #1: Keep paid SC Reddit posts when comments / Phase 3 hit deadline |
| 1474 | # --------------------------------------------------------------------------- |
| 1475 | |
| 1476 | |
| 1477 | class TestGreptileRound2P1PreservePaidPostsOnCommentDeadline: |
| 1478 | def test_deadline_before_comments_keeps_paid_posts_and_surfaces_note(self, monkeypatch): |
| 1479 | reddit.reset_scrapecreators_memo() |
| 1480 | now = [1000.0] |
| 1481 | monkeypatch.setattr(reddit.time, "monotonic", lambda: now[0]) |
| 1482 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 1483 | |
| 1484 | paid_post = { |
| 1485 | "id": "p100", |
| 1486 | "title": "SQLite WAL write-ahead logging guide", |
| 1487 | "permalink": "/r/sqlite/comments/p100/wal_guide/", |
| 1488 | "subreddit": "sqlite", |
| 1489 | "created_utc": 1793836800, |
| 1490 | "ups": 80, |
| 1491 | "num_comments": 15, |
| 1492 | } |
| 1493 | |
| 1494 | def fake_search_reddit(*_args, **_kwargs): |
| 1495 | # Search finishes right at the deadline -> no room left for comments. |
| 1496 | now[0] = 1050.0 |
| 1497 | return { |
| 1498 | "items": [{ |
| 1499 | "id": "R1", |
| 1500 | "reddit_id": "p100", |
| 1501 | "title": paid_post["title"], |
| 1502 | "url": "https://www.reddit.com/r/sqlite/comments/p100/wal_guide/", |
| 1503 | "subreddit": "sqlite", |
| 1504 | "date": "2026-11-05", |
| 1505 | "engagement": {"score": 80, "num_comments": 15}, |
| 1506 | "relevance": 0.9, |
| 1507 | }] |
| 1508 | } |
| 1509 | |
| 1510 | comment_calls: list[str] = [] |
| 1511 | monkeypatch.setattr(reddit, "search_reddit", fake_search_reddit) |
| 1512 | monkeypatch.setattr( |
| 1513 | reddit, "fetch_post_comments", |
| 1514 | lambda url, *_a, **_k: comment_calls.append(url) or [], |
| 1515 | ) |
| 1516 | |
| 1517 | # Direct search_and_enrich keeps the paid post and skips comment calls. |
| 1518 | res = reddit.search_and_enrich( |
| 1519 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1520 | depth="quick", token="dummy-sc-key", deadline_monotonic=1050.0, |
| 1521 | ) |
| 1522 | assert len(res["items"]) == 1 |
| 1523 | assert res["items"][0]["reddit_id"] == "p100" |
| 1524 | assert res.get("comments_incomplete") is True |
| 1525 | assert "comments incomplete" in res.get("comments_note", "").lower() |
| 1526 | assert comment_calls == [] |
| 1527 | |
| 1528 | # Pipeline backfill path surfaces comments_note in _source_outcome_detail. |
| 1529 | now[0] = 1000.0 |
| 1530 | reddit.reset_scrapecreators_memo() |
| 1531 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=[]): |
| 1532 | items, artifact = pipeline._retrieve_stream_impl( |
| 1533 | topic="SQLite WAL", |
| 1534 | subquery=schema.SubQuery( |
| 1535 | label="primary", search_query="SQLite WAL", ranking_query="SQLite WAL", sources=["reddit"], |
| 1536 | ), |
| 1537 | source="reddit", |
| 1538 | config={ |
| 1539 | "SCRAPECREATORS_API_KEY": "dummy-sc-key", |
| 1540 | "_research_deadline": 1055.0, # wait_deadline = 1050.0 -> hits deadline right after search |
| 1541 | }, |
| 1542 | depth="quick", |
| 1543 | date_range=("2026-10-10", "2026-11-10"), |
| 1544 | runtime=_runtime(), |
| 1545 | mock=False, |
| 1546 | ) |
| 1547 | |
| 1548 | assert len(items) == 1 |
| 1549 | assert "_source_outcome" not in artifact |
| 1550 | assert "Reddit comments incomplete" in artifact.get("_source_outcome_detail", "") |
| 1551 | |
| 1552 | def test_deadline_mid_comments_keeps_completed_comments_and_stops_further_calls(self, monkeypatch): |
| 1553 | reddit.reset_scrapecreators_memo() |
| 1554 | release = threading.Event() |
| 1555 | fetched: list[str] = [] |
| 1556 | |
| 1557 | def fake_fetch_comments(url, token, **kwargs): |
| 1558 | fetched.append(url) |
| 1559 | if "fast" in url: |
| 1560 | return [{"body": "Fast comment with useful detail on WAL", "ups": 25, "author": "alice"}] |
| 1561 | # Slow comment waits until cancelled/abandoned. |
| 1562 | release.wait(timeout=5.0) |
| 1563 | return [{"body": "Too late comment", "ups": 1, "author": "bob"}] |
| 1564 | |
| 1565 | posts = [ |
| 1566 | { |
| 1567 | "id": "R1", |
| 1568 | "reddit_id": "fast", |
| 1569 | "title": "SQLite WAL fast thread", |
| 1570 | "url": "https://www.reddit.com/r/sqlite/comments/fast/wal/", |
| 1571 | "subreddit": "sqlite", |
| 1572 | "date": "2026-11-05", |
| 1573 | "engagement": {"score": 100, "num_comments": 20}, |
| 1574 | "relevance": 0.9, |
| 1575 | }, |
| 1576 | { |
| 1577 | "id": "R2", |
| 1578 | "reddit_id": "slow", |
| 1579 | "title": "SQLite WAL slow thread", |
| 1580 | "url": "https://www.reddit.com/r/sqlite/comments/slow/wal/", |
| 1581 | "subreddit": "sqlite", |
| 1582 | "date": "2026-11-05", |
| 1583 | "engagement": {"score": 90, "num_comments": 15}, |
| 1584 | "relevance": 0.9, |
| 1585 | }, |
| 1586 | ] |
| 1587 | |
| 1588 | monkeypatch.setattr(reddit, "search_reddit", lambda *_a, **_k: {"items": posts}) |
| 1589 | monkeypatch.setattr(reddit, "fetch_post_comments", fake_fetch_comments) |
| 1590 | |
| 1591 | try: |
| 1592 | res = reddit.search_and_enrich( |
| 1593 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1594 | depth="quick", token="dummy-sc-key", |
| 1595 | deadline_monotonic=time.monotonic() + 0.35, |
| 1596 | ) |
| 1597 | finally: |
| 1598 | release.set() |
| 1599 | |
| 1600 | # Both paid posts survive, fast post keeps its completed comment, and flag is set. |
| 1601 | assert len(res["items"]) == 2 |
| 1602 | assert res["items"][0].get("top_comments") |
| 1603 | assert res["items"][0]["top_comments"][0]["author"] == "alice" |
| 1604 | assert not res["items"][1].get("top_comments") |
| 1605 | assert res.get("comments_incomplete") is True |
| 1606 | |
| 1607 | def test_phase3_deadline_keeps_phase2_paid_posts(self, monkeypatch): |
| 1608 | now = [1000.0] |
| 1609 | monkeypatch.setattr(reddit.time, "monotonic", lambda: now[0]) |
| 1610 | |
| 1611 | def fake_global(*_args, **_kwargs): |
| 1612 | # Phase 2 gathers a paid post and uses up the budget before Phase 3. |
| 1613 | now[0] = 1050.0 |
| 1614 | return [{ |
| 1615 | "id": "g1", |
| 1616 | "title": "SQLite WAL performance guide", |
| 1617 | "permalink": "/r/sqlite/comments/g1/wal/", |
| 1618 | "subreddit": "sqlite", |
| 1619 | "created_utc": 1793836800, |
| 1620 | "ups": 70, |
| 1621 | "num_comments": 14, |
| 1622 | }] |
| 1623 | |
| 1624 | sub_mock = mock.Mock(side_effect=AssertionError("Phase 3 must not fire past deadline")) |
| 1625 | monkeypatch.setattr(reddit, "_global_search", fake_global) |
| 1626 | monkeypatch.setattr(reddit, "_subreddit_search", sub_mock) |
| 1627 | |
| 1628 | res = reddit.search_reddit( |
| 1629 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1630 | depth="quick", token="dummy-sc-key", deadline_monotonic=1050.0, |
| 1631 | ) |
| 1632 | assert len(res["items"]) == 1 |
| 1633 | assert res["items"][0]["reddit_id"] == "g1" |
| 1634 | assert res.get("incomplete") is True |
| 1635 | sub_mock.assert_not_called() |
| 1636 | |
| 1637 | |
| 1638 | # --------------------------------------------------------------------------- |
| 1639 | # Greptile Round 2 P1 #2: Memo caches mid-spend timeouts, skips pre-spend ones |
| 1640 | # --------------------------------------------------------------------------- |
| 1641 | |
| 1642 | |
| 1643 | class TestGreptileRound2P1MemoNoDoubleSpend: |
| 1644 | def test_timeout_after_paid_request_caches_and_prevents_second_paid_call(self, monkeypatch): |
| 1645 | reddit.reset_scrapecreators_memo() |
| 1646 | http_calls: list[str] = [] |
| 1647 | |
| 1648 | def fake_http_get(url, **kwargs): |
| 1649 | http_calls.append(url) |
| 1650 | raise http.DeadlineExceeded(dispatched=True) |
| 1651 | |
| 1652 | monkeypatch.setattr(reddit.http, "get", fake_http_get) |
| 1653 | |
| 1654 | with pytest.raises(TimeoutError): |
| 1655 | reddit.search_and_enrich_memo( |
| 1656 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1657 | depth="quick", token="dummy-sc-key", |
| 1658 | deadline_monotonic=time.monotonic() + 10.0, |
| 1659 | ) |
| 1660 | |
| 1661 | first_call_count = len(http_calls) |
| 1662 | assert first_call_count >= 1 |
| 1663 | assert len(reddit._SC_MEMO) == 1 |
| 1664 | |
| 1665 | # Second call with a fresh generous deadline replays cached TimeoutError with ZERO new HTTP calls! |
| 1666 | with pytest.raises(TimeoutError): |
| 1667 | reddit.search_and_enrich_memo( |
| 1668 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1669 | depth="quick", token="dummy-sc-key", |
| 1670 | deadline_monotonic=time.monotonic() + 120.0, |
| 1671 | ) |
| 1672 | assert len(http_calls) == first_call_count |
| 1673 | |
| 1674 | def test_pre_spend_timeout_does_not_cache_so_fresh_deadline_can_run(self, monkeypatch): |
| 1675 | reddit.reset_scrapecreators_memo() |
| 1676 | http_calls: list[str] = [] |
| 1677 | |
| 1678 | def fake_http_get(url, **kwargs): |
| 1679 | http_calls.append(url) |
| 1680 | if url.endswith("/reddit/search"): |
| 1681 | return { |
| 1682 | "posts": [{ |
| 1683 | "id": "fresh1", |
| 1684 | "title": "SQLite WAL write-ahead logging", |
| 1685 | "permalink": "/r/sqlite/comments/fresh1/wal/", |
| 1686 | "subreddit": "sqlite", |
| 1687 | "created_utc": 1793836800, |
| 1688 | "ups": 60, |
| 1689 | "num_comments": 5, |
| 1690 | }] |
| 1691 | } |
| 1692 | return {"posts": [], "comments": []} |
| 1693 | |
| 1694 | monkeypatch.setattr(reddit.http, "get", fake_http_get) |
| 1695 | |
| 1696 | # Already-expired deadline stops BEFORE any paid HTTP request starts. |
| 1697 | with pytest.raises(TimeoutError): |
| 1698 | reddit.search_and_enrich_memo( |
| 1699 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1700 | depth="quick", token="dummy-sc-key", |
| 1701 | deadline_monotonic=time.monotonic() - 1.0, |
| 1702 | ) |
| 1703 | assert http_calls == [] |
| 1704 | assert reddit._SC_MEMO == {} |
| 1705 | |
| 1706 | # A subsequent call with a fresh deadline succeeds cleanly! |
| 1707 | result = reddit.search_and_enrich_memo( |
| 1708 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1709 | depth="quick", token="dummy-sc-key", |
| 1710 | deadline_monotonic=time.monotonic() + 60.0, |
| 1711 | ) |
| 1712 | assert len(result["items"]) == 1 |
| 1713 | assert result["items"][0]["reddit_id"] == "fresh1" |
| 1714 | assert len(http_calls) >= 1 |
| 1715 | |
| 1716 | |
| 1717 | # --------------------------------------------------------------------------- |
| 1718 | # Greptile Round 2 P2 #3: x_judge retry preserves error/timeout details when adopted |
| 1719 | # --------------------------------------------------------------------------- |
| 1720 | |
| 1721 | |
| 1722 | class TestGreptileRound2P2JudgeRetryPreservesErrorDetail: |
| 1723 | def test_adopted_retry_preserves_timeout_error_detail_and_state(self, monkeypatch): |
| 1724 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["xquik"]) |
| 1725 | monkeypatch.setattr(pipeline.fetch_memo, "fetch_once", lambda _k, fn, **_kw: fn()) |
| 1726 | |
| 1727 | calls: list[str] = [] |
| 1728 | |
| 1729 | def fake_attempt(backend, q, *_a, **_k): |
| 1730 | calls.append(q) |
| 1731 | if len(calls) == 1: |
| 1732 | return [ |
| 1733 | _x_post("1", "Unrelated movie trailer announcement"), |
| 1734 | _x_post("2", "Unrelated soccer match highlights"), |
| 1735 | _x_post("3", "Unrelated cooking recipe tips"), |
| 1736 | _x_post("4", "SQLite write-ahead logging note"), |
| 1737 | ], "", None |
| 1738 | # Retry improves on-topic ratio BUT also reports a timeout (partial search). |
| 1739 | return [ |
| 1740 | _x_post("10", "SQLite write-ahead logging concurrency benchmark"), |
| 1741 | _x_post("11", "SQLite write-ahead logging checkpoint latency"), |
| 1742 | ], "request timed out after 30s", health.TIMEOUT |
| 1743 | |
| 1744 | monkeypatch.setattr(pipeline, "_attempt_x_backend", fake_attempt) |
| 1745 | |
| 1746 | items, artifact = pipeline._retrieve_stream_impl( |
| 1747 | topic="SQLite write-ahead logging", |
| 1748 | subquery=schema.SubQuery( |
| 1749 | label="primary", |
| 1750 | search_query="SQLite write-ahead logging", |
| 1751 | ranking_query="SQLite write-ahead logging", |
| 1752 | sources=["x"], |
| 1753 | ), |
| 1754 | source="x", |
| 1755 | config={"XQUIK_API_KEY": "dummy"}, |
| 1756 | depth="default", |
| 1757 | date_range=("2026-10-10", "2026-11-10"), |
| 1758 | runtime=_runtime("xquik"), |
| 1759 | mock=False, |
| 1760 | raw_topic="SQLite write-ahead logging", |
| 1761 | ) |
| 1762 | |
| 1763 | assert len(calls) == 2 |
| 1764 | assert [it["id"] for it in items] == ["10", "11"] |
| 1765 | assert "X retry via xquik returned partial results (request timed out after 30s)" in artifact["_source_outcome_detail"] |
| 1766 | assert artifact["_source_outcome_detail_state"] == health.TIMEOUT |
| 1767 | |
| 1768 | def test_adopted_retry_auth_failed_preserves_outcome_and_existing_receipts(self, monkeypatch): |
| 1769 | monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda _cfg: ["grok"]) |
| 1770 | monkeypatch.setattr(pipeline.fetch_memo, "fetch_once", lambda _k, fn, **_kw: fn()) |
| 1771 | |
| 1772 | calls: list[str] = [] |
| 1773 | |
| 1774 | def fake_attempt(backend, q, from_date, to_date, depth, config, warnings=None, deadline=None): |
| 1775 | calls.append(q) |
| 1776 | if len(calls) == 1: |
| 1777 | if warnings is not None: |
| 1778 | warnings.append("X: grok narrowed window") |
| 1779 | return [ |
| 1780 | _x_post("1", "Unrelated movie trailer announcement"), |
| 1781 | _x_post("2", "Unrelated soccer match highlights"), |
| 1782 | _x_post("3", "Unrelated cooking recipe tips"), |
| 1783 | _x_post("4", "SQLite write-ahead logging note"), |
| 1784 | ], "", None |
| 1785 | return [ |
| 1786 | _x_post("10", "SQLite write-ahead logging concurrency benchmark"), |
| 1787 | _x_post("11", "SQLite write-ahead logging checkpoint latency"), |
| 1788 | ], "grok session expired", health.AUTH_FAILED |
| 1789 | |
| 1790 | monkeypatch.setattr(pipeline, "_attempt_x_backend", fake_attempt) |
| 1791 | |
| 1792 | items, artifact = pipeline._retrieve_stream_impl( |
| 1793 | topic="SQLite write-ahead logging", |
| 1794 | subquery=schema.SubQuery( |
| 1795 | label="primary", |
| 1796 | search_query="SQLite write-ahead logging", |
| 1797 | ranking_query="SQLite write-ahead logging", |
| 1798 | sources=["x"], |
| 1799 | ), |
| 1800 | source="x", |
| 1801 | config={}, |
| 1802 | depth="default", |
| 1803 | date_range=("2026-10-10", "2026-11-10"), |
| 1804 | runtime=_runtime("grok"), |
| 1805 | mock=False, |
| 1806 | raw_topic="SQLite write-ahead logging", |
| 1807 | ) |
| 1808 | |
| 1809 | assert [it["id"] for it in items] == ["10", "11"] |
| 1810 | assert artifact["x_receipts"] == ["X: grok narrowed window"] |
| 1811 | assert artifact["_source_outcome"]["state"] == schema.AUTH_FAILED |
| 1812 | assert "re-login needed" in artifact["_source_outcome"]["detail"] |
| 1813 | |
| 1814 | |
| 1815 | # --------------------------------------------------------------------------- |
| 1816 | # Greptile Round 3 P1 #1: Preserve finished sibling search results on timeout |
| 1817 | # --------------------------------------------------------------------------- |
| 1818 | |
| 1819 | |
| 1820 | class TestGreptileRound3P1BatchPartialSurvival: |
| 1821 | def test_global_batch_preserves_finished_sibling_when_other_query_times_out(self, monkeypatch): |
| 1822 | release = threading.Event() |
| 1823 | call_index = [0] |
| 1824 | lock = threading.Lock() |
| 1825 | |
| 1826 | def fake_global(query, token, sort, timeframe, **_kwargs): |
| 1827 | with lock: |
| 1828 | idx = call_index[0] |
| 1829 | call_index[0] += 1 |
| 1830 | if idx == 0: |
| 1831 | return [{ |
| 1832 | "id": "fast1", |
| 1833 | "title": "SQLite WAL concurrency benchmarks", |
| 1834 | "permalink": "/r/sqlite/comments/fast1/wal/", |
| 1835 | "subreddit": "sqlite", |
| 1836 | "created_utc": 1793836800, |
| 1837 | "ups": 90, |
| 1838 | "num_comments": 18, |
| 1839 | }] |
| 1840 | release.wait(timeout=5.0) |
| 1841 | return [] |
| 1842 | |
| 1843 | comment_mock = mock.Mock(side_effect=AssertionError("Comments must not run after incomplete search")) |
| 1844 | sub_mock = mock.Mock(side_effect=AssertionError("Phase 3 must not run after incomplete Phase 2")) |
| 1845 | monkeypatch.setattr( |
| 1846 | reddit, |
| 1847 | "expand_reddit_queries", |
| 1848 | lambda *_a, **_kw: ["sqlite wal concurrency", "sqlite wal benchmark"], |
| 1849 | ) |
| 1850 | monkeypatch.setattr(reddit, "_global_search", fake_global) |
| 1851 | monkeypatch.setattr(reddit, "_subreddit_search", sub_mock) |
| 1852 | monkeypatch.setattr(reddit, "fetch_post_comments", comment_mock) |
| 1853 | |
| 1854 | try: |
| 1855 | res = reddit.search_and_enrich( |
| 1856 | "SQLite WAL concurrency", "2026-10-10", "2026-11-10", |
| 1857 | depth="default", token="dummy-sc-key", |
| 1858 | deadline_monotonic=time.monotonic() + 0.3, |
| 1859 | ) |
| 1860 | finally: |
| 1861 | release.set() |
| 1862 | |
| 1863 | assert len(res["items"]) == 1 |
| 1864 | assert res["items"][0]["reddit_id"] == "fast1" |
| 1865 | assert res.get("incomplete") is True |
| 1866 | assert res.get("incomplete_note") |
| 1867 | assert res.get("comments_incomplete") is True |
| 1868 | sub_mock.assert_not_called() |
| 1869 | comment_mock.assert_not_called() |
| 1870 | |
| 1871 | def test_preresolved_subreddit_batch_preserves_finished_sibling_and_skips_global(self, monkeypatch): |
| 1872 | release = threading.Event() |
| 1873 | |
| 1874 | def fake_sub(sub, query, token, sort, timeframe, **_kwargs): |
| 1875 | if sub == "sqlite": |
| 1876 | return [{ |
| 1877 | "id": "sub1", |
| 1878 | "title": "SQLite WAL checkpoint tuning", |
| 1879 | "permalink": "/r/sqlite/comments/sub1/wal/", |
| 1880 | "subreddit": "sqlite", |
| 1881 | "created_utc": 1793836800, |
| 1882 | "ups": 75, |
| 1883 | "num_comments": 12, |
| 1884 | }] |
| 1885 | release.wait(timeout=5.0) |
| 1886 | return [] |
| 1887 | |
| 1888 | global_mock = mock.Mock(side_effect=AssertionError("Phase 2 must not run after incomplete Phase 1.5")) |
| 1889 | monkeypatch.setattr(reddit, "_subreddit_search", fake_sub) |
| 1890 | monkeypatch.setattr(reddit, "_global_search", global_mock) |
| 1891 | |
| 1892 | try: |
| 1893 | res = reddit.search_reddit( |
| 1894 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1895 | depth="quick", token="dummy-sc-key", |
| 1896 | subreddits=["sqlite", "slowsub"], |
| 1897 | deadline_monotonic=time.monotonic() + 0.3, |
| 1898 | ) |
| 1899 | finally: |
| 1900 | release.set() |
| 1901 | |
| 1902 | assert len(res["items"]) == 1 |
| 1903 | assert res["items"][0]["reddit_id"] == "sub1" |
| 1904 | assert res.get("incomplete") is True |
| 1905 | global_mock.assert_not_called() |
| 1906 | |
| 1907 | def test_global_batch_raises_timeout_when_zero_posts_collected(self, monkeypatch): |
| 1908 | release = threading.Event() |
| 1909 | |
| 1910 | def fake_global(*_args, **_kwargs): |
| 1911 | release.wait(timeout=5.0) |
| 1912 | return [] |
| 1913 | |
| 1914 | monkeypatch.setattr(reddit, "_global_search", fake_global) |
| 1915 | |
| 1916 | try: |
| 1917 | with pytest.raises(TimeoutError): |
| 1918 | reddit.search_reddit( |
| 1919 | "SQLite WAL concurrency", "2026-10-10", "2026-11-10", |
| 1920 | depth="default", token="dummy-sc-key", |
| 1921 | deadline_monotonic=time.monotonic() + 0.25, |
| 1922 | ) |
| 1923 | finally: |
| 1924 | release.set() |
| 1925 | |
| 1926 | |
| 1927 | # --------------------------------------------------------------------------- |
| 1928 | # Greptile Round 3 P2 #2: Dispatch-aware paid tracking in http.py + reddit.py |
| 1929 | # --------------------------------------------------------------------------- |
| 1930 | |
| 1931 | |
| 1932 | class TestGreptileRound3P2DispatchAwarePaidTracking: |
| 1933 | def test_presend_deadline_exceeded_does_not_cache_memo_and_allows_retry(self, monkeypatch): |
| 1934 | reddit.reset_scrapecreators_memo() |
| 1935 | fail_first = [True] |
| 1936 | calls: list[str] = [] |
| 1937 | |
| 1938 | def fake_http_get(url, **kwargs): |
| 1939 | calls.append(url) |
| 1940 | if fail_first[0]: |
| 1941 | # Default dispatched=False signals expiry before any network send. |
| 1942 | raise http.DeadlineExceeded() |
| 1943 | if url.endswith("/reddit/search"): |
| 1944 | return { |
| 1945 | "posts": [{ |
| 1946 | "id": "ok1", |
| 1947 | "title": "SQLite WAL write-ahead logging", |
| 1948 | "permalink": "/r/sqlite/comments/ok1/wal/", |
| 1949 | "subreddit": "sqlite", |
| 1950 | "created_utc": 1793836800, |
| 1951 | "ups": 60, |
| 1952 | "num_comments": 5, |
| 1953 | }] |
| 1954 | } |
| 1955 | return {"posts": [], "comments": []} |
| 1956 | |
| 1957 | monkeypatch.setattr(reddit.http, "get", fake_http_get) |
| 1958 | |
| 1959 | with pytest.raises(TimeoutError): |
| 1960 | reddit.search_and_enrich_memo( |
| 1961 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1962 | depth="quick", token="dummy-sc-key", |
| 1963 | deadline_monotonic=time.monotonic() + 10.0, |
| 1964 | ) |
| 1965 | assert reddit._SC_MEMO == {} |
| 1966 | |
| 1967 | fail_first[0] = False |
| 1968 | res = reddit.search_and_enrich_memo( |
| 1969 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 1970 | depth="quick", token="dummy-sc-key", |
| 1971 | deadline_monotonic=time.monotonic() + 60.0, |
| 1972 | ) |
| 1973 | assert len(res["items"]) == 1 |
| 1974 | assert res["items"][0]["reddit_id"] == "ok1" |
| 1975 | |
| 1976 | def test_real_http_request_presend_expiry_leaves_memo_uncached(self, monkeypatch): |
| 1977 | import json as _json |
| 1978 | from lib import bounded_get |
| 1979 | |
| 1980 | reddit.reset_scrapecreators_memo() |
| 1981 | transport_calls: list[str] = [] |
| 1982 | expire_in_http = [True] |
| 1983 | |
| 1984 | def fake_bounded_get(req, *, timeout, deadline_monotonic, cancel=None, on_start=None, **_kwargs): |
| 1985 | transport_calls.append(req.full_url) |
| 1986 | if on_start is not None: |
| 1987 | on_start() |
| 1988 | if "/reddit/search" in req.full_url: |
| 1989 | body = _json.dumps({ |
| 1990 | "posts": [{ |
| 1991 | "id": "real1", |
| 1992 | "title": "SQLite WAL write-ahead logging", |
| 1993 | "permalink": "/r/sqlite/comments/real1/wal/", |
| 1994 | "subreddit": "sqlite", |
| 1995 | "created_utc": 1793836800, |
| 1996 | "ups": 80, |
| 1997 | "num_comments": 7, |
| 1998 | }] |
| 1999 | }).encode("utf-8") |
| 2000 | return 200, body, None |
| 2001 | return 200, b'{"posts": [], "comments": []}', None |
| 2002 | |
| 2003 | real_monotonic = time.monotonic |
| 2004 | |
| 2005 | def fake_http_monotonic(): |
| 2006 | base = real_monotonic() |
| 2007 | return base + 100.0 if expire_in_http[0] else base |
| 2008 | |
| 2009 | monkeypatch.setattr(bounded_get, "get", fake_bounded_get) |
| 2010 | monkeypatch.setattr(http.time, "monotonic", fake_http_monotonic) |
| 2011 | monkeypatch.setattr(http.usage, "begin_http", lambda *_a, **_kw: None) |
| 2012 | monkeypatch.setattr(http.usage, "finish", lambda *_a, **_kw: None) |
| 2013 | |
| 2014 | # Deadline is still live in reddit._check_sc_spend, then expired by the time |
| 2015 | # http.request checks remaining budget before launching bounded_get. |
| 2016 | with pytest.raises(TimeoutError): |
| 2017 | reddit.search_and_enrich_memo( |
| 2018 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 2019 | depth="quick", token="dummy-sc-key", |
| 2020 | deadline_monotonic=real_monotonic() + 10.0, |
| 2021 | ) |
| 2022 | assert transport_calls == [] |
| 2023 | assert reddit._SC_MEMO == {} |
| 2024 | |
| 2025 | # Fresh call succeeds once budget is live inside http.request. |
| 2026 | expire_in_http[0] = False |
| 2027 | res = reddit.search_and_enrich_memo( |
| 2028 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 2029 | depth="quick", token="dummy-sc-key", |
| 2030 | deadline_monotonic=real_monotonic() + 60.0, |
| 2031 | ) |
| 2032 | assert len(res["items"]) == 1 |
| 2033 | assert res["items"][0]["reddit_id"] == "real1" |
| 2034 | assert len(transport_calls) >= 1 |
| 2035 | |
| 2036 | def test_real_http_request_midflight_timeout_marks_dispatched_and_caches_memo(self, monkeypatch): |
| 2037 | from lib import bounded_get |
| 2038 | |
| 2039 | reddit.reset_scrapecreators_memo() |
| 2040 | release = threading.Event() |
| 2041 | transport_calls: list[str] = [] |
| 2042 | |
| 2043 | def blocking_bounded_get(req, *, timeout, deadline_monotonic, cancel=None, on_start=None, **_kwargs): |
| 2044 | transport_calls.append(req.full_url) |
| 2045 | if on_start is not None: |
| 2046 | on_start() |
| 2047 | release.wait(timeout=5.0) |
| 2048 | raise bounded_get.GetTimeout("in flight", started=True) |
| 2049 | |
| 2050 | monkeypatch.setattr(bounded_get, "get", blocking_bounded_get) |
| 2051 | monkeypatch.setattr(http.usage, "begin_http", lambda *_a, **_kw: None) |
| 2052 | monkeypatch.setattr(http.usage, "finish", lambda *_a, **_kw: None) |
| 2053 | |
| 2054 | try: |
| 2055 | with pytest.raises(TimeoutError): |
| 2056 | reddit.search_and_enrich_memo( |
| 2057 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 2058 | depth="quick", token="dummy-sc-key", |
| 2059 | deadline_monotonic=time.monotonic() + 0.3, |
| 2060 | ) |
| 2061 | finally: |
| 2062 | release.set() |
| 2063 | |
| 2064 | first_opens = len(transport_calls) |
| 2065 | assert first_opens >= 1 |
| 2066 | assert len(reddit._SC_MEMO) == 1 |
| 2067 | |
| 2068 | # Second call replays cached TimeoutError without dispatching any new request. |
| 2069 | with pytest.raises(TimeoutError): |
| 2070 | reddit.search_and_enrich_memo( |
| 2071 | "SQLite WAL", "2026-10-10", "2026-11-10", |
| 2072 | depth="quick", token="dummy-sc-key", |
| 2073 | deadline_monotonic=time.monotonic() + 60.0, |
| 2074 | ) |
| 2075 | assert len(transport_calls) == first_opens |
| 2076 | |
| 2077 | def test_unowned_http_request_tracks_presend_vs_midflight_dispatch(self, monkeypatch): |
| 2078 | release = threading.Event() |
| 2079 | open_calls: list[str] = [] |
| 2080 | |
| 2081 | def blocking_open(req, timeout, **kwargs): |
| 2082 | open_calls.append(req.full_url) |
| 2083 | release.wait(timeout=5.0) |
| 2084 | raise TimeoutError("socket timed out") |
| 2085 | |
| 2086 | monkeypatch.setattr(http, "_open_request", blocking_open) |
| 2087 | monkeypatch.setattr(http.usage, "begin_http", lambda *_a, **_kw: None) |
| 2088 | monkeypatch.setattr(http.usage, "finish", lambda *_a, **_kw: None) |
| 2089 | |
| 2090 | # Pre-send expiry: _open_request never runs and dispatched=False. |
| 2091 | dispatched: list[bool] = [] |
| 2092 | with pytest.raises(http.DeadlineExceeded) as exc_pre: |
| 2093 | with http.observe_dispatch(lambda: dispatched.append(True)): |
| 2094 | http.get( |
| 2095 | "https://api.scrapecreators.com/v1/reddit/search", |
| 2096 | deadline_monotonic=time.monotonic() - 1.0, |
| 2097 | ) |
| 2098 | assert exc_pre.value.dispatched is False |
| 2099 | assert dispatched == [] |
| 2100 | assert open_calls == [] |
| 2101 | |
| 2102 | # Mid-flight timeout: _open_request starts, observe_dispatch fires, and dispatched=True. |
| 2103 | try: |
| 2104 | with pytest.raises(http.DeadlineExceeded) as exc_mid: |
| 2105 | with http.observe_dispatch(lambda: dispatched.append(True)): |
| 2106 | http.get( |
| 2107 | "https://api.scrapecreators.com/v1/reddit/search", |
| 2108 | deadline_monotonic=time.monotonic() + 0.15, |
| 2109 | ) |
| 2110 | finally: |
| 2111 | release.set() |
| 2112 | assert exc_mid.value.dispatched is True |
| 2113 | assert dispatched == [True] |
| 2114 | assert len(open_calls) == 1 |
| 2115 | |
| 2116 | def test_owned_get_timeout_dispatched_matches_bounded_get_started_flag(self, monkeypatch): |
| 2117 | from lib import bounded_get |
| 2118 | |
| 2119 | monkeypatch.setattr(http.usage, "begin_http", lambda *_a, **_kw: None) |
| 2120 | monkeypatch.setattr(http.usage, "cancel", lambda *_a, **_kw: None) |
| 2121 | |
| 2122 | dispatched_events: list[bool] = [] |
| 2123 | monkeypatch.setattr( |
| 2124 | bounded_get, |
| 2125 | "get", |
| 2126 | lambda *_a, **_kw: (_ for _ in ()).throw(bounded_get.GetTimeout("before launch", started=False)), |
| 2127 | ) |
| 2128 | with pytest.raises(http.DeadlineExceeded) as exc_unstarted: |
| 2129 | with http.observe_dispatch(lambda: dispatched_events.append(True)): |
| 2130 | http.get( |
| 2131 | "https://api.scrapecreators.com/v1/reddit/post/comments", |
| 2132 | owned_get=True, |
| 2133 | deadline_monotonic=time.monotonic() + 10.0, |
| 2134 | ) |
| 2135 | assert exc_unstarted.value.dispatched is False |
| 2136 | assert dispatched_events == [] |
| 2137 | |
| 2138 | monkeypatch.setattr( |
| 2139 | bounded_get, |
| 2140 | "get", |
| 2141 | lambda *_a, **_kw: (_ for _ in ()).throw(bounded_get.GetTimeout("in flight", started=True)), |
| 2142 | ) |
| 2143 | with pytest.raises(http.DeadlineExceeded) as exc_started: |
| 2144 | with http.observe_dispatch(lambda: dispatched_events.append(True)): |
| 2145 | http.get( |
| 2146 | "https://api.scrapecreators.com/v1/reddit/post/comments", |
| 2147 | owned_get=True, |
| 2148 | deadline_monotonic=time.monotonic() + 10.0, |
| 2149 | ) |
| 2150 | assert exc_started.value.dispatched is True |
| 2151 | assert dispatched_events == [True] |
| 2152 | |
| 2153 | |
| 2154 | # --------------------------------------------------------------------------- |
| 2155 | # Greptile Round 3 P2 #3: Pinned SC-primary incomplete empty -> TIMEOUT |
| 2156 | # --------------------------------------------------------------------------- |
| 2157 | |
| 2158 | |
| 2159 | class TestGreptileRound3P2PinnedIncompleteEmptyTimeout: |
| 2160 | def test_pinned_scrapecreators_incomplete_empty_after_date_filter_raises_timeout(self, monkeypatch): |
| 2161 | reddit.reset_scrapecreators_memo() |
| 2162 | now = [1000.0] |
| 2163 | monkeypatch.setattr(reddit.time, "monotonic", lambda: now[0]) |
| 2164 | |
| 2165 | # Phase 2 returns an out-of-window post (date filtered out in Phase 5), |
| 2166 | # and exhausts the budget before Phase 3 so search_reddit returns |
| 2167 | # {"items": [], "incomplete": True, "incomplete_note": ...}. |
| 2168 | def fake_global(*_args, **_kwargs): |
| 2169 | now[0] = 1050.0 |
| 2170 | return [{ |
| 2171 | "id": "old1", |
| 2172 | "title": "SQLite WAL write-ahead logging old post", |
| 2173 | "permalink": "/r/sqlite/comments/old1/wal/", |
| 2174 | "subreddit": "sqlite", |
| 2175 | "created_utc": 1700000000, # 2023-11-14: outside 2026-10-10..2026-11-10 |
| 2176 | "ups": 90, |
| 2177 | "num_comments": 10, |
| 2178 | }] |
| 2179 | |
| 2180 | monkeypatch.setattr(reddit, "_global_search", fake_global) |
| 2181 | monkeypatch.setattr(reddit, "_subreddit_search", mock.Mock(side_effect=AssertionError("Phase 3 must not run"))) |
| 2182 | monkeypatch.setattr(pipeline.reddit_public, "search_reddit_public", lambda *_a, **_kw: []) |
| 2183 | |
| 2184 | config = { |
| 2185 | "SCRAPECREATORS_API_KEY": "dummy-sc-key", |
| 2186 | pipeline.env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 2187 | "_research_deadline": 1050.0, |
| 2188 | } |
| 2189 | with pytest.raises(pipeline.SourceRunError) as exc_info: |
| 2190 | pipeline._retrieve_stream_impl( |
| 2191 | topic="SQLite WAL", |
| 2192 | subquery=schema.SubQuery( |
| 2193 | label="primary", |
| 2194 | search_query="SQLite WAL", |
| 2195 | ranking_query="SQLite WAL", |
| 2196 | sources=["reddit"], |
| 2197 | ), |
| 2198 | source="reddit", |
| 2199 | config=config, |
| 2200 | depth="quick", |
| 2201 | date_range=("2026-10-10", "2026-11-10"), |
| 2202 | runtime=_runtime("xquik"), |
| 2203 | mock=False, |
| 2204 | raw_topic="SQLite WAL", |
| 2205 | ) |
| 2206 | assert exc_info.value.outcome_state == health.TIMEOUT |
| 2207 | assert "deadline" in str(exc_info.value).lower() or "incomplete" in str(exc_info.value).lower() |
| 2208 | |
| 2209 | def test_pinned_scrapecreators_incomplete_empty_with_public_fallback_surfaces_timeout(self, monkeypatch): |
| 2210 | reddit.reset_scrapecreators_memo() |
| 2211 | monkeypatch.setattr( |
| 2212 | reddit, |
| 2213 | "search_and_enrich_memo", |
| 2214 | lambda *_a, **_kw: { |
| 2215 | "items": [], |
| 2216 | "incomplete": True, |
| 2217 | "incomplete_note": "Reddit search incomplete (deadline reached)", |
| 2218 | }, |
| 2219 | ) |
| 2220 | public_item = { |
| 2221 | "id": "R1", |
| 2222 | "title": "SQLite WAL public fallback item", |
| 2223 | "url": "https://www.reddit.com/r/sqlite/comments/pub1/wal/", |
| 2224 | "subreddit": "sqlite", |
| 2225 | "date": "2026-11-01", |
| 2226 | "score": 45, |
| 2227 | } |
| 2228 | monkeypatch.setattr( |
| 2229 | pipeline.reddit_public, |
| 2230 | "search_reddit_public", |
| 2231 | lambda *_a, **_kw: [public_item], |
| 2232 | ) |
| 2233 | |
| 2234 | items, artifact = pipeline._retrieve_stream_impl( |
| 2235 | topic="SQLite WAL", |
| 2236 | subquery=schema.SubQuery( |
| 2237 | label="primary", |
| 2238 | search_query="SQLite WAL", |
| 2239 | ranking_query="SQLite WAL", |
| 2240 | sources=["reddit"], |
| 2241 | ), |
| 2242 | source="reddit", |
| 2243 | config={ |
| 2244 | "SCRAPECREATORS_API_KEY": "dummy-sc-key", |
| 2245 | pipeline.env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 2246 | }, |
| 2247 | depth="quick", |
| 2248 | date_range=("2026-10-10", "2026-11-10"), |
| 2249 | runtime=_runtime("xquik"), |
| 2250 | mock=False, |
| 2251 | raw_topic="SQLite WAL", |
| 2252 | ) |
| 2253 | assert items == [public_item] |
| 2254 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 2255 | assert "deadline" in artifact["_source_outcome"]["detail"].lower() |
| 2256 |