From bb504effd628813bfa76c225250dc880ccfce482 Mon Sep 17 00:00:00 2001 From: lelia <2418071+lelia@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:32:48 -0500 Subject: [PATCH 1/4] Retry the PyPI lookup in the version check check_version read the latest release from PyPI with one request and no timeout, so a single dropped connection failed a required check and blocked the merge until someone reran the job. The request now has a 15 s timeout and is retried up to four times, with 2, 4 and 8 s pauses, on connection errors, timeouts and 5xx responses. If PyPI still can't be read, the job fails with a message that names PyPI and says the PR's version isn't the problem. The version comparison is unchanged. Also quotes $GITHUB_ENV, which actionlint's shellcheck pass flagged. --- .github/workflows/version-check.yml | 50 ++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/.github/workflows/version-check.yml b/.github/workflows/version-check.yml index ae187338..5fca25fb 100644 --- a/.github/workflows/version-check.yml +++ b/.github/workflows/version-check.yml @@ -31,21 +31,24 @@ jobs: # Get version from current PR PR_VERSION=$(grep -o "__version__.*" socketsecurity/__init__.py | awk '{print $3}' | tr -d "'") - echo "PR_VERSION=$PR_VERSION" >> $GITHUB_ENV + echo "PR_VERSION=$PR_VERSION" >> "$GITHUB_ENV" # Get version from main branch MAIN_VERSION=$(git show origin/main:socketsecurity/__init__.py | grep -o "__version__.*" | awk '{print $3}' | tr -d "'") - echo "MAIN_VERSION=$MAIN_VERSION" >> $GITHUB_ENV + echo "MAIN_VERSION=$MAIN_VERSION" >> "$GITHUB_ENV" export PR_VERSION export MAIN_VERSION # Compare against the latest published PyPI release. python3 <<'PY' + import http.client import json import os import subprocess + import time import tomllib + import urllib.error import urllib.request from packaging import version @@ -72,8 +75,47 @@ jobs: ) raise SystemExit(1) - with urllib.request.urlopen("https://pypi.org/pypi/socketsecurity/json") as response: - pypi_data = json.load(response) + # This is a required check, so a dropped connection to PyPI would + # otherwise block the merge until someone reruns the job. Retry + # network errors, timeouts and 5xx responses, and if PyPI still can't + # be read, say so instead of failing with a bare traceback that looks + # like a version problem. OSError covers URLError, timeouts and SSL + # errors; HTTPException covers a response cut off mid-read, which + # urllib doesn't wrap in URLError. + pypi_url = "https://pypi.org/pypi/socketsecurity/json" + attempts = 4 + pypi_data = None + for attempt in range(1, attempts + 1): + try: + with urllib.request.urlopen(pypi_url, timeout=15) as response: + pypi_data = json.load(response) + break + except urllib.error.HTTPError as exc: + if exc.code < 500: + print( + f"❌ PyPI returned HTTP {exc.code} for {pypi_url}, so the " + f"latest published version couldn't be read. This is " + f"not a problem with the version in this PR." + ) + raise SystemExit(1) + error = exc + except (OSError, http.client.HTTPException) as exc: + error = exc + if attempt < attempts: + delay = 2 ** attempt + print( + f"⚠️ PyPI request failed (attempt {attempt}/{attempts}): " + f"{error!r}. Retrying in {delay}s." + ) + time.sleep(delay) + + if pypi_data is None: + print( + f"❌ Couldn't reach PyPI ({pypi_url}) after {attempts} attempts; " + f"last error: {error!r}. This is a network problem, not a " + f"problem with the version in this PR. Rerun the job." + ) + raise SystemExit(1) published_versions = [] for raw in pypi_data.get("releases", {}).keys(): From 9a010002794e18df7c9b2b8660b21ff9a2e4298c Mon Sep 17 00:00:00 2001 From: lelia <2418071+lelia@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:36:05 -0500 Subject: [PATCH 2/4] Bump version to 2.15.2 main released 2.15.1, which this branch was riding unreleased. --- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- socketsecurity/__init__.py | 2 +- uv.lock | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c9860fe..9b8ab334 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 2.15.2 + +### Changed: retry the PyPI lookup in the version check + +- The `check_version` CI job now retries the PyPI request on connection + errors, timeouts and HTTP 5xx, and says when a failure is PyPI's rather + than the PR's version. No change to the CLI itself. + ## 2.15.1 ### Changed: bump pinned Coana CLI to 15.15.3 diff --git a/pyproject.toml b/pyproject.toml index a087a973..e0e26547 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" [project] name = "socketsecurity" -version = "2.15.1" +version = "2.15.2" requires-python = ">= 3.11" license = {"file" = "LICENSE"} dependencies = [ diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index 828d3ccb..a4353933 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -1,4 +1,4 @@ __author__ = 'socket.dev' -__version__ = '2.15.1' +__version__ = '2.15.2' USER_AGENT_NAME = 'socket-python-cli' USER_AGENT = f'{USER_AGENT_NAME}/{__version__}' diff --git a/uv.lock b/uv.lock index cef0b651..2f60a6ee 100644 --- a/uv.lock +++ b/uv.lock @@ -1334,7 +1334,7 @@ wheels = [ [[package]] name = "socketsecurity" -version = "2.15.1" +version = "2.15.2" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" }, From fa869b4edc27811e17c2d010c01cdb09131c84d8 Mon Sep 17 00:00:00 2001 From: lelia <2418071+lelia@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:43:15 -0500 Subject: [PATCH 3/4] Retry PyPI 429 responses in the version check A rate limit is as transient as a 5xx, so it gets the same backoff instead of failing the required check on the first attempt. Bump to 2.15.11, since main has released 2.15.10. --- .github/workflows/version-check.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/version-check.yml b/.github/workflows/version-check.yml index 6e3dd0cf..f55c09e6 100644 --- a/.github/workflows/version-check.yml +++ b/.github/workflows/version-check.yml @@ -79,9 +79,9 @@ jobs: # otherwise block the merge until someone reruns the job. Retry # network errors, timeouts, rate limits (429) and 5xx responses, and # if PyPI still can't be read, say so instead of failing with a bare - # traceback that looks like a version problem. OSError covers URLError, timeouts and SSL - # errors; HTTPException covers a response cut off mid-read, which - # urllib doesn't wrap in URLError. + # traceback that looks like a version problem. OSError covers + # URLError, timeouts and SSL errors; HTTPException covers a response + # cut off mid-read, which urllib doesn't wrap in URLError. pypi_url = "https://pypi.org/pypi/socketsecurity/json" attempts = 4 pypi_data = None From e82f40a968b512f0bae3b0cff36bc4a24cc4ba0c Mon Sep 17 00:00:00 2001 From: lelia <2418071+lelia@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:15:51 -0500 Subject: [PATCH 4/4] Handle PyPI outages in the version check Retry unreadable responses, honor bounded Retry-After delays, and report PyPI lookup failures in PR comments. Add regression coverage for retry and failure paths. --- .github/workflows/version-check.yml | 62 ++++------------ CHANGELOG.md | 7 +- scripts/ci/pypi_lookup.py | 71 ++++++++++++++++++ tests/unit/test_pypi_lookup.py | 107 ++++++++++++++++++++++++++++ 4 files changed, 196 insertions(+), 51 deletions(-) create mode 100644 scripts/ci/pypi_lookup.py create mode 100644 tests/unit/test_pypi_lookup.py diff --git a/.github/workflows/version-check.yml b/.github/workflows/version-check.yml index f55c09e6..eabcfbe1 100644 --- a/.github/workflows/version-check.yml +++ b/.github/workflows/version-check.yml @@ -42,15 +42,11 @@ jobs: # Compare against the latest published PyPI release. python3 <<'PY' - import http.client - import json import os import subprocess - import time import tomllib - import urllib.error - import urllib.request from packaging import version + from scripts.ci.pypi_lookup import PyPILookupError, fetch_pypi_releases pr_ver = version.parse(os.environ["PR_VERSION"]) main_ver = version.parse(os.environ["MAIN_VERSION"]) @@ -75,50 +71,16 @@ jobs: ) raise SystemExit(1) - # This is a required check, so a dropped connection to PyPI would - # otherwise block the merge until someone reruns the job. Retry - # network errors, timeouts, rate limits (429) and 5xx responses, and - # if PyPI still can't be read, say so instead of failing with a bare - # traceback that looks like a version problem. OSError covers - # URLError, timeouts and SSL errors; HTTPException covers a response - # cut off mid-read, which urllib doesn't wrap in URLError. - pypi_url = "https://pypi.org/pypi/socketsecurity/json" - attempts = 4 - pypi_data = None - for attempt in range(1, attempts + 1): - try: - with urllib.request.urlopen(pypi_url, timeout=15) as response: - pypi_data = json.load(response) - break - except urllib.error.HTTPError as exc: - if exc.code < 500 and exc.code != 429: - print( - f"❌ PyPI returned HTTP {exc.code} for {pypi_url}, so the " - f"latest published version couldn't be read. This is " - f"not a problem with the version in this PR." - ) - raise SystemExit(1) - error = exc - except (OSError, http.client.HTTPException) as exc: - error = exc - if attempt < attempts: - delay = 2 ** attempt - print( - f"⚠️ PyPI request failed (attempt {attempt}/{attempts}): " - f"{error!r}. Retrying in {delay}s." - ) - time.sleep(delay) - - if pypi_data is None: - print( - f"❌ Couldn't reach PyPI ({pypi_url}) after {attempts} attempts; " - f"last error: {error!r}. This is a network problem, not a " - f"problem with the version in this PR. Rerun the job." - ) + try: + releases = fetch_pypi_releases() + except PyPILookupError as exc: + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: + print("pypi_lookup_failed=true", file=output) + print(f"❌ {exc}") raise SystemExit(1) published_versions = [] - for raw in pypi_data.get("releases", {}).keys(): + for raw in releases: parsed = version.parse(raw) if not parsed.is_prerelease and not parsed.is_devrelease: published_versions.append(parsed) @@ -191,9 +153,13 @@ jobs: MAIN_VERSION: ${{ env.MAIN_VERSION }} PR_VERSION: ${{ env.PR_VERSION }} CHECK_RESULT: ${{ steps.version_check.outcome }} + PYPI_LOOKUP_FAILED: ${{ steps.version_check.outputs.pypi_lookup_failed }} with: script: | const success = process.env.CHECK_RESULT === 'success'; + const failureBody = process.env.PYPI_LOOKUP_FAILED === 'true' + ? '❌ **Version Check Failed**\n\nThe job could not read the latest release from PyPI. See the job log for details and rerun the check once PyPI is available.' + : '❌ **Version Check Failed**\n\nSee the Version Check job log for details.'; const prNumber = context.payload.pull_request.number; const owner = context.repo.owner; const repo = context.repo.repo; @@ -222,7 +188,7 @@ jobs: owner: owner, repo: repo, comment_id: versionComment.id, - body: `❌ **Version Check Failed**\n\nPlease increment...` + body: failureBody }); } } else if (!success) { @@ -231,6 +197,6 @@ jobs: owner: owner, repo: repo, issue_number: prNumber, - body: `❌ **Version Check Failed**\n\nPlease increment...` + body: failureBody }); } diff --git a/CHANGELOG.md b/CHANGELOG.md index 08ad6d3d..fb5cd2fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,10 @@ ### Changed: retry the PyPI lookup in the version check -- The `check_version` CI job now retries the PyPI request on connection - errors, timeouts, HTTP 429 and HTTP 5xx, and says when a failure is PyPI's - rather than the PR's version. No change to the CLI itself. +- The `check_version` CI job retries connection errors, timeouts, unreadable + responses, HTTP 429, and HTTP 5xx. It honors PyPI's `Retry-After` header + within its retry limits and reports PyPI lookup failures in the job log + and PR comment. ## 2.16.0 diff --git a/scripts/ci/pypi_lookup.py b/scripts/ci/pypi_lookup.py new file mode 100644 index 00000000..3c8c0a3a --- /dev/null +++ b/scripts/ci/pypi_lookup.py @@ -0,0 +1,71 @@ +import http.client +import json +import time +import urllib.error +import urllib.request +from datetime import UTC +from email.utils import parsedate_to_datetime + +PYPI_URL = "https://pypi.org/pypi/socketsecurity/json" +ATTEMPTS = 4 +MAX_RETRY_WAIT = 60 + + +class PyPILookupError(Exception): + pass + + +def retry_after_seconds(value: str | None) -> float: + if not value: + return 0 + value = value.strip() + try: + if value.isascii() and value.isdecimal(): + return float(value) + date = parsedate_to_datetime(value) + if date.tzinfo is None: + date = date.replace(tzinfo=UTC) + return max(0, date.timestamp() - time.time()) + except (ValueError, OverflowError): + return 0 + + +def fetch_pypi_releases() -> dict: + for attempt in range(1, ATTEMPTS + 1): + retry_after = 0 + try: + with urllib.request.urlopen(PYPI_URL, timeout=15) as response: + data = json.load(response) + if not isinstance(data, dict) or not isinstance(data.get("releases"), dict): + raise ValueError("Expected a PyPI response with a releases object") + return data["releases"] + except urllib.error.HTTPError as exc: + exc.close() + if exc.code != 429 and not 500 <= exc.code < 600: + raise PyPILookupError( + f"PyPI returned HTTP {exc.code} for {PYPI_URL}." + ) from exc + error = exc + if exc.headers is not None: + retry_after = retry_after_seconds(exc.headers.get("Retry-After")) + except (OSError, http.client.HTTPException, ValueError) as exc: + error = exc + + if attempt == ATTEMPTS: + raise PyPILookupError( + f"Could not read releases from PyPI ({PYPI_URL}) after {attempt} attempts. " + f"Last error: {error!r}. Rerun the check once PyPI is available." + ) from error + + delay = max(2**attempt, retry_after) + if delay > MAX_RETRY_WAIT: + raise PyPILookupError( + f"PyPI requested a retry delay longer than {MAX_RETRY_WAIT} seconds " + f"after {error!r}. Rerun the check once PyPI is available." + ) from error + + print( + f"⚠️ PyPI request failed (attempt {attempt}/{ATTEMPTS}): {error!r}. Retrying in {delay:g}s.", + flush=True, + ) + time.sleep(delay) diff --git a/tests/unit/test_pypi_lookup.py b/tests/unit/test_pypi_lookup.py new file mode 100644 index 00000000..ddb22317 --- /dev/null +++ b/tests/unit/test_pypi_lookup.py @@ -0,0 +1,107 @@ +import http.client +from email.message import Message +from email.utils import formatdate +from importlib import import_module +from io import BytesIO +from pathlib import Path +from unittest.mock import Mock +from urllib.error import HTTPError, URLError + +import pytest + + +@pytest.fixture +def pypi_lookup(monkeypatch): + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2])) + return import_module("scripts.ci.pypi_lookup") + + +@pytest.fixture +def pypi_request(monkeypatch, pypi_lookup): + request = Mock() + sleep = Mock() + monkeypatch.setattr(pypi_lookup.urllib.request, "urlopen", request) + monkeypatch.setattr(pypi_lookup.time, "sleep", sleep) + return request, sleep + + +def http_error(status, retry_after=None): + headers = Message() + if retry_after is not None: + headers["Retry-After"] = retry_after + return HTTPError("https://pypi.org", status, "test error", headers, BytesIO()) + + +@pytest.mark.parametrize( + "failure", + [ + pytest.param(lambda: URLError("connection reset"), id="connection"), + pytest.param(TimeoutError, id="timeout"), + pytest.param(lambda: http.client.IncompleteRead(b"{"), id="incomplete-read"), + pytest.param(lambda: BytesIO(b'{"releases":'), id="truncated-json"), + pytest.param(lambda: BytesIO(b'{"releases":null}'), id="invalid-releases"), + pytest.param(lambda: http_error(429), id="rate-limit"), + pytest.param(lambda: http_error(503), id="service-unavailable"), + ], +) +def test_pypi_lookup_recovers_after_retry(pypi_lookup, pypi_request, failure): + request, sleep = pypi_request + request.side_effect = [failure(), BytesIO(b'{"releases":{"2.16.0":[]}}')] + + assert pypi_lookup.fetch_pypi_releases() == {"2.16.0": []} + assert request.call_count == 2 + request.assert_called_with(pypi_lookup.PYPI_URL, timeout=15) + sleep.assert_called_once_with(2) + + +def test_pypi_lookup_reports_exhausted_retries(pypi_lookup, pypi_request): + request, sleep = pypi_request + request.side_effect = TimeoutError("read timed out") + + with pytest.raises(pypi_lookup.PyPILookupError, match="after 4 attempts"): + pypi_lookup.fetch_pypi_releases() + + assert request.call_count == 4 + assert [call.args[0] for call in sleep.call_args_list] == [2, 4, 8] + + +def test_pypi_lookup_does_not_retry_permanent_http_error(pypi_lookup, pypi_request): + request, sleep = pypi_request + request.side_effect = http_error(404) + + with pytest.raises(pypi_lookup.PyPILookupError, match="HTTP 404"): + pypi_lookup.fetch_pypi_releases() + + assert request.call_count == 1 + sleep.assert_not_called() + + +@pytest.mark.parametrize( + ("status", "header", "delay"), + [ + (429, "30", 30), + (503, formatdate(1_030, usegmt=True), 30), + (429, "invalid", 2), + (429, "1", 2), + ], +) +def test_pypi_lookup_honors_retry_after( + pypi_lookup, pypi_request, monkeypatch, status, header, delay +): + request, sleep = pypi_request + monkeypatch.setattr(pypi_lookup.time, "time", lambda: 1_000) + request.side_effect = [http_error(status, header), BytesIO(b'{"releases":{}}')] + + assert pypi_lookup.fetch_pypi_releases() == {} + sleep.assert_called_once_with(delay) + + +def test_pypi_lookup_stops_when_retry_after_exceeds_limit(pypi_lookup, pypi_request): + request, sleep = pypi_request + request.side_effect = http_error(429, "120") + + with pytest.raises(pypi_lookup.PyPILookupError, match="longer than 60 seconds"): + pypi_lookup.fetch_pypi_releases() + + assert request.call_count == 1 + sleep.assert_not_called()