| 1 | """Regression tests for PR 20: Reddit URL safety, health locking & session concurrency. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-124: Outbound URL validation and encoding in reddit_shreddit, |
| 5 | reddit_listing, reddit_arctic, reddit_public, and reddit_refs. |
| 6 | - HIGH-128: Per-thread parse exception isolation, mid-hydration consecutive-403 |
| 7 | session expiry, and single-ref 403 handling in reddit_session.hydrator. |
| 8 | - HIGH-129: Single-flight in-flight deduplication in reddit_session.discover |
| 9 | and Session.fetch with deadline/cancellation handling and named-subreddit |
| 10 | privacy isolation. |
| 11 | - HIGH-130: Owner-only (0o600) atomic writes, symlink refusal, temp cleanup, |
| 12 | and cross-process file locking in reddit_health. |
| 13 | - HIGH-131: Monotonic same-run health transitions so stale in-flight OK cannot |
| 14 | clobber a persisted BLOCKED cooldown on disk. |
| 15 | - HIGH-133: Strict host, scheme, port, userinfo, and thread-path validation in |
| 16 | reddit_enrich.extract_reddit_path. |
| 17 | """ |
| 18 | |
| 19 | from __future__ import annotations |
| 20 | |
| 21 | import concurrent.futures |
| 22 | import json |
| 23 | import os |
| 24 | import stat |
| 25 | import subprocess |
| 26 | import sys |
| 27 | import threading |
| 28 | import time |
| 29 | import types |
| 30 | from pathlib import Path |
| 31 | from unittest import mock |
| 32 | from urllib.parse import parse_qs, urlsplit |
| 33 | |
| 34 | import pytest |
| 35 | |
| 36 | from lib import ( |
| 37 | env, |
| 38 | http, |
| 39 | reddit_arctic, |
| 40 | reddit_enrich, |
| 41 | reddit_health, |
| 42 | reddit_hydrate, |
| 43 | reddit_listing, |
| 44 | reddit_public, |
| 45 | reddit_refs, |
| 46 | reddit_session, |
| 47 | reddit_shreddit, |
| 48 | ) |
| 49 | from lib.reddit_refs import canonical_thread |
| 50 | |
| 51 | FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" |
| 52 | SCRIPTS_DIR = Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts" |
| 53 | DUMMY_COOKIE = "dummy-pr20-session-cookie-0123456789" |
| 54 | TOPIC = "Ghostty terminal" |
| 55 | FROM, TO = "2026-10-16", "2026-11-15" |
| 56 | IN_WINDOW_UTC = 1794355200 # 2026-11-11T00:00:00Z |
| 57 | |
| 58 | POSTS_HTML = (FIXTURES / "reddit_session_posts.html").read_text(encoding="utf-8") |
| 59 | COMMENTS_HTML = (FIXTURES / "reddit_session_comments.html").read_text(encoding="utf-8") |
| 60 | COMMUNITIES_HTML = (FIXTURES / "reddit_session_communities.html").read_text(encoding="utf-8") |
| 61 | NO_COMMENTS_HTML = (FIXTURES / "reddit_session_comments_no_results.html").read_text(encoding="utf-8") |
| 62 | BLOCKED_HTML = (FIXTURES / "reddit_session_blocked_403.html").read_text(encoding="utf-8") |
| 63 | THREAD_DATA = json.loads((FIXTURES / "reddit_session_thread.json").read_text(encoding="utf-8")) |
| 64 | |
| 65 | |
| 66 | def _thread_json(post_id: str, **fields) -> str: |
| 67 | data = json.loads(json.dumps(THREAD_DATA)) |
| 68 | post = data[0]["data"]["children"][0]["data"] |
| 69 | sub = fields.get("subreddit", post["subreddit"]) |
| 70 | post.update({ |
| 71 | "id": post_id, |
| 72 | "created_utc": IN_WINDOW_UTC, |
| 73 | "permalink": f"/r/{sub}/comments/{post_id}/t/", |
| 74 | }) |
| 75 | post.update(fields) |
| 76 | return json.dumps(data) |
| 77 | |
| 78 | |
| 79 | def _ref(post_id: str, sub: str = "Ghostty", provenance: str = "session"): |
| 80 | ref = canonical_thread(f"https://www.reddit.com/r/{sub}/comments/{post_id}/") |
| 81 | ref.provenance.add(provenance) |
| 82 | ref.title = "Ghostty terminal thread" |
| 83 | ref.date = "2026-11-11" |
| 84 | return ref |
| 85 | |
| 86 | |
| 87 | def _archive_post(post_id: str, sub: str = "Ghostty", title: str = "Ghostty terminal thread"): |
| 88 | return reddit_arctic._normalize_listing_row({ |
| 89 | "id": post_id, |
| 90 | "title": title, |
| 91 | "score": 120, |
| 92 | "num_comments": 15, |
| 93 | "subreddit": sub, |
| 94 | "created_utc": IN_WINDOW_UTC, |
| 95 | "permalink": f"/r/{sub}/comments/{post_id}/t/", |
| 96 | "author": "public_user", |
| 97 | }) |
| 98 | |
| 99 | |
| 100 | def _session(**kwargs) -> reddit_session.Session: |
| 101 | return reddit_session.Session(DUMMY_COOKIE, browser="chrome", **kwargs) |
| 102 | |
| 103 | |
| 104 | # --------------------------------------------------------------------------- |
| 105 | # HIGH-124: URL validation & encoding across Reddit modules |
| 106 | # --------------------------------------------------------------------------- |
| 107 | |
| 108 | |
| 109 | class TestHigh124ShredditUrlSafety: |
| 110 | @pytest.mark.parametrize("bad_url", [ |
| 111 | "", |
| 112 | None, |
| 113 | 123, |
| 114 | "1taeiw0", |
| 115 | "https://evil.com/r/Rakuten/comments/1taeiw0/title/", |
| 116 | "https://evil-reddit.com/r/Rakuten/comments/1taeiw0/title/", |
| 117 | "https://reddit.com.attacker.com/r/Rakuten/comments/1taeiw0/title/", |
| 118 | "https://user:pass@www.reddit.com/r/Rakuten/comments/1taeiw0/title/", |
| 119 | "https://www.reddit.com:8443/r/Rakuten/comments/1taeiw0/title/", |
| 120 | "javascript://www.reddit.com/r/Rakuten/comments/1taeiw0/title/", |
| 121 | "https://www.reddit.com/r/../comments/1taeiw0/title/", |
| 122 | "https://www.reddit.com/r/foo%2Fbar/comments/1taeiw0/title/", |
| 123 | "https://www.reddit.com/r/a/comments/1taeiw0/title/", |
| 124 | "https://www.reddit.com/r/Rakuten/comments/1taeiw0/../../admin", |
| 125 | "https://[::1/r/Rakuten/comments/1taeiw0/title/", |
| 126 | ]) |
| 127 | def test_extract_post_ref_rejects_malicious_or_non_reddit_urls(self, bad_url): |
| 128 | assert reddit_shreddit.extract_post_ref(bad_url) is None |
| 129 | |
| 130 | @pytest.mark.parametrize("url", [ |
| 131 | "https://www.reddit.com/comments/1taeiw0/", |
| 132 | "https://old.reddit.com/comments/1taeiw0/post_slug/", |
| 133 | "https://redd.it/1taeiw0", |
| 134 | ]) |
| 135 | def test_subredditless_canonical_url_falls_back_to_arctic(self, url): |
| 136 | assert reddit_shreddit.extract_post_ref(url) == ("", "1taeiw0") |
| 137 | arctic_comment = { |
| 138 | "score": 55, |
| 139 | "date": "2026-11-11", |
| 140 | "author": "alice", |
| 141 | "body": "Helpful archive comment on subredditless thread.", |
| 142 | "excerpt": "Helpful archive comment on subredditless thread.", |
| 143 | "permalink": "/r/Rakuten/comments/1taeiw0/x/c1/", |
| 144 | "url": "https://reddit.com/r/Rakuten/comments/1taeiw0/x/c1/", |
| 145 | "depth": 0, |
| 146 | } |
| 147 | future_deadline = time.monotonic() + 999.0 |
| 148 | with mock.patch.object(reddit_shreddit.http, "reddit_keyless_get_text") as get_text, \ |
| 149 | mock.patch.object( |
| 150 | reddit_shreddit.reddit_arctic, "fetch_post_comments", return_value=[arctic_comment], |
| 151 | ) as arctic: |
| 152 | out = reddit_shreddit.fetch_comments(url, deadline=future_deadline) |
| 153 | get_text.assert_not_called() |
| 154 | arctic.assert_called_once_with( |
| 155 | "1taeiw0", |
| 156 | limit=reddit_shreddit.MAX_COMMENTS, |
| 157 | skip_author=reddit_shreddit._is_bot_author, |
| 158 | deadline=future_deadline, |
| 159 | ) |
| 160 | assert len(out["top_comments"]) == 1 |
| 161 | assert out["top_comments"][0]["score"] == 55 |
| 162 | |
| 163 | @pytest.mark.parametrize(("sub", "pid"), [ |
| 164 | ("", "1taeiw0"), |
| 165 | ("../admin", "1taeiw0"), |
| 166 | ("sub?x=1", "1taeiw0"), |
| 167 | ("sub#frag", "1taeiw0"), |
| 168 | ("a", "1taeiw0"), |
| 169 | ("Rakuten", ""), |
| 170 | ("Rakuten", "../evil"), |
| 171 | ("Rakuten", "1taeiw0?x=1"), |
| 172 | ]) |
| 173 | def test_svc_url_rejects_invalid_subreddit_or_post_id(self, sub, pid): |
| 174 | with pytest.raises(ValueError): |
| 175 | reddit_shreddit._svc_url(sub, pid) |
| 176 | |
| 177 | def test_svc_url_normalizes_r_prefix_and_encodes(self): |
| 178 | assert reddit_shreddit._svc_url("/R/Rakuten/", "t3_1TAEIW0") == ( |
| 179 | "https://www.reddit.com/svc/shreddit/comments/r/Rakuten/t3_1taeiw0?sort=top" |
| 180 | ) |
| 181 | |
| 182 | |
| 183 | class TestHigh124ListingUrlSafety: |
| 184 | def test_listing_url_strips_case_insensitive_prefix_and_slashes(self): |
| 185 | u1 = reddit_listing._listing_url("/R/Technology/", "top", "week") |
| 186 | assert u1 == "https://www.reddit.com/svc/shreddit/community-more-posts/top/?name=Technology&t=week" |
| 187 | u2 = reddit_listing._listing_url("/r/ALL/", "hot") |
| 188 | assert u2 == "https://www.reddit.com/r/all/hot/" |
| 189 | |
| 190 | @pytest.mark.parametrize(("sub", "sort", "tf"), [ |
| 191 | ("", "top", "month"), |
| 192 | ("r/", "top", "month"), |
| 193 | (" ", "hot", "month"), |
| 194 | ("../admin", "top", "month"), |
| 195 | ("tech&evil=1", "top", "month"), |
| 196 | ("tech#frag", "hot", "month"), |
| 197 | ("technology", "../evil", "month"), |
| 198 | ("technology", "top", "month&evil=1"), |
| 199 | ]) |
| 200 | def test_listing_url_rejects_invalid_inputs(self, sub, sort, tf): |
| 201 | with pytest.raises(ValueError): |
| 202 | reddit_listing._listing_url(sub, sort, tf) |
| 203 | |
| 204 | def test_fetch_listings_skips_empty_and_invalid_subreddits(self): |
| 205 | with mock.patch.object(reddit_listing.http, "reddit_keyless_get_text_retry_429") as fetch: |
| 206 | assert reddit_listing.fetch_listings(["", "r/", "../evil", "a&b=c"]) == [] |
| 207 | fetch.assert_not_called() |
| 208 | |
| 209 | def test_fetch_discovery_listings_skips_invalid_subreddits(self): |
| 210 | with mock.patch.object(reddit_listing.http, "reddit_keyless_get_text_retry_429") as fetch, \ |
| 211 | mock.patch("lib.reddit_arctic.fetch_listings") as arctic: |
| 212 | result = reddit_listing.fetch_discovery_listings(["", "r/", "../evil"], query="test") |
| 213 | assert result == {"items": [], "errors": []} |
| 214 | fetch.assert_not_called() |
| 215 | arctic.assert_not_called() |
| 216 | |
| 217 | |
| 218 | class TestHigh124ArcticUrlSafety: |
| 219 | @pytest.fixture(autouse=True) |
| 220 | def _no_arctic_network(self): |
| 221 | # Override conftest's stub so these tests exercise real arctic functions. |
| 222 | reddit_arctic.reset_memo() |
| 223 | yield |
| 224 | reddit_arctic.reset_memo() |
| 225 | |
| 226 | def test_fetch_scores_filters_invalid_ids_and_urlencodes(self): |
| 227 | with mock.patch.object( |
| 228 | reddit_arctic.http, "get", |
| 229 | return_value={"data": [{"id": "abc123", "score": 10, "num_comments": 2}]}, |
| 230 | ) as g: |
| 231 | out = reddit_arctic.fetch_scores(["abc&limit=999", "../evil", "t3_abc123", ""]) |
| 232 | assert out == {"abc123": {"score": 10, "num_comments": 2}} |
| 233 | g.assert_called_once() |
| 234 | assert parse_qs(urlsplit(g.call_args[0][0]).query) == {"ids": ["abc123"]} |
| 235 | |
| 236 | def test_fetch_posts_by_ids_makes_no_call_for_invalid_ids(self): |
| 237 | with mock.patch.object(reddit_arctic.http, "get") as g: |
| 238 | out, state = reddit_arctic.fetch_posts_by_ids(["../etc", "bad&limit=1", "not_valid!"]) |
| 239 | assert out == {} and state == "ok" |
| 240 | g.assert_not_called() |
| 241 | |
| 242 | def test_fetch_listings_validates_subreddits_and_dates(self): |
| 243 | with mock.patch.object(reddit_arctic.http, "get", return_value={"data": []}) as g: |
| 244 | reddit_arctic.fetch_listings( |
| 245 | ["/R/Tea/", "all", "", "../evil", "tea&limit=999"], |
| 246 | from_date="2026-09-20&evil=1", |
| 247 | to_date="not-a-date#frag", |
| 248 | ) |
| 249 | assert g.call_count == 1 |
| 250 | query = parse_qs(urlsplit(g.call_args[0][0]).query) |
| 251 | assert query == {"subreddit": ["Tea"], "limit": ["25"], "sort": ["desc"]} |
| 252 | assert "evil" not in g.call_args[0][0] |
| 253 | assert "frag" not in g.call_args[0][0] |
| 254 | |
| 255 | @pytest.mark.parametrize("bad_id", ["", None, 123, "abc&limit=999", "../evil", "bad_id"]) |
| 256 | def test_comment_endpoints_reject_invalid_post_ids(self, bad_id): |
| 257 | with mock.patch.object(reddit_arctic.http, "get") as g: |
| 258 | assert reddit_arctic.fetch_comment_tree(bad_id) is None |
| 259 | assert reddit_arctic.fetch_post_comments(bad_id) == [] |
| 260 | g.assert_not_called() |
| 261 | |
| 262 | def test_comment_endpoints_accept_valid_post_id_and_urlencode(self): |
| 263 | with mock.patch.object(reddit_arctic.http, "get", return_value={"data": []}) as g: |
| 264 | assert reddit_arctic.fetch_comment_tree("T3_ABC123") == [] |
| 265 | assert reddit_arctic.fetch_post_comments("T3_ABC123") == [] |
| 266 | assert g.call_count == 2 |
| 267 | tree_q = parse_qs(urlsplit(g.call_args_list[0][0][0]).query) |
| 268 | post_q = parse_qs(urlsplit(g.call_args_list[1][0][0]).query) |
| 269 | assert tree_q == {"link_id": ["t3_abc123"], "limit": [str(reddit_arctic.MAX_COMMENT_ROWS)]} |
| 270 | assert post_q == {"link_id": ["t3_abc123"], "limit": [str(reddit_arctic.FALLBACK_COMMENT_ROWS)]} |
| 271 | |
| 272 | |
| 273 | class TestHigh124PublicSearchUrlSafety: |
| 274 | @pytest.mark.parametrize("bad_sub", [ |
| 275 | "../api/v1/me", |
| 276 | "sub?evil=1", |
| 277 | "sub#frag", |
| 278 | "sub%2Fadmin", |
| 279 | "r/", |
| 280 | " ", |
| 281 | "a", |
| 282 | ]) |
| 283 | def test_public_search_rejects_malicious_subreddit_without_request(self, bad_sub): |
| 284 | with mock.patch("lib.reddit_public.urllib.request.urlopen") as urlopen: |
| 285 | assert reddit_public.search("python", subreddit=bad_sub) == [] |
| 286 | urlopen.assert_not_called() |
| 287 | |
| 288 | def test_public_search_normalizes_uppercase_prefix_and_encodes_query(self): |
| 289 | resp = mock.MagicMock() |
| 290 | resp.read.return_value = b'{"data": {"children": []}}' |
| 291 | resp.headers = {"Content-Type": "application/json"} |
| 292 | resp.__enter__ = mock.MagicMock(return_value=resp) |
| 293 | resp.__exit__ = mock.MagicMock(return_value=False) |
| 294 | with mock.patch("lib.reddit_public.urllib.request.urlopen", return_value=resp) as urlopen: |
| 295 | reddit_public.search("a&b=c #test", subreddit="/R/ClaudeAI/") |
| 296 | req = urlopen.call_args[0][0] |
| 297 | parts = urlsplit(req.full_url) |
| 298 | assert parts.path == "/r/ClaudeAI/search.json" |
| 299 | assert parse_qs(parts.query)["q"] == ["a&b=c #test"] |
| 300 | assert parse_qs(parts.query)["restrict_sr"] == ["on"] |
| 301 | |
| 302 | |
| 303 | # --------------------------------------------------------------------------- |
| 304 | # HIGH-128: hydrator parse resilience & mid-hydration / single-ref expiry |
| 305 | # --------------------------------------------------------------------------- |
| 306 | |
| 307 | |
| 308 | class TestHigh128HydratorResilienceAndExpiry: |
| 309 | def test_malformed_thread_json_preserves_prior_privacy_drop_and_continues(self, monkeypatch): |
| 310 | priv_body = _thread_json("1priv01", subreddit="secretclub", subreddit_type="private") |
| 311 | malformed_body = _thread_json("1mal002", subreddit="Ghostty", subreddit_type="public") |
| 312 | good_body = _thread_json("1good03", subreddit="Ghostty", subreddit_type="public") |
| 313 | |
| 314 | def fake_get(url, _cookie, **_k): |
| 315 | if "1priv01.json" in url: |
| 316 | return 200, priv_body, False |
| 317 | if "1mal002.json" in url: |
| 318 | return 200, malformed_body, False |
| 319 | if "1good03.json" in url: |
| 320 | return 200, good_body, False |
| 321 | return 404, "", False |
| 322 | |
| 323 | real_parse = reddit_enrich.parse_thread_data |
| 324 | |
| 325 | def failing_parse(data): |
| 326 | if ( |
| 327 | isinstance(data, list) |
| 328 | and data |
| 329 | and data[0]["data"]["children"][0]["data"].get("id") == "1mal002" |
| 330 | ): |
| 331 | raise TypeError("simulated unexpected parser failure") |
| 332 | return real_parse(data) |
| 333 | |
| 334 | logs: list[str] = [] |
| 335 | monkeypatch.setattr(http, "reddit_session_get", fake_get) |
| 336 | monkeypatch.setattr(reddit_enrich, "parse_thread_data", failing_parse) |
| 337 | monkeypatch.setattr(reddit_session, "_log", logs.append) |
| 338 | # Even if Arctic Shift holds a copy of 1priv01, DROP must block resurrection. |
| 339 | monkeypatch.setattr( |
| 340 | reddit_arctic, |
| 341 | "fetch_posts_by_ids", |
| 342 | lambda ids, **_k: ( |
| 343 | {pid: _archive_post(pid) for pid in ids}, |
| 344 | "ok", |
| 345 | ), |
| 346 | ) |
| 347 | monkeypatch.setattr(reddit_arctic, "fetch_comment_tree", lambda *_a, **_k: None) |
| 348 | |
| 349 | refs = [ |
| 350 | _ref("1priv01", "secretclub", provenance="host"), |
| 351 | _ref("1mal002", "Ghostty", provenance="host"), |
| 352 | _ref("1good03", "Ghostty", provenance="host"), |
| 353 | ] |
| 354 | result = reddit_hydrate.hydrate( |
| 355 | refs, |
| 356 | topic=TOPIC, |
| 357 | from_date=FROM, |
| 358 | to_date=TO, |
| 359 | comments=False, |
| 360 | session_hydrator=reddit_session.hydrator(_session()), |
| 361 | now=1.9e9, |
| 362 | ) |
| 363 | ids = [item["metadata"]["post_id"] for item in result.items] |
| 364 | assert "1priv01" not in ids |
| 365 | assert "1good03" in ids |
| 366 | assert any("1mal002" in line and ("TypeError" in line or "AttributeError" in line) for line in logs) |
| 367 | |
| 368 | def test_null_comment_score_typeerror_does_not_discard_prior_drop(self, monkeypatch): |
| 369 | priv_body = _thread_json("1priv09", subreddit="secretclub", subreddit_type="private") |
| 370 | null_score_body = json.dumps([ |
| 371 | {"data": {"children": [{"data": { |
| 372 | "id": "1null10", "subreddit": "Ghostty", "subreddit_type": "public", |
| 373 | "title": "Ghostty terminal", "score": 5, "num_comments": 2, |
| 374 | "created_utc": IN_WINDOW_UTC, "permalink": "/r/Ghostty/comments/1null10/t/", |
| 375 | "selftext": "ok", |
| 376 | }}]}}, |
| 377 | {"data": {"children": [ |
| 378 | {"kind": "t1", "data": {"author": "a", "body": "one", "score": None}}, |
| 379 | {"kind": "t1", "data": {"author": "b", "body": "two", "score": 10}}, |
| 380 | ]}}, |
| 381 | ]) |
| 382 | good_body = _thread_json("1good11", subreddit="Ghostty", subreddit_type="public") |
| 383 | |
| 384 | def fake_get(url, _cookie, **_k): |
| 385 | if "1priv09.json" in url: |
| 386 | return 200, priv_body, False |
| 387 | if "1null10.json" in url: |
| 388 | return 200, null_score_body, False |
| 389 | return 200, good_body, False |
| 390 | |
| 391 | monkeypatch.setattr(http, "reddit_session_get", fake_get) |
| 392 | monkeypatch.setattr( |
| 393 | reddit_arctic, |
| 394 | "fetch_posts_by_ids", |
| 395 | lambda ids, **_k: ({pid: _archive_post(pid) for pid in ids}, "ok"), |
| 396 | ) |
| 397 | monkeypatch.setattr(reddit_arctic, "fetch_comment_tree", lambda *_a, **_k: None) |
| 398 | |
| 399 | refs = [ |
| 400 | _ref("1priv09", "secretclub", provenance="host"), |
| 401 | _ref("1null10", "Ghostty", provenance="host"), |
| 402 | _ref("1good11", "Ghostty", provenance="host"), |
| 403 | ] |
| 404 | result = reddit_hydrate.hydrate( |
| 405 | refs, |
| 406 | topic=TOPIC, |
| 407 | from_date=FROM, |
| 408 | to_date=TO, |
| 409 | comments=False, |
| 410 | session_hydrator=reddit_session.hydrator(_session()), |
| 411 | now=1.9e9, |
| 412 | ) |
| 413 | ids = [item["metadata"]["post_id"] for item in result.items] |
| 414 | assert "1priv09" not in ids |
| 415 | assert "1good11" in ids |
| 416 | |
| 417 | def test_mid_hydration_expiry_preserves_prior_drop_and_releases_trailing_streak(self, monkeypatch): |
| 418 | responses = { |
| 419 | "1good01": (200, _thread_json("1good01", subreddit="Ghostty")), |
| 420 | "1priv02": (403, '{"reason": "private", "message": "Forbidden", "error": 403}'), |
| 421 | "1good03": (200, _thread_json("1good03", subreddit="Ghostty")), |
| 422 | "1pub004": (403, BLOCKED_HTML), |
| 423 | "1pub005": (403, BLOCKED_HTML), |
| 424 | "1pub006": (403, BLOCKED_HTML), |
| 425 | } |
| 426 | fetched_by_session: list[str] = [] |
| 427 | |
| 428 | def fake_get(url, _cookie, **_k): |
| 429 | pid = url.split("/comments/", 1)[1].split(".json", 1)[0] |
| 430 | fetched_by_session.append(pid) |
| 431 | status, body = responses[pid] |
| 432 | return status, body, False |
| 433 | |
| 434 | monkeypatch.setattr(http, "reddit_session_get", fake_get) |
| 435 | arctic_requested: list[list[str]] = [] |
| 436 | |
| 437 | def fake_arctic_ids(ids, **_k): |
| 438 | arctic_requested.append(list(ids)) |
| 439 | return ({pid: _archive_post(pid) for pid in ids if pid.startswith("1pub")}, "ok") |
| 440 | |
| 441 | monkeypatch.setattr(reddit_arctic, "fetch_posts_by_ids", fake_arctic_ids) |
| 442 | monkeypatch.setattr(reddit_arctic, "fetch_comment_tree", lambda *_a, **_k: None) |
| 443 | |
| 444 | session = _session() |
| 445 | refs = [_ref(pid, provenance="host") for pid in responses] |
| 446 | result = reddit_hydrate.hydrate( |
| 447 | refs, |
| 448 | topic=TOPIC, |
| 449 | from_date=FROM, |
| 450 | to_date=TO, |
| 451 | comments=False, |
| 452 | session_hydrator=reddit_session.hydrator(session), |
| 453 | now=1.9e9, |
| 454 | ) |
| 455 | assert session.state == reddit_session.EXPIRED |
| 456 | assert reddit_health.entries()["session"]["state"] == reddit_health.BLOCKED |
| 457 | assert "1pub006" not in fetched_by_session |
| 458 | assert arctic_requested == [["1pub004", "1pub005", "1pub006"]] |
| 459 | returned_ids = [item["metadata"]["post_id"] for item in result.items] |
| 460 | assert returned_ids == ["1good01", "1good03", "1pub004", "1pub005", "1pub006"] |
| 461 | assert "1priv02" not in returned_ids |
| 462 | |
| 463 | def test_single_ref_logged_out_403_on_unverified_session_expires_and_allows_arctic(self, monkeypatch): |
| 464 | monkeypatch.setattr(http, "reddit_session_get", lambda *_a, **_k: (403, BLOCKED_HTML, False)) |
| 465 | monkeypatch.setattr( |
| 466 | reddit_arctic, |
| 467 | "fetch_posts_by_ids", |
| 468 | lambda ids, **_k: ({pid: _archive_post(pid) for pid in ids}, "ok"), |
| 469 | ) |
| 470 | monkeypatch.setattr(reddit_arctic, "fetch_comment_tree", lambda *_a, **_k: None) |
| 471 | |
| 472 | session = _session() |
| 473 | assert not session.verified |
| 474 | result = reddit_hydrate.hydrate( |
| 475 | [_ref("1pub101", provenance="host")], |
| 476 | topic=TOPIC, |
| 477 | from_date=FROM, |
| 478 | to_date=TO, |
| 479 | comments=False, |
| 480 | session_hydrator=reddit_session.hydrator(session), |
| 481 | now=1.9e9, |
| 482 | ) |
| 483 | assert session.state == reddit_session.EXPIRED |
| 484 | assert [item["metadata"]["post_id"] for item in result.items] == ["1pub101"] |
| 485 | |
| 486 | def test_single_ref_opaque_403_on_unverified_host_ref_fails_closed_with_drop(self, monkeypatch): |
| 487 | monkeypatch.setattr(http, "reddit_session_get", lambda *_a, **_k: (403, "Forbidden", False)) |
| 488 | monkeypatch.setattr( |
| 489 | reddit_arctic, |
| 490 | "fetch_posts_by_ids", |
| 491 | lambda ids, **_k: ({pid: _archive_post(pid) for pid in ids}, "ok"), |
| 492 | ) |
| 493 | monkeypatch.setattr(reddit_arctic, "fetch_comment_tree", lambda *_a, **_k: None) |
| 494 | |
| 495 | session = _session() |
| 496 | result = reddit_hydrate.hydrate( |
| 497 | [_ref("1pub102", provenance="web")], |
| 498 | topic=TOPIC, |
| 499 | from_date=FROM, |
| 500 | to_date=TO, |
| 501 | comments=False, |
| 502 | session_hydrator=reddit_session.hydrator(session), |
| 503 | now=1.9e9, |
| 504 | ) |
| 505 | assert session.alive |
| 506 | assert result.items == [] |
| 507 | |
| 508 | def test_explicit_private_json_403_always_drops_and_does_not_expire_session(self, monkeypatch): |
| 509 | private_403 = '{"reason": "private", "message": "Forbidden", "error": 403}' |
| 510 | monkeypatch.setattr(http, "reddit_session_get", lambda *_a, **_k: (403, private_403, False)) |
| 511 | monkeypatch.setattr( |
| 512 | reddit_arctic, |
| 513 | "fetch_posts_by_ids", |
| 514 | lambda ids, **_k: ({pid: _archive_post(pid) for pid in ids}, "ok"), |
| 515 | ) |
| 516 | monkeypatch.setattr(reddit_arctic, "fetch_comment_tree", lambda *_a, **_k: None) |
| 517 | |
| 518 | session = _session() |
| 519 | result = reddit_hydrate.hydrate( |
| 520 | [_ref("1priv10", "secret", provenance="host"), _ref("1priv11", "secret", provenance="host")], |
| 521 | topic=TOPIC, |
| 522 | from_date=FROM, |
| 523 | to_date=TO, |
| 524 | comments=False, |
| 525 | session_hydrator=reddit_session.hydrator(session), |
| 526 | now=1.9e9, |
| 527 | ) |
| 528 | assert session.alive |
| 529 | assert result.items == [] |
| 530 | |
| 531 | def test_single_ref_session_only_logged_out_403_still_drops_if_absent_from_arctic(self, monkeypatch): |
| 532 | monkeypatch.setattr(http, "reddit_session_get", lambda *_a, **_k: (403, BLOCKED_HTML, False)) |
| 533 | monkeypatch.setattr(reddit_arctic, "fetch_posts_by_ids", lambda *_a, **_k: ({}, "ok")) |
| 534 | monkeypatch.setattr(reddit_arctic, "fetch_comment_tree", lambda *_a, **_k: None) |
| 535 | |
| 536 | session = _session() |
| 537 | result = reddit_hydrate.hydrate( |
| 538 | [_ref("1priv12", "secret", provenance="session")], |
| 539 | topic=TOPIC, |
| 540 | from_date=FROM, |
| 541 | to_date=TO, |
| 542 | comments=False, |
| 543 | session_hydrator=reddit_session.hydrator(session), |
| 544 | now=1.9e9, |
| 545 | ) |
| 546 | assert session.state == reddit_session.EXPIRED |
| 547 | assert result.items == [] |
| 548 | |
| 549 | |
| 550 | # --------------------------------------------------------------------------- |
| 551 | # HIGH-129: Single-flight deduplication in discover() and Session.fetch() |
| 552 | # --------------------------------------------------------------------------- |
| 553 | |
| 554 | |
| 555 | class TestHigh129SessionSingleFlight: |
| 556 | def test_parallel_discover_coalesces_into_single_run_and_preserves_budget(self, monkeypatch): |
| 557 | started = threading.Event() |
| 558 | release = threading.Event() |
| 559 | calls: list[str] = [] |
| 560 | calls_lock = threading.Lock() |
| 561 | |
| 562 | def fake_get(url, _cookie, **_k): |
| 563 | with calls_lock: |
| 564 | calls.append(url) |
| 565 | first = len(calls) == 1 |
| 566 | if first: |
| 567 | started.set() |
| 568 | release.wait(timeout=5.0) |
| 569 | if "type=posts" in url: |
| 570 | return 200, POSTS_HTML, False |
| 571 | if "type=comments" in url: |
| 572 | return 200, NO_COMMENTS_HTML, False |
| 573 | if "type=communities" in url: |
| 574 | return 200, COMMUNITIES_HTML, False |
| 575 | return 404, "", False |
| 576 | |
| 577 | monkeypatch.setattr(http, "reddit_session_get", fake_get) |
| 578 | session = _session() |
| 579 | |
| 580 | def run_one(): |
| 581 | with reddit_session.lane(session, TOPIC): |
| 582 | return reddit_session.discover(session, TOPIC, depth="quick", from_date=FROM, to_date=TO) |
| 583 | |
| 584 | with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: |
| 585 | f0 = pool.submit(run_one) |
| 586 | assert started.wait(timeout=3.0) |
| 587 | waiters = [pool.submit(run_one) for _ in range(3)] |
| 588 | time.sleep(0.05) |
| 589 | release.set() |
| 590 | results = [f.result(timeout=5.0) for f in (f0, *waiters)] |
| 591 | |
| 592 | assert all(r.state == reddit_health.OK and r.refs for r in results) |
| 593 | # Every thread gets its own deep copy of refs. |
| 594 | results[0].refs[0].title = "mutated" |
| 595 | assert all(r.refs[0].title != "mutated" for r in results[1:]) |
| 596 | # Only one discovery run executed against Reddit and charged REQUEST_CAP. |
| 597 | post_search_calls = [u for u in calls if "type=posts" in u and "/r/" not in u] |
| 598 | assert len(post_search_calls) == 1 |
| 599 | assert session.requests == len(calls) |
| 600 | |
| 601 | def test_discover_cache_isolates_different_named_subreddits(self, monkeypatch): |
| 602 | calls: list[str] = [] |
| 603 | |
| 604 | def fake_get(url, _cookie, **_k): |
| 605 | calls.append(url) |
| 606 | if "type=posts" in url: |
| 607 | ctx = json.dumps({ |
| 608 | "action_info": {"type": "post"}, |
| 609 | "post": {"id": "t3_1priv99", "nsfw": False}, |
| 610 | "subreddit": {"name": "PrivateA", "nsfw": False, "quarantined": True}, |
| 611 | }).replace('"', """) |
| 612 | body = ( |
| 613 | "user-logged-in " |
| 614 | f'<search-telemetry-tracker view-events="search/view/post" ' |
| 615 | f'data-faceplate-tracking-context="{ctx}"></search-telemetry-tracker>' |
| 616 | ) |
| 617 | return 200, body, False |
| 618 | return 200, NO_COMMENTS_HTML, False |
| 619 | |
| 620 | monkeypatch.setattr(http, "reddit_session_get", fake_get) |
| 621 | monkeypatch.setattr( |
| 622 | reddit_session.reddit_search, |
| 623 | "parse_page", |
| 624 | lambda _b, _t: ([{ |
| 625 | "title": "Ghostty private", |
| 626 | "url": "https://www.reddit.com/r/PrivateA/comments/1priv99/", |
| 627 | "subreddit": "PrivateA", |
| 628 | "date": "2026-11-11", |
| 629 | "metadata": {"post_id": "1priv99"}, |
| 630 | }], None), |
| 631 | ) |
| 632 | monkeypatch.setattr(reddit_session.reddit_search, "unrecognized_body", lambda _b: None) |
| 633 | monkeypatch.setattr(reddit_session.reddit_search, "next_cursor", lambda _b: None) |
| 634 | |
| 635 | session = _session() |
| 636 | with reddit_session.lane(session, "entity-a", named=frozenset({"privatea"})): |
| 637 | found_a = reddit_session.discover(session, TOPIC, depth="quick") |
| 638 | with reddit_session.lane(session, "entity-b", named=frozenset()): |
| 639 | found_b = reddit_session.discover(session, TOPIC, depth="quick") |
| 640 | |
| 641 | assert [r.post_id for r in found_a.refs] == ["1priv99"] |
| 642 | assert found_b.refs == [] |
| 643 | |
| 644 | def test_discover_waiter_respects_deadline_and_cancel_without_poisoning_cache(self, monkeypatch): |
| 645 | started = threading.Event() |
| 646 | release = threading.Event() |
| 647 | |
| 648 | def fake_get(url, _cookie, **_k): |
| 649 | started.set() |
| 650 | release.wait(timeout=5.0) |
| 651 | if "type=posts" in url: |
| 652 | return 200, POSTS_HTML, False |
| 653 | return 200, NO_COMMENTS_HTML, False |
| 654 | |
| 655 | monkeypatch.setattr(http, "reddit_session_get", fake_get) |
| 656 | session = _session() |
| 657 | cancel_ev = threading.Event() |
| 658 | |
| 659 | with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool: |
| 660 | owner_fut = pool.submit(reddit_session.discover, session, TOPIC, depth="quick") |
| 661 | assert started.wait(timeout=3.0) |
| 662 | |
| 663 | short_deadline = time.monotonic() + 0.08 |
| 664 | t0 = time.monotonic() |
| 665 | timed_out = reddit_session.discover(session, TOPIC, depth="quick", deadline=short_deadline) |
| 666 | assert timed_out.state == reddit_session.ERROR |
| 667 | assert time.monotonic() - t0 < 1.0 |
| 668 | |
| 669 | cancel_fut = pool.submit(reddit_session.discover, session, TOPIC, depth="quick", cancel=cancel_ev) |
| 670 | time.sleep(0.03) |
| 671 | cancel_ev.set() |
| 672 | cancelled = cancel_fut.result(timeout=2.0) |
| 673 | assert cancelled.state == reddit_session.ERROR |
| 674 | |
| 675 | release.set() |
| 676 | owner_res = owner_fut.result(timeout=5.0) |
| 677 | assert owner_res.state == reddit_health.OK and owner_res.refs |
| 678 | |
| 679 | # Subsequent call hits the clean cached result at zero extra requests. |
| 680 | before = session.requests |
| 681 | cached = reddit_session.discover(session, TOPIC, depth="quick") |
| 682 | assert cached.state == reddit_health.OK and len(cached.refs) == len(owner_res.refs) |
| 683 | assert session.requests == before |
| 684 | |
| 685 | def test_discover_owner_error_does_not_poison_cache(self, monkeypatch): |
| 686 | attempt = {"n": 0} |
| 687 | |
| 688 | def fake_get(url, _cookie, **_k): |
| 689 | attempt["n"] += 1 |
| 690 | if attempt["n"] == 1: |
| 691 | return None, None, False |
| 692 | if "type=posts" in url: |
| 693 | return 200, POSTS_HTML, False |
| 694 | return 200, NO_COMMENTS_HTML, False |
| 695 | |
| 696 | monkeypatch.setattr(http, "reddit_session_get", fake_get) |
| 697 | session = _session() |
| 698 | first = reddit_session.discover(session, TOPIC, depth="quick") |
| 699 | assert first.state == reddit_session.ERROR |
| 700 | second = reddit_session.discover(session, TOPIC, depth="quick") |
| 701 | assert second.state == reddit_health.OK and second.refs |
| 702 | |
| 703 | def test_partial_discover_timeout_or_budget_truncation_is_not_cached(self, monkeypatch): |
| 704 | comment_attempts = {"n": 0} |
| 705 | |
| 706 | def fake_get(url, _cookie, **_k): |
| 707 | if "type=posts" in url: |
| 708 | return 200, POSTS_HTML, False |
| 709 | if "type=comments" in url: |
| 710 | comment_attempts["n"] += 1 |
| 711 | if comment_attempts["n"] == 1: |
| 712 | # Simulate timeout on comments page after posts succeeded. |
| 713 | return None, None, False |
| 714 | return 200, COMMENTS_HTML, False |
| 715 | if "type=communities" in url: |
| 716 | return 200, NO_COMMENTS_HTML, False |
| 717 | return 404, "", False |
| 718 | |
| 719 | monkeypatch.setattr(http, "reddit_session_get", fake_get) |
| 720 | session = _session() |
| 721 | partial = reddit_session.discover(session, TOPIC, depth="quick") |
| 722 | assert partial.state == reddit_health.OK |
| 723 | assert partial.refs and not partial.comments |
| 724 | assert session._discover_cache == {} |
| 725 | |
| 726 | # A second caller with more time must NOT reuse the partial search. |
| 727 | complete = reddit_session.discover(session, TOPIC, depth="quick") |
| 728 | assert complete.state == reddit_health.OK |
| 729 | assert complete.comments |
| 730 | assert comment_attempts["n"] == 2 |
| 731 | assert len(session._discover_cache) == 1 |
| 732 | |
| 733 | # Cap exhaustion before comments also leaves the partial search uncached. |
| 734 | capped_session = _session(cap=1) |
| 735 | capped = reddit_session.discover(capped_session, TOPIC, depth="quick") |
| 736 | assert capped.state == reddit_health.OK and capped.refs and not capped.comments |
| 737 | assert capped_session._discover_cache == {} |
| 738 | |
| 739 | def test_waiting_discover_falls_back_to_partial_posts_when_retry_cannot_fetch(self, monkeypatch): |
| 740 | # Case 1: owner gets posts then exhausts shared cap while a waiter is waiting. |
| 741 | # Partial result stays uncached, and the waiter keeps the owner's partial posts. |
| 742 | owner_started = threading.Event() |
| 743 | waiter_waiting = threading.Event() |
| 744 | orig_wait = reddit_session._wait_event |
| 745 | |
| 746 | def spy_wait(event, deadline, cancel=None): |
| 747 | waiter_waiting.set() |
| 748 | return orig_wait(event, deadline, cancel) |
| 749 | |
| 750 | def fake_get_capped(url, _cookie, **_k): |
| 751 | owner_started.set() |
| 752 | assert waiter_waiting.wait(timeout=5.0) |
| 753 | if "type=posts" in url: |
| 754 | return 200, POSTS_HTML, False |
| 755 | return 200, COMMENTS_HTML, False |
| 756 | |
| 757 | monkeypatch.setattr(http, "reddit_session_get", fake_get_capped) |
| 758 | monkeypatch.setattr(reddit_session, "_wait_event", spy_wait) |
| 759 | capped = _session(cap=1) |
| 760 | |
| 761 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 762 | f_owner = pool.submit(reddit_session.discover, capped, TOPIC, depth="quick") |
| 763 | assert owner_started.wait(timeout=3.0) |
| 764 | f_waiter = pool.submit(reddit_session.discover, capped, TOPIC, depth="quick") |
| 765 | owner_res = f_owner.result(timeout=5.0) |
| 766 | waiter_res = f_waiter.result(timeout=5.0) |
| 767 | |
| 768 | assert owner_res.state == reddit_health.OK and owner_res.refs |
| 769 | assert waiter_res.state == reddit_health.OK |
| 770 | assert [r.post_id for r in waiter_res.refs] == [r.post_id for r in owner_res.refs] |
| 771 | assert waiter_res.refs[0] is not owner_res.refs[0] |
| 772 | assert capped._discover_cache == {} |
| 773 | |
| 774 | # Case 2: owner gets posts then comments times out; waiter retries with room |
| 775 | # left, its retry errors out empty, so it falls back to the owner's partial |
| 776 | # posts (never cached); a later caller with working responses completes & caches. |
| 777 | owner_started.clear() |
| 778 | waiter_waiting.clear() |
| 779 | phase = {"calls": 0} |
| 780 | |
| 781 | def fake_get_retry_fail(url, _cookie, **_k): |
| 782 | phase["calls"] += 1 |
| 783 | if phase["calls"] == 1: |
| 784 | owner_started.set() |
| 785 | assert waiter_waiting.wait(timeout=5.0) |
| 786 | return 200, POSTS_HTML, False |
| 787 | if phase["calls"] == 2: |
| 788 | # Owner's comments request times out. |
| 789 | return None, None, False |
| 790 | if phase["calls"] == 3: |
| 791 | # Waiter's retry hits a transient error on posts page. |
| 792 | return None, None, False |
| 793 | if "type=posts" in url: |
| 794 | return 200, POSTS_HTML, False |
| 795 | if "type=comments" in url: |
| 796 | return 200, COMMENTS_HTML, False |
| 797 | return 200, NO_COMMENTS_HTML, False |
| 798 | |
| 799 | monkeypatch.setattr(http, "reddit_session_get", fake_get_retry_fail) |
| 800 | session = _session() |
| 801 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 802 | f_owner = pool.submit(reddit_session.discover, session, TOPIC, depth="quick") |
| 803 | assert owner_started.wait(timeout=3.0) |
| 804 | f_waiter = pool.submit(reddit_session.discover, session, TOPIC, depth="quick") |
| 805 | owner_res2 = f_owner.result(timeout=5.0) |
| 806 | waiter_res2 = f_waiter.result(timeout=5.0) |
| 807 | |
| 808 | assert owner_res2.state == reddit_health.OK and owner_res2.refs |
| 809 | assert waiter_res2.state == reddit_health.OK |
| 810 | assert [r.post_id for r in waiter_res2.refs] == [r.post_id for r in owner_res2.refs] |
| 811 | assert session._discover_cache == {} |
| 812 | |
| 813 | # Later caller still retries and caches the complete search. |
| 814 | monkeypatch.setattr(reddit_session, "_wait_event", orig_wait) |
| 815 | complete_res = reddit_session.discover(session, TOPIC, depth="quick") |
| 816 | assert complete_res.state == reddit_health.OK and complete_res.comments |
| 817 | assert len(session._discover_cache) == 1 |
| 818 | |
| 819 | def test_parallel_session_fetch_coalesces_same_url_and_respects_waiter_cancel(self, monkeypatch): |
| 820 | started = threading.Event() |
| 821 | release = threading.Event() |
| 822 | calls: list[str] = [] |
| 823 | |
| 824 | def fake_get(url, _cookie, **_k): |
| 825 | calls.append(url) |
| 826 | started.set() |
| 827 | release.wait(timeout=5.0) |
| 828 | return 200, '{"ok": true}', False |
| 829 | |
| 830 | monkeypatch.setattr(http, "reddit_session_get", fake_get) |
| 831 | session = _session() |
| 832 | url = reddit_session.thread_url("1same01") |
| 833 | cancel_ev = threading.Event() |
| 834 | |
| 835 | with concurrent.futures.ThreadPoolExecutor(max_workers=5) as pool: |
| 836 | f0 = pool.submit(session.fetch, url, accept="application/json") |
| 837 | assert started.wait(timeout=3.0) |
| 838 | waiters = [pool.submit(session.fetch, url, accept="application/json") for _ in range(3)] |
| 839 | cancel_waiter = pool.submit(session.fetch, url, accept="application/json", cancel=cancel_ev) |
| 840 | time.sleep(0.03) |
| 841 | cancel_ev.set() |
| 842 | assert cancel_waiter.result(timeout=2.0) == (None, None) |
| 843 | release.set() |
| 844 | results = [f.result(timeout=5.0) for f in (f0, *waiters)] |
| 845 | |
| 846 | assert len(calls) == 1 |
| 847 | assert session.requests == 1 |
| 848 | assert all(res == (200, '{"ok": true}') for res in results) |
| 849 | |
| 850 | def test_fetch_exhausted_owner_entity_does_not_starve_other_entity_waiter(self, monkeypatch): |
| 851 | calls: list[str] = [] |
| 852 | |
| 853 | def fake_get(url, _cookie, **_k): |
| 854 | calls.append(url) |
| 855 | return 200, '{"ok": true}', False |
| 856 | |
| 857 | monkeypatch.setattr(http, "reddit_session_get", fake_get) |
| 858 | # 2 entities, cap=2 => 1 request per entity. |
| 859 | session = _session(entity_count=2, cap=2) |
| 860 | with reddit_session.lane(session, "entity-a"): |
| 861 | assert session.fetch(reddit_session.thread_url("1used01"), accept="application/json") == (200, '{"ok": true}') |
| 862 | |
| 863 | # entity-a is now out of budget; hold entity-a inside _take() while its |
| 864 | # inflight slot is active until entity-b is genuinely waiting on it. |
| 865 | url2 = reddit_session.thread_url("1used02") |
| 866 | owner_in_take = threading.Event() |
| 867 | waiter_waiting = threading.Event() |
| 868 | waiter_entered = {"seen": False} |
| 869 | |
| 870 | orig_take = session._take |
| 871 | |
| 872 | def gated_take(entity: str) -> bool: |
| 873 | if entity == "entity-a": |
| 874 | owner_in_take.set() |
| 875 | assert waiter_waiting.wait(timeout=5.0), "waiter never entered _wait_event" |
| 876 | return orig_take(entity) |
| 877 | |
| 878 | orig_wait_event = reddit_session._wait_event |
| 879 | |
| 880 | def spy_wait_event(event, deadline, cancel=None): |
| 881 | waiter_entered["seen"] = True |
| 882 | waiter_waiting.set() |
| 883 | return orig_wait_event(event, deadline, cancel) |
| 884 | |
| 885 | monkeypatch.setattr(session, "_take", gated_take) |
| 886 | monkeypatch.setattr(reddit_session, "_wait_event", spy_wait_event) |
| 887 | |
| 888 | def run_entity(name: str): |
| 889 | with reddit_session.lane(session, name): |
| 890 | return session.fetch(url2, accept="application/json") |
| 891 | |
| 892 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 893 | fut_a = pool.submit(run_entity, "entity-a") |
| 894 | assert owner_in_take.wait(timeout=3.0) |
| 895 | fut_b = pool.submit(run_entity, "entity-b") |
| 896 | res_a = fut_a.result(timeout=5.0) |
| 897 | res_b = fut_b.result(timeout=5.0) |
| 898 | |
| 899 | assert waiter_entered["seen"] is True |
| 900 | assert res_a == (None, None) |
| 901 | assert res_b == (200, '{"ok": true}') |
| 902 | assert len(calls) == 2 |
| 903 | |
| 904 | |
| 905 | # --------------------------------------------------------------------------- |
| 906 | # HIGH-130 & HIGH-131: reddit_health private writes, locking & monotonicity |
| 907 | # --------------------------------------------------------------------------- |
| 908 | |
| 909 | |
| 910 | class TestHigh130HealthPersistenceAndLocking: |
| 911 | @pytest.mark.skipif(os.name != "posix", reason="POSIX mode bits only") |
| 912 | def test_health_file_written_0600_and_refuses_symlink(self, tmp_path): |
| 913 | reddit_health.record("search", reddit_health.BLOCKED, "HTTP 403", cookie_fp="abcdef0123456789") |
| 914 | cache = reddit_health.cache_path() |
| 915 | assert cache is not None and cache.is_file() |
| 916 | assert stat.S_IMODE(cache.stat().st_mode) == 0o600 |
| 917 | |
| 918 | # Replace cache with a symlink pointing outside; _write must refuse and never overwrite target. |
| 919 | outside = tmp_path / "outside.txt" |
| 920 | outside.write_text("sentinel", encoding="utf-8") |
| 921 | cache.unlink() |
| 922 | cache.symlink_to(outside) |
| 923 | reddit_health.reset_run_state() |
| 924 | reddit_health.record("brave", reddit_health.BLOCKED, "HTTP 403") |
| 925 | assert outside.read_text(encoding="utf-8") == "sentinel" |
| 926 | |
| 927 | def test_failed_replace_leaves_no_temp_files(self, monkeypatch): |
| 928 | cache = reddit_health.cache_path() |
| 929 | assert cache is not None |
| 930 | monkeypatch.setattr(os, "replace", mock.Mock(side_effect=OSError("disk full"))) |
| 931 | reddit_health.record("search", reddit_health.BLOCKED, "HTTP 403") |
| 932 | leftovers = [p.name for p in cache.parent.iterdir() if ".tmp" in p.name or p.name.startswith(".reddit-health")] |
| 933 | assert leftovers == [] |
| 934 | |
| 935 | def test_cross_process_concurrent_records_preserve_all_paths(self): |
| 936 | cache = reddit_health.cache_path() |
| 937 | assert cache is not None |
| 938 | config_dir = str(cache.parent) |
| 939 | paths = ["search", "brave", "ddg", "startpage", "arctic", "session"] |
| 940 | worker_code = ( |
| 941 | "import sys\n" |
| 942 | f"sys.path.insert(0, {str(SCRIPTS_DIR)!r})\n" |
| 943 | "from pathlib import Path\n" |
| 944 | "from lib import env, reddit_health\n" |
| 945 | "env.CONFIG_DIR = Path(sys.argv[1])\n" |
| 946 | "path_name = sys.argv[2]\n" |
| 947 | "for i in range(6):\n" |
| 948 | " reddit_health.reset_run_state()\n" |
| 949 | " reddit_health.record(path_name, reddit_health.BLOCKED, f'worker-{i}')\n" |
| 950 | ) |
| 951 | procs = [ |
| 952 | subprocess.Popen([sys.executable, "-c", worker_code, config_dir, name]) |
| 953 | for name in paths |
| 954 | ] |
| 955 | for proc in procs: |
| 956 | assert proc.wait(timeout=20) == 0 |
| 957 | saved = reddit_health.entries() |
| 958 | assert set(saved.keys()) == set(paths) |
| 959 | assert all(saved[p]["state"] == reddit_health.BLOCKED for p in paths) |
| 960 | |
| 961 | def test_lock_failure_skips_disk_write_keeps_memory_and_closes_fd(self, monkeypatch): |
| 962 | # Seed a persisted entry from an earlier writer. |
| 963 | reddit_health.record("search", reddit_health.BLOCKED, "HTTP 403") |
| 964 | assert "search" in reddit_health.entries() |
| 965 | |
| 966 | closed_fds: list[int] = [] |
| 967 | real_close = os.close |
| 968 | |
| 969 | def spy_close(fd: int): |
| 970 | closed_fds.append(fd) |
| 971 | return real_close(fd) |
| 972 | |
| 973 | monkeypatch.setattr(os, "close", spy_close) |
| 974 | if os.name == "posix": |
| 975 | import fcntl |
| 976 | monkeypatch.setattr(fcntl, "flock", mock.Mock(side_effect=OSError("ENOLCK"))) |
| 977 | else: |
| 978 | monkeypatch.setattr(os, "open", mock.Mock(side_effect=OSError("EACCES"))) |
| 979 | |
| 980 | # record() must update in-memory state while skipping the unlocked disk write. |
| 981 | reddit_health.record("brave", reddit_health.BLOCKED, "HTTP 403") |
| 982 | assert reddit_health.run_state("brave") == reddit_health.BLOCKED |
| 983 | assert "brave" not in reddit_health.entries() |
| 984 | assert reddit_health.entries()["search"]["state"] == reddit_health.BLOCKED |
| 985 | if os.name == "posix": |
| 986 | assert len(closed_fds) >= 1 |
| 987 | |
| 988 | # clear() must clear in-memory state while skipping the unlocked disk write. |
| 989 | assert reddit_health.clear() == [] |
| 990 | assert reddit_health.run_state("brave") is None |
| 991 | assert reddit_health.entries()["search"]["state"] == reddit_health.BLOCKED |
| 992 | |
| 993 | def test_windows_msvcrt_lock_and_unlock_path(self, monkeypatch): |
| 994 | ops: list[tuple] = [] |
| 995 | fake_msvcrt = types.SimpleNamespace( |
| 996 | LK_LOCK=1, |
| 997 | LK_UNLCK=2, |
| 998 | locking=lambda fd, mode, nbytes: ops.append(("locking", mode, nbytes)), |
| 999 | ) |
| 1000 | monkeypatch.setitem(sys.modules, "msvcrt", fake_msvcrt) |
| 1001 | monkeypatch.setattr(reddit_health.os, "name", "nt") |
| 1002 | monkeypatch.setattr(reddit_health.private_files.os, "name", "nt") |
| 1003 | monkeypatch.setattr( |
| 1004 | reddit_health.os, |
| 1005 | "lseek", |
| 1006 | lambda fd, offset, how: ops.append(("lseek", offset, how)) or 0, |
| 1007 | ) |
| 1008 | |
| 1009 | reddit_health.record("brave", reddit_health.BLOCKED, "HTTP 403") |
| 1010 | assert ("locking", 1, 1) in ops |
| 1011 | assert ("locking", 2, 1) in ops |
| 1012 | assert ops.index(("locking", 1, 1)) < ops.index(("locking", 2, 1)) |
| 1013 | assert reddit_health.entries()["brave"]["state"] == reddit_health.BLOCKED |
| 1014 | |
| 1015 | |
| 1016 | class TestHigh131MonotonicHealthState: |
| 1017 | def test_stale_inflight_ok_never_overwrites_persisted_blocked_in_same_run(self): |
| 1018 | fp = "0123456789abcdef" |
| 1019 | reddit_health.record("session", reddit_health.BLOCKED, "session-expired: HTTP 403", cookie_fp=fp) |
| 1020 | reddit_health.record("session", reddit_health.OK, "session search", cookie_fp=fp) |
| 1021 | |
| 1022 | assert reddit_health.run_state("session") == reddit_health.BLOCKED |
| 1023 | assert reddit_health.entries()["session"]["state"] == reddit_health.BLOCKED |
| 1024 | assert reddit_health.skip_until("session", cookie_fp=fp) is not None |
| 1025 | |
| 1026 | def test_stale_inflight_ok_after_throttled_does_not_touch_disk(self): |
| 1027 | reddit_health.record("ddg", reddit_health.THROTTLED, "HTTP 429") |
| 1028 | reddit_health.record("ddg", reddit_health.OK, "web search ok") |
| 1029 | |
| 1030 | assert reddit_health.run_state("ddg") == reddit_health.THROTTLED |
| 1031 | assert "ddg" not in reddit_health.entries() |
| 1032 | |
| 1033 | def test_throttled_can_escalate_to_blocked_in_same_run(self): |
| 1034 | reddit_health.record("brave", reddit_health.THROTTLED, "HTTP 429") |
| 1035 | reddit_health.record("brave", reddit_health.BLOCKED, "HTTP 403") |
| 1036 | |
| 1037 | assert reddit_health.run_state("brave") == reddit_health.BLOCKED |
| 1038 | assert reddit_health.entries()["brave"]["state"] == reddit_health.BLOCKED |
| 1039 | |
| 1040 | def test_new_run_ok_still_clears_prior_run_blocked_skip(self): |
| 1041 | fp = "0123456789abcdef" |
| 1042 | reddit_health.record("session", reddit_health.BLOCKED, "session-expired", cookie_fp=fp) |
| 1043 | reddit_health.reset_run_state() |
| 1044 | reddit_health.record("session", reddit_health.OK, "session search", cookie_fp=fp) |
| 1045 | |
| 1046 | assert reddit_health.entries()["session"]["state"] == reddit_health.OK |
| 1047 | assert reddit_health.skip_until("session", cookie_fp=fp) is None |
| 1048 | |
| 1049 | |
| 1050 | # --------------------------------------------------------------------------- |
| 1051 | # HIGH-133: reddit_enrich.extract_reddit_path strict URL validation |
| 1052 | # --------------------------------------------------------------------------- |
| 1053 | |
| 1054 | |
| 1055 | class TestHigh133ExtractRedditPath: |
| 1056 | @pytest.mark.parametrize("malicious_url", [ |
| 1057 | "", |
| 1058 | None, |
| 1059 | 123, |
| 1060 | ["https://www.reddit.com/r/ClaudeAI/comments/abc123/post/"], |
| 1061 | "https://evil-reddit.com/r/ClaudeAI/comments/abc123/post/", |
| 1062 | "https://reddit.com.attacker.com/r/ClaudeAI/comments/abc123/post/", |
| 1063 | "https://reddit.com@attacker.com/r/ClaudeAI/comments/abc123/post/", |
| 1064 | "https://attacker@www.reddit.com/r/ClaudeAI/comments/abc123/post/", |
| 1065 | "https://www.reddit.com:8443/r/ClaudeAI/comments/abc123/post/", |
| 1066 | "https://www.reddit.com:99999/r/ClaudeAI/comments/abc123/post/", |
| 1067 | "https://[::1/r/ClaudeAI/comments/abc123/post/", |
| 1068 | "javascript://reddit.com/r/ClaudeAI/comments/abc123/post/", |
| 1069 | "ftp://www.reddit.com/r/ClaudeAI/comments/abc123/post/", |
| 1070 | "https://www.reddit.com/api/v1/me", |
| 1071 | "https://www.reddit.com//attacker.com/r/ClaudeAI/comments/abc123/post/", |
| 1072 | "https://www.reddit.com/r/ClaudeAI/comments/abc123/../../api/v1/me", |
| 1073 | "https://www.reddit.com/r/ClaudeAI/comments/abc123/%2e%2e/%2e%2e/api", |
| 1074 | "https://www.reddit.com/r/ClaudeAI/comments/abc123/slug%2f..%2fapi", |
| 1075 | "https://www.reddit.com/r/ClaudeAI/comments/abc123/slug%3Fextra=1", |
| 1076 | "https://www.reddit.com/r/ClaudeAI/comments/abc123/slug%23frag", |
| 1077 | "https://www.reddit.com/r/ClaudeAI/comments/abc123/slug%0Ainjected", |
| 1078 | "https://www.reddit.com/r/ClaudeAI/comments/abc123/slug%253Fextra=1", |
| 1079 | "https://www.reddit.com/r/ClaudeAI/comments/abc123/slug%2523frag", |
| 1080 | "https://www.reddit.com/r/ClaudeAI/comments/abc123/slug%2500nul", |
| 1081 | "https://www.reddit.com/r/ClaudeAI/comments/abc123/a/b/c", |
| 1082 | "https://redd.it/abc123", |
| 1083 | ]) |
| 1084 | def test_rejects_lookalike_userinfo_port_scheme_and_non_thread_urls(self, malicious_url): |
| 1085 | assert reddit_enrich.extract_reddit_path(malicious_url) is None |
| 1086 | |
| 1087 | @pytest.mark.parametrize(("url", "expected"), [ |
| 1088 | ( |
| 1089 | "https://www.reddit.com/r/ClaudeAI/comments/abc123/post_title/", |
| 1090 | "/r/ClaudeAI/comments/abc123/post_title/", |
| 1091 | ), |
| 1092 | ( |
| 1093 | "https://old.reddit.com/r/ClaudeAI/comments/abc123/post_title/?utm_source=x#top", |
| 1094 | "/r/ClaudeAI/comments/abc123/post_title/", |
| 1095 | ), |
| 1096 | ( |
| 1097 | "https://reddit.com/comments/abc123/", |
| 1098 | "/comments/abc123/", |
| 1099 | ), |
| 1100 | ( |
| 1101 | "https://sh.reddit.com/r/Ghostty/comments/1taeiw0/slug/c1d2e3/", |
| 1102 | "/r/Ghostty/comments/1taeiw0/slug/c1d2e3/", |
| 1103 | ), |
| 1104 | ( |
| 1105 | "http://www.reddit.com:80/r/Ghostty/comments/1taeiw0/", |
| 1106 | "/r/Ghostty/comments/1taeiw0/", |
| 1107 | ), |
| 1108 | ( |
| 1109 | "https://www.reddit.com:443/r/Ghostty/comments/1taeiw0/", |
| 1110 | "/r/Ghostty/comments/1taeiw0/", |
| 1111 | ), |
| 1112 | ]) |
| 1113 | def test_accepts_valid_reddit_thread_urls(self, url, expected): |
| 1114 | assert reddit_enrich.extract_reddit_path(url) == expected |
| 1115 | |
| 1116 | def test_fetch_thread_data_refuses_attacker_url_without_http_call(self): |
| 1117 | with mock.patch.object(reddit_enrich.http, "get_reddit_json") as get_json: |
| 1118 | assert reddit_enrich.fetch_thread_data("https://evil-reddit.com/api/v1/me") is None |
| 1119 | assert reddit_enrich.fetch_thread_data("https://reddit.com@attacker.com/r/x/comments/abc/") is None |
| 1120 | get_json.assert_not_called() |
| 1121 |