"""Strict adapter for the inspected CUDA result-row population.""" import hashlib import json import math import re from datetime import datetime UNITS = { "time_ms": "ms", "bandwidth_gb_s": "GB/s", "share_of_measured_peak": "fraction", "tflops": "TFLOP/s", "measured_device_peak_gb_s": "GB/s", "per_launch_us": "us", "per_layer_sync_us": "us", "compute_slowdown_with_copy": "fraction", "copies_per_compute_window": "count", "control_drift": "fraction", } class EvidenceError(ValueError): """Evidence cannot be rendered safely or interpreted under this adapter.""" def finite_number(value, label): if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): raise EvidenceError(f"{label}: expected a finite number") return value def validate_row(row: dict, run_id: str) -> dict: if not isinstance(row, dict) or any(k not in row for k in ("run", "arm", "field", "unit", "tag", "source")): raise EvidenceError("Missing result-row contract fields") if row["run"] != run_id: raise EvidenceError("Mixed run populations are not supported") if not isinstance(row["field"], str) or row["field"] not in UNITS or row["unit"] != UNITS[row["field"]]: raise EvidenceError("Unknown metric or inconsistent unit") for field in ("arm", "source"): if not isinstance(row[field], str) or not row[field] or len(row[field]) > 300: raise EvidenceError("Invalid result identity") if row["tag"] not in ("measured", "derived", "unavailable"): raise EvidenceError("Unsupported evidence classification") value = row.get("value") if row["tag"] == "unavailable": if value is not None or not isinstance(row.get("note"), str) or not row["note"]: raise EvidenceError("Unavailable values require a reason and no numeric value") else: finite_number(value, "value") if value < 0 and row["field"] not in ("compute_slowdown_with_copy", "control_drift"): raise EvidenceError("Negative magnitude") if row["field"] == "time_ms" and row["tag"] == "derived": raise EvidenceError("Timing must retain its measured classification") if row["field"] != "time_ms" and row["tag"] == "measured": raise EvidenceError("Calculated metrics must retain their derived classification") for field in ("p50", "p95", "ci_low", "ci_high", "overhead_ms"): if row.get(field) is not None and finite_number(row[field], field) < 0: raise EvidenceError("Negative timing statistic") if "n" in row and (type(row["n"]) is not int or not 1 <= row["n"] <= 1000): raise EvidenceError("Invalid sample count") if row["tag"] == "measured": if row.get("p50") != value or "n" not in row: raise EvidenceError("Measured timing requires matching median and sample count") if row.get("p95", value) < value: raise EvidenceError("p95 precedes p50") if row.get("ci_low") is not None and row.get("ci_high") is not None: if row["ci_low"] > row["ci_high"]: raise EvidenceError("Reversed confidence interval") return row def validate_manifest_document(doc: dict, kind: str) -> None: if (doc.get("schema") != "cuda-manifest" or doc.get("schema_version") != 1 or doc.get("kind") != kind or doc.get("platform") != "cuda"): raise EvidenceError("Unsupported CUDA manifest") body = {k: v for k, v in doc.items() if k != "manifest_id"} expected = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()).hexdigest()[:16] if doc.get("manifest_id") != expected: raise EvidenceError("Manifest content identity mismatch") try: datetime.fromisoformat(doc["created_utc"].replace("Z", "+00:00")) text_values = [doc["code"]["git"]["sha"]] if kind == "machine": text_values.extend([doc["gpu"]["framework_view"]["name"], doc["host"]["python"], doc["software"]["torch"]["version"], doc["software"]["driver"]["driver_version"]]) else: text_values.extend([doc["run_id"], doc["machine_manifest_id"], doc["instrument"]["version"]]) if not all(isinstance(value, str) and value for value in text_values): raise EvidenceError("Missing provenance identity") except (KeyError, TypeError, AttributeError, ValueError) as error: raise EvidenceError("Incomplete manifest provenance") from error def parse_copy_arm(arm: str): """Only ordinary copy cells; paired control cells never enter comparison curves.""" match = re.fullmatch(r"copy\.(h2d|d2h)\.(pinned|pageable)\.(\d+)\|(events|host)", arm) if not match: return None direction, backing, size, timer = match.groups() return {"direction": direction, "backing": backing, "bytes": int(size), "timer": timer}