Skip to content
Closed
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
163 changes: 163 additions & 0 deletions pixi.lock

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion pixi.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ pyyaml = ">=6.0.3,<7"
# Some git repos need git-lfs, see https://github.com/RoboStack/ros-jazzy/issues/118
git-lfs = ">=3.8.1,<4"
pytest = ">=9.2.0,<10"
# conda channels and package archives in the tools (repodata, versions, downloads)
py-rattler = ">=0.29.0,<0.30"
# gh for the workflows: one version everywhere (the runner's is not on PATH on Windows)
gh = ">=2.106.0,<3"
# built and published by vinca-rs's release workflow
Expand All @@ -46,5 +48,5 @@ vinca = { git = "https://github.com/RoboStack/vinca.git", rev = "74d1e856d5b00c0
rs = { cmd = "python tools/robostack.py", description = "Run a task for one distribution: `pixi run rs <distro> <task>` (generate-recipes, build, build-one, check-patches, check-deps, create-snapshot, render-pinning, sort, ...)." }
sort = { cmd = "sh -lc 'vinca-sort-vinca-lists $@ shared/vinca.yaml && vinca-sort-yaml-keys $@ shared/robostack.yaml shared/pkg_additional_info.yaml && for d in distros/*/; do [ -f $d/vinca.yaml ] || continue; (cd $d && vinca-sort-vinca-lists $@ vinca.yaml && vinca-sort-yaml-keys $@ pkg_additional_info.yaml rosdistro_additional_recipes.yaml) || exit 1; done' --", description = "Sort the YAML files of all distributions (`--check` to only check)." }
test = { cmd = "python -m pytest tools/tests", description = "Unit tests of the repository tooling (tools/tests)." }
abi-check = { cmd = "pixi exec -s python=3.14 -s zstandard -s pyyaml -s pyelftools python tools/abi_check.py", description = "Compare the ABI of package builds with libabigail (Linux only): `pixi run abi-check --distro jazzy --latest-pairs 30`, `--old a.conda --new b.conda`, or `--pr-builds <dir>` (a pull request's builds against the released ones)." }
abi-check = { cmd = "pixi exec -s python=3.14 -s py-rattler -s pyyaml -s pyelftools python tools/abi_check.py", description = "Compare the ABI of package builds with libabigail (Linux only): `pixi run abi-check --distro jazzy --latest-pairs 30`, `--old a.conda --new b.conda`, or `--pr-builds <dir>` (a pull request's builds against the released ones)." }
render-pinning = { cmd = "sh -lc 'for d in distros/*/; do [ -f $d/vinca.yaml ] || continue; python tools/robostack.py $(basename $d) render-pinning || exit 1; done'", description = "Regenerate every distribution's conda_build_config.yaml from shared/pinning and its distro.yaml." }
95 changes: 27 additions & 68 deletions tools/abi_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,20 @@
from __future__ import annotations

import argparse
import io
import asyncio
import re
import json
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile
import urllib.error
import urllib.request
import zipfile
from pathlib import Path

import zstandard
import rattler
from rattler.package_streaming import download_and_extract, download_to_path, extract

from channel_repodata import channel_records as _channel_records

# abidiff exit status bits (libabigail's abidiff_status)
ABI_ERROR = 1
Expand All @@ -53,39 +52,15 @@
ABI_INCOMPATIBLE_CHANGE = 8


def _open(url: str):
return urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "robostack-abi-check"}), timeout=300)


def extract_conda(path: Path, dest: Path) -> None:
"""Unpack a .conda (zip with zstd-compressed tarballs) or .tar.bz2 package."""
dest.mkdir(parents=True, exist_ok=True)
if path.suffix == ".conda":
with zipfile.ZipFile(path) as z:
for name in z.namelist():
if name.startswith("pkg-") and name.endswith(".tar.zst"):
data = zstandard.ZstdDecompressor().stream_reader(io.BytesIO(z.read(name)))
with tarfile.open(fileobj=data, mode="r|") as tar:
tar.extractall(dest, filter="data")
else:
with tarfile.open(path, "r:bz2") as tar:
tar.extractall(dest, filter="data")
def read_index(path: Path) -> dict:
"""The repodata record of a package file (its info/index.json)."""
return json.loads(asyncio.run(rattler.RepoDataRecord.from_package_archive(path)).to_json())


