Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import math
import os
import re
import shutil
import signal
import subprocess
import sys
import threading
Expand Down Expand Up @@ -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:
Expand Down
29 changes: 24 additions & 5 deletions src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: The two copies of the deadline guard check different preconditions

ai-accounts _http refuses to start when timeout <= 0 or a timer is already armed. Mergify _open only checks for an armed timer. With timeout=0, setitimer(ITIMER_REAL, 0) disarms the timer, so the request runs without a wall-clock bound. Today the only caller uses the default of 30, so this isn't a live bug. Keeping two copies is justified because the ai-accounts script runs standalone, but they should check the same things. Add the timeout <= 0 guard to _open, or drop the parameter.

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:
Expand Down
14 changes: 14 additions & 0 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import importlib.util
import json
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from pathlib import Path

import pytest
Expand Down Expand Up @@ -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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: ai-accounts deadline test covers only the error body and never checks that alarm state is restored

The new ai-accounts test only covers an HTTPError body read that times out. It never checks that the SIGALRM handler and ITIMER_REAL are restored afterwards. It also doesn't cover the headers phase, the success-body phase, or an alarm that fires during the cleanup finally (setitimer(0) raising before the handler is restored). Those are exactly the paths the acceptance criteria name ('interrupted cleanup restores the caller's handler'). The Mergify test covers them for _open, but _http has its own separate implementation. Smallest fix: parametrize the test like test_request_deadline (headers/body/cleanup), and after each case assert signal.getsignal(SIGALRM) is original and getitimer(ITIMER_REAL) == (0, 0).

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)
32 changes: 32 additions & 0 deletions tests/test_mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Loading