From 0a94ca35cafcc54f567f86f4de759ad27684767e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:04:37 +0100 Subject: [PATCH 1/2] Bound standalone HTTP responses by wall clock Architecture-Review: unchanged; the existing HTTP requests retain their endpoints, credentials, and failure paths while using an attempt-wide deadline. Co-Authored-By: Codex --- scripts/ai-accounts/ai-accounts | 24 +++++++++++++++++++----- src/loopzero/mergify.py | 26 ++++++++++++++++++++++---- tests/test_ai_accounts.py | 25 +++++++++++++++++++++++++ tests/test_mergify.py | 25 +++++++++++++++++++++++++ 4 files changed, 91 insertions(+), 9 deletions(-) diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index c7aeaca2..755dd0f0 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 @@ -267,12 +268,25 @@ 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]: +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 TimeoutError("provider HTTP request timed out") + + 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() + 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: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, handler) def reset_timestamp(value) -> float | None: diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index 6b7419d7..dbf8f037 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -7,10 +7,12 @@ import json import os import re +import signal import stat import time import urllib.error import urllib.request +from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path from urllib.parse import quote @@ -19,6 +21,7 @@ from .types import LoopZeroError API = "https://api.mergify.com/v1" +REQUEST_TIMEOUT = 30.0 REQUEST = "loopzero:mergify-request" CONFIRMED = "loopzero:mergify-confirmed" @@ -72,12 +75,27 @@ def redirect_request(self, *_args, **_kwargs): _retry_sleep = time.sleep +@contextmanager def _open(request: urllib.request.Request): + """Keep the CLI main thread deadline armed through response consumption.""" + def expire(_signum, _frame): + raise TimeoutError("Mergify HTTP request timed out") + + if any(signal.getitimer(signal.ITIMER_REAL)): + raise TimeoutError("Mergify HTTP request cannot start with an active alarm") + handler = signal.signal(signal.SIGALRM, expire) 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 + signal.setitimer(signal.ITIMER_REAL, REQUEST_TIMEOUT) + try: + response = urllib.request.build_opener(_NoRedirect).open(request, timeout=REQUEST_TIMEOUT) + 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 response: + yield response + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, handler) def api_get(repo: str, suffix: str) -> object | None: diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index 2d3037a6..4e62a547 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -492,3 +492,28 @@ def test_status_prints_account_email_after_plan(helper, capsys, provider, email, result = {'tier': 0, 'plan': 'max', 'email': email, 'windows': [], 'unknown_reason': 'no data'} helper.print_status({'checked_at': helper.now(), 'providers': {provider: {'active': 'a', 'accounts': {'a': result}}}}) assert shown in capsys.readouterr().out + + +def test_provider_deadline_covers_http_error_body(helper, monkeypatch): + signal = helper.signal + handler = signal.getsignal(signal.SIGALRM) + + class ErrorBody: + closed = False + + def read(self): + assert 0 < signal.getitimer(signal.ITIMER_REAL)[0] <= 1 + signal.raise_signal(signal.SIGALRM) + + def close(self): + pass + + def open_error(request, *, timeout): + error = helper.urllib.error.HTTPError(request.full_url, 503, "Busy", {}, ErrorBody()) + raise error + + monkeypatch.setattr(helper.urllib.request, "urlopen", open_error) + with pytest.raises(TimeoutError, match="provider HTTP request timed out"): + helper._http(helper.urllib.request.Request("https://example.invalid"), timeout=1) + assert signal.getsignal(signal.SIGALRM) is handler + assert signal.getitimer(signal.ITIMER_REAL) == (0, 0) diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 88ce09f8..c722b0dc 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -4,9 +4,11 @@ import http.client import io import json +import signal import subprocess import sys import traceback +from types import SimpleNamespace import urllib.error import urllib.request @@ -73,6 +75,29 @@ def forbidden(request): mergify.membership("acme/widgets", 7, "main") +@pytest.mark.parametrize("phase", ["headers", "body"]) +def test_request_deadline_covers_headers_and_body(monkeypatch, phase): + handler = signal.getsignal(signal.SIGALRM) + + def expire(): + assert 0 < signal.getitimer(signal.ITIMER_REAL)[0] <= 30 + signal.raise_signal(signal.SIGALRM) + + def open_(*args, **kwargs): + if phase == "headers": + expire() + return io.BytesIO(b"{}") + + monkeypatch.setattr(mergify.urllib.request, "build_opener", lambda *_: SimpleNamespace(open=open_)) + with ( + pytest.raises(TimeoutError, match="Mergify HTTP request timed out"), + mergify._open(urllib.request.Request("https://example.invalid")), + ): + expire() + assert signal.getsignal(signal.SIGALRM) is handler + assert signal.getitimer(signal.ITIMER_REAL) == (0, 0) + + def test_api_get_rejects_paths_outside_repository(): with pytest.raises(ValueError, match="repository-relative"): mergify.api_get("acme/widgets", "https://evil.example/x") From 7147cfa9e8fe37a52d6da53308090287482e2a89 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:48:26 +0100 Subject: [PATCH 2/2] Preserve the HTTP deadline across retry and cleanup Architecture-Review: unchanged; retain the existing wait and failure interfaces while covering their boundary cases. Co-Authored-By: Codex --- scripts/ai-accounts/ai-accounts | 29 ++++++++++++------- src/loopzero/mergify.py | 31 +++++++++++++-------- tests/test_mergify.py | 49 +++++++++++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 21 deletions(-) diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index ab18f3fc..ece6a37c 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -268,25 +268,34 @@ def with_accounts(providers: str, base: dict[str, str], # ----------------------------------------------------------------- probes +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 TimeoutError("provider HTTP request timed out") + 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: - 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: - signal.setitimer(signal.ITIMER_REAL, 0) - signal.signal(signal.SIGALRM, handler) + 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 25a5bc88..af4eb5f8 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -76,27 +76,36 @@ def redirect_request(self, *_args, **_kwargs): _retry_sleep = time.sleep +class _RequestDeadline(Exception): + """Skip transport handlers that treat OSError as retryable.""" + + @contextmanager def _open(request: urllib.request.Request): """Keep the CLI main thread deadline armed through response consumption.""" def expire(_signum, _frame): - raise TimeoutError("Mergify HTTP request timed out") + raise _RequestDeadline() if any(signal.getitimer(signal.ITIMER_REAL)): raise TimeoutError("Mergify HTTP request cannot start with an active alarm") handler = signal.signal(signal.SIGALRM, expire) try: - signal.setitimer(signal.ITIMER_REAL, REQUEST_TIMEOUT) try: - response = urllib.request.build_opener(_NoRedirect).open(request, timeout=REQUEST_TIMEOUT) - 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 response: - yield response - finally: - signal.setitimer(signal.ITIMER_REAL, 0) - signal.signal(signal.SIGALRM, handler) + signal.setitimer(signal.ITIMER_REAL, REQUEST_TIMEOUT) + try: + response = urllib.request.build_opener(_NoRedirect).open(request, timeout=REQUEST_TIMEOUT) + 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 response: + yield response + finally: + try: + signal.setitimer(signal.ITIMER_REAL, 0) + finally: + signal.signal(signal.SIGALRM, handler) + 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_mergify.py b/tests/test_mergify.py index 89287c19..8b079f19 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -5,6 +5,7 @@ import io import json import signal +import socket import ssl import subprocess import sys @@ -275,3 +276,51 @@ def open_(*args, **kwargs): expire() assert signal.getsignal(signal.SIGALRM) is handler assert signal.getitimer(signal.ITIMER_REAL) == (0, 0) + + + +def test_request_deadline_stops_address_fallback(monkeypatch): + addresses = [("192.0.2.1", 443), ("192.0.2.2", 443)] + attempted = [] + + def connect(address): + attempted.append(address) + if len(attempted) == 1: + signal.raise_signal(signal.SIGALRM) + + def open_(*args, **kwargs): + socket.create_connection(("example.invalid", 443)) + return io.BytesIO(b"{}") + + monkeypatch.setattr(socket, "getaddrinfo", lambda *_: [ + (socket.AF_INET, socket.SOCK_STREAM, 0, "", address) for address in addresses + ]) + monkeypatch.setattr(socket, "socket", lambda *_: SimpleNamespace(connect=connect, close=lambda: None)) + monkeypatch.setattr(mergify.urllib.request, "build_opener", lambda *_: SimpleNamespace(open=open_)) + with ( + pytest.raises(TimeoutError, match="Mergify HTTP request timed out"), + mergify._open(urllib.request.Request("https://example.invalid")), + ): + pytest.fail("address fallback swallowed the deadline") + assert attempted == addresses[:1] + + +def test_request_deadline_restores_handler_when_disarming_is_interrupted(monkeypatch): + handler = signal.getsignal(signal.SIGALRM) + setitimer = signal.setitimer + + def interrupt(timer, seconds): + result = setitimer(timer, seconds) + if seconds == 0: + signal.raise_signal(signal.SIGALRM) + return result + + monkeypatch.setattr(signal, "setitimer", interrupt) + monkeypatch.setattr(mergify.urllib.request, "build_opener", + lambda *_: SimpleNamespace(open=lambda *_, **__: io.BytesIO(b"{}"))) + with ( + pytest.raises(TimeoutError, match="Mergify HTTP request timed out"), + mergify._open(urllib.request.Request("https://example.invalid")), + ): + pass + assert signal.getsignal(signal.SIGALRM) is handler