From d9d2377995c37550cf09de765cae7faf84c60a98 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 5 Oct 2026 09:43:59 +0100 Subject: [PATCH] feat: validate setup-oriented profiling evidence alongside v1 --- AGENTS.md | 9 + REFERENCE.md | 106 +++++++ pulse/catalogue.py | 410 ++++++++++++++++++++++++ pulse/summary.py | 21 +- tests/fixtures/setup_summary_v2.json | 419 +++++++++++++++++++++++++ tests/fixtures/unsupported_schema.json | 2 +- tests/test_catalogue.py | 223 +++++++++++++ tests/test_summary.py | 2 +- 8 files changed, 1186 insertions(+), 6 deletions(-) create mode 100644 pulse/catalogue.py create mode 100644 tests/fixtures/setup_summary_v2.json create mode 100644 tests/test_catalogue.py diff --git a/AGENTS.md b/AGENTS.md index 58bbee2..73d3bd3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -117,6 +117,15 @@ else `$PYAUTO_MIND`, else `$PYAUTO_ROOT/organs/PyAutoMind` or `$PYAUTO_ROOT/PyAutoMind`, else beside this organ). There is no second catalogue of repositories. +## Setup catalogue migration + +The reader accepts `profiling-summary` v1 and v2; registry rows still pin one +exact version. V2 adds setup identities, typed evidence and explicit reference +selections (`pulse/catalogue.py`, `REFERENCE.md`). Keep the live registry on v1 +until the project exporter migration. Accepting a schema is not scientific +acceptance and does not launch a baseline campaign. The setup browser follows +in its own phase. + ## Boundary (what this organ never does) From the spec's "Profiling domain contract", verbatim: diff --git a/REFERENCE.md b/REFERENCE.md index 86ea9a7..c2fbc5e 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -94,6 +94,112 @@ precision`, in producer order (never sorted by ratio). **Outcomes.** `ok` · `invalid` (not JSON, or contract breaks) · `unsupported` (schema/version) · `unavailable` (transport: API or raw file unreadable). +## `profiling-summary` v2: setup catalogue + +The v2 reader lands before the project producer migrates. Registry entries +still pin an exact version; supporting v2 does **not** silently upgrade the live +`profiling-summary@1` registry or reinterpret a saved v1 snapshot. The full +[synthetic fixture](tests/fixtures/setup_summary_v2.json) is an executable +producer example. Validation is stdlib-only in `pulse/catalogue.py`, through +`pulse.summary.classify`; it never opens evidence files or judges science. + +V2 retains the common v1 envelope and receipt fields. It requires `setups`, +`records`, `selections`, `hazards`, and `recommendations` lists (empty is valid). +IDs are non-empty and unique within each list; references resolve within the +same document and project. `comparisons` must be `[]`: this catalogue presents +selected results, not release trends. Keep `comparison_policy.id` explicitly +labelled, e.g. `no-temporal-comparisons`, for common receipt/board compatibility. +The existing board can ingest/render v2 metadata; the interactive setup browser +is a subsequent phase. Historical v1 feeds and their comparison rules remain +supported without rewriting measurements, pins, or policy. + +### Setups + +Each setup has `id`, `label`, `dataset`, `model`, `instrument`, +`configuration_id`, and a non-empty `configuration` object. IDs are semantic, +not script paths. A configuration ID identifies exact scientific settings; +changing solver, regularization, dataset or resolution requires a different +setup. Instrument is a string, or null with `unknowns.instrument` explaining +why (including dataset-independent component profiling). + +Configuration fields are named objects with `value` and `unit`; examples are +`source_pixels: {value: 1500, unit: count}` and +`psf_shape: {value: [21, 21], unit: pixel}`. Use `name` for settings such as +solver and `dimensionless` where appropriate. A null value requires `reason`. +Include all scientifically relevant settings, not merely the instrument name; +legacy unknowns must remain unknown rather than inheriting today's defaults. +All nested metadata must be finite JSON; NaN and infinity are refused. + +### Measurement records + +Each record has: + +- `id`, `setup_id`, `run_id`, `axis`, `metric`, `unit`, and `measurement`. + Axes/units follow the v1 table. `measurement` contains **exactly one** key, + equal to `metric`, with a finite non-negative value; booleans/null are not + measurements. Missing cells belong in selections, not zero-valued records. +- `identity`: `device`, `backend`, `precision`, `library_version`, and a + non-empty `software` mapping of measured package names to versions/revisions. + Nullable identity fields require corresponding `identity.unknowns` reasons. + Software captures the measured stack, not the current reader environment. +- `method`: `id`, `statistic`, positive integer `repetitions`, `warmup`, + `synchronization`, and `cache_state`. Except for `id`, unknowns may be null + with corresponding `method.unknowns` reasons. Reusing a method ID with a + different method definition is invalid. Name single-call latency, batch + throughput, instrumented component cost and compile/cache procedures + distinctly; method IDs are meaningful producer-owned identifiers. +- `provenance`: boolean `has_provenance` and `qualified`; `host` and + `measured_at` (UTC timestamp), each nullable with `provenance.unknowns` + reasons. Qualified evidence requires `has_provenance: true`. +- `validation`: `status` (`accepted`, `unreviewed`, `rejected`) and a non-empty + `reason`. Accepted records must be qualified; these are producer declarations, + never an acceptance decision inferred by Pulse. +- `evidence`: repo-relative `path` and optional string/null `fragment`, resolved + at the captured project commit. Absolute paths, URLs and traversal are refused. + +Memory metrics are explicitly `host_peak_rss`, `device_peak_allocated`, +`device_peak_reserved`, or `device_total`; the last is device capacity, **not** +measured application VRAM. Additional memory meanings require an explicit +contract extension. Component timings remain `axis: breakdown`, never runtime. + +### Explicit selections and coverage + +A selection represents one declared measurement slot, with `id`, `setup_id`, +`axis`, `metric`, `unit`, `method_id`, full `identity`, `host`, `status`, +`record_id`, and a non-empty `reason`. Unknown host uses `unknowns.host`. + +For `accepted` or `unreviewed`, `record_id` must resolve, and the setup, axis, +metric, unit, method ID, complete identity (including software revisions), host +and validation status must match the named record. Duplicate slots are refused. +The producer chooses references; Pulse never selects a latest/fastest row. +Other states (`not_measured`, `failed`, `unusable`, `inapplicable`) require +`record_id: null`. Diagnostic artifacts can remain linked from findings; +a failed run is never presented as a zero-cost successful measurement. + +`coverage.expected.cells` equals the selection count. `coverage.observed` +contains accurate `setups`, `records`, and `selected` counts. This distinguishes +a declared missing GPU cell from an undeclared cell. The common `excluded` +list retains excluded evidence and reasons. An empty catalogue is no evidence, +not a scientific pass. + +### Hazards and recommendations + +Both have `id`, `title`, `description`, non-empty `evidence` (objects with safe +`path` and optional `fragment`), and `applies_to`: + +- non-empty `setup_ids` referencing exact setups; +- non-empty `library_versions` naming applicable measured versions; +- `constraints` object, plus a non-empty `limitations` string. + +Hazards have `status: open | resolved | unknown`. Recommendations additionally +have non-empty `record_ids` and `validation` as above. Supporting records must +belong to the applicable setups and library versions; an accepted recommendation +requires accepted supporting records. Constraints and scientific claims remain +producer-owned: the reader checks structure and reference integrity, not whether +a recommended solver is correct. Consumers must inspect the cited records' +hardware/method and applicability, and must not extrapolate to a different setup +or interpret a per-likelihood measurement as a total-fit prediction. + ## Ingest 1. `GET https://api.github.com/repos///commits/main` → one 40-hex SHA diff --git a/pulse/catalogue.py b/pulse/catalogue.py new file mode 100644 index 0000000..82ddada --- /dev/null +++ b/pulse/catalogue.py @@ -0,0 +1,410 @@ +"""Validate the setup-oriented v2 exchange contract without judging evidence. + +Stable setup IDs decouple scientific navigation from script paths. Selections +name exact records and their measurement context; missing cells remain explicit. +This module is stdlib-only and does not read files, choose results or compute +comparisons. See REFERENCE.md for the producer-facing grammar. +""" + +from __future__ import annotations + +import json +import math + +from pulse import summary + +SELECTION_STATES = {"accepted", "unreviewed", "not_measured", "failed", "unusable", "inapplicable"} +VALIDATION_STATES = {"accepted", "unreviewed", "rejected"} +MEMORY_METRICS = {"host_peak_rss", "device_peak_allocated", "device_peak_reserved", "device_total"} + + +class _Check: + def __init__(self): + self.errors: list[str] = [] + + def require(self, condition, where, message): + if not condition: + self.errors.append(f"{where}: {message}") + + def text(self, value, where): + self.require(summary._text(value), where, "must be a non-empty string") + + def choice(self, value, choices, where): + self.require( + isinstance(value, str) and value in choices, where, f"must be one of {sorted(choices)}" + ) + + def objects(self, value, where): + if not isinstance(value, list): + self.errors.append(f"{where}: must be a list") + return [] + result = [] + for i, item in enumerate(value): + if isinstance(item, dict): + result.append(item) + else: + self.errors.append(f"{where}[{i}]: must be an object") + return result + + def index(self, value, where): + result = {} + for i, item in enumerate(self.objects(value, where)): + key = item.get("id") + self.text(key, f"{where}[{i}].id") + if summary._text(key): + self.require(key not in result, where, f"duplicate id {key!r}") + result[key] = item + return result + + def reference(self, value, index, where): + self.require( + isinstance(value, str) and value in index, where, f"unknown reference {value!r}" + ) + return index.get(value) if isinstance(value, str) else None + + def references(self, value, index, where, nonempty=True): + if not isinstance(value, list): + self.errors.append(f"{where}: must be a list of references") + return [] + self.require(bool(value) or not nonempty, where, "must not be empty") + result = [] + seen = set() + for item in value: + record = self.reference(item, index, where) + if isinstance(item, str): + self.require(item not in seen, where, f"duplicate reference {item!r}") + seen.add(item) + if record is not None: + result.append(record) + return result + + def evidence(self, value, where): + if not isinstance(value, dict): + self.errors.append(f"{where}: must be an evidence object") + return + self.require(summary.safe_relative_path(value.get("path")), where, "unsafe evidence path") + self.require( + value.get("fragment") is None or summary._text(value["fragment"]), + where, + "invalid evidence fragment", + ) + + def nullable(self, obj, key, where, predicate=summary._text): + self.require(key in obj, where, f"missing {key}") + value = obj.get(key) + if value is None: + unknowns = obj.get("unknowns") + self.require( + isinstance(unknowns, dict) and summary._text(unknowns.get(key)), + where, + f"{key} is null without an unknowns reason", + ) + else: + self.require(predicate(value), where, f"invalid {key}") + + def validation(self, value, where): + if not isinstance(value, dict): + self.errors.append(f"{where}: must be a validation object") + return None + self.choice(value.get("status"), VALIDATION_STATES, where) + self.text(value.get("reason"), f"{where}.reason") + return value.get("status") + + +def _finite(value): + if isinstance(value, bool) or not isinstance(value, int | float): + return False + try: + return math.isfinite(value) + except OverflowError: + return False + + +def _integer(value): + return isinstance(value, int) and not isinstance(value, bool) and value >= 0 + + +def _json_values(check, value, where): + """Reject non-finite and non-JSON metadata, including nested extensions.""" + if isinstance(value, dict): + for key, item in value.items(): + check.text(key, where) + _json_values(check, item, f"{where}.{key}") + elif isinstance(value, list): + for i, item in enumerate(value): + _json_values(check, item, f"{where}[{i}]") + elif value is not None and not isinstance(value, str | bool): + check.require(_finite(value), where, "non-finite or non-JSON value") + + +def _identity(check, identity, where): + if not isinstance(identity, dict): + check.errors.append(f"{where}: must be an identity object") + return + for key in ("device", "backend", "precision", "library_version"): + check.nullable(identity, key, where) + software = identity.get("software") + check.require( + isinstance(software, dict) and bool(software), + where, + "software must identify measured package versions/revisions", + ) + if isinstance(software, dict): + for key in software: + check.text(software[key], f"{where}.software.{key}") + + +def _setup(check, item): + where = f"setup {item['id']!r}" + for key in ("label", "dataset", "model", "configuration_id"): + check.text(item.get(key), f"{where}.{key}") + check.nullable(item, "instrument", where) + config = item.get("configuration") + if not isinstance(config, dict): + check.errors.append(f"{where}: configuration must be an object") + return + check.require(bool(config), where, "configuration must describe the setup") + for key, field in config.items(): + loc = f"{where}.configuration.{key}" + if not isinstance(field, dict): + check.errors.append(f"{loc}: must contain value and unit") + continue + check.text(field.get("unit"), f"{loc}.unit") + check.require("value" in field, loc, "missing value") + if field.get("value") is None: + check.text(field.get("reason"), f"{loc}.reason") + # Values can be scalar or vectors (e.g. PSF shape), boolean or strings + # (e.g. solver). Units may be 'dimensionless' or 'name'. + + +def _record(check, item, setups): + where = f"record {item['id']!r}" + check.reference(item.get("setup_id"), setups, f"{where}.setup_id") + check.text(item.get("run_id"), f"{where}.run_id") + metric = item.get("metric") + check.text(metric, f"{where}.metric") + axis = item.get("axis") + check.choice(axis, summary.AXIS_UNITS, f"{where}.axis") + if isinstance(axis, str) and axis in summary.AXIS_UNITS: + check.choice(item.get("unit"), summary.AXIS_UNITS[axis], f"{where}.unit") + meas = item.get("measurement") + check.require( + isinstance(meas, dict) and list(meas) == [metric], + where, + "measurement must contain exactly its named metric", + ) + if isinstance(meas, dict): + for value in meas.values(): + check.require( + _finite(value) and value >= 0, + where, + "measurement must be finite and non-negative; missing cells use selections", + ) + if axis == "memory": + check.choice(metric, MEMORY_METRICS, f"{where}.metric") + _identity(check, item.get("identity"), f"{where}.identity") + method = item.get("method") + if not isinstance(method, dict): + check.errors.append(f"{where}: method must be an object") + else: + check.text(method.get("id"), f"{where}.method.id") + check.nullable(method, "statistic", f"{where}.method") + check.nullable(method, "repetitions", f"{where}.method", lambda n: _integer(n) and n > 0) + for key in ("warmup", "synchronization", "cache_state"): + check.nullable(method, key, f"{where}.method") + prov = item.get("provenance") + if not isinstance(prov, dict): + check.errors.append(f"{where}: provenance must be an object") + else: + check.nullable(prov, "host", f"{where}.provenance") + check.nullable( + prov, "measured_at", f"{where}.provenance", lambda x: summary.parse_utc(x) is not None + ) + for key in ("qualified", "has_provenance"): + check.require( + isinstance(prov.get(key), bool), where, f"provenance.{key} must be a boolean" + ) + if prov.get("qualified") is True: + check.require( + prov.get("has_provenance") is True, where, "qualified requires provenance" + ) + status = check.validation(item.get("validation"), f"{where}.validation") + if status == "accepted": + check.require( + isinstance(prov, dict) and prov.get("qualified") is True, + where, + "accepted evidence must be qualified", + ) + check.evidence(item.get("evidence"), f"{where}.evidence") + + +def _selection(check, item, setups, records): + where = f"selection {item['id']!r}" + check.reference(item.get("setup_id"), setups, f"{where}.setup_id") + check.choice(item.get("status"), SELECTION_STATES, f"{where}.status") + check.text(item.get("reason"), f"{where}.reason") + axis = item.get("axis") + check.choice(axis, summary.AXIS_UNITS, f"{where}.axis") + if isinstance(axis, str) and axis in summary.AXIS_UNITS: + check.choice(item.get("unit"), summary.AXIS_UNITS[axis], f"{where}.unit") + for key in ("metric", "method_id"): + check.text(item.get(key), f"{where}.{key}") + _identity(check, item.get("identity"), f"{where}.identity") + check.nullable(item, "host", where) + check.require("record_id" in item, where, "missing record_id") + if item.get("status") not in ("accepted", "unreviewed"): + check.require( + item.get("record_id") is None, + where, + "unmeasured/failed/unusable/inapplicable cells cannot select a measurement", + ) + return + record = check.reference(item.get("record_id"), records, f"{where}.record_id") + if record is None: + return + for key in ("setup_id", "axis", "metric", "unit", "identity"): + check.require( + item.get(key) == record.get(key), where, f"{key} mismatch with selected record" + ) + method = record.get("method") + check.require( + isinstance(method, dict) and item.get("method_id") == method.get("id"), + where, + "method mismatch with selected record", + ) + prov = record.get("provenance") + check.require( + isinstance(prov, dict) and item.get("host") == prov.get("host"), + where, + "host mismatch with selected record", + ) + validation = record.get("validation") + check.require( + isinstance(validation, dict) and validation.get("status") == item.get("status"), + where, + "validation status mismatch with selected record", + ) + + +def _advice(check, item, setups, records, kind): + where = f"{kind} {item['id']!r}" + for key in ("title", "description"): + check.text(item.get(key), f"{where}.{key}") + scope = item.get("applies_to") + if not isinstance(scope, dict): + check.errors.append(f"{where}: applies_to must be an object") + return + setup_rows = check.references(scope.get("setup_ids"), setups, f"{where}.applies_to.setup_ids") + versions = scope.get("library_versions") + check.require( + isinstance(versions, list) and bool(versions) and all(summary._text(x) for x in versions), + where, + "applicability must name measured library_versions", + ) + check.text(scope.get("limitations"), f"{where}.applies_to.limitations") + constraints = scope.get("constraints") + check.require( + isinstance(constraints, dict), + where, + "applicability constraints must be an object (exact setups apply even when empty)", + ) + evidence = check.objects(item.get("evidence"), f"{where}.evidence") + check.require(bool(evidence), where, "needs supporting evidence") + for ev in evidence: + check.evidence(ev, f"{where}.evidence") + if kind == "hazard": + check.choice(item.get("status"), {"open", "resolved", "unknown"}, f"{where}.status") + else: + status = check.validation(item.get("validation"), f"{where}.validation") + supports = check.references(item.get("record_ids"), records, f"{where}.record_ids") + allowed_setups = {s["id"] for s in setup_rows} + for record in supports: + check.require( + isinstance(record.get("setup_id"), str) + and record.get("setup_id") in allowed_setups, + where, + "supporting record is outside applicable setups", + ) + ident = record.get("identity") + check.require( + isinstance(ident, dict) + and isinstance(versions, list) + and ident.get("library_version") in versions, + where, + "supporting record is outside applicable library versions", + ) + if status == "accepted": + validation = record.get("validation") + check.require( + isinstance(validation, dict) and validation.get("status") == "accepted", + where, + "accepted recommendation requires accepted supporting records", + ) + + +def validate(doc): + """Return all detected v2 contract violations; never choose a baseline.""" + check = _Check() + _json_values(check, doc, "summary") + # The common envelope retains v1 transport/receipt/board fields. Validate + # it through the established reader with empty records/comparisons; v2 + # records are checked below and v2 deliberately carries no trend pairs. + envelope = dict(doc, records=[], comparisons=[]) + check.errors.extend(summary._validate_v1(envelope)) + check.require( + doc.get("comparisons") == [], + "comparisons", + "v2 setup feed has no temporal comparisons; must be []", + ) + setups = check.index(doc.get("setups"), "setups") + records = check.index(doc.get("records"), "records") + selections = check.index(doc.get("selections"), "selections") + for item in setups.values(): + _setup(check, item) + methods = {} + for item in records.values(): + _record(check, item, setups) + method = item.get("method") + if isinstance(method, dict) and summary._text(method.get("id")): + prior = methods.setdefault(method["id"], method) + check.require(prior == method, "records", "method id has conflicting definitions") + slots = set() + for item in selections.values(): + _selection(check, item, setups, records) + # JSON identity includes package revisions; canonical ordering avoids + # permitting two competing selections just because keys were reordered. + slot = json.dumps( + { + k: item.get(k) + for k in ("setup_id", "axis", "metric", "unit", "method_id", "identity", "host") + }, + sort_keys=True, + ) + check.require(slot not in slots, "selections", "duplicate measurement slot") + slots.add(slot) + for field, kind in (("hazards", "hazard"), ("recommendations", "recommendation")): + for item in check.index(doc.get(field), field).values(): + _advice(check, item, setups, records, kind) + cov = doc.get("coverage") + if isinstance(cov, dict): + expected = cov.get("expected") + observed = cov.get("observed") + check.require( + isinstance(expected, dict) + and expected.get("cells") == len(selections) + and type(expected.get("cells")) is int, + "coverage.expected.cells", + "must equal the declared selection count", + ) + if isinstance(observed, dict): + for key, count in ( + ("setups", len(setups)), + ("records", len(records)), + ("selected", sum(s.get("record_id") is not None for s in selections.values())), + ): + check.require( + observed.get(key) == count and type(observed.get(key)) is int, + f"coverage.observed.{key}", + "must match catalogue contents", + ) + return check.errors diff --git a/pulse/summary.py b/pulse/summary.py index 73e998c..4ca41db 100644 --- a/pulse/summary.py +++ b/pulse/summary.py @@ -1,9 +1,10 @@ -"""The ``profiling-summary`` v1 exchange contract, as the organ reads it. +"""The ``profiling-summary`` v1/v2 exchange contracts, as the organ reads them. The contract is owned by the producer and documented beside it (``autolens_profiling/dashboard/README.md``, "summary.json — the profiling-summary v1 read contract": Envelope / Records / Comparisons). This -module validates the **exchange** contract only — known schema/version, +module dispatches setup-oriented v2 validation to ``pulse.catalogue`` and +validates the **exchange** contract only — known schema/version, required fields, unique ids, finite numerics, UTC dates, safe evidence paths, axis/unit consistency — and pairs each producer comparison with its two records so the board can refuse a pair whose axis or hardware identity @@ -19,7 +20,7 @@ from dataclasses import dataclass, field from datetime import datetime -SUPPORTED = {("profiling-summary", 1)} +SUPPORTED = {("profiling-summary", 1), ("profiling-summary", 2)} ENVELOPE = ( "schema", @@ -107,7 +108,7 @@ def supported(doc, wanted: tuple[str, int] | None = None) -> str | None: if not isinstance(doc, dict): return "summary is not a JSON object" got = (doc.get("schema"), doc.get("version")) - if got not in SUPPORTED: + if not isinstance(got[0], str) or type(got[1]) is not int or got not in SUPPORTED: known = ", ".join(f"{s}@{v}" for s, v in sorted(SUPPORTED)) return f"unsupported schema {got[0]!r} version {got[1]!r} (this reader supports {known})" if wanted is not None and got != tuple(wanted): @@ -116,6 +117,18 @@ def supported(doc, wanted: tuple[str, int] | None = None) -> str | None: def validate(doc) -> list[str]: + """Validate the versioned contract; unsupported documents fail closed.""" + why = supported(doc) + if why: + return [why] + if doc["version"] == 2: + from pulse import catalogue + + return catalogue.validate(doc) + return _validate_v1(doc) + + +def _validate_v1(doc) -> list[str]: """Every exchange-contract break in a parsed summary (empty = valid). Schema/version support is checked separately by ``supported``; this diff --git a/tests/fixtures/setup_summary_v2.json b/tests/fixtures/setup_summary_v2.json new file mode 100644 index 0000000..44c88af --- /dev/null +++ b/tests/fixtures/setup_summary_v2.json @@ -0,0 +1,419 @@ +{ + "schema": "profiling-summary", + "version": 2, + "project": "fixture_profiling", + "scope": "setup-catalogue", + "generated_at": "2026-09-30T12:00:00Z", + "evidence_updated_at": null, + "evidence_updated_at_reason": "no rows measured yet", + "valid_until": null, + "producer_revision": "0123456789abcdef0123456789abcdef01234567", + "comparison_policy": { + "id": "no-temporal-comparisons" + }, + "coverage": { + "expected": { + "cells": 5 + }, + "observed": { + "setups": 1, + "records": 4, + "selected": 4 + }, + "excluded": [] + }, + "records": [ + { + "id": "runtime-fixture", + "setup_id": "imaging/delaunay/hst/reference", + "run_id": "synthetic-run-1", + "axis": "runtime", + "metric": "single_call", + "unit": "s", + "measurement": { + "single_call": 0.05 + }, + "identity": { + "device": "cpu", + "backend": "jax", + "precision": "float64", + "library_version": "2026.10.4.1", + "software": { + "PyAutoLens": "2026.10.4.1", + "PyAutoArray": "0123456789abcdef0123456789abcdef01234567", + "jax": "fixture" + } + }, + "method": { + "id": "runtime-fixture-method", + "statistic": "median", + "repetitions": 5, + "warmup": "one call", + "synchronization": "block_until_ready", + "cache_state": "warm" + }, + "provenance": { + "host": "fixture-host", + "measured_at": "2026-10-04T12:00:00Z", + "has_provenance": true, + "qualified": true + }, + "validation": { + "status": "accepted", + "reason": "synthetic fixture only; not a scientific result" + }, + "evidence": { + "path": "results/fixture/runtime.json", + "fragment": "single_call" + } + }, + { + "id": "breakdown-fixture", + "setup_id": "imaging/delaunay/hst/reference", + "run_id": "synthetic-run-1", + "axis": "breakdown", + "metric": "mapping", + "unit": "s", + "measurement": { + "mapping": 0.02 + }, + "identity": { + "device": "cpu", + "backend": "jax", + "precision": "float64", + "library_version": "2026.10.4.1", + "software": { + "PyAutoLens": "2026.10.4.1", + "PyAutoArray": "0123456789abcdef0123456789abcdef01234567", + "jax": "fixture" + } + }, + "method": { + "id": "breakdown-fixture-method", + "statistic": "median", + "repetitions": 5, + "warmup": "one call", + "synchronization": "block_until_ready", + "cache_state": "warm" + }, + "provenance": { + "host": "fixture-host", + "measured_at": "2026-10-04T12:00:00Z", + "has_provenance": true, + "qualified": true + }, + "validation": { + "status": "accepted", + "reason": "synthetic fixture only; not a scientific result" + }, + "evidence": { + "path": "results/fixture/breakdown.json", + "fragment": "mapping" + } + }, + { + "id": "compile-fixture", + "setup_id": "imaging/delaunay/hst/reference", + "run_id": "synthetic-run-1", + "axis": "compile", + "metric": "cold_compile", + "unit": "s", + "measurement": { + "cold_compile": 3.0 + }, + "identity": { + "device": "cpu", + "backend": "jax", + "precision": "float64", + "library_version": "2026.10.4.1", + "software": { + "PyAutoLens": "2026.10.4.1", + "PyAutoArray": "0123456789abcdef0123456789abcdef01234567", + "jax": "fixture" + } + }, + "method": { + "id": "compile-fixture-method", + "statistic": "median", + "repetitions": 5, + "warmup": "one call", + "synchronization": "block_until_ready", + "cache_state": "cold" + }, + "provenance": { + "host": "fixture-host", + "measured_at": "2026-10-04T12:00:00Z", + "has_provenance": true, + "qualified": true + }, + "validation": { + "status": "accepted", + "reason": "synthetic fixture only; not a scientific result" + }, + "evidence": { + "path": "results/fixture/compile.json", + "fragment": "cold_compile" + } + }, + { + "id": "memory-fixture", + "setup_id": "imaging/delaunay/hst/reference", + "run_id": "synthetic-run-1", + "axis": "memory", + "metric": "host_peak_rss", + "unit": "MiB", + "measurement": { + "host_peak_rss": 250 + }, + "identity": { + "device": "cpu", + "backend": "jax", + "precision": "float64", + "library_version": "2026.10.4.1", + "software": { + "PyAutoLens": "2026.10.4.1", + "PyAutoArray": "0123456789abcdef0123456789abcdef01234567", + "jax": "fixture" + } + }, + "method": { + "id": "memory-fixture-method", + "statistic": "median", + "repetitions": 5, + "warmup": "one call", + "synchronization": "block_until_ready", + "cache_state": "warm" + }, + "provenance": { + "host": "fixture-host", + "measured_at": "2026-10-04T12:00:00Z", + "has_provenance": true, + "qualified": true + }, + "validation": { + "status": "accepted", + "reason": "synthetic fixture only; not a scientific result" + }, + "evidence": { + "path": "results/fixture/memory.json", + "fragment": "host_peak_rss" + } + } + ], + "comparisons": [], + "limitations": [ + "fixture: hand-written to exercise one reader acceptance case" + ], + "setups": [ + { + "id": "imaging/delaunay/hst/reference", + "label": "HST Delaunay reference", + "dataset": "imaging", + "model": "delaunay", + "instrument": "hst", + "configuration_id": "synthetic-reference-v1", + "configuration": { + "source_pixels": { + "value": 1500, + "unit": "count" + }, + "psf_shape": { + "value": [ + 21, + 21 + ], + "unit": "pixel" + }, + "solver": { + "value": "fixture-solver", + "unit": "name" + }, + "oversampling": { + "value": null, + "unit": "dimensionless", + "reason": "not recorded in this synthetic fixture" + } + } + } + ], + "selections": [ + { + "setup_id": "imaging/delaunay/hst/reference", + "axis": "runtime", + "metric": "single_call", + "unit": "s", + "identity": { + "device": "cpu", + "backend": "jax", + "precision": "float64", + "library_version": "2026.10.4.1", + "software": { + "PyAutoLens": "2026.10.4.1", + "PyAutoArray": "0123456789abcdef0123456789abcdef01234567", + "jax": "fixture" + } + }, + "id": "runtime-selection", + "method_id": "runtime-fixture-method", + "host": "fixture-host", + "record_id": "runtime-fixture", + "status": "accepted", + "reason": "explicit synthetic reference selection" + }, + { + "setup_id": "imaging/delaunay/hst/reference", + "axis": "breakdown", + "metric": "mapping", + "unit": "s", + "identity": { + "device": "cpu", + "backend": "jax", + "precision": "float64", + "library_version": "2026.10.4.1", + "software": { + "PyAutoLens": "2026.10.4.1", + "PyAutoArray": "0123456789abcdef0123456789abcdef01234567", + "jax": "fixture" + } + }, + "id": "breakdown-selection", + "method_id": "breakdown-fixture-method", + "host": "fixture-host", + "record_id": "breakdown-fixture", + "status": "accepted", + "reason": "explicit synthetic reference selection" + }, + { + "setup_id": "imaging/delaunay/hst/reference", + "axis": "compile", + "metric": "cold_compile", + "unit": "s", + "identity": { + "device": "cpu", + "backend": "jax", + "precision": "float64", + "library_version": "2026.10.4.1", + "software": { + "PyAutoLens": "2026.10.4.1", + "PyAutoArray": "0123456789abcdef0123456789abcdef01234567", + "jax": "fixture" + } + }, + "id": "compile-selection", + "method_id": "compile-fixture-method", + "host": "fixture-host", + "record_id": "compile-fixture", + "status": "accepted", + "reason": "explicit synthetic reference selection" + }, + { + "setup_id": "imaging/delaunay/hst/reference", + "axis": "memory", + "metric": "host_peak_rss", + "unit": "MiB", + "identity": { + "device": "cpu", + "backend": "jax", + "precision": "float64", + "library_version": "2026.10.4.1", + "software": { + "PyAutoLens": "2026.10.4.1", + "PyAutoArray": "0123456789abcdef0123456789abcdef01234567", + "jax": "fixture" + } + }, + "id": "memory-selection", + "method_id": "memory-fixture-method", + "host": "fixture-host", + "record_id": "memory-fixture", + "status": "accepted", + "reason": "explicit synthetic reference selection" + }, + { + "setup_id": "imaging/delaunay/hst/reference", + "axis": "runtime", + "metric": "single_call", + "unit": "s", + "identity": { + "device": "a100", + "backend": "cuda", + "precision": "float64", + "library_version": "2026.10.4.1", + "software": { + "PyAutoLens": "2026.10.4.1", + "PyAutoArray": "0123456789abcdef0123456789abcdef01234567", + "jax": "fixture" + } + }, + "id": "missing-gpu", + "method_id": "runtime-fixture-method", + "host": null, + "record_id": null, + "status": "not_measured", + "reason": "no GPU measurement", + "unknowns": { + "host": "no measurement" + } + } + ], + "hazards": [ + { + "id": "fixture-hazard", + "title": "Synthetic hazard", + "description": "Exercise linking a finding to a setup.", + "status": "unknown", + "applies_to": { + "setup_ids": [ + "imaging/delaunay/hst/reference" + ], + "library_versions": [ + "2026.10.4.1" + ], + "constraints": { + "precision": [ + "float64" + ] + }, + "limitations": "Synthetic exact setup only; no extrapolation." + }, + "evidence": [ + { + "path": "results/hazards/fixture.json" + } + ] + } + ], + "recommendations": [ + { + "id": "fixture-recommendation", + "title": "Synthetic recommendation", + "description": "Fixture for validating an evidence-backed recommendation.", + "applies_to": { + "setup_ids": [ + "imaging/delaunay/hst/reference" + ], + "library_versions": [ + "2026.10.4.1" + ], + "constraints": { + "precision": [ + "float64" + ] + }, + "limitations": "Synthetic exact setup only; no extrapolation." + }, + "record_ids": [ + "runtime-fixture" + ], + "validation": { + "status": "accepted", + "reason": "synthetic fixture only" + }, + "evidence": [ + { + "path": "wiki/fixture.md" + } + ] + } + ] +} diff --git a/tests/fixtures/unsupported_schema.json b/tests/fixtures/unsupported_schema.json index 0fbe8de..0d1594e 100644 --- a/tests/fixtures/unsupported_schema.json +++ b/tests/fixtures/unsupported_schema.json @@ -1,6 +1,6 @@ { "schema": "profiling-summary", - "version": 2, + "version": 99, "project": "fixture_profiling", "scope": "release-runtime", "generated_at": "2026-09-30T12:00:00Z", diff --git a/tests/test_catalogue.py b/tests/test_catalogue.py new file mode 100644 index 0000000..a0bdc6b --- /dev/null +++ b/tests/test_catalogue.py @@ -0,0 +1,223 @@ +"""Scientifically incompatible and malformed feeds cannot become references.""" + +import copy +import json + +import pytest +import yaml +from conftest import SHA_A, SHA_B, fixture_doc + +from pulse import board, ingest, registry, summary + +V2 = ("profiling-summary", 2) + + +@pytest.fixture +def doc(): + return fixture_doc("setup_summary_v2.json") + + +def test_multi_axis_catalogue_and_v1_coexist(doc): + assert summary.classify(doc, V2) == ("ok", []) + assert summary.classify(fixture_doc("lens_summary_v1.json"))[0] == "ok" + assert summary.classify(doc, ("profiling-summary", 1))[0] == "unsupported" + assert summary.pair(doc) == [] + assert summary.qualified_records(doc) == 4 + + +def test_empty_catalogue_is_valid_but_not_a_pass(doc): + for key in ("setups", "records", "selections", "hazards", "recommendations"): + doc[key] = [] + doc["coverage"] = { + "expected": {"cells": 0}, + "observed": {"setups": 0, "records": 0, "selected": 0}, + "excluded": [], + } + assert summary.classify(doc) == ("ok", []) + assert summary.qualified_records(doc) == 0 + + +@pytest.mark.parametrize("field", ["setups", "records", "selections", "hazards", "recommendations"]) +@pytest.mark.parametrize("bad", [None, {}, 7, "wrong", [None]]) +def test_catalogue_collections_are_validated_without_crashing(doc, field, bad): + doc[field] = bad + assert summary.classify(doc)[0] == "invalid" + + +@pytest.mark.parametrize("field", ["setups", "records", "selections", "hazards", "recommendations"]) +def test_duplicate_semantic_ids_are_rejected(doc, field): + doc[field].append(copy.deepcopy(doc[field][0])) + assert any("duplicate id" in e for e in summary.validate(doc)) + + +@pytest.mark.parametrize( + "path,value,needle", + [ + (("records", 0, "setup_id"), "nonexistent", "unknown reference"), + (("records", 0, "axis"), {}, "axis"), + (("records", 0, "unit"), "MiB", "unit"), + (("records", 0, "measurement", "single_call"), -1, "non-negative"), + (("records", 0, "measurement", "single_call"), True, "non-negative"), + (("records", 0, "measurement", "single_call"), None, "non-negative"), + (("records", 0, "measurement", "single_call"), float("nan"), "non-finite"), + (("records", 0, "measurement", "single_call"), float("inf"), "non-finite"), + (("records", 0, "method", "repetitions"), 0, "repetitions"), + (("records", 0, "method", "repetitions"), True, "repetitions"), + (("records", 0, "method", "cache_state"), None, "unknowns reason"), + (("records", 0, "provenance", "measured_at"), "2026-10-04", "measured_at"), + (("records", 0, "provenance", "qualified"), False, "qualified"), + (("records", 0, "provenance", "has_provenance"), False, "requires provenance"), + (("records", 0, "identity", "software"), {}, "software"), + (("records", 3, "metric"), "vram", "metric"), + (("selections", 0, "record_id"), "nonexistent", "unknown reference"), + (("selections", 0, "record_id"), None, "unknown reference"), + (("selections", 0, "axis"), "compile", "axis mismatch"), + (("selections", 0, "metric"), "batch_per_call", "metric mismatch"), + (("selections", 0, "method_id"), "different-warmup", "method mismatch"), + (("selections", 0, "host"), "other-host", "host mismatch"), + (("selections", 0, "identity", "precision"), "mixed", "identity mismatch"), + (("selections", 0, "identity", "library_version"), "2026.1.1", "identity mismatch"), + ( + ("selections", 0, "identity", "software", "PyAutoArray"), + "other-sha", + "identity mismatch", + ), + (("selections", 4, "record_id"), "runtime-fixture", "cannot select"), + (("selections", 4, "reason"), "", "reason"), + (("coverage", "expected", "cells"), 6, "declared selection count"), + (("coverage", "observed", "records"), 9, "catalogue contents"), + (("setups", 0, "configuration", "psf_shape", "value"), [float("inf"), 21], "non-finite"), + (("setups", 0, "configuration", "oversampling", "reason"), "", "reason"), + (("hazards", 0, "applies_to", "setup_ids"), [], "must not be empty"), + (("recommendations", 0, "record_ids"), ["missing"], "unknown reference"), + ( + ("recommendations", 0, "applies_to", "library_versions"), + ["2020.1.1"], + "outside applicable", + ), + ], +) +def test_bad_evidence_cannot_be_selected(doc, path, value, needle): + target = doc + for key in path[:-1]: + target = target[key] + target[path[-1]] = value + outcome, errors = summary.classify(doc) + assert outcome == "invalid" + assert any(needle in e for e in errors), errors + + +@pytest.mark.parametrize("field", ["records", "hazards", "recommendations"]) +@pytest.mark.parametrize( + "path", ["/private/x", "../x", "results/../x", "https://example.invalid/x", "results\\x"] +) +def test_unsafe_evidence_links_are_rejected(doc, field, path): + evidence = doc[field][0]["evidence"] + (evidence if field == "records" else evidence[0])["path"] = path + assert any("unsafe evidence" in e for e in summary.validate(doc)) + + +def test_two_records_cannot_compete_for_one_selection_slot(doc): + extra = copy.deepcopy(doc["selections"][0]) + extra["id"] = "different-label-same-slot" + doc["selections"].append(extra) + assert any("duplicate measurement slot" in e for e in summary.validate(doc)) + + +def test_selected_setup_cannot_change_solver_or_regularization(doc): + alternate = copy.deepcopy(doc["setups"][0]) + alternate.update(id="other-setup", configuration_id="other-configuration") + alternate["configuration"]["solver"]["value"] = "different-solver" + doc["setups"].append(alternate) + doc["selections"][0]["setup_id"] = alternate["id"] + assert any("setup_id mismatch" in e for e in summary.validate(doc)) + + +def test_legacy_evidence_can_be_unreviewed_but_not_promoted(doc): + r = doc["records"][0] + r["validation"] = {"status": "unreviewed", "reason": "legacy evidence"} + r["provenance"].update( + qualified=False, + has_provenance=False, + measured_at=None, + unknowns={"measured_at": "not recorded"}, + ) + doc["selections"][0]["status"] = "unreviewed" + doc["recommendations"][0]["validation"]["status"] = "unreviewed" + assert summary.validate(doc) == [] + doc["selections"][0]["status"] = "accepted" + assert any("validation status mismatch" in e for e in summary.validate(doc)) + + +def test_accepted_recommendation_cannot_rest_on_unreviewed_evidence(doc): + doc["records"][0]["validation"]["status"] = "unreviewed" + doc["selections"][0]["status"] = "unreviewed" + assert any("accepted supporting records" in e for e in summary.validate(doc)) + + +@pytest.mark.parametrize( + "schema,version", + [("profiling-summary", 3), ("profiling-summary", True), ([], 2), ("profiling-summary", {})], +) +def test_bad_versions_fail_closed_without_crashing(doc, schema, version): + doc.update(schema=schema, version=version) + assert summary.classify(doc)[0] == "unsupported" + + +def test_v2_receipts_render_and_preserve_last_good_snapshot( + doc, registry_file, fake_mind, web, tmp_path +): + config = yaml.safe_load(registry_file.read_text()) + config["instances"][0]["supported_schema"] = "profiling-summary@2" + registry_file.write_text(yaml.safe_dump(config)) + instance = registry.load(registry_file, mind=fake_mind)[0] + gh, path = "PyAutoLabs/autolens_profiling", "dashboard/summary.json" + web.publish(gh, SHA_A, path, doc) + good = ingest.ingest(instance, tmp_path, now="2026-10-05T12:00:00Z") + assert good.outcome == "ok" and good.commit == SHA_A + assert ingest.read_receipt(tmp_path, "lens")["version"] == 2 + assert board.render_html([good]) and board.render_markdown([good]) + before = json.dumps(good.doc, sort_keys=True) + doc["selections"][0]["record_id"] = "missing" + web.publish(gh, SHA_B, path, doc) + failed = ingest.ingest(instance, tmp_path, now="2026-10-05T13:00:00Z") + assert failed.outcome == "invalid" and failed.cached + assert failed.commit == SHA_A and failed.attempt_commit == SHA_B + assert json.dumps(failed.doc, sort_keys=True) == before + assert board.render_html([failed]) + + +@pytest.mark.parametrize("value", [None, [], {}, True, 0, "", float("nan")]) +def test_malformed_nested_fields_return_errors_not_exceptions(doc, value): + """A corrupt field must not crash ingestion and lose the last-good fallback.""" + paths = [] + + def walk(obj, prefix=()): + items = ( + obj.items() + if isinstance(obj, dict) + else enumerate(obj) + if isinstance(obj, list) + else [] + ) + for key, child in items: + paths.append((*prefix, key)) + walk(child, (*prefix, key)) + + walk(doc) + for path in paths: + changed = copy.deepcopy(doc) + target = changed + for key in path[:-1]: + target = target[key] + target[path[-1]] = value + outcome, errors = summary.classify(changed) + assert outcome in ("ok", "invalid", "unsupported"), (path, outcome, errors) + + +def test_method_ids_cannot_hide_different_measurement_procedures(doc): + other = copy.deepcopy(doc["records"][0]) + other["id"] = "other-run" + other["method"]["statistic"] = "minimum" + doc["records"].append(other) + assert any("conflicting definitions" in e for e in summary.validate(doc)) diff --git a/tests/test_summary.py b/tests/test_summary.py index 741e6f6..305230c 100644 --- a/tests/test_summary.py +++ b/tests/test_summary.py @@ -43,7 +43,7 @@ def test_valid_empty_feed_is_ok(): def test_unsupported_version_is_refused_not_validated(): outcome, errors = summary.classify(fixture_doc("unsupported_schema.json"), V1) assert outcome == "unsupported" - assert "version 2" in errors[0] + assert "version 99" in errors[0] def test_registered_schema_must_match():