This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new 3caad5280b [python] Fix floating-point partition bounds in manifest 
lists (#11317)
3caad5280b is described below

commit 3caad5280bf9a01c1164debb820f540380b58b21
Author: Zouxxyy <[email protected]>
AuthorDate: Sun Nov 22 18:53:49 2026 +0800

    [python] Fix floating-point partition bounds in manifest lists (#11317)
---
 .../python/globalindex/btree/composite_key.py      | 15 +-----
 .../python/read/reader/sort_merge_reader.py        | 19 ++-----
 .../python/write/writer/single_file_writer.py      |  8 +--
 .../pypaimon/manifest/manifest_file_manager.py     | 40 +++++++++++---
 .../pypaimon/tests/metadata_stats_mode_test.py     | 61 ++++++++++++++++++++++
 paimon-python/pypaimon/tests/numeric_utils_test.py | 14 +++--
 paimon-python/pypaimon/utils/numeric_utils.py      | 25 ++++++++-
 7 files changed, 139 insertions(+), 43 deletions(-)

diff --git 
a/paimon-python/pypaimon/execution/python/globalindex/btree/composite_key.py 
b/paimon-python/pypaimon/execution/python/globalindex/btree/composite_key.py
index 6e41c20292..2f695f4305 100644
--- a/paimon-python/pypaimon/execution/python/globalindex/btree/composite_key.py
+++ b/paimon-python/pypaimon/execution/python/globalindex/btree/composite_key.py
@@ -25,6 +25,7 @@ from pypaimon.execution.python.globalindex.key_serializer 
import (
     KeySerializer, create_serializer, _read_var_len_int, _write_var_len_int,
     _parse_precision,
 )
+from pypaimon.utils.numeric_utils import java_float_compare
 
 
 class CompositeKeySerializer(KeySerializer):
@@ -32,7 +33,7 @@ class CompositeKeySerializer(KeySerializer):
         self._types = [field.type.type.upper() for field in fields]
         self._serializers = [create_serializer(field.type) for field in fields]
         self._comparators = [
-            _java_float_compare if type_name in ('FLOAT', 'DOUBLE')
+            java_float_compare if type_name in ('FLOAT', 'DOUBLE')
             else serializer.create_comparator()
             for type_name, serializer in zip(self._types, self._serializers)
         ]
@@ -139,15 +140,3 @@ def compare_nullable(left, right, comparator):
     if right is None:
         return 1
     return comparator(left, right)
-
-
-def _java_float_compare(left, right):
-    left, right = float(left), float(right)
-    if math.isnan(left):
-        return 0 if math.isnan(right) else 1
-    if math.isnan(right):
-        return -1
-    if left == right == 0:
-        return (math.copysign(1, left) > math.copysign(1, right)) - (
-            math.copysign(1, left) < math.copysign(1, right))
-    return (left > right) - (left < right)
diff --git 
a/paimon-python/pypaimon/execution/python/read/reader/sort_merge_reader.py 
b/paimon-python/pypaimon/execution/python/read/reader/sort_merge_reader.py
index f02abab936..531461ebd5 100644
--- a/paimon-python/pypaimon/execution/python/read/reader/sort_merge_reader.py
+++ b/paimon-python/pypaimon/execution/python/read/reader/sort_merge_reader.py
@@ -16,7 +16,6 @@
 # under the License.
 
 import heapq
-import math
 from typing import Any, Callable, List, Optional
 
 from pypaimon.execution.python.read.reader.deduplicate_merge_function import \
@@ -29,6 +28,7 @@ from pypaimon.table.row.internal_row import InternalRow
 from pypaimon.table.row.key_value import KeyValue
 from pypaimon.read.sequence_fields import (
     _base_type_name, _COMPARABLE_TYPE_NAMES, is_comparable_seq_field)
+from pypaimon.utils.numeric_utils import java_float_compare
 
 
 class SortMergeReaderWithMinHeap(RecordReader):
@@ -238,19 +238,10 @@ def _row_field_comparator(
                 raise ValueError(f"Unsupported {fields[idx].type} comparison")
 
             if floating_flags[pos]:
-                # Java Float/Double.compare: all NaNs tie above +inf, and
-                # -0.0 precedes +0.0. Primary-key equality is unchanged.
-                if math.isnan(val1):
-                    if not math.isnan(val2):
-                        return sign
-                    continue
-                if math.isnan(val2):
-                    return -sign
-                if val1 == val2 == 0.0:
-                    val1 = math.copysign(1.0, val1)
-                    val2 = math.copysign(1.0, val2)
-
-            if val1 < val2:
+                difference = java_float_compare(val1, val2)
+                if difference:
+                    return sign * difference
+            elif val1 < val2:
                 return -sign
             elif val1 > val2:
                 return sign
diff --git 
a/paimon-python/pypaimon/execution/python/write/writer/single_file_writer.py 
b/paimon-python/pypaimon/execution/python/write/writer/single_file_writer.py
index 3e1d49d6e6..44bb2fff7f 100644
--- a/paimon-python/pypaimon/execution/python/write/writer/single_file_writer.py
+++ b/paimon-python/pypaimon/execution/python/write/writer/single_file_writer.py
@@ -15,17 +15,13 @@
 # specific language governing permissions and limitations
 # under the License.
 
-import math
 from contextlib import suppress
 
 import pyarrow.parquet as pq
 
 from pypaimon.common.options.core_options import CoreOptions
 from pypaimon.execution.python.write.format_file_writer import 
parquet_write_data, parquet_write_schema
-
-
-def _float_sort_key(value):
-    return value, math.copysign(1.0, value)
+from pypaimon.utils.numeric_utils import java_floating_sort_key
 
 
 class SingleFileWriter:
@@ -81,7 +77,7 @@ class SingleFileWriter:
                             value for value in (previous[key], current[key])
                             if value is not None
                         ]
-                        sort_key = _float_sort_key if values and 
isinstance(values[0], float) else None
+                        sort_key = java_floating_sort_key if values and 
isinstance(values[0], float) else None
                         current[key] = choose(values, key=sort_key) if values 
else None
                 self.column_stats[field.name] = current
         except Exception:
diff --git a/paimon-python/pypaimon/manifest/manifest_file_manager.py 
b/paimon-python/pypaimon/manifest/manifest_file_manager.py
index d52b9f50d1..3b6dcf534f 100644
--- a/paimon-python/pypaimon/manifest/manifest_file_manager.py
+++ b/paimon-python/pypaimon/manifest/manifest_file_manager.py
@@ -15,6 +15,7 @@
 # specific language governing permissions and limitations
 # under the License.
 
+import math
 from concurrent.futures import ThreadPoolExecutor
 from io import BytesIO
 from typing import Callable, List, Optional
@@ -41,10 +42,12 @@ from pypaimon.manifest.schema.manifest_entry import 
(MANIFEST_ENTRY_SCHEMA,
                                                      ManifestEntry)
 from pypaimon.manifest.schema.manifest_file_meta import ManifestFileMeta
 from pypaimon.manifest.schema.simple_stats import SimpleStats
+from pypaimon.schema.data_types import AtomicType
 from pypaimon.table.row.generic_row import (GenericRow,
                                             GenericRowDeserializer,
                                             GenericRowSerializer)
 from pypaimon.table.row.binary_row import BinaryRow
+from pypaimon.utils.numeric_utils import java_float_compare
 
 
 _MANIFEST_FIELD_NAMES = (
@@ -52,6 +55,28 @@ _MANIFEST_FIELD_NAMES = (
 _MANIFEST_PREFIX_TYPES = ('int', 'int', 'bytes', 'int', 'int')
 
 
+def _floating_partition_bounds(values):
+    """Return the min and max of non-null partition values in Java 
floating-point order."""
+    minimum = maximum = None
+    for value in values:
+        if value is None:
+            continue
+        value = float(value)
+        if minimum is None:
+            minimum = maximum = value
+            continue
+        compared_to_minimum = java_float_compare(value, minimum)
+        if compared_to_minimum < 0:
+            minimum = value
+        elif compared_to_minimum > 0 and java_float_compare(value, maximum) > 
0:
+            maximum = value
+    if minimum is None:
+        return None, None
+    # Store a fixed NaN representation regardless of input order.
+    return (math.nan if math.isnan(minimum) else minimum,
+            math.nan if math.isnan(maximum) else maximum)
+
+
 def _read_manifest_records(buffer, early_entry_filter, partition_filter,
                            partition_fields):
     """Yield manifest records, skipping ``_FILE`` before decoding when 
possible."""
@@ -488,12 +513,15 @@ class ManifestFileManager:
 
         partition_columns = list(zip(*(entry.partition.values for entry in 
entries))) if entries else []
         partition_null_counts = [sum(1 for value in col if value is None) for 
col in partition_columns]
-        partition_min_stats = [
-            min((v for v in col if v is not None), default=None) for col in 
partition_columns
-        ]
-        partition_max_stats = [
-            max((v for v in col if v is not None), default=None) for col in 
partition_columns
-        ]
+        partition_min_stats, partition_max_stats = [], []
+        for field, col in zip(self.partition_keys_fields, partition_columns):
+            if isinstance(field.type, AtomicType) and field.type.type.upper() 
in ('FLOAT', 'REAL', 'DOUBLE'):
+                minimum, maximum = _floating_partition_bounds(col)
+            else:
+                minimum = min((v for v in col if v is not None), default=None)
+                maximum = max((v for v in col if v is not None), default=None)
+            partition_min_stats.append(minimum)
+            partition_max_stats.append(maximum)
 
         min_row_id = None
         max_row_id = None
diff --git a/paimon-python/pypaimon/tests/metadata_stats_mode_test.py 
b/paimon-python/pypaimon/tests/metadata_stats_mode_test.py
index 44c0b64435..8f463c4401 100644
--- a/paimon-python/pypaimon/tests/metadata_stats_mode_test.py
+++ b/paimon-python/pypaimon/tests/metadata_stats_mode_test.py
@@ -15,6 +15,7 @@
 # under the License.
 
 import math
+import struct
 from datetime import datetime
 
 import pyarrow as pa
@@ -74,6 +75,66 @@ def _bounds(stats):
                  for row in (stats.min_values, stats.max_values))
 
 
[email protected]('typ', [pa.float32(), pa.float64()], ids=['float', 
'double'])
[email protected]('values, expected_min, expected_max', [
+    pytest.param([5.0, math.nan], 5.0, math.nan, id='nan-last'),
+    pytest.param([math.nan, 5.0], 5.0, math.nan, id='nan-first'),
+    pytest.param([-0.0, +0.0], -0.0, +0.0, id='negative-zero-first'),
+    pytest.param([+0.0, -0.0], -0.0, +0.0, id='positive-zero-first'),
+    pytest.param([-0.0, -0.0], -0.0, -0.0, id='negative-zero-only'),
+    pytest.param([+0.0, +0.0], +0.0, +0.0, id='positive-zero-only'),
+    pytest.param([math.inf, None, -math.inf], -math.inf, math.inf, 
id='infinities'),
+    pytest.param([math.inf, math.inf], math.inf, math.inf, 
id='positive-infinity-only'),
+    pytest.param([-math.inf, -math.inf], -math.inf, -math.inf, 
id='negative-infinity-only'),
+    pytest.param([None, math.nan, math.inf], math.inf, math.nan, 
id='nan-and-infinity'),
+    pytest.param([5.0, None, -2.0, None], -2.0, 5.0, 
id='mixed-numbers-and-nulls'),
+    pytest.param([math.nan, -math.nan], math.nan, math.nan, id='all-nan'),
+    pytest.param([None, -math.nan, None], math.nan, math.nan, 
id='null-and-nan'),
+    pytest.param([None, None], None, None, id='all-null'),
+])
+def test_manifest_list_floating_partition_bounds(tmp_path, typ, values, 
expected_min, expected_max):
+    catalog = CatalogFactory.create({'warehouse': str(tmp_path)})
+    catalog.create_database('db', False)
+    schema = pa.schema([('id', pa.int32()), ('p', typ), ('seq', pa.int32())])
+    catalog.create_table('db.t', Schema.from_pyarrow_schema(
+        schema, partition_keys=['p', 'seq'],
+        options={'bucket': '-1', 'write.native.enabled': 'false', 
'commit.native.enabled': 'false'}), False)
+    table = catalog.get_table('db.t')
+    builder = table.new_batch_write_builder()
+    messages = []
+    # A distinct partition per entry keeps equal zeros and repeated NULLs in 
the same commit.
+    for i, value in enumerate(values):
+        writer = builder.new_write()
+        try:
+            writer.write_arrow(pa.table({'id': [i], 'p': [value], 'seq': [i]}, 
schema=schema))
+            messages.extend(writer.prepare_commit())
+        finally:
+            writer.close()
+    commit = builder.new_commit()
+    try:
+        commit.commit(messages)
+    finally:
+        commit.close()
+
+    manifest, = 
ManifestListManager(table).read_delta(table.snapshot_manager().get_latest_snapshot())
+    assert manifest.num_added_files == len(values)
+    entries = ManifestFileManager(table).read(manifest.file_name)
+    assert [entry.partition.get_field(1) for entry in entries] == 
list(range(len(values)))
+    stats = manifest.partition_stats
+    minimum, maximum = _bounds(stats)
+    assert stats.null_counts == [values.count(None), 0]
+    assert (minimum[1], maximum[1]) == (0, len(values) - 1)
+    encoding = '>f' if typ == pa.float32() else '>d'
+    for actual, expected in ((minimum[0], expected_min), (maximum[0], 
expected_max)):
+        if expected is None:
+            assert actual is None
+        elif math.isnan(expected):
+            assert math.isnan(actual)
+        else:
+            # Comparing the IEEE bits distinguishes -0.0 from +0.0.
+            assert struct.pack(encoding, actual) == struct.pack(encoding, 
expected)
+
+
 @pytest.mark.parametrize('mode', [None, 'truncate(16)', 'counts', 'full', 
'none'])
 def test_append_manifest_stats_modes(tmp_path, mode):
     table = _write(tmp_path, pa.table({
diff --git a/paimon-python/pypaimon/tests/numeric_utils_test.py 
b/paimon-python/pypaimon/tests/numeric_utils_test.py
index 874266007d..5b263d479d 100644
--- a/paimon-python/pypaimon/tests/numeric_utils_test.py
+++ b/paimon-python/pypaimon/tests/numeric_utils_test.py
@@ -15,14 +15,22 @@
 # specific language governing permissions and limitations
 # under the License.
 
-"""Golden numeric digits from Java 8, 11 and 17 Double.toString."""
+"""Tests for Java-compatible numeric formatting and ordering."""
 
-from decimal import Decimal
+import math
 import struct
+from decimal import Decimal
 
 import pytest
 
-from pypaimon.utils.numeric_utils import java_double_decimal_text
+from pypaimon.utils.numeric_utils import java_double_decimal_text, 
java_floating_sort_key
+
+
+def test_java_floating_sort_key():
+    ordered_values = [-math.inf, -1.0, -0.0, +0.0, 1.0, math.inf, math.nan]
+    keys = [java_floating_sort_key(value) for value in ordered_values]
+    assert all(left < right for left, right in zip(keys, keys[1:]))
+    assert java_floating_sort_key(-math.nan) == keys[-1]
 
 
 @pytest.mark.parametrize('bits,expected', [
diff --git a/paimon-python/pypaimon/utils/numeric_utils.py 
b/paimon-python/pypaimon/utils/numeric_utils.py
index a44ec07cfa..2a61c2843b 100644
--- a/paimon-python/pypaimon/utils/numeric_utils.py
+++ b/paimon-python/pypaimon/utils/numeric_utils.py
@@ -15,11 +15,34 @@
 # specific language governing permissions and limitations
 # under the License.
 
-"""Java numeric text shared by partition paths and value conversions."""
+"""Java-compatible numeric formatting and ordering."""
 
 import math
 import struct
 from decimal import Decimal
+from functools import cmp_to_key
+
+
+def java_float_compare(left: float, right: float) -> int:
+    """Compare non-null floats in Java Float.compare and Double.compare order.
+
+    Negative zero precedes positive zero, and all NaNs tie above positive 
infinity.
+    """
+    left, right = float(left), float(right)
+    if left == right:
+        if left == 0.0:
+            left_sign = math.copysign(1.0, left)
+            right_sign = math.copysign(1.0, right)
+            return (left_sign > right_sign) - (left_sign < right_sign)
+        return 0
+    if left < right:
+        return -1
+    if left > right:
+        return 1
+    return math.isnan(left) - math.isnan(right)
+
+
+java_floating_sort_key = cmp_to_key(java_float_compare)
 
 
 def java_floating_string(value, single_precision=False) -> str:

Reply via email to