-
Notifications
You must be signed in to change notification settings - Fork 1.3k
[python] Pre-repartition Ray writes by (partition, bucket) for fixed-bucket tables #7813
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
JingsongLi
merged 5 commits into
apache:master
from
TheR1sing3un:py-ray-write-fixed-bucket-shuffle
May 15, 2026
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c98a23d
[python] Add pre-shuffle helper for Ray writes to fixed-bucket tables
TheR1sing3un 553d9c0
[python] Wire shuffle/override_num_blocks options through write_paimon
TheR1sing3un 24fd02d
[python] Read back via direct API in shuffle roundtrip tests
TheR1sing3un bc24cf0
[python] Address #7813 review: collision-safe transient bucket column
TheR1sing3un 719ec43
[python] Address #7813 review: auto-shuffle HASH_FIXED Ray writes
TheR1sing3un File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| ################################################################################ | ||
| # 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. | ||
| ################################################################################ | ||
|
|
||
| """Pre-repartition a Ray Dataset by (partition, bucket) before writing | ||
| to a Paimon table. | ||
|
|
||
| Without this, Ray's default round-robin block distribution scatters rows | ||
| that share the same (partition, bucket) across many Ray tasks. Each | ||
| task then opens its own writer and emits its own data file, producing | ||
| ``partitions × buckets × ray_tasks`` files instead of the | ||
| ``partitions × buckets`` the writer would naturally produce. | ||
|
|
||
| When ``shuffle=True`` and the table is HASH_FIXED, we group rows by | ||
| ``(partition_keys..., bucket)`` so every distinct group lands in a | ||
| single Ray task. ``bucket`` is computed using the same | ||
| ``FixedBucketRowKeyExtractor`` the writer uses, so the shuffle-time | ||
| bucket assignment is byte-equivalent to the writer's. | ||
|
|
||
| For any other bucket mode the shuffle is a soft no-op with a warning; | ||
| we never raise. ``shuffle=False`` is the default and preserves the | ||
| original Ray round-robin behaviour. | ||
| """ | ||
|
|
||
| import logging | ||
| from typing import TYPE_CHECKING, List, Optional, Tuple | ||
|
|
||
| import pyarrow as pa | ||
|
|
||
| from pypaimon.table.bucket_mode import BucketMode | ||
|
|
||
| if TYPE_CHECKING: | ||
| import ray.data | ||
|
|
||
| from pypaimon.table.table import Table | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| # Transient column the helper appends before the groupby and strips | ||
| # afterwards. Sink-side schema is identical to caller-provided schema. | ||
| BUCKET_KEY_COL = "__paimon_bucket__" | ||
|
TheR1sing3un marked this conversation as resolved.
|
||
|
|
||
|
|
||
| def maybe_apply_repartition( | ||
| dataset: "ray.data.Dataset", | ||
| table: "Table", | ||
| *, | ||
| shuffle: bool, | ||
| override_num_blocks: Optional[int], | ||
| ) -> Tuple["ray.data.Dataset", bool]: | ||
| """Optionally rewrite ``dataset`` so rows are clustered for the writer. | ||
|
|
||
| Args: | ||
| dataset: The input Ray Dataset. | ||
| table: The Paimon target table (used for bucket mode + schema). | ||
| shuffle: When True, group rows by ``(partition_keys..., bucket)``. | ||
| Falls through to a warning + no-op for non-HASH_FIXED tables. | ||
| override_num_blocks: Optional. When ``shuffle=True``, used as the | ||
| ``num_partitions`` hint for the groupby shuffle. When | ||
| ``shuffle=False``, triggers a plain block rebalance to that | ||
| count. ``None`` + ``shuffle=False`` means no-op. | ||
|
|
||
| Returns: | ||
| ``(dataset, was_shuffle_applied)`` — the dataset to hand to the | ||
| sink, plus a flag the caller can use for telemetry. | ||
| """ | ||
| if not shuffle and override_num_blocks is None: | ||
| return dataset, False | ||
|
|
||
| if shuffle: | ||
| bucket_mode = table.bucket_mode() | ||
| if bucket_mode != BucketMode.HASH_FIXED: | ||
| logger.warning( | ||
| "shuffle=True requires a HASH_FIXED table; got %s. " | ||
| "Falling back to no-shuffle write.", | ||
| bucket_mode.name, | ||
| ) | ||
| shuffle = False | ||
|
|
||
| if shuffle: | ||
| partition_keys = list(table.table_schema.partition_keys or []) | ||
| extractor = table.create_row_key_extractor() | ||
| bucket_udf = _make_bucket_udf(extractor) | ||
|
|
||
| ds_with_bucket = dataset.map_batches( | ||
| bucket_udf, batch_format="pyarrow", zero_copy_batch=True, | ||
| ) | ||
| group_keys: List[str] = partition_keys + [BUCKET_KEY_COL] | ||
| grouped = ds_with_bucket.groupby( | ||
| group_keys, num_partitions=override_num_blocks, | ||
| ) | ||
| regrouped = grouped.map_groups(_identity_batch, batch_format="pyarrow") | ||
| return regrouped.drop_columns([BUCKET_KEY_COL]), True | ||
|
|
||
| # After a soft fallback, override_num_blocks may still be None — | ||
| # keep the contract that None means "no Ray-side repartition". | ||
| if override_num_blocks is None: | ||
| return dataset, False | ||
| return dataset.repartition(override_num_blocks, shuffle=False), False | ||
|
|
||
|
|
||
| def _identity_batch(batch: pa.Table) -> pa.Table: | ||
| # Some Ray versions promote ``string`` to ``large_string`` (and | ||
| # ``binary`` to ``large_binary``) while materialising blocks for | ||
| # ``groupby().map_groups``. Paimon's writer compares schemas with a | ||
| # strict ``!=`` and rejects the large variants, so coerce them back | ||
| # to the regular types here. Other Arrow types pass through. | ||
| return _coerce_large_string_types(batch) | ||
|
|
||
|
|
||
| def _coerce_large_string_types(batch: pa.Table) -> pa.Table: | ||
| needs_cast = False | ||
| fields = [] | ||
| for field in batch.schema: | ||
| if pa.types.is_large_string(field.type): | ||
| fields.append(field.with_type(pa.string())) | ||
| needs_cast = True | ||
| elif pa.types.is_large_binary(field.type): | ||
| fields.append(field.with_type(pa.binary())) | ||
| needs_cast = True | ||
| else: | ||
| fields.append(field) | ||
| return batch.cast(pa.schema(fields)) if needs_cast else batch | ||
|
|
||
|
|
||
| def _make_bucket_udf(extractor): | ||
| """Build a map_batches UDF that appends BUCKET_KEY_COL. | ||
|
|
||
| The bucket value comes from ``extract_partition_bucket_batch`` so it | ||
| matches the writer's bucket assignment for the same row exactly. | ||
| """ | ||
| def _udf(batch: pa.Table) -> pa.Table: | ||
| if batch.num_rows == 0: | ||
| return batch.append_column( | ||
| BUCKET_KEY_COL, pa.array([], type=pa.int32()) | ||
| ) | ||
| record_batch = batch.combine_chunks().to_batches()[0] | ||
| _, buckets = extractor.extract_partition_bucket_batch(record_batch) | ||
| return batch.append_column( | ||
| BUCKET_KEY_COL, pa.array(buckets, type=pa.int32()) | ||
| ) | ||
|
|
||
| return _udf | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.