diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md new file mode 100644 index 000000000..34d34f943 --- /dev/null +++ b/changelog.d/ITL-1464.md @@ -0,0 +1,3 @@ +### Added + +- Documented the storage cost of keeping provenance with function results and pipeline records, including Parquet encoding and local Arrow spill measurements. diff --git a/docs/dev/scripts/itl-1464-storage/column-sizes.csv b/docs/dev/scripts/itl-1464-storage/column-sizes.csv new file mode 100644 index 000000000..7d4f19a31 --- /dev/null +++ b/docs/dev/scripts/itl-1464-storage/column-sizes.csv @@ -0,0 +1,8 @@ +column_family,narrow_arrow_bytes_per_pipeline_row,narrow_delta_bytes_per_pipeline_row,narrow_zstd_prefix_bytes_per_pipeline_row,wide_arrow_bytes_per_pipeline_row,wide_delta_bytes_per_pipeline_row,wide_zstd_prefix_bytes_per_pipeline_row +Input data hash,100,75,65,100,75,65 +Pipeline output data hash,52,37,32,52,37,32 +Pipeline record and base entry IDs,100,75,65,100,75,65 +Result record and pipeline data IDs,48,31,22,48,31,22 +Pipeline system tags,52,6.4,0.3,52,6.4,0.3 +Input provenance tokens,53,7,0.3,53,7,0.3 +Output provenance tokens,140,31,13,1400,310,130 diff --git a/docs/dev/scripts/itl-1464-storage/columns.py b/docs/dev/scripts/itl-1464-storage/columns.py new file mode 100644 index 000000000..855e95a7e --- /dev/null +++ b/docs/dev/scripts/itl-1464-storage/columns.py @@ -0,0 +1,96 @@ +"""Summarize column families as rounded, normalized storage costs.""" + +from __future__ import annotations + +import argparse +import csv +import json +import sys +from pathlib import Path +from typing import TypedDict, cast + +Families = dict[str, list[int]] +PREFIX_SETTINGS = "zstd-3-prefix-131072" + + +class ByteCounts(TypedDict): + """Bytes in one physical Parquet variant.""" + + bytes: int + rows: int + compressed: dict[str, int] + + +class TableCounts(TypedDict): + """Measurement record for one Delta table.""" + + columns: list[str] + arrow: dict[str, int] + actual: ByteCounts + computed: dict[str, ByteCounts] + + +def column_family(table: str, column: str) -> str | None: + """Group internal columns that carry the same kind of storage overhead.""" + if column == "__input_data_hash": + return "Input data hash" + if column == "__output_data_hash": + return "Pipeline output data hash" + if table == "pdb_v1" and column in {"__record_id", "__pipeline_base_entry_id"}: + return "Pipeline record and base entry IDs" + if column in {"__record_id", "__data_id"}: + return "Result record and pipeline data IDs" + if column.startswith("_tag_"): + return "Pipeline system tags" + if column.startswith("_source_"): + return ( + "Input provenance tokens" + if table == "pdb_v1" + else "Output provenance tokens" + ) + return None + + +def summarize(path: Path) -> dict[str, list[str]]: + """Normalize private measurements by the pipeline row count.""" + tables = cast("dict[str, TableCounts]", json.loads(path.read_text())) + rows = tables["pdb_v1"]["actual"]["rows"] + sizes: Families = {} + for name, table in tables.items(): + for index, column in enumerate(table["columns"]): + family = column_family(name, column) + if family is None: + continue + key = str(index) + summed = sizes.setdefault(family, [0, 0, 0]) + summed[0] += table["arrow"][key] + summed[1] += table["actual"]["compressed"].get(key, 0) + summed[2] += table["computed"][PREFIX_SETTINGS]["compressed"].get(key, 0) + return { + family: [format(float(format(size / rows, ".2g")), "g") for size in variants] + for family, variants in sizes.items() + } + + +def main() -> None: + """Write only rounded ratios, without source labels or absolute counts.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("narrow", type=Path, help="local metrics for a narrow result") + parser.add_argument("wide", type=Path, help="local metrics for a wide result") + args = parser.parse_args() + narrow, wide = summarize(args.narrow), summarize(args.wide) + writer = csv.writer(sys.stdout, lineterminator="\n") + writer.writerow( + ["column_family"] + + [ + f"{width}_{variant}_bytes_per_pipeline_row" + for width in ("narrow", "wide") + for variant in ("arrow", "delta", "zstd_prefix") + ] + ) + for family in narrow: + writer.writerow([family, *narrow[family], *wide[family]]) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/scripts/itl-1464-storage/measure.py b/docs/dev/scripts/itl-1464-storage/measure.py new file mode 100644 index 000000000..493ecd18c --- /dev/null +++ b/docs/dev/scripts/itl-1464-storage/measure.py @@ -0,0 +1,466 @@ +"""Measure Delta files, Parquet encodings and provenance layouts without emitting values. + +Keep the raw measurements local. Use columns.py for rounded column ratios. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from collections import Counter +from pathlib import Path +from statistics import median +from tempfile import TemporaryDirectory +from time import perf_counter +from typing import Literal, TypedDict, cast +from urllib.parse import unquote, urlparse + +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.ipc as ipc +import pyarrow.parquet as pq +from deltalake import DeltaTable + +TAG_NAMES = ("group_key", "order_key") +DEFAULT_GROUP = 131_072 +CHAIN_LENGTH = 5 +Codec = Literal["snappy", "zstd"] + + +class ParquetSizes(TypedDict): + """Size of the physical files and their column chunks.""" + + bytes: int + compressed: dict[str, int] + rows: int + row_groups: int + files: int + codecs: list[str] + + +class EncodingOptions(TypedDict): + """Settings passed to both Parquet write entry points.""" + + use_dictionary: bool + column_encoding: dict[str, str] | None + + +def name_kind(name: str) -> str: + """Identify the public column family without exposing a dynamic namespaced suffix.""" + return name.split("::", 1)[0] + + +def delta_files(root: Path) -> list[Path]: + """List active Parquet files in addition order according to Delta logs.""" + root = root.resolve() + active = { + Path(unquote(urlparse(uri).path)).resolve() + for uri in DeltaTable(str(root)).file_uris() + } + ordered = [] + for log in sorted((root / "_delta_log").glob("*.json")): + for line in log.read_text().splitlines(): + added = json.loads(line).get("add") + if added is not None: + path = root / unquote(added["path"]) + if path in active: + ordered.append(path) + if set(ordered) != active: + raise ValueError("Active files are missing from the commit logs") + return ordered + + +def parquet_sizes(files: list[Path]) -> ParquetSizes: + """Total compressed leaf bytes by top-level ordinal, plus file overhead.""" + compressed: Counter[str] = Counter() + rows = 0 + row_groups = 0 + total = 0 + codecs = set() + for path in files: + file = pq.ParquetFile(path) + meta = file.metadata + total += path.stat().st_size + rows += meta.num_rows + row_groups += meta.num_row_groups + columns = { + field.name: str(index) for index, field in enumerate(file.schema_arrow) + } + for group_index in range(meta.num_row_groups): + group = meta.row_group(group_index) + for col_index in range(group.num_columns): + col = group.column(col_index) + field = col.path_in_schema.split(".", 1)[0] + compressed[columns[field]] += col.total_compressed_size + codecs.add(col.compression) + return { + "bytes": total, + "compressed": dict(compressed), + "rows": rows, + "row_groups": row_groups, + "files": len(files), + "codecs": sorted(codecs), + } + + +def arrow_bytes(table: pa.Table) -> dict[str, int]: + """Return each Arrow column's logical buffer bytes, including offsets and validity.""" + return {str(index): col.nbytes for index, col in enumerate(table.columns)} + + +def prefix_leaves(table: pa.Table) -> list[str]: + """List BYTE_ARRAY leaves whose names identify tokens, digests or record IDs.""" + leaves = [] + for field in table.schema: + kind = name_kind(field.name) + if not ( + kind.startswith("_source_") + or kind.startswith("_tag_") + or "hash" in kind + or kind.endswith("_id") + ): + continue + dtype = field.type + path = field.name + if pa.types.is_large_list(dtype) or pa.types.is_list(dtype): + path += ".list.element" + dtype = dtype.value_type + if ( + pa.types.is_string(dtype) + or pa.types.is_large_string(dtype) + or pa.types.is_binary(dtype) + or pa.types.is_large_binary(dtype) + ): + leaves.append(path) + return leaves + + +def encoding_options(table: pa.Table, dictionary: str) -> EncodingOptions: + """Choose dictionary and prefix encoding for the selected columns.""" + dictionaries: bool | list[str] = dictionary == "all" + encoding = None + if dictionary == "prefix": + prefixes = prefix_leaves(table) + # The selective dictionary applies to scalar fields outside the prefix test. + # Remaining nested fields use plain encoding in this variant. + dictionaries = [ + field.name + for field in table.schema + if not any( + leaf.startswith(field.name + ".") or leaf == field.name + for leaf in prefixes + ) + and not pa.types.is_nested(field.type) + ] + encoding = dict.fromkeys(prefixes, "DELTA_BYTE_ARRAY") + # PyArrow accepts a list of columns, omitted in the installed stubs. + return {"use_dictionary": cast("bool", dictionaries), "column_encoding": encoding} + + +def parquet_round( + table: pa.Table, + path: Path, + codec: Codec, + level: int | None, + dictionary: str, + row_group: int, +) -> ParquetSizes: + """Write a Parquet candidate and measure its physical column-chunk sizes.""" + pq.write_table( + table, + path, + compression=codec, + compression_level=level, + row_group_size=row_group, + **encoding_options(table, dictionary), + ) + return parquet_sizes([path]) + + +def parquet_grid(table: pa.Table, path: Path) -> dict[str, ParquetSizes]: + """Sweep codecs and dictionaries, then isolate row-group size at Zstd 3.""" + codecs: list[tuple[Codec, int | None]] = [ + ("snappy", None), + ("zstd", 1), + ("zstd", 3), + ("zstd", 9), + ] + settings: list[tuple[Codec, int | None, str, int]] = [ + (codec, level, dictionary, DEFAULT_GROUP) + for codec, level in codecs + for dictionary in ("all", "off", "prefix") + ] + for dictionary in ("all", "prefix"): + for row_group in (16_384, 1_048_576): + settings.append(("zstd", 3, dictionary, row_group)) + return { + f"{codec}-{level or 0}-{dictionary}-{row_group}": parquet_round( + table, path, codec, level, dictionary, row_group + ) + for codec, level, dictionary, row_group in settings + } + + +def ipc_grid(table: pa.Table, path: Path) -> dict[str, dict[str, float | int]]: + """Measure writes and warm reads into Arrow, including full decompression.""" + stats = {} + for codec in (None, "lz4", "zstd"): + writes, reads = [], [] + for _ in range(3): + started = perf_counter() + with pa.OSFile(str(path), "wb") as output: + with ipc.new_file( + output, table.schema, options=ipc.IpcWriteOptions(compression=codec) + ) as writer: + writer.write_table(table, max_chunksize=DEFAULT_GROUP) + writes.append(perf_counter() - started) + started = perf_counter() + with pa.OSFile(str(path), "rb") as source: + loaded = ipc.open_file(source).read_all() + reads.append(perf_counter() - started) + if loaded.num_rows != table.num_rows: + raise ValueError("IPC row count changed") + stats[codec or "plain"] = { + "bytes": path.stat().st_size, + "write_s": median(writes), + "read_s": median(reads), + } + return stats + + +def list_tokens(table: pa.Table, tokens: list[str]) -> list[str]: + """Select the list-valued provenance columns.""" + return [ + name + for name in tokens + if pa.types.is_list(table[name].type) + or pa.types.is_large_list(table[name].type) + ] + + +def pack_lookup( + table: pa.Table, tokens: list[str], *, mode: str +) -> tuple[pa.Table, pa.Table]: + """Replace a tuple of provenance values with one verified lookup foreign key.""" + source = table.select(tokens) + if mode == "integer": + # A different tuple per row is the normal case for per-row provenance. + # Deduplicate identical tuples too, for equality with the content key case. + values = zip(*(col.to_pylist() for col in source.columns), strict=True) + identifiers: dict[str, int] = {} + rows = [ + identifiers.setdefault(json.dumps(row), len(identifiers)) for row in values + ] + key = pa.array(rows, pa.int64()) + else: + values = zip(*(col.to_pylist() for col in source.columns), strict=True) + rows = [ + hashlib.blake2b(json.dumps(row).encode(), digest_size=16).digest() + for row in values + ] + key = pa.array(rows, pa.binary(16)) + first: dict[int | bytes, int] = {} + for index, identifier in enumerate(rows): + first.setdefault(identifier, index) + lookup = source.take(list(first.values())).append_column( + "provenance_key", pc.take(key, list(first.values())) + ) + data = table.drop(tokens).append_column("provenance_key", key) + return data, lookup + + +def derive_tokens( + table: pa.Table, tokens: list[str] +) -> tuple[pa.Table, pa.Table, dict[str, tuple[str, str]]]: + """Store fixed source/column templates where the existing row ID supplies the middle.""" + templates: dict[str, tuple[str, str]] = {} + for name in tokens: + col = table[name] + if name in list_tokens(table, tokens) or col.null_count or not len(col): + continue + prefix, _, suffix = str(col[0].as_py()).rsplit("::", 2) + templates[name] = prefix, suffix + lookup = pa.table( + { + "fixed_source": pa.array( + [prefix for prefix, _ in templates.values()], pa.string() + ), + "column_suffix": pa.array( + [suffix for _, suffix in templates.values()], pa.string() + ), + } + ) + return table.drop(list(templates)), lookup, templates + + +def derived_rebuild( + data: pa.Table, lookup: pa.Table, names: list[str], kind: str +) -> pa.Table: + """Rebuild token text from an existing scalar record ID and the template sidecar.""" + if not names: + return data + if kind == "pdb_v1": + record_name = next( + col for col in data.column_names if col.startswith("_tag_record_id::") + ) + record_ids = data[record_name].cast(pa.string()) + else: + record_ids = pa.array( + [cast("bytes", value).hex() for value in data["__record_id"].to_pylist()] + ) + for index, name in enumerate(names): + tokens = pc.call_function( + "binary_join_element_wise", + [ + lookup["fixed_source"][index], + record_ids, + lookup["column_suffix"][index], + pa.scalar("::"), + ], + ) + data = data.append_column( + name, + cast("pa.ChunkedArray[pa.Scalar[pa.DataType]]", tokens).cast( + pa.large_string() + ), + ) + return data + + +def layouts( + table: pa.Table, scratch: Path, kind: str +) -> dict[str, dict[str, float | int]]: + """Measure compressed sidecar layouts and verified warm rebuild costs.""" + tokens = [name for name in table.column_names if name.startswith("_source_")] + lists = list_tokens(table, tokens) + data_file = scratch / "data.parquet" + lookup_file = scratch / "lookup.parquet" + report = {} + for mode in ("inline", "none", "derived", "integer", "hash", "list_hash"): + lookup = None + templates: dict[str, tuple[str, str]] = {} + active_tokens = lists if mode == "list_hash" else tokens + if mode == "none": + data = table.drop(tokens) + elif mode == "derived": + data, lookup, templates = derive_tokens(table, tokens) + elif mode in ("integer", "hash", "list_hash") and active_tokens: + data, lookup = pack_lookup(table, active_tokens, mode=mode) + else: + data = table + data_bytes = int( + parquet_round(data, data_file, "zstd", 3, "prefix", DEFAULT_GROUP)["bytes"] + ) + lookup_bytes = 0 + if lookup is not None and lookup.num_rows: + lookup_bytes = int( + parquet_round(lookup, lookup_file, "zstd", 3, "prefix", DEFAULT_GROUP)[ + "bytes" + ] + ) + total_times, rebuild_times = [], [] + for _ in range(3): + started = perf_counter() + rebuilt = pq.read_table(data_file) + sidecar = pq.read_table(lookup_file) if lookup_bytes else None + read_done = perf_counter() + if sidecar is not None and mode == "derived": + rebuilt = derived_rebuild(rebuilt, sidecar, list(templates), kind) + elif sidecar is not None: + indices = pc.index_in( + rebuilt["provenance_key"], + value_set=sidecar["provenance_key"].combine_chunks(), + ) + recovered = sidecar.select(active_tokens).take(indices) + for name in active_tokens: + rebuilt = rebuilt.append_column(name, recovered[name]) + finished = perf_counter() + if mode != "none" and not rebuilt.select(table.column_names).equals(table): + raise ValueError(f"Token round trip failed for {kind} / {mode}") + total_times.append(finished - started) + rebuild_times.append(finished - read_done) + report[mode] = { + "data_bytes": data_bytes, + "lookup_bytes": lookup_bytes, + "chain_bytes": CHAIN_LENGTH * data_bytes + lookup_bytes, + "read_s": median(total_times), + "rebuild_s": median(rebuild_times), + } + return report + + +def measure( + root: Path, scratch: Path, *, sizes_only: bool = False +) -> dict[str, object]: + """Read a real Delta run and measure both physical tables.""" + output = {} + tables = {} + for kind in ("pdb_v1", "rdb_v1"): + (directory,) = root.rglob(kind) + files = delta_files(directory) + if sizes_only: + arrow: Counter[str] = Counter() + for path in files: + for batch in pq.ParquetFile(path).iter_batches(): + arrow.update(arrow_bytes(pa.Table.from_batches([batch]))) + columns = pq.ParquetFile(files[0]).schema_arrow.names + else: + table = pq.read_table(files) + tables[kind] = table + arrow = Counter(arrow_bytes(table)) + columns = table.column_names + output[kind] = { + "actual": parquet_sizes(files), + "logs": sum( + p.stat().st_size + for p in (directory / "_delta_log").iterdir() + if p.is_file() + ), + "arrow": dict(arrow), + "columns": [name_kind(name) for name in columns], + } + if sizes_only: + return output + pipeline = tables["pdb_v1"] + tags = [name for name in TAG_NAMES if name in pipeline.column_names] + sorted_pipeline = pipeline.sort_by([(name, "ascending") for name in tags]) + positions = pc.index_in( + sorted_pipeline["__data_id"], + value_set=tables["rdb_v1"]["__record_id"].combine_chunks(), + ) + # A result can be reused by many pipeline rows. Sort by its first tagged occurrence. + result_order = pc.unique(pc.drop_null(positions)) + if len(result_order) != tables["rdb_v1"].num_rows: + raise ValueError("Unexpected result records orphaned from the pipeline table") + sorted_tables = { + "pdb_v1": sorted_pipeline, + "rdb_v1": tables["rdb_v1"].take(result_order), + } + file = scratch / "bench.parquet" + for kind, computed in tables.items(): + output[kind].update( + computed=parquet_grid(computed, file), + sorted=parquet_grid(sorted_tables[kind], file), + layouts=layouts(computed, scratch, kind), + ipc=ipc_grid(computed, scratch / "bench.arrow"), + ) + return output + + +def main() -> None: + """Write JSON measurements only, using scratch space beside the input by default.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("root", type=Path) + parser.add_argument("--sizes-only", action="store_true") + args = parser.parse_args() + with TemporaryDirectory( + prefix=".storage-measure-", dir=args.root.parent + ) as directory: + print( + json.dumps(measure(args.root, Path(directory), sizes_only=args.sizes_only)) + ) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/scripts/itl-1464-storage/scale.py b/docs/dev/scripts/itl-1464-storage/scale.py new file mode 100644 index 000000000..79f4d6c96 --- /dev/null +++ b/docs/dev/scripts/itl-1464-storage/scale.py @@ -0,0 +1,246 @@ +"""Write bounded batches with the exact persisted node schema and seeded synthetic rows.""" + +from __future__ import annotations + +import argparse +import json +from binascii import hexlify +from collections.abc import Iterator +from pathlib import Path +from typing import Any, cast + +import numpy as np +from numpy.typing import NDArray +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.parquet as pq +from deltalake import write_deltalake + +from orcapod.databases.delta_statistics import statistics_configuration + +from measure import delta_files, encoding_options, name_kind, parquet_sizes # pyright: ignore[reportImplicitRelativeImport] # Script entry point. +from workloads import project, read_profile, synthetic # pyright: ignore[reportImplicitRelativeImport] # Script entry point. + +BATCH = 65_536 + + +def uniform(keys: NDArray[Any], salt: int) -> NDArray[Any]: + """Use SplitMix64 to generate reproducible high-entropy limbs from each key.""" + with np.errstate(over="ignore"): + stream = np.uint64((0xD2B74407B1CE6E93 * salt) % (1 << 64)) + x = keys.astype(np.uint64) * np.uint64(0x9E3779B97F4A7C15) + stream + x = (x ^ (x >> 30)) * np.uint64(0xBF58476D1CE4E5B9) + x = (x ^ (x >> 27)) * np.uint64(0x94D049BB133111EB) + return x ^ (x >> 31) + + +def text_or_binary( + buffer: bytes | NDArray[Any], width: int, dtype: pa.DataType +) -> pa.Array[pa.Scalar[pa.DataType]]: + """Make a variable-length Arrow column from uniformly sized data.""" + size = len(buffer) // width + offsets = np.arange(size + 1, dtype=np.int64) * width + # The validity buffer is absent. The PyArrow stubs omit the None case. + buffers = cast( + "list[pa.Buffer]", + [ + None, + pa.py_buffer(offsets.tobytes()), + pa.py_buffer(buffer if isinstance(buffer, bytes) else buffer.tobytes()), + ], + ) + return pa.Array.from_buffers(dtype, size, buffers) + + +def digest( + keys: NDArray[Any], prefix: bytes, salt: int +) -> pa.Array[pa.Scalar[pa.DataType]]: + """Generate each prefixed 32-byte digest at the template's logical width.""" + size = len(keys) + raw = np.empty((size, len(prefix) + 32), dtype=np.uint8) + raw[:, : len(prefix)] = np.frombuffer(prefix, dtype=np.uint8) + for limb in range(4): + start = len(prefix) + 8 * limb + raw[:, start : start + 8] = ( + uniform(keys, salt + limb).view(np.uint8).reshape(-1, 8) + ) + return text_or_binary(raw.ravel(), raw.shape[1], pa.large_binary()) + + +def uuid_bytes(keys: NDArray[Any]) -> NDArray[Any]: + """Generate UUIDv7-shaped IDs with a monotone clock and a random suffix.""" + result = np.empty((len(keys), 16), dtype=np.uint8) + clock = (np.uint64(1_700_000_000_000) + keys.astype(np.uint64)).astype(">u8") + result[:, :6] = clock.view(np.uint8).reshape(-1, 8)[:, 2:] + result[:, 6:8] = uniform(keys, 4).view(np.uint8).reshape(-1, 8)[:, :2] + result[:, 8:] = uniform(keys, 5).view(np.uint8).reshape(-1, 8) + result[:, 6] = (result[:, 6] & 0x0F) | 0x70 + result[:, 8] = (result[:, 8] & 0x3F) | 0x80 + return result + + +def join_token( + prefix: str, ids: pa.Array[pa.Scalar[pa.DataType]], suffix: str +) -> pa.Array[pa.Scalar[pa.DataType]]: + """Use Arrow to combine a source prefix, row ID and suffix.""" + values = [ + pa.scalar(prefix, pa.large_string()), + ids, + pa.scalar(suffix, pa.large_string()), + pa.scalar("::", pa.large_string()), + ] + return cast( + "pa.Array[pa.Scalar[pa.DataType]]", + pc.call_function("binary_join_element_wise", values), + ) + + +def value_column(values: NDArray[Any], name: str) -> NDArray[Any]: + """Apply the same numeric transforms as the measured pods.""" + match name: + case "v0": + return values * 1.25 + case "v1": + return np.square(values) + case "v2": + return np.sin(values) + case "v3": + return np.cos(values) + case "v4": + return np.arctan(values) + case "v5": + return np.sqrt(np.abs(values)) + case "v6": + return values * 2 + case "v7": + return values * 100 + case "v8": + return values * -0.5 + case "v9": + return values + 1 + case _: + raise ValueError(name) + + +def build_batches( + template: pa.Table, shape: pa.Table, kind: str +) -> Iterator[pa.RecordBatch]: + """Substitute seeded values into the real result or pipeline Parquet schema.""" + values = shape["value"].combine_chunks().to_numpy(zero_copy_only=False) + groups = shape["group_key"].combine_chunks().to_numpy(zero_copy_only=False) + integer_values = np.rint(values * 1000).astype(np.int64) + # Reused values share an actual result ID, as in the function-result store. + _, first, inverse = np.unique( + integer_values, return_index=True, return_inverse=True + ) + result_ids = first[inverse] + rows = np.sort(first) if kind == "rdb_v1" else np.arange(len(values)) + for start in range(0, len(rows), BATCH): + row = rows[start : start + BATCH] + data = integer_values[row] + uuid_buffer = uuid_bytes(result_ids[row]).ravel() + uuid = text_or_binary(uuid_buffer, 16, pa.large_binary()) + uuid_text = text_or_binary( + hexlify(uuid_buffer.tobytes()), 32, pa.large_string() + ) + row_tag = pa.array([f"row_{index}" for index in row], pa.large_string()) + fields = [] + for field in template.schema: + name = name_kind(field.name) + dtype = field.type + old = template[field.name][0].as_py() + if name == "__data_id" or (name == "__record_id" and kind == "rdb_v1"): + col = uuid + elif name in { + "__record_id", + "__pipeline_base_entry_id", + "__input_data_hash", + "__output_data_hash", + }: + entropy_keys = ( + row if name in {"__record_id", "__pipeline_base_entry_id"} else data + ) + salt = { + "__record_id": 40, + "__pipeline_base_entry_id": 50, + "__input_data_hash": 60, + "__output_data_hash": 70, + }[name] + col = digest(entropy_keys, old[:-32], salt) + elif name == "_tag_record_id": + col = row_tag + elif name.startswith("_source_"): + prefix, _, suffix = old.rsplit("::", 2) + col = join_token( + prefix, uuid_text if kind == "rdb_v1" else row_tag, suffix + ) + elif name == "group_key": + col = pa.array(groups[row], dtype) + elif name == "order_key": + col = pa.array(values[row], dtype) + elif name in {"__recorded_at", "__pod_ts"}: + col = pa.array(1_700_000_000_000_000 + row * 1000, dtype) + elif name.startswith("v"): + col = pa.array(value_column(values[row], name), dtype) + else: + col = pa.repeat(template[field.name][0], len(row)) + fields.append(col) + yield pa.RecordBatch.from_arrays(fields, schema=template.schema) + + +def main() -> None: + """Seed and write separate large physical tables into a local output directory.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("template", type=Path) + parser.add_argument("destination", type=Path) + parser.add_argument("rows", type=int) + calibration = parser.add_mutually_exclusive_group(required=True) + calibration.add_argument("--calibrate-export", type=Path) + calibration.add_argument("--profile-json", type=Path) + parser.add_argument("--rewrite", action="store_true") + parser.add_argument("--sample-rows", type=int, default=0) + args = parser.parse_args() + profile = read_profile(args.calibrate_export, args.profile_json) + shape = synthetic(args.rows, profile, 1464) + print( + json.dumps({"profile": profile, "synthetic_profile": project(shape)[1]}), + flush=True, + ) + for kind in ("pdb_v1", "rdb_v1"): + (root,) = args.template.rglob(kind) + template = pq.ParquetFile(delta_files(root)[0]).read_row_group(0).slice(0, 1) + batches = build_batches(template, shape, kind) + reader = pa.RecordBatchReader.from_batches(template.schema, batches) + write_deltalake( + str(args.destination / kind), + reader, + configuration=statistics_configuration(template.schema), + ) + print(f"wrote {kind}", flush=True) + if args.sample_rows: + reader = pa.RecordBatchReader.from_batches( + template.schema, + build_batches(template, shape.slice(0, args.sample_rows), kind), + ) + write_deltalake( + str( + args.destination.with_name(args.destination.name + "-sample") / kind + ), + reader, + ) + if args.rewrite: + file = args.destination / f"{kind}-zstd.parquet" + with pq.ParquetWriter( + file, + template.schema, + compression="zstd", + compression_level=3, + **encoding_options(template, "prefix"), + ) as writer: + for batch in build_batches(template, shape, kind): + writer.write_batch(batch) + print(json.dumps({kind: parquet_sizes([file])}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/scripts/itl-1464-storage/workloads.py b/docs/dev/scripts/itl-1464-storage/workloads.py new file mode 100644 index 000000000..cbf978c06 --- /dev/null +++ b/docs/dev/scripts/itl-1464-storage/workloads.py @@ -0,0 +1,228 @@ +"""Build and run the scalar storage workloads used by the ITL-1464 study.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path +from time import perf_counter +from typing import Any, cast + +import numpy as np +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.parquet as pq + +import orcapod as op +from orcapod.databases import DeltaTableDatabase +from orcapod.pipeline import SyncPipelineOrchestrator + +TAG_NAMES = ("group_key", "order_key") +WIDTHS = ("row1", "row3", "row10", "group") + + +@op.function_pod(output_keys=("v0",)) +def narrow(value: float) -> float: + """Return one numeric result per row.""" + return value * 1.25 + + +@op.function_pod(output_keys=("v0", "v1", "v2")) +def medium(value: float) -> tuple[float, float, float]: + """Return three numeric results per row.""" + return value * 1.25, value**2, math.sin(value) + + +@op.function_pod(output_keys=tuple(f"v{i}" for i in range(10))) +def wide( + value: float, +) -> tuple[float, float, float, float, float, float, float, float, float, float]: + """Return ten numeric results per row.""" + return ( + value * 1.25, + value**2, + math.sin(value), + math.cos(value), + math.atan(value), + math.sqrt(abs(value)), + value * 2, + value * 100, + value * -0.5, + value + 1, + ) + + +@op.function_pod(output_keys=("v0", "v1", "v2")) +def grouped(value: list[float]) -> tuple[int, float, float]: + """Return count, mean and range in one record per group.""" + return len(value), sum(value) / len(value), max(value) - min(value) + + +def sample(path: Path, limit: int) -> pa.Table: + """Read one bounded prefix, using export row order.""" + file = pq.ParquetFile(path) + flat = [field for field in file.schema_arrow if not pa.types.is_nested(field.type)] + batches = [] + remaining = limit + for batch in file.iter_batches( + batch_size=min(limit, 65_536), columns=[field.name for field in flat] + ): + batches.append(batch.slice(0, remaining)) + remaining -= batches[-1].num_rows + if remaining == 0: + break + return pa.Table.from_batches(batches) + + +def adjacent_fraction( + column: pa.ChunkedArray[Any] | pa.Array[Any], *, equal: bool = False +) -> float: + """Measure the share of adjacent pairs satisfying equality or ascending order.""" + if len(column) < 2: + return 1.0 + left, right = column.slice(0, len(column) - 1), column.slice(1) + compare = pc.equal if equal else pc.less_equal + matches = pc.mean(pc.cast(compare(left, right), pa.float64())).as_py() + return float(matches or 0.0) + + +def project(table: pa.Table) -> tuple[pa.Table, dict[str, int | float]]: + """Select scalar numeric data and a repeated key using only their cardinalities.""" + scalar = [ + column + for column in table.columns + if ( + pa.types.is_integer(column.type) + or pa.types.is_floating(column.type) + or pa.types.is_temporal(column.type) + or pa.types.is_string(column.type) + or pa.types.is_large_string(column.type) + ) + and column.null_count == 0 + ] + numeric = [ + column + for column in scalar + if pa.types.is_integer(column.type) or pa.types.is_floating(column.type) + ] + cardinalities = [ + (int(pc.count_distinct(column).as_py()), column) for column in scalar + ] + value = max(numeric, key=lambda col: int(pc.count_distinct(col).as_py())) + value = pc.cast(value, pa.float64(), safe=False) + value = pc.if_else(pc.is_finite(value), value, 0.0) + key_candidates = [ + item for item in cardinalities if 1 < item[0] <= max(2, table.num_rows // 4) + ] + if key_candidates: + # Prefer a meaningful repeated key with about 100 groups in a large sample, + # instead of any constant or a per-row identity. + key_count, key = min( + key_candidates, key=lambda item: abs(math.log(item[0] / 100)) + ) + indexed = pc.index_in(key, value_set=pc.unique(key)) + else: + key_count = min(10, table.num_rows) + indexed = pa.array(np.arange(table.num_rows) % key_count, pa.int32()) + data = pa.table({"group_key": indexed, "order_key": value, "value": value}) + return data, { + "rows": table.num_rows, + "columns": table.num_columns, + "group_count": key_count, + "group_adjacent_equal": adjacent_fraction(indexed, equal=True), + "value_distinct": int(pc.count_distinct(value).as_py()), + "value_adjacent_ascending": adjacent_fraction(value), + } + + +def read_profile(export: Path | None, profile: Path | None) -> dict[str, int | float]: + """Load calibration statistics from an export prefix or an aggregate JSON file.""" + if export is not None: + return project(sample(export, 250_000))[1] + if profile is None: + raise ValueError("A calibration export or profile is required") + return cast("dict[str, int | float]", json.loads(profile.read_text())) + + +def synthetic(rows: int, profile: dict[str, int | float], seed: int) -> pa.Table: + """Build anonymous keys and scalar values matched to aggregate export statistics.""" + rng = np.random.default_rng(seed) + template_rows = int(profile["rows"]) + groups = max(2, int(profile["group_count"])) + distinct = min( + rows, max(2, round(rows * profile["value_distinct"] / template_rows)) + ) + order = np.linspace(0, distinct - 1, rows).astype(np.int64) + # Shuffle a subset of ranks to introduce local reversals without changing cardinality. + swap_rate = min(1.0, 2 * (1 - profile["value_adjacent_ascending"])) + swaps = rng.random(rows) < swap_rate + shuffled = order[swaps] + rng.shuffle(shuffled) + order[swaps] = shuffled + # Geometrically distributed run lengths approximate adjacent key repetition. + advance = rng.random(rows) >= profile["group_adjacent_equal"] + key = np.cumsum(advance) % groups + values = order / 1000.0 + return pa.table( + { + "group_key": pa.array(key, pa.int32()), + "order_key": pa.array(values), + "value": pa.array(values), + } + ) + + +def run(table: pa.Table, root: Path, case: str, batch_size: int) -> float: + """Compute one case with the public synchronous job and a Delta store.""" + started = perf_counter() + source = op.sources.ArrowTableSource( + table, + tag_columns=TAG_NAMES, + tag_only_columns=True, + infer_nullable=True, + source_id="storage-study", + ) + job = op.PipelineJob(database=DeltaTableDatabase(root, batch_size=batch_size)) + with job: + match case: + case "row1": + narrow.pod(source) + case "row3": + medium.pod(source) + case "row10": + wide.pod(source) + case "group": + grouped.pod(source.group_by("group_key", member_order=("order_key",))) + case _: + raise ValueError(case) + job.run(orchestrator=SyncPipelineOrchestrator()) + return perf_counter() - started + + +def main() -> None: + """Run a case on one export or on a seeded synthetic projection.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("destination", type=Path) + parser.add_argument("case", choices=WIDTHS) + parser.add_argument("--export", type=Path) + parser.add_argument("--rows", type=int, default=10_000) + parser.add_argument("--batch-size", type=int, default=1000) + args = parser.parse_args() + if args.export: + table, profile = project(sample(args.export, args.rows)) + else: + profile = { + "rows": args.rows, + "group_count": 100, + "group_adjacent_equal": 0.95, + "value_distinct": args.rows, + "value_adjacent_ascending": 0.98, + } + table = synthetic(args.rows, profile, 1464) + elapsed = run(table, args.destination, args.case, args.batch_size) + print(json.dumps({"profile": profile, "seconds": elapsed})) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1464-storage.md b/docs/dev/specs/itl-1464-storage.md new file mode 100644 index 000000000..d0a1ea194 --- /dev/null +++ b/docs/dev/specs/itl-1464-storage.md @@ -0,0 +1,78 @@ +# ITL-1464 storage compressibility + +| Workload | Current Delta B/row | Zstd 3 inline B/row | Derived B/row | Integer / hash row lookup B/row | List-only lookup B/row | +| --- | ---: | ---: | ---: | ---: | ---: | +| 1 output | ~430 | ~220 | ~210 | ~235 / ~290 | ~220 | +| 3 outputs | ~525 | ~265 | ~225 | ~280 / ~335 | ~265 | +| 10 outputs | ~850 | ~410 | ~275 | ~420 / ~480 | ~410 | +| Grouped, 3 outputs | ~860 | ~585 | ~530 | ~615 / ~670 | ~630 | + +Keep logical provenance and try Zstd level 1 or 3 with larger commits first, using the existing row order as the baseline. For wide scalar results, deriving tokens from existing record IDs and a source/column dictionary reduced the compressed two-table store by about a third, with a measurable read cost. Use list lookups where lists recur across nodes, which saved about 45–80% in a five-node reuse model. + +The table combines pipeline and result Parquet bytes per pipeline row or group. The current Delta column uses the original files. Each alternative uses Zstd 3 with selective prefix encoding. + +## Workloads + +Synchronous function nodes wrote to fresh local Delta stores. Scalar projections covered workloads such as a time series table and an event table. Inputs ranged from roughly a hundred rows to several million rows and occupied roughly half a megabyte to a hundred megabytes as Parquet. Per-row runs used bounded samples of up to a few tens of thousands of rows. The larger grouped runs processed millions of inputs into on the order of tens to hundreds of groups. + +Each scalar projection used a non-null numeric field as a float value and order tag. It mapped a repeated scalar field to integer group keys, preserving equality and row order. A cyclic key provided groups where a suitable repeated field was unavailable. Grouped nodes computed count, mean, and range. + +A narrow real-node sample took about two minutes. At that rate, a million-scale per-row run would take hours. The scale measurements instead streamed seeded synthetic batches into the real nodes' on-disk schemas. The generator varies scalar cardinality, adjacent repetition and ordering independently. Repeated values reuse input and output digests, while distinct values have high-entropy digests. Result IDs use a UUIDv7-shaped prefix and suffix. + +| Approximate synthetic scale | Outputs | Delta pipeline B/input | Delta result B/input | Zstd 3 total B/input | Savings | +| --- | ---: | ---: | ---: | ---: | ---: | +| About 2.2 million rows | 1 | ~180 | ~90 | ~210 | ~20% | +| About 2.2 million rows | 10 | ~180 | ~400 | ~370 | ~35% | +| About 8 million rows | 1 | ~180 | ~90 | ~215 | ~20% | +| About 8 million rows | 10 | ~180 | ~410 | ~400 | ~35% | + +The scale baseline used fresh delta-rs writes. The rewrite used Zstd 3, selective prefix encoding, and batches of up to 64 Ki rows. This setting differs from the real job's smaller commits. + +Apple M5 Max, 128 GiB RAM, macOS 27.2, local APFS. Python 3.12.16, PyArrow 23.0.1, Delta Lake Python 1.6.6, NumPy 2.2.6, Polars 1.41.2, Orcapod base 0d1e017c40ba47105292e81cae8f459053e75b26. The suites ran serially under a 24 GiB memory guard. + +## Writer settings and column costs + +[DeltaTableDatabase](../../../src/orcapod/databases/delta_lake_databases.py) passes no writer properties on creation or insert-only MERGE. The actual files used Snappy and dictionary encoding where supported. The database's pending batch threshold defaults to 1,000, and [PipelineJob.run](../../../src/orcapod/pipeline/job.py) commits after 100 rows per function node by default. Logs and related Delta metadata added about 50 B/row narrow, 75 B/row wide, and 110 B/group in the compact grouped example. + +With the same packed file layout and row order, Zstd 3 with selective prefix encoding saved about 25% narrow and 35% wide versus packed Snappy with dictionaries. Savings against the original small-file store were about 50%, including the effect of coalescing. + +The [rounded column ratios](../scripts/itl-1464-storage/column-sizes.csv) report bytes per pipeline row for the main column families in Arrow, Delta and the Zstd rewrite. Under Zstd 3 prefix encoding the input hash accounted for about 30% of the narrow and 15% of the wide store. Input and output hashes and the main record identifiers together accounted for about 85% narrow and 45% wide. Distinct 32-byte digests took about 32 B/row after compression. A binary result ID copy took about 11 B/row because its time prefix is correlated. Wide output token columns together took roughly 130 B/row because the same textual UUID appeared in ten independently compressed columns. + +The codec grid compared Snappy and Zstd levels 1, 3, and 9 with dictionaries enabled, disabled, and selectively replaced by DELTA_BYTE_ARRAY for byte-array token, tag, hash, and record ID columns. In a wide synthetic trial, Zstd 3 at a 128 Ki-row limit took about 410 B/row with all dictionaries and 375 B/row with prefix encoding. Smaller row groups gave similar results. A single larger row group improved size by about 2%. Sorting by tags increased size by about 2% in that trial. At the 128 Ki-row limit, Snappy with prefix encoding took about 500 B/row and Zstd 1 or 9 each took around 365–375 B/row. Zstd 1 with dictionaries off was comparable. + +## Provenance layouts and reconstruction + +| Layout | Narrow change vs. inline | Wide change vs. inline | Grouped sample change vs. inline | +| --- | ---: | ---: | ---: | +| Derived | −6% | −33% | −9% | +| 8-byte integer per row | +6% | +3% | +5% | +| 16-byte hash per row | +32% | +17% | +15% | +| List-only hash | 0% | 0% | +7% | +| Omitted, as a storage bound | −6% | −33% | −30% | + +Totals include the data and sidecar files. An equality index and row gather rebuilt lookup values. Derived tokens used hexadecimal conversion and Arrow concatenation. Every preserving variant passed a comparison against the original stored values. + +For derivable scalar tokens the data table already holds the record ID, and a small dictionary supplies the source prefix and field suffix. In the wider synthetic trial, derivation took on the order of 90 ms to rebuild ten tokens per row, versus around 30 ms for either row lookup, before adding read time. Both row lookups store a key in the data and the sidecar, and the token tuples are nearly unique per row. + +The list-only layout uses a 16-byte content key for ordered list tokens and keeps scalar tokens inline. A grouped record ID cannot recover its members' ordered tokens. The larger grouped runs produced about 10–50 MB of pipeline Parquet and about 10–30 KB of result Parquet. After compressing inline tokens, a single list lookup changed total size by about 0–2%. Read and rebuild added on the order of tens to a hundred milliseconds in those runs. The five-node model counts five data writes and one shared sidecar, giving about 45–80% savings when all five nodes have identical lists. The model assumes fixed reuse and excludes sidecar transaction and lifecycle costs. + +## Arrow IPC for local spill + +These are rounded warm-cache medians from a wide synthetic trial. The timed writes and reads include encoding, decoding, and materialization and exclude durability sync. + +| Table | IPC codec | Approximate size | Write ms | Read ms | +| --- | --- | ---: | ---: | ---: | +| Pipeline | Plain | ~80 MB | ~9 | ~8 | +| Pipeline | LZ4 | ~40 MB | ~14 | ~4 | +| Pipeline | Zstd | ~30 MB | ~15 | ~5 | +| Result | Plain | ~320 MB | ~30 | ~35 | +| Result | LZ4 | ~80 MB | ~25 | ~11 | +| Result | Zstd | ~45 MB | ~27 | ~11 | + +Zstd was about 30% smaller than LZ4 for pipeline data and about 45% smaller for wide results, with writes about 10–20% slower. LZ4 is a starting point for frequent spills. Test actual join-cache and node-spill schemas when disk pressure makes the Zstd savings important. + +## Reproduction + +The [measurement scripts](../scripts/itl-1464-storage/) take user-supplied paths. Run workloads.py with a fresh destination and one of row1, row3, row10 or group. Keep any input-backed data, scratch files and raw metrics local. Run measure.py on the Delta destination and pass narrow and wide local metrics files to columns.py for the rounded column summary. + +For a synthetic run, build a template without an export. Pass the template store, a fresh destination, and a chosen row count to scale.py along with a locally supplied profile. The rewrite flag measures a whole-scale Zstd rewrite and sample-rows selects a bounded layout and IPC trial. Use sizes-only mode for streaming column accounting.