frexp_ldexp_f16_mods_probe: harden CLI tokens, upfront atomic JSON writes, and result count guard

This commit is contained in:
IlyassRS
2026-11-25 07:52:45 +01:00
parent 42537e7b6f
commit 7e2c52a9cc
2 changed files with 211 additions and 16 deletions

View File

@ -358,6 +358,80 @@ class ProbeCliTests(unittest.TestCase):
self.assertEqual(rc, 77)
self.assertIn("unavailable", buf.getvalue())
def test_malformed_comma_tokens_and_empty_args_rejected_before_oracle(self):
for bad_args in (
["--ops", "v_frexp_mant_f16,"],
["--ops", ",v_frexp_mant_f16"],
["--ops", "v_frexp_mant_f16,,v_ldexp_f16"],
["--waves", "32,"],
["--waves", "32,,64"],
["--hw-arch", ""],
["--hw-arch", " "],
["--json", ""],
["--json", " "],
):
with self.subTest(args=bad_args):
with mock.patch.object(runner, "open_oracle") as open_mock, redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as cm:
pr.main(bad_args)
self.assertEqual(cm.exception.code, 2)
open_mock.assert_not_called()
def test_json_blocker_trailing_sep_and_atomic_write_report(self):
with tempfile.TemporaryDirectory() as d:
blocker = os.path.join(d, "blocker")
Path(blocker).write_bytes(b"keep")
with mock.patch.object(runner, "open_oracle") as open_mock, redirect_stderr(io.StringIO()) as err:
rc = pr.main(["--ops", "v_frexp_mant_f16", "--waves", "32", "--json", os.path.join(blocker, "r.json")])
self.assertEqual(rc, 2)
open_mock.assert_not_called()
self.assertIn("ERROR: cannot write", err.getvalue())
self.assertEqual(Path(blocker).read_bytes(), b"keep")
with mock.patch.object(runner, "open_oracle") as open_mock, redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as cm:
pr.main(["--ops", "v_frexp_mant_f16", "--waves", "32", "--json", os.path.join(d, "sub") + os.sep])
self.assertEqual(cm.exception.code, 2)
open_mock.assert_not_called()
out = os.path.join(d, "sub", "report.json")
self.assertTrue(pr.write_report(out, {"ok": 1}))
raw = Path(out).read_bytes()
self.assertTrue(raw.endswith(b"\n"))
self.assertNotIn(b"\r\n", raw)
with redirect_stderr(io.StringIO()):
self.assertFalse(pr.write_report(out, {"bad": float("nan")}))
self.assertEqual(json.loads(Path(out).read_text(encoding="utf-8")), {"ok": 1})
if hasattr(os, "symlink"):
real = os.path.join(d, "real.json")
link = os.path.join(d, "link.json")
Path(real).write_text("old", encoding="utf-8")
try:
os.symlink(real, link)
except OSError:
link = None
if link is not None:
self.assertTrue(pr.write_report(link, {"via": "link"}))
self.assertTrue(os.path.islink(link))
self.assertEqual(json.loads(Path(real).read_text(encoding="utf-8")), {"via": "link"})
if os.name == "posix" and os.path.exists("/dev/null"):
self.assertTrue(pr.write_report("/dev/null", {"ok": 1}))
def test_evaluate_results_count_mismatch_and_unknown_arch_family(self):
_, meta = pr.build_jobs(["v_frexp_mant_f16"], [32])
rep = pr.evaluate_results(["v_frexp_mant_f16"], [32], meta, [])
self.assertEqual(len(rep["harness_errors"]), 1)
self.assertIn("expected", rep["harness_errors"][0]["error"])
oracle = FakeOracle()
oracle.arch = "unknown_arch_999"
rc, out, _ = _run_main(oracle, "--ops", "v_frexp_mant_f16", "--waves", "32")
self.assertEqual(rc, 77, out)
self.assertTrue(oracle.closed)
if __name__ == "__main__":
unittest.main()

View File