def read_index(path: Path) -> dict:
"""info/index.json of a package."""
if path.suffix == ".conda":
with zipfile.ZipFile(path) as z:
name = next(n for n in z.namelist() if n.startswith("info-") and n.endswith(".tar.zst"))
data = zstandard.ZstdDecompressor().stream_reader(io.BytesIO(z.read(name)))
with tarfile.open(fileobj=data, mode="r|") as tar:
for member in tar:
if member.name == "info/index.json":
return json.load(tar.extractfile(member))
else:
with tarfile.open(path, "r:bz2") as tar:
return json.load(tar.extractfile("info/index.json"))
raise ValueError(f"{path} has no info/index.json")
def channel_records(channel: str, platform: str) -> list[dict]:
"""The repodata records of the channel for the platform (none when it has no
packages for it)."""
return _channel_records(channel, platform) or []


def libraries(prefix: Path) -> dict[str, Path]:
Expand Down Expand Up @@ -125,8 +100,8 @@ def classify(rc: int, report: str) -> str:
def compare(old_pkg: Path, new_pkg: Path, work: Path) -> dict:
a, b = work / "old", work / "new"
shutil.rmtree(work, ignore_errors=True)
extract_conda(old_pkg, a)
extract_conda(new_pkg, b)
extract(old_pkg, a)
extract(new_pkg, b)
old_libs, new_libs = libraries(a), libraries(b)
result = {"libraries": {}, "removed_libraries": sorted(set(old_libs) - set(new_libs)),
"headers": header_changes(a, b)}
Expand Down Expand Up @@ -225,10 +200,6 @@ def short_name(name: str, distro: str) -> str | None:
return None


def _version_key(v: str):
return [int(p) if p.isdigit() else 0 for p in v.replace("-", ".").split(".")]


