kgyrtkirk commented on code in PR #17038:
URL: https://github.com/apache/druid/pull/17038#discussion_r1770980060


##########
extensions-core/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/WindowOperatorQueryFrameProcessor.java:
##########
@@ -510,4 +322,9 @@ private void ensureMaxRowsInAWindowConstraint(int 
numRowsInWindow)
       ));
     }
   }
+
+  private boolean needToProcessBatch()
+  {
+    return numRowsInFrameRowsAndCols >= maxRowsMaterialized / 2; // Can this 
be improved further?

Review Comment:
   why divide by `2` ? that doesn't give any guarantee that it will be inside 
bounds
   people could set it to half if needed - but I think its easier to document 
clear things...



##########
extensions-core/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/WindowOperatorQueryFrameProcessor.java:
##########
@@ -154,150 +130,60 @@ public List<WritableFrameChannel> outputChannels()
   @Override
   public ReturnOrAwait<Object> runIncrementally(IntSet readableInputs)
   {
-    /*
-     There are 2 scenarios:
-
-     *** Scenario 1: Query has atleast one window function with an OVER() 
clause without a PARTITION BY ***
-
-     In this scenario, we add all the RACs to a single RowsAndColumns to be 
processed. We do it via ConcatRowsAndColumns, and run all the operators on the 
ConcatRowsAndColumns.
-     This is done because we anyway need to run the operators on the entire 
set of rows when we have an OVER() clause without a PARTITION BY.
-     This scenario corresponds to partitionColumnNames.isEmpty()=true code 
flow.
-
-     *** Scenario 2: All window functions in the query have OVER() clause with 
a PARTITION BY ***
-
-     In this scenario, we need to process rows for each PARTITION BY group 
together, but we can batch multiple PARTITION BY keys into the same RAC before 
passing it to the operators for processing.
-     Batching is fine since the operators list would have the required 
NaivePartitioningOperatorFactory to segregate each PARTITION BY group during 
the processing.
-
-     The flow for this scenario can be summarised as following:
-     1. Frame Reading and Cursor Initialization: We start by reading a frame 
from the inputChannel and initializing frameCursor to iterate over the rows in 
that frame.
-     2. Row Comparison: For each row in the frame, we decide whether it 
belongs to the same PARTITION BY group as the previous row.
-                        This is determined by comparePartitionKeys() method.
-                        Please refer to the Javadoc of that method for further 
details and an example illustration.
-        2.1. If the PARTITION BY columns of current row matches the PARTITION 
BY columns of the previous row,
-             they belong to the same PARTITION BY group, and gets added to 
rowsToProcess.
-             If the number of total rows materialized exceed 
maxRowsMaterialized, we process the pending batch via 
processRowsUpToLastPartition() method.
-        2.2. If they don't match, then we have reached a partition boundary.
-             In this case, we update the value for lastPartitionIndex.
-     3. End of Input: If the input channel is finished, any remaining rows in 
rowsToProcess are processed.
-
-     *Illustration of Row Comparison step*
+    if (inputChannel.canRead()) {
+      final Frame frame = inputChannel.read();
+      convertRowFrameToRowsAndColumns(frame);
 
-     Let's say we have window_function() OVER (PARTITION BY A ORDER BY B) in 
our query, and we get 3 frames in the input channel to process.
-
-     Frame 1
-     A, B
-     1, 2
-     1, 3
-     2, 1 --> PARTITION BY key (column A) changed from 1 to 2.
-     2, 2
-
-     Frame 2
-     A, B
-     3, 1 --> PARTITION BY key (column A) changed from 2 to 3.
-     3, 2
-     3, 3
-     3, 4
-
-     Frame 3
-     A, B
-     3, 5
-     3, 6
-     4, 1 --> PARTITION BY key (column A) changed from 3 to 4.
-     4, 2
-
-     *Why batching?*
-     We batch multiple PARTITION BY keys for processing together to avoid the 
overhead of creating different RACs for each PARTITION BY keys, as that would 
be unnecessary in scenarios where we have a large number of PARTITION BY keys, 
but each key having a single row.
-
-     *Future thoughts: https://github.com/apache/druid/issues/16126*
-     Current approach with R&C and operators materialize a single R&C for 
processing. In case of data with low cardinality a single R&C might be too big 
to consume. Same for the case of empty OVER() clause.
-     Most of the window operations like SUM(), RANK(), RANGE() etc. can be 
made with 2 passes of the data. We might think to reimplement them in the MSQ 
way so that we do not have to materialize so much data.
-     */
-
-    if (partitionColumnNames.isEmpty()) {
-      // Scenario 1: Query has atleast one window function with an OVER() 
clause without a PARTITION BY.
-      if (inputChannel.canRead()) {
-        final Frame frame = inputChannel.read();
-        convertRowFrameToRowsAndColumns(frame);
-        return ReturnOrAwait.runAgain();
-      } else if (inputChannel.isFinished()) {
-        runAllOpsOnMultipleRac(frameRowsAndCols);
-        return ReturnOrAwait.returnObject(Unit.instance());
-      } else {
-        return ReturnOrAwait.awaitAll(inputChannels().size());
-      }
-    }
-
-    // Scenario 2: All window functions in the query have OVER() clause with a 
PARTITION BY
-    if (frameCursor == null || frameCursor.isDone()) {
-      if (readableInputs.isEmpty()) {
-        return ReturnOrAwait.awaitAll(1);
-      } else if (inputChannel.canRead()) {
-        final Frame frame = inputChannel.read();
-        frameCursor = FrameProcessors.makeCursor(frame, frameReader);
-        makeRowSupplierFromFrameCursor();
-      } else if (inputChannel.isFinished()) {
-        // Handle any remaining data.
-        lastPartitionIndex = rowsToProcess.size() - 1;
-        processRowsUpToLastPartition();
-        return ReturnOrAwait.returnObject(Unit.instance());
-      } else {
-        return ReturnOrAwait.runAgain();
-      }
-    }
-
-    while (!frameCursor.isDone()) {
-      final ResultRow currentRow = rowSupplierFromFrameCursor.get();
-      if (outputRow == null) {
-        outputRow = currentRow;
-        rowsToProcess.add(currentRow);
-      } else if (comparePartitionKeys(outputRow, currentRow, 
partitionColumnNames)) {
-        // Add current row to the same batch of rows for processing.
-        rowsToProcess.add(currentRow);
-        if (rowsToProcess.size() > maxRowsMaterialized) {
-          // We don't want to materialize more than maxRowsMaterialized rows 
at any point in time, so process the pending batch.
-          processRowsUpToLastPartition();
+      if (needToProcessBatch()) {
+        runAllOpsOnBatch();
+        try {
+          flushAllRowsAndCols(resultRowAndCols);
+        }
+        catch (IOException e) {
+          throw new RuntimeException(e);
         }
-        ensureMaxRowsInAWindowConstraint(rowsToProcess.size());
-      } else {
-        lastPartitionIndex = rowsToProcess.size() - 1;
-        outputRow = currentRow.copy();
-        return ReturnOrAwait.runAgain();
       }
-      frameCursor.advance();
+      return ReturnOrAwait.runAgain();
+    } else if (inputChannel.isFinished()) {
+      runAllOpsOnBatch();
+      return ReturnOrAwait.returnObject(Unit.instance());
+    } else {
+      return ReturnOrAwait.awaitAll(inputChannels().size());
     }
-    return ReturnOrAwait.runAgain();
   }
 
-  /**
-   * @param listOfRacs Concat this list of {@link RowsAndColumns} to a {@link 
ConcatRowsAndColumns} to use as a single input for the operators to be run
-   */
-  private void runAllOpsOnMultipleRac(ArrayList<RowsAndColumns> listOfRacs)
+  private void initialiseOperator()
   {
-    Operator op = new Operator()
+    op = new Operator()
     {
       @Nullable
       @Override
       public Closeable goOrContinue(Closeable continuationObject, Receiver 
receiver)
       {
-        RowsAndColumns rac = new ConcatRowsAndColumns(listOfRacs);
+        RowsAndColumns rac = new ConcatRowsAndColumns(new 
ArrayList<>(frameRowsAndCols));
+        frameRowsAndCols.clear();
+        numRowsInFrameRowsAndCols = 0;
         ensureMaxRowsInAWindowConstraint(rac.numRows());
         receiver.push(rac);
-        receiver.completed();
-        return null;
+
+        if (inputChannel.isFinished()) {
+          // Only call completed() when the input channel is finished.
+          receiver.completed();
+          return null; // Signal that the operator has completed its work
+        }
+
+        // Return a non-null continuation object to indicate that we want to 
continue processing.
+        return () -> {};
       }
     };
-    runOperatorsAfterThis(op);
-  }
-
-  /**
-   * @param op Base operator for the operators to be run. Other operators are 
wrapped under this to run
-   */
-  private void runOperatorsAfterThis(Operator op)
-  {
     for (OperatorFactory of : operatorFactoryList) {
       op = of.wrap(op);
     }
-    Operator.go(op, new Operator.Receiver()
+  }
+
+  private void runAllOpsOnBatch()
+  {
+    op.goOrContinue(null, new Operator.Receiver()

Review Comment:
   I find this a bit wierd....
   * why the `flush` method is outside of this class?
   * why this have to cache all the rows?
   * why it have to delay write up-until `completed` ?
   



##########
extensions-core/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/WindowOperatorQueryFrameProcessorFactory.java:
##########
@@ -61,26 +60,19 @@ public class WindowOperatorQueryFrameProcessorFactory 
extends BaseFrameProcessor
   private final List<OperatorFactory> operatorList;
   private final RowSignature stageRowSignature;
   private final int maxRowsMaterializedInWindow;
-  private final List<String> partitionColumnNames;
 
   @JsonCreator
   public WindowOperatorQueryFrameProcessorFactory(
       @JsonProperty("query") WindowOperatorQuery query,
       @JsonProperty("operatorList") List<OperatorFactory> operatorFactoryList,
       @JsonProperty("stageRowSignature") RowSignature stageRowSignature,
-      @JsonProperty("maxRowsMaterializedInWindow") int 
maxRowsMaterializedInWindow,
-      @JsonProperty("partitionColumnNames") List<String> partitionColumnNames
+      @JsonProperty("maxRowsMaterializedInWindow") int 
maxRowsMaterializedInWindow

Review Comment:
   does this really needs to be an option to the `processorFactory` ?
   isn't this a system-wide or query-wide setting? I don't see any reason to 
make it any finer grain than that..



##########
processing/src/main/java/org/apache/druid/query/operator/BasePartitioningOperator.java:
##########
@@ -0,0 +1,121 @@
+/*
+ * 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.druid.query.operator;
+
+import org.apache.druid.error.DruidException;
+import org.apache.druid.java.util.common.RE;
+import org.apache.druid.query.rowsandcols.RowsAndColumns;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+
+public abstract class BasePartitioningOperator implements Operator

Review Comment:
   can we call it `Abstract*`  as its abstract?



##########
extensions-core/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/WindowOperatorQueryFrameProcessor.java:
##########
@@ -338,6 +218,9 @@ private void flushAllRowsAndCols(ArrayList<RowsAndColumns> 
resultRowAndCols) thr
     AtomicInteger rowId = new AtomicInteger(0);
     createFrameWriterIfNeeded(rac, rowId);
     writeRacToFrame(rac, rowId);

Review Comment:
   seems like there are some incorrect method contracts here: as `rowId` is 
used incorrectly: 
   * if this method would be called 2 times the 1st invocation of 
`createFrameWriterIfNeeded` would still retain the previous rowid reference
   * however `writeRacToFrame` would  use the one passed from here
   
   



##########
extensions-core/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/WindowOperatorQueryKit.java:
##########
@@ -377,4 +324,37 @@ private static RowSignature 
computeSignatureForFinalWindowStage(RowSignature row
         finalWindowClusterBy.getColumns()
     );
   }
+
+  /**
+   * This method converts the operator chain received from native plan into 
MSQ plan.
+   * (NaiveSortOperator -> Naive/GlueingPartitioningOperator -> 
WindowOperator) is converted into (GlueingPartitioningOperator -> 
PartitionSortOperator -> WindowOperator).
+   * We rely on MSQ's shuffling to do the clustering on partitioning keys for 
us at every stage.
+   * This conversion allows us to blindly read N rows from input channel and 
push them into the operator chain, and repeat until the input channel isn't 
finished.
+   * @param operatorFactoryListFromQuery
+   * @param maxRowsMaterializedInWindow
+   * @return
+   */
+  private List<OperatorFactory> 
getOperatorFactoryListForStageDefinition(List<OperatorFactory> 
operatorFactoryListFromQuery, int maxRowsMaterializedInWindow)

Review Comment:
   please open a preceeding PR which fixes the optimization model of the 
WindowOperatorQueryKit to use a struct which is like:
   ```
   class StageX {
     SortOperator  sortOperator;
     PartitionOperator  partitionOperator;
     List<Operator> operators
   }
   ```



##########
extensions-core/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/WindowOperatorQueryKit.java:
##########
@@ -377,4 +324,37 @@ private static RowSignature 
computeSignatureForFinalWindowStage(RowSignature row
         finalWindowClusterBy.getColumns()
     );
   }
+
+  /**
+   * This method converts the operator chain received from native plan into 
MSQ plan.
+   * (NaiveSortOperator -> Naive/GlueingPartitioningOperator -> 
WindowOperator) is converted into (GlueingPartitioningOperator -> 
PartitionSortOperator -> WindowOperator).
+   * We rely on MSQ's shuffling to do the clustering on partitioning keys for 
us at every stage.
+   * This conversion allows us to blindly read N rows from input channel and 
push them into the operator chain, and repeat until the input channel isn't 
finished.
+   * @param operatorFactoryListFromQuery
+   * @param maxRowsMaterializedInWindow
+   * @return
+   */
+  private List<OperatorFactory> 
getOperatorFactoryListForStageDefinition(List<OperatorFactory> 
operatorFactoryListFromQuery, int maxRowsMaterializedInWindow)
+  {
+    final List<OperatorFactory> operatorFactoryList = new ArrayList<>();
+    final List<OperatorFactory> sortOperatorFactoryList = new ArrayList<>();
+    for (OperatorFactory operatorFactory : operatorFactoryListFromQuery) {
+      if (operatorFactory instanceof BasePartitioningOperatorFactory) {
+        BasePartitioningOperatorFactory partition = 
(BasePartitioningOperatorFactory) operatorFactory;
+        operatorFactoryList.add(new 
GlueingPartitioningOperatorFactory(partition.getPartitionColumns(), 
maxRowsMaterializedInWindow));
+      } else if (operatorFactory instanceof BaseSortOperatorFactory) {
+        BaseSortOperatorFactory sortOperatorFactory = 
(BaseSortOperatorFactory) operatorFactory;
+        sortOperatorFactoryList.add(new 
PartitionSortOperatorFactory(sortOperatorFactory.getSortColumns()));

Review Comment:
   this should be a planner level decision - if such thing is done here you 
will eventully be doing some optimization jobs here.
   please back off from this in MSQ



##########
extensions-core/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/WindowOperatorQueryFrameProcessor.java:
##########
@@ -154,150 +130,60 @@ public List<WritableFrameChannel> outputChannels()
   @Override
   public ReturnOrAwait<Object> runIncrementally(IntSet readableInputs)
   {
-    /*
-     There are 2 scenarios:
-
-     *** Scenario 1: Query has atleast one window function with an OVER() 
clause without a PARTITION BY ***
-
-     In this scenario, we add all the RACs to a single RowsAndColumns to be 
processed. We do it via ConcatRowsAndColumns, and run all the operators on the 
ConcatRowsAndColumns.
-     This is done because we anyway need to run the operators on the entire 
set of rows when we have an OVER() clause without a PARTITION BY.
-     This scenario corresponds to partitionColumnNames.isEmpty()=true code 
flow.
-
-     *** Scenario 2: All window functions in the query have OVER() clause with 
a PARTITION BY ***
-
-     In this scenario, we need to process rows for each PARTITION BY group 
together, but we can batch multiple PARTITION BY keys into the same RAC before 
passing it to the operators for processing.
-     Batching is fine since the operators list would have the required 
NaivePartitioningOperatorFactory to segregate each PARTITION BY group during 
the processing.
-
-     The flow for this scenario can be summarised as following:
-     1. Frame Reading and Cursor Initialization: We start by reading a frame 
from the inputChannel and initializing frameCursor to iterate over the rows in 
that frame.
-     2. Row Comparison: For each row in the frame, we decide whether it 
belongs to the same PARTITION BY group as the previous row.
-                        This is determined by comparePartitionKeys() method.
-                        Please refer to the Javadoc of that method for further 
details and an example illustration.
-        2.1. If the PARTITION BY columns of current row matches the PARTITION 
BY columns of the previous row,
-             they belong to the same PARTITION BY group, and gets added to 
rowsToProcess.
-             If the number of total rows materialized exceed 
maxRowsMaterialized, we process the pending batch via 
processRowsUpToLastPartition() method.
-        2.2. If they don't match, then we have reached a partition boundary.
-             In this case, we update the value for lastPartitionIndex.
-     3. End of Input: If the input channel is finished, any remaining rows in 
rowsToProcess are processed.
-
-     *Illustration of Row Comparison step*
+    if (inputChannel.canRead()) {
+      final Frame frame = inputChannel.read();
+      convertRowFrameToRowsAndColumns(frame);
 
-     Let's say we have window_function() OVER (PARTITION BY A ORDER BY B) in 
our query, and we get 3 frames in the input channel to process.
-
-     Frame 1
-     A, B
-     1, 2
-     1, 3
-     2, 1 --> PARTITION BY key (column A) changed from 1 to 2.
-     2, 2
-
-     Frame 2
-     A, B
-     3, 1 --> PARTITION BY key (column A) changed from 2 to 3.
-     3, 2
-     3, 3
-     3, 4
-
-     Frame 3
-     A, B
-     3, 5
-     3, 6
-     4, 1 --> PARTITION BY key (column A) changed from 3 to 4.
-     4, 2
-
-     *Why batching?*
-     We batch multiple PARTITION BY keys for processing together to avoid the 
overhead of creating different RACs for each PARTITION BY keys, as that would 
be unnecessary in scenarios where we have a large number of PARTITION BY keys, 
but each key having a single row.
-
-     *Future thoughts: https://github.com/apache/druid/issues/16126*
-     Current approach with R&C and operators materialize a single R&C for 
processing. In case of data with low cardinality a single R&C might be too big 
to consume. Same for the case of empty OVER() clause.
-     Most of the window operations like SUM(), RANK(), RANGE() etc. can be 
made with 2 passes of the data. We might think to reimplement them in the MSQ 
way so that we do not have to materialize so much data.
-     */
-
-    if (partitionColumnNames.isEmpty()) {
-      // Scenario 1: Query has atleast one window function with an OVER() 
clause without a PARTITION BY.
-      if (inputChannel.canRead()) {
-        final Frame frame = inputChannel.read();
-        convertRowFrameToRowsAndColumns(frame);
-        return ReturnOrAwait.runAgain();
-      } else if (inputChannel.isFinished()) {
-        runAllOpsOnMultipleRac(frameRowsAndCols);
-        return ReturnOrAwait.returnObject(Unit.instance());
-      } else {
-        return ReturnOrAwait.awaitAll(inputChannels().size());
-      }
-    }
-
-    // Scenario 2: All window functions in the query have OVER() clause with a 
PARTITION BY
-    if (frameCursor == null || frameCursor.isDone()) {
-      if (readableInputs.isEmpty()) {
-        return ReturnOrAwait.awaitAll(1);
-      } else if (inputChannel.canRead()) {
-        final Frame frame = inputChannel.read();
-        frameCursor = FrameProcessors.makeCursor(frame, frameReader);
-        makeRowSupplierFromFrameCursor();
-      } else if (inputChannel.isFinished()) {
-        // Handle any remaining data.
-        lastPartitionIndex = rowsToProcess.size() - 1;
-        processRowsUpToLastPartition();
-        return ReturnOrAwait.returnObject(Unit.instance());
-      } else {
-        return ReturnOrAwait.runAgain();
-      }
-    }
-
-    while (!frameCursor.isDone()) {
-      final ResultRow currentRow = rowSupplierFromFrameCursor.get();
-      if (outputRow == null) {
-        outputRow = currentRow;
-        rowsToProcess.add(currentRow);
-      } else if (comparePartitionKeys(outputRow, currentRow, 
partitionColumnNames)) {
-        // Add current row to the same batch of rows for processing.
-        rowsToProcess.add(currentRow);
-        if (rowsToProcess.size() > maxRowsMaterialized) {
-          // We don't want to materialize more than maxRowsMaterialized rows 
at any point in time, so process the pending batch.
-          processRowsUpToLastPartition();
+      if (needToProcessBatch()) {
+        runAllOpsOnBatch();
+        try {
+          flushAllRowsAndCols(resultRowAndCols);
+        }
+        catch (IOException e) {
+          throw new RuntimeException(e);
         }
-        ensureMaxRowsInAWindowConstraint(rowsToProcess.size());
-      } else {
-        lastPartitionIndex = rowsToProcess.size() - 1;
-        outputRow = currentRow.copy();
-        return ReturnOrAwait.runAgain();
       }
-      frameCursor.advance();
+      return ReturnOrAwait.runAgain();
+    } else if (inputChannel.isFinished()) {
+      runAllOpsOnBatch();
+      return ReturnOrAwait.returnObject(Unit.instance());
+    } else {
+      return ReturnOrAwait.awaitAll(inputChannels().size());
     }
-    return ReturnOrAwait.runAgain();
   }
 
-  /**
-   * @param listOfRacs Concat this list of {@link RowsAndColumns} to a {@link 
ConcatRowsAndColumns} to use as a single input for the operators to be run
-   */
-  private void runAllOpsOnMultipleRac(ArrayList<RowsAndColumns> listOfRacs)
+  private void initialiseOperator()
   {
-    Operator op = new Operator()
+    op = new Operator()
     {
       @Nullable
       @Override
       public Closeable goOrContinue(Closeable continuationObject, Receiver 
receiver)
       {
-        RowsAndColumns rac = new ConcatRowsAndColumns(listOfRacs);
+        RowsAndColumns rac = new ConcatRowsAndColumns(new 
ArrayList<>(frameRowsAndCols));
+        frameRowsAndCols.clear();
+        numRowsInFrameRowsAndCols = 0;

Review Comment:
   coupled contract of `numRowsInFrameRowsAndCols` + `frameRowsAndCols` ; make 
a small builder class which has an:
   * add racs
   * can answer numRows
   * production assembles the actual RAC



##########
extensions-core/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/WindowOperatorQueryKit.java:
##########
@@ -120,127 +111,83 @@ public QueryDefinition makeQueryDefinition(
       maxRowsMaterialized = Limits.MAX_ROWS_MATERIALIZED_IN_WINDOW;

Review Comment:
   evaluating such things as defaults should be out-of-scope in this class
   move this conditional to somewhere like `MultiStageQueryContext.getMax...` 



##########
extensions-core/multi-stage-query/src/main/java/org/apache/druid/msq/querykit/WindowOperatorQueryKit.java:
##########
@@ -120,127 +111,83 @@ public QueryDefinition makeQueryDefinition(
       maxRowsMaterialized = Limits.MAX_ROWS_MATERIALIZED_IN_WINDOW;
     }
 
-    if (isEmptyOverPresent) {
-      // Move everything to a single partition since we have to load all the 
data on a single worker anyway to compute empty over() clause.
-      log.info(
-          "Empty over clause is present in the query. Creating a single stage 
with all operator factories [%s].",
-          queryToRun.getOperators()
-      );
-      queryDefBuilder.add(
-          StageDefinition.builder(firstStageNumber)
-                         .inputs(new StageInputSpec(firstStageNumber - 1))
-                         .signature(finalWindowStageRowSignature)
-                         .maxWorkerCount(maxWorkerCount)
-                         .shuffleSpec(finalWindowStageShuffleSpec)
-                         .processorFactory(new 
WindowOperatorQueryFrameProcessorFactory(
-                             queryToRun,
-                             queryToRun.getOperators(),
-                             finalWindowStageRowSignature,
-                             maxRowsMaterialized,
-                             Collections.emptyList()
-                         ))
-      );
-    } else {
-      // There are multiple windows present in the query.
-      // Create stages for each window in the query.
-      // These stages will be serialized.
-      // The partition by clause of the next window will be the shuffle key 
for the previous window.
-      RowSignature.Builder bob = RowSignature.builder();
-      RowSignature signatureFromInput = 
dataSourcePlan.getSubQueryDefBuilder().get().build().getFinalStageDefinition().getSignature();
-      log.info("Row signature received from last stage is [%s].", 
signatureFromInput);
-
-      for (int i = 0; i < signatureFromInput.getColumnNames().size(); i++) {
-        bob.add(signatureFromInput.getColumnName(i), 
signatureFromInput.getColumnType(i).get());
-      }
+    // There are multiple windows present in the query.
+    // Create stages for each window in the query.
+    // These stages will be serialized.
+    // The partition by clause of the next window will be the shuffle key for 
the previous window.
+    RowSignature.Builder bob = RowSignature.builder();
+    RowSignature signatureFromInput = 
dataSourcePlan.getSubQueryDefBuilder().get().build().getFinalStageDefinition().getSignature();
+    log.info("Row signature received from last stage is [%s].", 
signatureFromInput);
+
+    for (int i = 0; i < signatureFromInput.getColumnNames().size(); i++) {
+      bob.add(signatureFromInput.getColumnName(i), 
signatureFromInput.getColumnType(i).get());
+    }
 
-      List<String> partitionColumnNames = new ArrayList<>();
-
-      /*
-      operatorList is a List<List<OperatorFactory>>, where each 
List<OperatorFactory> corresponds to the operator factories
-       to be used for a different window stage.
-
-       We iterate over operatorList, and add the definition for a window stage 
to QueryDefinitionBuilder.
-       */
-      for (int i = 0; i < operatorList.size(); i++) {
-        for (OperatorFactory operatorFactory : operatorList.get(i)) {
-          if (operatorFactory instanceof WindowOperatorFactory) {
-            List<String> outputColumnNames = ((WindowOperatorFactory) 
operatorFactory).getProcessor().getOutputColumnNames();
-
-            // Need to add column names which are present in outputColumnNames 
and rowSignature but not in bob,
-            // since they need to be present in the row signature for this 
window stage.
-            for (String columnName : outputColumnNames) {
-              int indexInRowSignature = rowSignature.indexOf(columnName);
-              if (indexInRowSignature != -1 && bob.build().indexOf(columnName) 
== -1) {
-                ColumnType columnType = 
rowSignature.getColumnType(indexInRowSignature).get();
-                bob.add(columnName, columnType);
-                log.info("Added column [%s] of type [%s] to row signature for 
window stage.", columnName, columnType);
-              } else {
-                throw new ISE(
-                    "Found unexpected column [%s] already present in row 
signature [%s].",
-                    columnName,
-                    rowSignature
-                );
-              }
+    /*
+    operatorList is a List<List<OperatorFactory>>, where each 
List<OperatorFactory> corresponds to the operator factories
+     to be used for a different window stage.
+
+     We iterate over operatorList, and add the definition for a window stage 
to QueryDefinitionBuilder.
+     */
+    for (int i = 0; i < operatorList.size(); i++) {
+      for (OperatorFactory operatorFactory : operatorList.get(i)) {
+        if (operatorFactory instanceof WindowOperatorFactory) {
+          List<String> outputColumnNames = ((WindowOperatorFactory) 
operatorFactory).getProcessor().getOutputColumnNames();
+
+          // Need to add column names which are present in outputColumnNames 
and rowSignature but not in bob,
+          // since they need to be present in the row signature for this 
window stage.
+          for (String columnName : outputColumnNames) {
+            int indexInRowSignature = rowSignature.indexOf(columnName);
+            if (indexInRowSignature != -1 && bob.build().indexOf(columnName) 
== -1) {
+              ColumnType columnType = 
rowSignature.getColumnType(indexInRowSignature).get();
+              bob.add(columnName, columnType);
+              log.info("Added column [%s] of type [%s] to row signature for 
window stage.", columnName, columnType);
+            } else {
+              throw new ISE(
+                  "Found unexpected column [%s] already present in row 
signature [%s].",
+                  columnName,
+                  rowSignature
+              );
             }
           }
         }
+      }
 
-        final RowSignature intermediateSignature = bob.build();
-        final RowSignature stageRowSignature;
+      final RowSignature intermediateSignature = bob.build();
+      final RowSignature stageRowSignature;
 
-        if (i + 1 == operatorList.size()) {
-          stageRowSignature = finalWindowStageRowSignature;
-          nextShuffleSpec = finalWindowStageShuffleSpec;
+      if (i + 1 == operatorList.size()) {
+        stageRowSignature = finalWindowStageRowSignature;
+        nextShuffleSpec = finalWindowStageShuffleSpec;
+      } else {
+        nextShuffleSpec = findShuffleSpecForNextWindow(operatorList.get(i + 
1), maxWorkerCount);

Review Comment:
   please open a separate PR and fix the stagebuilder rather than hacking it 
backwards from here



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