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


##########
pinot-query-planner/src/main/java/org/apache/pinot/query/planner/logical/RelToPlanNodeConverter.java:
##########
@@ -236,6 +254,17 @@ private UnnestNode convertLogicalUncollect(Uncollect node) 
{
   private BasePlanNode convertLogicalCorrelate(LogicalCorrelate node) {
     // Pattern: Correlate(left, Uncollect(Project(correlatedFields...)))
     RelNode right = node.getRight();
+    // A correlate survives decorrelation only when the decorrelator could not 
rewrite it into a join. The only such
+    // shape implemented here is CROSS JOIN UNNEST: an Uncollect, under 
projections and filters, of arrays projected
+    // from the left row over a one-row VALUES. Only that projection is read, 
against the left row, and nothing below
+    // it is converted, so any other correlate, including one whose array 
holds a sub-query, would lose that subtree
+    // and return wrong rows without an error.
+    // TODO: The projections above the Uncollect and the join type are not 
converted either, so a LEFT correlate runs
+    //  as an inner one, and a projection that trims, reorders or computes the 
UNNEST columns is lost.
+    Uncollect uncollect = findUncollect(right);
+    if (uncollect == null || !isUnnestArrayInput(uncollect.getInput())) {
+      throw new QueryException(QueryErrorCode.QUERY_PLANNING, 
unsupportedCorrelateMessage(right, uncollect != null));

Review Comment:
   Kept both commits here and called out the UNNEST behavior change in the PR 
description, including a new Release notes section. MATCH_RECOGNIZE itself 
reaches the same converter path (the decorrelator can't move a correlation 
through a Match, and the derived input can see the enclosing FROM items), so 
splitting them out would ship a silent wrong-result path with this PR unless 
the split PR lands first. Happy to open the generic part as its own PR if you'd 
still prefer that order.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
pinot-query-runtime/src/main/java/org/apache/pinot/query/runtime/operator/match/MatchTerm.java:
##########
@@ -0,0 +1,432 @@
+/**
+ * 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.runtime.operator.match;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.math.MathContext;
+import java.util.Arrays;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.utils.DataSchema.ColumnDataType;
+import org.apache.pinot.query.planner.logical.RexExpression;
+import org.apache.pinot.query.runtime.operator.operands.TransformOperand;
+import org.apache.pinot.query.runtime.operator.utils.TypeUtils;
+import org.apache.pinot.spi.exception.QueryErrorCode;
+import org.apache.pinot.spi.query.QueryThreadContext;
+
+
+/// A leaf of a MEASURES or DEFINE expression whose value depends on the match 
rather than on a single row: a row
+/// pattern navigation, `CLASSIFIER()`, `MATCH_NUMBER()`, or a single variable 
aggregate.
+///
+/// [MatchExpression] replaces every such leaf with a slot in a synthetic row, 
so that everything above the
+/// leaves - comparisons, boolean connectives, arithmetic, scalar functions - 
is evaluated by Pinot's ordinary
+/// [TransformOperand] machinery instead of a second expression interpreter.
+///
+/// Implementations are stateless with respect to the match: all match state 
is passed in through the
+/// [MatchTape], so one instance is reused across every match of every 
partition. [Aggregate] only counts the rows it
+/// visits, to pace its termination checks.
+public interface MatchTerm {
+
+  /// The type this term reports to the enclosing expression. Values returned 
by [#evaluate] are in the
+  /// corresponding [stored][ColumnDataType#getStoredType()] representation, 
exactly like the values of a real
+  /// input row.
+  ColumnDataType getResultType();
+
+  @Nullable
+  Object evaluate(MatchTape tape);
+
+  /// A row pattern navigation: an optional logical step (`FIRST` / `LAST`) 
that designates a row of the
+  /// match, followed by an optional physical step (`PREV` / `NEXT`) that 
moves a fixed number of rows
+  /// relative to it, and finally a column read.
+  ///
+  /// Both steps are needed because SQL:2016 nests them, e.g. 
`PREV(LAST(A.price), 2)` designates the last row
+  /// mapped to `A` and then moves two rows back. The logical step is bounded 
by the match; the physical step is
+  /// bounded only by the partition, so it may legally read a row outside the 
match. Either step falling off its bound
+  /// yields `null`, as the standard requires.
+  final class Navigation implements MatchTerm {
+    private final int _symbolOrdinal;
+    private final boolean _fromEnd;
+    private final int _logicalOffset;
+    private final int _physicalDelta;
+    private final int _columnIndex;
+    private final ColumnDataType _resultType;
+    private final ColumnDataType _storedType;
+    private final boolean _requiresConversion;
+
+    /// @param symbolOrdinal pattern variable to navigate, or
+    ///        
[org.apache.pinot.query.planner.logical.RexExpression.PatternFieldRef#UNIVERSAL_SYMBOL_ORDINAL]
+    ///        for an unqualified column reference, which navigates the rows 
of the whole match
+    /// @param fromEnd `true` for `LAST`, `false` for `FIRST`
+    /// @param logicalOffset how many rows back from the end (or forward from 
the start) of the designated variable
+    /// @param physicalDelta rows to move in the partition afterwards; 
negative for `PREV`, positive for
+    ///        `NEXT`, zero when there is no physical step
+    /// @param columnIndex column to read, as an index into the input row of 
the MATCH_RECOGNIZE node
+    /// @param sourceType type of that input column; values already use its 
stored representation
+    public Navigation(int symbolOrdinal, boolean fromEnd, int logicalOffset, 
int physicalDelta, int columnIndex,
+        ColumnDataType sourceType, ColumnDataType resultType) {
+      _symbolOrdinal = symbolOrdinal;
+      _fromEnd = fromEnd;
+      _logicalOffset = logicalOffset;
+      _physicalDelta = physicalDelta;
+      _columnIndex = columnIndex;
+      _resultType = resultType;
+      _storedType = resultType.getStoredType();
+      _requiresConversion = sourceType.getStoredType() != _storedType;
+    }
+
+    @Override
+    public ColumnDataType getResultType() {
+      return _resultType;
+    }
+
+    @Nullable
+    @Override
+    public Object evaluate(MatchTape tape) {
+      int rowIndex = _fromEnd ? tape.lastRow(_symbolOrdinal, _logicalOffset)
+          : tape.firstRow(_symbolOrdinal, _logicalOffset);
+      if (rowIndex == MatchTape.NO_ROW) {
+        return null;
+      }
+      long physicalRowIndex = (long) rowIndex + _physicalDelta;
+      List<Object[]> rows = tape.getPartitionRows();
+      if (physicalRowIndex < 0 || physicalRowIndex >= rows.size()) {
+        return null;
+      }
+      Object value = rows.get((int) physicalRowIndex)[_columnIndex];
+      // The declared type of the navigation may be wider than the column's 
(e.g. BIG_DECIMAL for a DOUBLE column),
+      // and the enclosing operand compares against that declared type.
+      return value != null && _requiresConversion ? TypeUtils.convert(value, 
_storedType) : value;
+    }
+  }
+
+  /// `CLASSIFIER()`: the name of the pattern variable the designated row is 
mapped to. A bare call designates the
+  /// last (current) row; FIRST / LAST may select another match row and PREV / 
NEXT may move relative to it.
+  final class Classifier implements MatchTerm {
+    public static final Classifier INSTANCE = new Classifier(true, 0, 0);
+
+    private final boolean _fromEnd;
+    private final int _logicalOffset;
+    private final int _physicalDelta;
+
+    public Classifier(boolean fromEnd, int logicalOffset, int physicalDelta) {
+      _fromEnd = fromEnd;
+      _logicalOffset = logicalOffset;
+      _physicalDelta = physicalDelta;
+    }
+
+    @Override
+    public ColumnDataType getResultType() {
+      return ColumnDataType.STRING;
+    }
+
+    @Nullable
+    @Override
+    public Object evaluate(MatchTape tape) {
+      int rowIndex = _fromEnd
+          ? 
tape.lastRow(RexExpression.PatternFieldRef.UNIVERSAL_SYMBOL_ORDINAL, 
_logicalOffset)
+          : 
tape.firstRow(RexExpression.PatternFieldRef.UNIVERSAL_SYMBOL_ORDINAL, 
_logicalOffset);
+      if (rowIndex == MatchTape.NO_ROW) {
+        return null;
+      }
+      long physicalRowIndex = (long) rowIndex + _physicalDelta;
+      if (physicalRowIndex < 0 || physicalRowIndex >= 
tape.getPartitionRows().size()) {
+        return null;
+      }
+      return tape.classifierAt((int) physicalRowIndex);
+    }
+  }
+
+  /// `MATCH_NUMBER()`: the sequential number of the match within its 
partition, starting at 1.
+  final class MatchNumber implements MatchTerm {
+    public static final MatchNumber INSTANCE = new MatchNumber();
+
+    private MatchNumber() {
+    }
+
+    @Override
+    public ColumnDataType getResultType() {
+      return ColumnDataType.LONG;
+    }
+
+    @Override
+    public Object evaluate(MatchTape tape) {
+      return tape.getMatchNumber();
+    }
+  }
+
+  /// A single variable aggregate in MEASURES, e.g. `SUM(A.price)` or 
`COUNT(*)`: the aggregate of an
+  /// expression evaluated over every row of the match that is mapped to one 
pattern variable.
+  ///
+  /// The argument is evaluated by an ordinary [TransformOperand] against the 
raw input row, so any scalar
+  /// expression works, e.g. `SUM(A.price * A.quantity)`. Nulls are skipped, 
as SQL requires; an aggregate over
+  /// zero rows is `null` except for `COUNT`, which is `0`.
+  ///
+  /// ## Termination checks
+  ///
+  /// A scan can visit every row of a partition, and the matcher's checks do 
not cover it: in MEASURES it runs after
+  /// the matcher has found the match. Every scan therefore runs the 
operator's termination check itself, once every
+  /// `CHECK_TERMINATION_AND_SAMPLE_USAGE_RECORD_MASK + 1` rows like
+  /// [QueryThreadContext#checkTerminationAndSampleUsagePeriodically]. The 
rows are counted across evaluations rather
+  /// than per scan, so many short scans are paced like one long one. Like 
[MatchExpression], an instance therefore
+  /// belongs to one operator. Validation rejects aggregates in DEFINE today. 
The DEFINE predicates get the check as
+  /// well, because there running semantics would make the k-th candidate row 
scan the k rows mapped so far inside a
+  /// single matcher step.
+  final class Aggregate implements MatchTerm {
+    private final Kind _kind;
+    private final int _symbolOrdinal;
+    @Nullable
+    private final TransformOperand _argument;
+    private final ColumnDataType _resultType;
+    private final ColumnDataType _storedType;
+    private final boolean _requiresResultConversion;
+    private final Runnable _terminationChecker;
+    /// Rows visited over every evaluation of this aggregate; paces 
[#_terminationChecker].
+    private int _numRowsVisited;
+
+    @VisibleForTesting
+    Aggregate(Kind kind, int symbolOrdinal, @Nullable TransformOperand 
argument, ColumnDataType resultType) {
+      this(kind, symbolOrdinal, argument, resultType, () -> { });
+    }
+
+    /// @param argument the aggregated expression evaluated against an input 
row, or `null` for `COUNT(*)`,
+    ///        which counts rows rather than values
+    /// @param terminationChecker checks for query termination and samples 
resource usage; throws to abort the scan
+    public Aggregate(Kind kind, int symbolOrdinal, @Nullable TransformOperand 
argument, ColumnDataType resultType,
+        Runnable terminationChecker) {
+      _kind = kind;
+      _symbolOrdinal = symbolOrdinal;
+      _argument = argument;
+      _terminationChecker = terminationChecker;
+      _resultType = resultType;
+      _storedType = resultType.getStoredType();
+      if (argument != null && argument.getResultType().isArray()) {
+        throw QueryErrorCode.QUERY_EXECUTION.asException(
+            "Multi-value operand type '" + argument.getResultType() + "' is 
not supported for " + kind
+                + " in a MATCH_RECOGNIZE MEASURES clause. Reduce the array to 
a scalar before aggregating it.");
+      }
+      if ((kind == Kind.SUM || kind == Kind.AVG) && !_storedType.isNumber()) {
+        throw QueryErrorCode.QUERY_EXECUTION.asException(
+            "MATCH_RECOGNIZE " + kind + " requires a numeric result type, got: 
" + resultType + ".");
+      }
+      _requiresResultConversion = argument != null && 
argument.getResultType().getStoredType() != _storedType;
+    }
+
+    @Override
+    public ColumnDataType getResultType() {
+      return _resultType;
+    }
+
+    @Nullable
+    @Override
+    public Object evaluate(MatchTape tape) {
+      int rowCount = tape.rowCount(_symbolOrdinal);
+      if (_kind == Kind.COUNT && _argument == null) {
+        return (long) rowCount;
+      }
+      List<Object[]> partitionRows = tape.getPartitionRows();
+      switch (_kind) {
+        case COUNT:
+          return countNonNull(tape, rowCount, partitionRows);
+        case MIN:
+        case MAX:
+          return evaluateExtremum(tape, rowCount, partitionRows);
+        case SUM:
+        case AVG:
+          return evaluateSumOrAverage(tape, rowCount, partitionRows);
+        default:
+          throw new IllegalStateException("Unexpected MATCH_RECOGNIZE 
aggregate: " + _kind);
+      }
+    }
+
+    private long countNonNull(MatchTape tape, int rowCount, List<Object[]> 
partitionRows) {
+      long count = 0;
+      for (int i = 0; i < rowCount; i++) {
+        checkTerminationPeriodically();
+        Object value = 
_argument.apply(partitionRows.get(tape.rowAt(_symbolOrdinal, i)));
+        if (value != null) {
+          count++;
+        }
+      }
+      return count;
+    }
+
+    @Nullable
+    private Object evaluateExtremum(MatchTape tape, int rowCount, 
List<Object[]> partitionRows) {
+      Object extremum = null;
+      for (int i = 0; i < rowCount; i++) {
+        checkTerminationPeriodically();
+        Object value = 
_argument.apply(partitionRows.get(tape.rowAt(_symbolOrdinal, i)));
+        if (value == null) {
+          continue;
+        }
+        if (extremum == null || (_kind == Kind.MIN ? compare(value, extremum) 
< 0 : compare(value, extremum) > 0)) {
+          extremum = value;
+        }
+      }
+      if (extremum == null || !_requiresResultConversion) {
+        return extremum;
+      }
+      return TypeUtils.convert(extremum, _storedType);
+    }
+
+    @Nullable
+    private Object evaluateSumOrAverage(MatchTape tape, int rowCount, 
List<Object[]> partitionRows) {
+      switch (_storedType) {
+        case INT:
+        case LONG:
+          return evaluateIntegralSumOrAverage(tape, rowCount, partitionRows);
+        case FLOAT:
+        case DOUBLE:
+          return evaluateFloatingPointSumOrAverage(tape, rowCount, 
partitionRows);
+        case BIG_DECIMAL:
+          return evaluateDecimalSumOrAverage(tape, rowCount, partitionRows);
+        default:
+          throw QueryErrorCode.QUERY_EXECUTION.asException(
+              "MATCH_RECOGNIZE " + _kind + " requires a numeric result type, 
got: " + _resultType + ".");
+      }
+    }
+
+    @Nullable
+    private Object evaluateIntegralSumOrAverage(MatchTape tape, int rowCount, 
List<Object[]> partitionRows) {
+      long sum = 0;
+      long count = 0;
+      for (int i = 0; i < rowCount; i++) {
+        checkTerminationPeriodically();
+        Object value = 
_argument.apply(partitionRows.get(tape.rowAt(_symbolOrdinal, i)));
+        if (value != null) {
+          sum += numericValue(value).longValue();

Review Comment:
   SUM now uses Math.addExact and fails with a QUERY_EXECUTION error that 
suggests casting the argument to DECIMAL or DOUBLE (82458ad3ba). The INT cast 
turned out to be reachable: SUM and AVG keep the type of a DECIMAL(p, 0) 
argument, which maps to INT for p <= 10, so it is now Math.toIntExact instead 
of being removed, and an integral AVG whose intermediate sum overflows is 
computed exactly over BigInteger.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



##########
pinot-common/src/main/proto/plan.proto:
##########
@@ -44,6 +44,7 @@ message PlanNode {
     // serialized by an older-version broker can still be deserialized. No 
current broker sets this field.
     EnrichedJoinNode enrichedJoinNode = 17 [deprecated = true];
     UnnestNode unnestNode = 18;
+    MatchNode matchNode = 19;

Review Comment:
   Done in 96a9d3d305: servers advertise MSE_MATCH_RECOGNIZE revision 1, and 
QueryEnvironment checks getMinServerCapabilityRevision where it builds the 
dispatchable plan, so execution and EXPLAIN with implementation fail with a 
QUERY_PLANNING error that asks to upgrade the servers. The manual upgrade step 
is gone from the description. MatchRecognizeServerCapabilityTest covers the 
planner, and an integration test drops one server's advertised revision to 0 
and back.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



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