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


##########
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:
   Since this thread was resolved, 
[apache/pinot#20058](https://github.com/apache/pinot/pull/20058) has merged, so 
we now have a way to gate this instead of only documenting it. A server can 
advertise an `InstanceCapability` (for example `MSE_MATCH_RECOGNIZE`, revision 
1). The broker can then read the minimum revision across servers with 
`RoutingManager.getMinServerCapabilityRevision`, which costs no extra ZK reads 
because the routing manager already has the instance configs.
   
   With that, the broker can reject MATCH_RECOGNIZE with an actionable "upgrade 
all servers first" error while any server lacks the capability. Today an old 
server fails the query with an opaque "Unsupported PlanNode type" instead. It 
would also let us drop the manual "upgrade all servers before issuing these 
queries" step from the release notes. `InstanceCapability.values()` is empty on 
master, so this would be the first real capability. That makes it a good first 
user of the API, and I'm happy to help with it.
   



##########
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:
   The two correlate commits (23b07f81e8 and bef724800a) fix real bugs, and I'm 
glad they're caught: a correlate without an Uncollect, or a sub-query inside 
the UNNEST array, used to plan into silently wrong results. But this changes 
how existing queries behave, and most of them have nothing to do with 
MATCH_RECOGNIZE. A correlated scalar sub-query over an UNNEST of the outer 
row's array used to return rows, and now it fails planning.
   
   I'd recommend moving these two commits to a separate PR. That PR would get 
its own release note, and someone who knows the UNNEST path could review it 
without reading 12K lines of MATCH_RECOGNIZE. It would also be a natural home 
for the TODOs the commit message mentions (LEFT correlate running as inner, and 
the lost projections above the Uncollect). If splitting is too painful, I'm 
fine keeping them here, but then please call out the UNNEST behavior change in 
the PR description and the release notes.
   



##########
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:
   `evaluateIntegralSumOrAverage` accumulates with a plain `sum += 
...longValue()`, so a SUM over large BIGINT values wraps past `Long.MAX_VALUE` 
and returns a wrong result without an error. The rest of this PR fails loudly 
instead of returning wrong rows, so I'd use `Math.addExact` here and turn an 
`ArithmeticException` into a clear query error. If wrapping is intentional (to 
match some other SUM path), a short comment saying so would help.
   
   Minor: the `(int) result` cast below looks unreachable. 
`TypeSystem.deriveSumType` types SUM over integers as BIGINT, and AVG is 
DOUBLE, so `_storedType` is never INT here. Removing it avoids a silent 
truncation if the typing ever changes.
   



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