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 df9785bb6d [core] Deduplicate initial listagg tokens (#11256)
df9785bb6d is described below

commit df9785bb6dd1a06d6adea6350b6a332540cee491
Author: YueZhang <[email protected]>
AuthorDate: Thu Nov 19 02:41:06 2026 -0500

    [core] Deduplicate initial listagg tokens (#11256)
---
 .../primary-key-table/merge-engine/aggregation.mdx |   2 +-
 .../compact/aggregate/FieldListaggAgg.java         |  79 ++++++--
 .../table/PrimaryKeyListaggDistinctTest.java       | 207 +++++++++++++++++++++
 3 files changed, 275 insertions(+), 13 deletions(-)

diff --git a/docs/docs/primary-key-table/merge-engine/aggregation.mdx 
b/docs/docs/primary-key-table/merge-engine/aggregation.mdx
index 0c47f78432..b0ec024956 100644
--- a/docs/docs/primary-key-table/merge-engine/aggregation.mdx
+++ b/docs/docs/primary-key-table/merge-engine/aggregation.mdx
@@ -165,7 +165,7 @@ count of distinct event IDs.
   The listagg function concatenates multiple string values into a single 
string.
   It supports STRING data type.
   Each field not part of the primary keys can be given a list agg delimiter, 
specified by the fields.\<field-name>.list-agg-delimiter table property, 
otherwise it will use "," as default.
-  You can use `fields.<field-name>.distinct=true` to deduplicate values split 
by the `fields.<field-name>.list-agg-delimiter`.
+  With `fields.<field-name>.distinct=true`, values are split by the 
`fields.<field-name>.list-agg-delimiter` and each non-blank token is kept once, 
in the order first seen. This also applies to the first value, so merging `a,a` 
with `b` produces `a,b`.
 
 ### bool_and
   The bool_and function evaluates whether all values in a boolean set are true.
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/mergetree/compact/aggregate/FieldListaggAgg.java
 
b/paimon-core/src/main/java/org/apache/paimon/mergetree/compact/aggregate/FieldListaggAgg.java
index 364993b558..4c62e2f238 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/mergetree/compact/aggregate/FieldListaggAgg.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/mergetree/compact/aggregate/FieldListaggAgg.java
@@ -51,13 +51,22 @@ public class FieldListaggAgg extends FieldAggregator {
 
     @Override
     public Object agg(Object accumulator, Object inputField) {
-        if (inputField == null || StringUtils.isBlank(inputField.toString())) {
-            return accumulator;
+        boolean normalizeAccumulator = distinct && 
delimiterBinaryString.getSizeInBytes() > 0;
+        if (inputField == null || isBlank((BinaryString) inputField)) {
+            if (!normalizeAccumulator
+                    || accumulator == null
+                    || isBlank((BinaryString) accumulator)) {
+                return accumulator;
+            }
+            inputField = BinaryString.EMPTY_UTF8;
         }
         // ordered by type root definition
 
-        if (accumulator == null || 
StringUtils.isBlank(accumulator.toString())) {
-            return inputField;
+        if (accumulator == null || isBlank((BinaryString) accumulator)) {
+            if (!normalizeAccumulator) {
+                return inputField;
+            }
+            accumulator = BinaryString.EMPTY_UTF8;
         }
 
         BinaryString mergeFieldSD = (BinaryString) accumulator;
@@ -67,21 +76,46 @@ public class FieldListaggAgg extends FieldAggregator {
             BinaryString[] accumulatorTokens =
                     splitByWholeSeparatorPreserveAllTokens(mergeFieldSD, 
delimiterBinaryString);
             Set<BinaryString> existingTokens = new 
HashSet<>(accumulatorTokens.length);
-            for (BinaryString token : accumulatorTokens) {
-                existingTokens.add(token);
+            // Rebuilt only after finding a blank or duplicate token to drop.
+            List<BinaryString> result = null;
+            for (int i = 0; i < accumulatorTokens.length; i++) {
+                BinaryString token = accumulatorTokens[i];
+                if (!normalizeAccumulator) {
+                    existingTokens.add(token);
+                    continue;
+                }
+                boolean keep = !isBlank(token) && existingTokens.add(token);
+                if (result != null) {
+                    if (keep) {
+                        appendToken(result, token);
+                    }
+                } else if (!keep) {
+                    result = new ArrayList<>();
+                    for (int j = 0; j < i; j++) {
+                        appendToken(result, accumulatorTokens[j]);
+                    }
+                }
             }
 
-            List<BinaryString> result = new ArrayList<>();
-            result.add(mergeFieldSD);
+            boolean changed = result != null;
+            if (result == null) {
+                result = new ArrayList<>();
+                if (mergeFieldSD.getSizeInBytes() > 0) {
+                    result.add(mergeFieldSD);
+                }
+            }
             for (BinaryString str :
                     splitByWholeSeparatorPreserveAllTokens(inFieldSD, 
delimiterBinaryString)) {
-                if (StringUtils.isBlank(str.toString()) || 
existingTokens.contains(str)) {
+                if (isBlank(str) || !existingTokens.add(str)) {
                     continue;
                 }
 
-                existingTokens.add(str);
-                result.add(delimiterBinaryString);
-                result.add(str);
+                appendToken(result, str);
+                changed = true;
+            }
+
+            if (!changed) {
+                return mergeFieldSD;
             }
 
             if (result.size() == 1) {
@@ -93,4 +127,25 @@ public class FieldListaggAgg extends FieldAggregator {
 
         return BinaryStringUtils.concat(mergeFieldSD, delimiterBinaryString, 
inFieldSD);
     }
+
+    private void appendToken(List<BinaryString> result, BinaryString token) {
+        if (!result.isEmpty()) {
+            result.add(delimiterBinaryString);
+        }
+        result.add(token);
+    }
+
+    /** Same as {@link StringUtils#isBlank}, but avoids decoding ASCII input 
to a Java string. */
+    private static boolean isBlank(BinaryString str) {
+        for (int i = 0; i < str.getSizeInBytes(); i++) {
+            byte b = str.byteAt(i);
+            if (b < 0) {
+                return StringUtils.isBlank(str.toString());
+            }
+            if (!Character.isWhitespace(b)) {
+                return false;
+            }
+        }
+        return true;
+    }
 }
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyListaggDistinctTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyListaggDistinctTest.java
new file mode 100644
index 0000000000..c776a2a228
--- /dev/null
+++ 
b/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyListaggDistinctTest.java
@@ -0,0 +1,207 @@
+/*
+ * 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.
+ */
+
+package org.apache.paimon.table;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.data.BinaryString;
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.sink.StreamTableCommit;
+import org.apache.paimon.table.sink.StreamTableWrite;
+import org.apache.paimon.types.DataTypes;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.SoftAssertions.assertSoftly;
+
+/** Tests for distinct listagg tokens across primary-key writes and 
compaction. */
+class PrimaryKeyListaggDistinctTest extends TableTestBase {
+
+    static Stream<Arguments> listaggCases() {
+        return Stream.of(false, true)
+                .flatMap(
+                        partial ->
+                                Stream.of(false, true)
+                                        .flatMap(
+                                                separate ->
+                                                        Stream.of(",", "::")
+                                                                .map(
+                                                                        
delimiter ->
+                                                                               
 Arguments.of(
+                                                                               
         partial,
+                                                                               
         separate,
+                                                                               
         delimiter))));
+    }
+
+    @ParameterizedTest
+    @MethodSource("listaggCases")
+    void testDistinctListaggFirstInput(
+            boolean partialUpdate, boolean separateCommits, String delimiter) 
throws Exception {
+        FileStoreTable table = createTable(partialUpdate, delimiter, true);
+        try (StreamTableWrite write = table.newWrite("contract");
+                StreamTableCommit commit = table.newCommit("contract")) {
+            write.write(GenericRow.of(1, BinaryString.fromString("a" + 
delimiter + "a"), 1L));
+            if (separateCommits) {
+                commit.commit(0, write.prepareCommit(false, 0));
+            }
+            write.write(GenericRow.of(1, BinaryString.fromString("b"), 2L));
+            commit.commit(1, write.prepareCommit(false, 1));
+            List<String> before =
+                    read(table).stream()
+                            .map(row -> row.getString(1).toString())
+                            .collect(Collectors.toList());
+            write.compact(BinaryRow.EMPTY_ROW, 0, true);
+            commit.commit(2, write.prepareCommit(true, 2));
+            List<String> after =
+                    read(table).stream()
+                            .map(row -> row.getString(1).toString())
+                            .collect(Collectors.toList());
+            assertSoftly(
+                    softly -> {
+                        softly.assertThat(before).containsExactly("a" + 
delimiter + "b");
+                        softly.assertThat(after).containsExactly("a" + 
delimiter + "b");
+                    });
+        }
+    }
+
+    static Stream<Arguments> reversedCases() {
+        return Stream.of(
+                Arguments.of(false, false),
+                Arguments.of(false, true),
+                Arguments.of(true, false),
+                Arguments.of(true, true));
+    }
+
+    @ParameterizedTest
+    @MethodSource("reversedCases")
+    void testReversedSequenceGroup(boolean separateCommits, boolean firstNull) 
throws Exception {
+        FileStoreTable table = createTable(true, ",", true);
+        try (StreamTableWrite write = table.newWrite("contract");
+                StreamTableCommit commit = table.newCommit("contract")) {
+            write.write(GenericRow.of(1, firstNull ? null : 
BinaryString.fromString("b"), 2L));
+            if (separateCommits) {
+                commit.commit(0, write.prepareCommit(false, 0));
+            }
+            write.write(GenericRow.of(1, BinaryString.fromString("a,a"), 1L));
+            commit.commit(1, write.prepareCommit(false, 1));
+            List<String> before =
+                    read(table).stream()
+                            .map(row -> row.getString(1).toString())
+                            .collect(Collectors.toList());
+            write.compact(BinaryRow.EMPTY_ROW, 0, true);
+            commit.commit(2, write.prepareCommit(true, 2));
+            List<String> after =
+                    read(table).stream()
+                            .map(row -> row.getString(1).toString())
+                            .collect(Collectors.toList());
+            String expected = firstNull ? "a" : "a,b";
+            assertSoftly(
+                    softly -> {
+                        softly.assertThat(before).containsExactly(expected);
+                        softly.assertThat(after).containsExactly(expected);
+                    });
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testNonDistinctPreservesTokens(boolean partialUpdate) throws 
Exception {
+        FileStoreTable table = createTable(partialUpdate, ",", false);
+        try (StreamTableWrite write = table.newWrite("contract");
+                StreamTableCommit commit = table.newCommit("contract")) {
+            write.write(GenericRow.of(1, BinaryString.fromString("a,a"), 1L));
+            write.write(GenericRow.of(1, BinaryString.fromString("b"), 2L));
+            commit.commit(0, write.prepareCommit(false, 0));
+            assertThat(read(table))
+                    .extracting(row -> row.getString(1).toString())
+                    .containsExactly("a,a,b");
+        }
+    }
+
+    private FileStoreTable createTable(boolean partialUpdate, String 
delimiter, boolean distinct)
+            throws Exception {
+        Schema.Builder schema =
+                Schema.newBuilder()
+                        .column("k", DataTypes.INT())
+                        .column("v", DataTypes.STRING())
+                        .column("seq", DataTypes.BIGINT())
+                        .primaryKey("k")
+                        .option(CoreOptions.BUCKET.key(), "1")
+                        .option("merge-engine", partialUpdate ? 
"partial-update" : "aggregation")
+                        .option("fields.v.aggregate-function", "listagg")
+                        .option("fields.v.distinct", String.valueOf(distinct))
+                        .option("fields.v.list-agg-delimiter", delimiter)
+                        
.option(CoreOptions.NUM_SORTED_RUNS_COMPACTION_TRIGGER.key(), "99");
+        if (partialUpdate) {
+            schema.option("fields.seq.sequence-group", "v");
+        } else {
+            schema.option("fields.seq.aggregate-function", "max");
+        }
+        catalog.createTable(identifier(), schema.build(), false);
+        return (FileStoreTable) catalog.getTable(identifier());
+    }
+
+    static Stream<Arguments> emptyDelimiterCases() {
+        return Stream.of(
+                Arguments.of(false, false),
+                Arguments.of(false, true),
+                Arguments.of(true, false),
+                Arguments.of(true, true));
+    }
+
+    @ParameterizedTest
+    @MethodSource("emptyDelimiterCases")
+    void testEmptyDelimiterPreservesTokens(boolean partialUpdate, boolean 
separateCommits)
+            throws Exception {
+        FileStoreTable table = createTable(partialUpdate, "", true);
+        try (StreamTableWrite write = table.newWrite("contract");
+                StreamTableCommit commit = table.newCommit("contract")) {
+            write.write(GenericRow.of(1, BinaryString.fromString("a b"), 1L));
+            if (separateCommits) {
+                commit.commit(0, write.prepareCommit(false, 0));
+            }
+            write.write(GenericRow.of(1, BinaryString.fromString("b"), 2L));
+            commit.commit(1, write.prepareCommit(false, 1));
+            List<String> before =
+                    read(table).stream()
+                            .map(row -> row.getString(1).toString())
+                            .collect(Collectors.toList());
+            write.compact(BinaryRow.EMPTY_ROW, 0, true);
+            commit.commit(2, write.prepareCommit(true, 2));
+            List<String> after =
+                    read(table).stream()
+                            .map(row -> row.getString(1).toString())
+                            .collect(Collectors.toList());
+            assertSoftly(
+                    softly -> {
+                        softly.assertThat(before).containsExactly("a b");
+                        softly.assertThat(after).containsExactly("a b");
+                    });
+        }
+    }
+}

Reply via email to