| 1 | """Tests for scripts/lib/reddit_discover.py: the keyless web floor and topic bar.""" |
| 2 | |
| 3 | import time |
| 4 | from concurrent.futures import ThreadPoolExecutor |
| 5 | from contextlib import nullcontext |
| 6 | from pathlib import Path |
| 7 | from threading import Event |
| 8 | from unittest import mock |
| 9 | |
| 10 | import pytest |
| 11 | |
| 12 | from lib import env, health, http, reddit_discover, web_search_keyless |
| 13 | |
| 14 | FIXTURE = ( |
| 15 | Path(__file__).resolve().parent.parent / "fixtures" / "brave_reddit_serp.html" |
| 16 | ).read_text(encoding="utf-8") |
| 17 | WINDOW = ("2026-10-16", "2026-11-15") |
| 18 | |
| 19 | |
| 20 | @pytest.fixture(autouse=True) |
| 21 | def _no_reddit_web_floor(): |
| 22 | """This module tests the real floor; override the suite-wide stub.""" |
| 23 | reddit_discover.reset_run_state() |
| 24 | web_search_keyless.reset_rung_health() |
| 25 | yield |
| 26 | reddit_discover.reset_run_state() |
| 27 | web_search_keyless.reset_rung_health() |
| 28 | |
| 29 | |
| 30 | def _brave_only(url, *args, **kwargs): |
| 31 | return FIXTURE if "search.brave.com" in url else "" |
| 32 | |
| 33 | |
| 34 | def _search_stub(results_by_query=None): |
| 35 | """A keyless_search stand-in that records each query it is asked.""" |
| 36 | calls = [] |
| 37 | |
| 38 | def search(query, date_range, config, count=5, **kwargs): |
| 39 | calls.append((query, kwargs)) |
| 40 | items = (results_by_query or {}).get(query, []) |
| 41 | return list(items), {"keyless_backend": "brave", "keyless_rungs": {"brave": "ok"}} |
| 42 | return search, calls |
| 43 | |
| 44 | |
| 45 | def _hit(url, title="", date=None): |
| 46 | return {"url": url, "title": title, "snippet": "", "date": date} |
| 47 | |
| 48 | |
| 49 | class TestWebRefs: |
| 50 | def test_captured_serp_yields_canonical_thread_refs(self): |
| 51 | with mock.patch.object(web_search_keyless.http, "get_text", side_effect=_brave_only): |
| 52 | floor = reddit_discover.web_refs("Kanye West", from_date=WINDOW[0], to_date=WINDOW[1]) |
| 53 | urls = [ref.url for ref in floor.refs] |
| 54 | assert urls |
| 55 | assert all(u.startswith("https://www.reddit.com/r/") and "/comments/" in u for u in urls) |
| 56 | # Profile pages and subreddit listing pages are not threads. |
| 57 | assert not any("/user/" in u or u.endswith("/new/") or u.endswith("/best/") for u in urls) |
| 58 | ref = next(r for r in floor.refs if r.post_id == "1xattdz") |
| 59 | assert ref.url == "https://www.reddit.com/r/Kanye/comments/1xattdz/" |
| 60 | assert ref.subreddit == "Kanye" |
| 61 | assert ref.provenance == {"web"} |
| 62 | # The SERP's "r/Kanye on Reddit: " prefix is not part of the title. |
| 63 | assert ref.title.startswith("Debunked: North West is not pregnant") |
| 64 | assert ref.date and len(ref.date) == 10 # relative SERP date resolved |
| 65 | assert floor.rungs["brave"] == "ok" |
| 66 | |
| 67 | def test_wiki_user_and_share_links_are_ignored(self): |
| 68 | hits = [ |
| 69 | _hit("https://www.reddit.com/r/Kanye/wiki/index/", "wiki"), |
| 70 | _hit("https://www.reddit.com/user/someone/", "profile"), |
| 71 | _hit("https://www.reddit.com/r/Kanye/s/AbCdEf", "share"), |
| 72 | _hit("https://old.reddit.com/r/Kanye/comments/abc123/slug/def456/", "Kanye thread"), |
| 73 | _hit("https://example.com/kanye", "not reddit"), |
| 74 | ] |
| 75 | search, _calls = _search_stub({"site:reddit.com Kanye West": hits}) |
| 76 | floor = reddit_discover.web_refs("Kanye West", search=search) |
| 77 | assert [r.post_id for r in floor.refs] == ["abc123"] |
| 78 | assert floor.refs[0].url == "https://www.reddit.com/r/Kanye/comments/abc123/" |
| 79 | |
| 80 | def test_duplicate_links_across_queries_merge_to_one_ref(self): |
| 81 | hits = [_hit("https://www.reddit.com/r/Kanye/comments/abc123/x/", "Kanye one")] |
| 82 | search, calls = _search_stub({ |
| 83 | "site:reddit.com Kanye West": hits, |
| 84 | "site:reddit.com r/hiphopheads Kanye West": hits, |
| 85 | }) |
| 86 | floor = reddit_discover.web_refs("Kanye West", subreddits=["hiphopheads"], search=search) |
| 87 | assert len(calls) == 2 |
| 88 | assert [r.post_id for r in floor.refs] == ["abc123"] |
| 89 | |
| 90 | def test_two_queries_topic_then_top_subreddit_hint(self): |
| 91 | search, calls = _search_stub() |
| 92 | reddit_discover.web_refs( |
| 93 | "Kanye West", subreddits=["hiphopheads", "Kanye"], search=search, |
| 94 | from_date=WINDOW[0], to_date=WINDOW[1], |
| 95 | ) |
| 96 | assert [q for q, _ in calls] == [ |
| 97 | "site:reddit.com Kanye West", "site:reddit.com r/hiphopheads Kanye West"] |
| 98 | |
| 99 | def test_current_month_window_is_month_filtered(self): |
| 100 | search, calls = _search_stub() |
| 101 | with mock.patch.object(reddit_discover, "_today", return_value="2026-11-15"): |
| 102 | reddit_discover.web_refs("Kanye West", search=search, |
| 103 | from_date=WINDOW[0], to_date=WINDOW[1]) |
| 104 | assert calls[0][1]["freshness"] == "month" |
| 105 | |
| 106 | def test_repeat_calls_for_one_entity_never_pass_two_queries(self): |
| 107 | search, calls = _search_stub() |
| 108 | for subs in (None, ["hiphopheads"], ["Kanye"], ["rap"]): |
| 109 | reddit_discover.web_refs("Kanye West", subreddits=subs, search=search) |
| 110 | assert len(calls) == 2 |
| 111 | |
| 112 | def test_comparison_with_three_entities_stays_within_two_queries_each(self): |
| 113 | search, calls = _search_stub() |
| 114 | for entity in ("Claude", "ChatGPT", "Gemini"): |
| 115 | for subs in (["LocalLLaMA"], ["singularity"], None): |
| 116 | reddit_discover.web_refs(entity, subreddits=subs, search=search) |
| 117 | per_entity = {} |
| 118 | for query, _ in calls: |
| 119 | entity = query.split()[-1] |
| 120 | per_entity[entity] = per_entity.get(entity, 0) + 1 |
| 121 | assert per_entity == {"Claude": 2, "ChatGPT": 2, "Gemini": 2} |
| 122 | |
| 123 | def test_web_failures_stay_out_of_the_reddit_stream_sink(self): |
| 124 | def brave_429(url, *args, **kwargs): |
| 125 | http._record_failure(http.HTTPError("HTTP 429", 429)) |
| 126 | return None |
| 127 | |
| 128 | with http.capture_failures() as failures, \ |
| 129 | mock.patch.object(web_search_keyless.http, "get_text", side_effect=brave_429): |
| 130 | floor = reddit_discover.web_refs("Kanye West") |
| 131 | assert failures == [] |
| 132 | assert floor.refs == [] |
| 133 | assert floor.rungs["brave"] == "throttled" |
| 134 | |
| 135 | def test_search_failure_never_raises(self): |
| 136 | def boom(*args, **kwargs): |
| 137 | raise RuntimeError("down") |
| 138 | floor = reddit_discover.web_refs("Kanye West", search=boom) |
| 139 | assert floor.refs == [] |
| 140 | |
| 141 | |
| 142 | def _item(title, subreddit="hiphopheads", selftext=""): |
| 143 | return {"title": title, "subreddit": subreddit, "selftext": selftext, |
| 144 | "url": f"https://www.reddit.com/r/{subreddit}/comments/abc/"} |
| 145 | |
| 146 | |
| 147 | class TestTopicBar: |
| 148 | def test_title_naming_the_topic_is_kept(self): |
| 149 | bar = reddit_discover.apply_bar("Kanye West", [_item("Kanye drops a new album")]) |
| 150 | assert len(bar.kept) == 1 and bar.dropped == [] |
| 151 | |
| 152 | def test_title_not_naming_the_topic_is_dropped(self): |
| 153 | bar = reddit_discover.apply_bar( |
| 154 | "Kanye West", [_item("Kanye drops a new album"), _item("Best pizza in town")]) |
| 155 | assert [i["title"] for i in bar.dropped] == ["Best pizza in town"] |
| 156 | assert bar.note("web search") == ( |
| 157 | "1 of 2 threads dropped for not naming the topic (web search)") |
| 158 | |
| 159 | def test_dedicated_subreddit_body_naming_the_topic_is_kept(self): |
| 160 | thread = _item("New album leak?", subreddit="Kanye", selftext="Is this really Kanye on track 3?") |
| 161 | bar = reddit_discover.apply_bar("Kanye West", [thread], dedicated=["kanye"]) |
| 162 | assert bar.kept == [thread] |
| 163 | |
| 164 | def test_same_thread_in_an_unrelated_subreddit_is_dropped(self): |
| 165 | thread = _item("New album leak?", subreddit="music", selftext="Is this really Kanye on track 3?") |
| 166 | bar = reddit_discover.apply_bar("Kanye West", [thread], dedicated=["Kanye"]) |
| 167 | assert bar.dropped == [thread] |
| 168 | |
| 169 | def test_resolved_subreddit_body_naming_the_topic_is_kept(self): |
| 170 | thread = _item("Album of the year?", subreddit="hiphopheads", selftext="Kanye or nobody") |
| 171 | bar = reddit_discover.apply_bar("Kanye West", [thread], subreddits=["HipHopHeads"]) |
| 172 | assert bar.kept == [thread] |
| 173 | |
| 174 | def test_resolved_subreddit_body_without_the_topic_is_dropped(self): |
| 175 | thread = _item("Album of the year?", subreddit="hiphopheads", selftext="Drake or nobody") |
| 176 | bar = reddit_discover.apply_bar("Kanye West", [thread], subreddits=["hiphopheads"]) |
| 177 | assert bar.dropped == [thread] |
| 178 | |
| 179 | def test_no_note_when_nothing_dropped(self): |
| 180 | assert reddit_discover.apply_bar("Kanye West", []).note("web search") is None |
| 181 | |
| 182 | |
| 183 | def test_a_rung_taken_out_keeps_its_cause_in_the_floor_rungs(): |
| 184 | def brave_403_then_ddg(url, *args, **kwargs): |
| 185 | if "search.brave.com" in url: |
| 186 | http._record_failure(http.HTTPError("HTTP 403", 403)) |
| 187 | return None |
| 188 | return "" |
| 189 | |
| 190 | with mock.patch.object(web_search_keyless.http, "get_text", side_effect=brave_403_then_ddg): |
| 191 | floor = reddit_discover.web_refs("Kanye West", subreddits=["Kanye"]) |
| 192 | assert len(floor.queries) == 2 |
| 193 | assert floor.rungs["brave"] == "blocked" |
| 194 | |
| 195 | |
| 196 | class TestWebFloorDeadline: |
| 197 | def test_threads_from_the_first_query_survive_a_spent_deadline(self): |
| 198 | clock = [100.0] |
| 199 | hits = [_hit("https://www.reddit.com/r/Kanye/comments/abc123/x/", "Kanye one")] |
| 200 | stub, calls = _search_stub({"site:reddit.com Kanye West": hits}) |
| 201 | |
| 202 | def slow_first(query, date_range, config, count=5, **kwargs): |
| 203 | out = stub(query, date_range, config, count, **kwargs) |
| 204 | clock[0] = 110.0 |
| 205 | return out |
| 206 | |
| 207 | partial = reddit_discover.WebFloor() |
| 208 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]): |
| 209 | floor = reddit_discover.web_refs( |
| 210 | "Kanye West", subreddits=["hiphopheads"], search=slow_first, |
| 211 | deadline=110.0, floor=partial, config={}, |
| 212 | ) |
| 213 | assert floor is partial |
| 214 | assert len(calls) == 1 |
| 215 | assert [r.post_id for r in partial.refs] == ["abc123"] |
| 216 | assert partial.timed_out |
| 217 | |
| 218 | |
| 219 | class TestSearxngConfigHandoff: |
| 220 | """Optional SearXNG fallback receives approved config without leaking secrets.""" |
| 221 | |
| 222 | @staticmethod |
| 223 | def _throttled_html(url, *args, **kwargs): |
| 224 | http._record_failure(http.HTTPError("HTTP 429", 429)) |
| 225 | return None |
| 226 | |
| 227 | @staticmethod |
| 228 | def _searxng_payload(): |
| 229 | return { |
| 230 | "results": [ |
| 231 | { |
| 232 | "url": "https://www.reddit.com/r/LocalLLaMA/comments/1sx9abc/iq3_quantization_notes/", |
| 233 | "title": "IQ3 quantization notes : r/LocalLLaMA - Reddit", |
| 234 | "content": "IQ3_XS quality vs IQ3_M", |
| 235 | }, |
| 236 | { |
| 237 | "url": "https://example.com/not-reddit", |
| 238 | "title": "Other site", |
| 239 | "content": "skip", |
| 240 | }, |
| 241 | ] |
| 242 | } |
| 243 | |
| 244 | def test_threaded_config_reaches_searxng_and_yields_thread_ref(self): |
| 245 | cfg = { |
| 246 | "LAST30DAYS_SEARXNG_URL": "https://searx.example", |
| 247 | "OPENAI_API_KEY": "sk-secret", |
| 248 | "SCRAPECREATORS_API_KEY": "sc-secret", |
| 249 | "AUTH_TOKEN": "cookie-secret", |
| 250 | } |
| 251 | seen_urls = [] |
| 252 | |
| 253 | def fake_get(url, **kwargs): |
| 254 | seen_urls.append(url) |
| 255 | return self._searxng_payload() |
| 256 | |
| 257 | with mock.patch.object(web_search_keyless.http, "get_text", side_effect=self._throttled_html), \ |
| 258 | mock.patch.object(web_search_keyless.http, "get", side_effect=fake_get), \ |
| 259 | mock.patch.object(env, "resolve_searxng_url", side_effect=AssertionError("should not reload config")) as load: |
| 260 | floor = reddit_discover.web_refs("IQ3 quantization", config=cfg) |
| 261 | |
| 262 | load.assert_not_called() |
| 263 | assert seen_urls and seen_urls[0].startswith("https://searx.example/search?") |
| 264 | assert [r.post_id for r in floor.refs] == ["1sx9abc"] |
| 265 | assert floor.refs[0].url == "https://www.reddit.com/r/LocalLLaMA/comments/1sx9abc/" |
| 266 | assert floor.refs[0].title == "IQ3 quantization notes" |
| 267 | assert floor.refs[0].provenance == {"web"} |
| 268 | |
| 269 | def test_config_passed_to_search_is_scoped_without_secrets(self): |
| 270 | seen_configs = [] |
| 271 | |
| 272 | def search(query, date_range, config, count=5, **kwargs): |
| 273 | seen_configs.append(dict(config)) |
| 274 | return [ |
| 275 | _hit("https://www.reddit.com/r/LocalLLaMA/comments/1sx9abc/x/", "IQ3 thread"), |
| 276 | ], {"keyless_backend": "searxng", "keyless_rungs": {"brave": "throttled"}} |
| 277 | |
| 278 | cfg = { |
| 279 | "LAST30DAYS_SEARXNG_URL": " https://searx.example ", |
| 280 | "OPENAI_API_KEY": "sk-secret", |
| 281 | "SCRAPECREATORS_API_KEY": "sc-secret", |
| 282 | "AUTH_TOKEN": "cookie-secret", |
| 283 | "_reddit_envelope": object(), |
| 284 | } |
| 285 | floor = reddit_discover.web_refs("IQ3 quantization", search=search, config=cfg) |
| 286 | assert seen_configs == [{"LAST30DAYS_SEARXNG_URL": "https://searx.example"}] |
| 287 | assert [r.post_id for r in floor.refs] == ["1sx9abc"] |
| 288 | |
| 289 | @pytest.mark.parametrize("cfg", [ |
| 290 | {}, |
| 291 | {"LAST30DAYS_SEARXNG_URL": None}, |
| 292 | {"LAST30DAYS_SEARXNG_URL": ""}, |
| 293 | {"LAST30DAYS_SEARXNG_URL": " "}, |
| 294 | {"LAST30DAYS_SEARXNG_URL": "${user_config.searxng_url}"}, |
| 295 | ]) |
| 296 | def test_disabled_or_empty_config_never_calls_searxng(self, cfg, monkeypatch): |
| 297 | monkeypatch.setenv("LAST30DAYS_SEARXNG_URL", "https://ambient.example") |
| 298 | with mock.patch.object(web_search_keyless.http, "get_text", side_effect=self._throttled_html), \ |
| 299 | mock.patch.object(web_search_keyless.http, "get") as sx_get, \ |
| 300 | mock.patch.object(env, "resolve_searxng_url", side_effect=AssertionError("explicit config must not reload")) as load: |
| 301 | floor = reddit_discover.web_refs("IQ3 quantization", config=cfg) |
| 302 | |
| 303 | load.assert_not_called() |
| 304 | sx_get.assert_not_called() |
| 305 | assert floor.refs == [] |
| 306 | |
| 307 | def test_omitted_config_loads_user_approved_env_once_per_run(self, monkeypatch): |
| 308 | monkeypatch.setenv("LAST30DAYS_SEARXNG_URL", "https://searx.example") |
| 309 | real_reader = env.resolve_searxng_url |
| 310 | with mock.patch.object(env, "resolve_searxng_url", wraps=real_reader) as load, \ |
| 311 | mock.patch.object(web_search_keyless.http, "get_text", side_effect=self._throttled_html), \ |
| 312 | mock.patch.object(web_search_keyless.http, "get", return_value=self._searxng_payload()): |
| 313 | floor = reddit_discover.web_refs("IQ3 quantization", subreddits=["LocalLLaMA"]) |
| 314 | |
| 315 | load.assert_called_once_with() |
| 316 | assert [r.post_id for r in floor.refs] == ["1sx9abc"] |
| 317 | |
| 318 | # Resetting run state clears the memoized config for the next run. |
| 319 | reddit_discover.reset_run_state() |
| 320 | monkeypatch.delenv("LAST30DAYS_SEARXNG_URL", raising=False) |
| 321 | with mock.patch.object(env, "resolve_searxng_url", wraps=real_reader) as load, \ |
| 322 | mock.patch.object(web_search_keyless.http, "get_text", side_effect=self._throttled_html), \ |
| 323 | mock.patch.object(web_search_keyless.http, "get") as sx_get: |
| 324 | floor2 = reddit_discover.web_refs("IQ3 quantization") |
| 325 | |
| 326 | load.assert_called_once_with() |
| 327 | sx_get.assert_not_called() |
| 328 | assert floor2.refs == [] |
| 329 | |
| 330 | def test_untrusted_project_config_searxng_is_ignored(self, tmp_path, monkeypatch): |
| 331 | project_env = tmp_path / ".claude" / "last30days.env" |
| 332 | project_env.parent.mkdir() |
| 333 | project_env.write_text( |
| 334 | "LAST30DAYS_SEARXNG_URL=https://untrusted-project.example\n", |
| 335 | encoding="utf-8", |
| 336 | ) |
| 337 | monkeypatch.chdir(tmp_path) |
| 338 | monkeypatch.delenv("LAST30DAYS_TRUST_PROJECT_CONFIG", raising=False) |
| 339 | monkeypatch.delenv("LAST30DAYS_SEARXNG_URL", raising=False) |
| 340 | |
| 341 | with mock.patch.object(web_search_keyless.http, "get_text", side_effect=self._throttled_html), \ |
| 342 | mock.patch.object(web_search_keyless.http, "get") as sx_get: |
| 343 | floor = reddit_discover.web_refs("IQ3 quantization") |
| 344 | |
| 345 | sx_get.assert_not_called() |
| 346 | assert floor.refs == [] |
| 347 | |
| 348 | def test_searxng_stays_fallback_when_html_rung_succeeds(self): |
| 349 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 350 | with mock.patch.object(web_search_keyless.http, "get_text", side_effect=_brave_only), \ |
| 351 | mock.patch.object(web_search_keyless.http, "get") as sx_get: |
| 352 | floor = reddit_discover.web_refs("Kanye West", from_date=WINDOW[0], to_date=WINDOW[1], config=cfg) |
| 353 | |
| 354 | sx_get.assert_not_called() |
| 355 | assert floor.refs and floor.rungs["brave"] == "ok" |
| 356 | |
| 357 | @pytest.mark.parametrize("has_thread", [False, True]) |
| 358 | def test_only_reddit_threads_can_stop_the_ladder(self, has_thread): |
| 359 | html_hits = [ |
| 360 | _hit("https://www.reddit.com/r/LocalLLaMA/"), |
| 361 | _hit("https://www.reddit.com/r/LocalLLaMA/wiki/index/"), |
| 362 | ] |
| 363 | if has_thread: |
| 364 | html_hits.append(_hit("https://www.reddit.com/r/LocalLLaMA/comments/html123/")) |
| 365 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 366 | with mock.patch.object(web_search_keyless, "_brave_rung", return_value=(html_hits, "ok")), \ |
| 367 | mock.patch.object(web_search_keyless.http, "get_text", return_value=""), \ |
| 368 | mock.patch.object(web_search_keyless.http, "get", return_value=self._searxng_payload()) as sx: |
| 369 | floor = reddit_discover.web_refs("IQ3 quantization", config=cfg) |
| 370 | |
| 371 | assert [ref.post_id for ref in floor.refs] == (["html123"] if has_thread else ["1sx9abc"]) |
| 372 | assert floor.rungs["brave"] == ("ok" if has_thread else "empty") |
| 373 | assert sx.call_count == (0 if has_thread else 1) |
| 374 | |
| 375 | def test_empty_web_timeout_can_retry_the_same_query_with_more_time(self): |
| 376 | clock = [100.0] |
| 377 | |
| 378 | def expire_first(query, count, freshness, **kwargs): |
| 379 | if clock[0] == 100.0: |
| 380 | clock[0] = 110.0 |
| 381 | return [], "empty" |
| 382 | |
| 383 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 384 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), \ |
| 385 | mock.patch.object(web_search_keyless, "_brave_rung", side_effect=expire_first), \ |
| 386 | mock.patch.object(web_search_keyless.http, "get_text", return_value=""), \ |
| 387 | mock.patch.object(web_search_keyless.http, "get", return_value=self._searxng_payload()) as sx: |
| 388 | first = reddit_discover.web_refs("IQ3 quantization", deadline=110.0, config=cfg) |
| 389 | assert not first.refs and not sx.called |
| 390 | second = reddit_discover.web_refs("IQ3 quantization", deadline=140.0, config=cfg) |
| 391 | |
| 392 | assert [ref.post_id for ref in second.refs] == ["1sx9abc"] |
| 393 | assert first.timed_out and not second.timed_out |
| 394 | sx.assert_called_once() |
| 395 | |
| 396 | def test_waiter_gets_its_attempt_timeout_before_the_slot_is_retried(self): |
| 397 | from threading import Thread, current_thread |
| 398 | |
| 399 | entered, waiting, release = Event(), Event(), Event() |
| 400 | calls, waiter_results = [], [] |
| 401 | real_wait = Event.wait |
| 402 | |
| 403 | def track_wait(event, timeout=None): |
| 404 | if current_thread().name == "reddit-floor-waiter": |
| 405 | waiting.set() |
| 406 | return real_wait(event, timeout) |
| 407 | |
| 408 | def search(query, *args, **kwargs): |
| 409 | calls.append(query) |
| 410 | if len(calls) == 1: |
| 411 | entered.set() |
| 412 | assert release.wait(5) |
| 413 | return [], {"_source_outcome": {"state": health.TIMEOUT}} |
| 414 | return [_hit("https://www.reddit.com/r/LocalLLaMA/comments/new123/")], {} |
| 415 | |
| 416 | def run(): |
| 417 | return reddit_discover.web_refs("IQ3 quantization", search=search, config={}) |
| 418 | |
| 419 | waiter = Thread(name="reddit-floor-waiter", target=lambda: waiter_results.append(run())) |
| 420 | with mock.patch.object(Event, "wait", track_wait), ThreadPoolExecutor(max_workers=1) as pool: |
| 421 | first = pool.submit(run) |
| 422 | try: |
| 423 | assert entered.wait(5) |
| 424 | waiter.start() |
| 425 | assert waiting.wait(5) |
| 426 | finally: |
| 427 | release.set() |
| 428 | assert first.result(timeout=5).timed_out |
| 429 | waiter.join(timeout=5) |
| 430 | |
| 431 | assert not waiter.is_alive() |
| 432 | assert len(calls) == 1 and waiter_results[0].timed_out |
| 433 | assert [ref.post_id for ref in run().refs] == ["new123"] |
| 434 | assert len(calls) == 2 |
| 435 | |
| 436 | def test_config_loader_exception_never_breaks_the_lane(self): |
| 437 | with mock.patch.object(env, "resolve_searxng_url", side_effect=RuntimeError("boom")), \ |
| 438 | mock.patch.object(web_search_keyless.http, "get_text", return_value=None): |
| 439 | floor = reddit_discover.web_refs("IQ3 quantization") |
| 440 | assert floor.refs == [] |
| 441 | |
| 442 | def test_config_loader_failure_runs_html_ladder_without_caching_empty(self): |
| 443 | with mock.patch.object(env, "resolve_searxng_url", side_effect=RuntimeError("boom")), \ |
| 444 | mock.patch.object(web_search_keyless.http, "get_text", side_effect=_brave_only): |
| 445 | floor = reddit_discover.web_refs( |
| 446 | "Kanye West", from_date=WINDOW[0], to_date=WINDOW[1], |
| 447 | ) |
| 448 | assert any(r.post_id == "1xattdz" for r in floor.refs) |
| 449 | assert floor.rungs["brave"] == "ok" |
| 450 | |
| 451 | # A subsequent call in the same run must reuse the HTML result rather |
| 452 | # than an empty answer cached because config loading failed. |
| 453 | second = reddit_discover.web_refs( |
| 454 | "Kanye West", from_date=WINDOW[0], to_date=WINDOW[1], |
| 455 | search=lambda *a, **kw: ([], {}), |
| 456 | ) |
| 457 | assert any(r.post_id == "1xattdz" for r in second.refs) |
| 458 | |
| 459 | @pytest.mark.parametrize("first_config", [OSError("config unavailable"), None], |
| 460 | ids=["transient-error", "stable-absence"]) |
| 461 | def test_same_query_retries_html_miss_only_after_config_read_error(self, first_config): |
| 462 | with mock.patch.object(env, "resolve_searxng_url", side_effect=[first_config, "https://searx.example"]) as load, \ |
| 463 | mock.patch.object(web_search_keyless.http, "get_text", return_value=None) as html, \ |
| 464 | mock.patch.object(web_search_keyless.http, "get", return_value=self._searxng_payload()): |
| 465 | first = reddit_discover.web_refs("IQ3 quantization") |
| 466 | first_calls = html.call_count |
| 467 | second = reddit_discover.web_refs("IQ3 quantization") |
| 468 | |
| 469 | assert first.refs == [] |
| 470 | if isinstance(first_config, OSError): |
| 471 | assert [r.post_id for r in second.refs] == ["1sx9abc"] |
| 472 | assert load.call_count == 2 |
| 473 | else: |
| 474 | assert second.refs == [] |
| 475 | assert load.call_count == 1 |
| 476 | assert html.call_count == first_calls |
| 477 | |
| 478 | def test_retryable_misses_do_not_free_slots_for_new_subreddit_queries(self): |
| 479 | search, calls = _search_stub() |
| 480 | with mock.patch.object(env, "resolve_searxng_url", side_effect=OSError("config unavailable")): |
| 481 | reddit_discover.web_refs("IQ3 quantization", subreddits=["LocalLLaMA"], search=search) |
| 482 | reddit_discover.web_refs("IQ3 quantization", subreddits=["llama"], search=search) |
| 483 | |
| 484 | assert [q for q, _ in calls] == [ |
| 485 | "site:reddit.com IQ3 quantization", |
| 486 | "site:reddit.com r/LocalLLaMA IQ3 quantization", |
| 487 | "site:reddit.com IQ3 quantization", |
| 488 | ] |
| 489 | |
| 490 | def test_spent_deadline_after_html_rungs_skips_late_searxng_and_retains_prior_results(self): |
| 491 | clock = [100.0] |
| 492 | deadline = 110.0 |
| 493 | |
| 494 | def fake_get_text(url, *args, **kwargs): |
| 495 | if "LocalLLaMA" not in url: |
| 496 | return FIXTURE if "search.brave.com" in url else "" |
| 497 | if "startpage.com" in url: |
| 498 | clock[0] = 110.5 |
| 499 | else: |
| 500 | clock[0] += 2.0 |
| 501 | http._record_failure(http.HTTPError("HTTP 429", 429)) |
| 502 | return None |
| 503 | |
| 504 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 505 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), \ |
| 506 | mock.patch.object(web_search_keyless.http, "get_text", side_effect=fake_get_text), \ |
| 507 | mock.patch.object(web_search_keyless.http, "get") as sx_get: |
| 508 | floor = reddit_discover.web_refs( |
| 509 | "Kanye West", |
| 510 | subreddits=["LocalLLaMA"], |
| 511 | from_date=WINDOW[0], |
| 512 | to_date=WINDOW[1], |
| 513 | deadline=deadline, |
| 514 | config=cfg, |
| 515 | ) |
| 516 | |
| 517 | sx_get.assert_not_called() |
| 518 | assert any(r.post_id == "1xattdz" for r in floor.refs) |
| 519 | |
| 520 | def test_standalone_cache_stores_normalized_url_or_absence(self): |
| 521 | with mock.patch.object(env, "resolve_searxng_url", return_value=" https://searx.example "), \ |
| 522 | mock.patch.object(web_search_keyless.http, "get_text", side_effect=self._throttled_html), \ |
| 523 | mock.patch.object(web_search_keyless.http, "get", return_value=self._searxng_payload()): |
| 524 | floor = reddit_discover.web_refs("IQ3 quantization") |
| 525 | |
| 526 | assert [r.post_id for r in floor.refs] == ["1sx9abc"] |
| 527 | assert reddit_discover._SEARXNG_URL == "https://searx.example" |
| 528 | |
| 529 | reddit_discover.reset_run_state() |
| 530 | assert reddit_discover._SEARXNG_URL is None |
| 531 | with mock.patch.object(env, "resolve_searxng_url", return_value=" "), \ |
| 532 | mock.patch.object(web_search_keyless.http, "get_text", return_value=None), \ |
| 533 | mock.patch.object(web_search_keyless.http, "get") as sx_get: |
| 534 | reddit_discover.web_refs("IQ3 quantization") |
| 535 | sx_get.assert_not_called() |
| 536 | assert reddit_discover._SEARXNG_URL == "" |
| 537 | |
| 538 | def test_concurrent_first_load_reads_config_once(self): |
| 539 | import threading |
| 540 | |
| 541 | load_count = 0 |
| 542 | count_lock = threading.Lock() |
| 543 | barrier = threading.Barrier(4) |
| 544 | seen_configs = [] |
| 545 | |
| 546 | def slow_url_read(): |
| 547 | nonlocal load_count |
| 548 | with count_lock: |
| 549 | load_count += 1 |
| 550 | import time as _time |
| 551 | _time.sleep(0.03) |
| 552 | return "https://concurrent.example" |
| 553 | |
| 554 | def search(query, date_range, config, count=5, **kwargs): |
| 555 | with count_lock: |
| 556 | seen_configs.append(dict(config)) |
| 557 | return [], {"keyless_backend": "searxng", "keyless_rungs": {}} |
| 558 | |
| 559 | def worker(idx): |
| 560 | barrier.wait(timeout=5) |
| 561 | reddit_discover.web_refs(f"topic {idx}", search=search) |
| 562 | |
| 563 | with mock.patch.object(env, "resolve_searxng_url", side_effect=slow_url_read): |
| 564 | threads = [threading.Thread(target=worker, args=(i,)) for i in range(4)] |
| 565 | for t in threads: |
| 566 | t.start() |
| 567 | for t in threads: |
| 568 | t.join(timeout=5) |
| 569 | |
| 570 | assert load_count == 1 |
| 571 | assert seen_configs == [{"LAST30DAYS_SEARXNG_URL": "https://concurrent.example"}] * 4 |
| 572 | |
| 573 | @pytest.mark.parametrize("blocked_at", ["load", "search"]) |
| 574 | def test_reset_fences_old_query_from_new_run_memo(self, blocked_at): |
| 575 | entered = Event() |
| 576 | release = Event() |
| 577 | topic = "IQ3 quantization" |
| 578 | query = "site:reddit.com IQ3 quantization" |
| 579 | new_hint = "site:reddit.com r/NewSub IQ3 quantization" |
| 580 | |
| 581 | def block(): |
| 582 | entered.set() |
| 583 | assert release.wait(timeout=5) |
| 584 | |
| 585 | def old_url(): |
| 586 | if blocked_at == "load": |
| 587 | block() |
| 588 | return "https://stale.example" |
| 589 | |
| 590 | def old_search(*args, **kwargs): |
| 591 | if blocked_at == "search": |
| 592 | block() |
| 593 | return [_hit("https://www.reddit.com/r/LocalLLaMA/comments/old123/")], {} |
| 594 | |
| 595 | new_search, calls = _search_stub({ |
| 596 | query: [_hit("https://www.reddit.com/r/LocalLLaMA/comments/new123/")], |
| 597 | new_hint: [_hit("https://www.reddit.com/r/NewSub/comments/new456/")], |
| 598 | }) |
| 599 | new_config = {"LAST30DAYS_SEARXNG_URL": "https://fresh.example"} |
| 600 | with mock.patch.object(env, "resolve_searxng_url", side_effect=old_url), \ |
| 601 | ThreadPoolExecutor(max_workers=1) as pool: |
| 602 | pending = pool.submit(reddit_discover.web_refs, topic, subreddits=["OldSub"], search=old_search) |
| 603 | try: |
| 604 | assert entered.wait(timeout=5) |
| 605 | reddit_discover.reset_run_state() |
| 606 | # Explicit config lets the new run finish even if the old run's loader is blocked. |
| 607 | fresh = reddit_discover.web_refs(topic, search=new_search, config=new_config) |
| 608 | assert [r.post_id for r in fresh.refs] == ["new123"] |
| 609 | finally: |
| 610 | release.set() |
| 611 | old = pending.result(timeout=5) |
| 612 | repeated = reddit_discover.web_refs( |
| 613 | topic, subreddits=["NewSub"], search=new_search, config=new_config, |
| 614 | ) |
| 615 | |
| 616 | assert [r.post_id for r in repeated.refs] == ["new123", "new456"] |
| 617 | assert [q for q, _ in calls] == [query, new_hint] |
| 618 | assert old.queries == ([] if blocked_at == "load" else [query]) |
| 619 | assert reddit_discover._SEARXNG_URL is None |
| 620 | |
| 621 | def test_trusted_project_config_searxng_is_loaded(self, tmp_path, monkeypatch): |
| 622 | project_env = tmp_path / ".claude" / "last30days.env" |
| 623 | project_env.parent.mkdir() |
| 624 | project_env.write_text( |
| 625 | "LAST30DAYS_SEARXNG_URL=https://trusted-project.example\n", |
| 626 | encoding="utf-8", |
| 627 | ) |
| 628 | monkeypatch.chdir(tmp_path) |
| 629 | monkeypatch.setenv("LAST30DAYS_TRUST_PROJECT_CONFIG", "1") |
| 630 | monkeypatch.delenv("LAST30DAYS_SEARXNG_URL", raising=False) |
| 631 | |
| 632 | seen_urls = [] |
| 633 | |
| 634 | def fake_get(url, **kwargs): |
| 635 | seen_urls.append(url) |
| 636 | return self._searxng_payload() |
| 637 | |
| 638 | with mock.patch.object(web_search_keyless.http, "get_text", side_effect=self._throttled_html), \ |
| 639 | mock.patch.object(web_search_keyless.http, "get", side_effect=fake_get): |
| 640 | floor = reddit_discover.web_refs("IQ3 quantization") |
| 641 | |
| 642 | assert seen_urls and seen_urls[0].startswith("https://trusted-project.example/search?") |
| 643 | assert [r.post_id for r in floor.refs] == ["1sx9abc"] |
| 644 | |
| 645 | def test_standalone_discovery_reads_trusted_url_without_exporting_settings(self, tmp_path, monkeypatch): |
| 646 | import os |
| 647 | |
| 648 | project_env = tmp_path / ".claude" / "last30days.env" |
| 649 | project_env.parent.mkdir() |
| 650 | project_env.write_text( |
| 651 | "LAST30DAYS_SEARXNG_URL=https://trusted-project.example\n" |
| 652 | "SCRAPECREATORS_BASE_URL=https://local-provider.example\n", |
| 653 | encoding="utf-8", |
| 654 | ) |
| 655 | monkeypatch.chdir(tmp_path) |
| 656 | monkeypatch.setenv("LAST30DAYS_TRUST_PROJECT_CONFIG", "1") |
| 657 | monkeypatch.setenv("LAST30DAYS_SEARXNG_URL", "${user_config.searxng_url}") |
| 658 | monkeypatch.delenv("SCRAPECREATORS_BASE_URL", raising=False) |
| 659 | with mock.patch.object(web_search_keyless.http, "get_text", return_value=""), \ |
| 660 | mock.patch.object(web_search_keyless.http, "get", return_value=self._searxng_payload()) as sx: |
| 661 | floor = reddit_discover.web_refs("IQ3 quantization") |
| 662 | |
| 663 | assert [ref.post_id for ref in floor.refs] == ["1sx9abc"] |
| 664 | assert sx.call_args.args[0].startswith("https://trusted-project.example/search?") |
| 665 | assert "SCRAPECREATORS_BASE_URL" not in os.environ |
| 666 | assert os.environ.get("LAST30DAYS_SEARXNG_URL") == "${user_config.searxng_url}" |
| 667 | |
| 668 | def test_standalone_url_uses_global_value_when_trusted_project_has_a_placeholder(self, tmp_path, monkeypatch): |
| 669 | env.CONFIG_FILE.write_text("LAST30DAYS_SEARXNG_URL=https://global.example\n", encoding="utf-8") |
| 670 | project_env = tmp_path / ".claude" / "last30days.env" |
| 671 | project_env.parent.mkdir() |
| 672 | project_env.write_text("LAST30DAYS_SEARXNG_URL=${user_config.searxng_url}\n", encoding="utf-8") |
| 673 | monkeypatch.chdir(tmp_path) |
| 674 | monkeypatch.setenv("LAST30DAYS_TRUST_PROJECT_CONFIG", "1") |
| 675 | monkeypatch.delenv("LAST30DAYS_SEARXNG_URL", raising=False) |
| 676 | with mock.patch.object(web_search_keyless.http, "get_text", return_value=""), \ |
| 677 | mock.patch.object(web_search_keyless.http, "get", return_value=self._searxng_payload()) as sx: |
| 678 | floor = reddit_discover.web_refs("IQ3 quantization") |
| 679 | |
| 680 | assert [ref.post_id for ref in floor.refs] == ["1sx9abc"] |
| 681 | assert sx.call_args.args[0].startswith("https://global.example/search?") |
| 682 | |
| 683 | def test_memoized_answers_are_reused_across_calls_with_config(self): |
| 684 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 685 | calls = [] |
| 686 | |
| 687 | def search(query, date_range, config, count=5, **kwargs): |
| 688 | calls.append((query, dict(config))) |
| 689 | return [ |
| 690 | _hit("https://www.reddit.com/r/LocalLLaMA/comments/1sx9abc/x/", "IQ3 thread"), |
| 691 | ], {"keyless_backend": "searxng", "keyless_rungs": {}} |
| 692 | |
| 693 | first = reddit_discover.web_refs("IQ3 quantization", search=search, config=cfg) |
| 694 | second = reddit_discover.web_refs("IQ3 quantization", search=search, config=cfg) |
| 695 | assert len(calls) == 1 |
| 696 | assert [r.post_id for r in first.refs] == ["1sx9abc"] |
| 697 | assert [r.post_id for r in second.refs] == ["1sx9abc"] |
| 698 | |
| 699 | def _run_pipeline_reddit_with_searxng( |
| 700 | self, cfg, *, sc_search=None, html_fetch=None, site_hits=(), searxng_get=None, |
| 701 | full_report=False, labels=("primary",), report_depth="quick", report_sources=("reddit",), |
| 702 | ): |
| 703 | from lib import pipeline, reddit, reddit_keyless, schema |
| 704 | |
| 705 | seen_urls = [] |
| 706 | archived = { |
| 707 | "id": "", |
| 708 | "title": "IQ3 quantization notes", |
| 709 | "url": "https://www.reddit.com/r/LocalLLaMA/comments/1sx9abc/iq3_quantization_notes/", |
| 710 | "score": 40, |
| 711 | "num_comments": 7, |
| 712 | "subreddit": "LocalLLaMA", |
| 713 | "created_utc": 1_700_000_000, |
| 714 | "author": "u", |
| 715 | "selftext": "IQ3 notes", |
| 716 | "date": "2026-05-20", |
| 717 | "engagement": {"score": 40, "num_comments": 7, "upvote_ratio": None}, |
| 718 | "relevance": 0.0, |
| 719 | "why_relevant": "Reddit listing (arctic-shift)", |
| 720 | "metadata": {"post_id": "1sx9abc"}, |
| 721 | } |
| 722 | |
| 723 | def fake_get(url, **kwargs): |
| 724 | seen_urls.append(url) |
| 725 | return self._searxng_payload() |
| 726 | |
| 727 | sc_ctx = ( |
| 728 | mock.patch.object(reddit, "search_and_enrich_memo", side_effect=sc_search) |
| 729 | if sc_search is not None else nullcontext() |
| 730 | ) |
| 731 | with sc_ctx, \ |
| 732 | mock.patch.object(reddit_keyless.reddit_search, "search", return_value=list(site_hits)), \ |
| 733 | mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings", return_value=[]), \ |
| 734 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_listings", return_value=[]), \ |
| 735 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_scores", return_value={}), \ |
| 736 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_posts_by_ids", |
| 737 | return_value=({"1sx9abc": dict(archived)}, "ok")), \ |
| 738 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_comment_tree", return_value=[]), \ |
| 739 | mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments", |
| 740 | return_value={"top_comments": [], "comment_insights": [], "num_comments": None}), \ |
| 741 | mock.patch.object(web_search_keyless.http, "get_text", side_effect=html_fetch or self._throttled_html), \ |
| 742 | mock.patch.object(web_search_keyless.http, "get", side_effect=searxng_get or fake_get), \ |
| 743 | mock.patch.object(env, "resolve_searxng_url", side_effect=AssertionError("already loaded config should be threaded")): |
| 744 | if full_report: |
| 745 | # The whole run, so the result is the serialized per-source outcome. |
| 746 | report = pipeline.run( |
| 747 | topic="IQ3 quantization", |
| 748 | config=cfg, |
| 749 | depth=report_depth, |
| 750 | requested_sources=list(report_sources), |
| 751 | web_backend="none", |
| 752 | as_of_date="2026-05-31", |
| 753 | external_plan={ |
| 754 | "intent": "research", |
| 755 | "freshness_mode": "balanced_recent", |
| 756 | "cluster_mode": "topic", |
| 757 | "subqueries": [{ |
| 758 | "label": label, |
| 759 | # Identical subqueries are planned once, and quick depth plans only one. |
| 760 | "search_query": "IQ3 quantization" if index == 0 else f"IQ3 quantization {label}", |
| 761 | "ranking_query": "IQ3 quantization" if index == 0 else f"IQ3 quantization {label}", |
| 762 | "sources": list(report_sources), |
| 763 | } for index, label in enumerate(labels)], |
| 764 | }, |
| 765 | ) |
| 766 | return report, None, seen_urls |
| 767 | items, artifact = pipeline._retrieve_stream( |
| 768 | topic="IQ3 quantization", |
| 769 | subquery=schema.SubQuery( |
| 770 | label="primary", search_query="IQ3 quantization", |
| 771 | ranking_query="IQ3 quantization", sources=["reddit"], |
| 772 | ), |
| 773 | source="reddit", |
| 774 | config=cfg, |
| 775 | depth="quick", |
| 776 | date_range=("2026-05-01", "2026-05-31"), |
| 777 | runtime=schema.ProviderRuntime( |
| 778 | reasoning_provider="mock", planner_model="mock", rerank_model="mock", |
| 779 | ), |
| 780 | mock=False, |
| 781 | ) |
| 782 | return items, artifact, seen_urls |
| 783 | |
| 784 | def test_pipeline_threads_config_end_to_end_to_searxng_web_floor(self): |
| 785 | cfg = { |
| 786 | "LAST30DAYS_SEARXNG_URL": "https://searx.example", |
| 787 | "OPENAI_API_KEY": "sk-secret", |
| 788 | } |
| 789 | items, _, seen_urls = self._run_pipeline_reddit_with_searxng(cfg) |
| 790 | assert seen_urls and seen_urls[0].startswith("https://searx.example/search?") |
| 791 | assert [i["metadata"]["post_id"] for i in items] == ["1sx9abc"] |
| 792 | |
| 793 | def test_sc_primary_fallback_also_threads_config_to_web_floor(self): |
| 794 | cfg = { |
| 795 | "SCRAPECREATORS_API_KEY": "sc-dummy-key", |
| 796 | env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 797 | "LAST30DAYS_SEARXNG_URL": "https://searx.example", |
| 798 | } |
| 799 | items, _, seen_urls = self._run_pipeline_reddit_with_searxng(cfg, sc_search=lambda *a, **kw: {}) |
| 800 | assert seen_urls and seen_urls[0].startswith("https://searx.example/search?") |
| 801 | assert [i["metadata"]["post_id"] for i in items] == ["1sx9abc"] |
| 802 | |
| 803 | @pytest.mark.parametrize("finished_at, http_status, expected_state", [ |
| 804 | (200.0, None, health.TIMEOUT), |
| 805 | (198.0, None, health.TIMEOUT), |
| 806 | (170.0, None, None), |
| 807 | (198.0, 429, health.RATE_LIMITED), |
| 808 | ], ids=["run-budget-spent", "public-budget-too-short", "in-budget-miss", "primary-rate-limit"]) |
| 809 | def test_sc_primary_empty_fallback_reports_its_outcome(self, finished_at, http_status, expected_state): |
| 810 | clock = [100.0] |
| 811 | |
| 812 | def sc_search(*args, **kwargs): |
| 813 | clock[0] = finished_at |
| 814 | if http_status is not None: |
| 815 | http._record_failure(http.HTTPError("HTTP 429", http_status)) |
| 816 | return {} |
| 817 | |
| 818 | cfg = { |
| 819 | "SCRAPECREATORS_API_KEY": "sc-dummy-key", |
| 820 | env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 821 | "LAST30DAYS_SEARXNG_URL": "https://searx.example" if expected_state is not None else "", |
| 822 | "_research_deadline": 200.0, |
| 823 | } |
| 824 | html_fetch = mock.Mock(return_value=None) |
| 825 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]): |
| 826 | if http_status is not None: |
| 827 | # A captured paid failure with nothing found is a typed failure of the stream. |
| 828 | from lib import pipeline |
| 829 | |
| 830 | with pytest.raises(pipeline.SourceRunError) as raised: |
| 831 | self._run_pipeline_reddit_with_searxng(cfg, sc_search=sc_search, html_fetch=html_fetch) |
| 832 | assert raised.value.outcome_state == expected_state |
| 833 | assert not html_fetch.call_count |
| 834 | return |
| 835 | items, artifact, seen_urls = self._run_pipeline_reddit_with_searxng( |
| 836 | cfg, sc_search=sc_search, html_fetch=html_fetch, |
| 837 | ) |
| 838 | |
| 839 | assert seen_urls == [] |
| 840 | assert items == [] |
| 841 | assert bool(html_fetch.call_count) is (expected_state is None) |
| 842 | assert artifact.get("_source_outcome", {}).get("state") == expected_state |
| 843 | |
| 844 | def test_sc_primary_raised_auth_failure_is_not_masked_by_public_timeout(self): |
| 845 | from lib import pipeline |
| 846 | |
| 847 | clock = [100.0] |
| 848 | |
| 849 | def sc_search(*args, **kwargs): |
| 850 | clock[0] = 179.0 |
| 851 | raise http.HTTPError("HTTP 401", 401) |
| 852 | |
| 853 | cfg = { |
| 854 | "SCRAPECREATORS_API_KEY": "sc-dummy-key", |
| 855 | env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 856 | "_research_deadline": 200.0, |
| 857 | } |
| 858 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), \ |
| 859 | pytest.raises(pipeline.SourceRunError) as exc: |
| 860 | self._run_pipeline_reddit_with_searxng(cfg, sc_search=sc_search) |
| 861 | assert exc.value.outcome_state == health.AUTH_FAILED |
| 862 | |
| 863 | @pytest.mark.parametrize("mode", ["public-first", "public-first-backfill", "sc-first", "sc-first-429"]) |
| 864 | @pytest.mark.parametrize("wait_expired", [False, True], ids=["ladder", "wait"]) |
| 865 | def test_nested_web_cutoff_is_visible_before_the_public_lane_expires(self, mode, wait_expired): |
| 866 | from lib import reddit_keyless |
| 867 | |
| 868 | clock = [100.0] |
| 869 | # Public-first without a key and the SC-first fallback both start with 100s left, so |
| 870 | # each ends at 200 - 15 = 185 (web cutoff 177). |
| 871 | exhausted_at = 128.0 if mode == "public-first-backfill" else 178.0 |
| 872 | # The public-first lane with a paid key ends at 170 - 10.5 - 24.5 = 135 (cutoff 127). |
| 873 | budget = 170.0 if mode == "public-first-backfill" else 200.0 |
| 874 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example", "_research_deadline": budget} |
| 875 | if mode != "public-first": |
| 876 | cfg["SCRAPECREATORS_API_KEY"] = "sc-dummy-key" |
| 877 | if mode.startswith("sc-first"): |
| 878 | cfg[env.REDDIT_BACKEND_PIN_VAR] = "scrapecreators" |
| 879 | |
| 880 | def sc_search(*args, **kwargs): |
| 881 | if mode == "sc-first-429": |
| 882 | http._record_failure(http.HTTPError("HTTP 429", 429)) |
| 883 | return {} |
| 884 | |
| 885 | def html_fetch(*args, **kwargs): |
| 886 | clock[0] = exhausted_at # Past discovery, before the public lane's deadline. |
| 887 | return "" |
| 888 | |
| 889 | def run_inline(_wait_until, stage, default, call, /, *args, **kwargs): |
| 890 | if wait_expired and stage == "web floor": |
| 891 | clock[0] = exhausted_at |
| 892 | return default |
| 893 | return call(*args, **kwargs) |
| 894 | |
| 895 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), \ |
| 896 | mock.patch.object(reddit_keyless, "_within", side_effect=run_inline): |
| 897 | if mode == "sc-first-429": |
| 898 | # A captured paid 429 with nothing found ends the stream with a typed failure. |
| 899 | from lib import pipeline |
| 900 | |
| 901 | with pytest.raises(pipeline.SourceRunError) as raised: |
| 902 | self._run_pipeline_reddit_with_searxng( |
| 903 | cfg, sc_search=sc_search, html_fetch=html_fetch, |
| 904 | ) |
| 905 | assert raised.value.outcome_state == health.RATE_LIMITED |
| 906 | return |
| 907 | items, artifact, seen_urls = self._run_pipeline_reddit_with_searxng( |
| 908 | cfg, sc_search=sc_search if mode != "public-first" else None, html_fetch=html_fetch, |
| 909 | ) |
| 910 | |
| 911 | assert not items and not seen_urls |
| 912 | assert artifact.get("_source_outcome", {}).get("state") == health.TIMEOUT |
| 913 | |
| 914 | def test_public_first_backfill_clean_miss_is_not_a_timeout(self): |
| 915 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", "_research_deadline": 200.0} |
| 916 | with mock.patch("time.monotonic", return_value=100.0): |
| 917 | items, artifact, seen_urls = self._run_pipeline_reddit_with_searxng( |
| 918 | cfg, sc_search=lambda *args, **kwargs: {}, html_fetch=lambda *args, **kwargs: "", |
| 919 | ) |
| 920 | |
| 921 | assert not items and not seen_urls |
| 922 | assert "_source_outcome" not in artifact |
| 923 | |
| 924 | @pytest.mark.parametrize("backfill, state", [ |
| 925 | ("empty", health.TIMEOUT), |
| 926 | ("rate-limited", health.RATE_LIMITED), |
| 927 | ("result", None), |
| 928 | ]) |
| 929 | def test_public_cutoff_precedes_failed_paths_after_backfill(self, backfill, state): |
| 930 | from lib import reddit_keyless |
| 931 | |
| 932 | clock = [100.0] |
| 933 | lanes = [] |
| 934 | thread = "https://www.reddit.com/r/LocalLLaMA/comments/paid123/" |
| 935 | # 170s budget: the free lane ends at 170 - 10.5 - 24.5 = 135 (see the lanes assertion). |
| 936 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", "_research_deadline": 170.0, |
| 937 | "LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 938 | real_lane = reddit_keyless.lane_deadline |
| 939 | |
| 940 | def record_lane(deadline): |
| 941 | lanes.append(deadline) |
| 942 | return real_lane(deadline) |
| 943 | |
| 944 | def blocked_html(*args, **kwargs): |
| 945 | http._record_failure(http.HTTPError("HTTP 403: HTML rung blocked", 403)) |
| 946 | clock[0] = 128.0 # Past the discovery cutoff (127), before the lane deadline (135). |
| 947 | return None |
| 948 | |
| 949 | def sc_search(*args, **kwargs): |
| 950 | if backfill == "rate-limited": |
| 951 | http._record_failure(http.HTTPError("HTTP 429: paid backfill throttled", 429)) |
| 952 | return {"items": [_hit(thread)] if backfill == "result" else []} |
| 953 | |
| 954 | def run_inline(_wait_until, _stage, _default, call, /, *args, **kwargs): |
| 955 | return call(*args, **kwargs) |
| 956 | |
| 957 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), \ |
| 958 | mock.patch.object(reddit_keyless, "_within", side_effect=run_inline), \ |
| 959 | mock.patch.object(reddit_keyless, "lane_deadline", side_effect=record_lane), \ |
| 960 | mock.patch.object(reddit_keyless.reddit_search, "_blocked_reason", "offline 403"): |
| 961 | items, artifact, seen_urls = self._run_pipeline_reddit_with_searxng( |
| 962 | cfg, sc_search=sc_search, html_fetch=blocked_html, |
| 963 | ) |
| 964 | |
| 965 | assert lanes == [135.0] |
| 966 | assert clock[0] == 128.0 and not seen_urls |
| 967 | assert [item["url"] for item in items] == ([thread] if backfill == "result" else []) |
| 968 | assert artifact.get("_source_outcome", {}).get("state") == state |
| 969 | if backfill == "rate-limited": |
| 970 | assert artifact["_source_outcome"]["detail"] == "HTTP 429: paid backfill throttled" |
| 971 | |
| 972 | @pytest.mark.parametrize("backfill, state, detail", [ |
| 973 | ("incomplete", health.TIMEOUT, "paid backfill stopped at its deadline before completing"), |
| 974 | ("incomplete-429", health.RATE_LIMITED, "HTTP 429: paid backfill throttled"), |
| 975 | ("complete-empty", health.TIMEOUT, "Reddit ran out of search time before it found threads"), |
| 976 | ]) |
| 977 | def test_actual_cutoff_keeps_the_incomplete_backfill_note(self, backfill, state, detail): |
| 978 | from lib import reddit_keyless |
| 979 | |
| 980 | clock = [100.0] |
| 981 | lanes = [] |
| 982 | note = "paid backfill stopped at its deadline before completing" |
| 983 | # 170s budget: the free lane ends at 135 and the web stage's own cutoff is 127. |
| 984 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", "_research_deadline": 170.0, |
| 985 | "LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 986 | real_lane = reddit_keyless.lane_deadline |
| 987 | |
| 988 | def record_lane(deadline): |
| 989 | lanes.append(deadline) |
| 990 | return real_lane(deadline) |
| 991 | |
| 992 | def clean_empty_html(*args, **kwargs): |
| 993 | clock[0] = 128.0 # Past the discovery cutoff (127), before the lane deadline (135). |
| 994 | return "" |
| 995 | |
| 996 | def sc_search(*args, **kwargs): |
| 997 | if backfill == "complete-empty": |
| 998 | return {} |
| 999 | if backfill == "incomplete-429": |
| 1000 | http._record_failure(http.HTTPError("HTTP 429: paid backfill throttled", 429)) |
| 1001 | return {"items": [], "incomplete": True, "incomplete_note": note} |
| 1002 | |
| 1003 | def run_inline(_wait_until, _stage, _default, call, /, *args, **kwargs): |
| 1004 | return call(*args, **kwargs) |
| 1005 | |
| 1006 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), mock.patch.object(reddit_keyless, "_within", side_effect=run_inline), mock.patch.object(reddit_keyless, "lane_deadline", side_effect=record_lane): |
| 1007 | items, artifact, seen_urls = self._run_pipeline_reddit_with_searxng( |
| 1008 | cfg, sc_search=sc_search, html_fetch=clean_empty_html, |
| 1009 | ) |
| 1010 | |
| 1011 | # The site search answered cleanly and empty, so no path failed; the web stage hit its |
| 1012 | # real cutoff and the paid backfill ended empty. A captured paid failure keeps precedence. |
| 1013 | assert lanes == [135.0] and clock[0] == 128.0 and not seen_urls and not items |
| 1014 | outcome = artifact["_source_outcome"] |
| 1015 | assert outcome["state"] == state and outcome["detail"] == detail |
| 1016 | |
| 1017 | def test_completed_failures_precede_the_incomplete_backfill_note(self): |
| 1018 | from lib import reddit_keyless |
| 1019 | |
| 1020 | note = "paid backfill stopped at its deadline before completing" |
| 1021 | |
| 1022 | def web_floor(*args, **kwargs): |
| 1023 | return [] |
| 1024 | |
| 1025 | def run_inline(_wait_until, _stage, _default, call, /, *args, **kwargs): |
| 1026 | return call(*args, **kwargs) |
| 1027 | |
| 1028 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", "_research_deadline": 170.0} |
| 1029 | with mock.patch("time.monotonic", return_value=100.0), \ |
| 1030 | mock.patch.object(reddit_keyless, "_within", side_effect=run_inline), \ |
| 1031 | mock.patch.object(reddit_keyless, "_web_floor", side_effect=web_floor), \ |
| 1032 | mock.patch.object(reddit_keyless.reddit_search, "_blocked_reason", "offline 403"): |
| 1033 | items, artifact, seen_urls = self._run_pipeline_reddit_with_searxng( |
| 1034 | cfg, sc_search=lambda *a, **k: {"items": [], "incomplete": True, "incomplete_note": note}, |
| 1035 | ) |
| 1036 | |
| 1037 | # Every asked path failed and nothing was cut off: the failure, not the paid note, is reported. |
| 1038 | assert not items and not seen_urls |
| 1039 | outcome = artifact["_source_outcome"] |
| 1040 | assert outcome["state"] == health.UNREACHABLE and "search blocked" in outcome["detail"] |
| 1041 | |
| 1042 | @pytest.mark.parametrize("backfill", ["empty", "rate-limited", "result"]) |
| 1043 | def test_return_margin_alone_keeps_completed_failures_after_backfill(self, backfill): |
| 1044 | from lib import reddit_keyless |
| 1045 | |
| 1046 | clock = [100.0] |
| 1047 | marks = [] |
| 1048 | lanes = [] |
| 1049 | thread = "https://www.reddit.com/r/LocalLLaMA/comments/paid123/" |
| 1050 | # 170s budget: the free lane ends at 170 - 10.5 - 24.5 = 135 (see the lanes assertion). |
| 1051 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", "_research_deadline": 170.0} |
| 1052 | real_lane = reddit_keyless.lane_deadline |
| 1053 | |
| 1054 | def record_lane(deadline): |
| 1055 | lanes.append(deadline) |
| 1056 | return real_lane(deadline) |
| 1057 | |
| 1058 | def web_floor_finishes_inside_margin(*args, **kwargs): |
| 1059 | # It starts with 4s left, so its own cutoff (133.4) is never reached; |
| 1060 | # it ends 1.8s before the 135 lane deadline: inside the 2s return margin. |
| 1061 | clock[0] = 133.2 |
| 1062 | return [] |
| 1063 | |
| 1064 | def sc_search(*args, **kwargs): |
| 1065 | if backfill == "rate-limited": |
| 1066 | http._record_failure(http.HTTPError("HTTP 429: paid backfill throttled", 429)) |
| 1067 | return {"items": [_hit(thread)] if backfill == "result" else []} |
| 1068 | |
| 1069 | def run_inline(_wait_until, _stage, _default, call, /, *args, **kwargs): |
| 1070 | return call(*args, **kwargs) |
| 1071 | |
| 1072 | real_mark = reddit_keyless._mark |
| 1073 | |
| 1074 | def record_mark(path, state): |
| 1075 | marks.append((path, state)) |
| 1076 | return real_mark(path, state) |
| 1077 | |
| 1078 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), mock.patch.object(reddit_keyless, "_within", side_effect=run_inline), mock.patch.object(reddit_keyless, "lane_deadline", side_effect=record_lane), mock.patch.object(reddit_keyless, "_web_floor", side_effect=web_floor_finishes_inside_margin), mock.patch.object(reddit_keyless, "_mark", side_effect=record_mark), mock.patch.object(reddit_keyless.reddit_search, "_blocked_reason", "offline 403"): |
| 1079 | items, artifact, seen_urls = self._run_pipeline_reddit_with_searxng(cfg, sc_search=sc_search) |
| 1080 | |
| 1081 | # Every asked path finished and failed. Only the return margin was crossed. |
| 1082 | assert lanes == [135.0] |
| 1083 | assert clock[0] == 133.2 and not seen_urls |
| 1084 | assert ("web", health.TIMEOUT) not in marks |
| 1085 | assert [item["url"] for item in items] == ([thread] if backfill == "result" else []) |
| 1086 | outcome = artifact.get("_source_outcome") |
| 1087 | if backfill == "result": |
| 1088 | assert outcome is None |
| 1089 | else: |
| 1090 | assert outcome["state"] == health.UNREACHABLE and "search blocked" in outcome["detail"] |
| 1091 | |
| 1092 | @pytest.mark.parametrize("margin_crossed", [False, True], ids=["in-margin", "past-margin"]) |
| 1093 | def test_incomplete_empty_backfill_keeps_its_note_ahead_of_the_margin_timeout(self, margin_crossed): |
| 1094 | from lib import reddit_keyless |
| 1095 | |
| 1096 | clock = [100.0] |
| 1097 | note = "Reddit ScrapeCreators backfill stopped at its deadline before completing" |
| 1098 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", "_research_deadline": 170.0} |
| 1099 | |
| 1100 | def web_floor(*args, **kwargs): |
| 1101 | clock[0] = 133.2 if margin_crossed else 100.0 # 133.2 is inside the 135 lane's 2s margin |
| 1102 | return [] |
| 1103 | |
| 1104 | def run_inline(_wait_until, _stage, _default, call, /, *args, **kwargs): |
| 1105 | return call(*args, **kwargs) |
| 1106 | |
| 1107 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), \ |
| 1108 | mock.patch.object(reddit_keyless, "_within", side_effect=run_inline), \ |
| 1109 | mock.patch.object(reddit_keyless, "_web_floor", side_effect=web_floor): |
| 1110 | items, artifact, seen_urls = self._run_pipeline_reddit_with_searxng( |
| 1111 | cfg, sc_search=lambda *a, **k: {"items": [], "incomplete": True, "incomplete_note": note}, |
| 1112 | ) |
| 1113 | |
| 1114 | assert not items and not seen_urls |
| 1115 | outcome = artifact["_source_outcome"] |
| 1116 | assert outcome["state"] == health.TIMEOUT and outcome["detail"] == note |
| 1117 | |
| 1118 | @pytest.mark.parametrize("failure, note", [ |
| 1119 | (http.HTTPError("HTTP 403: refused", 403), "SearXNG fallback refused (403)"), |
| 1120 | (http.HTTPError("HTTP 429: slow down", 429), "SearXNG fallback throttled (429)"), |
| 1121 | ]) |
| 1122 | def test_searxng_failure_is_noted_without_becoming_a_reddit_failure(self, failure, note): |
| 1123 | def refuse(*args, **kwargs): |
| 1124 | http._record_failure(failure) |
| 1125 | raise failure |
| 1126 | |
| 1127 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 1128 | items, artifact, _ = self._run_pipeline_reddit_with_searxng( |
| 1129 | cfg, html_fetch=lambda *args, **kwargs: "", searxng_get=refuse, |
| 1130 | ) |
| 1131 | |
| 1132 | assert not items |
| 1133 | assert note in artifact.get("_source_outcome_detail", "") |
| 1134 | assert artifact.get("_source_outcome", {}).get("state") not in (health.UNREACHABLE, health.RATE_LIMITED) |
| 1135 | assert "searx.example" not in str(artifact) |
| 1136 | |
| 1137 | def test_searxng_deadline_is_a_real_timeout_not_a_reddit_failure(self): |
| 1138 | def run_out(*args, **kwargs): |
| 1139 | failure = http.DeadlineExceeded() |
| 1140 | http._record_failure(failure) |
| 1141 | raise failure |
| 1142 | |
| 1143 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 1144 | items, artifact, _ = self._run_pipeline_reddit_with_searxng( |
| 1145 | cfg, html_fetch=lambda *args, **kwargs: "", searxng_get=run_out, |
| 1146 | ) |
| 1147 | |
| 1148 | assert not items |
| 1149 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 1150 | |
| 1151 | @pytest.mark.parametrize("failure, note", [ |
| 1152 | (http.HTTPError("HTTP 403: refused", 403), "SearXNG fallback refused (403)"), |
| 1153 | (http.HTTPError("HTTP 429: slow down", 429), "SearXNG fallback throttled (429)"), |
| 1154 | ]) |
| 1155 | def test_sc_first_public_dispatch_keeps_the_searxng_note(self, failure, note): |
| 1156 | def refuse(*args, **kwargs): |
| 1157 | http._record_failure(failure) |
| 1158 | raise failure |
| 1159 | |
| 1160 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 1161 | "LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 1162 | items, artifact, _ = self._run_pipeline_reddit_with_searxng( |
| 1163 | cfg, sc_search=lambda *a, **k: {}, html_fetch=lambda *a, **k: "", searxng_get=refuse, |
| 1164 | ) |
| 1165 | |
| 1166 | assert not items |
| 1167 | assert note in artifact.get("_source_outcome_detail", "") |
| 1168 | assert "_source_outcome_detail_state" not in artifact |
| 1169 | assert artifact.get("_source_outcome", {}).get("state") not in (health.UNREACHABLE, health.RATE_LIMITED) |
| 1170 | |
| 1171 | def test_sc_first_searxng_note_leaves_captured_http_priority_alone(self): |
| 1172 | from lib import pipeline |
| 1173 | |
| 1174 | def run(searxng_get): |
| 1175 | reddit_discover.reset_run_state() |
| 1176 | web_search_keyless.reset_rung_health() |
| 1177 | |
| 1178 | def sc_search(*args, **kwargs): |
| 1179 | http._record_failure(http.HTTPError("HTTP 429: paid primary throttled", 429)) |
| 1180 | return {} |
| 1181 | |
| 1182 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 1183 | "LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 1184 | # A captured paid failure with nothing found ends the stream with a typed failure. |
| 1185 | with pytest.raises(pipeline.SourceRunError) as raised: |
| 1186 | self._run_pipeline_reddit_with_searxng( |
| 1187 | cfg, sc_search=sc_search, html_fetch=lambda *a, **k: "", searxng_get=searxng_get, |
| 1188 | ) |
| 1189 | return raised.value |
| 1190 | |
| 1191 | def refuse(*args, **kwargs): |
| 1192 | failure = http.HTTPError("HTTP 403: refused", 403) |
| 1193 | http._record_failure(failure) |
| 1194 | raise failure |
| 1195 | |
| 1196 | baseline = run(lambda *a, **k: {"results": []}) |
| 1197 | noted = run(refuse) |
| 1198 | |
| 1199 | # The typed state and the reason are exactly what they were. The note travels beside them. |
| 1200 | assert noted.outcome_state == baseline.outcome_state == health.RATE_LIMITED |
| 1201 | assert str(noted) == str(baseline) |
| 1202 | assert baseline.lane_notes == () |
| 1203 | assert noted.lane_notes == ("SearXNG fallback refused (403)",) |
| 1204 | |
| 1205 | def test_public_first_early_timeout_keeps_the_observed_searxng_note(self): |
| 1206 | clock = [100.0] |
| 1207 | |
| 1208 | def refuse(*args, **kwargs): |
| 1209 | failure = http.HTTPError("HTTP 403: refused", 403) |
| 1210 | http._record_failure(failure) |
| 1211 | clock[0] = 158.0 # Past the web stage's own cutoff and inside the lane's 2s return margin. |
| 1212 | raise failure |
| 1213 | |
| 1214 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example", "_research_deadline": 170.0} |
| 1215 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]): |
| 1216 | items, artifact, _ = self._run_pipeline_reddit_with_searxng( |
| 1217 | cfg, html_fetch=lambda *a, **k: "", searxng_get=refuse, |
| 1218 | ) |
| 1219 | |
| 1220 | assert not items |
| 1221 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 1222 | assert "SearXNG fallback refused (403)" in artifact["_source_outcome_detail"] |
| 1223 | assert "_source_outcome_detail_state" not in artifact |
| 1224 | |
| 1225 | def test_public_first_early_failure_keeps_the_observed_searxng_note(self): |
| 1226 | def refuse(*args, **kwargs): |
| 1227 | failure = http.HTTPError("HTTP 403: refused", 403) |
| 1228 | http._record_failure(failure) |
| 1229 | raise failure |
| 1230 | |
| 1231 | def blocked_html(*args, **kwargs): |
| 1232 | http._record_failure(http.HTTPError("HTTP 403: HTML rung blocked", 403)) |
| 1233 | return None |
| 1234 | |
| 1235 | from lib import reddit_keyless |
| 1236 | |
| 1237 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 1238 | with mock.patch.object(reddit_keyless.reddit_search, "_blocked_reason", "offline 403"): |
| 1239 | items, artifact, _ = self._run_pipeline_reddit_with_searxng( |
| 1240 | cfg, html_fetch=blocked_html, searxng_get=refuse, |
| 1241 | ) |
| 1242 | |
| 1243 | assert not items |
| 1244 | assert artifact["_source_outcome"]["state"] == health.UNREACHABLE |
| 1245 | assert "SearXNG fallback refused (403)" in artifact["_source_outcome_detail"] |
| 1246 | |
| 1247 | def test_public_first_backfill_timeout_keeps_its_detail_and_gains_the_searxng_note(self): |
| 1248 | note = "paid backfill stopped at its deadline before completing" |
| 1249 | |
| 1250 | def refuse(*args, **kwargs): |
| 1251 | failure = http.HTTPError("HTTP 429: slow down", 429) |
| 1252 | http._record_failure(failure) |
| 1253 | raise failure |
| 1254 | |
| 1255 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", "LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 1256 | items, artifact, _ = self._run_pipeline_reddit_with_searxng( |
| 1257 | cfg, sc_search=lambda *a, **k: {"items": [], "incomplete": True, "incomplete_note": note}, |
| 1258 | html_fetch=lambda *a, **k: "", searxng_get=refuse, |
| 1259 | ) |
| 1260 | |
| 1261 | assert not items |
| 1262 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 1263 | assert artifact["_source_outcome"]["detail"] == note |
| 1264 | assert artifact["_source_outcome_detail"] == "SearXNG fallback throttled (429)" |
| 1265 | |
| 1266 | @staticmethod |
| 1267 | def _searxng_refusal(status, after=None): |
| 1268 | def refuse(*args, **kwargs): |
| 1269 | failure = http.HTTPError(f"HTTP {status}: refused", status) |
| 1270 | http._record_failure(failure) |
| 1271 | if after is not None: |
| 1272 | after() |
| 1273 | raise failure |
| 1274 | |
| 1275 | return refuse |
| 1276 | |
| 1277 | def test_report_keeps_the_note_with_a_real_cutoff_timeout(self): |
| 1278 | from lib import reddit_keyless |
| 1279 | |
| 1280 | clock = [100.0] |
| 1281 | lanes = [] |
| 1282 | real_lane = reddit_keyless.lane_deadline |
| 1283 | |
| 1284 | def record_lane(deadline): |
| 1285 | lanes.append(deadline) |
| 1286 | return real_lane(deadline) |
| 1287 | |
| 1288 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example", "_research_deadline": 170.0} |
| 1289 | refuse = self._searxng_refusal(403, after=lambda: clock.__setitem__(0, 158.0)) |
| 1290 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), \ |
| 1291 | mock.patch.object(reddit_keyless, "lane_deadline", side_effect=record_lane): |
| 1292 | report, _, _ = self._run_pipeline_reddit_with_searxng( |
| 1293 | cfg, html_fetch=lambda *a, **k: "", searxng_get=refuse, full_report=True, |
| 1294 | ) |
| 1295 | |
| 1296 | outcome = report.source_status["reddit"] |
| 1297 | assert lanes == [159.5] |
| 1298 | assert outcome.state == health.TIMEOUT |
| 1299 | assert outcome.detail == "Reddit ran out of search time before it found threads; SearXNG fallback refused (403)" |
| 1300 | |
| 1301 | def test_report_keeps_a_captured_paid_429_and_its_reason_with_the_note(self): |
| 1302 | def sc_search(*args, **kwargs): |
| 1303 | http._record_failure(http.HTTPError("HTTP 429: paid primary throttled", 429)) |
| 1304 | return {} |
| 1305 | |
| 1306 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 1307 | "LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 1308 | report, _, _ = self._run_pipeline_reddit_with_searxng( |
| 1309 | cfg, sc_search=sc_search, html_fetch=lambda *a, **k: "", |
| 1310 | searxng_get=self._searxng_refusal(403), full_report=True, |
| 1311 | ) |
| 1312 | |
| 1313 | outcome = report.source_status["reddit"] |
| 1314 | reason = "Reddit primary and fallback produced no results after failure: HTTP 429: paid primary throttled" |
| 1315 | assert outcome.state == health.RATE_LIMITED |
| 1316 | assert outcome.detail == f"{reason}; SearXNG fallback refused (403)" |
| 1317 | assert report.errors_by_source["reddit"] == reason |
| 1318 | |
| 1319 | def test_report_keeps_a_paid_backfill_timeout_and_its_note(self): |
| 1320 | note = "paid backfill stopped at its deadline before completing" |
| 1321 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", "LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 1322 | report, _, _ = self._run_pipeline_reddit_with_searxng( |
| 1323 | cfg, sc_search=lambda *a, **k: {"items": [], "incomplete": True, "incomplete_note": note}, |
| 1324 | html_fetch=lambda *a, **k: "", searxng_get=self._searxng_refusal(429), full_report=True, |
| 1325 | ) |
| 1326 | |
| 1327 | outcome = report.source_status["reddit"] |
| 1328 | assert outcome.state == health.TIMEOUT |
| 1329 | assert outcome.detail == f"{note}; SearXNG fallback throttled (429)" |
| 1330 | |
| 1331 | def test_report_without_a_fallback_failure_has_no_note(self): |
| 1332 | clock = [100.0] |
| 1333 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example", "_research_deadline": 170.0} |
| 1334 | |
| 1335 | def html_past_cutoff(*args, **kwargs): |
| 1336 | clock[0] = 158.0 |
| 1337 | return "" |
| 1338 | |
| 1339 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]): |
| 1340 | cutoff, _, _ = self._run_pipeline_reddit_with_searxng( |
| 1341 | cfg, html_fetch=html_past_cutoff, full_report=True, |
| 1342 | ) |
| 1343 | clean, _, _ = self._run_pipeline_reddit_with_searxng( |
| 1344 | {"LAST30DAYS_SEARXNG_URL": "https://searx.example"}, |
| 1345 | html_fetch=lambda *a, **k: "", searxng_get=lambda *a, **k: {"results": []}, full_report=True, |
| 1346 | ) |
| 1347 | |
| 1348 | assert cutoff.source_status["reddit"].detail == "Reddit ran out of search time before it found threads" |
| 1349 | assert "SearXNG" not in str(clean.source_status["reddit"].detail) |
| 1350 | |
| 1351 | def test_report_for_a_served_run_keeps_the_note_and_the_ok_state(self): |
| 1352 | site_hit = { |
| 1353 | "title": "IQ3 quantization discussion", |
| 1354 | "url": "https://www.reddit.com/r/LocalLLaMA/comments/site123/", |
| 1355 | "date": "2026-05-20", |
| 1356 | "engagement": {"score": 25, "num_comments": 3}, |
| 1357 | "relevance": 0.9, |
| 1358 | "metadata": {"post_id": "site123"}, |
| 1359 | } |
| 1360 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 1361 | report, _, _ = self._run_pipeline_reddit_with_searxng( |
| 1362 | cfg, html_fetch=lambda *a, **k: "", site_hits=[site_hit], |
| 1363 | searxng_get=self._searxng_refusal(403), full_report=True, |
| 1364 | ) |
| 1365 | |
| 1366 | outcome = report.source_status["reddit"] |
| 1367 | assert outcome.state == health.OK and outcome.items_returned >= 1 |
| 1368 | assert "SearXNG fallback refused (403)" in outcome.detail |
| 1369 | |
| 1370 | def test_another_sources_note_never_lands_on_reddit(self): |
| 1371 | import time |
| 1372 | |
| 1373 | from lib import pipeline |
| 1374 | |
| 1375 | reason = "Reddit ran out of search time before it found threads" |
| 1376 | |
| 1377 | def stream(*args, **kwargs): |
| 1378 | if kwargs["source"] == "polymarket": |
| 1379 | time.sleep(0.4) # Recorded after Reddit's failure, so a leaked note would have a target. |
| 1380 | return [], { |
| 1381 | "_source_outcome": {"state": health.ERROR, "detail": "market feed broke", "attempted": True}, |
| 1382 | "_source_outcome_detail": "a market note", |
| 1383 | } |
| 1384 | return [], {"_source_outcome": {"state": health.TIMEOUT, "detail": reason, "attempted": True}} |
| 1385 | |
| 1386 | with mock.patch.object(pipeline, "_retrieve_stream_impl", side_effect=stream): |
| 1387 | report, _, _ = self._run_pipeline_reddit_with_searxng( |
| 1388 | {"LAST30DAYS_SEARXNG_URL": "https://searx.example"}, full_report=True, |
| 1389 | report_sources=("reddit", "polymarket"), |
| 1390 | ) |
| 1391 | |
| 1392 | assert report.source_status["reddit"].detail == reason |
| 1393 | assert "a market note" not in str(report.source_status["reddit"].detail) |
| 1394 | assert report.source_status["polymarket"].state == health.ERROR |
| 1395 | assert report.source_status["polymarket"].detail == "market feed broke" |
| 1396 | |
| 1397 | _NOTE = "SearXNG fallback refused (403)" |
| 1398 | _SLOW = "Reddit ran out of search time before it found threads" |
| 1399 | _DRIFT = "Reddit answered with a page the parser could not read" |
| 1400 | _THREAD = { |
| 1401 | "id": "R1", |
| 1402 | "title": "IQ3 quantization notes", |
| 1403 | "url": "https://www.reddit.com/r/LocalLLaMA/comments/1sx9abc/iq3_quantization_notes/", |
| 1404 | "score": 40, |
| 1405 | "num_comments": 7, |
| 1406 | "subreddit": "LocalLLaMA", |
| 1407 | "created_utc": 1_779_000_000, |
| 1408 | "author": "u", |
| 1409 | "selftext": "IQ3 notes", |
| 1410 | "date": "2026-05-20", |
| 1411 | "engagement": {"score": 40, "num_comments": 7, "upvote_ratio": None}, |
| 1412 | "relevance": 1.0, |
| 1413 | "why_relevant": "Reddit listing", |
| 1414 | "metadata": {"post_id": "1sx9abc"}, |
| 1415 | } |
| 1416 | |
| 1417 | def _scripted_report(self, scripts, labels, *, sources=("reddit",)): |
| 1418 | """Run the whole pipeline with each stream scripted by source or label. |
| 1419 | |
| 1420 | A script is a tuple of items, artifact and delay. Streams are recorded as they |
| 1421 | finish, so the delay sets which one the report sees second. |
| 1422 | """ |
| 1423 | import time |
| 1424 | |
| 1425 | from lib import pipeline |
| 1426 | |
| 1427 | def stream(*args, **kwargs): |
| 1428 | key = kwargs["source"] if kwargs["source"] in scripts else kwargs["subquery"].label |
| 1429 | # Anything unscripted, such as the thin-results retry, is an empty clean stream. |
| 1430 | items, artifact, delay = scripts.get(key, ([], {}, 0)) |
| 1431 | if delay: |
| 1432 | time.sleep(delay) |
| 1433 | return list(items), dict(artifact) |
| 1434 | |
| 1435 | with mock.patch.object(pipeline, "_retrieve_stream_impl", side_effect=stream): |
| 1436 | report, _, _ = self._run_pipeline_reddit_with_searxng( |
| 1437 | {"LAST30DAYS_SEARXNG_URL": "https://searx.example"}, full_report=True, |
| 1438 | labels=labels, report_depth="default", report_sources=sources, |
| 1439 | ) |
| 1440 | return report |
| 1441 | |
| 1442 | def _typed(self, state, detail, note=None): |
| 1443 | artifact = {"_source_outcome": {"state": state, "detail": detail, "attempted": True}} |
| 1444 | if note: |
| 1445 | artifact["_source_outcome_detail"] = note |
| 1446 | return artifact |
| 1447 | |
| 1448 | @pytest.mark.parametrize("note_stream_first", [True, False], ids=["noted-first", "noted-second"]) |
| 1449 | @pytest.mark.parametrize("noted_wins", [True, False], ids=["noted-wins", "plain-wins"]) |
| 1450 | def test_report_keeps_the_note_when_the_competing_failure_has_higher_priority(self, noted_wins, note_stream_first): |
| 1451 | # SCHEMA_DRIFT outranks TIMEOUT in the bundle's own rules, so the winner is never in doubt. |
| 1452 | noted_state, noted_reason = (health.SCHEMA_DRIFT, self._DRIFT) if noted_wins else (health.TIMEOUT, self._SLOW) |
| 1453 | plain_state, plain_reason = (health.TIMEOUT, self._SLOW) if noted_wins else (health.SCHEMA_DRIFT, self._DRIFT) |
| 1454 | slow = 0.4 |
| 1455 | report = self._scripted_report( |
| 1456 | { |
| 1457 | "noted": ([], self._typed(noted_state, noted_reason, self._NOTE), 0 if note_stream_first else slow), |
| 1458 | "plain": ([], self._typed(plain_state, plain_reason), slow if note_stream_first else 0), |
| 1459 | }, |
| 1460 | labels=("noted", "plain") if note_stream_first else ("plain", "noted"), |
| 1461 | ) |
| 1462 | |
| 1463 | outcome = report.source_status["reddit"] |
| 1464 | winner_reason = noted_reason if noted_wins else plain_reason |
| 1465 | assert outcome.state == health.SCHEMA_DRIFT |
| 1466 | # The winner's own reason stays first and the note follows it exactly once. |
| 1467 | assert outcome.detail == f"{winner_reason}; {self._NOTE}" |
| 1468 | assert report.errors_by_source["reddit"] == winner_reason |
| 1469 | |
| 1470 | @pytest.mark.parametrize("noted_first", [True, False], ids=["noted-first", "noted-second"]) |
| 1471 | def test_report_keeps_the_note_when_the_other_stream_fails_alike(self, noted_first): |
| 1472 | slow = 0.4 |
| 1473 | report = self._scripted_report( |
| 1474 | { |
| 1475 | "noted": ([], self._typed(health.TIMEOUT, self._SLOW, self._NOTE), 0 if noted_first else slow), |
| 1476 | "plain": ([], self._typed(health.TIMEOUT, self._SLOW), slow if noted_first else 0), |
| 1477 | }, |
| 1478 | labels=("noted", "plain") if noted_first else ("plain", "noted"), |
| 1479 | ) |
| 1480 | |
| 1481 | outcome = report.source_status["reddit"] |
| 1482 | assert outcome.state == health.TIMEOUT |
| 1483 | assert outcome.detail == f"{self._SLOW}; {self._NOTE}" |
| 1484 | assert report.errors_by_source["reddit"] == self._SLOW |
| 1485 | |
| 1486 | def test_report_carries_a_note_seen_by_both_streams_once(self): |
| 1487 | report = self._scripted_report( |
| 1488 | { |
| 1489 | "one": ([], self._typed(health.TIMEOUT, self._SLOW, self._NOTE), 0), |
| 1490 | "two": ([], self._typed(health.TIMEOUT, self._SLOW, self._NOTE), 0.4), |
| 1491 | }, |
| 1492 | labels=("one", "two"), |
| 1493 | ) |
| 1494 | |
| 1495 | assert report.source_status["reddit"].detail == f"{self._SLOW}; {self._NOTE}" |
| 1496 | |
| 1497 | @pytest.mark.parametrize("served_first", [True, False], ids=["served-first", "served-second"]) |
| 1498 | def test_report_keeps_a_served_streams_note_beside_a_later_failure(self, served_first): |
| 1499 | slow = 0.4 |
| 1500 | report = self._scripted_report( |
| 1501 | { |
| 1502 | "served": ([self._THREAD], {"_source_outcome_detail": f"search served 1; {self._NOTE}"}, 0 if served_first else slow), |
| 1503 | "failed": ([], self._typed(health.TIMEOUT, self._SLOW), slow if served_first else 0), |
| 1504 | }, |
| 1505 | labels=("served", "failed") if served_first else ("failed", "served"), |
| 1506 | ) |
| 1507 | |
| 1508 | outcome = report.source_status["reddit"] |
| 1509 | assert outcome.state == health.PARTIAL and outcome.items_returned == 1 |
| 1510 | assert outcome.detail == f"{self._SLOW}; {self._NOTE}" |
| 1511 | |
| 1512 | def test_report_for_two_served_streams_shows_the_note_once_and_stays_ok(self): |
| 1513 | report = self._scripted_report( |
| 1514 | { |
| 1515 | "one": ([self._THREAD], {"_source_outcome_detail": self._NOTE}, 0), |
| 1516 | "two": ([], {"_source_outcome_detail": self._NOTE}, 0.4), |
| 1517 | }, |
| 1518 | labels=("one", "two"), |
| 1519 | ) |
| 1520 | |
| 1521 | outcome = report.source_status["reddit"] |
| 1522 | assert outcome.state == health.OK |
| 1523 | assert outcome.detail == self._NOTE |
| 1524 | |
| 1525 | def test_report_with_no_note_anywhere_shows_only_the_reason(self): |
| 1526 | report = self._scripted_report( |
| 1527 | { |
| 1528 | "one": ([], self._typed(health.TIMEOUT, self._SLOW), 0), |
| 1529 | "two": ([], self._typed(health.SCHEMA_DRIFT, self._DRIFT), 0.4), |
| 1530 | }, |
| 1531 | labels=("one", "two"), |
| 1532 | ) |
| 1533 | |
| 1534 | assert report.source_status["reddit"].detail == self._DRIFT |
| 1535 | |
| 1536 | def test_report_keeps_a_note_that_arrives_on_the_thin_results_retry(self): |
| 1537 | report = self._scripted_report( |
| 1538 | { |
| 1539 | "primary": ([], {}, 0), |
| 1540 | "retry": ([], self._typed(health.TIMEOUT, self._SLOW, self._NOTE), 0), |
| 1541 | }, |
| 1542 | labels=("primary",), |
| 1543 | ) |
| 1544 | |
| 1545 | outcome = report.source_status["reddit"] |
| 1546 | assert outcome.state == health.TIMEOUT |
| 1547 | assert outcome.detail == f"{self._SLOW}; {self._NOTE}" |
| 1548 | |
| 1549 | def test_a_note_on_another_source_never_reaches_reddit_and_reddit_notes_never_reach_it(self): |
| 1550 | report = self._scripted_report( |
| 1551 | { |
| 1552 | "reddit": ([], self._typed(health.TIMEOUT, self._SLOW, self._NOTE), 0), |
| 1553 | "polymarket": ([], self._typed(health.ERROR, "market feed broke", "a market note"), 0.4), |
| 1554 | }, |
| 1555 | labels=("primary",), sources=("reddit", "polymarket"), |
| 1556 | ) |
| 1557 | |
| 1558 | assert report.source_status["reddit"].detail == f"{self._SLOW}; {self._NOTE}" |
| 1559 | assert report.source_status["polymarket"].detail == "market feed broke" |
| 1560 | |
| 1561 | def test_text_that_looks_like_a_note_on_another_source_is_never_read_for_reddit(self): |
| 1562 | report = self._scripted_report( |
| 1563 | { |
| 1564 | "reddit": ([], self._typed(health.TIMEOUT, self._SLOW), 0), |
| 1565 | "polymarket": ([], self._typed(health.ERROR, "market feed broke", self._NOTE), 0.4), |
| 1566 | }, |
| 1567 | labels=("primary",), sources=("reddit", "polymarket"), |
| 1568 | ) |
| 1569 | |
| 1570 | assert report.source_status["reddit"].detail == self._SLOW |
| 1571 | assert report.source_status["polymarket"].detail == "market feed broke" |
| 1572 | |
| 1573 | def test_paid_429_with_a_delivering_fallback_is_partial_and_keeps_the_searxng_note(self): |
| 1574 | site_hit = { |
| 1575 | "title": "IQ3 quantization discussion", |
| 1576 | "url": "https://www.reddit.com/r/LocalLLaMA/comments/site123/", |
| 1577 | "date": "2026-05-20", |
| 1578 | "engagement": {"score": 25, "num_comments": 3}, |
| 1579 | "relevance": 0.9, |
| 1580 | "metadata": {"post_id": "site123"}, |
| 1581 | } |
| 1582 | |
| 1583 | def sc_search(*args, **kwargs): |
| 1584 | http._record_failure(http.HTTPError("HTTP 429: paid primary throttled", 429)) |
| 1585 | return {} |
| 1586 | |
| 1587 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 1588 | "LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 1589 | items, artifact, _ = self._run_pipeline_reddit_with_searxng( |
| 1590 | cfg, sc_search=sc_search, html_fetch=lambda *a, **k: "", site_hits=[site_hit], |
| 1591 | searxng_get=self._searxng_refusal(403), |
| 1592 | ) |
| 1593 | |
| 1594 | # Upstream's rule is that a paid 429 must not brand Reddit rate-limited when the fallback delivered. |
| 1595 | assert [i["metadata"]["post_id"] for i in items] == ["site123"] |
| 1596 | assert artifact["_source_outcome"]["state"] == health.PARTIAL |
| 1597 | assert artifact["_source_outcome"]["detail"].startswith( |
| 1598 | "Reddit primary failed; public fallback returned 1 items: HTTP 429" |
| 1599 | ) |
| 1600 | assert artifact["_source_outcome_detail"] == self._NOTE |
| 1601 | |
| 1602 | reddit_discover.reset_run_state() |
| 1603 | web_search_keyless.reset_rung_health() |
| 1604 | report, _, _ = self._run_pipeline_reddit_with_searxng( |
| 1605 | cfg, sc_search=sc_search, html_fetch=lambda *a, **k: "", site_hits=[site_hit], |
| 1606 | searxng_get=self._searxng_refusal(403), full_report=True, |
| 1607 | ) |
| 1608 | outcome = report.source_status["reddit"] |
| 1609 | assert outcome.state == health.PARTIAL and outcome.items_returned >= 1 |
| 1610 | assert outcome.detail.endswith(f"; {self._NOTE}") and outcome.detail.count(self._NOTE) == 1 |
| 1611 | |
| 1612 | @staticmethod |
| 1613 | def _blocked_first_config_load(): |
| 1614 | """A config resolver whose first call blocks until released and whose later calls answer at once.""" |
| 1615 | started, release, calls = Event(), Event(), [] |
| 1616 | |
| 1617 | def resolve(): |
| 1618 | calls.append(1) |
| 1619 | if len(calls) == 1: |
| 1620 | started.set() |
| 1621 | assert release.wait(10) |
| 1622 | return "https://old.example" |
| 1623 | return "https://new.example" |
| 1624 | |
| 1625 | return resolve, started, release, calls |
| 1626 | |
| 1627 | def test_a_blocked_old_config_load_neither_stalls_nor_seeds_the_next_run(self): |
| 1628 | resolve, started, release, calls = self._blocked_first_config_load() |
| 1629 | with mock.patch.object(env, "resolve_searxng_url", side_effect=resolve), ThreadPoolExecutor(2) as pool: |
| 1630 | old = pool.submit(reddit_discover._standalone_searxng_url, reddit_discover._RUN_GENERATION) |
| 1631 | assert started.wait(5) |
| 1632 | try: |
| 1633 | reddit_discover.reset_run_state() |
| 1634 | new_generation = reddit_discover._RUN_GENERATION |
| 1635 | new = pool.submit(reddit_discover._standalone_searxng_url, new_generation) |
| 1636 | assert new.result(timeout=3) == "https://new.example" |
| 1637 | finally: |
| 1638 | release.set() |
| 1639 | # The old load finishes after the reset and must not seed the new run. |
| 1640 | assert old.result(timeout=5) is None |
| 1641 | assert reddit_discover._standalone_searxng_url(new_generation) == "https://new.example" |
| 1642 | assert len(calls) == 2 |
| 1643 | |
| 1644 | def test_two_callers_of_one_run_share_a_single_config_load(self): |
| 1645 | resolve, started, release, calls = self._blocked_first_config_load() |
| 1646 | with mock.patch.object(env, "resolve_searxng_url", side_effect=resolve), ThreadPoolExecutor(2) as pool: |
| 1647 | generation = reddit_discover._RUN_GENERATION |
| 1648 | first = pool.submit(reddit_discover._standalone_searxng_url, generation) |
| 1649 | assert started.wait(5) |
| 1650 | second = pool.submit(reddit_discover._standalone_searxng_url, generation) |
| 1651 | release.set() |
| 1652 | assert first.result(timeout=5) == second.result(timeout=5) == "https://old.example" |
| 1653 | assert len(calls) == 1 |
| 1654 | |
| 1655 | def test_contention_for_the_config_load_honors_the_callers_deadline(self): |
| 1656 | resolve, started, release, calls = self._blocked_first_config_load() |
| 1657 | with mock.patch.object(env, "resolve_searxng_url", side_effect=resolve), ThreadPoolExecutor(1) as pool: |
| 1658 | generation = reddit_discover._RUN_GENERATION |
| 1659 | first = pool.submit(reddit_discover._standalone_searxng_url, generation) |
| 1660 | assert started.wait(5) |
| 1661 | began = time.monotonic() |
| 1662 | try: |
| 1663 | waiting = reddit_discover._standalone_searxng_url(generation, deadline=began + 0.3) |
| 1664 | waited = time.monotonic() - began |
| 1665 | finally: |
| 1666 | release.set() |
| 1667 | assert first.result(timeout=5) == "https://old.example" |
| 1668 | # Out of time, the caller gets "unavailable" without caching anything as a miss. |
| 1669 | assert waiting is None and waited < 2.0 |
| 1670 | # The load that was in progress still completes for the run, and nobody loaded twice. |
| 1671 | assert reddit_discover._standalone_searxng_url(generation) == "https://old.example" |
| 1672 | assert len(calls) == 1 |
| 1673 | |
| 1674 | def test_a_query_stays_retryable_when_its_config_load_wait_runs_out(self): |
| 1675 | resolve, started, release, calls = self._blocked_first_config_load() |
| 1676 | searched = [] |
| 1677 | |
| 1678 | def search(query, date_range, config, count=5, **kwargs): |
| 1679 | searched.append(dict(config)) |
| 1680 | return [], {} |
| 1681 | |
| 1682 | with mock.patch.object(env, "resolve_searxng_url", side_effect=resolve), ThreadPoolExecutor(2) as pool: |
| 1683 | generation = reddit_discover._RUN_GENERATION |
| 1684 | first = pool.submit(reddit_discover._standalone_searxng_url, generation) |
| 1685 | assert started.wait(5) |
| 1686 | ask = pool.submit( |
| 1687 | reddit_discover._ask, generation, "topic", "site:reddit.com topic", search, |
| 1688 | ("2026-05-01", "2026-05-31"), None, None, time.monotonic() + 0.3, |
| 1689 | ) |
| 1690 | try: |
| 1691 | items, artifact, timed_out = ask.result(timeout=3) |
| 1692 | finally: |
| 1693 | release.set() |
| 1694 | first.result(timeout=5) |
| 1695 | # It searched without the fallback and left the slot retryable, as for any unavailable config. |
| 1696 | assert searched == [{}] and items == [] |
| 1697 | assert reddit_discover._ASKED["topic"]["site:reddit.com topic"] is None |
| 1698 | |
| 1699 | def _cutoff_then_paid_backfill(self, captured, *, items=False, refuse_searxng=False, full_report=False): |
| 1700 | """A real free cutoff followed by a paid backfill that ends incomplete with the given captured failures.""" |
| 1701 | clock = [100.0] |
| 1702 | note = "paid backfill stopped at its deadline before completing" |
| 1703 | thread = "https://www.reddit.com/r/LocalLLaMA/comments/paid123/" |
| 1704 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", "_research_deadline": 170.0, |
| 1705 | "LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 1706 | |
| 1707 | def html(*args, **kwargs): |
| 1708 | if not refuse_searxng: |
| 1709 | clock[0] = 128.0 # Past the discovery cutoff (127), before the lane end (135). |
| 1710 | return "" |
| 1711 | |
| 1712 | def sc_search(*args, **kwargs): |
| 1713 | for failure in captured: |
| 1714 | http._record_failure(failure) |
| 1715 | return {"items": [_hit(thread)] if items else [], "incomplete": True, "incomplete_note": note} |
| 1716 | |
| 1717 | def run_inline(_wait_until, _stage, _default, call, /, *args, **kwargs): |
| 1718 | return call(*args, **kwargs) |
| 1719 | |
| 1720 | from lib import reddit_keyless |
| 1721 | |
| 1722 | # With a refusal wanted, SearXNG is asked first and its refusal is what moves the clock past the cutoff. |
| 1723 | searxng_get = ( |
| 1724 | self._searxng_refusal(403, after=lambda: clock.__setitem__(0, 128.0)) if refuse_searxng else None |
| 1725 | ) |
| 1726 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), \ |
| 1727 | mock.patch.object(reddit_keyless, "_within", side_effect=run_inline): |
| 1728 | result = self._run_pipeline_reddit_with_searxng( |
| 1729 | cfg, sc_search=sc_search, html_fetch=html, searxng_get=searxng_get, full_report=full_report, |
| 1730 | ) |
| 1731 | return result, note, thread |
| 1732 | |
| 1733 | @pytest.mark.parametrize("captured_kind", ["deadline", "transport-timeout"]) |
| 1734 | def test_a_same_class_timeout_keeps_the_paid_backfills_specific_note(self, captured_kind): |
| 1735 | failure = ( |
| 1736 | http.DeadlineExceeded() if captured_kind == "deadline" |
| 1737 | else http.HTTPError("request timed out", outcome_state=health.TIMEOUT) |
| 1738 | ) |
| 1739 | (items, artifact, _), note, _ = self._cutoff_then_paid_backfill([failure]) |
| 1740 | |
| 1741 | assert not items |
| 1742 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 1743 | assert artifact["_source_outcome"]["detail"] == note |
| 1744 | |
| 1745 | def test_a_distinct_captured_failure_still_takes_priority_over_the_paid_note(self): |
| 1746 | (items, artifact, _), note, _ = self._cutoff_then_paid_backfill( |
| 1747 | [http.HTTPError("HTTP 429: paid backfill throttled", 429)], |
| 1748 | ) |
| 1749 | |
| 1750 | assert not items |
| 1751 | assert artifact["_source_outcome"]["state"] == health.RATE_LIMITED |
| 1752 | assert artifact["_source_outcome"]["detail"].startswith("HTTP 429") |
| 1753 | assert note not in str(artifact) |
| 1754 | |
| 1755 | def test_one_distinct_failure_among_timeouts_still_takes_priority(self): |
| 1756 | (items, artifact, _), note, _ = self._cutoff_then_paid_backfill( |
| 1757 | [http.DeadlineExceeded(), http.HTTPError("HTTP 429: paid backfill throttled", 429)], |
| 1758 | ) |
| 1759 | |
| 1760 | assert artifact["_source_outcome"]["state"] == health.RATE_LIMITED |
| 1761 | assert note not in str(artifact) |
| 1762 | |
| 1763 | def test_without_a_captured_failure_the_paid_note_is_reported_as_before(self): |
| 1764 | (items, artifact, _), note, _ = self._cutoff_then_paid_backfill([]) |
| 1765 | |
| 1766 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 1767 | assert artifact["_source_outcome"]["detail"] == note |
| 1768 | |
| 1769 | def test_a_genuine_paid_partial_result_is_served_and_not_reported_as_a_timeout(self): |
| 1770 | (items, artifact, _), note, thread = self._cutoff_then_paid_backfill( |
| 1771 | [http.DeadlineExceeded()], items=True, |
| 1772 | ) |
| 1773 | |
| 1774 | assert [i["url"] for i in items] == [thread] |
| 1775 | assert "_source_outcome" not in artifact |
| 1776 | |
| 1777 | def test_the_final_report_shows_the_paid_note_once_beside_a_searxng_note(self): |
| 1778 | (report, _, _), note, _ = self._cutoff_then_paid_backfill( |
| 1779 | [http.DeadlineExceeded()], refuse_searxng=True, full_report=True, |
| 1780 | ) |
| 1781 | |
| 1782 | outcome = report.source_status["reddit"] |
| 1783 | assert outcome.state == health.TIMEOUT |
| 1784 | assert outcome.detail == f"{note}; {self._NOTE}" |
| 1785 | assert outcome.detail.count(note) == 1 and outcome.detail.count(self._NOTE) == 1 |
| 1786 | assert report.errors_by_source["reddit"] == note |
| 1787 | |
| 1788 | def test_public_first_failure_without_a_paid_key_carries_the_observed_notes(self): |
| 1789 | from lib import pipeline, reddit_keyless |
| 1790 | |
| 1791 | def public_lane_that_breaks(*args, **kwargs): |
| 1792 | reddit_keyless._note(self._NOTE) |
| 1793 | raise RuntimeError("the public lane broke") |
| 1794 | |
| 1795 | with mock.patch.object(pipeline.reddit_public, "search_reddit_public", side_effect=public_lane_that_breaks): |
| 1796 | with pytest.raises(pipeline.SourceRunError) as raised: |
| 1797 | self._run_pipeline_reddit_with_searxng({"LAST30DAYS_SEARXNG_URL": "https://searx.example"}) |
| 1798 | |
| 1799 | assert raised.value.lane_notes == (self._NOTE,) |
| 1800 | assert "the public lane broke" in str(raised.value) |
| 1801 | |
| 1802 | def test_report_keeps_the_notes_of_a_stream_that_failed_by_exception(self): |
| 1803 | from lib import pipeline |
| 1804 | |
| 1805 | reason = "Reddit primary and fallback produced no results after failure: HTTP 429: paid primary throttled" |
| 1806 | |
| 1807 | def stream(*args, **kwargs): |
| 1808 | raise pipeline.SourceRunError(reason, health.RATE_LIMITED, lane_notes=[self._NOTE]) |
| 1809 | |
| 1810 | with mock.patch.object(pipeline, "_retrieve_stream_impl", side_effect=stream): |
| 1811 | report, _, _ = self._run_pipeline_reddit_with_searxng( |
| 1812 | {"LAST30DAYS_SEARXNG_URL": "https://searx.example"}, full_report=True, |
| 1813 | ) |
| 1814 | |
| 1815 | outcome = report.source_status["reddit"] |
| 1816 | assert outcome.state == health.RATE_LIMITED |
| 1817 | assert outcome.detail == f"{reason}; {self._NOTE}" |
| 1818 | assert report.errors_by_source["reddit"] == reason |
| 1819 | |
| 1820 | def test_report_keeps_the_notes_of_a_thin_results_retry_that_failed_by_exception(self): |
| 1821 | from lib import pipeline |
| 1822 | |
| 1823 | def stream(*args, **kwargs): |
| 1824 | if kwargs["subquery"].label == "retry": |
| 1825 | raise pipeline.SourceRunError("retry broke", health.TIMEOUT, lane_notes=[self._NOTE]) |
| 1826 | return [], {} |
| 1827 | |
| 1828 | with mock.patch.object(pipeline, "_retrieve_stream_impl", side_effect=stream): |
| 1829 | report, _, _ = self._run_pipeline_reddit_with_searxng( |
| 1830 | {"LAST30DAYS_SEARXNG_URL": "https://searx.example"}, full_report=True, report_depth="default", |
| 1831 | ) |
| 1832 | |
| 1833 | outcome = report.source_status["reddit"] |
| 1834 | assert outcome.state == health.TIMEOUT |
| 1835 | assert outcome.detail == f"Simplified-query retry failed: retry broke; {self._NOTE}" |
| 1836 | |
| 1837 | def test_exception_notes_are_recorded_for_reddit_only_and_only_from_the_vocabulary(self): |
| 1838 | from lib import pipeline, schema |
| 1839 | |
| 1840 | note = "SearXNG fallback refused (403)" |
| 1841 | error = pipeline.SourceRunError("boom", health.TIMEOUT, lane_notes=[note, note, "https://searx.example", "x"]) |
| 1842 | assert error.lane_notes == (note, "https://searx.example", "x") |
| 1843 | |
| 1844 | reddit = schema.RetrievalBundle() |
| 1845 | pipeline._record_reddit_exception_notes(reddit, "reddit", error) |
| 1846 | assert reddit.detail_by_source == {"reddit": note} |
| 1847 | |
| 1848 | other = schema.RetrievalBundle() |
| 1849 | pipeline._record_reddit_exception_notes(other, "polymarket", error) |
| 1850 | assert other.detail_by_source == {} |
| 1851 | |
| 1852 | plain = schema.RetrievalBundle() |
| 1853 | pipeline._record_reddit_exception_notes(plain, "reddit", RuntimeError("no notes here")) |
| 1854 | pipeline._record_reddit_exception_notes(plain, "reddit", pipeline.SourceRunError("quiet")) |
| 1855 | assert plain.detail_by_source == {} and pipeline.SourceRunError("quiet").lane_notes == () |
| 1856 | |
| 1857 | def test_attach_step_edge_cases(self): |
| 1858 | from lib import pipeline, schema |
| 1859 | |
| 1860 | note = "SearXNG fallback refused (403)" |
| 1861 | |
| 1862 | def status(state, detail): |
| 1863 | return {"reddit": schema.SourceOutcome(source="reddit", state=state, detail=detail)} |
| 1864 | |
| 1865 | def bundle(detail): |
| 1866 | held = schema.RetrievalBundle() |
| 1867 | held.detail_by_source["reddit"] = detail |
| 1868 | held.errors_by_source["reddit"] = "the reason" |
| 1869 | return held |
| 1870 | |
| 1871 | # A failure gets the note after its own reason, once, and keeps its state. |
| 1872 | failed = status(health.TIMEOUT, "the reason") |
| 1873 | pipeline._attach_reddit_lane_notes(bundle(f"search served 1; {note}; {note}"), failed) |
| 1874 | assert failed["reddit"].detail == f"the reason; {note}" |
| 1875 | assert failed["reddit"].state == health.TIMEOUT |
| 1876 | |
| 1877 | # A note the detail already holds is not repeated. |
| 1878 | held = status(health.TIMEOUT, f"the reason; {note}") |
| 1879 | pipeline._attach_reddit_lane_notes(bundle(note), held) |
| 1880 | assert held["reddit"].detail == f"the reason; {note}" |
| 1881 | |
| 1882 | # Only the bounded SearXNG vocabulary is ever shown. Other lane text and unknown text are not. |
| 1883 | other = status(health.TIMEOUT, "the reason") |
| 1884 | pipeline._attach_reddit_lane_notes( |
| 1885 | bundle("search served 1; SearXNG fallback refused (HTTP 403); https://searx.example"), other, |
| 1886 | ) |
| 1887 | assert other["reddit"].detail == "the reason" |
| 1888 | |
| 1889 | # Delivered, empty, missing and detail-less outcomes are left alone. |
| 1890 | for state in (health.OK, schema.NO_RESULTS): |
| 1891 | untouched = status(state, "search served 1") |
| 1892 | pipeline._attach_reddit_lane_notes(bundle(note), untouched) |
| 1893 | assert untouched["reddit"].detail == "search served 1" |
| 1894 | pipeline._attach_reddit_lane_notes(bundle(note), {}) |
| 1895 | nodetail = status(health.TIMEOUT, None) |
| 1896 | pipeline._attach_reddit_lane_notes(bundle(note), nodetail) |
| 1897 | assert nodetail["reddit"].detail is None |
| 1898 | |
| 1899 | # The typed error text is never changed. |
| 1900 | held_bundle = bundle(note) |
| 1901 | pipeline._attach_reddit_lane_notes(held_bundle, status(health.TIMEOUT, "the reason")) |
| 1902 | assert held_bundle.errors_by_source["reddit"] == "the reason" |
| 1903 | |
| 1904 | @pytest.mark.parametrize("source", ["reddit", "hackernews"]) |
| 1905 | def test_the_stream_wrapper_leaves_every_typed_outcome_untouched(self, source): |
| 1906 | from lib import pipeline |
| 1907 | |
| 1908 | artifact = { |
| 1909 | "_source_outcome": {"state": health.ERROR, "detail": "boom", "attempted": True}, |
| 1910 | "_source_outcome_detail": "a side note", |
| 1911 | } |
| 1912 | with mock.patch.object(pipeline, "_retrieve_stream_impl", return_value=([], dict(artifact))): |
| 1913 | _, result = pipeline._retrieve_stream(source=source, config={}) |
| 1914 | |
| 1915 | assert result["_source_outcome"] == artifact["_source_outcome"] |
| 1916 | assert result["_source_outcome_detail"] == "a side note" |
| 1917 | |
| 1918 | def test_report_without_any_note_stays_unchanged_across_two_streams(self): |
| 1919 | from lib import pipeline |
| 1920 | |
| 1921 | reason = "Reddit ran out of search time before it found threads" |
| 1922 | plain = {"_source_outcome": {"state": health.TIMEOUT, "detail": reason, "attempted": True}} |
| 1923 | with mock.patch.object(pipeline, "_retrieve_stream_impl", side_effect=lambda *a, **k: ([], dict(plain))): |
| 1924 | report, _, _ = self._run_pipeline_reddit_with_searxng( |
| 1925 | {"LAST30DAYS_SEARXNG_URL": "https://searx.example"}, full_report=True, labels=("one", "two"), |
| 1926 | report_depth="default", |
| 1927 | ) |
| 1928 | |
| 1929 | assert report.source_status["reddit"].detail == reason |
| 1930 | |
| 1931 | @pytest.mark.parametrize("detail", [ |
| 1932 | "Reddit ran out of search time before it found threads", |
| 1933 | "HTTP 429: paid primary throttled", |
| 1934 | "paid backfill stopped at its deadline before completing", |
| 1935 | "Reddit backup failed after 1 public items: HTTP 500; search blocked", |
| 1936 | "Reddit primary failed; public fallback returned 1 items: connection error", |
| 1937 | ]) |
| 1938 | @pytest.mark.parametrize("state", ["blocked", "throttled", "timeout", "error"]) |
| 1939 | def test_a_searxng_note_can_never_change_how_a_detail_is_classified(self, state, detail): |
| 1940 | from lib import reddit_keyless |
| 1941 | |
| 1942 | note = f"SearXNG fallback {reddit_keyless._SEARXNG_NOTES[state]}" |
| 1943 | |
| 1944 | assert http.classify_failure(message=f"{detail}; {note}") == http.classify_failure(message=detail) |
| 1945 | assert http.classify_failure(message=note) == health.ERROR |
| 1946 | |
| 1947 | @pytest.mark.parametrize("with_partial", [True, False], ids=["partial", "empty"]) |
| 1948 | def test_paid_backfill_exception_keeps_the_searxng_note(self, with_partial): |
| 1949 | site_hit = { |
| 1950 | "title": "IQ3 quantization discussion", |
| 1951 | "url": "https://www.reddit.com/r/LocalLLaMA/comments/site123/", |
| 1952 | "date": "2026-05-20", |
| 1953 | "engagement": {"score": 25, "num_comments": 3}, |
| 1954 | "relevance": 0.9, |
| 1955 | "metadata": {"post_id": "site123"}, |
| 1956 | } |
| 1957 | |
| 1958 | def failing_backfill(*args, **kwargs): |
| 1959 | raise RuntimeError("paid lookup broke") |
| 1960 | |
| 1961 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", "LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 1962 | items, artifact, _ = self._run_pipeline_reddit_with_searxng( |
| 1963 | cfg, sc_search=failing_backfill, html_fetch=lambda *a, **k: "", |
| 1964 | site_hits=[site_hit] if with_partial else [], searxng_get=self._searxng_refusal(403), |
| 1965 | ) |
| 1966 | |
| 1967 | if with_partial: |
| 1968 | # The retained partial, the chosen detail state and the paid failure all stay as they were. |
| 1969 | assert [i["metadata"]["post_id"] for i in items] == ["site123"] |
| 1970 | assert artifact["_source_outcome_detail_state"] == health.ERROR |
| 1971 | assert artifact["_source_outcome_detail"] == ( |
| 1972 | "search served 1; ScrapeCreators backfill failed after 1 free items: paid lookup broke; " |
| 1973 | "SearXNG fallback refused (403)" |
| 1974 | ) |
| 1975 | assert "ScrapeCreators backfill failed" in artifact["_source_outcome_detail"] |
| 1976 | assert "_source_outcome" not in artifact |
| 1977 | else: |
| 1978 | assert artifact["_source_outcome"]["detail"].startswith("Reddit backup failed after") |
| 1979 | assert "SearXNG fallback refused (403)" in artifact["_source_outcome_detail"] |
| 1980 | |
| 1981 | def test_paid_backfill_exception_without_a_searxng_failure_has_no_note(self): |
| 1982 | def failing_backfill(*args, **kwargs): |
| 1983 | raise RuntimeError("paid lookup broke") |
| 1984 | |
| 1985 | for cfg in ({"SCRAPECREATORS_API_KEY": "sc-dummy-key"}, |
| 1986 | {"SCRAPECREATORS_API_KEY": "sc-dummy-key", "LAST30DAYS_SEARXNG_URL": "https://searx.example"}): |
| 1987 | reddit_discover.reset_run_state() |
| 1988 | items, artifact, _ = self._run_pipeline_reddit_with_searxng( |
| 1989 | cfg, sc_search=failing_backfill, html_fetch=lambda *a, **k: "", |
| 1990 | searxng_get=lambda *a, **k: {"results": []}, |
| 1991 | ) |
| 1992 | assert "SearXNG" not in str(artifact) |
| 1993 | |
| 1994 | def test_cutoff_before_searxng_runs_fabricates_no_note(self): |
| 1995 | clock = [100.0] |
| 1996 | |
| 1997 | def html_past_cutoff(*args, **kwargs): |
| 1998 | clock[0] = 158.0 |
| 1999 | return "" |
| 2000 | |
| 2001 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example", "_research_deadline": 170.0} |
| 2002 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]): |
| 2003 | items, artifact, seen_urls = self._run_pipeline_reddit_with_searxng( |
| 2004 | cfg, html_fetch=html_past_cutoff, |
| 2005 | ) |
| 2006 | |
| 2007 | assert not items and seen_urls == [] |
| 2008 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 2009 | assert "SearXNG" not in str(artifact) |
| 2010 | |
| 2011 | def test_observed_searxng_failure_survives_a_later_clean_query(self): |
| 2012 | from lib import reddit_keyless |
| 2013 | |
| 2014 | outcomes = iter([http.HTTPError("HTTP 429: slow down", 429), {"results": []}]) |
| 2015 | |
| 2016 | def searxng_get(*args, **kwargs): |
| 2017 | outcome = next(outcomes) |
| 2018 | if isinstance(outcome, Exception): |
| 2019 | http._record_failure(outcome) |
| 2020 | raise outcome |
| 2021 | return outcome |
| 2022 | |
| 2023 | with mock.patch.object(web_search_keyless.http, "get_text", return_value=""), \ |
| 2024 | mock.patch.object(web_search_keyless.http, "get", side_effect=searxng_get) as sx, \ |
| 2025 | reddit_keyless.lane_paths(), reddit_keyless.lane_notes() as notes: |
| 2026 | reddit_keyless._web_floor( |
| 2027 | "IQ3 quantization", "quick", ["LocalLLaMA"], None, "2026-05-01", "2026-05-31", None, |
| 2028 | {"LAST30DAYS_SEARXNG_URL": "https://searx.example"}, |
| 2029 | ) |
| 2030 | |
| 2031 | assert sx.call_count == 2 |
| 2032 | assert notes == ["SearXNG fallback throttled (429)"] |
| 2033 | |
| 2034 | def test_searxng_failure_is_kept_apart_from_the_latest_rung_and_deduplicated(self): |
| 2035 | floor = reddit_discover.WebFloor() |
| 2036 | for state in ["blocked", "throttled", "blocked", "empty"]: |
| 2037 | floor.record_query("q", {"brave": "empty", "searxng": state}, [], searxng=state) |
| 2038 | |
| 2039 | # The rung map still holds the latest state. The failures are kept, in order, once each. |
| 2040 | assert floor.rungs == {"brave": "empty", "searxng": "empty"} |
| 2041 | assert floor.searxng_failures == ["blocked", "throttled"] |
| 2042 | assert floor.snapshot().searxng_failures == ["blocked", "throttled"] |
| 2043 | |
| 2044 | def test_only_known_failure_states_are_kept(self): |
| 2045 | floor = reddit_discover.WebFloor() |
| 2046 | for state in ["ok", "empty", "skipped", "https://searx.example/secret", None]: |
| 2047 | floor.record_query("q", {}, [], searxng=state) |
| 2048 | |
| 2049 | assert floor.searxng_failures == [] |
| 2050 | |
| 2051 | def test_searxng_clean_miss_adds_no_note(self): |
| 2052 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example"} |
| 2053 | items, artifact, _ = self._run_pipeline_reddit_with_searxng( |
| 2054 | cfg, html_fetch=lambda *args, **kwargs: "", searxng_get=lambda *a, **k: {"results": []}, |
| 2055 | ) |
| 2056 | |
| 2057 | assert not items and "SearXNG" not in artifact.get("_source_outcome_detail", "") |
| 2058 | |
| 2059 | @pytest.mark.parametrize("site", ["open", "read"]) |
| 2060 | def test_transient_config_read_error_is_retried_not_cached_as_missing(self, site, tmp_path, monkeypatch): |
| 2061 | import errno |
| 2062 | import os |
| 2063 | |
| 2064 | env.CONFIG_FILE.write_text("LAST30DAYS_SEARXNG_URL=https://global.example\n", encoding="utf-8") |
| 2065 | monkeypatch.chdir(tmp_path) |
| 2066 | monkeypatch.delenv("LAST30DAYS_SEARXNG_URL", raising=False) |
| 2067 | real_open, real_fdopen, tripped = os.open, os.fdopen, [] |
| 2068 | |
| 2069 | def flaky_open(path, *args, **kwargs): |
| 2070 | if site == "open" and not tripped and os.fspath(path) == os.fspath(env.CONFIG_FILE): |
| 2071 | tripped.append(1) |
| 2072 | raise PermissionError(errno.EACCES, "file is in use") |
| 2073 | return real_open(path, *args, **kwargs) |
| 2074 | |
| 2075 | def flaky_fdopen(fd, *args, **kwargs): |
| 2076 | if site == "read" and not tripped: |
| 2077 | tripped.append(1) |
| 2078 | raise OSError(errno.EIO, "input/output error") |
| 2079 | return real_fdopen(fd, *args, **kwargs) |
| 2080 | |
| 2081 | monkeypatch.setattr(os, "open", flaky_open) |
| 2082 | monkeypatch.setattr(os, "fdopen", flaky_fdopen) |
| 2083 | generation = reddit_discover._RUN_GENERATION |
| 2084 | |
| 2085 | assert reddit_discover._standalone_searxng_url(generation) is None |
| 2086 | assert reddit_discover._standalone_searxng_url(generation) == "https://global.example" |
| 2087 | assert tripped == [1] |
| 2088 | |
| 2089 | @pytest.mark.parametrize("how", ["absent", "unsafe"]) |
| 2090 | def test_absent_or_unsafe_config_file_stays_a_cached_miss(self, how, tmp_path, monkeypatch): |
| 2091 | import errno |
| 2092 | import os |
| 2093 | |
| 2094 | env.CONFIG_FILE.write_text("LAST30DAYS_SEARXNG_URL=https://global.example\n", encoding="utf-8") |
| 2095 | monkeypatch.chdir(tmp_path) |
| 2096 | monkeypatch.delenv("LAST30DAYS_SEARXNG_URL", raising=False) |
| 2097 | real_open, opens = os.open, [] |
| 2098 | |
| 2099 | def refuse_open(path, *args, **kwargs): |
| 2100 | if os.fspath(path) == os.fspath(env.CONFIG_FILE): |
| 2101 | opens.append(1) |
| 2102 | raise OSError(errno.ELOOP, "symlink refused") if how == "unsafe" else FileNotFoundError(path) |
| 2103 | return real_open(path, *args, **kwargs) |
| 2104 | |
| 2105 | monkeypatch.setattr(os, "open", refuse_open) |
| 2106 | generation = reddit_discover._RUN_GENERATION |
| 2107 | |
| 2108 | assert reddit_discover._standalone_searxng_url(generation) == "" |
| 2109 | assert reddit_discover._standalone_searxng_url(generation) == "" |
| 2110 | assert opens == [1] |
| 2111 | |
| 2112 | def test_sc_first_public_fallback_gets_a_proportionate_margin_at_handoff(self): |
| 2113 | from lib import reddit_keyless |
| 2114 | |
| 2115 | clock = [100.0] |
| 2116 | lanes = [] |
| 2117 | site_hit = { |
| 2118 | "title": "IQ3 quantization discussion", |
| 2119 | "url": "https://www.reddit.com/r/LocalLLaMA/comments/site123/", |
| 2120 | "date": "2026-05-20", |
| 2121 | "engagement": {"score": 25, "num_comments": 3}, |
| 2122 | "relevance": 0.9, |
| 2123 | "metadata": {"post_id": "site123"}, |
| 2124 | } |
| 2125 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 2126 | "_research_deadline": 200.0} |
| 2127 | real_lane = reddit_keyless.lane_deadline |
| 2128 | |
| 2129 | def record_lane(deadline): |
| 2130 | lanes.append(deadline) |
| 2131 | return real_lane(deadline) |
| 2132 | |
| 2133 | def sc_search(*args, **kwargs): |
| 2134 | clock[0] = 185.0 # The paid primary came back empty with 15s left. |
| 2135 | return {} |
| 2136 | |
| 2137 | def run_inline(_wait_until, _stage, _default, call, /, *args, **kwargs): |
| 2138 | return call(*args, **kwargs) |
| 2139 | |
| 2140 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), \ |
| 2141 | mock.patch.object(reddit_keyless, "_within", side_effect=run_inline), \ |
| 2142 | mock.patch.object(reddit_keyless, "lane_deadline", side_effect=record_lane): |
| 2143 | items, artifact, _ = self._run_pipeline_reddit_with_searxng( |
| 2144 | cfg, sc_search=sc_search, html_fetch=lambda *a, **k: "", site_hits=[site_hit], |
| 2145 | ) |
| 2146 | |
| 2147 | # With 15s left the margin is min(20, 15 * 0.15) = 2.25s, so the fallback ends at 197.75 and never past 200. |
| 2148 | assert lanes == [pytest.approx(197.75)] |
| 2149 | assert [i["metadata"]["post_id"] for i in items] == ["site123"] |
| 2150 | |
| 2151 | def test_sc_first_public_fallback_gets_no_extra_allowance_when_time_is_spent(self): |
| 2152 | from lib import reddit_keyless |
| 2153 | |
| 2154 | clock = [100.0] |
| 2155 | lanes = [] |
| 2156 | cfg = {"SCRAPECREATORS_API_KEY": "sc-dummy-key", env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 2157 | "_research_deadline": 200.0} |
| 2158 | real_lane = reddit_keyless.lane_deadline |
| 2159 | |
| 2160 | def record_lane(deadline): |
| 2161 | lanes.append(deadline) |
| 2162 | return real_lane(deadline) |
| 2163 | |
| 2164 | def sc_search(*args, **kwargs): |
| 2165 | clock[0] = 201.0 # Already past the run deadline when the primary returns. |
| 2166 | return {} |
| 2167 | |
| 2168 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), \ |
| 2169 | mock.patch.object(reddit_keyless, "lane_deadline", side_effect=record_lane): |
| 2170 | items, artifact, _ = self._run_pipeline_reddit_with_searxng( |
| 2171 | cfg, sc_search=sc_search, html_fetch=lambda *a, **k: "", |
| 2172 | ) |
| 2173 | |
| 2174 | assert lanes == [200.0] and not items |
| 2175 | |
| 2176 | @pytest.mark.parametrize("sc_primary", [False, True], ids=["public-primary", "sc-primary"]) |
| 2177 | def test_pipeline_keeps_site_hit_without_late_searxng_on_either_primary_path(self, sc_primary): |
| 2178 | from lib import reddit_keyless |
| 2179 | |
| 2180 | clock = [100.0] |
| 2181 | html_urls = [] |
| 2182 | |
| 2183 | def html_fetch(url, *args, **kwargs): |
| 2184 | html_urls.append(url) |
| 2185 | # Too little time for a new lane stage, but the site hit is ready. |
| 2186 | clock[0] = 179.0 |
| 2187 | return None |
| 2188 | |
| 2189 | def run_inline(_wait_until, _stage, _default, call, /, *args, **kwargs): |
| 2190 | # Only replace the executor wait so the mocked clock cannot race it. |
| 2191 | return call(*args, **kwargs) |
| 2192 | |
| 2193 | cfg = {"LAST30DAYS_SEARXNG_URL": "https://searx.example", "_research_deadline": 200.0} |
| 2194 | if sc_primary: |
| 2195 | cfg.update({"SCRAPECREATORS_API_KEY": "sc-dummy-key", |
| 2196 | env.REDDIT_BACKEND_PIN_VAR: "scrapecreators"}) |
| 2197 | site_hit = { |
| 2198 | "title": "IQ3 quantization discussion", |
| 2199 | "url": "https://www.reddit.com/r/LocalLLaMA/comments/site123/", |
| 2200 | "date": "2026-05-20", |
| 2201 | "engagement": {"score": 25, "num_comments": 3}, |
| 2202 | "relevance": 0.9, |
| 2203 | "metadata": {"post_id": "site123"}, |
| 2204 | } |
| 2205 | with mock.patch("time.monotonic", side_effect=lambda: clock[0]), \ |
| 2206 | mock.patch.object(reddit_keyless, "_within", side_effect=run_inline): |
| 2207 | items, artifact, seen_urls = self._run_pipeline_reddit_with_searxng( |
| 2208 | cfg, sc_search=(lambda *a, **kw: {}) if sc_primary else None, |
| 2209 | html_fetch=html_fetch, site_hits=[site_hit], |
| 2210 | ) |
| 2211 | |
| 2212 | assert seen_urls == [] |
| 2213 | assert len(html_urls) == 1 and "search.brave.com" in html_urls[0] |
| 2214 | assert [i["metadata"]["post_id"] for i in items] == ["site123"] |
| 2215 | assert "_source_outcome" not in artifact |
| 2216 | |
| 2217 | def test_blocked_searxng_url_is_rejected_by_downstream_guard_without_get(self): |
| 2218 | cfg = {"LAST30DAYS_SEARXNG_URL": "http://169.254.169.254"} |
| 2219 | with mock.patch.object(web_search_keyless.http, "get_text", side_effect=self._throttled_html), \ |
| 2220 | mock.patch.object(web_search_keyless.http, "get") as sx_get: |
| 2221 | floor = reddit_discover.web_refs("IQ3 quantization", config=cfg) |
| 2222 | |
| 2223 | sx_get.assert_not_called() |
| 2224 | assert floor.refs == [] |
| 2225 |