xiangfu0 commented on code in PR #20389:
URL: https://github.com/apache/pinot/pull/20389#discussion_r4762327278


##########
pinot-query-planner/src/main/java/org/apache/pinot/calcite/rel/rules/PinotAggregateExchangeNodeInsertRule.java:
##########
@@ -295,15 +306,91 @@ private static RelNode createPlan(RelOptRuleCall call, 
Aggregate aggRel, boolean
     if (withinGroupCollation != null || (hasGroupBy && Boolean.parseBoolean(
         
hintOptions.get(PinotHintOptions.AggregateOptions.IS_SKIP_LEAF_STAGE_GROUP_BY))))
 {
       return createPlanWithExchangeDirectAggregation(call, aggRel, 
withinGroupCollation, collations, limit);
-    } else if (hasGroupBy && Boolean.parseBoolean(
+    }
+    RelNode directInput = null;
+    if (hasGroupBy && Boolean.parseBoolean(
         
hintOptions.get(PinotHintOptions.AggregateOptions.IS_PARTITIONED_BY_GROUP_BY_KEYS)))
 {
-      return new PinotLogicalAggregate(aggRel, aggRel.getInput(), 
buildAggCalls(aggRel, AggType.DIRECT, false),
+      directInput = aggRel.getInput();
+    } else if (hasGroupBy && hintOptions.isEmpty()) {
+      Context context = call.getPlanner().getContext();
+      PlannerContext planner = context != null ? 
context.unwrap(PlannerContext.class) : null;
+      if (planner != null && 
QueryOptionsUtils.isServerReturnFinalResult(planner.getOptions())
+          && 
!QueryOptionsUtils.isMultiClusterRoutingEnabled(planner.getOptions(), false)
+          && 
!planner.getOptions().containsKey(QueryOptionKey.MULTI_STAGE_LEAF_LIMIT)
+          && !planner.getOptions().containsKey(QueryOptionKey.TABLE_SAMPLER)
+          && !planner.getOptions().containsKey(QueryOptionKey.ROUTING_OPTIONS)
+          && planner.getEnvConfig().getWorkerManager() != null) {
+        directInput = partitionedGroupByInput(aggRel.getInput(), 
aggRel.getGroupSet(), planner);
+      }
+    }
+    if (directInput != null) {
+      return new PinotLogicalAggregate(aggRel, directInput, 
buildAggCalls(aggRel, AggType.DIRECT, false),
           AggType.DIRECT, false, collations, limit);
-    } else {
-      boolean leafReturnFinalResult =
-          
Boolean.parseBoolean(hintOptions.get(PinotHintOptions.AggregateOptions.IS_LEAF_RETURN_FINAL_RESULT));
-      return createPlanWithLeafExchangeFinalAggregate(aggRel, 
leafReturnFinalResult, collations, limit);
     }
+    boolean leafReturnFinalResult =
+        
Boolean.parseBoolean(hintOptions.get(PinotHintOptions.AggregateOptions.IS_LEAF_RETURN_FINAL_RESULT));
+    return createPlanWithLeafExchangeFinalAggregate(aggRel, 
leafReturnFinalResult, collations, limit);
+  }
+
+  /// Trace unmodified grouping columns through the leaf and give its scan the 
exact partition routing that
+  /// makes the aggregate direct. Grouping on a transformation of the 
partition column cannot establish colocation.
+  @Nullable
+  private static RelNode partitionedGroupByInput(RelNode input, 
ImmutableBitSet keys, PlannerContext planner) {
+    RelNode node = PinotRuleUtils.unboxRel(input);
+    if (node instanceof Project project) {
+      ImmutableBitSet.Builder refs = ImmutableBitSet.builder();
+      for (int key : keys) {
+        if (project.getProjects().get(key) instanceof RexInputRef ref) {
+          refs.set(ref.getIndex());
+        }
+      }
+      keys = refs.build();
+    } else if (node instanceof TableScan scan) {
+      if (PinotHintStrategyTable.getHint(scan, 
PinotHintOptions.TABLE_HINT_OPTIONS) != null) {
+        return null;
+      }
+      String tableName = planner.getEnvConfig().getTableCache()
+          
.getActualTableName(RelToPlanNodeConverter.getTableNameFromTableScan(scan));
+      if (tableName == null) {
+        return null;
+      }
+      Schema schema = 
planner.getEnvConfig().getTableCache().getSchema(TableNameBuilder.extractRawTableName(tableName));
+      if (schema == null) {
+        return null;
+      }
+      // Hashing the ingested value must agree with grouping the stored value. 
Null sentinels and decimal
+      // representations can differ between segments even when SQL considers 
the group keys equal.
+      Set<String> groupColumns = new HashSet<>();
+      for (int key : keys) {
+        String column = scan.getRowType().getFieldNames().get(key);
+        FieldSpec field = schema.getFieldSpecFor(column);
+        if (field != null && field.isSingleValueField() && field.isNotNull()
+            && (field.getDataType() == FieldSpec.DataType.INT || 
field.getDataType() == FieldSpec.DataType.LONG
+            || field.getDataType() == FieldSpec.DataType.STRING)) {

Review Comment:
   Fixed in `32829c6d03`. The automatic leaf optimization now requires 
effective query null handling to be disabled. The two-worker regression stores 
0 and 1 as different physical null sentinels with null bitmaps. Removing only 
the new gate produces two `(NULL,1)` rows. With the fix, the same legacy query 
returns one `(NULL,2)` row. The null-disabled control returns `(0,1)` and 
`(1,1)`.



##########
pinot-broker/src/main/java/org/apache/pinot/broker/routing/segmentpartition/SegmentPartitionMetadataManager.java:
##########
@@ -477,24 +479,59 @@ private void computeTablePartitionInfo() {
     }
     _tablePartitionInfo =
         new TablePartitionInfo(_tableNameWithType, _partitionColumn, 
_partitionFunctionName, _numPartitions,
-            segmentsByPartition, segmentsWithInvalidPartition);
+            segmentsByPartition, segmentsWithInvalidPartition, consistent && 
segmentsWithInvalidPartition.isEmpty());
   }
 
   private static class SegmentInfo {
     int _partitionId;
+    @Nullable
+    PartitionFunction _partitionFunction;
     long _creationTimeMs;
     List<String> _onlineServers;
     /// Servers the ideal state assigns the segment to in ONLINE or CONSUMING 
state; empty when the ideal state does
     /// not list it, or lists it only in other states (e.g. OFFLINE while it 
is being dropped).
     List<String> _assignedServers;
 
-    SegmentInfo(int partitionId, long creationTimeMs, List<String> 
onlineServers, List<String> assignedServers) {
-      _partitionId = partitionId;
-      _creationTimeMs = creationTimeMs;
+    SegmentInfo(SegmentPartitionInfo partitionInfo, long creationTimeMs, 
List<String> onlineServers,
+        List<String> assignedServers) {
+      updateMetadata(partitionInfo, creationTimeMs);
       _onlineServers = onlineServers;
       _assignedServers = assignedServers;
     }
 
+    private boolean updateMetadata(SegmentPartitionInfo info, long 
creationTimeMs) {
+      int partitionId = info == SegmentPartitionUtils.INVALID_PARTITION_INFO
+          ? INVALID_PARTITION_ID
+          : info.getPartitions().iterator().next();
+      PartitionFunction function = 
comparableFunction(info.getPartitionFunction());
+      boolean changed = _partitionId != partitionId || _creationTimeMs != 
creationTimeMs
+          || !Objects.equals(_partitionFunction, function);
+      _partitionId = partitionId;
+      _partitionFunction = function;
+      _creationTimeMs = creationTimeMs;
+      return changed;
+    }
+
+    /// These built-ins persist their hash settings and implement value 
equality. HashCode, Modulo and ByteArray
+    /// historically omitted their normalizer from segment metadata. For at 
most two partitions every normalizer
+    /// gives the same valid id (parity for two), so that missing setting 
cannot change group placement.
+    @Nullable
+    private static PartitionFunction comparableFunction(@Nullable 
PartitionFunction function) {
+      if (function == null) {
+        return null;
+      }
+      Class<?> type = function.getClass();
+      if (type == MurmurPartitionFunction.class || type == 
Murmur3PartitionFunction.class
+          || type == FnvPartitionFunction.class) {
+        return function;
+      }
+      if (function.getNumPartitions() <= 2 && (type == 
HashCodePartitionFunction.class
+          || type == ModuloPartitionFunction.class || type == 
ByteArrayPartitionFunction.class)) {
+        return function;

Review Comment:
   Fixed in `32829c6d03` by excluding HashCode-partitioned STRING group keys 
from automatic leaf finalization. The two-worker regression ingests U+10000 
with maxLength=1 and a literal question mark. Removing only this guard produced 
two `('?',1)` rows. The corrected legacy query returns one `('?',2)` group. I 
also verified that the independent v2 optimizer returns duplicate groups on 
upstream with the flag omitted. The PR documents that separate result.



-- 
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