| 1 | """Reddit on a network where site search is refused (ten live runs, 2026-11-10). |
| 2 | |
| 3 | What those runs logged, and what each test pins: |
| 4 | |
| 5 | [ArcticShift] listing search failed r/waymo: HTTP 422: Unprocessable Entity (x3 per URL) |
| 6 | [ArcticShift] comments lookup failed t3_...: HTTP 422: Unprocessable Entity |
| 7 | The archive's body was {"data":null,"error":"Timeout. Maybe slow down |
| 8 | a bit"}: it answers all but one of a set of identical concurrent |
| 9 | requests that way, and the lane sent each search once per subquery. |
| 10 | [RedditSearch] r/X page 1 failed: HTTP 403: Blocked (every sub, every subquery) |
| 11 | Reddit: 0 items (timeout: reddit timed out after 180s) |
| 12 | Reddit absent from Partial Coverage with search blocked and no comments. |
| 13 | """ |
| 14 | |
| 15 | import threading |
| 16 | import time |
| 17 | from unittest import mock |
| 18 | from urllib.parse import parse_qs, urlsplit |
| 19 | |
| 20 | import pytest |
| 21 | |
| 22 | from lib import health, http, pipeline, reddit_arctic, reddit_keyless, reddit_search, schema |
| 23 | |
| 24 | SLOW_DOWN = "HTTP 422: Unprocessable Entity" |
| 25 | |
| 26 | |
| 27 | @pytest.fixture(autouse=True) |
| 28 | def _no_reddit_kept_thread_comments(): |
| 29 | # Overrides conftest's no-op: these tests run the real comment pass with |
| 30 | # the comment fetch mocked. |
| 31 | yield |
| 32 | |
| 33 | |
| 34 | @pytest.fixture(autouse=True) |
| 35 | def _no_arctic_network(): |
| 36 | # Overrides conftest's stub: these tests run the real archive adapter |
| 37 | # with http.get mocked. |
| 38 | reddit_arctic.reset_memo() |
| 39 | yield |
| 40 | reddit_arctic.reset_memo() |
| 41 | |
| 42 | |
| 43 | def _row(pid, sub, score=10): |
| 44 | return { |
| 45 | "id": pid, "title": f"Elon Musk thread {pid}", "score": score, "num_comments": 3, |
| 46 | "subreddit": sub, "created_utc": 1794268800, # 2026-11-09 |
| 47 | "permalink": f"/r/{sub}/comments/{pid}/x/", "author": "someone", |
| 48 | } |
| 49 | |
| 50 | |
| 51 | class DuplicateIntolerantArchive: |
| 52 | """Answers like the archive: a request identical to one in flight gets 422.""" |
| 53 | |
| 54 | def __init__(self, hold=0.05): |
| 55 | self.lock = threading.Lock() |
| 56 | self.in_flight: set[str] = set() |
| 57 | self.calls: list[str] = [] |
| 58 | self.hold = hold |
| 59 | |
| 60 | def __call__(self, url, **_kwargs): |
| 61 | with self.lock: |
| 62 | self.calls.append(url) |
| 63 | duplicate = url in self.in_flight |
| 64 | self.in_flight.add(url) |
| 65 | if duplicate: |
| 66 | http._raise(http.HTTPError(SLOW_DOWN, status_code=422)) |
| 67 | try: |
| 68 | time.sleep(self.hold) |
| 69 | sub = parse_qs(urlsplit(url).query).get("subreddit", ["x"])[0] |
| 70 | return {"data": [_row(f"p{len(self.calls)}", sub)]} |
| 71 | finally: |
| 72 | with self.lock: |
| 73 | self.in_flight.discard(url) |
| 74 | |
| 75 | |
| 76 | class TestArchiveSharedAcrossSubqueries: |
| 77 | def test_four_subqueries_send_each_listing_search_once(self): |
| 78 | archive = DuplicateIntolerantArchive() |
| 79 | results: list[list] = [] |
| 80 | failures_seen: list[int] = [] |
| 81 | |
| 82 | def one_subquery(): |
| 83 | with http.capture_failures() as failures: |
| 84 | results.append(reddit_arctic.fetch_listings( |
| 85 | ["elonmusk", "teslamotors"], from_date="2026-10-12", to_date="2026-11-11", |
| 86 | )) |
| 87 | failures_seen.append(len(failures)) |
| 88 | |
| 89 | with mock.patch.object(reddit_arctic.http, "get", side_effect=archive), \ |
| 90 | mock.patch.object(reddit_arctic, "PACE_SECONDS", 0): |
| 91 | threads = [threading.Thread(target=one_subquery) for _ in range(4)] |
| 92 | [t.start() for t in threads] |
| 93 | [t.join() for t in threads] |
| 94 | |
| 95 | # 2 subreddits x 4 window slices, asked once each, never refused. |
| 96 | assert len(archive.calls) == len(set(archive.calls)) == 8 |
| 97 | assert failures_seen == [0, 0, 0, 0] |
| 98 | assert all(len(posts) == 8 for posts in results) |
| 99 | |
| 100 | def test_a_refused_slice_is_asked_for_again_after_the_others(self): |
| 101 | # The archive sheds load with the same 422 on some lone requests too, |
| 102 | # and a retry right after one tends to be refused again. |
| 103 | asked: list[str] = [] |
| 104 | refuse_once = {"waymo"} |
| 105 | |
| 106 | def get(url, **_kwargs): |
| 107 | sub = parse_qs(urlsplit(url).query)["subreddit"][0] |
| 108 | asked.append(sub) |
| 109 | if sub in refuse_once: |
| 110 | refuse_once.discard(sub) |
| 111 | http._raise(http.HTTPError(SLOW_DOWN, status_code=422)) |
| 112 | return {"data": [_row(f"{sub}1", sub)]} |
| 113 | |
| 114 | with mock.patch.object(reddit_arctic.http, "get", side_effect=get), \ |
| 115 | mock.patch.object(reddit_arctic.time, "sleep"), \ |
| 116 | http.capture_failures() as failures: |
| 117 | posts = reddit_arctic.fetch_listings(["waymo", "robotaxi"]) |
| 118 | |
| 119 | assert asked == ["waymo", "robotaxi", "waymo"] |
| 120 | assert sorted(post["subreddit"] for post in posts) == ["robotaxi", "waymo"] |
| 121 | # The recovered refusal is not reported as a lost sub-request. |
| 122 | assert failures == [] |
| 123 | |
| 124 | def test_a_refused_slice_with_no_time_left_is_reported(self, capsys): |
| 125 | clock = [0.0] |
| 126 | |
| 127 | def get(_url, **_kwargs): |
| 128 | clock[0] += 50 # past the 45s budget |
| 129 | http._raise(http.HTTPError(SLOW_DOWN, status_code=422)) |
| 130 | |
| 131 | with mock.patch.object(reddit_arctic.http, "get", side_effect=get), \ |
| 132 | mock.patch.object(reddit_arctic.time, "monotonic", side_effect=lambda: clock[0]), \ |
| 133 | mock.patch.object(reddit_arctic.time, "sleep"), \ |
| 134 | http.capture_failures() as failures: |
| 135 | assert reddit_arctic.fetch_listings(["waymo"]) == [] |
| 136 | |
| 137 | assert [failure.status_code for failure in failures] == [422] |
| 138 | assert f"listing search failed r/waymo: {SLOW_DOWN}" in capsys.readouterr().err |
| 139 | |
| 140 | def test_a_422_twice_is_reported_and_not_memoized(self): |
| 141 | def get(_url, **_kwargs): |
| 142 | http._raise(http.HTTPError(SLOW_DOWN, status_code=422)) |
| 143 | |
| 144 | with mock.patch.object(reddit_arctic.http, "get", side_effect=get) as archive, \ |
| 145 | mock.patch.object(reddit_arctic.time, "sleep"), \ |
| 146 | http.capture_failures() as failures: |
| 147 | assert reddit_arctic.fetch_listings(["waymo"]) == [] |
| 148 | assert reddit_arctic.fetch_listings(["waymo"]) == [] |
| 149 | |
| 150 | assert archive.call_count == 4 |
| 151 | assert [failure.status_code for failure in failures] == [422, 422] |
| 152 | |
| 153 | def test_comment_lookup_is_shared_and_retried(self): |
| 154 | comment = {"author": "reader", "body": "worth reading", "score": 7, |
| 155 | "permalink": "/r/elonmusk/comments/abc/x/c1/", "created_utc": 1794268800} |
| 156 | answers = iter([http.HTTPError(SLOW_DOWN, status_code=422), |
| 157 | {"data": [{"kind": "t1", "data": comment}]}]) |
| 158 | |
| 159 | def get(_url, **_kwargs): |
| 160 | answer = next(answers) |
| 161 | if isinstance(answer, Exception): |
| 162 | http._raise(answer) |
| 163 | return answer |
| 164 | |
| 165 | with mock.patch.object(reddit_arctic.http, "get", side_effect=get) as archive, \ |
| 166 | mock.patch.object(reddit_arctic.time, "sleep"): |
| 167 | first = reddit_arctic.fetch_post_comments("abc") |
| 168 | second = reddit_arctic.fetch_post_comments("t3_abc") |
| 169 | |
| 170 | assert [c["author"] for c in first] == ["reader"] |
| 171 | assert second == first |
| 172 | assert archive.call_count == 2 # the refusal, the retry; the second lookup is free |
| 173 | |
| 174 | def test_deadline_drops_the_oldest_week_not_the_newest(self): |
| 175 | asked: list[str] = [] |
| 176 | clock = [0.0] |
| 177 | |
| 178 | def get(url, **_kwargs): |
| 179 | asked.append(parse_qs(urlsplit(url).query)["before"][0]) |
| 180 | clock[0] += 30 # two requests fit in the 45s budget |
| 181 | return {"data": []} |
| 182 | |
| 183 | with mock.patch.object(reddit_arctic.http, "get", side_effect=get), \ |
| 184 | mock.patch.object(reddit_arctic.time, "monotonic", side_effect=lambda: clock[0]), \ |
| 185 | mock.patch.object(reddit_arctic.time, "sleep"): |
| 186 | reddit_arctic.fetch_listings(["elonmusk"], from_date="2026-10-12", to_date="2026-11-11") |
| 187 | |
| 188 | assert asked == ["2026-11-11", "2026-11-05"] |
| 189 | |
| 190 | |
| 191 | class BlockedSearch: |
| 192 | def __init__(self): |
| 193 | self.requests: list[str] = [] |
| 194 | |
| 195 | def __call__(self, url, **_kwargs): |
| 196 | self.requests.append(url) |
| 197 | http._record_failure(http.HTTPError("HTTP 403: Blocked", 403)) |
| 198 | return None |
| 199 | |
| 200 | |
| 201 | @pytest.fixture |
| 202 | def blocked_search(): |
| 203 | fake = BlockedSearch() |
| 204 | with mock.patch.object(http, "get_text", side_effect=fake), \ |
| 205 | mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \ |
| 206 | mock.patch.object(http.time, "sleep"): |
| 207 | yield fake |
| 208 | |
| 209 | |
| 210 | SUBS = ["elonmusk", "EnoughMuskSpam", "teslamotors", "teslainvestorsclub", "SpaceX"] |
| 211 | |
| 212 | |
| 213 | class TestBlockedSiteSearchFailsFast: |
| 214 | def test_first_block_stops_the_remaining_subreddits(self, blocked_search, capsys): |
| 215 | with mock.patch.object(reddit_search, "MAX_WORKERS", 1): |
| 216 | assert reddit_search.search("Elon Musk", subreddits=SUBS) == [] |
| 217 | |
| 218 | # One refused request, not one per subreddit plus the global search. |
| 219 | assert len(blocked_search.requests) == 1 |
| 220 | assert reddit_search.failed_reason() == "HTTP 403: Blocked" |
| 221 | assert "site search is blocked for this network" in capsys.readouterr().err |
| 222 | |
| 223 | def test_later_subqueries_of_the_command_do_not_ask_again(self, blocked_search): |
| 224 | with mock.patch.object(reddit_search, "MAX_WORKERS", 1): |
| 225 | for _subquery in range(4): |
| 226 | assert reddit_search.search("Elon Musk", subreddits=SUBS) == [] |
| 227 | |
| 228 | assert len(blocked_search.requests) == 1 |
| 229 | |
| 230 | def test_a_private_subreddit_403_does_not_stop_the_others(self): |
| 231 | requests: list[str] = [] |
| 232 | |
| 233 | def get_text(url, **_kwargs): |
| 234 | requests.append(url) |
| 235 | http._record_failure(http.HTTPError("HTTP 403: Forbidden", 403)) |
| 236 | return None |
| 237 | |
| 238 | with mock.patch.object(http, "get_text", side_effect=get_text), \ |
| 239 | mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \ |
| 240 | mock.patch.object(http.time, "sleep"): |
| 241 | reddit_search.search("Elon Musk", subreddits=SUBS, depth="quick") |
| 242 | |
| 243 | assert len(requests) == len(SUBS) + 1 |
| 244 | assert reddit_search.failed_reason() is None |
| 245 | |
| 246 | |
| 247 | def _post(pid): |
| 248 | return { |
| 249 | "id": "", "title": f"Elon Musk thread {pid}", |
| 250 | "url": f"https://www.reddit.com/r/elonmusk/comments/{pid}/x/", |
| 251 | "score": 50, "num_comments": 9, "subreddit": "elonmusk", "date": "2026-11-09", |
| 252 | "engagement": {"score": 50, "num_comments": 9}, "relevance": 0.9, |
| 253 | "metadata": {"post_id": pid}, |
| 254 | } |
| 255 | |
| 256 | |
| 257 | class TestLaneReturnsWhatItHasInsideItsBudget: |
| 258 | def test_spent_budget_skips_enrichment_and_keeps_the_threads(self, capsys): |
| 259 | posts = [_post("a"), _post("b"), _post("c")] |
| 260 | with mock.patch.object(reddit_keyless, "_discover", return_value=posts), \ |
| 261 | mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments") as comments, \ |
| 262 | reddit_keyless.lane_deadline(time.monotonic() + 0.5): |
| 263 | out = reddit_keyless.search_and_enrich( |
| 264 | "Elon Musk", "2026-10-12", "2026-11-11", subreddits=["elonmusk"], |
| 265 | ) |
| 266 | |
| 267 | assert len(out) == 3 |
| 268 | comments.assert_not_called() |
| 269 | assert "comment enrichment skipped: lane budget spent" in capsys.readouterr().err |
| 270 | |
| 271 | def test_spent_budget_skips_the_later_discovery_stages(self): |
| 272 | listing = [_post("a"), _post("b")] |
| 273 | with mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings", return_value=listing), \ |
| 274 | mock.patch.object(reddit_keyless.reddit_search, "search") as search, \ |
| 275 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_listings") as archive, \ |
| 276 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_scores") as scores: |
| 277 | out = reddit_keyless._discover( |
| 278 | "Elon Musk", "default", ["teslamotors"], dedicated_subreddits=["elonmusk"], |
| 279 | from_date="2026-10-12", to_date="2026-11-11", deadline=time.monotonic() + 0.5, |
| 280 | ) |
| 281 | |
| 282 | # The dedicated subreddit's listing came back; nothing slower is started. |
| 283 | assert [post["metadata"]["post_id"] for post in out] == ["a", "b"] |
| 284 | search.assert_not_called() |
| 285 | archive.assert_not_called() |
| 286 | scores.assert_not_called() |
| 287 | |
| 288 | def test_enrichment_wait_is_capped_by_the_lane_deadline(self): |
| 289 | release = threading.Event() |
| 290 | |
| 291 | def slow_comments(_url, deadline=None, post_author=None): |
| 292 | release.wait(5) |
| 293 | return {"top_comments": [], "comment_insights": [], "num_comments": None} |
| 294 | |
| 295 | started = time.monotonic() |
| 296 | try: |
| 297 | with mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments", side_effect=slow_comments): |
| 298 | out = reddit_keyless._enrich( |
| 299 | [_post("a"), _post("b")], "default", lane_deadline=time.monotonic() + 2.3, |
| 300 | ) |
| 301 | finally: |
| 302 | release.set() |
| 303 | |
| 304 | assert len(out) == 2 |
| 305 | assert time.monotonic() - started < 4 |
| 306 | |
| 307 | def test_pipeline_gives_the_lane_a_deadline_before_the_stream_wait_ends(self): |
| 308 | seen: list[float | None] = [] |
| 309 | |
| 310 | def public(*_args, **_kwargs): |
| 311 | seen.append(reddit_keyless._lane_deadline.get()) |
| 312 | return [_post("a")] |
| 313 | |
| 314 | research_deadline = time.monotonic() + 180 |
| 315 | with mock.patch("lib.reddit_public.search_reddit_public", side_effect=public): |
| 316 | _stream({"_research_deadline": research_deadline}) |
| 317 | |
| 318 | assert seen == [research_deadline - pipeline.REDDIT_LANE_RETURN_MARGIN_SECONDS] |
| 319 | |
| 320 | |
| 321 | def test_lane_that_starts_with_no_budget_is_a_timeout_not_no_results(): |
| 322 | # Under proportional return-margin scaling, < ~2.35s remaining leaves |
| 323 | # under MIN_STAGE_SECONDS (2s) for the free lane. |
| 324 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=[]): |
| 325 | items, artifact = _stream({"_research_deadline": time.monotonic() + 1.5}) |
| 326 | |
| 327 | assert items == [] |
| 328 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 329 | |
| 330 | |
| 331 | def test_lane_that_finds_nothing_in_time_is_still_no_results(): |
| 332 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=[]): |
| 333 | items, artifact = _stream({"_research_deadline": time.monotonic() + 180}) |
| 334 | |
| 335 | assert items == [] |
| 336 | assert "_source_outcome" not in (artifact or {}) |
| 337 | |
| 338 | |
| 339 | def _stream(config): |
| 340 | return pipeline._retrieve_stream( |
| 341 | topic="Elon Musk", |
| 342 | subquery=schema.SubQuery( |
| 343 | label="primary", search_query="Elon Musk", ranking_query="Elon Musk", sources=["reddit"], |
| 344 | ), |
| 345 | source="reddit", config=config, depth="quick", |
| 346 | date_range=("2026-10-12", "2026-11-11"), |
| 347 | runtime=schema.ProviderRuntime( |
| 348 | reasoning_provider="mock", planner_model="mock", rerank_model="mock", |
| 349 | ), |
| 350 | mock=False, |
| 351 | ) |
| 352 | |
| 353 | |
| 354 | class TestBlockedSearchIsAServedPathDetail: |
| 355 | """A refused site search is one path failing while the others serve: the |
| 356 | source stays ok and the detail names what served (R17, R21).""" |
| 357 | |
| 358 | def test_listing_threads_with_search_blocked_stay_ok(self, blocked_search): |
| 359 | listing = [_post("a"), _post("b")] |
| 360 | limited: set = set() |
| 361 | with mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings", return_value=listing), \ |
| 362 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_listings", return_value=[]), \ |
| 363 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_scores", return_value={}), \ |
| 364 | mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments", return_value={}), \ |
| 365 | mock.patch.object(reddit_search, "MAX_WORKERS", 1): |
| 366 | items, artifact = pipeline._retrieve_stream( |
| 367 | topic="Elon Musk", |
| 368 | subquery=schema.SubQuery( |
| 369 | label="primary", search_query="Elon Musk", ranking_query="Elon Musk", |
| 370 | sources=["reddit"], |
| 371 | ), |
| 372 | source="reddit", config={}, depth="quick", |
| 373 | date_range=("2026-10-12", "2026-11-11"), |
| 374 | subreddits=["elonmusk"], |
| 375 | runtime=schema.ProviderRuntime( |
| 376 | reasoning_provider="mock", planner_model="mock", rerank_model="mock", |
| 377 | ), |
| 378 | mock=False, rate_limited_sources=limited, |
| 379 | ) |
| 380 | |
| 381 | assert len(items) == 2 |
| 382 | assert "_source_outcome" not in artifact |
| 383 | assert artifact["_source_outcome_detail"] == "listing served 2; search blocked" |
| 384 | assert artifact.get("_source_outcome_detail_state") is None |
| 385 | assert "reddit" not in limited |
| 386 | |
| 387 | def test_working_search_leaves_reddit_ok(self): |
| 388 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=[_post("a")]): |
| 389 | items, artifact = _stream({}) |
| 390 | |
| 391 | assert len(items) == 1 |
| 392 | assert "_source_outcome" not in (artifact or {}) |
| 393 | |
| 394 | def test_partial_outcome_reaches_the_bundle_as_degraded(self): |
| 395 | bundle = schema.RetrievalBundle() |
| 396 | bundle.add_items("primary", "reddit", [ |
| 397 | schema.SourceItem(item_id="R1", source="reddit", title="t", body="", url="https://reddit.com/x"), |
| 398 | ]) |
| 399 | |
| 400 | bundle.record_failure("reddit", health.PARTIAL, "Reddit site search was blocked") |
| 401 | |
| 402 | assert bundle.source_status["reddit"].state == health.PARTIAL |
| 403 | assert bundle.source_status["reddit"].items_returned == 1 |
| 404 | |
| 405 | |
| 406 | # --- ScrapeCreators backfill (the owner's runs had a key and no backfill) --- |
| 407 | # |
| 408 | # "Fable 5.2": the free lane returned dozens of listing threads from the |
| 409 | # targeted subreddits, so the raw count never fell under the 5-item floor; |
| 410 | # the stream's relevance prune then kept one. "Elon Musk": the free lane was |
| 411 | # still running when the 180s wait ended, so the backfill, which comes after |
| 412 | # it in the same stream, never got a turn. |
| 413 | |
| 414 | KEY = {"SCRAPECREATORS_API_KEY": "dummy-key"} |
| 415 | |
| 416 | |
| 417 | def _off_topic(pid): |
| 418 | return {**_post(pid), "title": f"Weekly megathread {pid}", "relevance": 0.0} |
| 419 | |
| 420 | |
| 421 | def _sc_item(pid): |
| 422 | return {"url": f"https://www.reddit.com/r/elonmusk/comments/{pid}/x/", "title": f"Elon Musk {pid}"} |
| 423 | |
| 424 | |
| 425 | class TestBackfillRunsWhenFreeResultIsThin: |
| 426 | def _run(self, config, public, sc_side_effect=None, sc_items=()): |
| 427 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=public), \ |
| 428 | mock.patch("lib.reddit.search_and_enrich", return_value={"raw": 1}, |
| 429 | side_effect=sc_side_effect) as sc, \ |
| 430 | mock.patch("lib.reddit.parse_reddit_response", return_value=list(sc_items)): |
| 431 | items, artifact = _stream(config) |
| 432 | return items, artifact, sc |
| 433 | |
| 434 | def test_many_off_topic_listing_threads_do_not_hide_a_thin_result(self, capsys): |
| 435 | free = [_post("a")] + [_off_topic(f"o{i}") for i in range(40)] |
| 436 | |
| 437 | items, artifact, sc = self._run(KEY, free, sc_items=[_sc_item("z")]) |
| 438 | |
| 439 | sc.assert_called_once() |
| 440 | assert len(items) == 42 |
| 441 | assert "41 free items" in artifact["_source_outcome_detail"] |
| 442 | assert "(1 on topic, below the 5-item floor)" in capsys.readouterr().err |
| 443 | |
| 444 | def test_five_on_topic_threads_spend_nothing(self): |
| 445 | free = [_post(c) for c in "abcde"] + [_off_topic("o1")] |
| 446 | |
| 447 | _items, _artifact, sc = self._run(KEY, free, sc_items=[_sc_item("z")]) |
| 448 | |
| 449 | sc.assert_not_called() |
| 450 | |
| 451 | def test_no_key_never_backfills(self): |
| 452 | _items, _artifact, sc = self._run({}, [_off_topic("o1")], sc_items=[_sc_item("z")]) |
| 453 | |
| 454 | sc.assert_not_called() |
| 455 | |
| 456 | def test_free_lane_stops_early_enough_to_leave_the_backfill_a_turn(self): |
| 457 | seen: list[float | None] = [] |
| 458 | |
| 459 | def public(*_args, **_kwargs): |
| 460 | seen.append(reddit_keyless._lane_deadline.get()) |
| 461 | return [_post(c) for c in "abcde"] |
| 462 | |
| 463 | research_deadline = time.monotonic() + 180 |
| 464 | with mock.patch("lib.reddit_public.search_reddit_public", side_effect=public): |
| 465 | _stream({**KEY, "_research_deadline": research_deadline}) |
| 466 | |
| 467 | assert seen == [ |
| 468 | research_deadline - pipeline.REDDIT_LANE_RETURN_MARGIN_SECONDS |
| 469 | - pipeline.REDDIT_SC_BACKFILL_RESERVE_SECONDS |
| 470 | ] |
| 471 | |
| 472 | def test_free_path_that_timed_out_with_nothing_is_backfilled(self, capsys, monkeypatch): |
| 473 | # 60s left gives the free lane 30s and reserves 21s+9s for backfill; |
| 474 | # simulate the free lane spending its 30s share without finding threads, |
| 475 | # leaving room for ScrapeCreators backfill before the research deadline. |
| 476 | now = [1000.0] |
| 477 | monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0]) |
| 478 | monkeypatch.setattr(reddit_keyless.time, "monotonic", lambda: now[0]) |
| 479 | |
| 480 | def exhausted_free(*_args, **_kwargs): |
| 481 | now[0] += 30.0 |
| 482 | return [] |
| 483 | |
| 484 | config = {**KEY, "_research_deadline": now[0] + 60.0} |
| 485 | with mock.patch("lib.reddit_public.search_reddit_public", side_effect=exhausted_free), \ |
| 486 | mock.patch("lib.reddit.search_and_enrich", return_value={"raw": 1}) as sc, \ |
| 487 | mock.patch("lib.reddit.parse_reddit_response", return_value=[_sc_item("z")]): |
| 488 | items, _artifact = _stream(config) |
| 489 | |
| 490 | sc.assert_called_once() |
| 491 | assert [item["title"] for item in items] == ["Elon Musk z"] |
| 492 | assert "Free path ran out of time with no threads; backfilling" in capsys.readouterr().err |
| 493 | |
| 494 | def test_slow_backfill_is_abandoned_and_the_free_threads_are_kept(self, monkeypatch): |
| 495 | release = threading.Event() |
| 496 | monkeypatch.setattr(pipeline, "REDDIT_SC_BACKFILL_MIN_SECONDS", 0.1) |
| 497 | monkeypatch.setattr(pipeline, "REDDIT_SC_BACKFILL_RETURN_MARGIN_SECONDS", 0.0) |
| 498 | monkeypatch.setattr(pipeline, "REDDIT_SC_BACKFILL_RESERVE_SECONDS", 0.0) |
| 499 | monkeypatch.setattr(pipeline, "REDDIT_LANE_RETURN_MARGIN_SECONDS", 0.0) |
| 500 | |
| 501 | def slow(*_args, **_kwargs): |
| 502 | release.wait(5) |
| 503 | return {"raw": 1} |
| 504 | |
| 505 | started = time.monotonic() |
| 506 | try: |
| 507 | items, artifact, _sc = self._run( |
| 508 | {**KEY, "_research_deadline": time.monotonic() + 0.5}, [_post("a")], |
| 509 | sc_side_effect=slow, |
| 510 | ) |
| 511 | finally: |
| 512 | release.set() |
| 513 | |
| 514 | assert time.monotonic() - started < 3 |
| 515 | assert [item["metadata"]["post_id"] for item in items] == ["a"] |
| 516 | assert "ScrapeCreators backfill failed after 1 free items" in artifact["_source_outcome_detail"] |
| 517 | assert "did not finish" in artifact["_source_outcome_detail"] |
| 518 | |
| 519 | |
| 520 | # --- Every kept thread carries its top comments --- |
| 521 | # |
| 522 | # Lane-time enrichment picks its 8 slots before the pipeline's relevance |
| 523 | # prune and ranking; in the 2026-11-10 runs 3 to 5 of the final 12 threads |
| 524 | # had comments. |
| 525 | |
| 526 | |
| 527 | def _kept(pid, num_comments=9, top_comments=None): |
| 528 | return schema.SourceItem( |
| 529 | item_id=pid, source="reddit", title=f"Elon Musk thread {pid}", body="", |
| 530 | url=f"https://www.reddit.com/r/elonmusk/comments/{pid}/x/", container="elonmusk", |
| 531 | engagement={"score": 50, "num_comments": num_comments}, |
| 532 | metadata={"top_comments": top_comments} if top_comments else {}, |
| 533 | ) |
| 534 | |
| 535 | |
| 536 | def _comments_for(url, deadline=None, post_author=None): |
| 537 | pid = url.rstrip("/").split("/")[-2] |
| 538 | return { |
| 539 | "top_comments": [{ |
| 540 | "score": 321, "date": "2026-11-09", "author": f"reader_{pid}", |
| 541 | "excerpt": f"Top comment on {pid}", |
| 542 | "url": f"https://reddit.com/r/elonmusk/comments/{pid}/x/c_{pid}/", |
| 543 | }], |
| 544 | "comment_insights": [f"Insight on {pid}"], |
| 545 | "num_comments": 44, |
| 546 | } |
| 547 | |
| 548 | |
| 549 | class TestKeptThreadsGetTheirTopComments: |
| 550 | def test_every_kept_thread_without_comments_is_fetched_in_rank_order(self): |
| 551 | already = [{"score": 5, "author": "early", "excerpt": "kept", "url": "https://reddit.com/c"}] |
| 552 | items = [_kept("a", top_comments=already)] + [_kept(f"t{i}") for i in range(11)] |
| 553 | |
| 554 | with mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments", |
| 555 | side_effect=_comments_for) as fetch: |
| 556 | reddit_keyless.enrich_source_items(items) |
| 557 | |
| 558 | assert fetch.call_count == 11 # the thread the lane enriched costs nothing |
| 559 | assert all(item.metadata.get("top_comments") for item in items) |
| 560 | assert items[0].metadata["top_comments"] == already |
| 561 | top = items[3].metadata["top_comments"][0] |
| 562 | assert (top["author"], top["score"], top["url"]) == ( |
| 563 | "reader_t2", 321, "https://reddit.com/r/elonmusk/comments/t2/x/c_t2/", |
| 564 | ) |
| 565 | assert items[3].metadata["comment_insights"] == ["Insight on t2"] |
| 566 | assert items[3].engagement["num_comments"] == 44 |
| 567 | |
| 568 | def test_cap_goes_to_the_highest_ranked_threads(self): |
| 569 | items = [_kept(f"t{i}") for i in range(20)] |
| 570 | |
| 571 | with mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments", |
| 572 | side_effect=_comments_for): |
| 573 | reddit_keyless.enrich_source_items(items, depth="default") |
| 574 | |
| 575 | with_comments = [bool(item.metadata.get("top_comments")) for item in items] |
| 576 | assert with_comments == [True] * 12 + [False] * 8 |
| 577 | |
| 578 | def test_thread_with_no_comments_is_not_fetched(self): |
| 579 | with mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments") as fetch: |
| 580 | reddit_keyless.enrich_source_items([_kept("a", num_comments=0)]) |
| 581 | |
| 582 | fetch.assert_not_called() |
| 583 | |
| 584 | def test_no_time_left_fetches_nothing(self): |
| 585 | with mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments") as fetch: |
| 586 | reddit_keyless.enrich_source_items([_kept("a")], deadline=time.monotonic() + 0.5) |
| 587 | |
| 588 | fetch.assert_not_called() |
| 589 | |
| 590 | def test_slow_fetch_does_not_hold_the_report(self, monkeypatch): |
| 591 | release = threading.Event() |
| 592 | monkeypatch.setattr(reddit_keyless, "FINAL_ENRICH_BUDGET", 2.2) |
| 593 | |
| 594 | def fetch(url, deadline=None, post_author=None): |
| 595 | if url.endswith("/slow/x/"): |
| 596 | release.wait(5) |
| 597 | return _comments_for(url) |
| 598 | |
| 599 | items = [_kept("fast"), _kept("slow")] |
| 600 | started = time.monotonic() |
| 601 | try: |
| 602 | with mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments", side_effect=fetch): |
| 603 | reddit_keyless.enrich_source_items(items) |
| 604 | finally: |
| 605 | release.set() |
| 606 | |
| 607 | assert time.monotonic() - started < 4 |
| 608 | assert items[0].metadata.get("top_comments") and not items[1].metadata.get("top_comments") |
| 609 | |
| 610 | def test_finalize_enriches_the_surviving_reddit_threads(self): |
| 611 | items = [_kept(f"t{i}") for i in range(3)] |
| 612 | titles = ["Starship flight 15 catch", "Tesla pay package vote passes", "Neuralink trial update"] |
| 613 | for rank, (item, title) in enumerate(zip(items, titles)): |
| 614 | item.title = title # distinct, so the text dedupe keeps all three |
| 615 | item.local_rank_score = 1.0 - rank / 10 |
| 616 | |
| 617 | with mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments", |
| 618 | side_effect=_comments_for): |
| 619 | finalized = pipeline._finalize_items_by_source({"reddit": items}, topic="Elon Musk", config={}) |
| 620 | |
| 621 | assert [bool(item.metadata.get("top_comments")) for item in finalized["reddit"]] == [True] * 3 |
| 622 | |
| 623 | |
| 624 | # --- Review findings on the lane deadline (PR #1408) --- |
| 625 | |
| 626 | |
| 627 | class TestLaneDeadlineIsHard: |
| 628 | def test_listing_that_spends_the_budget_still_returns_its_threads(self): |
| 629 | # The shreddit listing returns with the budget gone: the archive |
| 630 | # supplement is skipped and the threads already fetched come back. |
| 631 | deadline = time.monotonic() + 3 |
| 632 | |
| 633 | def slow_listing(*_args, **_kwargs): |
| 634 | time.sleep(1.5) # under MIN_STAGE_SECONDS left afterwards |
| 635 | return [_post("a"), _post("b")] |
| 636 | |
| 637 | with mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings", side_effect=slow_listing), \ |
| 638 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_listings") as archive: |
| 639 | posts = reddit_keyless._scored_listings(["elonmusk"], deadline=deadline) |
| 640 | |
| 641 | archive.assert_not_called() |
| 642 | assert [post["metadata"]["post_id"] for post in posts] == ["a", "b"] |
| 643 | |
| 644 | def test_running_site_search_is_abandoned_at_the_deadline(self): |
| 645 | release = threading.Event() |
| 646 | |
| 647 | def slow_search(*_args, **_kwargs): |
| 648 | release.wait(10) |
| 649 | return [_post("late")] |
| 650 | |
| 651 | started = time.monotonic() |
| 652 | try: |
| 653 | with mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings", |
| 654 | return_value=[_post("a"), _post("b")]), \ |
| 655 | mock.patch.object(reddit_keyless.reddit_search, "search", side_effect=slow_search), \ |
| 656 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_listings", return_value=[]), \ |
| 657 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_scores", return_value={}): |
| 658 | out = reddit_keyless._discover( |
| 659 | "Elon Musk", "default", None, dedicated_subreddits=["elonmusk"], |
| 660 | from_date="2026-10-12", to_date="2026-11-11", deadline=time.monotonic() + 3, |
| 661 | ) |
| 662 | finally: |
| 663 | release.set() |
| 664 | |
| 665 | # The search started with budget left and never came back: the lane |
| 666 | # stops waiting at its deadline and keeps the dedicated threads. |
| 667 | assert time.monotonic() - started < 5 |
| 668 | assert [post["metadata"]["post_id"] for post in out] == ["a", "b"] |
| 669 | |
| 670 | @pytest.mark.parametrize("slow", ["listing", "scores"]) |
| 671 | def test_running_listing_and_score_calls_are_abandoned_too(self, slow): |
| 672 | release = threading.Event() |
| 673 | |
| 674 | def hang(*_args, **_kwargs): |
| 675 | release.wait(10) |
| 676 | return [] if slow == "listing" else {} |
| 677 | |
| 678 | unscored = {**_post("s"), "score": 0, "engagement": {"score": 0, "num_comments": 0}} |
| 679 | listing = hang if slow == "listing" else (lambda *_a, **_k: []) |
| 680 | scores = hang if slow == "scores" else (lambda *_a, **_k: {}) |
| 681 | started = time.monotonic() |
| 682 | try: |
| 683 | with mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings", side_effect=listing), \ |
| 684 | mock.patch.object(reddit_keyless.reddit_search, "search", return_value=[unscored]), \ |
| 685 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_listings", return_value=[]), \ |
| 686 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_scores", side_effect=scores): |
| 687 | out = reddit_keyless._discover( |
| 688 | "Elon Musk", "default", ["elonmusk"], |
| 689 | from_date="2026-10-12", to_date="2026-11-11", deadline=time.monotonic() + 3, |
| 690 | ) |
| 691 | finally: |
| 692 | release.set() |
| 693 | |
| 694 | assert time.monotonic() - started < 5 |
| 695 | assert [post["metadata"]["post_id"] for post in out] == ["s"] |
| 696 | |
| 697 | |
| 698 | # --- A stage that hits the deadline returns what it fetched (PR #1408) --- |
| 699 | |
| 700 | |
| 701 | class TestStagesReturnPartialResultsBeforeTheWait: |
| 702 | def test_archive_threads_fetched_before_the_deadline_are_kept(self): |
| 703 | # The archive answers one slice, then a later request runs into the |
| 704 | # deadline. Its partial result must come back before the lane stops |
| 705 | # waiting for it. |
| 706 | calls = [0] |
| 707 | |
| 708 | def get(url, **kwargs): |
| 709 | calls[0] += 1 |
| 710 | if calls[0] == 1: |
| 711 | return {"data": [_row("a1", "elonmusk")]} |
| 712 | time.sleep(max(0.0, kwargs["deadline_monotonic"] - time.monotonic())) |
| 713 | raise http.DeadlineExceeded() |
| 714 | |
| 715 | with mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings", return_value=[]), \ |
| 716 | mock.patch.object(reddit_arctic.http, "get", side_effect=get), \ |
| 717 | mock.patch.object(reddit_arctic, "PACE_SECONDS", 0): |
| 718 | posts = reddit_keyless._scored_listings( |
| 719 | ["elonmusk"], from_date="2026-10-12", to_date="2026-11-11", |
| 720 | deadline=time.monotonic() + 5, |
| 721 | ) |
| 722 | |
| 723 | assert [post["metadata"]["post_id"] for post in posts] == ["a1"] |
| 724 | |
| 725 | def test_listing_keeps_the_feeds_that_answered(self): |
| 726 | release = threading.Event() |
| 727 | |
| 728 | def fetch_one(sub, sort, query, timeframe): |
| 729 | if sort == "hot": |
| 730 | release.wait(10) |
| 731 | return [] |
| 732 | return [_post("top1")] |
| 733 | |
| 734 | try: |
| 735 | with mock.patch.object(reddit_keyless.reddit_listing, "_fetch_one", side_effect=fetch_one), \ |
| 736 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_listings", return_value=[]): |
| 737 | posts = reddit_keyless._scored_listings( |
| 738 | ["elonmusk"], sorts=["top", "hot"], deadline=time.monotonic() + 5, |
| 739 | ) |
| 740 | finally: |
| 741 | release.set() |
| 742 | |
| 743 | assert [post["metadata"]["post_id"] for post in posts] == ["top1"] |
| 744 | |
| 745 | def test_site_search_with_a_targeted_sub_returns_its_posts(self): |
| 746 | release = threading.Event() |
| 747 | |
| 748 | def stream(query, time_filter, pages, subreddit=None, deadline=None, collector=None): |
| 749 | if subreddit is None: |
| 750 | release.wait(10) |
| 751 | return [] |
| 752 | return [_post("s1")] |
| 753 | |
| 754 | try: |
| 755 | with mock.patch.object(reddit_search, "_search_stream", side_effect=stream): |
| 756 | posts = reddit_search.search( |
| 757 | "Elon Musk", subreddits=["elonmusk"], deadline=time.monotonic() + 2, |
| 758 | ) |
| 759 | finally: |
| 760 | release.set() |
| 761 | |
| 762 | assert [post["metadata"]["post_id"] for post in posts] == ["s1"] |
| 763 | |
| 764 | def test_score_lookup_keeps_the_batches_that_answered(self): |
| 765 | calls = [0] |
| 766 | |
| 767 | def get(url, **kwargs): |
| 768 | calls[0] += 1 |
| 769 | if calls[0] == 1: |
| 770 | return {"data": [{"id": "a", "score": 7, "num_comments": 2}]} |
| 771 | time.sleep(kwargs["timeout"]) |
| 772 | raise http.DeadlineExceeded() |
| 773 | |
| 774 | with mock.patch.object(reddit_arctic.http, "get", side_effect=get), \ |
| 775 | mock.patch.object(reddit_arctic, "BATCH", 1), \ |
| 776 | mock.patch.object(reddit_arctic, "PACE_SECONDS", 0): |
| 777 | scores = reddit_keyless._within( |
| 778 | time.monotonic() + 5, "score lookup", {}, |
| 779 | reddit_arctic.fetch_scores, ["a", "b"], |
| 780 | **reddit_keyless._stage_deadline(time.monotonic() + 5), |
| 781 | ) |
| 782 | |
| 783 | assert scores == {"a": {"score": 7, "num_comments": 2}} |
| 784 |