diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index f4bf6fec..bf9d96d1 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -55,6 +55,7 @@ import math import os import re import shutil +import signal import subprocess import sys import threading @@ -286,12 +287,34 @@ def with_accounts(providers: str, base: dict[str, str], # ----------------------------------------------------------------- probes -def _http(req: urllib.request.Request, timeout: int = 30) -> tuple[int, dict[str, str], bytes]: +class _RequestDeadline(Exception): + """Skip transport handlers that treat OSError as retryable.""" + + +def _http(req: urllib.request.Request, timeout: float = 30) -> tuple[int, dict[str, str], bytes]: + """Read the response within the account command main thread deadline.""" + def expire(_signum, _frame): + raise _RequestDeadline() + + if timeout <= 0 or any(signal.getitimer(signal.ITIMER_REAL)): + raise TimeoutError("provider HTTP request cannot start without an available time budget") + handler = signal.signal(signal.SIGALRM, expire) try: - with urllib.request.urlopen(req, timeout=timeout) as resp: - return resp.status, {k.lower(): v for k, v in resp.headers.items()}, resp.read() - except urllib.error.HTTPError as exc: - return exc.code, {k.lower(): v for k, v in exc.headers.items()}, exc.read() + try: + signal.setitimer(signal.ITIMER_REAL, timeout) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + return resp.status, {k.lower(): v for k, v in resp.headers.items()}, resp.read() + except urllib.error.HTTPError as exc: + with exc: + return exc.code, {k.lower(): v for k, v in exc.headers.items()}, exc.read() + finally: + try: + signal.setitimer(signal.ITIMER_REAL, 0) + finally: + signal.signal(signal.SIGALRM, handler) + except _RequestDeadline: + raise TimeoutError("provider HTTP request timed out") from None def reset_timestamp(value) -> float | None: diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index 1b3a796a..ff24cea0 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -7,11 +7,13 @@ import json import os import re +import signal import stat import ssl import time import urllib.error import urllib.request +from contextlib import ExitStack, contextmanager from dataclasses import dataclass from pathlib import Path from urllib.parse import quote @@ -73,12 +75,29 @@ def redirect_request(self, *_args, **_kwargs): _retry_sleep = time.sleep -def _open(request: urllib.request.Request): +class _RequestDeadline(Exception): + """Bypass transport handlers that retry OSError.""" + + +@contextmanager +def _open(request: urllib.request.Request, timeout: float = 30): + def expire(_signum, _frame): + raise _RequestDeadline() + + if signal.getitimer(signal.ITIMER_REAL) != (0, 0): + raise TimeoutError("Mergify HTTP request cannot start with an active alarm") try: - return urllib.request.build_opener(_NoRedirect).open(request, timeout=30) - except ValueError: - # The HTTP client can include the Authorization value in a header error. - raise MergifyError("Mergify API request has an invalid URL or header") from None + with ExitStack() as cleanup: + cleanup.callback(signal.signal, signal.SIGALRM, signal.signal(signal.SIGALRM, expire)) + cleanup.callback(signal.setitimer, signal.ITIMER_REAL, 0) + signal.setitimer(signal.ITIMER_REAL, timeout) + try: + response = urllib.request.build_opener(_NoRedirect).open(request, timeout=timeout) + except ValueError: + raise MergifyError("Mergify API request has an invalid URL or header") from None + yield cleanup.enter_context(response) + except _RequestDeadline: + raise TimeoutError("Mergify HTTP request timed out") from None def api_get(repo: str, suffix: str) -> object | None: diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index e51d80ab..82041ff8 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -3,6 +3,7 @@ import importlib.util import json from concurrent.futures import ThreadPoolExecutor +from io import BytesIO from pathlib import Path import pytest @@ -556,3 +557,16 @@ def count_home_lock(name): helper.set_active("codex", "b") assert helper.with_accounts("codex,codex", {})["CODEX_HOME"] == str(helper.codex_home("b")) assert home_lock_entries == [".codex-sync.lock"] * 2 + + +def test_provider_deadline_covers_http_error_body(helper, monkeypatch): + request = helper.urllib.request.Request("https://example.invalid") + body = BytesIO() + monkeypatch.setattr(body, "read", lambda: helper.signal.raise_signal(helper.signal.SIGALRM)) + + def open_(*args, **kwargs): + raise helper.urllib.error.HTTPError(request.full_url, 503, "Busy", {}, body) + + monkeypatch.setattr(helper.urllib.request, "urlopen", open_) + with pytest.raises(TimeoutError, match="provider HTTP request timed out"): + helper._http(request, timeout=1) diff --git a/tests/test_mergify.py b/tests/test_mergify.py index d1058ee1..59eb950b 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -4,10 +4,12 @@ import http.client import io import json +import signal import ssl import subprocess import sys import traceback +from types import SimpleNamespace import urllib.error import urllib.request @@ -249,3 +251,33 @@ def fake_open(request): mergify.api_get("acme/widgets", "/merge-queue/status") assert str(failure) in str(info.value) assert sleeps == expected_sleeps + + +@pytest.mark.parametrize("phase", ["headers", "body", "cleanup"]) +def test_request_deadline(monkeypatch, phase): + handler, setitimer = signal.getsignal(signal.SIGALRM), signal.setitimer + + def open_(*args, **kwargs): + if phase == "headers": + try: + signal.raise_signal(signal.SIGALRM) + except OSError: + pytest.fail("address fallback would swallow the deadline") + return io.BytesIO(b"{}") + + def arm(timer, seconds): + setitimer(timer, seconds) + if seconds == 0 and phase == "cleanup": + signal.raise_signal(signal.SIGALRM) + + monkeypatch.setattr(mergify.urllib.request, "build_opener", lambda *_: SimpleNamespace(open=open_)) + monkeypatch.setattr(signal, "setitimer", arm) + with ( + pytest.raises(TimeoutError, match="Mergify HTTP request timed out"), + mergify._open(urllib.request.Request("https://example.invalid")), + ): + if phase == "body": + assert 0 < signal.getitimer(signal.ITIMER_REAL)[0] <= 30 + signal.raise_signal(signal.SIGALRM) + assert signal.getsignal(signal.SIGALRM) is handler + assert signal.getitimer(signal.ITIMER_REAL) == (0, 0)