mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
63 lines
2.3 KiB
Python
63 lines
2.3 KiB
Python
"""Shared non-elidable checks and read-only --check helpers for ACR and Falcon 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_bytes(path: Path, data: bytes, *, check: bool) -> None:
|
|
"""Write binary `data` to `path` (creating parents), or verify equality without touching disk."""
|
|
if check:
|
|
if not path.is_file():
|
|
raise SystemExit(f"{path}: missing binary artifact in --check mode")
|
|
if path.read_bytes() != data:
|
|
raise SystemExit(f"{path}: binary artifact drift detected")
|
|
return
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_bytes(data)
|
|
|
|
|
|
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")
|