#!/usr/bin/env python3 # SPDX-License-Identifier: CC0-1.0 """Observe Parquet count/scan coverage on disposable, synthetic files only.""" import argparse import datetime import hashlib import json import platform from pathlib import Path import struct import tempfile import pyarrow as pa import pyarrow.dataset as ds import pyarrow.parquet as pq VERSION = "21.0.0" CASES = ("count-all", "count-wide", "count-none", "count-exact-value", "count-exact-id", "count-second-group", "empty-projection", "projected-scanner-count", "full-checked", "full-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("<64q", *range(100000, 100064)) chunk = raw[start:start + size] require(chunk.count(needle) == 1, "Expected exactly one complete payload") offset = start + chunk.index(needle) + 17 * 8 changed = bytearray(raw) changed[offset] ^= 1 differences = [i for i, (a, b) in enumerate(zip(raw, changed)) if a != b] require(differences == [offset], "Fault must change exactly one byte") require(raw[offset] ^ changed[offset] == 1, "Fault must change one bit") return bytes(changed), offset def expected_error(case, statistics, damaged): if not damaged: return False if case in ("full-checked", "count-exact-value"): return True return not statistics and case in ("count-wide", "count-none", "count-second-group") def expected_count(case): return {"count-none": 0, "count-exact-value": 1, "count-exact-id": 1, "count-second-group": 64}.get(case, 128) def observe(path, case, statistics, damaged, repetition, original): predicates = { "count-wide": ds.field("measurement") >= 100000, "count-none": ds.field("measurement") < 100000, "count-exact-value": ds.field("measurement") == 100017, "count-exact-id": ds.field("id") == 17, "count-second-group": ds.field("measurement") >= 100064, } verify = case != "full-unchecked" options = ds.ParquetFragmentScanOptions(page_checksum_verification=verify, pre_buffer=False) # A new dataset per operation avoids carrying cached metadata between cases. dataset = ds.dataset(path, format=ds.ParquetFileFormat( default_fragment_scan_options=options)) row = {"repetition": repetition, "statisticsWritten": statistics, "damaged": damaged, "case": case, "verificationEnabled": verify, "expectedOriginalCount": expected_count(case), "filter": str(predicates[case]) if case in predicates else None, "returnedCount": None, "returnedColumns": None, "values": None, "mismatches": [], "error": None} try: if case.startswith("count-"): row["returnedCount"] = dataset.count_rows( filter=predicates.get(case), use_threads=False) elif case == "projected-scanner-count": row["returnedCount"] = dataset.scanner( columns=["measurement"], use_threads=False).count_rows() else: table = dataset.to_table( columns=[] if case == "empty-projection" else None, use_threads=False) row["returnedCount"] = table.num_rows row["returnedColumns"] = table.column_names row["values"] = table.to_pydict() if case != "empty-projection": for column, values in row["values"].items(): for index, (actual, expected) in enumerate(zip(values, original[column])): if actual != expected: row["mismatches"].append({"column": column, "row": index, "expected": expected, "actual": actual}) row["outcome"] = "returned" except OSError as exc: require("CRC checksum verification failed" in str(exc), "Unexpected I/O error, not the intended CRC failure: " + str(exc)) row["outcome"] = "checksum-error" row["error"] = {"type": type(exc).__name__, "message": str(exc)} if expected_error(case, statistics, damaged): require(row["outcome"] == "checksum-error", "Expected CRC failure: " + case) else: require(row["outcome"] == "returned", "Unexpected CRC failure: " + case) require(row["returnedCount"] == expected_count(case), "Unexpected count: " + case) mismatches = ([{"column": "measurement", "row": 17, "expected": 100017, "actual": 100016}] if case == "full-unchecked" and damaged else []) require(row["mismatches"] == mismatches, "Unexpected complete-value comparison") if case in ("full-checked", "full-unchecked"): require(row["returnedColumns"] == ["id", "measurement"], "Wrong projection") require(all(len(v) == 128 for v in row["values"].values()), "Incomplete values") if case == "empty-projection": require(row["returnedColumns"] == [] and row["values"] == {}, "Not empty") return row 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(128)), "measurement": list(range(100000, 100128))} schema = pa.schema([pa.field(name, pa.int64(), nullable=False) for name in original]) table = pa.Table.from_pydict(original, schema=schema) observations, fixtures = [], [] with tempfile.TemporaryDirectory(prefix="hesela-parquet-count-") as directory: for repetition in range(1, repetitions + 1): for statistics in (True, False): clean = Path(directory) / "clean.parquet" bad = Path(directory) / "damaged.parquet" pq.write_table(table, clean, row_group_size=64, use_dictionary=False, compression="NONE", write_page_checksum=True, write_statistics=statistics, data_page_version="1.0") metadata = pq.read_metadata(clean) require(metadata.num_rows == 128 and metadata.num_row_groups == 2, "Unexpected fixture shape") for group in range(2): for column in range(2): require(metadata.row_group(group).column(column).is_stats_set == statistics, "Statistics control not applied") column = metadata.row_group(0).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 must remain unchanged") bad.write_bytes(changed) fixtures.append({"repetition": repetition, "statisticsWritten": statistics, "fileBytes": len(raw), "byteOffset": offset, "xorMask": 1, "footerStart": footer_start, "footerUnchanged": True, "cleanSha256": sha(raw), "damagedSha256": sha(changed)}) for damaged, path in ((False, clean), (True, bad)): for case in CASES: observations.append(observe(path, case, statistics, damaged, repetition, original)) require(clean.read_bytes() == raw and bad.read_bytes() == changed, "Read operations changed the fixtures") return { "schemaVersion": 1, "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "kind": "synthetic-fixture API observations; not a storage 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 the harness and generated observations; dependencies retain their licenses", "repetitions": repetitions, "casesPerRepetition": len(CASES) * 4, "fixture": {"rows": 128, "rowGroups": 2, "rowsPerGroup": 64, "columns": ["id", "measurement"], "type": "required INT64", "pageChecksums": True, "compression": "NONE", "dictionary": False, "fault": "measurement[17]: 100017 -> 100016; one payload bit", "units": "dimensionless synthetic integers", "original": original}, "limits": [ "One pinned implementation and host; repetitions are not a failure-rate sample.", "No physical I/O, page-cache, prefetch, performance or durability measurements.", "No encrypted, compressed, dictionary, nested or nullable data.", "Statistics controls are separately written fixtures, not footer-only mutations.", "A correct count does not establish complete value or checksum coverage.", "No claim of an Arrow defect or of all Parquet implementations." ], "sources": [ "https://github.com/apache/arrow/blob/apache-arrow-21.0.0/cpp/src/arrow/dataset/file_parquet.cc#L900-L918", "https://github.com/apache/arrow/blob/apache-arrow-21.0.0/cpp/src/arrow/dataset/scanner.cc#L670-L717", "https://arrow.apache.org/docs/21.0/python/generated/pyarrow.dataset.Dataset.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", type=Path, required=True) parser.add_argument("--repetitions", type=int, default=3) 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"]), "fixtures": len(result["fixtures"]), "output": str(args.output)})) if __name__ == "__main__": main()