def _belongs_to(rec: dict, distro: str) -> bool:
"""A record of this distribution: ros-<distro>-* names, or ros2-* builds pinned to
its mutex (a channel such as the test channel can hold several distributions)."""
Expand All @@ -248,20 +219,12 @@ def released(channels: str | list[str], platform: str, distro: str) -> dict[str,
empty compatibility packages are left out."""
builds: dict[str, dict[str, list[dict]]] = {}
for channel in [channels] if isinstance(channels, str) else channels:
try:
with _open(f"{channel.rstrip('/')}/{platform}/repodata.json") as r:
data = json.load(r)
except urllib.error.HTTPError as error:
if error.code == 404: # no packages for this platform there
continue
raise
records = list(data.get("packages", {}).items()) + list(data.get("packages.conda", {}).items())
for filename, rec in records:
for rec in channel_records(channel, platform):
short = short_name(rec["name"], distro)
if short is None or _is_compatibility_package(rec) or not _belongs_to(rec, distro):
continue
builds.setdefault(short, {}).setdefault(rec["version"], []).append(
{"file": filename, "channel": channel, **rec})
{**rec, "file": rec["fn"], "channel": channel})
by_name: dict[str, dict[str, dict]] = {}
for short, versions in builds.items():
for version, recs in versions.items():
Expand All @@ -284,7 +247,7 @@ def python_abi(rec):


def newest(versions: dict[str, dict]) -> dict:
return versions[max(versions, key=_version_key)]
return versions[max(versions, key=rattler.Version)]


def latest_pairs(channel: str, platform: str, count: int, distro: str) -> list[tuple[str, dict, dict]]:
Expand All @@ -294,7 +257,7 @@ def latest_pairs(channel: str, platform: str, count: int, distro: str) -> list[t
for short, versions in sorted(released(channel, platform, distro).items()):
if len(versions) < 2:
continue
ordered = sorted(versions, key=_version_key)
ordered = sorted(versions, key=rattler.Version)
pairs.append((short, versions[ordered[-2]], versions[ordered[-1]]))
# most recently uploaded new versions first
pairs.sort(key=lambda p: p[2].get("timestamp", 0), reverse=True)
Expand Down Expand Up @@ -362,31 +325,27 @@ def channel_for(distro: str) -> list[str]:
return extra + [rs.repodata_url(distro)]


def download(channel: str, platform: str, filename: str, dest: Path) -> Path:
target = dest / filename
def download(rec: dict, dest: Path) -> Path:
target = dest / rec["file"]
if not target.exists():
with _open(f"{channel.rstrip('/')}/{platform}/{filename}") as r, open(target, "wb") as f:
shutil.copyfileobj(r, f)
asyncio.run(download_to_path(rattler.Client(), rec["url"], target))
return target


# Above this many dependents, list them all instead of downloading each to check it.
MAX_DEPENDENTS_TO_INSPECT = 40


def linking_dependents(channel, platform, by_name, candidates, sonames, downloads: Path, tmp: Path) -> dict:
def linking_dependents(by_name, candidates, sonames, tmp: Path) -> dict:
"""Which of the dependents link to one of the SONAMEs (and so need a rebuild);
metapackages, Python packages and configurations don't."""
if len(candidates) > MAX_DEPENDENTS_TO_INSPECT:
return {"rebuild": candidates, "checked": False}
rebuild = []
for name in candidates:
rec = newest(by_name[name])
pkg = download(rec["channel"], platform, rec["file"], downloads)
target = tmp / "dependent"
shutil.rmtree(target, ignore_errors=True)
extract_conda(pkg, target)
pkg.unlink(missing_ok=True)
asyncio.run(download_and_extract(rattler.Client(), newest(by_name[name])["url"], target))
if needed(target) & set(sonames):
rebuild.append(name)
return {"rebuild": rebuild, "checked": True, "candidates": len(candidates)}
Expand Down Expand Up @@ -426,14 +385,14 @@ def check_pr_builds(pr_dir: Path, channel: str, platform: str, distro: str, tmp:
if old["file"] == pkg.name:
continue
print(f"{short}: {old['version']} (build {old.get('build_number', 0)}) -> {index['version']} (PR)", flush=True)
old_pkg = download(old["channel"], platform, old["file"], downloads)
old_pkg = download(old, downloads)
res = compare(old_pkg, pkg, tmp / "work")
old_pkg.unlink(missing_ok=True)
res.update(old=f"{old['version']} (build {old.get('build_number', 0)})", new=index["version"],
pins=pin_changes(old, index, distro))
if res["broken_sonames"]:
res["dependents"] = linking_dependents(
channel, platform, by_name, dependents(by_name, short, distro), res["broken_sonames"], downloads, tmp
by_name, dependents(by_name, short, distro), res["broken_sonames"], tmp
)
results[short] = res
print(f" -> {res['verdict']}", flush=True)
Expand Down Expand Up @@ -585,8 +544,8 @@ def main() -> int:
downloads.mkdir()
for name, old, new in latest_pairs(channel, args.platform, args.latest_pairs, args.distro):
print(f"{name}: {old['version']} -> {new['version']}", flush=True)
old_pkg = download(old["channel"], args.platform, old["file"], downloads)
new_pkg = download(new["channel"], args.platform, new["file"], downloads)
old_pkg = download(old, downloads)
new_pkg = download(new, downloads)
res = compare(old_pkg, new_pkg, tmp / "work")
res.update(old=old["version"], new=new["version"])
results[name] = res
Expand Down
30 changes: 30 additions & 0 deletions tools/channel_repodata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""The repodata records of a conda channel, fetched with py-rattler (sharded repodata
where the channel has it, compressed and cached otherwise)."""

from __future__ import annotations

import asyncio
import json
import tempfile
from pathlib import Path

import rattler
from rattler.exceptions import FetchRepoDataError

REPODATA_CACHE = Path(tempfile.gettempdir()) / "robostack-repodata"


def channel_records(channel: str, platform: str) -> list[dict] | None:
"""The records of the channel's platform subdir (each with its "fn" and "url"),
or None when the channel has no such subdir; network failures raise."""
try:
[repodata] = asyncio.run(rattler.fetch_repo_data(
channels=[rattler.Channel(channel)], platforms=[rattler.Subdir(platform)],
cache_path=REPODATA_CACHE, callback=None,
))
except FetchRepoDataError as error:
# network failures raise the same type
if not str(error).startswith("repodata not found"):
raise
return None
return [json.loads(record.to_json()) for record in repodata.load_all_records()]
87 changes: 23 additions & 64 deletions tools/check_dependency_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
from urllib.request import Request, urlopen

import ruamel.yaml
from rattler import Version, VersionSpec
from rattler.exceptions import InvalidVersionError, InvalidVersionSpecError

ROS_PREFIXES = ("ros-", "ros2-")
DEFAULT_CHANNELS = ["https://repo.prefix.dev/conda-forge"]
Expand Down Expand Up @@ -690,7 +692,7 @@ def report_conflicts(
if any(len(spec.split()) > 1 for _, spec in specs):
print(" note: the spec is version-restricted (dummy package in pkg_additional_info.yaml?);"
" a newer conda-forge version may already be built against the pinned libraries.")
glibc_needs = sorted({m.group(1) for m in _GLIBC_NEED_RE.finditer(block)}, key=version_tuple)
glibc_needs = sorted({m.group(1) for m in _GLIBC_NEED_RE.finditer(block)}, key=Version)
if (glibc_needs and host_names is not None and normalized(culprit) not in host_names
and args.platform.startswith("linux")
and solver.solve(f"glibc-{culprit}", pins, specs, glibc=glibc_needs[-1])[0]):
Expand Down Expand Up @@ -824,74 +826,31 @@ def report_migrations(


# ----------------------------------------------------------------------- stale
_VERSION_PART_RE = re.compile(r"^(\d+)(.*)$")


def version_tuple(version: str) -> tuple[int, ...]:
parts: list[int] = []
for part in version.strip().split("."):
match = _VERSION_PART_RE.match(part)
if not match:
break
parts.append(int(match.group(1)))
if match.group(2): # pre-release suffix such as '0a0': stop here
break
return tuple(parts)


def _pad(t: tuple[int, ...], n: int) -> tuple[int, ...]:
return t + (0,) * (n - len(t))


def _cmp(a: tuple[int, ...], b: tuple[int, ...]) -> int:
n = max(len(a), len(b))
a, b = _pad(a, n), _pad(b, n)
return (a > b) - (a < b)


def pin_range(pin_version: str) -> tuple[tuple[int, ...], tuple[int, ...], bool]:
"""Return (lowest, upper_exclusive, exact) for a pin such as '1.90', '7.35.1.*' or '11.*'."""
text = pin_version.strip()
exact = not text.endswith(".*") and "*" not in text
prefix = version_tuple(text.rstrip("*").rstrip("."))
if not prefix:
return (0,), (10**9,), False
upper = prefix[:-1] + (prefix[-1] + 1,)
return prefix, upper, exact
_SPEC_VERSION_RE = re.compile(r"\d[0-9A-Za-z_.+!]*")


def constraint_compatible(constraint: str, pin_version: str) -> bool:
"""Whether some version can satisfy both the dependency constraint and the pin."""
low, upper_excl, _ = pin_range(pin_version)
constraint = constraint.strip()
if constraint in ("", "*"):
"""Whether some version can satisfy both the dependency constraint and the pin
('1.90', '1.90.*': every version starting with 1.90)."""
pin = pin_version.strip().rstrip("*").rstrip(".")
if not pin[:1].isdigit():
return True
if "|" in constraint:
return any(constraint_compatible(part, pin_version) for part in constraint.split("|"))
for clause in [c.strip() for c in constraint.split(",") if c.strip()]:
if clause.startswith(">="):
if _cmp(upper_excl, version_tuple(clause[2:])) <= 0:
return False
elif clause.startswith(">"):
if _cmp(upper_excl, version_tuple(clause[1:])) <= 0:
return False
elif clause.startswith("<="):
if _cmp(low, version_tuple(clause[2:])) > 0:
return False
elif clause.startswith("<"):
if _cmp(low, version_tuple(clause[1:])) >= 0:
return False
elif clause.startswith("!="):
try:
spec = VersionSpec(constraint.strip() or "*")
pinned = VersionSpec(f"{pin}.*")
except InvalidVersionSpecError:
return True
# rattler can't intersect specs; if the two overlap, the lowest version they share
# is the pin's, a bound of the constraint, or (for a > bound) just above one
bounds = [v.rstrip(".") for v in _SPEC_VERSION_RE.findall(constraint)]
for candidate in [pin, *bounds, *(f"{v}.1" for v in bounds)]:
try:
version = Version(candidate)
except InvalidVersionError:
continue
else:
other = clause[2:] if clause.startswith("==") else clause
other_low, other_upper, _ = pin_range(other)
n = max(len(low), len(other_low))
a, b = _pad(low, n), _pad(other_low, n)
k = min(len(low), len(other_low))
if a[:k] != b[:k]:
return False
return True
if spec.matches(version) and pinned.matches(version):
return True
return False


_CBC_KEY_RE = re.compile(r"^([A-Za-z0-9_.-]+):\s*(?:#\s*\[(.+?)\])?\s*$")
Expand Down
Loading