65 lines
2.7 KiB
Python
65 lines
2.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Convert a private global PLE row trace into one KAR part's local batches."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--trace", required=True, type=Path)
|
|
parser.add_argument("--part-start", required=True, type=int)
|
|
parser.add_argument("--part-rows", required=True, type=int)
|
|
parser.add_argument("--output", required=True, type=Path)
|
|
args = parser.parse_args()
|
|
if args.part_start < 0 or args.part_rows < 1 or args.part_start + args.part_rows > 2**32:
|
|
parser.error("part bounds must fit global u32 row IDs")
|
|
if args.output.exists():
|
|
parser.error("output already exists; choose a new private path")
|
|
|
|
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
if hasattr(os, "O_NOFOLLOW"):
|
|
flags |= os.O_NOFOLLOW
|
|
fd = os.open(args.output, flags, 0o600)
|
|
tokens = batches = accesses = 0
|
|
output_hash = hashlib.sha256()
|
|
try:
|
|
with args.trace.open() as source, os.fdopen(fd, "w") as output:
|
|
header = f"# KAR part global rows [{args.part_start},{args.part_start + args.part_rows})\n"
|
|
output.write(header)
|
|
output_hash.update(header.encode())
|
|
for number, line in enumerate(source, 1):
|
|
if not line.strip() or line.startswith("#"):
|
|
continue
|
|
try:
|
|
global_rows = [int(field) for field in line.split()]
|
|
except ValueError as exc:
|
|
raise ValueError(f"invalid trace row on line {number}") from exc
|
|
if len(global_rows) != 16 or any(row < 0 or row > 0xFFFFFFFF for row in global_rows):
|
|
raise ValueError(f"expected sixteen global u32 rows on line {number}")
|
|
tokens += 1
|
|
local = [row - args.part_start for row in global_rows
|
|
if args.part_start <= row < args.part_start + args.part_rows]
|
|
if local:
|
|
text = " ".join(map(str, local)) + "\n"
|
|
output.write(text)
|
|
output_hash.update(text.encode())
|
|
batches += 1
|
|
accesses += len(local)
|
|
print(json.dumps({
|
|
"tokens": tokens, "batches": batches, "row_accesses": accesses,
|
|
"part_start": args.part_start, "part_rows": args.part_rows,
|
|
"input_sha256": hashlib.sha256(args.trace.read_bytes()).hexdigest(),
|
|
"output_sha256": output_hash.hexdigest(),
|
|
}))
|
|
except BaseException:
|
|
args.output.unlink(missing_ok=True)
|
|
raise
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|