# SPDX-License-Identifier: CC0-1.0 """Controlled integer-conversion observations, not a storage benchmark.""" import argparse import hashlib import json import os from pathlib import Path import platform import subprocess import sys import tempfile from datetime import datetime, timezone import h5py import numpy as np CASES = [ ("signed-narrow", "i8", "i2", [-40000, -32768, -1, 0, 32767, 32768, 40000]), ("signed-to-unsigned", "i8", "u2", [-1, 0, 1, 65534, 65535, 65536, 70000]), ("unsigned-to-signed", "u8", "i8", [0, 1, 2**53 + 1, 2**63 - 1, 2**63, 2**64 - 1]), ("unsigned-narrow", "u8", "u2", [0, 1, 65535, 65536, 2**53 + 1, 2**64 - 1]), ("in-range-narrow", "i8", "i2", [-32768, -1, 0, 1, 32767]), ("widen-control", "i2", "i8", [-32768, -1, 0, 1, 32767]), ] def sha256(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def array_record(array): array = np.ascontiguousarray(array) return { "dtype": array.dtype.str, "shape": list(array.shape), # Decimal strings avoid rounding uint64 values in JSON consumers. "decimal": [str(int(value)) for value in array.flat], "hexBytes": array.tobytes().hex(), "sha256": hashlib.sha256(array.tobytes()).hexdigest(), } def checked_integer_cast(array, dtype): """Value-based check for integer arrays only; no float promotion.""" array = np.asarray(array) dtype = np.dtype(dtype) if array.dtype.kind not in "iu" or dtype.kind not in "iu": raise TypeError("only integer-to-integer conversion is supported") limits = np.iinfo(dtype) if array.size and (int(array.min()) < int(limits.min) or int(array.max()) > int(limits.max)): raise ValueError("source values exceed destination integer range") return array.astype(dtype) def attempt(call): try: return {"status": "ok", "array": array_record(call())} except (TypeError, ValueError, OSError) as error: return {"status": "error", "type": type(error).__name__, "message": str(error)} def read_fixture(path, target): before = sha256(path) with h5py.File(path, "r", rdcc_nbytes=0) as file: dataset = file["values"] original = dataset[:] direct = np.empty(dataset.shape, dtype=target) dataset.read_direct(direct) plist = dataset.id.get_create_plist() filters = [int(plist.get_filter(i)[0]) for i in range(plist.get_nfilters())] chunk = dataset.id.get_chunk_info_by_coord((0,)) result = { "fileDtype": dataset.dtype.str, "filters": filters, "chunkMask": int(chunk.filter_mask), "chunkOffset": int(chunk.byte_offset), "chunkBytes": int(chunk.size), "native": array_record(original), "hdf5Astype": array_record(dataset.astype(target)[:]), "readDirect": array_record(direct), "numpyAstype": array_record(original.astype(target)), "numpySafe": attempt(lambda: original.astype(target, casting="safe")), "checked": attempt(lambda: checked_integer_cast(original, target)), } result["fileSha256Before"] = before result["fileSha256After"] = sha256(path) return result def worker(directory, target): return {name: read_fixture(Path(directory) / (name + ".h5"), target) for name in ("original", "hdf5-write", "numpy-write")} def damaged_control(path, offset): # This function is called only on disposable experiment files after all reads. before = sha256(path) with open(path, "r+b") as stream: stream.seek(offset) old = stream.read(1) if len(old) != 1: raise RuntimeError("chunk offset outside fixture") stream.seek(offset) stream.write(bytes([old[0] ^ 1])) with h5py.File(path, "r", rdcc_nbytes=0) as file: outcome = attempt(lambda: file["values"][:]) return { "bitFlip": {"offset": offset, "xor": 1}, "fileSha256Before": before, "fileSha256After": sha256(path), "read": outcome, } def run_case(case, byte_order): name, source_type, target_type, values = case source = np.array(values, dtype=source_type) target = np.dtype(byte_order + target_type) with tempfile.TemporaryDirectory(prefix="hesela-hdf5-conversion-") as tmp: original_bytes = source.tobytes() payloads = [ ("original", source, np.dtype(byte_order + source_type)), ("hdf5-write", source, target), ("numpy-write", source.astype(target), target), ] for label, payload, file_type in payloads: with h5py.File(Path(tmp) / (label + ".h5"), "w", libver=("v110", "v110")) as file: file.create_dataset("values", data=payload, dtype=file_type, chunks=(len(source),), fletcher32=True, track_times=False) if source.tobytes() != original_bytes: raise RuntimeError("input array was mutated") completed = subprocess.run( [sys.executable, str(Path(__file__).resolve()), "--worker", tmp, "--target", target.str], capture_output=True, text=True, check=True, timeout=30, ) reads = json.loads(completed.stdout) damage = { label: damaged_control(Path(tmp) / (label + ".h5"), row["chunkOffset"]) for label, row in reads.items() } return { "case": name, "byteOrder": byte_order, "input": array_record(source), "targetDtype": target.str, "freshProcessReads": reads, "damageControls": damage, } def observe(repetitions=3): if not 1 <= repetitions <= 10: raise ValueError("repetitions must be between 1 and 10") rows = [] for repetition in range(1, repetitions + 1): for case in CASES: for byte_order in ("<", ">"): rows.append({"repetition": repetition, **run_case(case, byte_order)}) return { "schemaVersion": 1, "kind": "controlled-library-observation", "generatedAt": datetime.now(timezone.utc).isoformat(), "license": "CC0-1.0", "runnerSha256": sha256(__file__), "environment": { "python": platform.python_version(), "h5py": h5py.__version__, "hdf5": h5py.version.hdf5_version, "numpy": np.__version__, "machine": platform.machine(), "system": platform.system(), "byteOrder": sys.byteorder, }, "design": { "cases": len(CASES), "fileByteOrders": ["little", "big"], "repetitions": repetitions, "filesPerSequence": 3, "filterIds": [3], "filterName": "Fletcher32", "lossyFilter": False, "completeChunk": True, "formatBounds": ["v110", "v110"], "readCacheBytes": 0, "reader": "new Python process after all writers close", "integerEncoding": "exact decimal strings", }, "observations": rows, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path) parser.add_argument("--repetitions", type=int, default=3) parser.add_argument("--worker", type=Path, help=argparse.SUPPRESS) parser.add_argument("--target", help=argparse.SUPPRESS) args = parser.parse_args() if args.worker: print(json.dumps(worker(args.worker, args.target), allow_nan=False)) return if not args.output: parser.error("--output is required") if args.output.exists(): parser.error("refusing to overwrite existing output") result = observe(args.repetitions) with args.output.open("x", encoding="utf-8") as stream: json.dump(result, stream, indent=2, allow_nan=False) stream.write("\n") if __name__ == "__main__": main()