Copilot commented on code in PR #17247:
URL: https://github.com/apache/pinot/pull/17247#discussion_r2573539549


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/DistinctOperator.java:
##########
@@ -40,31 +43,85 @@
  */
 public class DistinctOperator extends BaseOperator<DistinctResultsBlock> {
   private static final String EXPLAIN_NAME = "DISTINCT";
+  private static final int UNLIMITED_ROWS = Integer.MAX_VALUE;
 
   private final IndexSegment _indexSegment;
   private final QueryContext _queryContext;
   private final BaseProjectOperator<?> _projectOperator;
 
   private int _numDocsScanned = 0;
+  private final int _maxRowsInDistinct;
+  private final int _numRowsWithoutChangeInDistinct;
+  private int _numRowsWithoutNewDistinct = 0;
+  private boolean _hitMaxRowsLimit = false;
+  private boolean _hitNoChangeLimit = false;
 
   public DistinctOperator(IndexSegment indexSegment, QueryContext queryContext,
       BaseProjectOperator<?> projectOperator) {
     _indexSegment = indexSegment;
     _queryContext = queryContext;
     _projectOperator = projectOperator;
+    Map<String, String> queryOptions = queryContext.getQueryOptions();
+    if (queryOptions != null) {
+      Integer maxRowsInDistinct = 
QueryOptionsUtils.getMaxRowsInDistinct(queryOptions);
+      _maxRowsInDistinct = maxRowsInDistinct != null ? maxRowsInDistinct : 
UNLIMITED_ROWS;
+      Integer numRowsWithoutChange = 
QueryOptionsUtils.getNumRowsWithoutChangeInDistinct(queryOptions);
+      _numRowsWithoutChangeInDistinct =
+          numRowsWithoutChange != null ? numRowsWithoutChange : UNLIMITED_ROWS;
+    } else {
+      _maxRowsInDistinct = UNLIMITED_ROWS;
+      _numRowsWithoutChangeInDistinct = UNLIMITED_ROWS;
+    }
   }
 
   @Override
   protected DistinctResultsBlock getNextBlock() {
     DistinctExecutor executor = 
DistinctExecutorFactory.getDistinctExecutor(_projectOperator, _queryContext);
+    executor.setMaxRowsToProcess(_maxRowsInDistinct);
     ValueBlock valueBlock;
+    boolean enforceRowLimit = _maxRowsInDistinct != UNLIMITED_ROWS;
+    boolean enforceNoChangeLimit = _numRowsWithoutChangeInDistinct != 
UNLIMITED_ROWS;
     while ((valueBlock = _projectOperator.nextBlock()) != null) {
-      _numDocsScanned += valueBlock.getNumDocs();
-      if (executor.process(valueBlock)) {
+      if (enforceRowLimit && executor.getRemainingRowsToProcess() <= 0) {
+        _hitMaxRowsLimit = true;
         break;
       }
+      int rowsRemainingBefore = executor.getRemainingRowsToProcess();
+      int distinctCountBeforeBlock = enforceNoChangeLimit ? 
executor.getNumDistinctRowsCollected() : -1;
+      boolean satisfied = executor.process(valueBlock);
+      int rowsRemainingAfter = executor.getRemainingRowsToProcess();
+      int docsProcessedForLimit;
+      if (enforceRowLimit && rowsRemainingBefore != UNLIMITED_ROWS && 
rowsRemainingAfter != UNLIMITED_ROWS) {
+        docsProcessedForLimit = Math.max(0, rowsRemainingBefore - 
rowsRemainingAfter);
+      } else {
+        docsProcessedForLimit = valueBlock.getNumDocs();
+      }

Review Comment:
   The calculation of `docsProcessedForLimit` has redundant checks. If 
`enforceRowLimit` is true and both remaining values are not `UNLIMITED_ROWS`, 
we compute the difference. However, when `setMaxRowsToProcess` is called on 
line 80, `_rowsRemaining` will never be `UNLIMITED_ROWS` if `_maxRowsInDistinct 
!= UNLIMITED_ROWS`. This means the `rowsRemainingBefore != UNLIMITED_ROWS && 
rowsRemainingAfter != UNLIMITED_ROWS` check is redundant when `enforceRowLimit` 
is true. Simplify to: `docsProcessedForLimit = enforceRowLimit ? Math.max(0, 
rowsRemainingBefore - rowsRemainingAfter) : valueBlock.getNumDocs();`
   ```suggestion
         docsProcessedForLimit = enforceRowLimit
             ? Math.max(0, rowsRemainingBefore - rowsRemainingAfter)
             : valueBlock.getNumDocs();
   ```



##########
pinot-core/src/main/java/org/apache/pinot/core/query/distinct/DistinctExecutorFactory.java:
##########
@@ -56,6 +56,13 @@ public static DistinctExecutor 
getDistinctExecutor(BaseProjectOperator<?> projec
       QueryContext queryContext) {
     List<ExpressionContext> expressions = queryContext.getSelectExpressions();
     int limit = queryContext.getLimit();
+    if (queryContext.getQueryOptions() != null) {
+      Integer maxRowsInDistinct =
+          
org.apache.pinot.common.utils.config.QueryOptionsUtils.getMaxRowsInDistinct(queryContext.getQueryOptions());
+      if (maxRowsInDistinct != null) {
+        limit = Math.min(limit, maxRowsInDistinct);
+      }
+    }

Review Comment:
   This logic modifies the `limit` variable but doesn't communicate the intent 
clearly. The `limit` is being used for the distinct table capacity, but 
`maxRowsInDistinct` controls the number of rows to scan, which are conceptually 
different. This creates confusion because the distinct table might collect 
fewer distinct values than its capacity if early termination kicks in. Consider 
using a separate variable like `effectiveTableCapacity` to make the distinction 
clear, or add a comment explaining that the table capacity is being reduced to 
match the scan limit.



##########
pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/DistinctQueriesTest.java:
##########
@@ -0,0 +1,262 @@
+/**
+ * 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.pinot.integration.tests.custom;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.apache.avro.SchemaBuilder;
+import org.apache.avro.file.DataFileWriter;
+import org.apache.avro.generic.GenericData;
+import org.apache.avro.generic.GenericDatumWriter;
+import org.apache.pinot.integration.tests.ClusterIntegrationTestUtils;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.data.Schema;
+import 
org.apache.pinot.spi.utils.CommonConstants.Broker.Request.QueryOptionKey;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+
+@Test(suiteName = "CustomClusterIntegrationTest")
+public class DistinctQueriesTest extends CustomDataQueryClusterIntegrationTest 
{
+  private static final String TABLE_NAME = "DistinctQueriesCustomTest";
+
+  private static final String INT_COL = "intCol";
+  private static final String LONG_COL = "longCol";
+  private static final String DOUBLE_COL = "doubleCol";
+  private static final String STRING_COL = "stringCol";
+  private static final String MV_INT_COL = "intArrayCol";
+  private static final String MV_STRING_COL = "stringArrayCol";
+
+  private static final int NUM_ROWS = 24_000;
+  private static final int NUM_INT_VALUES = 5;
+  private static final int NUM_LONG_VALUES = 5;
+  private static final int NUM_DOUBLE_VALUES = 3;
+  private static final int NUM_STRING_VALUES = 4;
+  private static final int NUM_MV_INT_VALUES = 3;
+  private static final long LONG_BASE_VALUE = 1_000L;
+  private static final double DOUBLE_OFFSET = 0.25d;
+  private static final int MV_OFFSET = 50;
+
+  @Override
+  protected long getCountStarResult() {
+    return NUM_ROWS;
+  }
+
+  @Override
+  public String getTableName() {
+    return TABLE_NAME;
+  }
+
+  @Override
+  public Schema createSchema() {
+    return new Schema.SchemaBuilder().setSchemaName(TABLE_NAME)
+        .addSingleValueDimension(INT_COL, FieldSpec.DataType.INT)
+        .addSingleValueDimension(LONG_COL, FieldSpec.DataType.LONG)
+        .addSingleValueDimension(DOUBLE_COL, FieldSpec.DataType.DOUBLE)
+        .addSingleValueDimension(STRING_COL, FieldSpec.DataType.STRING)
+        .addMultiValueDimension(MV_INT_COL, FieldSpec.DataType.INT)
+        .addMultiValueDimension(MV_STRING_COL, FieldSpec.DataType.STRING)
+        .build();
+  }
+
+  @Override
+  public List<File> createAvroFiles()
+      throws Exception {
+    org.apache.avro.Schema avroSchema =
+        SchemaBuilder.record("DistinctRecord").fields()
+            .requiredInt(INT_COL)
+            .requiredLong(LONG_COL)
+            .requiredDouble(DOUBLE_COL)
+            .requiredString(STRING_COL)
+            .name(MV_INT_COL).type().array().items().intType().noDefault()
+            
.name(MV_STRING_COL).type().array().items().stringType().noDefault()
+            .endRecord();
+
+    File avroFile = new File(_tempDir, "distinct-data.avro");
+    try (DataFileWriter<GenericData.Record> writer = new DataFileWriter<>(new 
GenericDatumWriter<>(avroSchema))) {
+      writer.create(avroSchema, avroFile);
+      for (int i = 0; i < NUM_ROWS; i++) {
+        GenericData.Record record = new GenericData.Record(avroSchema);
+        record.put(INT_COL, getIntValue(i));
+        record.put(LONG_COL, getLongValue(i));
+        record.put(DOUBLE_COL, getDoubleValue(i));
+        record.put(STRING_COL, getStringValue(i));
+        record.put(MV_INT_COL, List.of(getMultiValueBase(i), 
getMultiValueBase(i) + MV_OFFSET));
+        record.put(MV_STRING_COL, List.of(getStringValue(i), getStringValue(i 
+ MV_OFFSET)));
+        writer.append(record);
+      }
+    }
+    return List.of(avroFile);
+  }
+
+  @Override
+  protected String getSortedColumn() {
+    return null;
+  }
+
+  private int getIntValue(int recordId) {
+    return recordId % NUM_INT_VALUES;
+  }
+
+  private long getLongValue(int recordId) {
+    return LONG_BASE_VALUE + (recordId % NUM_LONG_VALUES);
+  }
+
+  private double getDoubleValue(int recordId) {
+    return (recordId % NUM_DOUBLE_VALUES) + DOUBLE_OFFSET;
+  }
+
+  private String getStringValue(int recordId) {
+    return "type_" + (recordId % NUM_STRING_VALUES);
+  }
+
+  private int getMultiValueBase(int recordId) {
+    return recordId % NUM_MV_INT_VALUES;
+  }
+
+  @Test(dataProvider = "useBothQueryEngines")
+  public void testDistinctSingleValuedColumns(boolean useMultiStageQueryEngine)
+      throws Exception {
+    setUseMultiStageQueryEngine(useMultiStageQueryEngine);
+    assertDistinctColumnValues(INT_COL, getExpectedIntValues(), 
JsonNode::asInt);
+    assertDistinctColumnValues(LONG_COL, getExpectedLongValues(), 
JsonNode::asLong);
+    assertDistinctColumnValues(DOUBLE_COL, getExpectedDoubleValues(), 
JsonNode::asDouble);
+    assertDistinctColumnValues(STRING_COL, getExpectedStringValues(), 
JsonNode::textValue);
+  }
+
+  @Test(dataProvider = "useBothQueryEngines")
+  public void testDistinctMultiValueColumn(boolean useMultiStageQueryEngine)
+      throws Exception {
+    setUseMultiStageQueryEngine(useMultiStageQueryEngine);
+    String query = useMultiStageQueryEngine ? String.format("SELECT 
ARRAY_TO_MV(%s) FROM %s GROUP BY 1", MV_INT_COL,
+        getTableName()) : String.format("SELECT DISTINCT %s FROM %s", 
MV_INT_COL, getTableName());
+    JsonNode result = postQuery(query);
+    JsonNode rows = result.get("resultTable").get("rows");
+    Set<Integer> actual = new HashSet<>();
+    for (JsonNode row : rows) {
+      actual.add(row.get(0).asInt());
+    }
+    assertEquals(actual, getExpectedMultiValueEntries());
+  }
+
+  @Test(dataProvider = "useBothQueryEngines")
+  public void testDistinctMultipleColumns(boolean useMultiStageQueryEngine)
+      throws Exception {
+    setUseMultiStageQueryEngine(useMultiStageQueryEngine);
+    String query =
+        String.format("SELECT DISTINCT %s, %s FROM %s ORDER BY %s, %s LIMIT 
1000", INT_COL, STRING_COL, getTableName(),
+            INT_COL, STRING_COL);
+    JsonNode rows = postQuery(query).get("resultTable").get("rows");
+    List<String> actual = new ArrayList<>(rows.size());
+    for (JsonNode row : rows) {
+      actual.add(row.get(0).asInt() + "|" + row.get(1).textValue());
+    }
+    assertEquals(actual, getExpectedIntStringPairs());
+  }
+
+  @Test(dataProvider = "useBothQueryEngines")
+  public void testMaxRowsInDistinctEarlyTermination(boolean 
useMultiStageQueryEngine)
+      throws Exception {
+    setUseMultiStageQueryEngine(useMultiStageQueryEngine);
+    String sql = String.format("SELECT DISTINCT %s FROM %s WHERE rand() < 1.0 
LIMIT 100", STRING_COL, getTableName());
+    JsonNode response =
+        postQueryWithOptions(sql, useMultiStageQueryEngine, 
Map.of(QueryOptionKey.MAX_ROWS_IN_DISTINCT, "3"));
+    assertTrue(response.path("maxRowsInDistinctReached").asBoolean(false),
+        "expected maxRowsInDistinctReached flag. Response: " + response);
+    assertTrue(response.path("partialResult").asBoolean(false), "partialResult 
should be true. Response: " + response);
+    assertTrue(response.get("resultTable").get("rows").size() <= 3, "row count 
should honor threshold");

Review Comment:
   This assertion only checks that the row count is at most 3, but doesn't 
verify that early termination actually occurred at the expected point. With 
`maxRowsInDistinct=3`, the test should verify that exactly 3 rows were 
processed, not just that the result has ≤3 rows. The distinction matters 
because the query could naturally return fewer than 3 distinct values without 
hitting the limit. Consider verifying that `maxRowsInDistinctReached` is true 
AND checking execution statistics to confirm 3 rows were actually processed.



##########
pinot-core/src/test/java/org/apache/pinot/core/operator/combine/DistinctResultsBlockMergerTest.java:
##########
@@ -0,0 +1,132 @@
+/**
+ * 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.pinot.core.operator.combine;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import org.apache.pinot.common.datatable.DataTable;
+import org.apache.pinot.common.response.broker.ResultTable;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
+import org.apache.pinot.core.operator.blocks.results.BaseResultsBlock;
+import org.apache.pinot.core.operator.blocks.results.DistinctResultsBlock;
+import 
org.apache.pinot.core.operator.combine.merger.DistinctResultsBlockMerger;
+import org.apache.pinot.core.query.distinct.table.DistinctTable;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import 
org.apache.pinot.core.query.request.context.utils.QueryContextConverterUtils;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+
+public class DistinctResultsBlockMergerTest {
+
+  private static final DataSchema SCHEMA =
+      new DataSchema(new String[]{"col"}, new 
ColumnDataType[]{ColumnDataType.INT});
+
+  @Test
+  public void shouldRespectMaxRowsAcrossSegments() {
+    QueryContext queryContext =
+        QueryContextConverterUtils.getQueryContext("SET 
\"maxRowsInDistinct\"=1000; SELECT DISTINCT col FROM myTable");
+    DistinctResultsBlockMerger merger = new 
DistinctResultsBlockMerger(queryContext);
+
+    DistinctResultsBlock merged = new DistinctResultsBlock(fakeTable(0, 800), 
queryContext);
+    // First block under budget
+    assertTrue(!merger.isQuerySatisfied(merged));

Review Comment:
   [nitpick] Use `assertFalse` instead of `assertTrue(!...)` for better 
readability and clearer test failure messages. If this assertion fails, the 
error message will be more intuitive with `assertFalse`.



##########
pinot-core/src/main/java/org/apache/pinot/core/query/distinct/raw/RawMultiColumnDistinctExecutor.java:
##########
@@ -88,7 +97,11 @@ public boolean process(ValueBlock valueBlock) {
           RoaringBitmap nullBitmap = nullBitmaps[i];
           if (nullBitmap != null && !nullBitmap.isEmpty()) {
             int finalI = i;
-            nullBitmap.forEach((IntConsumer) j -> values[j][finalI] = null);
+            nullBitmap.forEach((IntConsumer) j -> {
+              if (j < numDocs) {
+                values[j][finalI] = null;
+              }
+            });

Review Comment:
   The null bitmap iteration is being limited by `numDocs` (which is already 
clamped by `_rowsRemaining`), but if there are more nulls beyond the clamped 
range, this creates inconsistent behavior. The values array still contains all 
rows from the block, but we're only nullifying entries up to `numDocs`. This 
mismatch can lead to accessing uninitialized or stale data in the non-nullified 
positions beyond `numDocs` when they're processed. Instead, the loop at line 
107 should only iterate up to `numDocs` to avoid accessing values beyond the 
clamped range.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to