| 1 | import errno |
| 2 | import json |
| 3 | import os |
| 4 | import shutil |
| 5 | import socket |
| 6 | import signal |
| 7 | import sqlite3 |
| 8 | import sys |
| 9 | import threading |
| 10 | import time |
| 11 | from types import SimpleNamespace |
| 12 | import urllib.error |
| 13 | import urllib.request |
| 14 | from concurrent.futures import ThreadPoolExecutor |
| 15 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 16 | from pathlib import Path |
| 17 | from urllib.parse import parse_qs, urlencode, urlsplit |
| 18 | from unittest.mock import patch |
| 19 | |
| 20 | import pytest |
| 21 | |
| 22 | from lib import bounded_get, doctor, health, http, reddit, subproc, usage |
| 23 | |
| 24 | |
| 25 | @pytest.fixture |
| 26 | def children(monkeypatch): |
| 27 | processes = [] |
| 28 | popen = subproc.subprocess.Popen |
| 29 | |
| 30 | def start(*args, **kwargs): |
| 31 | process = popen(*args, **kwargs) |
| 32 | processes.append(process) |
| 33 | return process |
| 34 | |
| 35 | monkeypatch.setattr(subproc.subprocess, "Popen", start) |
| 36 | yield processes |
| 37 | assert processes |
| 38 | assert all(process.poll() is not None for process in processes) |
| 39 | assert all(process.pid not in subproc._child_pids for process in processes) |
| 40 | |
| 41 | |
| 42 | @pytest.fixture |
| 43 | def local_http(): |
| 44 | started = threading.Event() |
| 45 | release = threading.Event() |
| 46 | finished = threading.Event() |
| 47 | |
| 48 | class Handler(BaseHTTPRequestHandler): |
| 49 | def log_message(self, *args): |
| 50 | pass |
| 51 | |
| 52 | def do_GET(self): |
| 53 | parsed = urlsplit(self.path) |
| 54 | query = parse_qs(parsed.query) |
| 55 | if parsed.path == "/redirect": |
| 56 | self.send_response(302) |
| 57 | self.send_header("Location", query["to"][0]) |
| 58 | self.end_headers() |
| 59 | return |
| 60 | status = int(parsed.path.rsplit("/", 1)[1]) if parsed.path.startswith("/status/") else 200 |
| 61 | if parsed.path == "/held-error": |
| 62 | status = 403 |
| 63 | if query.get("url") == ["failed"]: |
| 64 | status = 402 |
| 65 | self.send_response(status) |
| 66 | self.send_header("Retry-After", "0") |
| 67 | self.end_headers() |
| 68 | hold = parsed.path in ("/hold", "/held-error") or query.get("url") == ["slow"] |
| 69 | if hold: |
| 70 | started.set() |
| 71 | try: |
| 72 | while not release.wait(0.02): |
| 73 | self.wfile.write(b" ") |
| 74 | self.wfile.flush() |
| 75 | except (BrokenPipeError, ConnectionResetError): |
| 76 | pass |
| 77 | finally: |
| 78 | finished.set() |
| 79 | return |
| 80 | if parsed.path == "/echo": |
| 81 | self.wfile.write(json.dumps(dict(self.headers)).encode()) |
| 82 | return |
| 83 | if status != 200: |
| 84 | self.wfile.write(b'{"error":"credits exhausted"}') |
| 85 | return |
| 86 | self.wfile.write(json.dumps({"comments": [{ |
| 87 | "body": "The fast comment survives.", "score": 17, "author": "alice", |
| 88 | }]}).encode()) |
| 89 | |
| 90 | server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) |
| 91 | server.daemon_threads = True |
| 92 | thread = threading.Thread(target=server.serve_forever) |
| 93 | thread.start() |
| 94 | try: |
| 95 | yield f"http://127.0.0.1:{server.server_port}", started, release, finished |
| 96 | finally: |
| 97 | release.set() |
| 98 | if started.is_set(): |
| 99 | assert finished.wait(2), "fixture request did not finish" |
| 100 | server.shutdown() |
| 101 | server.server_close() |
| 102 | thread.join(2) |
| 103 | assert not thread.is_alive() |
| 104 | |
| 105 | |
| 106 | def test_doctor_returns_before_held_response_is_released(local_http, children): |
| 107 | url, started, release, _ = local_http |
| 108 | result = {} |
| 109 | returned = threading.Event() |
| 110 | |
| 111 | def run(): |
| 112 | result.update(doctor._probe_sources({}, timeout=0.8)) |
| 113 | returned.set() |
| 114 | |
| 115 | with patch.object(doctor, "_probeable_sources", return_value=("reddit",)), \ |
| 116 | patch.dict(doctor._HTTP_PROBE_URLS, {"reddit": f"{url}/hold"}): |
| 117 | caller = threading.Thread(target=run) |
| 118 | caller.start() |
| 119 | try: |
| 120 | assert started.wait(2), "real HTTP body read was not reached" |
| 121 | assert any(process.poll() is None for process in children) |
| 122 | assert returned.wait(1.0), "doctor waited for the stalled response" |
| 123 | assert all(process.poll() is not None for process in children), "owned HTTP worker survived timeout" |
| 124 | assert result["reddit"] == { |
| 125 | "ok": False, "detail": "probe exceeded deadline", "probed": True, |
| 126 | } |
| 127 | assert doctor.audit_state("reddit", {"tier": doctor.TIER_OK}, |
| 128 | probe_result=result["reddit"]) == doctor.AUDIT_NOT_WORKING |
| 129 | finally: |
| 130 | release.set() |
| 131 | caller.join(3) |
| 132 | assert not caller.is_alive() |
| 133 | |
| 134 | |
| 135 | @pytest.mark.parametrize("status,expected_audit", [ |
| 136 | (429, doctor.AUDIT_UNVERIFIED), |
| 137 | (403, doctor.AUDIT_NOT_WORKING), |
| 138 | ]) |
| 139 | def test_short_doctor_budget_preserves_completed_reddit_status(local_http, children, status, expected_audit): |
| 140 | url, _, _, _ = local_http |
| 141 | probe_time = SimpleNamespace(monotonic=time.monotonic, sleep=time.sleep) |
| 142 | with patch.dict(doctor._HTTP_PROBE_URLS, {"reddit": f"{url}/status/{status}"}), \ |
| 143 | patch.object(doctor, "time", probe_time), \ |
| 144 | patch.object(doctor.reddit_health, "arctic_listing_probe_url", return_value=f"{url}/status/{status}"), \ |
| 145 | patch.object(probe_time, "sleep") as sleep: |
| 146 | result = doctor._probe_source("reddit", {}, 1) |
| 147 | assert not result["ok"] |
| 148 | assert result["probed"] |
| 149 | assert result["detail"].startswith(f"HTTP {status}") |
| 150 | assert result.get("transient", False) is (status == 429) |
| 151 | assert doctor.audit_state("reddit", {"tier": doctor.TIER_OK}, |
| 152 | probe_result=result) == expected_audit |
| 153 | assert len(children) == (2 if status == 403 else 1) |
| 154 | sleep.assert_not_called() |
| 155 | |
| 156 | |
| 157 | def test_reddit_keeps_fast_comments_and_reaps_stalled_transport(local_http, children, monkeypatch): |
| 158 | url, started, release, _ = local_http |
| 159 | monkeypatch.setattr(reddit, "SCRAPECREATORS_BASE", url) |
| 160 | items = [ |
| 161 | {"id": "fast", "url": "fast", "engagement": {"score": 10}}, |
| 162 | {"id": "slow", "url": "slow", "engagement": {"score": 20}}, |
| 163 | ] |
| 164 | returned = threading.Event() |
| 165 | result = [] |
| 166 | |
| 167 | def run(): |
| 168 | result.extend(reddit.enrich_with_comments(items, "dummy-key", depth="quick", budget_seconds=1.2)) |
| 169 | returned.set() |
| 170 | |
| 171 | caller = threading.Thread(target=run) |
| 172 | caller.start() |
| 173 | try: |
| 174 | assert started.wait(2), "real HTTP body read was not reached" |
| 175 | assert returned.wait(1.8), "Reddit waited for the stalled response" |
| 176 | assert len(result) == 2 |
| 177 | assert result[0]["top_comments"][0]["excerpt"] == "The fast comment survives." |
| 178 | assert result[0]["top_comments"][0]["score"] == 17 |
| 179 | assert "top_comments" not in result[1] |
| 180 | assert all(process.poll() is not None for process in children) |
| 181 | before_release = json.dumps(result, sort_keys=True) |
| 182 | finally: |
| 183 | release.set() |
| 184 | caller.join(3) |
| 185 | assert not caller.is_alive() |
| 186 | assert json.dumps(result, sort_keys=True) == before_release |
| 187 | |
| 188 | |
| 189 | @pytest.mark.parametrize("path,body_check,expected", [ |
| 190 | ("/hold", None, True), |
| 191 | ("/held-error", lambda body: "must not run", True), |
| 192 | ]) |
| 193 | def test_doctor_header_only_modes_do_not_read_bodies(local_http, children, path, body_check, expected): |
| 194 | url, _, _, _ = local_http |
| 195 | result = doctor._http_ok(f"{url}{path}", 2, body_check=body_check, deadline_monotonic=time.monotonic() + 2) |
| 196 | assert result == (expected, "HTTP 403" if path == "/held-error" else "HTTP 200") |
| 197 | |
| 198 | |
| 199 | @pytest.mark.parametrize("status,state", [(401, health.AUTH_FAILED), (402, health.PAYMENT_REQUIRED), (429, health.RATE_LIMITED)]) |
| 200 | def test_owned_get_preserves_error_body_and_failure_capture(local_http, children, status, state): |
| 201 | url, _, _, _ = local_http |
| 202 | with http.capture_failures() as failures: |
| 203 | with pytest.raises(http.HTTPError) as caught: |
| 204 | http.get(f"{url}/status/{status}", retries=1, max_429_retries=1, |
| 205 | deadline_monotonic=time.monotonic() + 2, owned_get=True) |
| 206 | assert caught.value.status_code == status |
| 207 | assert caught.value.body == '{"error":"credits exhausted"}' |
| 208 | assert caught.value.outcome_state == state |
| 209 | assert failures == [caught.value] |
| 210 | |
| 211 | |
| 212 | @pytest.mark.parametrize("cross_origin", [False, True]) |
| 213 | def test_owned_get_preserves_redirect_auth_policy(local_http, children, cross_origin): |
| 214 | url, _, _, _ = local_http |
| 215 | target = url.replace("127.0.0.1", "localhost") if cross_origin else url |
| 216 | endpoint = f"{url}/redirect?{urlencode({'to': target + '/echo'})}" |
| 217 | result = http.get(endpoint, headers={"Authorization": "Bearer dummy", "x-api-key": "dummy-key"}, |
| 218 | deadline_monotonic=time.monotonic() + 3, owned_get=True) |
| 219 | lowered = {key.lower(): value for key, value in result.items()} |
| 220 | if cross_origin: |
| 221 | assert "authorization" not in lowered |
| 222 | assert "x-api-key" not in lowered |
| 223 | else: |
| 224 | assert lowered["authorization"] == "Bearer dummy" |
| 225 | assert lowered["x-api-key"] == "dummy-key" |
| 226 | |
| 227 | |
| 228 | def test_owned_get_worker_keeps_installed_sources_clean(local_http, tmp_path, monkeypatch): |
| 229 | url, _, _, _ = local_http |
| 230 | installed = tmp_path / "installed skill" / "lib" |
| 231 | shutil.copytree( |
| 232 | Path(bounded_get.__file__).parent, installed, |
| 233 | ignore=shutil.ignore_patterns("__pycache__", "*.pyc"), |
| 234 | ) |
| 235 | monkeypatch.setattr(bounded_get, "__file__", str(installed / "bounded_get.py")) |
| 236 | |
| 237 | req = urllib.request.Request(url + "/echo", headers={"X-Example": "worker"}) |
| 238 | status, body, error = bounded_get.get( |
| 239 | req, timeout=3, deadline_monotonic=time.monotonic() + 5, bypass_proxy=True, |
| 240 | ) |
| 241 | assert status == 200 and error is None |
| 242 | assert json.loads(body)["X-Example"] == "worker" |
| 243 | assert not list(installed.rglob("__pycache__")) |
| 244 | assert not list(installed.rglob("*.pyc")) |
| 245 | |
| 246 | |
| 247 | def test_owned_get_cancellation_reaps_transport(local_http, children): |
| 248 | url, started, release, _ = local_http |
| 249 | cancel = threading.Event() |
| 250 | returned = threading.Event() |
| 251 | caught = [] |
| 252 | |
| 253 | def run(): |
| 254 | try: |
| 255 | bounded_get.get(urllib.request.Request(f"{url}/hold"), timeout=5, |
| 256 | deadline_monotonic=time.monotonic() + 5, cancel=cancel) |
| 257 | except bounded_get.GetTimeout as exc: |
| 258 | caught.append(exc) |
| 259 | finally: |
| 260 | returned.set() |
| 261 | |
| 262 | caller = threading.Thread(target=run) |
| 263 | caller.start() |
| 264 | try: |
| 265 | assert started.wait(2) |
| 266 | cancel.set() |
| 267 | assert returned.wait(1) |
| 268 | assert len(caught) == 1 |
| 269 | assert all(process.poll() is not None for process in children) |
| 270 | finally: |
| 271 | release.set() |
| 272 | caller.join(3) |
| 273 | assert not caller.is_alive() |
| 274 | |
| 275 | |
| 276 | def test_stalled_error_body_is_reaped_and_captured_as_timeout(local_http, children): |
| 277 | url, started, release, _ = local_http |
| 278 | with http.capture_failures() as failures: |
| 279 | try: |
| 280 | with pytest.raises(http.DeadlineExceeded) as caught: |
| 281 | http.get(f"{url}/held-error", retries=1, |
| 282 | deadline_monotonic=time.monotonic() + 0.8, owned_get=True) |
| 283 | assert started.is_set(), "real HTTP error body read was not reached" |
| 284 | assert caught.value.outcome_state == health.TIMEOUT |
| 285 | assert failures == [caught.value] |
| 286 | assert all(process.poll() is not None for process in children) |
| 287 | finally: |
| 288 | release.set() |
| 289 | |
| 290 | |
| 291 | def test_reddit_comment_worker_preserves_parent_failure_capture(local_http, children, monkeypatch): |
| 292 | url, _, _, _ = local_http |
| 293 | monkeypatch.setattr(reddit, "SCRAPECREATORS_BASE", url) |
| 294 | items = [{"id": "failed", "url": "failed", "engagement": {"score": 10}}] |
| 295 | with http.capture_failures() as failures: |
| 296 | result = reddit.enrich_with_comments(items, "dummy-key", budget_seconds=2) |
| 297 | assert result is items |
| 298 | assert "top_comments" not in result[0] |
| 299 | assert len(failures) == 1 |
| 300 | assert failures[0].status_code == 402 |
| 301 | assert failures[0].outcome_state == health.PAYMENT_REQUIRED |
| 302 | assert failures[0].body == '{"error":"credits exhausted"}' |
| 303 | |
| 304 | |
| 305 | def test_dns_error_wire_record_retains_retry_signal(): |
| 306 | restored = bounded_get._error_from_record({ |
| 307 | "kind": "URLError", "reason": {"kind": "gaierror", "errno": socket.EAI_AGAIN, |
| 308 | "message": "temporary DNS failure"}, |
| 309 | }) |
| 310 | assert isinstance(restored, urllib.error.URLError) |
| 311 | assert isinstance(restored.reason, socket.gaierror) |
| 312 | assert restored.reason.errno == socket.EAI_AGAIN |
| 313 | assert http._is_dns_failure(restored) |
| 314 | |
| 315 | |
| 316 | def test_owned_get_replay_skips_child_and_request_accounting(local_http, children, tmp_path): |
| 317 | url, _, _, _ = local_http |
| 318 | fixture = tmp_path / "fixture" |
| 319 | with http.recording_requests(fixture): |
| 320 | recorded = http.get(f"{url}/echo", deadline_monotonic=time.monotonic() + 2, owned_get=True) |
| 321 | with patch.object(bounded_get, "get", side_effect=AssertionError("replay launched transport")), \ |
| 322 | patch.object(usage, "begin_http") as begin, http.replaying_requests(fixture): |
| 323 | replayed = http.get(f"{url}/echo", deadline_monotonic=time.monotonic() + 2, owned_get=True) |
| 324 | assert replayed == recorded |
| 325 | begin.assert_not_called() |
| 326 | |
| 327 | |
| 328 | def test_unstarted_owned_get_cancels_request_charge(local_http): |
| 329 | url, _, _, _ = local_http |
| 330 | charge = ("scrapecreators", "request", "dummy-attempt") |
| 331 | with patch.object(usage, "begin_http", return_value=charge) as begin, \ |
| 332 | patch.object(usage, "cancel") as cancel, patch.object(subproc.subprocess, "Popen") as spawn: |
| 333 | with pytest.raises(http.DeadlineExceeded): |
| 334 | http.get(f"{url}/echo", deadline_monotonic=time.monotonic() + 0.1, owned_get=True) |
| 335 | begin.assert_called_once() |
| 336 | cancel.assert_called_once_with(charge) |
| 337 | spawn.assert_not_called() |
| 338 | |
| 339 | |
| 340 | @pytest.fixture |
| 341 | def paid_owned_get(local_http, tmp_path, monkeypatch): |
| 342 | """Keep real provider accounting while restricting worker destinations to loopback.""" |
| 343 | local_url, _, _, _ = local_http |
| 344 | paid_url = "https://api.scrapecreators.com/v1/reddit/post" |
| 345 | journal = tmp_path / "usage.db" |
| 346 | usage.create_journal(journal) |
| 347 | monkeypatch.setenv(usage.JOURNAL_ENV, str(journal)) |
| 348 | guarded_get = bounded_get.get |
| 349 | |
| 350 | def local_transport(req, **kwargs): |
| 351 | assert req.full_url == paid_url |
| 352 | return guarded_get(urllib.request.Request(f"{local_url}/echo"), **kwargs) |
| 353 | |
| 354 | monkeypatch.setattr(bounded_get, "get", local_transport) |
| 355 | monkeypatch.setattr(http.time, "sleep", lambda _: None) |
| 356 | return paid_url, journal |
| 357 | |
| 358 | |
| 359 | def _pending_charges(journal): |
| 360 | with sqlite3.connect(journal) as connection: |
| 361 | return connection.execute("SELECT COUNT(*) FROM attempts WHERE unknown = 1").fetchone()[0] |
| 362 | |
| 363 | |
| 364 | @pytest.mark.parametrize("error_number", [errno.ENOENT, errno.EAGAIN, errno.EMFILE]) |
| 365 | def test_owned_get_launch_error_preserves_errno_and_cause(local_http, monkeypatch, error_number): |
| 366 | local_url, _, _, _ = local_http |
| 367 | error = OSError(error_number, "GET worker launch failed") |
| 368 | with patch.object(subproc.subprocess, "Popen", side_effect=error): |
| 369 | with pytest.raises(bounded_get.GetLaunchError) as caught: |
| 370 | bounded_get.get(urllib.request.Request(f"{local_url}/echo"), timeout=2, |
| 371 | deadline_monotonic=time.monotonic() + 2) |
| 372 | assert caught.value.errno == error_number |
| 373 | assert caught.value.__cause__ is error |
| 374 | |
| 375 | |
| 376 | @pytest.mark.parametrize("error_number", [errno.EAGAIN, errno.EMFILE]) |
| 377 | def test_owned_get_spawn_errors_cancel_each_paid_retry(paid_owned_get, monkeypatch, error_number): |
| 378 | url, journal = paid_owned_get |
| 379 | pending_before_spawn = [] |
| 380 | |
| 381 | def unavailable(*args, **kwargs): |
| 382 | pending_before_spawn.append(_pending_charges(journal)) |
| 383 | raise OSError(error_number, "GET worker could not start") |
| 384 | |
| 385 | monkeypatch.setattr(subproc.subprocess, "Popen", unavailable) |
| 386 | with http.capture_failures() as failures: |
| 387 | with pytest.raises(http.HTTPError) as caught: |
| 388 | http.get(url, retries=3, deadline_monotonic=time.monotonic() + 30, owned_get=True) |
| 389 | |
| 390 | assert len(pending_before_spawn) == 3 |
| 391 | assert _pending_charges(journal) == 0 |
| 392 | assert pending_before_spawn == [1, 1, 1] |
| 393 | assert usage.read_journal(journal) == { |
| 394 | "token_cost": 0.0, "cost_unknown": 0, "prompt_tokens": 0, "completion_tokens": 0, |
| 395 | } |
| 396 | assert caught.value.outcome_state == health.UNREACHABLE |
| 397 | assert "GET worker could not start" in str(caught.value) |
| 398 | assert failures == [caught.value] |
| 399 | |
| 400 | |
| 401 | @pytest.mark.parametrize("error_number", [errno.EAGAIN, errno.EMFILE]) |
| 402 | @pytest.mark.parametrize("stage", ["registration", "communication"]) |
| 403 | def test_owned_get_post_launch_errors_keep_unknown_paid_retries(paid_owned_get, children, monkeypatch, error_number, stage): |
| 404 | url, journal = paid_owned_get |
| 405 | pending_before_spawn = [] |
| 406 | start = subproc.subprocess.Popen |
| 407 | |
| 408 | def fail(*args, **kwargs): |
| 409 | raise OSError(error_number, "GET parent failed after launch") |
| 410 | |
| 411 | def fail_after_start(*args, **kwargs): |
| 412 | pending_before_spawn.append(_pending_charges(journal)) |
| 413 | process = start(*args, **kwargs) |
| 414 | if stage == "communication": |
| 415 | process.communicate = fail |
| 416 | return process |
| 417 | |
| 418 | monkeypatch.setattr(subproc.subprocess, "Popen", fail_after_start) |
| 419 | if stage == "registration": |
| 420 | monkeypatch.setattr(subproc, "register_child_pid", fail) |
| 421 | with http.capture_failures() as failures: |
| 422 | with pytest.raises(http.HTTPError) as caught: |
| 423 | http.get(url, retries=3, deadline_monotonic=time.monotonic() + 30, owned_get=True) |
| 424 | |
| 425 | assert len(children) == 3 |
| 426 | assert pending_before_spawn == [1, 2, 3] |
| 427 | assert _pending_charges(journal) == 3 |
| 428 | assert usage.read_journal(journal) == { |
| 429 | "token_cost": 0.0, "cost_unknown": 1, "prompt_tokens": 0, "completion_tokens": 0, |
| 430 | } |
| 431 | assert caught.value.outcome_state == health.UNREACHABLE |
| 432 | assert "GET parent failed after launch" in str(caught.value) |
| 433 | assert failures == [caught.value] |
| 434 | |
| 435 | |
| 436 | @pytest.mark.parametrize("kwargs", [ |
| 437 | {"method": "POST", "deadline_monotonic": 1}, |
| 438 | {"method": "GET", "json_data": {"key": "value"}, "deadline_monotonic": 1}, |
| 439 | {"method": "GET"}, |
| 440 | ]) |
| 441 | def test_owned_transport_rejects_unsupported_calls_before_accounting(kwargs): |
| 442 | with patch.object(usage, "begin_http") as begin, patch.object(bounded_get, "get") as transport: |
| 443 | with pytest.raises(ValueError): |
| 444 | http.request(url="http://example.test", owned_get=True, **kwargs) |
| 445 | begin.assert_not_called() |
| 446 | transport.assert_not_called() |
| 447 | |
| 448 | |
| 449 | def test_subprocess_without_process_groups_still_reaps_child(children, monkeypatch): |
| 450 | monkeypatch.setattr(subproc, "os", SimpleNamespace(kill=os.kill)) |
| 451 | with pytest.raises(subproc.SubprocTimeout): |
| 452 | subproc.run_with_timeout([sys.executable, "-c", "import time; time.sleep(30)"], |
| 453 | timeout=0.05, cleanup_grace=0.1) |
| 454 | assert all(process.poll() is not None for process in children) |
| 455 | |
| 456 | |
| 457 | def test_unexpected_parent_failure_reaps_owned_child(children, monkeypatch): |
| 458 | start = subproc.subprocess.Popen |
| 459 | |
| 460 | def fail_after_start(*args, **kwargs): |
| 461 | process = start(*args, **kwargs) |
| 462 | def fail(**kwargs): |
| 463 | raise RuntimeError("parent communication failed") |
| 464 | process.communicate = fail |
| 465 | return process |
| 466 | |
| 467 | monkeypatch.setattr(subproc.subprocess, "Popen", fail_after_start) |
| 468 | with pytest.raises(RuntimeError, match="parent communication failed"): |
| 469 | subproc.run_with_timeout([sys.executable, "-c", "import time; time.sleep(30)"], |
| 470 | timeout=2, cleanup_grace=0.1) |
| 471 | assert all(process.poll() is not None for process in children) |
| 472 | |
| 473 | |
| 474 | @pytest.mark.skipif(not hasattr(os, "killpg"), reason="POSIX process-group termination") |
| 475 | def test_health_timeout_terminates_inherited_output_descendant(tmp_path, children, monkeypatch): |
| 476 | descendant_pid = tmp_path / "descendant.pid" |
| 477 | stopped = tmp_path / "descendant.stopped" |
| 478 | child = ( |
| 479 | "import os, signal, sys, time\nfrom pathlib import Path\n" |
| 480 | f"def stop(*args):\n Path({str(stopped)!r}).write_text('terminated')\n sys.exit(0)\n" |
| 481 | "signal.signal(signal.SIGTERM, stop)\n" |
| 482 | f"Path({str(descendant_pid)!r}).write_text(str(os.getpid()))\n" |
| 483 | "time.sleep(30)\n" |
| 484 | ) |
| 485 | command = tmp_path / "version.py" |
| 486 | command.write_text(f"import subprocess, sys, time\nsubprocess.Popen([sys.executable, '-c', {child!r}])\ntime.sleep(30)\n") |
| 487 | monkeypatch.setitem(health._VERSION_ARGS, sys.executable, [str(command)]) |
| 488 | started = time.monotonic() |
| 489 | try: |
| 490 | result = health._probe_dependency_uncached(sys.executable, 0.8) |
| 491 | assert time.monotonic() - started < 1.5 |
| 492 | assert result.status == health.TIMEOUT |
| 493 | assert descendant_pid.exists(), "real descendant was not reached" |
| 494 | assert stopped.exists(), "timed-out version probe left its descendant running" |
| 495 | assert stopped.read_text() == "terminated" |
| 496 | assert all(process.poll() is not None for process in children) |
| 497 | finally: |
| 498 | if descendant_pid.exists() and not stopped.exists(): |
| 499 | try: |
| 500 | os.kill(int(descendant_pid.read_text()), signal.SIGTERM) |
| 501 | except ProcessLookupError: |
| 502 | pass |
| 503 | |
| 504 | |
| 505 | def test_health_real_version_command_preserves_first_line(children, monkeypatch): |
| 506 | monkeypatch.setitem(health._VERSION_ARGS, sys.executable, [ |
| 507 | "-c", "import sys; print('1.2.3'); print('ignored second line'); print('stderr detail', file=sys.stderr)", |
| 508 | ]) |
| 509 | result = health._probe_dependency_uncached(sys.executable, 2) |
| 510 | assert result.status == health.OK |
| 511 | assert result.detail == "1.2.3" |
| 512 | assert result.prescription == "" |
| 513 | assert all(process.stdout is None and process.stderr is None for process in children) |
| 514 | |
| 515 | |
| 516 | def test_file_capture_returns_bounded_stdout_and_stderr(children): |
| 517 | result = subproc.run_with_timeout([ |
| 518 | sys.executable, "-c", "import sys; print('a' * 100); print('b' * 100, file=sys.stderr)", |
| 519 | ], timeout=2, capture_limit_bytes=16) |
| 520 | assert result.returncode == 0 |
| 521 | assert result.stdout == "a" * 16 |
| 522 | assert result.stderr == "b" * 16 |
| 523 | assert all(process.stdout is None and process.stderr is None for process in children) |
| 524 | |
| 525 | |
| 526 | def test_file_capture_without_process_groups_avoids_descendant_pipe_wait(tmp_path, children, monkeypatch): |
| 527 | descendant_pid = tmp_path / "descendant.pid" |
| 528 | command = tmp_path / "version.py" |
| 529 | child = "import time; time.sleep(30)" |
| 530 | command.write_text( |
| 531 | "import subprocess, sys, time\nfrom pathlib import Path\n" |
| 532 | f"child = subprocess.Popen([sys.executable, '-c', {child!r}])\n" |
| 533 | f"Path({str(descendant_pid)!r}).write_text(str(child.pid))\n" |
| 534 | "time.sleep(30)\n" |
| 535 | ) |
| 536 | monkeypatch.setattr(subproc, "os", SimpleNamespace(kill=os.kill)) |
| 537 | started = time.monotonic() |
| 538 | try: |
| 539 | with pytest.raises(subproc.SubprocTimeout): |
| 540 | subproc.run_with_timeout([sys.executable, str(command)], timeout=0.6, |
| 541 | cleanup_grace=0.1, capture_limit_bytes=64 * 1024) |
| 542 | assert time.monotonic() - started < 1.5 |
| 543 | assert descendant_pid.exists(), "real descendant was not reached" |
| 544 | assert all(process.poll() is not None for process in children) |
| 545 | assert all(process.stdout is None and process.stderr is None for process in children) |
| 546 | finally: |
| 547 | if descendant_pid.exists(): |
| 548 | try: |
| 549 | os.kill(int(descendant_pid.read_text()), signal.SIGTERM) |
| 550 | except ProcessLookupError: |
| 551 | pass |
| 552 | |
| 553 | |
| 554 | def test_doctor_retry_spends_one_operation_budget(monkeypatch): |
| 555 | clock = [100.0] |
| 556 | timeouts = [] |
| 557 | |
| 558 | def get(*args, **kwargs): |
| 559 | timeouts.append((args[1], kwargs["deadline_monotonic"])) |
| 560 | clock[0] += 6 if len(timeouts) == 1 else 0.5 |
| 561 | return (False, "HTTP 429") if len(timeouts) == 1 else (True, "HTTP 200") |
| 562 | |
| 563 | monkeypatch.setattr(doctor.time, "monotonic", lambda: clock[0]) |
| 564 | monkeypatch.setattr(doctor.time, "sleep", lambda seconds: clock.__setitem__(0, clock[0] + seconds)) |
| 565 | monkeypatch.setattr(doctor, "_http_ok", get) |
| 566 | assert doctor._probe_source("reddit", {}, 10)["ok"] |
| 567 | # Brave, its one retry, then the Arctic Shift step on what is left. |
| 568 | assert timeouts == [(10, 110), (2, 110), (1.5, 110)] |
| 569 | |
| 570 | |
| 571 | @pytest.mark.parametrize("elapsed", [8, 9]) |
| 572 | def test_doctor_does_not_retry_when_backoff_exceeds_budget(monkeypatch, elapsed): |
| 573 | clock = [100.0] |
| 574 | |
| 575 | def get(*args, **kwargs): |
| 576 | clock[0] += elapsed |
| 577 | return False, "HTTP 429" |
| 578 | |
| 579 | monkeypatch.setattr(doctor.time, "monotonic", lambda: clock[0]) |
| 580 | monkeypatch.setattr(doctor, "_http_ok", get) |
| 581 | with patch.object(doctor.time, "sleep") as sleep: |
| 582 | result = doctor._probe_source("reddit", {}, 10) |
| 583 | assert result == { |
| 584 | "ok": False, "transient": True, |
| 585 | "detail": "HTTP 429 (retry skipped: insufficient probe budget)", "probed": True, |
| 586 | } |
| 587 | assert doctor.audit_state("reddit", {"tier": doctor.TIER_OK}, |
| 588 | probe_result=result) == doctor.AUDIT_UNVERIFIED |
| 589 | sleep.assert_not_called() |
| 590 | |
| 591 | |
| 592 | @pytest.mark.parametrize("readings", [ |
| 593 | (100.0, 101.0), |
| 594 | (100.0, 100.5, 101.0), |
| 595 | ]) |
| 596 | def test_doctor_expired_429_keeps_deadline_precedence(monkeypatch, readings): |
| 597 | clock = iter(readings) |
| 598 | monkeypatch.setattr(doctor.time, "monotonic", lambda: next(clock)) |
| 599 | with patch.object(doctor, "_http_ok", return_value=(False, "HTTP 429")) as transport, \ |
| 600 | patch.object(doctor.time, "sleep") as sleep: |
| 601 | result = doctor._probe_source("reddit", {}, 1) |
| 602 | assert result == {"ok": False, "detail": "probe exceeded deadline", "probed": True} |
| 603 | assert doctor.audit_state("reddit", {"tier": doctor.TIER_OK}, |
| 604 | probe_result=result) == doctor.AUDIT_NOT_WORKING |
| 605 | transport.assert_called_once() |
| 606 | sleep.assert_not_called() |
| 607 | |
| 608 | |
| 609 | def test_doctor_cli_receives_remaining_timeout(monkeypatch): |
| 610 | clock = iter([100.0, 100.25, 100.5]) |
| 611 | monkeypatch.setattr(doctor.time, "monotonic", lambda: next(clock)) |
| 612 | probe = health.DependencyProbe(name="yt-dlp", status=health.OK, detail="version") |
| 613 | with patch.object(health, "probe_dependency", return_value=probe) as dependency: |
| 614 | assert doctor._probe_source("youtube", {}, 5)["ok"] |
| 615 | dependency.assert_called_once_with("yt-dlp", timeout=4.75) |
| 616 | |
| 617 | |
| 618 | def test_queued_doctor_probe_gets_its_own_start_deadline(monkeypatch): |
| 619 | clock = [100.0] |
| 620 | deadlines = [] |
| 621 | |
| 622 | def get(*args, **kwargs): |
| 623 | deadlines.append(kwargs["deadline_monotonic"]) |
| 624 | clock[0] += 8 |
| 625 | return True, "HTTP 200" |
| 626 | |
| 627 | monkeypatch.setattr(doctor.time, "monotonic", lambda: clock[0]) |
| 628 | monkeypatch.setattr(doctor, "_http_ok", get) |
| 629 | monkeypatch.setattr(doctor, "_probeable_sources", lambda: ("github", "hackernews")) |
| 630 | monkeypatch.setattr(doctor.concurrent.futures, "ThreadPoolExecutor", lambda **kwargs: ThreadPoolExecutor(max_workers=1)) |
| 631 | assert all(result["ok"] for result in doctor._probe_sources({}, 10).values()) |
| 632 | assert deadlines == [110, 118] |
| 633 |