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 657b0ad85b [python] Support count-limit and optimize distinct collect
aggregation (#11033)
657b0ad85b is described below
commit 657b0ad85bbbb16791d2d549cc5c71c5bbb973ef
Author: AuroraVoyage <[email protected]>
AuthorDate: Tue Nov 10 17:13:06 2026 +0800
[python] Support count-limit and optimize distinct collect aggregation
(#11033)
---
.../pypaimon/common/options/core_options.py | 9 +
.../python/read/reader/aggregate/aggregators.py | 81 +++++++--
.../pypaimon/tests/test_field_aggregators.py | 187 ++++++++++++++++++++-
3 files changed, 258 insertions(+), 19 deletions(-)
diff --git a/paimon-python/pypaimon/common/options/core_options.py
b/paimon-python/pypaimon/common/options/core_options.py
index 1428f0937b..2e65a0d0f3 100644
--- a/paimon-python/pypaimon/common/options/core_options.py
+++ b/paimon-python/pypaimon/common/options/core_options.py
@@ -2074,6 +2074,15 @@ class CoreOptions:
.default_value(False)
)
+ def field_collect_agg_count_limit(self, field_name: str) -> int:
+ return self.options.get(
+ ConfigOptions.key(
+
f'{CoreOptions.FIELDS_PREFIX}.{field_name}.{CoreOptions.COUNT_LIMIT}'
+ )
+ .int_type()
+ .default_value(2147483647) # Integer.MAX_VALUE
+ )
+
def field_nested_update_agg_nested_key(self, field_name: str) -> List[str]:
key_string = self.options.get(
ConfigOptions.key(
diff --git
a/paimon-python/pypaimon/execution/python/read/reader/aggregate/aggregators.py
b/paimon-python/pypaimon/execution/python/read/reader/aggregate/aggregators.py
index ad1cf3a342..73c5e4c6b9 100644
---
a/paimon-python/pypaimon/execution/python/read/reader/aggregate/aggregators.py
+++
b/paimon-python/pypaimon/execution/python/read/reader/aggregate/aggregators.py
@@ -103,6 +103,21 @@ _INT_TYPES = frozenset({"INT", "INTEGER"})
# SQL type names treated as floating-point.
_FLOAT_TYPES = frozenset({"FLOAT", "DOUBLE"})
+# Atomic element types whose runtime values are hashable and whose equality
+# matches a list scan, so distinct collect can use a set. ARRAY and MAP
+# elements are list/dict and are not hashable. ROW stays on the list path:
+# GenericRow equality ignores field descriptors while its hash includes them.
+_COLLECT_SET_DEDUPE_TYPES = frozenset({
+ "CHAR", "VARCHAR", "STRING",
+ "BOOLEAN",
+ "BINARY", "VARBINARY", "BYTES",
+ "TINYINT", "SMALLINT", "INT", "INTEGER", "BIGINT",
+ "FLOAT", "DOUBLE",
+ "DECIMAL", "NUMERIC", "DEC",
+ "DATE", "TIME",
+ "TIMESTAMP", "TIMESTAMP_LTZ",
+})
+
def _atomic_base_name(field_type: DataType):
"""Extract the bare SQL type name from an :class:`AtomicType`,
@@ -801,28 +816,43 @@ class FieldCollectAgg(FieldAggregator):
)
self.distinct = options.field_collect_distinct(field_name)
+ self.count_limit = options.field_collect_agg_count_limit(field_name)
+ element_base = _atomic_base_name(field_type.element)
+ self._set_dedupe = (
+ self.distinct and element_base in _COLLECT_SET_DEDUPE_TYPES
+ )
def agg_reversed(self, accumulator: Any, input_field: Any) -> Any:
- # we don't need to actually do the reverse here for this agg
- # because accumulator has been distinct, just let accumulator be
accumulator will speed up
- # distinct process
- return self.agg(accumulator, input_field)
+ # Reverse traversal supplies the newer partial result as
+ # ``accumulator`` and the older value as ``input_field``. Aggregate
+ # older before newer so count-limit matches forward ``agg``.
+ return self.agg(input_field, accumulator)
def agg(self, accumulator: Any, input_field: Any) -> Any:
if accumulator is None and input_field is None:
return None
- if (accumulator is None or input_field is None) and not self.distinct:
- return input_field if accumulator is None else accumulator
-
- if self.distinct:
- result = []
- self._collect(result, accumulator)
- self._collect(result, input_field)
+ # No truncation needed, so keep the input array as it is.
+ limit = abs(self.count_limit)
+ if input_field is None and not self.distinct and len(accumulator) <=
limit:
+ return accumulator
+ if accumulator is None and not self.distinct and len(input_field) <=
limit:
+ return input_field
+ result = []
+ # One set covers both sides, so a value already kept from the
+ # accumulator is not collected again from the input.
+ seen = set() if self._set_dedupe else None
+ if self.count_limit >= 0:
+ self._collect(result, accumulator, seen)
+ self._collect(result, input_field, seen)
return result
- else:
- return list(accumulator) + list(input_field)
+
+ # A negative limit keeps the last elements in aggregation order.
+ self._collect(result, input_field, seen)
+ self._collect(result, accumulator, seen)
+ result.reverse()
+ return result
def retract(self, accumulator: Any, retract_field: Any) -> Any:
if accumulator is None:
@@ -841,12 +871,29 @@ class FieldCollectAgg(FieldAggregator):
return result
- def _collect(self, result: List[Any], data: List[Any]):
+ def _collect(self, result: List[Any], data: List[Any], seen:
Optional[set]):
if data is None:
return
- for element in data:
- if element not in result:
- result.append(element)
+
+ limit = abs(self.count_limit)
+ if self.count_limit < 0:
+ indices = range(len(data) - 1, -1, -1)
+ else:
+ indices = range(len(data))
+
+ for i in indices:
+ if len(result) >= limit:
+ break
+ element = data[i]
+ if self.distinct:
+ if seen is not None:
+ if element in seen:
+ continue
+ elif element in result:
+ continue
+ result.append(element)
+ if seen is not None:
+ seen.add(element)
class FieldNestedUpdateAgg(FieldAggregator):
diff --git a/paimon-python/pypaimon/tests/test_field_aggregators.py
b/paimon-python/pypaimon/tests/test_field_aggregators.py
index acfb17dfd1..5b3ef3b774 100644
--- a/paimon-python/pypaimon/tests/test_field_aggregators.py
+++ b/paimon-python/pypaimon/tests/test_field_aggregators.py
@@ -967,11 +967,14 @@ class FieldListaggAggTest(unittest.TestCase):
class FieldCollectAggTest(unittest.TestCase):
- def _make(self, distinct, element_type=None):
+ def _make(self, distinct, element_type=None, count_limit=None):
if element_type is None:
element_type = AtomicType("INT")
- options = CoreOptions(Options({"fields.field0.distinct": distinct}))
+ raw = {"fields.field0.distinct": distinct}
+ if count_limit is not None:
+ raw["fields.field0.count-limit"] = count_limit
+ options = CoreOptions(Options(raw))
return create_field_aggregator(
ArrayType(True, element_type),
@@ -1170,6 +1173,186 @@ class FieldCollectAggTest(unittest.TestCase):
)
self.assertEqual(acc, [{1: "C"}])
+ def test_field_collect_agg_count_limit_positive(self):
+ agg = self._make(distinct=False, count_limit=2)
+
+ acc = agg.agg(None, [1, 2])
+ self.assertEqual(acc, [1, 2])
+
+ acc = agg.agg(acc, [3, 4])
+ self.assertEqual(acc, [1, 2])
+
+ def test_field_collect_agg_count_limit_negative(self):
+ agg = self._make(distinct=False, count_limit=-2)
+
+ acc = agg.agg(None, [1, 2])
+ self.assertEqual(acc, [1, 2])
+
+ acc = agg.agg(acc, [3, 4])
+ self.assertEqual(acc, [3, 4])
+
+ acc = agg.agg(acc, [5])
+ self.assertEqual(acc, [4, 5])
+
+ def test_field_collect_agg_count_limit_with_distinct(self):
+ # The example from the Java docs.
+ agg = self._make(distinct=True, count_limit=2)
+ self.assertEqual(agg.agg(None, [1, 2, 1, 3]), [1, 2])
+
+ agg = self._make(distinct=True, count_limit=-2)
+ self.assertEqual(agg.agg(None, [1, 2, 1, 3]), [1, 3])
+
+ def test_field_collect_agg_count_limit_with_distinct_across_inputs(self):
+ agg = self._make(distinct=True, count_limit=2)
+
+ acc = agg.agg(None, [1, 1, 2])
+ self.assertEqual(acc, [1, 2])
+
+ acc = agg.agg(acc, [2, 3])
+ self.assertEqual(acc, [1, 2])
+
+ agg = self._make(distinct=True, count_limit=-2)
+
+ acc = agg.agg(None, [1, 1, 2])
+ self.assertEqual(acc, [1, 2])
+
+ acc = agg.agg(acc, [2, 3])
+ self.assertEqual(acc, [2, 3])
+
+ def
test_field_collect_agg_count_limit_without_distinct_keeps_duplicates(self):
+ agg = self._make(distinct=False, count_limit=3)
+
+ self.assertEqual(agg.agg(None, [1, 1, 2, 3]), [1, 1, 2])
+
+ agg = self._make(distinct=False, count_limit=-3)
+ self.assertEqual(agg.agg(None, [1, 1, 2, 3]), [1, 2, 3])
+
+ def test_field_collect_agg_count_limit_zero_returns_empty(self):
+ for limit in (0, -0):
+ agg = self._make(distinct=False, count_limit=limit)
+ self.assertEqual(agg.agg(None, [1, 2]), [])
+
+ def _assert_collect_forward_equals_reversed(
+ self, distinct, count_limit, older, newer, expected
+ ):
+ agg = self._make(distinct=distinct, count_limit=count_limit)
+ forward = agg.agg(agg.agg(None, older), newer)
+ reversed_result = agg.agg_reversed(agg.agg_reversed(None, newer),
older)
+ self.assertEqual(forward, expected)
+ self.assertEqual(reversed_result, expected)
+
+ def test_field_collect_agg_forward_vs_reversed_reviewer_repro(self):
+ older = [1, 2]
+ newer = [3, 4]
+ self._assert_collect_forward_equals_reversed(
+ False, 2, older, newer, [1, 2]
+ )
+ self._assert_collect_forward_equals_reversed(
+ False, -2, older, newer, [3, 4]
+ )
+
+ def test_field_collect_agg_forward_vs_reversed_java_matrix(self):
+ older = [2, 1, 2]
+ newer = [3, 3, 1]
+ cases = [
+ (False, 3, [2, 1, 2]),
+ (True, 3, [2, 1, 3]),
+ (False, -3, [3, 3, 1]),
+ (True, -3, [2, 3, 1]),
+ (False, 0, []),
+ (True, 0, []),
+ ]
+ for distinct, count_limit, expected in cases:
+ self._assert_collect_forward_equals_reversed(
+ distinct, count_limit, older, newer, expected
+ )
+
+ def test_field_collect_agg_set_dedupe_for_atomic_types(self):
+ for sql_type in (
+ "INT", "STRING", "BOOLEAN", "DECIMAL(10, 2)",
+ "DATE", "VARBINARY(8)", "TIMESTAMP(6)",
+ ):
+ agg = self._make(distinct=True, element_type=AtomicType(sql_type))
+ self.assertTrue(agg._set_dedupe, sql_type)
+
+ agg = self._make(distinct=False)
+ self.assertFalse(agg._set_dedupe)
+
+ agg = self._make(distinct=True, element_type=AtomicType("BLOB"))
+ self.assertFalse(agg._set_dedupe)
+
+ def test_field_collect_agg_set_dedupe_across_inputs(self):
+ agg = self._make(distinct=True)
+ self.assertTrue(agg._set_dedupe)
+
+ acc = agg.agg(None, [1, 2, 2])
+ acc = agg.agg(acc, [2, 3, 3])
+ self.assertEqual(acc, [1, 2, 3])
+
+ def test_field_collect_agg_set_dedupe_with_count_limit(self):
+ agg = self._make(distinct=True, count_limit=2)
+ self.assertTrue(agg._set_dedupe)
+ self.assertEqual(agg.agg(None, [1, 1, 2, 3]), [1, 2])
+
+ agg = self._make(distinct=True, count_limit=-2)
+ self.assertEqual(agg.agg(None, [1, 2, 1, 3]), [1, 3])
+
+ agg = self._make(distinct=True, count_limit=0)
+ self.assertEqual(agg.agg(None, [1, 2]), [])
+
+ def test_field_collect_agg_list_dedupe_for_array_and_map(self):
+ agg = self._make(
+ distinct=True,
+ element_type=ArrayType(True, AtomicType("INT")),
+ )
+ self.assertFalse(agg._set_dedupe)
+ self.assertEqual(agg.agg(None, [[1], [1], [2]]), [[1], [2]])
+
+ acc = agg.agg([[1], [2]], [[2], [3]])
+ self.assertEqual(acc, [[1], [2], [3]])
+
+ agg = self._make(
+ distinct=True,
+ element_type=MapType(True, AtomicType("INT"),
AtomicType("STRING")),
+ )
+ self.assertFalse(agg._set_dedupe)
+ self.assertEqual(
+ agg.agg(None, [{1: "A"}, {1: "A"}, {2: "B"}]),
+ [{1: "A"}, {2: "B"}],
+ )
+
+ def test_field_collect_agg_row_same_value_different_field_name(self):
+ fields_a = [DataField(0, "id", AtomicType("INT"))]
+ fields_b = [DataField(0, "other", AtomicType("INT"))]
+ agg = self._make(
+ distinct=True,
+ element_type=RowType(True, fields_a),
+ )
+ self.assertFalse(agg._set_dedupe)
+
+ left = self.row(1, fields=fields_a)
+ right = self.row(1, fields=fields_b)
+ self.assertEqual(agg.agg(None, [left, right]), [left])
+
+ def test_field_collect_agg_float_nan_signed_zero_and_binary(self):
+ agg = self._make(distinct=True, element_type=AtomicType("DOUBLE"))
+ self.assertTrue(agg._set_dedupe)
+
+ nan = float("nan")
+ result = agg.agg(None, [nan, float("nan"), 1.0])
+ self.assertEqual(len(result), 3)
+ self.assertTrue(math.isnan(result[0]))
+ self.assertTrue(math.isnan(result[1]))
+ self.assertEqual(result[2], 1.0)
+
+ self.assertEqual(agg.agg(None, [0.0, -0.0, 1.0]), [0.0, 1.0])
+
+ agg = self._make(distinct=True,
element_type=AtomicType("VARBINARY(8)"))
+ self.assertEqual(
+ agg.agg(None, [b"\x01\x02", bytes([1, 2]), b"\x03"]),
+ [b"\x01\x02", b"\x03"],
+ )
+
class FieldNestedUpdateAggTest(unittest.TestCase):
IDENTIFIER = "nested_update"