#!/usr/bin/env python3 """Verify the exact C11 replay environment and its native geospatial stack.""" from __future__ import annotations import argparse import hashlib import importlib.metadata import json import platform import re import sys import warnings from pathlib import Path ROOT = Path(__file__).resolve().parents[1] ENV_DIR = ROOT / "release_tools/environments" LOCK = ENV_DIR / "requirements-replay.lock.txt" PYTHON_VERSION = (ENV_DIR / "python-replay.version").read_text(encoding="utf-8").strip() EXPECTED_IMPLEMENTATION = "CPython" EXPECTED_SYSTEM = "Linux" EXPECTED_MACHINE = "x86_64" def sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() def locked_versions(path: Path) -> dict[str, str]: versions: dict[str, str] = {} for line in path.read_text(encoding="utf-8").splitlines(): match = re.match(r"^([A-Za-z0-9_.-]+)==([^ ;\\]+)", line) if match: versions[re.sub(r"[-_.]+", "-", match.group(1)).lower()] = match.group(2) if not versions: raise ValueError(f"no locked packages found in {path}") return versions def installed_versions() -> dict[str, str]: return { re.sub(r"[-_.]+", "-", distribution.metadata["Name"]).lower(): distribution.version for distribution in importlib.metadata.distributions() if distribution.metadata.get("Name") } def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--output", type=Path) args = parser.parse_args() locked = locked_versions(LOCK) installed = installed_versions() actual_python = platform.python_version() actual_implementation = platform.python_implementation() actual_system = platform.system() actual_machine = platform.machine() missing = sorted(name for name in locked if name not in installed) mismatched = { name: {"expected": version, "actual": installed.get(name)} for name, version in locked.items() if installed.get(name) != version } unexpected = sorted(name for name in installed if name not in locked) with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("error") import numpy as np import pyproj import rasterio import scipy from PIL import Image from rasterio.io import MemoryFile from scipy import ndimage from shapely.geometry import Polygon labels, components = ndimage.label(np.array([[1, 0], [0, 1]], dtype="uint8")) if components != 2 or labels.shape != (2, 2): raise AssertionError("SciPy connected-component smoke test failed") profile = { "driver": "GTiff", "height": 2, "width": 2, "count": 1, "dtype": "uint8", "nodata": 255, "transform": rasterio.transform.from_origin(0, 2, 1, 1), "crs": "EPSG:4326", } with MemoryFile() as memory: with memory.open(**profile) as dataset: dataset.write(np.array([[1, 0], [255, 1]], dtype="uint8"), 1) with memory.open() as dataset: if dataset.nodata != 255 or int((dataset.read(1) == 1).sum()) != 2: raise AssertionError("Rasterio finite-nodata smoke test failed") if Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]).area != 1.0: raise AssertionError("Shapely geometry smoke test failed") x, y = pyproj.Transformer.from_crs(4326, 3857, always_xy=True).transform(0, 0) if abs(x) > 1e-9 or abs(y) > 1e-9: raise AssertionError("PyProj transform smoke test failed") with Image.new("RGB", (2, 2)) as image: if image.size != (2, 2): raise AssertionError("Pillow smoke test failed") platform_matches = ( actual_implementation == EXPECTED_IMPLEMENTATION and actual_system == EXPECTED_SYSTEM and actual_machine == EXPECTED_MACHINE ) report = { "schema_version": "geodisaster_replay_environment_v1", "ready": ( actual_python == PYTHON_VERSION and platform_matches and not missing and not mismatched and not unexpected ), "python": { "expected": PYTHON_VERSION, "actual": actual_python, "expected_implementation": EXPECTED_IMPLEMENTATION, "implementation": actual_implementation, "executable": sys.executable, }, "platform": { "expected_system": EXPECTED_SYSTEM, "system": actual_system, "expected_machine": EXPECTED_MACHINE, "machine": actual_machine, "matches": platform_matches, "release": platform.release(), "libc": platform.libc_ver(), }, "lock": { "path": str(LOCK.relative_to(ROOT)), "sha256": sha256(LOCK), "packages": locked, }, "installed_packages": installed, "missing_packages": missing, "mismatched_packages": mismatched, "unexpected_packages": unexpected, "native_libraries": { "gdal": rasterio.__gdal_version__, "proj": pyproj.proj_version_str, "geos": getattr(__import__("shapely"), "geos_version_string", None), }, "compatibility_warnings": [str(item.message) for item in caught], "smoke_tests": { "numpy_scipy": "passed", "rasterio_finite_nodata": "passed", "shapely": "passed", "pyproj": "passed", "pillow": "passed", }, } if args.output: args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8") print(json.dumps(report, indent=2, sort_keys=True)) if not report["ready"]: raise SystemExit(1) if __name__ == "__main__": main()