yashmayya commented on code in PR #20293:
URL: https://github.com/apache/pinot/pull/20293#discussion_r4606700969


##########
pinot-query-planner/src/main/java/org/apache/pinot/query/planner/validation/ArrayToMvValidationVisitor.java:
##########
@@ -88,35 +195,58 @@ public Void visitMailboxSend(MailboxSendNode node, Boolean 
isIntermediateStage)
   @Override
   public Void visitAggregate(AggregateNode node, Boolean isIntermediateStage) {
     if (!isIntermediateStage) {
-      // No need to traverse underlying ProjectNode in leaf stage
+      // ARRAY_TO_MV is a no-op in the leaf stage: the leaf translation drops 
the call and the single-stage engine
+      // evaluates the expression on the multi-value column. The Project under 
the aggregate is not visited. A plain
+      // `GROUP BY mvCol` fails in the FINAL aggregate, except with the hint 
`is_partitioned_by_group_by_keys`, which
+      // gives one DIRECT aggregate in the leaf stage, as before the MV 
aggregate.
       return null;
     }
+    // The group keys are the first columns of the output.
+    checkNoArrayGroupKey(node.getDataSchema(), node.getGroupKeys().size(), 
List.of(), "AGGREGATE", true);

Review Comment:
   **Blocker.** This check is stricter than master's. Also, the row-8 change 
now checks aggregates above a lookup join or an UNNEST. So some queries that 
run on master now fail with "Multi-valued column found as a grouping key in 
AGGREGATE in the intermediate stage". They do not call `ARRAY_TO_MV`, so they 
are not row 7 or row 8.
   
   Master returns the correct rows for this query. The PR fails it at planning:
   ```sql
   SELECT /*+ aggOptions(is_partitioned_by_group_by_keys='true') */ t.k, 
t.strMv, COUNT(*)
   FROM tbl t CROSS JOIN UNNEST(t.intMv) AS u(e)
   GROUP BY t.k, t.strMv
   ```
   
   Other shapes that now fail:
   - the same hint above a hash join or a lookup join
   - `is_skip_leaf_stage_group_by` with an SV key and an MV key
   - `usePhysicalOptimizer` and lite mode, with no hint: `SELECT DISTINCT 
f.strMv FROM fact f JOIN other o ON f.k = o.k`
   
   Master groups arrays by reference. So when two rows have equal arrays, many 
of these results are wrong on master. Still, this changes queries that work 
today. Can we keep master's check for a plain aggregate here, and move the 
stricter check to its own PR?



##########
pinot-query-planner/src/main/java/org/apache/pinot/calcite/rel/logical/PinotLogicalMvAggregate.java:
##########
@@ -0,0 +1,162 @@
+/**
+ * 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.calcite.rel.logical;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.calcite.plan.RelOptCluster;
+import org.apache.calcite.plan.RelTraitSet;
+import org.apache.calcite.rel.RelFieldCollation;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.RelWriter;
+import org.apache.calcite.rel.core.Aggregate;
+import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.hint.RelHint;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rel.type.RelDataTypeFactory;
+import org.apache.calcite.rel.type.RelDataTypeField;
+import org.apache.calcite.util.ImmutableBitSet;
+import org.apache.pinot.calcite.sql.fun.PinotOperatorTable;
+import org.apache.pinot.query.planner.plannode.AggregateNode.AggType;
+
+
+/// An aggregate that groups each input row by every element of its 
multi-value (MV) group keys, with the
+/// single-stage engine semantics: a row contributes once to the group of each 
element, a repeated element counts
+/// once per copy, an empty array contributes to no group, and several MV keys 
give the cartesian product.
+///
+/// [#getMvKeyIndexes()] holds positions in the group set (ascending). The 
input column of an MV key is an array;
+/// the output column is its component type, nullable when the array or its 
component is nullable, as the type of
+/// `ARRAY_TO_MV(array)`. Every other field of the row type is the one of a 
plain [Aggregate], so a parent that
+/// referenced a plain aggregate over `ARRAY_TO_MV(e)` keeps its references.
+///
+/// This class does not extend [PinotLogicalAggregate] on purpose: a rule or 
converter that only knows the plain
+/// aggregate must not treat an MV aggregate as one. Grouping sets are not 
supported.
+///
+/// Instances are immutable and thread-safe, like every Calcite [RelNode].
+public class PinotLogicalMvAggregate extends Aggregate {
+  private final AggType _aggType;
+  private final boolean _leafReturnFinalResult;
+  // The following fields are set when group trim is enabled, and are 
extracted from the Sort on top of this Aggregate.
+  private final List<RelFieldCollation> _collations;
+  private final int _limit;
+  private final List<Integer> _mvKeyIndexes;
+
+  public PinotLogicalMvAggregate(RelOptCluster cluster, RelTraitSet traitSet, 
List<RelHint> hints, RelNode input,
+      ImmutableBitSet groupSet, @Nullable List<ImmutableBitSet> groupSets, 
List<AggregateCall> aggCalls,
+      AggType aggType, boolean leafReturnFinalResult, @Nullable 
List<RelFieldCollation> collations, int limit,
+      List<Integer> mvKeyIndexes) {
+    super(cluster, traitSet, hints, input, groupSet, groupSets, aggCalls);
+    if (getGroupType() != Group.SIMPLE) {
+      throw new IllegalArgumentException("Grouping sets are not supported by 
the MV aggregate, got: " + this.groupSets);
+    }
+    int groupCount = groupSet.cardinality();
+    int previous = -1;
+    for (int mvKeyIndex : mvKeyIndexes) {
+      if (mvKeyIndex <= previous || mvKeyIndex >= groupCount) {
+        throw new IllegalArgumentException(
+            "MV key indexes must be ascending positions in the group set of 
size " + groupCount + ", got: "
+                + mvKeyIndexes);
+      }
+      previous = mvKeyIndex;
+    }
+    _aggType = aggType;
+    _leafReturnFinalResult = leafReturnFinalResult;
+    _collations = collations;
+    _limit = limit;
+    _mvKeyIndexes = List.copyOf(mvKeyIndexes);
+  }
+
+  public AggType getAggType() {
+    return _aggType;
+  }
+
+  public boolean isLeafReturnFinalResult() {
+    return _leafReturnFinalResult;
+  }
+
+  @Nullable
+  public List<RelFieldCollation> getCollations() {
+    return _collations;
+  }
+
+  public int getLimit() {
+    return _limit;
+  }
+
+  /// The positions in the group set of the MV keys, in ascending order.
+  public List<Integer> getMvKeyIndexes() {
+    return _mvKeyIndexes;
+  }
+
+  @Override
+  public PinotLogicalMvAggregate copy(RelTraitSet traitSet, RelNode input, 
ImmutableBitSet groupSet,
+      @Nullable List<ImmutableBitSet> groupSets, List<AggregateCall> aggCalls) 
{
+    // The MV key indexes are positions in the group set. A rule that changes 
the group set (for example by merging a
+    // Project that reorders the input) would make them point at the wrong 
keys, so fail instead of returning a wrong
+    // plan. The MV aggregate is created after the rules that rewrite 
aggregates.
+    if (!groupSet.equals(this.groupSet)) {
+      throw new UnsupportedOperationException(
+          "Cannot change the group set of an MV aggregate from " + 
this.groupSet + " to " + groupSet);
+    }
+    return new PinotLogicalMvAggregate(getCluster(), traitSet, hints, input, 
groupSet, groupSets, aggCalls, _aggType,
+        _leafReturnFinalResult, _collations, _limit, _mvKeyIndexes);
+  }
+
+  @Override
+  protected RelDataType deriveRowType() {
+    RelDataType rowType = super.deriveRowType();
+    RelDataTypeFactory typeFactory = getCluster().getTypeFactory();
+    List<RelDataTypeField> fields = rowType.getFieldList();
+    List<RelDataType> types = new ArrayList<>(fields.size());
+    List<String> names = new ArrayList<>(fields.size());
+    for (RelDataTypeField field : fields) {
+      types.add(field.getType());
+      names.add(field.getName());
+    }
+    for (int mvKeyIndex : _mvKeyIndexes) {
+      RelDataType arrayType = types.get(mvKeyIndex);
+      if (arrayType.getComponentType() == null) {
+        throw new IllegalStateException(
+            "MV key at group position " + mvKeyIndex + " must be an array, 
got: " + arrayType.getFullTypeString());
+      }
+      // Same type as ARRAY_TO_MV(array), so the MV aggregate keeps the row 
type of the aggregate it replaces.
+      types.set(mvKeyIndex, 
PinotOperatorTable.arrayToMvReturnType(typeFactory, arrayType));

Review Comment:
   Plan B fails here for some row-2 queries:
   ```sql
   SELECT ARRAY_TO_MV(e.mcol1), COUNT(*)
   FROM a LEFT JOIN e ON a.col3 = e.col3 + 2
   WHERE e.col6 > 0
   GROUP BY ARRAY_TO_MV(e.mcol1)
   ```
   Error: `Cannot add expression of different type to set: set type is 
RecordType(VARCHAR ... EXPR$0, ...) expression type is RecordType(VARCHAR ... 
NOT NULL EXPR$0, ...)`.
   
   Same error for a `UNION ALL` with a `LEFT JOIN` branch:
   ```sql
   SELECT ARRAY_TO_MV(m), COUNT(*)
   FROM (SELECT mcol1 AS m FROM e UNION ALL SELECT e.mcol1 AS m FROM a LEFT 
JOIN e ON a.col1 = e.col1)
   GROUP BY ARRAY_TO_MV(m)
   ```
   
   This line derives the key type again from the array type. Rules can change 
the nullability of the array after validation: the outer join becomes an inner 
join, or the call moves into a `UNION ALL` branch. Then the type no longer 
matches the aggregate that this node replaces. Using the validated type of each 
`ARRAY_TO_MV` call (`ArrayToMvGroupKeys.rewriteProject` has it) can fix this.



##########
pinot-query-planner/src/main/java/org/apache/pinot/query/validate/SqlNodeCopier.java:
##########
@@ -0,0 +1,99 @@
+/**
+ * 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.query.validate;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.calcite.sql.SqlCall;
+import org.apache.calcite.sql.SqlDataTypeSpec;
+import org.apache.calcite.sql.SqlDynamicParam;
+import org.apache.calcite.sql.SqlIdentifier;
+import org.apache.calcite.sql.SqlIntervalQualifier;
+import org.apache.calcite.sql.SqlLiteral;
+import org.apache.calcite.sql.SqlNode;
+import org.apache.calcite.sql.SqlNodeList;
+import org.apache.calcite.sql.util.SqlBasicVisitor;
+import org.apache.calcite.sql.util.SqlShuttle;
+
+
+/// Copies a parsed [SqlNode] tree, so that the copy can be validated after 
the original.
+///
+/// The Calcite validator changes the tree that it validates: it expands `*`, 
qualifies identifiers and rewrites some
+/// calls in place. A tree can be validated only once. The planner copies the 
parsed query before the first validation
+/// when it can validate the query a second time, see 
`QueryEnvironment.CompiledQuery`.
+///
+/// The copy creates a new node for each call, node list, identifier, literal, 
data type, dynamic parameter and interval
+/// qualifier of the tree. It recreates a call with 
[org.apache.calcite.sql.SqlOperator#createCall], as the validator
+/// does.
+///
+/// The class has no state and is thread-safe.
+public final class SqlNodeCopier {
+  private static final SqlShuttle COPIER = new Copier();
+
+  private SqlNodeCopier() {
+  }
+
+  /// Returns a copy of `node` that shares no node with it.
+  public static SqlNode copy(SqlNode node) {
+    return node.accept(COPIER);
+  }
+
+  private static class Copier extends SqlShuttle {
+    @Override
+    public SqlNode visit(SqlLiteral literal) {
+      return literal.clone(literal.getParserPosition());
+    }
+
+    @Override
+    public SqlNode visit(SqlIdentifier id) {
+      return id.clone(id.getParserPosition());
+    }
+
+    @Override
+    public SqlNode visit(SqlDataTypeSpec type) {
+      return type.clone(type.getParserPosition());
+    }
+
+    @Override
+    public SqlNode visit(SqlDynamicParam param) {
+      return param.clone(param.getParserPosition());
+    }
+
+    @Override
+    public SqlNode visit(SqlIntervalQualifier intervalQualifier) {
+      return intervalQualifier.clone(intervalQualifier.getParserPosition());
+    }
+
+    @Override
+    public SqlNode visit(SqlCall call) {
+      SqlBasicVisitor.ArgHandler<SqlNode> argHandler = new 
CallCopyingArgHandler(call, true);
+      call.getOperator().acceptCall(this, call, false, argHandler);
+      return argHandler.result();
+    }
+
+    @Override
+    public SqlNode visit(SqlNodeList nodeList) {
+      List<SqlNode> copies = new ArrayList<>(nodeList.size());
+      for (SqlNode node : nodeList) {
+        copies.add(node == null ? null : node.accept(this));
+      }
+      return new SqlNodeList(copies, nodeList.getParserPosition());

Review Comment:
   This always makes a new list, so `SqlNodeList.EMPTY` is lost. 
`SqlOrderBy.unparse` checks `orderList != SqlNodeList.EMPTY`. So the copy of 
`SELECT * FROM d LIMIT 0` prints as ``SELECT * FROM `d` ORDER BY FETCH NEXT 0 
ROWS ONLY``.
   
   Plans are not affected. Only error text that prints the SQL of plan B is 
affected. Keep the singletons (`EMPTY`, `SINGLETON_EMPTY`, `SINGLETON_STAR`), 
and add a LIMIT-only query to `SqlNodeCopierTest`.



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