Jackie-Jiang commented on code in PR #20389:
URL: https://github.com/apache/pinot/pull/20389#discussion_r4730146311


##########
pinot-query-planner/src/main/java/org/apache/pinot/query/routing/WorkerManager.java:
##########
@@ -935,7 +938,14 @@ private void 
assignWorkersToNonPartitionedLeafFragment(PlanFragment fragment, Di
     // When broker pruning is enabled, routingPinotQuery carries the leaf 
stage filter so that segment pruners can
     // eliminate segments. When disabled (null), fall back to an unfiltered 
SELECT * routing request.
     Map<String, RoutingTable> routingTableMap = null;
-    if (routingPinotQuery != null) {
+    if (metadata.getTableOptions() != null
+        && 
metadata.getTableOptions().containsKey(PinotHintStrategyTable.GROUP_BY_ROUTE)) {
+      PlannerContext.GroupByRoute checked = 
context.getPlannerContext().getGroupByRoutes().get(tableName);
+      Preconditions.checkState(checked != null, "Missing verified GROUP BY 
route for table: %s", tableName);
+      routingTableMap =
+          Map.of(TableType.OFFLINE.name(), pruneGroupByRoute(checked.route(), 
fragment, tableName, context));
+    }

Review Comment:
   [P1] Preserve hash exchanges above finalized leaves
   
   With `serverReturnFinalResult=true`, two grouped inputs carrying 
`joinOptions(is_colocated_by_join_keys='true')` can be wired worker-to-worker 
despite having opposite partition placement. This route proves ownership within 
each table, but worker IDs are assigned by server order and carry no common 
partition mapping. `isPrePartitionAssignment` and `isDirectExchangeCompatible` 
accept the resulting null descriptors, silently dropping matching join rows. 
The previous FINAL stages hash-distributed both inputs consistently.
   
   For example, put partition 0 of `t1` on server A and partition 0 of `t2` on 
server B, with partition 1 placed oppositely, then join `(SELECT name, COUNT(*) 
FROM t1 GROUP BY name)` and `(SELECT name, MAX(val) FROM t2 GROUP BY name)` 
using that hint. Matching keys reach different join workers.
   
   Exclude route-pinned leaves from pre-partitioned exchange wiring unless 
cross-input compatibility is proven, and test reversed partition placement. 
This independently confirms the existing PR discussion finding.



##########
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:
   [P1] Do not certify HashCode STRING groups from metadata alone
   
   HashCode hashes Java UTF-16 strings, but dictionary storage encodes UTF-8. 
With `maxLength=1`, ingestion truncates U+10000 to the unpaired surrogate 
U+D800: it hashes to partition 0 with HashCode/2 but is stored as `?`. A 
literal `?` hashes to partition 1 and has the same stored value. Both segments 
therefore pass this certification even though equal query keys reside on 
different workers. With a nonnullable STRING group key, DIRECT can emit two 
`('?', 1)` groups instead of one `('?', 2)` for `SELECT name, COUNT(*) FROM t 
GROUP BY name`.
   
   The path is `StringUtil.sanitizeStringValue` truncating by UTF-16 index, 
`StringColumnPreIndexStatsCollector` hashing the resulting Java string, and 
`SegmentDictionaryCreator` calling `getBytes(UTF_8)`. A focused Java check 
confirms the opposite partition IDs and identical stored values.
   
   Exclude this combination unless metadata guarantees hashing the stored 
canonical value, and add a two-worker regression for truncation at a surrogate 
boundary. Fixing ingestion alone would leave existing segments affected.



##########
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:
   [P1] Check effective nullability before finalizing groups
   
   `field.isNotNull()` does not exclude nulls when column-based null handling 
is disabled: table-level null handling ignores that field flag 
(`BaseSegmentCreator.isNullable`). A supported `defaultNullValue` change from 
`0` to `1` can place null rows in different HashCode/2 partitions, while both 
segments pass this routing proof. With query null handling enabled and each 
partition on a different worker, each worker restores its key to SQL NULL, so 
DIRECT emits two `(NULL, 1)` rows for `SELECT key, COUNT(*) FROM t GROUP BY 
key` instead of the previous FINAL result `(NULL, 2)`.
   
   Require query null handling to be disabled, or column-based null handling 
with a nonnullable field, and add a regression spanning the sentinel change. 
`FieldSpec.isBackwardCompatibleWith` explicitly permits changing the default 
null value, so this does not require an unsupported schema update.



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