|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | +"""End-to-end benchmark: merge() vs create_match_filter + overwrite(). |
| 18 | +
|
| 19 | +Compares the full write path (filter construction + file I/O + snapshot commit) |
| 20 | +between the new merge() implementation and the previous approach. |
| 21 | +
|
| 22 | +Usage: |
| 23 | + poetry run pytest tests/benchmark/test_merge_filter.py -v -s -m benchmark |
| 24 | +""" |
| 25 | + |
| 26 | +import gc |
| 27 | +import itertools |
| 28 | +import timeit |
| 29 | +import tracemalloc |
| 30 | +from pathlib import PosixPath |
| 31 | +from typing import Any, Callable |
| 32 | + |
| 33 | +import pyarrow as pa |
| 34 | +import pytest |
| 35 | + |
| 36 | +from pyiceberg.catalog import Catalog |
| 37 | +from pyiceberg.exceptions import NoSuchTableError |
| 38 | +from pyiceberg.schema import Schema |
| 39 | +from pyiceberg.table import Table |
| 40 | +from pyiceberg.table.upsert_util import create_match_filter |
| 41 | +from pyiceberg.types import IntegerType, NestedField, StringType |
| 42 | +from tests.catalog.test_base import InMemoryCatalog |
| 43 | + |
| 44 | + |
| 45 | +def _make_schema(col_cardinalities: dict[str, int]) -> Schema: |
| 46 | + fields = [] |
| 47 | + for i, col in enumerate(col_cardinalities): |
| 48 | + field_type = IntegerType() if col == "date_id" else StringType() |
| 49 | + fields.append(NestedField(i + 1, col, field_type, required=True)) |
| 50 | + fields.append(NestedField(len(col_cardinalities) + 1, "v", IntegerType(), required=True)) |
| 51 | + return Schema(*fields) |
| 52 | + |
| 53 | + |
| 54 | +def _build_table(col_cardinalities: dict[str, int]) -> tuple[pa.Table, list[str], Schema]: |
| 55 | + from pyiceberg.io.pyarrow import schema_to_pyarrow |
| 56 | + |
| 57 | + schema = _make_schema(col_cardinalities) |
| 58 | + arrow_schema = schema_to_pyarrow(schema) |
| 59 | + |
| 60 | + vals: list[list[Any]] = [] |
| 61 | + for col, card in col_cardinalities.items(): |
| 62 | + if col == "date_id": |
| 63 | + vals.append(list(range(20260101, 20260101 + card))) |
| 64 | + else: |
| 65 | + vals.append([f"{col}_{i}" for i in range(card)]) |
| 66 | + combos = list(itertools.product(*vals)) |
| 67 | + data = {col: [c[i] for c in combos] for i, col in enumerate(col_cardinalities)} |
| 68 | + data["v"] = list(range(len(combos))) |
| 69 | + return pa.table(data, schema=arrow_schema), list(col_cardinalities.keys()), schema |
| 70 | + |
| 71 | + |
| 72 | +def _fresh_table(catalog: Catalog, name: str, schema: Schema, data: pa.Table) -> Table: |
| 73 | + ident = f"default.{name}" |
| 74 | + try: |
| 75 | + catalog.drop_table(ident) |
| 76 | + except NoSuchTableError: |
| 77 | + pass |
| 78 | + tbl = catalog.create_table(ident, schema=schema) |
| 79 | + tbl.append(data) |
| 80 | + return tbl |
| 81 | + |
| 82 | + |
| 83 | +def _measure(fn: Callable[[], Any], runs: int = 3) -> tuple[float, int]: |
| 84 | + """Returns (avg_seconds, peak_memory_bytes).""" |
| 85 | + times = [] |
| 86 | + peak = 0 |
| 87 | + for _ in range(runs): |
| 88 | + gc.collect() |
| 89 | + tracemalloc.start() |
| 90 | + t0 = timeit.default_timer() |
| 91 | + fn() |
| 92 | + times.append(timeit.default_timer() - t0) |
| 93 | + _, p = tracemalloc.get_traced_memory() |
| 94 | + tracemalloc.stop() |
| 95 | + peak = max(peak, p) |
| 96 | + return sum(times) / len(times), peak |
| 97 | + |
| 98 | + |
| 99 | +def _fmt(secs: float, mem_bytes: int) -> str: |
| 100 | + mem = f"{mem_bytes / 1024:.0f} KB" if mem_bytes < 1048576 else f"{mem_bytes / 1048576:.1f} MB" |
| 101 | + return f"{secs * 1000:.0f} ms, peak {mem}" |
| 102 | + |
| 103 | + |
| 104 | +COLS = {"date_id": 252, "account": 100} # 25,200 target rows |
| 105 | + |
| 106 | + |
| 107 | +@pytest.mark.benchmark |
| 108 | +@pytest.mark.parametrize("n_source", [100, 5000]) |
| 109 | +def test_e2e_merge(n_source: int, tmp_path: PosixPath) -> None: |
| 110 | + """End-to-end merge(): per-column In + anti-join + single OVERWRITE snapshot.""" |
| 111 | + target_data, join_cols, schema = _build_table(COLS) |
| 112 | + |
| 113 | + catalog = InMemoryCatalog("bench", warehouse=str(tmp_path)) |
| 114 | + catalog.create_namespace("default") |
| 115 | + tbl = _fresh_table(catalog, f"merge_{n_source}", schema, target_data) |
| 116 | + |
| 117 | + source_dict = {col: target_data.column(col).to_pylist()[:n_source] for col in target_data.column_names} |
| 118 | + source_dict["v"] = [x + 9000 for x in source_dict["v"]] |
| 119 | + source = pa.table(source_dict, schema=target_data.schema) |
| 120 | + |
| 121 | + avg, peak = _measure(lambda: tbl.merge(source, join_cols=join_cols)) |
| 122 | + print(f"\n merge(): {target_data.num_rows:,} target, {n_source:,} source -> {_fmt(avg, peak)}") |
| 123 | + |
| 124 | + |
| 125 | +@pytest.mark.benchmark |
| 126 | +def test_e2e_overwrite_100src(tmp_path: PosixPath) -> None: |
| 127 | + """End-to-end overwrite() with 100 source rows.""" |
| 128 | + target_data, join_cols, schema = _build_table(COLS) |
| 129 | + |
| 130 | + catalog = InMemoryCatalog("bench", warehouse=str(tmp_path)) |
| 131 | + catalog.create_namespace("default") |
| 132 | + tbl = _fresh_table(catalog, "overwrite_100", schema, target_data) |
| 133 | + |
| 134 | + source_dict = {col: target_data.column(col).to_pylist()[:100] for col in target_data.column_names} |
| 135 | + source_dict["v"] = [x + 9000 for x in source_dict["v"]] |
| 136 | + source = pa.table(source_dict, schema=target_data.schema) |
| 137 | + |
| 138 | + avg, peak = _measure(lambda: (tbl.overwrite(source, overwrite_filter=create_match_filter(source, join_cols)))) |
| 139 | + print(f"\n overwrite(): {target_data.num_rows:,} target, 100 source -> {_fmt(avg, peak)}") |
| 140 | + |
| 141 | + |
| 142 | +@pytest.mark.benchmark |
| 143 | +def test_e2e_overwrite_5ksrc_filter_only(tmp_path: PosixPath) -> None: |
| 144 | + """At 5,000 source rows, just constructing the filter takes seconds. |
| 145 | +
|
| 146 | + We only measure filter construction here because the full overwrite() |
| 147 | + with a 20,000-node expression tree causes process termination during |
| 148 | + manifest evaluation. |
| 149 | + """ |
| 150 | + target_data, join_cols, schema = _build_table(COLS) |
| 151 | + |
| 152 | + source_dict = {col: target_data.column(col).to_pylist()[:5000] for col in target_data.column_names} |
| 153 | + source_dict["v"] = [x + 9000 for x in source_dict["v"]] |
| 154 | + source = pa.table(source_dict, schema=target_data.schema) |
| 155 | + |
| 156 | + avg, peak = _measure(lambda: create_match_filter(source, join_cols), runs=1) |
| 157 | + print(f"\n create_match_filter only (no overwrite): 5,000 source -> {_fmt(avg, peak)}") |
0 commit comments