Files
nvdriver/tools/_gpu_pmu_oracle_check.py

51 lines
1.8 KiB
Python

"""Shared non-elidable checks and read-only --check helpers for GPU PMU 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) -> str:
return json.dumps(json.loads(json.dumps(value)), 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")
if path.read_text() != 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 = 2,
) -> 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
if _canonical_json(payload) != _canonical_json(existing):
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")