| 1 | """Regression tests for PR 37: YouTube root comments, Bluesky lock/cache, |
| 2 | LinkedIn 404 isolation, Corpus PDF streaming/encoding, and MCP manifest config. |
| 3 | |
| 4 | Covers: |
| 5 | - HIGH-179: yt-dlp max_comments zero-reply 4-tuple, root-parent filtering, post-filter cap |
| 6 | - HIGH-180: Bluesky thread-safe SHA-256 keyed session cache, stampede/rotation races, eviction |
| 7 | - HIGH-188: LinkedIn "No posts found" 404 & search_profile failure-sink isolation |
| 8 | - HIGH-217: Corpus pdftotext UTF-8/separator flags, streaming cap, timeout, UnicodeError safety |
| 9 | - HIGH-221: MCP manifest BSKY_HANDLE + BSKY_APP_PASSWORD pairing |
| 10 | - HIGH-222: MCP manifest LAST30DAYS_X_BACKEND + X_BEARER_TOKEN xapi opt-in |
| 11 | """ |
| 12 | |
| 13 | from __future__ import annotations |
| 14 | |
| 15 | import hashlib |
| 16 | import io |
| 17 | import json |
| 18 | import os |
| 19 | import signal |
| 20 | import stat |
| 21 | import subprocess |
| 22 | import sys |
| 23 | import threading |
| 24 | import time |
| 25 | import urllib.error |
| 26 | from concurrent.futures import ThreadPoolExecutor |
| 27 | from pathlib import Path |
| 28 | from unittest import mock |
| 29 | |
| 30 | import pytest |
| 31 | |
| 32 | from lib import backends, bluesky, corpus, doctor, env, health, http, linkedin, pipeline, subproc, youtube_yt |
| 33 | from lib.subproc import SubprocResult |
| 34 | |
| 35 | ROOT = Path(__file__).resolve().parents[1] |
| 36 | |
| 37 | |
| 38 | # --------------------------------------------------------------------------- |
| 39 | # HIGH-179: yt-dlp root comments, zero replies, post-filter cap |
| 40 | # --------------------------------------------------------------------------- |
| 41 | |
| 42 | |
| 43 | class TestHigh179YoutubeRootComments: |
| 44 | def test_ytdlp_command_requests_zero_replies_with_buffer_and_no_cookies(self) -> None: |
| 45 | payload = json.dumps({"id": "abc123", "comments": []}) |
| 46 | res = SubprocResult(returncode=0, stdout=payload, stderr="") |
| 47 | |
| 48 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 49 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=res) as run_mock: |
| 50 | comments, ran_cleanly = youtube_yt._ytdlp_comments_result("abc123", max_comments=5) |
| 51 | |
| 52 | assert comments == [] |
| 53 | assert ran_cleanly is True |
| 54 | cmd = run_mock.call_args.args[0] |
| 55 | assert "--no-cookies-from-browser" in cmd |
| 56 | spec = cmd[cmd.index("--extractor-args") + 1] |
| 57 | assert "comment_sort=top" in spec |
| 58 | assert "max_comments=7,7,0,0" in spec |
| 59 | assert ",all," not in spec |
| 60 | |
| 61 | def test_zero_max_comments_short_circuits_cleanly_without_spawning(self) -> None: |
| 62 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 63 | mock.patch.object(youtube_yt.subproc, "run_with_timeout") as run_mock: |
| 64 | comments, ran_cleanly = youtube_yt._ytdlp_comments_result("abc123", max_comments=0) |
| 65 | |
| 66 | assert comments == [] |
| 67 | assert ran_cleanly is True |
| 68 | run_mock.assert_not_called() |
| 69 | |
| 70 | def test_filters_nested_replies_non_dicts_and_empty_text_before_cap(self) -> None: |
| 71 | raw_comments = [ |
| 72 | { |
| 73 | "id": "c1", |
| 74 | "parent": "root", |
| 75 | "author": "@ChannelOwner", |
| 76 | "author_is_uploader": True, |
| 77 | "text": "Pinned creator note", |
| 78 | "like_count": 500, |
| 79 | "_time_text": "3 days ago", |
| 80 | }, |
| 81 | { |
| 82 | "id": "c1.r1", |
| 83 | "parent": "c1", |
| 84 | "author": "@replier1", |
| 85 | "text": "Nested reply 1 to pinned note", |
| 86 | "like_count": 2, |
| 87 | }, |
| 88 | { |
| 89 | "id": "c1.r2", |
| 90 | "parent": "c1", |
| 91 | "author": "@replier2", |
| 92 | "text": "Nested reply 2 to pinned note", |
| 93 | "like_count": 1, |
| 94 | }, |
| 95 | "not-a-dict-entry", |
| 96 | None, |
| 97 | {"id": "c2", "parent": "root", "author": "@empty", "text": " \n\t ", "like_count": 9}, |
| 98 | { |
| 99 | "id": "c3", |
| 100 | "parent": "root", |
| 101 | "author": "@viewerA", |
| 102 | "author_is_uploader": False, |
| 103 | "text": " First real community parent comment ", |
| 104 | "like_count": 210, |
| 105 | "_time_text": "2 days ago", |
| 106 | }, |
| 107 | { |
| 108 | "id": "c4", |
| 109 | "author": "@viewerB", |
| 110 | "text": "Legacy shape omitting parent defaults to root", |
| 111 | "like_count": 95, |
| 112 | "_time_text": "1 day ago", |
| 113 | }, |
| 114 | { |
| 115 | "id": "c5", |
| 116 | "parent": "root", |
| 117 | "author": "@viewerC", |
| 118 | "text": "Fourth root comment beyond max_comments=3", |
| 119 | "like_count": 40, |
| 120 | }, |
| 121 | ] |
| 122 | payload = json.dumps({"id": "abc123", "channel_id": "UC_CH", "comments": raw_comments}) |
| 123 | res = SubprocResult(returncode=0, stdout=payload, stderr="") |
| 124 | |
| 125 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 126 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=res): |
| 127 | comments, ran_cleanly = youtube_yt._ytdlp_comments_result("abc123", max_comments=3) |
| 128 | |
| 129 | assert ran_cleanly is True |
| 130 | assert [c["author"] for c in comments] == ["@ChannelOwner", "@viewerA", "@viewerB"] |
| 131 | assert comments[0]["is_uploader"] is True |
| 132 | assert comments[1]["text"] == "First real community parent comment" |
| 133 | assert comments[1]["is_uploader"] is False |
| 134 | |
| 135 | def test_malformed_top_level_json_or_non_list_comments_is_handled(self) -> None: |
| 136 | list_res = SubprocResult(returncode=0, stdout="[]", stderr="") |
| 137 | bad_comments_res = SubprocResult(returncode=0, stdout='{"comments": "not-a-list"}', stderr="") |
| 138 | |
| 139 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True): |
| 140 | with mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=list_res): |
| 141 | assert youtube_yt._ytdlp_comments_result("abc123", max_comments=3) == ([], False) |
| 142 | with mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=bad_comments_res): |
| 143 | assert youtube_yt._ytdlp_comments_result("abc123", max_comments=3) == ([], True) |
| 144 | |
| 145 | def test_skips_non_string_text_values_instead_of_stringifying(self) -> None: |
| 146 | raw_comments = [ |
| 147 | {"parent": "root", "author": "@bool", "text": False, "like_count": 50}, |
| 148 | {"parent": "root", "author": "@list", "text": [], "like_count": 40}, |
| 149 | {"parent": "root", "author": "@dict", "text": {}, "like_count": 30}, |
| 150 | {"parent": "root", "author": "@none", "text": None, "like_count": 20}, |
| 151 | {"parent": "root", "author": "@int", "text": 123, "like_count": 15}, |
| 152 | {"parent": "root", "author": "@real", "text": "Actual viewer comment", "like_count": 10}, |
| 153 | ] |
| 154 | payload = json.dumps({"id": "abc123", "comments": raw_comments}) |
| 155 | res = SubprocResult(returncode=0, stdout=payload, stderr="") |
| 156 | |
| 157 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 158 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=res): |
| 159 | comments, ran_cleanly = youtube_yt._ytdlp_comments_result("abc123", max_comments=3) |
| 160 | |
| 161 | assert ran_cleanly is True |
| 162 | assert [c["author"] for c in comments] == ["@real"] |
| 163 | assert comments[0]["text"] == "Actual viewer comment" |
| 164 | |
| 165 | |
| 166 | # --------------------------------------------------------------------------- |
| 167 | # HIGH-180: Bluesky locked/keyed cache, stampede & refresh rotation safety |
| 168 | # --------------------------------------------------------------------------- |
| 169 | |
| 170 | |
| 171 | class TestHigh180BlueskySessionConcurrency: |
| 172 | @pytest.fixture(autouse=True) |
| 173 | def _reset_cache(self): |
| 174 | bluesky._reset_session_cache() |
| 175 | yield |
| 176 | bluesky._reset_session_cache() |
| 177 | |
| 178 | def test_module_error_globals_removed_and_cache_key_hashes_password(self) -> None: |
| 179 | for legacy_global in ( |
| 180 | "_session_error", |
| 181 | "_refresh_error_status", |
| 182 | "_cached_token", |
| 183 | "_cached_refresh_token", |
| 184 | "_token_created_at", |
| 185 | ): |
| 186 | assert not hasattr(bluesky, legacy_global), f"race-prone global {legacy_global} still exists" |
| 187 | |
| 188 | secret_pw = "super-secret-app-pw-1234" |
| 189 | expected_digest = hashlib.sha256(secret_pw.encode("utf-8")).hexdigest() |
| 190 | with mock.patch.object( |
| 191 | bluesky.http, "request", return_value={"accessJwt": "tok-a", "refreshJwt": "ref-a"} |
| 192 | ): |
| 193 | tok, err, status = bluesky._create_session("alice.bsky.social", secret_pw) |
| 194 | |
| 195 | assert (tok, err, status) == ("tok-a", None, None) |
| 196 | keys = list(bluesky._session_cache.keys()) |
| 197 | assert keys == [("alice.bsky.social", expected_digest)] |
| 198 | assert all(secret_pw not in str(k) for k in keys) |
| 199 | assert all(secret_pw not in str(k) for k in bluesky._inflight_auth.keys()) |
| 200 | |
| 201 | def test_cross_account_and_password_change_isolation(self) -> None: |
| 202 | issued = iter([ |
| 203 | {"accessJwt": "tok-alice-1", "refreshJwt": "ref-a1"}, |
| 204 | {"accessJwt": "tok-bob-1", "refreshJwt": "ref-b1"}, |
| 205 | {"accessJwt": "tok-alice-2", "refreshJwt": "ref-a2"}, |
| 206 | ]) |
| 207 | |
| 208 | def fake_request(method, url, **kwargs): |
| 209 | if url == bluesky.BSKY_SESSION_URL: |
| 210 | return next(issued) |
| 211 | return {"posts": [{"uri": "at://did/app.bsky.feed.post/1", "author": {"handle": "u"}, "record": {"text": kwargs["headers"]["Authorization"]}}]} |
| 212 | |
| 213 | with mock.patch.object(bluesky.http, "request", side_effect=fake_request) as req_mock: |
| 214 | r1 = bluesky.search_bluesky("ai", "2026-08-01", "2026-09-01", config={"BSKY_HANDLE": "alice.bsky.social", "BSKY_APP_PASSWORD": "pw-1"}) |
| 215 | r2 = bluesky.search_bluesky("ai", "2026-08-01", "2026-09-01", config={"BSKY_HANDLE": "bob.bsky.social", "BSKY_APP_PASSWORD": "pw-2"}) |
| 216 | r3 = bluesky.search_bluesky("ai", "2026-08-01", "2026-09-01", config={"BSKY_HANDLE": "alice.bsky.social", "BSKY_APP_PASSWORD": "pw-new"}) |
| 217 | # Repeat alice/pw-1 hits cache, not createSession again. |
| 218 | r4 = bluesky.search_bluesky("ai", "2026-08-01", "2026-09-01", config={"BSKY_HANDLE": "alice.bsky.social", "BSKY_APP_PASSWORD": "pw-1"}) |
| 219 | |
| 220 | assert r1["posts"][0]["record"]["text"] == "Bearer tok-alice-1" |
| 221 | assert r2["posts"][0]["record"]["text"] == "Bearer tok-bob-1" |
| 222 | assert r3["posts"][0]["record"]["text"] == "Bearer tok-alice-2" |
| 223 | assert r4["posts"][0]["record"]["text"] == "Bearer tok-alice-1" |
| 224 | create_calls = [c for c in req_mock.call_args_list if c.args[1] == bluesky.BSKY_SESSION_URL] |
| 225 | assert len(create_calls) == 3 |
| 226 | |
| 227 | def test_concurrent_create_session_prevents_stampede(self) -> None: |
| 228 | create_calls = 0 |
| 229 | create_lock = threading.Lock() |
| 230 | start_barrier = threading.Barrier(8) |
| 231 | |
| 232 | def fake_request(method, url, **kwargs): |
| 233 | nonlocal create_calls |
| 234 | if url == bluesky.BSKY_SESSION_URL: |
| 235 | with create_lock: |
| 236 | create_calls += 1 |
| 237 | time.sleep(0.05) |
| 238 | return {"accessJwt": "tok-shared", "refreshJwt": "ref-shared"} |
| 239 | assert kwargs["headers"] == {"Authorization": "Bearer tok-shared"} |
| 240 | return {"posts": [{"uri": "at://did/app.bsky.feed.post/1", "author": {"handle": "u"}, "record": {"text": "ok"}}]} |
| 241 | |
| 242 | cfg = {"BSKY_HANDLE": "alice.bsky.social", "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop"} |
| 243 | |
| 244 | def worker(idx: int): |
| 245 | start_barrier.wait(timeout=5) |
| 246 | return bluesky.search_bluesky(f"topic {idx}", "2026-08-01", "2026-09-01", config=cfg) |
| 247 | |
| 248 | with mock.patch.object(bluesky.http, "request", side_effect=fake_request): |
| 249 | with ThreadPoolExecutor(max_workers=8) as pool: |
| 250 | results = list(pool.map(worker, range(8))) |
| 251 | |
| 252 | assert create_calls == 1 |
| 253 | assert all("error" not in r and len(r["posts"]) == 1 for r in results) |
| 254 | |
| 255 | def test_concurrent_failed_create_session_shares_error_and_allows_later_retry(self) -> None: |
| 256 | create_calls = 0 |
| 257 | create_lock = threading.Lock() |
| 258 | start_barrier = threading.Barrier(6) |
| 259 | fail_first = True |
| 260 | |
| 261 | def fake_request(method, url, **kwargs): |
| 262 | nonlocal create_calls |
| 263 | if url == bluesky.BSKY_SESSION_URL: |
| 264 | with create_lock: |
| 265 | create_calls += 1 |
| 266 | should_fail = fail_first |
| 267 | if should_fail: |
| 268 | time.sleep(0.08) |
| 269 | raise http.HTTPError("HTTP 503: Service Unavailable", 503, "") |
| 270 | return {"accessJwt": "tok-recovered", "refreshJwt": "ref-recovered"} |
| 271 | assert kwargs["headers"] == {"Authorization": "Bearer tok-recovered"} |
| 272 | return {"posts": [{"uri": "at://did/app.bsky.feed.post/ok", "author": {"handle": "u"}, "record": {"text": "ok"}}]} |
| 273 | |
| 274 | cfg = {"BSKY_HANDLE": "alice.bsky.social", "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop"} |
| 275 | |
| 276 | def worker(idx: int): |
| 277 | start_barrier.wait(timeout=5) |
| 278 | return bluesky.search_bluesky(f"topic {idx}", "2026-08-01", "2026-09-01", config=cfg) |
| 279 | |
| 280 | with mock.patch.object(bluesky.http, "request", side_effect=fake_request): |
| 281 | start = time.monotonic() |
| 282 | with ThreadPoolExecutor(max_workers=6) as pool: |
| 283 | results = list(pool.map(worker, range(6))) |
| 284 | elapsed = time.monotonic() - start |
| 285 | |
| 286 | assert create_calls == 1 |
| 287 | assert elapsed < 1.0 |
| 288 | assert all(r["posts"] == [] and "503" in r["error"] for r in results) |
| 289 | assert bluesky._inflight_auth == {} |
| 290 | |
| 291 | # A subsequent search after the in-flight attempt completes tries again. |
| 292 | fail_first = False |
| 293 | later = bluesky.search_bluesky("later", "2026-08-01", "2026-09-01", config=cfg) |
| 294 | |
| 295 | assert create_calls == 2 |
| 296 | assert "error" not in later |
| 297 | assert len(later["posts"]) == 1 |
| 298 | |
| 299 | def test_singleflight_clears_slot_and_wakes_waiters_on_leader_base_exception(self) -> None: |
| 300 | entered = threading.Event() |
| 301 | waiter_waiting = threading.Event() |
| 302 | release = threading.Event() |
| 303 | orig_wait = bluesky._wait_for_inflight_auth |
| 304 | |
| 305 | def aborting_request(method, url, **kwargs): |
| 306 | entered.set() |
| 307 | assert release.wait(timeout=5) |
| 308 | raise KeyboardInterrupt("simulated abort") |
| 309 | |
| 310 | def tracked_wait(inflight): |
| 311 | waiter_waiting.set() |
| 312 | return orig_wait(inflight) |
| 313 | |
| 314 | with ( |
| 315 | mock.patch.object(bluesky.http, "request", side_effect=aborting_request), |
| 316 | mock.patch.object(bluesky, "_wait_for_inflight_auth", side_effect=tracked_wait), |
| 317 | ): |
| 318 | leader_exc: list[BaseException] = [] |
| 319 | waiter_result: list[tuple] = [] |
| 320 | |
| 321 | def run_leader() -> None: |
| 322 | try: |
| 323 | bluesky._create_session("alice.bsky.social", "abcd-efgh-ijkl-mnop") |
| 324 | except BaseException as exc: |
| 325 | leader_exc.append(exc) |
| 326 | |
| 327 | def run_waiter() -> None: |
| 328 | assert entered.wait(timeout=5) |
| 329 | waiter_result.append( |
| 330 | bluesky._create_session("alice.bsky.social", "abcd-efgh-ijkl-mnop") |
| 331 | ) |
| 332 | |
| 333 | t1 = threading.Thread(target=run_leader) |
| 334 | t2 = threading.Thread(target=run_waiter) |
| 335 | t1.start() |
| 336 | t2.start() |
| 337 | assert entered.wait(timeout=5) |
| 338 | assert waiter_waiting.wait(timeout=5) |
| 339 | release.set() |
| 340 | t1.join(timeout=5) |
| 341 | t2.join(timeout=5) |
| 342 | |
| 343 | assert not t1.is_alive() and not t2.is_alive() |
| 344 | assert len(leader_exc) == 1 and isinstance(leader_exc[0], KeyboardInterrupt) |
| 345 | assert waiter_result[0][0] is None |
| 346 | assert "KeyboardInterrupt" in (waiter_result[0][1] or "") |
| 347 | assert bluesky._inflight_auth == {} |
| 348 | |
| 349 | def test_create_session_log_failure_clears_inflight_slot_and_wakes_waiters(self) -> None: |
| 350 | handle = "alice.bsky.social" |
| 351 | app_password = "abcd-efgh-ijkl-mnop" |
| 352 | cred_key = bluesky._credential_key(handle, app_password) |
| 353 | bluesky._session_cache[cred_key] = bluesky._SessionEntry( |
| 354 | access_token="tok-expired", |
| 355 | refresh_token="ref-expired", |
| 356 | created_at=time.monotonic() - bluesky._TOKEN_MAX_AGE_SECONDS - 10, |
| 357 | ) |
| 358 | |
| 359 | log_entered = threading.Event() |
| 360 | waiter_waiting = threading.Event() |
| 361 | orig_wait = bluesky._wait_for_inflight_auth |
| 362 | |
| 363 | def failing_log(msg: str) -> None: |
| 364 | if "Session token expired" in msg: |
| 365 | log_entered.set() |
| 366 | assert waiter_waiting.wait(timeout=5) |
| 367 | raise OSError("stderr closed") |
| 368 | |
| 369 | def tracked_wait(inflight) -> None: |
| 370 | waiter_waiting.set() |
| 371 | return orig_wait(inflight) |
| 372 | |
| 373 | leader_exc: list[BaseException] = [] |
| 374 | waiter_result: list[tuple] = [] |
| 375 | |
| 376 | def run_leader() -> None: |
| 377 | try: |
| 378 | bluesky._create_session(handle, app_password) |
| 379 | except BaseException as exc: |
| 380 | leader_exc.append(exc) |
| 381 | |
| 382 | def run_waiter() -> None: |
| 383 | assert log_entered.wait(timeout=5) |
| 384 | waiter_result.append(bluesky._create_session(handle, app_password)) |
| 385 | |
| 386 | with ( |
| 387 | mock.patch.object(bluesky, "_log", side_effect=failing_log), |
| 388 | mock.patch.object(bluesky, "_wait_for_inflight_auth", side_effect=tracked_wait), |
| 389 | ): |
| 390 | t1 = threading.Thread(target=run_leader) |
| 391 | t2 = threading.Thread(target=run_waiter) |
| 392 | t1.start() |
| 393 | t2.start() |
| 394 | t1.join(timeout=5) |
| 395 | t2.join(timeout=5) |
| 396 | |
| 397 | assert not t1.is_alive() and not t2.is_alive() |
| 398 | assert len(leader_exc) == 1 and isinstance(leader_exc[0], OSError) |
| 399 | assert waiter_result[0][0] is None |
| 400 | assert "OSError" in (waiter_result[0][1] or "") |
| 401 | assert bluesky._inflight_auth == {} |
| 402 | |
| 403 | with mock.patch.object( |
| 404 | bluesky.http, |
| 405 | "request", |
| 406 | return_value={"accessJwt": "tok-after-log-err", "refreshJwt": "ref-after"}, |
| 407 | ): |
| 408 | tok, err, status = bluesky._create_session(handle, app_password) |
| 409 | assert (tok, err, status) == ("tok-after-log-err", None, None) |
| 410 | |
| 411 | def test_concurrent_401_single_use_refresh_rotation_reuses_fresh_token(self) -> None: |
| 412 | cfg = {"BSKY_HANDLE": "alice.bsky.social", "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop"} |
| 413 | cred_key = bluesky._credential_key(cfg["BSKY_HANDLE"], cfg["BSKY_APP_PASSWORD"]) |
| 414 | bluesky._session_cache[cred_key] = bluesky._SessionEntry( |
| 415 | access_token="tok-stale", |
| 416 | refresh_token="ref-single-use", |
| 417 | created_at=time.monotonic(), |
| 418 | ) |
| 419 | |
| 420 | # Synchronize both threads so both observe 401 on tok-stale before either recovers. |
| 421 | both_got_401 = threading.Barrier(2) |
| 422 | state_lock = threading.Lock() |
| 423 | refresh_calls = 0 |
| 424 | session_calls = 0 |
| 425 | ref_consumed = False |
| 426 | |
| 427 | def fake_request(method, url, **kwargs): |
| 428 | nonlocal refresh_calls, session_calls, ref_consumed |
| 429 | if url == bluesky.BSKY_SESSION_URL: |
| 430 | with state_lock: |
| 431 | session_calls += 1 |
| 432 | raise AssertionError("createSession must not run when single-use refresh succeeded") |
| 433 | if url == bluesky.BSKY_REFRESH_URL: |
| 434 | with state_lock: |
| 435 | refresh_calls += 1 |
| 436 | if ref_consumed: |
| 437 | # Real AT Protocol rejects a consumed single-use refresh JWT. |
| 438 | raise http.HTTPError("HTTP 400: Refresh token already used", 400, "") |
| 439 | ref_consumed = True |
| 440 | time.sleep(0.05) |
| 441 | return {"accessJwt": "tok-fresh", "refreshJwt": "ref-fresh"} |
| 442 | auth = kwargs["headers"]["Authorization"] |
| 443 | if auth == "Bearer tok-stale": |
| 444 | both_got_401.wait(timeout=5) |
| 445 | raise http.HTTPError("HTTP 401: ExpiredToken", 401, "") |
| 446 | assert auth == "Bearer tok-fresh" |
| 447 | return {"posts": [{"uri": "at://did/app.bsky.feed.post/ok", "author": {"handle": "u"}, "record": {"text": "rotated"}}]} |
| 448 | |
| 449 | def worker(idx: int): |
| 450 | return bluesky.search_bluesky(f"query {idx}", "2026-08-01", "2026-09-01", config=cfg) |
| 451 | |
| 452 | with mock.patch.object(bluesky.http, "request", side_effect=fake_request): |
| 453 | with ThreadPoolExecutor(max_workers=2) as pool: |
| 454 | results = list(pool.map(worker, range(2))) |
| 455 | |
| 456 | assert refresh_calls == 1 |
| 457 | assert session_calls == 0 |
| 458 | assert all("error" not in r and len(r["posts"]) == 1 for r in results) |
| 459 | entry = bluesky._session_cache[cred_key] |
| 460 | assert entry.access_token == "tok-fresh" |
| 461 | assert entry.refresh_token == "ref-fresh" |
| 462 | |
| 463 | def test_concurrent_401_rejected_refresh_reauthenticates_once(self) -> None: |
| 464 | cfg = {"BSKY_HANDLE": "alice.bsky.social", "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop"} |
| 465 | cred_key = bluesky._credential_key(cfg["BSKY_HANDLE"], cfg["BSKY_APP_PASSWORD"]) |
| 466 | bluesky._session_cache[cred_key] = bluesky._SessionEntry( |
| 467 | access_token="tok-stale", |
| 468 | refresh_token="ref-dead", |
| 469 | created_at=time.monotonic(), |
| 470 | ) |
| 471 | |
| 472 | both_got_401 = threading.Barrier(2) |
| 473 | state_lock = threading.Lock() |
| 474 | refresh_calls = 0 |
| 475 | session_calls = 0 |
| 476 | |
| 477 | def fake_request(method, url, **kwargs): |
| 478 | nonlocal refresh_calls, session_calls |
| 479 | if url == bluesky.BSKY_REFRESH_URL: |
| 480 | with state_lock: |
| 481 | refresh_calls += 1 |
| 482 | raise http.HTTPError("HTTP 401: Invalid refresh", 401, "") |
| 483 | if url == bluesky.BSKY_SESSION_URL: |
| 484 | with state_lock: |
| 485 | session_calls += 1 |
| 486 | time.sleep(0.04) |
| 487 | return {"accessJwt": "tok-reauthed", "refreshJwt": "ref-reauthed"} |
| 488 | if kwargs["headers"]["Authorization"] == "Bearer tok-stale": |
| 489 | both_got_401.wait(timeout=5) |
| 490 | raise http.HTTPError("HTTP 401: Expired", 401, "") |
| 491 | assert kwargs["headers"]["Authorization"] == "Bearer tok-reauthed" |
| 492 | return {"posts": [{"uri": "at://did/app.bsky.feed.post/ok", "author": {"handle": "u"}, "record": {"text": "reauthed"}}]} |
| 493 | |
| 494 | with mock.patch.object(bluesky.http, "request", side_effect=fake_request): |
| 495 | with ThreadPoolExecutor(max_workers=2) as pool: |
| 496 | results = list(pool.map(lambda i: bluesky.search_bluesky(f"q{i}", "2026-08-01", "2026-09-01", config=cfg), range(2))) |
| 497 | |
| 498 | assert refresh_calls == 1 |
| 499 | assert session_calls == 1 |
| 500 | assert all("error" not in r and len(r["posts"]) == 1 for r in results) |
| 501 | |
| 502 | @pytest.mark.parametrize("refresh_succeeds", [True, False]) |
| 503 | def test_post_recovery_401_evicts_rejected_token_from_cache(self, refresh_succeeds: bool) -> None: |
| 504 | cfg = {"BSKY_HANDLE": "alice.bsky.social", "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop"} |
| 505 | cred_key = bluesky._credential_key(cfg["BSKY_HANDLE"], cfg["BSKY_APP_PASSWORD"]) |
| 506 | unauth = http.HTTPError("HTTP 401: Unauthorized", 401, "") |
| 507 | |
| 508 | if refresh_succeeds: |
| 509 | side_effects = [ |
| 510 | {"accessJwt": "tok-1", "refreshJwt": "ref-1"}, |
| 511 | unauth, |
| 512 | {"accessJwt": "tok-bad-refreshed", "refreshJwt": "ref-2"}, |
| 513 | unauth, |
| 514 | ] |
| 515 | else: |
| 516 | side_effects = [ |
| 517 | {"accessJwt": "tok-1", "refreshJwt": "ref-1"}, |
| 518 | unauth, |
| 519 | unauth, # refresh rejected |
| 520 | {"accessJwt": "tok-bad-reauthed", "refreshJwt": "ref-3"}, |
| 521 | unauth, |
| 522 | ] |
| 523 | |
| 524 | with mock.patch.object(bluesky.http, "request", side_effect=side_effects): |
| 525 | result = bluesky.search_bluesky("ai", "2026-08-01", "2026-09-01", config=cfg) |
| 526 | |
| 527 | assert result["posts"] == [] |
| 528 | assert "remained unauthorized" in result["error"] |
| 529 | assert cred_key not in bluesky._session_cache |
| 530 | |
| 531 | def test_401_recovery_joins_inflight_login_without_overwriting_newer_session(self) -> None: |
| 532 | cfg = {"BSKY_HANDLE": "alice.bsky.social", "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop"} |
| 533 | cred_key = bluesky._credential_key(cfg["BSKY_HANDLE"], cfg["BSKY_APP_PASSWORD"]) |
| 534 | bluesky._session_cache[cred_key] = bluesky._SessionEntry( |
| 535 | access_token="tok-old", |
| 536 | refresh_token="ref-old", |
| 537 | created_at=time.monotonic() - bluesky._TOKEN_MAX_AGE_SECONDS - 10, |
| 538 | ) |
| 539 | |
| 540 | login_entered = threading.Event() |
| 541 | waiter_waiting = threading.Event() |
| 542 | release_login = threading.Event() |
| 543 | orig_wait = bluesky._wait_for_inflight_auth |
| 544 | state_lock = threading.Lock() |
| 545 | session_calls = 0 |
| 546 | refresh_calls = 0 |
| 547 | |
| 548 | def fake_request(method, url, **kwargs): |
| 549 | nonlocal session_calls, refresh_calls |
| 550 | if url == bluesky.BSKY_SESSION_URL: |
| 551 | with state_lock: |
| 552 | session_calls += 1 |
| 553 | login_entered.set() |
| 554 | assert release_login.wait(timeout=5) |
| 555 | return {"accessJwt": "tok-newer-login", "refreshJwt": "ref-newer-login"} |
| 556 | if url == bluesky.BSKY_REFRESH_URL: |
| 557 | with state_lock: |
| 558 | refresh_calls += 1 |
| 559 | raise AssertionError("refreshSession must not race an in-flight createSession") |
| 560 | assert kwargs["headers"] == {"Authorization": "Bearer tok-newer-login"} |
| 561 | return {"posts": [{"uri": "at://did/app.bsky.feed.post/ok", "author": {"handle": "u"}, "record": {"text": "fresh"}}]} |
| 562 | |
| 563 | def tracked_wait(inflight) -> None: |
| 564 | waiter_waiting.set() |
| 565 | return orig_wait(inflight) |
| 566 | |
| 567 | login_result: list[dict] = [] |
| 568 | recovery_result: list[tuple] = [] |
| 569 | |
| 570 | def run_expired_search() -> None: |
| 571 | login_result.append( |
| 572 | bluesky.search_bluesky("ai", "2026-08-01", "2026-09-01", config=cfg) |
| 573 | ) |
| 574 | |
| 575 | def run_401_recovery() -> None: |
| 576 | assert login_entered.wait(timeout=5) |
| 577 | recovery_result.append( |
| 578 | bluesky._recover_session( |
| 579 | cfg["BSKY_HANDLE"], cfg["BSKY_APP_PASSWORD"], cred_key, "tok-old" |
| 580 | ) |
| 581 | ) |
| 582 | |
| 583 | with ( |
| 584 | mock.patch.object(bluesky.http, "request", side_effect=fake_request), |
| 585 | mock.patch.object(bluesky, "_wait_for_inflight_auth", side_effect=tracked_wait), |
| 586 | ): |
| 587 | t_login = threading.Thread(target=run_expired_search) |
| 588 | t_recover = threading.Thread(target=run_401_recovery) |
| 589 | t_login.start() |
| 590 | t_recover.start() |
| 591 | assert login_entered.wait(timeout=5) |
| 592 | assert waiter_waiting.wait(timeout=5) |
| 593 | release_login.set() |
| 594 | t_login.join(timeout=5) |
| 595 | t_recover.join(timeout=5) |
| 596 | |
| 597 | assert not t_login.is_alive() and not t_recover.is_alive() |
| 598 | assert session_calls == 1 |
| 599 | assert refresh_calls == 0 |
| 600 | assert "error" not in login_result[0] |
| 601 | assert len(login_result[0]["posts"]) == 1 |
| 602 | assert recovery_result == [("tok-newer-login", None, True)] |
| 603 | entry = bluesky._session_cache[cred_key] |
| 604 | assert entry.access_token == "tok-newer-login" |
| 605 | assert entry.refresh_token == "ref-newer-login" |
| 606 | assert bluesky._inflight_auth == {} |
| 607 | |
| 608 | def test_expired_login_joins_inflight_401_recovery_without_racing_refresh(self) -> None: |
| 609 | cfg = {"BSKY_HANDLE": "alice.bsky.social", "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop"} |
| 610 | cred_key = bluesky._credential_key(cfg["BSKY_HANDLE"], cfg["BSKY_APP_PASSWORD"]) |
| 611 | bluesky._session_cache[cred_key] = bluesky._SessionEntry( |
| 612 | access_token="tok-old", |
| 613 | refresh_token="ref-old", |
| 614 | created_at=time.monotonic() - bluesky._TOKEN_MAX_AGE_SECONDS - 10, |
| 615 | ) |
| 616 | |
| 617 | refresh_entered = threading.Event() |
| 618 | waiter_waiting = threading.Event() |
| 619 | release_refresh = threading.Event() |
| 620 | orig_wait = bluesky._wait_for_inflight_auth |
| 621 | state_lock = threading.Lock() |
| 622 | session_calls = 0 |
| 623 | refresh_calls = 0 |
| 624 | |
| 625 | def fake_request(method, url, **kwargs): |
| 626 | nonlocal session_calls, refresh_calls |
| 627 | if url == bluesky.BSKY_REFRESH_URL: |
| 628 | with state_lock: |
| 629 | refresh_calls += 1 |
| 630 | refresh_entered.set() |
| 631 | assert release_refresh.wait(timeout=5) |
| 632 | return {"accessJwt": "tok-refreshed", "refreshJwt": "ref-refreshed"} |
| 633 | if url == bluesky.BSKY_SESSION_URL: |
| 634 | with state_lock: |
| 635 | session_calls += 1 |
| 636 | raise AssertionError("createSession must not race an in-flight 401 refresh") |
| 637 | assert kwargs["headers"] == {"Authorization": "Bearer tok-refreshed"} |
| 638 | return {"posts": [{"uri": "at://did/app.bsky.feed.post/ok", "author": {"handle": "u"}, "record": {"text": "refreshed"}}]} |
| 639 | |
| 640 | def tracked_wait(inflight) -> None: |
| 641 | waiter_waiting.set() |
| 642 | return orig_wait(inflight) |
| 643 | |
| 644 | recovery_result: list[tuple] = [] |
| 645 | search_result: list[dict] = [] |
| 646 | |
| 647 | def run_401_recovery() -> None: |
| 648 | recovery_result.append( |
| 649 | bluesky._recover_session( |
| 650 | cfg["BSKY_HANDLE"], cfg["BSKY_APP_PASSWORD"], cred_key, "tok-old" |
| 651 | ) |
| 652 | ) |
| 653 | |
| 654 | def run_expired_search() -> None: |
| 655 | assert refresh_entered.wait(timeout=5) |
| 656 | search_result.append( |
| 657 | bluesky.search_bluesky("ai", "2026-08-01", "2026-09-01", config=cfg) |
| 658 | ) |
| 659 | |
| 660 | with ( |
| 661 | mock.patch.object(bluesky.http, "request", side_effect=fake_request), |
| 662 | mock.patch.object(bluesky, "_wait_for_inflight_auth", side_effect=tracked_wait), |
| 663 | ): |
| 664 | t_recover = threading.Thread(target=run_401_recovery) |
| 665 | t_search = threading.Thread(target=run_expired_search) |
| 666 | t_recover.start() |
| 667 | t_search.start() |
| 668 | assert refresh_entered.wait(timeout=5) |
| 669 | assert waiter_waiting.wait(timeout=5) |
| 670 | release_refresh.set() |
| 671 | t_recover.join(timeout=5) |
| 672 | t_search.join(timeout=5) |
| 673 | |
| 674 | assert not t_recover.is_alive() and not t_search.is_alive() |
| 675 | assert refresh_calls == 1 |
| 676 | assert session_calls == 0 |
| 677 | assert recovery_result == [("tok-refreshed", None, False)] |
| 678 | assert "error" not in search_result[0] |
| 679 | assert len(search_result[0]["posts"]) == 1 |
| 680 | entry = bluesky._session_cache[cred_key] |
| 681 | assert entry.access_token == "tok-refreshed" |
| 682 | assert entry.refresh_token == "ref-refreshed" |
| 683 | assert bluesky._inflight_auth == {} |
| 684 | |
| 685 | |
| 686 | # --------------------------------------------------------------------------- |
| 687 | # HIGH-188: LinkedIn 404 "No posts found" & search_profile failure-sink isolation |
| 688 | # --------------------------------------------------------------------------- |
| 689 | |
| 690 | |
| 691 | class TestHigh188LinkedinFailureSinkIsolation: |
| 692 | def test_no_posts_found_404_is_clean_empty_without_polluting_outer_sink(self, monkeypatch) -> None: |
| 693 | def open_404_no_posts(req, timeout): |
| 694 | raise urllib.error.HTTPError( |
| 695 | req.full_url, |
| 696 | 404, |
| 697 | "Not Found", |
| 698 | {}, |
| 699 | io.BytesIO(b'{"message": "No posts found"}'), |
| 700 | ) |
| 701 | |
| 702 | monkeypatch.setattr(http, "_open_request", open_404_no_posts) |
| 703 | |
| 704 | with http.capture_failures() as outer_failures: |
| 705 | result = linkedin.search_linkedin( |
| 706 | "hyper-niche-topic", "2026-06-01", "2026-06-30", token="dummy-sc-key" |
| 707 | ) |
| 708 | |
| 709 | assert result == {"posts": []} |
| 710 | assert "error" not in result |
| 711 | assert outer_failures == [] |
| 712 | # Verify pipeline outcome resolver sees no failure either. |
| 713 | outcome = pipeline._resolve_stream_outcome("linkedin", {}, outer_failures) |
| 714 | assert outcome is None |
| 715 | |
| 716 | @pytest.mark.parametrize( |
| 717 | "body", |
| 718 | [ |
| 719 | b"<html><title>404 Not Found</title><body>Cannot GET /v1/linkedin/search/posts</body></html>", |
| 720 | b'{"message": "Route not found"}', |
| 721 | b"", |
| 722 | ], |
| 723 | ) |
| 724 | def test_non_empty_result_404_surfaces_as_error_and_records_in_outer_sink( |
| 725 | self, monkeypatch, body: bytes |
| 726 | ) -> None: |
| 727 | def open_bad_404(req, timeout): |
| 728 | raise urllib.error.HTTPError( |
| 729 | req.full_url, |
| 730 | 404, |
| 731 | "Not Found", |
| 732 | {}, |
| 733 | io.BytesIO(body), |
| 734 | ) |
| 735 | |
| 736 | monkeypatch.setattr(http, "_open_request", open_bad_404) |
| 737 | |
| 738 | with http.capture_failures() as outer_failures: |
| 739 | result = linkedin.search_linkedin( |
| 740 | "ai agents", "2026-06-01", "2026-06-30", token="dummy-sc-key" |
| 741 | ) |
| 742 | |
| 743 | assert result["posts"] == [] |
| 744 | assert "error" in result |
| 745 | assert len(outer_failures) >= 1 |
| 746 | assert outer_failures[0].status_code == 404 |
| 747 | |
| 748 | def test_search_profile_error_does_not_pollute_outer_failure_sink(self, monkeypatch) -> None: |
| 749 | def open_500(req, timeout): |
| 750 | raise urllib.error.HTTPError( |
| 751 | req.full_url, |
| 752 | 500, |
| 753 | "Internal Server Error", |
| 754 | {}, |
| 755 | io.BytesIO(b"upstream error"), |
| 756 | ) |
| 757 | |
| 758 | monkeypatch.setattr(http, "_open_request", open_500) |
| 759 | monkeypatch.setattr(http.time, "sleep", lambda _s: None) |
| 760 | |
| 761 | with http.capture_failures() as outer_failures: |
| 762 | profile = linkedin.search_profile("https://www.linkedin.com/in/janedoe", "dummy-sc-key") |
| 763 | |
| 764 | assert profile == {} |
| 765 | assert outer_failures == [] |
| 766 | |
| 767 | |
| 768 | # --------------------------------------------------------------------------- |
| 769 | # HIGH-217: Corpus pdftotext UTF-8 flag, `--`, bounded streaming, UnicodeError |
| 770 | # --------------------------------------------------------------------------- |
| 771 | |
| 772 | |
| 773 | def _write_fake_pdftotext(tmp_path: Path, body: str) -> Path: |
| 774 | script = tmp_path / "fake_pdftotext.py" |
| 775 | script.write_text(f"#!{sys.executable}\n{body}\n", encoding="utf-8") |
| 776 | script.chmod(script.stat().st_mode | stat.S_IXUSR) |
| 777 | return script |
| 778 | |
| 779 | |
| 780 | class TestHigh217CorpusPdfHardening: |
| 781 | def test_pdftotext_uses_utf8_and_separator_and_decodes_invalid_bytes_safely( |
| 782 | self, tmp_path: Path, monkeypatch |
| 783 | ) -> None: |
| 784 | args_log = tmp_path / "argv.json" |
| 785 | fake_bin = _write_fake_pdftotext( |
| 786 | tmp_path, |
| 787 | f""" |
| 788 | import json, sys |
| 789 | with open({str(args_log)!r}, "w", encoding="utf-8") as fh: |
| 790 | json.dump(sys.argv[1:], fh) |
| 791 | sys.stdout.buffer.write(b"MCP servers \\xff\\xfe local pdf notes") |
| 792 | sys.stdout.buffer.flush() |
| 793 | """, |
| 794 | ) |
| 795 | docs = tmp_path / "docs" |
| 796 | docs.mkdir() |
| 797 | pdf = docs / "-dash-name.pdf" |
| 798 | pdf.write_bytes(b"%PDF-1.4") |
| 799 | |
| 800 | monkeypatch.setattr(corpus, "which", lambda _name: str(fake_bin)) |
| 801 | |
| 802 | result = corpus.search( |
| 803 | "MCP servers", |
| 804 | [docs], |
| 805 | from_date="2026-06-01", |
| 806 | to_date="2026-07-01", |
| 807 | all_time=True, |
| 808 | cache_dir=tmp_path / "cache", |
| 809 | ) |
| 810 | |
| 811 | argv = json.loads(args_log.read_text(encoding="utf-8")) |
| 812 | assert argv == ["-enc", "UTF-8", "--", str(pdf.resolve()), "-"] |
| 813 | assert len(result.items) == 1 |
| 814 | assert "MCP servers" in result.items[0].body |
| 815 | assert "\ufffd" in result.items[0].body |
| 816 | |
| 817 | def test_pdftotext_caps_streamed_bytes_and_terminates_huge_output_early( |
| 818 | self, tmp_path: Path, monkeypatch |
| 819 | ) -> None: |
| 820 | fake_bin = _write_fake_pdftotext( |
| 821 | tmp_path, |
| 822 | """ |
| 823 | import sys |
| 824 | chunk = b"MCP servers " * 4096 # ~48 KiB per write |
| 825 | try: |
| 826 | for _ in range(1000): # ~48 MiB total if uncapped |
| 827 | sys.stdout.buffer.write(chunk) |
| 828 | sys.stdout.buffer.flush() |
| 829 | except BrokenPipeError: |
| 830 | pass |
| 831 | """, |
| 832 | ) |
| 833 | pdf = tmp_path / "huge.pdf" |
| 834 | pdf.write_bytes(b"%PDF-1.4") |
| 835 | monkeypatch.setattr(corpus, "MAX_TEXT_CHARS", 256) |
| 836 | |
| 837 | start = time.monotonic() |
| 838 | extracted = corpus._extract_text(pdf, pdftotext=str(fake_bin)) |
| 839 | elapsed = time.monotonic() - start |
| 840 | |
| 841 | assert len(extracted) == 256 |
| 842 | assert extracted.startswith("MCP servers ") |
| 843 | assert elapsed < 5.0 |
| 844 | |
| 845 | def test_pdftotext_timeout_kills_hanging_child_and_search_continues( |
| 846 | self, tmp_path: Path, monkeypatch |
| 847 | ) -> None: |
| 848 | fake_bin = _write_fake_pdftotext( |
| 849 | tmp_path, |
| 850 | """ |
| 851 | import time |
| 852 | time.sleep(30) |
| 853 | """, |
| 854 | ) |
| 855 | docs = tmp_path / "docs" |
| 856 | docs.mkdir() |
| 857 | (docs / "hang.pdf").write_bytes(b"%PDF-1.4") |
| 858 | (docs / "good.md").write_text("MCP servers survive a hanging PDF", encoding="utf-8") |
| 859 | |
| 860 | monkeypatch.setattr(corpus, "which", lambda _name: str(fake_bin)) |
| 861 | monkeypatch.setattr(corpus, "PDF_TIMEOUT_SECONDS", 0.3) |
| 862 | |
| 863 | start = time.monotonic() |
| 864 | result = corpus.search( |
| 865 | "MCP servers", |
| 866 | [docs], |
| 867 | from_date="2026-06-01", |
| 868 | to_date="2026-07-01", |
| 869 | all_time=True, |
| 870 | cache_dir=tmp_path / "cache", |
| 871 | ) |
| 872 | elapsed = time.monotonic() - start |
| 873 | |
| 874 | assert elapsed < 5.0 |
| 875 | assert [item.title for item in result.items] == ["good"] |
| 876 | assert any("TimeoutExpired" in note for note in result.notes) |
| 877 | assert all(str(tmp_path) not in note for note in result.notes) |
| 878 | |
| 879 | def test_search_catches_unicode_error_and_continues_other_files( |
| 880 | self, tmp_path: Path, monkeypatch |
| 881 | ) -> None: |
| 882 | docs = tmp_path / "docs" |
| 883 | docs.mkdir() |
| 884 | bad = docs / "bad.pdf" |
| 885 | bad.write_bytes(b"%PDF-1.4") |
| 886 | good = docs / "good.md" |
| 887 | good.write_text("MCP servers good markdown doc", encoding="utf-8") |
| 888 | |
| 889 | orig_extract = corpus._extract_text |
| 890 | |
| 891 | def flaky_extract(path: Path, *, pdftotext: str | None) -> str: |
| 892 | if path.name == "bad.pdf": |
| 893 | raise UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid start byte") |
| 894 | return orig_extract(path, pdftotext=pdftotext) |
| 895 | |
| 896 | monkeypatch.setattr(corpus, "which", lambda _name: "/usr/bin/pdftotext") |
| 897 | monkeypatch.setattr(corpus, "_extract_text", flaky_extract) |
| 898 | |
| 899 | result = corpus.search( |
| 900 | "MCP servers", |
| 901 | [docs], |
| 902 | from_date="2026-06-01", |
| 903 | to_date="2026-07-01", |
| 904 | all_time=True, |
| 905 | cache_dir=tmp_path / "cache", |
| 906 | ) |
| 907 | |
| 908 | assert [item.title for item in result.items] == ["good"] |
| 909 | assert any("UnicodeDecodeError" in note for note in result.notes) |
| 910 | assert all(str(tmp_path) not in note for note in result.notes) |
| 911 | |
| 912 | def test_pdftotext_timeout_does_not_deadlock_when_detached_descendant_holds_stdout( |
| 913 | self, tmp_path: Path, monkeypatch |
| 914 | ) -> None: |
| 915 | pid_file = tmp_path / "descendant.pid" |
| 916 | fake_bin = _write_fake_pdftotext( |
| 917 | tmp_path, |
| 918 | f""" |
| 919 | import subprocess, sys, time |
| 920 | # Detached descendant inherits stdout and survives proc.kill()/killpg(), |
| 921 | # keeping the reader thread blocked inside BufferedReader.read(). |
| 922 | child = subprocess.Popen( |
| 923 | [sys.executable, "-c", "import time; time.sleep(30)"], |
| 924 | stdin=subprocess.DEVNULL, |
| 925 | stdout=sys.stdout, |
| 926 | stderr=subprocess.DEVNULL, |
| 927 | start_new_session=True, |
| 928 | ) |
| 929 | with open({str(pid_file)!r}, "w", encoding="utf-8") as fh: |
| 930 | fh.write(str(child.pid)) |
| 931 | time.sleep(30) |
| 932 | """, |
| 933 | ) |
| 934 | docs = tmp_path / "docs" |
| 935 | docs.mkdir() |
| 936 | pdf = docs / "leaked-fd.pdf" |
| 937 | pdf.write_bytes(b"%PDF-1.4") |
| 938 | (docs / "good.md").write_text("MCP servers survive leaked pipe fd", encoding="utf-8") |
| 939 | |
| 940 | monkeypatch.setattr(corpus, "which", lambda _name: str(fake_bin)) |
| 941 | monkeypatch.setattr(corpus, "PDF_TIMEOUT_SECONDS", 0.2) |
| 942 | |
| 943 | descendant_pids: list[int] = [] |
| 944 | spawned: list[subprocess.Popen] = [] |
| 945 | real_popen = subprocess.Popen |
| 946 | |
| 947 | def tracking_popen(*args, **kwargs): |
| 948 | proc = real_popen(*args, **kwargs) |
| 949 | spawned.append(proc) |
| 950 | return proc |
| 951 | |
| 952 | monkeypatch.setattr(corpus.subprocess, "Popen", tracking_popen) |
| 953 | threads_before = threading.active_count() |
| 954 | try: |
| 955 | start = time.monotonic() |
| 956 | with pytest.raises(subprocess.TimeoutExpired): |
| 957 | corpus._extract_pdf_text(pdf, str(fake_bin)) |
| 958 | elapsed = time.monotonic() - start |
| 959 | assert elapsed < 2.0, f"_extract_pdf_text hung for {elapsed:.2f}s" |
| 960 | assert spawned and spawned[-1].stdout is not None and spawned[-1].stdout.closed |
| 961 | assert threading.active_count() == threads_before |
| 962 | if pid_file.exists(): |
| 963 | descendant_pids.append(int(pid_file.read_text(encoding="utf-8").strip())) |
| 964 | pid_file.unlink() |
| 965 | |
| 966 | start = time.monotonic() |
| 967 | result = corpus.search( |
| 968 | "MCP servers", |
| 969 | [docs], |
| 970 | from_date="2026-06-01", |
| 971 | to_date="2026-07-01", |
| 972 | all_time=True, |
| 973 | cache_dir=tmp_path / "cache", |
| 974 | ) |
| 975 | elapsed = time.monotonic() - start |
| 976 | assert elapsed < 2.0, f"corpus.search hung for {elapsed:.2f}s" |
| 977 | assert [item.title for item in result.items] == ["good"] |
| 978 | assert any("TimeoutExpired" in note for note in result.notes) |
| 979 | assert spawned[-1].stdout is not None and spawned[-1].stdout.closed |
| 980 | assert threading.active_count() == threads_before |
| 981 | if pid_file.exists(): |
| 982 | descendant_pids.append(int(pid_file.read_text(encoding="utf-8").strip())) |
| 983 | finally: |
| 984 | for pid in descendant_pids: |
| 985 | try: |
| 986 | os.kill(pid, signal.SIGKILL) |
| 987 | except OSError: |
| 988 | pass |
| 989 | |
| 990 | def test_pdftotext_registers_with_subproc_and_cleanup_children_kills_it( |
| 991 | self, tmp_path: Path, monkeypatch |
| 992 | ) -> None: |
| 993 | started_flag = tmp_path / "started.txt" |
| 994 | fake_bin = _write_fake_pdftotext( |
| 995 | tmp_path, |
| 996 | f""" |
| 997 | import pathlib, time |
| 998 | pathlib.Path({str(started_flag)!r}).write_text("ready", encoding="utf-8") |
| 999 | time.sleep(30) |
| 1000 | """, |
| 1001 | ) |
| 1002 | pdf = tmp_path / "cancel-me.pdf" |
| 1003 | pdf.write_bytes(b"%PDF-1.4") |
| 1004 | |
| 1005 | registered: list[int] = [] |
| 1006 | unregistered: list[int] = [] |
| 1007 | orig_reg = subproc.register_child_pid |
| 1008 | orig_unreg = subproc.unregister_child_pid |
| 1009 | |
| 1010 | def spy_reg(pid: int) -> None: |
| 1011 | registered.append(pid) |
| 1012 | orig_reg(pid) |
| 1013 | |
| 1014 | def spy_unreg(pid: int) -> None: |
| 1015 | unregistered.append(pid) |
| 1016 | orig_unreg(pid) |
| 1017 | |
| 1018 | monkeypatch.setattr(subproc, "register_child_pid", spy_reg) |
| 1019 | monkeypatch.setattr(subproc, "unregister_child_pid", spy_unreg) |
| 1020 | monkeypatch.setattr(corpus, "PDF_TIMEOUT_SECONDS", 15.0) |
| 1021 | monkeypatch.setattr(subproc, "_shutting_down", False) |
| 1022 | |
| 1023 | outcome: list[BaseException] = [] |
| 1024 | |
| 1025 | def run_extract() -> None: |
| 1026 | try: |
| 1027 | corpus._extract_pdf_text(pdf, str(fake_bin)) |
| 1028 | except BaseException as exc: |
| 1029 | outcome.append(exc) |
| 1030 | |
| 1031 | worker = threading.Thread(target=run_extract) |
| 1032 | worker.start() |
| 1033 | try: |
| 1034 | wait_until = time.monotonic() + 5.0 |
| 1035 | while not started_flag.exists() and time.monotonic() < wait_until: |
| 1036 | time.sleep(0.02) |
| 1037 | assert started_flag.exists() |
| 1038 | assert len(registered) == 1 |
| 1039 | assert registered[0] in subproc._child_pids |
| 1040 | |
| 1041 | start = time.monotonic() |
| 1042 | subproc.cleanup_children(grace=0.3) |
| 1043 | worker.join(timeout=5.0) |
| 1044 | elapsed = time.monotonic() - start |
| 1045 | finally: |
| 1046 | subproc._shutting_down = False |
| 1047 | |
| 1048 | assert not worker.is_alive() |
| 1049 | assert elapsed < 3.0 |
| 1050 | assert len(outcome) == 1 and isinstance(outcome[0], subprocess.CalledProcessError) |
| 1051 | assert unregistered == registered |
| 1052 | assert registered[0] not in subproc._child_pids |
| 1053 | |
| 1054 | def test_pdftotext_fallback_supports_mock_popen_without_fileno( |
| 1055 | self, tmp_path: Path, monkeypatch |
| 1056 | ) -> None: |
| 1057 | pdf = tmp_path / "mocked.pdf" |
| 1058 | pdf.write_bytes(b"%PDF-1.4") |
| 1059 | |
| 1060 | class _FakeProc: |
| 1061 | def __init__(self, payload: bytes, returncode: int = 0) -> None: |
| 1062 | self.pid = 999991 |
| 1063 | self.stdout = io.BytesIO(payload) |
| 1064 | self.returncode: int | None = None |
| 1065 | self._final_rc = returncode |
| 1066 | |
| 1067 | def poll(self) -> int | None: |
| 1068 | return self.returncode |
| 1069 | |
| 1070 | def wait(self, timeout=None) -> int: |
| 1071 | self.returncode = self._final_rc |
| 1072 | return self._final_rc |
| 1073 | |
| 1074 | def terminate(self) -> None: |
| 1075 | self.returncode = -15 |
| 1076 | |
| 1077 | def kill(self) -> None: |
| 1078 | self.returncode = -9 |
| 1079 | |
| 1080 | fake_proc = _FakeProc(b"MCP servers mocked stream \xff\xfe ok") |
| 1081 | monkeypatch.setattr(corpus.subprocess, "Popen", lambda *a, **k: fake_proc) |
| 1082 | monkeypatch.setattr(subproc, "register_child_pid", lambda _pid: None) |
| 1083 | monkeypatch.setattr(subproc, "unregister_child_pid", lambda _pid: None) |
| 1084 | |
| 1085 | extracted = corpus._extract_pdf_text(pdf, "/usr/bin/pdftotext") |
| 1086 | assert "MCP servers mocked stream" in extracted |
| 1087 | assert "\ufffd" in extracted |
| 1088 | assert fake_proc.stdout.closed |
| 1089 | |
| 1090 | def test_pdftotext_cleans_up_child_when_reader_thread_start_fails( |
| 1091 | self, tmp_path: Path, monkeypatch |
| 1092 | ) -> None: |
| 1093 | fake_bin = _write_fake_pdftotext(tmp_path, "import time\ntime.sleep(30)\n") |
| 1094 | pdf = tmp_path / "thread-fail.pdf" |
| 1095 | pdf.write_bytes(b"%PDF-1.4") |
| 1096 | |
| 1097 | spawned: list[subprocess.Popen] = [] |
| 1098 | real_popen = subprocess.Popen |
| 1099 | |
| 1100 | def tracking_popen(*args, **kwargs): |
| 1101 | proc = real_popen(*args, **kwargs) |
| 1102 | spawned.append(proc) |
| 1103 | return proc |
| 1104 | |
| 1105 | monkeypatch.setattr(corpus.subprocess, "Popen", tracking_popen) |
| 1106 | monkeypatch.setattr(corpus, "_stdout_selectable_fd", lambda _stream: None) |
| 1107 | monkeypatch.setattr( |
| 1108 | corpus.threading.Thread, |
| 1109 | "start", |
| 1110 | mock.Mock(side_effect=RuntimeError("can't start new thread")), |
| 1111 | ) |
| 1112 | |
| 1113 | with pytest.raises(RuntimeError, match="can't start new thread"): |
| 1114 | corpus._extract_pdf_text(pdf, str(fake_bin)) |
| 1115 | |
| 1116 | assert len(spawned) == 1 |
| 1117 | assert spawned[0].poll() is not None |
| 1118 | |
| 1119 | |
| 1120 | # --------------------------------------------------------------------------- |
| 1121 | # HIGH-221 & HIGH-222: MCP manifest Bluesky handle & X backend config |
| 1122 | # --------------------------------------------------------------------------- |
| 1123 | |
| 1124 | |
| 1125 | class TestHigh221And222McpManifestConfig: |
| 1126 | def test_high221_manifest_enables_bluesky_with_handle_and_app_password(self) -> None: |
| 1127 | manifest = json.loads((ROOT / "mcp" / "manifest.json").read_text(encoding="utf-8")) |
| 1128 | env_map = manifest["server"]["mcp_config"]["env"] |
| 1129 | user_config = manifest["user_config"] |
| 1130 | |
| 1131 | assert env_map["BSKY_HANDLE"] == "${user_config.bsky_handle}" |
| 1132 | assert env_map["BSKY_APP_PASSWORD"] == "${user_config.bsky_app_password}" |
| 1133 | assert user_config["bsky_handle"]["sensitive"] is False |
| 1134 | assert user_config["bsky_handle"]["required"] is False |
| 1135 | assert user_config["bsky_app_password"]["sensitive"] is True |
| 1136 | assert env.is_bluesky_available({"BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop"}) is False |
| 1137 | assert env.is_bluesky_available({ |
| 1138 | "BSKY_HANDLE": "alice.bsky.social", |
| 1139 | "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop", |
| 1140 | }) is True |
| 1141 | |
| 1142 | def test_high222_manifest_exposes_x_backend_and_xapi_opt_in_selects_xapi(self, monkeypatch) -> None: |
| 1143 | manifest = json.loads((ROOT / "mcp" / "manifest.json").read_text(encoding="utf-8")) |
| 1144 | env_map = manifest["server"]["mcp_config"]["env"] |
| 1145 | user_config = manifest["user_config"] |
| 1146 | |
| 1147 | assert env_map["LAST30DAYS_X_BACKEND"] == "${user_config.last30days_x_backend}" |
| 1148 | assert user_config["last30days_x_backend"]["sensitive"] is False |
| 1149 | assert user_config["last30days_x_backend"]["required"] is False |
| 1150 | assert "xapi" in user_config["x_bearer_token"]["description"] |
| 1151 | assert "LAST30DAYS_X_BACKEND" in user_config["x_bearer_token"]["description"] |
| 1152 | for higher_priority in ("XAI_API_KEY", "XQUIK_API_KEY", "AUTH_TOKEN+CT0"): |
| 1153 | assert higher_priority in user_config["last30days_x_backend"]["description"] |
| 1154 | assert higher_priority in user_config["x_bearer_token"]["description"] |
| 1155 | |
| 1156 | # Off grok-bot without opt-in, bare X_BEARER_TOKEN stays inactive. |
| 1157 | monkeypatch.delenv(env.X_API_OPT_IN_VAR, raising=False) |
| 1158 | assert env.x_backend_chain({"X_BEARER_TOKEN": "dummy-bearer"}, local_only=True) == [] |
| 1159 | assert env.x_backend_chain( |
| 1160 | {"X_BEARER_TOKEN": "dummy-bearer", "LAST30DAYS_X_BACKEND": "xapi"}, |
| 1161 | local_only=True, |
| 1162 | ) == ["xapi"] |
| 1163 | |
| 1164 | # With MCP wrapper opt-in (LAST30DAYS_X_API_OPT_IN=1), xapi joins the |
| 1165 | # tail of x_policy(config).auto_chain without overriding explicit pins |
| 1166 | # or higher-priority backends. |
| 1167 | monkeypatch.setenv(env.X_API_OPT_IN_VAR, "1") |
| 1168 | assert env.x_policy({}).auto_chain == env.X_BACKEND_ORDER + ("xapi",) |
| 1169 | assert env.x_backend_chain({"X_BEARER_TOKEN": "dummy-bearer"}, local_only=True) == ["xapi"] |
| 1170 | assert env.x_backend_chain( |
| 1171 | {"X_BEARER_TOKEN": "dummy-bearer", "XAI_API_KEY": "dummy-xai"}, |
| 1172 | local_only=True, |
| 1173 | ) == ["xai", "xapi"] |
| 1174 | assert env.x_backend_chain( |
| 1175 | {"X_BEARER_TOKEN": "dummy-bearer", "XQUIK_API_KEY": "dummy-xquik"}, |
| 1176 | local_only=True, |
| 1177 | ) == ["xquik", "xapi"] |
| 1178 | assert env.x_backend_chain( |
| 1179 | {"X_BEARER_TOKEN": "dummy-bearer", "LAST30DAYS_X_BACKEND": "bird"}, |
| 1180 | local_only=True, |
| 1181 | ) == [] |
| 1182 | |
| 1183 | def test_high222_x_api_opt_in_parity_across_all_x_surfaces(self, monkeypatch) -> None: |
| 1184 | bird_off = {"installed": True, "authenticated": False, "username": "", "can_install": True} |
| 1185 | |
| 1186 | def _node_ok(name, timeout=health.PROBE_TIMEOUT): |
| 1187 | return health.DependencyProbe(name=name, status=health.OK, detail=f"{name} 1.0.0") |
| 1188 | |
| 1189 | with ( |
| 1190 | mock.patch("lib.bird_x.is_bird_installed", return_value=False), |
| 1191 | mock.patch("lib.bird_x.get_bird_status", return_value=dict(bird_off)), |
| 1192 | mock.patch("lib.xurl_x.has_stored_auth", return_value=False), |
| 1193 | mock.patch("lib.xurl_x.is_available", return_value=False), |
| 1194 | mock.patch("lib.grok_x.has_stored_auth", return_value=False), |
| 1195 | mock.patch("lib.backends.which", return_value=None), |
| 1196 | mock.patch("lib.health.probe_dependency", _node_ok), |
| 1197 | ): |
| 1198 | cfg_bearer = {"X_BEARER_TOKEN": "dummy-bearer", "_BROWSER_COOKIE_MODE": "plan_only"} |
| 1199 | |
| 1200 | # Baseline without opt-in: xapi stays opt-in everywhere. |
| 1201 | monkeypatch.delenv(env.X_API_OPT_IN_VAR, raising=False) |
| 1202 | fp_off = doctor._config_fingerprint(cfg_bearer) |
| 1203 | assert env.x_backend_chain(cfg_bearer, local_only=True) == [] |
| 1204 | assert env.get_x_source_status(cfg_bearer)["source"] is None |
| 1205 | assert env.get_x_source_with_method(cfg_bearer) == (None, "none") |
| 1206 | assert backends.resolve("x", cfg_bearer).active_backend is None |
| 1207 | assert doctor._x_record(cfg_bearer)["status"] == "unconfigured" |
| 1208 | assert pipeline.diagnose(cfg_bearer, safe=True)["x_backend"] is None |
| 1209 | |
| 1210 | # With LAST30DAYS_X_API_OPT_IN=1: all 6 surfaces agree on xapi. |
| 1211 | monkeypatch.setenv(env.X_API_OPT_IN_VAR, "1") |
| 1212 | fp_on = doctor._config_fingerprint(cfg_bearer) |
| 1213 | assert fp_on != fp_off |
| 1214 | assert env.x_backend_chain(cfg_bearer, local_only=True) == ["xapi"] |
| 1215 | assert env.get_x_source_status(cfg_bearer)["source"] == "xapi" |
| 1216 | assert env.get_x_source_with_method(cfg_bearer) == ("xapi", "bearer") |
| 1217 | resolved = backends.resolve("x", cfg_bearer) |
| 1218 | assert resolved.active_backend == "xapi" |
| 1219 | assert resolved.tier == backends.TIER_OK |
| 1220 | rec = doctor._x_record(cfg_bearer) |
| 1221 | assert rec["status"] == health.OK |
| 1222 | assert rec["active_backend"] == "xapi" |
| 1223 | diag = pipeline.diagnose(cfg_bearer, safe=True) |
| 1224 | assert diag["x_backend"] == "xapi" |
| 1225 | assert "x" in diag["available_sources"] |
| 1226 | |
| 1227 | # Higher-priority XAI_API_KEY still wins across all 6 surfaces. |
| 1228 | cfg_xai = {**cfg_bearer, "XAI_API_KEY": "dummy-xai"} |
| 1229 | assert env.x_backend_chain(cfg_xai, local_only=True)[0] == "xai" |
| 1230 | assert env.get_x_source_status(cfg_xai)["source"] == "xai" |
| 1231 | assert env.get_x_source_with_method(cfg_xai) == ("xai", "xai") |
| 1232 | assert backends.resolve("x", cfg_xai).active_backend == "xai" |
| 1233 | assert doctor._x_record(cfg_xai)["active_backend"] == "xai" |
| 1234 | assert pipeline.diagnose(cfg_xai, safe=True)["x_backend"] == "xai" |
| 1235 | |
| 1236 | # Higher-priority XQUIK_API_KEY still wins across all 6 surfaces. |
| 1237 | cfg_xquik = {**cfg_bearer, "XQUIK_API_KEY": "dummy-xquik"} |
| 1238 | assert env.x_backend_chain(cfg_xquik, local_only=True)[0] == "xquik" |
| 1239 | assert env.get_x_source_status(cfg_xquik)["source"] == "xquik" |
| 1240 | assert env.get_x_source_with_method(cfg_xquik) == ("xquik", "api_key") |
| 1241 | assert backends.resolve("x", cfg_xquik).active_backend == "xquik" |
| 1242 | assert doctor._x_record(cfg_xquik)["active_backend"] == "xquik" |
| 1243 | assert pipeline.diagnose(cfg_xquik, safe=True)["x_backend"] == "xquik" |
| 1244 | |
| 1245 | # Explicit LAST30DAYS_X_BACKEND=bird pin is never overridden by xapi opt-in. |
| 1246 | cfg_pin = {**cfg_bearer, "LAST30DAYS_X_BACKEND": "bird"} |
| 1247 | assert env.x_backend_chain(cfg_pin, local_only=True) == [] |
| 1248 | assert env.get_x_source_status(cfg_pin)["source"] is None |
| 1249 | res_pin = backends.resolve("x", cfg_pin) |
| 1250 | assert res_pin.pinned is True and res_pin.pin == "bird" |
| 1251 | assert res_pin.active_backend is None |
| 1252 | assert doctor._x_record(cfg_pin).get("active_backend") is None |
| 1253 | assert pipeline.diagnose(cfg_pin, safe=True)["x_backend"] is None |
| 1254 | |
| 1255 | # LAST30DAYS_X_BACKEND=auto is treated as unpinned -> xapi activates cleanly. |
| 1256 | cfg_auto = {**cfg_bearer, "LAST30DAYS_X_BACKEND": "auto"} |
| 1257 | assert env.x_backend_chain(cfg_auto, local_only=True) == ["xapi"] |
| 1258 | assert env.get_x_source_status(cfg_auto)["source"] == "xapi" |
| 1259 | assert backends.resolve("x", cfg_auto).active_backend == "xapi" |
| 1260 | assert doctor._x_record(cfg_auto)["active_backend"] == "xapi" |
| 1261 | assert pipeline.diagnose(cfg_auto, safe=True)["x_backend"] == "xapi" |
| 1262 | |
| 1263 | # AUTH_TOKEN+CT0 present without node (bird unavailable) falls back to xapi. |
| 1264 | cfg_cookies_no_node = { |
| 1265 | **cfg_bearer, |
| 1266 | "AUTH_TOKEN": "dummy-auth", |
| 1267 | "CT0": "dummy-ct0", |
| 1268 | } |
| 1269 | assert env.x_backend_chain(cfg_cookies_no_node, local_only=True) == ["xapi"] |
| 1270 | assert env.get_x_source_status(cfg_cookies_no_node)["source"] == "xapi" |
| 1271 | assert backends.resolve("x", cfg_cookies_no_node).active_backend == "xapi" |
| 1272 | assert doctor._x_record(cfg_cookies_no_node)["active_backend"] == "xapi" |
| 1273 | assert pipeline.diagnose(cfg_cookies_no_node, safe=True)["x_backend"] == "xapi" |
| 1274 | |
| 1275 | def test_high222_report_cache_key_changes_when_x_api_opt_in_toggles(self, monkeypatch) -> None: |
| 1276 | import last30days as cli |
| 1277 | |
| 1278 | args = cli.build_parser().parse_args(["MCP servers", "--emit=html"]) |
| 1279 | cfg = {"X_BEARER_TOKEN": "dummy-bearer"} |
| 1280 | |
| 1281 | monkeypatch.delenv(env.X_API_OPT_IN_VAR, raising=False) |
| 1282 | opts_off = cli._cache_research_options(args, cfg) |
| 1283 | |
| 1284 | monkeypatch.setenv(env.X_API_OPT_IN_VAR, "1") |
| 1285 | opts_on_1 = cli._cache_research_options(args, cfg) |
| 1286 | |
| 1287 | monkeypatch.setenv(env.X_API_OPT_IN_VAR, "true") |
| 1288 | opts_on_true = cli._cache_research_options(args, cfg) |
| 1289 | |
| 1290 | assert opts_off["config_sha256"] != opts_on_1["config_sha256"] |
| 1291 | assert opts_on_1["config_sha256"] == opts_on_true["config_sha256"] |
| 1292 |