#!/usr/bin/env python3 # SPDX-License-Identifier: CC0-1.0 """Observe prefix versus complete streaming reads on disposable Parquet fixtures.""" import argparse import datetime import hashlib import json from pathlib import Path import platform import struct import tempfile import pyarrow as pa import pyarrow.parquet as pq VERSION = "21.0.0" ROWS = 128 GROUP = 32 FAULT_ROW = 81 CASES = ("first-batch", "all-checked", "id-only", "all-unchecked") def require(condition, message): if not condition: raise ValueError(message) def sha(data): return hashlib.sha256(data).hexdigest() def corrupt(raw, start, size): needle = struct.pack("<32q", *range(100064, 100096)) chunk = raw[start:start + size] require(chunk.count(needle) == 1, "Expected one complete third-group payload") offset = start + chunk.index(needle) + (FAULT_ROW - 64) * 8 changed = bytearray(raw) changed[offset] ^= 1 require(sum((a ^ b).bit_count() for a, b in zip(raw, changed)) == 1, "Expected exactly one changed bit") return bytes(changed), offset def complete_value_check(row): return (row["exhausted"] and row["error"] is None and row["columns"] == ["id", "measurement"] and row["consumedRows"] == ROWS and not row["mismatches"]) def observe(path, case, size, damaged, repetition): require(case in CASES, "Unknown operation") require(type(size) is int and size in (16, 64), "Unsupported batch size") columns = ["id"] if case == "id-only" else ["id", "measurement"] verify = case != "all-unchecked" row = {"repetition": repetition, "case": case, "damaged": damaged, "batchSize": size, "columns": columns, "checksumVerification": verify, "consumedRows": 0, "batches": [], "maxYieldedBatchNbytes": 0, "exhausted": False, "mismatches": [], "error": None} with pq.ParquetFile(path, page_checksum_verification=verify, pre_buffer=False, memory_map=False) as reader: iterator = reader.iter_batches(batch_size=size, columns=columns, use_threads=False) try: for batch in iterator: require(batch.schema.names == columns, "Unexpected projected columns") require(0 < batch.num_rows <= size, "Unexpected batch size") data = batch.to_pydict() offset = row["consumedRows"] for column, values in data.items(): require(len(values) == batch.num_rows, "Incomplete batch values") for local, actual in enumerate(values): index = offset + local require(index < ROWS, "Extra row") expected = index + (100000 if column == "measurement" else 0) if actual != expected: row["mismatches"].append({"column": column, "row": index, "expected": expected, "actual": actual}) row["batches"].append({"rows": batch.num_rows, "nbytes": batch.nbytes}) row["maxYieldedBatchNbytes"] = max(row["maxYieldedBatchNbytes"], batch.nbytes) row["consumedRows"] += batch.num_rows if case == "first-batch": break else: row["exhausted"] = True except OSError as exc: require("CRC checksum verification failed" in str(exc), "Unexpected read error") row["error"] = {"type": type(exc).__name__, "message": str(exc)} finally: iterator.close() row["completeValueCheck"] = complete_value_check(row) row["outcome"] = ("checksum-error" if row["error"] else "exhausted" if row["exhausted"] else "stopped-after-first-batch") return row def validate(row): case, damaged, size = row["case"], row["damaged"], row["batchSize"] expected_error = damaged and case == "all-checked" require(bool(row["error"]) == expected_error, "Unexpected CRC outcome") expected_rows = size if case == "first-batch" else 64 if expected_error else ROWS require(row["consumedRows"] == expected_rows, "Unexpected consumed prefix") require(row["exhausted"] == (case != "first-batch" and not expected_error), "Unexpected exhaustion") mismatches = ([{"column": "measurement", "row": FAULT_ROW, "expected": 100081, "actual": 100080}] if damaged and case == "all-unchecked" else []) require(row["mismatches"] == mismatches, "Unexpected value comparison") require(row["completeValueCheck"] == (not damaged and case in ("all-checked", "all-unchecked")), "Unexpected completeness classification") require(sum(b["rows"] for b in row["batches"]) == expected_rows, "Batch accounting mismatch") def experiment(repetitions=3): require(pa.__version__ == VERSION and pa.cpp_version == VERSION, "Use PyArrow 21.0.0") require(type(repetitions) is int and 1 <= repetitions <= 20, "Repeats must be 1..20") original = {"id": list(range(ROWS)), "measurement": list(range(100000, 100000 + ROWS))} schema = pa.schema([pa.field(n, pa.int64(), nullable=False) for n in original]) table = pa.Table.from_pydict(original, schema=schema) observations, fixtures = [], [] with tempfile.TemporaryDirectory(prefix="hesela-parquet-stream-") as temporary: for repetition in range(1, repetitions + 1): clean, bad = (Path(temporary) / n for n in ("clean.parquet", "damaged.parquet")) pq.write_table(table, clean, row_group_size=GROUP, compression="NONE", use_dictionary=False, write_page_checksum=True, write_statistics=True, data_page_version="1.0") metadata = pq.read_metadata(clean) require(metadata.num_rows == ROWS and metadata.num_row_groups == 4, "Unexpected file shape") require(all(metadata.row_group(i).num_rows == GROUP for i in range(4)), "Unexpected group shape") column = metadata.row_group(2).column(1) raw = clean.read_bytes() changed, offset = corrupt(raw, column.data_page_offset, column.total_compressed_size) footer_start = len(raw) - 8 - int.from_bytes(raw[-8:-4], "little") require(offset < footer_start and raw[footer_start:] == changed[footer_start:], "Footer changed") bad.write_bytes(changed) fixtures.append({"repetition": repetition, "fileBytes": len(raw), "faultRow": FAULT_ROW, "byteOffset": offset, "xorMask": 1, "footerStart": footer_start, "footerUnchanged": True, "cleanSha256": sha(raw), "damagedSha256": sha(changed)}) for damaged, path in ((False, clean), (True, bad)): for size in (16, 64): for case in CASES: row = observe(path, case, size, damaged, repetition) validate(row) observations.append(row) require(clean.read_bytes() == raw and bad.read_bytes() == changed, "Read changed fixture") return { "schemaVersion": 1, "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "kind": "controlled synthetic API observations; not a storage or memory benchmark", "environment": {"python": platform.python_version(), "pyarrow": pa.__version__, "arrowCpp": pa.cpp_version, "system": platform.system(), "kernel": platform.release(), "machine": platform.machine(), "arrowBuild": pa.cpp_build_info._asdict()}, "codeSha256": sha(Path(__file__).read_bytes()), "license": "CC0-1.0 for original harness and observations; dependencies retain their licenses", "repetitions": repetitions, "fixture": {"rows": ROWS, "rowGroups": 4, "rowsPerGroup": GROUP, "columns": ["id", "measurement"], "type": "required INT64", "compression": "NONE", "dictionary": False, "pageChecksums": True, "fault": "measurement[81]: 100081 -> 100080; third row group; one payload bit", "units": "dimensionless synthetic integers"}, "limits": [ "One version, host and selected fault; repetitions are not independent field failures.", "Consumed rows are values delivered to the application, not physical read coverage.", "Batch nbytes is the yielded Arrow value-buffer size, not peak memory or process RSS.", "No claim that a batch-size setting bounds total decoder memory or prefetch.", "No compression, encryption, dictionary, null, nested or remote data tested.", "Complete value matching is against the generated fixture oracle, not authentication.", "An unchecked clean scan can match every value without checking any CRC." ], "sources": ["https://arrow.apache.org/docs/21.0/python/generated/pyarrow.parquet.ParquetFile.html", "https://parquet.apache.org/docs/file-format/data-pages/checksumming/"], "fixtures": fixtures, "observations": observations } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", required=True, type=Path) parser.add_argument("--repetitions", default=3, type=int) args = parser.parse_args() require(not args.output.exists(), "Refusing to replace an existing output") result = experiment(args.repetitions) with args.output.open("x", encoding="utf-8") as output: json.dump(result, output, indent=2) output.write("\n") print(json.dumps({"observations": len(result["observations"]), "output": str(args.output)})) if __name__ == "__main__": main()