upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorkirigayakazima <46666711+kirigayakazima@users.noreply.github.com>2026-11-25 21:08:25 +0800
committerkirigayakazima <46666711+kirigayakazima@users.noreply.github.com>2026-11-25 21:08:25 +0800
commit71c86830f58db2b70b35570689a68d60bece8fde (patch)
tree07a2c3c14a28e21221ba59c87c48a317bfeadcb2
parent98c2f7777276f83eb90b491a51721ef90a43ea73 (diff)
tools/int_hw_probe: write --json atomically and reject trailing-separator paths
-rw-r--r--tests/test_int_hw_probe.py54
-rw-r--r--tools/int_hw_probe.py39
2 files changed, 86 insertions, 7 deletions
diff --git a/tests/test_int_hw_probe.py b/tests/test_int_hw_probe.py
index 89a3b2d07..b59ff5c64 100644
--- a/tests/test_int_hw_probe.py
+++ b/tests/test_int_hw_probe.py
@@ -148,13 +148,65 @@ class IntHwProbeTests(unittest.TestCase):
148 jpath = os.path.join(tmp, "out.json") 148 jpath = os.path.join(tmp, "out.json")
149 out, err = io.StringIO(), io.StringIO() 149 out, err = io.StringIO(), io.StringIO()
150 with unittest.mock.patch.object(probe, "run_translator", return_value={"s_bfe_i32_past31": [0], "s_bfe_u32_past31": [0], "s_bfe_i32_width0": [0]}), \ 150 with unittest.mock.patch.object(probe, "run_translator", return_value={"s_bfe_i32_past31": [0], "s_bfe_u32_past31": [0], "s_bfe_i32_width0": [0]}), \
151 unittest.mock.patch("builtins.open", side_effect=OSError("disk full")), \ 151 unittest.mock.patch.object(probe.json, "dump", side_effect=OSError("disk full")), \
152 redirect_stdout(out), redirect_stderr(err): 152 redirect_stdout(out), redirect_stderr(err):
153 rc = probe.main(["--oracle", "translator", "--group", "salu_bfe_past31", "--json", jpath]) 153 rc = probe.main(["--oracle", "translator", "--group", "salu_bfe_past31", "--json", jpath])
154 self.assertEqual(rc, 2) 154 self.assertEqual(rc, 2)
155 self.assertIn("ERROR:", err.getvalue()) 155 self.assertIn("ERROR:", err.getvalue())
156 self.assertIn("disk full", err.getvalue()) 156 self.assertIn("disk full", err.getvalue())
157 157
158 def test_json_preflight_rejects_trailing_separators(self):
159 with tempfile.TemporaryDirectory() as tmp:
160 for bad in (os.path.join(tmp, "out.json") + os.sep, os.path.join(tmp, "out.json") + "/", "/"):
161 with self.subTest(json_path=bad):
162 err = io.StringIO()
163 with unittest.mock.patch.object(probe, "run_translator", side_effect=AssertionError("ran translator")), \
164 unittest.mock.patch.object(hw_runner, "open_oracle", side_effect=AssertionError("opened oracle")), \
165 redirect_stderr(err):
166 rc = probe.main(["--oracle", "both", "--group", "salu_bfe_past31", "--json", bad])
167 self.assertEqual(rc, 2)
168 self.assertIn("ERROR:", err.getvalue())
169
170 def test_json_write_failure_preserves_existing_file_and_cleans_staging(self):
171 fake_tr = {"s_bfe_i32_past31": [0], "s_bfe_u32_past31": [0], "s_bfe_i32_width0": [0]}
172 with tempfile.TemporaryDirectory() as tmp:
173 jpath = os.path.join(tmp, "existing.json")
174 Path(jpath).write_text('{"keep": true}\n', encoding="utf-8", newline="\n")
175 out, err = io.StringIO(), io.StringIO()
176 with unittest.mock.patch.object(probe, "run_translator", return_value=fake_tr), \
177 unittest.mock.patch.object(probe.json, "dump", side_effect=OSError("disk full")), \
178 redirect_stdout(out), redirect_stderr(err):
179 rc = probe.main(["--oracle", "translator", "--group", "salu_bfe_past31", "--json", jpath])
180 self.assertEqual(rc, 2)
181 self.assertEqual(Path(jpath).read_text(encoding="utf-8"), '{"keep": true}\n')
182 self.assertEqual([n for n in os.listdir(tmp) if n.startswith(".int-hw-probe-")], [])
183
184 def test_json_publish_uses_replace_retry_and_cleans_on_failure(self):
185 fake_tr = {"s_bfe_i32_past31": [0], "s_bfe_u32_past31": [0], "s_bfe_i32_width0": [0]}
186 with tempfile.TemporaryDirectory() as tmp:
187 jpath = os.path.join(tmp, "existing.json")
188 Path(jpath).write_text('{"keep": true}\n', encoding="utf-8", newline="\n")
189 out, err = io.StringIO(), io.StringIO()
190 with unittest.mock.patch.object(probe, "run_translator", return_value=fake_tr), \
191 unittest.mock.patch.object(probe.replace_retry, "replace", side_effect=PermissionError("locked")), \
192 redirect_stdout(out), redirect_stderr(err):
193 rc = probe.main(["--oracle", "translator", "--group", "salu_bfe_past31", "--json", jpath])
194 self.assertEqual(rc, 2)
195 self.assertEqual(Path(jpath).read_text(encoding="utf-8"), '{"keep": true}\n')
196 self.assertEqual([n for n in os.listdir(tmp) if n.startswith(".int-hw-probe-")], [])
197
198 out2 = io.StringIO()
199 with unittest.mock.patch.object(probe, "run_translator", return_value=fake_tr), \
200 unittest.mock.patch.object(probe.replace_retry, "replace", wraps=probe.replace_retry.replace) as spy_replace, \
201 redirect_stdout(out2):
202 rc2 = probe.main(["--oracle", "translator", "--group", "salu_bfe_past31", "--json", jpath])
203 self.assertEqual(rc2, 0)
204 spy_replace.assert_called_once()
205 raw = Path(jpath).read_text(encoding="utf-8")
206 self.assertTrue(raw.endswith("\n"))
207 self.assertEqual(json.loads(raw)["waves"], [32, 64])
208 self.assertEqual([n for n in os.listdir(tmp) if n.startswith(".int-hw-probe-")], [])
209
158 210
159# v_bfe_u32 / v_bfe_i32 words measured natively on an AMD Radeon 610M (gfx1036, RDNA2), wave32 and wave64 identical: 211# v_bfe_u32 / v_bfe_i32 words measured natively on an AMD Radeon 610M (gfx1036, RDNA2), wave32 and wave64 identical:
160# `python -I tools/int_hw_probe.py --oracle both --group valu_bfe_past31`. A field that would run past bit 31 stops 212# `python -I tools/int_hw_probe.py --oracle both --group valu_bfe_past31`. A field that would run past bit 31 stops
diff --git a/tools/int_hw_probe.py b/tools/int_hw_probe.py
index c76b65978..467fbfb6d 100644
--- a/tools/int_hw_probe.py
+++ b/tools/int_hw_probe.py
@@ -57,7 +57,9 @@ for p in (HERE, os.path.join(ROOT, "tests", "semantic")):
57 sys.path.insert(0, p) 57 sys.path.insert(0, p)
58 58
59import rdna2spirv # noqa: E402 59import rdna2spirv # noqa: E402
60import replace_retry # noqa: E402
60import spirv_mini_interp # noqa: E402 61import spirv_mini_interp # noqa: E402
62from file_mode import published_mode # noqa: E402
61 63
62STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) 64STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
63SENTINEL = 0x5A5A5A5A 65SENTINEL = 0x5A5A5A5A
@@ -877,6 +879,8 @@ def _validate_json_out(raw_path):
877 """Validate --json output path before running translator/hardware cases; return (abs_path, err_msg).""" 879 """Validate --json output path before running translator/hardware cases; return (abs_path, err_msg)."""
878 if not raw_path.strip(): 880 if not raw_path.strip():
879 return None, "ERROR: --json path must not be empty" 881 return None, "ERROR: --json path must not be empty"
882 if raw_path.endswith(os.sep) or (os.altsep and raw_path.endswith(os.altsep)):
883 return None, f"ERROR: --json path must name a file, not a directory: {raw_path}"
880 out_path = os.path.abspath(raw_path) 884 out_path = os.path.abspath(raw_path)
881 if os.path.isdir(out_path): 885 if os.path.isdir(out_path):
882 return None, f"ERROR: --json path is a directory: {out_path}" 886 return None, f"ERROR: --json path is a directory: {out_path}"
@@ -893,6 +897,34 @@ def _validate_json_out(raw_path):
893 return out_path, None 897 return out_path, None
894 898
895 899
900def _write_json_atomic(path, payload):
901 dest = os.path.realpath(path)
902 parent = os.path.dirname(dest)
903 if parent:
904 os.makedirs(parent, exist_ok=True)
905 fd, tmp = tempfile.mkstemp(dir=parent or ".", prefix=".int-hw-probe-", suffix=".tmp")
906 try:
907 try:
908 f = os.fdopen(fd, "w", encoding="utf-8", newline="\n")
909 except BaseException:
910 os.close(fd)
911 raise
912 with f:
913 json.dump(payload, f, indent=2)
914 f.write("\n")
915 f.flush()
916 os.fsync(f.fileno())
917 os.chmod(tmp, published_mode(dest))
918 replace_retry.replace(tmp, dest)
919 except BaseException:
920 try:
921 os.chmod(tmp, 0o600)
922 os.unlink(tmp)
923 except OSError:
924 pass
925 raise
926
927
896def main(argv=None): 928def main(argv=None):
897 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) 929 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
898 ap.add_argument("--oracle", choices=("translator", "hw", "both"), default="translator") 930 ap.add_argument("--oracle", choices=("translator", "hw", "both"), default="translator")
@@ -993,12 +1025,7 @@ def main(argv=None):
993 1025
994 if out_path is not None: 1026 if out_path is not None:
995 try: 1027 try:
996 parent = os.path.dirname(out_path) 1028 _write_json_atomic(out_path, {"device": hw_device, "waves": list(waves), "cases": records})
997 if parent:
998 os.makedirs(parent, exist_ok=True)
999 with open(out_path, "w", encoding="utf-8", newline="\n") as f:
1000 json.dump({"device": hw_device, "waves": list(waves), "cases": records}, f, indent=2)
1001 f.write("\n")
1002 except OSError as e: 1029 except OSError as e:
1003 print(f"ERROR: failed to write --json {out_path}: {e}", file=sys.stderr) 1030 print(f"ERROR: failed to write --json {out_path}: {e}", file=sys.stderr)
1004 return 2 1031 return 2