| 1 | """Pipeline Reddit dispatch: free-first, SC thinness-floor backfill (U7), and |
| 2 | that the keyless path never calls search.json (U2).""" |
| 3 | |
| 4 | from unittest import mock |
| 5 | from urllib.parse import urlsplit |
| 6 | |
| 7 | from pathlib import Path |
| 8 | |
| 9 | from lib import env, health, http, pipeline, reddit_keyless, schema |
| 10 | |
| 11 | |
| 12 | def _subquery(): |
| 13 | return schema.SubQuery(label="t", search_query="kanye", ranking_query="kanye", |
| 14 | sources=["reddit"]) |
| 15 | |
| 16 | |
| 17 | def _runtime(): |
| 18 | return schema.ProviderRuntime(reasoning_provider="mock", planner_model="mock", |
| 19 | rerank_model="mock") |
| 20 | |
| 21 | |
| 22 | def _item(rid): |
| 23 | # On topic for the "kanye" stream: the backfill floor counts the free |
| 24 | # threads its relevance prune will keep. |
| 25 | return { |
| 26 | "url": f"https://www.reddit.com/r/x/comments/{rid}/t/", "title": f"kanye {rid}", |
| 27 | "engagement": {"score": 40, "num_comments": 5}, |
| 28 | } |
| 29 | |
| 30 | |
| 31 | def _ids(items): |
| 32 | return [pipeline._reddit_post_key(i) for i in items] |
| 33 | |
| 34 | |
| 35 | class TestThinnessFloor: |
| 36 | KEY = {"SCRAPECREATORS_API_KEY": "k"} |
| 37 | FLOOR = env.REDDIT_SC_MIN_ITEMS_VAR |
| 38 | |
| 39 | def _run(self, config, public, sc_parsed): |
| 40 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=public), \ |
| 41 | mock.patch("lib.reddit.search_and_enrich", return_value={"raw": 1}) as sc, \ |
| 42 | mock.patch("lib.reddit.parse_reddit_response", return_value=sc_parsed): |
| 43 | items, _ = _stream(config) |
| 44 | return items, sc |
| 45 | |
| 46 | def test_unset_floor_backfills_thin_free_run_free_first(self): |
| 47 | # Default floor is 5: 3 free items < 5 -> one SC call, free first. |
| 48 | free = [_item("a"), _item("b"), _item("c")] |
| 49 | items, sc = self._run(self.KEY, free, [_item("b"), _item("z")]) |
| 50 | sc.assert_called_once() |
| 51 | assert _ids(items) == ["a", "b", "c", "z"] |
| 52 | |
| 53 | def test_unset_floor_six_free_items_spends_nothing(self): |
| 54 | free = [_item(c) for c in "abcdef"] |
| 55 | items, sc = self._run(self.KEY, free, [_item("z")]) |
| 56 | sc.assert_not_called() |
| 57 | assert len(items) == 6 |
| 58 | |
| 59 | def test_exactly_default_floor_is_acceptable(self): |
| 60 | free = [_item(c) for c in "abcde"] |
| 61 | items, sc = self._run(self.KEY, free, [_item("z")]) |
| 62 | sc.assert_not_called() |
| 63 | assert len(items) == 5 |
| 64 | |
| 65 | def test_empty_string_floor_behaves_as_unset(self): |
| 66 | cfg = {**self.KEY, self.FLOOR: ""} |
| 67 | items, sc = self._run(cfg, [_item("a"), _item("b"), _item("c")], [_item("z")]) |
| 68 | sc.assert_called_once() |
| 69 | assert _ids(items) == ["a", "b", "c", "z"] |
| 70 | |
| 71 | def test_explicit_zero_is_empty_only(self): |
| 72 | cfg = {**self.KEY, self.FLOOR: "0"} |
| 73 | items, sc = self._run(cfg, [_item("a"), _item("b"), _item("c")], [_item("z")]) |
| 74 | sc.assert_not_called() |
| 75 | assert len(items) == 3 |
| 76 | |
| 77 | def test_explicit_zero_still_backfills_empty_free_run(self): |
| 78 | cfg = {**self.KEY, self.FLOOR: "0"} |
| 79 | items, sc = self._run(cfg, [], [_item("z")]) |
| 80 | sc.assert_called_once() |
| 81 | assert _ids(items) == ["z"] |
| 82 | |
| 83 | def test_threshold_not_fired_when_free_above_floor(self): |
| 84 | cfg = {**self.KEY, self.FLOOR: "2"} |
| 85 | items, sc = self._run(cfg, [_item("a"), _item("b"), _item("c")], [_item("z")]) |
| 86 | sc.assert_not_called() |
| 87 | assert len(items) == 3 |
| 88 | |
| 89 | def test_no_key_never_calls_sc(self): |
| 90 | for floor in (None, "", "0", "5", "junk"): |
| 91 | cfg = {} if floor is None else {self.FLOOR: floor} |
| 92 | items, sc = self._run(cfg, [_item("a")], [_item("z")]) |
| 93 | sc.assert_not_called() |
| 94 | assert len(items) == 1 |
| 95 | |
| 96 | def test_malformed_floor_spends_nothing(self): |
| 97 | # Malformed means 0 (empty-only): 3 free items -> no SC call. |
| 98 | cfg = {**self.KEY, self.FLOOR: "not-an-int"} |
| 99 | items, sc = self._run(cfg, [_item("a"), _item("b"), _item("c")], [_item("z")]) |
| 100 | sc.assert_not_called() |
| 101 | assert len(items) == 3 |
| 102 | |
| 103 | |
| 104 | def _stream(config): |
| 105 | return pipeline._retrieve_stream( |
| 106 | topic="kanye", subquery=_subquery(), source="reddit", config=config, |
| 107 | depth="quick", date_range=("2026-05-26", "2026-06-25"), |
| 108 | runtime=_runtime(), mock=False, |
| 109 | ) |
| 110 | |
| 111 | |
| 112 | def test_sc_primary_keeps_captured_public_failure_at_the_fallback_cutoff(): |
| 113 | clock = [100.0] |
| 114 | failure = http.HTTPError("HTTP 429: public listing rate-limited", status_code=429) |
| 115 | |
| 116 | def public_search(*args, **kwargs): |
| 117 | clock[0] = 179.0 # Less than two seconds remain in the public lane. |
| 118 | http._record_failure(failure) |
| 119 | return [] |
| 120 | |
| 121 | config = { |
| 122 | "SCRAPECREATORS_API_KEY": "sc-dummy-key", |
| 123 | env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 124 | "_research_deadline": 200.0, |
| 125 | } |
| 126 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), \ |
| 127 | mock.patch("lib.reddit.search_and_enrich_memo", return_value={}), \ |
| 128 | mock.patch("lib.reddit_public.search_reddit_public", side_effect=public_search): |
| 129 | items, artifact = _stream(config) |
| 130 | |
| 131 | assert items == [] |
| 132 | outcome = artifact["_source_outcome"] |
| 133 | assert outcome["state"] == health.RATE_LIMITED |
| 134 | assert outcome["detail"] == str(failure) |
| 135 | |
| 136 | |
| 137 | def _sc_402(*_args, **_kwargs): |
| 138 | # Mirrors the real transport: http records the failure in the run's |
| 139 | # capture sink, then raises. |
| 140 | http._raise(http.HTTPError("HTTP 402: Payment Required", status_code=402)) |
| 141 | |
| 142 | |
| 143 | class TestBackfillOutcome: |
| 144 | KEY = {"SCRAPECREATORS_API_KEY": "k"} |
| 145 | |
| 146 | def test_backfill_402_after_free_items_keeps_source_working(self): |
| 147 | free = [_item("a"), _item("b"), _item("c")] |
| 148 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=free), \ |
| 149 | mock.patch("lib.reddit.search_and_enrich", side_effect=_sc_402): |
| 150 | items, artifact = _stream(self.KEY) |
| 151 | assert _ids(items) == ["a", "b", "c"] |
| 152 | assert not artifact.get("_source_outcome") # not branded failed |
| 153 | detail = artifact.get("_source_outcome_detail") or "" |
| 154 | assert "402" in detail |
| 155 | assert "ScrapeCreators backfill failed" in detail |
| 156 | assert artifact.get("_source_outcome_detail_state") == health.PAYMENT_REQUIRED |
| 157 | |
| 158 | def test_backfill_generic_failure_after_free_items_is_detail(self): |
| 159 | free = [_item("a")] |
| 160 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=free), \ |
| 161 | mock.patch("lib.reddit.search_and_enrich", side_effect=Exception("down")): |
| 162 | items, artifact = _stream(self.KEY) |
| 163 | assert _ids(items) == ["a"] |
| 164 | assert not artifact.get("_source_outcome") |
| 165 | assert "down" in (artifact.get("_source_outcome_detail") or "") |
| 166 | |
| 167 | def test_backfill_failure_with_no_free_items_keeps_explicit_failure(self): |
| 168 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=[]), \ |
| 169 | mock.patch("lib.reddit.search_and_enrich", side_effect=_sc_402): |
| 170 | items, artifact = _stream(self.KEY) |
| 171 | assert items == [] |
| 172 | outcome = artifact.get("_source_outcome") or {} |
| 173 | assert outcome.get("state") == health.PAYMENT_REQUIRED |
| 174 | |
| 175 | def test_backfill_note_and_swallowed_keyless_403_both_survive(self): |
| 176 | free = [_item("a"), _item("b"), _item("c")] |
| 177 | |
| 178 | def _public(*_args, **_kwargs): |
| 179 | # A keyless lane swallowed a 403 but the source still delivered. |
| 180 | http._record_failure(http.HTTPError("HTTP 403: Blocked", status_code=403)) |
| 181 | return free |
| 182 | |
| 183 | with mock.patch("lib.reddit_public.search_reddit_public", side_effect=_public), \ |
| 184 | mock.patch("lib.reddit.search_and_enrich", return_value={"raw": 1}), \ |
| 185 | mock.patch("lib.reddit.parse_reddit_response", return_value=[_item("z")]): |
| 186 | items, artifact = _stream(self.KEY) |
| 187 | assert _ids(items) == ["a", "b", "c", "z"] |
| 188 | assert not artifact.get("_source_outcome") |
| 189 | detail = artifact.get("_source_outcome_detail") or "" |
| 190 | assert "ScrapeCreators backfill ran" in detail |
| 191 | assert "1 sub-request blocked (HTTP 403)" in detail |
| 192 | |
| 193 | def test_backfill_that_ran_is_noted(self): |
| 194 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=[_item("a")]), \ |
| 195 | mock.patch("lib.reddit.search_and_enrich", return_value={"raw": 1}), \ |
| 196 | mock.patch("lib.reddit.parse_reddit_response", |
| 197 | return_value=[_item("a"), _item("z")]): |
| 198 | items, artifact = _stream(self.KEY) |
| 199 | assert _ids(items) == ["a", "z"] |
| 200 | assert not artifact.get("_source_outcome") |
| 201 | detail = artifact.get("_source_outcome_detail") or "" |
| 202 | assert "ScrapeCreators backfill ran" in detail |
| 203 | assert "added 1" in detail |
| 204 | |
| 205 | def test_swallowed_sc_429_after_free_items_does_not_rate_limit_reddit(self): |
| 206 | # ScrapeCreators 429s inside the backfill are swallowed by lib.reddit |
| 207 | # (recorded in the capture sink, then []). reddit.com was never |
| 208 | # rate-limited, so the stream must not carry RATE_LIMITED: the fan-out |
| 209 | # would add 'reddit' to rate_limited_sources and skip later Reddit |
| 210 | # streams and the thin-source retry. |
| 211 | free = [_item("a"), _item("b"), _item("c")] |
| 212 | |
| 213 | def _sc_http_429(*_args, **_kwargs): |
| 214 | http._raise(http.HTTPError("HTTP 429: Too Many Requests", status_code=429)) |
| 215 | |
| 216 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=free), \ |
| 217 | mock.patch("lib.http.get", side_effect=_sc_http_429) as sc_get: |
| 218 | items, artifact = _stream(self.KEY) |
| 219 | assert sc_get.called |
| 220 | assert _ids(items) == ["a", "b", "c"] |
| 221 | assert not artifact.get("_source_outcome") |
| 222 | assert artifact.get("_source_outcome_detail_state") != health.RATE_LIMITED |
| 223 | detail = artifact.get("_source_outcome_detail") or "" |
| 224 | assert "ScrapeCreators backfill" in detail |
| 225 | assert "HTTP 429" in detail |
| 226 | |
| 227 | def test_raised_sc_429_after_free_items_does_not_rate_limit_reddit(self): |
| 228 | free = [_item("a"), _item("b"), _item("c")] |
| 229 | |
| 230 | def _sc_raise_429(*_args, **_kwargs): |
| 231 | http._raise(http.HTTPError("HTTP 429: Too Many Requests", status_code=429)) |
| 232 | |
| 233 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=free), \ |
| 234 | mock.patch("lib.reddit.search_and_enrich", side_effect=_sc_raise_429): |
| 235 | items, artifact = _stream(self.KEY) |
| 236 | assert _ids(items) == ["a", "b", "c"] |
| 237 | assert not artifact.get("_source_outcome") |
| 238 | assert artifact.get("_source_outcome_detail_state") != health.RATE_LIMITED |
| 239 | detail = artifact.get("_source_outcome_detail") or "" |
| 240 | assert "ScrapeCreators backfill failed" in detail |
| 241 | assert "429" in detail |
| 242 | |
| 243 | def test_sc_429_with_no_free_items_keeps_explicit_rate_limited_outcome(self): |
| 244 | def _sc_raise_429(*_args, **_kwargs): |
| 245 | http._raise(http.HTTPError("HTTP 429: Too Many Requests", status_code=429)) |
| 246 | |
| 247 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=[]), \ |
| 248 | mock.patch("lib.reddit.search_and_enrich", side_effect=_sc_raise_429): |
| 249 | items, artifact = _stream(self.KEY) |
| 250 | assert items == [] |
| 251 | outcome = artifact.get("_source_outcome") or {} |
| 252 | assert outcome.get("state") == health.RATE_LIMITED |
| 253 | |
| 254 | def test_no_backfill_no_note(self): |
| 255 | free = [_item(c) for c in "abcdef"] |
| 256 | with mock.patch("lib.reddit_public.search_reddit_public", return_value=free), \ |
| 257 | mock.patch("lib.reddit.search_and_enrich") as sc: |
| 258 | _items, artifact = _stream(self.KEY) |
| 259 | sc.assert_not_called() |
| 260 | # Only the served-path line: no backfill note. |
| 261 | assert artifact.get("_source_outcome_detail") == "reddit served 6" |
| 262 | |
| 263 | |
| 264 | class TestMergeHelper: |
| 265 | def test_dedup_by_post_id_free_first(self): |
| 266 | out = pipeline._merge_reddit_items([_item("a"), _item("b")], [_item("b"), _item("c")]) |
| 267 | assert _ids(out) == ["a", "b", "c"] |
| 268 | |
| 269 | |
| 270 | class TestNoSearchJson: |
| 271 | def test_keyless_discovery_never_calls_searchjson(self): |
| 272 | # reddit_public.search (the .json caller) must never run in the keyless flow. |
| 273 | with mock.patch("lib.reddit_public.search") as json_search, \ |
| 274 | mock.patch("lib.reddit_keyless.reddit_search.search", return_value=[]), \ |
| 275 | mock.patch("lib.reddit_keyless.reddit_listing.fetch_listings", return_value=[]): |
| 276 | reddit_keyless._discover("topic", "default", ["test"]) |
| 277 | json_search.assert_not_called() |
| 278 | |
| 279 | def test_grounding_reddit_enrichment_never_requests_thread_json(self, monkeypatch): |
| 280 | # Anonymous thread .json has been 403 since 2026: the web lane's Reddit |
| 281 | # enrichment goes through the hydrator (Arctic Shift), never reddit.com. |
| 282 | from lib import grounding, reddit_arctic, reddit_enrich |
| 283 | |
| 284 | requested = [] |
| 285 | |
| 286 | def fake_get(url, headers=None, **_kwargs): |
| 287 | requested.append(url) |
| 288 | if "/posts/ids" in url: |
| 289 | return {"data": [{ |
| 290 | "id": "1abc2de", "title": "kanye thread", "score": 30, "num_comments": 4, |
| 291 | "created_utc": 1_700_000_000, "subreddit": "Kanye", |
| 292 | "permalink": "/r/Kanye/comments/1abc2de/kanye_thread/", |
| 293 | "author": "op", "selftext": "the thread body", |
| 294 | }]} |
| 295 | if "/comments/tree" in url: |
| 296 | return {"data": [{"kind": "t1", "data": { |
| 297 | "id": "c1", "score": 9, "created_utc": 1_700_000_100, "depth": 0, |
| 298 | "author": "fan", "body": "a comment about kanye", |
| 299 | "permalink": "/r/Kanye/comments/1abc2de/kanye_thread/c1/", "replies": "", |
| 300 | }}]} |
| 301 | raise AssertionError(f"unexpected URL {url}") |
| 302 | |
| 303 | monkeypatch.setattr(reddit_arctic.http, "get", fake_get) |
| 304 | monkeypatch.setattr(reddit_arctic.time, "sleep", lambda _s: None) |
| 305 | reddit_arctic.reset_memo() |
| 306 | with mock.patch.object(reddit_enrich, "fetch_thread_data") as thread_json, \ |
| 307 | mock.patch.object(http, "get_reddit_json") as reddit_json: |
| 308 | items = grounding._enrich_reddit_items([ |
| 309 | {"url": "https://old.reddit.com/r/Kanye/comments/1abc2de/kanye_thread/", "title": "t"}, |
| 310 | {"url": "https://example.com/news", "title": "n"}, |
| 311 | ]) |
| 312 | thread_json.assert_not_called() |
| 313 | reddit_json.assert_not_called() |
| 314 | hosts = {urlsplit(u).hostname for u in requested} |
| 315 | assert requested and not [h for h in hosts if h.split(".")[-2:] == ["reddit", "com"]] |
| 316 | assert not [u for u in requested if ".json" in u] |
| 317 | assert items[0]["snippet"] == "the thread body" |
| 318 | assert items[0]["top_comments"][0]["excerpt"] == "a comment about kanye" |
| 319 | assert items[0]["top_comments"][0]["depth"] == 0 |
| 320 | assert items[0]["enriched_via"] == "arctic" |
| 321 | assert "top_comments" not in items[1] |
| 322 | |
| 323 | |
| 324 | class TestEnvConstantParity: |
| 325 | """F2 regression (restate-as-mirror drift): pipeline's Reddit gating must |
| 326 | key off env's declared constants (env.REDDIT_BACKEND_PIN_VAR / |
| 327 | env.REDDIT_SC_MIN_ITEMS_VAR) — never restated raw strings that can drift |
| 328 | from the single source of truth in lib/env.py.""" |
| 329 | |
| 330 | def _run(self, config, public, sc_parsed): |
| 331 | with mock.patch("lib.reddit_public.search_reddit_public", |
| 332 | return_value=public) as pub, \ |
| 333 | mock.patch("lib.reddit.search_and_enrich", return_value={"raw": 1}) as sc, \ |
| 334 | mock.patch("lib.reddit.parse_reddit_response", return_value=sc_parsed): |
| 335 | items, _ = pipeline._retrieve_stream( |
| 336 | topic="kanye", subquery=_subquery(), source="reddit", config=config, |
| 337 | depth="quick", date_range=("2026-05-26", "2026-06-25"), |
| 338 | runtime=_runtime(), mock=False, |
| 339 | ) |
| 340 | return items, pub, sc |
| 341 | |
| 342 | def test_pipeline_source_has_no_raw_reddit_env_literals(self): |
| 343 | # The declared constants live in env.py; pipeline.py must not restate |
| 344 | # the raw LAST30DAYS_REDDIT_* strings (comments included — they drift too). |
| 345 | source = Path(pipeline.__file__).read_text() |
| 346 | assert "LAST30DAYS_REDDIT_" not in source |
| 347 | |
| 348 | def test_backend_pin_constant_flips_gating_to_sc_primary(self): |
| 349 | # Keyed via the env constant, not a raw string: pin=scrapecreators |
| 350 | # makes SC primary and skips the free path entirely. |
| 351 | cfg = {"SCRAPECREATORS_API_KEY": "k", env.REDDIT_BACKEND_PIN_VAR: "scrapecreators"} |
| 352 | items, pub, sc = self._run(cfg, [_item("a")], [_item("z")]) |
| 353 | sc.assert_called_once() |
| 354 | pub.assert_not_called() |
| 355 | assert _ids(items) == ["z"] |
| 356 | |
| 357 | def test_min_items_constant_drives_thinness_backfill(self): |
| 358 | # Keyed via the env constant: floor of 5 vs 1 free item -> SC backfill. |
| 359 | cfg = {"SCRAPECREATORS_API_KEY": "k", env.REDDIT_SC_MIN_ITEMS_VAR: "5"} |
| 360 | items, pub, sc = self._run(cfg, [_item("a")], [_item("z")]) |
| 361 | sc.assert_called_once() |
| 362 | assert _ids(items) == ["a", "z"] |
| 363 | |
| 364 | |
| 365 | class TestScBackfillFoldsIntoFreeCopies: |
| 366 | def test_live_sc_score_replaces_a_pending_free_score(self): |
| 367 | pending = { |
| 368 | "url": "https://www.reddit.com/r/x/comments/b/t/", "title": "kanye b", |
| 369 | "score": None, "engagement": {"score": None, "num_comments": 0}, |
| 370 | "engagement_source": "arctic-pending", "metadata": {"post_id": "b"}, |
| 371 | } |
| 372 | sc_copy = { |
| 373 | "url": "https://www.reddit.com/r/x/comments/b/t/", "title": "kanye b", |
| 374 | "engagement": {"score": 250, "num_comments": 31}, |
| 375 | "top_comments": [{"author": "u1", "score": 90, "excerpt": "kanye said it first"}], |
| 376 | } |
| 377 | out = pipeline._merge_reddit_items([pending], [sc_copy, _item("c")]) |
| 378 | assert _ids(out) == ["b", "c"] |
| 379 | merged = out[0] |
| 380 | assert merged["engagement"]["score"] == 250 |
| 381 | assert merged["engagement_source"] == "live" |
| 382 | assert merged["engagement"]["num_comments"] == 31 |
| 383 | assert [c["author"] for c in merged["top_comments"]] == ["u1"] |
| 384 | assert merged["top_comments"][0]["depth"] == 0 |
| 385 |