From 925f35e4987e697c2227c2a0ffb5950baa7f5f04 Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Tue, 6 Oct 2026 02:54:10 -0700 Subject: [PATCH 1/2] [python] Adapt parallel split reads to split cost Bound Python split reads with an adaptive active window and prevent nested readahead. Keep Rust native auto parallelism independent of the Python pipeline. --- docs/docs/pypaimon/reading.md | 4 + paimon-python/dev/benchmark_split_read.py | 205 ++++++++ .../pypaimon/common/options/core_options.py | 9 +- .../read/datasource/ray_datasource.py | 3 +- .../read/reader/format_pyarrow_reader.py | 16 +- paimon-python/pypaimon/read/split_read.py | 10 +- paimon-python/pypaimon/read/table_read.py | 323 +++++++++++-- .../pypaimon/tests/native_read_test.py | 70 +++ paimon-python/pypaimon/tests/ray_data_test.py | 33 +- .../pypaimon/tests/reader_parallel_test.py | 438 ++++++++++++++++-- 10 files changed, 1038 insertions(+), 73 deletions(-) create mode 100644 paimon-python/dev/benchmark_split_read.py diff --git a/docs/docs/pypaimon/reading.md b/docs/docs/pypaimon/reading.md index ec0d09c12e33..2fbe6b7c3ae2 100644 --- a/docs/docs/pypaimon/reading.md +++ b/docs/docs/pypaimon/reading.md @@ -122,6 +122,10 @@ for batch in table_read.to_arrow_batch_reader(splits): # f1: ["a","b","c"] ``` +The Python Arrow reader pipelines splits in order, adapting parallelism to +split cost and storage. Set `parallelism` or `read.parallelism` to override. +Older PyArrow versions use serial streaming reads. + ### Read Python Iterator You can read the data row by row into a native Python iterator. diff --git a/paimon-python/dev/benchmark_split_read.py b/paimon-python/dev/benchmark_split_read.py new file mode 100644 index 000000000000..5326c1444b06 --- /dev/null +++ b/paimon-python/dev/benchmark_split_read.py @@ -0,0 +1,205 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Linux split-read matrix; remote mode simulates 5 ms open RTT. + +Run from paimon-python: ``python dev/benchmark_split_read.py``. +Each measurement uses a fresh process so peak RSS is comparable. +``--with-rust`` compares the same table through the direct Rust reader. +""" + +import json +import os +import statistics +import subprocess +import sys +import tempfile +import threading +import time + +import pyarrow as pa + +sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) +from pypaimon import CatalogFactory, Schema + + +def prepare(warehouse): + catalog = CatalogFactory.create({'warehouse': warehouse}) + catalog.create_database('default', False) + for name, payload_size in [('small', 4096), ('large', 4 * 1024 * 1024)]: + arrow_schema = pa.schema([ + ('id', pa.int64()), ('payload', pa.binary()), ('partition', pa.string()) + ]) + schema = Schema.from_pyarrow_schema( + arrow_schema, partition_keys=['partition'], options={ + 'source.split.target-size': '4mb', + 'read.batch-size': '1', + }) + catalog.create_table('default.' + name, schema, False) + table = catalog.get_table('default.' + name) + payloads = [os.urandom(payload_size) for _ in range(8)] + data = pa.Table.from_pydict({ + 'id': list(range(8)), + 'payload': payloads, + 'partition': [str(index) for index in range(8)], + }, schema=arrow_schema) + builder = table.new_batch_write_builder() + writer, commit = builder.new_write(), builder.new_commit() + try: + writer.write_arrow(data) + commit.commit(writer.prepare_commit()) + finally: + writer.close() + commit.close() + + +def measure(warehouse, name, backend, mode): + if mode == 'rust': + from pypaimon_rust.datafusion import PaimonCatalog + table = PaimonCatalog({'warehouse': warehouse}).get_table( + 'default.' + name) + read_builder = table.new_read_builder({ + 'source.split.target-size': '4mb', + 'read.batch-size': '1', + }) + splits = read_builder.new_scan().plan().splits() + read = read_builder.new_read() + else: + catalog = CatalogFactory.create({'warehouse': warehouse}) + table = catalog.get_table('default.' + name) + read_builder = table.new_read_builder() + splits = read_builder.new_scan().plan().splits() + read = read_builder.new_read() + + if backend == 'remote-simulated': + read._pipeline_reads_are_local = lambda unused: False + original_create = read._TableRead__create_reader_for_split + + def delayed_create(*args, **kwargs): + time.sleep(0.005) + return original_create(*args, **kwargs) + + read._TableRead__create_reader_for_split = delayed_create + + parallelism = {'serial': 1, 'auto': None, 'four': 4, 'rust': None}[mode] + + def rss_mib(): + with open('/proc/self/statm') as statm: + resident_pages = int(statm.read().split()[1]) + return resident_pages * os.sysconf('SC_PAGE_SIZE') / (1024 * 1024) + + initial_rss = rss_mib() + peak_rss = [initial_rss] + stop_sampling = threading.Event() + + def sample_rss(): + while not stop_sampling.wait(0.001): + peak_rss[0] = max(peak_rss[0], rss_mib()) + + sampler = threading.Thread(target=sample_rss, daemon=True) + sampler.start() + start = time.perf_counter() + rows = 0 + first_ms = None + try: + reader = (read.read(splits) if mode == 'rust' + else read.to_arrow_batch_reader( + splits, parallelism=parallelism)) + try: + for batch in reader: + if first_ms is None: + first_ms = (time.perf_counter() - start) * 1000 + rows += batch.num_rows + peak_rss[0] = max(peak_rss[0], rss_mib()) + finally: + close = getattr(reader, 'close', None) + if close is not None: + close() + finally: + stop_sampling.set() + sampler.join() + elapsed = time.perf_counter() - start + peak_rss[0] = max(peak_rss[0], rss_mib()) + if rows != 8 or len(splits) != 8: + raise AssertionError((rows, len(splits))) + return { + 'input': name, + 'backend': backend, + 'mode': mode, + 'workers': (None if mode == 'rust' + else read._read_workers(splits, parallelism)), + 'first_ms': round(first_ms, 3), + 'total_ms': round(elapsed * 1000, 3), + 'rows_per_second': round(rows / elapsed, 1), + 'baseline_rss_mib': round(initial_rss, 1), + 'sampled_peak_rss_mib': round(peak_rss[0], 1), + 'read_rss_delta_mib': round(peak_rss[0] - initial_rss, 1), + } + + +def main(): + if len(sys.argv) == 6 and sys.argv[1] == '--measure': + print(json.dumps(measure(*sys.argv[2:]))) + return + with_rust = '--with-rust' in sys.argv[1:] + with tempfile.TemporaryDirectory(prefix='paimon-split-bench-') as directory: + prepare(directory) + print(json.dumps({ + 'python': sys.version.split()[0], + 'pyarrow': pa.__version__, + 'cpu_count': os.cpu_count(), + 'small_bytes_per_split': 4096, + 'large_bytes_per_split': 4 * 1024 * 1024, + 'splits': 8, + 'target_split_size': 4 * 1024 * 1024, + 'rss_sample_period_ms': 1, + }), flush=True) + results = {} + for name in ('small', 'large'): + for backend in ('local', 'remote-simulated'): + modes = ('serial', 'auto', 'four') + if backend == 'local' and with_rust: + modes += ('rust',) + for repeat in range(3): + for mode in (modes if repeat % 2 == 0 else modes[::-1]): + command = [sys.executable, __file__, '--measure', + directory, name, backend, mode] + completed = subprocess.run( + command, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True) + if completed.returncode: + raise RuntimeError(completed.stderr) + result = json.loads(completed.stdout) + results.setdefault((name, backend, mode), []).append(result) + for (name, backend, mode), measurements in results.items(): + print(json.dumps({ + 'input': name, + 'backend': backend, + 'mode': mode, + 'workers': measurements[0]['workers'], + **{ + key: round(statistics.median(row[key] for row in measurements), 3) + for key in ('first_ms', 'total_ms', 'rows_per_second', + 'baseline_rss_mib', 'sampled_peak_rss_mib', + 'read_rss_delta_mib') + }, + })) + + +if __name__ == '__main__': + main() diff --git a/paimon-python/pypaimon/common/options/core_options.py b/paimon-python/pypaimon/common/options/core_options.py index 525b16f70892..9d4ff3ebc2f1 100644 --- a/paimon-python/pypaimon/common/options/core_options.py +++ b/paimon-python/pypaimon/common/options/core_options.py @@ -1181,12 +1181,9 @@ class CoreOptions: .int_type() .no_default_value() .with_description( - "Parallelism for reading splits within a single TableRead call. " - "When unset (the default), reads auto-scale to " - "min(number of splits, CPU count). Set to 1 to force serial " - "reads, or to a specific value >= 1 to cap the thread pool that " - "reads splits concurrently and assembles the result in input " - "order. Has no effect when fewer than 2 splits are passed.") + "Maximum split-read parallelism. Unset reads auto-scale; " + "1 forces serial. Streaming batch reads also consider input size " + "and storage locality. Has no effect with fewer than 2 splits.") ) ADD_COLUMN_BEFORE_PARTITION: ConfigOption[bool] = ( diff --git a/paimon-python/pypaimon/read/datasource/ray_datasource.py b/paimon-python/pypaimon/read/datasource/ray_datasource.py index dae0484c6b95..bb4bd8abc7fa 100644 --- a/paimon-python/pypaimon/read/datasource/ray_datasource.py +++ b/paimon-python/pypaimon/read/datasource/ray_datasource.py @@ -167,7 +167,8 @@ def _get_read_task( output_projection=output_projection, include_row_kind=include_row_kind) - batch_reader = worker_table_read.to_arrow_batch_reader(splits) + batch_reader = worker_table_read.to_arrow_batch_reader( + splits, parallelism=1) has_data = False for batch in iter(batch_reader.read_next_batch, None): if batch.num_rows == 0: diff --git a/paimon-python/pypaimon/read/reader/format_pyarrow_reader.py b/paimon-python/pypaimon/read/reader/format_pyarrow_reader.py index ff9517892df1..d6b40167e447 100644 --- a/paimon-python/pypaimon/read/reader/format_pyarrow_reader.py +++ b/paimon-python/pypaimon/read/reader/format_pyarrow_reader.py @@ -373,7 +373,8 @@ def __init__(self, file_io: FileIO, file_format: str, file_path: str, row_indices: Optional[List[int]] = None, row_ranges: Optional[List[Tuple[int, int]]] = None, row_group_cache: Optional[_DecodedRowGroupCache] = None, - file_size: Optional[int] = None): + file_size: Optional[int] = None, + parallel_split_read: bool = False): from pypaimon.filesystem.resolving_file_io import ResolvingFileIO if isinstance(file_io, ResolvingFileIO): file_io = file_io._get_fileio(file_path) @@ -436,6 +437,7 @@ def __init__(self, file_io: FileIO, file_format: str, file_path: str, self._range_slicer = _RowRunSlicer( selected_infos, runs) self._file_format = file_format + self._parallel_split_read = parallel_split_read self.read_fields = read_fields self._read_field_names = [f.name for f in read_fields] @@ -594,10 +596,21 @@ def __init__(self, file_io: FileIO, file_format: str, file_path: str, elif self._orc_file is not None: self._raw_batches = self._iter_orc_batches() else: + scan_options = {} + if parallel_split_read: + # The outer split window owns concurrency and batch readahead. + scan_options['use_threads'] = False + if not _pyarrow_lt_7(): + scan_options['batch_readahead'] = 1 + scan_options['fragment_readahead'] = 1 + if file_format == 'parquet': + scan_options['fragment_scan_options'] = ( + ds.ParquetFragmentScanOptions(pre_buffer=False)) reader = self.dataset.scanner( columns=self._scan_columns, filter=self._scan_filter, batch_size=self._scan_batch_size, + **scan_options, ).to_reader() raw_batches = self._iter_reader_batches(reader) if self._select_nested_after_scan: @@ -701,6 +714,7 @@ def _read_parquet_row_group_batches(self, row_group, columns): row_groups=[row_group], columns=columns, batch_size=self._scan_batch_size, + use_threads=not self._parallel_split_read, ) def _iter_orc_batches(self): diff --git a/paimon-python/pypaimon/read/split_read.py b/paimon-python/pypaimon/read/split_read.py index 7107692b3dbd..c7c41aa46f65 100644 --- a/paimon-python/pypaimon/read/split_read.py +++ b/paimon-python/pypaimon/read/split_read.py @@ -463,7 +463,9 @@ def file_reader_supplier(self, file: DataFileMeta, for_merge_read: bool, predicate_field_names=predicate_fields, row_ranges=parquet_row_ranges, row_group_cache=self._parquet_row_group_cache, - file_size=file.file_size) + file_size=file.file_size, + parallel_split_read=getattr( + self, '_parallel_split_read', False)) elif file_format == CoreOptions.FILE_FORMAT_ROW: if has_nested: raise NotImplementedError( @@ -994,6 +996,8 @@ def _create_blob_view_prescan_reader(self, field_names: set): # self.split is already unwrapped from IndexedSplit. Keep its physical # selection so LIMIT preloads the same views as the main reader. prescan_read._physical_row_ranges = self._physical_row_ranges + prescan_read._parallel_split_read = getattr( + self, '_parallel_split_read', False) return prescan_read.create_reader() def raw_reader_supplier(self, file: DataFileMeta, dv_factory: Optional[Callable] = None) -> Optional[RecordReader]: @@ -1275,6 +1279,8 @@ def _create_blob_view_prescan_reader(self, field_names: set): _blob_view_prescan=True, ) prescan_read.row_ranges = self.row_ranges + prescan_read._parallel_split_read = getattr( + self, '_parallel_split_read', False) reader = prescan_read.create_reader() if isinstance(reader, RecordBatchReader): return reader @@ -1552,6 +1558,8 @@ def _create_prescan_reader(self, field_names): limit=self._blob_view_prescan_limit(), ) prescan_read.row_ranges = self.row_ranges + prescan_read._parallel_split_read = getattr( + self, '_parallel_split_read', False) return prescan_read._create_raw_reader() def _split_by_row_id(self, files: List[DataFileMeta]) -> List[List[DataFileMeta]]: diff --git a/paimon-python/pypaimon/read/table_read.py b/paimon-python/pypaimon/read/table_read.py index e94df3f0af82..f58a90d58129 100644 --- a/paimon-python/pypaimon/read/table_read.py +++ b/paimon-python/pypaimon/read/table_read.py @@ -21,6 +21,7 @@ import threading from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Callable, Dict, Iterator, List, Optional +from urllib.parse import urlparse import pandas import pyarrow @@ -95,6 +96,12 @@ def close(self): close() +def _supports_cancellable_arrow_reader(): + reader_type = pyarrow.ipc.RecordBatchReader + return (hasattr(reader_type, "from_stream") + and hasattr(reader_type, "close")) + + class _RemainingRows: """Thread-safe remaining-rows counter for parallel reads. @@ -141,6 +148,9 @@ class TableRead: # split workers (P) each allow blob_parallelism (B) in-flight reads, so # peak connections ~= P*B. Shrink per-reader B to keep the product bounded. _MAX_TOTAL_BLOB_WORKERS = 64 + # Keep the automatic window modest; explicit parallelism can exceed it. + _PIPELINE_REMOTE_MIN_WORKERS = 4 + _PIPELINE_MAX_AUTO_WORKERS = 4 def __init__( self, @@ -245,19 +255,19 @@ def to_arrow_batch_reader( splits: List[Split], blob_parallelism: Optional[int] = None, parallelism: Optional[int] = None) -> pyarrow.ipc.RecordBatchReader: - """Lazily read batches using bounded native split concurrency. + """Lazily read batches using bounded split concurrency. ``parallelism`` follows :meth:`to_arrow`: an explicit value overrides - ``read.parallelism``, otherwise the reader auto-scales to the available - splits and CPUs. Native workers buffer at most one batch each; batches - from different split groups are emitted as they become ready because - table reads do not guarantee row order. Python fallback reads remain - serial. + ``read.parallelism``; otherwise native reads use the CPU/split cap, + while Python reads use split cost and storage locality to choose a + small active window. Python split batches are emitted in split order. """ # Cleanup ownership follows the uncapped concurrency decision. LIMIT # may reduce the actual native worker count to one, but the returned # PyArrow reader still does not close its suspended batch iterator. - effective = self._resolve_parallelism(parallelism, len(splits)) + effective = (self._resolve_parallelism(parallelism, len(splits)) + if self.limit is not None + else self._effective_parallelism(parallelism, len(splits))) reader, batch_iterator = self._new_arrow_batch_reader( splits, blob_parallelism, parallelism) if self._should_run_parallel(splits, effective): @@ -277,7 +287,9 @@ def _to_managed_arrow_batch_reader( """ # Keep the explicit iterator cleanup chain even when LIMIT caps the # native worker count inside _new_arrow_batch_reader to one. - effective = self._resolve_parallelism(parallelism, len(splits)) + effective = (self._resolve_parallelism(parallelism, len(splits)) + if self.limit is not None + else self._effective_parallelism(parallelism, len(splits))) reader, batch_iterator = self._new_arrow_batch_reader( splits, blob_parallelism, parallelism) if self._should_run_parallel(splits, effective): @@ -295,28 +307,158 @@ def _new_arrow_batch_reader( schema = self._output_arrow_schema() if self.include_row_kind: schema = self._add_row_kind_to_schema(schema) - effective = self._effective_parallelism(parallelism, len(splits)) + native_effective = self._effective_parallelism(parallelism, len(splits)) effective_bp = self._resolve_blob_parallelism(blob_parallelism) - if self._should_run_parallel(splits, effective): - effective_bp = self._cap_blob_parallelism( - min(effective, len(splits)), effective_bp) + native_bp = effective_bp + if self._should_run_parallel(splits, native_effective): + native_bp = self._cap_blob_parallelism( + min(native_effective, len(splits)), native_bp) native_batches = self._try_native_batches( splits, schema, - parallelism=effective, - blob_parallelism=effective_bp, + parallelism=native_effective, + blob_parallelism=native_bp, streaming=True, ) if native_batches is not None: batch_iterator = iter(native_batches) else: self._check_python_merge_supported() - batch_iterator = self._arrow_batch_generator( - splits, schema, effective_bp) + effective = self._read_workers(splits, parallelism) + if self.limit is not None and self.limit <= 0: + batch_iterator = iter(()) + reader = pyarrow.ipc.RecordBatchReader.from_batches( + schema, batch_iterator) + return reader, batch_iterator + workers = (effective if self.limit is None + and _supports_cancellable_arrow_reader() else 1) + if self._should_run_parallel(splits, workers): + python_bp = self._cap_blob_parallelism(workers, effective_bp) + batch_iterator = self._pipelined_arrow_batch_generator( + splits, schema, python_bp, workers) + else: + batch_iterator = self._arrow_batch_generator( + splits, schema, effective_bp) reader_type = pyarrow.ipc.RecordBatchReader reader = reader_type.from_batches(schema, batch_iterator) return reader, batch_iterator + def _pipelined_arrow_batch_generator( + self, + splits: List[Split], + schema: pyarrow.Schema, + blob_parallelism: int, + workers: int, + ) -> Iterator[pyarrow.RecordBatch]: + cancel = threading.Event() + workers = min(workers, len(splits)) + if workers < 2: + yield from self._arrow_batch_generator( + splits, schema, blob_parallelism) + return + end = object() + stop = object() + results = queue.Queue() + batch_slots = {} + task_queue = queue.Queue() + + def read_split(index, split): + batches = None + error = None + try: + batch_slot = batch_slots[index] + batches = self._arrow_batch_generator( + [split], schema, blob_parallelism, + parallel_split_read=True) + while not cancel.is_set(): + batch_slot.acquire() + if cancel.is_set(): + batch_slot.release() + break + try: + batch = next(batches) + except StopIteration: + batch_slot.release() + break + except BaseException: + batch_slot.release() + raise + if cancel.is_set(): + batch_slot.release() + return + results.put((index, batch)) + except BaseException as exception: + error = exception + finally: + try: + if batches is not None: + batches.close() + except BaseException as exception: + if error is None: + error = exception + if error is not None and not cancel.is_set(): + cancel.set() + results.put((-1, error)) + elif not cancel.is_set(): + results.put((index, end)) + + def worker(): + while True: + task = task_queue.get() + if task is stop: + return + read_split(*task) + if cancel.is_set(): + return + + threads = [] + try: + for _ in range(workers): + thread = threading.Thread(target=worker, daemon=True) + thread.start() + threads.append(thread) + + next_split = 0 + + def submit_next(): + nonlocal next_split + if next_split < len(splits): + index = next_split + batch_slots[index] = threading.Semaphore(1) + task_queue.put((index, splits[index])) + next_split += 1 + + for _ in range(workers): + submit_next() + + pending = {} + for index in range(len(splits)): + batch_slot = batch_slots[index] + while True: + if index in pending: + item = pending.pop(index) + else: + item_index, item = results.get() + if item_index < 0: + raise item + if item_index != index: + pending[item_index] = item + continue + if item is end: + break + try: + yield item + finally: + batch_slot.release() + del batch_slots[index] + submit_next() + finally: + cancel.set() + for batch_slot in batch_slots.values(): + batch_slot.release() + for _ in threads: + task_queue.put(stop) + @staticmethod def _add_row_kind_to_schema(schema: pyarrow.Schema) -> pyarrow.Schema: """Add _row_kind column to the schema as the first column.""" @@ -368,10 +510,10 @@ def to_arrow( splits: scan-plan splits returned from a ``TableScan``. parallelism: optional runtime override of the ``read.parallelism`` table option. ``None`` (default) falls - back to the table option; when that is also unset the read - auto-scales to ``min(number of splits, CPU count)``. ``1`` - keeps reads serial; ``>= 2`` caps the thread pool that reads - byte-balanced contiguous split groups concurrently and + back to the table option; when that is also unset, native + reads use the CPU/split cap, while Python reads also consider + split cost and storage locality. ``1`` keeps + reads serial; ``>= 2`` caps the active split window and assembles the final table in input order. An unfiltered row limit caps this further to avoid speculative work. Must be ``>= 1``. Note that with ``>= 2`` (or auto) @@ -389,27 +531,38 @@ def to_arrow( shrunk to stay within it. """ effective_bp = self._resolve_blob_parallelism(blob_parallelism) - effective = self._effective_parallelism(parallelism, len(splits)) + native_effective = self._effective_parallelism(parallelism, len(splits)) schema = self._output_arrow_schema() if self.include_row_kind: schema = self._add_row_kind_to_schema(schema) - native_parallel = self._should_run_parallel(splits, effective) + native_parallel = self._should_run_parallel(splits, native_effective) native_bp = effective_bp if native_parallel: native_bp = self._cap_blob_parallelism( - min(effective, len(splits)), effective_bp) + min(native_effective, len(splits)), effective_bp) native_batches = self._try_native_batches( splits, schema, - parallelism=effective, + parallelism=native_effective, blob_parallelism=native_bp, ) if native_batches is not None: return self._batches_to_arrow(native_batches, schema) self._check_python_merge_supported() + effective = self._read_workers(splits, parallelism) if self._should_run_parallel(splits, effective): + if self.limit is None: + batches = self._pipelined_arrow_batch_generator( + splits, schema, + self._cap_blob_parallelism(effective, effective_bp), + effective) + try: + return self._batches_to_arrow( + batches, schema, allow_type_cast=True) + finally: + batches.close() return self._to_arrow_parallel(splits, schema, effective, effective_bp) batch_iterator = self._arrow_batch_generator( @@ -867,7 +1020,8 @@ def _flatten_native_nested_batch(self, batch, schema): return pyarrow.RecordBatch.from_arrays(arrays, schema=pyarrow.schema(fields)) def _arrow_batch_generator(self, splits: List[Split], schema: pyarrow.Schema, - blob_parallelism: int = 1) -> Iterator[pyarrow.RecordBatch]: + blob_parallelism: int = 1, + parallel_split_read: bool = False) -> Iterator[pyarrow.RecordBatch]: self._begin_auth_read(splits) chunk_size = 65536 # ``remaining`` tracks how many rows we are still allowed to emit @@ -878,7 +1032,8 @@ def _arrow_batch_generator(self, splits: List[Split], schema: pyarrow.Schema, if remaining is not None and remaining <= 0: break reader = self.__create_reader_for_split( - split, blob_parallelism, limit=remaining) + split, blob_parallelism, limit=remaining, + parallel_split_read=parallel_split_read) try: if isinstance(reader, RecordBatchReader): for batch in iter(reader.read_arrow_batch, None): @@ -939,10 +1094,10 @@ def _resolve_parallelism(self, runtime: Optional[int], num_splits: int) -> int: """Pick the effective parallelism and reject illegal values. Priority: explicit ``parallelism`` argument > ``read.parallelism`` - table option > auto. When neither the argument nor the option is set - the read auto-scales to ``min(num_splits, CPU count)``. A value >= 1 - caps the thread pool; ``1`` forces serial reads. The validation - message names whichever source produced the offending value. + table option > auto. This is the CPU/split cap; ``_pipeline_workers`` + also considers split cost and locality for the automatic choice. + A value >= 1 caps the thread pool; ``1`` forces serial reads. The + validation message names whichever source produced the offending value. """ if runtime is not None: value, source = runtime, "parallelism" @@ -964,6 +1119,11 @@ def _effective_parallelism( return effective return min(effective, max(1, self.limit)) + def _read_workers(self, splits: List[Split], runtime: Optional[int]) -> int: + effective = self._effective_parallelism(runtime, len(splits)) + configured = runtime is not None or self._read_parallelism is not None + return self._pipeline_workers(splits, effective, configured) + @staticmethod def _resolve_blob_parallelism(runtime: Optional[int]) -> int: if runtime is None: @@ -1029,6 +1189,91 @@ def _native_inline_blob_fields(self) -> set: } return inline_fields & read_names + def _pipeline_workers( + self, + splits: List[Split], + effective: int, + configured: bool, + ) -> int: + maximum = min(effective, len(splits)) + if configured or maximum < 2: + return maximum + maximum = min(maximum, self._PIPELINE_MAX_AUTO_WORKERS) + + options = self.table.options + target_size = max(1, options.source_split_target_size()) + open_cost = max(0, options.source_split_open_file_cost()) + total_bytes = sum( + self._estimated_split_work(split, 0) for split in splits) + total_work = sum( + self._estimated_split_work(split, open_cost) for split in splits) + local = self._pipeline_reads_are_local(splits) + if local and total_bytes < target_size: + return 1 + if total_work <= 0: + return (1 if local else + min(maximum, self._PIPELINE_REMOTE_MIN_WORKERS)) + + workers = max(1, (total_work + target_size - 1) // target_size) + if not local: + workers = max( + workers, min(maximum, self._PIPELINE_REMOTE_MIN_WORKERS)) + return min(maximum, workers) + + @staticmethod + def _estimated_split_work(split: Split, open_cost: int) -> int: + try: + files = split.files + if files is not None: + return sum(max(max(0, int(f.file_size)), open_cost) + for f in files) + return max(0, int(getattr(split, 'file_size', 0) or 0)) + except (AttributeError, TypeError, ValueError): + return 0 + + def _pipeline_reads_are_local(self, splits: List[Split]) -> bool: + runtime_locality = self._runtime_file_io_is_local() + if runtime_locality is not None: + return runtime_locality + + data_paths = [] + missing_path = False + for split in splits: + files = getattr(split, "files", None) + if files is None: + missing_path = True + continue + for data_file in files: + path = ( + getattr(data_file, "external_path", None) + or getattr(data_file, "file_path", None) + ) + if path: + data_paths.append(str(path)) + else: + missing_path = True + + if not data_paths or missing_path: + data_paths.append(str(getattr(self.table, "table_path", "") or "")) + return all(self._is_local_data_path(path) for path in data_paths) + + def _runtime_file_io_is_local(self) -> Optional[bool]: + from pypaimon.filesystem.caching_file_io import CachingFileIO + from pypaimon.filesystem.local_file_io import LocalFileIO + + file_io = getattr(self.table, "file_io", None) + while isinstance(file_io, CachingFileIO): + file_io = getattr(file_io, "_delegate", None) + if isinstance(file_io, LocalFileIO): + return True + return None + + @staticmethod + def _is_local_data_path(path: str) -> bool: + if len(path) >= 2 and path[0].isalpha() and path[1] == ":": + return True + return urlparse(path).scheme.lower() in ("", "file") + def _limit_covers_all_splits(self, splits: List[Split]) -> bool: """Return whether split metadata proves that LIMIT cannot drop rows.""" total_rows = 0 @@ -1491,7 +1736,8 @@ def _create_split_read(self, split: Split, blob_parallelism: int = 1, push_down_limit: bool = True, post_merge_filter=None, eager_blob_fields=None, - post_filter_after_inline: bool = False) -> SplitRead: + post_filter_after_inline: bool = False, + parallel_split_read: bool = False) -> SplitRead: sr = self._build_split_read( split, read_type, @@ -1503,6 +1749,7 @@ def _create_split_read(self, split: Split, blob_parallelism: int = 1, ) sr._blob_parallelism = blob_parallelism sr._parquet_row_group_cache = self._parquet_row_group_cache + sr._parallel_split_read = parallel_split_read return sr def _build_split_read(self, split: Split, read_type=None, @@ -1797,7 +2044,8 @@ def _check_python_merge_supported(self): self._python_merge_validation_pending = False def __create_reader_for_split(self, split, blob_parallelism=1, - limit: Optional[int] = None): + limit: Optional[int] = None, + parallel_split_read: bool = False): # Raw-convertible splits skip MergeFileSplitRead, so validate before # dispatch, including when native setup failed or bindings are absent. self._check_python_merge_supported() @@ -1808,18 +2056,22 @@ def __create_reader_for_split(self, split, blob_parallelism=1, if auth_result is not None: return self.__authed_reader( - split, auth_result, blob_parallelism, limit) + split, auth_result, blob_parallelism, limit, + parallel_split_read) if limit is None: return self._create_split_read( - split, blob_parallelism=blob_parallelism).create_reader() + split, blob_parallelism=blob_parallelism, + parallel_split_read=parallel_split_read).create_reader() return self._create_split_read( split, blob_parallelism=blob_parallelism, limit=limit, + parallel_split_read=parallel_split_read, ).create_reader() def __authed_reader(self, split, auth_result, blob_parallelism=1, - limit: Optional[int] = None): + limit: Optional[int] = None, + parallel_split_read: bool = False): if self._has_map_key_projection(): raise NotImplementedError( "MAP-key projection with query authorization is not supported") @@ -1866,6 +2118,7 @@ def __authed_reader(self, split, auth_result, blob_parallelism=1, post_merge_filter=filter_fn if embed_filter else None, eager_blob_fields=auth_fields if embed_filter else None, post_filter_after_inline=post_filter_after_inline, + parallel_split_read=parallel_split_read, ) reader = split_read.create_reader() diff --git a/paimon-python/pypaimon/tests/native_read_test.py b/paimon-python/pypaimon/tests/native_read_test.py index c076fa2666e2..b90b8f8dd042 100644 --- a/paimon-python/pypaimon/tests/native_read_test.py +++ b/paimon-python/pypaimon/tests/native_read_test.py @@ -63,6 +63,14 @@ def _table_read(limit=None): return read +def _auto_table_read(): + read = _table_read() + read._read_parallelism = None + read.table.options.source_split_target_size.return_value = 1024 + read.table.options.source_split_open_file_cost.return_value = 0 + return read + + def _blob_table_read(limit=None): read = _table_read(limit) read.read_type = [DataField(0, 'payload', AtomicType('BLOB'))] @@ -376,6 +384,36 @@ def batches(): assert len(worker_names) == 2 +@pytest.mark.parametrize('streaming', [False, True]) +@pytest.mark.parametrize('target_size, python_workers', [(1024, 1), (1, 4)]) +def test_native_auto_parallelism_is_not_capped_by_python_pipeline( + streaming, target_size, python_workers): + read = _auto_table_read() + read.table.options.source_split_target_size.return_value = target_size + splits = [_Split() for _ in range(8)] + for index, split in enumerate(splits): + split._native_split = index + + groups = [] + + def read_group(rust_splits): + groups.append(rust_splits) + return [_id_batch(rust_splits)] + + with patch('pypaimon.read.table_read.os.cpu_count', return_value=8), patch( + 'pypaimon.read.native_plan._prepare_native_read', + return_value=read_group) as prepare: + assert read._read_workers(splits, None) == python_workers + if streaming: + result = read.to_arrow_batch_reader(splits).read_all() + else: + result = read.to_arrow(splits) + + assert result.column('id').to_pylist() == list(range(8)) + prepare.assert_called_once() + assert sorted(groups) == [[index] for index in range(8)] + + def test_parallel_native_read_prepares_rust_reader_once(): read = _table_read() splits = [_Split() for _ in range(4)] @@ -472,6 +510,38 @@ def close(self): assert iterator_closed.wait(timeout=1) +def test_native_auto_batch_reader_close_closes_parallel_iterator(): + read = _auto_table_read() + iterator_closed = threading.Event() + + def batches(): + try: + yield _id_batch([1]) + yield _id_batch([2]) + finally: + iterator_closed.set() + + batch_iterator = batches() + + class Reader: + def read_next_batch(self): + return next(batch_iterator) + + def close(self): + pass + + splits = [_Split() for _ in range(8)] + with patch('pypaimon.read.table_read.os.cpu_count', return_value=8), patch.object( + read, '_new_arrow_batch_reader', + return_value=(Reader(), batch_iterator)): + assert read._read_workers(splits, None) == 1 + batch_reader = read.to_arrow_batch_reader(splits) + batch_reader.read_next_batch() + batch_reader.close() + + assert iterator_closed.wait(timeout=1) + + def test_native_batch_reader_caps_blob_parallelism_across_rust_readers(): read = _table_read() splits = [_Split() for _ in range(16)] diff --git a/paimon-python/pypaimon/tests/ray_data_test.py b/paimon-python/pypaimon/tests/ray_data_test.py index 6d00d13ff956..4c6ae36fbee7 100644 --- a/paimon-python/pypaimon/tests/ray_data_test.py +++ b/paimon-python/pypaimon/tests/ray_data_test.py @@ -16,9 +16,10 @@ # under the License. import os +import shutil import tempfile import unittest -import shutil +from unittest import mock import pyarrow as pa import pyarrow.types as pa_types @@ -132,6 +133,36 @@ def test_basic_ray_data_read(self): "Name column should match" ) + def test_ray_task_reads_splits_serially(self): + from pypaimon.read.datasource.ray_datasource import RayDatasource + + splits = [mock.Mock(file_size=1, row_count=1, file_paths=[]) + for _ in range(2)] + for split in splits: + split.merged_row_count.return_value = None + provider = mock.Mock() + provider.table.return_value.is_primary_key_table = False + provider.predicate.return_value = None + provider.read_type.return_value = [] + provider.nested_name_paths.return_value = None + provider.splits.return_value = splits + provider.limit.return_value = None + provider.expression_projection.return_value = None + provider.include_row_kind.return_value = False + + worker_read = mock.Mock() + worker_read.to_arrow_batch_reader.return_value = ( + pa.ipc.RecordBatchReader.from_batches(pa.schema([]), iter(()))) + with mock.patch( + 'pypaimon.read.table_read.TableRead', return_value=worker_read + ): + task = RayDatasource(provider).get_read_tasks(1)[0] + list(task()) + + self.assertEqual( + 1, + worker_read.to_arrow_batch_reader.call_args[1]['parallelism']) + def test_basic_ray_data_write(self): """Test basic Ray Data write from PyPaimon table.""" # Create schema diff --git a/paimon-python/pypaimon/tests/reader_parallel_test.py b/paimon-python/pypaimon/tests/reader_parallel_test.py index b31ba265e4cb..d2d4df86903d 100644 --- a/paimon-python/pypaimon/tests/reader_parallel_test.py +++ b/paimon-python/pypaimon/tests/reader_parallel_test.py @@ -19,15 +19,19 @@ import shutil import tempfile import threading +import time import types import unittest from unittest import mock import pyarrow as pa +import pyarrow.dataset as ds import pytest from pypaimon import CatalogFactory, Schema -from pypaimon.read.table_read import TableRead, _RemainingRows +from pypaimon.read.reader.format_pyarrow_reader import FormatPyArrowReader +from pypaimon.read.table_read import ( + TableRead, _RemainingRows, _supports_cancellable_arrow_reader) class ResolveParallelismTest(unittest.TestCase): @@ -121,6 +125,310 @@ def worker(): self.assertTrue(rr.exhausted()) +class PipelinePolicyTest(unittest.TestCase): + + @staticmethod + def _workers( + path, + sizes, + configured=False, + data_paths=None, + file_io=None, + effective=8, + target_size=128 * 1024 * 1024, + ): + read = TableRead.__new__(TableRead) + read.table = types.SimpleNamespace( + table_path=path, file_io=file_io, + options=types.SimpleNamespace( + source_split_target_size=lambda: target_size, + source_split_open_file_cost=lambda: 4 * 1024 * 1024)) + splits = [] + for index, size in enumerate(sizes): + files = None + if data_paths is not None: + files = [types.SimpleNamespace( + external_path=data_paths[index], file_path=None)] + splits.append(types.SimpleNamespace( + file_size=size, files=files)) + return read._pipeline_workers(splits, effective, configured) + + def test_adaptive_workers(self): + mb = 1024 * 1024 + cases = [ + ('small_local', '/tmp/table', [8 * mb] * 8, False, None, 1), + ('small_remote', 's3://bucket/table', [4 * mb] * 8, + False, None, 4), + ('large_remote', 'oss://bucket/table', [64 * mb] * 4, + False, None, 4), + ('large_local', 'file:///tmp/table', [256 * mb] * 2, + False, None, 2), + ('explicit', '/tmp/table', [1] * 4, True, None, 4), + ('unknown_remote', 'hdfs://host/table', [0, 0], + False, None, 2), + ('external_remote', '/tmp/table', [64 * mb] * 2, False, + ['oss://bucket/a', 'oss://bucket/b'], 2), + ('external_local', 'oss://bucket/table', [64 * mb] * 2, False, + ['file:///cache/a', 'file:///cache/b'], 1), + ] + for name, path, sizes, configured, paths, expected in cases: + with self.subTest(name=name): + self.assertEqual(expected, self._workers( + path, sizes, configured, paths)) + + self.assertEqual(4, self._workers( + 's3://bucket/table', [64 * mb] * 32, effective=32)) + self.assertEqual(1, self._workers( + '/tmp/table', [4096] * 8, target_size=4 * mb)) + self.assertEqual(32, self._workers( + '/tmp/table', [1] * 32, configured=True, effective=32)) + + from pypaimon.filesystem.caching_file_io import CachingFileIO + from pypaimon.filesystem.local_file_io import FuseLocalFileIO + from pypaimon.utils.file_type import FileType + + fuse_file_io = FuseLocalFileIO( + 'oss://bucket/table', '/tmp/fuse/table') + local_file_ios = [ + fuse_file_io, + CachingFileIO(fuse_file_io, object(), {FileType.DATA}), + ] + for file_io in local_file_ios: + with self.subTest(file_io=type(file_io).__name__): + self.assertEqual(1, self._workers( + 'oss://bucket/table', [64 * mb] * 2, + file_io=file_io)) + + remote_cache = CachingFileIO( + object(), object(), {FileType.DATA}) + for sizes in ([0] * 8, [4 * mb] * 8): + with self.subTest(cached_file_size=sizes[0]): + self.assertEqual(4, self._workers( + 'oss://bucket/table', sizes, file_io=remote_cache)) + + def test_split_work_uses_scan_open_file_cost(self): + mb = 1024 * 1024 + split = types.SimpleNamespace(files=[ + types.SimpleNamespace(file_size=mb), + types.SimpleNamespace(file_size=16 * mb), + ]) + self.assertEqual(20 * mb, TableRead._estimated_split_work( + split, 4 * mb)) + + +class PipelinedBatchGeneratorTest(unittest.TestCase): + + def setUp(self): + self.read = TableRead.__new__(TableRead) + self.read.limit = None + self.read._read_parallelism = None + self.read.read_type = [] + self.read.expression_projection = None + self.read.include_row_kind = False + self.schema = pa.schema([('value', pa.int64())]) + + def _batch(self, value): + return pa.RecordBatch.from_arrays( + [pa.array([value], type=pa.int64())], schema=self.schema) + + def test_reads_concurrently_and_preserves_split_order(self): + second_started = threading.Event() + + def generate(splits, schema, blob_parallelism, + parallel_split_read=False): + self.assertTrue(parallel_split_read) + value = splits[0] + if value == 0 and not second_started.wait(5): + raise TimeoutError('second split did not start') + if value == 1: + second_started.set() + yield self._batch(value) + + with mock.patch.object( + self.read, '_arrow_batch_generator', side_effect=generate + ): + batches = list(self.read._pipelined_arrow_batch_generator( + [0, 1, 2], self.schema, 1, 2)) + + self.assertEqual( + [0, 1, 2], + [batch.column(0)[0].as_py() for batch in batches], + ) + + def test_buffers_one_batch_per_active_split(self): + produced = [0, 0] + second_ready = threading.Event() + + def generate(splits, schema, blob_parallelism, + parallel_split_read=False): + self.assertTrue(parallel_split_read) + value = splits[0] + for _ in range(3): + produced[value] += 1 + if value == 1: + second_ready.set() + elif produced[value] == 1 and not second_ready.wait(5): + raise TimeoutError('second split did not produce a batch') + yield self._batch(value) + + with mock.patch.object( + self.read, '_arrow_batch_generator', side_effect=generate, + ): + batches = self.read._pipelined_arrow_batch_generator( + [0, 1], self.schema, 1, 2) + next(batches) + self.assertEqual([1, 1], produced) + batches.close() + + def test_later_error_bypasses_blocked_earlier_split(self): + first_started = threading.Event() + release = threading.Event() + + def generate(splits, schema, blob_parallelism, + parallel_split_read=False): + self.assertTrue(parallel_split_read) + if splits[0] == 0: + first_started.set() + release.wait(5) + yield self._batch(0) + else: + if not first_started.wait(5): + raise TimeoutError('first split did not start') + raise RuntimeError('later split failed') + + try: + with mock.patch.object( + self.read, '_arrow_batch_generator', side_effect=generate + ): + with self.assertRaisesRegex( + RuntimeError, 'later split failed' + ): + list(self.read._pipelined_arrow_batch_generator( + [0, 1], self.schema, 1, 2)) + finally: + release.set() + + def test_only_active_splits_are_submitted(self): + first_started = threading.Event() + second_started = threading.Event() + release_first = threading.Event() + started = [] + + def generate(splits, schema, blob_parallelism, + parallel_split_read=False): + value = splits[0] + started.append(value) + if value == 0: + first_started.set() + release_first.wait(5) + elif value == 1: + second_started.set() + return + yield self._batch(value) + + batches = self.read._pipelined_arrow_batch_generator( + list(range(100)), self.schema, 1, 2) + consumed = [] + with mock.patch.object( + self.read, '_arrow_batch_generator', side_effect=generate + ): + consumer = threading.Thread( + target=lambda: consumed.append(next(batches))) + consumer.start() + try: + self.assertTrue(first_started.wait(5)) + self.assertTrue(second_started.wait(5)) + time.sleep(0.05) + self.assertCountEqual([0, 1], started) + finally: + release_first.set() + consumer.join(5) + self.assertFalse(consumer.is_alive()) + batches.close() + self.assertEqual(0, consumed[0].column(0)[0].as_py()) + + def test_split_reader_setup_failure_propagates(self): + with mock.patch.object( + self.read, '_arrow_batch_generator', + side_effect=RuntimeError('setup failed') + ): + with self.assertRaisesRegex(RuntimeError, 'setup failed'): + list(self.read._pipelined_arrow_batch_generator( + [0, 1], self.schema, 1, 2)) + + @unittest.skipUnless( + _supports_cancellable_arrow_reader(), 'reader close is unavailable') + def test_public_reader_close_cancels_workers(self): + started = threading.Barrier(2) + closed = [] + closed_lock = threading.Lock() + + def generate(splits, schema, blob_parallelism, + parallel_split_read=False): + self.assertTrue(parallel_split_read) + value = splits[0] + try: + started.wait(5) + while True: + yield self._batch(value) + finally: + with closed_lock: + closed.append(value) + + with mock.patch( + 'pypaimon.read.table_read.PyarrowFieldParser.from_paimon_schema', + return_value=self.schema, + ), mock.patch.object( + self.read, '_arrow_batch_generator', side_effect=generate + ), mock.patch.object( + self.read, '_try_native_batches', return_value=None + ), mock.patch.object( + self.read, '_check_python_merge_supported' + ): + reader = self.read.to_arrow_batch_reader( + [0, 1], parallelism=2) + reader.read_next_batch() + reader.close() + + deadline = time.monotonic() + 1 + while len(closed) < 2 and time.monotonic() < deadline: + time.sleep(0.01) + self.assertCountEqual([0, 1], closed) + + +class ParallelPyArrowScanTest(unittest.TestCase): + + def test_outer_pipeline_disables_scanner_readahead(self): + dataset = ds.dataset(pa.table({'value': [1, 2]})) + wrapped = types.SimpleNamespace( + schema=dataset.schema, + scanner=mock.Mock(wraps=dataset.scanner)) + file_io = types.SimpleNamespace( + to_filesystem_path=lambda path: path, + filesystem=pa.fs.LocalFileSystem(), + properties=None) + fields = Schema.from_pyarrow_schema(dataset.schema).fields + + with mock.patch( + 'pypaimon.read.reader.format_pyarrow_reader._file_format_dataset', + return_value=wrapped, + ): + reader = FormatPyArrowReader( + file_io, 'parquet', '/unused.parquet', fields, None, + parallel_split_read=True) + try: + self.assertEqual(2, reader.read_arrow_batch().num_rows) + finally: + reader.close() + + options = wrapped.scanner.call_args[1] + self.assertFalse(options['use_threads']) + self.assertFalse(options['fragment_scan_options'].pre_buffer) + if 'batch_readahead' in ds.Dataset.scanner.__doc__: + self.assertEqual(1, options['batch_readahead']) + self.assertEqual(1, options['fragment_readahead']) + + class ParallelReaderAppendOnlyTest(unittest.TestCase): """Append-only multi-partition table — parallel must match serial exactly.""" @@ -155,8 +463,7 @@ def setUpClass(cls): 'dt': dts, }, schema=cls.pa_schema) - # Default table — read.parallelism unset => auto (parallel when - # there are >= 2 splits and >= 2 CPUs). + # Default table — read.parallelism unset => adaptive local reads. cls.table = cls._build_table('append_parallel_default', None, data) # Option-set table — read.parallelism=4 baked into the table schema. cls.table_opt_4 = cls._build_table( @@ -226,10 +533,70 @@ def test_parallel_via_table_option_matches_serial(self): .sort_values('user_id').reset_index(drop=True) self.assertTrue(serial_df.equals(parallel_df)) - def test_default_none_runs_auto_parallel(self): - # No runtime arg and no table option => auto. With >= 2 splits on a - # multi-core box this takes the parallel fan-out path; the result - # must still match a forced-serial read row for row. + def test_batch_reader_parallelism_controls(self): + supports_pipeline = _supports_cancellable_arrow_reader() + cases = [ + ('runtime', self.table, {'parallelism': 4}, + supports_pipeline, supports_pipeline, True), + ('option', self.table_opt_4, {}, + supports_pipeline, supports_pipeline, False), + ('default', self.table, {}, supports_pipeline, False, False), + ('no_close', self.table, {'parallelism': 4}, False, False, False), + ] + for name, table, kwargs, can_close, uses_pipeline, use_scanner in cases: + with self.subTest(name=name): + rb = table.new_read_builder() + splits = self._scan_splits(rb) + read = rb.new_read() + expected = pa.Table.from_batches( + read.to_arrow_batch_reader(splits, parallelism=1)) + with mock.patch( + 'pypaimon.read.table_read.' + '_supports_cancellable_arrow_reader', + return_value=can_close, + ), mock.patch.object( + read, + '_pipelined_arrow_batch_generator', + wraps=read._pipelined_arrow_batch_generator, + ) as pipeline: + reader = read.to_arrow_batch_reader(splits, **kwargs) + actual = ( + ds.Scanner.from_batches(reader).to_table() + if use_scanner else reader.read_all() + ) + if uses_pipeline: + pipeline.assert_called_once() + else: + pipeline.assert_not_called() + self.assertEqual(expected, actual) + + def test_parallel_batch_reader_limit_matches_serial(self): + for limit in (0, 600): + with self.subTest(limit=limit): + rb = self.table.new_read_builder().with_limit(limit) + splits = self._scan_splits(rb) + read = rb.new_read() + serial = read.to_arrow_batch_reader( + splits, parallelism=1).read_all() + with mock.patch.object( + read, '_pipelined_arrow_batch_generator' + ) as pipeline, mock.patch.object( + read, + '_arrow_batch_generator', + wraps=read._arrow_batch_generator, + ) as serial_read: + parallel = read.to_arrow_batch_reader( + splits, parallelism=4).read_all() + pipeline.assert_not_called() + if limit == 0: + serial_read.assert_not_called() + else: + serial_read.assert_called_once() + self.assertEqual(serial, parallel) + self.assertEqual(limit, parallel.num_rows) + + def test_default_none_matches_serial(self): + # The default may stay serial for small local inputs. read = self.table.new_read_builder().new_read() splits = self._scan_splits(self.table.new_read_builder()) self.assertGreaterEqual(len(splits), 2) @@ -239,18 +606,15 @@ def test_default_none_runs_auto_parallel(self): self.assertEqual(auto.num_rows, self.expected_rows) @pytest.mark.python_read - def test_default_none_auto_takes_parallel_path_when_multicore(self): + def test_default_none_stays_serial_for_small_local_input(self): read = self.table.new_read_builder().new_read() splits = self._scan_splits(self.table.new_read_builder()) - # Only assert fan-out where the box actually has >= 2 CPUs, else - # auto legitimately resolves to 1 and stays serial. - if (os.cpu_count() or 1) < 2: - self.skipTest("single-core runner: auto resolves to serial") + self.assertEqual(1, read._read_workers(splits, None)) with mock.patch.object( read, '_to_arrow_parallel', wraps=read._to_arrow_parallel ) as spy: read.to_arrow(splits) - spy.assert_called_once() + spy.assert_not_called() # ------------------------------------------------------------------ # Priority: method arg > table option > built-in default. @@ -259,11 +623,14 @@ def test_default_none_auto_takes_parallel_path_when_multicore(self): def test_method_arg_overrides_option_to_serial(self): # option=4 but caller passes 1: should disable parallelism. read = self.table_opt_4.new_read_builder().new_read() - with mock.patch.object(read, '_to_arrow_parallel') as patched: + with mock.patch.object(read, '_to_arrow_parallel') as patched, \ + mock.patch.object( + read, '_pipelined_arrow_batch_generator') as pipeline: patched.side_effect = AssertionError( "_to_arrow_parallel should not be called when arg=1 overrides option") splits = self._scan_splits(self.table_opt_4.new_read_builder()) read.to_arrow(splits, parallelism=1) + pipeline.assert_not_called() @pytest.mark.python_read def test_method_arg_overrides_option_to_parallel(self): @@ -271,7 +638,8 @@ def test_method_arg_overrides_option_to_parallel(self): read = self.table_opt_1.new_read_builder().new_read() splits = self._scan_splits(self.table_opt_1.new_read_builder()) with mock.patch.object( - read, '_to_arrow_parallel', wraps=read._to_arrow_parallel + read, '_pipelined_arrow_batch_generator', + wraps=read._pipelined_arrow_batch_generator ) as spy: result = read.to_arrow(splits, parallelism=4) spy.assert_called_once() @@ -308,6 +676,8 @@ def test_invalid_method_arg_raises(self): self.assertNotIn("read.parallelism", str(ctx.exception)) with self.assertRaises(ValueError): read.to_pandas(splits, parallelism=-1) + with self.assertRaises(ValueError): + read.to_arrow_batch_reader(splits, parallelism=0) def test_invalid_option_value_raises(self): # Build a fresh table with an invalid option value. @@ -362,13 +732,16 @@ def test_parallel_reader_error_propagates(self): call_counter = {'n': 0} lock = threading.Lock() - def flaky(self_, split, blob_parallelism=1): + def flaky(self_, split, blob_parallelism=1, + parallel_split_read=False): with lock: call_counter['n'] += 1 idx = call_counter['n'] if idx == 2: raise RuntimeError("simulated reader failure") - return original_create(self_, split, blob_parallelism) + return original_create( + self_, split, blob_parallelism, + parallel_split_read=parallel_split_read) with mock.patch.object(TableRead, '_create_split_read', flaky): read = rb.new_read() @@ -445,17 +818,26 @@ def test_parallel_merge_matches_serial(self): rb = self.table.new_read_builder() splits = rb.new_scan().plan().splits() read = rb.new_read() - serial = read.to_pandas(splits).sort_values( - ['dt', 'user_id']).reset_index(drop=True) - parallel = read.to_pandas(splits, parallelism=4).sort_values( - ['dt', 'user_id']).reset_index(drop=True) - self.assertTrue(serial.equals(parallel)) - # Ensure the merge actually picked the latest version. - # user_id=1 / dt=p1 must have behavior='v2-updated', item_id=9001. - updated = parallel[(parallel.user_id == 1) & (parallel.dt == 'p1')] - self.assertEqual(len(updated), 1) - self.assertEqual(updated.iloc[0].behavior, 'v2-updated') - self.assertEqual(updated.iloc[0].item_id, 9001) + + def load(kind, parallelism): + if kind == 'table': + return read.to_pandas(splits, parallelism=parallelism) + return pa.Table.from_batches( + read.to_arrow_batch_reader( + splits, parallelism=parallelism)).to_pandas() + + for kind in ('table', 'batch_reader'): + with self.subTest(kind=kind): + serial = load(kind, 1).sort_values( + ['dt', 'user_id']).reset_index(drop=True) + parallel = load(kind, 4).sort_values( + ['dt', 'user_id']).reset_index(drop=True) + self.assertTrue(serial.equals(parallel)) + updated = parallel[ + (parallel.user_id == 1) & (parallel.dt == 'p1')] + self.assertEqual(len(updated), 1) + self.assertEqual(updated.iloc[0].behavior, 'v2-updated') + self.assertEqual(updated.iloc[0].item_id, 9001) def test_parallel_with_limit_pk(self): limit = 12 From f750cc51716aeb6c98d0594341d9e740e70ecfbf Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Tue, 6 Oct 2026 06:07:54 -0700 Subject: [PATCH 2/2] [python] Fix split-read CI regressions after rebase --- paimon-python/pypaimon/read/table_read.py | 4 +++- .../pypaimon/table/source/vector_search_read.py | 7 +++++-- .../pypaimon/tests/batch_vector_raw_scan_test.py | 15 ++++++++------- .../tests/batch_vector_streaming_refine_test.py | 2 +- paimon-python/pypaimon/tests/ray_data_test.py | 2 +- .../pypaimon/tests/reader_parallel_test.py | 2 +- .../pypaimon/tests/vector_search_filter_test.py | 2 +- 7 files changed, 20 insertions(+), 14 deletions(-) diff --git a/paimon-python/pypaimon/read/table_read.py b/paimon-python/pypaimon/read/table_read.py index f58a90d58129..9eaa929df679 100644 --- a/paimon-python/pypaimon/read/table_read.py +++ b/paimon-python/pypaimon/read/table_read.py @@ -356,6 +356,7 @@ def _pipelined_arrow_batch_generator( yield from self._arrow_batch_generator( splits, schema, blob_parallelism) return + self._begin_auth_read(splits) end = object() stop = object() results = queue.Queue() @@ -1022,7 +1023,8 @@ def _flatten_native_nested_batch(self, batch, schema): def _arrow_batch_generator(self, splits: List[Split], schema: pyarrow.Schema, blob_parallelism: int = 1, parallel_split_read: bool = False) -> Iterator[pyarrow.RecordBatch]: - self._begin_auth_read(splits) + if not parallel_split_read: + self._begin_auth_read(splits) chunk_size = 65536 # ``remaining`` tracks how many rows we are still allowed to emit # across all splits. ``None`` means unlimited. diff --git a/paimon-python/pypaimon/table/source/vector_search_read.py b/paimon-python/pypaimon/table/source/vector_search_read.py index 0df1fec9839b..edeb6453c8d6 100644 --- a/paimon-python/pypaimon/table/source/vector_search_read.py +++ b/paimon-python/pypaimon/table/source/vector_search_read.py @@ -605,7 +605,9 @@ def _score_refine_splits(self, table_read, splits, queries_by_row, query_vectors from pypaimon.read.table_read import _ClosableArrowBatchReader heaps = [[] for _ in query_vectors] - reader, batches = table_read._new_arrow_batch_reader(splits) + # The caller already parallelizes these split groups. Do not create + # another split worker pool for each group. + reader, batches = table_read._new_arrow_batch_reader(splits, parallelism=1) with _ClosableArrowBatchReader(reader, batches) as batch_reader: for batch in batch_reader: row_ids = batch.column(SpecialFields.ROW_ID.name).to_pylist() @@ -775,7 +777,8 @@ def _read_raw_batch_search(self, raw_row_ranges, pre_filter, def _score_raw_splits(self, table_read, splits, metric): from pypaimon.read.table_read import _ClosableArrowBatchReader - reader, batches = table_read._new_arrow_batch_reader(splits) + # The caller already parallelizes these split groups. + reader, batches = table_read._new_arrow_batch_reader(splits, parallelism=1) # Close the underlying iterator as well if scoring fails mid-batch. with _ClosableArrowBatchReader(reader, batches) as batch_reader: return self._score_raw_batch_queries(batch_reader, metric) diff --git a/paimon-python/pypaimon/tests/batch_vector_raw_scan_test.py b/paimon-python/pypaimon/tests/batch_vector_raw_scan_test.py index 80ae700f16d6..d9892aac5aa1 100644 --- a/paimon-python/pypaimon/tests/batch_vector_raw_scan_test.py +++ b/paimon-python/pypaimon/tests/batch_vector_raw_scan_test.py @@ -130,8 +130,8 @@ def test_scoring_finishes_each_batch_before_reading_the_next(self): module = 'pypaimon.table.source.vector_search_read' from pypaimon.table.source.vector_search_read import _compute_scores - def batches(table_read, splits): - arrow, generator = original(table_read, splits) + def batches(table_read, splits, **kwargs): + arrow, generator = original(table_read, splits, **kwargs) generators.append(generator) return arrow, generator @@ -223,8 +223,8 @@ def test_public_batch_search_preserves_split_parallelism(self): state = {'active': 0, 'peak': 0, 'closed': 0} seen = [] - def tracked(table_read, splits, *args): - source = original(table_read, splits, *args) + def tracked(table_read, splits, *args, **kwargs): + source = original(table_read, splits, *args, **kwargs) with lock: state['active'] += 1 state['peak'] = max(state['peak'], state['active']) @@ -263,8 +263,8 @@ def test_parallel_failure_closes_all_started_readers(self): started = [] closed = [] - def tracked(table_read, *args): - source = original(table_read, *args) + def tracked(table_read, *args, **kwargs): + source = original(table_read, *args, **kwargs) with lock: worker = len(started) started.append(worker) @@ -286,7 +286,8 @@ def tracked(table_read, *args): with self.assertRaisesRegex(exception, message): (table.new_batch_vector_search_builder().with_vector_column('embedding') .with_query_vectors([query]).with_limit(2).execute_batch_local()) - self.assertEqual([0, 1], sorted(closed)) + self.assertGreaterEqual(len(started), 2) + self.assertEqual(sorted(started), sorted(closed)) if __name__ == '__main__': diff --git a/paimon-python/pypaimon/tests/batch_vector_streaming_refine_test.py b/paimon-python/pypaimon/tests/batch_vector_streaming_refine_test.py index c7636943e6c1..09db4ed73fa7 100644 --- a/paimon-python/pypaimon/tests/batch_vector_streaming_refine_test.py +++ b/paimon-python/pypaimon/tests/batch_vector_streaming_refine_test.py @@ -224,7 +224,7 @@ class TableRead: def _resolve_parallelism(self, runtime, count): return 2 - def _new_arrow_batch_reader(self, splits): + def _new_arrow_batch_reader(self, splits, parallelism=None): owner = splits[0] with lock: active.add(owner) diff --git a/paimon-python/pypaimon/tests/ray_data_test.py b/paimon-python/pypaimon/tests/ray_data_test.py index 4c6ae36fbee7..5c0599fd8c96 100644 --- a/paimon-python/pypaimon/tests/ray_data_test.py +++ b/paimon-python/pypaimon/tests/ray_data_test.py @@ -147,7 +147,7 @@ def test_ray_task_reads_splits_serially(self): provider.nested_name_paths.return_value = None provider.splits.return_value = splits provider.limit.return_value = None - provider.expression_projection.return_value = None + provider.output_projection.return_value = None provider.include_row_kind.return_value = False worker_read = mock.Mock() diff --git a/paimon-python/pypaimon/tests/reader_parallel_test.py b/paimon-python/pypaimon/tests/reader_parallel_test.py index d2d4df86903d..345c5249f399 100644 --- a/paimon-python/pypaimon/tests/reader_parallel_test.py +++ b/paimon-python/pypaimon/tests/reader_parallel_test.py @@ -223,7 +223,7 @@ def setUp(self): self.read.limit = None self.read._read_parallelism = None self.read.read_type = [] - self.read.expression_projection = None + self.read.output_projection = None self.read.include_row_kind = False self.schema = pa.schema([('value', pa.int64())]) diff --git a/paimon-python/pypaimon/tests/vector_search_filter_test.py b/paimon-python/pypaimon/tests/vector_search_filter_test.py index f707189faef6..fc305f4e5459 100644 --- a/paimon-python/pypaimon/tests/vector_search_filter_test.py +++ b/paimon-python/pypaimon/tests/vector_search_filter_test.py @@ -216,7 +216,7 @@ def to_arrow(self, splits): "_ROW_ID": pa.array(row_ids, type=pa.int64()), }) - def _new_arrow_batch_reader(self, splits): + def _new_arrow_batch_reader(self, splits, parallelism=None): table = self.to_arrow(splits) batches = (batch for batch in table.to_batches(max_chunksize=2)) return pa.RecordBatchReader.from_batches(table.schema, batches), batches