Files
nvdriver/tools/_gpu_graphics_oracle_check.py

64 lines
2.3 KiB
Python

"""Shared non-elidable checks and read-only --check helpers for GPU graphics binary oracles."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
def require(condition: bool, detail: Any = None) -> None:
"""Enforce an oracle invariant even under `python3 -O`."""
if not condition:
raise AssertionError("oracle check failed" if detail is None else str(detail))
def _canonical_json(value: Any, *, normalize_original_basename: bool = False) -> str:
normalized = json.loads(json.dumps(value))
if normalize_original_basename and isinstance(normalized, dict):
orig = normalized.get("original")
if isinstance(orig, str) and orig:
normalized["original"] = Path(orig).name
return json.dumps(normalized, sort_keys=True, separators=(",", ":"))
def write_or_check_text(path: Path, text: str, *, check: bool) -> None:
"""Write `text` to `path` (creating parents), or verify equality without touching disk."""
if check:
if not path.is_file():
raise SystemExit(f"{path}: missing oracle file in --check mode")
existing = path.read_text()
if existing != text:
raise SystemExit(f"{path}: oracle content drift detected")
return
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
def write_or_check_json(
path: Path,
payload: dict[str, Any],
*,
check: bool,
indent: int = 1,
normalize_original_basename: bool = False,
) -> None:
"""Write JSON report to `path`, or verify canonical JSON equality without touching disk."""
if check:
if not path.is_file():
raise SystemExit(f"{path}: missing report file in --check mode")
try:
existing = json.loads(path.read_text())
except ValueError as exc:
raise SystemExit(f"{path}: invalid JSON in existing report: {exc}") from exc
got = _canonical_json(
payload, normalize_original_basename=normalize_original_basename
)
want = _canonical_json(
existing, normalize_original_basename=normalize_original_basename
)
if got != want:
raise SystemExit(f"{path}: report drift detected")
return
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=indent) + "\n")