From 43c8f03cf5375434060b060d421389581da49213 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 2 Nov 2026 13:38:15 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20results=20library=20phase=204=20?= =?UTF-8?q?=E2=80=94=20packaging,=20distribution=20and=20parity?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - autofit/export/package.py: package() — size-capped / exactly-N part zips (objects whole), tables.zip, parts_manifest.csv, package.json, SHA256SUMS, README + KNOWN_ISSUES with provenance (git revs, results-index hash); deterministic atomic zips (UTC times, STORED media); delta rebuilds keep assignments and leave unchanged parts byte-identical; stale parts removed; include_dataset; force - autofit/export/verify.py: verify() — checksums, CRC (corruption reported, not raised), members vs package.json, empty members, CSV parse/ragged/row counts, coverage from the real zips, unlisted zips - autofit/export/parity.py: compare() (identity incl. column sets, exact incl. big-integer ids and one-sided blanks, tolerance-by-sigma with floors, gating, markdown report) and scatter_between() (run-to-run z distribution) - python -m autofit.export {package,verify,compare}; af.export Refs #1756 Co-Authored-By: Claude Opus 5.5 --- autofit/__init__.py | 1 + autofit/export/__init__.py | 21 ++ autofit/export/__main__.py | 117 +++++++ autofit/export/package.py | 465 ++++++++++++++++++++++++++++ autofit/export/parity.py | 463 +++++++++++++++++++++++++++ autofit/export/readme.py | 100 ++++++ autofit/export/verify.py | 183 +++++++++++ test_autofit/export/__init__.py | 0 test_autofit/export/test_package.py | 331 ++++++++++++++++++++ test_autofit/export/test_parity.py | 164 ++++++++++ 10 files changed, 1845 insertions(+) create mode 100644 autofit/export/__init__.py create mode 100644 autofit/export/__main__.py create mode 100644 autofit/export/package.py create mode 100644 autofit/export/parity.py create mode 100644 autofit/export/readme.py create mode 100644 autofit/export/verify.py create mode 100644 test_autofit/export/__init__.py create mode 100644 test_autofit/export/test_package.py create mode 100644 test_autofit/export/test_parity.py diff --git a/autofit/__init__.py b/autofit/__init__.py index 2e4287267..e439692bf 100644 --- a/autofit/__init__.py +++ b/autofit/__init__.py @@ -41,6 +41,7 @@ from autofit.aggregator.fit_interface import Fit from .aggregator.search_output import SearchOutput from .results.library import ResultsLibrary +from . import export from .mapper import prior from .mapper.model import AbstractModel from .mapper.model import ModelInstance diff --git a/autofit/export/__init__.py b/autofit/export/__init__.py new file mode 100644 index 000000000..e0bd68f67 --- /dev/null +++ b/autofit/export/__init__.py @@ -0,0 +1,21 @@ +""" +Ship and check a finished results library (results-library epic, phase 4). + +- ``package``: size-capped part zips with a manifest, checksums, row counts and a + provenance README; rebuilds rewrite only the parts whose files changed; +- ``verify``: check a package is whole (checksums, CRCs, empty files, table rows, + manifest coverage); +- ``compare``: diff two results tables — identity, exact columns and tolerance by σ; +- ``scatter_between``: the run-to-run scatter of two sets of fits, which is what a + parity tolerance must be calibrated against; +- ``python -m autofit.export {package,verify,compare}``: the command line. +""" +from autofit.export.package import PackageException, PackageReport, index_hash, package +from autofit.export.parity import ( + ColumnParity, + ParityReport, + ScatterReport, + compare, + scatter_between, +) +from autofit.export.verify import VerifyReport, verify diff --git a/autofit/export/__main__.py b/autofit/export/__main__.py new file mode 100644 index 000000000..44c1e8535 --- /dev/null +++ b/autofit/export/__main__.py @@ -0,0 +1,117 @@ +""" +``python -m autofit.export``: package, verify and compare from the shell. + + python -m autofit.export package LIBRARY DIST [--cap-gb 10 | --n-parts 5] [--title T] + [--repo PATH ...] [--replan] + python -m autofit.export verify DIST + python -m autofit.export compare A.csv B.csv [--key id] [--exact col,...] + [--gate col,...] [--threshold 3] [--floor 0] [--rel-floor 0] [--report parity.md] + +``verify`` and ``compare`` exit 0 when the package is whole / the tables agree, 1 +when they do not, and 2 on an error. +""" +import argparse +import sys + + +def _list(value): + return [item.strip() for item in (value or "").split(",") if item.strip()] + + +def command_package(arguments) -> int: + from autofit.export.package import package + + try: + report = package( + arguments.library, + arguments.dist, + cap_gb=arguments.cap_gb, + n_parts=arguments.n_parts, + title=arguments.title, + repos=arguments.repo or (), + replan=arguments.replan, + ) + except Exception as exception: + print(f"package failed: {type(exception).__name__}: {exception}", file=sys.stderr) + return 2 + print(report) + return 0 + + +def command_verify(arguments) -> int: + from autofit.export.verify import verify + + try: + report = verify(arguments.dist) + except Exception as exception: + print(f"verify failed: {type(exception).__name__}: {exception}", file=sys.stderr) + return 2 + print(report) + return 0 if report.ok else 1 + + +def command_compare(arguments) -> int: + from autofit.export.parity import compare + + try: + report = compare( + arguments.a, + arguments.b, + key=_list(arguments.key), + exact=_list(arguments.exact), + gate=_list(arguments.gate), + threshold=arguments.threshold, + floor=arguments.floor, + rel_floor=arguments.rel_floor, + ) + markdown = report.to_markdown() + if arguments.report: + with open(arguments.report, "w") as f: + f.write(markdown) + except Exception as exception: + print(f"compare failed: {type(exception).__name__}: {exception}", file=sys.stderr) + return 2 + print(markdown) + return 0 if report.passed else 1 + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser( + prog="python -m autofit.export", + description="Package, verify and compare PyAutoFit results libraries.", + ) + commands = parser.add_subparsers(dest="command", required=True) + + package = commands.add_parser("package", help="Package a library folder.") + package.add_argument("library") + package.add_argument("dist") + size = package.add_mutually_exclusive_group() + size.add_argument("--cap-gb", type=float, default=None) + size.add_argument("--n-parts", type=int, default=None) + package.add_argument("--title", default=None) + package.add_argument("--repo", action="append", help="A git checkout to record.") + package.add_argument("--replan", action="store_true") + package.set_defaults(function=command_package) + + verify = commands.add_parser("verify", help="Check a package is whole.") + verify.add_argument("dist") + verify.set_defaults(function=command_verify) + + compare = commands.add_parser("compare", help="Diff two results tables.") + compare.add_argument("a", help="The table under test.") + compare.add_argument("b", help="The reference table.") + compare.add_argument("--key", default="id", help="Comma-separated key columns.") + compare.add_argument("--exact", default="", help="Columns that must be equal.") + compare.add_argument("--gate", default="", help="Value columns that gate.") + compare.add_argument("--threshold", type=float, default=3.0) + compare.add_argument("--floor", type=float, default=0.0) + compare.add_argument("--rel-floor", type=float, default=0.0) + compare.add_argument("--report", default=None, help="Write the markdown here.") + compare.set_defaults(function=command_compare) + + arguments = parser.parse_args(argv) + return arguments.function(arguments) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/autofit/export/package.py b/autofit/export/package.py new file mode 100644 index 000000000..e34875be5 --- /dev/null +++ b/autofit/export/package.py @@ -0,0 +1,465 @@ +""" +``package``: ship a finished results library as a set of zips anyone can download, +check and unpack. + +The source is a *library folder*: one sub-folder per object (a lens, a galaxy, a +dataset), kept whole, plus tables (CSVs, a README) at its root:: + + library/ + summary.csv + summary.columns.json + obj0001/ ... + obj0002/ ... + +``package(source, dist)`` writes to ``dist``: + +- ``tables.zip``: the root files; +- ``part_001.zip``, ``part_002.zip`` ...: the object folders, each wholly inside one + part, the parts no larger than ``cap_gb`` (or exactly ``n_parts`` near-equal parts); +- ``parts_manifest.csv``: which part holds each object; +- ``package.json``: everything ``verify`` checks and a rebuild reuses — each object's + part, each zip's members (size, modification time), its SHA256, the row count of + every CSV, and the provenance; +- ``SHA256SUMS``: the checksum of every zip, the manifest and ``package.json``; +- ``README.md`` (regenerated) and ``KNOWN_ISSUES.md`` (written once, then yours). + +Members are archived ``ZIP_STORED`` when already compressed or large binaries (PNG, +FITS, HDF5) and ``ZIP_DEFLATED`` otherwise, in sorted order with each file's own +modification time, so the same files always give the same zip. Every zip is written +to a temporary file and moved into place: a killed run leaves the previous zip whole. + +**Rebuilds are deltas.** Packaging again into the same ``dist`` keeps every object in +the part it was in; new objects go into the last part while it has room, then into +new parts; a part whose files (names, sizes, modification times) are unchanged is not +rewritten, so it stays byte-identical and its checksum stays valid for anyone who +already downloaded it. ``replan=True`` plans from scratch. + +``include_dataset(object_name)`` may return extra files to ship with an object (its +input data, a segmentation map), archived under ``/dataset/``. +""" +import csv +import hashlib +import io +import json +import logging +import os +import shutil +import zipfile +from dataclasses import dataclass, field +from datetime import datetime, timezone +from pathlib import Path +from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union + +from autofit.tools.util import compress_type_for, open_atomic + +logger = logging.getLogger(__name__) + +SCHEMA = 1 +TABLES = "tables.zip" +MANIFEST = "parts_manifest.csv" +PACKAGE_JSON = "package.json" +SUMS = "SHA256SUMS" + +PathLike = Union[str, os.PathLike] + +# (arcname, source path) +Member = Tuple[str, Path] + + +class PackageException(Exception): + pass + + +@dataclass +class PackageReport: + dist: Path + parts: Dict[str, List[str]] + """Each part zip's objects.""" + written: List[str] = field(default_factory=list) + """The zips written by this run.""" + kept: List[str] = field(default_factory=list) + """The zips left untouched because their files did not change.""" + + def __str__(self): + return ( + f"package {self.dist}: {sum(len(v) for v in self.parts.values())} objects in " + f"{len(self.parts)} parts; wrote {len(self.written)} zips, kept " + f"{len(self.kept)} unchanged" + ) + + +def part_name(index: int) -> str: + return f"part_{index:03d}.zip" + + +def sha256(path: PathLike) -> str: + digest = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +_SKIP_DIRS = {".git", "__pycache__", ".ipynb_checkpoints"} + + +def _files(directory: Path) -> List[Path]: + # Dot-files inside an object ship (a result's .completed and .identifier are part + # of it); only version-control and cache folders are left out. + return sorted( + path + for path in directory.rglob("*") + if path.is_file() + and not any(part in _SKIP_DIRS for part in path.relative_to(directory).parts) + ) + + +def _stat_entries(members: Sequence[Member]) -> List[List]: + entries = [] + for arcname, path in members: + stat = path.stat() + entries.append([arcname, stat.st_size, stat.st_mtime_ns]) + return entries + + +def _date_time(path: Path) -> Tuple[int, ...]: + # UTC, so the same files give the same zip on any machine. + stamp = datetime.fromtimestamp(path.stat().st_mtime, timezone.utc) + if stamp.year < 1980: + return (1980, 1, 1, 0, 0, 0) + return stamp.timetuple()[:6] + + +csv.field_size_limit(2**31 - 1) + + +def csv_records(handle) -> List[List[str]]: + """ + The non-blank records of a CSV (bytes ``handle``); undecodable bytes are replaced + rather than fatal, so one odd table never stops a package or a verify. + """ + reader = csv.reader( + io.TextIOWrapper(handle, encoding="utf-8", errors="replace", newline="") + ) + return [row for row in reader if row] + + +def _count_csv_rows(handle) -> Optional[int]: + try: + return max(len(csv_records(handle)) - 1, 0) + except csv.Error as exception: + logger.warning(f"package: a CSV cannot be counted: {exception}") + return None + + +def write_zip(zip_path: Path, members: Sequence[Member]) -> Dict[str, int]: + """ + Write ``members`` to ``zip_path`` atomically and deterministically (sorted, each + member with its file's modification time). Returns the row count of every CSV + member. + """ + tmp = zip_path.with_name(f"{zip_path.name}.{os.getpid()}.tmp") + csv_rows = {} + try: + with zipfile.ZipFile(tmp, "w") as archive: + for arcname, path in sorted(members): + info = zipfile.ZipInfo(arcname, date_time=_date_time(path)) + info.compress_type = compress_type_for(path) + info.external_attr = 0o644 << 16 + with open(path, "rb") as source, archive.open(info, "w", force_zip64=True) as target: + shutil.copyfileobj(source, target, 1024 * 1024) + if arcname.endswith(".csv"): + with open(path, "rb") as handle: + csv_rows[arcname] = _count_csv_rows(handle) + os.replace(tmp, zip_path) + except BaseException: + tmp.unlink(missing_ok=True) + raise + return csv_rows + + +def _plan( + items: Sequence[str], + sizes: Dict[str, int], + cap_bytes: Optional[int], + n_parts: Optional[int], + previous: Dict[str, str], +) -> Dict[str, str]: + """ + Object → part name: previous assignments kept; new objects appended to the last + part while it fits ``cap_bytes``, then to new parts. Without a previous plan, + ``n_parts`` splits the objects into that many contiguous near-equal parts. + """ + if not previous and n_parts: + n = min(n_parts, len(items)) + total = sum(sizes[item] for item in items) or 1 + assignment = {} + index, filled, in_part = 1, 0, 0 + for position, item in enumerate(items): + parts_left = n - index + items_left = len(items) - position + if in_part and parts_left and ( + filled >= total * index / n or items_left <= parts_left + ): + index += 1 + in_part = 0 + assignment[item] = part_name(index) + filled += sizes[item] + in_part += 1 + return assignment + + assignment = {item: previous[item] for item in items if item in previous} + part_sizes = {} + for item, part in assignment.items(): + part_sizes[part] = part_sizes.get(part, 0) + sizes[item] + index = max((int(part[5:8]) for part in part_sizes), default=0) + if index == 0: + index = 1 + part_sizes[part_name(1)] = 0 + for item in items: + if item in assignment: + continue + name = part_name(index) + if ( + cap_bytes is not None + and part_sizes.get(name, 0) > 0 + and part_sizes.get(name, 0) + sizes[item] > cap_bytes + ): + index += 1 + name = part_name(index) + assignment[item] = name + part_sizes[name] = part_sizes.get(name, 0) + sizes[item] + return assignment + + +def _git_revision(repo: Path) -> Dict[str, Optional[str]]: + import subprocess + + def run(*args): + try: + return subprocess.run( + ["git", "-C", str(repo), *args], capture_output=True, text=True, check=True + ).stdout.strip() + except (OSError, subprocess.CalledProcessError): + return None + + return { + "repo": str(repo), + "revision": run("rev-parse", "HEAD"), + "dirty": bool(run("status", "--porcelain")), + } + + +def index_hash(index) -> str: + """ + A digest of a results index (``autofit.results.ResultsIndex``): its records' + paths, states and completion times, so a package names exactly which results it + was built from. + """ + digest = hashlib.sha256() + for record in index.records(): + digest.update( + f"{record.output_path}|{record.state}|{record.completed_at}\n".encode() + ) + return digest.hexdigest() + + +def package( + source: PathLike, + dist: PathLike, + cap_gb: Optional[float] = None, + n_parts: Optional[int] = None, + include_dataset: Optional[Callable[[str], Iterable[PathLike]]] = None, + title: Optional[str] = None, + repos: Sequence[PathLike] = (), + index=None, + notes: str = "", + replan: bool = False, + force: bool = False, +) -> PackageReport: + """ + Package the library folder ``source`` into ``dist`` (see the module docstring). + + Parameters + ---------- + cap_gb + The largest a part may grow when objects are added to it (an object larger + than the cap gets a part of its own). + n_parts + Split into exactly this many near-equal parts (first build or ``replan``). + include_dataset + ``include_dataset(object_name)`` returns extra files shipped with that object + under ``/dataset/``. + title + The README heading (default: the previous build's, else the source folder's + name). + repos + Git checkouts whose revisions the README and ``package.json`` record. + index + The ``ResultsIndex`` the library was built from; its hash is recorded. + notes + Free text for the README (default: the previous build's). + replan + Ignore the previous package's part assignments. + force + Rewrite every zip, even those whose files look unchanged (a file rewritten + with its size and modification time preserved is otherwise not noticed). + """ + source = Path(source) + dist = Path(dist) + if not source.is_dir(): + raise PackageException(f"{source} is not a folder.") + if cap_gb is not None and n_parts is not None: + raise PackageException("Pass cap_gb or n_parts, not both.") + dist.mkdir(parents=True, exist_ok=True) + root = source.name + + previous = {} + previous_document = {} + if not replan and (dist / PACKAGE_JSON).exists(): + previous_document = json.loads((dist / PACKAGE_JSON).read_text()) + if previous_document.get("schema") == SCHEMA and previous_document.get("root") == root: + previous = dict(previous_document.get("objects") or {}) + else: + previous_document = {} + if previous: + if cap_gb is None and n_parts is None: + cap_gb = previous_document.get("cap_gb") + n_previous = len(set(previous.values())) + if n_parts is not None and n_parts != n_previous: + raise PackageException( + f"{dist} already holds {n_previous} parts; a rebuild keeps them. Pass " + f"replan=True (--replan) to split into {n_parts} parts instead." + ) + + items = sorted( + path.name + for path in source.iterdir() + if path.is_dir() and not path.name.startswith(".") + ) + members_of = {} + for item in items: + members = [ + (f"{root}/{path.relative_to(source).as_posix()}", path) + for path in _files(source / item) + ] + if include_dataset is not None: + for extra in include_dataset(item) or (): + extra = Path(extra) + members.append((f"{root}/{item}/dataset/{extra.name}", extra)) + if not members: + logger.warning(f"package: {item} holds no files; it is left out.") + continue + names = [arcname for arcname, _ in members] + duplicates = sorted({name for name in names if names.count(name) > 1}) + if duplicates: + raise PackageException( + f"{item}: several files would be archived as {duplicates[:3]} " + f"(an include_dataset file colliding with another file?)." + ) + members_of[item] = members + items = [item for item in items if item in members_of] + sizes = { + item: sum(path.stat().st_size for _, path in members_of[item]) for item in items + } + + cap_bytes = int(cap_gb * 1024**3) if cap_gb is not None else None + assignment = _plan(items, sizes, cap_bytes, n_parts, previous) + parts: Dict[str, List[str]] = {} + for item in items: + parts.setdefault(assignment[item], []).append(item) + + zips = { + name: [member for item in parts[name] for member in members_of[item]] + for name in sorted(parts) + } + tables = [ + (f"{root}/{path.name}", path) + for path in sorted(source.iterdir()) + if path.is_file() and not path.name.startswith(".") + ] + zips[TABLES] = tables + + report = PackageReport(dist=dist, parts={name: parts[name] for name in sorted(parts)}) + old_zips = previous_document.get("zips") or {} + zip_documents = {} + for name, members in zips.items(): + entries = _stat_entries(members) + old = old_zips.get(name) + zip_path = dist / name + if ( + not force + and old is not None + and old.get("members") == entries + and zip_path.exists() + and zip_path.stat().st_size == old.get("bytes") + ): + zip_documents[name] = old + report.kept.append(name) + continue + csv_rows = write_zip(zip_path, members) + zip_documents[name] = { + "members": entries, + "csv_rows": csv_rows, + "bytes": zip_path.stat().st_size, + "sha256": sha256(zip_path), + } + report.written.append(name) + logger.info(f"package: wrote {name} ({len(members)} files)") + + # Every part zip not in this build goes — including one left by a replan, a renamed + # source or an interrupted run, which no package.json names. + for stale in sorted(set(old_zips) | {p.name for p in dist.glob("part_*.zip")}): + if stale not in zips: + (dist / stale).unlink(missing_ok=True) + logger.info(f"package: removed stale {stale}") + + provenance = { + "created": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "source": str(source.resolve()), + "repos": [_git_revision(Path(repo)) for repo in repos], + "index_hash": index_hash(index) if index is not None else None, + "autofit_version": _autofit_version(), + } + title = title or previous_document.get("title") or root + notes = notes or previous_document.get("notes") or "" + document = { + "schema": SCHEMA, + "root": root, + "title": title, + "notes": notes, + "cap_gb": cap_gb, + "objects": {item: assignment[item] for item in items}, + "zips": zip_documents, + "provenance": provenance, + } + + with open_atomic(dist / MANIFEST, "w") as f: + writer = csv.writer(f, lineterminator="\n") + writer.writerow(["object", "part_zip", "n_files", "bytes"]) + for item in items: + writer.writerow([item, assignment[item], len(members_of[item]), sizes[item]]) + with open_atomic(dist / PACKAGE_JSON, "w") as f: + json.dump(document, f, indent=1) + + from autofit.export.readme import write_readme + + write_readme(dist, document, title=title, notes=notes) + + with open_atomic(dist / SUMS, "w") as f: + for name in sorted(zip_documents): + f.write(f"{zip_documents[name]['sha256']} {name}\n") + for name in (MANIFEST, PACKAGE_JSON): + f.write(f"{sha256(dist / name)} {name}\n") + + logger.info(str(report)) + return report + + +def _autofit_version() -> Optional[str]: + try: + import autofit + + return getattr(autofit, "__version__", None) + except Exception: + return None diff --git a/autofit/export/parity.py b/autofit/export/parity.py new file mode 100644 index 000000000..b47f4f345 --- /dev/null +++ b/autofit/export/parity.py @@ -0,0 +1,463 @@ +""" +Parity: is one results table the same as another — a rebuild against its reference, +a rerun against the first run? + +``compare(a, b, key=...)`` diffs two tables (CSV paths, or lists of row dicts) row by +row under three kinds of rule: + +- **identity** — keys present on one side only, keys repeated on either side, and + columns present on one side only. Always gated: a table that gained, lost or + duplicated objects or columns is not the same table. A column named in ``exact`` + or ``gate`` that is not in both tables fails too, never silently passes; +- **exact** — the columns named in ``exact`` (positions read from a header, an + object's name) must be equal — as integers, as numbers, else as text — and a value + blank on one side only is a difference; gated; +- **tolerance by σ** — a value column ``x`` with ``x_lower_1_sigma`` / + ``x_upper_1_sigma`` on both sides is compared as:: + + sigma = max((upper - lower) / 2, floor, rel_floor * |x|) + z = |a - b| / sqrt(sigma_a ** 2 + sigma_b ** 2) + + and reported as the median and maximum ``z`` over the common rows. The floors keep a + vanishing error bar from turning a negligible difference into an enormous ``z``. + +Value columns are **informational unless named in** ``gate``: two runs of the same +fit are not bitwise reproducible, and two Nautilus runs of the same model on the same +data have been measured differing by a median ``z`` of 15 (results-library report +P19). So "within 3σ" is not a parity test until the run-to-run scatter has been +measured — ``scatter_between`` measures it — and a parity check of reruns reports +their scatter instead of failing on it. +""" +import csv +import math +import os +import re +import statistics +from collections import Counter +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union + +SIGMA_SUFFIXES = ("_lower_1_sigma", "_upper_1_sigma") +DERIVED_SUFFIXES = ( + "_lower_1_sigma", + "_upper_1_sigma", + "_lower_3_sigma", + "_upper_3_sigma", + "_max_lh", + "_at_prior_edge", +) + +Table = Union[str, os.PathLike, Sequence[Dict]] + + +def _rows(table: Table) -> List[Dict]: + if isinstance(table, (str, os.PathLike)): + with open(table, newline="") as f: + return list(csv.DictReader(f)) + return [dict(row) for row in table] + + +def _float(value) -> Optional[float]: + if value is None or value == "": + return None + try: + number = float(value) + except (TypeError, ValueError): + return None + return number if math.isfinite(number) else None + + +@dataclass +class ColumnParity: + name: str + kind: str + """``exact``, ``sigma`` (tolerance by σ), ``numeric`` or ``text``.""" + gated: bool + n: int = 0 + """Rows compared (both sides non-blank).""" + n_blank: int = 0 + n_mismatch: int = 0 + """Rows that differ (exact / text) or exceed the threshold (sigma).""" + median_z: Optional[float] = None + max_z: Optional[float] = None + max_abs_diff: Optional[float] = None + worst: List[Tuple] = field(default_factory=list) + """Up to five ``(key, a, b, z or None)`` of the largest differences.""" + + @property + def passed(self) -> bool: + return not self.gated or self.n_mismatch == 0 + + +@dataclass +class ParityReport: + key: Tuple[str, ...] + threshold: float + n_a: int + n_b: int + n_common: int + only_a: List = field(default_factory=list) + only_b: List = field(default_factory=list) + duplicates_a: List = field(default_factory=list) + duplicates_b: List = field(default_factory=list) + columns_only_a: List[str] = field(default_factory=list) + columns_only_b: List[str] = field(default_factory=list) + unknown: List[str] = field(default_factory=list) + """Columns named in ``exact`` or ``gate`` that are not in both tables.""" + columns: Dict[str, ColumnParity] = field(default_factory=dict) + + @property + def passed(self) -> bool: + return ( + not self.only_a + and not self.only_b + and not self.duplicates_a + and not self.duplicates_b + and not self.columns_only_a + and not self.columns_only_b + and not self.unknown + and all(column.passed for column in self.columns.values()) + ) + + def to_markdown(self, title: str = "Parity") -> str: + lines = [ + f"# {title}: {'PASS' if self.passed else 'FAIL'}", + "", + f"Key `{', '.join(self.key)}`: {self.n_a} rows in A, {self.n_b} in B, " + f"{self.n_common} in both. Tolerance: z ≤ {self.threshold:g} on gated " + f"σ columns.", + "", + "## Identity (gated)", + "", + f"- only in A: {len(self.only_a)} {self.only_a[:5]}", + f"- only in B: {len(self.only_b)} {self.only_b[:5]}", + f"- duplicate keys in A: {len(self.duplicates_a)} {self.duplicates_a[:5]}", + f"- duplicate keys in B: {len(self.duplicates_b)} {self.duplicates_b[:5]}", + f"- columns only in A: {self.columns_only_a}", + f"- columns only in B: {self.columns_only_b}", + f"- exact / gate columns not in both tables: {self.unknown}", + "", + "## Columns", + "", + "| column | kind | gated | n | blank | median z | max z | over / differing | result |", + "|---|---|---|---|---|---|---|---|---|", + ] + + def fmt(value): + return "" if value is None else f"{value:.3g}" + + for column in self.columns.values(): + lines.append( + f"| `{column.name}` | {column.kind} | {'yes' if column.gated else 'no'} | " + f"{column.n} | {column.n_blank} | {fmt(column.median_z)} | " + f"{fmt(column.max_z)} | {column.n_mismatch} | " + f"{'pass' if column.passed else 'FAIL'} |" + ) + failing = [c for c in self.columns.values() if c.worst and (c.gated or c.kind == "sigma")] + if failing: + lines += ["", "## Largest differences", ""] + for column in failing: + lines.append(f"- `{column.name}`: {column.worst}") + return "\n".join(lines) + "\n" + + +def compare( + a: Table, + b: Table, + key: Union[str, Sequence[str]] = "id", + exact: Sequence[str] = (), + gate: Sequence[str] = (), + threshold: float = 3.0, + floor: float = 0.0, + rel_floor: float = 0.0, + columns: Optional[Sequence[str]] = None, +) -> ParityReport: + """ + Compare table ``a`` (under test) with table ``b`` (the reference); see the module + docstring. + + Parameters + ---------- + key + The column (or columns) naming a row. + exact + Columns that must be equal (as numbers when both parse, else as text); gated. + gate + Value columns whose ``z`` (or, without σ columns, any difference) fails the + comparison; every other value column is informational. + threshold + The largest ``z`` a gated σ column may reach. + floor, rel_floor + The smallest σ used: ``max(sigma, floor, rel_floor * |value|)``. + columns + Compare only these value columns (default: every column on both sides). + """ + keys = (key,) if isinstance(key, str) else tuple(key) + rows_a, rows_b = _rows(a), _rows(b) + + def index(rows): + counts = Counter(tuple(row.get(k, "") for k in keys) for row in rows) + by_key = {} + for row in rows: + by_key.setdefault(tuple(row.get(k, "") for k in keys), row) + return by_key, sorted(k for k, n in counts.items() if n > 1) + + by_a, duplicates_a = index(rows_a) + by_b, duplicates_b = index(rows_b) + common = sorted(set(by_a) & set(by_b)) + + def label(k): + return k[0] if len(k) == 1 else k + + report = ParityReport( + key=keys, + threshold=threshold, + n_a=len(rows_a), + n_b=len(rows_b), + n_common=len(common), + only_a=[label(k) for k in sorted(set(by_a) - set(by_b))], + only_b=[label(k) for k in sorted(set(by_b) - set(by_a))], + duplicates_a=[label(k) for k in duplicates_a], + duplicates_b=[label(k) for k in duplicates_b], + ) + + fields_a = _fieldnames(a, rows_a) + fields_b = _fieldnames(b, rows_b) + report.columns_only_a = [f for f in fields_a if f not in fields_b] + report.columns_only_b = [f for f in fields_b if f not in fields_a] + shared = [f for f in fields_a if f in fields_b and f not in keys] + report.unknown = sorted( + {name for name in list(exact) + list(gate) if name not in shared} + ) + values = [f for f in shared if f in exact or not f.endswith(DERIVED_SUFFIXES)] + if columns is not None: + values = [f for f in values if f in columns or f in exact or f in gate] + + for name in values: + has_sigma = all(f"{name}{suffix}" in shared for suffix in SIGMA_SUFFIXES) + if name in exact: + kind = "exact" + elif has_sigma: + kind = "sigma" + else: + numeric = all( + _float(by_a[k].get(name)) is not None or by_a[k].get(name) in ("", None) + for k in common + ) + kind = "numeric" if numeric else "text" + column = ColumnParity(name=name, kind=kind, gated=name in exact or name in gate) + zs = [] + diffs = [] + for k in common: + va, vb = by_a[k].get(name, ""), by_b[k].get(name, "") + blank_a, blank_b = va in ("", None), vb in ("", None) + if blank_a or blank_b: + column.n_blank += 1 + if blank_a != blank_b and column.gated: + # A value lost (or gained) is a difference, not a blank. + column.n_mismatch += 1 + column.worst.append((label(k), va, vb, None)) + continue + column.n += 1 + fa, fb = _float(va), _float(vb) + if kind == "sigma" and fa is not None and fb is not None: + sa = _sigma(by_a[k], name, fa, floor, rel_floor) + sb = _sigma(by_b[k], name, fb, floor, rel_floor) + scale = math.sqrt(sa**2 + sb**2) + z = abs(fa - fb) / scale if scale > 0 else (0.0 if fa == fb else math.inf) + zs.append((z, label(k), fa, fb)) + if z > threshold: + column.n_mismatch += 1 + elif kind == "exact": + if not _exact_equal(va, vb, fa, fb): + diffs.append((abs(fa - fb) if fa is not None and fb is not None else None, label(k), va, vb)) + column.n_mismatch += 1 + elif fa is not None and fb is not None: + diffs.append((abs(fa - fb), label(k), fa, fb)) + if fa != fb: + column.n_mismatch += 1 + elif va != vb: + diffs.append((None, label(k), va, vb)) + column.n_mismatch += 1 + if zs: + values_z = [z for z, *_ in zs] + column.median_z = statistics.median(values_z) + column.max_z = max(values_z) + column.worst = [ + (k, fa, fb, round(z, 3)) + for z, k, fa, fb in sorted(zs, key=lambda item: -item[0])[:5] + if z > 0 + ] + if diffs: + numeric = [d for d in diffs if d[0] is not None] + if numeric: + column.max_abs_diff = max(d[0] for d in numeric) + column.worst += [ + (k, va, vb, None) + for d, k, va, vb in sorted(diffs, key=lambda d: -(d[0] or 0))[:5] + if d is None or d > 0 + ] + column.worst = column.worst[:5] + report.columns[name] = column + return report + + +_INTEGER = re.compile(r"^[+-]?\d+$") + + +def _exact_equal(va: str, vb: str, fa, fb) -> bool: + """ + Equal as integers when both are integers (a 19-digit object id is not a float), as + numbers when both parse ("1.0" == "1"), else as text. + """ + va, vb = str(va).strip(), str(vb).strip() + if va == vb: + return True + if _INTEGER.match(va) and _INTEGER.match(vb): + return int(va) == int(vb) + if fa is not None and fb is not None: + return fa == fb + return False + + +def _fieldnames(table, rows) -> List[str]: + if isinstance(table, (str, os.PathLike)): + with open(table, newline="") as f: + return list(csv.DictReader(f).fieldnames or []) + names = {} + for row in rows: + names.update(dict.fromkeys(row)) + return list(names) + + +def _sigma(row, name, value, floor, rel_floor) -> float: + lower = _float(row.get(f"{name}_lower_1_sigma")) + upper = _float(row.get(f"{name}_upper_1_sigma")) + sigma = (upper - lower) / 2 if lower is not None and upper is not None else 0.0 + return max(sigma, floor, rel_floor * abs(value)) + + +@dataclass +class Scatter: + path: str + n: int + median_z: Optional[float] + p84_z: Optional[float] + max_z: Optional[float] + zs: List[float] = field(default_factory=list) + + +@dataclass +class ScatterReport: + matched: int + only_a: List + only_b: List + paths: Dict[str, Scatter] + + def __str__(self): + lines = [ + f"scatter between runs: {self.matched} matched fits " + f"({len(self.only_a)} only in A, {len(self.only_b)} only in B)" + ] + for scatter in self.paths.values(): + if scatter.n: + lines.append( + f" {scatter.path}: n={scatter.n} median z={scatter.median_z:.3g} " + f"p84 z={scatter.p84_z:.3g} max z={scatter.max_z:.3g}" + ) + else: + lines.append(f" {scatter.path}: no matched values") + return "\n".join(lines) + + +def _default_key(search_output): + return tuple( + str(getattr(search_output, attribute, None)) + for attribute in ("path_prefix", "unique_tag", "name") + ) + + +def scatter_between( + a, + b, + paths: Iterable[str], + key: Callable = _default_key, +) -> ScatterReport: + """ + The run-to-run scatter of two sets of fits of the same objects: for each parameter + (or latent) ``path``, the distribution of ``z = |a - b| / sqrt(sa**2 + sb**2)`` over + the fits matched between ``a`` and ``b``, with ``sa`` / ``sb`` each run's 1σ + half-width. + + It is the calibration a parity test needs: a median ``z`` well above 1 between two + runs of the same code on the same data says the quoted errors understate the + run-to-run variation, and no tolerance tighter than that scatter can pass a rerun. + + Parameters + ---------- + a, b + Aggregators (or lists of search outputs) of the two runs. + paths + Model paths, e.g. ``"galaxies.lens.mass.einstein_radius"`` or a latent + ``"latent.value"``. + key + Matches a fit in ``a`` to its rerun in ``b`` (default: ``path_prefix``, + ``unique_tag``, ``name``). It must name one fit per object on each side; + a repeated key raises ``ValueError`` rather than silently dropping fits. + """ + from autofit.aggregator.summary.aggregate_csv.row import Row + + def by_key(outputs, side): + found = {} + repeated = set() + for output in outputs: + k = key(output) + if k in found: + repeated.add(k) + found[k] = output + if repeated: + raise ValueError( + f"The key names several fits in {side}: {sorted(repeated)[:3]}. Pass a " + f"key that identifies one fit of one object, e.g. " + f"key=lambda output: output.unique_tag." + ) + return found + + outputs_a = by_key(getattr(a, "search_outputs", a), "a") + outputs_b = by_key(getattr(b, "search_outputs", b), "b") + common = sorted(set(outputs_a) & set(outputs_b)) + + rows = {k: (Row(outputs_a[k], [], 0), Row(outputs_b[k], [], 0)) for k in common} + scatters = {} + for path in paths: + parts = tuple(path.split(".")) + zs = [] + for row_a, row_b in rows.values(): + try: + va = row_a.median_pdf_sample_kwargs.get(parts) + vb = row_b.median_pdf_sample_kwargs.get(parts) + la, ua = row_a.values_at_sigma_1_kwargs.get(parts, (None, None)) + lb, ub = row_b.values_at_sigma_1_kwargs.get(parts, (None, None)) + except Exception: + continue + if None in (va, vb, la, ua, lb, ub): + continue + scale = math.sqrt(((ua - la) / 2) ** 2 + ((ub - lb) / 2) ** 2) + if scale > 0: + zs.append(abs(va - vb) / scale) + zs.sort() + scatters[path] = Scatter( + path=path, + n=len(zs), + median_z=statistics.median(zs) if zs else None, + p84_z=zs[min(len(zs) - 1, int(math.ceil(0.84 * len(zs))) - 1)] if zs else None, + max_z=zs[-1] if zs else None, + zs=zs, + ) + return ScatterReport( + matched=len(common), + only_a=sorted(set(outputs_a) - set(outputs_b)), + only_b=sorted(set(outputs_b) - set(outputs_a)), + paths=scatters, + ) diff --git a/autofit/export/readme.py b/autofit/export/readme.py new file mode 100644 index 000000000..bbbd6952c --- /dev/null +++ b/autofit/export/readme.py @@ -0,0 +1,100 @@ +""" +The ``README.md`` and ``KNOWN_ISSUES.md`` of a package (``package``). + +``README.md`` is regenerated on every build from ``package.json``: what is in the +package, how to check and unpack it, and its provenance (when, from which code, from +which results). ``KNOWN_ISSUES.md`` is written once as a template and then left to its +maintainer — it is where a release states what it knowingly gets wrong. +""" +from pathlib import Path + +from autofit.tools.util import open_atomic + +KNOWN_ISSUES_TEMPLATE = """# Known issues — {title} + +List what this release knowingly gets wrong or leaves out, one line each, with the +objects affected and whether a later release fixes it. A reader should never have to +discover one of these from the data. + +- (none recorded yet) +""" + + +def _size(n: float) -> str: + for unit in ("B", "KB", "MB", "GB", "TB"): + if n < 1024 or unit == "TB": + return f"{n:.1f} {unit}" if unit != "B" else f"{int(n)} B" + n /= 1024 + + +def write_readme(dist: Path, document: dict, title: str, notes: str = ""): + zips = document["zips"] + objects = document["objects"] + provenance = document["provenance"] + parts = sorted(name for name in zips if name.startswith("part_")) + total = sum(entry["bytes"] for entry in zips.values()) + csv_rows = { + name: rows + for entry in zips.values() + for name, rows in (entry.get("csv_rows") or {}).items() + } + + lines = [ + f"# {title}", + "", + f"{len(objects)} objects in {len(parts)} part zips, plus `tables.zip` " + f"({_size(total)} in all).", + "", + ] + if notes: + lines += [notes.strip(), ""] + lines += [ + "## Contents", + "", + "| file | holds | size |", + "|---|---|---|", + f"| `tables.zip` | the tables ({len(zips['tables.zip']['members'])} files) | " + f"{_size(zips['tables.zip']['bytes'])} |", + ] + for name in parts: + n = sum(1 for part in objects.values() if part == name) + lines.append(f"| `{name}` | {n} objects | {_size(zips[name]['bytes'])} |") + lines += [ + "| `parts_manifest.csv` | which part holds each object | |", + "| `package.json` | members, checksums and row counts, for `verify` | |", + "| `SHA256SUMS` | the checksum of every file above | |", + "", + ] + if csv_rows: + lines += ["## Tables", "", "| table | rows |", "|---|---|"] + lines += [f"| `{name}` | {rows} |" for name, rows in sorted(csv_rows.items())] + lines.append("") + lines += [ + "## Check and unpack", + "", + "```bash", + "sha256sum -c SHA256SUMS", + "python -m autofit.export verify . # checksums, CRCs, empty files, table rows", + "for z in *.zip; do unzip -q \"$z\"; done", + "```", + "", + "Only the parts holding the objects you need are required: `parts_manifest.csv`", + "names each object's part.", + "", + "## Provenance", + "", + f"- built: {provenance.get('created')}", + f"- autofit: {provenance.get('autofit_version')}", + ] + if provenance.get("index_hash"): + lines.append(f"- results index: `{provenance['index_hash']}`") + for repo in provenance.get("repos") or []: + dirty = " (uncommitted changes)" if repo.get("dirty") else "" + lines.append(f"- `{Path(repo['repo']).name}`: `{repo.get('revision')}`{dirty}") + lines += ["", "See `KNOWN_ISSUES.md` for what this release knowingly gets wrong.", ""] + + with open_atomic(dist / "README.md", "w") as f: + f.write("\n".join(lines)) + known_issues = dist / "KNOWN_ISSUES.md" + if not known_issues.exists(): + known_issues.write_text(KNOWN_ISSUES_TEMPLATE.format(title=title)) diff --git a/autofit/export/verify.py b/autofit/export/verify.py new file mode 100644 index 000000000..ccb7f5cca --- /dev/null +++ b/autofit/export/verify.py @@ -0,0 +1,183 @@ +""" +``verify``: check a package (``package``) is whole before it is published or after it +is downloaded — the questions a reader of the release cannot answer by eye. + +1. every file in ``SHA256SUMS`` exists and matches its checksum, and every zip + ``package.json`` names is in ``SHA256SUMS``; +2. every zip passes its CRC check and holds exactly the members ``package.json`` + records; +3. no member is empty (a zero-byte FITS or CSV is a failed write, not data), except + names matched by ``allow_empty``; +4. every CSV member parses, every row has as many fields as the header, and its row + count is the one recorded when the package was built; +5. every object is in exactly one part as the zips actually hold them — the part + ``package.json`` and ``parts_manifest.csv`` both name. +""" +import csv +import fnmatch +import json +import zipfile +import zlib +from dataclasses import dataclass, field +from pathlib import Path +from typing import List, Sequence + +from autofit.export.package import MANIFEST, PACKAGE_JSON, SUMS, csv_records, sha256 + + +@dataclass +class VerifyReport: + dist: Path + problems: List[str] = field(default_factory=list) + zips: int = 0 + members: int = 0 + csv_rows: int = 0 + + @property + def ok(self) -> bool: + return not self.problems + + def __str__(self): + head = ( + f"verify {self.dist}: {'OK' if self.ok else 'FAILED'} — {self.zips} zips, " + f"{self.members} members, {self.csv_rows} table rows checked" + ) + return "\n".join([head] + [f" {problem}" for problem in self.problems]) + + +def verify(dist, allow_empty: Sequence[str] = (".completed", "*/.completed")) -> VerifyReport: + """ + Check the package in ``dist`` (see the module docstring). + + Parameters + ---------- + allow_empty + ``fnmatch`` patterns of member names allowed to be empty (marker files). + """ + dist = Path(dist) + report = VerifyReport(dist=dist) + problems = report.problems + + try: + document = json.loads((dist / PACKAGE_JSON).read_text()) + except (OSError, ValueError) as exception: + problems.append(f"{PACKAGE_JSON} cannot be read: {exception}") + return report + + sums = {} + try: + for number, line in enumerate((dist / SUMS).read_text().splitlines(), start=1): + if not line.strip(): + continue + fields = line.split(maxsplit=1) + if len(fields) != 2: + problems.append(f"{SUMS} line {number} is not ' ': {line!r}") + continue + sums[fields[1].strip().lstrip("*")] = fields[0] + except OSError as exception: + problems.append(f"{SUMS} cannot be read: {exception}") + for name, digest in sorted(sums.items()): + path = dist / name + if not path.exists(): + problems.append(f"{name}: listed in {SUMS} but missing") + elif sha256(path) != digest: + problems.append(f"{name}: SHA256 does not match {SUMS}") + + zips = document.get("zips") or {} + root = document.get("root") + seen = {} + for name, entry in sorted(zips.items()): + if name not in sums: + problems.append(f"{name}: not listed in {SUMS}") + path = dist / name + if not path.exists(): + problems.append(f"{name}: missing") + continue + report.zips += 1 + try: + with zipfile.ZipFile(path) as archive: + bad = archive.testzip() + if bad is not None: + problems.append(f"{name}: CRC failure on {bad}") + infos = [info for info in archive.infolist() if not info.is_dir()] + names = sorted(info.filename for info in infos) + if name.startswith("part_"): + for member in names: + parts = member.split("/") + if len(parts) >= 3 and parts[0] == root: + seen.setdefault(parts[1], set()).add(name) + expected = sorted(member[0] for member in entry.get("members") or []) + if names != expected: + extra = sorted(set(names) - set(expected))[:3] + missing = sorted(set(expected) - set(names))[:3] + problems.append( + f"{name}: members differ from {PACKAGE_JSON} " + f"(extra {extra}, missing {missing})" + ) + csv_rows = entry.get("csv_rows") or {} + for info in infos: + report.members += 1 + if info.file_size == 0 and not any( + fnmatch.fnmatch(info.filename, pattern) for pattern in allow_empty + ): + problems.append(f"{name}: {info.filename} is empty") + if info.filename.endswith(".csv"): + problems += _check_csv(archive, info, name, csv_rows, report) + except (zipfile.BadZipFile, OSError, zlib.error, EOFError, RuntimeError) as exception: + problems.append(f"{name}: unreadable zip: {type(exception).__name__}: {exception}") + + for path in sorted(dist.glob("*.zip")): + if path.name not in zips: + problems.append( + f"{path.name}: a zip {PACKAGE_JSON} does not list (stale or foreign); " + f"unpacking every *.zip would include it" + ) + + objects = document.get("objects") or {} + for item, part in sorted(objects.items()): + holders = seen.get(item, set()) + if holders != {part}: + problems.append( + f"{item}: {PACKAGE_JSON} names {part}, found in {sorted(holders) or 'no part'}" + ) + for item in sorted(set(seen) - set(objects)): + problems.append(f"{item}: in {sorted(seen[item])} but not in {PACKAGE_JSON}") + try: + with open(dist / MANIFEST, newline="") as f: + manifest = {row["object"]: row["part_zip"] for row in csv.DictReader(f)} + if manifest != objects: + differ = sorted( + item + for item in set(manifest) | set(objects) + if manifest.get(item) != objects.get(item) + ) + problems.append(f"{MANIFEST} disagrees with {PACKAGE_JSON} for {differ[:5]}") + except (OSError, KeyError) as exception: + problems.append(f"{MANIFEST} cannot be read: {exception}") + + return report + + +def _check_csv(archive, info, name, csv_rows, report) -> List[str]: + problems = [] + try: + with archive.open(info) as handle: + rows = csv_records(handle) + except csv.Error as exception: + return [f"{name}: {info.filename} does not parse: {exception}"] + if not rows: + return problems + width = len(rows[0]) + ragged = [i + 1 for i, row in enumerate(rows[1:], start=1) if len(row) != width] + if ragged: + problems.append( + f"{name}: {info.filename} rows {ragged[:5]} do not have {width} fields" + ) + n = len(rows) - 1 + report.csv_rows += n + expected = csv_rows.get(info.filename) + if expected is not None and expected != n: + problems.append( + f"{name}: {info.filename} has {n} rows, {PACKAGE_JSON} records {expected}" + ) + return problems diff --git a/test_autofit/export/__init__.py b/test_autofit/export/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/test_autofit/export/test_package.py b/test_autofit/export/test_package.py new file mode 100644 index 000000000..6ef9f64a8 --- /dev/null +++ b/test_autofit/export/test_package.py @@ -0,0 +1,331 @@ +import json +import zipfile +from pathlib import Path + +import pytest + +from autofit.export import PackageException, package, verify +from autofit.export.__main__ import main + + +def _library(root: Path, n: int = 9) -> Path: + library = root / "library" + for i in range(n): + item = library / f"obj{i:03d}" + (item / "image").mkdir(parents=True) + (item / "result.json").write_text(json.dumps({"object": i})) + (item / "image" / "fit.png").write_bytes(b"\x89PNG" + bytes(1000 + 100 * i)) + (item / "table.csv").write_text("a,b\n1,2\n3,4\n") + (library / "summary.csv").write_text( + "id,value\n" + "".join(f"obj{i:03d},{i}\n" for i in range(n)) + ) + return library + + +def _sha(dist): + return {path.name: path.read_bytes() for path in dist.glob("*.zip")} + + +@pytest.fixture(name="library") +def make_library(tmp_path): + return _library(tmp_path) + + +def test_package_into_three_parts(library, tmp_path): + dist = tmp_path / "dist" + report = package(library, dist, n_parts=3) + + assert sorted(report.parts) == ["part_001.zip", "part_002.zip", "part_003.zip"] + assert sorted(item for items in report.parts.values() for item in items) == [ + f"obj{i:03d}" for i in range(9) + ] + assert {p.name for p in dist.iterdir()} >= { + "tables.zip", + "parts_manifest.csv", + "package.json", + "SHA256SUMS", + "README.md", + "KNOWN_ISSUES.md", + } + with zipfile.ZipFile(dist / "part_001.zip") as archive: + info = archive.getinfo("library/obj000/image/fit.png") + assert info.compress_type == zipfile.ZIP_STORED + assert archive.getinfo("library/obj000/result.json").compress_type == zipfile.ZIP_DEFLATED + document = json.loads((dist / "package.json").read_text()) + assert document["zips"]["tables.zip"]["csv_rows"] == {"library/summary.csv": 9} + assert "9 objects in 3 part zips" in (dist / "README.md").read_text() + + report = verify(dist) + assert report.ok, report.problems + assert report.csv_rows == 9 + 9 * 2 + + +def test_rebuild_rewrites_only_the_changed_part(library, tmp_path): + dist = tmp_path / "dist" + package(library, dist, n_parts=3) + before = _sha(dist) + + (library / "obj004" / "result.json").write_text(json.dumps({"object": 4, "v": 2})) + report = package(library, dist, n_parts=3) + + assert report.written == ["part_002.zip"] + after = _sha(dist) + assert [name for name in after if after[name] != before[name]] == ["part_002.zip"] + assert verify(dist).ok + + +def test_same_files_same_zip(library, tmp_path): + package(library, tmp_path / "a", n_parts=3) + package(library, tmp_path / "b", n_parts=3) + assert _sha(tmp_path / "a") == _sha(tmp_path / "b") + + +def test_new_objects_fill_the_last_part_then_a_new_one(library, tmp_path): + dist = tmp_path / "dist" + package(library, dist, cap_gb=8000 / 1024**3) + first = json.loads((dist / "package.json").read_text())["objects"] + + for i in range(9, 14): + item = library / f"obj{i:03d}" + item.mkdir() + (item / "result.json").write_text("x" * 3000) + report = package(library, dist, cap_gb=8000 / 1024**3) + objects = json.loads((dist / "package.json").read_text())["objects"] + + assert {k: objects[k] for k in first} == first + assert len(report.parts) > len(set(first.values())) + assert set(report.kept) >= set(first.values()) - {max(first.values())} + assert verify(dist).ok + + +def test_removed_object_and_stale_part(library, tmp_path): + import shutil + + dist = tmp_path / "dist" + package(library, dist, n_parts=3) + for i in (6, 7, 8): + shutil.rmtree(library / f"obj{i:03d}") + report = package(library, dist) + assert "part_003.zip" not in report.parts + assert not (dist / "part_003.zip").exists() + assert verify(dist).ok + + +def test_include_dataset(library, tmp_path): + data = tmp_path / "data" + data.mkdir() + (data / "obj000.fits").write_bytes(b"SIMPLE") + dist = tmp_path / "dist" + package( + library, + dist, + n_parts=1, + include_dataset=lambda item: [data / f"{item}.fits"] if item == "obj000" else [], + ) + with zipfile.ZipFile(dist / "part_001.zip") as archive: + assert archive.read("library/obj000/dataset/obj000.fits") == b"SIMPLE" + + +def test_provenance(library, tmp_path): + from autofit.results import ResultsIndex + + repo = Path(__file__).parents[2] + dist = tmp_path / "dist" + package(library, dist, n_parts=1, repos=[repo], index=ResultsIndex(tmp_path, index_dir=tmp_path / "i")) + provenance = json.loads((dist / "package.json").read_text())["provenance"] + assert len(provenance["repos"][0]["revision"]) == 40 + assert len(provenance["index_hash"]) == 64 + assert provenance["repos"][0]["revision"] in (dist / "README.md").read_text() + + (dist / "KNOWN_ISSUES.md").write_text("mine") + package(library, dist, n_parts=1, title="My release", notes="Read me.") + package(library, dist, n_parts=1) + assert (dist / "KNOWN_ISSUES.md").read_text() == "mine" + readme = (dist / "README.md").read_text() + assert readme.startswith("# My release") and "Read me." in readme + + +def test_refusals(library, tmp_path): + with pytest.raises(PackageException): + package(library, tmp_path / "d", cap_gb=1, n_parts=2) + with pytest.raises(PackageException): + package(tmp_path / "absent", tmp_path / "d") + + +def _rewrite_member(zip_path, name, data): + entries = {} + with zipfile.ZipFile(zip_path) as archive: + for info in archive.infolist(): + entries[info.filename] = archive.read(info) + entries[name] = data + with zipfile.ZipFile(zip_path, "w") as archive: + for member, content in entries.items(): + archive.writestr(member, content) + + +@pytest.fixture(name="dist") +def make_dist(library, tmp_path): + dist = tmp_path / "dist" + package(library, dist, n_parts=3) + return dist + + +def test_verify_catches_an_empty_member(dist): + _rewrite_member(dist / "part_001.zip", "library/obj000/result.json", b"") + problems = verify(dist).problems + assert any("library/obj000/result.json is empty" in p for p in problems) + assert any("part_001.zip: SHA256 does not match" in p for p in problems) + + +def test_verify_catches_a_corrupt_byte(dist): + path = dist / "part_002.zip" + data = bytearray(path.read_bytes()) + data[60] ^= 0xFF + path.write_bytes(bytes(data)) + problems = verify(dist).problems + assert any("part_002.zip" in p for p in problems) + + +def test_verify_catches_row_count_and_ragged_rows(dist): + _rewrite_member(dist / "tables.zip", "library/summary.csv", b"id,value\nobj000,0\nobj001\n") + problems = verify(dist).problems + assert any("has 2 rows, package.json records 9" in p for p in problems) + assert any("do not have 2 fields" in p for p in problems) + + +def test_verify_catches_manifest_drift(dist): + text = (dist / "parts_manifest.csv").read_text().replace("obj000,part_001.zip", "obj000,part_002.zip") + (dist / "parts_manifest.csv").write_text(text) + problems = verify(dist).problems + assert any("parts_manifest.csv disagrees" in p for p in problems) + + +def test_verify_catches_a_missing_part(dist): + (dist / "part_003.zip").unlink() + problems = verify(dist).problems + assert any("part_003.zip: listed in SHA256SUMS but missing" in p for p in problems) + assert any("obj008" in p for p in problems) + + +def test_cli(library, tmp_path, capsys): + dist = tmp_path / "dist" + assert main(["package", str(library), str(dist), "--n-parts", "2"]) == 0 + assert main(["verify", str(dist)]) == 0 + assert "OK" in capsys.readouterr().out + _rewrite_member(dist / "part_001.zip", "library/obj000/result.json", b"") + assert main(["verify", str(dist)]) == 1 + assert main(["package", str(tmp_path / "absent"), str(dist)]) == 2 + + +# Regressions from the independent review. + + +def test_replan_removes_stale_parts_and_verify_flags_foreign_zips(library, tmp_path): + dist = tmp_path / "dist" + package(library, dist, n_parts=3) + package(library, dist, n_parts=2, replan=True) + assert sorted(p.name for p in dist.glob("part_*.zip")) == ["part_001.zip", "part_002.zip"] + assert verify(dist).ok + (dist / "part_009.zip").write_bytes((dist / "part_001.zip").read_bytes()) + assert any("part_009.zip: a zip package.json does not list" in p for p in verify(dist).problems) + + +def test_rebuild_refuses_a_different_part_count(library, tmp_path): + dist = tmp_path / "dist" + package(library, dist, n_parts=2) + with pytest.raises(PackageException, match="replan"): + package(library, dist, n_parts=9) + + +def test_cap_is_remembered(library, tmp_path): + dist = tmp_path / "dist" + package(library, dist, cap_gb=8000 / 1024**3) + n = len(set(json.loads((dist / "package.json").read_text())["objects"].values())) + for i in range(9, 20): + item = library / f"obj{i:03d}" + item.mkdir() + (item / "result.json").write_text("x" * 3000) + report = package(library, dist) # no cap passed + assert len(report.parts) > n + 2 + + +def test_exactly_n_parts(): + from autofit.export.package import _plan + + items = ["a", "b", "c", "d"] + sizes = {"a": 1, "b": 1, "c": 1, "d": 100} + assert len(set(_plan(items, sizes, None, 2, {}).values())) == 2 + assert len(set(_plan(items, sizes, None, 9, {}).values())) == 4 + + +def test_duplicate_member_refused(library, tmp_path): + (library / "obj000" / "dataset").mkdir() + (library / "obj000" / "dataset" / "img.fits").write_bytes(b"A") + extra = tmp_path / "img.fits" + extra.write_bytes(b"B") + with pytest.raises(PackageException, match="several files"): + package(library, tmp_path / "dist", include_dataset=lambda item: [extra]) + + +def test_dot_files_ship_and_vcs_folders_do_not(library, tmp_path): + (library / "obj000" / ".completed").write_text("") + (library / "obj000" / ".git").mkdir() + (library / "obj000" / ".git" / "HEAD").write_text("x") + dist = tmp_path / "dist" + package(library, dist, n_parts=1) + with zipfile.ZipFile(dist / "part_001.zip") as archive: + names = archive.namelist() + assert "library/obj000/.completed" in names + assert not any(".git" in name for name in names) + assert verify(dist).ok # .completed is allowed to be empty + + +def test_odd_csvs_do_not_stop_a_package(library, tmp_path): + (library / "obj000" / "latin.csv").write_bytes("name\nM\xfcller\n".encode("latin-1")) + (library / "obj001" / "wide.csv").write_text("a\n" + "x" * 200_000 + "\n") + (library / "obj002" / "blank_end.csv").write_text("a,b\n1,2\n\n") + dist = tmp_path / "dist" + package(library, dist, n_parts=1) + report = verify(dist) + assert report.ok, report.problems + + +def test_same_zip_in_any_timezone(library, tmp_path, monkeypatch): + import time + + hashes = [] + for tz in ("UTC", "America/New_York"): + monkeypatch.setenv("TZ", tz) + time.tzset() + package(library, tmp_path / tz.replace("/", "_"), n_parts=1) + hashes.append((tmp_path / tz.replace("/", "_") / "part_001.zip").read_bytes()) + monkeypatch.delenv("TZ") + time.tzset() + assert hashes[0] == hashes[1] + + +def test_force_rewrites(library, tmp_path): + dist = tmp_path / "dist" + package(library, dist, n_parts=2) + assert package(library, dist).written == [] + assert sorted(package(library, dist, force=True).written) == [ + "part_001.zip", + "part_002.zip", + "tables.zip", + ] + + +def test_verify_reports_corruption_instead_of_crashing(dist): + path = dist / "tables.zip" + with zipfile.ZipFile(path) as archive: + info = archive.infolist()[0] + offset = info.header_offset + 30 + len(info.filename) + len(info.extra) + 2 + data = bytearray(path.read_bytes()) + for i in range(8): + data[offset + i] ^= 0xFF + path.write_bytes(bytes(data)) + (dist / "SHA256SUMS").write_text((dist / "SHA256SUMS").read_text() + "garbage\n") + report = verify(dist) + assert not report.ok + assert any("SHA256SUMS line" in p for p in report.problems) + assert main(["verify", str(dist)]) == 1 diff --git a/test_autofit/export/test_parity.py b/test_autofit/export/test_parity.py new file mode 100644 index 000000000..c886d3990 --- /dev/null +++ b/test_autofit/export/test_parity.py @@ -0,0 +1,164 @@ +import csv +import random +import shutil +from pathlib import Path + +import pytest + +from autofit.aggregator import Aggregator +from autofit.export import compare, scatter_between +from autofit.export.__main__ import main + +FIXTURE = Path(__file__).parents[1] / "aggregator" / "summary_files" / "aggregate_summary" + + +def _table(n=50, shift=0.0, seed=0, sigma=0.1): + rng = random.Random(seed) + rows = [] + for i in range(n): + value = i + shift + rng.gauss(0, sigma) + rows.append( + { + "id": f"obj{i:03d}", + "ra": f"{10 + i * 0.01:.6f}", + "einstein_radius": value, + "einstein_radius_lower_1_sigma": value - sigma, + "einstein_radius_upper_1_sigma": value + sigma, + "flag": "ok", + } + ) + return rows + + +def test_reruns_report_scatter_not_fail(): + report = compare(_table(seed=1), _table(seed=2)) + column = report.columns["einstein_radius"] + assert report.passed + assert column.kind == "sigma" and not column.gated + assert 0.3 < column.median_z < 2.0 + assert column.max_z > column.median_z + assert "PASS" in report.to_markdown() + assert compare(_table(), _table()).columns["einstein_radius"].worst == [] + + +def test_gated_column_fails_beyond_threshold(): + report = compare(_table(), _table(shift=1.0), gate=["einstein_radius"]) + assert not report.passed + assert report.columns["einstein_radius"].n_mismatch == 50 + assert "FAIL" in report.to_markdown() + + +def test_identity_and_duplicates_fail(): + a = _table() + b = _table()[:-2] + [_table()[0]] + report = compare(a, b) + assert report.only_a == ["obj048", "obj049"] + assert report.duplicates_b == ["obj000"] + assert not report.passed + + +def test_exact_columns(): + b = _table() + b[3]["ra"] = "99.0" + report = compare(_table(), b, exact=["ra"]) + assert report.columns["ra"].kind == "exact" + assert report.columns["ra"].n_mismatch == 1 + assert not report.passed + assert compare(_table(), _table(), exact=["ra", "flag"]).passed + + +def test_error_floor(): + a = _table(sigma=0.0) + b = _table(sigma=0.0, shift=1e-6) + assert compare(a, b).columns["einstein_radius"].max_z == float("inf") + assert compare(a, b, floor=1e-3).columns["einstein_radius"].max_z < 0.01 + assert compare(a, b, rel_floor=0.01).columns["einstein_radius"].median_z < 1 + + +def test_blank_and_composite_key(): + a = _table() + b = _table() + a[0]["einstein_radius"] = "" + for row in a + b: + row["band"] = "vis" + report = compare(a, b, key=["id", "band"]) + assert report.key == ("id", "band") + assert report.columns["einstein_radius"].n_blank == 1 + + +def test_cli_compare(tmp_path): + def write(path, rows): + with open(path, "w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + return path + + a = write(tmp_path / "a.csv", _table(seed=1)) + b = write(tmp_path / "b.csv", _table(seed=2)) + assert main(["compare", str(a), str(b), "--report", str(tmp_path / "r.md")]) == 0 + assert (tmp_path / "r.md").read_text().startswith("# Parity: PASS") + assert main(["compare", str(a), str(b), "--gate", "einstein_radius", "--threshold", "0.01"]) == 1 + assert main(["compare", str(a), str(tmp_path / "absent.csv")]) == 2 + + +def _copies(root, n): + for i in range(n): + shutil.copytree(FIXTURE / ("fit_1" if i % 2 else "fit_2"), root / f"obj{i}" / "fit") + return Aggregator.from_directory(root) + + +def test_scatter_between(tmp_path): + a = _copies(tmp_path / "a", 2) + b = _copies(tmp_path / "b", 2) + + def key(output): + return Path(output.directory).parent.name + + report = scatter_between( + a, b, ["galaxies.lens.bulge.centre.centre_0", "latent.value", "nope"], key=key + ) + assert report.matched == 2 + centre = report.paths["galaxies.lens.bulge.centre.centre_0"] + assert centre.n == 2 and centre.median_z == 0.0 + assert report.paths["nope"].n == 0 + assert "matched fits" in str(report) + + +# Regressions from the independent review. + + +def test_missing_and_unknown_columns_fail(): + a = _table() + b = [{k: v for k, v in row.items() if k != "flag"} for row in _table()] + report = compare(a, b) + assert report.columns_only_a == ["flag"] and not report.passed + report = compare(_table(), _table(), exact=["typo"], gate=["nope"]) + assert report.unknown == ["nope", "typo"] and not report.passed + + +def test_value_lost_on_one_side_fails_a_gate(): + a = [{"id": "o1", "n": "x"}] + b = [{"id": "o1", "n": ""}] + assert not compare(a, b, exact=["n"]).passed + assert compare(a, b).passed # informational column: reported as blank + + +def test_columns_keeps_sigma_companions(): + report = compare(_table(seed=1), _table(seed=2), gate=["einstein_radius"], columns=["einstein_radius"]) + assert report.columns["einstein_radius"].kind == "sigma" + assert list(report.columns) == ["einstein_radius"] + + +def test_exact_large_integer_ids(): + a = [{"id": "1", "oid": "9007199254740993"}] + b = [{"id": "1", "oid": "9007199254740992"}] + assert not compare(a, b, exact=["oid"]).passed + assert compare([{"id": "1", "x": "1.0"}], [{"id": "1", "x": "1"}], exact=["x"]).passed + + +def test_scatter_key_must_be_unique(tmp_path): + a = _copies(tmp_path / "a", 4) + b = _copies(tmp_path / "b", 4) + with pytest.raises(ValueError, match="several fits"): + scatter_between(a, b, ["galaxies.lens.bulge.centre.centre_0"], key=lambda o: "same")