xiangfu0 commented on code in PR #20389:
URL: https://github.com/apache/pinot/pull/20389#discussion_r4729464300
##########
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)) {
+ groupColumns.add(column);
+ }
+ }
+ if (groupColumns.isEmpty()) {
+ return null;
+ }
+ WorkerManager workerManager = planner.getEnvConfig().getWorkerManager();
+ try {
+ if (!workerManager.hasPartitionedGroupByRoute(tableName, groupColumns,
planner)) {
+ return null;
+ }
+ } catch (RuntimeException e) {
+ LOGGER.debug("Could not verify GROUP BY routing for {}", tableName, e);
Review Comment:
This is the only log on the whole path, and it only fires on an exception.
The flag quietly does nothing in a lot of setups. The default balanced selector
alternates replicas per segment, so with replication above 1 a partition almost
never lands on one server. HashCode, Modulo and ByteArray tables with more than
2 partitions are excluded, and so are REALTIME and hybrid tables.
A debug line with the reason `hasPartitionedGroupByRoute` said no, plus a
sentence on the option's Javadoc about when it applies, would save people from
guessing why nothing changed.
##########
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()
Review Comment:
I don't think `isNotNull()` is the right predicate here. `notNull` only
decides nullability when the schema has column-based null handling on
(`BaseSegmentCreator.isNullable`). In the table-level mode it is ignored, so
this check doesn't protect that mode. It also defaults to false, which turns
the fast path off for almost every existing schema.
The mismatch the comment above describes needs the query to run with null
handling, so a gate like "null handling is off for this query, or the schema
uses column-based null handling and the column is notNull" would cover the same
risk and reach many more tables.
##########
pinot-query-planner/src/main/java/org/apache/pinot/query/routing/WorkerManager.java:
##########
@@ -1882,6 +1911,59 @@ static void checkLeafWorkerAssignment(String tableName,
@Nullable int[] partitio
}
}
+ /// Checks the ordinary selector's segment assignment. When every partition
has just one server, a group that
+ /// contains the partition key can finish there. Pin this route so dispatch
uses the same replica choices.
+ public boolean hasPartitionedGroupByRoute(String tableName, Set<String>
groupColumns, PlannerContext planner) {
+ PlannerContext.GroupByRoute checked =
planner.getGroupByRoutes().get(tableName);
+ if (checked != null) {
+ return groupColumns.contains(checked.partitionColumn());
+ }
+ TableType type = TableNameBuilder.getTableTypeFromTableName(tableName);
+ if (type == TableType.REALTIME || (type == null
+ &&
_routingManager.routingExists(TableNameBuilder.REALTIME.tableNameWithType(tableName))))
{
+ return false;
+ }
+ String offline = TableNameBuilder.OFFLINE.tableNameWithType(tableName);
+ TablePartitionInfo partitions =
_routingManager.getTablePartitionInfo(offline);
+ if (partitions == null || !partitions.hasConsistentPartitionFunction()
+ || !groupColumns.contains(partitions.getPartitionColumn())) {
+ return false;
+ }
+ RoutingTable route = getRoutingTableHelper(offline,
planner.getEnvConfig().getRequestId(), planner.getOptions());
Review Comment:
Nit: a failed check isn't remembered, so a query with several aggregates
over the same table computes this full-table route once per aggregate, and
dispatch then computes its own. Remembering the negative result for the query
would avoid the repeats.
##########
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:
Nit: this hard-codes the six built-in classes, so a plugin partition
function can never qualify. A method on `PartitionFunction` that says whether
segment metadata captures all of its settings would let each function answer
for itself. Fine as a follow-up.
##########
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:
This is where the wrong result comes from. A leaf that takes this branch
ends up with one worker per server and no partition function, and nothing stops
an exchange above it from being treated as pre-partitioned.
`isPrePartitionAssignment` and
`MailboxAssignmentVisitor.isDirectExchangeCompatible` both accept inputs whose
partition function is null as long as the worker counts match, so a
colocated-join hint over two such leaves gets wired worker i to worker i by
server order. That only lines up if partition p of both tables lives on the
same server.
Repro in `ResourceBasedQueriesTest`: two OFFLINE tables, `t1(num INT, name
STRING notNull)` and `t2(name STRING notNull, val INT)`, both partitioned on
`name` with 4 partitions, with t1's partitions 0-1 on server 1 and t2's
partitions 0-1 on server 2.
```sql
SET serverReturnFinalResult=true;
SELECT /*+ joinOptions(is_colocated_by_join_keys='true') */ x.name, x.c, y.m
FROM (SELECT name, COUNT(*) AS c FROM t1 GROUP BY name) x
JOIN (SELECT name, MAX(val) AS m FROM t2 GROUP BY name) y ON x.name = y.name
```
H2 expects 16 rows. On this commit the query returns 16 rows without the
flag and 0 rows with it. On the base commit (5260361daa) it returns 16 rows
either way, because there the join inputs are the FINAL stages,
hash-distributed on `name` over the same workers, so the hint is true. Adding
`inferPartitionHint=true` makes no difference. The implementation plan for the
same shape shows join worker 0 fed by one table's partitions 0-1 and the other
table's partitions 2-3.
The existing join test can't catch this because the test harnesses put
partition i of every table on the same server
(`QueryEnvironmentTestBase.getQueryEnvironment` and
`ResourceBasedQueriesTest.addSegments`). A test for it needs one table's
placement flipped.
I think an exchange whose sender is a route-pinned leaf should never count
as pre-partitioned. "One server owns each group" isn't something a second input
can share by worker id. When only one input is leaf-finalized the planner
already falls back to a hash shuffle, which is correct, although the hinted
join then shuffles both sides. The set-op colocation hint goes through the same
check and I didn't test it.
##########
pinot-query-planner/src/main/java/org/apache/pinot/query/routing/WorkerManager.java:
##########
@@ -1033,6 +1043,25 @@ private void
assignWorkersToNonPartitionedLeafFragment(PlanFragment fragment, Di
metadata.setWorkerIdToSegmentsMap(workerIdToSegmentsMap);
}
+ private RoutingTable pruneGroupByRoute(RoutingTable route, PlanFragment
fragment, String tableName,
+ DispatchablePlanContext context) {
+ Set<String> pruned = getPrunedSegments(fragment, tableName, context);
+ if (pruned == null || pruned.isEmpty()) {
+ return route;
+ }
+ Map<ServerInstance, SegmentsToQuery> remaining = new HashMap<>();
+ int removed = 0;
+ for (var entry : route.getServerInstanceToSegmentsMap().entrySet()) {
+ List<String> segments = entry.getValue().getSegments();
+ List<String> kept = segments.stream().filter(segment ->
!pruned.contains(segment)).toList();
+ removed += segments.size() - kept.size();
+ if (!kept.isEmpty()) {
+ remaining.put(entry.getKey(), new SegmentsToQuery(kept, null));
+ }
+ }
Review Comment:
No test reaches this loop. The mock routing manager's `getPrunedSegments`
always returns an empty set, so every test leaves through the early return
above. The REALTIME/hybrid guard and the unavailable-segment and
optional-segment guards in `hasPartitionedGroupByRoute` aren't covered either,
and Codecov has the patch at about 51% for this file. One test that prunes a
segment, and one for each of those guards, would close it.
##########
pinot-query-planner/src/main/java/org/apache/pinot/query/routing/WorkerManager.java:
##########
@@ -1033,6 +1043,25 @@ private void
assignWorkersToNonPartitionedLeafFragment(PlanFragment fragment, Di
metadata.setWorkerIdToSegmentsMap(workerIdToSegmentsMap);
}
+ private RoutingTable pruneGroupByRoute(RoutingTable route, PlanFragment
fragment, String tableName,
+ DispatchablePlanContext context) {
+ Set<String> pruned = getPrunedSegments(fragment, tableName, context);
+ if (pruned == null || pruned.isEmpty()) {
+ return route;
Review Comment:
Nit: this returns the cached `RoutingTable` itself, and the segment lists go
into the worker metadata as they are, so two fragments that scan this table
share the same list instances. The `filterLeafStageSegments` Javadoc promises
an override that what it is handed is safe to edit in place. Returning a copy
here keeps that true.
--
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]