From 6d783539e4a4780ebbf0f9e2947a47f44da2812a Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 13:19:10 -0500 Subject: [PATCH 1/7] fix(plotting): keep connect segments colour-mapped and honour every colour key With a varying z, a colour in connect_kwargs replaced the segments' z colouring, so they no longer read off the colorbar. The segments now keep the points' colormap and norm, and the colour is dropped with a UserWarning naming the key. Without a varying z, every spelling of the colour (color, c, colors, edgecolor, edgecolors, ec) sets the segments' colour; before, c raised AttributeError and the others were overridden by the points' colour. Two colour keys raise TypeError. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++++ src/solarwindpy/plotting/scatter.py | 41 ++++++++++++++--- tests/plotting/test_scatter.py | 69 +++++++++++++++++++++++++++++ 3 files changed, 112 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c62d5af2e..3c0ca751c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- `Scatter.make_plot(connect=True)`: with a varying z, a colour in `connect_kwargs` replaced the + segments' z colouring, so they no longer matched the colorbar. The segments now keep the + colormap and the colour is ignored with a `UserWarning` naming its key. Without a varying z, + every spelling of the colour (`color`, `c`, `colors`, `edgecolor`, `edgecolors`, `ec`) now sets + the segments' colour; before, only `color` did, `c` raised `AttributeError`, and the others were + overridden by the points' colour. Giving two of them raises `TypeError`. + ## [0.5.0] - 2026-11-05 ### Changed - BREAKING CHANGES diff --git a/src/solarwindpy/plotting/scatter.py b/src/solarwindpy/plotting/scatter.py index a864fcf0e..25a529d27 100644 --- a/src/solarwindpy/plotting/scatter.py +++ b/src/solarwindpy/plotting/scatter.py @@ -10,8 +10,13 @@ from matplotlib import pyplot as plt from matplotlib.collections import LineCollection +from ..tools import _warn from . import base +# Every spelling of the segments' colour that LineCollection accepts, and +# ``c``, which ``ax.scatter`` accepts. +_COLOR_KEYS = ("color", "c", "colors", "edgecolor", "edgecolors", "ec") + class Scatter(base.ColorPlot): r"""Scatter plot of y against x, optionally colored by z. @@ -93,6 +98,9 @@ def make_plot( Passed to :class:`~matplotlib.collections.LineCollection`, e.g. ``linewidth``, ``alpha`` or ``zorder``. The defaults are a ``linewidth`` of 0.75 and a ``zorder`` just below the points'. + A colour, under any of the keys ``color``, ``c``, ``colors``, + ``edgecolor``, ``edgecolors`` or ``ec``, applies only without a + varying z (see Notes); at most one of them may be given. Not modified. kwargs: Passed to `ax.scatter`. @@ -125,9 +133,11 @@ def make_plot( When z varies, each segment is coloured by the mean z of its two points, ``(z_a + z_b) / 2``, through the points' colormap and norm, - the same objects, so the one colorbar reads both. Otherwise every - segment has the points' colour, unless ``connect_kwargs`` sets - ``color``. The segments do not set the axis limits. + the same objects, so the one colorbar reads both; a colour in + ``connect_kwargs`` is then ignored, with a ``UserWarning`` naming its + key. Otherwise every segment has the colour that ``connect_kwargs`` + sets, or the points' colour if it sets none. The segments do not set + the axis limits. """ if ax is None: fig, ax = plt.subplots() @@ -176,7 +186,8 @@ def _connect(self, ax, collection, data, zkey, connect_kwargs): zkey: str or None ``"z"`` if the points are colour-mapped, else None. connect_kwargs: Mapping or None - Passed to ``LineCollection``. + Passed to ``LineCollection``, except a colour key, which sets the + segments' colour only when `zkey` is None. Returns ------- @@ -190,14 +201,30 @@ def _connect(self, ax, collection, data, zkey, connect_kwargs): drawn &= xy[:, i] > 0 xy = xy[drawn] - kwargs = cbook.normalize_kwargs(connect_kwargs or {}, LineCollection) + kwargs = dict(connect_kwargs or {}) + given = [k for k in _COLOR_KEYS if k in kwargs] + if len(given) > 1: + raise TypeError( + f"connect_kwargs gives the colour twice, as {given!r}; give one." + ) + color = kwargs.pop(given[0]) if given else None + kwargs = cbook.normalize_kwargs(kwargs, LineCollection) kwargs.setdefault("linewidth", 0.75) kwargs.setdefault("zorder", collection.get_zorder() - 0.5) if zkey is None: - kwargs.setdefault("color", collection.get_facecolor()[0]) - segments = LineCollection(np.stack([xy[:-1], xy[1:]], axis=1), **kwargs) + if color is None: + color = collection.get_facecolor()[0] + segments = LineCollection( + np.stack([xy[:-1], xy[1:]], axis=1), color=color, **kwargs + ) else: + if given: + _warn( + f"connect_kwargs[{given[0]!r}] is ignored: z varies, so each " + "segment is coloured by the mean z of its two points through " + "the points' colormap and norm." + ) z = data.loc[:, zkey].to_numpy(dtype=float)[drawn] order = np.argsort(z, kind="stable") xy, z = xy[order], z[order] diff --git a/tests/plotting/test_scatter.py b/tests/plotting/test_scatter.py index aaa18a263..d5192a529 100644 --- a/tests/plotting/test_scatter.py +++ b/tests/plotting/test_scatter.py @@ -581,3 +581,72 @@ def test_segments_do_not_change_the_axis_limits(ax): Scatter(EX, EY, EZ).make_plot(ax=ax, connect=True) assert ax.get_xlim() == (EX.min(), EX.max()) assert ax.get_ylim() == (EY.min(), EY.max()) + + +# --------------------------------------------------------------------------- +# A colour in connect_kwargs: with a varying z the segments are colour-mapped, +# so the colour is dropped with a warning naming the key the caller typed; +# otherwise it is the segments' one colour, under any of its spellings. +# --------------------------------------------------------------------------- + +COLOR_KEYS = ["color", "c", "colors", "edgecolor", "edgecolors", "ec"] + + +@pytest.mark.parametrize("key", COLOR_KEYS) +def test_connect_colour_with_varying_z_warns_and_is_ignored(ax, key): + """With a varying z the segments keep the colormap; the colour key is named. + + ON FAILURE: the code is wrong. + """ + kwargs = {key: "red"} + with pytest.warns(UserWarning, match=rf"connect_kwargs\['{key}'\]") as record: + _, points, lc, _ = Scatter(EX, EY, EZ).make_plot( + ax=ax, connect=True, connect_kwargs=kwargs + ) + assert kwargs == {key: "red"} + assert len(record) == 1 + assert record[0].filename == __file__ + assert "colormap" in str(record[0].message) + ax.figure.canvas.draw() + expected = points.get_cmap()(points.norm(_mean_z(EZ, Z_ORDER))) + np.testing.assert_allclose(lc.get_edgecolor(), expected) + + +@pytest.mark.parametrize("key", COLOR_KEYS) +@pytest.mark.parametrize("z", [None, pd.Series(7.0, index=range(EX.size))]) +def test_connect_colour_without_varying_z_is_honoured(ax, key, z): + """With no z, or a constant one, every spelling of the colour sets the segments'. + + ON FAILURE: the code is wrong. + """ + with warnings.catch_warnings(): + warnings.simplefilter("error") + _, _, lc, _ = Scatter(EX, EY, z).make_plot( + ax=ax, connect=True, connect_kwargs={key: "red"} + ) + ax.figure.canvas.draw() + np.testing.assert_array_equal(lc.get_edgecolor(), [[1.0, 0.0, 0.0, 1.0]]) + + +@pytest.mark.parametrize("z", [None, EZ]) +def test_connect_without_a_colour_key_does_not_warn(ax, z): + """Styling the segments without a colour issues no warning. + + ON FAILURE: the code is wrong. + """ + with warnings.catch_warnings(): + warnings.simplefilter("error") + Scatter(EX, EY, z).make_plot( + ax=ax, connect=True, connect_kwargs={"linewidth": 2.0} + ) + + +def test_connect_refuses_two_colour_keys(ax): + """Two spellings of the colour are ambiguous, as matplotlib's aliases are. + + ON FAILURE: the code is wrong. + """ + with pytest.raises(TypeError, match="'color'.*'ec'"): + Scatter(EX, EY).make_plot( + ax=ax, connect=True, connect_kwargs={"color": "red", "ec": "blue"} + ) From e60a36929fd5110a8c59a151a26eb581c01b50fb Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 14:26:32 -0500 Subject: [PATCH 2/7] fix(scripts): fill the feedstock tracking issue and report the tagged commit The issue body was a plain string, so its version, checksum, commands and dependency comparison went out as literal placeholders; it is now built by build_issue_body as an f-string. The Git Commit line read the annotated tag object's ID; it now resolves the tag to the commit it names. Co-Authored-By: Claude Opus 5.5 --- scripts/update_conda_feedstock.py | 64 ++++++++++++++------ tests/test_update_conda_feedstock.py | 90 ++++++++++++++++++++++++++++ 2 files changed, 137 insertions(+), 17 deletions(-) create mode 100644 tests/test_update_conda_feedstock.py diff --git a/scripts/update_conda_feedstock.py b/scripts/update_conda_feedstock.py index 5a2356be1..203c9f5ac 100644 --- a/scripts/update_conda_feedstock.py +++ b/scripts/update_conda_feedstock.py @@ -119,9 +119,10 @@ def verify_git_tag_provenance( print(f"⚠️ Git tag {tag_name} not found in repository") return False, None - # Get commit SHA for the tag + # The commit the tag names; a bare annotated tag resolves to the + # tag object, not the commit. result = subprocess.run( - ["git", "rev-parse", tag_name], + ["git", "rev-parse", f"{tag_name}^{{commit}}"], capture_output=True, text=True, check=True, @@ -433,36 +434,30 @@ def _get_dependency_comparison(self) -> str: ⚠️ **CRITICAL**: The autotick bot updates **version and SHA256 ONLY**, NOT dependencies! """ - def create_tracking_issue( + def build_issue_body( self, version_str: str, sha256_hash: str, - dry_run: bool = False, + comparison_output: str, commit_sha: Optional[str] = None, - ) -> Optional[str]: - """Create GitHub issue for tracking the feedstock update. + ) -> str: + """Return the tracking issue's Markdown body. Parameters ---------- version_str : str Version being updated sha256_hash : str - SHA256 hash for reference - dry_run : bool - If True, only print what would be done + SHA256 hash of the sdist + comparison_output : str + The dependency comparison, from `_get_dependency_comparison` commit_sha : str, optional Git commit SHA if provenance was verified Returns ------- - str or None - Issue URL if created successfully + str """ - title = f"Conda feedstock update for SolarWindPy v{version_str}" - - # Get dependency comparison - self._get_dependency_comparison() - body = f"""## Automated Conda Feedstock Update **Version**: `{version_str}` @@ -477,7 +472,7 @@ def create_tracking_issue( **GitHub Release**: https://github.com/blalterman/SolarWindPy/releases/tag/v{version_str} **Source Provenance**: ✅ Verified""" - body += """ + body += f""" --- @@ -550,6 +545,41 @@ def create_tracking_issue( 🤖 Generated by conda feedstock automation """ + return body + + def create_tracking_issue( + self, + version_str: str, + sha256_hash: str, + dry_run: bool = False, + commit_sha: Optional[str] = None, + ) -> Optional[str]: + """Create GitHub issue for tracking the feedstock update. + + Parameters + ---------- + version_str : str + Version being updated + sha256_hash : str + SHA256 hash for reference + dry_run : bool + If True, only print what would be done + commit_sha : str, optional + Git commit SHA if provenance was verified + + Returns + ------- + str or None + Issue URL if created successfully + """ + title = f"Conda feedstock update for SolarWindPy v{version_str}" + + body = self.build_issue_body( + version_str, + sha256_hash, + self._get_dependency_comparison(), + commit_sha=commit_sha, + ) if dry_run: print(f"🔍 DRY RUN: Would create issue '{title}'") diff --git a/tests/test_update_conda_feedstock.py b/tests/test_update_conda_feedstock.py new file mode 100644 index 000000000..2fcfedf4d --- /dev/null +++ b/tests/test_update_conda_feedstock.py @@ -0,0 +1,90 @@ +# Spent-When: PERMANENT(scripts/update_conda_feedstock.py is deleted) +# Supersedes: none +"""``scripts/update_conda_feedstock.py`` fills its tracking issue. + +``subprocess.run`` is replaced by a stub where the test would run ``gh`` or the +dependency comparison. The commit SHA is checked against a real annotated tag +in a temporary repo. +""" + +import importlib.util +import os +import re +import subprocess +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[1] + +_spec = importlib.util.spec_from_file_location( + "update_conda_feedstock", REPO_ROOT / "scripts" / "update_conda_feedstock.py" +) +feedstock = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(feedstock) + +VERSION = "0.5.0" +SHA = "ab" * 32 + + +@pytest.fixture +def updater(): + return feedstock.CondaFeedstockUpdater(fork_owner="someone") + + +def test_the_issue_body_fills_every_placeholder(updater, monkeypatch): + """The issue names the version, package, hash and commit, and the comparison. + + ON FAILURE: the code is wrong. + """ + table = "DEPENDENCY COMPARISON\nnumpy>=2 | numpy >=2" + created = {} + + def run(cmd, **kwargs): + if cmd[0] == "gh": + created["body"] = cmd[cmd.index("--body") + 1] + return subprocess.CompletedProcess(cmd, 0, stdout="https://issue\n") + assert cmd[-1] == "scripts/compare_feedstock_deps.py" + return subprocess.CompletedProcess(cmd, 0, stdout=table) + + monkeypatch.setattr(feedstock.subprocess, "run", run) + url = updater.create_tracking_issue(VERSION, SHA, commit_sha="c0ffee") + assert url == "https://issue" + body = created["body"] + assert re.findall(r"\{[^{}\s]*\}", body) == [] + assert table in body + for text in (VERSION, SHA, "c0ffee", "solarwindpy-feedstock"): + assert text in body + + +def test_the_commit_sha_is_the_tagged_commit_not_the_tag_object(tmp_path, monkeypatch): + """An annotated tag is its own object; the issue reports the commit it names. + + Under a git hook, ``GIT_DIR``, ``GIT_INDEX_FILE`` and the like name the + repository being committed to; every git call here, the script's too, + would act on it, not on ``tmp_path``. They are cleared first. + ON FAILURE: the code is wrong. + """ + for name in [n for n in os.environ if n.startswith("GIT_")]: + monkeypatch.delenv(name) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull) + monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") + + def git(*args): + return subprocess.run( + ["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], + cwd=tmp_path, + capture_output=True, + text=True, + check=True, + ).stdout.strip() + + git("init", "-q", "-b", "master") + git("commit", "-q", "--allow-empty", "-m", "release") + git("tag", "-a", f"v{VERSION}", "-m", "the release") + head = git("rev-parse", "HEAD") + assert git("rev-parse", f"v{VERSION}") != head + + u = feedstock.CondaFeedstockUpdater(fork_owner="someone") + u.project_root = tmp_path + assert u.verify_git_tag_provenance(VERSION) == (True, head) From 98fdb53d40b4ecd42a268b6bd5a9413812970fc9 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 14:29:18 -0500 Subject: [PATCH 3/7] test(scripts): pin the feedstock script's PyPI wait and JSON checksum read Target tests, xfail(strict=True) until the script change lands: a 404 or a release listed before its sdist is retried with a bounded backoff, and the sdist SHA256 comes from PyPI's JSON API without downloading the file. The pre-release refusal already holds and guards. requests joins the test and dev extras because the tests import it. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 2 + tests/test_update_conda_feedstock.py | 136 ++++++++++++++++++++++++++- 2 files changed, 133 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 9d74e8df7..50dc09609 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -126,6 +126,7 @@ test = [ "pytest-cov>=6.0", "packaging>=23.0", "pyyaml>=6.0", # tests/test_declared_versions.py reads YAML + "requests>=2.31", # tests/test_update_conda_feedstock.py stubs requests.get ] docs = [ "sphinx>=7.0", @@ -142,6 +143,7 @@ dev = [ "pytest>=9.0", "pytest-cov>=6.0", "pyyaml>=6.0", # tests/test_declared_versions.py reads YAML + "requests>=2.31", # tests/test_update_conda_feedstock.py stubs requests.get # Documentation tools "sphinx>=7.0", "sphinx_rtd_theme>=2.0", diff --git a/tests/test_update_conda_feedstock.py b/tests/test_update_conda_feedstock.py index 2fcfedf4d..aed550198 100644 --- a/tests/test_update_conda_feedstock.py +++ b/tests/test_update_conda_feedstock.py @@ -1,10 +1,15 @@ # Spent-When: PERMANENT(scripts/update_conda_feedstock.py is deleted) # Supersedes: none -"""``scripts/update_conda_feedstock.py`` fills its tracking issue. +"""``scripts/update_conda_feedstock.py`` reads PyPI reliably and fills its issue. -``subprocess.run`` is replaced by a stub where the test would run ``gh`` or the -dependency comparison. The commit SHA is checked against a real annotated tag -in a temporary repo. +The release workflow runs the script right after the upload, when PyPI may not +yet list the release or its sdist. The script reads the sdist's SHA256 from +PyPI's JSON API, retrying with a bounded backoff, and never downloads the file. + +The network is the boundary: ``requests.get`` is replaced by a scripted +sequence of responses, ``subprocess.run`` by a stub where the test would run +``gh`` or the dependency comparison, and the backoff's sleep by a recorder. +The commit SHA is checked against a real annotated tag in a temporary repo. """ import importlib.util @@ -14,6 +19,7 @@ from pathlib import Path import pytest +import requests REPO_ROOT = Path(__file__).resolve().parents[1] @@ -25,11 +31,131 @@ VERSION = "0.5.0" SHA = "ab" * 32 +JSON_URL = f"https://pypi.org/pypi/solarwindpy/{VERSION}/json" +SDIST = { + "packagetype": "sdist", + "url": f"https://files.pythonhosted.org/packages/xx/solarwindpy-{VERSION}.tar.gz", + "digests": {"sha256": SHA}, +} +WHEEL = {"packagetype": "bdist_wheel", "digests": {"sha256": "cd" * 32}} + + +class Response: + """The parts of ``requests.Response`` the script reads.""" + + def __init__(self, status_code, payload=None): + self.status_code = status_code + self._payload = payload + + def json(self): + return self._payload + + +def released(*urls): + return Response(200, {"info": {"version": VERSION}, "urls": list(urls)}) @pytest.fixture def updater(): - return feedstock.CondaFeedstockUpdater(fork_owner="someone") + """An updater whose sleeps are recorded, not waited.""" + u = feedstock.CondaFeedstockUpdater(fork_owner="someone") + u.slept = [] + u._sleep = u.slept.append + return u + + +@pytest.fixture +def pypi(monkeypatch): + """Serve ``requests.get`` from a list of responses; record the URLs asked for.""" + calls = [] + responses = [] + + def get(url, timeout): + calls.append(url) + r = responses.pop(0) + if isinstance(r, Exception): + raise r + return r + + monkeypatch.setattr(feedstock.requests, "get", get) + return responses, calls + + +@pytest.mark.xfail(strict=True, reason="the PyPI JSON read lands next") +def test_a_404_is_retried_with_backoff_until_the_release_is_listed(updater, pypi): + """The CDN-style 404s right after an upload are waited out, not fatal. + + ON FAILURE: the code is wrong. + """ + responses, calls = pypi + responses += [Response(404), Response(404), released(WHEEL, SDIST)] + assert updater.get_sdist_sha256(VERSION) == SHA + assert calls == [JSON_URL] * 3 + assert updater.slept == [15, 30] + + +@pytest.mark.xfail(strict=True, reason="the PyPI JSON read lands next") +def test_a_release_without_its_sdist_yet_is_retried(updater, pypi): + """PyPI listing the wheel before the sdist is not yet ready. + + ON FAILURE: the code is wrong. + """ + responses, _ = pypi + responses += [ + released(WHEEL), + requests.ConnectionError("reset"), + released(WHEEL, SDIST), + ] + assert updater.get_sdist_sha256(VERSION) == SHA + assert updater.slept == [15, 30] + + +@pytest.mark.xfail(strict=True, reason="the PyPI JSON read lands next") +def test_the_wait_is_bounded(updater, pypi): + """A release that never appears gives up after ``RELEASE_WAIT`` seconds. + + ON FAILURE: the code is wrong. + """ + responses, calls = pypi + responses += [Response(404)] * 50 + assert updater.get_sdist_sha256(VERSION) is None + assert updater.slept == [15, 30, 60, 120, 120, 120, 120, 15] + assert sum(updater.slept) == feedstock.RELEASE_WAIT + assert len(calls) == len(updater.slept) + 1 + + +@pytest.mark.xfail(strict=True, reason="the PyPI JSON read lands next") +def test_the_sha256_is_read_from_the_json_without_downloading_the_sdist(updater, pypi): + """Only the JSON API is requested; the digest is PyPI's, not recomputed. + + ON FAILURE: the code is wrong. + """ + responses, calls = pypi + responses += [released(SDIST)] + assert updater.get_sdist_sha256(VERSION) == SHA + assert calls == [JSON_URL] + + +@pytest.mark.xfail(strict=True, reason="the PyPI JSON read lands next") +def test_validation_waits_for_the_release_and_checks_its_version(updater, pypi): + """``validate_pypi_release`` shares the retrying fetch and checks the version. + + ON FAILURE: the code is wrong. + """ + responses, _ = pypi + responses += [Response(404), released(SDIST)] + assert updater.validate_pypi_release(VERSION) + assert updater.slept == [15] + + responses += [Response(200, {"info": {"version": "0.4.1"}, "urls": [SDIST]})] + assert not updater.validate_pypi_release(VERSION) + + +def test_a_prerelease_is_refused_without_asking_pypi(updater, pypi): + """ON FAILURE: the code is wrong.""" + _, calls = pypi + assert not updater.validate_pypi_release("0.6.0rc1") + assert calls == [] def test_the_issue_body_fills_every_placeholder(updater, monkeypatch): From 44b5997ca6aafc6d4aea9818283b1999b4270d72 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 14:31:51 -0500 Subject: [PATCH 4/7] fix(scripts): read the sdist SHA256 from PyPI's JSON API with a bounded wait Right after an upload, files.pythonhosted.org returned a cached 404 for the sdist, so the publish job's tracking issue failed until a manual retry. The script now reads the digest PyPI lists in its JSON API, retrying a 404, a release listed before its sdist, or a network error with a 15 s backoff that doubles to a 120 s cap, for at most 600 s. calculate_sha256 and its download are removed; validate_pypi_release shares the same retrying fetch. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 + scripts/update_conda_feedstock.py | 166 ++++++++++++++++++--------- tests/test_update_conda_feedstock.py | 5 - 3 files changed, 114 insertions(+), 62 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c0ca751c..a1e7a6f61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 every spelling of the colour (`color`, `c`, `colors`, `edgecolor`, `edgecolors`, `ec`) now sets the segments' colour; before, only `color` did, `c` raised `AttributeError`, and the others were overridden by the points' colour. Giving two of them raises `TypeError`. +- Release automation: the conda-forge tracking issue now reads the sdist's SHA256 from PyPI's + JSON API, waiting up to ten minutes with backoff while a new release is not yet listed, instead + of downloading the file and failing on the CDN's early 404. Its body fills in the version, + checksum and dependency comparison, which went out as literal placeholders, and its Git Commit + line names the released commit rather than the annotated tag object. ## [0.5.0] - 2026-11-05 diff --git a/scripts/update_conda_feedstock.py b/scripts/update_conda_feedstock.py index 203c9f5ac..0e513f033 100644 --- a/scripts/update_conda_feedstock.py +++ b/scripts/update_conda_feedstock.py @@ -2,8 +2,9 @@ """Automate conda-forge feedstock updates for SolarWindPy releases. This script automates the process of updating the conda-forge feedstock -after a new PyPI release. It handles version updates, SHA256 calculation, -and creates GitHub issues for tracking. +after a new PyPI release. It reads the sdist's SHA256 from PyPI's JSON API, +waiting with backoff while the new release is not yet listed, and creates a +GitHub issue for tracking. Usage: python scripts/update_conda_feedstock.py v0.1.5 @@ -12,11 +13,11 @@ """ import argparse -import hashlib import json import os import subprocess import sys +import time from pathlib import Path from typing import Optional, Tuple @@ -26,6 +27,13 @@ # Add project root to path for imports sys.path.insert(0, str(Path(__file__).parent.parent)) +# How long to wait for PyPI to list a new release and its sdist, and the +# backoff between attempts: the first wait, the factor, and the cap. +RELEASE_WAIT = 600 +BACKOFF_START = 15 +BACKOFF_FACTOR = 2 +BACKOFF_MAX = 120 + class CondaFeedstockUpdater: """Handles automated conda-forge feedstock updates. @@ -55,6 +63,8 @@ def __init__( self.feedstock_repo = feedstock_repo self.fork_owner = fork_owner or self._get_github_username() self.project_root = Path(__file__).parent.parent + # Injectable so the tests need not wait out the backoff. + self._sleep = time.sleep def _get_github_username(self) -> str: """Get current GitHub username from git config or environment. @@ -246,87 +256,129 @@ def verify_github_release_integrity( print(f"⚠️ GitHub release verification skipped: {e}") return True # Permissive - don't block on errors - def validate_pypi_release(self, version_str: str, timeout: int = 10) -> bool: - """Validate that the PyPI release exists and is not a pre-release. + def fetch_release_json( + self, version_str: str, max_wait: float = RELEASE_WAIT, timeout: int = 10 + ) -> Optional[dict]: + """Return PyPI's JSON for the release, once it lists the sdist. + + Right after an upload PyPI may not list the release, or may list it + before its sdist; both are retried with exponential backoff until + ``max_wait`` seconds of waiting have passed. Parameters ---------- version_str : str - Version string to validate + Version to fetch + max_wait : float + Total seconds to wait between attempts before giving up timeout : int Request timeout in seconds Returns ------- - bool - True if valid stable release exists + dict or None + The release's JSON, or None if it never listed an sdist """ - try: - # Parse version to check for pre-release - v = version.parse(version_str) - if v.is_prerelease: - print( - f"❌ Pre-release version {version_str} - skipping feedstock update" - ) - return False - - # Check PyPI availability - url = f"https://pypi.org/pypi/{self.package_name}/{version_str}/json" - response = requests.get(url, timeout=timeout) + url = f"https://pypi.org/pypi/{self.package_name}/{version_str}/json" + waited = 0.0 + delay = BACKOFF_START + while True: + try: + response = requests.get(url, timeout=timeout) + if response.status_code == 200: + data = response.json() + if self._sdist_entry(data) is not None: + return data + reason = "no sdist listed yet" + else: + reason = f"status {response.status_code}" + except (requests.RequestException, ValueError) as e: + reason = str(e) - if response.status_code != 200: + if waited >= max_wait: print( - f"❌ PyPI version {version_str} not found (status: {response.status_code})" + f"❌ PyPI has no sdist for {self.package_name} v{version_str} " + f"after {waited:.0f}s ({reason})" ) - return False + return None + pause = min(delay, max_wait - waited) + print(f"⏳ PyPI not ready ({reason}); retrying in {pause:.0f}s...") + self._sleep(pause) + waited += pause + delay = min(delay * BACKOFF_FACTOR, BACKOFF_MAX) + + @staticmethod + def _sdist_entry(data: dict) -> Optional[dict]: + """Return the ``urls`` entry of the sdist in PyPI release JSON, if any.""" + for entry in data.get("urls", []): + if entry.get("packagetype") == "sdist": + return entry + return None + + def validate_pypi_release(self, version_str: str) -> bool: + """Validate that the PyPI release exists and is not a pre-release. - data = response.json() - pypi_version = data.get("info", {}).get("version") + Parameters + ---------- + version_str : str + Version string to validate - if pypi_version != version_str: - print( - f"❌ Version mismatch: requested {version_str}, PyPI has {pypi_version}" - ) - return False + Returns + ------- + bool + True if valid stable release exists + """ + try: + v = version.parse(version_str) + except version.InvalidVersion as e: + print(f"❌ Invalid version {version_str}: {e}") + return False + if v.is_prerelease: + print(f"❌ Pre-release version {version_str} - skipping feedstock update") + return False - print(f"✅ Validated PyPI release: {self.package_name} v{version_str}") - return True + data = self.fetch_release_json(version_str) + if data is None: + return False - except Exception as e: - print(f"❌ Failed to validate PyPI release: {e}") + pypi_version = data.get("info", {}).get("version") + if pypi_version != version_str: + print( + f"❌ Version mismatch: requested {version_str}, PyPI has {pypi_version}" + ) return False - def calculate_sha256(self, version_str: str, timeout: int = 30) -> Optional[str]: - """Calculate SHA256 hash of the PyPI source distribution. + print(f"✅ Validated PyPI release: {self.package_name} v{version_str}") + return True + + def get_sdist_sha256(self, version_str: str) -> Optional[str]: + """Return the SHA256 of the release's sdist, as PyPI's JSON API lists it. + + Reading the digest PyPI computed at upload needs no download, so it + does not depend on the file CDN, which can serve a cached 404 for a + while after the upload. Parameters ---------- version_str : str - Version to download and hash - timeout : int - Download timeout in seconds + Version whose sdist to look up Returns ------- str or None SHA256 hash as hex string, or None if failed """ - url = f"https://pypi.org/packages/source/{self.package_name[0]}/{self.package_name}/{self.package_name}-{version_str}.tar.gz" - - try: - print( - f"Downloading {self.package_name} v{version_str} for SHA256 calculation..." - ) - response = requests.get(url, timeout=timeout) - response.raise_for_status() - - sha256_hash = hashlib.sha256(response.content).hexdigest() - print(f"✅ SHA256: {sha256_hash}") - return sha256_hash - - except Exception as e: - print(f"❌ Failed to calculate SHA256: {e}") + data = self.fetch_release_json(version_str) + if data is None: + return None + entry = self._sdist_entry(data) + sha256_hash = entry.get("digests", {}).get("sha256") + if not sha256_hash: + print(f"❌ PyPI lists no sha256 for {entry.get('url')}") return None + print(f"✅ sdist: {entry.get('url')}") + print(f"✅ SHA256: {sha256_hash}") + return sha256_hash def update_meta_yaml( self, version_str: str, sha256_hash: str, meta_path: Path @@ -484,7 +536,7 @@ def build_issue_body( ### Update Checklist - [x] PyPI release validated -- [x] SHA256 calculated from source distribution +- [x] SHA256 read from PyPI's listing of the source distribution - [ ] **Dependencies reviewed** (see comparison above) - [ ] Autotick bot PR created (usually 2-6 hours) - [ ] If dependencies changed: manually update bot PR @@ -684,8 +736,8 @@ def update_feedstock(self, version_str: str, dry_run: bool = False) -> bool: print("⚠️ Git provenance could not be verified (may be running in CI)") commit_sha = None # Ensure it's None if verification failed - # Step 2: Calculate SHA256 - sha256_hash = self.calculate_sha256(version_str) + # Step 2: Read the sdist's SHA256 from PyPI + sha256_hash = self.get_sdist_sha256(version_str) if not sha256_hash: return False diff --git a/tests/test_update_conda_feedstock.py b/tests/test_update_conda_feedstock.py index aed550198..7919ca78a 100644 --- a/tests/test_update_conda_feedstock.py +++ b/tests/test_update_conda_feedstock.py @@ -81,7 +81,6 @@ def get(url, timeout): return responses, calls -@pytest.mark.xfail(strict=True, reason="the PyPI JSON read lands next") def test_a_404_is_retried_with_backoff_until_the_release_is_listed(updater, pypi): """The CDN-style 404s right after an upload are waited out, not fatal. @@ -94,7 +93,6 @@ def test_a_404_is_retried_with_backoff_until_the_release_is_listed(updater, pypi assert updater.slept == [15, 30] -@pytest.mark.xfail(strict=True, reason="the PyPI JSON read lands next") def test_a_release_without_its_sdist_yet_is_retried(updater, pypi): """PyPI listing the wheel before the sdist is not yet ready. @@ -110,7 +108,6 @@ def test_a_release_without_its_sdist_yet_is_retried(updater, pypi): assert updater.slept == [15, 30] -@pytest.mark.xfail(strict=True, reason="the PyPI JSON read lands next") def test_the_wait_is_bounded(updater, pypi): """A release that never appears gives up after ``RELEASE_WAIT`` seconds. @@ -124,7 +121,6 @@ def test_the_wait_is_bounded(updater, pypi): assert len(calls) == len(updater.slept) + 1 -@pytest.mark.xfail(strict=True, reason="the PyPI JSON read lands next") def test_the_sha256_is_read_from_the_json_without_downloading_the_sdist(updater, pypi): """Only the JSON API is requested; the digest is PyPI's, not recomputed. @@ -136,7 +132,6 @@ def test_the_sha256_is_read_from_the_json_without_downloading_the_sdist(updater, assert calls == [JSON_URL] -@pytest.mark.xfail(strict=True, reason="the PyPI JSON read lands next") def test_validation_waits_for_the_release_and_checks_its_version(updater, pypi): """``validate_pypi_release`` shares the retrying fetch and checks the version. From db61971aaff32863bc47275bdd3ad31a4b92e353 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 15:07:17 -0500 Subject: [PATCH 5/7] test(scripts): pin one PyPI fetch per run, a null urls list, and --max-wait Target tests from the PR review, xfail(strict=True) until the script change lands. The version-mismatch check moves to its own test, since a shared fetch answers a second validation from the first response. Co-Authored-By: Claude Opus 5.5 --- tests/test_update_conda_feedstock.py | 75 ++++++++++++++++++++++++++-- 1 file changed, 72 insertions(+), 3 deletions(-) diff --git a/tests/test_update_conda_feedstock.py b/tests/test_update_conda_feedstock.py index 7919ca78a..5cdfdf743 100644 --- a/tests/test_update_conda_feedstock.py +++ b/tests/test_update_conda_feedstock.py @@ -55,15 +55,19 @@ def released(*urls): return Response(200, {"info": {"version": VERSION}, "urls": list(urls)}) -@pytest.fixture -def updater(): +def make_updater(**kwargs): """An updater whose sleeps are recorded, not waited.""" - u = feedstock.CondaFeedstockUpdater(fork_owner="someone") + u = feedstock.CondaFeedstockUpdater(fork_owner="someone", **kwargs) u.slept = [] u._sleep = u.slept.append return u +@pytest.fixture +def updater(): + return make_updater() + + @pytest.fixture def pypi(monkeypatch): """Serve ``requests.get`` from a list of responses; record the URLs asked for.""" @@ -142,10 +146,75 @@ def test_validation_waits_for_the_release_and_checks_its_version(updater, pypi): assert updater.validate_pypi_release(VERSION) assert updater.slept == [15] + +def test_a_version_mismatch_is_refused(updater, pypi): + """ON FAILURE: the code is wrong.""" + responses, _ = pypi responses += [Response(200, {"info": {"version": "0.4.1"}, "urls": [SDIST]})] assert not updater.validate_pypi_release(VERSION) +@pytest.mark.xfail(strict=True, reason="the shared fetch and --max-wait land next") +def test_one_fetch_serves_validation_and_the_checksum(updater, pypi): + """The release is validated and hashed from one response, asked for once. + + ON FAILURE: the code is wrong. + """ + responses, calls = pypi + responses += [released(SDIST)] + assert updater.validate_pypi_release(VERSION) + assert updater.get_sdist_sha256(VERSION) == SHA + assert calls == [JSON_URL] + + +@pytest.mark.xfail(strict=True, reason="the shared fetch and --max-wait land next") +def test_a_null_urls_list_is_a_release_without_its_sdist(updater, pypi): + """ON FAILURE: the code is wrong.""" + responses, _ = pypi + responses += [ + Response(200, {"info": {"version": VERSION}, "urls": None}), + released(SDIST), + ] + assert updater.get_sdist_sha256(VERSION) == SHA + assert updater.slept == [15] + + +@pytest.mark.xfail(strict=True, reason="the shared fetch and --max-wait land next") +def test_release_wait_bounds_the_wait(pypi): + """With ``release_wait=0`` a missing release fails after one request. + + ON FAILURE: the code is wrong. + """ + u = make_updater(release_wait=0) + responses, calls = pypi + responses += [Response(404)] + assert u.get_sdist_sha256(VERSION) is None + assert calls == [JSON_URL] + assert u.slept == [] + + +@pytest.mark.xfail(strict=True, reason="the shared fetch and --max-wait land next") +def test_the_max_wait_flag_reaches_the_updater(monkeypatch): + """ON FAILURE: the code is wrong.""" + made = {} + + class Recorder: + def __init__(self, **kwargs): + made.update(kwargs) + + def update_feedstock(self, version_str, dry_run=False): + return True + + monkeypatch.setattr(feedstock, "CondaFeedstockUpdater", Recorder) + monkeypatch.setattr( + feedstock.sys, "argv", ["update_conda_feedstock.py", VERSION, "--max-wait", "0"] + ) + with pytest.raises(SystemExit) as exit_: + feedstock.main() + assert exit_.value.code == 0 + assert made["release_wait"] == 0 + + def test_a_prerelease_is_refused_without_asking_pypi(updater, pypi): """ON FAILURE: the code is wrong.""" _, calls = pypi From c084dce2daab4dd64dc775c6cbc30fee7139674f Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 15:10:20 -0500 Subject: [PATCH 6/7] fix(scripts): fetch the PyPI release once and bound the wait from the CLI Validation and the checksum read now share one PyPI response, kept per version, so a run asks PyPI once and cannot wait twice. A null urls list counts as a release without its sdist. --max-wait sets the wait, so a local run on a mistyped version need not sit out ten minutes. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++- scripts/update_conda_feedstock.py | 33 +++++++++++++++++++++++----- tests/test_update_conda_feedstock.py | 4 ---- 3 files changed, 30 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a1e7a6f61..8c5aaa344 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 JSON API, waiting up to ten minutes with backoff while a new release is not yet listed, instead of downloading the file and failing on the CDN's early 404. Its body fills in the version, checksum and dependency comparison, which went out as literal placeholders, and its Git Commit - line names the released commit rather than the annotated tag object. + line names the released commit rather than the annotated tag object. `--max-wait SECONDS` shortens the wait for + local runs. ## [0.5.0] - 2026-11-05 diff --git a/scripts/update_conda_feedstock.py b/scripts/update_conda_feedstock.py index 0e513f033..372da6d0b 100644 --- a/scripts/update_conda_feedstock.py +++ b/scripts/update_conda_feedstock.py @@ -47,6 +47,7 @@ def __init__( package_name: str = "solarwindpy", feedstock_repo: str = "conda-forge/solarwindpy-feedstock", fork_owner: Optional[str] = None, + release_wait: float = RELEASE_WAIT, ): """Initialize the feedstock updater. @@ -58,13 +59,18 @@ def __init__( GitHub repository for the feedstock (org/repo format) fork_owner : str, optional GitHub username for fork (if different from current user) + release_wait : float + Total seconds to wait for PyPI to list a release and its sdist """ self.package_name = package_name self.feedstock_repo = feedstock_repo self.fork_owner = fork_owner or self._get_github_username() self.project_root = Path(__file__).parent.parent + self.release_wait = release_wait # Injectable so the tests need not wait out the backoff. self._sleep = time.sleep + # One fetch per version serves both validation and the checksum. + self._release_json = {} def _get_github_username(self) -> str: """Get current GitHub username from git config or environment. @@ -257,20 +263,22 @@ def verify_github_release_integrity( return True # Permissive - don't block on errors def fetch_release_json( - self, version_str: str, max_wait: float = RELEASE_WAIT, timeout: int = 10 + self, version_str: str, max_wait: Optional[float] = None, timeout: int = 10 ) -> Optional[dict]: """Return PyPI's JSON for the release, once it lists the sdist. Right after an upload PyPI may not list the release, or may list it before its sdist; both are retried with exponential backoff until - ``max_wait`` seconds of waiting have passed. + ``max_wait`` seconds of waiting have passed. A release once found is + kept, so later calls for the same version do not ask PyPI again. Parameters ---------- version_str : str Version to fetch - max_wait : float - Total seconds to wait between attempts before giving up + max_wait : float, optional + Total seconds to wait between attempts before giving up; defaults + to ``release_wait`` timeout : int Request timeout in seconds @@ -279,6 +287,10 @@ def fetch_release_json( dict or None The release's JSON, or None if it never listed an sdist """ + if version_str in self._release_json: + return self._release_json[version_str] + if max_wait is None: + max_wait = self.release_wait url = f"https://pypi.org/pypi/{self.package_name}/{version_str}/json" waited = 0.0 delay = BACKOFF_START @@ -288,6 +300,7 @@ def fetch_release_json( if response.status_code == 200: data = response.json() if self._sdist_entry(data) is not None: + self._release_json[version_str] = data return data reason = "no sdist listed yet" else: @@ -310,7 +323,7 @@ def fetch_release_json( @staticmethod def _sdist_entry(data: dict) -> Optional[dict]: """Return the ``urls`` entry of the sdist in PyPI release JSON, if any.""" - for entry in data.get("urls", []): + for entry in data.get("urls") or []: if entry.get("packagetype") == "sdist": return entry return None @@ -813,6 +826,15 @@ def main(): parser.add_argument( "--no-issue", action="store_true", help="Skip creating tracking issue" ) + parser.add_argument( + "--max-wait", + type=float, + default=RELEASE_WAIT, + help=( + "Seconds to wait for PyPI to list the release and its sdist " + f"(default: {RELEASE_WAIT})" + ), + ) args = parser.parse_args() @@ -824,6 +846,7 @@ def main(): package_name=args.package, feedstock_repo=args.feedstock_repo, fork_owner=args.fork_owner, + release_wait=args.max_wait, ) # Run update workflow diff --git a/tests/test_update_conda_feedstock.py b/tests/test_update_conda_feedstock.py index 5cdfdf743..98eb8ba1d 100644 --- a/tests/test_update_conda_feedstock.py +++ b/tests/test_update_conda_feedstock.py @@ -154,7 +154,6 @@ def test_a_version_mismatch_is_refused(updater, pypi): assert not updater.validate_pypi_release(VERSION) -@pytest.mark.xfail(strict=True, reason="the shared fetch and --max-wait land next") def test_one_fetch_serves_validation_and_the_checksum(updater, pypi): """The release is validated and hashed from one response, asked for once. @@ -167,7 +166,6 @@ def test_one_fetch_serves_validation_and_the_checksum(updater, pypi): assert calls == [JSON_URL] -@pytest.mark.xfail(strict=True, reason="the shared fetch and --max-wait land next") def test_a_null_urls_list_is_a_release_without_its_sdist(updater, pypi): """ON FAILURE: the code is wrong.""" responses, _ = pypi @@ -179,7 +177,6 @@ def test_a_null_urls_list_is_a_release_without_its_sdist(updater, pypi): assert updater.slept == [15] -@pytest.mark.xfail(strict=True, reason="the shared fetch and --max-wait land next") def test_release_wait_bounds_the_wait(pypi): """With ``release_wait=0`` a missing release fails after one request. @@ -193,7 +190,6 @@ def test_release_wait_bounds_the_wait(pypi): assert u.slept == [] -@pytest.mark.xfail(strict=True, reason="the shared fetch and --max-wait land next") def test_the_max_wait_flag_reaches_the_updater(monkeypatch): """ON FAILURE: the code is wrong.""" made = {} From 94c27b1fc4f4c0ed001dc452837053983ba13470 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 15:12:03 -0500 Subject: [PATCH 7/7] docs(plotting): note that facecolor in connect_kwargs has no effect Co-Authored-By: Claude Opus 5.5 --- src/solarwindpy/plotting/scatter.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/solarwindpy/plotting/scatter.py b/src/solarwindpy/plotting/scatter.py index 25a529d27..2a695cc51 100644 --- a/src/solarwindpy/plotting/scatter.py +++ b/src/solarwindpy/plotting/scatter.py @@ -98,6 +98,7 @@ def make_plot( Passed to :class:`~matplotlib.collections.LineCollection`, e.g. ``linewidth``, ``alpha`` or ``zorder``. The defaults are a ``linewidth`` of 0.75 and a ``zorder`` just below the points'. + ``facecolor`` has no visible effect, since lines have no faces. A colour, under any of the keys ``color``, ``c``, ``colors``, ``edgecolor``, ``edgecolors`` or ``ec``, applies only without a varying z (see Notes); at most one of them may be given.