| 1 | """Regression tests for PR 21: Reddit keyless/shreddit/arctic thread safety, OP filter & deadlines. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-111: OP (`is_submitter` / `is_uploader`) preservation across Arctic Shift, |
| 5 | shreddit HTML, site search, normalization, and lane/post-ranking enrichment. |
| 6 | - HIGH-115: Synchronized `WebFloor` updates and snapshots under concurrent timeout. |
| 7 | - HIGH-116: Main-thread-only application of `_enrich` results so abandoned workers |
| 8 | cannot mutate returned post dicts. |
| 9 | - HIGH-117: Thread-isolated `last_tree_throttled` / status tuple and locked, |
| 10 | in-flight-deduplicated `_cache` in `reddit_arctic.fetch_scores`. |
| 11 | - HIGH-119: Shreddit comment fetch deadline clamping, `retries=1`, challenge HTML |
| 12 | rejection (never memoized), and 0-comment Arctic Shift skip. |
| 13 | - HIGH-123: `reddit_search.search` waiter deadline bounds, no uncoordinated |
| 14 | post-election fallthrough, and deadline-aware `_search_stream` paging. |
| 15 | """ |
| 16 | |
| 17 | from __future__ import annotations |
| 18 | |
| 19 | import concurrent.futures |
| 20 | import json |
| 21 | import threading |
| 22 | import time |
| 23 | from pathlib import Path |
| 24 | from unittest import mock |
| 25 | |
| 26 | import pytest |
| 27 | |
| 28 | from lib import ( |
| 29 | http, |
| 30 | normalize, |
| 31 | reddit_arctic, |
| 32 | reddit_discover, |
| 33 | reddit_hydrate, |
| 34 | reddit_keyless, |
| 35 | reddit_refs, |
| 36 | reddit_search, |
| 37 | reddit_shreddit, |
| 38 | render, |
| 39 | schema, |
| 40 | ) |
| 41 | |
| 42 | FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" |
| 43 | CHALLENGE_HTML = (FIXTURES / "reddit_search_challenge.html").read_text(encoding="utf-8") |
| 44 | SEARCH_PAGE1_HTML = (FIXTURES / "reddit_search_page1.html").read_text(encoding="utf-8") |
| 45 | SHREDDIT_HTML = (FIXTURES / "reddit_shreddit_comments_sample.html").read_text(encoding="utf-8") |
| 46 | |
| 47 | |
| 48 | @pytest.fixture(autouse=True) |
| 49 | def _clean_reddit_state(): |
| 50 | """Exercise real module logic with clean per-run memos and state.""" |
| 51 | http.reset_reddit_keyless_memo() |
| 52 | reddit_arctic.reset_memo() |
| 53 | reddit_search.reset_run_state() |
| 54 | reddit_discover.reset_run_state() |
| 55 | yield |
| 56 | http.reset_reddit_keyless_memo() |
| 57 | reddit_arctic.reset_memo() |
| 58 | reddit_search.reset_run_state() |
| 59 | reddit_discover.reset_run_state() |
| 60 | |
| 61 | |
| 62 | @pytest.fixture(autouse=True) |
| 63 | def _no_arctic_network(): |
| 64 | """Override conftest's stub so arctic tests exercise real functions.""" |
| 65 | yield |
| 66 | |
| 67 | |
| 68 | @pytest.fixture(autouse=True) |
| 69 | def _no_reddit_web_floor(): |
| 70 | """Override conftest's stub so web floor tests exercise real logic.""" |
| 71 | yield |
| 72 | |
| 73 | |
| 74 | @pytest.fixture(autouse=True) |
| 75 | def _no_reddit_kept_thread_comments(): |
| 76 | """Override conftest's stub so enrich_source_items tests run real logic.""" |
| 77 | yield |
| 78 | |
| 79 | |
| 80 | def _shreddit_comment_html( |
| 81 | author: str, |
| 82 | thing_id: str, |
| 83 | score: int, |
| 84 | body: str, |
| 85 | extra_attrs: str = "", |
| 86 | ) -> str: |
| 87 | attrs = f" {extra_attrs.strip()}" if extra_attrs.strip() else "" |
| 88 | return ( |
| 89 | f'<shreddit-comment created="2026-10-10T10:00:00+0000" author="{author}" ' |
| 90 | f'thingId="{thing_id}" depth="0" permalink="/r/test/comments/abc123/comment/{thing_id}/" ' |
| 91 | f'score="{score}"{attrs}>' |
| 92 | f'<div id="{thing_id}-post-rtjson-content"><p>{body}</p></div>' |
| 93 | f"</shreddit-comment>" |
| 94 | ) |
| 95 | |
| 96 | |
| 97 | def _search_page_html(post_id: str, author: str | None = None, cursor: str | None = None) -> str: |
| 98 | ctx: dict = { |
| 99 | "action_info": {"type": "post"}, |
| 100 | "post": {"id": f"t3_{post_id}", "title": f"Ghostty topic {post_id}"}, |
| 101 | "subreddit": {"name": "ghostty"}, |
| 102 | } |
| 103 | if author is not None: |
| 104 | ctx["profile"] = {"id": "t2_author1", "name": author} |
| 105 | encoded = json.dumps(ctx).replace('"', """) |
| 106 | parts = [ |
| 107 | f'<search-telemetry-tracker data-faceplate-tracking-context="{encoded}" ' |
| 108 | f'view-events="search/view/post">' |
| 109 | f'<h2><a data-testid="post-title" href="/r/ghostty/comments/{post_id}/slug/">' |
| 110 | f"Ghostty topic {post_id}</a></h2>" |
| 111 | f"</search-telemetry-tracker>" |
| 112 | f'<faceplate-timeago ts="2026-10-10T10:00:00.000000+0000"></faceplate-timeago>' |
| 113 | f'<div data-testid="search-counter-row">' |
| 114 | f'<span><faceplate-number number="42" pretty></faceplate-number> votes</span>' |
| 115 | f'<span><faceplate-number number="9" pretty></faceplate-number> comments</span>' |
| 116 | f"</div>", |
| 117 | ] |
| 118 | if cursor: |
| 119 | parts.append( |
| 120 | f'<faceplate-partial loading="lazy" ' |
| 121 | f'src="/svc/shreddit/search/?q=ghostty&type=posts&cursor={cursor}">' |
| 122 | f"</faceplate-partial>" |
| 123 | ) |
| 124 | return "<html><body>" + "".join(parts) + "</body></html>" |
| 125 | |
| 126 | |
| 127 | # --------------------------------------------------------------------------- |
| 128 | # HIGH-111: OP (`is_submitter` / `is_uploader`) preservation across all paths |
| 129 | # --------------------------------------------------------------------------- |
| 130 | |
| 131 | |
| 132 | class TestHigh111OpCommentFiltering: |
| 133 | def test_arctic_comment_tree_and_post_comments_propagate_is_submitter(self): |
| 134 | rows = [ |
| 135 | { |
| 136 | "kind": "t1", |
| 137 | "data": { |
| 138 | "id": "c_op", |
| 139 | "author": "ThreadStarter", |
| 140 | "body": "OP clarification comment", |
| 141 | "score": 120, |
| 142 | "created_utc": 1783000000, |
| 143 | "permalink": "/r/test/comments/abc123/x/c_op/", |
| 144 | "depth": 0, |
| 145 | "is_submitter": True, |
| 146 | }, |
| 147 | }, |
| 148 | { |
| 149 | "kind": "t1", |
| 150 | "data": { |
| 151 | "id": "c_user", |
| 152 | "author": "CommunityReader", |
| 153 | "body": "Community feedback comment", |
| 154 | "score": 80, |
| 155 | "created_utc": 1783000000, |
| 156 | "permalink": "/r/test/comments/abc123/x/c_user/", |
| 157 | "depth": 0, |
| 158 | "is_submitter": False, |
| 159 | }, |
| 160 | }, |
| 161 | { |
| 162 | "kind": "t1", |
| 163 | "data": { |
| 164 | "id": "c_nonbool", |
| 165 | "author": "OtherReader", |
| 166 | "body": "Comment without boolean is_submitter", |
| 167 | "score": 10, |
| 168 | "created_utc": 1783000000, |
| 169 | "permalink": "/r/test/comments/abc123/x/c_nonbool/", |
| 170 | "depth": 0, |
| 171 | "is_submitter": "true", |
| 172 | }, |
| 173 | }, |
| 174 | ] |
| 175 | with mock.patch.object(reddit_arctic.http, "get", return_value={"data": rows}): |
| 176 | tree = reddit_arctic.fetch_comment_tree("abc123") |
| 177 | fallback = reddit_arctic.fetch_post_comments("abc123") |
| 178 | |
| 179 | assert tree is not None |
| 180 | by_author_tree = {c["author"]: c for c in tree} |
| 181 | assert by_author_tree["ThreadStarter"]["is_uploader"] is True |
| 182 | assert by_author_tree["CommunityReader"]["is_uploader"] is False |
| 183 | assert "is_uploader" not in by_author_tree["OtherReader"] |
| 184 | |
| 185 | by_author_fb = {c["author"]: c for c in fallback} |
| 186 | assert by_author_fb["ThreadStarter"]["is_uploader"] is True |
| 187 | assert by_author_fb["CommunityReader"]["is_uploader"] is False |
| 188 | assert "is_uploader" not in by_author_fb["OtherReader"] |
| 189 | |
| 190 | def test_shreddit_fetch_comments_preserves_arctic_is_uploader_flag(self): |
| 191 | arctic_rows = [ |
| 192 | { |
| 193 | "score": 95, |
| 194 | "date": "2026-10-10", |
| 195 | "author": "ThreadStarter", |
| 196 | "body": "OP note from archive", |
| 197 | "excerpt": "OP note from archive", |
| 198 | "permalink": "/r/test/comments/abc123/x/c1/", |
| 199 | "url": "https://reddit.com/r/test/comments/abc123/x/c1/", |
| 200 | "depth": 0, |
| 201 | "is_uploader": True, |
| 202 | }, |
| 203 | { |
| 204 | "score": 50, |
| 205 | "date": "2026-10-10", |
| 206 | "author": "CommunityUser", |
| 207 | "body": "Real community reply", |
| 208 | "excerpt": "Real community reply", |
| 209 | "permalink": "/r/test/comments/abc123/x/c2/", |
| 210 | "url": "https://reddit.com/r/test/comments/abc123/x/c2/", |
| 211 | "depth": 0, |
| 212 | "is_uploader": False, |
| 213 | }, |
| 214 | ] |
| 215 | url = "https://www.reddit.com/r/test/comments/abc123/slug/" |
| 216 | with mock.patch.object(reddit_shreddit.http, "reddit_keyless_get_text", return_value=None), \ |
| 217 | mock.patch.object(reddit_shreddit.reddit_arctic, "fetch_post_comments", return_value=arctic_rows): |
| 218 | out = reddit_shreddit.fetch_comments(url) |
| 219 | |
| 220 | marks = {c["author"]: c["is_uploader"] for c in out["top_comments"]} |
| 221 | assert marks == {"ThreadStarter": True, "CommunityUser": False} |
| 222 | |
| 223 | def test_shreddit_parse_and_fetch_handle_html_op_attr_and_post_author(self): |
| 224 | html_with_attr = ( |
| 225 | '<shreddit-comment-tree-stats total-comments="2"></shreddit-comment-tree-stats>' |
| 226 | + _shreddit_comment_html("OpUser", "t1_op", 200, "OP reply", extra_attrs="is-op") |
| 227 | + _shreddit_comment_html("Reader1", "t1_u1", 50, "Reader reply", extra_attrs='is-op="false"') |
| 228 | ) |
| 229 | parsed = reddit_shreddit.parse_comments(html_with_attr) |
| 230 | assert {c["author"]: c["is_uploader"] for c in parsed} == { |
| 231 | "OpUser": True, |
| 232 | "Reader1": False, |
| 233 | } |
| 234 | |
| 235 | html_no_attr = ( |
| 236 | '<shreddit-comment-tree-stats total-comments="2"></shreddit-comment-tree-stats>' |
| 237 | + _shreddit_comment_html("OpUser", "t1_op", 200, "OP reply without attr") |
| 238 | + _shreddit_comment_html("Reader1", "t1_u1", 50, "Reader reply without attr") |
| 239 | ) |
| 240 | url = "https://www.reddit.com/r/test/comments/abc123/slug/" |
| 241 | with mock.patch.object(reddit_shreddit.http, "get_text", return_value=html_no_attr): |
| 242 | out = reddit_shreddit.fetch_comments(url, post_author="opuser") |
| 243 | assert {c["author"]: c["is_uploader"] for c in out["top_comments"]} == { |
| 244 | "OpUser": True, |
| 245 | "Reader1": False, |
| 246 | } |
| 247 | |
| 248 | # Deleted/removed post author must not stamp false is_uploader values. |
| 249 | http.reset_reddit_keyless_memo() |
| 250 | with mock.patch.object(reddit_shreddit.http, "get_text", return_value=html_no_attr): |
| 251 | out_deleted = reddit_shreddit.fetch_comments(url, post_author="[deleted]") |
| 252 | assert all("is_uploader" not in c for c in out_deleted["top_comments"]) |
| 253 | |
| 254 | def test_reddit_search_parse_page_extracts_profile_author(self): |
| 255 | posts, _ = reddit_search.parse_page(SEARCH_PAGE1_HTML, "ButcherBox") |
| 256 | assert posts[0]["author"] == "grassyglassy" |
| 257 | assert posts[1]["author"] == "Altruistic_Echidna86" |
| 258 | |
| 259 | no_profile, _ = reddit_search.parse_page(_search_page_html("p999", author=None), "ghostty") |
| 260 | assert no_profile[0]["author"] == "" |
| 261 | |
| 262 | def test_lane_and_post_ranking_enrichment_filter_op_comments_in_render(self): |
| 263 | html_no_attr = ( |
| 264 | '<shreddit-comment-tree-stats total-comments="2"></shreddit-comment-tree-stats>' |
| 265 | + _shreddit_comment_html("RealOP", "t1_op", 500, "My own OP follow-up on Ghostty") |
| 266 | + _shreddit_comment_html("CommunityFan", "t1_fan", 75, "Great community take on Ghostty") |
| 267 | ) |
| 268 | post = { |
| 269 | "id": "R1", |
| 270 | "title": "Ghostty benchmark thread", |
| 271 | "url": "https://www.reddit.com/r/ghostty/comments/abc123/slug/", |
| 272 | "score": 150, |
| 273 | "num_comments": 2, |
| 274 | "subreddit": "ghostty", |
| 275 | "author": "RealOP", |
| 276 | "selftext": "", |
| 277 | "date": "2026-10-10", |
| 278 | "engagement": {"score": 150, "num_comments": 2}, |
| 279 | "relevance": 0.9, |
| 280 | "metadata": {"post_id": "abc123"}, |
| 281 | } |
| 282 | |
| 283 | # Path 1: lane-time _enrich stamps OP before normalization. |
| 284 | with mock.patch.object(reddit_shreddit.http, "get_text", return_value=html_no_attr): |
| 285 | enriched_posts = reddit_keyless._enrich([dict(post)], "quick") |
| 286 | [norm_lane] = normalize.normalize_source_items("reddit", enriched_posts, "2026-10-01", "2026-10-31") |
| 287 | assert norm_lane.author is None |
| 288 | assert norm_lane.metadata["post_author"] == "RealOP" |
| 289 | quotable_lane = [ |
| 290 | c for c in norm_lane.metadata["top_comments"] |
| 291 | if render._is_community_comment(norm_lane, c, c.get("excerpt", "")) |
| 292 | ] |
| 293 | assert [c["author"] for c in quotable_lane] == ["CommunityFan"] |
| 294 | |
| 295 | # Path 2: post-normalization enrich_source_items preserves OP filtering via metadata["post_author"]. |
| 296 | http.reset_reddit_keyless_memo() |
| 297 | [norm_empty] = normalize.normalize_source_items("reddit", [dict(post)], "2026-10-01", "2026-10-31") |
| 298 | assert norm_empty.author is None |
| 299 | assert norm_empty.metadata["post_author"] == "RealOP" |
| 300 | with mock.patch.object(reddit_shreddit.http, "get_text", return_value=html_no_attr): |
| 301 | reddit_keyless.enrich_source_items([norm_empty], depth="quick") |
| 302 | quotable_final = [ |
| 303 | c for c in norm_empty.metadata["top_comments"] |
| 304 | if render._is_community_comment(norm_empty, c, c.get("excerpt", "")) |
| 305 | ] |
| 306 | assert [c["author"] for c in quotable_final] == ["CommunityFan"] |
| 307 | |
| 308 | |
| 309 | # --------------------------------------------------------------------------- |
| 310 | # HIGH-115: Synchronized WebFloor updates and snapshots under _within timeout |
| 311 | # --------------------------------------------------------------------------- |
| 312 | |
| 313 | |
| 314 | class TestHigh115WebFloorThreadSafety: |
| 315 | def test_web_floor_concurrent_mutations_and_snapshots_never_raise(self): |
| 316 | floor = reddit_discover.WebFloor() |
| 317 | stop = threading.Event() |
| 318 | errors: list[BaseException] = [] |
| 319 | |
| 320 | def writer(): |
| 321 | try: |
| 322 | for i in range(400): |
| 323 | ref = reddit_refs.canonical_thread( |
| 324 | f"https://www.reddit.com/r/ghostty/comments/p{i:04d}/" |
| 325 | ) |
| 326 | assert ref is not None |
| 327 | floor.record_query( |
| 328 | f"query-{i}", |
| 329 | {f"rung_{i % 25}": "ok"}, |
| 330 | [*floor.snapshot().refs[-10:], ref], |
| 331 | ) |
| 332 | floor.record_rung(f"extra_{i % 30}", "empty") |
| 333 | floor.add_refs([ref]) |
| 334 | except BaseException as exc: |
| 335 | errors.append(exc) |
| 336 | finally: |
| 337 | stop.set() |
| 338 | |
| 339 | t = threading.Thread(target=writer) |
| 340 | t.start() |
| 341 | snapshots = 0 |
| 342 | try: |
| 343 | while not stop.is_set() or snapshots < 20: |
| 344 | snap = floor.snapshot() |
| 345 | assert isinstance(snap.rungs, dict) |
| 346 | assert isinstance(snap.refs, list) |
| 347 | assert isinstance(snap.queries, list) |
| 348 | snapshots += 1 |
| 349 | except BaseException as exc: |
| 350 | errors.append(exc) |
| 351 | t.join(timeout=5) |
| 352 | assert errors == [] |
| 353 | |
| 354 | def test_web_floor_timeout_salvages_partial_refs_while_worker_still_writes(self): |
| 355 | first_ref = reddit_refs.canonical_thread("https://www.reddit.com/r/ghostty/comments/salv1/") |
| 356 | assert first_ref is not None |
| 357 | first_ref.provenance.add("web") |
| 358 | first_ref.title = "Ghostty salvaged thread" |
| 359 | |
| 360 | started_mutating = threading.Event() |
| 361 | stop_worker = threading.Event() |
| 362 | |
| 363 | def slow_mutating_web_refs(topic, *, floor=None, **_kwargs): |
| 364 | assert floor is not None |
| 365 | floor.record_query(f"site:reddit.com {topic}", {"brave": "ok"}, [first_ref]) |
| 366 | started_mutating.set() |
| 367 | i = 0 |
| 368 | while not stop_worker.is_set() and i < 2000: |
| 369 | floor.record_rung(f"dyn_{i}", "ok") |
| 370 | i += 1 |
| 371 | time.sleep(0.0005) |
| 372 | return floor |
| 373 | |
| 374 | archived = { |
| 375 | "id": "", |
| 376 | "title": "Ghostty salvaged thread", |
| 377 | "url": "https://www.reddit.com/r/ghostty/comments/salv1/slug/", |
| 378 | "score": 50, |
| 379 | "num_comments": 5, |
| 380 | "subreddit": "ghostty", |
| 381 | "created_utc": 1700000000, |
| 382 | "author": "op", |
| 383 | "selftext": "", |
| 384 | "date": "2026-10-10", |
| 385 | "engagement": {"score": 50, "num_comments": 5}, |
| 386 | "relevance": 0.8, |
| 387 | "why_relevant": "Reddit listing (arctic-shift)", |
| 388 | "metadata": {"post_id": "salv1"}, |
| 389 | } |
| 390 | |
| 391 | def fake_within(wait_until, stage, default, call, *args, **kwargs): |
| 392 | if stage == "web floor": |
| 393 | t = threading.Thread(target=call, args=args, kwargs=kwargs) |
| 394 | t.start() |
| 395 | assert started_mutating.wait(timeout=3.0) |
| 396 | return default |
| 397 | return call(*args, **kwargs) |
| 398 | |
| 399 | try: |
| 400 | with mock.patch.object(reddit_keyless, "_within", side_effect=fake_within), \ |
| 401 | mock.patch.object(reddit_keyless.reddit_discover, "web_refs", side_effect=slow_mutating_web_refs), \ |
| 402 | mock.patch.object( |
| 403 | reddit_keyless.reddit_arctic, "fetch_posts_by_ids", |
| 404 | return_value=({"salv1": dict(archived)}, "ok"), |
| 405 | ), \ |
| 406 | mock.patch.object(reddit_keyless.reddit_arctic, "fetch_comment_tree", return_value=[]): |
| 407 | kept = reddit_keyless._web_floor( |
| 408 | "Ghostty", "quick", None, None, "2026-10-01", "2026-10-31", |
| 409 | deadline=time.monotonic() + 30.0, |
| 410 | ) |
| 411 | finally: |
| 412 | stop_worker.set() |
| 413 | |
| 414 | assert [p["metadata"]["post_id"] for p in kept] == ["salv1"] |
| 415 | |
| 416 | |
| 417 | # --------------------------------------------------------------------------- |
| 418 | # HIGH-116: Abandoned _enrich workers never mutate returned post dicts |
| 419 | # --------------------------------------------------------------------------- |
| 420 | |
| 421 | |
| 422 | class TestHigh116EnrichMainThreadOnlyMutation: |
| 423 | def test_enrich_one_does_not_mutate_post_in_place(self): |
| 424 | post = { |
| 425 | "url": "https://www.reddit.com/r/test/comments/abc123/slug/", |
| 426 | "author": "op", |
| 427 | "num_comments": 0, |
| 428 | "engagement": {"score": 10, "num_comments": 0}, |
| 429 | } |
| 430 | payload = { |
| 431 | "top_comments": [{"score": 12, "author": "reader", "excerpt": "nice", "url": "", "depth": 0}], |
| 432 | "comment_insights": ["nice"], |
| 433 | "num_comments": 25, |
| 434 | } |
| 435 | with mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments", return_value=payload): |
| 436 | returned = reddit_keyless._enrich_one(post) |
| 437 | assert returned == payload |
| 438 | assert "top_comments" not in post |
| 439 | assert post["num_comments"] == 0 |
| 440 | assert post["engagement"]["num_comments"] == 0 |
| 441 | |
| 442 | def test_abandoned_worker_finishing_after_timeout_never_mutates_returned_post(self, monkeypatch): |
| 443 | monkeypatch.setattr(reddit_keyless, "MIN_STAGE_SECONDS", 0.05) |
| 444 | release = threading.Event() |
| 445 | slow_finished = threading.Event() |
| 446 | |
| 447 | def fetch(url, deadline=None, post_author=None): |
| 448 | if "slow02" in url: |
| 449 | release.wait(timeout=5.0) |
| 450 | slow_finished.set() |
| 451 | return { |
| 452 | "top_comments": [{"score": 99, "author": "late", "excerpt": "too late", "url": "", "depth": 0}], |
| 453 | "comment_insights": ["late insight"], |
| 454 | "num_comments": 999, |
| 455 | } |
| 456 | return { |
| 457 | "top_comments": [{"score": 15, "author": "fast_user", "excerpt": "fast comment", "url": "", "depth": 0}], |
| 458 | "comment_insights": ["fast insight"], |
| 459 | "num_comments": 15, |
| 460 | } |
| 461 | |
| 462 | fast_post = { |
| 463 | "url": "https://www.reddit.com/r/test/comments/fast01/slug/", |
| 464 | "author": "op1", |
| 465 | "num_comments": 1, |
| 466 | "engagement": {"score": 10, "num_comments": 1}, |
| 467 | } |
| 468 | slow_post = { |
| 469 | "url": "https://www.reddit.com/r/test/comments/slow02/slug/", |
| 470 | "author": "op2", |
| 471 | "num_comments": 1, |
| 472 | "engagement": {"score": 10, "num_comments": 1}, |
| 473 | } |
| 474 | with mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments", side_effect=fetch): |
| 475 | result = reddit_keyless._enrich( |
| 476 | [fast_post, slow_post], "quick", lane_deadline=time.monotonic() + 0.15, |
| 477 | ) |
| 478 | |
| 479 | # Fast post was enriched on the main thread; slow post was timed out. |
| 480 | assert result[0]["num_comments"] == 15 |
| 481 | assert result[0]["top_comments"][0]["author"] == "fast_user" |
| 482 | assert "top_comments" not in result[1] |
| 483 | assert result[1]["num_comments"] == 1 |
| 484 | |
| 485 | # Let the abandoned worker complete and prove it cannot mutate slow_post. |
| 486 | release.set() |
| 487 | assert slow_finished.wait(timeout=3.0) |
| 488 | time.sleep(0.05) |
| 489 | assert "top_comments" not in result[1] |
| 490 | assert "comment_insights" not in result[1] |
| 491 | assert result[1]["num_comments"] == 1 |
| 492 | assert result[1]["engagement"]["num_comments"] == 1 |
| 493 | |
| 494 | |
| 495 | # --------------------------------------------------------------------------- |
| 496 | # HIGH-117: Thread-isolated last_tree_throttled & locked/deduped fetch_scores |
| 497 | # --------------------------------------------------------------------------- |
| 498 | |
| 499 | |
| 500 | class TestHigh117ArcticThreadSafety: |
| 501 | def test_concurrent_comment_tree_throttles_do_not_bleed_across_threads(self): |
| 502 | a_done = threading.Event() |
| 503 | b_done = threading.Event() |
| 504 | |
| 505 | def fake_get(url, **_kwargs): |
| 506 | if "t3_throttled1" in url: |
| 507 | raise http.HTTPError("HTTP 422: slow down", status_code=422) |
| 508 | if "t3_error2" in url: |
| 509 | raise http.HTTPError("HTTP 500: boom", status_code=500) |
| 510 | return {"data": []} |
| 511 | |
| 512 | def thread_a(): |
| 513 | item = { |
| 514 | "metadata": {"post_id": "throttled1"}, |
| 515 | "engagement": {"score": 20, "num_comments": 5}, |
| 516 | "engagement_source": reddit_refs.ARCTIC, |
| 517 | } |
| 518 | filled, failed, throttled = reddit_hydrate._attach_comments( |
| 519 | [item], "quick", deadline=time.monotonic() + 10.0, now=1800000000.0, |
| 520 | ) |
| 521 | a_done.set() |
| 522 | assert b_done.wait(timeout=3.0) |
| 523 | # Even after thread B failed with HTTP 500, thread A's thread-local |
| 524 | # throttle flag must remain True. |
| 525 | return filled, failed, throttled, reddit_arctic.last_tree_throttled |
| 526 | |
| 527 | def thread_b(): |
| 528 | assert a_done.wait(timeout=3.0) |
| 529 | item = { |
| 530 | "metadata": {"post_id": "error2"}, |
| 531 | "engagement": {"score": 20, "num_comments": 5}, |
| 532 | "engagement_source": reddit_refs.ARCTIC, |
| 533 | } |
| 534 | filled, failed, throttled = reddit_hydrate._attach_comments( |
| 535 | [item], "quick", deadline=time.monotonic() + 10.0, now=1800000000.0, |
| 536 | ) |
| 537 | b_done.set() |
| 538 | return filled, failed, throttled, reddit_arctic.last_tree_throttled |
| 539 | |
| 540 | with mock.patch.object(reddit_arctic.http, "get", side_effect=fake_get), \ |
| 541 | mock.patch.object(reddit_arctic.time, "sleep"): |
| 542 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 543 | f_throttled = pool.submit(thread_a) |
| 544 | f_error = pool.submit(thread_b) |
| 545 | res_throttled = f_throttled.result(timeout=5.0) |
| 546 | res_error = f_error.result(timeout=5.0) |
| 547 | |
| 548 | assert res_throttled == (0, 1, 1, True) |
| 549 | assert res_error == (0, 1, 0, False) |
| 550 | |
| 551 | def test_fetch_scores_coalesces_concurrent_requests_and_respects_waiter_deadline(self): |
| 552 | started = threading.Event() |
| 553 | release = threading.Event() |
| 554 | calls: list[str] = [] |
| 555 | calls_lock = threading.Lock() |
| 556 | |
| 557 | def slow_get(url, **_kwargs): |
| 558 | with calls_lock: |
| 559 | calls.append(url) |
| 560 | started.set() |
| 561 | release.wait(timeout=5.0) |
| 562 | return { |
| 563 | "data": [ |
| 564 | {"id": "p1", "score": 111, "num_comments": 12}, |
| 565 | {"id": "p2", "score": 222, "num_comments": 24}, |
| 566 | ] |
| 567 | } |
| 568 | |
| 569 | with mock.patch.object(reddit_arctic.http, "get", side_effect=slow_get): |
| 570 | with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: |
| 571 | f_owner = pool.submit(reddit_arctic.fetch_scores, ["p1", "p2"]) |
| 572 | assert started.wait(timeout=3.0) |
| 573 | # Waiter with generous deadline coalesces on owner's single request. |
| 574 | f_waiter_ok = pool.submit( |
| 575 | reddit_arctic.fetch_scores, ["p1", "p2"], time.monotonic() + 5.0, |
| 576 | ) |
| 577 | # Waiter with short deadline returns promptly without blocking. |
| 578 | t0 = time.monotonic() |
| 579 | timed_out = reddit_arctic.fetch_scores(["p1"], deadline=time.monotonic() + 0.08) |
| 580 | elapsed = time.monotonic() - t0 |
| 581 | assert timed_out == {} |
| 582 | assert elapsed < 1.0 |
| 583 | |
| 584 | release.set() |
| 585 | owner_res = f_owner.result(timeout=5.0) |
| 586 | waiter_res = f_waiter_ok.result(timeout=5.0) |
| 587 | |
| 588 | assert len(calls) == 1 |
| 589 | assert owner_res == waiter_res == { |
| 590 | "p1": {"score": 111, "num_comments": 12}, |
| 591 | "p2": {"score": 222, "num_comments": 24}, |
| 592 | } |
| 593 | assert reddit_arctic._score_inflight == {} |
| 594 | |
| 595 | def test_fetch_scores_failure_does_not_poison_cache_or_leak_inflight(self): |
| 596 | attempts = {"n": 0} |
| 597 | |
| 598 | def flaky_get(url, **_kwargs): |
| 599 | attempts["n"] += 1 |
| 600 | if attempts["n"] == 1: |
| 601 | raise http.HTTPError("HTTP 503", status_code=503) |
| 602 | return {"data": [{"id": "p9", "score": 77, "num_comments": 4}]} |
| 603 | |
| 604 | with mock.patch.object(reddit_arctic.http, "get", side_effect=flaky_get): |
| 605 | assert reddit_arctic.fetch_scores(["p9"]) == {} |
| 606 | assert "p9" not in reddit_arctic._cache |
| 607 | assert reddit_arctic._score_inflight == {} |
| 608 | assert reddit_arctic.fetch_scores(["p9"]) == {"p9": {"score": 77, "num_comments": 4}} |
| 609 | |
| 610 | |
| 611 | # --------------------------------------------------------------------------- |
| 612 | # HIGH-119: Shreddit comment fetch deadline, retries=1, challenge & 0-comment |
| 613 | # --------------------------------------------------------------------------- |
| 614 | |
| 615 | |
| 616 | class TestHigh119ShredditFetchHardening: |
| 617 | URL = "https://www.reddit.com/r/Rakuten/comments/1taeiw0/title/" |
| 618 | |
| 619 | def test_expired_deadline_skips_both_shreddit_and_arctic(self): |
| 620 | for url in (self.URL, "https://www.reddit.com/comments/1taeiw0/"): |
| 621 | with mock.patch.object(reddit_shreddit.http, "reddit_keyless_get_text") as shreddit_get, \ |
| 622 | mock.patch.object(reddit_shreddit.reddit_arctic, "fetch_post_comments") as arctic_fetch: |
| 623 | out = reddit_shreddit.fetch_comments(url, deadline=time.monotonic() - 1.0) |
| 624 | assert out == {"top_comments": [], "comment_insights": [], "num_comments": None} |
| 625 | shreddit_get.assert_not_called() |
| 626 | arctic_fetch.assert_not_called() |
| 627 | |
| 628 | def test_uses_retries_1_and_clamps_timeout_to_deadline(self): |
| 629 | seen_kwargs: dict = {} |
| 630 | |
| 631 | def fake_get_text(url, **kwargs): |
| 632 | seen_kwargs.update(kwargs) |
| 633 | return SHREDDIT_HTML |
| 634 | |
| 635 | with mock.patch.object(reddit_shreddit.http, "get_text", side_effect=fake_get_text), \ |
| 636 | mock.patch.object(reddit_shreddit.time, "monotonic", return_value=1000.0): |
| 637 | out = reddit_shreddit.fetch_comments(self.URL, timeout=12, deadline=1003.5) |
| 638 | |
| 639 | assert out["top_comments"] |
| 640 | assert seen_kwargs["retries"] == 1 |
| 641 | assert seen_kwargs["timeout"] == pytest.approx(3.5) |
| 642 | assert seen_kwargs["deadline_monotonic"] == 1003.5 |
| 643 | |
| 644 | def test_forwards_deadline_monotonic_when_transport_supports_it(self): |
| 645 | seen: dict = {} |
| 646 | |
| 647 | def fake_keyless_get(url, timeout=12, retries=1, accept="*/*", headers=None, |
| 648 | validate=None, deadline_monotonic=None): |
| 649 | seen.update( |
| 650 | timeout=timeout, |
| 651 | retries=retries, |
| 652 | validate=validate, |
| 653 | deadline_monotonic=deadline_monotonic, |
| 654 | ) |
| 655 | return SHREDDIT_HTML |
| 656 | |
| 657 | with mock.patch.object(reddit_shreddit.http, "reddit_keyless_get_text", side_effect=fake_keyless_get), \ |
| 658 | mock.patch.object(reddit_shreddit.time, "monotonic", return_value=500.0): |
| 659 | out = reddit_shreddit.fetch_comments(self.URL, deadline=504.0) |
| 660 | |
| 661 | assert out["top_comments"] |
| 662 | assert seen["retries"] == 1 |
| 663 | assert seen["timeout"] == pytest.approx(4.0) |
| 664 | assert seen["deadline_monotonic"] == 504.0 |
| 665 | assert callable(seen["validate"]) |
| 666 | |
| 667 | def test_challenge_page_is_rejected_not_memoized_and_allows_fallback(self): |
| 668 | bodies = [CHALLENGE_HTML, SHREDDIT_HTML] |
| 669 | |
| 670 | def fake_get_text(url, **_kwargs): |
| 671 | return bodies.pop(0) |
| 672 | |
| 673 | with mock.patch.object(reddit_shreddit.http, "get_text", side_effect=fake_get_text) as gt, \ |
| 674 | mock.patch.object(reddit_shreddit.reddit_arctic, "fetch_post_comments", return_value=[]) as arctic, \ |
| 675 | http.capture_failures() as failures: |
| 676 | first = reddit_shreddit.fetch_comments(self.URL) |
| 677 | second = reddit_shreddit.fetch_comments(self.URL) |
| 678 | |
| 679 | assert first["top_comments"] == [] |
| 680 | assert arctic.call_count == 1 # fell back after challenge rejection |
| 681 | assert len(failures) == 1 |
| 682 | assert "challenge" in str(failures[0]).lower() |
| 683 | assert second["top_comments"] # second call fetched fresh, not memoized challenge HTML |
| 684 | assert gt.call_count == 2 |
| 685 | |
| 686 | def test_zero_comment_shreddit_page_skips_arctic_fallback(self): |
| 687 | zero_html = '<shreddit-comment-tree-stats total-comments="0"></shreddit-comment-tree-stats>' |
| 688 | with mock.patch.object(reddit_shreddit.http, "get_text", return_value=zero_html), \ |
| 689 | mock.patch.object(reddit_shreddit.reddit_arctic, "fetch_post_comments") as arctic: |
| 690 | out = reddit_shreddit.fetch_comments(self.URL) |
| 691 | |
| 692 | assert out == {"top_comments": [], "comment_insights": [], "num_comments": 0} |
| 693 | arctic.assert_not_called() |
| 694 | |
| 695 | |
| 696 | # --------------------------------------------------------------------------- |
| 697 | # HIGH-123: reddit_search waiter deadline, no election fallthrough, stream cap |
| 698 | # --------------------------------------------------------------------------- |
| 699 | |
| 700 | |
| 701 | class TestHigh123SearchDeadlinesAndElection: |
| 702 | def test_waiter_respects_deadline_and_never_falls_through_uncached(self): |
| 703 | started = threading.Event() |
| 704 | release = threading.Event() |
| 705 | uncached_calls = {"n": 0} |
| 706 | lock = threading.Lock() |
| 707 | |
| 708 | def slow_uncached(*args, **kwargs): |
| 709 | with lock: |
| 710 | uncached_calls["n"] += 1 |
| 711 | started.set() |
| 712 | release.wait(timeout=5.0) |
| 713 | return [{"id": "R1", "url": "https://www.reddit.com/r/ghostty/comments/p1/"}], True |
| 714 | |
| 715 | with mock.patch.object(reddit_search, "_search_uncached_with_status", side_effect=slow_uncached): |
| 716 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 717 | f_owner = pool.submit(reddit_search.search, "Ghostty", depth="deep", subreddits=["a", "b", "c"]) |
| 718 | assert started.wait(timeout=3.0) |
| 719 | |
| 720 | t0 = time.monotonic() |
| 721 | waiter_res = reddit_search.search( |
| 722 | "Ghostty", depth="deep", subreddits=["a", "b", "c"], |
| 723 | deadline=time.monotonic() + 0.1, |
| 724 | ) |
| 725 | elapsed = time.monotonic() - t0 |
| 726 | assert waiter_res == [] |
| 727 | assert elapsed < 1.0 |
| 728 | # Waiter must NOT have fallen through to _search_uncached! |
| 729 | assert uncached_calls["n"] == 1 |
| 730 | |
| 731 | release.set() |
| 732 | owner_res = f_owner.result(timeout=5.0) |
| 733 | assert len(owner_res) == 1 |
| 734 | |
| 735 | def test_election_loop_without_owner_returns_empty_instead_of_stampeding(self): |
| 736 | # Pre-seed an inflight slot that never finishes across both election |
| 737 | # rounds: waiter must return [] instead of running uncached without |
| 738 | # holding _run_inflight[key]. |
| 739 | key = ("Ghostty", "quick", "month", ()) |
| 740 | stuck_slot = reddit_search._InflightSearch() |
| 741 | with reddit_search._run_lock: |
| 742 | reddit_search._run_inflight[key] = stuck_slot |
| 743 | |
| 744 | with mock.patch.object(reddit_search, "_result_timeout", return_value=0.02), \ |
| 745 | mock.patch.object(reddit_search, "_search_uncached_with_status") as uncached: |
| 746 | out = reddit_search.search("Ghostty", depth="quick") |
| 747 | |
| 748 | assert out == [] |
| 749 | uncached.assert_not_called() |
| 750 | |
| 751 | def test_search_stream_stops_paging_at_deadline_and_clamps_timeout(self): |
| 752 | pages_fetched: list[tuple[str, float]] = [] |
| 753 | clock = [100.0] |
| 754 | |
| 755 | def fake_retry_get(url, **kwargs): |
| 756 | pages_fetched.append((url, kwargs["timeout"])) |
| 757 | # First page takes 4 seconds, pushing clock past deadline 103.0. |
| 758 | clock[0] += 4.0 |
| 759 | return _search_page_html(f"p{len(pages_fetched)}", author="alice", cursor=f"cur{len(pages_fetched)}"), None |
| 760 | |
| 761 | with mock.patch.object(reddit_search.http, "reddit_keyless_get_text_retry_429", side_effect=fake_retry_get), \ |
| 762 | mock.patch.object(reddit_search.time, "monotonic", side_effect=lambda: clock[0]): |
| 763 | posts = reddit_search._search_stream( |
| 764 | "ghostty", "month", max_pages=8, deadline=103.0, |
| 765 | ) |
| 766 | |
| 767 | assert len(pages_fetched) == 1 |
| 768 | assert pages_fetched[0][1] == pytest.approx(3.0) |
| 769 | assert [p["metadata"]["post_id"] for p in posts] == ["p1"] |
| 770 | assert posts[0]["author"] == "alice" |
| 771 | |
| 772 | |
| 773 | # --------------------------------------------------------------------------- |
| 774 | # Review fixes: real http.reddit_keyless_* deadline_monotonic, u/ prefix OP |
| 775 | # matching, strict start-tag attribute tokenization, expired fetch_scores gate |
| 776 | # --------------------------------------------------------------------------- |
| 777 | |
| 778 | |
| 779 | class TestReviewFixes: |
| 780 | def test_bool_attr_tokenizes_attributes_without_value_false_positives(self): |
| 781 | html = ( |
| 782 | '<shreddit-comment-tree-stats total-comments="4"></shreddit-comment-tree-stats>' |
| 783 | + _shreddit_comment_html( |
| 784 | "NoteUser", "t1_note", 100, "Quoted text mentioning OP", |
| 785 | extra_attrs='aria-label="a is-op note" data-note=\'is-submitter\'', |
| 786 | ) |
| 787 | + _shreddit_comment_html( |
| 788 | "SingleFalse", "t1_sf", 90, "Single-quoted false", |
| 789 | extra_attrs="is-op='false'", |
| 790 | ) |
| 791 | + _shreddit_comment_html( |
| 792 | "SingleTrue", "t1_st", 80, "Single-quoted true", |
| 793 | extra_attrs="is-op='true'", |
| 794 | ) |
| 795 | + _shreddit_comment_html( |
| 796 | "PrefixedAttr", "t1_pref", 70, "Different attribute name", |
| 797 | extra_attrs='author-is-op="true"', |
| 798 | ) |
| 799 | ) |
| 800 | parsed = {c["author"]: c for c in reddit_shreddit.parse_comments(html)} |
| 801 | assert "is_uploader" not in parsed["NoteUser"] |
| 802 | assert parsed["SingleFalse"]["is_uploader"] is False |
| 803 | assert parsed["SingleTrue"]["is_uploader"] is True |
| 804 | assert "is_uploader" not in parsed["PrefixedAttr"] |
| 805 | |
| 806 | def test_u_prefix_stripped_when_matching_op_author(self): |
| 807 | html = ( |
| 808 | '<shreddit-comment-tree-stats total-comments="3"></shreddit-comment-tree-stats>' |
| 809 | + _shreddit_comment_html("u/Alice", "t1_a1", 50, "OP with u/ prefix") |
| 810 | + _shreddit_comment_html("/u/Alice", "t1_a2", 40, "OP with /u/ prefix") |
| 811 | + _shreddit_comment_html("u/Bob", "t1_b1", 30, "Other user with u/ prefix") |
| 812 | ) |
| 813 | url = "https://www.reddit.com/r/test/comments/abc123/slug/" |
| 814 | with mock.patch.object(reddit_shreddit.http, "get_text", return_value=html): |
| 815 | out = reddit_shreddit.fetch_comments(url, post_author="Alice") |
| 816 | marks = {c["author"]: c["is_uploader"] for c in out["top_comments"]} |
| 817 | assert marks == {"u/Alice": True, "/u/Alice": True, "u/Bob": False} |
| 818 | |
| 819 | # Also verify post_author with u/ prefix matches bare comment author, |
| 820 | # and reddit_hydrate._stamp_uploader strips u/ and /u/ consistently. |
| 821 | post = { |
| 822 | "author": "/u/Alice", |
| 823 | "top_comments": [ |
| 824 | {"author": "Alice", "excerpt": "bare op"}, |
| 825 | {"author": "u/alice", "excerpt": "prefixed op"}, |
| 826 | {"author": "u/other", "excerpt": "community"}, |
| 827 | {"author": "u/[deleted]", "excerpt": "deleted"}, |
| 828 | ], |
| 829 | } |
| 830 | reddit_hydrate._stamp_uploader(post) |
| 831 | assert [c.get("is_uploader") for c in post["top_comments"]] == [True, True, False, None] |
| 832 | |
| 833 | def test_expired_fetch_scores_returns_cached_hits_without_registering_inflight(self): |
| 834 | with reddit_arctic._memo_lock: |
| 835 | reddit_arctic._cache["cached1"] = {"score": 42, "num_comments": 7} |
| 836 | |
| 837 | seen_inserts: list[str] = [] |
| 838 | |
| 839 | class SpyDict(dict): |
| 840 | def __setitem__(self, key, value): |
| 841 | seen_inserts.append(key) |
| 842 | super().__setitem__(key, value) |
| 843 | |
| 844 | spy_inflight = SpyDict() |
| 845 | with mock.patch.object(reddit_arctic, "_score_inflight", spy_inflight), \ |
| 846 | mock.patch.object(reddit_arctic.http, "get") as http_get: |
| 847 | out = reddit_arctic.fetch_scores( |
| 848 | ["cached1", "uncached2"], deadline=time.monotonic() - 1.0, |
| 849 | ) |
| 850 | |
| 851 | assert out == {"cached1": {"score": 42, "num_comments": 7}} |
| 852 | http_get.assert_not_called() |
| 853 | assert seen_inserts == [] |
| 854 | assert spy_inflight == {} |
| 855 | |
| 856 | def test_http_reddit_keyless_get_text_enforces_deadline_on_limiter_waiter_and_get_text(self, monkeypatch): |
| 857 | url_limiter = "https://www.reddit.com/svc/shreddit/comments/r/test/t3_lim1?sort=top" |
| 858 | # 1. Drained limiter fails fast inside acquire(deadline_monotonic=...) without calling get_text. |
| 859 | slow_limiter = http.RateLimiter(rate_per_sec=0.05, burst=1) |
| 860 | slow_limiter.acquire() # drain the single token (next refill in 20s) |
| 861 | monkeypatch.setattr(http, "REDDIT_KEYLESS_LIMITER", slow_limiter) |
| 862 | |
| 863 | with mock.patch.object(http, "get_text") as gt, \ |
| 864 | http.capture_failures() as failures: |
| 865 | t0 = time.monotonic() |
| 866 | body = http.reddit_keyless_get_text( |
| 867 | url_limiter, timeout=12, retries=1, deadline_monotonic=time.monotonic() + 0.1, |
| 868 | ) |
| 869 | elapsed = time.monotonic() - t0 |
| 870 | assert body is None |
| 871 | assert elapsed < 1.0 |
| 872 | gt.assert_not_called() |
| 873 | assert any(isinstance(f, http.DeadlineExceeded) for f in failures) |
| 874 | |
| 875 | # 2. Coalesced waiter respects deadline_monotonic and does not block on wait allowance. |
| 876 | monkeypatch.setattr(http, "REDDIT_KEYLESS_LIMITER", http.RateLimiter(rate_per_sec=100.0, burst=100)) |
| 877 | url_waiter = "https://www.reddit.com/svc/shreddit/comments/r/test/t3_wait1?sort=top" |
| 878 | owner_started = threading.Event() |
| 879 | release_owner = threading.Event() |
| 880 | seen_get_text_kwargs: dict = {} |
| 881 | |
| 882 | def slow_owner_get(u, **kwargs): |
| 883 | seen_get_text_kwargs.update(kwargs) |
| 884 | owner_started.set() |
| 885 | release_owner.wait(timeout=5.0) |
| 886 | return SHREDDIT_HTML |
| 887 | |
| 888 | with mock.patch.object(http, "get_text", side_effect=slow_owner_get): |
| 889 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 890 | owner_deadline = time.monotonic() + 5.0 |
| 891 | f_owner = pool.submit( |
| 892 | http.reddit_keyless_get_text, |
| 893 | url_waiter, |
| 894 | timeout=12, |
| 895 | retries=1, |
| 896 | deadline_monotonic=owner_deadline, |
| 897 | ) |
| 898 | assert owner_started.wait(timeout=3.0) |
| 899 | |
| 900 | t0 = time.monotonic() |
| 901 | waiter_res = http.reddit_keyless_get_text( |
| 902 | url_waiter, timeout=12, retries=1, deadline_monotonic=time.monotonic() + 0.08, |
| 903 | ) |
| 904 | elapsed = time.monotonic() - t0 |
| 905 | assert waiter_res is None |
| 906 | assert elapsed < 1.0 |
| 907 | |
| 908 | release_owner.set() |
| 909 | assert f_owner.result(timeout=5.0) == SHREDDIT_HTML |
| 910 | |
| 911 | assert seen_get_text_kwargs["deadline_monotonic"] == owner_deadline |
| 912 | assert seen_get_text_kwargs["timeout"] <= 5.0 |
| 913 | |
| 914 | def test_http_reddit_keyless_retry_429_respects_deadline_monotonic(self): |
| 915 | url = "https://www.reddit.com/svc/shreddit/search/?q=ghostty&type=posts&t=month&sort=relevance" |
| 916 | |
| 917 | # Case A: insufficient remaining budget after 429 skips sleep & retry. |
| 918 | def always_429(u, **kwargs): |
| 919 | http._record_failure(http.HTTPError("HTTP 429: Too Many Requests", 429)) |
| 920 | return None |
| 921 | |
| 922 | with mock.patch.object(http, "get_text", side_effect=always_429) as gt, \ |
| 923 | mock.patch.object(http.time, "sleep") as slept, \ |
| 924 | http.capture_failures() as failures: |
| 925 | body, err = http.reddit_keyless_get_text_retry_429( |
| 926 | url, |
| 927 | timeout=15, |
| 928 | accept="text/html", |
| 929 | deadline_monotonic=time.monotonic() + 0.3, |
| 930 | ) |
| 931 | |
| 932 | assert body is None |
| 933 | assert err is not None and "429" in err |
| 934 | assert gt.call_count == 1 |
| 935 | slept.assert_not_called() |
| 936 | assert any(f.status_code == 429 for f in failures) |
| 937 | |
| 938 | # Case B: sufficient budget sleeps once, forwards deadline_monotonic to both attempts, and recovers. |
| 939 | seen_deadlines: list[float | None] = [] |
| 940 | responses = [None, _search_page_html("p429", author="alice")] |
| 941 | |
| 942 | def recover_429(u, **kwargs): |
| 943 | seen_deadlines.append(kwargs.get("deadline_monotonic")) |
| 944 | val = responses.pop(0) |
| 945 | if val is None: |
| 946 | http._record_failure(http.HTTPError("HTTP 429: Too Many Requests", 429)) |
| 947 | return val |
| 948 | |
| 949 | future_deadline = time.monotonic() + 10.0 |
| 950 | with mock.patch.object(http, "get_text", side_effect=recover_429), \ |
| 951 | mock.patch.object(http.time, "sleep") as slept, \ |
| 952 | http.capture_failures() as failures: |
| 953 | body, err = reddit_search._fetch_page(url, deadline=future_deadline) |
| 954 | |
| 955 | assert body is not None and err is None |
| 956 | assert seen_deadlines == [future_deadline, future_deadline] |
| 957 | slept.assert_called_once() |
| 958 | assert failures == [] |
| 959 | |
| 960 | |
| 961 | # --------------------------------------------------------------------------- |
| 962 | # Greptile review fixes: partial page salvage, web-floor hydration reserve, |
| 963 | # incremental/full-cache fetch_scores handoff, direct kwarg forwarding |
| 964 | # --------------------------------------------------------------------------- |
| 965 | |
| 966 | |
| 967 | class TestGreptileFixes: |
| 968 | def test_search_salvages_page_one_when_page_two_stalls_past_deadline(self): |
| 969 | page2_started = threading.Event() |
| 970 | release_page2 = threading.Event() |
| 971 | |
| 972 | def fake_retry_get(url, **kwargs): |
| 973 | if "cursor=" not in url: |
| 974 | return _search_page_html("p1keep", author="alice", cursor="nextcur1"), None |
| 975 | page2_started.set() |
| 976 | release_page2.wait(timeout=5.0) |
| 977 | return _search_page_html("p2late", author="bob"), None |
| 978 | |
| 979 | t0 = time.monotonic() |
| 980 | try: |
| 981 | with mock.patch.object( |
| 982 | reddit_search.http, "reddit_keyless_get_text_retry_429", side_effect=fake_retry_get, |
| 983 | ): |
| 984 | posts = reddit_search.search( |
| 985 | "Ghostty", depth="quick", deadline=time.monotonic() + 0.15, |
| 986 | ) |
| 987 | finally: |
| 988 | release_page2.set() |
| 989 | |
| 990 | assert page2_started.is_set() |
| 991 | assert time.monotonic() - t0 < 1.5 |
| 992 | assert [p["metadata"]["post_id"] for p in posts] == ["p1keep"] |
| 993 | assert posts[0]["author"] == "alice" |
| 994 | |
| 995 | def test_web_floor_hydrates_query_one_threads_when_query_two_blocks(self): |
| 996 | query2_started = threading.Event() |
| 997 | release_query2 = threading.Event() |
| 998 | |
| 999 | def fake_keyless_search(query, date_range, config, count=20, freshness=None, *, |
| 1000 | deadline_monotonic, accept_result=None): |
| 1001 | assert deadline_monotonic is not None |
| 1002 | if "r/ghostty" not in query: |
| 1003 | return ( |
| 1004 | [{ |
| 1005 | "url": "https://www.reddit.com/r/ghostty/comments/q1hit/ghostty_fast/", |
| 1006 | "title": "r/ghostty on Reddit: Ghostty fast terminal", |
| 1007 | "snippet": "", |
| 1008 | "date": "2026-10-10", |
| 1009 | }], |
| 1010 | {"keyless_backend": "brave", "keyless_rungs": {"brave": "ok"}}, |
| 1011 | ) |
| 1012 | query2_started.set() |
| 1013 | release_query2.wait(timeout=5.0) |
| 1014 | return ([], {"keyless_backend": "brave", "keyless_rungs": {"brave": "ok"}}) |
| 1015 | |
| 1016 | archived = { |
| 1017 | "id": "", |
| 1018 | "title": "Ghostty fast terminal", |
| 1019 | "url": "https://www.reddit.com/r/ghostty/comments/q1hit/ghostty_fast/", |
| 1020 | "score": 88, |
| 1021 | "num_comments": 12, |
| 1022 | "subreddit": "ghostty", |
| 1023 | "created_utc": 1700000000, |
| 1024 | "author": "op_user", |
| 1025 | "selftext": "", |
| 1026 | "date": "2026-10-10", |
| 1027 | "engagement": {"score": 88, "num_comments": 12}, |
| 1028 | "relevance": 0.9, |
| 1029 | "why_relevant": "Reddit listing (arctic-shift)", |
| 1030 | "metadata": {"post_id": "q1hit"}, |
| 1031 | } |
| 1032 | |
| 1033 | t0 = time.monotonic() |
| 1034 | try: |
| 1035 | with mock.patch.object( |
| 1036 | reddit_discover.web_search_keyless, "keyless_search", side_effect=fake_keyless_search, |
| 1037 | ), mock.patch.object( |
| 1038 | reddit_keyless.reddit_arctic, "fetch_posts_by_ids", |
| 1039 | return_value=({"q1hit": dict(archived)}, "ok"), |
| 1040 | ), mock.patch.object( |
| 1041 | reddit_keyless.reddit_arctic, "fetch_comment_tree", return_value=[], |
| 1042 | ): |
| 1043 | # 1.8s lane budget gives discovery 60% (~1.08s) and reserves 40% (~0.72s) |
| 1044 | # for hydration, so blocked query 2 cuts off early while query 1's ref is hydrated. |
| 1045 | kept = reddit_keyless._web_floor( |
| 1046 | "Ghostty", "quick", ["ghostty"], None, "2026-10-01", "2026-10-31", |
| 1047 | deadline=time.monotonic() + 1.8, |
| 1048 | ) |
| 1049 | finally: |
| 1050 | release_query2.set() |
| 1051 | |
| 1052 | assert query2_started.is_set() |
| 1053 | assert time.monotonic() - t0 < 2.5 |
| 1054 | assert [p["metadata"]["post_id"] for p in kept] == ["q1hit"] |
| 1055 | |
| 1056 | def test_web_discover_deadline_keeps_meaningful_share_at_tight_budget_and_hydrates(self): |
| 1057 | # At 2.9s remaining, web discovery must get 60% (1.74s, >= 1.5s) and |
| 1058 | # reserve 40% (1.16s, >= 1.0s) for hydration rather than starving query 1. |
| 1059 | now = 1000.0 |
| 1060 | cutoff_tight = reddit_keyless._web_discover_deadline(now + 2.9, now=now) |
| 1061 | assert cutoff_tight is not None |
| 1062 | assert cutoff_tight - now == pytest.approx(1.74) |
| 1063 | assert (now + 2.9) - cutoff_tight == pytest.approx(1.16) |
| 1064 | |
| 1065 | # At 20s remaining, reserve caps at _WEB_HYDRATION_RESERVE_SECONDS (8s). |
| 1066 | cutoff_wide = reddit_keyless._web_discover_deadline(now + 20.0, now=now) |
| 1067 | assert cutoff_wide == pytest.approx(now + 12.0) |
| 1068 | |
| 1069 | # With a 2.9s budget where the single query takes 0.35s (> old 100ms cutoff), |
| 1070 | # _web_floor must still find and hydrate query 1's thread. |
| 1071 | def moderate_query(query, date_range, config, count=20, freshness=None, *, |
| 1072 | deadline_monotonic, accept_result=None): |
| 1073 | assert deadline_monotonic is not None |
| 1074 | time.sleep(0.35) |
| 1075 | return ( |
| 1076 | [{ |
| 1077 | "url": "https://www.reddit.com/r/ghostty/comments/tight1/ghostty_tight/", |
| 1078 | "title": "r/ghostty on Reddit: Ghostty tight budget", |
| 1079 | "snippet": "", |
| 1080 | "date": "2026-10-10", |
| 1081 | }], |
| 1082 | {"keyless_backend": "brave", "keyless_rungs": {"brave": "ok"}}, |
| 1083 | ) |
| 1084 | |
| 1085 | archived = { |
| 1086 | "id": "", |
| 1087 | "title": "Ghostty tight budget", |
| 1088 | "url": "https://www.reddit.com/r/ghostty/comments/tight1/ghostty_tight/", |
| 1089 | "score": 55, |
| 1090 | "num_comments": 4, |
| 1091 | "subreddit": "ghostty", |
| 1092 | "created_utc": 1700000000, |
| 1093 | "author": "op_user", |
| 1094 | "selftext": "", |
| 1095 | "date": "2026-10-10", |
| 1096 | "engagement": {"score": 55, "num_comments": 4}, |
| 1097 | "relevance": 0.9, |
| 1098 | "why_relevant": "Reddit listing (arctic-shift)", |
| 1099 | "metadata": {"post_id": "tight1"}, |
| 1100 | } |
| 1101 | |
| 1102 | with mock.patch.object( |
| 1103 | reddit_discover.web_search_keyless, "keyless_search", side_effect=moderate_query, |
| 1104 | ), mock.patch.object( |
| 1105 | reddit_keyless.reddit_arctic, "fetch_posts_by_ids", |
| 1106 | return_value=({"tight1": dict(archived)}, "ok"), |
| 1107 | ), mock.patch.object( |
| 1108 | reddit_keyless.reddit_arctic, "fetch_comment_tree", return_value=[], |
| 1109 | ): |
| 1110 | kept = reddit_keyless._web_floor( |
| 1111 | "Ghostty", "quick", None, None, "2026-10-01", "2026-10-31", |
| 1112 | deadline=time.monotonic() + 2.9, |
| 1113 | ) |
| 1114 | |
| 1115 | assert [p["metadata"]["post_id"] for p in kept] == ["tight1"] |
| 1116 | |
| 1117 | def test_partial_search_is_not_cached_and_later_call_fetches_all_pages(self): |
| 1118 | page2_attempts = {"n": 0} |
| 1119 | release_first_page2 = threading.Event() |
| 1120 | first_page2_started = threading.Event() |
| 1121 | |
| 1122 | def fake_retry_get(url, **kwargs): |
| 1123 | if "cursor=" not in url: |
| 1124 | return _search_page_html("p1full", author="alice", cursor="cur2"), None |
| 1125 | page2_attempts["n"] += 1 |
| 1126 | if page2_attempts["n"] == 1: |
| 1127 | first_page2_started.set() |
| 1128 | release_first_page2.wait(timeout=5.0) |
| 1129 | return None, "deadline exceeded" |
| 1130 | return _search_page_html("p2full", author="bob"), None |
| 1131 | |
| 1132 | try: |
| 1133 | with mock.patch.object( |
| 1134 | reddit_search.http, "reddit_keyless_get_text_retry_429", side_effect=fake_retry_get, |
| 1135 | ): |
| 1136 | # Call 1 times out on page 2 and returns salvaged page-1 posts, |
| 1137 | # without caching the truncated result in _run_results. |
| 1138 | partial = reddit_search.search( |
| 1139 | "Ghostty", depth="quick", deadline=time.monotonic() + 0.15, |
| 1140 | ) |
| 1141 | assert [p["metadata"]["post_id"] for p in partial] == ["p1full"] |
| 1142 | assert reddit_search._run_results == {} |
| 1143 | |
| 1144 | # Call 2 has ample time and fetches both page 1 and page 2, then caches. |
| 1145 | full = reddit_search.search( |
| 1146 | "Ghostty", depth="quick", deadline=time.monotonic() + 5.0, |
| 1147 | ) |
| 1148 | assert [p["metadata"]["post_id"] for p in full] == ["p1full", "p2full"] |
| 1149 | assert len(reddit_search._run_results) == 1 |
| 1150 | finally: |
| 1151 | release_first_page2.set() |
| 1152 | assert first_page2_started.is_set() |
| 1153 | |
| 1154 | def test_partial_search_hands_partial_fallback_to_concurrent_waiter(self): |
| 1155 | owner_started = threading.Event() |
| 1156 | release_owner = threading.Event() |
| 1157 | calls = {"n": 0} |
| 1158 | lock = threading.Lock() |
| 1159 | |
| 1160 | def fake_uncached_status(*_args, **_kwargs): |
| 1161 | with lock: |
| 1162 | calls["n"] += 1 |
| 1163 | n = calls["n"] |
| 1164 | if n == 1: |
| 1165 | owner_started.set() |
| 1166 | release_owner.wait(timeout=5.0) |
| 1167 | return [{"id": "R1", "url": "https://www.reddit.com/r/ghostty/comments/part1/"}], False |
| 1168 | # Waiter's retry yields nothing; it must fall back to the owner's partial list. |
| 1169 | return [], False |
| 1170 | |
| 1171 | with mock.patch.object( |
| 1172 | reddit_search, "_search_uncached_with_status", side_effect=fake_uncached_status, |
| 1173 | ): |
| 1174 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 1175 | f_owner = pool.submit( |
| 1176 | reddit_search.search, "Ghostty", depth="quick", deadline=time.monotonic() + 5.0, |
| 1177 | ) |
| 1178 | assert owner_started.wait(timeout=3.0) |
| 1179 | f_waiter = pool.submit( |
| 1180 | reddit_search.search, "Ghostty", depth="quick", deadline=time.monotonic() + 5.0, |
| 1181 | ) |
| 1182 | time.sleep(0.05) |
| 1183 | release_owner.set() |
| 1184 | owner_res = f_owner.result(timeout=5.0) |
| 1185 | waiter_res = f_waiter.result(timeout=5.0) |
| 1186 | |
| 1187 | assert calls["n"] == 2 |
| 1188 | assert len(owner_res) == 1 |
| 1189 | assert len(waiter_res) == 1 |
| 1190 | assert waiter_res[0]["url"] == owner_res[0]["url"] |
| 1191 | assert waiter_res[0] is not owner_res[0] |
| 1192 | assert reddit_search._run_results == {} |
| 1193 | |
| 1194 | def test_shared_deadline_waiter_receives_live_page_one_while_page_two_stalls(self): |
| 1195 | page2_started = threading.Event() |
| 1196 | release_page2 = threading.Event() |
| 1197 | |
| 1198 | def fake_retry_get(url, **kwargs): |
| 1199 | if "cursor=" not in url: |
| 1200 | return _search_page_html("p1live", author="alice", cursor="cur_live"), None |
| 1201 | page2_started.set() |
| 1202 | release_page2.wait(timeout=5.0) |
| 1203 | return _search_page_html("p2slow", author="bob"), None |
| 1204 | |
| 1205 | try: |
| 1206 | with mock.patch.object( |
| 1207 | reddit_search.http, "reddit_keyless_get_text_retry_429", side_effect=fake_retry_get, |
| 1208 | ): |
| 1209 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 1210 | # Owner stays paused on page 2 until we explicitly release it, |
| 1211 | # guaranteeing slot.partial is still None when the waiter times out. |
| 1212 | f_owner = pool.submit( |
| 1213 | reddit_search.search, "Ghostty", depth="quick", deadline=time.monotonic() + 5.0, |
| 1214 | ) |
| 1215 | assert page2_started.wait(timeout=3.0) |
| 1216 | key = ("Ghostty", "quick", "month", ()) |
| 1217 | with reddit_search._run_lock: |
| 1218 | inflight_slot = reddit_search._run_inflight[key] |
| 1219 | assert inflight_slot.partial is None |
| 1220 | |
| 1221 | f_waiter = pool.submit( |
| 1222 | reddit_search.search, "Ghostty", depth="quick", deadline=time.monotonic() + 0.12, |
| 1223 | ) |
| 1224 | waiter_res = f_waiter.result(timeout=2.0) |
| 1225 | # Check waiter result BEFORE releasing the owner so live_snapshot() is proven. |
| 1226 | assert not f_owner.done() |
| 1227 | assert inflight_slot.partial is None |
| 1228 | assert [p["metadata"]["post_id"] for p in waiter_res] == ["p1live"] |
| 1229 | |
| 1230 | release_page2.set() |
| 1231 | owner_res = f_owner.result(timeout=3.0) |
| 1232 | finally: |
| 1233 | release_page2.set() |
| 1234 | |
| 1235 | assert [p["metadata"]["post_id"] for p in owner_res] == ["p1live", "p2slow"] |
| 1236 | assert owner_res[0] is not waiter_res[0] |
| 1237 | |
| 1238 | def test_live_snapshot_interleaves_subreddit_and_global_streams_like_owner(self): |
| 1239 | sub_done = threading.Barrier(2) |
| 1240 | global_page2_started = threading.Event() |
| 1241 | release_global_page2 = threading.Event() |
| 1242 | |
| 1243 | def multi_post_page(prefix: str, count: int, sub: str, cursor: str | None = None) -> str: |
| 1244 | units = [] |
| 1245 | for i in range(count): |
| 1246 | pid = f"{prefix}{i}" |
| 1247 | ctx = json.dumps({ |
| 1248 | "action_info": {"type": "post"}, |
| 1249 | "post": {"id": f"t3_{pid}", "title": f"Ghostty {pid}"}, |
| 1250 | "subreddit": {"name": sub}, |
| 1251 | "profile": {"id": f"t2_{pid}", "name": f"user_{pid}"}, |
| 1252 | }).replace('"', """) |
| 1253 | units.append( |
| 1254 | f'<search-telemetry-tracker data-faceplate-tracking-context="{ctx}" ' |
| 1255 | f'view-events="search/view/post">' |
| 1256 | f'<h2><a data-testid="post-title" href="/r/{sub}/comments/{pid}/slug/">' |
| 1257 | f"Ghostty {pid}</a></h2></search-telemetry-tracker>" |
| 1258 | f'<faceplate-timeago ts="2026-10-10T10:00:00.000000+0000"></faceplate-timeago>' |
| 1259 | f'<div data-testid="search-counter-row">' |
| 1260 | f'<span><faceplate-number number="10" pretty></faceplate-number> votes</span>' |
| 1261 | f'<span><faceplate-number number="2" pretty></faceplate-number> comments</span>' |
| 1262 | f"</div>" |
| 1263 | ) |
| 1264 | if cursor: |
| 1265 | units.append( |
| 1266 | f'<faceplate-partial loading="lazy" ' |
| 1267 | f'src="/svc/shreddit/search/?q=Ghostty&type=posts&cursor={cursor}">' |
| 1268 | f"</faceplate-partial>" |
| 1269 | ) |
| 1270 | return "<html><body>" + "".join(units) + "</body></html>" |
| 1271 | |
| 1272 | def fake_retry_get(url, **kwargs): |
| 1273 | if "/r/SubA/" in url: |
| 1274 | html = multi_post_page("a", 7, "SubA") |
| 1275 | sub_done.wait(timeout=3.0) |
| 1276 | return html, None |
| 1277 | if "/r/SubB/" in url: |
| 1278 | html = multi_post_page("b", 7, "SubB") |
| 1279 | sub_done.wait(timeout=3.0) |
| 1280 | return html, None |
| 1281 | if "cursor=" not in url: |
| 1282 | # Ensure both subreddit streams complete (14 sub posts > quick cap of 10) |
| 1283 | # BEFORE global page 1 arrives. |
| 1284 | time.sleep(0.05) |
| 1285 | return multi_post_page("g", 7, "allnews", cursor="gcur2"), None |
| 1286 | global_page2_started.set() |
| 1287 | release_global_page2.wait(timeout=5.0) |
| 1288 | return multi_post_page("g2", 3, "allnews"), None |
| 1289 | |
| 1290 | try: |
| 1291 | with mock.patch.object( |
| 1292 | reddit_search.http, "reddit_keyless_get_text_retry_429", side_effect=fake_retry_get, |
| 1293 | ): |
| 1294 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 1295 | f_owner = pool.submit( |
| 1296 | reddit_search.search, |
| 1297 | "Ghostty", depth="quick", subreddits=["SubA", "SubB"], |
| 1298 | deadline=time.monotonic() + 5.0, |
| 1299 | ) |
| 1300 | assert global_page2_started.wait(timeout=3.0) |
| 1301 | f_waiter = pool.submit( |
| 1302 | reddit_search.search, |
| 1303 | "Ghostty", depth="quick", subreddits=["SubA", "SubB"], |
| 1304 | deadline=time.monotonic() + 0.12, |
| 1305 | ) |
| 1306 | waiter_res = f_waiter.result(timeout=2.0) |
| 1307 | assert not f_owner.done() |
| 1308 | waiter_ids = [p["metadata"]["post_id"] for p in waiter_res] |
| 1309 | assert len(waiter_ids) == 10 |
| 1310 | # Round-robin across [SubA, SubB, global] keeps global posts even |
| 1311 | # though SubA + SubB alone finished earlier with 14 posts. |
| 1312 | assert waiter_ids == ["a0", "b0", "g0", "a1", "b1", "g1", "a2", "b2", "g2", "a3"] |
| 1313 | |
| 1314 | release_global_page2.set() |
| 1315 | owner_res = f_owner.result(timeout=3.0) |
| 1316 | finally: |
| 1317 | release_global_page2.set() |
| 1318 | |
| 1319 | assert [p["metadata"]["post_id"] for p in owner_res] == [ |
| 1320 | "a0", "b0", "g0", "a1", "b1", "g1", "a2", "b2", "g2", "a3", |
| 1321 | ] |
| 1322 | |
| 1323 | def test_web_floor_passes_earlier_hydration_cutoff_to_session_and_archive(self): |
| 1324 | ref = reddit_refs.canonical_thread("https://www.reddit.com/r/ghostty/comments/sess1/") |
| 1325 | assert ref is not None |
| 1326 | ref.provenance.add("web") |
| 1327 | ref.title = "Ghostty session hydration cutoff" |
| 1328 | |
| 1329 | seen_deadlines: dict[str, float | None] = {} |
| 1330 | |
| 1331 | class FakeSession: |
| 1332 | alive = True |
| 1333 | |
| 1334 | def fake_session_hydrator(session, *, depth="default", deadline=None): |
| 1335 | seen_deadlines["session_hydrator"] = deadline |
| 1336 | return lambda _refs: {} |
| 1337 | |
| 1338 | def fake_hydrate(refs, *, topic="", depth="default", from_date=None, to_date=None, |
| 1339 | session_hydrator=None, deadline=None, **_kwargs): |
| 1340 | seen_deadlines["hydrate"] = deadline |
| 1341 | return reddit_hydrate.Hydration( |
| 1342 | items=[{ |
| 1343 | "title": "Ghostty session hydration cutoff", |
| 1344 | "url": ref.url, |
| 1345 | "subreddit": "ghostty", |
| 1346 | "metadata": {"post_id": "sess1"}, |
| 1347 | }], |
| 1348 | detail="web+session served 1", |
| 1349 | arctic_state="ok", |
| 1350 | ) |
| 1351 | |
| 1352 | outer_deadline = time.monotonic() + 10.0 |
| 1353 | with mock.patch.object( |
| 1354 | reddit_keyless.reddit_discover, "web_refs", |
| 1355 | return_value=reddit_discover.WebFloor( |
| 1356 | refs=[ref], queries=["site:reddit.com Ghostty"], rungs={"brave": "ok"}, |
| 1357 | ), |
| 1358 | ), mock.patch.object( |
| 1359 | reddit_keyless.reddit_session, "current", return_value=FakeSession(), |
| 1360 | ), mock.patch.object( |
| 1361 | reddit_keyless.reddit_session, "hydrator", side_effect=fake_session_hydrator, |
| 1362 | ), mock.patch.object( |
| 1363 | reddit_keyless.reddit_hydrate, "hydrate", side_effect=fake_hydrate, |
| 1364 | ): |
| 1365 | kept = reddit_keyless._web_floor( |
| 1366 | "Ghostty", "quick", None, None, "2026-10-01", "2026-10-31", |
| 1367 | deadline=outer_deadline, |
| 1368 | ) |
| 1369 | |
| 1370 | assert [p["metadata"]["post_id"] for p in kept] == ["sess1"] |
| 1371 | assert seen_deadlines["session_hydrator"] is not None |
| 1372 | assert seen_deadlines["hydrate"] is not None |
| 1373 | assert seen_deadlines["session_hydrator"] == seen_deadlines["hydrate"] |
| 1374 | assert seen_deadlines["session_hydrator"] < outer_deadline |
| 1375 | |
| 1376 | def test_fetch_scores_waiter_fetches_batch_two_when_owner_expires_after_batch_one(self): |
| 1377 | batch1_started = threading.Event() |
| 1378 | release_batch1 = threading.Event() |
| 1379 | calls: list[tuple[str, int]] = [] |
| 1380 | calls_lock = threading.Lock() |
| 1381 | owner_tid: list[int] = [] |
| 1382 | waiter_tid: list[int] = [] |
| 1383 | |
| 1384 | def fake_get(url, **_kwargs): |
| 1385 | tid = threading.get_ident() |
| 1386 | with calls_lock: |
| 1387 | calls.append((url, tid)) |
| 1388 | if "ids=b1" in url: |
| 1389 | batch1_started.set() |
| 1390 | release_batch1.wait(timeout=5.0) |
| 1391 | return {"data": [{"id": "b1", "score": 11, "num_comments": 1}]} |
| 1392 | if "ids=b2" in url: |
| 1393 | return {"data": [{"id": "b2", "score": 22, "num_comments": 2}]} |
| 1394 | return {"data": []} |
| 1395 | |
| 1396 | def run_owner(): |
| 1397 | owner_tid.append(threading.get_ident()) |
| 1398 | return reddit_arctic.fetch_scores(["b1", "b2"], time.monotonic() + 0.12) |
| 1399 | |
| 1400 | def run_waiter(): |
| 1401 | waiter_tid.append(threading.get_ident()) |
| 1402 | return reddit_arctic.fetch_scores(["b1", "b2"], time.monotonic() + 5.0) |
| 1403 | |
| 1404 | with mock.patch.object(reddit_arctic, "BATCH", 1), \ |
| 1405 | mock.patch.object(reddit_arctic, "PACE_SECONDS", 0.0), \ |
| 1406 | mock.patch.object(reddit_arctic.http, "get", side_effect=fake_get): |
| 1407 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 1408 | # Owner has a tight deadline that expires while batch 1 is in flight, |
| 1409 | # so owner must NOT block waiter from fetching batch 2 ("b2"). |
| 1410 | f_owner = pool.submit(run_owner) |
| 1411 | assert batch1_started.wait(timeout=3.0) |
| 1412 | f_waiter = pool.submit(run_waiter) |
| 1413 | time.sleep(0.15) # let owner's deadline expire before releasing batch 1 |
| 1414 | release_batch1.set() |
| 1415 | owner_res = f_owner.result(timeout=5.0) |
| 1416 | waiter_res = f_waiter.result(timeout=5.0) |
| 1417 | |
| 1418 | assert owner_res["b1"] == {"score": 11, "num_comments": 1} |
| 1419 | assert waiter_res == { |
| 1420 | "b1": {"score": 11, "num_comments": 1}, |
| 1421 | "b2": {"score": 22, "num_comments": 2}, |
| 1422 | } |
| 1423 | assert len(calls) == 2 |
| 1424 | by_batch = {("b1" if "ids=b1" in url else "b2"): tid for url, tid in calls} |
| 1425 | assert by_batch == {"b1": owner_tid[0], "b2": waiter_tid[0]} |
| 1426 | |
| 1427 | def test_fetch_scores_waiter_retries_slot_when_owner_fails_mid_batch(self): |
| 1428 | started = threading.Event() |
| 1429 | release = threading.Event() |
| 1430 | attempt = {"n": 0} |
| 1431 | lock = threading.Lock() |
| 1432 | |
| 1433 | def flaky_get(url, **_kwargs): |
| 1434 | with lock: |
| 1435 | attempt["n"] += 1 |
| 1436 | n = attempt["n"] |
| 1437 | if n == 1: |
| 1438 | started.set() |
| 1439 | release.wait(timeout=5.0) |
| 1440 | raise http.DeadlineExceeded() |
| 1441 | return {"data": [{"id": "retry1", "score": 99, "num_comments": 8}]} |
| 1442 | |
| 1443 | with mock.patch.object(reddit_arctic.http, "get", side_effect=flaky_get): |
| 1444 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 1445 | f_owner = pool.submit( |
| 1446 | reddit_arctic.fetch_scores, ["retry1"], time.monotonic() + 0.1, |
| 1447 | ) |
| 1448 | assert started.wait(timeout=3.0) |
| 1449 | f_waiter = pool.submit( |
| 1450 | reddit_arctic.fetch_scores, ["retry1"], time.monotonic() + 5.0, |
| 1451 | ) |
| 1452 | time.sleep(0.03) |
| 1453 | release.set() |
| 1454 | owner_res = f_owner.result(timeout=5.0) |
| 1455 | waiter_res = f_waiter.result(timeout=5.0) |
| 1456 | |
| 1457 | assert owner_res == {} |
| 1458 | assert waiter_res == {"retry1": {"score": 99, "num_comments": 8}} |
| 1459 | assert attempt["n"] == 2 |
| 1460 | |
| 1461 | def test_fetch_scores_waiter_receives_scores_even_when_cache_is_full(self): |
| 1462 | with reddit_arctic._memo_lock: |
| 1463 | reddit_arctic._cache["existing"] = {"score": 1, "num_comments": 0} |
| 1464 | |
| 1465 | started = threading.Event() |
| 1466 | release = threading.Event() |
| 1467 | calls: list[str] = [] |
| 1468 | |
| 1469 | def slow_get(url, **_kwargs): |
| 1470 | calls.append(url) |
| 1471 | started.set() |
| 1472 | release.wait(timeout=5.0) |
| 1473 | return {"data": [{"id": "fresh1", "score": 333, "num_comments": 44}]} |
| 1474 | |
| 1475 | with mock.patch.object(reddit_arctic, "CACHE_MAX", 1), \ |
| 1476 | mock.patch.object(reddit_arctic.http, "get", side_effect=slow_get): |
| 1477 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: |
| 1478 | f_owner = pool.submit(reddit_arctic.fetch_scores, ["fresh1"]) |
| 1479 | assert started.wait(timeout=3.0) |
| 1480 | f_waiter = pool.submit(reddit_arctic.fetch_scores, ["fresh1"]) |
| 1481 | time.sleep(0.03) |
| 1482 | release.set() |
| 1483 | owner_res = f_owner.result(timeout=5.0) |
| 1484 | waiter_res = f_waiter.result(timeout=5.0) |
| 1485 | |
| 1486 | assert len(calls) == 1 |
| 1487 | assert owner_res == {"fresh1": {"score": 333, "num_comments": 44}} |
| 1488 | assert waiter_res == {"fresh1": {"score": 333, "num_comments": 44}} |
| 1489 | # Cache stayed strictly bounded at CACHE_MAX == 1. |
| 1490 | assert len(reddit_arctic._cache) == 1 |
| 1491 | assert "fresh1" not in reddit_arctic._cache |
| 1492 | |
| 1493 | def test_no_reflection_helpers_and_direct_kwarg_forwarding(self): |
| 1494 | assert not hasattr(reddit_search, "_accepts_kwarg") |
| 1495 | assert not hasattr(reddit_shreddit, "_accepts_kwarg") |
| 1496 | assert not hasattr(reddit_shreddit, "_accepts_named_kwarg") |
| 1497 | assert not hasattr(reddit_keyless, "_accepts_kwarg") |
| 1498 | |
| 1499 | # Direct post_author forwarding from reddit_keyless._fetch_enrichment. |
| 1500 | with mock.patch.object( |
| 1501 | reddit_keyless.reddit_shreddit, "fetch_comments", |
| 1502 | return_value={"top_comments": [], "comment_insights": [], "num_comments": None}, |
| 1503 | ) as fc: |
| 1504 | reddit_keyless._fetch_enrichment( |
| 1505 | "https://www.reddit.com/r/test/comments/abc123/slug/", |
| 1506 | deadline=1234.5, |
| 1507 | post_author="Alice", |
| 1508 | ) |
| 1509 | fc.assert_called_once_with( |
| 1510 | "https://www.reddit.com/r/test/comments/abc123/slug/", |
| 1511 | deadline=1234.5, |
| 1512 | post_author="Alice", |
| 1513 | ) |
| 1514 |