@ -17,19 +17,24 @@ Exit 0 when all hardware results match the expected RDNA2 model with zero wave32
omod diffs; 1 on a mismatch or parity failure; 2 on a harness/CLI error; 77 when the hardware oracle is unavailable or
the GPU is not GFX10. Nothing here reads game files.
"""
import argparse
from dataclasses import dataclass
import json
import math
import os
import stat
import struct
import sys
import argparse
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
sys.dont_write_bytecode = True
if HERE not in sys.path:
sys.path.insert(0, HERE)
from file_mode import published_mode # noqa: E402
import replace_retry # noqa: E402
OPS: tuple[str, ...] = ("v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_ldexp_f16")
MODS: tuple[str, ...] = ("", "clamp", "mul:2", "mul:4", "div:2", "clamp mul:2", "clamp mul:4", "clamp div:2")
@ -289,6 +294,26 @@ def evaluate_results(ops: list[str], waves: list[int], meta, raw_results) -> dic
harness_errors: list[dict] = []
incomplete_result = False
seen_jobs: set[tuple[str, int] | tuple[str, int, str, str]] = set()
if len(raw_results) != len(meta):
return {
"total_words": 0,
"grid_words": 0,
"src_mod_words": 0,
"control_words": 0,
"mismatches": 0,
"wave_diffs": 0,
"omod_diffs": 0,
"harness_errors": [{
"kind": "batch",
"wave": 0,
"op": "*",
"mod": "count",
"error": f"expected {len(meta)} kernel results, got {len(raw_results)}",
}],
"first_mismatches": [],
"first_wave_diffs": [],
"first_omod_diffs": [],
}
for (kind, wave, op, mod, items), res in zip(meta, raw_results):
# Each non-grid job covers all selected ops for one wave.
@ -466,16 +491,93 @@ def evaluate_results(ops: list[str], waves: list[int], meta, raw_results) -> dic
}
def _has_trailing_sep(path: str) -> bool:
seps = tuple(s for s in (os.sep, os.altsep) if s)
return path.endswith(seps)
def _resolve_output_target(path: str) -> tuple[str, str]:
out_path = os.path.abspath(path)
target = os.path.realpath(out_path) if os.path.islink(out_path) else out_path
return out_path, target
def _check_json_writable(path: str) -> str | None:
"""Check non-directory parent blockers and existing unwritable targets before GPU work."""
_, target = _resolve_output_target(path)
parent = os.path.dirname(target)
probe = parent
while probe and not os.path.exists(probe):
nxt = os.path.dirname(probe)
if nxt == probe:
break
probe = nxt
if probe and os.path.exists(probe) and not os.path.isdir(probe):
return f"parent path is not a directory: {probe}"
if os.path.exists(target):
try:
fd = os.open(target, os.O_WRONLY)
os.close(fd)
except OSError as exc:
return exc.strerror or str(exc)
return None
def write_report(path: str, doc: dict) -> bool:
"""Write JSON report with LF line endings, creating parent folders."""
"""Write JSON report with LF line endings atomically, creating parent folders."""
if not isinstance(path, str) or not path.strip():
print("ERROR: cannot write empty --json path", file=sys.stderr)
return False
out_path, target = _resolve_output_target(path)
if _has_trailing_sep(path) or os.path.isdir(out_path) or os.path.isdir(target):
print(f"ERROR: cannot write {path}: path is a directory", file=sys.stderr)
return False
try:
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
with open(path, "w", encoding="utf-8", newline="\n") as f:
json.dump(doc, f, indent=1)
f.write("\n")
text = json.dumps(doc, indent=1, allow_nan=False) + "\n"
except (TypeError, ValueError) as exc:
print(f"ERROR: cannot serialize JSON report for {path}: {exc}", file=sys.stderr)
return False
try:
st = os.stat(target) if os.path.exists(target) else None
except OSError as exc:
print(f"ERROR: cannot write {path}: {exc}", file=sys.stderr)
return False
if st is not None and not stat.S_ISREG(st.st_mode):
try:
with open(target, "w", encoding="utf-8", newline="\n") as f:
f.write(text)
return True
except OSError as exc:
print(f"ERROR: cannot write {path}: {exc}", file=sys.stderr)
return False
parent = os.path.dirname(target)
tmp_path = None
try:
if parent:
os.makedirs(parent, exist_ok=True)
fd, tmp_path = tempfile.mkstemp(prefix=".frexp_ldexp_f16_mods_probe.", suffix=".tmp", dir=parent or ".")
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f:
f.write(text)
f.flush()
except Exception:
try:
os.close(fd)
except OSError:
pass
raise
os.chmod(tmp_path, published_mode(target))
replace_retry.replace(tmp_path, target)
tmp_path = None
except OSError as e:
print(f"ERROR: cannot write {path}: {e}", file=sys.stderr)
return False
finally:
if tmp_path is not None:
try:
os.unlink(tmp_path)
except OSError:
pass
return True
@ -546,16 +648,31 @@ def main(argv=None) -> int:
if a.self_test:
return self_test()
ops = [o.strip() for o in a.ops.split(",") if o.strip()]
wave_tokens = [w.strip() for w in a.waves.split(",") if w.strip()]
raw_ops = [o.strip() for o in a.ops.split(",")]
raw_waves = [w.strip() for w in a.waves.split(",")]
if not raw_ops or any(not o for o in raw_ops):
ap.error(f"empty or malformed --ops: {a.ops!r}")
if not raw_waves or any(not w for w in raw_waves):
ap.error(f"empty or malformed --waves: {a.waves!r}")
ops = list(dict.fromkeys(raw_ops))
wave_tokens = list(dict.fromkeys(raw_waves))
bad_ops = [o for o in ops if o not in OPS]
bad_waves = [w for w in wave_tokens if w not in ("32", "64")]
if bad_ops or bad_waves or not ops or not wave_tokens:
ap.error("unknown or empty: " + ", ".join(bad_ops + bad_waves or ["--ops/--waves"]))
ops = list(dict.fromkeys(ops))
waves = list(dict.fromkeys(int(w) for w in wave_tokens))
if a.json and os.path.isdir(a.json):
ap.error(f"--json {a.json} is a folder, not a file")
if bad_ops or bad_waves:
ap.error("unknown: " + ", ".join(bad_ops + bad_waves))
waves = [int(w) for w in wave_tokens]
if a.hw_arch is not None and not a.hw_arch.strip():
ap.error("--hw-arch must not be empty")
if a.json is not None:
if not a.json.strip():
ap.error("--json path must not be empty")
out_path, target = _resolve_output_target(a.json)
if _has_trailing_sep(a.json) or os.path.isdir(out_path) or os.path.isdir(target):
ap.error(f"--json {a.json} is a folder, not a file")
werr = _check_json_writable(a.json)
if werr:
print(f"ERROR: cannot write {a.json}: {werr}", file=sys.stderr)
return 2
from hw_oracle import asm, runner
@ -566,7 +683,11 @@ def main(argv=None) -> int:
return 77
try:
if asm.family(oracle.arch) != "gfx10":
try:
fam = asm.family(oracle.arch)
except ValueError:
fam = None
if fam != "gfx10":
print(f"hardware oracle unavailable: {oracle.arch} is not GFX10")
return 77
print(f"hardware oracle: {oracle.device} ({oracle.arch})")
@ -587,7 +708,7 @@ def main(argv=None) -> int:
"mods": list(MODS),
**summary,
}
if a.json and not write_report(a.json, report):
if a.json is not None and not write_report(a.json, report):
return 2
if summary["harness_errors"]: